BsFileSerializer.cpp 2.2 KB

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