Not used in code
[novacoin.git] / src / serialize.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_SERIALIZE_H
6 #define BITCOIN_SERIALIZE_H
7
8 #include <string>
9 #include <vector>
10 #include <map>
11 #include <set>
12 #include <cassert>
13 #include <limits>
14 #include <cstring>
15 #include <cstdio>
16 #include <tuple>
17 #include <type_traits>
18
19 #ifndef Q_MOC_RUN
20 #endif
21
22 #if defined __USE_MINGW_ANSI_STDIO
23 #undef __USE_MINGW_ANSI_STDIO // This constant forces MinGW to conduct stupid behavior
24 #endif
25 #include <inttypes.h>
26
27 #include "allocators.h"
28 #include "version.h"
29
30
31 class CScript;
32 class CDataStream;
33 class CAutoFile;
34 static const unsigned int MAX_SIZE = 0x02000000;
35
36 // Used to bypass the rule against non-const reference to temporary
37 // where it makes sense with wrappers such as CFlatData or CTxDB
38 template<typename T>
39 inline T& REF(const T& val)
40 {
41     return const_cast<T&>(val);
42 }
43
44 /////////////////////////////////////////////////////////////////
45 //
46 // Templates for serializing to anything that looks like a stream,
47 // i.e. anything that supports .read(char*, int) and .write(char*, int)
48 //
49
50 enum
51 {
52     // primary actions
53     SER_NETWORK         = (1 << 0),
54     SER_DISK            = (1 << 1),
55     SER_GETHASH         = (1 << 2),
56
57     // modifiers
58     SER_SKIPSIG         = (1 << 16),
59     SER_BLOCKHEADERONLY = (1 << 17)
60
61 };
62
63 #define IMPLEMENT_SERIALIZE(statements)    \
64     unsigned int GetSerializeSize(int nType, int nVersion) const  \
65     {                                           \
66         CSerActionGetSerializeSize ser_action;  \
67         const bool fGetSize = true;             \
68         const bool fWrite = false;              \
69         const bool fRead = false;               \
70         unsigned int nSerSize = 0;              \
71         ser_streamplaceholder s;                \
72         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
73         s.nType = nType;                        \
74         s.nVersion = nVersion;                  \
75         {statements}                            \
76         return nSerSize;                        \
77     }                                           \
78     template<typename Stream>                   \
79     void Serialize(Stream& s, int nType, int nVersion) const  \
80     {                                           \
81         CSerActionSerialize ser_action;         \
82         const bool fGetSize = false;            \
83         const bool fWrite = true;               \
84         const bool fRead = false;               \
85         unsigned int nSerSize = 0;              \
86         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
87         {statements}                            \
88     }                                           \
89     template<typename Stream>                   \
90     void Unserialize(Stream& s, int nType, int nVersion)  \
91     {                                           \
92         CSerActionUnserialize ser_action;       \
93         const bool fGetSize = false;            \
94         const bool fWrite = false;              \
95         const bool fRead = true;                \
96         unsigned int nSerSize = 0;              \
97         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
98         {statements}                            \
99     }
100
101 #define READWRITE(obj)      (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
102
103
104
105
106 //
107 // Basic types
108 //
109 #define WRITEDATA(s, obj)   s.write((char*)&(obj), sizeof(obj))
110 #define READDATA(s, obj)    s.read((char*)&(obj), sizeof(obj))
111
112 inline unsigned int GetSerializeSize(char a,           int, int=0) { return sizeof(a); }
113 inline unsigned int GetSerializeSize(signed char a,    int, int=0) { return sizeof(a); }
114 inline unsigned int GetSerializeSize(unsigned char a,  int, int=0) { return sizeof(a); }
115 inline unsigned int GetSerializeSize(signed short a,   int, int=0) { return sizeof(a); }
116 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
117 inline unsigned int GetSerializeSize(signed int a,     int, int=0) { return sizeof(a); }
118 inline unsigned int GetSerializeSize(unsigned int a,   int, int=0) { return sizeof(a); }
119 //inline unsigned int GetSerializeSize(signed long a,    int, int=0) { return sizeof(a); }
120 //inline unsigned int GetSerializeSize(unsigned long a,  int, int=0) { return sizeof(a); }
121 inline unsigned int GetSerializeSize(int64_t a,    int, int=0) { return sizeof(a); }
122 inline unsigned int GetSerializeSize(uint64_t a,  int, int=0) { return sizeof(a); }
123 inline unsigned int GetSerializeSize(float a,          int, int=0) { return sizeof(a); }
124 inline unsigned int GetSerializeSize(double a,         int, int=0) { return sizeof(a); }
125
126 template<typename Stream> inline void Serialize(Stream& s, char a,           int, int=0) { WRITEDATA(s, a); }
127 template<typename Stream> inline void Serialize(Stream& s, signed char a,    int, int=0) { WRITEDATA(s, a); }
128 template<typename Stream> inline void Serialize(Stream& s, unsigned char a,  int, int=0) { WRITEDATA(s, a); }
129 template<typename Stream> inline void Serialize(Stream& s, signed short a,   int, int=0) { WRITEDATA(s, a); }
130 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
131 template<typename Stream> inline void Serialize(Stream& s, signed int a,     int, int=0) { WRITEDATA(s, a); }
132 template<typename Stream> inline void Serialize(Stream& s, unsigned int a,   int, int=0) { WRITEDATA(s, a); }
133 //template<typename Stream> inline void Serialize(Stream& s, signed long a,    int, int=0) { WRITEDATA(s, a); }
134 //template<typename Stream> inline void Serialize(Stream& s, unsigned long a,  int, int=0) { WRITEDATA(s, a); }
135 template<typename Stream> inline void Serialize(Stream& s, int64_t a,    int, int=0) { WRITEDATA(s, a); }
136 template<typename Stream> inline void Serialize(Stream& s, uint64_t a,  int, int=0) { WRITEDATA(s, a); }
137 template<typename Stream> inline void Serialize(Stream& s, float a,          int, int=0) { WRITEDATA(s, a); }
138 template<typename Stream> inline void Serialize(Stream& s, double a,         int, int=0) { WRITEDATA(s, a); }
139
140 template<typename Stream> inline void Unserialize(Stream& s, char& a,           int, int=0) { READDATA(s, a); }
141 template<typename Stream> inline void Unserialize(Stream& s, signed char& a,    int, int=0) { READDATA(s, a); }
142 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a,  int, int=0) { READDATA(s, a); }
143 template<typename Stream> inline void Unserialize(Stream& s, signed short& a,   int, int=0) { READDATA(s, a); }
144 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
145 template<typename Stream> inline void Unserialize(Stream& s, signed int& a,     int, int=0) { READDATA(s, a); }
146 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a,   int, int=0) { READDATA(s, a); }
147 //template<typename Stream> inline void Unserialize(Stream& s, signed long& a,    int, int=0) { READDATA(s, a); }
148 //template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a,  int, int=0) { READDATA(s, a); }
149 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a,    int, int=0) { READDATA(s, a); }
150 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a,  int, int=0) { READDATA(s, a); }
151 template<typename Stream> inline void Unserialize(Stream& s, float& a,          int, int=0) { READDATA(s, a); }
152 template<typename Stream> inline void Unserialize(Stream& s, double& a,         int, int=0) { READDATA(s, a); }
153
154 inline unsigned int GetSerializeSize(bool a, int, int=0)                          { return sizeof(char); }
155 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0)    { char f=a; WRITEDATA(s, f); }
156 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
157
158
159
160
161 //
162 // Compact size
163 //  size <  253          -- 1 byte
164 //  size <= UINT16_MAX   -- 3 bytes  (253 + 2 bytes)
165 //  size <= UINT32_MAX   -- 5 bytes  (254 + 4 bytes)
166 //  size >  UINT32_MAX   -- 9 bytes  (255 + 8 bytes)
167 //
168 inline uint32_t GetSizeOfCompactSize(uint64_t nSize)
169 {
170     if (nSize < 0xfd)
171         return 1;
172     if (nSize <= std::numeric_limits<uint16_t>::max())
173         return 3;
174     if (nSize <= std::numeric_limits<uint32_t>::max())
175         return 5;
176     return 9;
177 }
178
179 template<typename Stream>
180 void WriteCompactSize(Stream& os, uint64_t nSize);
181
182 template<typename Stream>
183 uint64_t ReadCompactSize(Stream& is);
184
185 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
186 // The high bit in each byte signifies whether another digit follows. To make
187 // the encoding is one-to-one, one is subtracted from all but the last digit.
188 // Thus, the byte sequence a[] with length len, where all but the last byte
189 // has bit 128 set, encodes the number:
190 //
191 //   (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
192 //
193 // Properties:
194 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
195 // * Every integer has exactly one encoding
196 // * Encoding does not depend on size of original integer type
197 // * No redundancy: every (infinite) byte sequence corresponds to a list
198 //   of encoded integers.
199 //
200 // 0:         [0x00]  256:        [0x81 0x00]
201 // 1:         [0x01]  16383:      [0xFE 0x7F]
202 // 127:       [0x7F]  16384:      [0xFF 0x00]
203 // 128:  [0x80 0x00]  16511: [0x80 0xFF 0x7F]
204 // 255:  [0x80 0x7F]  65535: [0x82 0xFD 0x7F]
205 // 2^32:           [0x8E 0xFE 0xFE 0xFF 0x00]
206
207 template<typename I>
208 inline unsigned int GetSizeOfVarInt(I n)
209 {
210     int nRet = 0;
211     for ( ; ; ) {
212         nRet++;
213         if (n <= 0x7F)
214             break;
215         n = (n >> 7) - 1;
216     }
217     return nRet;
218 }
219
220 template<typename Stream, typename I>
221 void WriteVarInt(Stream& os, I n)
222 {
223     unsigned char tmp[(sizeof(n)*8+6)/7];
224     int len=0;
225     for ( ; ; ) {
226         tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
227         if (n <= 0x7F)
228             break;
229         n = (n >> 7) - 1;
230         len++;
231     }
232     do {
233         WRITEDATA(os, tmp[len]);
234     } while(len--);
235 }
236
237 template<typename Stream, typename I>
238 I ReadVarInt(Stream& is)
239 {
240     I n = 0;
241     for ( ; ; ) {
242         unsigned char chData;
243         READDATA(is, chData);
244         n = (n << 7) | (chData & 0x7F);
245         if (chData & 0x80)
246             n++;
247         else
248             return n;
249     }
250 }
251
252 #define FLATDATA(obj)  REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
253 #define VARINT(obj)    REF(WrapVarInt(REF(obj)))
254
255 /** Wrapper for serializing arrays and POD.
256  */
257 class CFlatData
258 {
259 protected:
260     char* pbegin;
261     char* pend;
262 public:
263     CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
264     char* begin() { return pbegin; }
265     const char* begin() const { return pbegin; }
266     char* end() { return pend; }
267     const char* end() const { return pend; }
268
269     unsigned int GetSerializeSize(int, int=0) const
270     {
271         return (unsigned int)(pend - pbegin);
272     }
273
274     template<typename Stream>
275     void Serialize(Stream& s, int, int=0) const
276     {
277         s.write(pbegin, (int)(pend - pbegin));
278     }
279
280     template<typename Stream>
281     void Unserialize(Stream& s, int, int=0)
282     {
283         s.read(pbegin, pend - pbegin);
284     }
285 };
286
287 template<typename I>
288 class CVarInt
289 {
290 protected:
291     I &n;
292 public:
293     CVarInt(I& nIn) : n(nIn) { }
294
295     unsigned int GetSerializeSize(int, int) const {
296         return GetSizeOfVarInt<I>(n);
297     }
298
299     template<typename Stream>
300     void Serialize(Stream &s, int, int) const {
301         WriteVarInt<Stream,I>(s, n);
302     }
303
304     template<typename Stream>
305     void Unserialize(Stream& s, int, int) {
306         n = ReadVarInt<Stream,I>(s);
307     }
308 };
309
310 template<typename I>
311 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
312
313 //
314 // Forward declarations
315 //
316
317 // string
318 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
319 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
320 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
321
322 // vector
323 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
324 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
325 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
326 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
327 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
328 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
329 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
330 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
331 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
332
333 // others derived from vector
334 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
335 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
336 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
337
338 // pair
339 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
340 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
341 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
342
343 // 3 tuple
344 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
345 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
346 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion);
347
348 // map
349 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
350 template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion);
351 template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion);
352
353 // set
354 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
355 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
356 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
357
358
359
360
361 //
362 // If none of the specialized versions above matched, default to calling member function.
363 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
364 // The compiler will only cast int to long if none of the other templates matched.
365 // Thanks to Boost serialization for this idea.
366 //
367 template<typename T>
368 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
369 {
370     return a.GetSerializeSize((int)nType, nVersion);
371 }
372
373 template<typename Stream, typename T>
374 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
375 {
376     a.Serialize(os, (int)nType, nVersion);
377 }
378
379 template<typename Stream, typename T>
380 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
381 {
382     a.Unserialize(is, (int)nType, nVersion);
383 }
384
385
386
387
388 //
389 // string
390 //
391 template<typename C>
392 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
393 {
394     return (unsigned int)(GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]));
395 }
396
397 template<typename Stream, typename C>
398 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
399 {
400     WriteCompactSize(os, str.size());
401     if (!str.empty())
402         os.write((char*)&str[0], (int)(str.size() * sizeof(str[0])));
403 }
404
405 template<typename Stream, typename C>
406 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
407 {
408     unsigned int nSize = (unsigned int)(ReadCompactSize(is));
409     str.resize(nSize);
410     if (nSize != 0)
411         is.read((char*)&str[0], nSize * sizeof(str[0]));
412 }
413
414
415
416 //
417 // vector
418 //
419 template<typename T, typename A>
420 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
421 {
422     return (unsigned int)(GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
423 }
424
425 template<typename T, typename A>
426 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
427 {
428     unsigned int nSize = GetSizeOfCompactSize(v.size());
429     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
430         nSize += GetSerializeSize((*vi), nType, nVersion);
431     return nSize;
432 }
433
434 template<typename T, typename A>
435 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
436 {
437     return GetSerializeSize_impl(v, nType, nVersion, std::is_fundamental<T>());
438 }
439
440
441 template<typename Stream, typename T, typename A>
442 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
443 {
444     WriteCompactSize(os, v.size());
445     if (!v.empty())
446         os.write((char*)&v[0], (int)(v.size() * sizeof(T)));
447 }
448
449 template<typename Stream, typename T, typename A>
450 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
451 {
452     WriteCompactSize(os, v.size());
453     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
454         ::Serialize(os, (*vi), nType, nVersion);
455 }
456
457 template<typename Stream, typename T, typename A>
458 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
459 {
460     Serialize_impl(os, v, nType, nVersion, std::is_fundamental<T>());
461 }
462
463
464 template<typename Stream, typename T, typename A>
465 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
466 {
467     // Limit size per read so bogus size value won't cause out of memory
468     v.clear();
469     unsigned int nSize = (unsigned int)(ReadCompactSize(is));
470     unsigned int i = 0;
471     while (i < nSize)
472     {
473         unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
474         v.resize(i + blk);
475         is.read((char*)&v[i], blk * sizeof(T));
476         i += blk;
477     }
478 }
479
480 template<typename Stream, typename T, typename A>
481 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
482 {
483     v.clear();
484     unsigned int nSize = (unsigned int)(ReadCompactSize(is));
485     unsigned int i = 0;
486     unsigned int nMid = 0;
487     while (nMid < nSize)
488     {
489         nMid += 5000000 / sizeof(T);
490         if (nMid > nSize)
491             nMid = nSize;
492         v.resize(nMid);
493         for (; i < nMid; i++)
494             Unserialize(is, v[i], nType, nVersion);
495     }
496 }
497
498 template<typename Stream, typename T, typename A>
499 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
500 {
501     Unserialize_impl(is, v, nType, nVersion, std::is_fundamental<T>());
502 }
503
504
505
506 //
507 // others derived from vector
508 //
509 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
510 {
511     return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
512 }
513
514 template<typename Stream>
515 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
516 {
517     Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
518 }
519
520 template<typename Stream>
521 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
522 {
523     Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
524 }
525
526
527
528 //
529 // pair
530 //
531 template<typename K, typename T>
532 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
533 {
534     return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
535 }
536
537 template<typename Stream, typename K, typename T>
538 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
539 {
540     Serialize(os, item.first, nType, nVersion);
541     Serialize(os, item.second, nType, nVersion);
542 }
543
544 template<typename Stream, typename K, typename T>
545 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
546 {
547     Unserialize(is, item.first, nType, nVersion);
548     Unserialize(is, item.second, nType, nVersion);
549 }
550
551
552
553 //
554 // 3 tuple
555 //
556 template<typename T0, typename T1, typename T2>
557 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
558 {
559     unsigned int nSize = 0;
560     nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
561     nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
562     nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
563     return nSize;
564 }
565
566 template<typename Stream, typename T0, typename T1, typename T2>
567 void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
568 {
569     Serialize(os, std::get<0>(item), nType, nVersion);
570     Serialize(os, std::get<1>(item), nType, nVersion);
571     Serialize(os, std::get<2>(item), nType, nVersion);
572 }
573
574 template<typename Stream, typename T0, typename T1, typename T2>
575 void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion)
576 {
577     Unserialize(is, std::get<0>(item), nType, nVersion);
578     Unserialize(is, std::get<1>(item), nType, nVersion);
579     Unserialize(is, std::get<2>(item), nType, nVersion);
580 }
581
582
583
584 //
585 // map
586 //
587 template<typename K, typename T, typename Pred, typename A>
588 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
589 {
590     unsigned int nSize = GetSizeOfCompactSize(m.size());
591     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
592         nSize += GetSerializeSize((*mi), nType, nVersion);
593     return nSize;
594 }
595
596 template<typename Stream, typename K, typename T, typename Pred, typename A>
597 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
598 {
599     WriteCompactSize(os, m.size());
600     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
601         Serialize(os, (*mi), nType, nVersion);
602 }
603
604 template<typename Stream, typename K, typename T, typename Pred, typename A>
605 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
606 {
607     m.clear();
608     unsigned int nSize = (unsigned int)(ReadCompactSize(is));
609     typename std::map<K, T, Pred, A>::iterator mi = m.begin();
610     for (unsigned int i = 0; i < nSize; i++)
611     {
612         std::pair<K, T> item;
613         Unserialize(is, item, nType, nVersion);
614         mi = m.insert(mi, item);
615     }
616 }
617
618
619
620 //
621 // set
622 //
623 template<typename K, typename Pred, typename A>
624 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
625 {
626     unsigned int nSize = GetSizeOfCompactSize(m.size());
627     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
628         nSize += GetSerializeSize((*it), nType, nVersion);
629     return nSize;
630 }
631
632 template<typename Stream, typename K, typename Pred, typename A>
633 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
634 {
635     WriteCompactSize(os, m.size());
636     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
637         Serialize(os, (*it), nType, nVersion);
638 }
639
640 template<typename Stream, typename K, typename Pred, typename A>
641 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
642 {
643     m.clear();
644     unsigned int nSize = ReadCompactSize(is);
645     typename std::set<K, Pred, A>::iterator it = m.begin();
646     for (unsigned int i = 0; i < nSize; i++)
647     {
648         K key;
649         Unserialize(is, key, nType, nVersion);
650         it = m.insert(it, key);
651     }
652 }
653
654
655
656 //
657 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
658 //
659 class CSerActionGetSerializeSize { };
660 class CSerActionSerialize { };
661 class CSerActionUnserialize { };
662
663 template<typename Stream, typename T>
664 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
665 {
666     return ::GetSerializeSize(obj, nType, nVersion);
667 }
668
669 template<typename Stream, typename T>
670 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
671 {
672     ::Serialize(s, obj, nType, nVersion);
673     return 0;
674 }
675
676 template<typename Stream, typename T>
677 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
678 {
679     ::Unserialize(s, obj, nType, nVersion);
680     return 0;
681 }
682
683 struct ser_streamplaceholder
684 {
685     int nType;
686     int nVersion;
687 };
688
689
690
691
692 typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
693
694 /** Double ended buffer combining vector and stream-like interfaces.
695  *
696  * >> and << read and write unformatted data using the above serialization templates.
697  * Fills with data in linear time; some stringstream implementations take N^2 time.
698  */
699 class CDataStream
700 {
701 protected:
702     typedef CSerializeData vector_type;
703     vector_type vch;
704     unsigned int nReadPos;
705     short state;
706     short exceptmask;
707 public:
708     int nType;
709     int nVersion;
710
711     typedef vector_type::allocator_type   allocator_type;
712     typedef vector_type::size_type        size_type;
713     typedef vector_type::difference_type  difference_type;
714     typedef vector_type::reference        reference;
715     typedef vector_type::const_reference  const_reference;
716     typedef vector_type::value_type       value_type;
717     typedef vector_type::iterator         iterator;
718     typedef vector_type::const_iterator   const_iterator;
719     typedef vector_type::reverse_iterator reverse_iterator;
720
721     explicit CDataStream(int nTypeIn, int nVersionIn)
722     {
723         Init(nTypeIn, nVersionIn);
724     }
725
726     CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
727     {
728         Init(nTypeIn, nVersionIn);
729     }
730
731     CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
732     {
733         Init(nTypeIn, nVersionIn);
734     }
735
736     CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
737     {
738         Init(nTypeIn, nVersionIn);
739     }
740
741     CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
742     {
743         Init(nTypeIn, nVersionIn);
744     }
745
746     CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
747     {
748         Init(nTypeIn, nVersionIn);
749     }
750
751     void Init(int nTypeIn, int nVersionIn)
752     {
753         nReadPos = 0;
754         nType = nTypeIn;
755         nVersion = nVersionIn;
756         state = 0;
757         exceptmask = std::ios::badbit | std::ios::failbit;
758     }
759
760     CDataStream& operator+=(const CDataStream& b)
761     {
762         vch.insert(vch.end(), b.begin(), b.end());
763         return *this;
764     }
765
766     friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
767     {
768         CDataStream ret = a;
769         ret += b;
770         return (ret);
771     }
772
773     std::string str() const
774     {
775         return (std::string(begin(), end()));
776     }
777
778
779     //
780     // Vector subset
781     //
782     const_iterator begin() const                     { return vch.begin() + nReadPos; }
783     iterator begin()                                 { return vch.begin() + nReadPos; }
784     const_iterator end() const                       { return vch.end(); }
785     iterator end()                                   { return vch.end(); }
786     size_type size() const                           { return vch.size() - nReadPos; }
787     bool empty() const                               { return vch.size() == nReadPos; }
788     void resize(size_type n, value_type c=0)         { vch.resize(n + nReadPos, c); }
789     void reserve(size_type n)                        { vch.reserve(n + nReadPos); }
790     const_reference operator[](size_type pos) const  { return vch[pos + nReadPos]; }
791     reference operator[](size_type pos)              { return vch[pos + nReadPos]; }
792     void clear()                                     { vch.clear(); nReadPos = 0; }
793     iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
794     void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
795
796     void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
797     {
798         assert(last - first >= 0);
799         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
800         {
801             // special case for inserting at the front when there's room
802             nReadPos -= (last - first);
803             memcpy(&vch[nReadPos], &first[0], last - first);
804         }
805         else
806             vch.insert(it, first, last);
807     }
808
809     void insert(iterator it, const char* first, const char* last)
810     {
811         assert(last - first >= 0);
812         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
813         {
814             // special case for inserting at the front when there's room
815             nReadPos -= (unsigned int)(last - first);
816             memcpy(&vch[nReadPos], &first[0], last - first);
817         }
818         else
819             vch.insert(it, first, last);
820     }
821
822     iterator erase(iterator it)
823     {
824         if (it == vch.begin() + nReadPos)
825         {
826             // special case for erasing from the front
827             if (++nReadPos >= vch.size())
828             {
829                 // whenever we reach the end, we take the opportunity to clear the buffer
830                 nReadPos = 0;
831                 return vch.erase(vch.begin(), vch.end());
832             }
833             return vch.begin() + nReadPos;
834         }
835         else
836             return vch.erase(it);
837     }
838
839     iterator erase(iterator first, iterator last)
840     {
841         if (first == vch.begin() + nReadPos)
842         {
843             // special case for erasing from the front
844             if (last == vch.end())
845             {
846                 nReadPos = 0;
847                 return vch.erase(vch.begin(), vch.end());
848             }
849             else
850             {
851                 nReadPos = (unsigned int)(last - vch.begin());
852                 return last;
853             }
854         }
855         else
856             return vch.erase(first, last);
857     }
858
859     inline void Compact()
860     {
861         vch.erase(vch.begin(), vch.begin() + nReadPos);
862         nReadPos = 0;
863     }
864
865     bool Rewind(size_type n);
866
867     //
868     // Stream subset
869     //
870     void setstate(short bits, const char* psz);
871     bool eof() const             { return size() == 0; }
872     bool fail() const            { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
873     bool good() const            { return !eof() && (state == 0); }
874     void clear(short n)          { state = n; }  // name conflict with vector clear()
875     short exceptions()           { return exceptmask; }
876     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
877     CDataStream* rdbuf()         { return this; }
878     int in_avail()               { return (int)(size()); }
879
880     void SetType(int n)          { nType = n; }
881     int GetType()                { return nType; }
882     void SetVersion(int n)       { nVersion = n; }
883     int GetVersion()             { return nVersion; }
884     void ReadVersion()           { *this >> nVersion; }
885     void WriteVersion()          { *this << nVersion; }
886
887     CDataStream& read(char* pch, int nSize);
888     CDataStream& ignore(int nSize);
889     CDataStream& write(const char* pch, int nSize);
890
891     template<typename Stream>
892     void Serialize(Stream& s, int nType, int nVersion) const
893     {
894         // Special case: stream << stream concatenates like stream += stream
895         if (!vch.empty())
896             s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
897     }
898
899     template<typename T>
900     unsigned int GetSerializeSize(const T& obj)
901     {
902         // Tells the size of the object if serialized to this stream
903         return ::GetSerializeSize(obj, nType, nVersion);
904     }
905
906     template<typename T>
907     CDataStream& operator<<(const T& obj)
908     {
909         // Serialize to this stream
910         ::Serialize(*this, obj, nType, nVersion);
911         return (*this);
912     }
913
914     template<typename T>
915     CDataStream& operator>>(T& obj)
916     {
917         // Unserialize from this stream
918         ::Unserialize(*this, obj, nType, nVersion);
919         return (*this);
920     }
921
922     void GetAndClear(CSerializeData &data);
923 };
924
925
926 // RAII wrapper for FILE*.
927 //
928 // Will automatically close the file when it goes out of scope if not null.
929 // If you're returning the file pointer, return file.release().
930 // If you need to close the file early, use file.fclose() instead of fclose(file).
931 class CAutoFile
932 {
933 protected:
934     FILE* file;
935     short state;
936     short exceptmask;
937 public:
938     int nType;
939     int nVersion;
940
941     CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn);
942     ~CAutoFile();
943     void fclose();
944
945     FILE* release()             { FILE* ret = file; file = NULL; return ret; }
946     operator FILE*()            { return file; }
947     FILE* operator->()          { return file; }
948     FILE& operator*()           { return *file; }
949     FILE** operator&()          { return &file; }
950     FILE* operator=(FILE* pnew) { return file = pnew; }
951     bool operator!()            { return (file == NULL); }
952
953
954     //
955     // Stream subset
956     //
957     void setstate(short bits, const char* psz);
958     bool fail() const            { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
959     bool good() const            { return state == 0; }
960     void clear(short n = 0)      { state = n; }
961     short exceptions()           { return exceptmask; }
962     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
963
964     void SetType(int n)          { nType = n; }
965     int GetType()                { return nType; }
966     void SetVersion(int n)       { nVersion = n; }
967     int GetVersion()             { return nVersion; }
968     void ReadVersion()           { *this >> nVersion; }
969     void WriteVersion()          { *this << nVersion; }
970
971     CAutoFile& read(char* pch, size_t nSize);
972     CAutoFile& write(const char* pch, size_t nSize);
973
974     template<typename T>
975     unsigned int GetSerializeSize(const T& obj)
976     {
977         // Tells the size of the object if serialized to this stream
978         return ::GetSerializeSize(obj, nType, nVersion);
979     }
980
981     template<typename T>
982     CAutoFile& operator<<(const T& obj)
983     {
984         // Serialize to this stream
985         if (!file)
986             throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
987         ::Serialize(*this, obj, nType, nVersion);
988         return (*this);
989     }
990
991     template<typename T>
992     CAutoFile& operator>>(T& obj)
993     {
994         // Unserialize from this stream
995         if (!file)
996             throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
997         ::Unserialize(*this, obj, nType, nVersion);
998         return (*this);
999     }
1000 };
1001
1002 // Wrapper around a FILE* that implements a ring buffer to
1003 // deserialize from. It guarantees the ability to rewind
1004 // a given number of bytes.
1005 class CBufferedFile
1006 {
1007 private:
1008     FILE *src;          // source file
1009     uint64_t nSrcPos;     // how many bytes have been read from source
1010     uint64_t nReadPos;    // how many bytes have been read from this
1011     uint64_t nReadLimit;  // up to which position we're allowed to read
1012     uint64_t nRewind;     // how many bytes we guarantee to rewind
1013     std::vector<char> vchBuf; // the buffer
1014
1015     short state;
1016     short exceptmask;
1017
1018 protected:
1019     void setstate(short bits, const char *psz);
1020     // read data from the source to fill the buffer
1021     bool Fill();
1022
1023 public:
1024     int nType;
1025     int nVersion;
1026
1027     CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn);
1028     // check whether no error occurred
1029     bool good() const;
1030     // check whether we're at the end of the source file
1031     bool eof() const;
1032     // read a number of bytes
1033     CBufferedFile& read(char *pch, size_t nSize);
1034     // return the current reading position
1035     uint64_t GetPos();
1036     // rewind to a given reading position
1037     bool SetPos(uint64_t nPos);
1038     bool Seek(uint64_t nPos);
1039     // prevent reading beyond a certain position
1040     // no argument removes the limit
1041     bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max());
1042
1043     template<typename T>
1044     CBufferedFile& operator>>(T& obj) {
1045         // Unserialize from this stream
1046         ::Unserialize(*this, obj, nType, nVersion);
1047         return (*this);
1048     }
1049
1050     // search for a given byte in the stream, and remain positioned on it
1051     void FindByte(char ch);
1052 };
1053
1054 #endif