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
8 #include "allocators.h"
14 #include <type_traits>
20 #if defined __USE_MINGW_ANSI_STDIO
21 #undef __USE_MINGW_ANSI_STDIO // This constant forces MinGW to conduct stupid behavior
28 static const unsigned int MAX_SIZE = 0x02000000;
30 // Used to bypass the rule against non-const reference to temporary
31 // where it makes sense with wrappers such as CFlatData or CTxDB
33 inline T& REF(const T& val)
35 return const_cast<T&>(val);
38 /////////////////////////////////////////////////////////////////
40 // Templates for serializing to anything that looks like a stream,
41 // i.e. anything that supports .read(char*, int) and .write(char*, int)
47 SER_NETWORK = (1 << 0),
49 SER_GETHASH = (1 << 2),
52 SER_SKIPSIG = (1 << 16),
53 SER_BLOCKHEADERONLY = (1 << 17)
57 #define IMPLEMENT_SERIALIZE(statements) \
58 unsigned int GetSerializeSize(int nType, int nVersion) const \
60 CSerActionGetSerializeSize ser_action; \
61 const bool fGetSize = true; \
62 const bool fWrite = false; \
63 const bool fRead = false; \
64 unsigned int nSerSize = 0; \
65 ser_streamplaceholder s; \
66 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
68 s.nVersion = nVersion; \
72 template<typename Stream> \
73 void Serialize(Stream& s, int nType, int nVersion) const \
75 CSerActionSerialize ser_action; \
76 const bool fGetSize = false; \
77 const bool fWrite = true; \
78 const bool fRead = false; \
79 unsigned int nSerSize = 0; \
80 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
83 template<typename Stream> \
84 void Unserialize(Stream& s, int nType, int nVersion) \
86 CSerActionUnserialize ser_action; \
87 const bool fGetSize = false; \
88 const bool fWrite = false; \
89 const bool fRead = true; \
90 unsigned int nSerSize = 0; \
91 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
95 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
105 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
106 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
108 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
109 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
110 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
111 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
112 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
113 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
114 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
115 //inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
116 //inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
117 inline unsigned int GetSerializeSize(int64_t a, int, int=0) { return sizeof(a); }
118 inline unsigned int GetSerializeSize(uint64_t a, int, int=0) { return sizeof(a); }
119 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
120 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
122 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
123 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
124 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
125 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
126 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
127 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
128 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
129 //template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
130 //template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
131 template<typename Stream> inline void Serialize(Stream& s, int64_t a, int, int=0) { WRITEDATA(s, a); }
132 template<typename Stream> inline void Serialize(Stream& s, uint64_t a, int, int=0) { WRITEDATA(s, a); }
133 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
134 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
136 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
137 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
138 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
139 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
140 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
141 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
142 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
143 //template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
144 //template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
145 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a, int, int=0) { READDATA(s, a); }
146 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a, int, int=0) { READDATA(s, a); }
147 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
148 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
150 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
151 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
152 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
161 // size < 253 -- 1 byte
162 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
163 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
164 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
166 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
168 if (nSize < 253) return sizeof(unsigned char);
169 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
170 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
171 else return sizeof(unsigned char) + sizeof(uint64_t);
174 template<typename Stream>
175 void WriteCompactSize(Stream& os, uint64_t nSize)
179 unsigned char chSize = (unsigned char)nSize;
180 WRITEDATA(os, chSize);
182 else if (nSize <= std::numeric_limits<unsigned short>::max())
184 unsigned char chSize = 253;
185 unsigned short xSize = (unsigned short)nSize;
186 WRITEDATA(os, chSize);
187 WRITEDATA(os, xSize);
189 else if (nSize <= std::numeric_limits<unsigned int>::max())
191 unsigned char chSize = 254;
192 unsigned int xSize = (unsigned int)nSize;
193 WRITEDATA(os, chSize);
194 WRITEDATA(os, xSize);
198 unsigned char chSize = 255;
199 uint64_t xSize = nSize;
200 WRITEDATA(os, chSize);
201 WRITEDATA(os, xSize);
206 template<typename Stream>
207 uint64_t ReadCompactSize(Stream& is)
209 unsigned char chSize;
210 READDATA(is, chSize);
211 uint64_t nSizeRet = 0;
216 else if (chSize == 253)
218 unsigned short xSize;
222 else if (chSize == 254)
234 if (nSizeRet > (uint64_t)MAX_SIZE)
235 throw std::ios_base::failure("ReadCompactSize() : size too large");
239 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
240 // The high bit in each byte signifies whether another digit follows. To make
241 // the encoding is one-to-one, one is subtracted from all but the last digit.
242 // Thus, the byte sequence a[] with length len, where all but the last byte
243 // has bit 128 set, encodes the number:
245 // (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
248 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
249 // * Every integer has exactly one encoding
250 // * Encoding does not depend on size of original integer type
251 // * No redundancy: every (infinite) byte sequence corresponds to a list
252 // of encoded integers.
254 // 0: [0x00] 256: [0x81 0x00]
255 // 1: [0x01] 16383: [0xFE 0x7F]
256 // 127: [0x7F] 16384: [0xFF 0x00]
257 // 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F]
258 // 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F]
259 // 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
262 inline unsigned int GetSizeOfVarInt(I n)
274 template<typename Stream, typename I>
275 void WriteVarInt(Stream& os, I n)
277 unsigned char tmp[(sizeof(n)*8+6)/7];
280 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
287 WRITEDATA(os, tmp[len]);
291 template<typename Stream, typename I>
292 I ReadVarInt(Stream& is)
296 unsigned char chData;
297 READDATA(is, chData);
298 n = (n << 7) | (chData & 0x7F);
306 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
307 #define VARINT(obj) REF(WrapVarInt(REF(obj)))
309 /** Wrapper for serializing arrays and POD.
317 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
318 char* begin() { return pbegin; }
319 const char* begin() const { return pbegin; }
320 char* end() { return pend; }
321 const char* end() const { return pend; }
323 unsigned int GetSerializeSize(int, int=0) const
325 return (unsigned int)(pend - pbegin);
328 template<typename Stream>
329 void Serialize(Stream& s, int, int=0) const
331 s.write(pbegin, (int)(pend - pbegin));
334 template<typename Stream>
335 void Unserialize(Stream& s, int, int=0)
337 s.read(pbegin, pend - pbegin);
347 CVarInt(I& nIn) : n(nIn) { }
349 unsigned int GetSerializeSize(int, int) const {
350 return GetSizeOfVarInt<I>(n);
353 template<typename Stream>
354 void Serialize(Stream &s, int, int) const {
355 WriteVarInt<Stream,I>(s, n);
358 template<typename Stream>
359 void Unserialize(Stream& s, int, int) {
360 n = ReadVarInt<Stream,I>(s);
365 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
368 // Forward declarations
372 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
373 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
374 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
377 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
378 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
379 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
380 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&);
381 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&);
382 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
383 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&);
384 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&);
385 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
387 // others derived from vector
388 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
389 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
390 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
393 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
394 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
395 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
398 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
399 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
400 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion);
403 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
404 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);
405 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);
408 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
409 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);
410 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);
413 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
414 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
415 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
422 // If none of the specialized versions above matched, default to calling member function.
423 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
424 // The compiler will only cast int to long if none of the other templates matched.
425 // Thanks to Boost serialization for this idea.
428 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
430 return a.GetSerializeSize((int)nType, nVersion);
433 template<typename Stream, typename T>
434 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
436 a.Serialize(os, (int)nType, nVersion);
439 template<typename Stream, typename T>
440 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
442 a.Unserialize(is, (int)nType, nVersion);
453 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
455 return (unsigned int)(GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]));
458 template<typename Stream, typename C>
459 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
461 WriteCompactSize(os, str.size());
463 os.write((char*)&str[0], (int)(str.size() * sizeof(str[0])));
466 template<typename Stream, typename C>
467 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
469 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
472 is.read((char*)&str[0], nSize * sizeof(str[0]));
480 template<typename T, typename A>
481 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
483 return (unsigned int)(GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
486 template<typename T, typename A>
487 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
489 unsigned int nSize = GetSizeOfCompactSize(v.size());
490 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
491 nSize += GetSerializeSize((*vi), nType, nVersion);
495 template<typename T, typename A>
496 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
498 return GetSerializeSize_impl(v, nType, nVersion, std::is_fundamental<T>());
502 template<typename Stream, typename T, typename A>
503 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
505 WriteCompactSize(os, v.size());
507 os.write((char*)&v[0], (int)(v.size() * sizeof(T)));
510 template<typename Stream, typename T, typename A>
511 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
513 WriteCompactSize(os, v.size());
514 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
515 ::Serialize(os, (*vi), nType, nVersion);
518 template<typename Stream, typename T, typename A>
519 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
521 Serialize_impl(os, v, nType, nVersion, std::is_fundamental<T>());
525 template<typename Stream, typename T, typename A>
526 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
528 // Limit size per read so bogus size value won't cause out of memory
530 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
534 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
536 is.read((char*)&v[i], blk * sizeof(T));
541 template<typename Stream, typename T, typename A>
542 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
545 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
547 unsigned int nMid = 0;
550 nMid += 5000000 / sizeof(T);
554 for (; i < nMid; i++)
555 Unserialize(is, v[i], nType, nVersion);
559 template<typename Stream, typename T, typename A>
560 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
562 Unserialize_impl(is, v, nType, nVersion, std::is_fundamental<T>());
568 // others derived from vector
570 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
572 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
575 template<typename Stream>
576 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
578 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
581 template<typename Stream>
582 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
584 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
592 template<typename K, typename T>
593 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
595 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
598 template<typename Stream, typename K, typename T>
599 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
601 Serialize(os, item.first, nType, nVersion);
602 Serialize(os, item.second, nType, nVersion);
605 template<typename Stream, typename K, typename T>
606 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
608 Unserialize(is, item.first, nType, nVersion);
609 Unserialize(is, item.second, nType, nVersion);
617 template<typename T0, typename T1, typename T2>
618 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
620 unsigned int nSize = 0;
621 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
622 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
623 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
627 template<typename Stream, typename T0, typename T1, typename T2>
628 void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
630 Serialize(os, std::get<0>(item), nType, nVersion);
631 Serialize(os, std::get<1>(item), nType, nVersion);
632 Serialize(os, std::get<2>(item), nType, nVersion);
635 template<typename Stream, typename T0, typename T1, typename T2>
636 void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion)
638 Unserialize(is, std::get<0>(item), nType, nVersion);
639 Unserialize(is, std::get<1>(item), nType, nVersion);
640 Unserialize(is, std::get<2>(item), nType, nVersion);
648 template<typename T0, typename T1, typename T2, typename T3>
649 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
651 unsigned int nSize = 0;
652 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
653 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
654 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
655 nSize += GetSerializeSize(std::get<3>(item), nType, nVersion);
659 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
660 void Serialize(Stream& os, const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
662 Serialize(os, std::get<0>(item), nType, nVersion);
663 Serialize(os, std::get<1>(item), nType, nVersion);
664 Serialize(os, std::get<2>(item), nType, nVersion);
665 Serialize(os, std::get<3>(item), nType, nVersion);
668 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
669 void Unserialize(Stream& is, std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
671 Unserialize(is, std::get<0>(item), nType, nVersion);
672 Unserialize(is, std::get<1>(item), nType, nVersion);
673 Unserialize(is, std::get<2>(item), nType, nVersion);
674 Unserialize(is, std::get<3>(item), nType, nVersion);
682 template<typename K, typename T, typename Pred, typename A>
683 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
685 unsigned int nSize = GetSizeOfCompactSize(m.size());
686 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
687 nSize += GetSerializeSize((*mi), nType, nVersion);
691 template<typename Stream, typename K, typename T, typename Pred, typename A>
692 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
694 WriteCompactSize(os, m.size());
695 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
696 Serialize(os, (*mi), nType, nVersion);
699 template<typename Stream, typename K, typename T, typename Pred, typename A>
700 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
703 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
704 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
705 for (unsigned int i = 0; i < nSize; i++)
707 std::pair<K, T> item;
708 Unserialize(is, item, nType, nVersion);
709 mi = m.insert(mi, item);
718 template<typename K, typename Pred, typename A>
719 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
721 unsigned int nSize = GetSizeOfCompactSize(m.size());
722 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
723 nSize += GetSerializeSize((*it), nType, nVersion);
727 template<typename Stream, typename K, typename Pred, typename A>
728 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
730 WriteCompactSize(os, m.size());
731 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
732 Serialize(os, (*it), nType, nVersion);
735 template<typename Stream, typename K, typename Pred, typename A>
736 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
739 unsigned int nSize = ReadCompactSize(is);
740 typename std::set<K, Pred, A>::iterator it = m.begin();
741 for (unsigned int i = 0; i < nSize; i++)
744 Unserialize(is, key, nType, nVersion);
745 it = m.insert(it, key);
752 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
754 class CSerActionGetSerializeSize { };
755 class CSerActionSerialize { };
756 class CSerActionUnserialize { };
758 template<typename Stream, typename T>
759 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
761 return ::GetSerializeSize(obj, nType, nVersion);
764 template<typename Stream, typename T>
765 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
767 ::Serialize(s, obj, nType, nVersion);
771 template<typename Stream, typename T>
772 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
774 ::Unserialize(s, obj, nType, nVersion);
778 struct ser_streamplaceholder
794 typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
796 /** Double ended buffer combining vector and stream-like interfaces.
798 * >> and << read and write unformatted data using the above serialization templates.
799 * Fills with data in linear time; some stringstream implementations take N^2 time.
804 typedef CSerializeData vector_type;
806 unsigned int nReadPos;
813 typedef vector_type::allocator_type allocator_type;
814 typedef vector_type::size_type size_type;
815 typedef vector_type::difference_type difference_type;
816 typedef vector_type::reference reference;
817 typedef vector_type::const_reference const_reference;
818 typedef vector_type::value_type value_type;
819 typedef vector_type::iterator iterator;
820 typedef vector_type::const_iterator const_iterator;
821 typedef vector_type::reverse_iterator reverse_iterator;
823 explicit CDataStream(int nTypeIn, int nVersionIn)
825 Init(nTypeIn, nVersionIn);
828 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
830 Init(nTypeIn, nVersionIn);
833 #if !defined(_MSC_VER) || _MSC_VER >= 1300
834 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
836 Init(nTypeIn, nVersionIn);
840 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
842 Init(nTypeIn, nVersionIn);
845 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
847 Init(nTypeIn, nVersionIn);
850 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
852 Init(nTypeIn, nVersionIn);
855 void Init(int nTypeIn, int nVersionIn)
859 nVersion = nVersionIn;
861 exceptmask = std::ios::badbit | std::ios::failbit;
864 CDataStream& operator+=(const CDataStream& b)
866 vch.insert(vch.end(), b.begin(), b.end());
870 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
877 std::string str() const
879 return (std::string(begin(), end()));
886 const_iterator begin() const { return vch.begin() + nReadPos; }
887 iterator begin() { return vch.begin() + nReadPos; }
888 const_iterator end() const { return vch.end(); }
889 iterator end() { return vch.end(); }
890 size_type size() const { return vch.size() - nReadPos; }
891 bool empty() const { return vch.size() == nReadPos; }
892 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
893 void reserve(size_type n) { vch.reserve(n + nReadPos); }
894 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
895 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
896 void clear() { vch.clear(); nReadPos = 0; }
897 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
898 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
901 void insert(iterator it, const_iterator first, const_iterator last)
903 assert(last - first >= 0);
904 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
906 // special case for inserting at the front when there's room
907 nReadPos -= (unsigned int)(last - first);
908 memcpy(&vch[nReadPos], &first[0], last - first);
911 vch.insert(it, first, last);
916 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
918 assert(last - first >= 0);
919 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
921 // special case for inserting at the front when there's room
922 nReadPos -= (last - first);
923 memcpy(&vch[nReadPos], &first[0], last - first);
926 vch.insert(it, first, last);
930 #if !defined(_MSC_VER) || _MSC_VER >= 1300
931 void insert(iterator it, const char* first, const char* last)
933 assert(last - first >= 0);
934 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
936 // special case for inserting at the front when there's room
937 nReadPos -= (unsigned int)(last - first);
938 memcpy(&vch[nReadPos], &first[0], last - first);
941 vch.insert(it, first, last);
945 iterator erase(iterator it)
947 if (it == vch.begin() + nReadPos)
949 // special case for erasing from the front
950 if (++nReadPos >= vch.size())
952 // whenever we reach the end, we take the opportunity to clear the buffer
954 return vch.erase(vch.begin(), vch.end());
956 return vch.begin() + nReadPos;
959 return vch.erase(it);
962 iterator erase(iterator first, iterator last)
964 if (first == vch.begin() + nReadPos)
966 // special case for erasing from the front
967 if (last == vch.end())
970 return vch.erase(vch.begin(), vch.end());
974 nReadPos = (unsigned int)(last - vch.begin());
979 return vch.erase(first, last);
982 inline void Compact()
984 vch.erase(vch.begin(), vch.begin() + nReadPos);
988 bool Rewind(size_type n)
990 // Rewind by n characters if the buffer hasn't been compacted yet
993 nReadPos -= (unsigned int)n;
1001 void setstate(short bits, const char* psz)
1004 if (state & exceptmask)
1005 throw std::ios_base::failure(psz);
1008 bool eof() const { return size() == 0; }
1009 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1010 bool good() const { return !eof() && (state == 0); }
1011 void clear(short n) { state = n; } // name conflict with vector clear()
1012 short exceptions() { return exceptmask; }
1013 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1014 CDataStream* rdbuf() { return this; }
1015 int in_avail() { return (int)(size()); }
1017 void SetType(int n) { nType = n; }
1018 int GetType() { return nType; }
1019 void SetVersion(int n) { nVersion = n; }
1020 int GetVersion() { return nVersion; }
1021 void ReadVersion() { *this >> nVersion; }
1022 void WriteVersion() { *this << nVersion; }
1024 CDataStream& read(char* pch, int nSize)
1026 // Read from the beginning of the buffer
1028 unsigned int nReadPosNext = nReadPos + nSize;
1029 if (nReadPosNext >= vch.size())
1031 if (nReadPosNext > vch.size())
1033 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1034 memset(pch, 0, nSize);
1035 nSize = (int)(vch.size() - nReadPos);
1037 memcpy(pch, &vch[nReadPos], nSize);
1042 memcpy(pch, &vch[nReadPos], nSize);
1043 nReadPos = nReadPosNext;
1047 CDataStream& ignore(int nSize)
1049 // Ignore from the beginning of the buffer
1051 unsigned int nReadPosNext = nReadPos + nSize;
1052 if (nReadPosNext >= vch.size())
1054 if (nReadPosNext > vch.size())
1055 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1060 nReadPos = nReadPosNext;
1064 CDataStream& write(const char* pch, int nSize)
1066 // Write to the end of the buffer
1068 vch.insert(vch.end(), pch, pch + nSize);
1072 template<typename Stream>
1073 void Serialize(Stream& s, int nType, int nVersion) const
1075 // Special case: stream << stream concatenates like stream += stream
1077 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1080 template<typename T>
1081 unsigned int GetSerializeSize(const T& obj)
1083 // Tells the size of the object if serialized to this stream
1084 return ::GetSerializeSize(obj, nType, nVersion);
1087 template<typename T>
1088 CDataStream& operator<<(const T& obj)
1090 // Serialize to this stream
1091 ::Serialize(*this, obj, nType, nVersion);
1095 template<typename T>
1096 CDataStream& operator>>(T& obj)
1098 // Unserialize from this stream
1099 ::Unserialize(*this, obj, nType, nVersion);
1103 void GetAndClear(CSerializeData &data) {
1105 CSerializeData().swap(vch);
1118 /** RAII wrapper for FILE*.
1120 * Will automatically close the file when it goes out of scope if not null.
1121 * If you're returning the file pointer, return file.release().
1122 * If you need to close the file early, use file.fclose() instead of fclose(file).
1134 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
1138 nVersion = nVersionIn;
1140 exceptmask = std::ios::badbit | std::ios::failbit;
1150 if (file != NULL && file != stdin && file != stdout && file != stderr)
1155 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1156 operator FILE*() { return file; }
1157 FILE* operator->() { return file; }
1158 FILE& operator*() { return *file; }
1159 FILE** operator&() { return &file; }
1160 FILE* operator=(FILE* pnew) { return file = pnew; }
1161 bool operator!() { return (file == NULL); }
1167 void setstate(short bits, const char* psz)
1170 if (state & exceptmask)
1171 throw std::ios_base::failure(psz);
1174 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1175 bool good() const { return state == 0; }
1176 void clear(short n = 0) { state = n; }
1177 short exceptions() { return exceptmask; }
1178 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1180 void SetType(int n) { nType = n; }
1181 int GetType() { return nType; }
1182 void SetVersion(int n) { nVersion = n; }
1183 int GetVersion() { return nVersion; }
1184 void ReadVersion() { *this >> nVersion; }
1185 void WriteVersion() { *this << nVersion; }
1187 CAutoFile& read(char* pch, size_t nSize)
1190 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1191 if (fread(pch, 1, nSize, file) != nSize)
1192 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1196 CAutoFile& write(const char* pch, size_t nSize)
1199 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1200 if (fwrite(pch, 1, nSize, file) != nSize)
1201 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1205 template<typename T>
1206 unsigned int GetSerializeSize(const T& obj)
1208 // Tells the size of the object if serialized to this stream
1209 return ::GetSerializeSize(obj, nType, nVersion);
1212 template<typename T>
1213 CAutoFile& operator<<(const T& obj)
1215 // Serialize to this stream
1217 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1218 ::Serialize(*this, obj, nType, nVersion);
1222 template<typename T>
1223 CAutoFile& operator>>(T& obj)
1225 // Unserialize from this stream
1227 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1228 ::Unserialize(*this, obj, nType, nVersion);
1233 /** Wrapper around a FILE* that implements a ring buffer to
1234 * deserialize from. It guarantees the ability to rewind
1235 * a given number of bytes. */
1239 FILE *src; // source file
1240 uint64_t nSrcPos; // how many bytes have been read from source
1241 uint64_t nReadPos; // how many bytes have been read from this
1242 uint64_t nReadLimit; // up to which position we're allowed to read
1243 uint64_t nRewind; // how many bytes we guarantee to rewind
1244 std::vector<char> vchBuf; // the buffer
1250 void setstate(short bits, const char *psz) {
1252 if (state & exceptmask)
1253 throw std::ios_base::failure(psz);
1256 // read data from the source to fill the buffer
1258 unsigned int pos = (unsigned int)(nSrcPos % vchBuf.size());
1259 unsigned int readNow = (unsigned int)(vchBuf.size() - pos);
1260 unsigned int nAvail = (unsigned int)(vchBuf.size() - (nSrcPos - nReadPos) - nRewind);
1261 if (nAvail < readNow)
1265 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
1267 setstate(std::ios_base::failbit, feof(src) ? "CBufferedFile::Fill : end of file" : "CBufferedFile::Fill : fread failed");
1279 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
1280 src(fileIn), nSrcPos(0), nReadPos(0), nReadLimit(std::numeric_limits<uint64_t>::max()), nRewind(nRewindIn), vchBuf(nBufSize, 0),
1281 state(0), exceptmask(std::ios_base::badbit | std::ios_base::failbit), nType(nTypeIn), nVersion(nVersionIn) {
1284 // check whether no error occurred
1289 // check whether we're at the end of the source file
1291 return nReadPos == nSrcPos && feof(src);
1294 // read a number of bytes
1295 CBufferedFile& read(char *pch, size_t nSize) {
1296 if (nSize + nReadPos > nReadLimit)
1297 throw std::ios_base::failure("Read attempted past buffer limit");
1298 if (nSize + nRewind > vchBuf.size())
1299 throw std::ios_base::failure("Read larger than buffer size");
1301 if (nReadPos == nSrcPos)
1303 unsigned int pos = (unsigned int)(nReadPos % vchBuf.size());
1304 size_t nNow = nSize;
1305 if (nNow + pos > vchBuf.size())
1306 nNow = vchBuf.size() - pos;
1307 if (nNow + nReadPos > nSrcPos)
1308 nNow = (size_t)(nSrcPos - nReadPos);
1309 memcpy(pch, &vchBuf[pos], nNow);
1317 // return the current reading position
1322 // rewind to a given reading position
1323 bool SetPos(uint64_t nPos) {
1325 if (nReadPos + nRewind < nSrcPos) {
1326 nReadPos = nSrcPos - nRewind;
1328 } else if (nReadPos > nSrcPos) {
1336 bool Seek(uint64_t nPos) {
1337 long nLongPos = (long)nPos;
1338 if (nPos != (uint64_t)nLongPos)
1340 if (fseek(src, nLongPos, SEEK_SET))
1342 nLongPos = ftell(src);
1344 nReadPos = nLongPos;
1349 // prevent reading beyond a certain position
1350 // no argument removes the limit
1351 bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
1352 if (nPos < nReadPos)
1358 template<typename T>
1359 CBufferedFile& operator>>(T& obj) {
1360 // Unserialize from this stream
1361 ::Unserialize(*this, obj, nType, nVersion);
1365 // search for a given byte in the stream, and remain positioned on it
1366 void FindByte(char ch) {
1368 if (nReadPos == nSrcPos)
1370 if (vchBuf[nReadPos % vchBuf.size()] == ch)