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