1 | //************************************ bs::framework - Copyright 2018 Marko Pintera **************************************// |
2 | //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// |
3 | #include "Serialization/BsMemorySerializer.h" |
4 | |
5 | #include "Error/BsException.h" |
6 | #include "Reflection/BsIReflectable.h" |
7 | #include "Serialization/BsBinarySerializer.h" |
8 | #include "FileSystem/BsDataStream.h" |
9 | |
10 | using namespace std::placeholders; |
11 | |
12 | namespace bs |
13 | { |
14 | UINT8* MemorySerializer::encode(IReflectable* object, UINT32& bytesWritten, |
15 | std::function<void*(UINT32)> allocator, bool shallow, SerializationContext* context) |
16 | { |
17 | using namespace std::placeholders; |
18 | |
19 | BinarySerializer bs; |
20 | |
21 | BufferPiece piece; |
22 | piece.buffer = (UINT8*)bs_alloc(WRITE_BUFFER_SIZE); |
23 | piece.size = 0; |
24 | |
25 | mBufferPieces.push_back(piece); |
26 | |
27 | bs.encode(object, piece.buffer, WRITE_BUFFER_SIZE, &bytesWritten, |
28 | std::bind(&MemorySerializer::flushBuffer, this, _1, _2, _3), shallow, context); |
29 | |
30 | UINT8* resultBuffer; |
31 | if(allocator != nullptr) |
32 | resultBuffer = (UINT8*)allocator(bytesWritten); |
33 | else |
34 | resultBuffer = (UINT8*)bs_alloc(bytesWritten); |
35 | |
36 | UINT32 offset = 0; |
37 | for(auto iter = mBufferPieces.begin(); iter != mBufferPieces.end(); ++iter) |
38 | { |
39 | if(iter->size > 0) |
40 | { |
41 | memcpy(resultBuffer + offset, iter->buffer, iter->size); |
42 | offset += iter->size; |
43 | } |
44 | } |
45 | |
46 | for(auto iter = mBufferPieces.rbegin(); iter != mBufferPieces.rend(); ++iter) |
47 | { |
48 | bs_free(iter->buffer); |
49 | } |
50 | |
51 | mBufferPieces.clear(); |
52 | |
53 | return resultBuffer; |
54 | } |
55 | |
56 | SPtr<IReflectable> MemorySerializer::decode(UINT8* buffer, UINT32 bufferSize, SerializationContext* context) |
57 | { |
58 | SPtr<MemoryDataStream> stream = bs_shared_ptr_new<MemoryDataStream>(buffer, bufferSize, false); |
59 | |
60 | BinarySerializer bs; |
61 | SPtr<IReflectable> object = bs.decode(stream, (UINT32)bufferSize, context); |
62 | |
63 | return object; |
64 | } |
65 | |
66 | UINT8* MemorySerializer::flushBuffer(UINT8* bufferStart, UINT32 bytesWritten, UINT32& newBufferSize) |
67 | { |
68 | mBufferPieces.back().size = bytesWritten; |
69 | |
70 | BufferPiece piece; |
71 | piece.buffer = (UINT8*)bs_alloc(WRITE_BUFFER_SIZE); |
72 | piece.size = 0; |
73 | |
74 | mBufferPieces.push_back(piece); |
75 | |
76 | return piece.buffer; |
77 | } |
78 | } |
79 | |