Wip: more compact serialize.h
[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 #if !defined(_MSC_VER) || _MSC_VER >= 1300
781     CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
782     {
783         Init(nTypeIn, nVersionIn);
784     }
785 #endif
786
787     CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
788     {
789         Init(nTypeIn, nVersionIn);
790     }
791
792     CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
793     {
794         Init(nTypeIn, nVersionIn);
795     }
796
797     CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
798     {
799         Init(nTypeIn, nVersionIn);
800     }
801
802     void Init(int nTypeIn, int nVersionIn)
803     {
804         nReadPos = 0;
805         nType = nTypeIn;
806         nVersion = nVersionIn;
807         state = 0;
808         exceptmask = std::ios::badbit | std::ios::failbit;
809     }
810
811     CDataStream& operator+=(const CDataStream& b)
812     {
813         vch.insert(vch.end(), b.begin(), b.end());
814         return *this;
815     }
816
817     friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
818     {
819         CDataStream ret = a;
820         ret += b;
821         return (ret);
822     }
823
824     std::string str() const
825     {
826         return (std::string(begin(), end()));
827     }
828
829
830     //
831     // Vector subset
832     //
833     const_iterator begin() const                     { return vch.begin() + nReadPos; }
834     iterator begin()                                 { return vch.begin() + nReadPos; }
835     const_iterator end() const                       { return vch.end(); }
836     iterator end()                                   { return vch.end(); }
837     size_type size() const                           { return vch.size() - nReadPos; }
838     bool empty() const                               { return vch.size() == nReadPos; }
839     void resize(size_type n, value_type c=0)         { vch.resize(n + nReadPos, c); }
840     void reserve(size_type n)                        { vch.reserve(n + nReadPos); }
841     const_reference operator[](size_type pos) const  { return vch[pos + nReadPos]; }
842     reference operator[](size_type pos)              { return vch[pos + nReadPos]; }
843     void clear()                                     { vch.clear(); nReadPos = 0; }
844     iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
845     void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
846
847 #ifdef _MSC_VER
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 #endif
861
862 #ifndef _MSC_VER
863     void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
864     {
865         assert(last - first >= 0);
866         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
867         {
868             // special case for inserting at the front when there's room
869             nReadPos -= (last - first);
870             memcpy(&vch[nReadPos], &first[0], last - first);
871         }
872         else
873             vch.insert(it, first, last);
874     }
875 #endif
876
877 #if !defined(_MSC_VER) || _MSC_VER >= 1300
878     void insert(iterator it, const char* first, const char* last)
879     {
880         assert(last - first >= 0);
881         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
882         {
883             // special case for inserting at the front when there's room
884             nReadPos -= (unsigned int)(last - first);
885             memcpy(&vch[nReadPos], &first[0], last - first);
886         }
887         else
888             vch.insert(it, first, last);
889     }
890 #endif
891
892     iterator erase(iterator it)
893     {
894         if (it == vch.begin() + nReadPos)
895         {
896             // special case for erasing from the front
897             if (++nReadPos >= vch.size())
898             {
899                 // whenever we reach the end, we take the opportunity to clear the buffer
900                 nReadPos = 0;
901                 return vch.erase(vch.begin(), vch.end());
902             }
903             return vch.begin() + nReadPos;
904         }
905         else
906             return vch.erase(it);
907     }
908
909     iterator erase(iterator first, iterator last)
910     {
911         if (first == vch.begin() + nReadPos)
912         {
913             // special case for erasing from the front
914             if (last == vch.end())
915             {
916                 nReadPos = 0;
917                 return vch.erase(vch.begin(), vch.end());
918             }
919             else
920             {
921                 nReadPos = (unsigned int)(last - vch.begin());
922                 return last;
923             }
924         }
925         else
926             return vch.erase(first, last);
927     }
928
929     inline void Compact()
930     {
931         vch.erase(vch.begin(), vch.begin() + nReadPos);
932         nReadPos = 0;
933     }
934
935     bool Rewind(size_type n)
936     {
937         // Rewind by n characters if the buffer hasn't been compacted yet
938         if (n > nReadPos)
939             return false;
940         nReadPos -= (unsigned int)n;
941         return true;
942     }
943
944
945     //
946     // Stream subset
947     //
948     void setstate(short bits, const char* psz)
949     {
950         state |= bits;
951         if (state & exceptmask)
952             throw std::ios_base::failure(psz);
953     }
954
955     bool eof() const             { return size() == 0; }
956     bool fail() const            { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
957     bool good() const            { return !eof() && (state == 0); }
958     void clear(short n)          { state = n; }  // name conflict with vector clear()
959     short exceptions()           { return exceptmask; }
960     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
961     CDataStream* rdbuf()         { return this; }
962     int in_avail()               { return (int)(size()); }
963
964     void SetType(int n)          { nType = n; }
965     int GetType()                { return nType; }
966     void SetVersion(int n)       { nVersion = n; }
967     int GetVersion()             { return nVersion; }
968     void ReadVersion()           { *this >> nVersion; }
969     void WriteVersion()          { *this << nVersion; }
970
971     CDataStream& read(char* pch, int nSize)
972     {
973         // Read from the beginning of the buffer
974         assert(nSize >= 0);
975         unsigned int nReadPosNext = nReadPos + nSize;
976         if (nReadPosNext >= vch.size())
977         {
978             if (nReadPosNext > vch.size())
979             {
980                 setstate(std::ios::failbit, "CDataStream::read() : end of data");
981                 memset(pch, 0, nSize);
982                 nSize = (int)(vch.size() - nReadPos);
983             }
984             memcpy(pch, &vch[nReadPos], nSize);
985             nReadPos = 0;
986             vch.clear();
987             return (*this);
988         }
989         memcpy(pch, &vch[nReadPos], nSize);
990         nReadPos = nReadPosNext;
991         return (*this);
992     }
993
994     CDataStream& ignore(int nSize)
995     {
996         // Ignore from the beginning of the buffer
997         assert(nSize >= 0);
998         unsigned int nReadPosNext = nReadPos + nSize;
999         if (nReadPosNext >= vch.size())
1000         {
1001             if (nReadPosNext > vch.size())
1002                 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1003             nReadPos = 0;
1004             vch.clear();
1005             return (*this);
1006         }
1007         nReadPos = nReadPosNext;
1008         return (*this);
1009     }
1010
1011     CDataStream& write(const char* pch, int nSize)
1012     {
1013         // Write to the end of the buffer
1014         assert(nSize >= 0);
1015         vch.insert(vch.end(), pch, pch + nSize);
1016         return (*this);
1017     }
1018
1019     template<typename Stream>
1020     void Serialize(Stream& s, int nType, int nVersion) const
1021     {
1022         // Special case: stream << stream concatenates like stream += stream
1023         if (!vch.empty())
1024             s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1025     }
1026
1027     template<typename T>
1028     unsigned int GetSerializeSize(const T& obj)
1029     {
1030         // Tells the size of the object if serialized to this stream
1031         return ::GetSerializeSize(obj, nType, nVersion);
1032     }
1033
1034     template<typename T>
1035     CDataStream& operator<<(const T& obj)
1036     {
1037         // Serialize to this stream
1038         ::Serialize(*this, obj, nType, nVersion);
1039         return (*this);
1040     }
1041
1042     template<typename T>
1043     CDataStream& operator>>(T& obj)
1044     {
1045         // Unserialize from this stream
1046         ::Unserialize(*this, obj, nType, nVersion);
1047         return (*this);
1048     }
1049
1050     void GetAndClear(CSerializeData &data) {
1051         vch.swap(data);
1052         CSerializeData().swap(vch);
1053     }
1054 };
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065 /** RAII wrapper for FILE*.
1066  *
1067  * Will automatically close the file when it goes out of scope if not null.
1068  * If you're returning the file pointer, return file.release().
1069  * If you need to close the file early, use file.fclose() instead of fclose(file).
1070  */
1071 class CAutoFile
1072 {
1073 protected:
1074     FILE* file;
1075     short state;
1076     short exceptmask;
1077 public:
1078     int nType;
1079     int nVersion;
1080
1081     CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
1082     {
1083         file = filenew;
1084         nType = nTypeIn;
1085         nVersion = nVersionIn;
1086         state = 0;
1087         exceptmask = std::ios::badbit | std::ios::failbit;
1088     }
1089
1090     ~CAutoFile()
1091     {
1092         fclose();
1093     }
1094
1095     void fclose()
1096     {
1097         if (file != NULL && file != stdin && file != stdout && file != stderr)
1098             ::fclose(file);
1099         file = NULL;
1100     }
1101
1102     FILE* release()             { FILE* ret = file; file = NULL; return ret; }
1103     operator FILE*()            { return file; }
1104     FILE* operator->()          { return file; }
1105     FILE& operator*()           { return *file; }
1106     FILE** operator&()          { return &file; }
1107     FILE* operator=(FILE* pnew) { return file = pnew; }
1108     bool operator!()            { return (file == NULL); }
1109
1110
1111     //
1112     // Stream subset
1113     //
1114     void setstate(short bits, const char* psz)
1115     {
1116         state |= bits;
1117         if (state & exceptmask)
1118             throw std::ios_base::failure(psz);
1119     }
1120
1121     bool fail() const            { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1122     bool good() const            { return state == 0; }
1123     void clear(short n = 0)      { state = n; }
1124     short exceptions()           { return exceptmask; }
1125     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1126
1127     void SetType(int n)          { nType = n; }
1128     int GetType()                { return nType; }
1129     void SetVersion(int n)       { nVersion = n; }
1130     int GetVersion()             { return nVersion; }
1131     void ReadVersion()           { *this >> nVersion; }
1132     void WriteVersion()          { *this << nVersion; }
1133
1134     CAutoFile& read(char* pch, size_t nSize)
1135     {
1136         if (!file)
1137             throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1138         if (fread(pch, 1, nSize, file) != nSize)
1139             setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1140         return (*this);
1141     }
1142
1143     CAutoFile& write(const char* pch, size_t nSize)
1144     {
1145         if (!file)
1146             throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1147         if (fwrite(pch, 1, nSize, file) != nSize)
1148             setstate(std::ios::failbit, "CAutoFile::write : write failed");
1149         return (*this);
1150     }
1151
1152     template<typename T>
1153     unsigned int GetSerializeSize(const T& obj)
1154     {
1155         // Tells the size of the object if serialized to this stream
1156         return ::GetSerializeSize(obj, nType, nVersion);
1157     }
1158
1159     template<typename T>
1160     CAutoFile& operator<<(const T& obj)
1161     {
1162         // Serialize to this stream
1163         if (!file)
1164             throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1165         ::Serialize(*this, obj, nType, nVersion);
1166         return (*this);
1167     }
1168
1169     template<typename T>
1170     CAutoFile& operator>>(T& obj)
1171     {
1172         // Unserialize from this stream
1173         if (!file)
1174             throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1175         ::Unserialize(*this, obj, nType, nVersion);
1176         return (*this);
1177     }
1178 };
1179
1180 // Wrapper around a FILE* that implements a ring buffer to
1181 // deserialize from. It guarantees the ability to rewind
1182 // a given number of bytes.
1183 class CBufferedFile
1184 {
1185 private:
1186     FILE *src;          // source file
1187     uint64_t nSrcPos;     // how many bytes have been read from source
1188     uint64_t nReadPos;    // how many bytes have been read from this
1189     uint64_t nReadLimit;  // up to which position we're allowed to read
1190     uint64_t nRewind;     // how many bytes we guarantee to rewind
1191     std::vector<char> vchBuf; // the buffer
1192
1193     short state;
1194     short exceptmask;
1195
1196 protected:
1197     void setstate(short bits, const char *psz);
1198     // read data from the source to fill the buffer
1199     bool Fill();
1200
1201 public:
1202     int nType;
1203     int nVersion;
1204
1205     CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn);
1206     // check whether no error occurred
1207     bool good() const;
1208     // check whether we're at the end of the source file
1209     bool eof() const;
1210     // read a number of bytes
1211     CBufferedFile& read(char *pch, size_t nSize);
1212     // return the current reading position
1213     uint64_t GetPos();
1214     // rewind to a given reading position
1215     bool SetPos(uint64_t nPos);
1216     bool Seek(uint64_t nPos);
1217     // prevent reading beyond a certain position
1218     // no argument removes the limit
1219     bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max());
1220
1221     template<typename T>
1222     CBufferedFile& operator>>(T& obj) {
1223         // Unserialize from this stream
1224         ::Unserialize(*this, obj, nType, nVersion);
1225         return (*this);
1226     }
1227
1228     // search for a given byte in the stream, and remain positioned on it
1229     void FindByte(char ch);
1230 };
1231
1232 #endif