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))
109 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
110 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
112 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
113 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
114 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
115 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
116 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
117 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
118 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
119 //inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
120 //inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
121 inline unsigned int GetSerializeSize(int64_t a, int, int=0) { return sizeof(a); }
122 inline unsigned int GetSerializeSize(uint64_t a, int, int=0) { return sizeof(a); }
123 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
124 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
126 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
127 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
128 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
129 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
130 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
131 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
132 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
133 //template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
134 //template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
135 template<typename Stream> inline void Serialize(Stream& s, int64_t a, int, int=0) { WRITEDATA(s, a); }
136 template<typename Stream> inline void Serialize(Stream& s, uint64_t a, int, int=0) { WRITEDATA(s, a); }
137 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
138 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
140 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
141 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
142 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
143 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
144 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
145 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
146 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
147 //template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
148 //template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
149 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a, int, int=0) { READDATA(s, a); }
150 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a, int, int=0) { READDATA(s, a); }
151 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
152 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
154 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
155 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
156 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
163 // size < 253 -- 1 byte
164 // size <= UINT16_MAX -- 3 bytes (253 + 2 bytes)
165 // size <= UINT32_MAX -- 5 bytes (254 + 4 bytes)
166 // size > UINT32_MAX -- 9 bytes (255 + 8 bytes)
168 inline uint32_t GetSizeOfCompactSize(uint64_t nSize)
172 if (nSize <= std::numeric_limits<uint16_t>::max())
174 if (nSize <= std::numeric_limits<uint32_t>::max())
179 template<typename Stream>
180 void WriteCompactSize(Stream& os, uint64_t nSize);
182 template<typename Stream>
183 uint64_t ReadCompactSize(Stream& is);
185 // Variable-length integers: bytes are a MSB base-128 encoding of the number.
186 // The high bit in each byte signifies whether another digit follows. To make
187 // the encoding is one-to-one, one is subtracted from all but the last digit.
188 // Thus, the byte sequence a[] with length len, where all but the last byte
189 // has bit 128 set, encodes the number:
191 // (a[len-1] & 0x7F) + sum(i=1..len-1, 128^i*((a[len-i-1] & 0x7F)+1))
194 // * Very small (0-127: 1 byte, 128-16511: 2 bytes, 16512-2113663: 3 bytes)
195 // * Every integer has exactly one encoding
196 // * Encoding does not depend on size of original integer type
197 // * No redundancy: every (infinite) byte sequence corresponds to a list
198 // of encoded integers.
200 // 0: [0x00] 256: [0x81 0x00]
201 // 1: [0x01] 16383: [0xFE 0x7F]
202 // 127: [0x7F] 16384: [0xFF 0x00]
203 // 128: [0x80 0x00] 16511: [0x80 0xFF 0x7F]
204 // 255: [0x80 0x7F] 65535: [0x82 0xFD 0x7F]
205 // 2^32: [0x8E 0xFE 0xFE 0xFF 0x00]
208 inline unsigned int GetSizeOfVarInt(I n)
220 template<typename Stream, typename I>
221 void WriteVarInt(Stream& os, I n)
223 unsigned char tmp[(sizeof(n)*8+6)/7];
226 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
233 WRITEDATA(os, tmp[len]);
237 template<typename Stream, typename I>
238 I ReadVarInt(Stream& is)
242 unsigned char chData;
243 READDATA(is, chData);
244 n = (n << 7) | (chData & 0x7F);
252 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
253 #define VARINT(obj) REF(WrapVarInt(REF(obj)))
255 /** Wrapper for serializing arrays and POD.
263 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
264 char* begin() { return pbegin; }
265 const char* begin() const { return pbegin; }
266 char* end() { return pend; }
267 const char* end() const { return pend; }
269 unsigned int GetSerializeSize(int, int=0) const
271 return (unsigned int)(pend - pbegin);
274 template<typename Stream>
275 void Serialize(Stream& s, int, int=0) const
277 s.write(pbegin, (int)(pend - pbegin));
280 template<typename Stream>
281 void Unserialize(Stream& s, int, int=0)
283 s.read(pbegin, pend - pbegin);
293 CVarInt(I& nIn) : n(nIn) { }
295 unsigned int GetSerializeSize(int, int) const {
296 return GetSizeOfVarInt<I>(n);
299 template<typename Stream>
300 void Serialize(Stream &s, int, int) const {
301 WriteVarInt<Stream,I>(s, n);
304 template<typename Stream>
305 void Unserialize(Stream& s, int, int) {
306 n = ReadVarInt<Stream,I>(s);
311 CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }
314 // Forward declarations
318 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
319 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
320 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
323 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&);
324 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&);
325 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
326 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&);
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::false_type&);
328 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
329 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&);
330 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&);
331 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
333 // others derived from vector
334 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
335 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
336 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
339 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
340 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
341 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
344 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
345 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion);
346 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion);
349 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
350 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);
351 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);
354 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
355 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
356 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
362 // If none of the specialized versions above matched, default to calling member function.
363 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
364 // The compiler will only cast int to long if none of the other templates matched.
365 // Thanks to Boost serialization for this idea.
368 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
370 return a.GetSerializeSize((int)nType, nVersion);
373 template<typename Stream, typename T>
374 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
376 a.Serialize(os, (int)nType, nVersion);
379 template<typename Stream, typename T>
380 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
382 a.Unserialize(is, (int)nType, nVersion);
392 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
394 return (unsigned int)(GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]));
397 template<typename Stream, typename C>
398 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
400 WriteCompactSize(os, str.size());
402 os.write((char*)&str[0], (int)(str.size() * sizeof(str[0])));
405 template<typename Stream, typename C>
406 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
408 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
411 is.read((char*)&str[0], nSize * sizeof(str[0]));
419 template<typename T, typename A>
420 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
422 return (unsigned int)(GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
425 template<typename T, typename A>
426 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
428 unsigned int nSize = GetSizeOfCompactSize(v.size());
429 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
430 nSize += GetSerializeSize((*vi), nType, nVersion);
434 template<typename T, typename A>
435 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
437 return GetSerializeSize_impl(v, nType, nVersion, std::is_fundamental<T>());
441 template<typename Stream, typename T, typename A>
442 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
444 WriteCompactSize(os, v.size());
446 os.write((char*)&v[0], (int)(v.size() * sizeof(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::false_type&)
452 WriteCompactSize(os, v.size());
453 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
454 ::Serialize(os, (*vi), nType, nVersion);
457 template<typename Stream, typename T, typename A>
458 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
460 Serialize_impl(os, v, nType, nVersion, std::is_fundamental<T>());
464 template<typename Stream, typename T, typename A>
465 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::true_type&)
467 // Limit size per read so bogus size value won't cause out of memory
469 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
473 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
475 is.read((char*)&v[i], blk * sizeof(T));
480 template<typename Stream, typename T, typename A>
481 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const std::false_type&)
484 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
486 unsigned int nMid = 0;
489 nMid += 5000000 / sizeof(T);
493 for (; i < nMid; i++)
494 Unserialize(is, v[i], nType, nVersion);
498 template<typename Stream, typename T, typename A>
499 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
501 Unserialize_impl(is, v, nType, nVersion, std::is_fundamental<T>());
507 // others derived from vector
509 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
511 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
514 template<typename Stream>
515 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
517 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
520 template<typename Stream>
521 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
523 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
531 template<typename K, typename T>
532 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
534 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
537 template<typename Stream, typename K, typename T>
538 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
540 Serialize(os, item.first, nType, nVersion);
541 Serialize(os, item.second, nType, nVersion);
544 template<typename Stream, typename K, typename T>
545 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
547 Unserialize(is, item.first, nType, nVersion);
548 Unserialize(is, item.second, nType, nVersion);
556 template<typename T0, typename T1, typename T2>
557 unsigned int GetSerializeSize(const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
559 unsigned int nSize = 0;
560 nSize += GetSerializeSize(std::get<0>(item), nType, nVersion);
561 nSize += GetSerializeSize(std::get<1>(item), nType, nVersion);
562 nSize += GetSerializeSize(std::get<2>(item), nType, nVersion);
566 template<typename Stream, typename T0, typename T1, typename T2>
567 void Serialize(Stream& os, const std::tuple<T0, T1, T2>& item, int nType, int nVersion)
569 Serialize(os, std::get<0>(item), nType, nVersion);
570 Serialize(os, std::get<1>(item), nType, nVersion);
571 Serialize(os, std::get<2>(item), nType, nVersion);
574 template<typename Stream, typename T0, typename T1, typename T2>
575 void Unserialize(Stream& is, std::tuple<T0, T1, T2>& item, int nType, int nVersion)
577 Unserialize(is, std::get<0>(item), nType, nVersion);
578 Unserialize(is, std::get<1>(item), nType, nVersion);
579 Unserialize(is, std::get<2>(item), nType, nVersion);
587 template<typename K, typename T, typename Pred, typename A>
588 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
590 unsigned int nSize = GetSizeOfCompactSize(m.size());
591 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
592 nSize += GetSerializeSize((*mi), nType, nVersion);
596 template<typename Stream, typename K, typename T, typename Pred, typename A>
597 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
599 WriteCompactSize(os, m.size());
600 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
601 Serialize(os, (*mi), nType, nVersion);
604 template<typename Stream, typename K, typename T, typename Pred, typename A>
605 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
608 unsigned int nSize = (unsigned int)(ReadCompactSize(is));
609 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
610 for (unsigned int i = 0; i < nSize; i++)
612 std::pair<K, T> item;
613 Unserialize(is, item, nType, nVersion);
614 mi = m.insert(mi, item);
623 template<typename K, typename Pred, typename A>
624 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
626 unsigned int nSize = GetSizeOfCompactSize(m.size());
627 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
628 nSize += GetSerializeSize((*it), nType, nVersion);
632 template<typename Stream, typename K, typename Pred, typename A>
633 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
635 WriteCompactSize(os, m.size());
636 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
637 Serialize(os, (*it), nType, nVersion);
640 template<typename Stream, typename K, typename Pred, typename A>
641 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
644 unsigned int nSize = ReadCompactSize(is);
645 typename std::set<K, Pred, A>::iterator it = m.begin();
646 for (unsigned int i = 0; i < nSize; i++)
649 Unserialize(is, key, nType, nVersion);
650 it = m.insert(it, key);
657 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
659 class CSerActionGetSerializeSize { };
660 class CSerActionSerialize { };
661 class CSerActionUnserialize { };
663 template<typename Stream, typename T>
664 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
666 return ::GetSerializeSize(obj, nType, nVersion);
669 template<typename Stream, typename T>
670 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
672 ::Serialize(s, obj, nType, nVersion);
676 template<typename Stream, typename T>
677 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
679 ::Unserialize(s, obj, nType, nVersion);
683 struct ser_streamplaceholder
692 typedef std::vector<char, zero_after_free_allocator<char> > CSerializeData;
694 /** Double ended buffer combining vector and stream-like interfaces.
696 * >> and << read and write unformatted data using the above serialization templates.
697 * Fills with data in linear time; some stringstream implementations take N^2 time.
702 typedef CSerializeData vector_type;
704 unsigned int nReadPos;
711 typedef vector_type::allocator_type allocator_type;
712 typedef vector_type::size_type size_type;
713 typedef vector_type::difference_type difference_type;
714 typedef vector_type::reference reference;
715 typedef vector_type::const_reference const_reference;
716 typedef vector_type::value_type value_type;
717 typedef vector_type::iterator iterator;
718 typedef vector_type::const_iterator const_iterator;
719 typedef vector_type::reverse_iterator reverse_iterator;
721 explicit CDataStream(int nTypeIn, int nVersionIn)
723 Init(nTypeIn, nVersionIn);
726 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
728 Init(nTypeIn, nVersionIn);
731 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
733 Init(nTypeIn, nVersionIn);
736 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
738 Init(nTypeIn, nVersionIn);
741 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
743 Init(nTypeIn, nVersionIn);
746 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
748 Init(nTypeIn, nVersionIn);
751 void Init(int nTypeIn, int nVersionIn)
755 nVersion = nVersionIn;
757 exceptmask = std::ios::badbit | std::ios::failbit;
760 CDataStream& operator+=(const CDataStream& b)
762 vch.insert(vch.end(), b.begin(), b.end());
766 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
773 std::string str() const
775 return (std::string(begin(), end()));
782 const_iterator begin() const { return vch.begin() + nReadPos; }
783 iterator begin() { return vch.begin() + nReadPos; }
784 const_iterator end() const { return vch.end(); }
785 iterator end() { return vch.end(); }
786 size_type size() const { return vch.size() - nReadPos; }
787 bool empty() const { return vch.size() == nReadPos; }
788 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
789 void reserve(size_type n) { vch.reserve(n + nReadPos); }
790 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
791 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
792 void clear() { vch.clear(); nReadPos = 0; }
793 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
794 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
796 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
798 assert(last - first >= 0);
799 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
801 // special case for inserting at the front when there's room
802 nReadPos -= (last - first);
803 memcpy(&vch[nReadPos], &first[0], last - first);
806 vch.insert(it, first, last);
809 void insert(iterator it, const char* first, const char* last)
811 assert(last - first >= 0);
812 if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
814 // special case for inserting at the front when there's room
815 nReadPos -= (unsigned int)(last - first);
816 memcpy(&vch[nReadPos], &first[0], last - first);
819 vch.insert(it, first, last);
822 iterator erase(iterator it)
824 if (it == vch.begin() + nReadPos)
826 // special case for erasing from the front
827 if (++nReadPos >= vch.size())
829 // whenever we reach the end, we take the opportunity to clear the buffer
831 return vch.erase(vch.begin(), vch.end());
833 return vch.begin() + nReadPos;
836 return vch.erase(it);
839 iterator erase(iterator first, iterator last)
841 if (first == vch.begin() + nReadPos)
843 // special case for erasing from the front
844 if (last == vch.end())
847 return vch.erase(vch.begin(), vch.end());
851 nReadPos = (unsigned int)(last - vch.begin());
856 return vch.erase(first, last);
859 inline void Compact()
861 vch.erase(vch.begin(), vch.begin() + nReadPos);
865 bool Rewind(size_type n);
870 void setstate(short bits, const char* psz);
871 bool eof() const { return size() == 0; }
872 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
873 bool good() const { return !eof() && (state == 0); }
874 void clear(short n) { state = n; } // name conflict with vector clear()
875 short exceptions() { return exceptmask; }
876 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
877 CDataStream* rdbuf() { return this; }
878 int in_avail() { return (int)(size()); }
880 void SetType(int n) { nType = n; }
881 int GetType() { return nType; }
882 void SetVersion(int n) { nVersion = n; }
883 int GetVersion() { return nVersion; }
884 void ReadVersion() { *this >> nVersion; }
885 void WriteVersion() { *this << nVersion; }
887 CDataStream& read(char* pch, int nSize);
888 CDataStream& ignore(int nSize);
889 CDataStream& write(const char* pch, int nSize);
891 template<typename Stream>
892 void Serialize(Stream& s, int nType, int nVersion) const
894 // Special case: stream << stream concatenates like stream += stream
896 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
900 unsigned int GetSerializeSize(const T& obj)
902 // Tells the size of the object if serialized to this stream
903 return ::GetSerializeSize(obj, nType, nVersion);
907 CDataStream& operator<<(const T& obj)
909 // Serialize to this stream
910 ::Serialize(*this, obj, nType, nVersion);
915 CDataStream& operator>>(T& obj)
917 // Unserialize from this stream
918 ::Unserialize(*this, obj, nType, nVersion);
922 void GetAndClear(CSerializeData &data);
926 // RAII wrapper for FILE*.
928 // Will automatically close the file when it goes out of scope if not null.
929 // If you're returning the file pointer, return file.release().
930 // If you need to close the file early, use file.fclose() instead of fclose(file).
941 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn);
945 FILE* release() { FILE* ret = file; file = NULL; return ret; }
946 operator FILE*() { return file; }
947 FILE* operator->() { return file; }
948 FILE& operator*() { return *file; }
949 FILE** operator&() { return &file; }
950 FILE* operator=(FILE* pnew) { return file = pnew; }
951 bool operator!() { return (file == NULL); }
957 void setstate(short bits, const char* psz);
958 bool fail() const { return (state & (std::ios::badbit | std::ios::failbit)) != 0; }
959 bool good() const { return state == 0; }
960 void clear(short n = 0) { state = n; }
961 short exceptions() { return exceptmask; }
962 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
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 CAutoFile& read(char* pch, size_t nSize);
972 CAutoFile& write(const char* pch, size_t nSize);
975 unsigned int GetSerializeSize(const T& obj)
977 // Tells the size of the object if serialized to this stream
978 return ::GetSerializeSize(obj, nType, nVersion);
982 CAutoFile& operator<<(const T& obj)
984 // Serialize to this stream
986 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
987 ::Serialize(*this, obj, nType, nVersion);
992 CAutoFile& operator>>(T& obj)
994 // Unserialize from this stream
996 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
997 ::Unserialize(*this, obj, nType, nVersion);
1002 // Wrapper around a FILE* that implements a ring buffer to
1003 // deserialize from. It guarantees the ability to rewind
1004 // a given number of bytes.
1008 FILE *src; // source file
1009 uint64_t nSrcPos; // how many bytes have been read from source
1010 uint64_t nReadPos; // how many bytes have been read from this
1011 uint64_t nReadLimit; // up to which position we're allowed to read
1012 uint64_t nRewind; // how many bytes we guarantee to rewind
1013 std::vector<char> vchBuf; // the buffer
1019 void setstate(short bits, const char *psz);
1020 // read data from the source to fill the buffer
1027 CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn);
1028 // check whether no error occurred
1030 // check whether we're at the end of the source file
1032 // read a number of bytes
1033 CBufferedFile& read(char *pch, size_t nSize);
1034 // return the current reading position
1036 // rewind to a given reading position
1037 bool SetPos(uint64_t nPos);
1038 bool Seek(uint64_t nPos);
1039 // prevent reading beyond a certain position
1040 // no argument removes the limit
1041 bool SetLimit(uint64_t nPos = std::numeric_limits<uint64_t>::max());
1043 template<typename T>
1044 CBufferedFile& operator>>(T& obj) {
1045 // Unserialize from this stream
1046 ::Unserialize(*this, obj, nType, nVersion);
1050 // search for a given byte in the stream, and remain positioned on it
1051 void FindByte(char ch);