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 license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_SERIALIZE_H
6 #define BITCOIN_SERIALIZE_H
17 #include <boost/type_traits/is_fundamental.hpp>
18 #include <boost/tuple/tuple.hpp>
19 #include <boost/tuple/tuple_comparison.hpp>
20 #include <boost/tuple/tuple_io.hpp>
22 #include "allocators.h"
24 typedef long long int64;
25 typedef unsigned long long uint64;
30 static const unsigned int MAX_SIZE = 0x02000000;
32 static const int PROTOCOL_VERSION = 60000;
34 // Used to bypass the rule against non-const reference to temporary
35 // where it makes sense with wrappers such as CFlatData or CTxDB
37 inline T& REF(const T& val)
39 return const_cast<T&>(val);
42 /////////////////////////////////////////////////////////////////
44 // Templates for serializing to anything that looks like a stream,
45 // i.e. anything that supports .read(char*, int) and .write(char*, int)
51 SER_NETWORK = (1 << 0),
53 SER_GETHASH = (1 << 2),
56 SER_SKIPSIG = (1 << 16),
57 SER_BLOCKHEADERONLY = (1 << 17),
60 #define IMPLEMENT_SERIALIZE(statements) \
61 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const \
63 CSerActionGetSerializeSize ser_action; \
64 const bool fGetSize = true; \
65 const bool fWrite = false; \
66 const bool fRead = false; \
67 unsigned int nSerSize = 0; \
68 ser_streamplaceholder s; \
69 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
71 s.nVersion = nVersion; \
75 template<typename Stream> \
76 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const \
78 CSerActionSerialize ser_action; \
79 const bool fGetSize = false; \
80 const bool fWrite = true; \
81 const bool fRead = false; \
82 unsigned int nSerSize = 0; \
83 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
86 template<typename Stream> \
87 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) \
89 CSerActionUnserialize ser_action; \
90 const bool fGetSize = false; \
91 const bool fWrite = false; \
92 const bool fRead = true; \
93 unsigned int nSerSize = 0; \
94 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
98 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
108 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
109 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
111 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
112 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
113 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
114 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
115 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
116 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
117 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
118 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
119 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
120 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
121 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
122 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
123 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
125 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
126 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
127 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
128 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
129 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
130 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
131 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
132 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
133 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
134 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
135 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
136 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
137 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
139 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
140 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
141 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
142 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
143 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
144 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
145 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
146 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
147 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
148 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
149 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
150 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
151 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
153 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
154 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
155 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
164 // size < 253 -- 1 byte
165 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
166 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
167 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
169 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
171 if (nSize < 253) return sizeof(unsigned char);
172 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
173 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
174 else return sizeof(unsigned char) + sizeof(uint64);
177 template<typename Stream>
178 void WriteCompactSize(Stream& os, uint64 nSize)
182 unsigned char chSize = nSize;
183 WRITEDATA(os, chSize);
185 else if (nSize <= std::numeric_limits<unsigned short>::max())
187 unsigned char chSize = 253;
188 unsigned short xSize = nSize;
189 WRITEDATA(os, chSize);
190 WRITEDATA(os, xSize);
192 else if (nSize <= std::numeric_limits<unsigned int>::max())
194 unsigned char chSize = 254;
195 unsigned int xSize = nSize;
196 WRITEDATA(os, chSize);
197 WRITEDATA(os, xSize);
201 unsigned char chSize = 255;
202 uint64 xSize = nSize;
203 WRITEDATA(os, chSize);
204 WRITEDATA(os, xSize);
209 template<typename Stream>
210 uint64 ReadCompactSize(Stream& is)
212 unsigned char chSize;
213 READDATA(is, chSize);
219 else if (chSize == 253)
221 unsigned short xSize;
225 else if (chSize == 254)
237 if (nSizeRet > (uint64)MAX_SIZE)
238 throw std::ios_base::failure("ReadCompactSize() : size too large");
244 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
246 /** Wrapper for serializing arrays and POD.
247 * There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it.
255 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
256 char* begin() { return pbegin; }
257 const char* begin() const { return pbegin; }
258 char* end() { return pend; }
259 const char* end() const { return pend; }
261 unsigned int GetSerializeSize(int, int=0) const
263 return pend - pbegin;
266 template<typename Stream>
267 void Serialize(Stream& s, int, int=0) const
269 s.write(pbegin, pend - pbegin);
272 template<typename Stream>
273 void Unserialize(Stream& s, int, int=0)
275 s.read(pbegin, pend - pbegin);
280 // Forward declarations
284 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
285 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
286 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
289 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
290 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
291 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
292 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
293 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
294 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
295 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
296 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
297 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
299 // others derived from vector
300 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
301 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
302 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
305 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
306 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
307 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
310 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
311 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
312 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
315 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion=PROTOCOL_VERSION);
316 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion=PROTOCOL_VERSION);
317 template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion=PROTOCOL_VERSION);
320 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
321 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=PROTOCOL_VERSION);
322 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=PROTOCOL_VERSION);
325 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
326 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
327 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
334 // If none of the specialized versions above matched, default to calling member function.
335 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
336 // The compiler will only cast int to long if none of the other templates matched.
337 // Thanks to Boost serialization for this idea.
340 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=PROTOCOL_VERSION)
342 return a.GetSerializeSize((int)nType, nVersion);
345 template<typename Stream, typename T>
346 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=PROTOCOL_VERSION)
348 a.Serialize(os, (int)nType, nVersion);
351 template<typename Stream, typename T>
352 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=PROTOCOL_VERSION)
354 a.Unserialize(is, (int)nType, nVersion);
365 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
367 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
370 template<typename Stream, typename C>
371 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
373 WriteCompactSize(os, str.size());
375 os.write((char*)&str[0], str.size() * sizeof(str[0]));
378 template<typename Stream, typename C>
379 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
381 unsigned int nSize = ReadCompactSize(is);
384 is.read((char*)&str[0], nSize * sizeof(str[0]));
392 template<typename T, typename A>
393 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
395 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
398 template<typename T, typename A>
399 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
401 unsigned int nSize = GetSizeOfCompactSize(v.size());
402 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
403 nSize += GetSerializeSize((*vi), nType, nVersion);
407 template<typename T, typename A>
408 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
410 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
414 template<typename Stream, typename T, typename A>
415 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
417 WriteCompactSize(os, v.size());
419 os.write((char*)&v[0], v.size() * sizeof(T));
422 template<typename Stream, typename T, typename A>
423 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
425 WriteCompactSize(os, v.size());
426 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
427 ::Serialize(os, (*vi), nType, nVersion);
430 template<typename Stream, typename T, typename A>
431 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
433 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
437 template<typename Stream, typename T, typename A>
438 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
440 // Limit size per read so bogus size value won't cause out of memory
442 unsigned int nSize = ReadCompactSize(is);
446 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
448 is.read((char*)&v[i], blk * sizeof(T));
453 template<typename Stream, typename T, typename A>
454 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
457 unsigned int nSize = ReadCompactSize(is);
459 unsigned int nMid = 0;
462 nMid += 5000000 / sizeof(T);
466 for (; i < nMid; i++)
467 Unserialize(is, v[i], nType, nVersion);
471 template<typename Stream, typename T, typename A>
472 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
474 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
480 // others derived from vector
482 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
484 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
487 template<typename Stream>
488 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
490 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
493 template<typename Stream>
494 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
496 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
504 template<typename K, typename T>
505 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
507 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
510 template<typename Stream, typename K, typename T>
511 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
513 Serialize(os, item.first, nType, nVersion);
514 Serialize(os, item.second, nType, nVersion);
517 template<typename Stream, typename K, typename T>
518 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
520 Unserialize(is, item.first, nType, nVersion);
521 Unserialize(is, item.second, nType, nVersion);
529 template<typename T0, typename T1, typename T2>
530 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
532 unsigned int nSize = 0;
533 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
534 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
535 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
539 template<typename Stream, typename T0, typename T1, typename T2>
540 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
542 Serialize(os, boost::get<0>(item), nType, nVersion);
543 Serialize(os, boost::get<1>(item), nType, nVersion);
544 Serialize(os, boost::get<2>(item), nType, nVersion);
547 template<typename Stream, typename T0, typename T1, typename T2>
548 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
550 Unserialize(is, boost::get<0>(item), nType, nVersion);
551 Unserialize(is, boost::get<1>(item), nType, nVersion);
552 Unserialize(is, boost::get<2>(item), nType, nVersion);
560 template<typename T0, typename T1, typename T2, typename T3>
561 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
563 unsigned int nSize = 0;
564 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
565 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
566 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
567 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
571 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
572 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
574 Serialize(os, boost::get<0>(item), nType, nVersion);
575 Serialize(os, boost::get<1>(item), nType, nVersion);
576 Serialize(os, boost::get<2>(item), nType, nVersion);
577 Serialize(os, boost::get<3>(item), nType, nVersion);
580 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
581 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
583 Unserialize(is, boost::get<0>(item), nType, nVersion);
584 Unserialize(is, boost::get<1>(item), nType, nVersion);
585 Unserialize(is, boost::get<2>(item), nType, nVersion);
586 Unserialize(is, boost::get<3>(item), nType, nVersion);
594 template<typename K, typename T, typename Pred, typename A>
595 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
597 unsigned int nSize = GetSizeOfCompactSize(m.size());
598 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
599 nSize += GetSerializeSize((*mi), nType, nVersion);
603 template<typename Stream, typename K, typename T, typename Pred, typename A>
604 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
606 WriteCompactSize(os, m.size());
607 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
608 Serialize(os, (*mi), nType, nVersion);
611 template<typename Stream, typename K, typename T, typename Pred, typename A>
612 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
615 unsigned int nSize = ReadCompactSize(is);
616 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
617 for (unsigned int i = 0; i < nSize; i++)
619 std::pair<K, T> item;
620 Unserialize(is, item, nType, nVersion);
621 mi = m.insert(mi, item);
630 template<typename K, typename Pred, typename A>
631 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
633 unsigned int nSize = GetSizeOfCompactSize(m.size());
634 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
635 nSize += GetSerializeSize((*it), nType, nVersion);
639 template<typename Stream, typename K, typename Pred, typename A>
640 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
642 WriteCompactSize(os, m.size());
643 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
644 Serialize(os, (*it), nType, nVersion);
647 template<typename Stream, typename K, typename Pred, typename A>
648 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
651 unsigned int nSize = ReadCompactSize(is);
652 typename std::set<K, Pred, A>::iterator it = m.begin();
653 for (unsigned int i = 0; i < nSize; i++)
656 Unserialize(is, key, nType, nVersion);
657 it = m.insert(it, key);
664 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
666 class CSerActionGetSerializeSize { };
667 class CSerActionSerialize { };
668 class CSerActionUnserialize { };
670 template<typename Stream, typename T>
671 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
673 return ::GetSerializeSize(obj, nType, nVersion);
676 template<typename Stream, typename T>
677 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
679 ::Serialize(s, obj, nType, nVersion);
683 template<typename Stream, typename T>
684 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
686 ::Unserialize(s, obj, nType, nVersion);
690 struct ser_streamplaceholder
707 /** Double ended buffer combining vector and stream-like interfaces.
709 * >> and << read and write unformatted data using the above serialization templates.
710 * Fills with data in linear time; some stringstream implementations take N^2 time.
715 typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
717 unsigned int nReadPos;
724 typedef vector_type::allocator_type allocator_type;
725 typedef vector_type::size_type size_type;
726 typedef vector_type::difference_type difference_type;
727 typedef vector_type::reference reference;
728 typedef vector_type::const_reference const_reference;
729 typedef vector_type::value_type value_type;
730 typedef vector_type::iterator iterator;
731 typedef vector_type::const_iterator const_iterator;
732 typedef vector_type::reverse_iterator reverse_iterator;
734 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
736 Init(nTypeIn, nVersionIn);
739 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
741 Init(nTypeIn, nVersionIn);
744 #if !defined(_MSC_VER) || _MSC_VER >= 1300
745 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
747 Init(nTypeIn, nVersionIn);
751 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
753 Init(nTypeIn, nVersionIn);
756 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
758 Init(nTypeIn, nVersionIn);
761 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
763 Init(nTypeIn, nVersionIn);
766 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
770 nVersion = nVersionIn;
772 exceptmask = std::ios::badbit | std::ios::failbit;
775 CDataStream& operator+=(const CDataStream& b)
777 vch.insert(vch.end(), b.begin(), b.end());
781 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
788 std::string str() const
790 return (std::string(begin(), end()));
797 const_iterator begin() const { return vch.begin() + nReadPos; }
798 iterator begin() { return vch.begin() + nReadPos; }
799 const_iterator end() const { return vch.end(); }
800 iterator end() { return vch.end(); }
801 size_type size() const { return vch.size() - nReadPos; }
802 bool empty() const { return vch.size() == nReadPos; }
803 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
804 void reserve(size_type n) { vch.reserve(n + nReadPos); }
805 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
806 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
807 void clear() { vch.clear(); nReadPos = 0; }
808 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
809 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
811 void insert(iterator it, const_iterator first, const_iterator last)
813 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
815 // special case for inserting at the front when there's room
816 nReadPos -= (last - first);
817 memcpy(&vch[nReadPos], &first[0], last - first);
820 vch.insert(it, first, last);
823 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
825 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
827 // special case for inserting at the front when there's room
828 nReadPos -= (last - first);
829 memcpy(&vch[nReadPos], &first[0], last - first);
832 vch.insert(it, first, last);
835 #if !defined(_MSC_VER) || _MSC_VER >= 1300
836 void insert(iterator it, const char* first, const char* last)
838 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
840 // special case for inserting at the front when there's room
841 nReadPos -= (last - first);
842 memcpy(&vch[nReadPos], &first[0], last - first);
845 vch.insert(it, first, last);
849 iterator erase(iterator it)
851 if (it == vch.begin() + nReadPos)
853 // special case for erasing from the front
854 if (++nReadPos >= vch.size())
856 // whenever we reach the end, we take the opportunity to clear the buffer
858 return vch.erase(vch.begin(), vch.end());
860 return vch.begin() + nReadPos;
863 return vch.erase(it);
866 iterator erase(iterator first, iterator last)
868 if (first == vch.begin() + nReadPos)
870 // special case for erasing from the front
871 if (last == vch.end())
874 return vch.erase(vch.begin(), vch.end());
878 nReadPos = (last - vch.begin());
883 return vch.erase(first, last);
886 inline void Compact()
888 vch.erase(vch.begin(), vch.begin() + nReadPos);
892 bool Rewind(size_type n)
894 // Rewind by n characters if the buffer hasn't been compacted yet
905 void setstate(short bits, const char* psz)
908 if (state & exceptmask)
909 throw std::ios_base::failure(psz);
912 bool eof() const { return size() == 0; }
913 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
914 bool good() const { return !eof() && (state == 0); }
915 void clear(short n) { state = n; } // name conflict with vector clear()
916 short exceptions() { return exceptmask; }
917 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
918 CDataStream* rdbuf() { return this; }
919 int in_avail() { return size(); }
921 void SetType(int n) { nType = n; }
922 int GetType() { return nType; }
923 void SetVersion(int n) { nVersion = n; }
924 int GetVersion() { return nVersion; }
925 void ReadVersion() { *this >> nVersion; }
926 void WriteVersion() { *this << nVersion; }
928 CDataStream& read(char* pch, int nSize)
930 // Read from the beginning of the buffer
932 unsigned int nReadPosNext = nReadPos + nSize;
933 if (nReadPosNext >= vch.size())
935 if (nReadPosNext > vch.size())
937 setstate(std::ios::failbit, "CDataStream::read() : end of data");
938 memset(pch, 0, nSize);
939 nSize = vch.size() - nReadPos;
941 memcpy(pch, &vch[nReadPos], nSize);
946 memcpy(pch, &vch[nReadPos], nSize);
947 nReadPos = nReadPosNext;
951 CDataStream& ignore(int nSize)
953 // Ignore from the beginning of the buffer
955 unsigned int nReadPosNext = nReadPos + nSize;
956 if (nReadPosNext >= vch.size())
958 if (nReadPosNext > vch.size())
960 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
961 nSize = vch.size() - nReadPos;
967 nReadPos = nReadPosNext;
971 CDataStream& write(const char* pch, int nSize)
973 // Write to the end of the buffer
975 vch.insert(vch.end(), pch, pch + nSize);
979 template<typename Stream>
980 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
982 // Special case: stream << stream concatenates like stream += stream
984 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
988 unsigned int GetSerializeSize(const T& obj)
990 // Tells the size of the object if serialized to this stream
991 return ::GetSerializeSize(obj, nType, nVersion);
995 CDataStream& operator<<(const T& obj)
997 // Serialize to this stream
998 ::Serialize(*this, obj, nType, nVersion);
1002 template<typename T>
1003 CDataStream& operator>>(T& obj)
1005 // Unserialize from this stream
1006 ::Unserialize(*this, obj, nType, nVersion);
1011 #ifdef TESTCDATASTREAM
1018 // n=16000 0 seconds
1019 // n=32000 0 seconds
1020 // n=64000 1 seconds
1021 // n=128000 1 seconds
1022 // n=256000 2 seconds
1023 // n=512000 4 seconds
1024 // n=1024000 8 seconds
1025 // n=2048000 16 seconds
1026 // n=4096000 32 seconds
1030 // n=4000 13 seconds
1031 // n=8000 87 seconds
1032 // n=16000 400 seconds
1033 // n=32000 1660 seconds
1034 // n=64000 6749 seconds
1035 // n=128000 27241 seconds
1036 // n=256000 109804 seconds
1038 int main(int argc, char *argv[])
1040 vector<unsigned char> vch(0xcc, 250);
1041 printf("CDataStream:\n");
1042 for (int n = 1000; n <= 4500000; n *= 2)
1045 time_t nStart = time(NULL);
1046 for (int i = 0; i < n; i++)
1047 ss.write((char*)&vch[0], vch.size());
1048 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1050 printf("stringstream:\n");
1051 for (int n = 1000; n <= 4500000; n *= 2)
1054 time_t nStart = time(NULL);
1055 for (int i = 0; i < n; i++)
1056 ss.write((char*)&vch[0], vch.size());
1057 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1071 /** RAII wrapper for FILE*.
1073 * Will automatically close the file when it goes out of scope if not null.
1074 * If you're returning the file pointer, return file.release().
1075 * If you need to close the file early, use file.fclose() instead of fclose(file).
1087 typedef FILE element_type;
1089 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=PROTOCOL_VERSION)
1093 nVersion = nVersionIn;
1095 exceptmask = std::ios::badbit | std::ios::failbit;
1105 if (file != NULL && file != stdin && file != stdout && file != stderr)
1110 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1111 operator FILE*() { return file; }
1112 FILE* operator->() { return file; }
1113 FILE& operator*() { return *file; }
1114 FILE** operator&() { return &file; }
1115 FILE* operator=(FILE* pnew) { return file = pnew; }
1116 bool operator!() { return (file == NULL); }
1122 void setstate(short bits, const char* psz)
1125 if (state & exceptmask)
1126 throw std::ios_base::failure(psz);
1129 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1130 bool good() const { return state == 0; }
1131 void clear(short n = 0) { state = n; }
1132 short exceptions() { return exceptmask; }
1133 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1135 void SetType(int n) { nType = n; }
1136 int GetType() { return nType; }
1137 void SetVersion(int n) { nVersion = n; }
1138 int GetVersion() { return nVersion; }
1139 void ReadVersion() { *this >> nVersion; }
1140 void WriteVersion() { *this << nVersion; }
1142 CAutoFile& read(char* pch, int nSize)
1145 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1146 if (fread(pch, 1, nSize, file) != nSize)
1147 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1151 CAutoFile& write(const char* pch, int nSize)
1154 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1155 if (fwrite(pch, 1, nSize, file) != nSize)
1156 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1160 template<typename T>
1161 unsigned int GetSerializeSize(const T& obj)
1163 // Tells the size of the object if serialized to this stream
1164 return ::GetSerializeSize(obj, nType, nVersion);
1167 template<typename T>
1168 CAutoFile& operator<<(const T& obj)
1170 // Serialize to this stream
1172 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1173 ::Serialize(*this, obj, nType, nVersion);
1177 template<typename T>
1178 CAutoFile& operator>>(T& obj)
1180 // Unserialize from this stream
1182 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1183 ::Unserialize(*this, obj, nType, nVersion);