1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 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 #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 = 50100;
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; \
103 s.nVersion = nVersion; \
107 template<typename Stream> \
108 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const \
110 CSerActionSerialize ser_action; \
111 const bool fGetSize = false; \
112 const bool fWrite = true; \
113 const bool fRead = false; \
114 unsigned int nSerSize = 0; \
117 template<typename Stream> \
118 void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) \
120 CSerActionUnserialize ser_action; \
121 const bool fGetSize = false; \
122 const bool fWrite = false; \
123 const bool fRead = true; \
124 unsigned int nSerSize = 0; \
128 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
138 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
139 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
141 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
142 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
143 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
144 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
145 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
146 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
147 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
148 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
149 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
150 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
151 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
152 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
153 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
155 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
156 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
157 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
158 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
159 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
160 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
161 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
162 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
163 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
164 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
165 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
166 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
167 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
169 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
170 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
171 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
172 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
173 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
174 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
175 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
176 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
177 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
178 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
179 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
180 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
181 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
183 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
184 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
185 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
194 // size < 253 -- 1 byte
195 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
196 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
197 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
199 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
201 if (nSize < 253) return sizeof(unsigned char);
202 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);
203 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);
204 else return sizeof(unsigned char) + sizeof(uint64);
207 template<typename Stream>
208 void WriteCompactSize(Stream& os, uint64 nSize)
212 unsigned char chSize = nSize;
213 WRITEDATA(os, chSize);
215 else if (nSize <= USHRT_MAX)
217 unsigned char chSize = 253;
218 unsigned short xSize = nSize;
219 WRITEDATA(os, chSize);
220 WRITEDATA(os, xSize);
222 else if (nSize <= UINT_MAX)
224 unsigned char chSize = 254;
225 unsigned int xSize = nSize;
226 WRITEDATA(os, chSize);
227 WRITEDATA(os, xSize);
231 unsigned char chSize = 255;
232 uint64 xSize = nSize;
233 WRITEDATA(os, chSize);
234 WRITEDATA(os, xSize);
239 template<typename Stream>
240 uint64 ReadCompactSize(Stream& is)
242 unsigned char chSize;
243 READDATA(is, chSize);
249 else if (chSize == 253)
251 unsigned short xSize;
255 else if (chSize == 254)
267 if (nSizeRet > (uint64)MAX_SIZE)
268 throw std::ios_base::failure("ReadCompactSize() : size too large");
275 // Wrapper for serializing arrays and POD
276 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
278 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
285 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
286 char* begin() { return pbegin; }
287 const char* begin() const { return pbegin; }
288 char* end() { return pend; }
289 const char* end() const { return pend; }
291 unsigned int GetSerializeSize(int, int=0) const
293 return pend - pbegin;
296 template<typename Stream>
297 void Serialize(Stream& s, int, int=0) const
299 s.write(pbegin, pend - pbegin);
302 template<typename Stream>
303 void Unserialize(Stream& s, int, int=0)
305 s.read(pbegin, pend - pbegin);
312 // string stored as a fixed length field
314 template<std::size_t LEN>
315 class CFixedFieldString
318 const std::string* pcstr;
321 explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
322 explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
324 unsigned int GetSerializeSize(int, int=0) const
329 template<typename Stream>
330 void Serialize(Stream& s, int, int=0) const
333 strncpy(pszBuf, pcstr->c_str(), LEN);
334 s.write(pszBuf, LEN);
337 template<typename Stream>
338 void Unserialize(Stream& s, int, int=0)
341 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
354 // Forward declarations
358 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
359 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
360 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
363 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
364 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
365 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);
366 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&);
367 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&);
368 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);
369 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&);
370 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&);
371 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);
373 // others derived from vector
374 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);
375 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);
376 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);
379 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);
380 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);
381 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);
384 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
385 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);
386 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
389 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);
390 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);
391 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);
394 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);
395 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);
396 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);
399 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
400 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);
401 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
408 // If none of the specialized versions above matched, default to calling member function.
409 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
410 // The compiler will only cast int to long if none of the other templates matched.
411 // Thanks to Boost serialization for this idea.
414 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)
416 return a.GetSerializeSize((int)nType, nVersion);
419 template<typename Stream, typename T>
420 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)
422 a.Serialize(os, (int)nType, nVersion);
425 template<typename Stream, typename T>
426 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)
428 a.Unserialize(is, (int)nType, nVersion);
439 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
441 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
444 template<typename Stream, typename C>
445 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
447 WriteCompactSize(os, str.size());
449 os.write((char*)&str[0], str.size() * sizeof(str[0]));
452 template<typename Stream, typename C>
453 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
455 unsigned int nSize = ReadCompactSize(is);
458 is.read((char*)&str[0], nSize * sizeof(str[0]));
466 template<typename T, typename A>
467 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
469 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
472 template<typename T, typename A>
473 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
475 unsigned int nSize = GetSizeOfCompactSize(v.size());
476 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
477 nSize += GetSerializeSize((*vi), nType, nVersion);
481 template<typename T, typename A>
482 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
484 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
488 template<typename Stream, typename T, typename A>
489 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
491 WriteCompactSize(os, v.size());
493 os.write((char*)&v[0], v.size() * sizeof(T));
496 template<typename Stream, typename T, typename A>
497 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
499 WriteCompactSize(os, v.size());
500 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
501 ::Serialize(os, (*vi), nType, nVersion);
504 template<typename Stream, typename T, typename A>
505 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
507 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
511 template<typename Stream, typename T, typename A>
512 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
514 //unsigned int nSize = ReadCompactSize(is);
516 //is.read((char*)&v[0], nSize * sizeof(T));
518 // Limit size per read so bogus size value won't cause out of memory
520 unsigned int nSize = ReadCompactSize(is);
524 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
526 is.read((char*)&v[i], blk * sizeof(T));
531 template<typename Stream, typename T, typename A>
532 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
534 //unsigned int nSize = ReadCompactSize(is);
536 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
537 // Unserialize(is, (*vi), nType, nVersion);
540 unsigned int nSize = ReadCompactSize(is);
542 unsigned int nMid = 0;
545 nMid += 5000000 / sizeof(T);
549 for (; i < nMid; i++)
550 Unserialize(is, v[i], nType, nVersion);
554 template<typename Stream, typename T, typename A>
555 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
557 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
563 // others derived from vector
565 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
567 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
570 template<typename Stream>
571 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
573 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
576 template<typename Stream>
577 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
579 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
587 template<typename K, typename T>
588 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
590 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
593 template<typename Stream, typename K, typename T>
594 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
596 Serialize(os, item.first, nType, nVersion);
597 Serialize(os, item.second, nType, nVersion);
600 template<typename Stream, typename K, typename T>
601 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
603 Unserialize(is, item.first, nType, nVersion);
604 Unserialize(is, item.second, nType, nVersion);
612 template<typename T0, typename T1, typename T2>
613 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
615 unsigned int nSize = 0;
616 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
617 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
618 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
622 template<typename Stream, typename T0, typename T1, typename T2>
623 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
625 Serialize(os, boost::get<0>(item), nType, nVersion);
626 Serialize(os, boost::get<1>(item), nType, nVersion);
627 Serialize(os, boost::get<2>(item), nType, nVersion);
630 template<typename Stream, typename T0, typename T1, typename T2>
631 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
633 Unserialize(is, boost::get<0>(item), nType, nVersion);
634 Unserialize(is, boost::get<1>(item), nType, nVersion);
635 Unserialize(is, boost::get<2>(item), nType, nVersion);
643 template<typename T0, typename T1, typename T2, typename T3>
644 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
646 unsigned int nSize = 0;
647 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
648 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
649 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
650 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
654 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
655 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
657 Serialize(os, boost::get<0>(item), nType, nVersion);
658 Serialize(os, boost::get<1>(item), nType, nVersion);
659 Serialize(os, boost::get<2>(item), nType, nVersion);
660 Serialize(os, boost::get<3>(item), nType, nVersion);
663 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
664 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
666 Unserialize(is, boost::get<0>(item), nType, nVersion);
667 Unserialize(is, boost::get<1>(item), nType, nVersion);
668 Unserialize(is, boost::get<2>(item), nType, nVersion);
669 Unserialize(is, boost::get<3>(item), nType, nVersion);
677 template<typename K, typename T, typename Pred, typename A>
678 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
680 unsigned int nSize = GetSizeOfCompactSize(m.size());
681 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
682 nSize += GetSerializeSize((*mi), nType, nVersion);
686 template<typename Stream, typename K, typename T, typename Pred, typename A>
687 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
689 WriteCompactSize(os, m.size());
690 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
691 Serialize(os, (*mi), nType, nVersion);
694 template<typename Stream, typename K, typename T, typename Pred, typename A>
695 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
698 unsigned int nSize = ReadCompactSize(is);
699 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
700 for (unsigned int i = 0; i < nSize; i++)
702 std::pair<K, T> item;
703 Unserialize(is, item, nType, nVersion);
704 mi = m.insert(mi, item);
713 template<typename K, typename Pred, typename A>
714 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
716 unsigned int nSize = GetSizeOfCompactSize(m.size());
717 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
718 nSize += GetSerializeSize((*it), nType, nVersion);
722 template<typename Stream, typename K, typename Pred, typename A>
723 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
725 WriteCompactSize(os, m.size());
726 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
727 Serialize(os, (*it), nType, nVersion);
730 template<typename Stream, typename K, typename Pred, typename A>
731 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
734 unsigned int nSize = ReadCompactSize(is);
735 typename std::set<K, Pred, A>::iterator it = m.begin();
736 for (unsigned int i = 0; i < nSize; i++)
739 Unserialize(is, key, nType, nVersion);
740 it = m.insert(it, key);
747 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
749 class CSerActionGetSerializeSize { };
750 class CSerActionSerialize { };
751 class CSerActionUnserialize { };
753 template<typename Stream, typename T>
754 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
756 return ::GetSerializeSize(obj, nType, nVersion);
759 template<typename Stream, typename T>
760 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
762 ::Serialize(s, obj, nType, nVersion);
766 template<typename Stream, typename T>
767 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
769 ::Unserialize(s, obj, nType, nVersion);
773 struct ser_streamplaceholder
788 // Allocator that locks its contents from being paged
789 // out of memory and clears its contents before deletion.
792 struct secure_allocator : public std::allocator<T>
794 // MSVC8 default copy constructor is broken
795 typedef std::allocator<T> base;
796 typedef typename base::size_type size_type;
797 typedef typename base::difference_type difference_type;
798 typedef typename base::pointer pointer;
799 typedef typename base::const_pointer const_pointer;
800 typedef typename base::reference reference;
801 typedef typename base::const_reference const_reference;
802 typedef typename base::value_type value_type;
803 secure_allocator() throw() {}
804 secure_allocator(const secure_allocator& a) throw() : base(a) {}
805 template <typename U>
806 secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
807 ~secure_allocator() throw() {}
808 template<typename _Other> struct rebind
809 { typedef secure_allocator<_Other> other; };
811 T* allocate(std::size_t n, const void *hint = 0)
814 p = std::allocator<T>::allocate(n, hint);
816 mlock(p, sizeof(T) * n);
820 void deallocate(T* p, std::size_t n)
824 memset(p, 0, sizeof(T) * n);
825 munlock(p, sizeof(T) * n);
827 std::allocator<T>::deallocate(p, n);
834 // Double ended buffer combining vector and stream-like interfaces.
835 // >> and << read and write unformatted data using the above serialization templates.
836 // Fills with data in linear time; some stringstream implementations take N^2 time.
841 typedef std::vector<char, secure_allocator<char> > vector_type;
843 unsigned int nReadPos;
850 typedef vector_type::allocator_type allocator_type;
851 typedef vector_type::size_type size_type;
852 typedef vector_type::difference_type difference_type;
853 typedef vector_type::reference reference;
854 typedef vector_type::const_reference const_reference;
855 typedef vector_type::value_type value_type;
856 typedef vector_type::iterator iterator;
857 typedef vector_type::const_iterator const_iterator;
858 typedef vector_type::reverse_iterator reverse_iterator;
860 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
862 Init(nTypeIn, nVersionIn);
865 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
867 Init(nTypeIn, nVersionIn);
870 #if !defined(_MSC_VER) || _MSC_VER >= 1300
871 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
873 Init(nTypeIn, nVersionIn);
877 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
879 Init(nTypeIn, nVersionIn);
882 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
884 Init(nTypeIn, nVersionIn);
887 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
889 Init(nTypeIn, nVersionIn);
892 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
896 nVersion = nVersionIn;
898 exceptmask = std::ios::badbit | std::ios::failbit;
901 CDataStream& operator+=(const CDataStream& b)
903 vch.insert(vch.end(), b.begin(), b.end());
907 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
914 std::string str() const
916 return (std::string(begin(), end()));
923 const_iterator begin() const { return vch.begin() + nReadPos; }
924 iterator begin() { return vch.begin() + nReadPos; }
925 const_iterator end() const { return vch.end(); }
926 iterator end() { return vch.end(); }
927 size_type size() const { return vch.size() - nReadPos; }
928 bool empty() const { return vch.size() == nReadPos; }
929 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
930 void reserve(size_type n) { vch.reserve(n + nReadPos); }
931 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
932 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
933 void clear() { vch.clear(); nReadPos = 0; }
934 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
935 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
937 void insert(iterator it, const_iterator first, const_iterator last)
939 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
941 // special case for inserting at the front when there's room
942 nReadPos -= (last - first);
943 memcpy(&vch[nReadPos], &first[0], last - first);
946 vch.insert(it, first, last);
949 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
951 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
953 // special case for inserting at the front when there's room
954 nReadPos -= (last - first);
955 memcpy(&vch[nReadPos], &first[0], last - first);
958 vch.insert(it, first, last);
961 #if !defined(_MSC_VER) || _MSC_VER >= 1300
962 void insert(iterator it, const char* first, const char* last)
964 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
966 // special case for inserting at the front when there's room
967 nReadPos -= (last - first);
968 memcpy(&vch[nReadPos], &first[0], last - first);
971 vch.insert(it, first, last);
975 iterator erase(iterator it)
977 if (it == vch.begin() + nReadPos)
979 // special case for erasing from the front
980 if (++nReadPos >= vch.size())
982 // whenever we reach the end, we take the opportunity to clear the buffer
984 return vch.erase(vch.begin(), vch.end());
986 return vch.begin() + nReadPos;
989 return vch.erase(it);
992 iterator erase(iterator first, iterator last)
994 if (first == vch.begin() + nReadPos)
996 // special case for erasing from the front
997 if (last == vch.end())
1000 return vch.erase(vch.begin(), vch.end());
1004 nReadPos = (last - vch.begin());
1009 return vch.erase(first, last);
1012 inline void Compact()
1014 vch.erase(vch.begin(), vch.begin() + nReadPos);
1018 bool Rewind(size_type n)
1020 // Rewind by n characters if the buffer hasn't been compacted yet
1031 void setstate(short bits, const char* psz)
1034 if (state & exceptmask)
1035 throw std::ios_base::failure(psz);
1038 bool eof() const { return size() == 0; }
1039 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1040 bool good() const { return !eof() && (state == 0); }
1041 void clear(short n) { state = n; } // name conflict with vector clear()
1042 short exceptions() { return exceptmask; }
1043 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1044 CDataStream* rdbuf() { return this; }
1045 int in_avail() { return size(); }
1047 void SetType(int n) { nType = n; }
1048 int GetType() { return nType; }
1049 void SetVersion(int n) { nVersion = n; }
1050 int GetVersion() { return nVersion; }
1051 void ReadVersion() { *this >> nVersion; }
1052 void WriteVersion() { *this << nVersion; }
1054 CDataStream& read(char* pch, int nSize)
1056 // Read from the beginning of the buffer
1058 unsigned int nReadPosNext = nReadPos + nSize;
1059 if (nReadPosNext >= vch.size())
1061 if (nReadPosNext > vch.size())
1063 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1064 memset(pch, 0, nSize);
1065 nSize = vch.size() - nReadPos;
1067 memcpy(pch, &vch[nReadPos], nSize);
1072 memcpy(pch, &vch[nReadPos], nSize);
1073 nReadPos = nReadPosNext;
1077 CDataStream& ignore(int nSize)
1079 // Ignore from the beginning of the buffer
1081 unsigned int nReadPosNext = nReadPos + nSize;
1082 if (nReadPosNext >= vch.size())
1084 if (nReadPosNext > vch.size())
1086 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1087 nSize = vch.size() - nReadPos;
1093 nReadPos = nReadPosNext;
1097 CDataStream& write(const char* pch, int nSize)
1099 // Write to the end of the buffer
1101 vch.insert(vch.end(), pch, pch + nSize);
1105 template<typename Stream>
1106 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const
1108 // Special case: stream << stream concatenates like stream += stream
1110 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1113 template<typename T>
1114 unsigned int GetSerializeSize(const T& obj)
1116 // Tells the size of the object if serialized to this stream
1117 return ::GetSerializeSize(obj, nType, nVersion);
1120 template<typename T>
1121 CDataStream& operator<<(const T& obj)
1123 // Serialize to this stream
1124 ::Serialize(*this, obj, nType, nVersion);
1128 template<typename T>
1129 CDataStream& operator>>(T& obj)
1131 // Unserialize from this stream
1132 ::Unserialize(*this, obj, nType, nVersion);
1137 #ifdef TESTCDATASTREAM
1144 // n=16000 0 seconds
1145 // n=32000 0 seconds
1146 // n=64000 1 seconds
1147 // n=128000 1 seconds
1148 // n=256000 2 seconds
1149 // n=512000 4 seconds
1150 // n=1024000 8 seconds
1151 // n=2048000 16 seconds
1152 // n=4096000 32 seconds
1156 // n=4000 13 seconds
1157 // n=8000 87 seconds
1158 // n=16000 400 seconds
1159 // n=32000 1660 seconds
1160 // n=64000 6749 seconds
1161 // n=128000 27241 seconds
1162 // n=256000 109804 seconds
1164 int main(int argc, char *argv[])
1166 vector<unsigned char> vch(0xcc, 250);
1167 printf("CDataStream:\n");
1168 for (int n = 1000; n <= 4500000; n *= 2)
1171 time_t nStart = time(NULL);
1172 for (int i = 0; i < n; i++)
1173 ss.write((char*)&vch[0], vch.size());
1174 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1176 printf("stringstream:\n");
1177 for (int n = 1000; n <= 4500000; n *= 2)
1180 time_t nStart = time(NULL);
1181 for (int i = 0; i < n; i++)
1182 ss.write((char*)&vch[0], vch.size());
1183 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1198 // Automatic closing wrapper for FILE*
1199 // - Will automatically close the file when it goes out of scope if not null.
1200 // - If you're returning the file pointer, return file.release().
1201 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1213 typedef FILE element_type;
1215 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)
1219 nVersion = nVersionIn;
1221 exceptmask = std::ios::badbit | std::ios::failbit;
1231 if (file != NULL && file != stdin && file != stdout && file != stderr)
1236 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1237 operator FILE*() { return file; }
1238 FILE* operator->() { return file; }
1239 FILE& operator*() { return *file; }
1240 FILE** operator&() { return &file; }
1241 FILE* operator=(FILE* pnew) { return file = pnew; }
1242 bool operator!() { return (file == NULL); }
1248 void setstate(short bits, const char* psz)
1251 if (state & exceptmask)
1252 throw std::ios_base::failure(psz);
1255 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1256 bool good() const { return state == 0; }
1257 void clear(short n = 0) { state = n; }
1258 short exceptions() { return exceptmask; }
1259 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1261 void SetType(int n) { nType = n; }
1262 int GetType() { return nType; }
1263 void SetVersion(int n) { nVersion = n; }
1264 int GetVersion() { return nVersion; }
1265 void ReadVersion() { *this >> nVersion; }
1266 void WriteVersion() { *this << nVersion; }
1268 CAutoFile& read(char* pch, int nSize)
1271 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1272 if (fread(pch, 1, nSize, file) != nSize)
1273 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1277 CAutoFile& write(const char* pch, int nSize)
1280 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1281 if (fwrite(pch, 1, nSize, file) != nSize)
1282 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1286 template<typename T>
1287 unsigned int GetSerializeSize(const T& obj)
1289 // Tells the size of the object if serialized to this stream
1290 return ::GetSerializeSize(obj, nType, nVersion);
1293 template<typename T>
1294 CAutoFile& operator<<(const T& obj)
1296 // Serialize to this stream
1298 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1299 ::Serialize(*this, obj, nType, nVersion);
1303 template<typename T>
1304 CAutoFile& operator>>(T& obj)
1306 // Unserialize from this stream
1308 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1309 ::Unserialize(*this, obj, nType, nVersion);