GPBDecoder.cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. #include "Base.h"
  2. #include "GPBDecoder.h"
  3. namespace gameplay
  4. {
  5. GPBDecoder::GPBDecoder(void) : _file(NULL), _outFile(NULL)
  6. {
  7. }
  8. GPBDecoder::~GPBDecoder(void)
  9. {
  10. }
  11. void GPBDecoder::readBinary(const std::string& filepath)
  12. {
  13. // open files
  14. _file = fopen(filepath.c_str(), "rb");
  15. std::string outfilePath = filepath;
  16. outfilePath += ".xml";
  17. _outFile = fopen(outfilePath.c_str(), "w");
  18. // read and write files
  19. assert(validateHeading());
  20. fprintf(_outFile, "<root>\n");
  21. readRefs();
  22. fprintf(_outFile, "</root>\n");
  23. // close files
  24. fclose(_outFile);
  25. _outFile = NULL;
  26. fclose(_file);
  27. _file = NULL;
  28. }
  29. bool GPBDecoder::validateHeading()
  30. {
  31. const size_t HEADING_SIZE = 9;
  32. const char identifier[] = "\xABGPB\xBB\r\n\x1A\n";
  33. char heading[HEADING_SIZE];
  34. fread(heading, sizeof(unsigned char), HEADING_SIZE, _file);
  35. for (size_t i = 0; i < HEADING_SIZE; ++i)
  36. {
  37. if (heading[i] != identifier[i])
  38. {
  39. return false;
  40. }
  41. }
  42. // read version
  43. unsigned char version[2];
  44. fread(version, sizeof(unsigned char), 2, _file);
  45. // don't care about version
  46. return true;
  47. }
  48. void GPBDecoder::readRefs()
  49. {
  50. fprintf(_outFile, "<RefTable>\n");
  51. // read number of refs
  52. unsigned int refCount = 0;
  53. assert(read(&refCount));
  54. for (size_t i = 0; i < refCount; ++i)
  55. {
  56. readRef();
  57. }
  58. fprintf(_outFile, "</RefTable>\n");
  59. }
  60. void GPBDecoder::readRef()
  61. {
  62. std::string xref = readString(_file);
  63. unsigned int type = 0, offset = 0;
  64. assert(read(&type));
  65. assert(read(&offset));
  66. fprintf(_outFile, "<Reference>\n");
  67. fprintfElement(_outFile, "xref", xref);
  68. fprintfElement(_outFile, "type", type);
  69. fprintfElement(_outFile, "offset", offset);
  70. fprintf(_outFile, "</Reference>\n");
  71. }
  72. bool GPBDecoder::read(unsigned int* ptr)
  73. {
  74. return fread(ptr, sizeof(unsigned int), 1, _file) == 1;
  75. }
  76. std::string GPBDecoder::readString(FILE* fp)
  77. {
  78. unsigned int length;
  79. if (fread(&length, 4, 1, fp) != 1)
  80. {
  81. return std::string();
  82. }
  83. char* str = new char[length + 1];
  84. if (length > 0)
  85. {
  86. if (fread(str, 1, length, fp) != length)
  87. {
  88. delete[] str;
  89. return std::string();
  90. }
  91. }
  92. str[length] = '\0';
  93. std::string result(str);
  94. delete[] str;
  95. return result;
  96. }
  97. }