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
18 #include <boost/type_traits/is_fundamental.hpp>
19 #include <boost/tuple/tuple.hpp>
20 #include <boost/tuple/tuple_comparison.hpp>
21 #include <boost/tuple/tuple_io.hpp>
24 #if defined __USE_MINGW_ANSI_STDIO
25 #undef __USE_MINGW_ANSI_STDIO // This constant forces MinGW to conduct stupid behavior
29 #include "allocators.h"
36 static const unsigned int MAX_SIZE = 0x02000000;
38 // Used to bypass the rule against non-const reference to temporary
39 // where it makes sense with wrappers such as CFlatData or CTxDB
41 inline T& REF(const T& val)
43 return const_cast<T&>(val);
46 /////////////////////////////////////////////////////////////////
48 // Templates for serializing to anything that looks like a stream,
49 // i.e. anything that supports .read(char*, int) and .write(char*, int)
55 SER_NETWORK = (1 << 0),
57 SER_GETHASH = (1 << 2),
60 SER_SKIPSIG = (1 << 16),
61 SER_BLOCKHEADERONLY = (1 << 17),
66 #define IMPLEMENT_SERIALIZE(statements) \
67 unsigned int GetSerializeSize(int nType, int nVersion) const \
69 CSerActionGetSerializeSize ser_action; \
70 const bool fGetSize = true; \
71 const bool fWrite = false; \
72 const bool fRead = false; \
73 unsigned int nSerSize = 0; \
74 ser_streamplaceholder s; \
75 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
77 s.nVersion = nVersion; \
78 std::map<int, int> mapUnkIds; \
82 template<typename Stream> \
83 void Serialize(Stream& s, int nType, int nVersion) const \
85 CSerActionSerialize ser_action; \
86 const bool fGetSize = false; \
87 const bool fWrite = true; \
88 const bool fRead = false; \
89 unsigned int nSerSize = 0; \
90 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
91 std::map<int, int> mapUnkIds; \
94 template<typename Stream> \
95 void Unserialize(Stream& s, int nType, int nVersion) \
97 CSerActionUnserialize ser_action; \
98 const bool fGetSize = false; \
99 const bool fWrite = false; \
100 const bool fRead = true; \
101 unsigned int nSerSize = 0; \
102 std::map<int, int> mapUnkIds; \
103 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
109 #define IMPLEMENT_SERIALIZE(statements) \
110 unsigned int GetSerializeSize(int nType, int nVersion) const \
112 CSerActionGetSerializeSize ser_action; \
113 const bool fGetSize = true; \
114 const bool fWrite = false; \
115 const bool fRead = false; \
116 unsigned int nSerSize = 0; \
117 ser_streamplaceholder s; \
118 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
120 s.nVersion = nVersion; \
124 template<typename Stream> \
125 void Serialize(Stream& s, int nType, int nVersion) const \
127 CSerActionSerialize ser_action; \
128 const bool fGetSize = false; \
129 const bool fWrite = true; \
130 const bool fRead = false; \
131 unsigned int nSerSize = 0; \
132 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
135 template<typename Stream> \
136 void Unserialize(Stream& s, int nType, int nVersion) \
138 CSerActionUnserialize ser_action; \
139 const bool fGetSize = false; \
140 const bool fWrite = false; \
141 const bool fRead = true; \
142 unsigned int nSerSize = 0; \
143 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
149 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
159 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
160 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
162 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
163 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
164 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
165 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
166 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
167 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
168 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
169 //inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
170 //inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
171 inline unsigned int GetSerializeSize(int64_t a, int, int=0) { return sizeof(a); }
172 inline unsigned int GetSerializeSize(uint64_t a, int, int=0) { return sizeof(a); }
173 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
174 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
176 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
177 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
178 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
179 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
180 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
181 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
182 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
183 //template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
184 //template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
185 template<typename Stream> inline void Serialize(Stream& s, int64_t a, int, int=0) { WRITEDATA(s, a); }
186 template<typename Stream> inline void Serialize(Stream& s, uint64_t a, int, int=0) { WRITEDATA(s, a); }
187 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
188 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
190 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
191 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
192 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
193 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
194 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
195 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
196 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
197 //template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
198 //template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
199 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a, int, int=0) { READDATA(s, a); }
200 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a, int, int=0) { READDATA(s, a); }
201 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
202 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
204 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
205 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
206 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
215 // size < 253 -- 1 byte
216 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
217 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
218 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
220 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
222 if (nSize < 253) return sizeof(unsigned char);
223 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
224 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
225 else return sizeof(unsigned char) + sizeof(uint64_t);
228 template<typename Stream>
229 void WriteCompactSize(Stream& os, uint64_t nSize)
233 unsigned char chSize = nSize;
234 WRITEDATA(os, chSize);
236 else if (nSize <= std::numeric_limits<unsigned short>::max())
238 unsigned char chSize = 253;
239 unsigned short xSize = nSize;
240 WRITEDATA(os, chSize);
241 WRITEDATA(os, xSize);
243 else if (nSize <= std::numeric_limits<unsigned int>::max())
245 unsigned char chSize = 254;
246 unsigned int xSize = nSize;
247 WRITEDATA(os, chSize);
248 WRITEDATA(os, xSize);
252 unsigned char chSize = 255;
253 uint64_t xSize = nSize;
254 WRITEDATA(os, chSize);
255 WRITEDATA(os, xSize);
260 template<typename Stream>
261 uint64_t ReadCompactSize(Stream& is)
263 unsigned char chSize;
264 READDATA(is, chSize);
265 uint64_t nSizeRet = 0;
270 else if (chSize == 253)
272 unsigned short xSize;
276 else if (chSize == 254)
288 if (nSizeRet > (uint64_t)MAX_SIZE)
289 throw std::ios_base::failure("ReadCompactSize() : size too large");
293 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
294 // The high bit in each byte signifies whether another digit follows. To make
295 // the encoding is one-to-one, one is subtracted from all but the last digit.
296 // Thus, the byte sequence a[] with length len, where all but the last byte
297 // has bit 128 set, encodes the number:
299 // (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
302 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
303 // * Every integer has exactly one encoding
304 // * Encoding does not depend on size of original integer type
305 // * No redundancy: every (infinite) byte sequence corresponds to a list
306 // of encoded integers.
308 // 0: [0x00] 256: [0x81 0x00]
309 // 1: [0x01] 16383: [0xFE 0x7F]
310 // 127: [0x7F] 16384: [0xFF 0x00]
311 // 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F]
312 // 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F]
313 // 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
316 inline unsigned int GetSizeOfVarInt(I n)
328 template<typename Stream, typename I>
329 void WriteVarInt(Stream& os, I n)
331 unsigned char tmp[(sizeof(n)*8+6)/7];
334 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
341 WRITEDATA(os, tmp[len]);
345 template<typename Stream, typename I>
346 I ReadVarInt(Stream& is)
350 unsigned char chData;
351 READDATA(is, chData);
352 n = (n << 7) | (chData & 0x7F);
360 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
361 #define VARINT(obj) REF(WrapVarInt(REF(obj)))
363 /** Wrapper for serializing arrays and POD.
371 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
372 char* begin() { return pbegin; }
373 const char* begin() const { return pbegin; }
374 char* end() { return pend; }
375 const char* end() const { return pend; }
377 unsigned int GetSerializeSize(int, int=0) const
379 return pend - pbegin;
382 template<typename Stream>
383 void Serialize(Stream& s, int, int=0) const
385 s.write(pbegin, pend - pbegin);
388 template<typename Stream>
389 void Unserialize(Stream& s, int, int=0)
391 s.read(pbegin, pend - pbegin);
401 CVarInt(I& nIn) : n(nIn) { }
403 unsigned int GetSerializeSize(int, int) const {
404 return GetSizeOfVarInt<I>(n);
407 template<typename Stream>
408 void Serialize(Stream &s, int, int) const {
409 WriteVarInt<Stream,I>(s, n);
412 template<typename Stream>
413 void Unserialize(Stream& s, int, int) {
414 n = ReadVarInt<Stream,I>(s);
419 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
422 // Forward declarations
426 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
427 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
428 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
431 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
432 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
433 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
434 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
435 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
436 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
437 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
438 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
439 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
441 // others derived from vector
442 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
443 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
444 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
447 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
448 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
449 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
452 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
453 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
454 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
457 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
458 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
459 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
462 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
463 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);
464 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);
467 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
468 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
469 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
476 // If none of the specialized versions above matched, default to calling member function.
477 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
478 // The compiler will only cast int to long if none of the other templates matched.
479 // Thanks to Boost serialization for this idea.
482 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
484 return a.GetSerializeSize((int)nType, nVersion);
487 template<typename Stream, typename T>
488 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
490 a.Serialize(os, (int)nType, nVersion);
493 template<typename Stream, typename T>
494 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
496 a.Unserialize(is, (int)nType, nVersion);
507 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
509 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
512 template<typename Stream, typename C>
513 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
515 WriteCompactSize(os, str.size());
517 os.write((char*)&str[0], str.size() * sizeof(str[0]));
520 template<typename Stream, typename C>
521 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
523 unsigned int nSize = ReadCompactSize(is);
526 is.read((char*)&str[0], nSize * sizeof(str[0]));
534 template<typename T, typename A>
535 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
537 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
540 template<typename T, typename A>
541 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
543 unsigned int nSize = GetSizeOfCompactSize(v.size());
544 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
545 nSize += GetSerializeSize((*vi), nType, nVersion);
549 template<typename T, typename A>
550 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
552 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
556 template<typename Stream, typename T, typename A>
557 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
559 WriteCompactSize(os, v.size());
561 os.write((char*)&v[0], v.size() * sizeof(T));
564 template<typename Stream, typename T, typename A>
565 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
567 WriteCompactSize(os, v.size());
568 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
569 ::Serialize(os, (*vi), nType, nVersion);
572 template<typename Stream, typename T, typename A>
573 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
575 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
579 template<typename Stream, typename T, typename A>
580 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
582 // Limit size per read so bogus size value won't cause out of memory
584 unsigned int nSize = ReadCompactSize(is);
588 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
590 is.read((char*)&v[i], blk * sizeof(T));
595 template<typename Stream, typename T, typename A>
596 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
599 unsigned int nSize = ReadCompactSize(is);
601 unsigned int nMid = 0;
604 nMid += 5000000 / sizeof(T);
608 for (; i < nMid; i++)
609 Unserialize(is, v[i], nType, nVersion);
613 template<typename Stream, typename T, typename A>
614 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
616 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
622 // others derived from vector
624 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
626 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
629 template<typename Stream>
630 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
632 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
635 template<typename Stream>
636 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
638 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
646 template<typename K, typename T>
647 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
649 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
652 template<typename Stream, typename K, typename T>
653 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
655 Serialize(os, item.first, nType, nVersion);
656 Serialize(os, item.second, nType, nVersion);
659 template<typename Stream, typename K, typename T>
660 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
662 Unserialize(is, item.first, nType, nVersion);
663 Unserialize(is, item.second, nType, nVersion);
671 template<typename T0, typename T1, typename T2>
672 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
674 unsigned int nSize = 0;
675 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
676 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
677 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
681 template<typename Stream, typename T0, typename T1, typename T2>
682 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
684 Serialize(os, boost::get<0>(item), nType, nVersion);
685 Serialize(os, boost::get<1>(item), nType, nVersion);
686 Serialize(os, boost::get<2>(item), nType, nVersion);
689 template<typename Stream, typename T0, typename T1, typename T2>
690 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
692 Unserialize(is, boost::get<0>(item), nType, nVersion);
693 Unserialize(is, boost::get<1>(item), nType, nVersion);
694 Unserialize(is, boost::get<2>(item), nType, nVersion);
702 template<typename T0, typename T1, typename T2, typename T3>
703 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
705 unsigned int nSize = 0;
706 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
707 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
708 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
709 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
713 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
714 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
716 Serialize(os, boost::get<0>(item), nType, nVersion);
717 Serialize(os, boost::get<1>(item), nType, nVersion);
718 Serialize(os, boost::get<2>(item), nType, nVersion);
719 Serialize(os, boost::get<3>(item), nType, nVersion);
722 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
723 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
725 Unserialize(is, boost::get<0>(item), nType, nVersion);
726 Unserialize(is, boost::get<1>(item), nType, nVersion);
727 Unserialize(is, boost::get<2>(item), nType, nVersion);
728 Unserialize(is, boost::get<3>(item), nType, nVersion);
736 template<typename K, typename T, typename Pred, typename A>
737 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
739 unsigned int nSize = GetSizeOfCompactSize(m.size());
740 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
741 nSize += GetSerializeSize((*mi), nType, nVersion);
745 template<typename Stream, typename K, typename T, typename Pred, typename A>
746 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
748 WriteCompactSize(os, m.size());
749 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
750 Serialize(os, (*mi), nType, nVersion);
753 template<typename Stream, typename K, typename T, typename Pred, typename A>
754 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
757 unsigned int nSize = ReadCompactSize(is);
758 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
759 for (unsigned int i = 0; i < nSize; i++)
761 std::pair<K, T> item;
762 Unserialize(is, item, nType, nVersion);
763 mi = m.insert(mi, item);
772 template<typename K, typename Pred, typename A>
773 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
775 unsigned int nSize = GetSizeOfCompactSize(m.size());
776 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
777 nSize += GetSerializeSize((*it), nType, nVersion);
781 template<typename Stream, typename K, typename Pred, typename A>
782 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
784 WriteCompactSize(os, m.size());
785 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
786 Serialize(os, (*it), nType, nVersion);
789 template<typename Stream, typename K, typename Pred, typename A>
790 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
793 unsigned int nSize = ReadCompactSize(is);
794 typename std::set<K, Pred, A>::iterator it = m.begin();
795 for (unsigned int i = 0; i < nSize; i++)
798 Unserialize(is, key, nType, nVersion);
799 it = m.insert(it, key);
806 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
808 class CSerActionGetSerializeSize { };
809 class CSerActionSerialize { };
810 class CSerActionUnserialize { };
812 template<typename Stream, typename T>
813 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
815 return ::GetSerializeSize(obj, nType, nVersion);
818 template<typename Stream, typename T>
819 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
821 ::Serialize(s, obj, nType, nVersion);
825 template<typename Stream, typename T>
826 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
828 ::Unserialize(s, obj, nType, nVersion);
832 struct ser_streamplaceholder
848 typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
850 /** Double ended buffer combining vector and stream-like interfaces.
852 * >> and << read and write unformatted data using the above serialization templates.
853 * Fills with data in linear time; some stringstream implementations take N^2 time.
858 typedef CSerializeData vector_type;
860 unsigned int nReadPos;
867 typedef vector_type::allocator_type allocator_type;
868 typedef vector_type::size_type size_type;
869 typedef vector_type::difference_type difference_type;
870 typedef vector_type::reference reference;
871 typedef vector_type::const_reference const_reference;
872 typedef vector_type::value_type value_type;
873 typedef vector_type::iterator iterator;
874 typedef vector_type::const_iterator const_iterator;
875 typedef vector_type::reverse_iterator reverse_iterator;
877 explicit CDataStream(int nTypeIn, int nVersionIn)
879 Init(nTypeIn, nVersionIn);
882 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
884 Init(nTypeIn, nVersionIn);
887 #if !defined(_MSC_VER) || _MSC_VER >= 1300
888 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
890 Init(nTypeIn, nVersionIn);
894 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
896 Init(nTypeIn, nVersionIn);
899 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
901 Init(nTypeIn, nVersionIn);
904 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
906 Init(nTypeIn, nVersionIn);
909 void Init(int nTypeIn, int nVersionIn)
913 nVersion = nVersionIn;
915 exceptmask = std::ios::badbit | std::ios::failbit;
918 CDataStream& operator+=(const CDataStream& b)
920 vch.insert(vch.end(), b.begin(), b.end());
924 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
931 std::string str() const
933 return (std::string(begin(), end()));
940 const_iterator begin() const { return vch.begin() + nReadPos; }
941 iterator begin() { return vch.begin() + nReadPos; }
942 const_iterator end() const { return vch.end(); }
943 iterator end() { return vch.end(); }
944 size_type size() const { return vch.size() - nReadPos; }
945 bool empty() const { return vch.size() == nReadPos; }
946 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
947 void reserve(size_type n) { vch.reserve(n + nReadPos); }
948 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
949 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
950 void clear() { vch.clear(); nReadPos = 0; }
951 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
952 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
955 void insert(iterator it, const_iterator first, const_iterator last)
957 assert(last - first >= 0);
958 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
960 // special case for inserting at the front when there's room
961 nReadPos -= (last - first);
962 memcpy(&vch[nReadPos], &first[0], last - first);
965 vch.insert(it, first, last);
970 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
972 assert(last - first >= 0);
973 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
975 // special case for inserting at the front when there's room
976 nReadPos -= (last - first);
977 memcpy(&vch[nReadPos], &first[0], last - first);
980 vch.insert(it, first, last);
984 #if !defined(_MSC_VER) || _MSC_VER >= 1300
985 void insert(iterator it, const char* first, const char* last)
987 assert(last - first >= 0);
988 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
990 // special case for inserting at the front when there's room
991 nReadPos -= (last - first);
992 memcpy(&vch[nReadPos], &first[0], last - first);
995 vch.insert(it, first, last);
999 iterator erase(iterator it)
1001 if (it == vch.begin() + nReadPos)
1003 // special case for erasing from the front
1004 if (++nReadPos >= vch.size())
1006 // whenever we reach the end, we take the opportunity to clear the buffer
1008 return vch.erase(vch.begin(), vch.end());
1010 return vch.begin() + nReadPos;
1013 return vch.erase(it);
1016 iterator erase(iterator first, iterator last)
1018 if (first == vch.begin() + nReadPos)
1020 // special case for erasing from the front
1021 if (last == vch.end())
1024 return vch.erase(vch.begin(), vch.end());
1028 nReadPos = (last - vch.begin());
1033 return vch.erase(first, last);
1036 inline void Compact()
1038 vch.erase(vch.begin(), vch.begin() + nReadPos);
1042 bool Rewind(size_type n)
1044 // Rewind by n characters if the buffer hasn't been compacted yet
1055 void setstate(short bits, const char* psz)
1058 if (state & exceptmask)
1059 throw std::ios_base::failure(psz);
1062 bool eof() const { return size() == 0; }
1063 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1064 bool good() const { return !eof() && (state == 0); }
1065 void clear(short n) { state = n; } // name conflict with vector clear()
1066 short exceptions() { return exceptmask; }
1067 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1068 CDataStream* rdbuf() { return this; }
1069 int in_avail() { return size(); }
1071 void SetType(int n) { nType = n; }
1072 int GetType() { return nType; }
1073 void SetVersion(int n) { nVersion = n; }
1074 int GetVersion() { return nVersion; }
1075 void ReadVersion() { *this >> nVersion; }
1076 void WriteVersion() { *this << nVersion; }
1078 CDataStream& read(char* pch, int nSize)
1080 // Read from the beginning of the buffer
1082 unsigned int nReadPosNext = nReadPos + nSize;
1083 if (nReadPosNext >= vch.size())
1085 if (nReadPosNext > vch.size())
1087 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1088 memset(pch, 0, nSize);
1089 nSize = vch.size() - nReadPos;
1091 memcpy(pch, &vch[nReadPos], nSize);
1096 memcpy(pch, &vch[nReadPos], nSize);
1097 nReadPos = nReadPosNext;
1101 CDataStream& ignore(int nSize)
1103 // Ignore from the beginning of the buffer
1105 unsigned int nReadPosNext = nReadPos + nSize;
1106 if (nReadPosNext >= vch.size())
1108 if (nReadPosNext > vch.size())
1110 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1111 nSize = vch.size() - nReadPos;
1117 nReadPos = nReadPosNext;
1121 CDataStream& write(const char* pch, int nSize)
1123 // Write to the end of the buffer
1125 vch.insert(vch.end(), pch, pch + nSize);
1129 template<typename Stream>
1130 void Serialize(Stream& s, int nType, int nVersion) const
1132 // Special case: stream << stream concatenates like stream += stream
1134 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1137 template<typename T>
1138 unsigned int GetSerializeSize(const T& obj)
1140 // Tells the size of the object if serialized to this stream
1141 return ::GetSerializeSize(obj, nType, nVersion);
1144 template<typename T>
1145 CDataStream& operator<<(const T& obj)
1147 // Serialize to this stream
1148 ::Serialize(*this, obj, nType, nVersion);
1152 template<typename T>
1153 CDataStream& operator>>(T& obj)
1155 // Unserialize from this stream
1156 ::Unserialize(*this, obj, nType, nVersion);
1160 void GetAndClear(CSerializeData &data) {
1162 CSerializeData().swap(vch);
1175 /** RAII wrapper for FILE*.
1177 * Will automatically close the file when it goes out of scope if not null.
1178 * If you're returning the file pointer, return file.release().
1179 * If you need to close the file early, use file.fclose() instead of fclose(file).
1191 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
1195 nVersion = nVersionIn;
1197 exceptmask = std::ios::badbit | std::ios::failbit;
1207 if (file != NULL && file != stdin && file != stdout && file != stderr)
1212 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1213 operator FILE*() { return file; }
1214 FILE* operator->() { return file; }
1215 FILE& operator*() { return *file; }
1216 FILE** operator&() { return &file; }
1217 FILE* operator=(FILE* pnew) { return file = pnew; }
1218 bool operator!() { return (file == NULL); }
1224 void setstate(short bits, const char* psz)
1227 if (state & exceptmask)
1228 throw std::ios_base::failure(psz);
1231 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1232 bool good() const { return state == 0; }
1233 void clear(short n = 0) { state = n; }
1234 short exceptions() { return exceptmask; }
1235 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1237 void SetType(int n) { nType = n; }
1238 int GetType() { return nType; }
1239 void SetVersion(int n) { nVersion = n; }
1240 int GetVersion() { return nVersion; }
1241 void ReadVersion() { *this >> nVersion; }
1242 void WriteVersion() { *this << nVersion; }
1244 CAutoFile& read(char* pch, size_t nSize)
1247 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1248 if (fread(pch, 1, nSize, file) != nSize)
1249 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1253 CAutoFile& write(const char* pch, size_t nSize)
1256 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1257 if (fwrite(pch, 1, nSize, file) != nSize)
1258 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1262 template<typename T>
1263 unsigned int GetSerializeSize(const T& obj)
1265 // Tells the size of the object if serialized to this stream
1266 return ::GetSerializeSize(obj, nType, nVersion);
1269 template<typename T>
1270 CAutoFile& operator<<(const T& obj)
1272 // Serialize to this stream
1274 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1275 ::Serialize(*this, obj, nType, nVersion);
1279 template<typename T>
1280 CAutoFile& operator>>(T& obj)
1282 // Unserialize from this stream
1284 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1285 ::Unserialize(*this, obj, nType, nVersion);
1290 /** Wrapper around a FILE* that implements a ring buffer to
1291 * deserialize from. It guarantees the ability to rewind
1292 * a given number of bytes. */
1296 FILE *src; // source file
1297 uint64_t nSrcPos; // how many bytes have been read from source
1298 uint64_t nReadPos; // how many bytes have been read from this
1299 uint64_t nReadLimit; // up to which position we're allowed to read
1300 uint64_t nRewind; // how many bytes we guarantee to rewind
1301 std::vector<char> vchBuf; // the buffer
1307 void setstate(short bits, const char *psz) {
1309 if (state & exceptmask)
1310 throw std::ios_base::failure(psz);
1313 // read data from the source to fill the buffer
1315 unsigned int pos = nSrcPos % vchBuf.size();
1316 unsigned int readNow = vchBuf.size() - pos;
1317 unsigned int nAvail = vchBuf.size() - (nSrcPos - nReadPos) - nRewind;
1318 if (nAvail < readNow)
1322 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
1324 setstate(std::ios_base::failbit, feof(src) ? "CBufferedFile::Fill : end of file" : "CBufferedFile::Fill : fread failed");
1336 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
1337 src(fileIn), nSrcPos(0), nReadPos(0), nReadLimit((uint64_t)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0),
1338 state(0), exceptmask(std::ios_base::badbit | std::ios_base::failbit), nType(nTypeIn), nVersion(nVersionIn) {
1341 // check whether no error occurred
1346 // check whether we're at the end of the source file
1348 return nReadPos == nSrcPos && feof(src);
1351 // read a number of bytes
1352 CBufferedFile& read(char *pch, size_t nSize) {
1353 if (nSize + nReadPos > nReadLimit)
1354 throw std::ios_base::failure("Read attempted past buffer limit");
1355 if (nSize + nRewind > vchBuf.size())
1356 throw std::ios_base::failure("Read larger than buffer size");
1358 if (nReadPos == nSrcPos)
1360 unsigned int pos = nReadPos % vchBuf.size();
1361 size_t nNow = nSize;
1362 if (nNow + pos > vchBuf.size())
1363 nNow = vchBuf.size() - pos;
1364 if (nNow + nReadPos > nSrcPos)
1365 nNow = nSrcPos - nReadPos;
1366 memcpy(pch, &vchBuf[pos], nNow);
1374 // return the current reading position
1379 // rewind to a given reading position
1380 bool SetPos(uint64_t nPos) {
1382 if (nReadPos + nRewind < nSrcPos) {
1383 nReadPos = nSrcPos - nRewind;
1385 } else if (nReadPos > nSrcPos) {
1393 bool Seek(uint64_t nPos) {
1394 long nLongPos = nPos;
1395 if (nPos != (uint64_t)nLongPos)
1397 if (fseek(src, nLongPos, SEEK_SET))
1399 nLongPos = ftell(src);
1401 nReadPos = nLongPos;
1406 // prevent reading beyond a certain position
1407 // no argument removes the limit
1408 bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
1409 if (nPos < nReadPos)
1415 template<typename T>
1416 CBufferedFile& operator>>(T& obj) {
1417 // Unserialize from this stream
1418 ::Unserialize(*this, obj, nType, nVersion);
1422 // search for a given byte in the stream, and remain positioned on it
1423 void FindByte(char ch) {
1425 if (nReadPos == nSrcPos)
1427 if (vchBuf[nReadPos % vchBuf.size()] == ch)