Fix msvc c4127 warning
[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
17 #ifndef Q_MOC_RUN
18 #include <boost/type_traits/is_fundamental.hpp>
19 #include <boost/tuple/tuple.hpp>
20 #include <boost/tuple/tuple_comparison.hpp>
21 #include <boost/tuple/tuple_io.hpp>
22 #endif
23
24 #if defined __USE_MINGW_ANSI_STDIO
25 #undef __USE_MINGW_ANSI_STDIO // This constant forces MinGW to conduct stupid behavior
26 #endif
27 #include <inttypes.h>
28
29 #include "allocators.h"
30 #include "version.h"
31
32
33 class CScript;
34 class CDataStream;
35 class CAutoFile;
36 static const unsigned int MAX_SIZE = 0x02000000;
37
38 // Used to bypass the rule against non-const reference to temporary
39 // where it makes sense with wrappers such as CFlatData or CTxDB
40 template<typename T>
41 inline T& REF(const T& val)
42 {
43     return const_cast<T&>(val);
44 }
45
46 /////////////////////////////////////////////////////////////////
47 //
48 // Templates for serializing to anything that looks like a stream,
49 // i.e. anything that supports .read(char*, int) and .write(char*, int)
50 //
51
52 enum
53 {
54     // primary actions
55     SER_NETWORK         = (1 << 0),
56     SER_DISK            = (1 << 1),
57     SER_GETHASH         = (1 << 2),
58
59          // modifiers
60          SER_SKIPSIG = (1 << 16),
61          SER_BLOCKHEADERONLY = (1 << 17),
62
63 };
64
65 #ifdef _MSC_VER
66 #define IMPLEMENT_SERIALIZE(statements)    \
67     unsigned int GetSerializeSize(int nType, int nVersion) const  \
68     {                                           \
69         CSerActionGetSerializeSize ser_action;  \
70         const bool fGetSize = true;             \
71         const bool fWrite = false;              \
72         const bool fRead = false;               \
73         unsigned int nSerSize = 0;              \
74         ser_streamplaceholder s;                \
75         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
76         s.nType = nType;                        \
77         s.nVersion = nVersion;                  \
78         std::map<int, int>  mapUnkIds;          \
79         {statements}                            \
80         return nSerSize;                        \
81     }                                           \
82     template<typename Stream>                   \
83     void Serialize(Stream& s, int nType, int nVersion) const  \
84     {                                           \
85         CSerActionSerialize ser_action;         \
86         const bool fGetSize = false;            \
87         const bool fWrite = true;               \
88         const bool fRead = false;               \
89         unsigned int nSerSize = 0;              \
90         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
91     std::map<int, int>  mapUnkIds;  \
92         {statements}                            \
93     }                                           \
94     template<typename Stream>                   \
95     void Unserialize(Stream& s, int nType, int nVersion)  \
96     {                                           \
97         CSerActionUnserialize ser_action;       \
98         const bool fGetSize = false;            \
99         const bool fWrite = false;              \
100         const bool fRead = true;                \
101         unsigned int nSerSize = 0;              \
102     std::map<int, int>  mapUnkIds;  \
103         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
104         {statements}                            \
105     }
106
107 #else
108
109 #define IMPLEMENT_SERIALIZE(statements)    \
110     unsigned int GetSerializeSize(int nType, int nVersion) const  \
111     {                                           \
112         CSerActionGetSerializeSize ser_action;  \
113         const bool fGetSize = true;             \
114         const bool fWrite = false;              \
115         const bool fRead = false;               \
116         unsigned int nSerSize = 0;              \
117         ser_streamplaceholder s;                \
118         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
119         s.nType = nType;                        \
120         s.nVersion = nVersion;                  \
121         {statements}                            \
122         return nSerSize;                        \
123     }                                           \
124     template<typename Stream>                   \
125     void Serialize(Stream& s, int nType, int nVersion) const  \
126     {                                           \
127         CSerActionSerialize ser_action;         \
128         const bool fGetSize = false;            \
129         const bool fWrite = true;               \
130         const bool fRead = false;               \
131         unsigned int nSerSize = 0;              \
132         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
133         {statements}                            \
134     }                                           \
135     template<typename Stream>                   \
136     void Unserialize(Stream& s, int nType, int nVersion)  \
137     {                                           \
138         CSerActionUnserialize ser_action;       \
139         const bool fGetSize = false;            \
140         const bool fWrite = false;              \
141         const bool fRead = true;                \
142         unsigned int nSerSize = 0;              \
143         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
144         {statements}                            \
145     }
146
147 #endif
148
149 #define READWRITE(obj)      (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
150
151
152
153
154
155
156 //
157 // Basic types
158 //
159 #define WRITEDATA(s, obj)   s.write((char*)&(obj), sizeof(obj))
160 #define READDATA(s, obj)    s.read((char*)&(obj), sizeof(obj))
161
162 inline unsigned int GetSerializeSize(char a,           int, int=0) { return sizeof(a); }
163 inline unsigned int GetSerializeSize(signed char a,    int, int=0) { return sizeof(a); }
164 inline unsigned int GetSerializeSize(unsigned char a,  int, int=0) { return sizeof(a); }
165 inline unsigned int GetSerializeSize(signed short a,   int, int=0) { return sizeof(a); }
166 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
167 inline unsigned int GetSerializeSize(signed int a,     int, int=0) { return sizeof(a); }
168 inline unsigned int GetSerializeSize(unsigned int a,   int, int=0) { return sizeof(a); }
169 //inline unsigned int GetSerializeSize(signed long a,    int, int=0) { return sizeof(a); }
170 //inline unsigned int GetSerializeSize(unsigned long a,  int, int=0) { return sizeof(a); }
171 inline unsigned int GetSerializeSize(int64_t a,    int, int=0) { return sizeof(a); }
172 inline unsigned int GetSerializeSize(uint64_t a,  int, int=0) { return sizeof(a); }
173 inline unsigned int GetSerializeSize(float a,          int, int=0) { return sizeof(a); }
174 inline unsigned int GetSerializeSize(double a,         int, int=0) { return sizeof(a); }
175
176 template<typename Stream> inline void Serialize(Stream& s, char a,           int, int=0) { WRITEDATA(s, a); }
177 template<typename Stream> inline void Serialize(Stream& s, signed char a,    int, int=0) { WRITEDATA(s, a); }
178 template<typename Stream> inline void Serialize(Stream& s, unsigned char a,  int, int=0) { WRITEDATA(s, a); }
179 template<typename Stream> inline void Serialize(Stream& s, signed short a,   int, int=0) { WRITEDATA(s, a); }
180 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
181 template<typename Stream> inline void Serialize(Stream& s, signed int a,     int, int=0) { WRITEDATA(s, a); }
182 template<typename Stream> inline void Serialize(Stream& s, unsigned int a,   int, int=0) { WRITEDATA(s, a); }
183 //template<typename Stream> inline void Serialize(Stream& s, signed long a,    int, int=0) { WRITEDATA(s, a); }
184 //template<typename Stream> inline void Serialize(Stream& s, unsigned long a,  int, int=0) { WRITEDATA(s, a); }
185 template<typename Stream> inline void Serialize(Stream& s, int64_t a,    int, int=0) { WRITEDATA(s, a); }
186 template<typename Stream> inline void Serialize(Stream& s, uint64_t a,  int, int=0) { WRITEDATA(s, a); }
187 template<typename Stream> inline void Serialize(Stream& s, float a,          int, int=0) { WRITEDATA(s, a); }
188 template<typename Stream> inline void Serialize(Stream& s, double a,         int, int=0) { WRITEDATA(s, a); }
189
190 template<typename Stream> inline void Unserialize(Stream& s, char& a,           int, int=0) { READDATA(s, a); }
191 template<typename Stream> inline void Unserialize(Stream& s, signed char& a,    int, int=0) { READDATA(s, a); }
192 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a,  int, int=0) { READDATA(s, a); }
193 template<typename Stream> inline void Unserialize(Stream& s, signed short& a,   int, int=0) { READDATA(s, a); }
194 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
195 template<typename Stream> inline void Unserialize(Stream& s, signed int& a,     int, int=0) { READDATA(s, a); }
196 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a,   int, int=0) { READDATA(s, a); }
197 //template<typename Stream> inline void Unserialize(Stream& s, signed long& a,    int, int=0) { READDATA(s, a); }
198 //template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a,  int, int=0) { READDATA(s, a); }
199 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a,    int, int=0) { READDATA(s, a); }
200 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a,  int, int=0) { READDATA(s, a); }
201 template<typename Stream> inline void Unserialize(Stream& s, float& a,          int, int=0) { READDATA(s, a); }
202 template<typename Stream> inline void Unserialize(Stream& s, double& a,         int, int=0) { READDATA(s, a); }
203
204 inline unsigned int GetSerializeSize(bool a, int, int=0)                          { return sizeof(char); }
205 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0)    { char f=a; WRITEDATA(s, f); }
206 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
207
208
209
210
211
212
213 //
214 // Compact size
215 //  size <  253        -- 1 byte
216 //  size <= USHRT_MAX  -- 3 bytes  (253 + 2 bytes)
217 //  size <= UINT_MAX   -- 5 bytes  (254 + 4 bytes)
218 //  size >  UINT_MAX   -- 9 bytes  (255 + 8 bytes)
219 //
220 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
221 {
222     if (nSize < 253)             return sizeof(unsigned char);
223     else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
224     else if (nSize <= std::numeric_limits<unsigned int>::max())  return sizeof(unsigned char) + sizeof(unsigned int);
225     else                         return sizeof(unsigned char) + sizeof(uint64_t);
226 }
227
228 template<typename Stream>
229 void WriteCompactSize(Stream& os, uint64_t nSize)
230 {
231     if (nSize < 253)
232     {
233         unsigned char chSize = (unsigned char)nSize;
234         WRITEDATA(os, chSize);
235     }
236     else if (nSize <= std::numeric_limits<unsigned short>::max())
237     {
238         unsigned char chSize = 253;
239         unsigned short xSize = (unsigned short)nSize;
240         WRITEDATA(os, chSize);
241         WRITEDATA(os, xSize);
242     }
243     else if (nSize <= std::numeric_limits<unsigned int>::max())
244     {
245         unsigned char chSize = 254;
246         unsigned int xSize = (unsigned int)nSize;
247         WRITEDATA(os, chSize);
248         WRITEDATA(os, xSize);
249     }
250     else
251     {
252         unsigned char chSize = 255;
253         uint64_t xSize = nSize;
254         WRITEDATA(os, chSize);
255         WRITEDATA(os, xSize);
256     }
257     return;
258 }
259
260 template<typename Stream>
261 uint64_t ReadCompactSize(Stream& is)
262 {
263     unsigned char chSize;
264     READDATA(is, chSize);
265     uint64_t nSizeRet = 0;
266     if (chSize < 253)
267     {
268         nSizeRet = chSize;
269     }
270     else if (chSize == 253)
271     {
272         unsigned short xSize;
273         READDATA(is, xSize);
274         nSizeRet = xSize;
275     }
276     else if (chSize == 254)
277     {
278         unsigned int xSize;
279         READDATA(is, xSize);
280         nSizeRet = xSize;
281     }
282     else
283     {
284         uint64_t xSize;
285         READDATA(is, xSize);
286         nSizeRet = xSize;
287     }
288     if (nSizeRet > (uint64_t)MAX_SIZE)
289         throw std::ios_base::failure("ReadCompactSize() : size too large");
290     return nSizeRet;
291 }
292
293 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
294 // The high bit in each byte signifies whether another digit follows. To make
295 // the encoding is one-to-one, one is subtracted from all but the last digit.
296 // Thus, the byte sequence a[] with length len, where all but the last byte
297 // has bit 128 set, encodes the number:
298 //
299 //   (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
300 //
301 // Properties:
302 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
303 // * Every integer has exactly one encoding
304 // * Encoding does not depend on size of original integer type
305 // * No redundancy: every (infinite) byte sequence corresponds to a list
306 //   of encoded integers.
307 //
308 // 0:         [0x00]  256:        [0x81 0x00]
309 // 1:         [0x01]  16383:      [0xFE 0x7F]
310 // 127:       [0x7F]  16384:      [0xFF 0x00]
311 // 128:  [0x80 0x00]  16511: [0x80 0xFF 0x7F]
312 // 255:  [0x80 0x7F]  65535: [0x82 0xFD 0x7F]
313 // 2^32:           [0x8E 0xFE 0xFE 0xFF 0x00]
314
315 template<typename I>
316 inline unsigned int GetSizeOfVarInt(I n)
317 {
318     int nRet = 0;
319     while(true) {
320         nRet++;
321         if (n <= 0x7F)
322             break;
323         n = (n >> 7) - 1;
324     }
325     return nRet;
326 }
327
328 template<typename Stream, typename I>
329 void WriteVarInt(Stream& os, I n)
330 {
331     unsigned char tmp[(sizeof(n)*8+6)/7];
332     int len=0;
333     while(true) {
334         tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
335         if (n <= 0x7F)
336             break;
337         n = (n >> 7) - 1;
338         len++;
339     }
340     do {
341         WRITEDATA(os, tmp[len]);
342     } while(len--);
343 }
344
345 template<typename Stream, typename I>
346 I ReadVarInt(Stream& is)
347 {
348     I n = 0;
349     while(true) {
350         unsigned char chData;
351         READDATA(is, chData);
352         n = (n << 7) | (chData & 0x7F);
353         if (chData & 0x80)
354             n++;
355         else
356             return n;
357     }
358 }
359
360 #define FLATDATA(obj)  REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
361 #define VARINT(obj)    REF(WrapVarInt(REF(obj)))
362
363 /** Wrapper for serializing arrays and POD.
364  */
365 class CFlatData
366 {
367 protected:
368     char* pbegin;
369     char* pend;
370 public:
371     CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
372     char* begin() { return pbegin; }
373     const char* begin() const { return pbegin; }
374     char* end() { return pend; }
375     const char* end() const { return pend; }
376
377     unsigned int GetSerializeSize(int, int=0) const
378     {
379         return (unsigned int)(pend - pbegin);
380     }
381
382     template<typename Stream>
383     void Serialize(Stream& s, int, int=0) const
384     {
385         s.write(pbegin, (int)(pend - pbegin));
386     }
387
388     template<typename Stream>
389     void Unserialize(Stream& s, int, int=0)
390     {
391         s.read(pbegin, pend - pbegin);
392     }
393 };
394
395 template<typename I>
396 class CVarInt
397 {
398 protected:
399     I &n;
400 public:
401     CVarInt(I& nIn) : n(nIn) { }
402
403     unsigned int GetSerializeSize(int, int) const {
404         return GetSizeOfVarInt<I>(n);
405     }
406
407     template<typename Stream>
408     void Serialize(Stream &s, int, int) const {
409         WriteVarInt<Stream,I>(s, n);
410     }
411
412     template<typename Stream>
413     void Unserialize(Stream& s, int, int) {
414         n = ReadVarInt<Stream,I>(s);
415     }
416 };
417
418 template<typename I>
419 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
420
421 //
422 // Forward declarations
423 //
424
425 // string
426 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
427 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
428 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
429
430 // vector
431 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
432 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
433 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
434 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
435 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
436 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
437 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
438 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
439 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
440
441 // others derived from vector
442 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
443 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
444 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
445
446 // pair
447 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
448 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
449 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
450
451 // 3 tuple
452 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
453 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
454 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
455
456 // 4 tuple
457 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
458 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
459 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
460
461 // map
462 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
463 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);
464 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);
465
466 // set
467 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
468 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
469 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
470
471
472
473
474
475 //
476 // If none of the specialized versions above matched, default to calling member function.
477 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
478 // The compiler will only cast int to long if none of the other templates matched.
479 // Thanks to Boost serialization for this idea.
480 //
481 template<typename T>
482 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
483 {
484     return a.GetSerializeSize((int)nType, nVersion);
485 }
486
487 template<typename Stream, typename T>
488 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
489 {
490     a.Serialize(os, (int)nType, nVersion);
491 }
492
493 template<typename Stream, typename T>
494 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
495 {
496     a.Unserialize(is, (int)nType, nVersion);
497 }
498
499
500
501
502
503 //
504 // string
505 //
506 template<typename C>
507 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
508 {
509     return (unsigned int)(GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]));
510 }
511
512 template<typename Stream, typename C>
513 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
514 {
515     WriteCompactSize(os, str.size());
516     if (!str.empty())
517         os.write((char*)&str[0], (int)(str.size() * sizeof(str[0])));
518 }
519
520 template<typename Stream, typename C>
521 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
522 {
523     unsigned int nSize = (unsigned int)(ReadCompactSize(is));
524     str.resize(nSize);
525     if (nSize != 0)
526         is.read((char*)&str[0], nSize * sizeof(str[0]));
527 }
528
529
530
531 //
532 // vector
533 //
534 template<typename T, typename A>
535 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
536 {
537     return (unsigned int)(GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
538 }
539
540 template<typename T, typename A>
541 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
542 {
543     unsigned int nSize = GetSizeOfCompactSize(v.size());
544     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
545         nSize += GetSerializeSize((*vi), nType, nVersion);
546     return nSize;
547 }
548
549 template<typename T, typename A>
550 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
551 {
552     return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
553 }
554
555
556 template<typename Stream, typename T, typename A>
557 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
558 {
559     WriteCompactSize(os, v.size());
560     if (!v.empty())
561         os.write((char*)&v[0], (int)(v.size() * sizeof(T)));
562 }
563
564 template<typename Stream, typename T, typename A>
565 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
566 {
567     WriteCompactSize(os, v.size());
568     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
569         ::Serialize(os, (*vi), nType, nVersion);
570 }
571
572 template<typename Stream, typename T, typename A>
573 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
574 {
575     Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
576 }
577
578
579 template<typename Stream, typename T, typename A>
580 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
581 {
582     // Limit size per read so bogus size value won't cause out of memory
583     v.clear();
584     unsigned int nSize = (unsigned int)(ReadCompactSize(is));
585     unsigned int i = 0;
586     while (i < nSize)
587     {
588         unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
589         v.resize(i + blk);
590         is.read((char*)&v[i], blk * sizeof(T));
591         i += blk;
592     }
593 }
594
595 template<typename Stream, typename T, typename A>
596 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
597 {
598     v.clear();
599     unsigned int nSize = (unsigned int)(ReadCompactSize(is));
600     unsigned int i = 0;
601     unsigned int nMid = 0;
602     while (nMid < nSize)
603     {
604         nMid += 5000000 / sizeof(T);
605         if (nMid > nSize)
606             nMid = nSize;
607         v.resize(nMid);
608         for (; i < nMid; i++)
609             Unserialize(is, v[i], nType, nVersion);
610     }
611 }
612
613 template<typename Stream, typename T, typename A>
614 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
615 {
616     Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
617 }
618
619
620
621 //
622 // others derived from vector
623 //
624 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
625 {
626     return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
627 }
628
629 template<typename Stream>
630 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
631 {
632     Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
633 }
634
635 template<typename Stream>
636 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
637 {
638     Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
639 }
640
641
642
643 //
644 // pair
645 //
646 template<typename K, typename T>
647 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
648 {
649     return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
650 }
651
652 template<typename Stream, typename K, typename T>
653 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
654 {
655     Serialize(os, item.first, nType, nVersion);
656     Serialize(os, item.second, nType, nVersion);
657 }
658
659 template<typename Stream, typename K, typename T>
660 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
661 {
662     Unserialize(is, item.first, nType, nVersion);
663     Unserialize(is, item.second, nType, nVersion);
664 }
665
666
667
668 //
669 // 3 tuple
670 //
671 template<typename T0, typename T1, typename T2>
672 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
673 {
674     unsigned int nSize = 0;
675     nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
676     nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
677     nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
678     return nSize;
679 }
680
681 template<typename Stream, typename T0, typename T1, typename T2>
682 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
683 {
684     Serialize(os, boost::get<0>(item), nType, nVersion);
685     Serialize(os, boost::get<1>(item), nType, nVersion);
686     Serialize(os, boost::get<2>(item), nType, nVersion);
687 }
688
689 template<typename Stream, typename T0, typename T1, typename T2>
690 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
691 {
692     Unserialize(is, boost::get<0>(item), nType, nVersion);
693     Unserialize(is, boost::get<1>(item), nType, nVersion);
694     Unserialize(is, boost::get<2>(item), nType, nVersion);
695 }
696
697
698
699 //
700 // 4 tuple
701 //
702 template<typename T0, typename T1, typename T2, typename T3>
703 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
704 {
705     unsigned int nSize = 0;
706     nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
707     nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
708     nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
709     nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
710     return nSize;
711 }
712
713 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
714 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
715 {
716     Serialize(os, boost::get<0>(item), nType, nVersion);
717     Serialize(os, boost::get<1>(item), nType, nVersion);
718     Serialize(os, boost::get<2>(item), nType, nVersion);
719     Serialize(os, boost::get<3>(item), nType, nVersion);
720 }
721
722 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
723 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
724 {
725     Unserialize(is, boost::get<0>(item), nType, nVersion);
726     Unserialize(is, boost::get<1>(item), nType, nVersion);
727     Unserialize(is, boost::get<2>(item), nType, nVersion);
728     Unserialize(is, boost::get<3>(item), nType, nVersion);
729 }
730
731
732
733 //
734 // map
735 //
736 template<typename K, typename T, typename Pred, typename A>
737 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
738 {
739     unsigned int nSize = GetSizeOfCompactSize(m.size());
740     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
741         nSize += GetSerializeSize((*mi), nType, nVersion);
742     return nSize;
743 }
744
745 template<typename Stream, typename K, typename T, typename Pred, typename A>
746 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
747 {
748     WriteCompactSize(os, m.size());
749     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
750         Serialize(os, (*mi), nType, nVersion);
751 }
752
753 template<typename Stream, typename K, typename T, typename Pred, typename A>
754 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
755 {
756     m.clear();
757     unsigned int nSize = (unsigned int)(ReadCompactSize(is));
758     typename std::map<K, T, Pred, A>::iterator mi = m.begin();
759     for (unsigned int i = 0; i < nSize; i++)
760     {
761         std::pair<K, T> item;
762         Unserialize(is, item, nType, nVersion);
763         mi = m.insert(mi, item);
764     }
765 }
766
767
768
769 //
770 // set
771 //
772 template<typename K, typename Pred, typename A>
773 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
774 {
775     unsigned int nSize = GetSizeOfCompactSize(m.size());
776     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
777         nSize += GetSerializeSize((*it), nType, nVersion);
778     return nSize;
779 }
780
781 template<typename Stream, typename K, typename Pred, typename A>
782 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
783 {
784     WriteCompactSize(os, m.size());
785     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
786         Serialize(os, (*it), nType, nVersion);
787 }
788
789 template<typename Stream, typename K, typename Pred, typename A>
790 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
791 {
792     m.clear();
793     unsigned int nSize = ReadCompactSize(is);
794     typename std::set<K, Pred, A>::iterator it = m.begin();
795     for (unsigned int i = 0; i < nSize; i++)
796     {
797         K key;
798         Unserialize(is, key, nType, nVersion);
799         it = m.insert(it, key);
800     }
801 }
802
803
804
805 //
806 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
807 //
808 class CSerActionGetSerializeSize { };
809 class CSerActionSerialize { };
810 class CSerActionUnserialize { };
811
812 template<typename Stream, typename T>
813 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
814 {
815     return ::GetSerializeSize(obj, nType, nVersion);
816 }
817
818 template<typename Stream, typename T>
819 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
820 {
821     ::Serialize(s, obj, nType, nVersion);
822     return 0;
823 }
824
825 template<typename Stream, typename T>
826 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
827 {
828     ::Unserialize(s, obj, nType, nVersion);
829     return 0;
830 }
831
832 struct ser_streamplaceholder
833 {
834     int nType;
835     int nVersion;
836 };
837
838
839
840
841
842
843
844
845
846
847
848 typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
849
850 /** Double ended buffer combining vector and stream-like interfaces.
851  *
852  * >> and << read and write unformatted data using the above serialization templates.
853  * Fills with data in linear time; some stringstream implementations take N^2 time.
854  */
855 class CDataStream
856 {
857 protected:
858     typedef CSerializeData vector_type;
859     vector_type vch;
860     unsigned int nReadPos;
861     short state;
862     short exceptmask;
863 public:
864     int nType;
865     int nVersion;
866
867     typedef vector_type::allocator_type   allocator_type;
868     typedef vector_type::size_type        size_type;
869     typedef vector_type::difference_type  difference_type;
870     typedef vector_type::reference        reference;
871     typedef vector_type::const_reference  const_reference;
872     typedef vector_type::value_type       value_type;
873     typedef vector_type::iterator         iterator;
874     typedef vector_type::const_iterator   const_iterator;
875     typedef vector_type::reverse_iterator reverse_iterator;
876
877     explicit CDataStream(int nTypeIn, int nVersionIn)
878     {
879         Init(nTypeIn, nVersionIn);
880     }
881
882     CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
883     {
884         Init(nTypeIn, nVersionIn);
885     }
886
887 #if !defined(_MSC_VER) || _MSC_VER >= 1300
888     CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
889     {
890         Init(nTypeIn, nVersionIn);
891     }
892 #endif
893
894     CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
895     {
896         Init(nTypeIn, nVersionIn);
897     }
898
899     CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
900     {
901         Init(nTypeIn, nVersionIn);
902     }
903
904     CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
905     {
906         Init(nTypeIn, nVersionIn);
907     }
908
909     void Init(int nTypeIn, int nVersionIn)
910     {
911         nReadPos = 0;
912         nType = nTypeIn;
913         nVersion = nVersionIn;
914         state = 0;
915         exceptmask = std::ios::badbit | std::ios::failbit;
916     }
917
918     CDataStream& operator+=(const CDataStream& b)
919     {
920         vch.insert(vch.end(), b.begin(), b.end());
921         return *this;
922     }
923
924     friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
925     {
926         CDataStream ret = a;
927         ret += b;
928         return (ret);
929     }
930
931     std::string str() const
932     {
933         return (std::string(begin(), end()));
934     }
935
936
937     //
938     // Vector subset
939     //
940     const_iterator begin() const                     { return vch.begin() + nReadPos; }
941     iterator begin()                                 { return vch.begin() + nReadPos; }
942     const_iterator end() const                       { return vch.end(); }
943     iterator end()                                   { return vch.end(); }
944     size_type size() const                           { return vch.size() - nReadPos; }
945     bool empty() const                               { return vch.size() == nReadPos; }
946     void resize(size_type n, value_type c=0)         { vch.resize(n + nReadPos, c); }
947     void reserve(size_type n)                        { vch.reserve(n + nReadPos); }
948     const_reference operator[](size_type pos) const  { return vch[pos + nReadPos]; }
949     reference operator[](size_type pos)              { return vch[pos + nReadPos]; }
950     void clear()                                     { vch.clear(); nReadPos = 0; }
951     iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
952     void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
953
954 #ifdef _MSC_VER
955     void insert(iterator it, const_iterator first, const_iterator last)
956     {
957         assert(last - first >= 0);
958         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
959         {
960             // special case for inserting at the front when there's room
961             nReadPos -= (unsigned int)(last - first);
962             memcpy(&vch[nReadPos], &first[0], last - first);
963         }
964         else
965             vch.insert(it, first, last);
966     }
967 #endif
968
969 #ifndef _MSC_VER
970     void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
971     {
972         assert(last - first >= 0);
973         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
974         {
975             // special case for inserting at the front when there's room
976             nReadPos -= (last - first);
977             memcpy(&vch[nReadPos], &first[0], last - first);
978         }
979         else
980             vch.insert(it, first, last);
981     }
982 #endif
983
984 #if !defined(_MSC_VER) || _MSC_VER >= 1300
985     void insert(iterator it, const char* first, const char* last)
986     {
987         assert(last - first >= 0);
988         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
989         {
990             // special case for inserting at the front when there's room
991             nReadPos -= (unsigned int)(last - first);
992             memcpy(&vch[nReadPos], &first[0], last - first);
993         }
994         else
995             vch.insert(it, first, last);
996     }
997 #endif
998
999     iterator erase(iterator it)
1000     {
1001         if (it == vch.begin() + nReadPos)
1002         {
1003             // special case for erasing from the front
1004             if (++nReadPos >= vch.size())
1005             {
1006                 // whenever we reach the end, we take the opportunity to clear the buffer
1007                 nReadPos = 0;
1008                 return vch.erase(vch.begin(), vch.end());
1009             }
1010             return vch.begin() + nReadPos;
1011         }
1012         else
1013             return vch.erase(it);
1014     }
1015
1016     iterator erase(iterator first, iterator last)
1017     {
1018         if (first == vch.begin() + nReadPos)
1019         {
1020             // special case for erasing from the front
1021             if (last == vch.end())
1022             {
1023                 nReadPos = 0;
1024                 return vch.erase(vch.begin(), vch.end());
1025             }
1026             else
1027             {
1028                 nReadPos = (unsigned int)(last - vch.begin());
1029                 return last;
1030             }
1031         }
1032         else
1033             return vch.erase(first, last);
1034     }
1035
1036     inline void Compact()
1037     {
1038         vch.erase(vch.begin(), vch.begin() + nReadPos);
1039         nReadPos = 0;
1040     }
1041
1042     bool Rewind(size_type n)
1043     {
1044         // Rewind by n characters if the buffer hasn't been compacted yet
1045         if (n > nReadPos)
1046             return false;
1047         nReadPos -= (unsigned int)n;
1048         return true;
1049     }
1050
1051
1052     //
1053     // Stream subset
1054     //
1055     void setstate(short bits, const char* psz)
1056     {
1057         state |= bits;
1058         if (state & exceptmask)
1059             throw std::ios_base::failure(psz);
1060     }
1061
1062     bool eof() const             { return size() == 0; }
1063     bool fail() const            { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1064     bool good() const            { return !eof() && (state == 0); }
1065     void clear(short n)          { state = n; }  // name conflict with vector clear()
1066     short exceptions()           { return exceptmask; }
1067     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1068     CDataStream* rdbuf()         { return this; }
1069     int in_avail()               { return (int)(size()); }
1070
1071     void SetType(int n)          { nType = n; }
1072     int GetType()                { return nType; }
1073     void SetVersion(int n)       { nVersion = n; }
1074     int GetVersion()             { return nVersion; }
1075     void ReadVersion()           { *this >> nVersion; }
1076     void WriteVersion()          { *this << nVersion; }
1077
1078     CDataStream& read(char* pch, int nSize)
1079     {
1080         // Read from the beginning of the buffer
1081         assert(nSize >= 0);
1082         unsigned int nReadPosNext = nReadPos + nSize;
1083         if (nReadPosNext >= vch.size())
1084         {
1085             if (nReadPosNext > vch.size())
1086             {
1087                 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1088                 memset(pch, 0, nSize);
1089                 nSize = (int)(vch.size() - nReadPos);
1090             }
1091             memcpy(pch, &vch[nReadPos], nSize);
1092             nReadPos = 0;
1093             vch.clear();
1094             return (*this);
1095         }
1096         memcpy(pch, &vch[nReadPos], nSize);
1097         nReadPos = nReadPosNext;
1098         return (*this);
1099     }
1100
1101     CDataStream& ignore(int nSize)
1102     {
1103         // Ignore from the beginning of the buffer
1104         assert(nSize >= 0);
1105         unsigned int nReadPosNext = nReadPos + nSize;
1106         if (nReadPosNext >= vch.size())
1107         {
1108             if (nReadPosNext > vch.size())
1109                 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1110             nReadPos = 0;
1111             vch.clear();
1112             return (*this);
1113         }
1114         nReadPos = nReadPosNext;
1115         return (*this);
1116     }
1117
1118     CDataStream& write(const char* pch, int nSize)
1119     {
1120         // Write to the end of the buffer
1121         assert(nSize >= 0);
1122         vch.insert(vch.end(), pch, pch + nSize);
1123         return (*this);
1124     }
1125
1126     template<typename Stream>
1127     void Serialize(Stream& s, int nType, int nVersion) const
1128     {
1129         // Special case: stream << stream concatenates like stream += stream
1130         if (!vch.empty())
1131             s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1132     }
1133
1134     template<typename T>
1135     unsigned int GetSerializeSize(const T& obj)
1136     {
1137         // Tells the size of the object if serialized to this stream
1138         return ::GetSerializeSize(obj, nType, nVersion);
1139     }
1140
1141     template<typename T>
1142     CDataStream& operator<<(const T& obj)
1143     {
1144         // Serialize to this stream
1145         ::Serialize(*this, obj, nType, nVersion);
1146         return (*this);
1147     }
1148
1149     template<typename T>
1150     CDataStream& operator>>(T& obj)
1151     {
1152         // Unserialize from this stream
1153         ::Unserialize(*this, obj, nType, nVersion);
1154         return (*this);
1155     }
1156
1157     void GetAndClear(CSerializeData &data) {
1158         vch.swap(data);
1159         CSerializeData().swap(vch);
1160     }
1161 };
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172 /** RAII wrapper for FILE*.
1173  *
1174  * Will automatically close the file when it goes out of scope if not null.
1175  * If you're returning the file pointer, return file.release().
1176  * If you need to close the file early, use file.fclose() instead of fclose(file).
1177  */
1178 class CAutoFile
1179 {
1180 protected:
1181     FILE* file;
1182     short state;
1183     short exceptmask;
1184 public:
1185     int nType;
1186     int nVersion;
1187
1188     CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
1189     {
1190         file = filenew;
1191         nType = nTypeIn;
1192         nVersion = nVersionIn;
1193         state = 0;
1194         exceptmask = std::ios::badbit | std::ios::failbit;
1195     }
1196
1197     ~CAutoFile()
1198     {
1199         fclose();
1200     }
1201
1202     void fclose()
1203     {
1204         if (file != NULL && file != stdin && file != stdout && file != stderr)
1205             ::fclose(file);
1206         file = NULL;
1207     }
1208
1209     FILE* release()             { FILE* ret = file; file = NULL; return ret; }
1210     operator FILE*()            { return file; }
1211     FILE* operator->()          { return file; }
1212     FILE& operator*()           { return *file; }
1213     FILE** operator&()          { return &file; }
1214     FILE* operator=(FILE* pnew) { return file = pnew; }
1215     bool operator!()            { return (file == NULL); }
1216
1217
1218     //
1219     // Stream subset
1220     //
1221     void setstate(short bits, const char* psz)
1222     {
1223         state |= bits;
1224         if (state & exceptmask)
1225             throw std::ios_base::failure(psz);
1226     }
1227
1228     bool fail() const            { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1229     bool good() const            { return state == 0; }
1230     void clear(short n = 0)      { state = n; }
1231     short exceptions()           { return exceptmask; }
1232     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1233
1234     void SetType(int n)          { nType = n; }
1235     int GetType()                { return nType; }
1236     void SetVersion(int n)       { nVersion = n; }
1237     int GetVersion()             { return nVersion; }
1238     void ReadVersion()           { *this >> nVersion; }
1239     void WriteVersion()          { *this << nVersion; }
1240
1241     CAutoFile& read(char* pch, size_t nSize)
1242     {
1243         if (!file)
1244             throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1245         if (fread(pch, 1, nSize, file) != nSize)
1246             setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1247         return (*this);
1248     }
1249
1250     CAutoFile& write(const char* pch, size_t nSize)
1251     {
1252         if (!file)
1253             throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1254         if (fwrite(pch, 1, nSize, file) != nSize)
1255             setstate(std::ios::failbit, "CAutoFile::write : write failed");
1256         return (*this);
1257     }
1258
1259     template<typename T>
1260     unsigned int GetSerializeSize(const T& obj)
1261     {
1262         // Tells the size of the object if serialized to this stream
1263         return ::GetSerializeSize(obj, nType, nVersion);
1264     }
1265
1266     template<typename T>
1267     CAutoFile& operator<<(const T& obj)
1268     {
1269         // Serialize to this stream
1270         if (!file)
1271             throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1272         ::Serialize(*this, obj, nType, nVersion);
1273         return (*this);
1274     }
1275
1276     template<typename T>
1277     CAutoFile& operator>>(T& obj)
1278     {
1279         // Unserialize from this stream
1280         if (!file)
1281             throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1282         ::Unserialize(*this, obj, nType, nVersion);
1283         return (*this);
1284     }
1285 };
1286
1287 /** Wrapper around a FILE* that implements a ring buffer to
1288  *  deserialize from. It guarantees the ability to rewind
1289  *  a given number of bytes. */
1290 class CBufferedFile
1291 {
1292 private:
1293     FILE *src;          // source file
1294     uint64_t nSrcPos;     // how many bytes have been read from source
1295     uint64_t nReadPos;    // how many bytes have been read from this
1296     uint64_t nReadLimit;  // up to which position we're allowed to read
1297     uint64_t nRewind;     // how many bytes we guarantee to rewind
1298     std::vector<char> vchBuf; // the buffer
1299
1300     short state;
1301     short exceptmask;
1302
1303 protected:
1304     void setstate(short bits, const char *psz) {
1305         state |= bits;
1306         if (state & exceptmask)
1307             throw std::ios_base::failure(psz);
1308     }
1309
1310     // read data from the source to fill the buffer
1311     bool Fill() {
1312         unsigned int pos = (unsigned int)(nSrcPos % vchBuf.size());
1313         unsigned int readNow = (unsigned int)(vchBuf.size() - pos);
1314         unsigned int nAvail = (unsigned int)(vchBuf.size() - (nSrcPos - nReadPos) - nRewind);
1315         if (nAvail < readNow)
1316             readNow = nAvail;
1317         if (readNow == 0)
1318             return false;
1319         size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
1320         if (read == 0) {
1321             setstate(std::ios_base::failbit, feof(src) ? "CBufferedFile::Fill : end of file" : "CBufferedFile::Fill : fread failed");
1322             return false;
1323         } else {
1324             nSrcPos += read;
1325             return true;
1326         }
1327     }
1328
1329 public:
1330     int nType;
1331     int nVersion;
1332
1333     CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
1334         src(fileIn), nSrcPos(0), nReadPos(0), nReadLimit((uint64_t)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0),
1335         state(0), exceptmask(std::ios_base::badbit | std::ios_base::failbit), nType(nTypeIn), nVersion(nVersionIn) {
1336     }
1337
1338     // check whether no error occurred
1339     bool good() const {
1340         return state == 0;
1341     }
1342
1343     // check whether we're at the end of the source file
1344     bool eof() const {
1345         return nReadPos == nSrcPos && feof(src);
1346     }
1347
1348     // read a number of bytes
1349     CBufferedFile& read(char *pch, size_t nSize) {
1350         if (nSize + nReadPos > nReadLimit)
1351             throw std::ios_base::failure("Read attempted past buffer limit");
1352         if (nSize + nRewind > vchBuf.size())
1353             throw std::ios_base::failure("Read larger than buffer size");
1354         while (nSize > 0) {
1355             if (nReadPos == nSrcPos)
1356                 Fill();
1357             unsigned int pos = (unsigned int)(nReadPos % vchBuf.size());
1358             size_t nNow = nSize;
1359             if (nNow + pos > vchBuf.size())
1360                 nNow = (size_t)(vchBuf.size() - pos);
1361             if (nNow + nReadPos > nSrcPos)
1362                 nNow = (size_t)(nSrcPos - nReadPos);
1363             memcpy(pch, &vchBuf[pos], nNow);
1364             nReadPos += nNow;
1365             pch += nNow;
1366             nSize -= nNow;
1367         }
1368         return (*this);
1369     }
1370
1371     // return the current reading position
1372     uint64_t GetPos() {
1373         return nReadPos;
1374     }
1375
1376     // rewind to a given reading position
1377     bool SetPos(uint64_t nPos) {
1378         nReadPos = nPos;
1379         if (nReadPos + nRewind < nSrcPos) {
1380             nReadPos = nSrcPos - nRewind;
1381             return false;
1382         } else if (nReadPos > nSrcPos) {
1383             nReadPos = nSrcPos;
1384             return false;
1385         } else {
1386             return true;
1387         }
1388     }
1389
1390     bool Seek(uint64_t nPos) {
1391         long nLongPos = (long)nPos;
1392         if (nPos != (uint64_t)nLongPos)
1393             return false;
1394         if (fseek(src, nLongPos, SEEK_SET))
1395             return false;
1396         nLongPos = ftell(src);
1397         nSrcPos = nLongPos;
1398         nReadPos = nLongPos;
1399         state = 0;
1400         return true;
1401     }
1402
1403     // prevent reading beyond a certain position
1404     // no argument removes the limit
1405     bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
1406         if (nPos < nReadPos)
1407             return false;
1408         nReadLimit = nPos;
1409         return true;
1410     }
1411
1412     template<typename T>
1413     CBufferedFile& operator>>(T& obj) {
1414         // Unserialize from this stream
1415         ::Unserialize(*this, obj, nType, nVersion);
1416         return (*this);
1417     }
1418
1419     // search for a given byte in the stream, and remain positioned on it
1420     void FindByte(char ch) {
1421         for ( ; ; ) {
1422             if (nReadPos == nSrcPos)
1423                 Fill();
1424             if (vchBuf[nReadPos % vchBuf.size()] == ch)
1425                 break;
1426             nReadPos++;
1427         }
1428     }
1429 };
1430
1431 #endif