1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_SERIALIZE_H
6 #define BITCOIN_SERIALIZE_H
17 #include <boost/type_traits/is_fundamental.hpp>
18 #include <boost/tuple/tuple.hpp>
19 #include <boost/tuple/tuple_comparison.hpp>
20 #include <boost/tuple/tuple_io.hpp>
22 typedef long long int64;
23 typedef unsigned long long uint64;
27 // This is used to attempt to keep keying material out of swap
28 // Note that VirtualLock does not provide this as a guarantee on Windows,
29 // but, in practice, memory that has been VirtualLock'd almost never gets written to
30 // the pagefile except in rare circumstances where memory is extremely low.
32 #define mlock(p, n) VirtualLock((p), (n));
33 #define munlock(p, n) VirtualUnlock((p), (n));
37 /* This comes from limits.h if it's not defined there set a sane default */
40 #define PAGESIZE sysconf(_SC_PAGESIZE)
43 mlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
44 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
45 #define munlock(a,b) \
46 munlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
47 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
53 static const unsigned int MAX_SIZE = 0x02000000;
55 static const int PROTOCOL_VERSION = 60000;
57 // Used to bypass the rule against non-const reference to temporary
58 // where it makes sense with wrappers such as CFlatData or CTxDB
60 inline T& REF(const T& val)
62 return const_cast<T&>(val);
65 /////////////////////////////////////////////////////////////////
67 // Templates for serializing to anything that looks like a stream,
68 // i.e. anything that supports .read(char*, int) and .write(char*, int)
74 SER_NETWORK = (1 << 0),
76 SER_GETHASH = (1 << 2),
79 SER_SKIPSIG = (1 << 16),
80 SER_BLOCKHEADERONLY = (1 << 17),
83 #define IMPLEMENT_SERIALIZE(statements) \
84 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const \
86 CSerActionGetSerializeSize ser_action; \
87 const bool fGetSize = true; \
88 const bool fWrite = false; \
89 const bool fRead = false; \
90 unsigned int nSerSize = 0; \
91 ser_streamplaceholder s; \
92 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
94 s.nVersion = nVersion; \
98 template<typename Stream> \
99 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const \
101 CSerActionSerialize ser_action; \
102 const bool fGetSize = false; \
103 const bool fWrite = true; \
104 const bool fRead = false; \
105 unsigned int nSerSize = 0; \
106 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
109 template<typename Stream> \
110 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) \
112 CSerActionUnserialize ser_action; \
113 const bool fGetSize = false; \
114 const bool fWrite = false; \
115 const bool fRead = true; \
116 unsigned int nSerSize = 0; \
117 assert(fGetSize||fWrite||fRead); /* suppress warning */ \
121 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
131 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
132 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
134 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
135 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
136 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
137 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
138 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
139 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
140 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
141 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
142 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
143 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
144 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
145 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
146 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
148 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
149 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
150 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
151 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
152 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
153 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
154 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
155 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
156 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
157 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
158 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
159 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
160 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
162 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
163 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
164 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
165 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
166 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
167 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
168 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
169 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
170 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
171 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
172 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
173 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
174 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
176 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
177 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
178 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
187 // size < 253 -- 1 byte
188 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
189 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
190 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
192 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
194 if (nSize < 253) return sizeof(unsigned char);
195 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
196 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
197 else return sizeof(unsigned char) + sizeof(uint64);
200 template<typename Stream>
201 void WriteCompactSize(Stream& os, uint64 nSize)
205 unsigned char chSize = nSize;
206 WRITEDATA(os, chSize);
208 else if (nSize <= std::numeric_limits<unsigned short>::max())
210 unsigned char chSize = 253;
211 unsigned short xSize = nSize;
212 WRITEDATA(os, chSize);
213 WRITEDATA(os, xSize);
215 else if (nSize <= std::numeric_limits<unsigned int>::max())
217 unsigned char chSize = 254;
218 unsigned int xSize = nSize;
219 WRITEDATA(os, chSize);
220 WRITEDATA(os, xSize);
224 unsigned char chSize = 255;
225 uint64 xSize = nSize;
226 WRITEDATA(os, chSize);
227 WRITEDATA(os, xSize);
232 template<typename Stream>
233 uint64 ReadCompactSize(Stream& is)
235 unsigned char chSize;
236 READDATA(is, chSize);
242 else if (chSize == 253)
244 unsigned short xSize;
248 else if (chSize == 254)
260 if (nSizeRet > (uint64)MAX_SIZE)
261 throw std::ios_base::failure("ReadCompactSize() : size too large");
268 // Wrapper for serializing arrays and POD
269 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
271 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
278 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
279 char* begin() { return pbegin; }
280 const char* begin() const { return pbegin; }
281 char* end() { return pend; }
282 const char* end() const { return pend; }
284 unsigned int GetSerializeSize(int, int=0) const
286 return pend - pbegin;
289 template<typename Stream>
290 void Serialize(Stream& s, int, int=0) const
292 s.write(pbegin, pend - pbegin);
295 template<typename Stream>
296 void Unserialize(Stream& s, int, int=0)
298 s.read(pbegin, pend - pbegin);
305 // string stored as a fixed length field
307 template<std::size_t LEN>
308 class CFixedFieldString
311 const std::string* pcstr;
314 explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
315 explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
317 unsigned int GetSerializeSize(int, int=0) const
322 template<typename Stream>
323 void Serialize(Stream& s, int, int=0) const
326 strncpy(pszBuf, pcstr->c_str(), LEN);
327 s.write(pszBuf, LEN);
330 template<typename Stream>
331 void Unserialize(Stream& s, int, int=0)
334 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
347 // Forward declarations
351 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
352 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
353 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
356 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
357 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
358 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
359 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&);
360 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&);
361 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
362 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&);
363 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&);
364 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
366 // others derived from vector
367 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
368 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
369 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
372 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
373 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
374 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
377 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
378 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
379 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
382 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion=PROTOCOL_VERSION);
383 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=PROTOCOL_VERSION);
384 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=PROTOCOL_VERSION);
387 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
388 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=PROTOCOL_VERSION);
389 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=PROTOCOL_VERSION);
392 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
393 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
394 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
401 // If none of the specialized versions above matched, default to calling member function.
402 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
403 // The compiler will only cast int to long if none of the other templates matched.
404 // Thanks to Boost serialization for this idea.
407 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=PROTOCOL_VERSION)
409 return a.GetSerializeSize((int)nType, nVersion);
412 template<typename Stream, typename T>
413 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=PROTOCOL_VERSION)
415 a.Serialize(os, (int)nType, nVersion);
418 template<typename Stream, typename T>
419 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=PROTOCOL_VERSION)
421 a.Unserialize(is, (int)nType, nVersion);
432 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
434 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
437 template<typename Stream, typename C>
438 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
440 WriteCompactSize(os, str.size());
442 os.write((char*)&str[0], str.size() * sizeof(str[0]));
445 template<typename Stream, typename C>
446 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
448 unsigned int nSize = ReadCompactSize(is);
451 is.read((char*)&str[0], nSize * sizeof(str[0]));
459 template<typename T, typename A>
460 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
462 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
465 template<typename T, typename A>
466 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
468 unsigned int nSize = GetSizeOfCompactSize(v.size());
469 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
470 nSize += GetSerializeSize((*vi), nType, nVersion);
474 template<typename T, typename A>
475 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
477 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
481 template<typename Stream, typename T, typename A>
482 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
484 WriteCompactSize(os, v.size());
486 os.write((char*)&v[0], v.size() * sizeof(T));
489 template<typename Stream, typename T, typename A>
490 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
492 WriteCompactSize(os, v.size());
493 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
494 ::Serialize(os, (*vi), nType, nVersion);
497 template<typename Stream, typename T, typename A>
498 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
500 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
504 template<typename Stream, typename T, typename A>
505 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
507 //unsigned int nSize = ReadCompactSize(is);
509 //is.read((char*)&v[0], nSize * sizeof(T));
511 // Limit size per read so bogus size value won't cause out of memory
513 unsigned int nSize = ReadCompactSize(is);
517 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
519 is.read((char*)&v[i], blk * sizeof(T));
524 template<typename Stream, typename T, typename A>
525 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
527 //unsigned int nSize = ReadCompactSize(is);
529 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
530 // Unserialize(is, (*vi), nType, nVersion);
533 unsigned int nSize = ReadCompactSize(is);
535 unsigned int nMid = 0;
538 nMid += 5000000 / sizeof(T);
542 for (; i < nMid; i++)
543 Unserialize(is, v[i], nType, nVersion);
547 template<typename Stream, typename T, typename A>
548 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
550 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
556 // others derived from vector
558 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
560 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
563 template<typename Stream>
564 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
566 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
569 template<typename Stream>
570 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
572 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
580 template<typename K, typename T>
581 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
583 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
586 template<typename Stream, typename K, typename T>
587 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
589 Serialize(os, item.first, nType, nVersion);
590 Serialize(os, item.second, nType, nVersion);
593 template<typename Stream, typename K, typename T>
594 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
596 Unserialize(is, item.first, nType, nVersion);
597 Unserialize(is, item.second, nType, nVersion);
605 template<typename T0, typename T1, typename T2>
606 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
608 unsigned int nSize = 0;
609 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
610 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
611 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
615 template<typename Stream, typename T0, typename T1, typename T2>
616 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
618 Serialize(os, boost::get<0>(item), nType, nVersion);
619 Serialize(os, boost::get<1>(item), nType, nVersion);
620 Serialize(os, boost::get<2>(item), nType, nVersion);
623 template<typename Stream, typename T0, typename T1, typename T2>
624 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
626 Unserialize(is, boost::get<0>(item), nType, nVersion);
627 Unserialize(is, boost::get<1>(item), nType, nVersion);
628 Unserialize(is, boost::get<2>(item), nType, nVersion);
636 template<typename T0, typename T1, typename T2, typename T3>
637 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
639 unsigned int nSize = 0;
640 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
641 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
642 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
643 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
647 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
648 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
650 Serialize(os, boost::get<0>(item), nType, nVersion);
651 Serialize(os, boost::get<1>(item), nType, nVersion);
652 Serialize(os, boost::get<2>(item), nType, nVersion);
653 Serialize(os, boost::get<3>(item), nType, nVersion);
656 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
657 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
659 Unserialize(is, boost::get<0>(item), nType, nVersion);
660 Unserialize(is, boost::get<1>(item), nType, nVersion);
661 Unserialize(is, boost::get<2>(item), nType, nVersion);
662 Unserialize(is, boost::get<3>(item), nType, nVersion);
670 template<typename K, typename T, typename Pred, typename A>
671 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
673 unsigned int nSize = GetSizeOfCompactSize(m.size());
674 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
675 nSize += GetSerializeSize((*mi), nType, nVersion);
679 template<typename Stream, typename K, typename T, typename Pred, typename A>
680 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
682 WriteCompactSize(os, m.size());
683 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
684 Serialize(os, (*mi), nType, nVersion);
687 template<typename Stream, typename K, typename T, typename Pred, typename A>
688 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
691 unsigned int nSize = ReadCompactSize(is);
692 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
693 for (unsigned int i = 0; i < nSize; i++)
695 std::pair<K, T> item;
696 Unserialize(is, item, nType, nVersion);
697 mi = m.insert(mi, item);
706 template<typename K, typename Pred, typename A>
707 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
709 unsigned int nSize = GetSizeOfCompactSize(m.size());
710 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
711 nSize += GetSerializeSize((*it), nType, nVersion);
715 template<typename Stream, typename K, typename Pred, typename A>
716 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
718 WriteCompactSize(os, m.size());
719 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
720 Serialize(os, (*it), nType, nVersion);
723 template<typename Stream, typename K, typename Pred, typename A>
724 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
727 unsigned int nSize = ReadCompactSize(is);
728 typename std::set<K, Pred, A>::iterator it = m.begin();
729 for (unsigned int i = 0; i < nSize; i++)
732 Unserialize(is, key, nType, nVersion);
733 it = m.insert(it, key);
740 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
742 class CSerActionGetSerializeSize { };
743 class CSerActionSerialize { };
744 class CSerActionUnserialize { };
746 template<typename Stream, typename T>
747 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
749 return ::GetSerializeSize(obj, nType, nVersion);
752 template<typename Stream, typename T>
753 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
755 ::Serialize(s, obj, nType, nVersion);
759 template<typename Stream, typename T>
760 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
762 ::Unserialize(s, obj, nType, nVersion);
766 struct ser_streamplaceholder
781 // Allocator that locks its contents from being paged
782 // out of memory and clears its contents before deletion.
785 struct secure_allocator : public std::allocator<T>
787 // MSVC8 default copy constructor is broken
788 typedef std::allocator<T> base;
789 typedef typename base::size_type size_type;
790 typedef typename base::difference_type difference_type;
791 typedef typename base::pointer pointer;
792 typedef typename base::const_pointer const_pointer;
793 typedef typename base::reference reference;
794 typedef typename base::const_reference const_reference;
795 typedef typename base::value_type value_type;
796 secure_allocator() throw() {}
797 secure_allocator(const secure_allocator& a) throw() : base(a) {}
798 template <typename U>
799 secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
800 ~secure_allocator() throw() {}
801 template<typename _Other> struct rebind
802 { typedef secure_allocator<_Other> other; };
804 T* allocate(std::size_t n, const void *hint = 0)
807 p = std::allocator<T>::allocate(n, hint);
809 mlock(p, sizeof(T) * n);
813 void deallocate(T* p, std::size_t n)
817 memset(p, 0, sizeof(T) * n);
818 munlock(p, sizeof(T) * n);
820 std::allocator<T>::deallocate(p, n);
826 // Allocator that clears its contents before deletion.
829 struct zero_after_free_allocator : public std::allocator<T>
831 // MSVC8 default copy constructor is broken
832 typedef std::allocator<T> base;
833 typedef typename base::size_type size_type;
834 typedef typename base::difference_type difference_type;
835 typedef typename base::pointer pointer;
836 typedef typename base::const_pointer const_pointer;
837 typedef typename base::reference reference;
838 typedef typename base::const_reference const_reference;
839 typedef typename base::value_type value_type;
840 zero_after_free_allocator() throw() {}
841 zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
842 template <typename U>
843 zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a) {}
844 ~zero_after_free_allocator() throw() {}
845 template<typename _Other> struct rebind
846 { typedef zero_after_free_allocator<_Other> other; };
848 void deallocate(T* p, std::size_t n)
851 memset(p, 0, sizeof(T) * n);
852 std::allocator<T>::deallocate(p, n);
859 // Double ended buffer combining vector and stream-like interfaces.
860 // >> and << read and write unformatted data using the above serialization templates.
861 // Fills with data in linear time; some stringstream implementations take N^2 time.
866 typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
868 unsigned int nReadPos;
875 typedef vector_type::allocator_type allocator_type;
876 typedef vector_type::size_type size_type;
877 typedef vector_type::difference_type difference_type;
878 typedef vector_type::reference reference;
879 typedef vector_type::const_reference const_reference;
880 typedef vector_type::value_type value_type;
881 typedef vector_type::iterator iterator;
882 typedef vector_type::const_iterator const_iterator;
883 typedef vector_type::reverse_iterator reverse_iterator;
885 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
887 Init(nTypeIn, nVersionIn);
890 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
892 Init(nTypeIn, nVersionIn);
895 #if !defined(_MSC_VER) || _MSC_VER >= 1300
896 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
898 Init(nTypeIn, nVersionIn);
902 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
904 Init(nTypeIn, nVersionIn);
907 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
909 Init(nTypeIn, nVersionIn);
912 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
914 Init(nTypeIn, nVersionIn);
917 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
921 nVersion = nVersionIn;
923 exceptmask = std::ios::badbit | std::ios::failbit;
926 CDataStream& operator+=(const CDataStream& b)
928 vch.insert(vch.end(), b.begin(), b.end());
932 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
939 std::string str() const
941 return (std::string(begin(), end()));
948 const_iterator begin() const { return vch.begin() + nReadPos; }
949 iterator begin() { return vch.begin() + nReadPos; }
950 const_iterator end() const { return vch.end(); }
951 iterator end() { return vch.end(); }
952 size_type size() const { return vch.size() - nReadPos; }
953 bool empty() const { return vch.size() == nReadPos; }
954 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
955 void reserve(size_type n) { vch.reserve(n + nReadPos); }
956 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
957 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
958 void clear() { vch.clear(); nReadPos = 0; }
959 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
960 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
962 void insert(iterator it, const_iterator first, const_iterator last)
964 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
966 // special case for inserting at the front when there's room
967 nReadPos -= (last - first);
968 memcpy(&vch[nReadPos], &first[0], last - first);
971 vch.insert(it, first, last);
974 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
976 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
978 // special case for inserting at the front when there's room
979 nReadPos -= (last - first);
980 memcpy(&vch[nReadPos], &first[0], last - first);
983 vch.insert(it, first, last);
986 #if !defined(_MSC_VER) || _MSC_VER >= 1300
987 void insert(iterator it, const char* first, const char* last)
989 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
991 // special case for inserting at the front when there's room
992 nReadPos -= (last - first);
993 memcpy(&vch[nReadPos], &first[0], last - first);
996 vch.insert(it, first, last);
1000 iterator erase(iterator it)
1002 if (it == vch.begin() + nReadPos)
1004 // special case for erasing from the front
1005 if (++nReadPos >= vch.size())
1007 // whenever we reach the end, we take the opportunity to clear the buffer
1009 return vch.erase(vch.begin(), vch.end());
1011 return vch.begin() + nReadPos;
1014 return vch.erase(it);
1017 iterator erase(iterator first, iterator last)
1019 if (first == vch.begin() + nReadPos)
1021 // special case for erasing from the front
1022 if (last == vch.end())
1025 return vch.erase(vch.begin(), vch.end());
1029 nReadPos = (last - vch.begin());
1034 return vch.erase(first, last);
1037 inline void Compact()
1039 vch.erase(vch.begin(), vch.begin() + nReadPos);
1043 bool Rewind(size_type n)
1045 // Rewind by n characters if the buffer hasn't been compacted yet
1056 void setstate(short bits, const char* psz)
1059 if (state & exceptmask)
1060 throw std::ios_base::failure(psz);
1063 bool eof() const { return size() == 0; }
1064 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1065 bool good() const { return !eof() && (state == 0); }
1066 void clear(short n) { state = n; } // name conflict with vector clear()
1067 short exceptions() { return exceptmask; }
1068 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1069 CDataStream* rdbuf() { return this; }
1070 int in_avail() { return size(); }
1072 void SetType(int n) { nType = n; }
1073 int GetType() { return nType; }
1074 void SetVersion(int n) { nVersion = n; }
1075 int GetVersion() { return nVersion; }
1076 void ReadVersion() { *this >> nVersion; }
1077 void WriteVersion() { *this << nVersion; }
1079 CDataStream& read(char* pch, int nSize)
1081 // Read from the beginning of the buffer
1083 unsigned int nReadPosNext = nReadPos + nSize;
1084 if (nReadPosNext >= vch.size())
1086 if (nReadPosNext > vch.size())
1088 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1089 memset(pch, 0, nSize);
1090 nSize = vch.size() - nReadPos;
1092 memcpy(pch, &vch[nReadPos], nSize);
1097 memcpy(pch, &vch[nReadPos], nSize);
1098 nReadPos = nReadPosNext;
1102 CDataStream& ignore(int nSize)
1104 // Ignore from the beginning of the buffer
1106 unsigned int nReadPosNext = nReadPos + nSize;
1107 if (nReadPosNext >= vch.size())
1109 if (nReadPosNext > vch.size())
1111 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1112 nSize = vch.size() - nReadPos;
1118 nReadPos = nReadPosNext;
1122 CDataStream& write(const char* pch, int nSize)
1124 // Write to the end of the buffer
1126 vch.insert(vch.end(), pch, pch + nSize);
1130 template<typename Stream>
1131 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
1133 // Special case: stream << stream concatenates like stream += stream
1135 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1138 template<typename T>
1139 unsigned int GetSerializeSize(const T& obj)
1141 // Tells the size of the object if serialized to this stream
1142 return ::GetSerializeSize(obj, nType, nVersion);
1145 template<typename T>
1146 CDataStream& operator<<(const T& obj)
1148 // Serialize to this stream
1149 ::Serialize(*this, obj, nType, nVersion);
1153 template<typename T>
1154 CDataStream& operator>>(T& obj)
1156 // Unserialize from this stream
1157 ::Unserialize(*this, obj, nType, nVersion);
1162 #ifdef TESTCDATASTREAM
1169 // n=16000 0 seconds
1170 // n=32000 0 seconds
1171 // n=64000 1 seconds
1172 // n=128000 1 seconds
1173 // n=256000 2 seconds
1174 // n=512000 4 seconds
1175 // n=1024000 8 seconds
1176 // n=2048000 16 seconds
1177 // n=4096000 32 seconds
1181 // n=4000 13 seconds
1182 // n=8000 87 seconds
1183 // n=16000 400 seconds
1184 // n=32000 1660 seconds
1185 // n=64000 6749 seconds
1186 // n=128000 27241 seconds
1187 // n=256000 109804 seconds
1189 int main(int argc, char *argv[])
1191 vector<unsigned char> vch(0xcc, 250);
1192 printf("CDataStream:\n");
1193 for (int n = 1000; n <= 4500000; n *= 2)
1196 time_t nStart = time(NULL);
1197 for (int i = 0; i < n; i++)
1198 ss.write((char*)&vch[0], vch.size());
1199 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1201 printf("stringstream:\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);
1223 // Automatic closing wrapper for FILE*
1224 // - Will automatically close the file when it goes out of scope if not null.
1225 // - If you're returning the file pointer, return file.release().
1226 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1238 typedef FILE element_type;
1240 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=PROTOCOL_VERSION)
1244 nVersion = nVersionIn;
1246 exceptmask = std::ios::badbit | std::ios::failbit;
1256 if (file != NULL && file != stdin && file != stdout && file != stderr)
1261 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1262 operator FILE*() { return file; }
1263 FILE* operator->() { return file; }
1264 FILE& operator*() { return *file; }
1265 FILE** operator&() { return &file; }
1266 FILE* operator=(FILE* pnew) { return file = pnew; }
1267 bool operator!() { return (file == NULL); }
1273 void setstate(short bits, const char* psz)
1276 if (state & exceptmask)
1277 throw std::ios_base::failure(psz);
1280 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1281 bool good() const { return state == 0; }
1282 void clear(short n = 0) { state = n; }
1283 short exceptions() { return exceptmask; }
1284 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1286 void SetType(int n) { nType = n; }
1287 int GetType() { return nType; }
1288 void SetVersion(int n) { nVersion = n; }
1289 int GetVersion() { return nVersion; }
1290 void ReadVersion() { *this >> nVersion; }
1291 void WriteVersion() { *this << nVersion; }
1293 CAutoFile& read(char* pch, int nSize)
1296 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1297 if (fread(pch, 1, nSize, file) != nSize)
1298 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1302 CAutoFile& write(const char* pch, int nSize)
1305 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1306 if (fwrite(pch, 1, nSize, file) != nSize)
1307 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1311 template<typename T>
1312 unsigned int GetSerializeSize(const T& obj)
1314 // Tells the size of the object if serialized to this stream
1315 return ::GetSerializeSize(obj, nType, nVersion);
1318 template<typename T>
1319 CAutoFile& operator<<(const T& obj)
1321 // Serialize to this stream
1323 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1324 ::Serialize(*this, obj, nType, nVersion);
1328 template<typename T>
1329 CAutoFile& operator>>(T& obj)
1331 // Unserialize from this stream
1333 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1334 ::Unserialize(*this, obj, nType, nVersion);