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
13 #include <type_traits>
20 //#include <boost/type_traits/is_fundamental.hpp>
23 #if defined __USE_MINGW_ANSI_STDIO
24 #undef __USE_MINGW_ANSI_STDIO // This constant forces MinGW to conduct stupid behavior
28 #include "allocators.h"
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)
64 #define IMPLEMENT_SERIALIZE(statements) \
65 unsigned int GetSerializeSize(int nType, int nVersion) const \
67 CSerActionGetSerializeSize ser_action; \
68 const bool fGetSize = true; \
69 const bool fWrite = false; \
70 const bool fRead = false; \
71 unsigned int nSerSize = 0; \
72 ser_streamplaceholder s; \
73 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
75 s.nVersion = nVersion; \
79 template<typename Stream> \
80 void Serialize(Stream& s, int nType, int nVersion) const \
82 CSerActionSerialize ser_action; \
83 const bool fGetSize = false; \
84 const bool fWrite = true; \
85 const bool fRead = false; \
86 unsigned int nSerSize = 0; \
87 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
90 template<typename Stream> \
91 void Unserialize(Stream& s, int nType, int nVersion) \
93 CSerActionUnserialize ser_action; \
94 const bool fGetSize = false; \
95 const bool fWrite = false; \
96 const bool fRead = true; \
97 unsigned int nSerSize = 0; \
98 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
102 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
112 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
113 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
115 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
116 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
117 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
118 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
119 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
120 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
121 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
122 //inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
123 //inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
124 inline unsigned int GetSerializeSize(int64_t a, int, int=0) { return sizeof(a); }
125 inline unsigned int GetSerializeSize(uint64_t a, int, int=0) { return sizeof(a); }
126 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
127 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
129 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
130 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
131 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
132 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
133 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
134 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
135 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
136 //template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
137 //template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
138 template<typename Stream> inline void Serialize(Stream& s, int64_t a, int, int=0) { WRITEDATA(s, a); }
139 template<typename Stream> inline void Serialize(Stream& s, uint64_t a, int, int=0) { WRITEDATA(s, a); }
140 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
141 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
143 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
144 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
145 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
146 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
147 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
148 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
149 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
150 //template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
151 //template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
152 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a, int, int=0) { READDATA(s, a); }
153 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a, int, int=0) { READDATA(s, a); }
154 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
155 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
157 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
158 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
159 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
168 // size < 253 -- 1 byte
169 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
170 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
171 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
173 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
175 if (nSize < 253) return sizeof(unsigned char);
176 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
177 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
178 else return sizeof(unsigned char) + sizeof(uint64_t);
181 template<typename Stream>
182 void WriteCompactSize(Stream& os, uint64_t nSize)
186 unsigned char chSize = (unsigned char)nSize;
187 WRITEDATA(os, chSize);
189 else if (nSize <= std::numeric_limits<unsigned short>::max())
191 unsigned char chSize = 253;
192 unsigned short xSize = (unsigned short)nSize;
193 WRITEDATA(os, chSize);
194 WRITEDATA(os, xSize);
196 else if (nSize <= std::numeric_limits<unsigned int>::max())
198 unsigned char chSize = 254;
199 unsigned int xSize = (unsigned int)nSize;
200 WRITEDATA(os, chSize);
201 WRITEDATA(os, xSize);
205 unsigned char chSize = 255;
206 uint64_t xSize = nSize;
207 WRITEDATA(os, chSize);
208 WRITEDATA(os, xSize);
213 template<typename Stream>
214 uint64_t ReadCompactSize(Stream& is)
216 unsigned char chSize;
217 READDATA(is, chSize);
218 uint64_t nSizeRet = 0;
223 else if (chSize == 253)
225 unsigned short xSize;
229 else if (chSize == 254)
241 if (nSizeRet > (uint64_t)MAX_SIZE)
242 throw std::ios_base::failure("ReadCompactSize() : size too large");
246 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
247 // The high bit in each byte signifies whether another digit follows. To make
248 // the encoding is one-to-one, one is subtracted from all but the last digit.
249 // Thus, the byte sequence a[] with length len, where all but the last byte
250 // has bit 128 set, encodes the number:
252 // (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
255 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
256 // * Every integer has exactly one encoding
257 // * Encoding does not depend on size of original integer type
258 // * No redundancy: every (infinite) byte sequence corresponds to a list
259 // of encoded integers.
261 // 0: [0x00] 256: [0x81 0x00]
262 // 1: [0x01] 16383: [0xFE 0x7F]
263 // 127: [0x7F] 16384: [0xFF 0x00]
264 // 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F]
265 // 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F]
266 // 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
269 inline unsigned int GetSizeOfVarInt(I n)
281 template<typename Stream, typename I>
282 void WriteVarInt(Stream& os, I n)
284 unsigned char tmp[(sizeof(n)*8+6)/7];
287 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
294 WRITEDATA(os, tmp[len]);
298 template<typename Stream, typename I>
299 I ReadVarInt(Stream& is)
303 unsigned char chData;
304 READDATA(is, chData);
305 n = (n << 7) | (chData & 0x7F);
313 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
314 #define VARINT(obj) REF(WrapVarInt(REF(obj)))
316 /** Wrapper for serializing arrays and POD.
324 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
325 char* begin() { return pbegin; }
326 const char* begin() const { return pbegin; }
327 char* end() { return pend; }
328 const char* end() const { return pend; }
330 unsigned int GetSerializeSize(int, int=0) const
332 return (unsigned int)(pend - pbegin);
335 template<typename Stream>
336 void Serialize(Stream& s, int, int=0) const
338 s.write(pbegin, (int)(pend - pbegin));
341 template<typename Stream>
342 void Unserialize(Stream& s, int, int=0)
344 s.read(pbegin, pend - pbegin);
354 CVarInt(I& nIn) : n(nIn) { }
356 unsigned int GetSerializeSize(int, int) const {
357 return GetSizeOfVarInt<I>(n);
360 template<typename Stream>
361 void Serialize(Stream &s, int, int) const {
362 WriteVarInt<Stream,I>(s, n);
365 template<typename Stream>
366 void Unserialize(Stream& s, int, int) {
367 n = ReadVarInt<Stream,I>(s);
372 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
375 // Forward declarations
379 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
380 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
381 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
384 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
385 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
386 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
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::true_type&);
388 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&);
389 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
390 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&);
391 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&);
392 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
394 // others derived from vector
395 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
396 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
397 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
400 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
401 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
402 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
405 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
406 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
407 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion);
410 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(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 Serialize(Stream& os, const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
412 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);
415 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(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 Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion);
417 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);
420 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
421 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
422 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
429 // If none of the specialized versions above matched, default to calling member function.
430 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
431 // The compiler will only cast int to long if none of the other templates matched.
432 // Thanks to Boost serialization for this idea.
435 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
437 return a.GetSerializeSize((int)nType, nVersion);
440 template<typename Stream, typename T>
441 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
443 a.Serialize(os, (int)nType, nVersion);
446 template<typename Stream, typename T>
447 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
449 a.Unserialize(is, (int)nType, nVersion);
460 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
462 return (unsigned int)(GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]));
465 template<typename Stream, typename C>
466 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
468 WriteCompactSize(os, str.size());
470 os.write((char*)&str[0], (int)(str.size() * sizeof(str[0])));
473 template<typename Stream, typename C>
474 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
476 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
479 is.read((char*)&str[0], nSize * sizeof(str[0]));
487 template<typename T, typename A>
488 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
490 return (unsigned int)(GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
493 template<typename T, typename A>
494 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
496 unsigned int nSize = GetSizeOfCompactSize(v.size());
497 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
498 nSize += GetSerializeSize((*vi), nType, nVersion);
502 template<typename T, typename A>
503 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
505 return GetSerializeSize_impl(v, nType, nVersion, std::is_fundamental<T>());
509 template<typename Stream, typename T, typename A>
510 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
512 WriteCompactSize(os, v.size());
514 os.write((char*)&v[0], (int)(v.size() * sizeof(T)));
517 template<typename Stream, typename T, typename A>
518 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
520 WriteCompactSize(os, v.size());
521 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
522 ::Serialize(os, (*vi), nType, nVersion);
525 template<typename Stream, typename T, typename A>
526 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
528 Serialize_impl(os, v, nType, nVersion, std::is_fundamental<T>());
532 template<typename Stream, typename T, typename A>
533 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
535 // Limit size per read so bogus size value won't cause out of memory
537 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
541 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
543 is.read((char*)&v[i], blk * sizeof(T));
548 template<typename Stream, typename T, typename A>
549 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
552 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
554 unsigned int nMid = 0;
557 nMid += 5000000 / sizeof(T);
561 for (; i < nMid; i++)
562 Unserialize(is, v[i], nType, nVersion);
566 template<typename Stream, typename T, typename A>
567 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
569 Unserialize_impl(is, v, nType, nVersion, std::is_fundamental<T>());
575 // others derived from vector
577 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
579 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
582 template<typename Stream>
583 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
585 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
588 template<typename Stream>
589 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
591 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
599 template<typename K, typename T>
600 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
602 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
605 template<typename Stream, typename K, typename T>
606 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
608 Serialize(os, item.first, nType, nVersion);
609 Serialize(os, item.second, nType, nVersion);
612 template<typename Stream, typename K, typename T>
613 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
615 Unserialize(is, item.first, nType, nVersion);
616 Unserialize(is, item.second, nType, nVersion);
624 template<typename T0, typename T1, typename T2>
625 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
627 unsigned int nSize = 0;
628 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
629 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
630 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
634 template<typename Stream, typename T0, typename T1, typename T2>
635 void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
637 Serialize(os, std::get<0>(item), nType, nVersion);
638 Serialize(os, std::get<1>(item), nType, nVersion);
639 Serialize(os, std::get<2>(item), nType, nVersion);
642 template<typename Stream, typename T0, typename T1, typename T2>
643 void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion)
645 Unserialize(is, std::get<0>(item), nType, nVersion);
646 Unserialize(is, std::get<1>(item), nType, nVersion);
647 Unserialize(is, std::get<2>(item), nType, nVersion);
655 template<typename T0, typename T1, typename T2, typename T3>
656 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
658 unsigned int nSize = 0;
659 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
660 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
661 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
662 nSize += GetSerializeSize(std::get<3>(item), nType, nVersion);
666 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
667 void Serialize(Stream& os, const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
669 Serialize(os, std::get<0>(item), nType, nVersion);
670 Serialize(os, std::get<1>(item), nType, nVersion);
671 Serialize(os, std::get<2>(item), nType, nVersion);
672 Serialize(os, std::get<3>(item), nType, nVersion);
675 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
676 void Unserialize(Stream& is, std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
678 Unserialize(is, std::get<0>(item), nType, nVersion);
679 Unserialize(is, std::get<1>(item), nType, nVersion);
680 Unserialize(is, std::get<2>(item), nType, nVersion);
681 Unserialize(is, std::get<3>(item), nType, nVersion);
689 template<typename K, typename T, typename Pred, typename A>
690 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
692 unsigned int nSize = GetSizeOfCompactSize(m.size());
693 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
694 nSize += GetSerializeSize((*mi), nType, nVersion);
698 template<typename Stream, typename K, typename T, typename Pred, typename A>
699 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
701 WriteCompactSize(os, m.size());
702 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
703 Serialize(os, (*mi), nType, nVersion);
706 template<typename Stream, typename K, typename T, typename Pred, typename A>
707 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
710 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
711 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
712 for (unsigned int i = 0; i < nSize; i++)
714 std::pair<K, T> item;
715 Unserialize(is, item, nType, nVersion);
716 mi = m.insert(mi, item);
725 template<typename K, typename Pred, typename A>
726 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
728 unsigned int nSize = GetSizeOfCompactSize(m.size());
729 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
730 nSize += GetSerializeSize((*it), nType, nVersion);
734 template<typename Stream, typename K, typename Pred, typename A>
735 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
737 WriteCompactSize(os, m.size());
738 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
739 Serialize(os, (*it), nType, nVersion);
742 template<typename Stream, typename K, typename Pred, typename A>
743 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
746 unsigned int nSize = ReadCompactSize(is);
747 typename std::set<K, Pred, A>::iterator it = m.begin();
748 for (unsigned int i = 0; i < nSize; i++)
751 Unserialize(is, key, nType, nVersion);
752 it = m.insert(it, key);
759 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
761 class CSerActionGetSerializeSize { };
762 class CSerActionSerialize { };
763 class CSerActionUnserialize { };
765 template<typename Stream, typename T>
766 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
768 return ::GetSerializeSize(obj, nType, nVersion);
771 template<typename Stream, typename T>
772 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
774 ::Serialize(s, obj, nType, nVersion);
778 template<typename Stream, typename T>
779 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
781 ::Unserialize(s, obj, nType, nVersion);
785 struct ser_streamplaceholder
801 typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
803 /** Double ended buffer combining vector and stream-like interfaces.
805 * >> and << read and write unformatted data using the above serialization templates.
806 * Fills with data in linear time; some stringstream implementations take N^2 time.
811 typedef CSerializeData vector_type;
813 unsigned int nReadPos;
820 typedef vector_type::allocator_type allocator_type;
821 typedef vector_type::size_type size_type;
822 typedef vector_type::difference_type difference_type;
823 typedef vector_type::reference reference;
824 typedef vector_type::const_reference const_reference;
825 typedef vector_type::value_type value_type;
826 typedef vector_type::iterator iterator;
827 typedef vector_type::const_iterator const_iterator;
828 typedef vector_type::reverse_iterator reverse_iterator;
830 explicit CDataStream(int nTypeIn, int nVersionIn)
832 Init(nTypeIn, nVersionIn);
835 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
837 Init(nTypeIn, nVersionIn);
840 #if !defined(_MSC_VER) || _MSC_VER >= 1300
841 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
843 Init(nTypeIn, nVersionIn);
847 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
849 Init(nTypeIn, nVersionIn);
852 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
854 Init(nTypeIn, nVersionIn);
857 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
859 Init(nTypeIn, nVersionIn);
862 void Init(int nTypeIn, int nVersionIn)
866 nVersion = nVersionIn;
868 exceptmask = std::ios::badbit | std::ios::failbit;
871 CDataStream& operator+=(const CDataStream& b)
873 vch.insert(vch.end(), b.begin(), b.end());
877 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
884 std::string str() const
886 return (std::string(begin(), end()));
893 const_iterator begin() const { return vch.begin() + nReadPos; }
894 iterator begin() { return vch.begin() + nReadPos; }
895 const_iterator end() const { return vch.end(); }
896 iterator end() { return vch.end(); }
897 size_type size() const { return vch.size() - nReadPos; }
898 bool empty() const { return vch.size() == nReadPos; }
899 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
900 void reserve(size_type n) { vch.reserve(n + nReadPos); }
901 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
902 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
903 void clear() { vch.clear(); nReadPos = 0; }
904 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
905 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
908 void insert(iterator it, const_iterator first, const_iterator last)
910 assert(last - first >= 0);
911 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
913 // special case for inserting at the front when there's room
914 nReadPos -= (unsigned int)(last - first);
915 memcpy(&vch[nReadPos], &first[0], last - first);
918 vch.insert(it, first, last);
923 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
925 assert(last - first >= 0);
926 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
928 // special case for inserting at the front when there's room
929 nReadPos -= (last - first);
930 memcpy(&vch[nReadPos], &first[0], last - first);
933 vch.insert(it, first, last);
937 #if !defined(_MSC_VER) || _MSC_VER >= 1300
938 void insert(iterator it, const char* first, const char* last)
940 assert(last - first >= 0);
941 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
943 // special case for inserting at the front when there's room
944 nReadPos -= (unsigned int)(last - first);
945 memcpy(&vch[nReadPos], &first[0], last - first);
948 vch.insert(it, first, last);
952 iterator erase(iterator it)
954 if (it == vch.begin() + nReadPos)
956 // special case for erasing from the front
957 if (++nReadPos >= vch.size())
959 // whenever we reach the end, we take the opportunity to clear the buffer
961 return vch.erase(vch.begin(), vch.end());
963 return vch.begin() + nReadPos;
966 return vch.erase(it);
969 iterator erase(iterator first, iterator last)
971 if (first == vch.begin() + nReadPos)
973 // special case for erasing from the front
974 if (last == vch.end())
977 return vch.erase(vch.begin(), vch.end());
981 nReadPos = (unsigned int)(last - vch.begin());
986 return vch.erase(first, last);
989 inline void Compact()
991 vch.erase(vch.begin(), vch.begin() + nReadPos);
995 bool Rewind(size_type n)
997 // Rewind by n characters if the buffer hasn't been compacted yet
1000 nReadPos -= (unsigned int)n;
1008 void setstate(short bits, const char* psz)
1011 if (state & exceptmask)
1012 throw std::ios_base::failure(psz);
1015 bool eof() const { return size() == 0; }
1016 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1017 bool good() const { return !eof() && (state == 0); }
1018 void clear(short n) { state = n; } // name conflict with vector clear()
1019 short exceptions() { return exceptmask; }
1020 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1021 CDataStream* rdbuf() { return this; }
1022 int in_avail() { return (int)(size()); }
1024 void SetType(int n) { nType = n; }
1025 int GetType() { return nType; }
1026 void SetVersion(int n) { nVersion = n; }
1027 int GetVersion() { return nVersion; }
1028 void ReadVersion() { *this >> nVersion; }
1029 void WriteVersion() { *this << nVersion; }
1031 CDataStream& read(char* pch, int nSize)
1033 // Read from the beginning of the buffer
1035 unsigned int nReadPosNext = nReadPos + nSize;
1036 if (nReadPosNext >= vch.size())
1038 if (nReadPosNext > vch.size())
1040 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1041 memset(pch, 0, nSize);
1042 nSize = (int)(vch.size() - nReadPos);
1044 memcpy(pch, &vch[nReadPos], nSize);
1049 memcpy(pch, &vch[nReadPos], nSize);
1050 nReadPos = nReadPosNext;
1054 CDataStream& ignore(int nSize)
1056 // Ignore from the beginning of the buffer
1058 unsigned int nReadPosNext = nReadPos + nSize;
1059 if (nReadPosNext >= vch.size())
1061 if (nReadPosNext > vch.size())
1062 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1067 nReadPos = nReadPosNext;
1071 CDataStream& write(const char* pch, int nSize)
1073 // Write to the end of the buffer
1075 vch.insert(vch.end(), pch, pch + nSize);
1079 template<typename Stream>
1080 void Serialize(Stream& s, int nType, int nVersion) const
1082 // Special case: stream << stream concatenates like stream += stream
1084 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1087 template<typename T>
1088 unsigned int GetSerializeSize(const T& obj)
1090 // Tells the size of the object if serialized to this stream
1091 return ::GetSerializeSize(obj, nType, nVersion);
1094 template<typename T>
1095 CDataStream& operator<<(const T& obj)
1097 // Serialize to this stream
1098 ::Serialize(*this, obj, nType, nVersion);
1102 template<typename T>
1103 CDataStream& operator>>(T& obj)
1105 // Unserialize from this stream
1106 ::Unserialize(*this, obj, nType, nVersion);
1110 void GetAndClear(CSerializeData &data) {
1112 CSerializeData().swap(vch);
1125 /** RAII wrapper for FILE*.
1127 * Will automatically close the file when it goes out of scope if not null.
1128 * If you're returning the file pointer, return file.release().
1129 * If you need to close the file early, use file.fclose() instead of fclose(file).
1141 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
1145 nVersion = nVersionIn;
1147 exceptmask = std::ios::badbit | std::ios::failbit;
1157 if (file != NULL && file != stdin && file != stdout && file != stderr)
1162 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1163 operator FILE*() { return file; }
1164 FILE* operator->() { return file; }
1165 FILE& operator*() { return *file; }
1166 FILE** operator&() { return &file; }
1167 FILE* operator=(FILE* pnew) { return file = pnew; }
1168 bool operator!() { return (file == NULL); }
1174 void setstate(short bits, const char* psz)
1177 if (state & exceptmask)
1178 throw std::ios_base::failure(psz);
1181 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1182 bool good() const { return state == 0; }
1183 void clear(short n = 0) { state = n; }
1184 short exceptions() { return exceptmask; }
1185 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1187 void SetType(int n) { nType = n; }
1188 int GetType() { return nType; }
1189 void SetVersion(int n) { nVersion = n; }
1190 int GetVersion() { return nVersion; }
1191 void ReadVersion() { *this >> nVersion; }
1192 void WriteVersion() { *this << nVersion; }
1194 CAutoFile& read(char* pch, size_t nSize)
1197 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1198 if (fread(pch, 1, nSize, file) != nSize)
1199 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1203 CAutoFile& write(const char* pch, size_t nSize)
1206 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1207 if (fwrite(pch, 1, nSize, file) != nSize)
1208 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1212 template<typename T>
1213 unsigned int GetSerializeSize(const T& obj)
1215 // Tells the size of the object if serialized to this stream
1216 return ::GetSerializeSize(obj, nType, nVersion);
1219 template<typename T>
1220 CAutoFile& operator<<(const T& obj)
1222 // Serialize to this stream
1224 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1225 ::Serialize(*this, obj, nType, nVersion);
1229 template<typename T>
1230 CAutoFile& operator>>(T& obj)
1232 // Unserialize from this stream
1234 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1235 ::Unserialize(*this, obj, nType, nVersion);
1240 /** Wrapper around a FILE* that implements a ring buffer to
1241 * deserialize from. It guarantees the ability to rewind
1242 * a given number of bytes. */
1246 FILE *src; // source file
1247 uint64_t nSrcPos; // how many bytes have been read from source
1248 uint64_t nReadPos; // how many bytes have been read from this
1249 uint64_t nReadLimit; // up to which position we're allowed to read
1250 uint64_t nRewind; // how many bytes we guarantee to rewind
1251 std::vector<char> vchBuf; // the buffer
1257 void setstate(short bits, const char *psz) {
1259 if (state & exceptmask)
1260 throw std::ios_base::failure(psz);
1263 // read data from the source to fill the buffer
1265 unsigned int pos = (unsigned int)(nSrcPos % vchBuf.size());
1266 unsigned int readNow = (unsigned int)(vchBuf.size() - pos);
1267 unsigned int nAvail = (unsigned int)(vchBuf.size() - (nSrcPos - nReadPos) - nRewind);
1268 if (nAvail < readNow)
1272 size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
1274 setstate(std::ios_base::failbit, feof(src) ? "CBufferedFile::Fill : end of file" : "CBufferedFile::Fill : fread failed");
1286 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
1287 src(fileIn), nSrcPos(0), nReadPos(0), nReadLimit(std::numeric_limits<uint64_t>::max()), nRewind(nRewindIn), vchBuf(nBufSize, 0),
1288 state(0), exceptmask(std::ios_base::badbit | std::ios_base::failbit), nType(nTypeIn), nVersion(nVersionIn) {
1291 // check whether no error occurred
1296 // check whether we're at the end of the source file
1298 return nReadPos == nSrcPos && feof(src);
1301 // read a number of bytes
1302 CBufferedFile& read(char *pch, size_t nSize) {
1303 if (nSize + nReadPos > nReadLimit)
1304 throw std::ios_base::failure("Read attempted past buffer limit");
1305 if (nSize + nRewind > vchBuf.size())
1306 throw std::ios_base::failure("Read larger than buffer size");
1308 if (nReadPos == nSrcPos)
1310 unsigned int pos = (unsigned int)(nReadPos % vchBuf.size());
1311 size_t nNow = nSize;
1312 if (nNow + pos > vchBuf.size())
1313 nNow = vchBuf.size() - pos;
1314 if (nNow + nReadPos > nSrcPos)
1315 nNow = (size_t)(nSrcPos - nReadPos);
1316 memcpy(pch, &vchBuf[pos], nNow);
1324 // return the current reading position
1329 // rewind to a given reading position
1330 bool SetPos(uint64_t nPos) {
1332 if (nReadPos + nRewind < nSrcPos) {
1333 nReadPos = nSrcPos - nRewind;
1335 } else if (nReadPos > nSrcPos) {
1343 bool Seek(uint64_t nPos) {
1344 long nLongPos = (long)nPos;
1345 if (nPos != (uint64_t)nLongPos)
1347 if (fseek(src, nLongPos, SEEK_SET))
1349 nLongPos = ftell(src);
1351 nReadPos = nLongPos;
1356 // prevent reading beyond a certain position
1357 // no argument removes the limit
1358 bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max()) {
1359 if (nPos < nReadPos)
1365 template<typename T>
1366 CBufferedFile& operator>>(T& obj) {
1367 // Unserialize from this stream
1368 ::Unserialize(*this, obj, nType, nVersion);
1372 // search for a given byte in the stream, and remain positioned on it
1373 void FindByte(char ch) {
1375 if (nReadPos == nSrcPos)
1377 if (vchBuf[nReadPos % vchBuf.size()] == ch)