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.
7 #include <boost/type_traits/is_fundamental.hpp>
8 #if defined(_MSC_VER) || defined(__BORLANDC__)
10 typedef unsigned __int64 uint64;
12 typedef long long int64;
13 typedef unsigned long long uint64;
15 #if defined(_MSC_VER) && _MSC_VER < 1300
16 #define for if (false) ; else for
22 static const int VERSION = 310;
23 static const char* pszSubVer = ".4";
29 /////////////////////////////////////////////////////////////////
31 // Templates for serializing to anything that looks like a stream,
32 // i.e. anything that supports .read(char*, int) and .write(char*, int)
38 SER_NETWORK = (1 << 0),
40 SER_GETHASH = (1 << 2),
43 SER_SKIPSIG = (1 << 16),
44 SER_BLOCKHEADERONLY = (1 << 17),
47 #define IMPLEMENT_SERIALIZE(statements) \
48 unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const \
50 CSerActionGetSerializeSize ser_action; \
51 const bool fGetSize = true; \
52 const bool fWrite = false; \
53 const bool fRead = false; \
54 unsigned int nSerSize = 0; \
55 ser_streamplaceholder s; \
57 s.nVersion = nVersion; \
61 template<typename Stream> \
62 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const \
64 CSerActionSerialize ser_action; \
65 const bool fGetSize = false; \
66 const bool fWrite = true; \
67 const bool fRead = false; \
68 unsigned int nSerSize = 0; \
71 template<typename Stream> \
72 void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) \
74 CSerActionUnserialize ser_action; \
75 const bool fGetSize = false; \
76 const bool fWrite = false; \
77 const bool fRead = true; \
78 unsigned int nSerSize = 0; \
82 #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
84 #define READWRITEVER(obj) \
99 #define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))
100 #define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))
102 inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }
103 inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }
104 inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }
105 inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }
106 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
107 inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }
108 inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }
109 inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }
110 inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }
111 inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }
112 inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }
113 inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }
114 inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }
116 template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }
117 template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }
118 template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }
119 template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }
120 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
121 template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }
122 template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }
123 template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }
124 template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }
125 template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }
126 template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }
127 template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }
128 template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }
130 template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }
131 template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }
132 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }
133 template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }
134 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
135 template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }
136 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }
137 template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }
138 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }
139 template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }
140 template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }
141 template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }
142 template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }
144 inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }
145 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }
146 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
155 // size < 253 -- 1 byte
156 // size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)
157 // size <= UINT_MAX -- 5 bytes (254 + 4 bytes)
158 // size > UINT_MAX -- 9 bytes (255 + 8 bytes)
160 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
162 if (nSize < UCHAR_MAX-2) return sizeof(unsigned char);
163 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);
164 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);
165 else return sizeof(unsigned char) + sizeof(uint64);
168 template<typename Stream>
169 void WriteCompactSize(Stream& os, uint64 nSize)
171 if (nSize < UCHAR_MAX-2)
173 unsigned char chSize = nSize;
174 WRITEDATA(os, chSize);
176 else if (nSize <= USHRT_MAX)
178 unsigned char chSize = UCHAR_MAX-2;
179 unsigned short xSize = nSize;
180 WRITEDATA(os, chSize);
181 WRITEDATA(os, xSize);
183 else if (nSize <= UINT_MAX)
185 unsigned char chSize = UCHAR_MAX-1;
186 unsigned int xSize = nSize;
187 WRITEDATA(os, chSize);
188 WRITEDATA(os, xSize);
192 unsigned char chSize = UCHAR_MAX;
193 WRITEDATA(os, chSize);
194 WRITEDATA(os, nSize);
199 template<typename Stream>
200 uint64 ReadCompactSize(Stream& is)
202 unsigned char chSize;
203 READDATA(is, chSize);
205 if (chSize < UCHAR_MAX-2)
209 else if (chSize == UCHAR_MAX-2)
211 unsigned short nSize;
215 else if (chSize == UCHAR_MAX-1)
227 if (nSizeRet > (uint64)INT_MAX)
228 throw std::ios_base::failure("ReadCompactSize() : size too large");
235 // Wrapper for serializing arrays and POD
236 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
238 #define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
245 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
246 char* begin() { return pbegin; }
247 const char* begin() const { return pbegin; }
248 char* end() { return pend; }
249 const char* end() const { return pend; }
251 unsigned int GetSerializeSize(int, int=0) const
253 return pend - pbegin;
256 template<typename Stream>
257 void Serialize(Stream& s, int, int=0) const
259 s.write(pbegin, pend - pbegin);
262 template<typename Stream>
263 void Unserialize(Stream& s, int, int=0)
265 s.read(pbegin, pend - pbegin);
272 // string stored as a fixed length field
274 template<std::size_t LEN>
275 class CFixedFieldString
281 explicit CFixedFieldString(const string& str) : pcstr(&str), pstr(NULL) { }
282 explicit CFixedFieldString(string& str) : pcstr(&str), pstr(&str) { }
284 unsigned int GetSerializeSize(int, int=0) const
289 template<typename Stream>
290 void Serialize(Stream& s, int, int=0) const
293 strncpy(pszBuf, pcstr->c_str(), LEN);
294 s.write(pszBuf, LEN);
297 template<typename Stream>
298 void Unserialize(Stream& s, int, int=0)
301 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
314 // Forward declarations
318 template<typename C> unsigned int GetSerializeSize(const basic_string<C>& str, int, int=0);
319 template<typename Stream, typename C> void Serialize(Stream& os, const basic_string<C>& str, int, int=0);
320 template<typename Stream, typename C> void Unserialize(Stream& is, basic_string<C>& str, int, int=0);
323 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
324 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
325 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);
326 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&);
327 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&);
328 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);
329 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&);
330 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&);
331 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);
333 // others derived from vector
334 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);
335 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);
336 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);
339 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);
340 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);
341 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);
344 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);
345 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);
346 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);
349 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
350 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);
351 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
358 // If none of the specialized versions above matched, default to calling member function.
359 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
360 // The compiler will only cast int to long if none of the other templates matched.
361 // Thanks to Boost serialization for this idea.
364 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)
366 return a.GetSerializeSize((int)nType, nVersion);
369 template<typename Stream, typename T>
370 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)
372 a.Serialize(os, (int)nType, nVersion);
375 template<typename Stream, typename T>
376 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)
378 a.Unserialize(is, (int)nType, nVersion);
389 unsigned int GetSerializeSize(const basic_string<C>& str, int, int)
391 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
394 template<typename Stream, typename C>
395 void Serialize(Stream& os, const basic_string<C>& str, int, int)
397 WriteCompactSize(os, str.size());
399 os.write((char*)&str[0], str.size() * sizeof(str[0]));
402 template<typename Stream, typename C>
403 void Unserialize(Stream& is, basic_string<C>& str, int, int)
405 unsigned int nSize = ReadCompactSize(is);
408 is.read((char*)&str[0], nSize * sizeof(str[0]));
416 template<typename T, typename A>
417 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
419 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
422 template<typename T, typename A>
423 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
425 unsigned int nSize = GetSizeOfCompactSize(v.size());
426 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
427 nSize += GetSerializeSize((*vi), nType, nVersion);
431 template<typename T, typename A>
432 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
434 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
438 template<typename Stream, typename T, typename A>
439 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
441 WriteCompactSize(os, v.size());
443 os.write((char*)&v[0], v.size() * sizeof(T));
446 template<typename Stream, typename T, typename A>
447 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
449 WriteCompactSize(os, v.size());
450 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
451 ::Serialize(os, (*vi), nType, nVersion);
454 template<typename Stream, typename T, typename A>
455 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
457 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
461 template<typename Stream, typename T, typename A>
462 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
464 //unsigned int nSize = ReadCompactSize(is);
466 //is.read((char*)&v[0], nSize * sizeof(T));
468 // Limit size per read so bogus size value won't cause out of memory
470 unsigned int nSize = ReadCompactSize(is);
474 unsigned int blk = min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
476 is.read((char*)&v[i], blk * sizeof(T));
481 template<typename Stream, typename T, typename A>
482 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
484 //unsigned int nSize = ReadCompactSize(is);
486 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
487 // Unserialize(is, (*vi), nType, nVersion);
490 unsigned int nSize = ReadCompactSize(is);
492 unsigned int nMid = 0;
495 nMid += 5000000 / sizeof(T);
499 for (; i < nMid; i++)
500 Unserialize(is, v[i], nType, nVersion);
504 template<typename Stream, typename T, typename A>
505 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
507 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
513 // others derived from vector
515 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
517 return GetSerializeSize((const vector<unsigned char>&)v, nType, nVersion);
520 template<typename Stream>
521 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
523 Serialize(os, (const vector<unsigned char>&)v, nType, nVersion);
526 template<typename Stream>
527 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
529 Unserialize(is, (vector<unsigned char>&)v, nType, nVersion);
537 template<typename K, typename T>
538 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
540 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
543 template<typename Stream, typename K, typename T>
544 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
546 Serialize(os, item.first, nType, nVersion);
547 Serialize(os, item.second, nType, nVersion);
550 template<typename Stream, typename K, typename T>
551 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
553 Unserialize(is, item.first, nType, nVersion);
554 Unserialize(is, item.second, nType, nVersion);
562 template<typename K, typename T, typename Pred, typename A>
563 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
565 unsigned int nSize = GetSizeOfCompactSize(m.size());
566 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
567 nSize += GetSerializeSize((*mi), nType, nVersion);
571 template<typename Stream, typename K, typename T, typename Pred, typename A>
572 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
574 WriteCompactSize(os, m.size());
575 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
576 Serialize(os, (*mi), nType, nVersion);
579 template<typename Stream, typename K, typename T, typename Pred, typename A>
580 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
583 unsigned int nSize = ReadCompactSize(is);
584 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
585 for (unsigned int i = 0; i < nSize; i++)
588 Unserialize(is, item, nType, nVersion);
589 mi = m.insert(mi, item);
598 template<typename K, typename Pred, typename A>
599 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
601 unsigned int nSize = GetSizeOfCompactSize(m.size());
602 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
603 nSize += GetSerializeSize((*it), nType, nVersion);
607 template<typename Stream, typename K, typename Pred, typename A>
608 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
610 WriteCompactSize(os, m.size());
611 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
612 Serialize(os, (*it), nType, nVersion);
615 template<typename Stream, typename K, typename Pred, typename A>
616 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
619 unsigned int nSize = ReadCompactSize(is);
620 typename std::set<K, Pred, A>::iterator it = m.begin();
621 for (unsigned int i = 0; i < nSize; i++)
624 Unserialize(is, key, nType, nVersion);
625 it = m.insert(it, key);
632 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
634 class CSerActionGetSerializeSize { };
635 class CSerActionSerialize { };
636 class CSerActionUnserialize { };
638 template<typename Stream, typename T>
639 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
641 return ::GetSerializeSize(obj, nType, nVersion);
644 template<typename Stream, typename T>
645 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
647 ::Serialize(s, obj, nType, nVersion);
651 template<typename Stream, typename T>
652 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
654 ::Unserialize(s, obj, nType, nVersion);
658 struct ser_streamplaceholder
673 // Allocator that clears its contents before deletion
676 struct secure_allocator : public std::allocator<T>
678 // MSVC8 default copy constructor is broken
679 typedef std::allocator<T> base;
680 typedef typename base::size_type size_type;
681 typedef typename base::difference_type difference_type;
682 typedef typename base::pointer pointer;
683 typedef typename base::const_pointer const_pointer;
684 typedef typename base::reference reference;
685 typedef typename base::const_reference const_reference;
686 typedef typename base::value_type value_type;
687 secure_allocator() throw() {}
688 secure_allocator(const secure_allocator& a) throw() : base(a) {}
689 ~secure_allocator() throw() {}
690 template<typename _Other> struct rebind
691 { typedef secure_allocator<_Other> other; };
693 void deallocate(T* p, std::size_t n)
696 memset(p, 0, sizeof(T) * n);
697 allocator<T>::deallocate(p, n);
704 // Double ended buffer combining vector and stream-like interfaces.
705 // >> and << read and write unformatted data using the above serialization templates.
706 // Fills with data in linear time; some stringstream implementations take N^2 time.
711 typedef vector<char, secure_allocator<char> > vector_type;
713 unsigned int nReadPos;
720 typedef vector_type::allocator_type allocator_type;
721 typedef vector_type::size_type size_type;
722 typedef vector_type::difference_type difference_type;
723 typedef vector_type::reference reference;
724 typedef vector_type::const_reference const_reference;
725 typedef vector_type::value_type value_type;
726 typedef vector_type::iterator iterator;
727 typedef vector_type::const_iterator const_iterator;
728 typedef vector_type::reverse_iterator reverse_iterator;
730 explicit CDataStream(int nTypeIn=0, int nVersionIn=VERSION)
732 Init(nTypeIn, nVersionIn);
735 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=0, int nVersionIn=VERSION) : vch(pbegin, pend)
737 Init(nTypeIn, nVersionIn);
740 #if !defined(_MSC_VER) || _MSC_VER >= 1300
741 CDataStream(const char* pbegin, const char* pend, int nTypeIn=0, int nVersionIn=VERSION) : vch(pbegin, pend)
743 Init(nTypeIn, nVersionIn);
747 CDataStream(const vector_type& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
749 Init(nTypeIn, nVersionIn);
752 CDataStream(const vector<char>& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
754 Init(nTypeIn, nVersionIn);
757 CDataStream(const vector<unsigned char>& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
759 Init(nTypeIn, nVersionIn);
762 void Init(int nTypeIn=0, int nVersionIn=VERSION)
766 nVersion = nVersionIn;
768 exceptmask = ios::badbit | ios::failbit;
771 CDataStream& operator+=(const CDataStream& b)
773 vch.insert(vch.end(), b.begin(), b.end());
777 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
786 return (string(begin(), end()));
793 const_iterator begin() const { return vch.begin() + nReadPos; }
794 iterator begin() { return vch.begin() + nReadPos; }
795 const_iterator end() const { return vch.end(); }
796 iterator end() { return vch.end(); }
797 size_type size() const { return vch.size() - nReadPos; }
798 bool empty() const { return vch.size() == nReadPos; }
799 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }
800 void reserve(size_type n) { vch.reserve(n + nReadPos); }
801 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }
802 reference operator[](size_type pos) { return vch[pos + nReadPos]; }
803 void clear() { vch.clear(); nReadPos = 0; }
804 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
805 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
807 void insert(iterator it, const_iterator first, const_iterator last)
809 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
811 // special case for inserting at the front when there's room
812 nReadPos -= (last - first);
813 memcpy(&vch[nReadPos], &first[0], last - first);
816 vch.insert(it, first, last);
819 void insert(iterator it, vector<char>::const_iterator first, vector<char>::const_iterator last)
821 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
823 // special case for inserting at the front when there's room
824 nReadPos -= (last - first);
825 memcpy(&vch[nReadPos], &first[0], last - first);
828 vch.insert(it, first, last);
831 #if !defined(_MSC_VER) || _MSC_VER >= 1300
832 void insert(iterator it, const char* first, const char* last)
834 if (it == vch.begin() + nReadPos && last - first <= nReadPos)
836 // special case for inserting at the front when there's room
837 nReadPos -= (last - first);
838 memcpy(&vch[nReadPos], &first[0], last - first);
841 vch.insert(it, first, last);
845 iterator erase(iterator it)
847 if (it == vch.begin() + nReadPos)
849 // special case for erasing from the front
850 if (++nReadPos >= vch.size())
852 // whenever we reach the end, we take the opportunity to clear the buffer
854 return vch.erase(vch.begin(), vch.end());
856 return vch.begin() + nReadPos;
859 return vch.erase(it);
862 iterator erase(iterator first, iterator last)
864 if (first == vch.begin() + nReadPos)
866 // special case for erasing from the front
867 if (last == vch.end())
870 return vch.erase(vch.begin(), vch.end());
874 nReadPos = (last - vch.begin());
879 return vch.erase(first, last);
882 inline void Compact()
884 vch.erase(vch.begin(), vch.begin() + nReadPos);
888 bool Rewind(size_type n)
890 // Rewind by n characters if the buffer hasn't been compacted yet
901 void setstate(short bits, const char* psz)
904 if (state & exceptmask)
905 throw std::ios_base::failure(psz);
908 bool eof() const { return size() == 0; }
909 bool fail() const { return state & (ios::badbit | ios::failbit); }
910 bool good() const { return !eof() && (state == 0); }
911 void clear(short n) { state = n; } // name conflict with vector clear()
912 short exceptions() { return exceptmask; }
913 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
914 CDataStream* rdbuf() { return this; }
915 int in_avail() { return size(); }
917 void SetType(int n) { nType = n; }
918 int GetType() { return nType; }
919 void SetVersion(int n) { nVersion = n; }
920 int GetVersion() { return nVersion; }
921 void ReadVersion() { *this >> nVersion; }
922 void WriteVersion() { *this << nVersion; }
924 CDataStream& read(char* pch, int nSize)
926 // Read from the beginning of the buffer
928 unsigned int nReadPosNext = nReadPos + nSize;
929 if (nReadPosNext >= vch.size())
931 if (nReadPosNext > vch.size())
933 setstate(ios::failbit, "CDataStream::read() : end of data");
934 memset(pch, 0, nSize);
935 nSize = vch.size() - nReadPos;
937 memcpy(pch, &vch[nReadPos], nSize);
942 memcpy(pch, &vch[nReadPos], nSize);
943 nReadPos = nReadPosNext;
947 CDataStream& ignore(int nSize)
949 // Ignore from the beginning of the buffer
951 unsigned int nReadPosNext = nReadPos + nSize;
952 if (nReadPosNext >= vch.size())
954 if (nReadPosNext > vch.size())
956 setstate(ios::failbit, "CDataStream::ignore() : end of data");
957 nSize = vch.size() - nReadPos;
963 nReadPos = nReadPosNext;
967 CDataStream& write(const char* pch, int nSize)
969 // Write to the end of the buffer
971 vch.insert(vch.end(), pch, pch + nSize);
975 template<typename Stream>
976 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const
978 // Special case: stream << stream concatenates like stream += stream
980 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
984 unsigned int GetSerializeSize(const T& obj)
986 // Tells the size of the object if serialized to this stream
987 return ::GetSerializeSize(obj, nType, nVersion);
991 CDataStream& operator<<(const T& obj)
993 // Serialize to this stream
994 ::Serialize(*this, obj, nType, nVersion);
999 CDataStream& operator>>(T& obj)
1001 // Unserialize from this stream
1002 ::Unserialize(*this, obj, nType, nVersion);
1007 #ifdef TESTCDATASTREAM
1014 // n=16000 0 seconds
1015 // n=32000 0 seconds
1016 // n=64000 1 seconds
1017 // n=128000 1 seconds
1018 // n=256000 2 seconds
1019 // n=512000 4 seconds
1020 // n=1024000 8 seconds
1021 // n=2048000 16 seconds
1022 // n=4096000 32 seconds
1026 // n=4000 13 seconds
1027 // n=8000 87 seconds
1028 // n=16000 400 seconds
1029 // n=32000 1660 seconds
1030 // n=64000 6749 seconds
1031 // n=128000 27241 seconds
1032 // n=256000 109804 seconds
1034 int main(int argc, char *argv[])
1036 vector<unsigned char> vch(0xcc, 250);
1037 printf("CDataStream:\n");
1038 for (int n = 1000; n <= 4500000; n *= 2)
1041 time_t nStart = time(NULL);
1042 for (int i = 0; i < n; i++)
1043 ss.write((char*)&vch[0], vch.size());
1044 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1046 printf("stringstream:\n");
1047 for (int n = 1000; n <= 4500000; n *= 2)
1050 time_t nStart = time(NULL);
1051 for (int i = 0; i < n; i++)
1052 ss.write((char*)&vch[0], vch.size());
1053 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1068 // Automatic closing wrapper for FILE*
1069 // - Will automatically close the file when it goes out of scope if not null.
1070 // - If you're returning the file pointer, return file.release().
1071 // - If you need to close the file early, use file.fclose() instead of fclose(file).
1083 typedef FILE element_type;
1085 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)
1089 nVersion = nVersionIn;
1091 exceptmask = ios::badbit | ios::failbit;
1101 if (file != NULL && file != stdin && file != stdout && file != stderr)
1106 FILE* release() { FILE* ret = file; file = NULL; return ret; }
1107 operator FILE*() { return file; }
1108 FILE* operator->() { return file; }
1109 FILE& operator*() { return *file; }
1110 FILE** operator&() { return &file; }
1111 FILE* operator=(FILE* pnew) { return file = pnew; }
1112 bool operator!() { return (file == NULL); }
1118 void setstate(short bits, const char* psz)
1121 if (state & exceptmask)
1122 throw std::ios_base::failure(psz);
1125 bool fail() const { return state & (ios::badbit | ios::failbit); }
1126 bool good() const { return state == 0; }
1127 void clear(short n = 0) { state = n; }
1128 short exceptions() { return exceptmask; }
1129 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1131 void SetType(int n) { nType = n; }
1132 int GetType() { return nType; }
1133 void SetVersion(int n) { nVersion = n; }
1134 int GetVersion() { return nVersion; }
1135 void ReadVersion() { *this >> nVersion; }
1136 void WriteVersion() { *this << nVersion; }
1138 CAutoFile& read(char* pch, int nSize)
1141 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1142 if (fread(pch, 1, nSize, file) != nSize)
1143 setstate(ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1147 CAutoFile& write(const char* pch, int nSize)
1150 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1151 if (fwrite(pch, 1, nSize, file) != nSize)
1152 setstate(ios::failbit, "CAutoFile::write : write failed");
1156 template<typename T>
1157 unsigned int GetSerializeSize(const T& obj)
1159 // Tells the size of the object if serialized to this stream
1160 return ::GetSerializeSize(obj, nType, nVersion);
1163 template<typename T>
1164 CAutoFile& operator<<(const T& obj)
1166 // Serialize to this stream
1168 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1169 ::Serialize(*this, obj, nType, nVersion);
1173 template<typename T>
1174 CAutoFile& operator>>(T& obj)
1176 // Unserialize from this stream
1178 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1179 ::Unserialize(*this, obj, nType, nVersion);