binaryreader.h 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. #pragma once
  2. #include <fstream>
  3. #include <sstream>
  4. #include <iterator>
  5. #include "decompiler/unknown_opcode_exception.h"
  6. class BinaryReader
  7. {
  8. public:
  9. static std::vector<unsigned char> ReadAll(std::string fileName)
  10. {
  11. std::ifstream file(fileName.c_str(), std::ios::binary | std::ios::ate);
  12. if (file.is_open())
  13. {
  14. size_t fileSizeInBytes = size_t(file.tellg());
  15. std::vector<unsigned char> fileContents(fileSizeInBytes);
  16. file.seekg(0, std::ios::beg);
  17. file.read(reinterpret_cast<char*>(fileContents.data()), fileContents.size());
  18. return fileContents;
  19. }
  20. else
  21. {
  22. throw std::runtime_error("Can't open file");
  23. }
  24. }
  25. BinaryReader(std::vector<unsigned char>&& data)
  26. {
  27. mSize = data.size();
  28. std::copy(data.begin(), data.end(), std::ostream_iterator<unsigned char>(mStream));
  29. mStream.seekg(std::ios::beg);
  30. }
  31. size_t Size() const
  32. {
  33. return mSize;
  34. }
  35. void Seek(unsigned int pos)
  36. {
  37. if (!mStream.seekg(pos))
  38. {
  39. throw InternalDecompilerError();
  40. }
  41. }
  42. unsigned int Position()
  43. {
  44. return static_cast<unsigned int>(mStream.tellg());
  45. }
  46. unsigned int ReadU32()
  47. {
  48. return InternalRead<unsigned int>();
  49. }
  50. signed int ReadS32()
  51. {
  52. return InternalRead<signed int>();
  53. }
  54. signed short int ReadS16()
  55. {
  56. return InternalRead<signed short int>();
  57. }
  58. unsigned short int ReadU16()
  59. {
  60. return InternalRead<unsigned short int>();
  61. }
  62. unsigned char ReadU8()
  63. {
  64. return InternalRead<unsigned char>();
  65. }
  66. signed char ReadS8()
  67. {
  68. return InternalRead<signed char>();
  69. }
  70. private:
  71. template<class T>
  72. T InternalRead()
  73. {
  74. T r = {};
  75. if (!mStream.read(reinterpret_cast<char*>(&r), sizeof(r)))
  76. {
  77. throw InternalDecompilerError();
  78. }
  79. return r;
  80. }
  81. std::stringstream mStream;
  82. size_t mSize = 0;
  83. };