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 <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
169 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
170 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
172 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
174 if (nSize < 253) return sizeof(unsigned char);
175 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
176 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
177 else return sizeof(unsigned char) + sizeof(uint64_t);
180 template<typename Stream>
181 void WriteCompactSize(Stream& os, uint64_t nSize)
185 unsigned char chSize = (unsigned char)nSize;
186 WRITEDATA(os, chSize);
188 else if (nSize <= std::numeric_limits<unsigned short>::max())
190 unsigned char chSize = 253;
191 unsigned short xSize = (unsigned short)nSize;
192 WRITEDATA(os, chSize);
193 WRITEDATA(os, xSize);
195 else if (nSize <= std::numeric_limits<unsigned int>::max())
197 unsigned char chSize = 254;
198 unsigned int xSize = (unsigned int)nSize;
199 WRITEDATA(os, chSize);
200 WRITEDATA(os, xSize);
204 unsigned char chSize = 255;
205 uint64_t xSize = nSize;
206 WRITEDATA(os, chSize);
207 WRITEDATA(os, xSize);
212 template<typename Stream>
213 uint64_t ReadCompactSize(Stream& is)
215 unsigned char chSize;
216 READDATA(is, chSize);
217 uint64_t nSizeRet = 0;
222 else if (chSize == 253)
224 unsigned short xSize;
228 else if (chSize == 254)
240 if (nSizeRet > (uint64_t)MAX_SIZE)
241 throw std::ios_base::failure("ReadCompactSize() : size too large");
245 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
246 // The high bit in each byte signifies whether another digit follows. To make
247 // the encoding is one-to-one, one is subtracted from all but the last digit.
248 // Thus, the byte sequence a[] with length len, where all but the last byte
249 // has bit 128 set, encodes the number:
251 // (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
254 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
255 // * Every integer has exactly one encoding
256 // * Encoding does not depend on size of original integer type
257 // * No redundancy: every (infinite) byte sequence corresponds to a list
258 // of encoded integers.
260 // 0: [0x00] 256: [0x81 0x00]
261 // 1: [0x01] 16383: [0xFE 0x7F]
262 // 127: [0x7F] 16384: [0xFF 0x00]
263 // 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F]
264 // 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F]
265 // 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
268 inline unsigned int GetSizeOfVarInt(I n)
280 template<typename Stream, typename I>
281 void WriteVarInt(Stream& os, I n)
283 unsigned char tmp[(sizeof(n)*8+6)/7];
286 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
293 WRITEDATA(os, tmp[len]);
297 template<typename Stream, typename I>
298 I ReadVarInt(Stream& is)
302 unsigned char chData;
303 READDATA(is, chData);
304 n = (n << 7) | (chData & 0x7F);
312 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
313 #define VARINT(obj) REF(WrapVarInt(REF(obj)))
315 /** Wrapper for serializing arrays and POD.
323 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
324 char* begin() { return pbegin; }
325 const char* begin() const { return pbegin; }
326 char* end() { return pend; }
327 const char* end() const { return pend; }
329 unsigned int GetSerializeSize(int, int=0) const
331 return (unsigned int)(pend - pbegin);
334 template<typename Stream>
335 void Serialize(Stream& s, int, int=0) const
337 s.write(pbegin, (int)(pend - pbegin));
340 template<typename Stream>
341 void Unserialize(Stream& s, int, int=0)
343 s.read(pbegin, pend - pbegin);
353 CVarInt(I& nIn) : n(nIn) { }
355 unsigned int GetSerializeSize(int, int) const {
356 return GetSizeOfVarInt<I>(n);
359 template<typename Stream>
360 void Serialize(Stream &s, int, int) const {
361 WriteVarInt<Stream,I>(s, n);
364 template<typename Stream>
365 void Unserialize(Stream& s, int, int) {
366 n = ReadVarInt<Stream,I>(s);
371 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
374 // Forward declarations
378 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
379 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
380 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
383 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
384 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
385 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
386 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
387 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
388 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
389 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
390 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
391 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
393 // others derived from vector
394 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
395 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
396 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
399 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
400 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
401 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
404 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
405 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
406 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion);
409 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
410 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Serialize(Stream& os, const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
411 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Unserialize(Stream& is, std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
414 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
415 template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion);
416 template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion);
419 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
420 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
421 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
428 // If none of the specialized versions above matched, default to calling member function.
429 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
430 // The compiler will only cast int to long if none of the other templates matched.
431 // Thanks to Boost serialization for this idea.
434 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
436 return a.GetSerializeSize((int)nType, nVersion);
439 template<typename Stream, typename T>
440 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
442 a.Serialize(os, (int)nType, nVersion);
445 template<typename Stream, typename T>
446 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
448 a.Unserialize(is, (int)nType, nVersion);
459 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
461 return (unsigned int)(GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]));
464 template<typename Stream, typename C>
465 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
467 WriteCompactSize(os, str.size());
469 os.write((char*)&str[0], (int)(str.size() * sizeof(str[0])));
472 template<typename Stream, typename C>
473 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
475 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
478 is.read((char*)&str[0], nSize * sizeof(str[0]));
486 template<typename T, typename A>
487 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
489 return (unsigned int)(GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
492 template<typename T, typename A>
493 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
495 unsigned int nSize = GetSizeOfCompactSize(v.size());
496 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
497 nSize += GetSerializeSize((*vi), nType, nVersion);
501 template<typename T, typename A>
502 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
504 return GetSerializeSize_impl(v, nType, nVersion, std::is_fundamental<T>());
508 template<typename Stream, typename T, typename A>
509 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
511 WriteCompactSize(os, v.size());
513 os.write((char*)&v[0], (int)(v.size() * sizeof(T)));
516 template<typename Stream, typename T, typename A>
517 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
519 WriteCompactSize(os, v.size());
520 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
521 ::Serialize(os, (*vi), nType, nVersion);
524 template<typename Stream, typename T, typename A>
525 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
527 Serialize_impl(os, v, nType, nVersion, std::is_fundamental<T>());
531 template<typename Stream, typename T, typename A>
532 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
534 // Limit size per read so bogus size value won't cause out of memory
536 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
540 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
542 is.read((char*)&v[i], blk * sizeof(T));
547 template<typename Stream, typename T, typename A>
548 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
551 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
553 unsigned int nMid = 0;
556 nMid += 5000000 / sizeof(T);
560 for (; i < nMid; i++)
561 Unserialize(is, v[i], nType, nVersion);
565 template<typename Stream, typename T, typename A>
566 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
568 Unserialize_impl(is, v, nType, nVersion, std::is_fundamental<T>());
574 // others derived from vector
576 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
578 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
581 template<typename Stream>
582 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
584 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
587 template<typename Stream>
588 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
590 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
598 template<typename K, typename T>
599 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
601 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
604 template<typename Stream, typename K, typename T>
605 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
607 Serialize(os, item.first, nType, nVersion);
608 Serialize(os, item.second, nType, nVersion);
611 template<typename Stream, typename K, typename T>
612 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
614 Unserialize(is, item.first, nType, nVersion);
615 Unserialize(is, item.second, nType, nVersion);
623 template<typename T0, typename T1, typename T2>
624 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
626 unsigned int nSize = 0;
627 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
628 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
629 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
633 template<typename Stream, typename T0, typename T1, typename T2>
634 void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
636 Serialize(os, std::get<0>(item), nType, nVersion);
637 Serialize(os, std::get<1>(item), nType, nVersion);
638 Serialize(os, std::get<2>(item), nType, nVersion);
641 template<typename Stream, typename T0, typename T1, typename T2>
642 void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion)
644 Unserialize(is, std::get<0>(item), nType, nVersion);
645 Unserialize(is, std::get<1>(item), nType, nVersion);
646 Unserialize(is, std::get<2>(item), nType, nVersion);
654 template<typename T0, typename T1, typename T2, typename T3>
655 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
657 unsigned int nSize = 0;
658 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
659 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
660 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
661 nSize += GetSerializeSize(std::get<3>(item), nType, nVersion);
665 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
666 void Serialize(Stream& os, const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
668 Serialize(os, std::get<0>(item), nType, nVersion);
669 Serialize(os, std::get<1>(item), nType, nVersion);
670 Serialize(os, std::get<2>(item), nType, nVersion);
671 Serialize(os, std::get<3>(item), nType, nVersion);
674 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
675 void Unserialize(Stream& is, std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
677 Unserialize(is, std::get<0>(item), nType, nVersion);
678 Unserialize(is, std::get<1>(item), nType, nVersion);
679 Unserialize(is, std::get<2>(item), nType, nVersion);
680 Unserialize(is, std::get<3>(item), nType, nVersion);
688 template<typename K, typename T, typename Pred, typename A>
689 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
691 unsigned int nSize = GetSizeOfCompactSize(m.size());
692 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
693 nSize += GetSerializeSize((*mi), nType, nVersion);
697 template<typename Stream, typename K, typename T, typename Pred, typename A>
698 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
700 WriteCompactSize(os, m.size());
701 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
702 Serialize(os, (*mi), nType, nVersion);
705 template<typename Stream, typename K, typename T, typename Pred, typename A>
706 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
709 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
710 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
711 for (unsigned int i = 0; i < nSize; i++)
713 std::pair<K, T> item;
714 Unserialize(is, item, nType, nVersion);
715 mi = m.insert(mi, item);
724 template<typename K, typename Pred, typename A>
725 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
727 unsigned int nSize = GetSizeOfCompactSize(m.size());
728 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
729 nSize += GetSerializeSize((*it), nType, nVersion);
733 template<typename Stream, typename K, typename Pred, typename A>
734 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
736 WriteCompactSize(os, m.size());
737 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
738 Serialize(os, (*it), nType, nVersion);
741 template<typename Stream, typename K, typename Pred, typename A>
742 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
745 unsigned int nSize = ReadCompactSize(is);
746 typename std::set<K, Pred, A>::iterator it = m.begin();
747 for (unsigned int i = 0; i < nSize; i++)
750 Unserialize(is, key, nType, nVersion);
751 it = m.insert(it, key);
758 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
760 class CSerActionGetSerializeSize { };
761 class CSerActionSerialize { };
762 class CSerActionUnserialize { };
764 template<typename Stream, typename T>
765 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
767 return ::GetSerializeSize(obj, nType, nVersion);
770 template<typename Stream, typename T>
771 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
773 ::Serialize(s, obj, nType, nVersion);
777 template<typename Stream, typename T>
778 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
780 ::Unserialize(s, obj, nType, nVersion);
784 struct ser_streamplaceholder
800 typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
802 /** Double ended buffer combining vector and stream-like interfaces.
804 * >> and << read and write unformatted data using the above serialization templates.
805 * Fills with data in linear time; some stringstream implementations take N^2 time.
810 typedef CSerializeData vector_type;
812 unsigned int nReadPos;
819 typedef vector_type::allocator_type allocator_type;
820 typedef vector_type::size_type size_type;
821 typedef vector_type::difference_type difference_type;
822 typedef vector_type::reference reference;
823 typedef vector_type::const_reference const_reference;
824 typedef vector_type::value_type value_type;
825 typedef vector_type::iterator iterator;
826 typedef vector_type::const_iterator const_iterator;
827 typedef vector_type::reverse_iterator reverse_iterator;
829 explicit CDataStream(int nTypeIn, int nVersionIn)
831 Init(nTypeIn, nVersionIn);
834 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
836 Init(nTypeIn, nVersionIn);
839 #if !defined(_MSC_VER) || _MSC_VER >= 1300
840 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
842 Init(nTypeIn, nVersionIn);
846 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
848 Init(nTypeIn, nVersionIn);
851 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
853 Init(nTypeIn, nVersionIn);
856 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
858 Init(nTypeIn, nVersionIn);
861 void Init(int nTypeIn, int nVersionIn)
865 nVersion = nVersionIn;
867 exceptmask = std::ios::badbit | std::ios::failbit;
870 CDataStream& operator+=(const CDataStream& b)
872 vch.insert(vch.end(), b.begin(), b.end());
876 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
883 std::string str() const
885 return (std::string(begin(), end()));
892 const_iterator begin() const { return vch.begin() + nReadPos; }
893 iterator begin() { return vch.begin() + nReadPos; }
894 const_iterator end() const { return vch.end(); }
895 iterator end() { return vch.end(); }
896 size_type size() const { return vch.size() - nReadPos; }
897 bool empty() const { return vch.size() == nReadPos; }
898 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
899 void reserve(size_type n) { vch.reserve(n + nReadPos); }
900 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
901 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
902 void clear() { vch.clear(); nReadPos = 0; }
903 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
904 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
907 void insert(iterator it, const_iterator first, const_iterator last)
909 assert(last - first >= 0);
910 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
912 // special case for inserting at the front when there's room
913 nReadPos -= (unsigned int)(last - first);
914 memcpy(&vch[nReadPos], &first[0], last - first);
917 vch.insert(it, first, last);
922 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
924 assert(last - first >= 0);
925 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
927 // special case for inserting at the front when there's room
928 nReadPos -= (last - first);
929 memcpy(&vch[nReadPos], &first[0], last - first);
932 vch.insert(it, first, last);
936 #if !defined(_MSC_VER) || _MSC_VER >= 1300
937 void insert(iterator it, const char* first, const char* last)
939 assert(last - first >= 0);
940 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
942 // special case for inserting at the front when there's room
943 nReadPos -= (unsigned int)(last - first);
944 memcpy(&vch[nReadPos], &first[0], last - first);
947 vch.insert(it, first, last);
951 iterator erase(iterator it)
953 if (it == vch.begin() + nReadPos)
955 // special case for erasing from the front
956 if (++nReadPos >= vch.size())
958 // whenever we reach the end, we take the opportunity to clear the buffer
960 return vch.erase(vch.begin(), vch.end());
962 return vch.begin() + nReadPos;
965 return vch.erase(it);
968 iterator erase(iterator first, iterator last)
970 if (first == vch.begin() + nReadPos)
972 // special case for erasing from the front
973 if (last == vch.end())
976 return vch.erase(vch.begin(), vch.end());
980 nReadPos = (unsigned int)(last - vch.begin());
985 return vch.erase(first, last);
988 inline void Compact()
990 vch.erase(vch.begin(), vch.begin() + nReadPos);
994 bool Rewind(size_type n)
996 // Rewind by n characters if the buffer hasn't been compacted yet
999 nReadPos -= (unsigned int)n;
1007 void setstate(short bits, const char* psz)
1010 if (state & exceptmask)
1011 throw std::ios_base::failure(psz);
1014 bool eof() const { return size() == 0; }
1015 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1016 bool good() const { return !eof() && (state == 0); }
1017 void clear(short n) { state = n; } // name conflict with vector clear()
1018 short exceptions() { return exceptmask; }
1019 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1020 CDataStream* rdbuf() { return this; }
1021 int in_avail() { return (int)(size()); }
1023 void SetType(int n) { nType = n; }
1024 int GetType() { return nType; }
1025 void SetVersion(int n) { nVersion = n; }
1026 int GetVersion() { return nVersion; }
1027 void ReadVersion() { *this >> nVersion; }
1028 void WriteVersion() { *this << nVersion; }
1030 CDataStream& read(char* pch, int nSize)
1032 // Read from the beginning of the buffer
1034 unsigned int nReadPosNext = nReadPos + nSize;
1035 if (nReadPosNext >= vch.size())
1037 if (nReadPosNext > vch.size())
1039 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1040 memset(pch, 0, nSize);
1041 nSize = (int)(vch.size() - nReadPos);
1043 memcpy(pch, &vch[nReadPos], nSize);
1048 memcpy(pch, &vch[nReadPos], nSize);
1049 nReadPos = nReadPosNext;
1053 CDataStream& ignore(int nSize)
1055 // Ignore from the beginning of the buffer
1057 unsigned int nReadPosNext = nReadPos + nSize;
1058 if (nReadPosNext >= vch.size())
1060 if (nReadPosNext > vch.size())
1061 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1066 nReadPos = nReadPosNext;
1070 CDataStream& write(const char* pch, int nSize)
1072 // Write to the end of the buffer
1074 vch.insert(vch.end(), pch, pch + nSize);
1078 template<typename Stream>
1079 void Serialize(Stream& s, int nType, int nVersion) const
1081 // Special case: stream << stream concatenates like stream += stream
1083 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1086 template<typename T>
1087 unsigned int GetSerializeSize(const T& obj)
1089 // Tells the size of the object if serialized to this stream
1090 return ::GetSerializeSize(obj, nType, nVersion);
1093 template<typename T>
1094 CDataStream& operator<<(const T& obj)
1096 // Serialize to this stream
1097 ::Serialize(*this, obj, nType, nVersion);
1101 template<typename T>
1102 CDataStream& operator>>(T& obj)
1104 // Unserialize from this stream
1105 ::Unserialize(*this, obj, nType, nVersion);
1109 void GetAndClear(CSerializeData &data) {
1111 CSerializeData().swap(vch);
1124 /** RAII wrapper for FILE*.
1126 * Will automatically close the file when it goes out of scope if not null.
1127 * If you're returning the file pointer, return file.release().
1128 * If you need to close the file early, use file.fclose() instead of fclose(file).
1140 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
1144 nVersion = nVersionIn;
1146 exceptmask = std::ios::badbit | std::ios::failbit;
1156 if (file != NULL && file != stdin && file != stdout && file != stderr)
1161 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1162 operator FILE*() { return file; }
1163 FILE* operator->() { return file; }
1164 FILE& operator*() { return *file; }
1165 FILE** operator&() { return &file; }
1166 FILE* operator=(FILE* pnew) { return file = pnew; }
1167 bool operator!() { return (file == NULL); }
1173 void setstate(short bits, const char* psz)
1176 if (state & exceptmask)
1177 throw std::ios_base::failure(psz);
1180 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1181 bool good() const { return state == 0; }
1182 void clear(short n = 0) { state = n; }
1183 short exceptions() { return exceptmask; }
1184 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1186 void SetType(int n) { nType = n; }
1187 int GetType() { return nType; }
1188 void SetVersion(int n) { nVersion = n; }
1189 int GetVersion() { return nVersion; }
1190 void ReadVersion() { *this >> nVersion; }
1191 void WriteVersion() { *this << nVersion; }
1193 CAutoFile& read(char* pch, size_t nSize)
1196 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1197 if (fread(pch, 1, nSize, file) != nSize)
1198 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1202 CAutoFile& write(const char* pch, size_t nSize)
1205 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1206 if (fwrite(pch, 1, nSize, file) != nSize)
1207 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1211 template<typename T>
1212 unsigned int GetSerializeSize(const T& obj)
1214 // Tells the size of the object if serialized to this stream
1215 return ::GetSerializeSize(obj, nType, nVersion);
1218 template<typename T>
1219 CAutoFile& operator<<(const T& obj)
1221 // Serialize to this stream
1223 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1224 ::Serialize(*this, obj, nType, nVersion);
1228 template<typename T>
1229 CAutoFile& operator>>(T& obj)
1231 // Unserialize from this stream
1233 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1234 ::Unserialize(*this, obj, nType, nVersion);
1239 /** Wrapper around a FILE* that implements a ring buffer to
1240 * deserialize from. It guarantees the ability to rewind
1241 * a given number of bytes. */
1245 FILE *src; // source file
1246 uint64_t nSrcPos; // how many bytes have been read from source
1247 uint64_t nReadPos; // how many bytes have been read from this
1248 uint64_t nReadLimit; // up to which position we're allowed to read
1249 uint64_t nRewind; // how many bytes we guarantee to rewind
1250 std::vector<char> vchBuf; // the buffer
1256 void setstate(short bits, const char *psz) {
1258 if (state & exceptmask)
1259 throw std::ios_base::failure(psz);
1262 // read data from the source to fill the buffer
1264 unsigned int pos = (unsigned int)(nSrcPos % vchBuf.size());
1265 unsigned int readNow = (unsigned int)(vchBuf.size() - pos);
1266 unsigned int nAvail = (unsigned int)(vchBuf.size() - (nSrcPos - nReadPos) - nRewind);
1267 if (nAvail < readNow)
1271 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
1273 setstate(std::ios_base::failbit, feof(src) ? "CBufferedFile::Fill : end of file" : "CBufferedFile::Fill : fread failed");
1285 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
1286 src(fileIn), nSrcPos(0), nReadPos(0), nReadLimit(std::numeric_limits<uint64_t>::max()), nRewind(nRewindIn), vchBuf(nBufSize, 0),
1287 state(0), exceptmask(std::ios_base::badbit | std::ios_base::failbit), nType(nTypeIn), nVersion(nVersionIn) {
1290 // check whether no error occurred
1295 // check whether we're at the end of the source file
1297 return nReadPos == nSrcPos && feof(src);
1300 // read a number of bytes
1301 CBufferedFile& read(char *pch, size_t nSize) {
1302 if (nSize + nReadPos > nReadLimit)
1303 throw std::ios_base::failure("Read attempted past buffer limit");
1304 if (nSize + nRewind > vchBuf.size())
1305 throw std::ios_base::failure("Read larger than buffer size");
1307 if (nReadPos == nSrcPos)
1309 unsigned int pos = (unsigned int)(nReadPos % vchBuf.size());
1310 size_t nNow = nSize;
1311 if (nNow + pos > vchBuf.size())
1312 nNow = vchBuf.size() - pos;
1313 if (nNow + nReadPos > nSrcPos)
1314 nNow = (size_t)(nSrcPos - nReadPos);
1315 memcpy(pch, &vchBuf[pos], nNow);
1323 // return the current reading position
1328 // rewind to a given reading position
1329 bool SetPos(uint64_t nPos) {
1331 if (nReadPos + nRewind < nSrcPos) {
1332 nReadPos = nSrcPos - nRewind;
1334 } else if (nReadPos > nSrcPos) {
1342 bool Seek(uint64_t nPos) {
1343 long nLongPos = (long)nPos;
1344 if (nPos != (uint64_t)nLongPos)
1346 if (fseek(src, nLongPos, SEEK_SET))
1348 nLongPos = ftell(src);
1350 nReadPos = nLongPos;
1355 // prevent reading beyond a certain position
1356 // no argument removes the limit
1357 bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
1358 if (nPos < nReadPos)
1364 template<typename T>
1365 CBufferedFile& operator>>(T& obj) {
1366 // Unserialize from this stream
1367 ::Unserialize(*this, obj, nType, nVersion);
1371 // search for a given byte in the stream, and remain positioned on it
1372 void FindByte(char ch) {
1374 if (nReadPos == nSrcPos)
1376 if (vchBuf[nReadPos % vchBuf.size()] == ch)