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