BsFileSerializer.cpp 1.9 KB

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