]> Git Repo - VerusCoin.git/blame - src/serialize.h
Added better WalletTools description.
[VerusCoin.git] / src / serialize.h
CommitLineData
0a61b0df 1// Copyright (c) 2009-2010 Satoshi Nakamoto
88216419 2// Copyright (c) 2009-2012 The Bitcoin developers
0a61b0df 3// Distributed under the MIT/X11 software license, see the accompanying
3a25a2b9 4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
223b6f1b
WL
5#ifndef BITCOIN_SERIALIZE_H
6#define BITCOIN_SERIALIZE_H
0a61b0df 7
d743f035 8#include <string>
0a61b0df 9#include <vector>
10#include <map>
d743f035 11#include <set>
223b6f1b 12#include <cassert>
0e87f34b 13#include <limits>
223b6f1b
WL
14#include <cstring>
15#include <cstdio>
16
0a61b0df 17#include <boost/type_traits/is_fundamental.hpp>
84d7c981 18#include <boost/tuple/tuple.hpp>
19#include <boost/tuple/tuple_comparison.hpp>
20#include <boost/tuple/tuple_io.hpp>
223b6f1b 21
6cb6d623 22#include "allocators.h"
b87c0fc4 23#include "version.h"
6cb6d623 24
bde280b9
WL
25typedef long long int64;
26typedef unsigned long long uint64;
27
0a61b0df 28class CScript;
29class CDataStream;
30class CAutoFile;
0a61b0df 31static const unsigned int MAX_SIZE = 0x02000000;
32
82dc6426
GS
33// Used to bypass the rule against non-const reference to temporary
34// where it makes sense with wrappers such as CFlatData or CTxDB
35template<typename T>
36inline T& REF(const T& val)
37{
38 return const_cast<T&>(val);
39}
0a61b0df 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
47enum
48{
49 // primary actions
50 SER_NETWORK = (1 << 0),
51 SER_DISK = (1 << 1),
52 SER_GETHASH = (1 << 2),
0a61b0df 53};
54
55#define IMPLEMENT_SERIALIZE(statements) \
6b6aaa16 56 unsigned int GetSerializeSize(int nType, int nVersion) const \
0a61b0df 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; \
a1de57a0 64 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
0a61b0df 65 s.nType = nType; \
66 s.nVersion = nVersion; \
67 {statements} \
68 return nSerSize; \
69 } \
70 template<typename Stream> \
6b6aaa16 71 void Serialize(Stream& s, int nType, int nVersion) const \
0a61b0df 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; \
a1de57a0 78 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
0a61b0df 79 {statements} \
80 } \
81 template<typename Stream> \
6b6aaa16 82 void Unserialize(Stream& s, int nType, int nVersion) \
0a61b0df 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; \
a1de57a0 89 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
0a61b0df 90 {statements} \
91 }
92
93#define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
94
0a61b0df 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
106inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
107inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
108inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
109inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
110inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
111inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
112inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
113inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
114inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
bde280b9
WL
115inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
116inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
0a61b0df 117inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
118inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
119
120template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
121template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
122template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
123template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
124template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
125template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
126template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
127template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
128template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
bde280b9
WL
129template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
130template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
0a61b0df 131template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
132template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
133
134template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
135template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
136template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
137template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
138template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
139template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
140template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
141template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
142template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
bde280b9
WL
143template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
144template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
0a61b0df 145template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
146template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
147
148inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
149template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
150template<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//
bde280b9 164inline unsigned int GetSizeOfCompactSize(uint64 nSize)
0a61b0df 165{
a790fa46 166 if (nSize < 253) return sizeof(unsigned char);
26ce92b3
GA
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);
bde280b9 169 else return sizeof(unsigned char) + sizeof(uint64);
0a61b0df 170}
171
172template<typename Stream>
bde280b9 173void WriteCompactSize(Stream& os, uint64 nSize)
0a61b0df 174{
a790fa46 175 if (nSize < 253)
0a61b0df 176 {
177 unsigned char chSize = nSize;
178 WRITEDATA(os, chSize);
179 }
26ce92b3 180 else if (nSize <= std::numeric_limits<unsigned short>::max())
0a61b0df 181 {
a790fa46 182 unsigned char chSize = 253;
0a61b0df 183 unsigned short xSize = nSize;
184 WRITEDATA(os, chSize);
185 WRITEDATA(os, xSize);
186 }
26ce92b3 187 else if (nSize <= std::numeric_limits<unsigned int>::max())
0a61b0df 188 {
a790fa46 189 unsigned char chSize = 254;
0a61b0df 190 unsigned int xSize = nSize;
191 WRITEDATA(os, chSize);
192 WRITEDATA(os, xSize);
193 }
194 else
195 {
a790fa46 196 unsigned char chSize = 255;
bde280b9 197 uint64 xSize = nSize;
0a61b0df 198 WRITEDATA(os, chSize);
a790fa46 199 WRITEDATA(os, xSize);
0a61b0df 200 }
201 return;
202}
203
204template<typename Stream>
bde280b9 205uint64 ReadCompactSize(Stream& is)
0a61b0df 206{
207 unsigned char chSize;
208 READDATA(is, chSize);
bde280b9 209 uint64 nSizeRet = 0;
a790fa46 210 if (chSize < 253)
0a61b0df 211 {
212 nSizeRet = chSize;
213 }
a790fa46 214 else if (chSize == 253)
0a61b0df 215 {
a790fa46 216 unsigned short xSize;
217 READDATA(is, xSize);
218 nSizeRet = xSize;
0a61b0df 219 }
a790fa46 220 else if (chSize == 254)
0a61b0df 221 {
a790fa46 222 unsigned int xSize;
223 READDATA(is, xSize);
224 nSizeRet = xSize;
0a61b0df 225 }
226 else
227 {
bde280b9 228 uint64 xSize;
a790fa46 229 READDATA(is, xSize);
230 nSizeRet = xSize;
0a61b0df 231 }
bde280b9 232 if (nSizeRet > (uint64)MAX_SIZE)
0a61b0df 233 throw std::ios_base::failure("ReadCompactSize() : size too large");
234 return nSizeRet;
235}
236
4d6144f9
PW
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
259template<typename I>
260inline 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
272template<typename Stream, typename I>
273void 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}
0a61b0df 288
4d6144f9
PW
289template<typename Stream, typename I>
290I 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}
0a61b0df 303
4d6144f9
PW
304#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
305#define VARINT(obj) REF(WrapVarInt(REF(obj)))
6b8de05d
PW
306
307/** Wrapper for serializing arrays and POD.
6b8de05d 308 */
0a61b0df 309class CFlatData
310{
311protected:
312 char* pbegin;
313 char* pend;
314public:
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
4d6144f9
PW
339template<typename I>
340class CVarInt
341{
342protected:
343 I &n;
344public:
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
362template<typename I>
363CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
364
0a61b0df 365//
366// Forward declarations
367//
368
369// string
223b6f1b
WL
370template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
371template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
372template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
0a61b0df 373
374// vector
375template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
376template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
6b6aaa16 377template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
0a61b0df 378template<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&);
379template<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&);
6b6aaa16 380template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
0a61b0df 381template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
382template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
6b6aaa16 383template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
0a61b0df 384
385// others derived from vector
6b6aaa16
PW
386extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
387template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
388template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
0a61b0df 389
390// pair
6b6aaa16
PW
391template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
392template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
393template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
0a61b0df 394
84d7c981 395// 3 tuple
6b6aaa16
PW
396template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
397template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
398template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
84d7c981 399
400// 4 tuple
6b6aaa16
PW
401template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
402template<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);
403template<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);
84d7c981 404
0a61b0df 405// map
6b6aaa16
PW
406template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
407template<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);
408template<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);
0a61b0df 409
410// set
6b6aaa16
PW
411template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
412template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
413template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
0a61b0df 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//
425template<typename T>
6b6aaa16 426inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
0a61b0df 427{
428 return a.GetSerializeSize((int)nType, nVersion);
429}
430
431template<typename Stream, typename T>
6b6aaa16 432inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
0a61b0df 433{
434 a.Serialize(os, (int)nType, nVersion);
435}
436
437template<typename Stream, typename T>
6b6aaa16 438inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
0a61b0df 439{
440 a.Unserialize(is, (int)nType, nVersion);
441}
442
443
444
445
446
447//
448// string
449//
450template<typename C>
223b6f1b 451unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
0a61b0df 452{
453 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
454}
455
456template<typename Stream, typename C>
223b6f1b 457void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
0a61b0df 458{
459 WriteCompactSize(os, str.size());
460 if (!str.empty())
461 os.write((char*)&str[0], str.size() * sizeof(str[0]));
462}
463
464template<typename Stream, typename C>
223b6f1b 465void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
0a61b0df 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//
478template<typename T, typename A>
479unsigned 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
484template<typename T, typename A>
485unsigned 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
493template<typename T, typename A>
494inline 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
500template<typename Stream, typename T, typename A>
501void 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
508template<typename Stream, typename T, typename A>
509void 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
516template<typename Stream, typename T, typename A>
517inline 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
523template<typename Stream, typename T, typename A>
524void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
525{
0a61b0df 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 {
223b6f1b 532 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
0a61b0df 533 v.resize(i + blk);
534 is.read((char*)&v[i], blk * sizeof(T));
535 i += blk;
536 }
537}
538
539template<typename Stream, typename T, typename A>
540void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
541{
0a61b0df 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
557template<typename Stream, typename T, typename A>
558inline 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//
568inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
569{
223b6f1b 570 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
0a61b0df 571}
572
573template<typename Stream>
574void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
575{
223b6f1b 576 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
0a61b0df 577}
578
579template<typename Stream>
580void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
581{
223b6f1b 582 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
0a61b0df 583}
584
585
586
587//
588// pair
589//
590template<typename K, typename T>
591unsigned 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
596template<typename Stream, typename K, typename T>
597void 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
603template<typename Stream, typename K, typename T>
604void 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
84d7c981 612//
613// 3 tuple
614//
615template<typename T0, typename T1, typename T2>
616unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
617{
618 unsigned int nSize = 0;
223b6f1b
WL
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);
84d7c981 622 return nSize;
623}
624
625template<typename Stream, typename T0, typename T1, typename T2>
626void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
627{
223b6f1b
WL
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);
84d7c981 631}
632
633template<typename Stream, typename T0, typename T1, typename T2>
634void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
635{
223b6f1b
WL
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);
84d7c981 639}
640
641
642
643//
644// 4 tuple
645//
646template<typename T0, typename T1, typename T2, typename T3>
647unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
648{
649 unsigned int nSize = 0;
223b6f1b
WL
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);
84d7c981 654 return nSize;
655}
656
657template<typename Stream, typename T0, typename T1, typename T2, typename T3>
658void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
659{
223b6f1b
WL
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);
84d7c981 664}
665
666template<typename Stream, typename T0, typename T1, typename T2, typename T3>
667void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
668{
223b6f1b
WL
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);
84d7c981 673}
674
675
676
0a61b0df 677//
678// map
679//
680template<typename K, typename T, typename Pred, typename A>
681unsigned 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
689template<typename Stream, typename K, typename T, typename Pred, typename A>
690void 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
697template<typename Stream, typename K, typename T, typename Pred, typename A>
698void 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 {
223b6f1b 705 std::pair<K, T> item;
0a61b0df 706 Unserialize(is, item, nType, nVersion);
707 mi = m.insert(mi, item);
708 }
709}
710
711
712
713//
714// set
715//
716template<typename K, typename Pred, typename A>
717unsigned 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
725template<typename Stream, typename K, typename Pred, typename A>
726void 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
733template<typename Stream, typename K, typename Pred, typename A>
734void 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//
752class CSerActionGetSerializeSize { };
753class CSerActionSerialize { };
754class CSerActionUnserialize { };
755
756template<typename Stream, typename T>
757inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
758{
759 return ::GetSerializeSize(obj, nType, nVersion);
760}
761
762template<typename Stream, typename T>
763inline 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
769template<typename Stream, typename T>
770inline 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
776struct ser_streamplaceholder
777{
778 int nType;
779 int nVersion;
780};
781
782
783
784
785
786
787
788
789
f7a9a113
MC
790
791
41b052ad 792typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
0a61b0df 793
6b8de05d
PW
794/** Double ended buffer combining vector and stream-like interfaces.
795 *
796 * >> and << read and write unformatted data using the above serialization templates.
797 * Fills with data in linear time; some stringstream implementations take N^2 time.
798 */
0a61b0df 799class CDataStream
800{
801protected:
41b052ad 802 typedef CSerializeData vector_type;
0a61b0df 803 vector_type vch;
804 unsigned int nReadPos;
805 short state;
806 short exceptmask;
807public:
808 int nType;
809 int nVersion;
810
811 typedef vector_type::allocator_type allocator_type;
812 typedef vector_type::size_type size_type;
813 typedef vector_type::difference_type difference_type;
814 typedef vector_type::reference reference;
815 typedef vector_type::const_reference const_reference;
816 typedef vector_type::value_type value_type;
817 typedef vector_type::iterator iterator;
818 typedef vector_type::const_iterator const_iterator;
819 typedef vector_type::reverse_iterator reverse_iterator;
820
6b6aaa16 821 explicit CDataStream(int nTypeIn, int nVersionIn)
0a61b0df 822 {
823 Init(nTypeIn, nVersionIn);
824 }
825
6b6aaa16 826 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
0a61b0df 827 {
828 Init(nTypeIn, nVersionIn);
829 }
830
831#if !defined(_MSC_VER) || _MSC_VER >= 1300
6b6aaa16 832 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
0a61b0df 833 {
834 Init(nTypeIn, nVersionIn);
835 }
836#endif
837
6b6aaa16 838 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
0a61b0df 839 {
840 Init(nTypeIn, nVersionIn);
841 }
842
6b6aaa16 843 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
0a61b0df 844 {
845 Init(nTypeIn, nVersionIn);
846 }
847
6b6aaa16 848 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
0a61b0df 849 {
850 Init(nTypeIn, nVersionIn);
851 }
852
6b6aaa16 853 void Init(int nTypeIn, int nVersionIn)
0a61b0df 854 {
855 nReadPos = 0;
856 nType = nTypeIn;
857 nVersion = nVersionIn;
858 state = 0;
223b6f1b 859 exceptmask = std::ios::badbit | std::ios::failbit;
0a61b0df 860 }
861
862 CDataStream& operator+=(const CDataStream& b)
863 {
864 vch.insert(vch.end(), b.begin(), b.end());
865 return *this;
866 }
867
868 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
869 {
870 CDataStream ret = a;
871 ret += b;
872 return (ret);
873 }
874
223b6f1b 875 std::string str() const
0a61b0df 876 {
223b6f1b 877 return (std::string(begin(), end()));
0a61b0df 878 }
879
880
881 //
882 // Vector subset
883 //
884 const_iterator begin() const { return vch.begin() + nReadPos; }
885 iterator begin() { return vch.begin() + nReadPos; }
886 const_iterator end() const { return vch.end(); }
887 iterator end() { return vch.end(); }
888 size_type size() const { return vch.size() - nReadPos; }
889 bool empty() const { return vch.size() == nReadPos; }
890 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
891 void reserve(size_type n) { vch.reserve(n + nReadPos); }
892 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
893 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
894 void clear() { vch.clear(); nReadPos = 0; }
895 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
896 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
897
898 void insert(iterator it, const_iterator first, const_iterator last)
899 {
467b7939
MC
900 assert(last - first >= 0);
901 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
0a61b0df 902 {
903 // special case for inserting at the front when there's room
904 nReadPos -= (last - first);
905 memcpy(&vch[nReadPos], &first[0], last - first);
906 }
907 else
908 vch.insert(it, first, last);
909 }
910
223b6f1b 911 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
0a61b0df 912 {
467b7939
MC
913 assert(last - first >= 0);
914 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
0a61b0df 915 {
916 // special case for inserting at the front when there's room
917 nReadPos -= (last - first);
918 memcpy(&vch[nReadPos], &first[0], last - first);
919 }
920 else
921 vch.insert(it, first, last);
922 }
923
924#if !defined(_MSC_VER) || _MSC_VER >= 1300
925 void insert(iterator it, const char* first, const char* last)
926 {
467b7939
MC
927 assert(last - first >= 0);
928 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
0a61b0df 929 {
930 // special case for inserting at the front when there's room
931 nReadPos -= (last - first);
932 memcpy(&vch[nReadPos], &first[0], last - first);
933 }
934 else
935 vch.insert(it, first, last);
936 }
937#endif
938
939 iterator erase(iterator it)
940 {
941 if (it == vch.begin() + nReadPos)
942 {
943 // special case for erasing from the front
944 if (++nReadPos >= vch.size())
945 {
946 // whenever we reach the end, we take the opportunity to clear the buffer
947 nReadPos = 0;
948 return vch.erase(vch.begin(), vch.end());
949 }
950 return vch.begin() + nReadPos;
951 }
952 else
953 return vch.erase(it);
954 }
955
956 iterator erase(iterator first, iterator last)
957 {
958 if (first == vch.begin() + nReadPos)
959 {
960 // special case for erasing from the front
961 if (last == vch.end())
962 {
963 nReadPos = 0;
964 return vch.erase(vch.begin(), vch.end());
965 }
966 else
967 {
968 nReadPos = (last - vch.begin());
969 return last;
970 }
971 }
972 else
973 return vch.erase(first, last);
974 }
975
976 inline void Compact()
977 {
978 vch.erase(vch.begin(), vch.begin() + nReadPos);
979 nReadPos = 0;
980 }
981
982 bool Rewind(size_type n)
983 {
984 // Rewind by n characters if the buffer hasn't been compacted yet
985 if (n > nReadPos)
986 return false;
987 nReadPos -= n;
988 return true;
989 }
990
991
992 //
993 // Stream subset
994 //
995 void setstate(short bits, const char* psz)
996 {
997 state |= bits;
998 if (state & exceptmask)
999 throw std::ios_base::failure(psz);
1000 }
1001
1002 bool eof() const { return size() == 0; }
223b6f1b 1003 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
0a61b0df 1004 bool good() const { return !eof() && (state == 0); }
1005 void clear(short n) { state = n; } // name conflict with vector clear()
1006 short exceptions() { return exceptmask; }
1007 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1008 CDataStream* rdbuf() { return this; }
1009 int in_avail() { return size(); }
1010
1011 void SetType(int n) { nType = n; }
1012 int GetType() { return nType; }
1013 void SetVersion(int n) { nVersion = n; }
1014 int GetVersion() { return nVersion; }
1015 void ReadVersion() { *this >> nVersion; }
1016 void WriteVersion() { *this << nVersion; }
1017
1018 CDataStream& read(char* pch, int nSize)
1019 {
1020 // Read from the beginning of the buffer
1021 assert(nSize >= 0);
1022 unsigned int nReadPosNext = nReadPos + nSize;
1023 if (nReadPosNext >= vch.size())
1024 {
1025 if (nReadPosNext > vch.size())
1026 {
223b6f1b 1027 setstate(std::ios::failbit, "CDataStream::read() : end of data");
0a61b0df 1028 memset(pch, 0, nSize);
1029 nSize = vch.size() - nReadPos;
1030 }
1031 memcpy(pch, &vch[nReadPos], nSize);
1032 nReadPos = 0;
1033 vch.clear();
1034 return (*this);
1035 }
1036 memcpy(pch, &vch[nReadPos], nSize);
1037 nReadPos = nReadPosNext;
1038 return (*this);
1039 }
1040
1041 CDataStream& ignore(int nSize)
1042 {
1043 // Ignore from the beginning of the buffer
1044 assert(nSize >= 0);
1045 unsigned int nReadPosNext = nReadPos + nSize;
1046 if (nReadPosNext >= vch.size())
1047 {
1048 if (nReadPosNext > vch.size())
1049 {
223b6f1b 1050 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
0a61b0df 1051 nSize = vch.size() - nReadPos;
1052 }
1053 nReadPos = 0;
1054 vch.clear();
1055 return (*this);
1056 }
1057 nReadPos = nReadPosNext;
1058 return (*this);
1059 }
1060
1061 CDataStream& write(const char* pch, int nSize)
1062 {
1063 // Write to the end of the buffer
1064 assert(nSize >= 0);
1065 vch.insert(vch.end(), pch, pch + nSize);
1066 return (*this);
1067 }
1068
1069 template<typename Stream>
6b6aaa16 1070 void Serialize(Stream& s, int nType, int nVersion) const
0a61b0df 1071 {
1072 // Special case: stream << stream concatenates like stream += stream
1073 if (!vch.empty())
1074 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1075 }
1076
1077 template<typename T>
1078 unsigned int GetSerializeSize(const T& obj)
1079 {
1080 // Tells the size of the object if serialized to this stream
1081 return ::GetSerializeSize(obj, nType, nVersion);
1082 }
1083
1084 template<typename T>
1085 CDataStream& operator<<(const T& obj)
1086 {
1087 // Serialize to this stream
1088 ::Serialize(*this, obj, nType, nVersion);
1089 return (*this);
1090 }
1091
1092 template<typename T>
1093 CDataStream& operator>>(T& obj)
1094 {
1095 // Unserialize from this stream
1096 ::Unserialize(*this, obj, nType, nVersion);
1097 return (*this);
1098 }
41b052ad
PW
1099
1100 void GetAndClear(CSerializeData &data) {
1101 vch.swap(data);
1102 CSerializeData().swap(vch);
1103 }
0a61b0df 1104};
1105
0a61b0df 1106
1107
1108
1109
1110
1111
1112
1113
1114
6b8de05d
PW
1115/** RAII wrapper for FILE*.
1116 *
1117 * Will automatically close the file when it goes out of scope if not null.
1118 * If you're returning the file pointer, return file.release().
1119 * If you need to close the file early, use file.fclose() instead of fclose(file).
1120 */
0a61b0df 1121class CAutoFile
1122{
1123protected:
1124 FILE* file;
1125 short state;
1126 short exceptmask;
1127public:
1128 int nType;
1129 int nVersion;
1130
6b6aaa16 1131 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
0a61b0df 1132 {
1133 file = filenew;
1134 nType = nTypeIn;
1135 nVersion = nVersionIn;
1136 state = 0;
223b6f1b 1137 exceptmask = std::ios::badbit | std::ios::failbit;
0a61b0df 1138 }
1139
1140 ~CAutoFile()
1141 {
1142 fclose();
1143 }
1144
1145 void fclose()
1146 {
1147 if (file != NULL && file != stdin && file != stdout && file != stderr)
1148 ::fclose(file);
1149 file = NULL;
1150 }
1151
1152 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1153 operator FILE*() { return file; }
1154 FILE* operator->() { return file; }
1155 FILE& operator*() { return *file; }
1156 FILE** operator&() { return &file; }
1157 FILE* operator=(FILE* pnew) { return file = pnew; }
1158 bool operator!() { return (file == NULL); }
1159
1160
1161 //
1162 // Stream subset
1163 //
1164 void setstate(short bits, const char* psz)
1165 {
1166 state |= bits;
1167 if (state & exceptmask)
1168 throw std::ios_base::failure(psz);
1169 }
1170
223b6f1b 1171 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
0a61b0df 1172 bool good() const { return state == 0; }
1173 void clear(short n = 0) { state = n; }
1174 short exceptions() { return exceptmask; }
1175 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1176
1177 void SetType(int n) { nType = n; }
1178 int GetType() { return nType; }
1179 void SetVersion(int n) { nVersion = n; }
1180 int GetVersion() { return nVersion; }
1181 void ReadVersion() { *this >> nVersion; }
1182 void WriteVersion() { *this << nVersion; }
1183
c3fad835 1184 CAutoFile& read(char* pch, size_t nSize)
0a61b0df 1185 {
1186 if (!file)
1187 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1188 if (fread(pch, 1, nSize, file) != nSize)
223b6f1b 1189 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
0a61b0df 1190 return (*this);
1191 }
1192
c3fad835 1193 CAutoFile& write(const char* pch, size_t nSize)
0a61b0df 1194 {
1195 if (!file)
1196 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1197 if (fwrite(pch, 1, nSize, file) != nSize)
223b6f1b 1198 setstate(std::ios::failbit, "CAutoFile::write : write failed");
0a61b0df 1199 return (*this);
1200 }
1201
1202 template<typename T>
1203 unsigned int GetSerializeSize(const T& obj)
1204 {
1205 // Tells the size of the object if serialized to this stream
1206 return ::GetSerializeSize(obj, nType, nVersion);
1207 }
1208
1209 template<typename T>
1210 CAutoFile& operator<<(const T& obj)
1211 {
1212 // Serialize to this stream
1213 if (!file)
1214 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1215 ::Serialize(*this, obj, nType, nVersion);
1216 return (*this);
1217 }
1218
1219 template<typename T>
1220 CAutoFile& operator>>(T& obj)
1221 {
1222 // Unserialize from this stream
1223 if (!file)
1224 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1225 ::Unserialize(*this, obj, nType, nVersion);
1226 return (*this);
1227 }
1228};
223b6f1b 1229
b5d5f44c
PW
1230/** Wrapper around a FILE* that implements a ring buffer to
1231 * deserialize from. It guarantees the ability to rewind
1232 * a given number of bytes. */
1233class CBufferedFile
1234{
1235private:
1236 FILE *src; // source file
1237 uint64 nSrcPos; // how many bytes have been read from source
1238 uint64 nReadPos; // how many bytes have been read from this
1239 uint64 nReadLimit; // up to which position we're allowed to read
1240 uint64 nRewind; // how many bytes we guarantee to rewind
1241 std::vector<char> vchBuf; // the buffer
1242
1243 short state;
1244 short exceptmask;
1245
1246protected:
1247 void setstate(short bits, const char *psz) {
1248 state |= bits;
1249 if (state & exceptmask)
1250 throw std::ios_base::failure(psz);
1251 }
1252
1253 // read data from the source to fill the buffer
1254 bool Fill() {
1255 unsigned int pos = nSrcPos % vchBuf.size();
1256 unsigned int readNow = vchBuf.size() - pos;
1257 unsigned int nAvail = vchBuf.size() - (nSrcPos - nReadPos) - nRewind;
1258 if (nAvail < readNow)
1259 readNow = nAvail;
1260 if (readNow == 0)
1261 return false;
1262 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
1263 if (read == 0) {
1264 setstate(std::ios_base::failbit, feof(src) ? "CBufferedFile::Fill : end of file" : "CBufferedFile::Fill : fread failed");
1265 return false;
1266 } else {
1267 nSrcPos += read;
1268 return true;
1269 }
1270 }
1271
1272public:
1273 int nType;
1274 int nVersion;
1275
1276 CBufferedFile(FILE *fileIn, uint64 nBufSize, uint64 nRewindIn, int nTypeIn, int nVersionIn) :
1277 src(fileIn), nSrcPos(0), nReadPos(0), nReadLimit((uint64)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0),
1278 state(0), exceptmask(std::ios_base::badbit | std::ios_base::failbit), nType(nTypeIn), nVersion(nVersionIn) {
1279 }
1280
1281 // check whether no error occurred
1282 bool good() const {
1283 return state == 0;
1284 }
1285
1286 // check whether we're at the end of the source file
1287 bool eof() const {
1288 return nReadPos == nSrcPos && feof(src);
1289 }
1290
1291 // read a number of bytes
1292 CBufferedFile& read(char *pch, size_t nSize) {
1293 if (nSize + nReadPos > nReadLimit)
1294 throw std::ios_base::failure("Read attempted past buffer limit");
1295 if (nSize + nRewind > vchBuf.size())
1296 throw std::ios_base::failure("Read larger than buffer size");
1297 while (nSize > 0) {
1298 if (nReadPos == nSrcPos)
1299 Fill();
1300 unsigned int pos = nReadPos % vchBuf.size();
1301 size_t nNow = nSize;
1302 if (nNow + pos > vchBuf.size())
1303 nNow = vchBuf.size() - pos;
1304 if (nNow + nReadPos > nSrcPos)
1305 nNow = nSrcPos - nReadPos;
1306 memcpy(pch, &vchBuf[pos], nNow);
1307 nReadPos += nNow;
1308 pch += nNow;
1309 nSize -= nNow;
1310 }
1311 return (*this);
1312 }
1313
1314 // return the current reading position
1315 uint64 GetPos() {
1316 return nReadPos;
1317 }
1318
1319 // rewind to a given reading position
1320 bool SetPos(uint64 nPos) {
1321 nReadPos = nPos;
1322 if (nReadPos + nRewind < nSrcPos) {
1323 nReadPos = nSrcPos - nRewind;
1324 return false;
1325 } else if (nReadPos > nSrcPos) {
1326 nReadPos = nSrcPos;
1327 return false;
1328 } else {
1329 return true;
1330 }
1331 }
1332
1333 bool Seek(uint64 nPos) {
1334 long nLongPos = nPos;
1335 if (nPos != (uint64)nLongPos)
1336 return false;
1337 if (fseek(src, nLongPos, SEEK_SET))
1338 return false;
1339 nLongPos = ftell(src);
1340 nSrcPos = nLongPos;
1341 nReadPos = nLongPos;
1342 state = 0;
1343 return true;
1344 }
1345
1346 // prevent reading beyond a certain position
1347 // no argument removes the limit
1348 bool SetLimit(uint64 nPos = (uint64)(-1)) {
1349 if (nPos < nReadPos)
1350 return false;
1351 nReadLimit = nPos;
1352 return true;
1353 }
1354
1355 template<typename T>
1356 CBufferedFile& operator>>(T& obj) {
1357 // Unserialize from this stream
1358 ::Unserialize(*this, obj, nType, nVersion);
1359 return (*this);
1360 }
1361
1362 // search for a given byte in the stream, and remain positioned on it
1363 void FindByte(char ch) {
1364 while (true) {
1365 if (nReadPos == nSrcPos)
1366 Fill();
1367 if (vchBuf[nReadPos % vchBuf.size()] == ch)
1368 break;
1369 nReadPos++;
1370 }
1371 }
1372};
1373
223b6f1b 1374#endif
This page took 0.291198 seconds and 4 git commands to generate.