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
17 #include <type_traits>
22 #if defined __USE_MINGW_ANSI_STDIO
23 #undef __USE_MINGW_ANSI_STDIO // This constant forces MinGW to conduct stupid behavior
27 #include "allocators.h"
34 static const unsigned int MAX_SIZE = 0x02000000;
36 // Used to bypass the rule against non-const reference to temporary
37 // where it makes sense with wrappers such as CFlatData or CTxDB
39 inline T& REF(const T& val)
41 return const_cast<T&>(val);
44 /////////////////////////////////////////////////////////////////
46 // Templates for serializing to anything that looks like a stream,
47 // i.e. anything that supports .read(char*, int) and .write(char*, int)
53 SER_NETWORK = (1 << 0),
55 SER_GETHASH = (1 << 2),
58 SER_SKIPSIG = (1 << 16),
59 SER_BLOCKHEADERONLY = (1 << 17)
63 #define IMPLEMENT_SERIALIZE(statements) \
64 unsigned int GetSerializeSize(int nType, int nVersion) const \
66 CSerActionGetSerializeSize ser_action; \
67 const bool fGetSize = true; \
68 const bool fWrite = false; \
69 const bool fRead = false; \
70 unsigned int nSerSize = 0; \
71 ser_streamplaceholder s; \
72 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
74 s.nVersion = nVersion; \
78 template<typename Stream> \
79 void Serialize(Stream& s, int nType, int nVersion) const \
81 CSerActionSerialize ser_action; \
82 const bool fGetSize = false; \
83 const bool fWrite = true; \
84 const bool fRead = false; \
85 unsigned int nSerSize = 0; \
86 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
89 template<typename Stream> \
90 void Unserialize(Stream& s, int nType, int nVersion) \
92 CSerActionUnserialize ser_action; \
93 const bool fGetSize = false; \
94 const bool fWrite = false; \
95 const bool fRead = true; \
96 unsigned int nSerSize = 0; \
97 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
101 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
111 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
112 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
114 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
115 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
116 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
117 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
118 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
119 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
120 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
121 //inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
122 //inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
123 inline unsigned int GetSerializeSize(int64_t a, int, int=0) { return sizeof(a); }
124 inline unsigned int GetSerializeSize(uint64_t a, int, int=0) { return sizeof(a); }
125 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
126 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
128 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
129 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
130 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
131 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
132 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
133 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
134 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
135 //template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
136 //template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
137 template<typename Stream> inline void Serialize(Stream& s, int64_t a, int, int=0) { WRITEDATA(s, a); }
138 template<typename Stream> inline void Serialize(Stream& s, uint64_t a, int, int=0) { WRITEDATA(s, a); }
139 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
140 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
142 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
143 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
144 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
145 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
146 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
147 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
148 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
149 //template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
150 //template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
151 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a, int, int=0) { READDATA(s, a); }
152 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a, int, int=0) { READDATA(s, a); }
153 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
154 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
156 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
157 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
158 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
167 // size < 253 -- 1 byte
168 // size <= UINT16_MAX -- 3 bytes (253 + 2 bytes)
169 // size <= UINT32_MAX -- 5 bytes (254 + 4 bytes)
170 // size > UINT32_MAX -- 9 bytes (255 + 8 bytes)
172 inline uint32_t GetSizeOfCompactSize(uint64_t nSize)
176 if (nSize <= std::numeric_limits<uint16_t>::max())
178 if (nSize <= std::numeric_limits<uint32_t>::max())
183 template<typename Stream>
184 void WriteCompactSize(Stream& os, uint64_t nSize);
186 template<typename Stream>
187 uint64_t ReadCompactSize(Stream& is);
189 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
190 // The high bit in each byte signifies whether another digit follows. To make
191 // the encoding is one-to-one, one is subtracted from all but the last digit.
192 // Thus, the byte sequence a[] with length len, where all but the last byte
193 // has bit 128 set, encodes the number:
195 // (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
198 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
199 // * Every integer has exactly one encoding
200 // * Encoding does not depend on size of original integer type
201 // * No redundancy: every (infinite) byte sequence corresponds to a list
202 // of encoded integers.
204 // 0: [0x00] 256: [0x81 0x00]
205 // 1: [0x01] 16383: [0xFE 0x7F]
206 // 127: [0x7F] 16384: [0xFF 0x00]
207 // 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F]
208 // 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F]
209 // 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
212 inline unsigned int GetSizeOfVarInt(I n)
224 template<typename Stream, typename I>
225 void WriteVarInt(Stream& os, I n)
227 unsigned char tmp[(sizeof(n)*8+6)/7];
230 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
237 WRITEDATA(os, tmp[len]);
241 template<typename Stream, typename I>
242 I ReadVarInt(Stream& is)
246 unsigned char chData;
247 READDATA(is, chData);
248 n = (n << 7) | (chData & 0x7F);
256 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
257 #define VARINT(obj) REF(WrapVarInt(REF(obj)))
259 /** Wrapper for serializing arrays and POD.
267 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
268 char* begin() { return pbegin; }
269 const char* begin() const { return pbegin; }
270 char* end() { return pend; }
271 const char* end() const { return pend; }
273 unsigned int GetSerializeSize(int, int=0) const
275 return (unsigned int)(pend - pbegin);
278 template<typename Stream>
279 void Serialize(Stream& s, int, int=0) const
281 s.write(pbegin, (int)(pend - pbegin));
284 template<typename Stream>
285 void Unserialize(Stream& s, int, int=0)
287 s.read(pbegin, pend - pbegin);
297 CVarInt(I& nIn) : n(nIn) { }
299 unsigned int GetSerializeSize(int, int) const {
300 return GetSizeOfVarInt<I>(n);
303 template<typename Stream>
304 void Serialize(Stream &s, int, int) const {
305 WriteVarInt<Stream,I>(s, n);
308 template<typename Stream>
309 void Unserialize(Stream& s, int, int) {
310 n = ReadVarInt<Stream,I>(s);
315 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
318 // Forward declarations
322 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
323 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
324 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
327 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
328 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
329 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
330 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
331 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
332 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
333 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
334 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
335 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
337 // others derived from vector
338 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
339 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
340 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
343 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
344 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
345 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
348 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
349 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
350 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion);
353 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
354 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Serialize(Stream& os, const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
355 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Unserialize(Stream& is, std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
358 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
359 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);
360 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);
363 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
364 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
365 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
372 // If none of the specialized versions above matched, default to calling member function.
373 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
374 // The compiler will only cast int to long if none of the other templates matched.
375 // Thanks to Boost serialization for this idea.
378 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
380 return a.GetSerializeSize((int)nType, nVersion);
383 template<typename Stream, typename T>
384 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
386 a.Serialize(os, (int)nType, nVersion);
389 template<typename Stream, typename T>
390 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
392 a.Unserialize(is, (int)nType, nVersion);
403 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
405 return (unsigned int)(GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]));
408 template<typename Stream, typename C>
409 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
411 WriteCompactSize(os, str.size());
413 os.write((char*)&str[0], (int)(str.size() * sizeof(str[0])));
416 template<typename Stream, typename C>
417 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
419 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
422 is.read((char*)&str[0], nSize * sizeof(str[0]));
430 template<typename T, typename A>
431 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
433 return (unsigned int)(GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
436 template<typename T, typename A>
437 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
439 unsigned int nSize = GetSizeOfCompactSize(v.size());
440 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
441 nSize += GetSerializeSize((*vi), nType, nVersion);
445 template<typename T, typename A>
446 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
448 return GetSerializeSize_impl(v, nType, nVersion, std::is_fundamental<T>());
452 template<typename Stream, typename T, typename A>
453 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
455 WriteCompactSize(os, v.size());
457 os.write((char*)&v[0], (int)(v.size() * sizeof(T)));
460 template<typename Stream, typename T, typename A>
461 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
463 WriteCompactSize(os, v.size());
464 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
465 ::Serialize(os, (*vi), nType, nVersion);
468 template<typename Stream, typename T, typename A>
469 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
471 Serialize_impl(os, v, nType, nVersion, std::is_fundamental<T>());
475 template<typename Stream, typename T, typename A>
476 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
478 // Limit size per read so bogus size value won't cause out of memory
480 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
484 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
486 is.read((char*)&v[i], blk * sizeof(T));
491 template<typename Stream, typename T, typename A>
492 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
495 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
497 unsigned int nMid = 0;
500 nMid += 5000000 / sizeof(T);
504 for (; i < nMid; i++)
505 Unserialize(is, v[i], nType, nVersion);
509 template<typename Stream, typename T, typename A>
510 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
512 Unserialize_impl(is, v, nType, nVersion, std::is_fundamental<T>());
518 // others derived from vector
520 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
522 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
525 template<typename Stream>
526 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
528 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
531 template<typename Stream>
532 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
534 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
542 template<typename K, typename T>
543 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
545 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
548 template<typename Stream, typename K, typename T>
549 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
551 Serialize(os, item.first, nType, nVersion);
552 Serialize(os, item.second, nType, nVersion);
555 template<typename Stream, typename K, typename T>
556 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
558 Unserialize(is, item.first, nType, nVersion);
559 Unserialize(is, item.second, nType, nVersion);
567 template<typename T0, typename T1, typename T2>
568 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
570 unsigned int nSize = 0;
571 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
572 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
573 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
577 template<typename Stream, typename T0, typename T1, typename T2>
578 void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
580 Serialize(os, std::get<0>(item), nType, nVersion);
581 Serialize(os, std::get<1>(item), nType, nVersion);
582 Serialize(os, std::get<2>(item), nType, nVersion);
585 template<typename Stream, typename T0, typename T1, typename T2>
586 void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion)
588 Unserialize(is, std::get<0>(item), nType, nVersion);
589 Unserialize(is, std::get<1>(item), nType, nVersion);
590 Unserialize(is, std::get<2>(item), nType, nVersion);
598 template<typename T0, typename T1, typename T2, typename T3>
599 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
601 unsigned int nSize = 0;
602 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
603 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
604 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
605 nSize += GetSerializeSize(std::get<3>(item), nType, nVersion);
609 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
610 void Serialize(Stream& os, const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
612 Serialize(os, std::get<0>(item), nType, nVersion);
613 Serialize(os, std::get<1>(item), nType, nVersion);
614 Serialize(os, std::get<2>(item), nType, nVersion);
615 Serialize(os, std::get<3>(item), nType, nVersion);
618 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
619 void Unserialize(Stream& is, std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
621 Unserialize(is, std::get<0>(item), nType, nVersion);
622 Unserialize(is, std::get<1>(item), nType, nVersion);
623 Unserialize(is, std::get<2>(item), nType, nVersion);
624 Unserialize(is, std::get<3>(item), nType, nVersion);
632 template<typename K, typename T, typename Pred, typename A>
633 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
635 unsigned int nSize = GetSizeOfCompactSize(m.size());
636 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
637 nSize += GetSerializeSize((*mi), nType, nVersion);
641 template<typename Stream, typename K, typename T, typename Pred, typename A>
642 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
644 WriteCompactSize(os, m.size());
645 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
646 Serialize(os, (*mi), nType, nVersion);
649 template<typename Stream, typename K, typename T, typename Pred, typename A>
650 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
653 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
654 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
655 for (unsigned int i = 0; i < nSize; i++)
657 std::pair<K, T> item;
658 Unserialize(is, item, nType, nVersion);
659 mi = m.insert(mi, item);
668 template<typename K, typename Pred, typename A>
669 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
671 unsigned int nSize = GetSizeOfCompactSize(m.size());
672 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
673 nSize += GetSerializeSize((*it), nType, nVersion);
677 template<typename Stream, typename K, typename Pred, typename A>
678 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
680 WriteCompactSize(os, m.size());
681 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
682 Serialize(os, (*it), nType, nVersion);
685 template<typename Stream, typename K, typename Pred, typename A>
686 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
689 unsigned int nSize = ReadCompactSize(is);
690 typename std::set<K, Pred, A>::iterator it = m.begin();
691 for (unsigned int i = 0; i < nSize; i++)
694 Unserialize(is, key, nType, nVersion);
695 it = m.insert(it, key);
702 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
704 class CSerActionGetSerializeSize { };
705 class CSerActionSerialize { };
706 class CSerActionUnserialize { };
708 template<typename Stream, typename T>
709 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
711 return ::GetSerializeSize(obj, nType, nVersion);
714 template<typename Stream, typename T>
715 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
717 ::Serialize(s, obj, nType, nVersion);
721 template<typename Stream, typename T>
722 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
724 ::Unserialize(s, obj, nType, nVersion);
728 struct ser_streamplaceholder
744 typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
746 /** Double ended buffer combining vector and stream-like interfaces.
748 * >> and << read and write unformatted data using the above serialization templates.
749 * Fills with data in linear time; some stringstream implementations take N^2 time.
754 typedef CSerializeData vector_type;
756 unsigned int nReadPos;
763 typedef vector_type::allocator_type allocator_type;
764 typedef vector_type::size_type size_type;
765 typedef vector_type::difference_type difference_type;
766 typedef vector_type::reference reference;
767 typedef vector_type::const_reference const_reference;
768 typedef vector_type::value_type value_type;
769 typedef vector_type::iterator iterator;
770 typedef vector_type::const_iterator const_iterator;
771 typedef vector_type::reverse_iterator reverse_iterator;
773 explicit CDataStream(int nTypeIn, int nVersionIn)
775 Init(nTypeIn, nVersionIn);
778 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
780 Init(nTypeIn, nVersionIn);
783 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
785 Init(nTypeIn, nVersionIn);
788 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
790 Init(nTypeIn, nVersionIn);
793 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
795 Init(nTypeIn, nVersionIn);
798 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
800 Init(nTypeIn, nVersionIn);
803 void Init(int nTypeIn, int nVersionIn)
807 nVersion = nVersionIn;
809 exceptmask = std::ios::badbit | std::ios::failbit;
812 CDataStream& operator+=(const CDataStream& b)
814 vch.insert(vch.end(), b.begin(), b.end());
818 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
825 std::string str() const
827 return (std::string(begin(), end()));
834 const_iterator begin() const { return vch.begin() + nReadPos; }
835 iterator begin() { return vch.begin() + nReadPos; }
836 const_iterator end() const { return vch.end(); }
837 iterator end() { return vch.end(); }
838 size_type size() const { return vch.size() - nReadPos; }
839 bool empty() const { return vch.size() == nReadPos; }
840 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
841 void reserve(size_type n) { vch.reserve(n + nReadPos); }
842 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
843 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
844 void clear() { vch.clear(); nReadPos = 0; }
845 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
846 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
848 void insert(iterator it, const_iterator first, const_iterator last)
850 assert(last - first >= 0);
851 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
853 // special case for inserting at the front when there's room
854 nReadPos -= (unsigned int)(last - first);
855 memcpy(&vch[nReadPos], &first[0], last - first);
858 vch.insert(it, first, last);
862 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
864 assert(last - first >= 0);
865 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
867 // special case for inserting at the front when there's room
868 nReadPos -= (last - first);
869 memcpy(&vch[nReadPos], &first[0], last - first);
872 vch.insert(it, first, last);
876 void insert(iterator it, const char* first, const char* last)
878 assert(last - first >= 0);
879 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
881 // special case for inserting at the front when there's room
882 nReadPos -= (unsigned int)(last - first);
883 memcpy(&vch[nReadPos], &first[0], last - first);
886 vch.insert(it, first, last);
889 iterator erase(iterator it)
891 if (it == vch.begin() + nReadPos)
893 // special case for erasing from the front
894 if (++nReadPos >= vch.size())
896 // whenever we reach the end, we take the opportunity to clear the buffer
898 return vch.erase(vch.begin(), vch.end());
900 return vch.begin() + nReadPos;
903 return vch.erase(it);
906 iterator erase(iterator first, iterator last)
908 if (first == vch.begin() + nReadPos)
910 // special case for erasing from the front
911 if (last == vch.end())
914 return vch.erase(vch.begin(), vch.end());
918 nReadPos = (unsigned int)(last - vch.begin());
923 return vch.erase(first, last);
926 inline void Compact()
928 vch.erase(vch.begin(), vch.begin() + nReadPos);
932 bool Rewind(size_type n)
934 // Rewind by n characters if the buffer hasn't been compacted yet
937 nReadPos -= (unsigned int)n;
945 void setstate(short bits, const char* psz)
948 if (state & exceptmask)
949 throw std::ios_base::failure(psz);
952 bool eof() const { return size() == 0; }
953 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
954 bool good() const { return !eof() && (state == 0); }
955 void clear(short n) { state = n; } // name conflict with vector clear()
956 short exceptions() { return exceptmask; }
957 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
958 CDataStream* rdbuf() { return this; }
959 int in_avail() { return (int)(size()); }
961 void SetType(int n) { nType = n; }
962 int GetType() { return nType; }
963 void SetVersion(int n) { nVersion = n; }
964 int GetVersion() { return nVersion; }
965 void ReadVersion() { *this >> nVersion; }
966 void WriteVersion() { *this << nVersion; }
968 CDataStream& read(char* pch, int nSize)
970 // Read from the beginning of the buffer
972 unsigned int nReadPosNext = nReadPos + nSize;
973 if (nReadPosNext >= vch.size())
975 if (nReadPosNext > vch.size())
977 setstate(std::ios::failbit, "CDataStream::read() : end of data");
978 memset(pch, 0, nSize);
979 nSize = (int)(vch.size() - nReadPos);
981 memcpy(pch, &vch[nReadPos], nSize);
986 memcpy(pch, &vch[nReadPos], nSize);
987 nReadPos = nReadPosNext;
991 CDataStream& ignore(int nSize)
993 // Ignore from the beginning of the buffer
995 unsigned int nReadPosNext = nReadPos + nSize;
996 if (nReadPosNext >= vch.size())
998 if (nReadPosNext > vch.size())
999 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1004 nReadPos = nReadPosNext;
1008 CDataStream& write(const char* pch, int nSize)
1010 // Write to the end of the buffer
1012 vch.insert(vch.end(), pch, pch + nSize);
1016 template<typename Stream>
1017 void Serialize(Stream& s, int nType, int nVersion) const
1019 // Special case: stream << stream concatenates like stream += stream
1021 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1024 template<typename T>
1025 unsigned int GetSerializeSize(const T& obj)
1027 // Tells the size of the object if serialized to this stream
1028 return ::GetSerializeSize(obj, nType, nVersion);
1031 template<typename T>
1032 CDataStream& operator<<(const T& obj)
1034 // Serialize to this stream
1035 ::Serialize(*this, obj, nType, nVersion);
1039 template<typename T>
1040 CDataStream& operator>>(T& obj)
1042 // Unserialize from this stream
1043 ::Unserialize(*this, obj, nType, nVersion);
1047 void GetAndClear(CSerializeData &data) {
1049 CSerializeData().swap(vch);
1054 // RAII wrapper for FILE*.
1056 // Will automatically close the file when it goes out of scope if not null.
1057 // If you're returning the file pointer, return file.release().
1058 // If you need to close the file early, use file.fclose() instead of fclose(file).
1069 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn);
1073 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1074 operator FILE*() { return file; }
1075 FILE* operator->() { return file; }
1076 FILE& operator*() { return *file; }
1077 FILE** operator&() { return &file; }
1078 FILE* operator=(FILE* pnew) { return file = pnew; }
1079 bool operator!() { return (file == NULL); }
1085 void setstate(short bits, const char* psz);
1086 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1087 bool good() const { return state == 0; }
1088 void clear(short n = 0) { state = n; }
1089 short exceptions() { return exceptmask; }
1090 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1092 void SetType(int n) { nType = n; }
1093 int GetType() { return nType; }
1094 void SetVersion(int n) { nVersion = n; }
1095 int GetVersion() { return nVersion; }
1096 void ReadVersion() { *this >> nVersion; }
1097 void WriteVersion() { *this << nVersion; }
1099 CAutoFile& read(char* pch, size_t nSize);
1100 CAutoFile& write(const char* pch, size_t nSize);
1102 template<typename T>
1103 unsigned int GetSerializeSize(const T& obj)
1105 // Tells the size of the object if serialized to this stream
1106 return ::GetSerializeSize(obj, nType, nVersion);
1109 template<typename T>
1110 CAutoFile& operator<<(const T& obj)
1112 // Serialize to this stream
1114 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1115 ::Serialize(*this, obj, nType, nVersion);
1119 template<typename T>
1120 CAutoFile& operator>>(T& obj)
1122 // Unserialize from this stream
1124 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1125 ::Unserialize(*this, obj, nType, nVersion);
1130 // Wrapper around a FILE* that implements a ring buffer to
1131 // deserialize from. It guarantees the ability to rewind
1132 // a given number of bytes.
1136 FILE *src; // source file
1137 uint64_t nSrcPos; // how many bytes have been read from source
1138 uint64_t nReadPos; // how many bytes have been read from this
1139 uint64_t nReadLimit; // up to which position we're allowed to read
1140 uint64_t nRewind; // how many bytes we guarantee to rewind
1141 std::vector<char> vchBuf; // the buffer
1147 void setstate(short bits, const char *psz);
1148 // read data from the source to fill the buffer
1155 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn);
1156 // check whether no error occurred
1158 // check whether we're at the end of the source file
1160 // read a number of bytes
1161 CBufferedFile& read(char *pch, size_t nSize);
1162 // return the current reading position
1164 // rewind to a given reading position
1165 bool SetPos(uint64_t nPos);
1166 bool Seek(uint64_t nPos);
1167 // prevent reading beyond a certain position
1168 // no argument removes the limit
1169 bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max());
1171 template<typename T>
1172 CBufferedFile& operator>>(T& obj) {
1173 // Unserialize from this stream
1174 ::Unserialize(*this, obj, nType, nVersion);
1178 // search for a given byte in the stream, and remain positioned on it
1179 void FindByte(char ch);