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