1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Copyright (c) 2012 The PPCoin developers
4 // Distributed under the MIT/X11 software license, see the accompanying
5 // file license.txt 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 #if defined(_MSC_VER) || defined(__BORLANDC__)
24 typedef __int64 int64;
25 typedef unsigned __int64 uint64;
27 typedef long long int64;
28 typedef unsigned long long uint64;
30 #if defined(_MSC_VER) && _MSC_VER < 1300
31 #define for if (false) ; else for
36 // This is used to attempt to keep keying material out of swap
37 // Note that VirtualLock does not provide this as a guarantee on Windows,
38 // but, in practice, memory that has been VirtualLock'd almost never gets written to
39 // the pagefile except in rare circumstances where memory is extremely low.
41 #define mlock(p, n) VirtualLock((p), (n));
42 #define munlock(p, n) VirtualUnlock((p), (n));
46 /* This comes from limits.h if it's not defined there set a sane default */
49 #define PAGESIZE sysconf(_SC_PAGESIZE)
52 mlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
53 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
54 #define munlock(a,b) \
55 munlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
56 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
62 static const unsigned int MAX_SIZE = 0x02000000;
64 static const int VERSION = 50100;
65 static const char* pszSubVer = "";
66 static const bool VERSION_IS_BETA = true;
68 // Used to bypass the rule against non-const reference to temporary
69 // where it makes sense with wrappers such as CFlatData or CTxDB
71 inline T& REF(const T& val)
73 return const_cast<T&>(val);
76 /////////////////////////////////////////////////////////////////
78 // Templates for serializing to anything that looks like a stream,
79 // i.e. anything that supports .read(char*, int) and .write(char*, int)
85 SER_NETWORK = (1 << 0),
87 SER_GETHASH = (1 << 2),
90 SER_SKIPSIG = (1 << 16),
91 SER_BLOCKHEADERONLY = (1 << 17),
94 #define IMPLEMENT_SERIALIZE(statements) \
95 unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const \
97 CSerActionGetSerializeSize ser_action; \
98 const bool fGetSize = true; \
99 const bool fWrite = false; \
100 const bool fRead = false; \
101 unsigned int nSerSize = 0; \
102 ser_streamplaceholder s; \
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; \
118 template<typename Stream> \
119 void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) \
121 CSerActionUnserialize ser_action; \
122 const bool fGetSize = false; \
123 const bool fWrite = false; \
124 const bool fRead = true; \
125 unsigned int nSerSize = 0; \
129 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
139 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
140 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
142 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
143 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
144 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
145 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
146 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
147 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
148 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
149 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
150 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
151 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
152 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
153 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
154 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
156 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
157 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
158 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
159 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
160 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
161 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
162 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
163 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
164 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
165 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
166 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
167 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
168 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
170 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
171 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
172 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
173 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
174 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
175 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
176 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
177 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
178 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
179 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
180 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
181 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
182 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
184 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
185 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
186 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
190 #ifndef THROW_WITH_STACKTRACE
191 #define THROW_WITH_STACKTRACE(exception) \
196 void LogStackTrace();
201 // size < 253 -- 1 byte
202 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
203 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
204 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
206 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
208 if (nSize < 253) return sizeof(unsigned char);
209 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);
210 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);
211 else return sizeof(unsigned char) + sizeof(uint64);
214 template<typename Stream>
215 void WriteCompactSize(Stream& os, uint64 nSize)
219 unsigned char chSize = nSize;
220 WRITEDATA(os, chSize);
222 else if (nSize <= USHRT_MAX)
224 unsigned char chSize = 253;
225 unsigned short xSize = nSize;
226 WRITEDATA(os, chSize);
227 WRITEDATA(os, xSize);
229 else if (nSize <= UINT_MAX)
231 unsigned char chSize = 254;
232 unsigned int xSize = nSize;
233 WRITEDATA(os, chSize);
234 WRITEDATA(os, xSize);
238 unsigned char chSize = 255;
239 uint64 xSize = nSize;
240 WRITEDATA(os, chSize);
241 WRITEDATA(os, xSize);
246 template<typename Stream>
247 uint64 ReadCompactSize(Stream& is)
249 unsigned char chSize;
250 READDATA(is, chSize);
256 else if (chSize == 253)
258 unsigned short xSize;
262 else if (chSize == 254)
274 if (nSizeRet > (uint64)MAX_SIZE)
275 THROW_WITH_STACKTRACE(std::ios_base::failure("ReadCompactSize() : size too large"));
282 // Wrapper for serializing arrays and POD
283 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
285 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
292 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
293 char* begin() { return pbegin; }
294 const char* begin() const { return pbegin; }
295 char* end() { return pend; }
296 const char* end() const { return pend; }
298 unsigned int GetSerializeSize(int, int=0) const
300 return pend - pbegin;
303 template<typename Stream>
304 void Serialize(Stream& s, int, int=0) const
306 s.write(pbegin, pend - pbegin);
309 template<typename Stream>
310 void Unserialize(Stream& s, int, int=0)
312 s.read(pbegin, pend - pbegin);
319 // string stored as a fixed length field
321 template<std::size_t LEN>
322 class CFixedFieldString
325 const std::string* pcstr;
328 explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
329 explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
331 unsigned int GetSerializeSize(int, int=0) const
336 template<typename Stream>
337 void Serialize(Stream& s, int, int=0) const
340 strncpy(pszBuf, pcstr->c_str(), LEN);
341 s.write(pszBuf, LEN);
344 template<typename Stream>
345 void Unserialize(Stream& s, int, int=0)
348 THROW_WITH_STACKTRACE(std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string"));
361 // Forward declarations
365 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
366 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
367 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
370 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
371 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
372 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);
373 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&);
374 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&);
375 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);
376 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&);
377 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&);
378 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);
380 // others derived from vector
381 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);
382 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);
383 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);
386 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);
387 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);
388 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);
391 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
392 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);
393 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
396 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);
397 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);
398 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);
401 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);
402 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);
403 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);
406 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
407 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);
408 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
415 // If none of the specialized versions above matched, default to calling member function.
416 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
417 // The compiler will only cast int to long if none of the other templates matched.
418 // Thanks to Boost serialization for this idea.
421 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)
423 return a.GetSerializeSize((int)nType, nVersion);
426 template<typename Stream, typename T>
427 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)
429 a.Serialize(os, (int)nType, nVersion);
432 template<typename Stream, typename T>
433 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)
435 a.Unserialize(is, (int)nType, nVersion);
446 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
448 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
451 template<typename Stream, typename C>
452 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
454 WriteCompactSize(os, str.size());
456 os.write((char*)&str[0], str.size() * sizeof(str[0]));
459 template<typename Stream, typename C>
460 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
462 unsigned int nSize = ReadCompactSize(is);
465 is.read((char*)&str[0], nSize * sizeof(str[0]));
473 template<typename T, typename A>
474 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
476 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
479 template<typename T, typename A>
480 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
482 unsigned int nSize = GetSizeOfCompactSize(v.size());
483 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
484 nSize += GetSerializeSize((*vi), nType, nVersion);
488 template<typename T, typename A>
489 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
491 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
495 template<typename Stream, typename T, typename A>
496 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
498 WriteCompactSize(os, v.size());
500 os.write((char*)&v[0], v.size() * sizeof(T));
503 template<typename Stream, typename T, typename A>
504 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
506 WriteCompactSize(os, v.size());
507 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
508 ::Serialize(os, (*vi), nType, nVersion);
511 template<typename Stream, typename T, typename A>
512 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
514 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
518 template<typename Stream, typename T, typename A>
519 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
521 //unsigned int nSize = ReadCompactSize(is);
523 //is.read((char*)&v[0], nSize * sizeof(T));
525 // Limit size per read so bogus size value won't cause out of memory
527 unsigned int nSize = ReadCompactSize(is);
531 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
533 is.read((char*)&v[i], blk * sizeof(T));
538 template<typename Stream, typename T, typename A>
539 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
541 //unsigned int nSize = ReadCompactSize(is);
543 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
544 // Unserialize(is, (*vi), nType, nVersion);
547 unsigned int nSize = ReadCompactSize(is);
549 unsigned int nMid = 0;
552 nMid += 5000000 / sizeof(T);
556 for (; i < nMid; i++)
557 Unserialize(is, v[i], nType, nVersion);
561 template<typename Stream, typename T, typename A>
562 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
564 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
570 // others derived from vector
572 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
574 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
577 template<typename Stream>
578 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
580 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
583 template<typename Stream>
584 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
586 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
594 template<typename K, typename T>
595 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
597 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
600 template<typename Stream, typename K, typename T>
601 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
603 Serialize(os, item.first, nType, nVersion);
604 Serialize(os, item.second, nType, nVersion);
607 template<typename Stream, typename K, typename T>
608 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
610 Unserialize(is, item.first, nType, nVersion);
611 Unserialize(is, item.second, nType, nVersion);
619 template<typename T0, typename T1, typename T2>
620 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
622 unsigned int nSize = 0;
623 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
624 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
625 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
629 template<typename Stream, typename T0, typename T1, typename T2>
630 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
632 Serialize(os, boost::get<0>(item), nType, nVersion);
633 Serialize(os, boost::get<1>(item), nType, nVersion);
634 Serialize(os, boost::get<2>(item), nType, nVersion);
637 template<typename Stream, typename T0, typename T1, typename T2>
638 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
640 Unserialize(is, boost::get<0>(item), nType, nVersion);
641 Unserialize(is, boost::get<1>(item), nType, nVersion);
642 Unserialize(is, boost::get<2>(item), nType, nVersion);
650 template<typename T0, typename T1, typename T2, typename T3>
651 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
653 unsigned int nSize = 0;
654 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
655 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
656 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
657 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
661 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
662 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
664 Serialize(os, boost::get<0>(item), nType, nVersion);
665 Serialize(os, boost::get<1>(item), nType, nVersion);
666 Serialize(os, boost::get<2>(item), nType, nVersion);
667 Serialize(os, boost::get<3>(item), nType, nVersion);
670 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
671 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
673 Unserialize(is, boost::get<0>(item), nType, nVersion);
674 Unserialize(is, boost::get<1>(item), nType, nVersion);
675 Unserialize(is, boost::get<2>(item), nType, nVersion);
676 Unserialize(is, boost::get<3>(item), nType, nVersion);
684 template<typename K, typename T, typename Pred, typename A>
685 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
687 unsigned int nSize = GetSizeOfCompactSize(m.size());
688 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
689 nSize += GetSerializeSize((*mi), nType, nVersion);
693 template<typename Stream, typename K, typename T, typename Pred, typename A>
694 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
696 WriteCompactSize(os, m.size());
697 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
698 Serialize(os, (*mi), nType, nVersion);
701 template<typename Stream, typename K, typename T, typename Pred, typename A>
702 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
705 unsigned int nSize = ReadCompactSize(is);
706 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
707 for (unsigned int i = 0; i < nSize; i++)
709 std::pair<K, T> item;
710 Unserialize(is, item, nType, nVersion);
711 mi = m.insert(mi, item);
720 template<typename K, typename Pred, typename A>
721 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
723 unsigned int nSize = GetSizeOfCompactSize(m.size());
724 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
725 nSize += GetSerializeSize((*it), nType, nVersion);
729 template<typename Stream, typename K, typename Pred, typename A>
730 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
732 WriteCompactSize(os, m.size());
733 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
734 Serialize(os, (*it), nType, nVersion);
737 template<typename Stream, typename K, typename Pred, typename A>
738 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
741 unsigned int nSize = ReadCompactSize(is);
742 typename std::set<K, Pred, A>::iterator it = m.begin();
743 for (unsigned int i = 0; i < nSize; i++)
746 Unserialize(is, key, nType, nVersion);
747 it = m.insert(it, key);
754 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
756 class CSerActionGetSerializeSize { };
757 class CSerActionSerialize { };
758 class CSerActionUnserialize { };
760 template<typename Stream, typename T>
761 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
763 return ::GetSerializeSize(obj, nType, nVersion);
766 template<typename Stream, typename T>
767 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
769 ::Serialize(s, obj, nType, nVersion);
773 template<typename Stream, typename T>
774 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
776 ::Unserialize(s, obj, nType, nVersion);
780 struct ser_streamplaceholder
795 // Allocator that locks its contents from being paged
796 // out of memory and clears its contents before deletion.
799 struct secure_allocator : public std::allocator<T>
801 // MSVC8 default copy constructor is broken
802 typedef std::allocator<T> base;
803 typedef typename base::size_type size_type;
804 typedef typename base::difference_type difference_type;
805 typedef typename base::pointer pointer;
806 typedef typename base::const_pointer const_pointer;
807 typedef typename base::reference reference;
808 typedef typename base::const_reference const_reference;
809 typedef typename base::value_type value_type;
810 secure_allocator() throw() {}
811 secure_allocator(const secure_allocator& a) throw() : base(a) {}
812 template <typename U>
813 secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
814 ~secure_allocator() throw() {}
815 template<typename _Other> struct rebind
816 { typedef secure_allocator<_Other> other; };
818 T* allocate(std::size_t n, const void *hint = 0)
821 p = std::allocator<T>::allocate(n, hint);
823 mlock(p, sizeof(T) * n);
827 void deallocate(T* p, std::size_t n)
831 memset(p, 0, sizeof(T) * n);
832 munlock(p, sizeof(T) * n);
834 std::allocator<T>::deallocate(p, n);
841 // Double ended buffer combining vector and stream-like interfaces.
842 // >> and << read and write unformatted data using the above serialization templates.
843 // Fills with data in linear time; some stringstream implementations take N^2 time.
848 typedef std::vector<char, secure_allocator<char> > vector_type;
850 unsigned int nReadPos;
857 typedef vector_type::allocator_type allocator_type;
858 typedef vector_type::size_type size_type;
859 typedef vector_type::difference_type difference_type;
860 typedef vector_type::reference reference;
861 typedef vector_type::const_reference const_reference;
862 typedef vector_type::value_type value_type;
863 typedef vector_type::iterator iterator;
864 typedef vector_type::const_iterator const_iterator;
865 typedef vector_type::reverse_iterator reverse_iterator;
867 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
869 Init(nTypeIn, nVersionIn);
872 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
874 Init(nTypeIn, nVersionIn);
877 #if !defined(_MSC_VER) || _MSC_VER >= 1300
878 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
880 Init(nTypeIn, nVersionIn);
884 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
886 Init(nTypeIn, nVersionIn);
889 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
891 Init(nTypeIn, nVersionIn);
894 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
896 Init(nTypeIn, nVersionIn);
899 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
903 nVersion = nVersionIn;
905 exceptmask = std::ios::badbit | std::ios::failbit;
908 CDataStream& operator+=(const CDataStream& b)
910 vch.insert(vch.end(), b.begin(), b.end());
914 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
921 std::string str() const
923 return (std::string(begin(), end()));
930 const_iterator begin() const { return vch.begin() + nReadPos; }
931 iterator begin() { return vch.begin() + nReadPos; }
932 const_iterator end() const { return vch.end(); }
933 iterator end() { return vch.end(); }
934 size_type size() const { return vch.size() - nReadPos; }
935 bool empty() const { return vch.size() == nReadPos; }
936 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
937 void reserve(size_type n) { vch.reserve(n + nReadPos); }
938 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
939 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
940 void clear() { vch.clear(); nReadPos = 0; }
941 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
942 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
944 void insert(iterator it, const_iterator first, const_iterator last)
946 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
948 // special case for inserting at the front when there's room
949 nReadPos -= (last - first);
950 memcpy(&vch[nReadPos], &first[0], last - first);
953 vch.insert(it, first, last);
956 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
958 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
960 // special case for inserting at the front when there's room
961 nReadPos -= (last - first);
962 memcpy(&vch[nReadPos], &first[0], last - first);
965 vch.insert(it, first, last);
968 #if !defined(_MSC_VER) || _MSC_VER >= 1300
969 void insert(iterator it, const char* first, const char* last)
971 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
973 // special case for inserting at the front when there's room
974 nReadPos -= (last - first);
975 memcpy(&vch[nReadPos], &first[0], last - first);
978 vch.insert(it, first, last);
982 iterator erase(iterator it)
984 if (it == vch.begin() + nReadPos)
986 // special case for erasing from the front
987 if (++nReadPos >= vch.size())
989 // whenever we reach the end, we take the opportunity to clear the buffer
991 return vch.erase(vch.begin(), vch.end());
993 return vch.begin() + nReadPos;
996 return vch.erase(it);
999 iterator erase(iterator first, iterator last)
1001 if (first == vch.begin() + nReadPos)
1003 // special case for erasing from the front
1004 if (last == vch.end())
1007 return vch.erase(vch.begin(), vch.end());
1011 nReadPos = (last - vch.begin());
1016 return vch.erase(first, last);
1019 inline void Compact()
1021 vch.erase(vch.begin(), vch.begin() + nReadPos);
1025 bool Rewind(size_type n)
1027 // Rewind by n characters if the buffer hasn't been compacted yet
1038 void setstate(short bits, const char* psz)
1041 if (state & exceptmask)
1042 THROW_WITH_STACKTRACE(std::ios_base::failure(psz));
1045 bool eof() const { return size() == 0; }
1046 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1047 bool good() const { return !eof() && (state == 0); }
1048 void clear(short n) { state = n; } // name conflict with vector clear()
1049 short exceptions() { return exceptmask; }
1050 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1051 CDataStream* rdbuf() { return this; }
1052 int in_avail() { return size(); }
1054 void SetType(int n) { nType = n; }
1055 int GetType() { return nType; }
1056 void SetVersion(int n) { nVersion = n; }
1057 int GetVersion() { return nVersion; }
1058 void ReadVersion() { *this >> nVersion; }
1059 void WriteVersion() { *this << nVersion; }
1061 CDataStream& read(char* pch, int nSize)
1063 // Read from the beginning of the buffer
1065 unsigned int nReadPosNext = nReadPos + nSize;
1066 if (nReadPosNext >= vch.size())
1068 if (nReadPosNext > vch.size())
1070 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1071 memset(pch, 0, nSize);
1072 nSize = vch.size() - nReadPos;
1074 memcpy(pch, &vch[nReadPos], nSize);
1079 memcpy(pch, &vch[nReadPos], nSize);
1080 nReadPos = nReadPosNext;
1084 CDataStream& ignore(int nSize)
1086 // Ignore from the beginning of the buffer
1088 unsigned int nReadPosNext = nReadPos + nSize;
1089 if (nReadPosNext >= vch.size())
1091 if (nReadPosNext > vch.size())
1093 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1094 nSize = vch.size() - nReadPos;
1100 nReadPos = nReadPosNext;
1104 CDataStream& write(const char* pch, int nSize)
1106 // Write to the end of the buffer
1108 vch.insert(vch.end(), pch, pch + nSize);
1112 template<typename Stream>
1113 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const
1115 // Special case: stream << stream concatenates like stream += stream
1117 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1120 template<typename T>
1121 unsigned int GetSerializeSize(const T& obj)
1123 // Tells the size of the object if serialized to this stream
1124 return ::GetSerializeSize(obj, nType, nVersion);
1127 template<typename T>
1128 CDataStream& operator<<(const T& obj)
1130 // Serialize to this stream
1131 ::Serialize(*this, obj, nType, nVersion);
1135 template<typename T>
1136 CDataStream& operator>>(T& obj)
1138 // Unserialize from this stream
1139 ::Unserialize(*this, obj, nType, nVersion);
1144 #ifdef TESTCDATASTREAM
1151 // n=16000 0 seconds
1152 // n=32000 0 seconds
1153 // n=64000 1 seconds
1154 // n=128000 1 seconds
1155 // n=256000 2 seconds
1156 // n=512000 4 seconds
1157 // n=1024000 8 seconds
1158 // n=2048000 16 seconds
1159 // n=4096000 32 seconds
1163 // n=4000 13 seconds
1164 // n=8000 87 seconds
1165 // n=16000 400 seconds
1166 // n=32000 1660 seconds
1167 // n=64000 6749 seconds
1168 // n=128000 27241 seconds
1169 // n=256000 109804 seconds
1171 int main(int argc, char *argv[])
1173 vector<unsigned char> vch(0xcc, 250);
1174 printf("CDataStream:\n");
1175 for (int n = 1000; n <= 4500000; n *= 2)
1178 time_t nStart = time(NULL);
1179 for (int i = 0; i < n; i++)
1180 ss.write((char*)&vch[0], vch.size());
1181 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1183 printf("stringstream:\n");
1184 for (int n = 1000; n <= 4500000; n *= 2)
1187 time_t nStart = time(NULL);
1188 for (int i = 0; i < n; i++)
1189 ss.write((char*)&vch[0], vch.size());
1190 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1205 // Automatic closing wrapper for FILE*
1206 // - Will automatically close the file when it goes out of scope if not null.
1207 // - If you're returning the file pointer, return file.release().
1208 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1220 typedef FILE element_type;
1222 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)
1226 nVersion = nVersionIn;
1228 exceptmask = std::ios::badbit | std::ios::failbit;
1238 if (file != NULL && file != stdin && file != stdout && file != stderr)
1243 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1244 operator FILE*() { return file; }
1245 FILE* operator->() { return file; }
1246 FILE& operator*() { return *file; }
1247 FILE** operator&() { return &file; }
1248 FILE* operator=(FILE* pnew) { return file = pnew; }
1249 bool operator!() { return (file == NULL); }
1255 void setstate(short bits, const char* psz)
1258 if (state & exceptmask)
1259 THROW_WITH_STACKTRACE(std::ios_base::failure(psz));
1262 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1263 bool good() const { return state == 0; }
1264 void clear(short n = 0) { state = n; }
1265 short exceptions() { return exceptmask; }
1266 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1268 void SetType(int n) { nType = n; }
1269 int GetType() { return nType; }
1270 void SetVersion(int n) { nVersion = n; }
1271 int GetVersion() { return nVersion; }
1272 void ReadVersion() { *this >> nVersion; }
1273 void WriteVersion() { *this << nVersion; }
1275 CAutoFile& read(char* pch, int nSize)
1278 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1279 if (fread(pch, 1, nSize, file) != nSize)
1280 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1284 CAutoFile& write(const char* pch, int nSize)
1287 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1288 if (fwrite(pch, 1, nSize, file) != nSize)
1289 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1293 template<typename T>
1294 unsigned int GetSerializeSize(const T& obj)
1296 // Tells the size of the object if serialized to this stream
1297 return ::GetSerializeSize(obj, nType, nVersion);
1300 template<typename T>
1301 CAutoFile& operator<<(const T& obj)
1303 // Serialize to this stream
1305 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1306 ::Serialize(*this, obj, nType, nVersion);
1310 template<typename T>
1311 CAutoFile& operator>>(T& obj)
1313 // Unserialize from this stream
1315 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1316 ::Unserialize(*this, obj, nType, nVersion);