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 #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 = 40300;
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; \
102 s.nVersion = nVersion; \
106 template<typename Stream> \
107 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const \
109 CSerActionSerialize ser_action; \
110 const bool fGetSize = false; \
111 const bool fWrite = true; \
112 const bool fRead = false; \
113 unsigned int nSerSize = 0; \
116 template<typename Stream> \
117 void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) \
119 CSerActionUnserialize ser_action; \
120 const bool fGetSize = false; \
121 const bool fWrite = false; \
122 const bool fRead = true; \
123 unsigned int nSerSize = 0; \
127 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
137 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
138 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
140 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
141 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
142 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
143 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
144 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
145 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
146 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
147 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
148 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
149 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
150 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
151 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
152 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
154 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
155 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
156 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
157 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
158 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
159 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
160 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
161 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
162 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
163 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
164 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
165 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
166 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
168 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
169 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
170 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
171 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
172 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
173 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
174 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
175 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
176 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
177 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
178 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
179 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
180 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
182 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
183 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
184 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
193 // size < 253 -- 1 byte
194 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
195 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
196 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
198 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
200 if (nSize < 253) return sizeof(unsigned char);
201 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);
202 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);
203 else return sizeof(unsigned char) + sizeof(uint64);
206 template<typename Stream>
207 void WriteCompactSize(Stream& os, uint64 nSize)
211 unsigned char chSize = nSize;
212 WRITEDATA(os, chSize);
214 else if (nSize <= USHRT_MAX)
216 unsigned char chSize = 253;
217 unsigned short xSize = nSize;
218 WRITEDATA(os, chSize);
219 WRITEDATA(os, xSize);
221 else if (nSize <= UINT_MAX)
223 unsigned char chSize = 254;
224 unsigned int xSize = nSize;
225 WRITEDATA(os, chSize);
226 WRITEDATA(os, xSize);
230 unsigned char chSize = 255;
231 uint64 xSize = nSize;
232 WRITEDATA(os, chSize);
233 WRITEDATA(os, xSize);
238 template<typename Stream>
239 uint64 ReadCompactSize(Stream& is)
241 unsigned char chSize;
242 READDATA(is, chSize);
248 else if (chSize == 253)
250 unsigned short xSize;
254 else if (chSize == 254)
266 if (nSizeRet > (uint64)MAX_SIZE)
267 throw std::ios_base::failure("ReadCompactSize() : size too large");
274 // Wrapper for serializing arrays and POD
275 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
277 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
284 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
285 char* begin() { return pbegin; }
286 const char* begin() const { return pbegin; }
287 char* end() { return pend; }
288 const char* end() const { return pend; }
290 unsigned int GetSerializeSize(int, int=0) const
292 return pend - pbegin;
295 template<typename Stream>
296 void Serialize(Stream& s, int, int=0) const
298 s.write(pbegin, pend - pbegin);
301 template<typename Stream>
302 void Unserialize(Stream& s, int, int=0)
304 s.read(pbegin, pend - pbegin);
311 // string stored as a fixed length field
313 template<std::size_t LEN>
314 class CFixedFieldString
317 const std::string* pcstr;
320 explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
321 explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
323 unsigned int GetSerializeSize(int, int=0) const
328 template<typename Stream>
329 void Serialize(Stream& s, int, int=0) const
332 strncpy(pszBuf, pcstr->c_str(), LEN);
333 s.write(pszBuf, LEN);
336 template<typename Stream>
337 void Unserialize(Stream& s, int, int=0)
340 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
353 // Forward declarations
357 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
358 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
359 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
362 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
363 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
364 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);
365 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&);
366 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&);
367 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);
368 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&);
369 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&);
370 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);
372 // others derived from vector
373 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);
374 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);
375 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);
378 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);
379 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);
380 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);
383 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
384 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);
385 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
388 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);
389 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);
390 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);
393 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);
394 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);
395 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);
398 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
399 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);
400 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
407 // If none of the specialized versions above matched, default to calling member function.
408 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
409 // The compiler will only cast int to long if none of the other templates matched.
410 // Thanks to Boost serialization for this idea.
413 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)
415 return a.GetSerializeSize((int)nType, nVersion);
418 template<typename Stream, typename T>
419 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)
421 a.Serialize(os, (int)nType, nVersion);
424 template<typename Stream, typename T>
425 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)
427 a.Unserialize(is, (int)nType, nVersion);
438 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
440 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
443 template<typename Stream, typename C>
444 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
446 WriteCompactSize(os, str.size());
448 os.write((char*)&str[0], str.size() * sizeof(str[0]));
451 template<typename Stream, typename C>
452 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
454 unsigned int nSize = ReadCompactSize(is);
457 is.read((char*)&str[0], nSize * sizeof(str[0]));
465 template<typename T, typename A>
466 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
468 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
471 template<typename T, typename A>
472 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
474 unsigned int nSize = GetSizeOfCompactSize(v.size());
475 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
476 nSize += GetSerializeSize((*vi), nType, nVersion);
480 template<typename T, typename A>
481 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
483 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
487 template<typename Stream, typename T, typename A>
488 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
490 WriteCompactSize(os, v.size());
492 os.write((char*)&v[0], v.size() * sizeof(T));
495 template<typename Stream, typename T, typename A>
496 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
498 WriteCompactSize(os, v.size());
499 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
500 ::Serialize(os, (*vi), nType, nVersion);
503 template<typename Stream, typename T, typename A>
504 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
506 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
510 template<typename Stream, typename T, typename A>
511 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
513 //unsigned int nSize = ReadCompactSize(is);
515 //is.read((char*)&v[0], nSize * sizeof(T));
517 // Limit size per read so bogus size value won't cause out of memory
519 unsigned int nSize = ReadCompactSize(is);
523 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
525 is.read((char*)&v[i], blk * sizeof(T));
530 template<typename Stream, typename T, typename A>
531 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
533 //unsigned int nSize = ReadCompactSize(is);
535 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
536 // Unserialize(is, (*vi), nType, nVersion);
539 unsigned int nSize = ReadCompactSize(is);
541 unsigned int nMid = 0;
544 nMid += 5000000 / sizeof(T);
548 for (; i < nMid; i++)
549 Unserialize(is, v[i], nType, nVersion);
553 template<typename Stream, typename T, typename A>
554 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
556 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
562 // others derived from vector
564 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
566 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
569 template<typename Stream>
570 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
572 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
575 template<typename Stream>
576 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
578 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
586 template<typename K, typename T>
587 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
589 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
592 template<typename Stream, typename K, typename T>
593 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
595 Serialize(os, item.first, nType, nVersion);
596 Serialize(os, item.second, nType, nVersion);
599 template<typename Stream, typename K, typename T>
600 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
602 Unserialize(is, item.first, nType, nVersion);
603 Unserialize(is, item.second, nType, nVersion);
611 template<typename T0, typename T1, typename T2>
612 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
614 unsigned int nSize = 0;
615 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
616 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
617 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
621 template<typename Stream, typename T0, typename T1, typename T2>
622 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
624 Serialize(os, boost::get<0>(item), nType, nVersion);
625 Serialize(os, boost::get<1>(item), nType, nVersion);
626 Serialize(os, boost::get<2>(item), nType, nVersion);
629 template<typename Stream, typename T0, typename T1, typename T2>
630 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
632 Unserialize(is, boost::get<0>(item), nType, nVersion);
633 Unserialize(is, boost::get<1>(item), nType, nVersion);
634 Unserialize(is, boost::get<2>(item), nType, nVersion);
642 template<typename T0, typename T1, typename T2, typename T3>
643 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
645 unsigned int nSize = 0;
646 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
647 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
648 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
649 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
653 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
654 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
656 Serialize(os, boost::get<0>(item), nType, nVersion);
657 Serialize(os, boost::get<1>(item), nType, nVersion);
658 Serialize(os, boost::get<2>(item), nType, nVersion);
659 Serialize(os, boost::get<3>(item), nType, nVersion);
662 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
663 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
665 Unserialize(is, boost::get<0>(item), nType, nVersion);
666 Unserialize(is, boost::get<1>(item), nType, nVersion);
667 Unserialize(is, boost::get<2>(item), nType, nVersion);
668 Unserialize(is, boost::get<3>(item), nType, nVersion);
676 template<typename K, typename T, typename Pred, typename A>
677 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
679 unsigned int nSize = GetSizeOfCompactSize(m.size());
680 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
681 nSize += GetSerializeSize((*mi), nType, nVersion);
685 template<typename Stream, typename K, typename T, typename Pred, typename A>
686 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
688 WriteCompactSize(os, m.size());
689 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
690 Serialize(os, (*mi), nType, nVersion);
693 template<typename Stream, typename K, typename T, typename Pred, typename A>
694 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
697 unsigned int nSize = ReadCompactSize(is);
698 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
699 for (unsigned int i = 0; i < nSize; i++)
701 std::pair<K, T> item;
702 Unserialize(is, item, nType, nVersion);
703 mi = m.insert(mi, item);
712 template<typename K, typename Pred, typename A>
713 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
715 unsigned int nSize = GetSizeOfCompactSize(m.size());
716 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
717 nSize += GetSerializeSize((*it), nType, nVersion);
721 template<typename Stream, typename K, typename Pred, typename A>
722 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
724 WriteCompactSize(os, m.size());
725 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
726 Serialize(os, (*it), nType, nVersion);
729 template<typename Stream, typename K, typename Pred, typename A>
730 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
733 unsigned int nSize = ReadCompactSize(is);
734 typename std::set<K, Pred, A>::iterator it = m.begin();
735 for (unsigned int i = 0; i < nSize; i++)
738 Unserialize(is, key, nType, nVersion);
739 it = m.insert(it, key);
746 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
748 class CSerActionGetSerializeSize { };
749 class CSerActionSerialize { };
750 class CSerActionUnserialize { };
752 template<typename Stream, typename T>
753 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
755 return ::GetSerializeSize(obj, nType, nVersion);
758 template<typename Stream, typename T>
759 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
761 ::Serialize(s, obj, nType, nVersion);
765 template<typename Stream, typename T>
766 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
768 ::Unserialize(s, obj, nType, nVersion);
772 struct ser_streamplaceholder
787 // Allocator that locks its contents from being paged
788 // out of memory and clears its contents before deletion.
791 struct secure_allocator : public std::allocator<T>
793 // MSVC8 default copy constructor is broken
794 typedef std::allocator<T> base;
795 typedef typename base::size_type size_type;
796 typedef typename base::difference_type difference_type;
797 typedef typename base::pointer pointer;
798 typedef typename base::const_pointer const_pointer;
799 typedef typename base::reference reference;
800 typedef typename base::const_reference const_reference;
801 typedef typename base::value_type value_type;
802 secure_allocator() throw() {}
803 secure_allocator(const secure_allocator& a) throw() : base(a) {}
804 template <typename U>
805 secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
806 ~secure_allocator() throw() {}
807 template<typename _Other> struct rebind
808 { typedef secure_allocator<_Other> other; };
810 T* allocate(std::size_t n, const void *hint = 0)
813 p = std::allocator<T>::allocate(n, hint);
815 mlock(p, sizeof(T) * n);
819 void deallocate(T* p, std::size_t n)
823 memset(p, 0, sizeof(T) * n);
824 munlock(p, sizeof(T) * n);
826 std::allocator<T>::deallocate(p, n);
832 // Allocator that clears its contents before deletion.
835 struct zero_after_free_allocator : public std::allocator<T>
837 // MSVC8 default copy constructor is broken
838 typedef std::allocator<T> base;
839 typedef typename base::size_type size_type;
840 typedef typename base::difference_type difference_type;
841 typedef typename base::pointer pointer;
842 typedef typename base::const_pointer const_pointer;
843 typedef typename base::reference reference;
844 typedef typename base::const_reference const_reference;
845 typedef typename base::value_type value_type;
846 zero_after_free_allocator() throw() {}
847 zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
848 template <typename U>
849 zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a) {}
850 ~zero_after_free_allocator() throw() {}
851 template<typename _Other> struct rebind
852 { typedef zero_after_free_allocator<_Other> other; };
854 void deallocate(T* p, std::size_t n)
857 memset(p, 0, sizeof(T) * n);
858 std::allocator<T>::deallocate(p, n);
865 // Double ended buffer combining vector and stream-like interfaces.
866 // >> and << read and write unformatted data using the above serialization templates.
867 // Fills with data in linear time; some stringstream implementations take N^2 time.
872 typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
874 unsigned int nReadPos;
881 typedef vector_type::allocator_type allocator_type;
882 typedef vector_type::size_type size_type;
883 typedef vector_type::difference_type difference_type;
884 typedef vector_type::reference reference;
885 typedef vector_type::const_reference const_reference;
886 typedef vector_type::value_type value_type;
887 typedef vector_type::iterator iterator;
888 typedef vector_type::const_iterator const_iterator;
889 typedef vector_type::reverse_iterator reverse_iterator;
891 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
893 Init(nTypeIn, nVersionIn);
896 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
898 Init(nTypeIn, nVersionIn);
901 #if !defined(_MSC_VER) || _MSC_VER >= 1300
902 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
904 Init(nTypeIn, nVersionIn);
908 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
910 Init(nTypeIn, nVersionIn);
913 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
915 Init(nTypeIn, nVersionIn);
918 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
920 Init(nTypeIn, nVersionIn);
923 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
927 nVersion = nVersionIn;
929 exceptmask = std::ios::badbit | std::ios::failbit;
932 CDataStream& operator+=(const CDataStream& b)
934 vch.insert(vch.end(), b.begin(), b.end());
938 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
945 std::string str() const
947 return (std::string(begin(), end()));
954 const_iterator begin() const { return vch.begin() + nReadPos; }
955 iterator begin() { return vch.begin() + nReadPos; }
956 const_iterator end() const { return vch.end(); }
957 iterator end() { return vch.end(); }
958 size_type size() const { return vch.size() - nReadPos; }
959 bool empty() const { return vch.size() == nReadPos; }
960 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
961 void reserve(size_type n) { vch.reserve(n + nReadPos); }
962 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
963 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
964 void clear() { vch.clear(); nReadPos = 0; }
965 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
966 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
968 void insert(iterator it, const_iterator first, const_iterator last)
970 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
972 // special case for inserting at the front when there's room
973 nReadPos -= (last - first);
974 memcpy(&vch[nReadPos], &first[0], last - first);
977 vch.insert(it, first, last);
980 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
982 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
984 // special case for inserting at the front when there's room
985 nReadPos -= (last - first);
986 memcpy(&vch[nReadPos], &first[0], last - first);
989 vch.insert(it, first, last);
992 #if !defined(_MSC_VER) || _MSC_VER >= 1300
993 void insert(iterator it, const char* first, const char* last)
995 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
997 // special case for inserting at the front when there's room
998 nReadPos -= (last - first);
999 memcpy(&vch[nReadPos], &first[0], last - first);
1002 vch.insert(it, first, last);
1006 iterator erase(iterator it)
1008 if (it == vch.begin() + nReadPos)
1010 // special case for erasing from the front
1011 if (++nReadPos >= vch.size())
1013 // whenever we reach the end, we take the opportunity to clear the buffer
1015 return vch.erase(vch.begin(), vch.end());
1017 return vch.begin() + nReadPos;
1020 return vch.erase(it);
1023 iterator erase(iterator first, iterator last)
1025 if (first == vch.begin() + nReadPos)
1027 // special case for erasing from the front
1028 if (last == vch.end())
1031 return vch.erase(vch.begin(), vch.end());
1035 nReadPos = (last - vch.begin());
1040 return vch.erase(first, last);
1043 inline void Compact()
1045 vch.erase(vch.begin(), vch.begin() + nReadPos);
1049 bool Rewind(size_type n)
1051 // Rewind by n characters if the buffer hasn't been compacted yet
1062 void setstate(short bits, const char* psz)
1065 if (state & exceptmask)
1066 throw std::ios_base::failure(psz);
1069 bool eof() const { return size() == 0; }
1070 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1071 bool good() const { return !eof() && (state == 0); }
1072 void clear(short n) { state = n; } // name conflict with vector clear()
1073 short exceptions() { return exceptmask; }
1074 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1075 CDataStream* rdbuf() { return this; }
1076 int in_avail() { return size(); }
1078 void SetType(int n) { nType = n; }
1079 int GetType() { return nType; }
1080 void SetVersion(int n) { nVersion = n; }
1081 int GetVersion() { return nVersion; }
1082 void ReadVersion() { *this >> nVersion; }
1083 void WriteVersion() { *this << nVersion; }
1085 CDataStream& read(char* pch, int nSize)
1087 // Read from the beginning of the buffer
1089 unsigned int nReadPosNext = nReadPos + nSize;
1090 if (nReadPosNext >= vch.size())
1092 if (nReadPosNext > vch.size())
1094 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1095 memset(pch, 0, nSize);
1096 nSize = vch.size() - nReadPos;
1098 memcpy(pch, &vch[nReadPos], nSize);
1103 memcpy(pch, &vch[nReadPos], nSize);
1104 nReadPos = nReadPosNext;
1108 CDataStream& ignore(int nSize)
1110 // Ignore from the beginning of the buffer
1112 unsigned int nReadPosNext = nReadPos + nSize;
1113 if (nReadPosNext >= vch.size())
1115 if (nReadPosNext > vch.size())
1117 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1118 nSize = vch.size() - nReadPos;
1124 nReadPos = nReadPosNext;
1128 CDataStream& write(const char* pch, int nSize)
1130 // Write to the end of the buffer
1132 vch.insert(vch.end(), pch, pch + nSize);
1136 template<typename Stream>
1137 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const
1139 // Special case: stream << stream concatenates like stream += stream
1141 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1144 template<typename T>
1145 unsigned int GetSerializeSize(const T& obj)
1147 // Tells the size of the object if serialized to this stream
1148 return ::GetSerializeSize(obj, nType, nVersion);
1151 template<typename T>
1152 CDataStream& operator<<(const T& obj)
1154 // Serialize to this stream
1155 ::Serialize(*this, obj, nType, nVersion);
1159 template<typename T>
1160 CDataStream& operator>>(T& obj)
1162 // Unserialize from this stream
1163 ::Unserialize(*this, obj, nType, nVersion);
1168 #ifdef TESTCDATASTREAM
1175 // n=16000 0 seconds
1176 // n=32000 0 seconds
1177 // n=64000 1 seconds
1178 // n=128000 1 seconds
1179 // n=256000 2 seconds
1180 // n=512000 4 seconds
1181 // n=1024000 8 seconds
1182 // n=2048000 16 seconds
1183 // n=4096000 32 seconds
1187 // n=4000 13 seconds
1188 // n=8000 87 seconds
1189 // n=16000 400 seconds
1190 // n=32000 1660 seconds
1191 // n=64000 6749 seconds
1192 // n=128000 27241 seconds
1193 // n=256000 109804 seconds
1195 int main(int argc, char *argv[])
1197 vector<unsigned char> vch(0xcc, 250);
1198 printf("CDataStream:\n");
1199 for (int n = 1000; n <= 4500000; n *= 2)
1202 time_t nStart = time(NULL);
1203 for (int i = 0; i < n; i++)
1204 ss.write((char*)&vch[0], vch.size());
1205 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1207 printf("stringstream:\n");
1208 for (int n = 1000; n <= 4500000; n *= 2)
1211 time_t nStart = time(NULL);
1212 for (int i = 0; i < n; i++)
1213 ss.write((char*)&vch[0], vch.size());
1214 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1229 // Automatic closing wrapper for FILE*
1230 // - Will automatically close the file when it goes out of scope if not null.
1231 // - If you're returning the file pointer, return file.release().
1232 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1244 typedef FILE element_type;
1246 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)
1250 nVersion = nVersionIn;
1252 exceptmask = std::ios::badbit | std::ios::failbit;
1262 if (file != NULL && file != stdin && file != stdout && file != stderr)
1267 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1268 operator FILE*() { return file; }
1269 FILE* operator->() { return file; }
1270 FILE& operator*() { return *file; }
1271 FILE** operator&() { return &file; }
1272 FILE* operator=(FILE* pnew) { return file = pnew; }
1273 bool operator!() { return (file == NULL); }
1279 void setstate(short bits, const char* psz)
1282 if (state & exceptmask)
1283 throw std::ios_base::failure(psz);
1286 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1287 bool good() const { return state == 0; }
1288 void clear(short n = 0) { state = n; }
1289 short exceptions() { return exceptmask; }
1290 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1292 void SetType(int n) { nType = n; }
1293 int GetType() { return nType; }
1294 void SetVersion(int n) { nVersion = n; }
1295 int GetVersion() { return nVersion; }
1296 void ReadVersion() { *this >> nVersion; }
1297 void WriteVersion() { *this << nVersion; }
1299 CAutoFile& read(char* pch, int nSize)
1302 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1303 if (fread(pch, 1, nSize, file) != nSize)
1304 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1308 CAutoFile& write(const char* pch, int nSize)
1311 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1312 if (fwrite(pch, 1, nSize, file) != nSize)
1313 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1317 template<typename T>
1318 unsigned int GetSerializeSize(const T& obj)
1320 // Tells the size of the object if serialized to this stream
1321 return ::GetSerializeSize(obj, nType, nVersion);
1324 template<typename T>
1325 CAutoFile& operator<<(const T& obj)
1327 // Serialize to this stream
1329 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1330 ::Serialize(*this, obj, nType, nVersion);
1334 template<typename T>
1335 CAutoFile& operator>>(T& obj)
1337 // Unserialize from this stream
1339 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1340 ::Unserialize(*this, obj, nType, nVersion);