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