File: BinarySerializer.h

package info (click to toggle)
vcmi 0.99%2Bdfsg%2Bgit20190113.f06c8a87-2
  • links: PTS, VCS
  • area: contrib
  • in suites: bullseye
  • size: 11,136 kB
  • sloc: cpp: 142,615; sh: 315; objc: 248; makefile: 32; ansic: 28; python: 13
file content (373 lines) | stat: -rw-r--r-- 9,323 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
 * BinarySerializer.h, part of VCMI engine
 *
 * Authors: listed in file AUTHORS in main folder
 *
 * License: GNU General Public License v2.0 or later
 * Full text of license available in license.txt file, in main folder
 *
 */
#pragma once

#include "CTypeList.h"
#include "../mapObjects/CArmedInstance.h"

class FileStream;

class DLL_LINKAGE CSaverBase
{
protected:
	IBinaryWriter * writer;
public:
	CSaverBase(IBinaryWriter * w): writer(w){};

	inline int write(const void * data, unsigned size)
	{
		return writer->write(data, size);
	};
};

/// Main class for serialization of classes into binary form
/// Behaviour for various classes is following:
/// Primitives:    copy memory into underlying stream (defined in CSaverBase)
/// Containers:    custom overloaded method that decouples class into primitives
/// VCMI Classes:  recursively serialize them via ClassName::serialize( BinarySerializer &, int version) call
class DLL_LINKAGE BinarySerializer : public CSaverBase
{
	template <typename Handler>
	struct VariantVisitorSaver : boost::static_visitor<>
	{
		Handler &h;
		VariantVisitorSaver(Handler &H):h(H)
		{
		}

		template <typename T>
		void operator()(const T &t)
		{
			h & t;
		}
	};

	template<typename Ser,typename T>
	struct SaveIfStackInstance
	{
		static bool invoke(Ser &s, const T &data)
		{
			return false;
		}
	};

	template<typename Ser>
	struct SaveIfStackInstance<Ser, CStackInstance *>
	{
		static bool invoke(Ser &s, const CStackInstance* const &data)
		{
			assert(data->armyObj);
			SlotID slot;

			if(data->getNodeType() == CBonusSystemNode::COMMANDER)
				slot = SlotID::COMMANDER_SLOT_PLACEHOLDER;
			else
				slot = data->armyObj->findStack(data);

			assert(slot != SlotID());
			s & data->armyObj & slot;
			return true;
		}
	};

	template <typename T> class CPointerSaver;

	class CBasicPointerSaver
	{
	public:
		virtual void savePtr(CSaverBase &ar, const void *data) const =0;
		virtual ~CBasicPointerSaver(){}

		template<typename T> static CBasicPointerSaver *getApplier(const T * t=nullptr)
		{
			return new CPointerSaver<T>();
		}
	};


	template <typename T>
	class CPointerSaver : public CBasicPointerSaver
	{
	public:
		void savePtr(CSaverBase &ar, const void *data) const override
		{
			BinarySerializer &s = static_cast<BinarySerializer&>(ar);
			const T *ptr = static_cast<const T*>(data);

			//T is most derived known type, it's time to call actual serialize
			const_cast<T*>(ptr)->serialize(s, SERIALIZATION_VERSION);
		}
	};

	CApplier<CBasicPointerSaver> applier;

public:
	std::map<const void*, ui32> savedPointers;

	bool smartPointerSerialization;
	bool saving;

	BinarySerializer(IBinaryWriter * w): CSaverBase(w)
	{
		saving=true;
		smartPointerSerialization = true;
	}

	template<typename Base, typename Derived>
	void registerType(const Base * b = nullptr, const Derived * d = nullptr)
	{
		applier.registerType(b, d);
	}

	template<class T>
	BinarySerializer & operator&(const T & t)
	{
		this->save(t);
		return * this;
	}

	template < typename T, typename std::enable_if < std::is_same<T, bool>::value, int >::type = 0 >
	void save(const T &data)
	{
		ui8 writ = static_cast<ui8>(data);
		save(writ);
	}

	template < typename T, typename std::enable_if < std::is_same<T, std::vector<bool> >::value, int  >::type = 0 >
	void save(const T &data)
	{
		std::vector<ui8> convData;
		std::copy(data.begin(), data.end(), std::back_inserter(convData));
		save(convData);
	}

	template < class T, typename std::enable_if < std::is_fundamental<T>::value && !std::is_same<T, bool>::value, int  >::type = 0 >
	void save(const T &data)
	{
		// save primitive - simply dump binary data to output
		this->write(&data,sizeof(data));
	}

	template < typename T, typename std::enable_if < std::is_enum<T>::value, int  >::type = 0 >
	void save(const T &data)
	{
		si32 writ = static_cast<si32>(data);
		*this & writ;
	}

	template < typename T, typename std::enable_if < std::is_array<T>::value, int  >::type = 0 >
	void save(const T &data)
	{
		ui32 size = ARRAY_COUNT(data);
		for(ui32 i=0; i < size; i++)
			*this & data[i];
	}

	template < typename T, typename std::enable_if < std::is_pointer<T>::value, int  >::type = 0 >
	void save(const T &data)
	{
		//write if pointer is not nullptr
		ui8 hlp = (data!=nullptr);
		save(hlp);

		//if pointer is nullptr then we don't need anything more...
		if(!hlp)
			return;

		if(writer->smartVectorMembersSerialization)
		{
			typedef typename std::remove_const<typename std::remove_pointer<T>::type>::type TObjectType;
			typedef typename VectorizedTypeFor<TObjectType>::type VType;
			typedef typename VectorizedIDType<TObjectType>::type IDType;

			if(const auto *info = writer->getVectorizedTypeInfo<VType, IDType>())
			{
				IDType id = writer->getIdFromVectorItem<VType>(*info, data);
				save(id);
				if(id != IDType(-1)) //vector id is enough
					return;
			}
		}

		if(writer->sendStackInstanceByIds)
		{
			const bool gotSaved = SaveIfStackInstance<BinarySerializer,T>::invoke(*this, data);
			if(gotSaved)
				return;
		}

		if(smartPointerSerialization)
		{
			// We might have an object that has multiple inheritance and store it via the non-first base pointer.
			// Therefore, all pointers need to be normalized to the actual object address.
			auto actualPointer = typeList.castToMostDerived(data);
			std::map<const void*,ui32>::iterator i = savedPointers.find(actualPointer);
			if(i != savedPointers.end())
			{
				//this pointer has been already serialized - write only it's id
				save(i->second);
				return;
			}

			//give id to this pointer
			ui32 pid = (ui32)savedPointers.size();
			savedPointers[actualPointer] = pid;
			save(pid);
		}

		//write type identifier
		ui16 tid = typeList.getTypeID(data);
		save(tid);

		if(!tid)
			save(*data); //if type is unregistered simply write all data in a standard way
		else
			applier.getApplier(tid)->savePtr(*this, typeList.castToMostDerived(data));  //call serializer specific for our real type
	}

	template < typename T, typename std::enable_if < is_serializeable<BinarySerializer, T>::value, int  >::type = 0 >
	void save(const T &data)
	{
		const_cast<T&>(data).serialize(*this, SERIALIZATION_VERSION);
	}

	template <typename T>
	void save(const std::shared_ptr<T> &data)
	{
		T *internalPtr = data.get();
		save(internalPtr);
	}
	template <typename T>
	void save(const std::unique_ptr<T> &data)
	{
		T *internalPtr = data.get();
		save(internalPtr);
	}
	template <typename T, typename std::enable_if < !std::is_same<T, bool >::value, int  >::type = 0>
	void save(const std::vector<T> &data)
	{
		ui32 length = data.size();
		*this & length;
		for(ui32 i=0;i<length;i++)
			save(data[i]);
	}
	template <typename T, size_t N>
	void save(const std::array<T, N> &data)
	{
		for(ui32 i=0; i < N; i++)
			save(data[i]);
	}
	template <typename T>
	void save(const std::set<T> &data)
	{
		std::set<T> &d = const_cast<std::set<T> &>(data);
		ui32 length = d.size();
		save(length);
		for(typename std::set<T>::iterator i=d.begin();i!=d.end();i++)
			save(*i);
	}
	template <typename T, typename U>
	void save(const std::unordered_set<T, U> &data)
	{
		std::unordered_set<T, U> &d = const_cast<std::unordered_set<T, U> &>(data);
		ui32 length = d.size();
		*this & length;
		for(typename std::unordered_set<T, U>::iterator i=d.begin();i!=d.end();i++)
			save(*i);
	}
	template <typename T>
	void save(const std::list<T> &data)
	{
		std::list<T> &d = const_cast<std::list<T> &>(data);
		ui32 length = d.size();
		*this & length;
		for(typename std::list<T>::iterator i=d.begin();i!=d.end();i++)
			save(*i);
	}
	void save(const std::string &data)
	{
		save(ui32(data.length()));
		this->write(data.c_str(),data.size());
	}
	template <typename T1, typename T2>
	void save(const std::pair<T1,T2> &data)
	{
		save(data.first);
		save(data.second);
	}
	template <typename T1, typename T2>
	void save(const std::map<T1,T2> &data)
	{
		*this & ui32(data.size());
		for(typename std::map<T1,T2>::const_iterator i=data.begin();i!=data.end();i++)
		{
			save(i->first);
			save(i->second);
		}
	}
	template <typename T1, typename T2>
	void save(const std::multimap<T1, T2> &data)
	{
		*this & ui32(data.size());
		for(typename std::map<T1, T2>::const_iterator i = data.begin(); i != data.end(); i++)
		{
			save(i->first);
			save(i->second);
		}
	}
	template <BOOST_VARIANT_ENUM_PARAMS(typename T)>
	void save(const boost::variant<BOOST_VARIANT_ENUM_PARAMS(T)> &data)
	{
		si32 which = data.which();
		save(which);

		VariantVisitorSaver<BinarySerializer> visitor(*this);
		boost::apply_visitor(visitor, data);
	}
	template <typename T>
	void save(const boost::optional<T> &data)
	{
		if(data)
		{
			save((ui8)1);
			save(*data);
		}
		else
		{
			save((ui8)0);
		}
	}
};

class DLL_LINKAGE CSaveFile : public IBinaryWriter
{
public:
	BinarySerializer serializer;

	boost::filesystem::path fName;
	std::unique_ptr<FileStream> sfile;

	CSaveFile(const boost::filesystem::path &fname); //throws!
	~CSaveFile();
	int write(const void * data, unsigned size) override;

	void openNextFile(const boost::filesystem::path &fname); //throws!
	void clear();
	void reportState(vstd::CLoggerBase * out) override;

	void putMagicBytes(const std::string &text);

	template<class T>
	CSaveFile & operator<<(const T &t)
	{
		serializer & t;
		return * this;
	}
};