1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Distributed under the MIT/X11 software license, see the accompanying
3 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
4 #ifndef BITCOIN_SERIALIZE_H
5 #define BITCOIN_SERIALIZE_H
16 #include <boost/type_traits/is_fundamental.hpp>
17 #include <boost/tuple/tuple.hpp>
18 #include <boost/tuple/tuple_comparison.hpp>
19 #include <boost/tuple/tuple_io.hpp>
21 #if defined(_MSC_VER) || defined(__BORLANDC__)
22 typedef __int64 int64;
23 typedef unsigned __int64 uint64;
25 typedef long long int64;
26 typedef unsigned long long uint64;
28 #if defined(_MSC_VER) && _MSC_VER < 1300
29 #define for if (false) ; else for
33 // This is used to attempt to keep keying material out of swap
34 // Note that VirtualLock does not provide this as a guarantee on Windows,
35 // but, in practice, memory that has been VirtualLock'd almost never gets written to
36 // the pagefile except in rare circumstances where memory is extremely low.
37 #define mlock(p, n) VirtualLock((p), (n));
38 #define munlock(p, n) VirtualUnlock((p), (n));
42 /* This comes from limits.h if it's not defined there set a sane default */
45 #define PAGESIZE sysconf(_SC_PAGESIZE)
48 mlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
49 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
50 #define munlock(a,b) \
51 munlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
52 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
58 static const unsigned int MAX_SIZE = 0x02000000;
60 static const int VERSION = 32400;
61 static const char* pszSubVer = "";
62 static const bool VERSION_IS_BETA = true;
69 /////////////////////////////////////////////////////////////////
71 // Templates for serializing to anything that looks like a stream,
72 // i.e. anything that supports .read(char*, int) and .write(char*, int)
78 SER_NETWORK = (1 << 0),
80 SER_GETHASH = (1 << 2),
83 SER_SKIPSIG = (1 << 16),
84 SER_BLOCKHEADERONLY = (1 << 17),
87 #define IMPLEMENT_SERIALIZE(statements) \
88 unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const \
90 CSerActionGetSerializeSize ser_action; \
91 const bool fGetSize = true; \
92 const bool fWrite = false; \
93 const bool fRead = false; \
94 unsigned int nSerSize = 0; \
95 ser_streamplaceholder s; \
97 s.nVersion = nVersion; \
101 template<typename Stream> \
102 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const \
104 CSerActionSerialize ser_action; \
105 const bool fGetSize = false; \
106 const bool fWrite = true; \
107 const bool fRead = false; \
108 unsigned int nSerSize = 0; \
111 template<typename Stream> \
112 void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) \
114 CSerActionUnserialize ser_action; \
115 const bool fGetSize = false; \
116 const bool fWrite = false; \
117 const bool fRead = true; \
118 unsigned int nSerSize = 0; \
122 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
132 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
133 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
135 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
136 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
137 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
138 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
139 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
140 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
141 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
142 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
143 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
144 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
145 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
146 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
147 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
149 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
150 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
151 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
152 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
153 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
154 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
155 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
156 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
157 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
158 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
159 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
160 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
161 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
163 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
164 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
165 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
166 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
167 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
168 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
169 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
170 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
171 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
172 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
173 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
174 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
175 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
177 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
178 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
179 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
188 // size < 253 -- 1 byte
189 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
190 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
191 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
193 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
195 if (nSize < 253) return sizeof(unsigned char);
196 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);
197 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);
198 else return sizeof(unsigned char) + sizeof(uint64);
201 template<typename Stream>
202 void WriteCompactSize(Stream& os, uint64 nSize)
206 unsigned char chSize = nSize;
207 WRITEDATA(os, chSize);
209 else if (nSize <= USHRT_MAX)
211 unsigned char chSize = 253;
212 unsigned short xSize = nSize;
213 WRITEDATA(os, chSize);
214 WRITEDATA(os, xSize);
216 else if (nSize <= UINT_MAX)
218 unsigned char chSize = 254;
219 unsigned int xSize = nSize;
220 WRITEDATA(os, chSize);
221 WRITEDATA(os, xSize);
225 unsigned char chSize = 255;
226 uint64 xSize = nSize;
227 WRITEDATA(os, chSize);
228 WRITEDATA(os, xSize);
233 template<typename Stream>
234 uint64 ReadCompactSize(Stream& is)
236 unsigned char chSize;
237 READDATA(is, chSize);
243 else if (chSize == 253)
245 unsigned short xSize;
249 else if (chSize == 254)
261 if (nSizeRet > (uint64)MAX_SIZE)
262 throw std::ios_base::failure("ReadCompactSize() : size too large");
269 // Wrapper for serializing arrays and POD
270 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
272 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
279 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
280 char* begin() { return pbegin; }
281 const char* begin() const { return pbegin; }
282 char* end() { return pend; }
283 const char* end() const { return pend; }
285 unsigned int GetSerializeSize(int, int=0) const
287 return pend - pbegin;
290 template<typename Stream>
291 void Serialize(Stream& s, int, int=0) const
293 s.write(pbegin, pend - pbegin);
296 template<typename Stream>
297 void Unserialize(Stream& s, int, int=0)
299 s.read(pbegin, pend - pbegin);
306 // string stored as a fixed length field
308 template<std::size_t LEN>
309 class CFixedFieldString
312 const std::string* pcstr;
315 explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
316 explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
318 unsigned int GetSerializeSize(int, int=0) const
323 template<typename Stream>
324 void Serialize(Stream& s, int, int=0) const
327 strncpy(pszBuf, pcstr->c_str(), LEN);
328 s.write(pszBuf, LEN);
331 template<typename Stream>
332 void Unserialize(Stream& s, int, int=0)
335 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
348 // Forward declarations
352 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
353 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
354 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
357 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
358 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
359 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);
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::true_type&);
361 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&);
362 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);
363 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&);
364 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&);
365 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);
367 // others derived from vector
368 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);
369 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);
370 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);
373 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);
374 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);
375 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);
378 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
379 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);
380 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
383 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);
384 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);
385 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);
388 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);
389 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);
390 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);
393 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
394 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);
395 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
402 // If none of the specialized versions above matched, default to calling member function.
403 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
404 // The compiler will only cast int to long if none of the other templates matched.
405 // Thanks to Boost serialization for this idea.
408 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)
410 return a.GetSerializeSize((int)nType, nVersion);
413 template<typename Stream, typename T>
414 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)
416 a.Serialize(os, (int)nType, nVersion);
419 template<typename Stream, typename T>
420 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)
422 a.Unserialize(is, (int)nType, nVersion);
433 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
435 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
438 template<typename Stream, typename C>
439 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
441 WriteCompactSize(os, str.size());
443 os.write((char*)&str[0], str.size() * sizeof(str[0]));
446 template<typename Stream, typename C>
447 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
449 unsigned int nSize = ReadCompactSize(is);
452 is.read((char*)&str[0], nSize * sizeof(str[0]));
460 template<typename T, typename A>
461 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
463 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
466 template<typename T, typename A>
467 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
469 unsigned int nSize = GetSizeOfCompactSize(v.size());
470 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
471 nSize += GetSerializeSize((*vi), nType, nVersion);
475 template<typename T, typename A>
476 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
478 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
482 template<typename Stream, typename T, typename A>
483 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
485 WriteCompactSize(os, v.size());
487 os.write((char*)&v[0], v.size() * sizeof(T));
490 template<typename Stream, typename T, typename A>
491 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
493 WriteCompactSize(os, v.size());
494 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
495 ::Serialize(os, (*vi), nType, nVersion);
498 template<typename Stream, typename T, typename A>
499 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
501 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
505 template<typename Stream, typename T, typename A>
506 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
508 //unsigned int nSize = ReadCompactSize(is);
510 //is.read((char*)&v[0], nSize * sizeof(T));
512 // Limit size per read so bogus size value won't cause out of memory
514 unsigned int nSize = ReadCompactSize(is);
518 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
520 is.read((char*)&v[i], blk * sizeof(T));
525 template<typename Stream, typename T, typename A>
526 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
528 //unsigned int nSize = ReadCompactSize(is);
530 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
531 // Unserialize(is, (*vi), nType, nVersion);
534 unsigned int nSize = ReadCompactSize(is);
536 unsigned int nMid = 0;
539 nMid += 5000000 / sizeof(T);
543 for (; i < nMid; i++)
544 Unserialize(is, v[i], nType, nVersion);
548 template<typename Stream, typename T, typename A>
549 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
551 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
557 // others derived from vector
559 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
561 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
564 template<typename Stream>
565 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
567 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
570 template<typename Stream>
571 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
573 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
581 template<typename K, typename T>
582 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
584 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
587 template<typename Stream, typename K, typename T>
588 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
590 Serialize(os, item.first, nType, nVersion);
591 Serialize(os, item.second, nType, nVersion);
594 template<typename Stream, typename K, typename T>
595 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
597 Unserialize(is, item.first, nType, nVersion);
598 Unserialize(is, item.second, nType, nVersion);
606 template<typename T0, typename T1, typename T2>
607 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
609 unsigned int nSize = 0;
610 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
611 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
612 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
616 template<typename Stream, typename T0, typename T1, typename T2>
617 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
619 Serialize(os, boost::get<0>(item), nType, nVersion);
620 Serialize(os, boost::get<1>(item), nType, nVersion);
621 Serialize(os, boost::get<2>(item), nType, nVersion);
624 template<typename Stream, typename T0, typename T1, typename T2>
625 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
627 Unserialize(is, boost::get<0>(item), nType, nVersion);
628 Unserialize(is, boost::get<1>(item), nType, nVersion);
629 Unserialize(is, boost::get<2>(item), nType, nVersion);
637 template<typename T0, typename T1, typename T2, typename T3>
638 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
640 unsigned int nSize = 0;
641 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
642 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
643 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
644 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
648 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
649 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
651 Serialize(os, boost::get<0>(item), nType, nVersion);
652 Serialize(os, boost::get<1>(item), nType, nVersion);
653 Serialize(os, boost::get<2>(item), nType, nVersion);
654 Serialize(os, boost::get<3>(item), nType, nVersion);
657 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
658 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
660 Unserialize(is, boost::get<0>(item), nType, nVersion);
661 Unserialize(is, boost::get<1>(item), nType, nVersion);
662 Unserialize(is, boost::get<2>(item), nType, nVersion);
663 Unserialize(is, boost::get<3>(item), nType, nVersion);
671 template<typename K, typename T, typename Pred, typename A>
672 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
674 unsigned int nSize = GetSizeOfCompactSize(m.size());
675 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
676 nSize += GetSerializeSize((*mi), nType, nVersion);
680 template<typename Stream, typename K, typename T, typename Pred, typename A>
681 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
683 WriteCompactSize(os, m.size());
684 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
685 Serialize(os, (*mi), nType, nVersion);
688 template<typename Stream, typename K, typename T, typename Pred, typename A>
689 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
692 unsigned int nSize = ReadCompactSize(is);
693 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
694 for (unsigned int i = 0; i < nSize; i++)
696 std::pair<K, T> item;
697 Unserialize(is, item, nType, nVersion);
698 mi = m.insert(mi, item);
707 template<typename K, typename Pred, typename A>
708 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
710 unsigned int nSize = GetSizeOfCompactSize(m.size());
711 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
712 nSize += GetSerializeSize((*it), nType, nVersion);
716 template<typename Stream, typename K, typename Pred, typename A>
717 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
719 WriteCompactSize(os, m.size());
720 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
721 Serialize(os, (*it), nType, nVersion);
724 template<typename Stream, typename K, typename Pred, typename A>
725 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
728 unsigned int nSize = ReadCompactSize(is);
729 typename std::set<K, Pred, A>::iterator it = m.begin();
730 for (unsigned int i = 0; i < nSize; i++)
733 Unserialize(is, key, nType, nVersion);
734 it = m.insert(it, key);
741 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
743 class CSerActionGetSerializeSize { };
744 class CSerActionSerialize { };
745 class CSerActionUnserialize { };
747 template<typename Stream, typename T>
748 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
750 return ::GetSerializeSize(obj, nType, nVersion);
753 template<typename Stream, typename T>
754 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
756 ::Serialize(s, obj, nType, nVersion);
760 template<typename Stream, typename T>
761 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
763 ::Unserialize(s, obj, nType, nVersion);
767 struct ser_streamplaceholder
782 // Allocator that locks its contents from being paged
783 // out of memory and clears its contents before deletion.
786 struct secure_allocator : public std::allocator<T>
788 // MSVC8 default copy constructor is broken
789 typedef std::allocator<T> base;
790 typedef typename base::size_type size_type;
791 typedef typename base::difference_type difference_type;
792 typedef typename base::pointer pointer;
793 typedef typename base::const_pointer const_pointer;
794 typedef typename base::reference reference;
795 typedef typename base::const_reference const_reference;
796 typedef typename base::value_type value_type;
797 secure_allocator() throw() {}
798 secure_allocator(const secure_allocator& a) throw() : base(a) {}
799 template <typename U>
800 secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
801 ~secure_allocator() throw() {}
802 template<typename _Other> struct rebind
803 { typedef secure_allocator<_Other> other; };
805 T* allocate(std::size_t n, const void *hint = 0)
808 p = std::allocator<T>::allocate(n, hint);
810 mlock(p, sizeof(T) * n);
814 void deallocate(T* p, std::size_t n)
818 memset(p, 0, sizeof(T) * n);
819 munlock(p, sizeof(T) * n);
821 std::allocator<T>::deallocate(p, n);
828 // Double ended buffer combining vector and stream-like interfaces.
829 // >> and << read and write unformatted data using the above serialization templates.
830 // Fills with data in linear time; some stringstream implementations take N^2 time.
835 typedef std::vector<char, secure_allocator<char> > vector_type;
837 unsigned int nReadPos;
844 typedef vector_type::allocator_type allocator_type;
845 typedef vector_type::size_type size_type;
846 typedef vector_type::difference_type difference_type;
847 typedef vector_type::reference reference;
848 typedef vector_type::const_reference const_reference;
849 typedef vector_type::value_type value_type;
850 typedef vector_type::iterator iterator;
851 typedef vector_type::const_iterator const_iterator;
852 typedef vector_type::reverse_iterator reverse_iterator;
854 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
856 Init(nTypeIn, nVersionIn);
859 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
861 Init(nTypeIn, nVersionIn);
864 #if !defined(_MSC_VER) || _MSC_VER >= 1300
865 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
867 Init(nTypeIn, nVersionIn);
871 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
873 Init(nTypeIn, nVersionIn);
876 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
878 Init(nTypeIn, nVersionIn);
881 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
883 Init(nTypeIn, nVersionIn);
886 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
890 nVersion = nVersionIn;
892 exceptmask = std::ios::badbit | std::ios::failbit;
895 CDataStream& operator+=(const CDataStream& b)
897 vch.insert(vch.end(), b.begin(), b.end());
901 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
908 std::string str() const
910 return (std::string(begin(), end()));
917 const_iterator begin() const { return vch.begin() + nReadPos; }
918 iterator begin() { return vch.begin() + nReadPos; }
919 const_iterator end() const { return vch.end(); }
920 iterator end() { return vch.end(); }
921 size_type size() const { return vch.size() - nReadPos; }
922 bool empty() const { return vch.size() == nReadPos; }
923 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
924 void reserve(size_type n) { vch.reserve(n + nReadPos); }
925 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
926 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
927 void clear() { vch.clear(); nReadPos = 0; }
928 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
929 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
931 void insert(iterator it, const_iterator first, const_iterator last)
933 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
935 // special case for inserting at the front when there's room
936 nReadPos -= (last - first);
937 memcpy(&vch[nReadPos], &first[0], last - first);
940 vch.insert(it, first, last);
943 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
945 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
947 // special case for inserting at the front when there's room
948 nReadPos -= (last - first);
949 memcpy(&vch[nReadPos], &first[0], last - first);
952 vch.insert(it, first, last);
955 #if !defined(_MSC_VER) || _MSC_VER >= 1300
956 void insert(iterator it, const char* first, const char* last)
958 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
960 // special case for inserting at the front when there's room
961 nReadPos -= (last - first);
962 memcpy(&vch[nReadPos], &first[0], last - first);
965 vch.insert(it, first, last);
969 iterator erase(iterator it)
971 if (it == vch.begin() + nReadPos)
973 // special case for erasing from the front
974 if (++nReadPos >= vch.size())
976 // whenever we reach the end, we take the opportunity to clear the buffer
978 return vch.erase(vch.begin(), vch.end());
980 return vch.begin() + nReadPos;
983 return vch.erase(it);
986 iterator erase(iterator first, iterator last)
988 if (first == vch.begin() + nReadPos)
990 // special case for erasing from the front
991 if (last == vch.end())
994 return vch.erase(vch.begin(), vch.end());
998 nReadPos = (last - vch.begin());
1003 return vch.erase(first, last);
1006 inline void Compact()
1008 vch.erase(vch.begin(), vch.begin() + nReadPos);
1012 bool Rewind(size_type n)
1014 // Rewind by n characters if the buffer hasn't been compacted yet
1025 void setstate(short bits, const char* psz)
1028 if (state & exceptmask)
1029 throw std::ios_base::failure(psz);
1032 bool eof() const { return size() == 0; }
1033 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1034 bool good() const { return !eof() && (state == 0); }
1035 void clear(short n) { state = n; } // name conflict with vector clear()
1036 short exceptions() { return exceptmask; }
1037 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1038 CDataStream* rdbuf() { return this; }
1039 int in_avail() { return size(); }
1041 void SetType(int n) { nType = n; }
1042 int GetType() { return nType; }
1043 void SetVersion(int n) { nVersion = n; }
1044 int GetVersion() { return nVersion; }
1045 void ReadVersion() { *this >> nVersion; }
1046 void WriteVersion() { *this << nVersion; }
1048 CDataStream& read(char* pch, int nSize)
1050 // Read from the beginning of the buffer
1052 unsigned int nReadPosNext = nReadPos + nSize;
1053 if (nReadPosNext >= vch.size())
1055 if (nReadPosNext > vch.size())
1057 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1058 memset(pch, 0, nSize);
1059 nSize = vch.size() - nReadPos;
1061 memcpy(pch, &vch[nReadPos], nSize);
1066 memcpy(pch, &vch[nReadPos], nSize);
1067 nReadPos = nReadPosNext;
1071 CDataStream& ignore(int nSize)
1073 // Ignore from the beginning of the buffer
1075 unsigned int nReadPosNext = nReadPos + nSize;
1076 if (nReadPosNext >= vch.size())
1078 if (nReadPosNext > vch.size())
1080 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1081 nSize = vch.size() - nReadPos;
1087 nReadPos = nReadPosNext;
1091 CDataStream& write(const char* pch, int nSize)
1093 // Write to the end of the buffer
1095 vch.insert(vch.end(), pch, pch + nSize);
1099 template<typename Stream>
1100 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const
1102 // Special case: stream << stream concatenates like stream += stream
1104 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1107 template<typename T>
1108 unsigned int GetSerializeSize(const T& obj)
1110 // Tells the size of the object if serialized to this stream
1111 return ::GetSerializeSize(obj, nType, nVersion);
1114 template<typename T>
1115 CDataStream& operator<<(const T& obj)
1117 // Serialize to this stream
1118 ::Serialize(*this, obj, nType, nVersion);
1122 template<typename T>
1123 CDataStream& operator>>(T& obj)
1125 // Unserialize from this stream
1126 ::Unserialize(*this, obj, nType, nVersion);
1131 #ifdef TESTCDATASTREAM
1138 // n=16000 0 seconds
1139 // n=32000 0 seconds
1140 // n=64000 1 seconds
1141 // n=128000 1 seconds
1142 // n=256000 2 seconds
1143 // n=512000 4 seconds
1144 // n=1024000 8 seconds
1145 // n=2048000 16 seconds
1146 // n=4096000 32 seconds
1150 // n=4000 13 seconds
1151 // n=8000 87 seconds
1152 // n=16000 400 seconds
1153 // n=32000 1660 seconds
1154 // n=64000 6749 seconds
1155 // n=128000 27241 seconds
1156 // n=256000 109804 seconds
1158 int main(int argc, char *argv[])
1160 vector<unsigned char> vch(0xcc, 250);
1161 printf("CDataStream:\n");
1162 for (int n = 1000; n <= 4500000; n *= 2)
1165 time_t nStart = time(NULL);
1166 for (int i = 0; i < n; i++)
1167 ss.write((char*)&vch[0], vch.size());
1168 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1170 printf("stringstream:\n");
1171 for (int n = 1000; n <= 4500000; n *= 2)
1174 time_t nStart = time(NULL);
1175 for (int i = 0; i < n; i++)
1176 ss.write((char*)&vch[0], vch.size());
1177 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1192 // Automatic closing wrapper for FILE*
1193 // - Will automatically close the file when it goes out of scope if not null.
1194 // - If you're returning the file pointer, return file.release().
1195 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1207 typedef FILE element_type;
1209 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)
1213 nVersion = nVersionIn;
1215 exceptmask = std::ios::badbit | std::ios::failbit;
1225 if (file != NULL && file != stdin && file != stdout && file != stderr)
1230 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1231 operator FILE*() { return file; }
1232 FILE* operator->() { return file; }
1233 FILE& operator*() { return *file; }
1234 FILE** operator&() { return &file; }
1235 FILE* operator=(FILE* pnew) { return file = pnew; }
1236 bool operator!() { return (file == NULL); }
1242 void setstate(short bits, const char* psz)
1245 if (state & exceptmask)
1246 throw std::ios_base::failure(psz);
1249 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1250 bool good() const { return state == 0; }
1251 void clear(short n = 0) { state = n; }
1252 short exceptions() { return exceptmask; }
1253 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1255 void SetType(int n) { nType = n; }
1256 int GetType() { return nType; }
1257 void SetVersion(int n) { nVersion = n; }
1258 int GetVersion() { return nVersion; }
1259 void ReadVersion() { *this >> nVersion; }
1260 void WriteVersion() { *this << nVersion; }
1262 CAutoFile& read(char* pch, int nSize)
1265 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1266 if (fread(pch, 1, nSize, file) != nSize)
1267 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1271 CAutoFile& write(const char* pch, int nSize)
1274 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1275 if (fwrite(pch, 1, nSize, file) != nSize)
1276 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1280 template<typename T>
1281 unsigned int GetSerializeSize(const T& obj)
1283 // Tells the size of the object if serialized to this stream
1284 return ::GetSerializeSize(obj, nType, nVersion);
1287 template<typename T>
1288 CAutoFile& operator<<(const T& obj)
1290 // Serialize to this stream
1292 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1293 ::Serialize(*this, obj, nType, nVersion);
1297 template<typename T>
1298 CAutoFile& operator>>(T& obj)
1300 // Unserialize from this stream
1302 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1303 ::Unserialize(*this, obj, nType, nVersion);