1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file 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
34 // This is used to attempt to keep keying material out of swap
35 // Note that VirtualLock does not provide this as a guarantee on Windows,
36 // but, in practice, memory that has been VirtualLock'd almost never gets written to
37 // the pagefile except in rare circumstances where memory is extremely low.
39 #define mlock(p, n) VirtualLock((p), (n));
40 #define munlock(p, n) VirtualUnlock((p), (n));
44 /* This comes from limits.h if it's not defined there set a sane default */
47 #define PAGESIZE sysconf(_SC_PAGESIZE)
50 mlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
51 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
52 #define munlock(a,b) \
53 munlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
54 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
60 static const unsigned int MAX_SIZE = 0x02000000;
62 static const int VERSION = 40600;
63 static const char* pszSubVer = "";
64 static const bool VERSION_IS_BETA = true;
66 // Used to bypass the rule against non-const reference to temporary
67 // where it makes sense with wrappers such as CFlatData or CTxDB
69 inline T& REF(const T& val)
71 return const_cast<T&>(val);
74 /////////////////////////////////////////////////////////////////
76 // Templates for serializing to anything that looks like a stream,
77 // i.e. anything that supports .read(char*, int) and .write(char*, int)
83 SER_NETWORK = (1 << 0),
85 SER_GETHASH = (1 << 2),
88 SER_SKIPSIG = (1 << 16),
89 SER_BLOCKHEADERONLY = (1 << 17),
92 #define IMPLEMENT_SERIALIZE(statements) \
93 unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const \
95 CSerActionGetSerializeSize ser_action; \
96 const bool fGetSize = true; \
97 const bool fWrite = false; \
98 const bool fRead = false; \
99 unsigned int nSerSize = 0; \
100 ser_streamplaceholder s; \
101 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
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; \
115 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
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; \
126 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
130 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
140 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
141 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
143 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
144 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
145 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
146 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
147 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
148 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
149 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
150 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
151 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
152 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
153 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
154 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
155 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
157 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
158 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
159 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
160 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
161 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
162 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
163 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
164 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
165 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
166 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
167 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
168 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
169 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
171 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
172 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
173 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
174 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
175 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
176 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
177 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
178 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
179 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
180 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
181 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
182 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
183 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
185 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
186 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
187 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
196 // size < 253 -- 1 byte
197 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
198 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
199 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
201 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
203 if (nSize < 253) return sizeof(unsigned char);
204 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);
205 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);
206 else return sizeof(unsigned char) + sizeof(uint64);
209 template<typename Stream>
210 void WriteCompactSize(Stream& os, uint64 nSize)
214 unsigned char chSize = nSize;
215 WRITEDATA(os, chSize);
217 else if (nSize <= USHRT_MAX)
219 unsigned char chSize = 253;
220 unsigned short xSize = nSize;
221 WRITEDATA(os, chSize);
222 WRITEDATA(os, xSize);
224 else if (nSize <= UINT_MAX)
226 unsigned char chSize = 254;
227 unsigned int xSize = nSize;
228 WRITEDATA(os, chSize);
229 WRITEDATA(os, xSize);
233 unsigned char chSize = 255;
234 uint64 xSize = nSize;
235 WRITEDATA(os, chSize);
236 WRITEDATA(os, xSize);
241 template<typename Stream>
242 uint64 ReadCompactSize(Stream& is)
244 unsigned char chSize;
245 READDATA(is, chSize);
251 else if (chSize == 253)
253 unsigned short xSize;
257 else if (chSize == 254)
269 if (nSizeRet > (uint64)MAX_SIZE)
270 throw std::ios_base::failure("ReadCompactSize() : size too large");
277 // Wrapper for serializing arrays and POD
278 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
280 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
287 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
288 char* begin() { return pbegin; }
289 const char* begin() const { return pbegin; }
290 char* end() { return pend; }
291 const char* end() const { return pend; }
293 unsigned int GetSerializeSize(int, int=0) const
295 return pend - pbegin;
298 template<typename Stream>
299 void Serialize(Stream& s, int, int=0) const
301 s.write(pbegin, pend - pbegin);
304 template<typename Stream>
305 void Unserialize(Stream& s, int, int=0)
307 s.read(pbegin, pend - pbegin);
314 // string stored as a fixed length field
316 template<std::size_t LEN>
317 class CFixedFieldString
320 const std::string* pcstr;
323 explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
324 explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
326 unsigned int GetSerializeSize(int, int=0) const
331 template<typename Stream>
332 void Serialize(Stream& s, int, int=0) const
335 strncpy(pszBuf, pcstr->c_str(), LEN);
336 s.write(pszBuf, LEN);
339 template<typename Stream>
340 void Unserialize(Stream& s, int, int=0)
343 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
356 // Forward declarations
360 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
361 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
362 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
365 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
366 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
367 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);
368 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&);
369 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
370 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);
371 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&);
372 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&);
373 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);
375 // others derived from vector
376 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);
377 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);
378 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);
381 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);
382 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);
383 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);
386 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
387 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);
388 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
391 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);
392 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);
393 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);
396 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);
397 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);
398 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);
401 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
402 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);
403 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
410 // If none of the specialized versions above matched, default to calling member function.
411 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
412 // The compiler will only cast int to long if none of the other templates matched.
413 // Thanks to Boost serialization for this idea.
416 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)
418 return a.GetSerializeSize((int)nType, nVersion);
421 template<typename Stream, typename T>
422 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)
424 a.Serialize(os, (int)nType, nVersion);
427 template<typename Stream, typename T>
428 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)
430 a.Unserialize(is, (int)nType, nVersion);
441 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
443 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
446 template<typename Stream, typename C>
447 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
449 WriteCompactSize(os, str.size());
451 os.write((char*)&str[0], str.size() * sizeof(str[0]));
454 template<typename Stream, typename C>
455 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
457 unsigned int nSize = ReadCompactSize(is);
460 is.read((char*)&str[0], nSize * sizeof(str[0]));
468 template<typename T, typename A>
469 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
471 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
474 template<typename T, typename A>
475 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
477 unsigned int nSize = GetSizeOfCompactSize(v.size());
478 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
479 nSize += GetSerializeSize((*vi), nType, nVersion);
483 template<typename T, typename A>
484 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
486 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
490 template<typename Stream, typename T, typename A>
491 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
493 WriteCompactSize(os, v.size());
495 os.write((char*)&v[0], v.size() * sizeof(T));
498 template<typename Stream, typename T, typename A>
499 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
501 WriteCompactSize(os, v.size());
502 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
503 ::Serialize(os, (*vi), nType, nVersion);
506 template<typename Stream, typename T, typename A>
507 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
509 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
513 template<typename Stream, typename T, typename A>
514 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
516 //unsigned int nSize = ReadCompactSize(is);
518 //is.read((char*)&v[0], nSize * sizeof(T));
520 // Limit size per read so bogus size value won't cause out of memory
522 unsigned int nSize = ReadCompactSize(is);
526 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
528 is.read((char*)&v[i], blk * sizeof(T));
533 template<typename Stream, typename T, typename A>
534 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
536 //unsigned int nSize = ReadCompactSize(is);
538 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
539 // Unserialize(is, (*vi), nType, nVersion);
542 unsigned int nSize = ReadCompactSize(is);
544 unsigned int nMid = 0;
547 nMid += 5000000 / sizeof(T);
551 for (; i < nMid; i++)
552 Unserialize(is, v[i], nType, nVersion);
556 template<typename Stream, typename T, typename A>
557 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
559 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
565 // others derived from vector
567 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
569 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
572 template<typename Stream>
573 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
575 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
578 template<typename Stream>
579 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
581 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
589 template<typename K, typename T>
590 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
592 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
595 template<typename Stream, typename K, typename T>
596 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
598 Serialize(os, item.first, nType, nVersion);
599 Serialize(os, item.second, nType, nVersion);
602 template<typename Stream, typename K, typename T>
603 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
605 Unserialize(is, item.first, nType, nVersion);
606 Unserialize(is, item.second, nType, nVersion);
614 template<typename T0, typename T1, typename T2>
615 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
617 unsigned int nSize = 0;
618 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
619 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
620 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
624 template<typename Stream, typename T0, typename T1, typename T2>
625 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
627 Serialize(os, boost::get<0>(item), nType, nVersion);
628 Serialize(os, boost::get<1>(item), nType, nVersion);
629 Serialize(os, boost::get<2>(item), nType, nVersion);
632 template<typename Stream, typename T0, typename T1, typename T2>
633 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
635 Unserialize(is, boost::get<0>(item), nType, nVersion);
636 Unserialize(is, boost::get<1>(item), nType, nVersion);
637 Unserialize(is, boost::get<2>(item), nType, nVersion);
645 template<typename T0, typename T1, typename T2, typename T3>
646 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
648 unsigned int nSize = 0;
649 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
650 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
651 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
652 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
656 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
657 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
659 Serialize(os, boost::get<0>(item), nType, nVersion);
660 Serialize(os, boost::get<1>(item), nType, nVersion);
661 Serialize(os, boost::get<2>(item), nType, nVersion);
662 Serialize(os, boost::get<3>(item), nType, nVersion);
665 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
666 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
668 Unserialize(is, boost::get<0>(item), nType, nVersion);
669 Unserialize(is, boost::get<1>(item), nType, nVersion);
670 Unserialize(is, boost::get<2>(item), nType, nVersion);
671 Unserialize(is, boost::get<3>(item), nType, nVersion);
679 template<typename K, typename T, typename Pred, typename A>
680 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
682 unsigned int nSize = GetSizeOfCompactSize(m.size());
683 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
684 nSize += GetSerializeSize((*mi), nType, nVersion);
688 template<typename Stream, typename K, typename T, typename Pred, typename A>
689 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
691 WriteCompactSize(os, m.size());
692 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
693 Serialize(os, (*mi), nType, nVersion);
696 template<typename Stream, typename K, typename T, typename Pred, typename A>
697 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
700 unsigned int nSize = ReadCompactSize(is);
701 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
702 for (unsigned int i = 0; i < nSize; i++)
704 std::pair<K, T> item;
705 Unserialize(is, item, nType, nVersion);
706 mi = m.insert(mi, item);
715 template<typename K, typename Pred, typename A>
716 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
718 unsigned int nSize = GetSizeOfCompactSize(m.size());
719 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
720 nSize += GetSerializeSize((*it), nType, nVersion);
724 template<typename Stream, typename K, typename Pred, typename A>
725 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
727 WriteCompactSize(os, m.size());
728 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
729 Serialize(os, (*it), nType, nVersion);
732 template<typename Stream, typename K, typename Pred, typename A>
733 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
736 unsigned int nSize = ReadCompactSize(is);
737 typename std::set<K, Pred, A>::iterator it = m.begin();
738 for (unsigned int i = 0; i < nSize; i++)
741 Unserialize(is, key, nType, nVersion);
742 it = m.insert(it, key);
749 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
751 class CSerActionGetSerializeSize { };
752 class CSerActionSerialize { };
753 class CSerActionUnserialize { };
755 template<typename Stream, typename T>
756 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
758 return ::GetSerializeSize(obj, nType, nVersion);
761 template<typename Stream, typename T>
762 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
764 ::Serialize(s, obj, nType, nVersion);
768 template<typename Stream, typename T>
769 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
771 ::Unserialize(s, obj, nType, nVersion);
775 struct ser_streamplaceholder
790 // Allocator that locks its contents from being paged
791 // out of memory and clears its contents before deletion.
794 struct secure_allocator : public std::allocator<T>
796 // MSVC8 default copy constructor is broken
797 typedef std::allocator<T> base;
798 typedef typename base::size_type size_type;
799 typedef typename base::difference_type difference_type;
800 typedef typename base::pointer pointer;
801 typedef typename base::const_pointer const_pointer;
802 typedef typename base::reference reference;
803 typedef typename base::const_reference const_reference;
804 typedef typename base::value_type value_type;
805 secure_allocator() throw() {}
806 secure_allocator(const secure_allocator& a) throw() : base(a) {}
807 template <typename U>
808 secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
809 ~secure_allocator() throw() {}
810 template<typename _Other> struct rebind
811 { typedef secure_allocator<_Other> other; };
813 T* allocate(std::size_t n, const void *hint = 0)
816 p = std::allocator<T>::allocate(n, hint);
818 mlock(p, sizeof(T) * n);
822 void deallocate(T* p, std::size_t n)
826 memset(p, 0, sizeof(T) * n);
827 munlock(p, sizeof(T) * n);
829 std::allocator<T>::deallocate(p, n);
835 // Allocator that clears its contents before deletion.
838 struct zero_after_free_allocator : public std::allocator<T>
840 // MSVC8 default copy constructor is broken
841 typedef std::allocator<T> base;
842 typedef typename base::size_type size_type;
843 typedef typename base::difference_type difference_type;
844 typedef typename base::pointer pointer;
845 typedef typename base::const_pointer const_pointer;
846 typedef typename base::reference reference;
847 typedef typename base::const_reference const_reference;
848 typedef typename base::value_type value_type;
849 zero_after_free_allocator() throw() {}
850 zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
851 template <typename U>
852 zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a) {}
853 ~zero_after_free_allocator() throw() {}
854 template<typename _Other> struct rebind
855 { typedef zero_after_free_allocator<_Other> other; };
857 void deallocate(T* p, std::size_t n)
860 memset(p, 0, sizeof(T) * n);
861 std::allocator<T>::deallocate(p, n);
868 // Double ended buffer combining vector and stream-like interfaces.
869 // >> and << read and write unformatted data using the above serialization templates.
870 // Fills with data in linear time; some stringstream implementations take N^2 time.
875 typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
877 unsigned int nReadPos;
884 typedef vector_type::allocator_type allocator_type;
885 typedef vector_type::size_type size_type;
886 typedef vector_type::difference_type difference_type;
887 typedef vector_type::reference reference;
888 typedef vector_type::const_reference const_reference;
889 typedef vector_type::value_type value_type;
890 typedef vector_type::iterator iterator;
891 typedef vector_type::const_iterator const_iterator;
892 typedef vector_type::reverse_iterator reverse_iterator;
894 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
896 Init(nTypeIn, nVersionIn);
899 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
901 Init(nTypeIn, nVersionIn);
904 #if !defined(_MSC_VER) || _MSC_VER >= 1300
905 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
907 Init(nTypeIn, nVersionIn);
911 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
913 Init(nTypeIn, nVersionIn);
916 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
918 Init(nTypeIn, nVersionIn);
921 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
923 Init(nTypeIn, nVersionIn);
926 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
930 nVersion = nVersionIn;
932 exceptmask = std::ios::badbit | std::ios::failbit;
935 CDataStream& operator+=(const CDataStream& b)
937 vch.insert(vch.end(), b.begin(), b.end());
941 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
948 std::string str() const
950 return (std::string(begin(), end()));
957 const_iterator begin() const { return vch.begin() + nReadPos; }
958 iterator begin() { return vch.begin() + nReadPos; }
959 const_iterator end() const { return vch.end(); }
960 iterator end() { return vch.end(); }
961 size_type size() const { return vch.size() - nReadPos; }
962 bool empty() const { return vch.size() == nReadPos; }
963 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
964 void reserve(size_type n) { vch.reserve(n + nReadPos); }
965 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
966 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
967 void clear() { vch.clear(); nReadPos = 0; }
968 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
969 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
971 void insert(iterator it, const_iterator first, const_iterator 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);
983 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
985 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
987 // special case for inserting at the front when there's room
988 nReadPos -= (last - first);
989 memcpy(&vch[nReadPos], &first[0], last - first);
992 vch.insert(it, first, last);
995 #if !defined(_MSC_VER) || _MSC_VER >= 1300
996 void insert(iterator it, const char* first, const char* last)
998 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
1000 // special case for inserting at the front when there's room
1001 nReadPos -= (last - first);
1002 memcpy(&vch[nReadPos], &first[0], last - first);
1005 vch.insert(it, first, last);
1009 iterator erase(iterator it)
1011 if (it == vch.begin() + nReadPos)
1013 // special case for erasing from the front
1014 if (++nReadPos >= vch.size())
1016 // whenever we reach the end, we take the opportunity to clear the buffer
1018 return vch.erase(vch.begin(), vch.end());
1020 return vch.begin() + nReadPos;
1023 return vch.erase(it);
1026 iterator erase(iterator first, iterator last)
1028 if (first == vch.begin() + nReadPos)
1030 // special case for erasing from the front
1031 if (last == vch.end())
1034 return vch.erase(vch.begin(), vch.end());
1038 nReadPos = (last - vch.begin());
1043 return vch.erase(first, last);
1046 inline void Compact()
1048 vch.erase(vch.begin(), vch.begin() + nReadPos);
1052 bool Rewind(size_type n)
1054 // Rewind by n characters if the buffer hasn't been compacted yet
1065 void setstate(short bits, const char* psz)
1068 if (state & exceptmask)
1069 throw std::ios_base::failure(psz);
1072 bool eof() const { return size() == 0; }
1073 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1074 bool good() const { return !eof() && (state == 0); }
1075 void clear(short n) { state = n; } // name conflict with vector clear()
1076 short exceptions() { return exceptmask; }
1077 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1078 CDataStream* rdbuf() { return this; }
1079 int in_avail() { return size(); }
1081 void SetType(int n) { nType = n; }
1082 int GetType() { return nType; }
1083 void SetVersion(int n) { nVersion = n; }
1084 int GetVersion() { return nVersion; }
1085 void ReadVersion() { *this >> nVersion; }
1086 void WriteVersion() { *this << nVersion; }
1088 CDataStream& read(char* pch, int nSize)
1090 // Read from the beginning of the buffer
1092 unsigned int nReadPosNext = nReadPos + nSize;
1093 if (nReadPosNext >= vch.size())
1095 if (nReadPosNext > vch.size())
1097 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1098 memset(pch, 0, nSize);
1099 nSize = vch.size() - nReadPos;
1101 memcpy(pch, &vch[nReadPos], nSize);
1106 memcpy(pch, &vch[nReadPos], nSize);
1107 nReadPos = nReadPosNext;
1111 CDataStream& ignore(int nSize)
1113 // Ignore from the beginning of the buffer
1115 unsigned int nReadPosNext = nReadPos + nSize;
1116 if (nReadPosNext >= vch.size())
1118 if (nReadPosNext > vch.size())
1120 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1121 nSize = vch.size() - nReadPos;
1127 nReadPos = nReadPosNext;
1131 CDataStream& write(const char* pch, int nSize)
1133 // Write to the end of the buffer
1135 vch.insert(vch.end(), pch, pch + nSize);
1139 template<typename Stream>
1140 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const
1142 // Special case: stream << stream concatenates like stream += stream
1144 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1147 template<typename T>
1148 unsigned int GetSerializeSize(const T& obj)
1150 // Tells the size of the object if serialized to this stream
1151 return ::GetSerializeSize(obj, nType, nVersion);
1154 template<typename T>
1155 CDataStream& operator<<(const T& obj)
1157 // Serialize to this stream
1158 ::Serialize(*this, obj, nType, nVersion);
1162 template<typename T>
1163 CDataStream& operator>>(T& obj)
1165 // Unserialize from this stream
1166 ::Unserialize(*this, obj, nType, nVersion);
1171 #ifdef TESTCDATASTREAM
1178 // n=16000 0 seconds
1179 // n=32000 0 seconds
1180 // n=64000 1 seconds
1181 // n=128000 1 seconds
1182 // n=256000 2 seconds
1183 // n=512000 4 seconds
1184 // n=1024000 8 seconds
1185 // n=2048000 16 seconds
1186 // n=4096000 32 seconds
1190 // n=4000 13 seconds
1191 // n=8000 87 seconds
1192 // n=16000 400 seconds
1193 // n=32000 1660 seconds
1194 // n=64000 6749 seconds
1195 // n=128000 27241 seconds
1196 // n=256000 109804 seconds
1198 int main(int argc, char *argv[])
1200 vector<unsigned char> vch(0xcc, 250);
1201 printf("CDataStream:\n");
1202 for (int n = 1000; n <= 4500000; n *= 2)
1205 time_t nStart = time(NULL);
1206 for (int i = 0; i < n; i++)
1207 ss.write((char*)&vch[0], vch.size());
1208 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1210 printf("stringstream:\n");
1211 for (int n = 1000; n <= 4500000; n *= 2)
1214 time_t nStart = time(NULL);
1215 for (int i = 0; i < n; i++)
1216 ss.write((char*)&vch[0], vch.size());
1217 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1232 // Automatic closing wrapper for FILE*
1233 // - Will automatically close the file when it goes out of scope if not null.
1234 // - If you're returning the file pointer, return file.release().
1235 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1247 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)
1251 nVersion = nVersionIn;
1253 exceptmask = std::ios::badbit | std::ios::failbit;
1263 if (file != NULL && file != stdin && file != stdout && file != stderr)
1268 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1269 operator FILE*() { return file; }
1270 FILE* operator->() { return file; }
1271 FILE& operator*() { return *file; }
1272 FILE** operator&() { return &file; }
1273 FILE* operator=(FILE* pnew) { return file = pnew; }
1274 bool operator!() { return (file == NULL); }
1280 void setstate(short bits, const char* psz)
1283 if (state & exceptmask)
1284 throw std::ios_base::failure(psz);
1287 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1288 bool good() const { return state == 0; }
1289 void clear(short n = 0) { state = n; }
1290 short exceptions() { return exceptmask; }
1291 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1293 void SetType(int n) { nType = n; }
1294 int GetType() { return nType; }
1295 void SetVersion(int n) { nVersion = n; }
1296 int GetVersion() { return nVersion; }
1297 void ReadVersion() { *this >> nVersion; }
1298 void WriteVersion() { *this << nVersion; }
1300 CAutoFile& read(char* pch, int nSize)
1303 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1304 if (fread(pch, 1, nSize, file) != nSize)
1305 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1309 CAutoFile& write(const char* pch, int nSize)
1312 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1313 if (fwrite(pch, 1, nSize, file) != nSize)
1314 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1318 template<typename T>
1319 unsigned int GetSerializeSize(const T& obj)
1321 // Tells the size of the object if serialized to this stream
1322 return ::GetSerializeSize(obj, nType, nVersion);
1325 template<typename T>
1326 CAutoFile& operator<<(const T& obj)
1328 // Serialize to this stream
1330 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1331 ::Serialize(*this, obj, nType, nVersion);
1335 template<typename T>
1336 CAutoFile& operator>>(T& obj)
1338 // Unserialize from this stream
1340 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1341 ::Unserialize(*this, obj, nType, nVersion);