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