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 <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 #if defined(_MSC_VER) || defined(__BORLANDC__)
23 typedef __int64 int64;
24 typedef unsigned __int64 uint64;
26 typedef long long int64;
27 typedef unsigned long long uint64;
29 #if defined(_MSC_VER) && _MSC_VER < 1300
30 #define for if (false) ; else for
35 // This is used to attempt to keep keying material out of swap
36 // Note that VirtualLock does not provide this as a guarantee on Windows,
37 // but, in practice, memory that has been VirtualLock'd almost never gets written to
38 // the pagefile except in rare circumstances where memory is extremely low.
40 #define mlock(p, n) VirtualLock((p), (n));
41 #define munlock(p, n) VirtualUnlock((p), (n));
45 /* This comes from limits.h if it's not defined there set a sane default */
48 #define PAGESIZE sysconf(_SC_PAGESIZE)
51 mlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
52 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
53 #define munlock(a,b) \
54 munlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
55 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
61 static const unsigned int MAX_SIZE = 0x02000000;
63 static const int VERSION = 50600;
64 static const char* pszSubVer = "";
65 static const bool VERSION_IS_BETA = true;
67 // Used to bypass the rule against non-const reference to temporary
68 // where it makes sense with wrappers such as CFlatData or CTxDB
70 inline T& REF(const T& val)
72 return const_cast<T&>(val);
75 /////////////////////////////////////////////////////////////////
77 // Templates for serializing to anything that looks like a stream,
78 // i.e. anything that supports .read(char*, int) and .write(char*, int)
84 SER_NETWORK = (1 << 0),
86 SER_GETHASH = (1 << 2),
89 SER_SKIPSIG = (1 << 16),
90 SER_BLOCKHEADERONLY = (1 << 17),
93 #define IMPLEMENT_SERIALIZE(statements) \
94 unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const \
96 CSerActionGetSerializeSize ser_action; \
97 const bool fGetSize = true; \
98 const bool fWrite = false; \
99 const bool fRead = false; \
100 unsigned int nSerSize = 0; \
101 ser_streamplaceholder s; \
102 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
104 s.nVersion = nVersion; \
108 template<typename Stream> \
109 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const \
111 CSerActionSerialize ser_action; \
112 const bool fGetSize = false; \
113 const bool fWrite = true; \
114 const bool fRead = false; \
115 unsigned int nSerSize = 0; \
116 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
119 template<typename Stream> \
120 void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) \
122 CSerActionUnserialize ser_action; \
123 const bool fGetSize = false; \
124 const bool fWrite = false; \
125 const bool fRead = true; \
126 unsigned int nSerSize = 0; \
127 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
131 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
141 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
142 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
144 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
145 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
146 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
147 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
148 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
149 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
150 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
151 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
152 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
153 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
154 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
155 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
156 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
158 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
159 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
160 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
161 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
162 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
163 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
164 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
165 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
166 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
167 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
168 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
169 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
170 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
172 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
173 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
174 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
175 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
176 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
177 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
178 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
179 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
180 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
181 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
182 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
183 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
184 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
186 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
187 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
188 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
197 // size < 253 -- 1 byte
198 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
199 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
200 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
202 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
204 if (nSize < 253) return sizeof(unsigned char);
205 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);
206 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);
207 else return sizeof(unsigned char) + sizeof(uint64);
210 template<typename Stream>
211 void WriteCompactSize(Stream& os, uint64 nSize)
215 unsigned char chSize = nSize;
216 WRITEDATA(os, chSize);
218 else if (nSize <= USHRT_MAX)
220 unsigned char chSize = 253;
221 unsigned short xSize = nSize;
222 WRITEDATA(os, chSize);
223 WRITEDATA(os, xSize);
225 else if (nSize <= UINT_MAX)
227 unsigned char chSize = 254;
228 unsigned int xSize = nSize;
229 WRITEDATA(os, chSize);
230 WRITEDATA(os, xSize);
234 unsigned char chSize = 255;
235 uint64 xSize = nSize;
236 WRITEDATA(os, chSize);
237 WRITEDATA(os, xSize);
242 template<typename Stream>
243 uint64 ReadCompactSize(Stream& is)
245 unsigned char chSize;
246 READDATA(is, chSize);
252 else if (chSize == 253)
254 unsigned short xSize;
258 else if (chSize == 254)
270 if (nSizeRet > (uint64)MAX_SIZE)
271 throw std::ios_base::failure("ReadCompactSize() : size too large");
278 // Wrapper for serializing arrays and POD
279 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
281 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
288 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
289 char* begin() { return pbegin; }
290 const char* begin() const { return pbegin; }
291 char* end() { return pend; }
292 const char* end() const { return pend; }
294 unsigned int GetSerializeSize(int, int=0) const
296 return pend - pbegin;
299 template<typename Stream>
300 void Serialize(Stream& s, int, int=0) const
302 s.write(pbegin, pend - pbegin);
305 template<typename Stream>
306 void Unserialize(Stream& s, int, int=0)
308 s.read(pbegin, pend - pbegin);
315 // string stored as a fixed length field
317 template<std::size_t LEN>
318 class CFixedFieldString
321 const std::string* pcstr;
324 explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
325 explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
327 unsigned int GetSerializeSize(int, int=0) const
332 template<typename Stream>
333 void Serialize(Stream& s, int, int=0) const
336 strncpy(pszBuf, pcstr->c_str(), LEN);
337 s.write(pszBuf, LEN);
340 template<typename Stream>
341 void Unserialize(Stream& s, int, int=0)
344 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
357 // Forward declarations
361 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
362 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
363 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
366 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
367 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
368 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);
369 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&);
370 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&);
371 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);
372 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&);
373 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&);
374 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);
376 // others derived from vector
377 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);
378 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);
379 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);
382 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);
383 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);
384 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);
387 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
388 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
389 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
392 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion=VERSION);
393 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=VERSION);
394 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=VERSION);
397 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion=VERSION);
398 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=VERSION);
399 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=VERSION);
402 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
403 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
404 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
411 // If none of the specialized versions above matched, default to calling member function.
412 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
413 // The compiler will only cast int to long if none of the other templates matched.
414 // Thanks to Boost serialization for this idea.
417 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)
419 return a.GetSerializeSize((int)nType, nVersion);
422 template<typename Stream, typename T>
423 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)
425 a.Serialize(os, (int)nType, nVersion);
428 template<typename Stream, typename T>
429 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)
431 a.Unserialize(is, (int)nType, nVersion);
442 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
444 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
447 template<typename Stream, typename C>
448 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
450 WriteCompactSize(os, str.size());
452 os.write((char*)&str[0], str.size() * sizeof(str[0]));
455 template<typename Stream, typename C>
456 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
458 unsigned int nSize = ReadCompactSize(is);
461 is.read((char*)&str[0], nSize * sizeof(str[0]));
469 template<typename T, typename A>
470 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
472 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
475 template<typename T, typename A>
476 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
478 unsigned int nSize = GetSizeOfCompactSize(v.size());
479 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
480 nSize += GetSerializeSize((*vi), nType, nVersion);
484 template<typename T, typename A>
485 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
487 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
491 template<typename Stream, typename T, typename A>
492 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
494 WriteCompactSize(os, v.size());
496 os.write((char*)&v[0], v.size() * sizeof(T));
499 template<typename Stream, typename T, typename A>
500 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
502 WriteCompactSize(os, v.size());
503 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
504 ::Serialize(os, (*vi), nType, nVersion);
507 template<typename Stream, typename T, typename A>
508 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
510 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
514 template<typename Stream, typename T, typename A>
515 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
517 //unsigned int nSize = ReadCompactSize(is);
519 //is.read((char*)&v[0], nSize * sizeof(T));
521 // Limit size per read so bogus size value won't cause out of memory
523 unsigned int nSize = ReadCompactSize(is);
527 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
529 is.read((char*)&v[i], blk * sizeof(T));
534 template<typename Stream, typename T, typename A>
535 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
537 //unsigned int nSize = ReadCompactSize(is);
539 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
540 // Unserialize(is, (*vi), nType, nVersion);
543 unsigned int nSize = ReadCompactSize(is);
545 unsigned int nMid = 0;
548 nMid += 5000000 / sizeof(T);
552 for (; i < nMid; i++)
553 Unserialize(is, v[i], nType, nVersion);
557 template<typename Stream, typename T, typename A>
558 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
560 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
566 // others derived from vector
568 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
570 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
573 template<typename Stream>
574 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
576 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
579 template<typename Stream>
580 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
582 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
590 template<typename K, typename T>
591 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
593 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
596 template<typename Stream, typename K, typename T>
597 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
599 Serialize(os, item.first, nType, nVersion);
600 Serialize(os, item.second, nType, nVersion);
603 template<typename Stream, typename K, typename T>
604 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
606 Unserialize(is, item.first, nType, nVersion);
607 Unserialize(is, item.second, nType, nVersion);
615 template<typename T0, typename T1, typename T2>
616 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
618 unsigned int nSize = 0;
619 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
620 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
621 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
625 template<typename Stream, typename T0, typename T1, typename T2>
626 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
628 Serialize(os, boost::get<0>(item), nType, nVersion);
629 Serialize(os, boost::get<1>(item), nType, nVersion);
630 Serialize(os, boost::get<2>(item), nType, nVersion);
633 template<typename Stream, typename T0, typename T1, typename T2>
634 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
636 Unserialize(is, boost::get<0>(item), nType, nVersion);
637 Unserialize(is, boost::get<1>(item), nType, nVersion);
638 Unserialize(is, boost::get<2>(item), nType, nVersion);
646 template<typename T0, typename T1, typename T2, typename T3>
647 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
649 unsigned int nSize = 0;
650 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
651 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
652 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
653 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
657 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
658 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
660 Serialize(os, boost::get<0>(item), nType, nVersion);
661 Serialize(os, boost::get<1>(item), nType, nVersion);
662 Serialize(os, boost::get<2>(item), nType, nVersion);
663 Serialize(os, boost::get<3>(item), nType, nVersion);
666 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
667 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
669 Unserialize(is, boost::get<0>(item), nType, nVersion);
670 Unserialize(is, boost::get<1>(item), nType, nVersion);
671 Unserialize(is, boost::get<2>(item), nType, nVersion);
672 Unserialize(is, boost::get<3>(item), nType, nVersion);
680 template<typename K, typename T, typename Pred, typename A>
681 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
683 unsigned int nSize = GetSizeOfCompactSize(m.size());
684 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
685 nSize += GetSerializeSize((*mi), nType, nVersion);
689 template<typename Stream, typename K, typename T, typename Pred, typename A>
690 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
692 WriteCompactSize(os, m.size());
693 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
694 Serialize(os, (*mi), nType, nVersion);
697 template<typename Stream, typename K, typename T, typename Pred, typename A>
698 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
701 unsigned int nSize = ReadCompactSize(is);
702 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
703 for (unsigned int i = 0; i < nSize; i++)
705 std::pair<K, T> item;
706 Unserialize(is, item, nType, nVersion);
707 mi = m.insert(mi, item);
716 template<typename K, typename Pred, typename A>
717 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
719 unsigned int nSize = GetSizeOfCompactSize(m.size());
720 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
721 nSize += GetSerializeSize((*it), nType, nVersion);
725 template<typename Stream, typename K, typename Pred, typename A>
726 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
728 WriteCompactSize(os, m.size());
729 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
730 Serialize(os, (*it), nType, nVersion);
733 template<typename Stream, typename K, typename Pred, typename A>
734 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
737 unsigned int nSize = ReadCompactSize(is);
738 typename std::set<K, Pred, A>::iterator it = m.begin();
739 for (unsigned int i = 0; i < nSize; i++)
742 Unserialize(is, key, nType, nVersion);
743 it = m.insert(it, key);
750 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
752 class CSerActionGetSerializeSize { };
753 class CSerActionSerialize { };
754 class CSerActionUnserialize { };
756 template<typename Stream, typename T>
757 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
759 return ::GetSerializeSize(obj, nType, nVersion);
762 template<typename Stream, typename T>
763 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
765 ::Serialize(s, obj, nType, nVersion);
769 template<typename Stream, typename T>
770 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
772 ::Unserialize(s, obj, nType, nVersion);
776 struct ser_streamplaceholder
791 // Allocator that locks its contents from being paged
792 // out of memory and clears its contents before deletion.
795 struct secure_allocator : public std::allocator<T>
797 // MSVC8 default copy constructor is broken
798 typedef std::allocator<T> base;
799 typedef typename base::size_type size_type;
800 typedef typename base::difference_type difference_type;
801 typedef typename base::pointer pointer;
802 typedef typename base::const_pointer const_pointer;
803 typedef typename base::reference reference;
804 typedef typename base::const_reference const_reference;
805 typedef typename base::value_type value_type;
806 secure_allocator() throw() {}
807 secure_allocator(const secure_allocator& a) throw() : base(a) {}
808 template <typename U>
809 secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
810 ~secure_allocator() throw() {}
811 template<typename _Other> struct rebind
812 { typedef secure_allocator<_Other> other; };
814 T* allocate(std::size_t n, const void *hint = 0)
817 p = std::allocator<T>::allocate(n, hint);
819 mlock(p, sizeof(T) * n);
823 void deallocate(T* p, std::size_t n)
827 memset(p, 0, sizeof(T) * n);
828 munlock(p, sizeof(T) * n);
830 std::allocator<T>::deallocate(p, n);
836 // Allocator that clears its contents before deletion.
839 struct zero_after_free_allocator : public std::allocator<T>
841 // MSVC8 default copy constructor is broken
842 typedef std::allocator<T> base;
843 typedef typename base::size_type size_type;
844 typedef typename base::difference_type difference_type;
845 typedef typename base::pointer pointer;
846 typedef typename base::const_pointer const_pointer;
847 typedef typename base::reference reference;
848 typedef typename base::const_reference const_reference;
849 typedef typename base::value_type value_type;
850 zero_after_free_allocator() throw() {}
851 zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
852 template <typename U>
853 zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a) {}
854 ~zero_after_free_allocator() throw() {}
855 template<typename _Other> struct rebind
856 { typedef zero_after_free_allocator<_Other> other; };
858 void deallocate(T* p, std::size_t n)
861 memset(p, 0, sizeof(T) * n);
862 std::allocator<T>::deallocate(p, n);
869 // Double ended buffer combining vector and stream-like interfaces.
870 // >> and << read and write unformatted data using the above serialization templates.
871 // Fills with data in linear time; some stringstream implementations take N^2 time.
876 typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
878 unsigned int nReadPos;
885 typedef vector_type::allocator_type allocator_type;
886 typedef vector_type::size_type size_type;
887 typedef vector_type::difference_type difference_type;
888 typedef vector_type::reference reference;
889 typedef vector_type::const_reference const_reference;
890 typedef vector_type::value_type value_type;
891 typedef vector_type::iterator iterator;
892 typedef vector_type::const_iterator const_iterator;
893 typedef vector_type::reverse_iterator reverse_iterator;
895 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
897 Init(nTypeIn, nVersionIn);
900 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
902 Init(nTypeIn, nVersionIn);
905 #if !defined(_MSC_VER) || _MSC_VER >= 1300
906 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
908 Init(nTypeIn, nVersionIn);
912 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
914 Init(nTypeIn, nVersionIn);
917 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
919 Init(nTypeIn, nVersionIn);
922 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
924 Init(nTypeIn, nVersionIn);
927 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
931 nVersion = nVersionIn;
933 exceptmask = std::ios::badbit | std::ios::failbit;
936 CDataStream& operator+=(const CDataStream& b)
938 vch.insert(vch.end(), b.begin(), b.end());
942 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
949 std::string str() const
951 return (std::string(begin(), end()));
958 const_iterator begin() const { return vch.begin() + nReadPos; }
959 iterator begin() { return vch.begin() + nReadPos; }
960 const_iterator end() const { return vch.end(); }
961 iterator end() { return vch.end(); }
962 size_type size() const { return vch.size() - nReadPos; }
963 bool empty() const { return vch.size() == nReadPos; }
964 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
965 void reserve(size_type n) { vch.reserve(n + nReadPos); }
966 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
967 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
968 void clear() { vch.clear(); nReadPos = 0; }
969 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
970 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
972 void insert(iterator it, const_iterator first, const_iterator last)
974 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
976 // special case for inserting at the front when there's room
977 nReadPos -= (last - first);
978 memcpy(&vch[nReadPos], &first[0], last - first);
981 vch.insert(it, first, last);
984 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
986 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
988 // special case for inserting at the front when there's room
989 nReadPos -= (last - first);
990 memcpy(&vch[nReadPos], &first[0], last - first);
993 vch.insert(it, first, last);
996 #if !defined(_MSC_VER) || _MSC_VER >= 1300
997 void insert(iterator it, const char* first, const char* last)
999 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
1001 // special case for inserting at the front when there's room
1002 nReadPos -= (last - first);
1003 memcpy(&vch[nReadPos], &first[0], last - first);
1006 vch.insert(it, first, last);
1010 iterator erase(iterator it)
1012 if (it == vch.begin() + nReadPos)
1014 // special case for erasing from the front
1015 if (++nReadPos >= vch.size())
1017 // whenever we reach the end, we take the opportunity to clear the buffer
1019 return vch.erase(vch.begin(), vch.end());
1021 return vch.begin() + nReadPos;
1024 return vch.erase(it);
1027 iterator erase(iterator first, iterator last)
1029 if (first == vch.begin() + nReadPos)
1031 // special case for erasing from the front
1032 if (last == vch.end())
1035 return vch.erase(vch.begin(), vch.end());
1039 nReadPos = (last - vch.begin());
1044 return vch.erase(first, last);
1047 inline void Compact()
1049 vch.erase(vch.begin(), vch.begin() + nReadPos);
1053 bool Rewind(size_type n)
1055 // Rewind by n characters if the buffer hasn't been compacted yet
1066 void setstate(short bits, const char* psz)
1069 if (state & exceptmask)
1070 throw std::ios_base::failure(psz);
1073 bool eof() const { return size() == 0; }
1074 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1075 bool good() const { return !eof() && (state == 0); }
1076 void clear(short n) { state = n; } // name conflict with vector clear()
1077 short exceptions() { return exceptmask; }
1078 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1079 CDataStream* rdbuf() { return this; }
1080 int in_avail() { return size(); }
1082 void SetType(int n) { nType = n; }
1083 int GetType() { return nType; }
1084 void SetVersion(int n) { nVersion = n; }
1085 int GetVersion() { return nVersion; }
1086 void ReadVersion() { *this >> nVersion; }
1087 void WriteVersion() { *this << nVersion; }
1089 CDataStream& read(char* pch, int nSize)
1091 // Read from the beginning of the buffer
1093 unsigned int nReadPosNext = nReadPos + nSize;
1094 if (nReadPosNext >= vch.size())
1096 if (nReadPosNext > vch.size())
1098 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1099 memset(pch, 0, nSize);
1100 nSize = vch.size() - nReadPos;
1102 memcpy(pch, &vch[nReadPos], nSize);
1107 memcpy(pch, &vch[nReadPos], nSize);
1108 nReadPos = nReadPosNext;
1112 CDataStream& ignore(int nSize)
1114 // Ignore from the beginning of the buffer
1116 unsigned int nReadPosNext = nReadPos + nSize;
1117 if (nReadPosNext >= vch.size())
1119 if (nReadPosNext > vch.size())
1121 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1122 nSize = vch.size() - nReadPos;
1128 nReadPos = nReadPosNext;
1132 CDataStream& write(const char* pch, int nSize)
1134 // Write to the end of the buffer
1136 vch.insert(vch.end(), pch, pch + nSize);
1140 template<typename Stream>
1141 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const
1143 // Special case: stream << stream concatenates like stream += stream
1145 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1148 template<typename T>
1149 unsigned int GetSerializeSize(const T& obj)
1151 // Tells the size of the object if serialized to this stream
1152 return ::GetSerializeSize(obj, nType, nVersion);
1155 template<typename T>
1156 CDataStream& operator<<(const T& obj)
1158 // Serialize to this stream
1159 ::Serialize(*this, obj, nType, nVersion);
1163 template<typename T>
1164 CDataStream& operator>>(T& obj)
1166 // Unserialize from this stream
1167 ::Unserialize(*this, obj, nType, nVersion);
1172 #ifdef TESTCDATASTREAM
1179 // n=16000 0 seconds
1180 // n=32000 0 seconds
1181 // n=64000 1 seconds
1182 // n=128000 1 seconds
1183 // n=256000 2 seconds
1184 // n=512000 4 seconds
1185 // n=1024000 8 seconds
1186 // n=2048000 16 seconds
1187 // n=4096000 32 seconds
1191 // n=4000 13 seconds
1192 // n=8000 87 seconds
1193 // n=16000 400 seconds
1194 // n=32000 1660 seconds
1195 // n=64000 6749 seconds
1196 // n=128000 27241 seconds
1197 // n=256000 109804 seconds
1199 int main(int argc, char *argv[])
1201 vector<unsigned char> vch(0xcc, 250);
1202 printf("CDataStream:\n");
1203 for (int n = 1000; n <= 4500000; n *= 2)
1206 time_t nStart = time(NULL);
1207 for (int i = 0; i < n; i++)
1208 ss.write((char*)&vch[0], vch.size());
1209 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1211 printf("stringstream:\n");
1212 for (int n = 1000; n <= 4500000; n *= 2)
1215 time_t nStart = time(NULL);
1216 for (int i = 0; i < n; i++)
1217 ss.write((char*)&vch[0], vch.size());
1218 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1233 // Automatic closing wrapper for FILE*
1234 // - Will automatically close the file when it goes out of scope if not null.
1235 // - If you're returning the file pointer, return file.release().
1236 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1248 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)
1252 nVersion = nVersionIn;
1254 exceptmask = std::ios::badbit | std::ios::failbit;
1264 if (file != NULL && file != stdin && file != stdout && file != stderr)
1269 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1270 operator FILE*() { return file; }
1271 FILE* operator->() { return file; }
1272 FILE& operator*() { return *file; }
1273 FILE** operator&() { return &file; }
1274 FILE* operator=(FILE* pnew) { return file = pnew; }
1275 bool operator!() { return (file == NULL); }
1281 void setstate(short bits, const char* psz)
1284 if (state & exceptmask)
1285 throw std::ios_base::failure(psz);
1288 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1289 bool good() const { return state == 0; }
1290 void clear(short n = 0) { state = n; }
1291 short exceptions() { return exceptmask; }
1292 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1294 void SetType(int n) { nType = n; }
1295 int GetType() { return nType; }
1296 void SetVersion(int n) { nVersion = n; }
1297 int GetVersion() { return nVersion; }
1298 void ReadVersion() { *this >> nVersion; }
1299 void WriteVersion() { *this << nVersion; }
1301 CAutoFile& read(char* pch, int nSize)
1304 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1305 if (fread(pch, 1, nSize, file) != nSize)
1306 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1310 CAutoFile& write(const char* pch, int nSize)
1313 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1314 if (fwrite(pch, 1, nSize, file) != nSize)
1315 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1319 template<typename T>
1320 unsigned int GetSerializeSize(const T& obj)
1322 // Tells the size of the object if serialized to this stream
1323 return ::GetSerializeSize(obj, nType, nVersion);
1326 template<typename T>
1327 CAutoFile& operator<<(const T& obj)
1329 // Serialize to this stream
1331 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1332 ::Serialize(*this, obj, nType, nVersion);
1336 template<typename T>
1337 CAutoFile& operator>>(T& obj)
1339 // Unserialize from this stream
1341 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1342 ::Unserialize(*this, obj, nType, nVersion);