1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2011 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_SERIALIZE_H
6 #define BITCOIN_SERIALIZE_H
17 #include <boost/type_traits/is_fundamental.hpp>
18 #include <boost/tuple/tuple.hpp>
19 #include <boost/tuple/tuple_comparison.hpp>
20 #include <boost/tuple/tuple_io.hpp>
22 typedef long long int64;
23 typedef unsigned long long uint64;
27 // This is used to attempt to keep keying material out of swap
28 // Note that VirtualLock does not provide this as a guarantee on Windows,
29 // but, in practice, memory that has been VirtualLock'd almost never gets written to
30 // the pagefile except in rare circumstances where memory is extremely low.
32 #define mlock(p, n) VirtualLock((p), (n));
33 #define munlock(p, n) VirtualUnlock((p), (n));
37 /* This comes from limits.h if it's not defined there set a sane default */
40 #define PAGESIZE sysconf(_SC_PAGESIZE)
43 mlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
44 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
45 #define munlock(a,b) \
46 munlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
47 (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
53 static const unsigned int MAX_SIZE = 0x02000000;
55 static const int PROTOCOL_VERSION = 60000;
57 // Used to bypass the rule against non-const reference to temporary
58 // where it makes sense with wrappers such as CFlatData or CTxDB
60 inline T& REF(const T& val)
62 return const_cast<T&>(val);
65 /////////////////////////////////////////////////////////////////
67 // Templates for serializing to anything that looks like a stream,
68 // i.e. anything that supports .read(char*, int) and .write(char*, int)
74 SER_NETWORK = (1 << 0),
76 SER_GETHASH = (1 << 2),
79 SER_SKIPSIG = (1 << 16),
80 SER_BLOCKHEADERONLY = (1 << 17),
83 #define IMPLEMENT_SERIALIZE(statements) \
84 unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const \
86 CSerActionGetSerializeSize ser_action; \
87 const bool fGetSize = true; \
88 const bool fWrite = false; \
89 const bool fRead = false; \
90 unsigned int nSerSize = 0; \
91 ser_streamplaceholder s; \
93 s.nVersion = nVersion; \
97 template<typename Stream> \
98 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const \
100 CSerActionSerialize ser_action; \
101 const bool fGetSize = false; \
102 const bool fWrite = true; \
103 const bool fRead = false; \
104 unsigned int nSerSize = 0; \
107 template<typename Stream> \
108 void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) \
110 CSerActionUnserialize ser_action; \
111 const bool fGetSize = false; \
112 const bool fWrite = false; \
113 const bool fRead = true; \
114 unsigned int nSerSize = 0; \
118 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
128 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
129 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
131 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
132 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
133 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
134 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
135 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
136 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
137 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
138 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
139 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
140 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
141 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
142 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
143 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
145 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
146 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
147 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
148 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
149 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
150 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
151 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
152 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
153 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
154 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
155 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
156 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
157 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
159 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
160 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
161 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
162 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
163 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
164 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
165 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
166 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
167 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
168 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
169 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
170 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
171 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
173 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
174 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
175 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
184 // size < 253 -- 1 byte
185 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
186 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
187 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
189 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
191 if (nSize < 253) return sizeof(unsigned char);
192 else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
193 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
194 else return sizeof(unsigned char) + sizeof(uint64);
197 template<typename Stream>
198 void WriteCompactSize(Stream& os, uint64 nSize)
202 unsigned char chSize = nSize;
203 WRITEDATA(os, chSize);
205 else if (nSize <= std::numeric_limits<unsigned short>::max())
207 unsigned char chSize = 253;
208 unsigned short xSize = nSize;
209 WRITEDATA(os, chSize);
210 WRITEDATA(os, xSize);
212 else if (nSize <= std::numeric_limits<unsigned int>::max())
214 unsigned char chSize = 254;
215 unsigned int xSize = nSize;
216 WRITEDATA(os, chSize);
217 WRITEDATA(os, xSize);
221 unsigned char chSize = 255;
222 uint64 xSize = nSize;
223 WRITEDATA(os, chSize);
224 WRITEDATA(os, xSize);
229 template<typename Stream>
230 uint64 ReadCompactSize(Stream& is)
232 unsigned char chSize;
233 READDATA(is, chSize);
239 else if (chSize == 253)
241 unsigned short xSize;
245 else if (chSize == 254)
257 if (nSizeRet > (uint64)MAX_SIZE)
258 throw std::ios_base::failure("ReadCompactSize() : size too large");
265 // Wrapper for serializing arrays and POD
266 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
268 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
275 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
276 char* begin() { return pbegin; }
277 const char* begin() const { return pbegin; }
278 char* end() { return pend; }
279 const char* end() const { return pend; }
281 unsigned int GetSerializeSize(int, int=0) const
283 return pend - pbegin;
286 template<typename Stream>
287 void Serialize(Stream& s, int, int=0) const
289 s.write(pbegin, pend - pbegin);
292 template<typename Stream>
293 void Unserialize(Stream& s, int, int=0)
295 s.read(pbegin, pend - pbegin);
302 // string stored as a fixed length field
304 template<std::size_t LEN>
305 class CFixedFieldString
308 const std::string* pcstr;
311 explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
312 explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
314 unsigned int GetSerializeSize(int, int=0) const
319 template<typename Stream>
320 void Serialize(Stream& s, int, int=0) const
323 strncpy(pszBuf, pcstr->c_str(), LEN);
324 s.write(pszBuf, LEN);
327 template<typename Stream>
328 void Unserialize(Stream& s, int, int=0)
331 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
344 // Forward declarations
348 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
349 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
350 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
353 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
354 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
355 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
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::true_type&);
357 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&);
358 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
359 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&);
360 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&);
361 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
363 // others derived from vector
364 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
365 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
366 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
369 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
370 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
371 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
374 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
375 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);
376 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);
379 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);
380 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);
381 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);
384 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);
385 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);
386 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);
389 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
390 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);
391 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);
398 // If none of the specialized versions above matched, default to calling member function.
399 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
400 // The compiler will only cast int to long if none of the other templates matched.
401 // Thanks to Boost serialization for this idea.
404 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=PROTOCOL_VERSION)
406 return a.GetSerializeSize((int)nType, nVersion);
409 template<typename Stream, typename T>
410 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=PROTOCOL_VERSION)
412 a.Serialize(os, (int)nType, nVersion);
415 template<typename Stream, typename T>
416 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=PROTOCOL_VERSION)
418 a.Unserialize(is, (int)nType, nVersion);
429 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
431 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
434 template<typename Stream, typename C>
435 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
437 WriteCompactSize(os, str.size());
439 os.write((char*)&str[0], str.size() * sizeof(str[0]));
442 template<typename Stream, typename C>
443 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
445 unsigned int nSize = ReadCompactSize(is);
448 is.read((char*)&str[0], nSize * sizeof(str[0]));
456 template<typename T, typename A>
457 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
459 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
462 template<typename T, typename A>
463 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
465 unsigned int nSize = GetSizeOfCompactSize(v.size());
466 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
467 nSize += GetSerializeSize((*vi), nType, nVersion);
471 template<typename T, typename A>
472 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
474 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
478 template<typename Stream, typename T, typename A>
479 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
481 WriteCompactSize(os, v.size());
483 os.write((char*)&v[0], v.size() * sizeof(T));
486 template<typename Stream, typename T, typename A>
487 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
489 WriteCompactSize(os, v.size());
490 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
491 ::Serialize(os, (*vi), nType, nVersion);
494 template<typename Stream, typename T, typename A>
495 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
497 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
501 template<typename Stream, typename T, typename A>
502 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
504 //unsigned int nSize = ReadCompactSize(is);
506 //is.read((char*)&v[0], nSize * sizeof(T));
508 // Limit size per read so bogus size value won't cause out of memory
510 unsigned int nSize = ReadCompactSize(is);
514 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
516 is.read((char*)&v[i], blk * sizeof(T));
521 template<typename Stream, typename T, typename A>
522 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
524 //unsigned int nSize = ReadCompactSize(is);
526 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
527 // Unserialize(is, (*vi), nType, nVersion);
530 unsigned int nSize = ReadCompactSize(is);
532 unsigned int nMid = 0;
535 nMid += 5000000 / sizeof(T);
539 for (; i < nMid; i++)
540 Unserialize(is, v[i], nType, nVersion);
544 template<typename Stream, typename T, typename A>
545 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
547 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
553 // others derived from vector
555 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
557 return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
560 template<typename Stream>
561 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
563 Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
566 template<typename Stream>
567 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
569 Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
577 template<typename K, typename T>
578 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
580 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
583 template<typename Stream, typename K, typename T>
584 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
586 Serialize(os, item.first, nType, nVersion);
587 Serialize(os, item.second, nType, nVersion);
590 template<typename Stream, typename K, typename T>
591 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
593 Unserialize(is, item.first, nType, nVersion);
594 Unserialize(is, item.second, nType, nVersion);
602 template<typename T0, typename T1, typename T2>
603 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
605 unsigned int nSize = 0;
606 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
607 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
608 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
612 template<typename Stream, typename T0, typename T1, typename T2>
613 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
615 Serialize(os, boost::get<0>(item), nType, nVersion);
616 Serialize(os, boost::get<1>(item), nType, nVersion);
617 Serialize(os, boost::get<2>(item), nType, nVersion);
620 template<typename Stream, typename T0, typename T1, typename T2>
621 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
623 Unserialize(is, boost::get<0>(item), nType, nVersion);
624 Unserialize(is, boost::get<1>(item), nType, nVersion);
625 Unserialize(is, boost::get<2>(item), nType, nVersion);
633 template<typename T0, typename T1, typename T2, typename T3>
634 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
636 unsigned int nSize = 0;
637 nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
638 nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
639 nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
640 nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
644 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
645 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
647 Serialize(os, boost::get<0>(item), nType, nVersion);
648 Serialize(os, boost::get<1>(item), nType, nVersion);
649 Serialize(os, boost::get<2>(item), nType, nVersion);
650 Serialize(os, boost::get<3>(item), nType, nVersion);
653 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
654 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
656 Unserialize(is, boost::get<0>(item), nType, nVersion);
657 Unserialize(is, boost::get<1>(item), nType, nVersion);
658 Unserialize(is, boost::get<2>(item), nType, nVersion);
659 Unserialize(is, boost::get<3>(item), nType, nVersion);
667 template<typename K, typename T, typename Pred, typename A>
668 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
670 unsigned int nSize = GetSizeOfCompactSize(m.size());
671 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
672 nSize += GetSerializeSize((*mi), nType, nVersion);
676 template<typename Stream, typename K, typename T, typename Pred, typename A>
677 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
679 WriteCompactSize(os, m.size());
680 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
681 Serialize(os, (*mi), nType, nVersion);
684 template<typename Stream, typename K, typename T, typename Pred, typename A>
685 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
688 unsigned int nSize = ReadCompactSize(is);
689 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
690 for (unsigned int i = 0; i < nSize; i++)
692 std::pair<K, T> item;
693 Unserialize(is, item, nType, nVersion);
694 mi = m.insert(mi, item);
703 template<typename K, typename Pred, typename A>
704 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
706 unsigned int nSize = GetSizeOfCompactSize(m.size());
707 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
708 nSize += GetSerializeSize((*it), nType, nVersion);
712 template<typename Stream, typename K, typename Pred, typename A>
713 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
715 WriteCompactSize(os, m.size());
716 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
717 Serialize(os, (*it), nType, nVersion);
720 template<typename Stream, typename K, typename Pred, typename A>
721 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
724 unsigned int nSize = ReadCompactSize(is);
725 typename std::set<K, Pred, A>::iterator it = m.begin();
726 for (unsigned int i = 0; i < nSize; i++)
729 Unserialize(is, key, nType, nVersion);
730 it = m.insert(it, key);
737 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
739 class CSerActionGetSerializeSize { };
740 class CSerActionSerialize { };
741 class CSerActionUnserialize { };
743 template<typename Stream, typename T>
744 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
746 return ::GetSerializeSize(obj, nType, nVersion);
749 template<typename Stream, typename T>
750 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
752 ::Serialize(s, obj, nType, nVersion);
756 template<typename Stream, typename T>
757 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
759 ::Unserialize(s, obj, nType, nVersion);
763 struct ser_streamplaceholder
778 // Allocator that locks its contents from being paged
779 // out of memory and clears its contents before deletion.
782 struct secure_allocator : public std::allocator<T>
784 // MSVC8 default copy constructor is broken
785 typedef std::allocator<T> base;
786 typedef typename base::size_type size_type;
787 typedef typename base::difference_type difference_type;
788 typedef typename base::pointer pointer;
789 typedef typename base::const_pointer const_pointer;
790 typedef typename base::reference reference;
791 typedef typename base::const_reference const_reference;
792 typedef typename base::value_type value_type;
793 secure_allocator() throw() {}
794 secure_allocator(const secure_allocator& a) throw() : base(a) {}
795 template <typename U>
796 secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
797 ~secure_allocator() throw() {}
798 template<typename _Other> struct rebind
799 { typedef secure_allocator<_Other> other; };
801 T* allocate(std::size_t n, const void *hint = 0)
804 p = std::allocator<T>::allocate(n, hint);
806 mlock(p, sizeof(T) * n);
810 void deallocate(T* p, std::size_t n)
814 memset(p, 0, sizeof(T) * n);
815 munlock(p, sizeof(T) * n);
817 std::allocator<T>::deallocate(p, n);
823 // Allocator that clears its contents before deletion.
826 struct zero_after_free_allocator : public std::allocator<T>
828 // MSVC8 default copy constructor is broken
829 typedef std::allocator<T> base;
830 typedef typename base::size_type size_type;
831 typedef typename base::difference_type difference_type;
832 typedef typename base::pointer pointer;
833 typedef typename base::const_pointer const_pointer;
834 typedef typename base::reference reference;
835 typedef typename base::const_reference const_reference;
836 typedef typename base::value_type value_type;
837 zero_after_free_allocator() throw() {}
838 zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
839 template <typename U>
840 zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a) {}
841 ~zero_after_free_allocator() throw() {}
842 template<typename _Other> struct rebind
843 { typedef zero_after_free_allocator<_Other> other; };
845 void deallocate(T* p, std::size_t n)
848 memset(p, 0, sizeof(T) * n);
849 std::allocator<T>::deallocate(p, n);
856 // Double ended buffer combining vector and stream-like interfaces.
857 // >> and << read and write unformatted data using the above serialization templates.
858 // Fills with data in linear time; some stringstream implementations take N^2 time.
863 typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
865 unsigned int nReadPos;
872 typedef vector_type::allocator_type allocator_type;
873 typedef vector_type::size_type size_type;
874 typedef vector_type::difference_type difference_type;
875 typedef vector_type::reference reference;
876 typedef vector_type::const_reference const_reference;
877 typedef vector_type::value_type value_type;
878 typedef vector_type::iterator iterator;
879 typedef vector_type::const_iterator const_iterator;
880 typedef vector_type::reverse_iterator reverse_iterator;
882 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
884 Init(nTypeIn, nVersionIn);
887 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
889 Init(nTypeIn, nVersionIn);
892 #if !defined(_MSC_VER) || _MSC_VER >= 1300
893 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
895 Init(nTypeIn, nVersionIn);
899 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
901 Init(nTypeIn, nVersionIn);
904 CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
906 Init(nTypeIn, nVersionIn);
909 CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
911 Init(nTypeIn, nVersionIn);
914 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
918 nVersion = nVersionIn;
920 exceptmask = std::ios::badbit | std::ios::failbit;
923 CDataStream& operator+=(const CDataStream& b)
925 vch.insert(vch.end(), b.begin(), b.end());
929 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
936 std::string str() const
938 return (std::string(begin(), end()));
945 const_iterator begin() const { return vch.begin() + nReadPos; }
946 iterator begin() { return vch.begin() + nReadPos; }
947 const_iterator end() const { return vch.end(); }
948 iterator end() { return vch.end(); }
949 size_type size() const { return vch.size() - nReadPos; }
950 bool empty() const { return vch.size() == nReadPos; }
951 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
952 void reserve(size_type n) { vch.reserve(n + nReadPos); }
953 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
954 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
955 void clear() { vch.clear(); nReadPos = 0; }
956 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
957 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
959 void insert(iterator it, const_iterator first, const_iterator last)
961 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
963 // special case for inserting at the front when there's room
964 nReadPos -= (last - first);
965 memcpy(&vch[nReadPos], &first[0], last - first);
968 vch.insert(it, first, last);
971 void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
973 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
975 // special case for inserting at the front when there's room
976 nReadPos -= (last - first);
977 memcpy(&vch[nReadPos], &first[0], last - first);
980 vch.insert(it, first, last);
983 #if !defined(_MSC_VER) || _MSC_VER >= 1300
984 void insert(iterator it, const char* first, const char* last)
986 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
988 // special case for inserting at the front when there's room
989 nReadPos -= (last - first);
990 memcpy(&vch[nReadPos], &first[0], last - first);
993 vch.insert(it, first, last);
997 iterator erase(iterator it)
999 if (it == vch.begin() + nReadPos)
1001 // special case for erasing from the front
1002 if (++nReadPos >= vch.size())
1004 // whenever we reach the end, we take the opportunity to clear the buffer
1006 return vch.erase(vch.begin(), vch.end());
1008 return vch.begin() + nReadPos;
1011 return vch.erase(it);
1014 iterator erase(iterator first, iterator last)
1016 if (first == vch.begin() + nReadPos)
1018 // special case for erasing from the front
1019 if (last == vch.end())
1022 return vch.erase(vch.begin(), vch.end());
1026 nReadPos = (last - vch.begin());
1031 return vch.erase(first, last);
1034 inline void Compact()
1036 vch.erase(vch.begin(), vch.begin() + nReadPos);
1040 bool Rewind(size_type n)
1042 // Rewind by n characters if the buffer hasn't been compacted yet
1053 void setstate(short bits, const char* psz)
1056 if (state & exceptmask)
1057 throw std::ios_base::failure(psz);
1060 bool eof() const { return size() == 0; }
1061 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1062 bool good() const { return !eof() && (state == 0); }
1063 void clear(short n) { state = n; } // name conflict with vector clear()
1064 short exceptions() { return exceptmask; }
1065 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1066 CDataStream* rdbuf() { return this; }
1067 int in_avail() { return size(); }
1069 void SetType(int n) { nType = n; }
1070 int GetType() { return nType; }
1071 void SetVersion(int n) { nVersion = n; }
1072 int GetVersion() { return nVersion; }
1073 void ReadVersion() { *this >> nVersion; }
1074 void WriteVersion() { *this << nVersion; }
1076 CDataStream& read(char* pch, int nSize)
1078 // Read from the beginning of the buffer
1080 unsigned int nReadPosNext = nReadPos + nSize;
1081 if (nReadPosNext >= vch.size())
1083 if (nReadPosNext > vch.size())
1085 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1086 memset(pch, 0, nSize);
1087 nSize = vch.size() - nReadPos;
1089 memcpy(pch, &vch[nReadPos], nSize);
1094 memcpy(pch, &vch[nReadPos], nSize);
1095 nReadPos = nReadPosNext;
1099 CDataStream& ignore(int nSize)
1101 // Ignore from the beginning of the buffer
1103 unsigned int nReadPosNext = nReadPos + nSize;
1104 if (nReadPosNext >= vch.size())
1106 if (nReadPosNext > vch.size())
1108 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1109 nSize = vch.size() - nReadPos;
1115 nReadPos = nReadPosNext;
1119 CDataStream& write(const char* pch, int nSize)
1121 // Write to the end of the buffer
1123 vch.insert(vch.end(), pch, pch + nSize);
1127 template<typename Stream>
1128 void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
1130 // Special case: stream << stream concatenates like stream += stream
1132 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1135 template<typename T>
1136 unsigned int GetSerializeSize(const T& obj)
1138 // Tells the size of the object if serialized to this stream
1139 return ::GetSerializeSize(obj, nType, nVersion);
1142 template<typename T>
1143 CDataStream& operator<<(const T& obj)
1145 // Serialize to this stream
1146 ::Serialize(*this, obj, nType, nVersion);
1150 template<typename T>
1151 CDataStream& operator>>(T& obj)
1153 // Unserialize from this stream
1154 ::Unserialize(*this, obj, nType, nVersion);
1159 #ifdef TESTCDATASTREAM
1166 // n=16000 0 seconds
1167 // n=32000 0 seconds
1168 // n=64000 1 seconds
1169 // n=128000 1 seconds
1170 // n=256000 2 seconds
1171 // n=512000 4 seconds
1172 // n=1024000 8 seconds
1173 // n=2048000 16 seconds
1174 // n=4096000 32 seconds
1178 // n=4000 13 seconds
1179 // n=8000 87 seconds
1180 // n=16000 400 seconds
1181 // n=32000 1660 seconds
1182 // n=64000 6749 seconds
1183 // n=128000 27241 seconds
1184 // n=256000 109804 seconds
1186 int main(int argc, char *argv[])
1188 vector<unsigned char> vch(0xcc, 250);
1189 printf("CDataStream:\n");
1190 for (int n = 1000; n <= 4500000; n *= 2)
1193 time_t nStart = time(NULL);
1194 for (int i = 0; i < n; i++)
1195 ss.write((char*)&vch[0], vch.size());
1196 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1198 printf("stringstream:\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);
1220 // Automatic closing wrapper for FILE*
1221 // - Will automatically close the file when it goes out of scope if not null.
1222 // - If you're returning the file pointer, return file.release().
1223 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1235 typedef FILE element_type;
1237 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=PROTOCOL_VERSION)
1241 nVersion = nVersionIn;
1243 exceptmask = std::ios::badbit | std::ios::failbit;
1253 if (file != NULL && file != stdin && file != stdout && file != stderr)
1258 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1259 operator FILE*() { return file; }
1260 FILE* operator->() { return file; }
1261 FILE& operator*() { return *file; }
1262 FILE** operator&() { return &file; }
1263 FILE* operator=(FILE* pnew) { return file = pnew; }
1264 bool operator!() { return (file == NULL); }
1270 void setstate(short bits, const char* psz)
1273 if (state & exceptmask)
1274 throw std::ios_base::failure(psz);
1277 bool fail() const { return state & (std::ios::badbit | std::ios::failbit); }
1278 bool good() const { return state == 0; }
1279 void clear(short n = 0) { state = n; }
1280 short exceptions() { return exceptmask; }
1281 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1283 void SetType(int n) { nType = n; }
1284 int GetType() { return nType; }
1285 void SetVersion(int n) { nVersion = n; }
1286 int GetVersion() { return nVersion; }
1287 void ReadVersion() { *this >> nVersion; }
1288 void WriteVersion() { *this << nVersion; }
1290 CAutoFile& read(char* pch, int nSize)
1293 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1294 if (fread(pch, 1, nSize, file) != nSize)
1295 setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1299 CAutoFile& write(const char* pch, int nSize)
1302 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1303 if (fwrite(pch, 1, nSize, file) != nSize)
1304 setstate(std::ios::failbit, "CAutoFile::write : write failed");
1308 template<typename T>
1309 unsigned int GetSerializeSize(const T& obj)
1311 // Tells the size of the object if serialized to this stream
1312 return ::GetSerializeSize(obj, nType, nVersion);
1315 template<typename T>
1316 CAutoFile& operator<<(const T& obj)
1318 // Serialize to this stream
1320 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1321 ::Serialize(*this, obj, nType, nVersion);
1325 template<typename T>
1326 CAutoFile& operator>>(T& obj)
1328 // Unserialize from this stream
1330 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1331 ::Unserialize(*this, obj, nType, nVersion);