1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Copyright (c) 2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
6 #ifndef BITCOIN_SERIALIZE_H
7 #define BITCOIN_SERIALIZE_H
18 #include <boost/type_traits/is_fundamental.hpp>
19 #include <boost/tuple/tuple.hpp>
20 #include <boost/tuple/tuple_comparison.hpp>
21 #include <boost/tuple/tuple_io.hpp>
23 #include "allocators.h"
26 typedef long long int64;
27 typedef unsigned long long uint64;
32 static const unsigned int MAX_SIZE = 0x02000000;
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, int nVersion) 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, int nVersion) 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, int nVersion) \
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; }
159 #ifndef THROW_WITH_STACKTRACE
160 #define THROW_WITH_STACKTRACE(exception) \
165 void LogStackTrace();
170 // size < 253 -- 1 byte
171 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
172 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
173 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
175 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
177 if (nSize < 253) return sizeof(unsigned char);
178 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
179 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
180 else return sizeof(unsigned char) + sizeof(uint64);
183 template<typename Stream>
184 void WriteCompactSize(Stream& os, uint64 nSize)
188 unsigned char chSize = nSize;
189 WRITEDATA(os, chSize);
191 else if (nSize <= std::numeric_limits<unsigned short>::max())
193 unsigned char chSize = 253;
194 unsigned short xSize = nSize;
195 WRITEDATA(os, chSize);
196 WRITEDATA(os, xSize);
198 else if (nSize <= std::numeric_limits<unsigned int>::max())
200 unsigned char chSize = 254;
201 unsigned int xSize = nSize;
202 WRITEDATA(os, chSize);
203 WRITEDATA(os, xSize);
207 unsigned char chSize = 255;
208 uint64 xSize = nSize;
209 WRITEDATA(os, chSize);
210 WRITEDATA(os, xSize);
215 template<typename Stream>
216 uint64 ReadCompactSize(Stream& is)
218 unsigned char chSize;
219 READDATA(is, chSize);
225 else if (chSize == 253)
227 unsigned short xSize;
231 else if (chSize == 254)
243 if (nSizeRet > (uint64)MAX_SIZE)
244 THROW_WITH_STACKTRACE(std::ios_base::failure("ReadCompactSize() : size too large"));
250 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
252 /** Wrapper for serializing arrays and POD.
253 * There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it.
261 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
262 char* begin() { return pbegin; }
263 const char* begin() const { return pbegin; }
264 char* end() { return pend; }
265 const char* end() const { return pend; }
267 unsigned int GetSerializeSize(int, int=0) const
269 return pend - pbegin;
272 template<typename Stream>
273 void Serialize(Stream& s, int, int=0) const
275 s.write(pbegin, pend - pbegin);
278 template<typename Stream>
279 void Unserialize(Stream& s, int, int=0)
281 s.read(pbegin, pend - pbegin);
286 // Forward declarations
290 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
291 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
292 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
295 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
296 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
297 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion);
298 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&);
299 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&);
300 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion);
301 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&);
302 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&);
303 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion);
305 // others derived from vector
306 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion);
307 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion);
308 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion);
311 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion);
312 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion);
313 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion);
316 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
317 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
318 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion);
321 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion);
322 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);
323 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);
326 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion);
327 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);
328 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);
331 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion);
332 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion);
333 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion);
340 // If none of the specialized versions above matched, default to calling member function.
341 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
342 // The compiler will only cast int to long if none of the other templates matched.
343 // Thanks to Boost serialization for this idea.
346 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion)
348 return a.GetSerializeSize((int)nType, nVersion);
351 template<typename Stream, typename T>
352 inline void Serialize(Stream& os, const T& a, long nType, int nVersion)
354 a.Serialize(os, (int)nType, nVersion);
357 template<typename Stream, typename T>
358 inline void Unserialize(Stream& is, T& a, long nType, int nVersion)
360 a.Unserialize(is, (int)nType, nVersion);
371 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
373 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
376 template<typename Stream, typename C>
377 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
379 WriteCompactSize(os, str.size());
381 os.write((char*)&str[0], str.size() * sizeof(str[0]));
384 template<typename Stream, typename C>
385 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
387 unsigned int nSize = ReadCompactSize(is);
390 is.read((char*)&str[0], nSize * sizeof(str[0]));
398 template<typename T, typename A>
399 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
401 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
404 template<typename T, typename A>
405 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
407 unsigned int nSize = GetSizeOfCompactSize(v.size());
408 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
409 nSize += GetSerializeSize((*vi), nType, nVersion);
413 template<typename T, typename A>
414 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
416 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
420 template<typename Stream, typename T, typename A>
421 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
423 WriteCompactSize(os, v.size());
425 os.write((char*)&v[0], v.size() * sizeof(T));
428 template<typename Stream, typename T, typename A>
429 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
431 WriteCompactSize(os, v.size());
432 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
433 ::Serialize(os, (*vi), nType, nVersion);
436 template<typename Stream, typename T, typename A>
437 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
439 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
443 template<typename Stream, typename T, typename A>
444 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
446 // Limit size per read so bogus size value won't cause out of memory
448 unsigned int nSize = ReadCompactSize(is);
452 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
454 is.read((char*)&v[i], blk * sizeof(T));
459 template<typename Stream, typename T, typename A>
460 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
463 unsigned int nSize = ReadCompactSize(is);
465 unsigned int nMid = 0;
468 nMid += 5000000 / sizeof(T);
472 for (; i < nMid; i++)
473 Unserialize(is, v[i], nType, nVersion);
477 template<typename Stream, typename T, typename A>
478 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
480 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
486 // others derived from vector
488 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
490 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
493 template<typename Stream>
494 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
496 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
499 template<typename Stream>
500 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
502 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
510 template<typename K, typename T>
511 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
513 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
516 template<typename Stream, typename K, typename T>
517 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
519 Serialize(os, item.first, nType, nVersion);
520 Serialize(os, item.second, nType, nVersion);
523 template<typename Stream, typename K, typename T>
524 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
526 Unserialize(is, item.first, nType, nVersion);
527 Unserialize(is, item.second, nType, nVersion);
535 template<typename T0, typename T1, typename T2>
536 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
538 unsigned int nSize = 0;
539 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
540 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
541 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
545 template<typename Stream, typename T0, typename T1, typename T2>
546 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
548 Serialize(os, boost::get<0>(item), nType, nVersion);
549 Serialize(os, boost::get<1>(item), nType, nVersion);
550 Serialize(os, boost::get<2>(item), nType, nVersion);
553 template<typename Stream, typename T0, typename T1, typename T2>
554 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
556 Unserialize(is, boost::get<0>(item), nType, nVersion);
557 Unserialize(is, boost::get<1>(item), nType, nVersion);
558 Unserialize(is, boost::get<2>(item), nType, nVersion);
566 template<typename T0, typename T1, typename T2, typename T3>
567 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
569 unsigned int nSize = 0;
570 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
571 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
572 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
573 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
577 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
578 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
580 Serialize(os, boost::get<0>(item), nType, nVersion);
581 Serialize(os, boost::get<1>(item), nType, nVersion);
582 Serialize(os, boost::get<2>(item), nType, nVersion);
583 Serialize(os, boost::get<3>(item), nType, nVersion);
586 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
587 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
589 Unserialize(is, boost::get<0>(item), nType, nVersion);
590 Unserialize(is, boost::get<1>(item), nType, nVersion);
591 Unserialize(is, boost::get<2>(item), nType, nVersion);
592 Unserialize(is, boost::get<3>(item), nType, nVersion);
600 template<typename K, typename T, typename Pred, typename A>
601 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
603 unsigned int nSize = GetSizeOfCompactSize(m.size());
604 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
605 nSize += GetSerializeSize((*mi), nType, nVersion);
609 template<typename Stream, typename K, typename T, typename Pred, typename A>
610 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
612 WriteCompactSize(os, m.size());
613 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
614 Serialize(os, (*mi), nType, nVersion);
617 template<typename Stream, typename K, typename T, typename Pred, typename A>
618 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
621 unsigned int nSize = ReadCompactSize(is);
622 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
623 for (unsigned int i = 0; i < nSize; i++)
625 std::pair<K, T> item;
626 Unserialize(is, item, nType, nVersion);
627 mi = m.insert(mi, item);
636 template<typename K, typename Pred, typename A>
637 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
639 unsigned int nSize = GetSizeOfCompactSize(m.size());
640 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
641 nSize += GetSerializeSize((*it), nType, nVersion);
645 template<typename Stream, typename K, typename Pred, typename A>
646 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
648 WriteCompactSize(os, m.size());
649 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
650 Serialize(os, (*it), nType, nVersion);
653 template<typename Stream, typename K, typename Pred, typename A>
654 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
657 unsigned int nSize = ReadCompactSize(is);
658 typename std::set<K, Pred, A>::iterator it = m.begin();
659 for (unsigned int i = 0; i < nSize; i++)
662 Unserialize(is, key, nType, nVersion);
663 it = m.insert(it, key);
670 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
672 class CSerActionGetSerializeSize { };
673 class CSerActionSerialize { };
674 class CSerActionUnserialize { };
676 template<typename Stream, typename T>
677 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
679 return ::GetSerializeSize(obj, nType, nVersion);
682 template<typename Stream, typename T>
683 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
685 ::Serialize(s, obj, nType, nVersion);
689 template<typename Stream, typename T>
690 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
692 ::Unserialize(s, obj, nType, nVersion);
696 struct ser_streamplaceholder
713 /** Double ended buffer combining vector and stream-like interfaces.
715 * >> and << read and write unformatted data using the above serialization templates.
716 * Fills with data in linear time; some stringstream implementations take N^2 time.
721 typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
723 unsigned int nReadPos;
730 typedef vector_type::allocator_type allocator_type;
731 typedef vector_type::size_type size_type;
732 typedef vector_type::difference_type difference_type;
733 typedef vector_type::reference reference;
734 typedef vector_type::const_reference const_reference;
735 typedef vector_type::value_type value_type;
736 typedef vector_type::iterator iterator;
737 typedef vector_type::const_iterator const_iterator;
738 typedef vector_type::reverse_iterator reverse_iterator;
740 explicit CDataStream(int nTypeIn, int nVersionIn)
742 Init(nTypeIn, nVersionIn);
745 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
747 Init(nTypeIn, nVersionIn);
750 #if !defined(_MSC_VER) || _MSC_VER >= 1300
751 CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
753 Init(nTypeIn, nVersionIn);
757 CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
759 Init(nTypeIn, nVersionIn);
762 CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
764 Init(nTypeIn, nVersionIn);
767 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
769 Init(nTypeIn, nVersionIn);
772 void Init(int nTypeIn, int nVersionIn)
776 nVersion = nVersionIn;
778 exceptmask = std::ios::badbit | std::ios::failbit;
781 CDataStream& operator+=(const CDataStream& b)
783 vch.insert(vch.end(), b.begin(), b.end());
787 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
794 std::string str() const
796 return (std::string(begin(), end()));
803 const_iterator begin() const { return vch.begin() + nReadPos; }
804 iterator begin() { return vch.begin() + nReadPos; }
805 const_iterator end() const { return vch.end(); }
806 iterator end() { return vch.end(); }
807 size_type size() const { return vch.size() - nReadPos; }
808 bool empty() const { return vch.size() == nReadPos; }
809 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
810 void reserve(size_type n) { vch.reserve(n + nReadPos); }
811 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
812 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
813 void clear() { vch.clear(); nReadPos = 0; }
814 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
815 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
817 void insert(iterator it, const_iterator first, const_iterator last)
819 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
821 // special case for inserting at the front when there's room
822 nReadPos -= (last - first);
823 memcpy(&vch[nReadPos], &first[0], last - first);
826 vch.insert(it, first, last);
829 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
831 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
833 // special case for inserting at the front when there's room
834 nReadPos -= (last - first);
835 memcpy(&vch[nReadPos], &first[0], last - first);
838 vch.insert(it, first, last);
841 #if !defined(_MSC_VER) || _MSC_VER >= 1300
842 void insert(iterator it, const char* first, const char* last)
844 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
846 // special case for inserting at the front when there's room
847 nReadPos -= (last - first);
848 memcpy(&vch[nReadPos], &first[0], last - first);
851 vch.insert(it, first, last);
855 iterator erase(iterator it)
857 if (it == vch.begin() + nReadPos)
859 // special case for erasing from the front
860 if (++nReadPos >= vch.size())
862 // whenever we reach the end, we take the opportunity to clear the buffer
864 return vch.erase(vch.begin(), vch.end());
866 return vch.begin() + nReadPos;
869 return vch.erase(it);
872 iterator erase(iterator first, iterator last)
874 if (first == vch.begin() + nReadPos)
876 // special case for erasing from the front
877 if (last == vch.end())
880 return vch.erase(vch.begin(), vch.end());
884 nReadPos = (last - vch.begin());
889 return vch.erase(first, last);
892 inline void Compact()
894 vch.erase(vch.begin(), vch.begin() + nReadPos);
898 bool Rewind(size_type n)
900 // Rewind by n characters if the buffer hasn't been compacted yet
911 void setstate(short bits, const char* psz)
914 if (state & exceptmask)
915 THROW_WITH_STACKTRACE(std::ios_base::failure(psz));
918 bool eof() const { return size() == 0; }
919 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
920 bool good() const { return !eof() && (state == 0); }
921 void clear(short n) { state = n; } // name conflict with vector clear()
922 short exceptions() { return exceptmask; }
923 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
924 CDataStream* rdbuf() { return this; }
925 int in_avail() { return size(); }
927 void SetType(int n) { nType = n; }
928 int GetType() { return nType; }
929 void SetVersion(int n) { nVersion = n; }
930 int GetVersion() { return nVersion; }
931 void ReadVersion() { *this >> nVersion; }
932 void WriteVersion() { *this << nVersion; }
934 CDataStream& read(char* pch, int nSize)
936 // Read from the beginning of the buffer
938 unsigned int nReadPosNext = nReadPos + nSize;
939 if (nReadPosNext >= vch.size())
941 if (nReadPosNext > vch.size())
943 setstate(std::ios::failbit, "CDataStream::read() : end of data");
944 memset(pch, 0, nSize);
945 nSize = vch.size() - nReadPos;
947 memcpy(pch, &vch[nReadPos], nSize);
952 memcpy(pch, &vch[nReadPos], nSize);
953 nReadPos = nReadPosNext;
957 CDataStream& ignore(int nSize)
959 // Ignore from the beginning of the buffer
961 unsigned int nReadPosNext = nReadPos + nSize;
962 if (nReadPosNext >= vch.size())
964 if (nReadPosNext > vch.size())
966 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
967 nSize = vch.size() - nReadPos;
973 nReadPos = nReadPosNext;
977 CDataStream& write(const char* pch, int nSize)
979 // Write to the end of the buffer
981 vch.insert(vch.end(), pch, pch + nSize);
985 template<typename Stream>
986 void Serialize(Stream& s, int nType, int nVersion) const
988 // Special case: stream << stream concatenates like stream += stream
990 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
994 unsigned int GetSerializeSize(const T& obj)
996 // Tells the size of the object if serialized to this stream
997 return ::GetSerializeSize(obj, nType, nVersion);
1000 template<typename T>
1001 CDataStream& operator<<(const T& obj)
1003 // Serialize to this stream
1004 ::Serialize(*this, obj, nType, nVersion);
1008 template<typename T>
1009 CDataStream& operator>>(T& obj)
1011 // Unserialize from this stream
1012 ::Unserialize(*this, obj, nType, nVersion);
1017 #ifdef TESTCDATASTREAM
1024 // n=16000 0 seconds
1025 // n=32000 0 seconds
1026 // n=64000 1 seconds
1027 // n=128000 1 seconds
1028 // n=256000 2 seconds
1029 // n=512000 4 seconds
1030 // n=1024000 8 seconds
1031 // n=2048000 16 seconds
1032 // n=4096000 32 seconds
1036 // n=4000 13 seconds
1037 // n=8000 87 seconds
1038 // n=16000 400 seconds
1039 // n=32000 1660 seconds
1040 // n=64000 6749 seconds
1041 // n=128000 27241 seconds
1042 // n=256000 109804 seconds
1044 int main(int argc, char *argv[])
1046 vector<unsigned char> vch(0xcc, 250);
1047 printf("CDataStream:\n");
1048 for (int n = 1000; n <= 4500000; n *= 2)
1051 time_t nStart = time(NULL);
1052 for (int i = 0; i < n; i++)
1053 ss.write((char*)&vch[0], vch.size());
1054 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1056 printf("stringstream:\n");
1057 for (int n = 1000; n <= 4500000; n *= 2)
1060 time_t nStart = time(NULL);
1061 for (int i = 0; i < n; i++)
1062 ss.write((char*)&vch[0], vch.size());
1063 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1077 /** RAII wrapper for FILE*.
1079 * Will automatically close the file when it goes out of scope if not null.
1080 * If you're returning the file pointer, return file.release().
1081 * If you need to close the file early, use file.fclose() instead of fclose(file).
1093 CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
1097 nVersion = nVersionIn;
1099 exceptmask = std::ios::badbit | std::ios::failbit;
1109 if (file != NULL && file != stdin && file != stdout && file != stderr)
1114 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1115 operator FILE*() { return file; }
1116 FILE* operator->() { return file; }
1117 FILE& operator*() { return *file; }
1118 FILE** operator&() { return &file; }
1119 FILE* operator=(FILE* pnew) { return file = pnew; }
1120 bool operator!() { return (file == NULL); }
1126 void setstate(short bits, const char* psz)
1129 if (state & exceptmask)
1130 THROW_WITH_STACKTRACE(std::ios_base::failure(psz));
1133 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1134 bool good() const { return state == 0; }
1135 void clear(short n = 0) { state = n; }
1136 short exceptions() { return exceptmask; }
1137 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1139 void SetType(int n) { nType = n; }
1140 int GetType() { return nType; }
1141 void SetVersion(int n) { nVersion = n; }
1142 int GetVersion() { return nVersion; }
1143 void ReadVersion() { *this >> nVersion; }
1144 void WriteVersion() { *this << nVersion; }
1146 CAutoFile& read(char* pch, size_t nSize)
1149 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1150 if (fread(pch, 1, nSize, file) != nSize)
1151 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1155 CAutoFile& write(const char* pch, size_t nSize)
1158 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1159 if (fwrite(pch, 1, nSize, file) != nSize)
1160 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1164 template<typename T>
1165 unsigned int GetSerializeSize(const T& obj)
1167 // Tells the size of the object if serialized to this stream
1168 return ::GetSerializeSize(obj, nType, nVersion);
1171 template<typename T>
1172 CAutoFile& operator<<(const T& obj)
1174 // Serialize to this stream
1176 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1177 ::Serialize(*this, obj, nType, nVersion);
1181 template<typename T>
1182 CAutoFile& operator>>(T& obj)
1184 // Unserialize from this stream
1186 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1187 ::Unserialize(*this, obj, nType, nVersion);