CmFileSerializer.cpp 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #include "CmFileSerializer.h"
  2. #include "CmException.h"
  3. #include "CmIReflectable.h"
  4. #include "CmBinarySerializer.h"
  5. #include <numeric>
  6. #include <boost/bind.hpp>
  7. namespace CamelotEngine
  8. {
  9. FileSerializer::FileSerializer()
  10. {
  11. mWriteBuffer = CM_NEW_BYTES(WRITE_BUFFER_SIZE, ScratchAlloc);
  12. }
  13. FileSerializer::~FileSerializer()
  14. {
  15. CM_DELETE_BYTES(mWriteBuffer, ScratchAlloc);
  16. }
  17. void FileSerializer::encode(IReflectable* object, std::string fileLocation)
  18. {
  19. mOutputStream.open(fileLocation.c_str(), std::ios::out | std::ios::binary);
  20. BinarySerializer bs;
  21. int totalBytesWritten = 0;
  22. bs.encode(object, mWriteBuffer, WRITE_BUFFER_SIZE, &totalBytesWritten, boost::bind(&FileSerializer::flushBuffer, this, _1, _2, _3));
  23. mOutputStream.close();
  24. mOutputStream.clear();
  25. }
  26. std::shared_ptr<IReflectable> FileSerializer::decode(std::string fileLocation)
  27. {
  28. mInputStream.open(fileLocation.c_str(), std::ios::in | std::ios::ate | std::ios::binary);
  29. std::streamoff fileSize = mInputStream.tellg();
  30. if(fileSize > std::numeric_limits<UINT32>::max())
  31. {
  32. CM_EXCEPT(InternalErrorException,
  33. "File size is larger that UINT32 can hold. Ask a programmer to use a bigger data type.");
  34. }
  35. UINT8* readBuffer = CM_NEW_BYTES((UINT32)fileSize, ScratchAlloc); // TODO - Low priority. Consider upgrading BinarySerializer so we don't have to read everything at once
  36. mInputStream.seekg(0, std::ios::beg);
  37. mInputStream.read((char*)readBuffer, fileSize);
  38. BinarySerializer bs;
  39. std::shared_ptr<IReflectable> object = bs.decode(readBuffer, (UINT32)fileSize);
  40. mInputStream.close();
  41. mInputStream.clear();
  42. CM_DELETE_BYTES(readBuffer, ScratchAlloc);
  43. return object;
  44. }
  45. UINT8* FileSerializer::flushBuffer(UINT8* bufferStart, int bytesWritten, UINT32& newBufferSize)
  46. {
  47. mOutputStream.write((const char*)bufferStart, bytesWritten);
  48. return bufferStart;
  49. }
  50. }