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 <boost/type_traits/is_fundamental.hpp>
18 #include <boost/tuple/tuple.hpp>
19 #include <boost/tuple/tuple_comparison.hpp>
20 #include <boost/tuple/tuple_io.hpp>
22 #include "allocators.h"
29 typedef long long int64;
30 typedef unsigned long long uint64;
35 static const unsigned int MAX_SIZE = 0x02000000;
37 // Used to bypass the rule against non-const reference to temporary
38 // where it makes sense with wrappers such as CFlatData or CTxDB
40 inline T& REF(const T& val)
42 return const_cast<T&>(val);
45 /////////////////////////////////////////////////////////////////
47 // Templates for serializing to anything that looks like a stream,
48 // i.e. anything that supports .read(char*, int) and .write(char*, int)
54 SER_NETWORK = (1 << 0),
56 SER_GETHASH = (1 << 2),
59 SER_SKIPSIG = (1 << 16),
60 SER_BLOCKHEADERONLY = (1 << 17),
65 #define IMPLEMENT_SERIALIZE(statements) \
66 unsigned int GetSerializeSize(int nType, int nVersion) const \
68 CSerActionGetSerializeSize ser_action; \
69 const bool fGetSize = true; \
70 const bool fWrite = false; \
71 const bool fRead = false; \
72 unsigned int nSerSize = 0; \
73 ser_streamplaceholder s; \
74 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
76 s.nVersion = nVersion; \
77 std::map<int, int> mapUnkIds; \
81 template<typename Stream> \
82 void Serialize(Stream& s, int nType, int nVersion) const \
84 CSerActionSerialize ser_action; \
85 const bool fGetSize = false; \
86 const bool fWrite = true; \
87 const bool fRead = false; \
88 unsigned int nSerSize = 0; \
89 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
90 std::map<int, int> mapUnkIds; \
93 template<typename Stream> \
94 void Unserialize(Stream& s, int nType, int nVersion) \
96 CSerActionUnserialize ser_action; \
97 const bool fGetSize = false; \
98 const bool fWrite = false; \
99 const bool fRead = true; \
100 unsigned int nSerSize = 0; \
101 std::map<int, int> mapUnkIds; \
102 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
108 #define IMPLEMENT_SERIALIZE(statements) \
109 unsigned int GetSerializeSize(int nType, int nVersion) const \
111 CSerActionGetSerializeSize ser_action; \
112 const bool fGetSize = true; \
113 const bool fWrite = false; \
114 const bool fRead = false; \
115 unsigned int nSerSize = 0; \
116 ser_streamplaceholder s; \
117 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
119 s.nVersion = nVersion; \
123 template<typename Stream> \
124 void Serialize(Stream& s, int nType, int nVersion) const \
126 CSerActionSerialize ser_action; \
127 const bool fGetSize = false; \
128 const bool fWrite = true; \
129 const bool fRead = false; \
130 unsigned int nSerSize = 0; \
131 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
134 template<typename Stream> \
135 void Unserialize(Stream& s, int nType, int nVersion) \
137 CSerActionUnserialize ser_action; \
138 const bool fGetSize = false; \
139 const bool fWrite = false; \
140 const bool fRead = true; \
141 unsigned int nSerSize = 0; \
142 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
148 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
158 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
159 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
161 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
162 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
163 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
164 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
165 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
166 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
167 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
168 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
169 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
170 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
171 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
172 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
173 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
175 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
176 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
177 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
178 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
179 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
180 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
181 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
182 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
183 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
184 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
185 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
186 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
187 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
189 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
190 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
191 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
192 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
193 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
194 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
195 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
196 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
197 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
198 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
199 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
200 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
201 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
203 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
204 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
205 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
214 // size < 253 -- 1 byte
215 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
216 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
217 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
219 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
221 if (nSize < 253) return sizeof(unsigned char);
222 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
223 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
224 else return sizeof(unsigned char) + sizeof(uint64);
227 template<typename Stream>
228 void WriteCompactSize(Stream& os, uint64 nSize)
232 unsigned char chSize = nSize;
233 WRITEDATA(os, chSize);
235 else if (nSize <= std::numeric_limits<unsigned short>::max())
237 unsigned char chSize = 253;
238 unsigned short xSize = nSize;
239 WRITEDATA(os, chSize);
240 WRITEDATA(os, xSize);
242 else if (nSize <= std::numeric_limits<unsigned int>::max())
244 unsigned char chSize = 254;
245 unsigned int xSize = nSize;
246 WRITEDATA(os, chSize);
247 WRITEDATA(os, xSize);
251 unsigned char chSize = 255;
252 uint64 xSize = nSize;
253 WRITEDATA(os, chSize);
254 WRITEDATA(os, xSize);
259 template<typename Stream>
260 uint64 ReadCompactSize(Stream& is)
262 unsigned char chSize;
263 READDATA(is, chSize);
269 else if (chSize == 253)
271 unsigned short xSize;
275 else if (chSize == 254)
287 if (nSizeRet > (uint64)MAX_SIZE)
288 throw std::ios_base::failure("ReadCompactSize() : size too large");
292 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
293 // The high bit in each byte signifies whether another digit follows. To make
294 // the encoding is one-to-one, one is subtracted from all but the last digit.
295 // Thus, the byte sequence a[] with length len, where all but the last byte
296 // has bit 128 set, encodes the number:
298 // (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
301 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
302 // * Every integer has exactly one encoding
303 // * Encoding does not depend on size of original integer type
304 // * No redundancy: every (infinite) byte sequence corresponds to a list
305 // of encoded integers.
307 // 0: [0x00] 256: [0x81 0x00]
308 // 1: [0x01] 16383: [0xFE 0x7F]
309 // 127: [0x7F] 16384: [0xFF 0x00]
310 // 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F]
311 // 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F]
312 // 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
315 inline unsigned int GetSizeOfVarInt(I n)
327 template<typename Stream, typename I>
328 void WriteVarInt(Stream& os, I n)
330 unsigned char tmp[(sizeof(n)*8+6)/7];
333 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
340 WRITEDATA(os, tmp[len]);
344 template<typename Stream, typename I>
345 I ReadVarInt(Stream& is)
349 unsigned char chData;
350 READDATA(is, chData);
351 n = (n << 7) | (chData & 0x7F);
359 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
360 #define VARINT(obj) REF(WrapVarInt(REF(obj)))
362 /** Wrapper for serializing arrays and POD.
370 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
371 char* begin() { return pbegin; }
372 const char* begin() const { return pbegin; }
373 char* end() { return pend; }
374 const char* end() const { return pend; }
376 unsigned int GetSerializeSize(int, int=0) const
378 return pend - pbegin;
381 template<typename Stream>
382 void Serialize(Stream& s, int, int=0) const
384 s.write(pbegin, pend - pbegin);
387 template<typename Stream>
388 void Unserialize(Stream& s, int, int=0)
390 s.read(pbegin, pend - pbegin);
400 CVarInt(I& nIn) : n(nIn) { }
402 unsigned int GetSerializeSize(int, int) const {
403 return GetSizeOfVarInt<I>(n);
406 template<typename Stream>
407 void Serialize(Stream &s, int, int) const {
408 WriteVarInt<Stream,I>(s, n);
411 template<typename Stream>
412 void Unserialize(Stream& s, int, int) {
413 n = ReadVarInt<Stream,I>(s);
418 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
421 // Forward declarations
425 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
426 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
427 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
430 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
431 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
432 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
433 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&);
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::false_type&);
435 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
436 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&);
437 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&);
438 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
440 // others derived from vector
441 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
442 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
443 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
446 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
447 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
448 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
451 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
452 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
453 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
456 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
457 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);
458 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);
461 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
462 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);
463 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);
466 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
467 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
468 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
475 // If none of the specialized versions above matched, default to calling member function.
476 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
477 // The compiler will only cast int to long if none of the other templates matched.
478 // Thanks to Boost serialization for this idea.
481 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
483 return a.GetSerializeSize((int)nType, nVersion);
486 template<typename Stream, typename T>
487 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
489 a.Serialize(os, (int)nType, nVersion);
492 template<typename Stream, typename T>
493 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
495 a.Unserialize(is, (int)nType, nVersion);
506 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
508 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
511 template<typename Stream, typename C>
512 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
514 WriteCompactSize(os, str.size());
516 os.write((char*)&str[0], str.size() * sizeof(str[0]));
519 template<typename Stream, typename C>
520 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
522 unsigned int nSize = ReadCompactSize(is);
525 is.read((char*)&str[0], nSize * sizeof(str[0]));
533 template<typename T, typename A>
534 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
536 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
539 template<typename T, typename A>
540 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
542 unsigned int nSize = GetSizeOfCompactSize(v.size());
543 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
544 nSize += GetSerializeSize((*vi), nType, nVersion);
548 template<typename T, typename A>
549 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
551 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
555 template<typename Stream, typename T, typename A>
556 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
558 WriteCompactSize(os, v.size());
560 os.write((char*)&v[0], v.size() * sizeof(T));
563 template<typename Stream, typename T, typename A>
564 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
566 WriteCompactSize(os, v.size());
567 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
568 ::Serialize(os, (*vi), nType, nVersion);
571 template<typename Stream, typename T, typename A>
572 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
574 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
578 template<typename Stream, typename T, typename A>
579 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
581 // Limit size per read so bogus size value won't cause out of memory
583 unsigned int nSize = ReadCompactSize(is);
587 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
589 is.read((char*)&v[i], blk * sizeof(T));
594 template<typename Stream, typename T, typename A>
595 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
598 unsigned int nSize = ReadCompactSize(is);
600 unsigned int nMid = 0;
603 nMid += 5000000 / sizeof(T);
607 for (; i < nMid; i++)
608 Unserialize(is, v[i], nType, nVersion);
612 template<typename Stream, typename T, typename A>
613 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
615 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
621 // others derived from vector
623 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
625 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
628 template<typename Stream>
629 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
631 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
634 template<typename Stream>
635 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
637 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
645 template<typename K, typename T>
646 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
648 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
651 template<typename Stream, typename K, typename T>
652 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
654 Serialize(os, item.first, nType, nVersion);
655 Serialize(os, item.second, nType, nVersion);
658 template<typename Stream, typename K, typename T>
659 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
661 Unserialize(is, item.first, nType, nVersion);
662 Unserialize(is, item.second, nType, nVersion);
670 template<typename T0, typename T1, typename T2>
671 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
673 unsigned int nSize = 0;
674 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
675 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
676 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
680 template<typename Stream, typename T0, typename T1, typename T2>
681 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
683 Serialize(os, boost::get<0>(item), nType, nVersion);
684 Serialize(os, boost::get<1>(item), nType, nVersion);
685 Serialize(os, boost::get<2>(item), nType, nVersion);
688 template<typename Stream, typename T0, typename T1, typename T2>
689 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
691 Unserialize(is, boost::get<0>(item), nType, nVersion);
692 Unserialize(is, boost::get<1>(item), nType, nVersion);
693 Unserialize(is, boost::get<2>(item), nType, nVersion);
701 template<typename T0, typename T1, typename T2, typename T3>
702 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
704 unsigned int nSize = 0;
705 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
706 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
707 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
708 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
712 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
713 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
715 Serialize(os, boost::get<0>(item), nType, nVersion);
716 Serialize(os, boost::get<1>(item), nType, nVersion);
717 Serialize(os, boost::get<2>(item), nType, nVersion);
718 Serialize(os, boost::get<3>(item), nType, nVersion);
721 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
722 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
724 Unserialize(is, boost::get<0>(item), nType, nVersion);
725 Unserialize(is, boost::get<1>(item), nType, nVersion);
726 Unserialize(is, boost::get<2>(item), nType, nVersion);
727 Unserialize(is, boost::get<3>(item), nType, nVersion);
735 template<typename K, typename T, typename Pred, typename A>
736 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
738 unsigned int nSize = GetSizeOfCompactSize(m.size());
739 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
740 nSize += GetSerializeSize((*mi), nType, nVersion);
744 template<typename Stream, typename K, typename T, typename Pred, typename A>
745 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
747 WriteCompactSize(os, m.size());
748 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
749 Serialize(os, (*mi), nType, nVersion);
752 template<typename Stream, typename K, typename T, typename Pred, typename A>
753 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
756 unsigned int nSize = ReadCompactSize(is);
757 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
758 for (unsigned int i = 0; i < nSize; i++)
760 std::pair<K, T> item;
761 Unserialize(is, item, nType, nVersion);
762 mi = m.insert(mi, item);
771 template<typename K, typename Pred, typename A>
772 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
774 unsigned int nSize = GetSizeOfCompactSize(m.size());
775 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
776 nSize += GetSerializeSize((*it), nType, nVersion);
780 template<typename Stream, typename K, typename Pred, typename A>
781 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
783 WriteCompactSize(os, m.size());
784 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
785 Serialize(os, (*it), nType, nVersion);
788 template<typename Stream, typename K, typename Pred, typename A>
789 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
792 unsigned int nSize = ReadCompactSize(is);
793 typename std::set<K, Pred, A>::iterator it = m.begin();
794 for (unsigned int i = 0; i < nSize; i++)
797 Unserialize(is, key, nType, nVersion);
798 it = m.insert(it, key);
805 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
807 class CSerActionGetSerializeSize { };
808 class CSerActionSerialize { };
809 class CSerActionUnserialize { };
811 template<typename Stream, typename T>
812 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
814 return ::GetSerializeSize(obj, nType, nVersion);
817 template<typename Stream, typename T>
818 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
820 ::Serialize(s, obj, nType, nVersion);
824 template<typename Stream, typename T>
825 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
827 ::Unserialize(s, obj, nType, nVersion);
831 struct ser_streamplaceholder
847 typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
849 /** Double ended buffer combining vector and stream-like interfaces.
851 * >> and << read and write unformatted data using the above serialization templates.
852 * Fills with data in linear time; some stringstream implementations take N^2 time.
857 typedef CSerializeData vector_type;
859 unsigned int nReadPos;
866 typedef vector_type::allocator_type allocator_type;
867 typedef vector_type::size_type size_type;
868 typedef vector_type::difference_type difference_type;
869 typedef vector_type::reference reference;
870 typedef vector_type::const_reference const_reference;
871 typedef vector_type::value_type value_type;
872 typedef vector_type::iterator iterator;
873 typedef vector_type::const_iterator const_iterator;
874 typedef vector_type::reverse_iterator reverse_iterator;
876 explicit CDataStream(int nTypeIn, int nVersionIn)
878 Init(nTypeIn, nVersionIn);
881 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
883 Init(nTypeIn, nVersionIn);
886 #if !defined(_MSC_VER) || _MSC_VER >= 1300
887 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
889 Init(nTypeIn, nVersionIn);
893 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
895 Init(nTypeIn, nVersionIn);
898 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
900 Init(nTypeIn, nVersionIn);
903 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
905 Init(nTypeIn, nVersionIn);
908 void Init(int nTypeIn, int nVersionIn)
912 nVersion = nVersionIn;
914 exceptmask = std::ios::badbit | std::ios::failbit;
917 CDataStream& operator+=(const CDataStream& b)
919 vch.insert(vch.end(), b.begin(), b.end());
923 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
930 std::string str() const
932 return (std::string(begin(), end()));
939 const_iterator begin() const { return vch.begin() + nReadPos; }
940 iterator begin() { return vch.begin() + nReadPos; }
941 const_iterator end() const { return vch.end(); }
942 iterator end() { return vch.end(); }
943 size_type size() const { return vch.size() - nReadPos; }
944 bool empty() const { return vch.size() == nReadPos; }
945 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
946 void reserve(size_type n) { vch.reserve(n + nReadPos); }
947 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
948 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
949 void clear() { vch.clear(); nReadPos = 0; }
950 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
951 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
954 void insert(iterator it, const_iterator first, const_iterator last)
956 assert(last - first >= 0);
957 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
959 // special case for inserting at the front when there's room
960 nReadPos -= (last - first);
961 memcpy(&vch[nReadPos], &first[0], last - first);
964 vch.insert(it, first, last);
969 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
971 assert(last - first >= 0);
972 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
974 // special case for inserting at the front when there's room
975 nReadPos -= (last - first);
976 memcpy(&vch[nReadPos], &first[0], last - first);
979 vch.insert(it, first, last);
983 #if !defined(_MSC_VER) || _MSC_VER >= 1300
984 void insert(iterator it, const char* first, const char* last)
986 assert(last - first >= 0);
987 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
989 // special case for inserting at the front when there's room
990 nReadPos -= (last - first);
991 memcpy(&vch[nReadPos], &first[0], last - first);
994 vch.insert(it, first, last);
998 iterator erase(iterator it)
1000 if (it == vch.begin() + nReadPos)
1002 // special case for erasing from the front
1003 if (++nReadPos >= vch.size())
1005 // whenever we reach the end, we take the opportunity to clear the buffer
1007 return vch.erase(vch.begin(), vch.end());
1009 return vch.begin() + nReadPos;
1012 return vch.erase(it);
1015 iterator erase(iterator first, iterator last)
1017 if (first == vch.begin() + nReadPos)
1019 // special case for erasing from the front
1020 if (last == vch.end())
1023 return vch.erase(vch.begin(), vch.end());
1027 nReadPos = (last - vch.begin());
1032 return vch.erase(first, last);
1035 inline void Compact()
1037 vch.erase(vch.begin(), vch.begin() + nReadPos);
1041 bool Rewind(size_type n)
1043 // Rewind by n characters if the buffer hasn't been compacted yet
1054 void setstate(short bits, const char* psz)
1057 if (state & exceptmask)
1058 throw std::ios_base::failure(psz);
1061 bool eof() const { return size() == 0; }
1062 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1063 bool good() const { return !eof() && (state == 0); }
1064 void clear(short n) { state = n; } // name conflict with vector clear()
1065 short exceptions() { return exceptmask; }
1066 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1067 CDataStream* rdbuf() { return this; }
1068 int in_avail() { return size(); }
1070 void SetType(int n) { nType = n; }
1071 int GetType() { return nType; }
1072 void SetVersion(int n) { nVersion = n; }
1073 int GetVersion() { return nVersion; }
1074 void ReadVersion() { *this >> nVersion; }
1075 void WriteVersion() { *this << nVersion; }
1077 CDataStream& read(char* pch, int nSize)
1079 // Read from the beginning of the buffer
1081 unsigned int nReadPosNext = nReadPos + nSize;
1082 if (nReadPosNext >= vch.size())
1084 if (nReadPosNext > vch.size())
1086 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1087 memset(pch, 0, nSize);
1088 nSize = vch.size() - nReadPos;
1090 memcpy(pch, &vch[nReadPos], nSize);
1095 memcpy(pch, &vch[nReadPos], nSize);
1096 nReadPos = nReadPosNext;
1100 CDataStream& ignore(int nSize)
1102 // Ignore from the beginning of the buffer
1104 unsigned int nReadPosNext = nReadPos + nSize;
1105 if (nReadPosNext >= vch.size())
1107 if (nReadPosNext > vch.size())
1109 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1110 nSize = vch.size() - nReadPos;
1116 nReadPos = nReadPosNext;
1120 CDataStream& write(const char* pch, int nSize)
1122 // Write to the end of the buffer
1124 vch.insert(vch.end(), pch, pch + nSize);
1128 template<typename Stream>
1129 void Serialize(Stream& s, int nType, int nVersion) const
1131 // Special case: stream << stream concatenates like stream += stream
1133 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1136 template<typename T>
1137 unsigned int GetSerializeSize(const T& obj)
1139 // Tells the size of the object if serialized to this stream
1140 return ::GetSerializeSize(obj, nType, nVersion);
1143 template<typename T>
1144 CDataStream& operator<<(const T& obj)
1146 // Serialize to this stream
1147 ::Serialize(*this, obj, nType, nVersion);
1151 template<typename T>
1152 CDataStream& operator>>(T& obj)
1154 // Unserialize from this stream
1155 ::Unserialize(*this, obj, nType, nVersion);
1159 void GetAndClear(CSerializeData &data) {
1161 CSerializeData().swap(vch);
1174 /** RAII wrapper for FILE*.
1176 * Will automatically close the file when it goes out of scope if not null.
1177 * If you're returning the file pointer, return file.release().
1178 * If you need to close the file early, use file.fclose() instead of fclose(file).
1190 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
1194 nVersion = nVersionIn;
1196 exceptmask = std::ios::badbit | std::ios::failbit;
1206 if (file != NULL && file != stdin && file != stdout && file != stderr)
1211 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1212 operator FILE*() { return file; }
1213 FILE* operator->() { return file; }
1214 FILE& operator*() { return *file; }
1215 FILE** operator&() { return &file; }
1216 FILE* operator=(FILE* pnew) { return file = pnew; }
1217 bool operator!() { return (file == NULL); }
1223 void setstate(short bits, const char* psz)
1226 if (state & exceptmask)
1227 throw std::ios_base::failure(psz);
1230 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1231 bool good() const { return state == 0; }
1232 void clear(short n = 0) { state = n; }
1233 short exceptions() { return exceptmask; }
1234 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1236 void SetType(int n) { nType = n; }
1237 int GetType() { return nType; }
1238 void SetVersion(int n) { nVersion = n; }
1239 int GetVersion() { return nVersion; }
1240 void ReadVersion() { *this >> nVersion; }
1241 void WriteVersion() { *this << nVersion; }
1243 CAutoFile& read(char* pch, size_t nSize)
1246 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1247 if (fread(pch, 1, nSize, file) != nSize)
1248 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1252 CAutoFile& write(const char* pch, size_t nSize)
1255 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1256 if (fwrite(pch, 1, nSize, file) != nSize)
1257 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1261 template<typename T>
1262 unsigned int GetSerializeSize(const T& obj)
1264 // Tells the size of the object if serialized to this stream
1265 return ::GetSerializeSize(obj, nType, nVersion);
1268 template<typename T>
1269 CAutoFile& operator<<(const T& obj)
1271 // Serialize to this stream
1273 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1274 ::Serialize(*this, obj, nType, nVersion);
1278 template<typename T>
1279 CAutoFile& operator>>(T& obj)
1281 // Unserialize from this stream
1283 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1284 ::Unserialize(*this, obj, nType, nVersion);
1289 /** Wrapper around a FILE* that implements a ring buffer to
1290 * deserialize from. It guarantees the ability to rewind
1291 * a given number of bytes. */
1295 FILE *src; // source file
1296 uint64 nSrcPos; // how many bytes have been read from source
1297 uint64 nReadPos; // how many bytes have been read from this
1298 uint64 nReadLimit; // up to which position we're allowed to read
1299 uint64 nRewind; // how many bytes we guarantee to rewind
1300 std::vector<char> vchBuf; // the buffer
1306 void setstate(short bits, const char *psz) {
1308 if (state & exceptmask)
1309 throw std::ios_base::failure(psz);
1312 // read data from the source to fill the buffer
1314 unsigned int pos = nSrcPos % vchBuf.size();
1315 unsigned int readNow = vchBuf.size() - pos;
1316 unsigned int nAvail = vchBuf.size() - (nSrcPos - nReadPos) - nRewind;
1317 if (nAvail < readNow)
1321 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
1323 setstate(std::ios_base::failbit, feof(src) ? "CBufferedFile::Fill : end of file" : "CBufferedFile::Fill : fread failed");
1335 CBufferedFile(FILE *fileIn, uint64 nBufSize, uint64 nRewindIn, int nTypeIn, int nVersionIn) :
1336 src(fileIn), nSrcPos(0), nReadPos(0), nReadLimit((uint64)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0),
1337 state(0), exceptmask(std::ios_base::badbit | std::ios_base::failbit), nType(nTypeIn), nVersion(nVersionIn) {
1340 // check whether no error occurred
1345 // check whether we're at the end of the source file
1347 return nReadPos == nSrcPos && feof(src);
1350 // read a number of bytes
1351 CBufferedFile& read(char *pch, size_t nSize) {
1352 if (nSize + nReadPos > nReadLimit)
1353 throw std::ios_base::failure("Read attempted past buffer limit");
1354 if (nSize + nRewind > vchBuf.size())
1355 throw std::ios_base::failure("Read larger than buffer size");
1357 if (nReadPos == nSrcPos)
1359 unsigned int pos = nReadPos % vchBuf.size();
1360 size_t nNow = nSize;
1361 if (nNow + pos > vchBuf.size())
1362 nNow = vchBuf.size() - pos;
1363 if (nNow + nReadPos > nSrcPos)
1364 nNow = nSrcPos - nReadPos;
1365 memcpy(pch, &vchBuf[pos], nNow);
1373 // return the current reading position
1378 // rewind to a given reading position
1379 bool SetPos(uint64 nPos) {
1381 if (nReadPos + nRewind < nSrcPos) {
1382 nReadPos = nSrcPos - nRewind;
1384 } else if (nReadPos > nSrcPos) {
1392 bool Seek(uint64 nPos) {
1393 long nLongPos = nPos;
1394 if (nPos != (uint64)nLongPos)
1396 if (fseek(src, nLongPos, SEEK_SET))
1398 nLongPos = ftell(src);
1400 nReadPos = nLongPos;
1405 // prevent reading beyond a certain position
1406 // no argument removes the limit
1407 bool SetLimit(uint64 nPos = (uint64)(-1)) {
1408 if (nPos < nReadPos)
1414 template<typename T>
1415 CBufferedFile& operator>>(T& obj) {
1416 // Unserialize from this stream
1417 ::Unserialize(*this, obj, nType, nVersion);
1421 // search for a given byte in the stream, and remain positioned on it
1422 void FindByte(char ch) {
1424 if (nReadPos == nSrcPos)
1426 if (vchBuf[nReadPos % vchBuf.size()] == ch)