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 static const int PPCOIN_VERSION = 100;
70 // Used to bypass the rule against non-const reference to temporary
71 // where it makes sense with wrappers such as CFlatData or CTxDB
73 inline T& REF(const T& val)
75 return const_cast<T&>(val);
78 /////////////////////////////////////////////////////////////////
80 // Templates for serializing to anything that looks like a stream,
81 // i.e. anything that supports .read(char*, int) and .write(char*, int)
87 SER_NETWORK = (1 << 0),
89 SER_GETHASH = (1 << 2),
92 SER_SKIPSIG = (1 << 16),
93 SER_BLOCKHEADERONLY = (1 << 17),
96 #define IMPLEMENT_SERIALIZE(statements) \
97 unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const \
99 CSerActionGetSerializeSize ser_action; \
100 const bool fGetSize = true; \
101 const bool fWrite = false; \
102 const bool fRead = false; \
103 unsigned int nSerSize = 0; \
104 ser_streamplaceholder s; \
106 s.nVersion = nVersion; \
110 template<typename Stream> \
111 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const \
113 CSerActionSerialize ser_action; \
114 const bool fGetSize = false; \
115 const bool fWrite = true; \
116 const bool fRead = false; \
117 unsigned int nSerSize = 0; \
120 template<typename Stream> \
121 void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) \
123 CSerActionUnserialize ser_action; \
124 const bool fGetSize = false; \
125 const bool fWrite = false; \
126 const bool fRead = true; \
127 unsigned int nSerSize = 0; \
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; }
192 #ifndef THROW_WITH_STACKTRACE
193 #define THROW_WITH_STACKTRACE(exception) \
198 void LogStackTrace();
203 // size < 253 -- 1 byte
204 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
205 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
206 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
208 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
210 if (nSize < 253) return sizeof(unsigned char);
211 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);
212 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);
213 else return sizeof(unsigned char) + sizeof(uint64);
216 template<typename Stream>
217 void WriteCompactSize(Stream& os, uint64 nSize)
221 unsigned char chSize = nSize;
222 WRITEDATA(os, chSize);
224 else if (nSize <= USHRT_MAX)
226 unsigned char chSize = 253;
227 unsigned short xSize = nSize;
228 WRITEDATA(os, chSize);
229 WRITEDATA(os, xSize);
231 else if (nSize <= UINT_MAX)
233 unsigned char chSize = 254;
234 unsigned int xSize = nSize;
235 WRITEDATA(os, chSize);
236 WRITEDATA(os, xSize);
240 unsigned char chSize = 255;
241 uint64 xSize = nSize;
242 WRITEDATA(os, chSize);
243 WRITEDATA(os, xSize);
248 template<typename Stream>
249 uint64 ReadCompactSize(Stream& is)
251 unsigned char chSize;
252 READDATA(is, chSize);
258 else if (chSize == 253)
260 unsigned short xSize;
264 else if (chSize == 254)
276 if (nSizeRet > (uint64)MAX_SIZE)
277 THROW_WITH_STACKTRACE(std::ios_base::failure("ReadCompactSize() : size too large"));
284 // Wrapper for serializing arrays and POD
285 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
287 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
294 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
295 char* begin() { return pbegin; }
296 const char* begin() const { return pbegin; }
297 char* end() { return pend; }
298 const char* end() const { return pend; }
300 unsigned int GetSerializeSize(int, int=0) const
302 return pend - pbegin;
305 template<typename Stream>
306 void Serialize(Stream& s, int, int=0) const
308 s.write(pbegin, pend - pbegin);
311 template<typename Stream>
312 void Unserialize(Stream& s, int, int=0)
314 s.read(pbegin, pend - pbegin);
321 // string stored as a fixed length field
323 template<std::size_t LEN>
324 class CFixedFieldString
327 const std::string* pcstr;
330 explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
331 explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
333 unsigned int GetSerializeSize(int, int=0) const
338 template<typename Stream>
339 void Serialize(Stream& s, int, int=0) const
342 strncpy(pszBuf, pcstr->c_str(), LEN);
343 s.write(pszBuf, LEN);
346 template<typename Stream>
347 void Unserialize(Stream& s, int, int=0)
350 THROW_WITH_STACKTRACE(std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string"));
363 // Forward declarations
367 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
368 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
369 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
372 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
373 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
374 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);
375 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&);
376 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&);
377 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);
378 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&);
379 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&);
380 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);
382 // others derived from vector
383 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);
384 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);
385 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);
388 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);
389 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);
390 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);
393 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
394 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);
395 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
398 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);
399 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);
400 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);
403 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);
404 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);
405 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);
408 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
409 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);
410 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
417 // If none of the specialized versions above matched, default to calling member function.
418 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
419 // The compiler will only cast int to long if none of the other templates matched.
420 // Thanks to Boost serialization for this idea.
423 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)
425 return a.GetSerializeSize((int)nType, nVersion);
428 template<typename Stream, typename T>
429 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)
431 a.Serialize(os, (int)nType, nVersion);
434 template<typename Stream, typename T>
435 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)
437 a.Unserialize(is, (int)nType, nVersion);
448 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
450 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
453 template<typename Stream, typename C>
454 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
456 WriteCompactSize(os, str.size());
458 os.write((char*)&str[0], str.size() * sizeof(str[0]));
461 template<typename Stream, typename C>
462 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
464 unsigned int nSize = ReadCompactSize(is);
467 is.read((char*)&str[0], nSize * sizeof(str[0]));
475 template<typename T, typename A>
476 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
478 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
481 template<typename T, typename A>
482 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
484 unsigned int nSize = GetSizeOfCompactSize(v.size());
485 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
486 nSize += GetSerializeSize((*vi), nType, nVersion);
490 template<typename T, typename A>
491 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
493 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
497 template<typename Stream, typename T, typename A>
498 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
500 WriteCompactSize(os, v.size());
502 os.write((char*)&v[0], v.size() * sizeof(T));
505 template<typename Stream, typename T, typename A>
506 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
508 WriteCompactSize(os, v.size());
509 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
510 ::Serialize(os, (*vi), nType, nVersion);
513 template<typename Stream, typename T, typename A>
514 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
516 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
520 template<typename Stream, typename T, typename A>
521 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
523 //unsigned int nSize = ReadCompactSize(is);
525 //is.read((char*)&v[0], nSize * sizeof(T));
527 // Limit size per read so bogus size value won't cause out of memory
529 unsigned int nSize = ReadCompactSize(is);
533 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
535 is.read((char*)&v[i], blk * sizeof(T));
540 template<typename Stream, typename T, typename A>
541 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
543 //unsigned int nSize = ReadCompactSize(is);
545 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
546 // Unserialize(is, (*vi), nType, nVersion);
549 unsigned int nSize = ReadCompactSize(is);
551 unsigned int nMid = 0;
554 nMid += 5000000 / sizeof(T);
558 for (; i < nMid; i++)
559 Unserialize(is, v[i], nType, nVersion);
563 template<typename Stream, typename T, typename A>
564 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
566 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
572 // others derived from vector
574 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
576 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
579 template<typename Stream>
580 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
582 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
585 template<typename Stream>
586 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
588 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
596 template<typename K, typename T>
597 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
599 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
602 template<typename Stream, typename K, typename T>
603 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
605 Serialize(os, item.first, nType, nVersion);
606 Serialize(os, item.second, nType, nVersion);
609 template<typename Stream, typename K, typename T>
610 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
612 Unserialize(is, item.first, nType, nVersion);
613 Unserialize(is, item.second, nType, nVersion);
621 template<typename T0, typename T1, typename T2>
622 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
624 unsigned int nSize = 0;
625 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
626 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
627 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
631 template<typename Stream, typename T0, typename T1, typename T2>
632 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
634 Serialize(os, boost::get<0>(item), nType, nVersion);
635 Serialize(os, boost::get<1>(item), nType, nVersion);
636 Serialize(os, boost::get<2>(item), nType, nVersion);
639 template<typename Stream, typename T0, typename T1, typename T2>
640 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
642 Unserialize(is, boost::get<0>(item), nType, nVersion);
643 Unserialize(is, boost::get<1>(item), nType, nVersion);
644 Unserialize(is, boost::get<2>(item), nType, nVersion);
652 template<typename T0, typename T1, typename T2, typename T3>
653 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
655 unsigned int nSize = 0;
656 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
657 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
658 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
659 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
663 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
664 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
666 Serialize(os, boost::get<0>(item), nType, nVersion);
667 Serialize(os, boost::get<1>(item), nType, nVersion);
668 Serialize(os, boost::get<2>(item), nType, nVersion);
669 Serialize(os, boost::get<3>(item), nType, nVersion);
672 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
673 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
675 Unserialize(is, boost::get<0>(item), nType, nVersion);
676 Unserialize(is, boost::get<1>(item), nType, nVersion);
677 Unserialize(is, boost::get<2>(item), nType, nVersion);
678 Unserialize(is, boost::get<3>(item), nType, nVersion);
686 template<typename K, typename T, typename Pred, typename A>
687 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
689 unsigned int nSize = GetSizeOfCompactSize(m.size());
690 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
691 nSize += GetSerializeSize((*mi), nType, nVersion);
695 template<typename Stream, typename K, typename T, typename Pred, typename A>
696 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
698 WriteCompactSize(os, m.size());
699 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
700 Serialize(os, (*mi), nType, nVersion);
703 template<typename Stream, typename K, typename T, typename Pred, typename A>
704 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
707 unsigned int nSize = ReadCompactSize(is);
708 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
709 for (unsigned int i = 0; i < nSize; i++)
711 std::pair<K, T> item;
712 Unserialize(is, item, nType, nVersion);
713 mi = m.insert(mi, item);
722 template<typename K, typename Pred, typename A>
723 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
725 unsigned int nSize = GetSizeOfCompactSize(m.size());
726 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
727 nSize += GetSerializeSize((*it), nType, nVersion);
731 template<typename Stream, typename K, typename Pred, typename A>
732 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
734 WriteCompactSize(os, m.size());
735 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
736 Serialize(os, (*it), nType, nVersion);
739 template<typename Stream, typename K, typename Pred, typename A>
740 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
743 unsigned int nSize = ReadCompactSize(is);
744 typename std::set<K, Pred, A>::iterator it = m.begin();
745 for (unsigned int i = 0; i < nSize; i++)
748 Unserialize(is, key, nType, nVersion);
749 it = m.insert(it, key);
756 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
758 class CSerActionGetSerializeSize { };
759 class CSerActionSerialize { };
760 class CSerActionUnserialize { };
762 template<typename Stream, typename T>
763 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
765 return ::GetSerializeSize(obj, nType, nVersion);
768 template<typename Stream, typename T>
769 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
771 ::Serialize(s, obj, nType, nVersion);
775 template<typename Stream, typename T>
776 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
778 ::Unserialize(s, obj, nType, nVersion);
782 struct ser_streamplaceholder
797 // Allocator that locks its contents from being paged
798 // out of memory and clears its contents before deletion.
801 struct secure_allocator : public std::allocator<T>
803 // MSVC8 default copy constructor is broken
804 typedef std::allocator<T> base;
805 typedef typename base::size_type size_type;
806 typedef typename base::difference_type difference_type;
807 typedef typename base::pointer pointer;
808 typedef typename base::const_pointer const_pointer;
809 typedef typename base::reference reference;
810 typedef typename base::const_reference const_reference;
811 typedef typename base::value_type value_type;
812 secure_allocator() throw() {}
813 secure_allocator(const secure_allocator& a) throw() : base(a) {}
814 template <typename U>
815 secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
816 ~secure_allocator() throw() {}
817 template<typename _Other> struct rebind
818 { typedef secure_allocator<_Other> other; };
820 T* allocate(std::size_t n, const void *hint = 0)
823 p = std::allocator<T>::allocate(n, hint);
825 mlock(p, sizeof(T) * n);
829 void deallocate(T* p, std::size_t n)
833 memset(p, 0, sizeof(T) * n);
834 munlock(p, sizeof(T) * n);
836 std::allocator<T>::deallocate(p, n);
843 // Double ended buffer combining vector and stream-like interfaces.
844 // >> and << read and write unformatted data using the above serialization templates.
845 // Fills with data in linear time; some stringstream implementations take N^2 time.
850 typedef std::vector<char, secure_allocator<char> > vector_type;
852 unsigned int nReadPos;
859 typedef vector_type::allocator_type allocator_type;
860 typedef vector_type::size_type size_type;
861 typedef vector_type::difference_type difference_type;
862 typedef vector_type::reference reference;
863 typedef vector_type::const_reference const_reference;
864 typedef vector_type::value_type value_type;
865 typedef vector_type::iterator iterator;
866 typedef vector_type::const_iterator const_iterator;
867 typedef vector_type::reverse_iterator reverse_iterator;
869 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
871 Init(nTypeIn, nVersionIn);
874 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
876 Init(nTypeIn, nVersionIn);
879 #if !defined(_MSC_VER) || _MSC_VER >= 1300
880 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
882 Init(nTypeIn, nVersionIn);
886 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
888 Init(nTypeIn, nVersionIn);
891 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
893 Init(nTypeIn, nVersionIn);
896 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
898 Init(nTypeIn, nVersionIn);
901 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
905 nVersion = nVersionIn;
907 exceptmask = std::ios::badbit | std::ios::failbit;
910 CDataStream& operator+=(const CDataStream& b)
912 vch.insert(vch.end(), b.begin(), b.end());
916 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
923 std::string str() const
925 return (std::string(begin(), end()));
932 const_iterator begin() const { return vch.begin() + nReadPos; }
933 iterator begin() { return vch.begin() + nReadPos; }
934 const_iterator end() const { return vch.end(); }
935 iterator end() { return vch.end(); }
936 size_type size() const { return vch.size() - nReadPos; }
937 bool empty() const { return vch.size() == nReadPos; }
938 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
939 void reserve(size_type n) { vch.reserve(n + nReadPos); }
940 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
941 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
942 void clear() { vch.clear(); nReadPos = 0; }
943 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
944 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
946 void insert(iterator it, const_iterator first, const_iterator last)
948 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
950 // special case for inserting at the front when there's room
951 nReadPos -= (last - first);
952 memcpy(&vch[nReadPos], &first[0], last - first);
955 vch.insert(it, first, last);
958 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
960 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
962 // special case for inserting at the front when there's room
963 nReadPos -= (last - first);
964 memcpy(&vch[nReadPos], &first[0], last - first);
967 vch.insert(it, first, last);
970 #if !defined(_MSC_VER) || _MSC_VER >= 1300
971 void insert(iterator it, const char* first, const char* last)
973 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
975 // special case for inserting at the front when there's room
976 nReadPos -= (last - first);
977 memcpy(&vch[nReadPos], &first[0], last - first);
980 vch.insert(it, first, last);
984 iterator erase(iterator it)
986 if (it == vch.begin() + nReadPos)
988 // special case for erasing from the front
989 if (++nReadPos >= vch.size())
991 // whenever we reach the end, we take the opportunity to clear the buffer
993 return vch.erase(vch.begin(), vch.end());
995 return vch.begin() + nReadPos;
998 return vch.erase(it);
1001 iterator erase(iterator first, iterator last)
1003 if (first == vch.begin() + nReadPos)
1005 // special case for erasing from the front
1006 if (last == vch.end())
1009 return vch.erase(vch.begin(), vch.end());
1013 nReadPos = (last - vch.begin());
1018 return vch.erase(first, last);
1021 inline void Compact()
1023 vch.erase(vch.begin(), vch.begin() + nReadPos);
1027 bool Rewind(size_type n)
1029 // Rewind by n characters if the buffer hasn't been compacted yet
1040 void setstate(short bits, const char* psz)
1043 if (state & exceptmask)
1044 THROW_WITH_STACKTRACE(std::ios_base::failure(psz));
1047 bool eof() const { return size() == 0; }
1048 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1049 bool good() const { return !eof() && (state == 0); }
1050 void clear(short n) { state = n; } // name conflict with vector clear()
1051 short exceptions() { return exceptmask; }
1052 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1053 CDataStream* rdbuf() { return this; }
1054 int in_avail() { return size(); }
1056 void SetType(int n) { nType = n; }
1057 int GetType() { return nType; }
1058 void SetVersion(int n) { nVersion = n; }
1059 int GetVersion() { return nVersion; }
1060 void ReadVersion() { *this >> nVersion; }
1061 void WriteVersion() { *this << nVersion; }
1063 CDataStream& read(char* pch, int nSize)
1065 // Read from the beginning of the buffer
1067 unsigned int nReadPosNext = nReadPos + nSize;
1068 if (nReadPosNext >= vch.size())
1070 if (nReadPosNext > vch.size())
1072 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1073 memset(pch, 0, nSize);
1074 nSize = vch.size() - nReadPos;
1076 memcpy(pch, &vch[nReadPos], nSize);
1081 memcpy(pch, &vch[nReadPos], nSize);
1082 nReadPos = nReadPosNext;
1086 CDataStream& ignore(int nSize)
1088 // Ignore from the beginning of the buffer
1090 unsigned int nReadPosNext = nReadPos + nSize;
1091 if (nReadPosNext >= vch.size())
1093 if (nReadPosNext > vch.size())
1095 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1096 nSize = vch.size() - nReadPos;
1102 nReadPos = nReadPosNext;
1106 CDataStream& write(const char* pch, int nSize)
1108 // Write to the end of the buffer
1110 vch.insert(vch.end(), pch, pch + nSize);
1114 template<typename Stream>
1115 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const
1117 // Special case: stream << stream concatenates like stream += stream
1119 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1122 template<typename T>
1123 unsigned int GetSerializeSize(const T& obj)
1125 // Tells the size of the object if serialized to this stream
1126 return ::GetSerializeSize(obj, nType, nVersion);
1129 template<typename T>
1130 CDataStream& operator<<(const T& obj)
1132 // Serialize to this stream
1133 ::Serialize(*this, obj, nType, nVersion);
1137 template<typename T>
1138 CDataStream& operator>>(T& obj)
1140 // Unserialize from this stream
1141 ::Unserialize(*this, obj, nType, nVersion);
1146 #ifdef TESTCDATASTREAM
1153 // n=16000 0 seconds
1154 // n=32000 0 seconds
1155 // n=64000 1 seconds
1156 // n=128000 1 seconds
1157 // n=256000 2 seconds
1158 // n=512000 4 seconds
1159 // n=1024000 8 seconds
1160 // n=2048000 16 seconds
1161 // n=4096000 32 seconds
1165 // n=4000 13 seconds
1166 // n=8000 87 seconds
1167 // n=16000 400 seconds
1168 // n=32000 1660 seconds
1169 // n=64000 6749 seconds
1170 // n=128000 27241 seconds
1171 // n=256000 109804 seconds
1173 int main(int argc, char *argv[])
1175 vector<unsigned char> vch(0xcc, 250);
1176 printf("CDataStream:\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);
1185 printf("stringstream:\n");
1186 for (int n = 1000; n <= 4500000; n *= 2)
1189 time_t nStart = time(NULL);
1190 for (int i = 0; i < n; i++)
1191 ss.write((char*)&vch[0], vch.size());
1192 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1207 // Automatic closing wrapper for FILE*
1208 // - Will automatically close the file when it goes out of scope if not null.
1209 // - If you're returning the file pointer, return file.release().
1210 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1222 typedef FILE element_type;
1224 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)
1228 nVersion = nVersionIn;
1230 exceptmask = std::ios::badbit | std::ios::failbit;
1240 if (file != NULL && file != stdin && file != stdout && file != stderr)
1245 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1246 operator FILE*() { return file; }
1247 FILE* operator->() { return file; }
1248 FILE& operator*() { return *file; }
1249 FILE** operator&() { return &file; }
1250 FILE* operator=(FILE* pnew) { return file = pnew; }
1251 bool operator!() { return (file == NULL); }
1257 void setstate(short bits, const char* psz)
1260 if (state & exceptmask)
1261 THROW_WITH_STACKTRACE(std::ios_base::failure(psz));
1264 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1265 bool good() const { return state == 0; }
1266 void clear(short n = 0) { state = n; }
1267 short exceptions() { return exceptmask; }
1268 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1270 void SetType(int n) { nType = n; }
1271 int GetType() { return nType; }
1272 void SetVersion(int n) { nVersion = n; }
1273 int GetVersion() { return nVersion; }
1274 void ReadVersion() { *this >> nVersion; }
1275 void WriteVersion() { *this << nVersion; }
1277 CAutoFile& read(char* pch, int nSize)
1280 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1281 if (fread(pch, 1, nSize, file) != nSize)
1282 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1286 CAutoFile& write(const char* pch, int nSize)
1289 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1290 if (fwrite(pch, 1, nSize, file) != nSize)
1291 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1295 template<typename T>
1296 unsigned int GetSerializeSize(const T& obj)
1298 // Tells the size of the object if serialized to this stream
1299 return ::GetSerializeSize(obj, nType, nVersion);
1302 template<typename T>
1303 CAutoFile& operator<<(const T& obj)
1305 // Serialize to this stream
1307 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1308 ::Serialize(*this, obj, nType, nVersion);
1312 template<typename T>
1313 CAutoFile& operator>>(T& obj)
1315 // Unserialize from this stream
1317 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1318 ::Unserialize(*this, obj, nType, nVersion);