1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_SERIALIZE_H
6 #define BITCOIN_SERIALIZE_H
17 #include <type_traits>
22 #if defined __USE_MINGW_ANSI_STDIO
23 #undef __USE_MINGW_ANSI_STDIO // This constant forces MinGW to conduct stupid behavior
27 #include "allocators.h"
34 static const unsigned int MAX_SIZE = 0x02000000;
36 // Used to bypass the rule against non-const reference to temporary
37 // where it makes sense with wrappers such as CFlatData or CTxDB
39 inline T& REF(const T& val)
41 return const_cast<T&>(val);
44 /////////////////////////////////////////////////////////////////
46 // Templates for serializing to anything that looks like a stream,
47 // i.e. anything that supports .read(char*, int) and .write(char*, int)
53 SER_NETWORK = (1 << 0),
55 SER_GETHASH = (1 << 2),
58 SER_SKIPSIG = (1 << 16),
59 SER_BLOCKHEADERONLY = (1 << 17)
63 #define IMPLEMENT_SERIALIZE(statements) \
64 unsigned int GetSerializeSize(int nType, int nVersion) const \
66 CSerActionGetSerializeSize ser_action; \
67 const bool fGetSize = true; \
68 const bool fWrite = false; \
69 const bool fRead = false; \
70 unsigned int nSerSize = 0; \
71 ser_streamplaceholder s; \
72 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
74 s.nVersion = nVersion; \
78 template<typename Stream> \
79 void Serialize(Stream& s, int nType, int nVersion) const \
81 CSerActionSerialize ser_action; \
82 const bool fGetSize = false; \
83 const bool fWrite = true; \
84 const bool fRead = false; \
85 unsigned int nSerSize = 0; \
86 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
89 template<typename Stream> \
90 void Unserialize(Stream& s, int nType, int nVersion) \
92 CSerActionUnserialize ser_action; \
93 const bool fGetSize = false; \
94 const bool fWrite = false; \
95 const bool fRead = true; \
96 unsigned int nSerSize = 0; \
97 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
101 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
111 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
112 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
114 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
115 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
116 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
117 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
118 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
119 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
120 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
121 //inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
122 //inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
123 inline unsigned int GetSerializeSize(int64_t a, int, int=0) { return sizeof(a); }
124 inline unsigned int GetSerializeSize(uint64_t a, int, int=0) { return sizeof(a); }
125 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
126 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
128 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
129 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
130 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
131 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
132 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
133 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
134 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
135 //template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
136 //template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
137 template<typename Stream> inline void Serialize(Stream& s, int64_t a, int, int=0) { WRITEDATA(s, a); }
138 template<typename Stream> inline void Serialize(Stream& s, uint64_t a, int, int=0) { WRITEDATA(s, a); }
139 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
140 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
142 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
143 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
144 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
145 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
146 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
147 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
148 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
149 //template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
150 //template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
151 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a, int, int=0) { READDATA(s, a); }
152 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a, int, int=0) { READDATA(s, a); }
153 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
154 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
156 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
157 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
158 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
167 // size < 253 -- 1 byte
168 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
169 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
170 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
172 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
174 if (nSize < 253) return sizeof(unsigned char);
175 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
176 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
177 else return sizeof(unsigned char) + sizeof(uint64_t);
180 template<typename Stream>
181 void WriteCompactSize(Stream& os, uint64_t nSize);
183 template<typename Stream>
184 uint64_t ReadCompactSize(Stream& is);
186 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
187 // The high bit in each byte signifies whether another digit follows. To make
188 // the encoding is one-to-one, one is subtracted from all but the last digit.
189 // Thus, the byte sequence a[] with length len, where all but the last byte
190 // has bit 128 set, encodes the number:
192 // (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
195 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
196 // * Every integer has exactly one encoding
197 // * Encoding does not depend on size of original integer type
198 // * No redundancy: every (infinite) byte sequence corresponds to a list
199 // of encoded integers.
201 // 0: [0x00] 256: [0x81 0x00]
202 // 1: [0x01] 16383: [0xFE 0x7F]
203 // 127: [0x7F] 16384: [0xFF 0x00]
204 // 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F]
205 // 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F]
206 // 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
209 inline unsigned int GetSizeOfVarInt(I n)
221 template<typename Stream, typename I>
222 void WriteVarInt(Stream& os, I n)
224 unsigned char tmp[(sizeof(n)*8+6)/7];
227 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
234 WRITEDATA(os, tmp[len]);
238 template<typename Stream, typename I>
239 I ReadVarInt(Stream& is)
243 unsigned char chData;
244 READDATA(is, chData);
245 n = (n << 7) | (chData & 0x7F);
253 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
254 #define VARINT(obj) REF(WrapVarInt(REF(obj)))
256 /** Wrapper for serializing arrays and POD.
264 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
265 char* begin() { return pbegin; }
266 const char* begin() const { return pbegin; }
267 char* end() { return pend; }
268 const char* end() const { return pend; }
270 unsigned int GetSerializeSize(int, int=0) const
272 return (unsigned int)(pend - pbegin);
275 template<typename Stream>
276 void Serialize(Stream& s, int, int=0) const
278 s.write(pbegin, (int)(pend - pbegin));
281 template<typename Stream>
282 void Unserialize(Stream& s, int, int=0)
284 s.read(pbegin, pend - pbegin);
294 CVarInt(I& nIn) : n(nIn) { }
296 unsigned int GetSerializeSize(int, int) const {
297 return GetSizeOfVarInt<I>(n);
300 template<typename Stream>
301 void Serialize(Stream &s, int, int) const {
302 WriteVarInt<Stream,I>(s, n);
305 template<typename Stream>
306 void Unserialize(Stream& s, int, int) {
307 n = ReadVarInt<Stream,I>(s);
312 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
315 // Forward declarations
319 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
320 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
321 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
324 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
325 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
326 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
327 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&);
328 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&);
329 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
330 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&);
331 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&);
332 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
334 // others derived from vector
335 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
336 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
337 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
340 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
341 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
342 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
345 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
346 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
347 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion);
350 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
351 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);
352 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);
355 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
356 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);
357 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);
360 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
361 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
362 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
369 // If none of the specialized versions above matched, default to calling member function.
370 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
371 // The compiler will only cast int to long if none of the other templates matched.
372 // Thanks to Boost serialization for this idea.
375 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
377 return a.GetSerializeSize((int)nType, nVersion);
380 template<typename Stream, typename T>
381 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
383 a.Serialize(os, (int)nType, nVersion);
386 template<typename Stream, typename T>
387 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
389 a.Unserialize(is, (int)nType, nVersion);
400 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
402 return (unsigned int)(GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]));
405 template<typename Stream, typename C>
406 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
408 WriteCompactSize(os, str.size());
410 os.write((char*)&str[0], (int)(str.size() * sizeof(str[0])));
413 template<typename Stream, typename C>
414 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
416 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
419 is.read((char*)&str[0], nSize * sizeof(str[0]));
427 template<typename T, typename A>
428 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
430 return (unsigned int)(GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
433 template<typename T, typename A>
434 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
436 unsigned int nSize = GetSizeOfCompactSize(v.size());
437 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
438 nSize += GetSerializeSize((*vi), nType, nVersion);
442 template<typename T, typename A>
443 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
445 return GetSerializeSize_impl(v, nType, nVersion, std::is_fundamental<T>());
449 template<typename Stream, typename T, typename A>
450 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
452 WriteCompactSize(os, v.size());
454 os.write((char*)&v[0], (int)(v.size() * sizeof(T)));
457 template<typename Stream, typename T, typename A>
458 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
460 WriteCompactSize(os, v.size());
461 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
462 ::Serialize(os, (*vi), nType, nVersion);
465 template<typename Stream, typename T, typename A>
466 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
468 Serialize_impl(os, v, nType, nVersion, std::is_fundamental<T>());
472 template<typename Stream, typename T, typename A>
473 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
475 // Limit size per read so bogus size value won't cause out of memory
477 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
481 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
483 is.read((char*)&v[i], blk * sizeof(T));
488 template<typename Stream, typename T, typename A>
489 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
492 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
494 unsigned int nMid = 0;
497 nMid += 5000000 / sizeof(T);
501 for (; i < nMid; i++)
502 Unserialize(is, v[i], nType, nVersion);
506 template<typename Stream, typename T, typename A>
507 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
509 Unserialize_impl(is, v, nType, nVersion, std::is_fundamental<T>());
515 // others derived from vector
517 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
519 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
522 template<typename Stream>
523 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
525 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
528 template<typename Stream>
529 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
531 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
539 template<typename K, typename T>
540 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
542 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
545 template<typename Stream, typename K, typename T>
546 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
548 Serialize(os, item.first, nType, nVersion);
549 Serialize(os, item.second, nType, nVersion);
552 template<typename Stream, typename K, typename T>
553 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
555 Unserialize(is, item.first, nType, nVersion);
556 Unserialize(is, item.second, nType, nVersion);
564 template<typename T0, typename T1, typename T2>
565 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
567 unsigned int nSize = 0;
568 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
569 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
570 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
574 template<typename Stream, typename T0, typename T1, typename T2>
575 void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
577 Serialize(os, std::get<0>(item), nType, nVersion);
578 Serialize(os, std::get<1>(item), nType, nVersion);
579 Serialize(os, std::get<2>(item), nType, nVersion);
582 template<typename Stream, typename T0, typename T1, typename T2>
583 void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion)
585 Unserialize(is, std::get<0>(item), nType, nVersion);
586 Unserialize(is, std::get<1>(item), nType, nVersion);
587 Unserialize(is, std::get<2>(item), nType, nVersion);
595 template<typename T0, typename T1, typename T2, typename T3>
596 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
598 unsigned int nSize = 0;
599 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
600 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
601 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
602 nSize += GetSerializeSize(std::get<3>(item), nType, nVersion);
606 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
607 void Serialize(Stream& os, const std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
609 Serialize(os, std::get<0>(item), nType, nVersion);
610 Serialize(os, std::get<1>(item), nType, nVersion);
611 Serialize(os, std::get<2>(item), nType, nVersion);
612 Serialize(os, std::get<3>(item), nType, nVersion);
615 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
616 void Unserialize(Stream& is, std::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
618 Unserialize(is, std::get<0>(item), nType, nVersion);
619 Unserialize(is, std::get<1>(item), nType, nVersion);
620 Unserialize(is, std::get<2>(item), nType, nVersion);
621 Unserialize(is, std::get<3>(item), nType, nVersion);
629 template<typename K, typename T, typename Pred, typename A>
630 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
632 unsigned int nSize = GetSizeOfCompactSize(m.size());
633 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
634 nSize += GetSerializeSize((*mi), nType, nVersion);
638 template<typename Stream, typename K, typename T, typename Pred, typename A>
639 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
641 WriteCompactSize(os, m.size());
642 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
643 Serialize(os, (*mi), nType, nVersion);
646 template<typename Stream, typename K, typename T, typename Pred, typename A>
647 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
650 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
651 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
652 for (unsigned int i = 0; i < nSize; i++)
654 std::pair<K, T> item;
655 Unserialize(is, item, nType, nVersion);
656 mi = m.insert(mi, item);
665 template<typename K, typename Pred, typename A>
666 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
668 unsigned int nSize = GetSizeOfCompactSize(m.size());
669 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
670 nSize += GetSerializeSize((*it), nType, nVersion);
674 template<typename Stream, typename K, typename Pred, typename A>
675 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
677 WriteCompactSize(os, m.size());
678 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
679 Serialize(os, (*it), nType, nVersion);
682 template<typename Stream, typename K, typename Pred, typename A>
683 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
686 unsigned int nSize = ReadCompactSize(is);
687 typename std::set<K, Pred, A>::iterator it = m.begin();
688 for (unsigned int i = 0; i < nSize; i++)
691 Unserialize(is, key, nType, nVersion);
692 it = m.insert(it, key);
699 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
701 class CSerActionGetSerializeSize { };
702 class CSerActionSerialize { };
703 class CSerActionUnserialize { };
705 template<typename Stream, typename T>
706 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
708 return ::GetSerializeSize(obj, nType, nVersion);
711 template<typename Stream, typename T>
712 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
714 ::Serialize(s, obj, nType, nVersion);
718 template<typename Stream, typename T>
719 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
721 ::Unserialize(s, obj, nType, nVersion);
725 struct ser_streamplaceholder
741 typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
743 /** Double ended buffer combining vector and stream-like interfaces.
745 * >> and << read and write unformatted data using the above serialization templates.
746 * Fills with data in linear time; some stringstream implementations take N^2 time.
751 typedef CSerializeData vector_type;
753 unsigned int nReadPos;
760 typedef vector_type::allocator_type allocator_type;
761 typedef vector_type::size_type size_type;
762 typedef vector_type::difference_type difference_type;
763 typedef vector_type::reference reference;
764 typedef vector_type::const_reference const_reference;
765 typedef vector_type::value_type value_type;
766 typedef vector_type::iterator iterator;
767 typedef vector_type::const_iterator const_iterator;
768 typedef vector_type::reverse_iterator reverse_iterator;
770 explicit CDataStream(int nTypeIn, int nVersionIn)
772 Init(nTypeIn, nVersionIn);
775 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
777 Init(nTypeIn, nVersionIn);
780 #if !defined(_MSC_VER) || _MSC_VER >= 1300
781 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
783 Init(nTypeIn, nVersionIn);
787 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
789 Init(nTypeIn, nVersionIn);
792 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
794 Init(nTypeIn, nVersionIn);
797 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
799 Init(nTypeIn, nVersionIn);
802 void Init(int nTypeIn, int nVersionIn)
806 nVersion = nVersionIn;
808 exceptmask = std::ios::badbit | std::ios::failbit;
811 CDataStream& operator+=(const CDataStream& b)
813 vch.insert(vch.end(), b.begin(), b.end());
817 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
824 std::string str() const
826 return (std::string(begin(), end()));
833 const_iterator begin() const { return vch.begin() + nReadPos; }
834 iterator begin() { return vch.begin() + nReadPos; }
835 const_iterator end() const { return vch.end(); }
836 iterator end() { return vch.end(); }
837 size_type size() const { return vch.size() - nReadPos; }
838 bool empty() const { return vch.size() == nReadPos; }
839 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
840 void reserve(size_type n) { vch.reserve(n + nReadPos); }
841 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
842 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
843 void clear() { vch.clear(); nReadPos = 0; }
844 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
845 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
848 void insert(iterator it, const_iterator first, const_iterator last)
850 assert(last - first >= 0);
851 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
853 // special case for inserting at the front when there's room
854 nReadPos -= (unsigned int)(last - first);
855 memcpy(&vch[nReadPos], &first[0], last - first);
858 vch.insert(it, first, last);
863 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
865 assert(last - first >= 0);
866 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
868 // special case for inserting at the front when there's room
869 nReadPos -= (last - first);
870 memcpy(&vch[nReadPos], &first[0], last - first);
873 vch.insert(it, first, last);
877 #if !defined(_MSC_VER) || _MSC_VER >= 1300
878 void insert(iterator it, const char* first, const char* last)
880 assert(last - first >= 0);
881 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
883 // special case for inserting at the front when there's room
884 nReadPos -= (unsigned int)(last - first);
885 memcpy(&vch[nReadPos], &first[0], last - first);
888 vch.insert(it, first, last);
892 iterator erase(iterator it)
894 if (it == vch.begin() + nReadPos)
896 // special case for erasing from the front
897 if (++nReadPos >= vch.size())
899 // whenever we reach the end, we take the opportunity to clear the buffer
901 return vch.erase(vch.begin(), vch.end());
903 return vch.begin() + nReadPos;
906 return vch.erase(it);
909 iterator erase(iterator first, iterator last)
911 if (first == vch.begin() + nReadPos)
913 // special case for erasing from the front
914 if (last == vch.end())
917 return vch.erase(vch.begin(), vch.end());
921 nReadPos = (unsigned int)(last - vch.begin());
926 return vch.erase(first, last);
929 inline void Compact()
931 vch.erase(vch.begin(), vch.begin() + nReadPos);
935 bool Rewind(size_type n)
937 // Rewind by n characters if the buffer hasn't been compacted yet
940 nReadPos -= (unsigned int)n;
948 void setstate(short bits, const char* psz)
951 if (state & exceptmask)
952 throw std::ios_base::failure(psz);
955 bool eof() const { return size() == 0; }
956 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
957 bool good() const { return !eof() && (state == 0); }
958 void clear(short n) { state = n; } // name conflict with vector clear()
959 short exceptions() { return exceptmask; }
960 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
961 CDataStream* rdbuf() { return this; }
962 int in_avail() { return (int)(size()); }
964 void SetType(int n) { nType = n; }
965 int GetType() { return nType; }
966 void SetVersion(int n) { nVersion = n; }
967 int GetVersion() { return nVersion; }
968 void ReadVersion() { *this >> nVersion; }
969 void WriteVersion() { *this << nVersion; }
971 CDataStream& read(char* pch, int nSize)
973 // Read from the beginning of the buffer
975 unsigned int nReadPosNext = nReadPos + nSize;
976 if (nReadPosNext >= vch.size())
978 if (nReadPosNext > vch.size())
980 setstate(std::ios::failbit, "CDataStream::read() : end of data");
981 memset(pch, 0, nSize);
982 nSize = (int)(vch.size() - nReadPos);
984 memcpy(pch, &vch[nReadPos], nSize);
989 memcpy(pch, &vch[nReadPos], nSize);
990 nReadPos = nReadPosNext;
994 CDataStream& ignore(int nSize)
996 // Ignore from the beginning of the buffer
998 unsigned int nReadPosNext = nReadPos + nSize;
999 if (nReadPosNext >= vch.size())
1001 if (nReadPosNext > vch.size())
1002 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1007 nReadPos = nReadPosNext;
1011 CDataStream& write(const char* pch, int nSize)
1013 // Write to the end of the buffer
1015 vch.insert(vch.end(), pch, pch + nSize);
1019 template<typename Stream>
1020 void Serialize(Stream& s, int nType, int nVersion) const
1022 // Special case: stream << stream concatenates like stream += stream
1024 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1027 template<typename T>
1028 unsigned int GetSerializeSize(const T& obj)
1030 // Tells the size of the object if serialized to this stream
1031 return ::GetSerializeSize(obj, nType, nVersion);
1034 template<typename T>
1035 CDataStream& operator<<(const T& obj)
1037 // Serialize to this stream
1038 ::Serialize(*this, obj, nType, nVersion);
1042 template<typename T>
1043 CDataStream& operator>>(T& obj)
1045 // Unserialize from this stream
1046 ::Unserialize(*this, obj, nType, nVersion);
1050 void GetAndClear(CSerializeData &data) {
1052 CSerializeData().swap(vch);
1065 /** RAII wrapper for FILE*.
1067 * Will automatically close the file when it goes out of scope if not null.
1068 * If you're returning the file pointer, return file.release().
1069 * If you need to close the file early, use file.fclose() instead of fclose(file).
1081 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
1085 nVersion = nVersionIn;
1087 exceptmask = std::ios::badbit | std::ios::failbit;
1097 if (file != NULL && file != stdin && file != stdout && file != stderr)
1102 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1103 operator FILE*() { return file; }
1104 FILE* operator->() { return file; }
1105 FILE& operator*() { return *file; }
1106 FILE** operator&() { return &file; }
1107 FILE* operator=(FILE* pnew) { return file = pnew; }
1108 bool operator!() { return (file == NULL); }
1114 void setstate(short bits, const char* psz)
1117 if (state & exceptmask)
1118 throw std::ios_base::failure(psz);
1121 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
1122 bool good() const { return state == 0; }
1123 void clear(short n = 0) { state = n; }
1124 short exceptions() { return exceptmask; }
1125 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1127 void SetType(int n) { nType = n; }
1128 int GetType() { return nType; }
1129 void SetVersion(int n) { nVersion = n; }
1130 int GetVersion() { return nVersion; }
1131 void ReadVersion() { *this >> nVersion; }
1132 void WriteVersion() { *this << nVersion; }
1134 CAutoFile& read(char* pch, size_t nSize)
1137 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1138 if (fread(pch, 1, nSize, file) != nSize)
1139 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1143 CAutoFile& write(const char* pch, size_t nSize)
1146 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1147 if (fwrite(pch, 1, nSize, file) != nSize)
1148 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1152 template<typename T>
1153 unsigned int GetSerializeSize(const T& obj)
1155 // Tells the size of the object if serialized to this stream
1156 return ::GetSerializeSize(obj, nType, nVersion);
1159 template<typename T>
1160 CAutoFile& operator<<(const T& obj)
1162 // Serialize to this stream
1164 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1165 ::Serialize(*this, obj, nType, nVersion);
1169 template<typename T>
1170 CAutoFile& operator>>(T& obj)
1172 // Unserialize from this stream
1174 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1175 ::Unserialize(*this, obj, nType, nVersion);
1180 // Wrapper around a FILE* that implements a ring buffer to
1181 // deserialize from. It guarantees the ability to rewind
1182 // a given number of bytes.
1186 FILE *src; // source file
1187 uint64_t nSrcPos; // how many bytes have been read from source
1188 uint64_t nReadPos; // how many bytes have been read from this
1189 uint64_t nReadLimit; // up to which position we're allowed to read
1190 uint64_t nRewind; // how many bytes we guarantee to rewind
1191 std::vector<char> vchBuf; // the buffer
1197 void setstate(short bits, const char *psz);
1198 // read data from the source to fill the buffer
1205 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn);
1206 // check whether no error occurred
1208 // check whether we're at the end of the source file
1210 // read a number of bytes
1211 CBufferedFile& read(char *pch, size_t nSize);
1212 // return the current reading position
1214 // rewind to a given reading position
1215 bool SetPos(uint64_t nPos);
1216 bool Seek(uint64_t nPos);
1217 // prevent reading beyond a certain position
1218 // no argument removes the limit
1219 bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max());
1221 template<typename T>
1222 CBufferedFile& operator>>(T& obj) {
1223 // Unserialize from this stream
1224 ::Unserialize(*this, obj, nType, nVersion);
1228 // search for a given byte in the stream, and remain positioned on it
1229 void FindByte(char ch);