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
19 #include <boost/type_traits/is_fundamental.hpp>
20 #include <boost/tuple/tuple.hpp>
21 #include <boost/tuple/tuple_comparison.hpp>
22 #include <boost/tuple/tuple_io.hpp>
26 // This is used to attempt to keep keying material out of swap
27 // Note that VirtualLock does not provide this as a guarantee on Windows,
28 // but, in practice, memory that has been VirtualLock'd almost never gets written to
29 // the pagefile except in rare circumstances where memory is extremely low.
31 #define mlock(p, n) VirtualLock((p), (n));
32 #define munlock(p, n) VirtualUnlock((p), (n));
36 /* This comes from limits.h if it's not defined there set a sane default */
39 #define PAGESIZE sysconf(_SC_PAGESIZE)
42 mlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
43 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
44 #define munlock(a,b) \
45 munlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
46 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
52 static const unsigned int MAX_SIZE = 0x02000000;
54 static const int PROTOCOL_VERSION = 60000;
56 // Used to bypass the rule against non-const reference to temporary
57 // where it makes sense with wrappers such as CFlatData or CTxDB
59 inline T& REF(const T& val)
61 return const_cast<T&>(val);
64 /////////////////////////////////////////////////////////////////
66 // Templates for serializing to anything that looks like a stream,
67 // i.e. anything that supports .read(char*, int) and .write(char*, int)
73 SER_NETWORK = (1 << 0),
75 SER_GETHASH = (1 << 2),
78 SER_SKIPSIG = (1 << 16),
79 SER_BLOCKHEADERONLY = (1 << 17),
82 #define IMPLEMENT_SERIALIZE(statements) \
83 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const \
85 CSerActionGetSerializeSize ser_action; \
86 const bool fGetSize = true; \
87 const bool fWrite = false; \
88 const bool fRead = false; \
89 unsigned int nSerSize = 0; \
90 ser_streamplaceholder s; \
92 s.nVersion = nVersion; \
96 template<typename Stream> \
97 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const \
99 CSerActionSerialize ser_action; \
100 const bool fGetSize = false; \
101 const bool fWrite = true; \
102 const bool fRead = false; \
103 unsigned int nSerSize = 0; \
106 template<typename Stream> \
107 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) \
109 CSerActionUnserialize ser_action; \
110 const bool fGetSize = false; \
111 const bool fWrite = false; \
112 const bool fRead = true; \
113 unsigned int nSerSize = 0; \
117 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
127 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
128 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
130 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
131 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
132 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
133 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
134 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
135 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
136 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
137 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
138 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
139 inline unsigned int GetSerializeSize(int64_t a, int, int=0) { return sizeof(a); }
140 inline unsigned int GetSerializeSize(uint64_t a, int, int=0) { return sizeof(a); }
141 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
142 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
144 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
145 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
146 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
147 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
148 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
149 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
150 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
151 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
152 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
153 template<typename Stream> inline void Serialize(Stream& s, int64_t a, int, int=0) { WRITEDATA(s, a); }
154 template<typename Stream> inline void Serialize(Stream& s, uint64_t a, int, int=0) { WRITEDATA(s, a); }
155 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
156 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
158 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
159 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
160 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
161 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
162 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
163 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
164 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
165 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
166 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
167 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a, int, int=0) { READDATA(s, a); }
168 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a, int, int=0) { READDATA(s, a); }
169 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
170 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
172 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
173 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
174 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
183 // size < 253 -- 1 byte
184 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
185 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
186 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
188 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
190 if (nSize < 253) return sizeof(unsigned char);
191 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
192 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
193 else return sizeof(unsigned char) + sizeof(uint64_t);
196 template<typename Stream>
197 void WriteCompactSize(Stream& os, uint64_t nSize)
201 unsigned char chSize = nSize;
202 WRITEDATA(os, chSize);
204 else if (nSize <= std::numeric_limits<unsigned short>::max())
206 unsigned char chSize = 253;
207 unsigned short xSize = nSize;
208 WRITEDATA(os, chSize);
209 WRITEDATA(os, xSize);
211 else if (nSize <= std::numeric_limits<unsigned int>::max())
213 unsigned char chSize = 254;
214 unsigned int xSize = nSize;
215 WRITEDATA(os, chSize);
216 WRITEDATA(os, xSize);
220 unsigned char chSize = 255;
221 uint64_t xSize = nSize;
222 WRITEDATA(os, chSize);
223 WRITEDATA(os, xSize);
228 template<typename Stream>
229 uint64_t ReadCompactSize(Stream& is)
231 unsigned char chSize;
232 READDATA(is, chSize);
233 uint64_t nSizeRet = 0;
238 else if (chSize == 253)
240 unsigned short xSize;
244 else if (chSize == 254)
256 if (nSizeRet > (uint64_t)MAX_SIZE)
257 throw std::ios_base::failure("ReadCompactSize() : size too large");
264 // Wrapper for serializing arrays and POD
265 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
267 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
274 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
275 char* begin() { return pbegin; }
276 const char* begin() const { return pbegin; }
277 char* end() { return pend; }
278 const char* end() const { return pend; }
280 unsigned int GetSerializeSize(int, int=0) const
282 return pend - pbegin;
285 template<typename Stream>
286 void Serialize(Stream& s, int, int=0) const
288 s.write(pbegin, pend - pbegin);
291 template<typename Stream>
292 void Unserialize(Stream& s, int, int=0)
294 s.read(pbegin, pend - pbegin);
301 // string stored as a fixed length field
303 template<std::size_t LEN>
304 class CFixedFieldString
307 const std::string* pcstr;
310 explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
311 explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
313 unsigned int GetSerializeSize(int, int=0) const
318 template<typename Stream>
319 void Serialize(Stream& s, int, int=0) const
322 strncpy(pszBuf, pcstr->c_str(), LEN);
323 s.write(pszBuf, LEN);
326 template<typename Stream>
327 void Unserialize(Stream& s, int, int=0)
330 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
343 // Forward declarations
347 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
348 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
349 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
352 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
353 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
354 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
355 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&);
356 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&);
357 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
358 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&);
359 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&);
360 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
362 // others derived from vector
363 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
364 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
365 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
368 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
369 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
370 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
373 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
374 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);
375 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);
378 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);
379 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);
380 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);
383 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);
384 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);
385 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);
388 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
389 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);
390 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);
397 // If none of the specialized versions above matched, default to calling member function.
398 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
399 // The compiler will only cast int to long if none of the other templates matched.
400 // Thanks to Boost serialization for this idea.
403 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=PROTOCOL_VERSION)
405 return a.GetSerializeSize((int)nType, nVersion);
408 template<typename Stream, typename T>
409 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=PROTOCOL_VERSION)
411 a.Serialize(os, (int)nType, nVersion);
414 template<typename Stream, typename T>
415 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=PROTOCOL_VERSION)
417 a.Unserialize(is, (int)nType, nVersion);
428 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
430 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
433 template<typename Stream, typename C>
434 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
436 WriteCompactSize(os, str.size());
438 os.write((char*)&str[0], str.size() * sizeof(str[0]));
441 template<typename Stream, typename C>
442 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
444 unsigned int nSize = ReadCompactSize(is);
447 is.read((char*)&str[0], nSize * sizeof(str[0]));
455 template<typename T, typename A>
456 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
458 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
461 template<typename T, typename A>
462 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
464 unsigned int nSize = GetSizeOfCompactSize(v.size());
465 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
466 nSize += GetSerializeSize((*vi), nType, nVersion);
470 template<typename T, typename A>
471 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
473 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
477 template<typename Stream, typename T, typename A>
478 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
480 WriteCompactSize(os, v.size());
482 os.write((char*)&v[0], v.size() * sizeof(T));
485 template<typename Stream, typename T, typename A>
486 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
488 WriteCompactSize(os, v.size());
489 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
490 ::Serialize(os, (*vi), nType, nVersion);
493 template<typename Stream, typename T, typename A>
494 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
496 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
500 template<typename Stream, typename T, typename A>
501 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
503 //unsigned int nSize = ReadCompactSize(is);
505 //is.read((char*)&v[0], nSize * sizeof(T));
507 // Limit size per read so bogus size value won't cause out of memory
509 unsigned int nSize = ReadCompactSize(is);
513 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
515 is.read((char*)&v[i], blk * sizeof(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::false_type&)
523 //unsigned int nSize = ReadCompactSize(is);
525 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
526 // Unserialize(is, (*vi), nType, nVersion);
529 unsigned int nSize = ReadCompactSize(is);
531 unsigned int nMid = 0;
534 nMid += 5000000 / sizeof(T);
538 for (; i < nMid; i++)
539 Unserialize(is, v[i], nType, nVersion);
543 template<typename Stream, typename T, typename A>
544 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
546 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
552 // others derived from vector
554 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
556 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
559 template<typename Stream>
560 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
562 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
565 template<typename Stream>
566 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
568 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
576 template<typename K, typename T>
577 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
579 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
582 template<typename Stream, typename K, typename T>
583 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
585 Serialize(os, item.first, nType, nVersion);
586 Serialize(os, item.second, nType, nVersion);
589 template<typename Stream, typename K, typename T>
590 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
592 Unserialize(is, item.first, nType, nVersion);
593 Unserialize(is, item.second, nType, nVersion);
601 template<typename T0, typename T1, typename T2>
602 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
604 unsigned int nSize = 0;
605 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
606 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
607 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
611 template<typename Stream, typename T0, typename T1, typename T2>
612 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
614 Serialize(os, boost::get<0>(item), nType, nVersion);
615 Serialize(os, boost::get<1>(item), nType, nVersion);
616 Serialize(os, boost::get<2>(item), nType, nVersion);
619 template<typename Stream, typename T0, typename T1, typename T2>
620 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
622 Unserialize(is, boost::get<0>(item), nType, nVersion);
623 Unserialize(is, boost::get<1>(item), nType, nVersion);
624 Unserialize(is, boost::get<2>(item), nType, nVersion);
632 template<typename T0, typename T1, typename T2, typename T3>
633 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
635 unsigned int nSize = 0;
636 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
637 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
638 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
639 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
643 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
644 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
646 Serialize(os, boost::get<0>(item), nType, nVersion);
647 Serialize(os, boost::get<1>(item), nType, nVersion);
648 Serialize(os, boost::get<2>(item), nType, nVersion);
649 Serialize(os, boost::get<3>(item), nType, nVersion);
652 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
653 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
655 Unserialize(is, boost::get<0>(item), nType, nVersion);
656 Unserialize(is, boost::get<1>(item), nType, nVersion);
657 Unserialize(is, boost::get<2>(item), nType, nVersion);
658 Unserialize(is, boost::get<3>(item), nType, nVersion);
666 template<typename K, typename T, typename Pred, typename A>
667 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
669 unsigned int nSize = GetSizeOfCompactSize(m.size());
670 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
671 nSize += GetSerializeSize((*mi), nType, nVersion);
675 template<typename Stream, typename K, typename T, typename Pred, typename A>
676 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
678 WriteCompactSize(os, m.size());
679 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
680 Serialize(os, (*mi), nType, nVersion);
683 template<typename Stream, typename K, typename T, typename Pred, typename A>
684 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
687 unsigned int nSize = ReadCompactSize(is);
688 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
689 for (unsigned int i = 0; i < nSize; i++)
691 std::pair<K, T> item;
692 Unserialize(is, item, nType, nVersion);
693 mi = m.insert(mi, item);
702 template<typename K, typename Pred, typename A>
703 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
705 unsigned int nSize = GetSizeOfCompactSize(m.size());
706 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
707 nSize += GetSerializeSize((*it), nType, nVersion);
711 template<typename Stream, typename K, typename Pred, typename A>
712 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
714 WriteCompactSize(os, m.size());
715 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
716 Serialize(os, (*it), nType, nVersion);
719 template<typename Stream, typename K, typename Pred, typename A>
720 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
723 unsigned int nSize = ReadCompactSize(is);
724 typename std::set<K, Pred, A>::iterator it = m.begin();
725 for (unsigned int i = 0; i < nSize; i++)
728 Unserialize(is, key, nType, nVersion);
729 it = m.insert(it, key);
736 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
738 class CSerActionGetSerializeSize { };
739 class CSerActionSerialize { };
740 class CSerActionUnserialize { };
742 template<typename Stream, typename T>
743 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
745 return ::GetSerializeSize(obj, nType, nVersion);
748 template<typename Stream, typename T>
749 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
751 ::Serialize(s, obj, nType, nVersion);
755 template<typename Stream, typename T>
756 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
758 ::Unserialize(s, obj, nType, nVersion);
762 struct ser_streamplaceholder
777 // Allocator that locks its contents from being paged
778 // out of memory and clears its contents before deletion.
781 struct secure_allocator : public std::allocator<T>
783 // MSVC8 default copy constructor is broken
784 typedef std::allocator<T> base;
785 typedef typename base::size_type size_type;
786 typedef typename base::difference_type difference_type;
787 typedef typename base::pointer pointer;
788 typedef typename base::const_pointer const_pointer;
789 typedef typename base::reference reference;
790 typedef typename base::const_reference const_reference;
791 typedef typename base::value_type value_type;
792 secure_allocator() throw() {}
793 secure_allocator(const secure_allocator& a) throw() : base(a) {}
794 template <typename U>
795 secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
796 ~secure_allocator() throw() {}
797 template<typename _Other> struct rebind
798 { typedef secure_allocator<_Other> other; };
800 T* allocate(std::size_t n, const void *hint = 0)
803 p = std::allocator<T>::allocate(n, hint);
805 mlock(p, sizeof(T) * n);
809 void deallocate(T* p, std::size_t n)
813 memset(p, 0, sizeof(T) * n);
814 munlock(p, sizeof(T) * n);
816 std::allocator<T>::deallocate(p, n);
823 // Double ended buffer combining vector and stream-like interfaces.
824 // >> and << read and write unformatted data using the above serialization templates.
825 // Fills with data in linear time; some stringstream implementations take N^2 time.
830 typedef std::vector<char, secure_allocator<char> > vector_type;
832 unsigned int nReadPos;
839 typedef vector_type::allocator_type allocator_type;
840 typedef vector_type::size_type size_type;
841 typedef vector_type::difference_type difference_type;
842 typedef vector_type::reference reference;
843 typedef vector_type::const_reference const_reference;
844 typedef vector_type::value_type value_type;
845 typedef vector_type::iterator iterator;
846 typedef vector_type::const_iterator const_iterator;
847 typedef vector_type::reverse_iterator reverse_iterator;
849 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
851 Init(nTypeIn, nVersionIn);
854 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
856 Init(nTypeIn, nVersionIn);
859 #if !defined(_MSC_VER) || _MSC_VER >= 1300
860 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
862 Init(nTypeIn, nVersionIn);
866 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
868 Init(nTypeIn, nVersionIn);
871 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
873 Init(nTypeIn, nVersionIn);
876 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
878 Init(nTypeIn, nVersionIn);
881 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
885 nVersion = nVersionIn;
887 exceptmask = std::ios::badbit | std::ios::failbit;
890 CDataStream& operator+=(const CDataStream& b)
892 vch.insert(vch.end(), b.begin(), b.end());
896 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
903 std::string str() const
905 return (std::string(begin(), end()));
912 const_iterator begin() const { return vch.begin() + nReadPos; }
913 iterator begin() { return vch.begin() + nReadPos; }
914 const_iterator end() const { return vch.end(); }
915 iterator end() { return vch.end(); }
916 size_type size() const { return vch.size() - nReadPos; }
917 bool empty() const { return vch.size() == nReadPos; }
918 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
919 void reserve(size_type n) { vch.reserve(n + nReadPos); }
920 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
921 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
922 void clear() { vch.clear(); nReadPos = 0; }
923 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
924 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
926 void insert(iterator it, const_iterator first, const_iterator last)
928 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
930 // special case for inserting at the front when there's room
931 nReadPos -= (last - first);
932 memcpy(&vch[nReadPos], &first[0], last - first);
935 vch.insert(it, first, last);
938 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
940 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
942 // special case for inserting at the front when there's room
943 nReadPos -= (last - first);
944 memcpy(&vch[nReadPos], &first[0], last - first);
947 vch.insert(it, first, last);
950 #if !defined(_MSC_VER) || _MSC_VER >= 1300
951 void insert(iterator it, const char* first, const char* last)
953 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
955 // special case for inserting at the front when there's room
956 nReadPos -= (last - first);
957 memcpy(&vch[nReadPos], &first[0], last - first);
960 vch.insert(it, first, last);
964 iterator erase(iterator it)
966 if (it == vch.begin() + nReadPos)
968 // special case for erasing from the front
969 if (++nReadPos >= vch.size())
971 // whenever we reach the end, we take the opportunity to clear the buffer
973 return vch.erase(vch.begin(), vch.end());
975 return vch.begin() + nReadPos;
978 return vch.erase(it);
981 iterator erase(iterator first, iterator last)
983 if (first == vch.begin() + nReadPos)
985 // special case for erasing from the front
986 if (last == vch.end())
989 return vch.erase(vch.begin(), vch.end());
993 nReadPos = (last - vch.begin());
998 return vch.erase(first, last);
1001 inline void Compact()
1003 vch.erase(vch.begin(), vch.begin() + nReadPos);
1007 bool Rewind(size_type n)
1009 // Rewind by n characters if the buffer hasn't been compacted yet
1020 void setstate(short bits, const char* psz)
1023 if (state & exceptmask)
1024 throw std::ios_base::failure(psz);
1027 bool eof() const { return size() == 0; }
1028 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1029 bool good() const { return !eof() && (state == 0); }
1030 void clear(short n) { state = n; } // name conflict with vector clear()
1031 short exceptions() { return exceptmask; }
1032 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1033 CDataStream* rdbuf() { return this; }
1034 int in_avail() { return size(); }
1036 void SetType(int n) { nType = n; }
1037 int GetType() { return nType; }
1038 void SetVersion(int n) { nVersion = n; }
1039 int GetVersion() { return nVersion; }
1040 void ReadVersion() { *this >> nVersion; }
1041 void WriteVersion() { *this << nVersion; }
1043 CDataStream& read(char* pch, int nSize)
1045 // Read from the beginning of the buffer
1047 unsigned int nReadPosNext = nReadPos + nSize;
1048 if (nReadPosNext >= vch.size())
1050 if (nReadPosNext > vch.size())
1052 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1053 memset(pch, 0, nSize);
1054 nSize = vch.size() - nReadPos;
1056 memcpy(pch, &vch[nReadPos], nSize);
1061 memcpy(pch, &vch[nReadPos], nSize);
1062 nReadPos = nReadPosNext;
1066 CDataStream& ignore(int nSize)
1068 // Ignore from the beginning of the buffer
1070 unsigned int nReadPosNext = nReadPos + nSize;
1071 if (nReadPosNext >= vch.size())
1073 if (nReadPosNext > vch.size())
1075 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1076 nSize = vch.size() - nReadPos;
1082 nReadPos = nReadPosNext;
1086 CDataStream& write(const char* pch, int nSize)
1088 // Write to the end of the buffer
1090 vch.insert(vch.end(), pch, pch + nSize);
1094 template<typename Stream>
1095 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
1097 // Special case: stream << stream concatenates like stream += stream
1099 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1102 template<typename T>
1103 unsigned int GetSerializeSize(const T& obj)
1105 // Tells the size of the object if serialized to this stream
1106 return ::GetSerializeSize(obj, nType, nVersion);
1109 template<typename T>
1110 CDataStream& operator<<(const T& obj)
1112 // Serialize to this stream
1113 ::Serialize(*this, obj, nType, nVersion);
1117 template<typename T>
1118 CDataStream& operator>>(T& obj)
1120 // Unserialize from this stream
1121 ::Unserialize(*this, obj, nType, nVersion);
1126 #ifdef TESTCDATASTREAM
1133 // n=16000 0 seconds
1134 // n=32000 0 seconds
1135 // n=64000 1 seconds
1136 // n=128000 1 seconds
1137 // n=256000 2 seconds
1138 // n=512000 4 seconds
1139 // n=1024000 8 seconds
1140 // n=2048000 16 seconds
1141 // n=4096000 32 seconds
1145 // n=4000 13 seconds
1146 // n=8000 87 seconds
1147 // n=16000 400 seconds
1148 // n=32000 1660 seconds
1149 // n=64000 6749 seconds
1150 // n=128000 27241 seconds
1151 // n=256000 109804 seconds
1153 int main(int argc, char *argv[])
1155 vector<unsigned char> vch(0xcc, 250);
1156 printf("CDataStream:\n");
1157 for (int n = 1000; n <= 4500000; n *= 2)
1160 time_t nStart = time(NULL);
1161 for (int i = 0; i < n; i++)
1162 ss.write((char*)&vch[0], vch.size());
1163 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1165 printf("stringstream:\n");
1166 for (int n = 1000; n <= 4500000; n *= 2)
1169 time_t nStart = time(NULL);
1170 for (int i = 0; i < n; i++)
1171 ss.write((char*)&vch[0], vch.size());
1172 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1187 // Automatic closing wrapper for FILE*
1188 // - Will automatically close the file when it goes out of scope if not null.
1189 // - If you're returning the file pointer, return file.release().
1190 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1202 typedef FILE element_type;
1204 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=PROTOCOL_VERSION)
1208 nVersion = nVersionIn;
1210 exceptmask = std::ios::badbit | std::ios::failbit;
1220 if (file != NULL && file != stdin && file != stdout && file != stderr)
1225 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1226 operator FILE*() { return file; }
1227 FILE* operator->() { return file; }
1228 FILE& operator*() { return *file; }
1229 FILE** operator&() { return &file; }
1230 FILE* operator=(FILE* pnew) { return file = pnew; }
1231 bool operator!() { return (file == NULL); }
1237 void setstate(short bits, const char* psz)
1240 if (state & exceptmask)
1241 throw std::ios_base::failure(psz);
1244 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1245 bool good() const { return state == 0; }
1246 void clear(short n = 0) { state = n; }
1247 short exceptions() { return exceptmask; }
1248 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1250 void SetType(int n) { nType = n; }
1251 int GetType() { return nType; }
1252 void SetVersion(int n) { nVersion = n; }
1253 int GetVersion() { return nVersion; }
1254 void ReadVersion() { *this >> nVersion; }
1255 void WriteVersion() { *this << nVersion; }
1257 CAutoFile& read(char* pch, int nSize)
1260 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1261 if (fread(pch, 1, nSize, file) != nSize)
1262 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1266 CAutoFile& write(const char* pch, int nSize)
1269 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1270 if (fwrite(pch, 1, nSize, file) != nSize)
1271 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1275 template<typename T>
1276 unsigned int GetSerializeSize(const T& obj)
1278 // Tells the size of the object if serialized to this stream
1279 return ::GetSerializeSize(obj, nType, nVersion);
1282 template<typename T>
1283 CAutoFile& operator<<(const T& obj)
1285 // Serialize to this stream
1287 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1288 ::Serialize(*this, obj, nType, nVersion);
1292 template<typename T>
1293 CAutoFile& operator>>(T& obj)
1295 // Unserialize from this stream
1297 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1298 ::Unserialize(*this, obj, nType, nVersion);