Bitcoin v0.3.0 · 2010-07-06
serialize.h
1// Copyright (c) 2009-2010 Satoshi Nakamoto2// Distributed under the MIT/X11 software license, see the accompanying3// file license.txt or http://www.opensource.org/licenses/mit-license.php.45#include <vector>6#include <map>7#include <boost/type_traits/is_fundamental.hpp>8#if defined(_MSC_VER) || defined(__BORLANDC__)9typedef __int64 int64;10typedef unsigned __int64 uint64;11#else12typedef long long int64;13typedef unsigned long long uint64;14#endif15#if defined(_MSC_VER) && _MSC_VER < 130016#define for if (false) ; else for17#endif18class CScript;19class CDataStream;20class CAutoFile;2122static const int VERSION = 300;23static const char* pszSubVer = "";242526272829/////////////////////////////////////////////////////////////////30//31// Templates for serializing to anything that looks like a stream,32// i.e. anything that supports .read(char*, int) and .write(char*, int)33//3435enum36{37 // primary actions38 SER_NETWORK = (1 << 0),39 SER_DISK = (1 << 1),40 SER_GETHASH = (1 << 2),4142 // modifiers43 SER_SKIPSIG = (1 << 16),44 SER_BLOCKHEADERONLY = (1 << 17),45};4647#define IMPLEMENT_SERIALIZE(statements) \48 unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const \49 { \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; \56 s.nType = nType; \57 s.nVersion = nVersion; \58 {statements} \59 return nSerSize; \60 } \61 template<typename Stream> \62 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const \63 { \64 CSerActionSerialize ser_action; \65 const bool fGetSize = false; \66 const bool fWrite = true; \67 const bool fRead = false; \68 unsigned int nSerSize = 0; \69 {statements} \70 } \71 template<typename Stream> \72 void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) \73 { \74 CSerActionUnserialize ser_action; \75 const bool fGetSize = false; \76 const bool fWrite = false; \77 const bool fRead = true; \78 unsigned int nSerSize = 0; \79 {statements} \80 }8182#define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))83848586878889//90// Basic types91//92#define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))93#define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))9495inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }96inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }97inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }98inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }99inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }100inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }101inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }102inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }103inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }104inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }105inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }106inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }107inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }108109template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }110template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }111template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }112template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }113template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }114template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }115template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }116template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }117template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }118template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }119template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }120template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }121template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }122123template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }124template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }125template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }126template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }127template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }128template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }129template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }130template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }131template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }132template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }133template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }134template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }135template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }136137inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }138template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }139template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }140141142143144145146//147// Compact size148// size < 253 -- 1 byte149// size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)150// size <= UINT_MAX -- 5 bytes (254 + 4 bytes)151// size > UINT_MAX -- 9 bytes (255 + 8 bytes)152//153inline unsigned int GetSizeOfCompactSize(uint64 nSize)154{155 if (nSize < UCHAR_MAX-2) return sizeof(unsigned char);156 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);157 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);158 else return sizeof(unsigned char) + sizeof(uint64);159}160161template<typename Stream>162void WriteCompactSize(Stream& os, uint64 nSize)163{164 if (nSize < UCHAR_MAX-2)165 {166 unsigned char chSize = nSize;167 WRITEDATA(os, chSize);168 }169 else if (nSize <= USHRT_MAX)170 {171 unsigned char chSize = UCHAR_MAX-2;172 unsigned short xSize = nSize;173 WRITEDATA(os, chSize);174 WRITEDATA(os, xSize);175 }176 else if (nSize <= UINT_MAX)177 {178 unsigned char chSize = UCHAR_MAX-1;179 unsigned int xSize = nSize;180 WRITEDATA(os, chSize);181 WRITEDATA(os, xSize);182 }183 else184 {185 unsigned char chSize = UCHAR_MAX;186 WRITEDATA(os, chSize);187 WRITEDATA(os, nSize);188 }189 return;190}191192template<typename Stream>193uint64 ReadCompactSize(Stream& is)194{195 unsigned char chSize;196 READDATA(is, chSize);197 uint64 nSizeRet = 0;198 if (chSize < UCHAR_MAX-2)199 {200 nSizeRet = chSize;201 }202 else if (chSize == UCHAR_MAX-2)203 {204 unsigned short nSize;205 READDATA(is, nSize);206 nSizeRet = nSize;207 }208 else if (chSize == UCHAR_MAX-1)209 {210 unsigned int nSize;211 READDATA(is, nSize);212 nSizeRet = nSize;213 }214 else215 {216 uint64 nSize;217 READDATA(is, nSize);218 nSizeRet = nSize;219 }220 if (nSizeRet > (uint64)INT_MAX)221 throw std::ios_base::failure("ReadCompactSize() : size too large");222 return nSizeRet;223}224225226227//228// Wrapper for serializing arrays and POD229// There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it230//231#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))232class CFlatData233{234protected:235 char* pbegin;236 char* pend;237public:238 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }239 char* begin() { return pbegin; }240 const char* begin() const { return pbegin; }241 char* end() { return pend; }242 const char* end() const { return pend; }243244 unsigned int GetSerializeSize(int, int=0) const245 {246 return pend - pbegin;247 }248249 template<typename Stream>250 void Serialize(Stream& s, int, int=0) const251 {252 s.write(pbegin, pend - pbegin);253 }254255 template<typename Stream>256 void Unserialize(Stream& s, int, int=0)257 {258 s.read(pbegin, pend - pbegin);259 }260};261262263264//265// string stored as a fixed length field266//267template<std::size_t LEN>268class CFixedFieldString269{270protected:271 const string* pcstr;272 string* pstr;273public:274 explicit CFixedFieldString(const string& str) : pcstr(&str), pstr(NULL) { }275 explicit CFixedFieldString(string& str) : pcstr(&str), pstr(&str) { }276277 unsigned int GetSerializeSize(int, int=0) const278 {279 return LEN;280 }281282 template<typename Stream>283 void Serialize(Stream& s, int, int=0) const284 {285 char pszBuf[LEN];286 strncpy(pszBuf, pcstr->c_str(), LEN);287 s.write(pszBuf, LEN);288 }289290 template<typename Stream>291 void Unserialize(Stream& s, int, int=0)292 {293 if (pstr == NULL)294 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");295 char pszBuf[LEN+1];296 s.read(pszBuf, LEN);297 pszBuf[LEN] = '\0';298 *pstr = pszBuf;299 }300};301302303304305306//307// Forward declarations308//309310// string311template<typename C> unsigned int GetSerializeSize(const basic_string<C>& str, int, int=0);312template<typename Stream, typename C> void Serialize(Stream& os, const basic_string<C>& str, int, int=0);313template<typename Stream, typename C> void Unserialize(Stream& is, basic_string<C>& str, int, int=0);314315// vector316template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);317template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);318template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);319template<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&);320template<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&);321template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);322template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);323template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);324template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);325326// others derived from vector327extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);328template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);329template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);330331// pair332template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);333template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);334template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);335336// map337template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion=VERSION);338template<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);339template<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);340341// set342template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);343template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);344template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);345346347348349350//351// If none of the specialized versions above matched, default to calling member function.352// "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.353// The compiler will only cast int to long if none of the other templates matched.354// Thanks to Boost serialization for this idea.355//356template<typename T>357inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)358{359 return a.GetSerializeSize((int)nType, nVersion);360}361362template<typename Stream, typename T>363inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)364{365 a.Serialize(os, (int)nType, nVersion);366}367368template<typename Stream, typename T>369inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)370{371 a.Unserialize(is, (int)nType, nVersion);372}373374375376377378//379// string380//381template<typename C>382unsigned int GetSerializeSize(const basic_string<C>& str, int, int)383{384 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);385}386387template<typename Stream, typename C>388void Serialize(Stream& os, const basic_string<C>& str, int, int)389{390 WriteCompactSize(os, str.size());391 if (!str.empty())392 os.write((char*)&str[0], str.size() * sizeof(str[0]));393}394395template<typename Stream, typename C>396void Unserialize(Stream& is, basic_string<C>& str, int, int)397{398 unsigned int nSize = ReadCompactSize(is);399 str.resize(nSize);400 if (nSize != 0)401 is.read((char*)&str[0], nSize * sizeof(str[0]));402}403404405406//407// vector408//409template<typename T, typename A>410unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)411{412 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));413}414415template<typename T, typename A>416unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)417{418 unsigned int nSize = GetSizeOfCompactSize(v.size());419 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)420 nSize += GetSerializeSize((*vi), nType, nVersion);421 return nSize;422}423424template<typename T, typename A>425inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)426{427 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());428}429430431template<typename Stream, typename T, typename A>432void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)433{434 WriteCompactSize(os, v.size());435 if (!v.empty())436 os.write((char*)&v[0], v.size() * sizeof(T));437}438439template<typename Stream, typename T, typename A>440void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)441{442 WriteCompactSize(os, v.size());443 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)444 ::Serialize(os, (*vi), nType, nVersion);445}446447template<typename Stream, typename T, typename A>448inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)449{450 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());451}452453454template<typename Stream, typename T, typename A>455void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)456{457 //unsigned int nSize = ReadCompactSize(is);458 //v.resize(nSize);459 //is.read((char*)&v[0], nSize * sizeof(T));460461 // Limit size per read so bogus size value won't cause out of memory462 v.clear();463 unsigned int nSize = ReadCompactSize(is);464 unsigned int i = 0;465 while (i < nSize)466 {467 unsigned int blk = min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));468 v.resize(i + blk);469 is.read((char*)&v[i], blk * sizeof(T));470 i += blk;471 }472}473474template<typename Stream, typename T, typename A>475void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)476{477 //unsigned int nSize = ReadCompactSize(is);478 //v.resize(nSize);479 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)480 // Unserialize(is, (*vi), nType, nVersion);481482 v.clear();483 unsigned int nSize = ReadCompactSize(is);484 unsigned int i = 0;485 unsigned int nMid = 0;486 while (nMid < nSize)487 {488 nMid += 5000000 / sizeof(T);489 if (nMid > nSize)490 nMid = nSize;491 v.resize(nMid);492 for (; i < nMid; i++)493 Unserialize(is, v[i], nType, nVersion);494 }495}496497template<typename Stream, typename T, typename A>498inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)499{500 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());501}502503504505//506// others derived from vector507//508inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)509{510 return GetSerializeSize((const vector<unsigned char>&)v, nType, nVersion);511}512513template<typename Stream>514void Serialize(Stream& os, const CScript& v, int nType, int nVersion)515{516 Serialize(os, (const vector<unsigned char>&)v, nType, nVersion);517}518519template<typename Stream>520void Unserialize(Stream& is, CScript& v, int nType, int nVersion)521{522 Unserialize(is, (vector<unsigned char>&)v, nType, nVersion);523}524525526527//528// pair529//530template<typename K, typename T>531unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)532{533 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);534}535536template<typename Stream, typename K, typename T>537void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)538{539 Serialize(os, item.first, nType, nVersion);540 Serialize(os, item.second, nType, nVersion);541}542543template<typename Stream, typename K, typename T>544void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)545{546 Unserialize(is, item.first, nType, nVersion);547 Unserialize(is, item.second, nType, nVersion);548}549550551552//553// map554//555template<typename K, typename T, typename Pred, typename A>556unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)557{558 unsigned int nSize = GetSizeOfCompactSize(m.size());559 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)560 nSize += GetSerializeSize((*mi), nType, nVersion);561 return nSize;562}563564template<typename Stream, typename K, typename T, typename Pred, typename A>565void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)566{567 WriteCompactSize(os, m.size());568 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)569 Serialize(os, (*mi), nType, nVersion);570}571572template<typename Stream, typename K, typename T, typename Pred, typename A>573void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)574{575 m.clear();576 unsigned int nSize = ReadCompactSize(is);577 typename std::map<K, T, Pred, A>::iterator mi = m.begin();578 for (unsigned int i = 0; i < nSize; i++)579 {580 pair<K, T> item;581 Unserialize(is, item, nType, nVersion);582 mi = m.insert(mi, item);583 }584}585586587588//589// set590//591template<typename K, typename Pred, typename A>592unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)593{594 unsigned int nSize = GetSizeOfCompactSize(m.size());595 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)596 nSize += GetSerializeSize((*it), nType, nVersion);597 return nSize;598}599600template<typename Stream, typename K, typename Pred, typename A>601void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)602{603 WriteCompactSize(os, m.size());604 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)605 Serialize(os, (*it), nType, nVersion);606}607608template<typename Stream, typename K, typename Pred, typename A>609void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)610{611 m.clear();612 unsigned int nSize = ReadCompactSize(is);613 typename std::set<K, Pred, A>::iterator it = m.begin();614 for (unsigned int i = 0; i < nSize; i++)615 {616 K key;617 Unserialize(is, key, nType, nVersion);618 it = m.insert(it, key);619 }620}621622623624//625// Support for IMPLEMENT_SERIALIZE and READWRITE macro626//627class CSerActionGetSerializeSize { };628class CSerActionSerialize { };629class CSerActionUnserialize { };630631template<typename Stream, typename T>632inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)633{634 return ::GetSerializeSize(obj, nType, nVersion);635}636637template<typename Stream, typename T>638inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)639{640 ::Serialize(s, obj, nType, nVersion);641 return 0;642}643644template<typename Stream, typename T>645inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)646{647 ::Unserialize(s, obj, nType, nVersion);648 return 0;649}650651struct ser_streamplaceholder652{653 int nType;654 int nVersion;655};656657658659660661662663664665//666// Allocator that clears its contents before deletion667//668template<typename T>669struct secure_allocator : public std::allocator<T>670{671 // MSVC8 default copy constructor is broken672 typedef std::allocator<T> base;673 typedef typename base::size_type size_type;674 typedef typename base::difference_type difference_type;675 typedef typename base::pointer pointer;676 typedef typename base::const_pointer const_pointer;677 typedef typename base::reference reference;678 typedef typename base::const_reference const_reference;679 typedef typename base::value_type value_type;680 secure_allocator() throw() {}681 secure_allocator(const secure_allocator& a) throw() : base(a) {}682 ~secure_allocator() throw() {}683 template<typename _Other> struct rebind684 { typedef secure_allocator<_Other> other; };685686 void deallocate(T* p, std::size_t n)687 {688 if (p != NULL)689 memset(p, 0, sizeof(T) * n);690 allocator<T>::deallocate(p, n);691 }692};693694695696//697// Double ended buffer combining vector and stream-like interfaces.698// >> and << read and write unformatted data using the above serialization templates.699// Fills with data in linear time; some stringstream implementations take N^2 time.700//701class CDataStream702{703protected:704 typedef vector<char, secure_allocator<char> > vector_type;705 vector_type vch;706 unsigned int nReadPos;707 short state;708 short exceptmask;709public:710 int nType;711 int nVersion;712713 typedef vector_type::allocator_type allocator_type;714 typedef vector_type::size_type size_type;715 typedef vector_type::difference_type difference_type;716 typedef vector_type::reference reference;717 typedef vector_type::const_reference const_reference;718 typedef vector_type::value_type value_type;719 typedef vector_type::iterator iterator;720 typedef vector_type::const_iterator const_iterator;721 typedef vector_type::reverse_iterator reverse_iterator;722723 explicit CDataStream(int nTypeIn=0, int nVersionIn=VERSION)724 {725 Init(nTypeIn, nVersionIn);726 }727728 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=0, int nVersionIn=VERSION) : vch(pbegin, pend)729 {730 Init(nTypeIn, nVersionIn);731 }732733#if !defined(_MSC_VER) || _MSC_VER >= 1300734 CDataStream(const char* pbegin, const char* pend, int nTypeIn=0, int nVersionIn=VERSION) : vch(pbegin, pend)735 {736 Init(nTypeIn, nVersionIn);737 }738#endif739740 CDataStream(const vector_type& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())741 {742 Init(nTypeIn, nVersionIn);743 }744745 CDataStream(const vector<char>& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())746 {747 Init(nTypeIn, nVersionIn);748 }749750 CDataStream(const vector<unsigned char>& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])751 {752 Init(nTypeIn, nVersionIn);753 }754755 void Init(int nTypeIn=0, int nVersionIn=VERSION)756 {757 nReadPos = 0;758 nType = nTypeIn;759 nVersion = nVersionIn;760 state = 0;761 exceptmask = ios::badbit | ios::failbit;762 }763764 CDataStream& operator+=(const CDataStream& b)765 {766 vch.insert(vch.end(), b.begin(), b.end());767 return *this;768 }769770 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)771 {772 CDataStream ret = a;773 ret += b;774 return (ret);775 }776777 string str() const778 {779 return (string(begin(), end()));780 }781782783 //784 // Vector subset785 //786 const_iterator begin() const { return vch.begin() + nReadPos; }787 iterator begin() { return vch.begin() + nReadPos; }788 const_iterator end() const { return vch.end(); }789 iterator end() { return vch.end(); }790 size_type size() const { return vch.size() - nReadPos; }791 bool empty() const { return vch.size() == nReadPos; }792 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }793 void reserve(size_type n) { vch.reserve(n + nReadPos); }794 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }795 reference operator[](size_type pos) { return vch[pos + nReadPos]; }796 void clear() { vch.clear(); nReadPos = 0; }797 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }798 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }799800 void insert(iterator it, const_iterator first, const_iterator last)801 {802 if (it == vch.begin() + nReadPos && last - first <= nReadPos)803 {804 // special case for inserting at the front when there's room805 nReadPos -= (last - first);806 memcpy(&vch[nReadPos], &first[0], last - first);807 }808 else809 vch.insert(it, first, last);810 }811812 void insert(iterator it, vector<char>::const_iterator first, vector<char>::const_iterator last)813 {814 if (it == vch.begin() + nReadPos && last - first <= nReadPos)815 {816 // special case for inserting at the front when there's room817 nReadPos -= (last - first);818 memcpy(&vch[nReadPos], &first[0], last - first);819 }820 else821 vch.insert(it, first, last);822 }823824#if !defined(_MSC_VER) || _MSC_VER >= 1300825 void insert(iterator it, const char* first, const char* last)826 {827 if (it == vch.begin() + nReadPos && last - first <= nReadPos)828 {829 // special case for inserting at the front when there's room830 nReadPos -= (last - first);831 memcpy(&vch[nReadPos], &first[0], last - first);832 }833 else834 vch.insert(it, first, last);835 }836#endif837838 iterator erase(iterator it)839 {840 if (it == vch.begin() + nReadPos)841 {842 // special case for erasing from the front843 if (++nReadPos >= vch.size())844 {845 // whenever we reach the end, we take the opportunity to clear the buffer846 nReadPos = 0;847 return vch.erase(vch.begin(), vch.end());848 }849 return vch.begin() + nReadPos;850 }851 else852 return vch.erase(it);853 }854855 iterator erase(iterator first, iterator last)856 {857 if (first == vch.begin() + nReadPos)858 {859 // special case for erasing from the front860 if (last == vch.end())861 {862 nReadPos = 0;863 return vch.erase(vch.begin(), vch.end());864 }865 else866 {867 nReadPos = (last - vch.begin());868 return last;869 }870 }871 else872 return vch.erase(first, last);873 }874875 inline void Compact()876 {877 vch.erase(vch.begin(), vch.begin() + nReadPos);878 nReadPos = 0;879 }880881 bool Rewind(size_type n)882 {883 // Rewind by n characters if the buffer hasn't been compacted yet884 if (n > nReadPos)885 return false;886 nReadPos -= n;887 return true;888 }889890891 //892 // Stream subset893 //894 void setstate(short bits, const char* psz)895 {896 state |= bits;897 if (state & exceptmask)898 throw std::ios_base::failure(psz);899 }900901 bool eof() const { return size() == 0; }902 bool fail() const { return state & (ios::badbit | ios::failbit); }903 bool good() const { return !eof() && (state == 0); }904 void clear(short n) { state = n; } // name conflict with vector clear()905 short exceptions() { return exceptmask; }906 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }907 CDataStream* rdbuf() { return this; }908 int in_avail() { return size(); }909910 void SetType(int n) { nType = n; }911 int GetType() { return nType; }912 void SetVersion(int n) { nVersion = n; }913 int GetVersion() { return nVersion; }914 void ReadVersion() { *this >> nVersion; }915 void WriteVersion() { *this << nVersion; }916917 CDataStream& read(char* pch, int nSize)918 {919 // Read from the beginning of the buffer920 assert(nSize >= 0);921 unsigned int nReadPosNext = nReadPos + nSize;922 if (nReadPosNext >= vch.size())923 {924 if (nReadPosNext > vch.size())925 {926 setstate(ios::failbit, "CDataStream::read() : end of data");927 memset(pch, 0, nSize);928 nSize = vch.size() - nReadPos;929 }930 memcpy(pch, &vch[nReadPos], nSize);931 nReadPos = 0;932 vch.clear();933 return (*this);934 }935 memcpy(pch, &vch[nReadPos], nSize);936 nReadPos = nReadPosNext;937 return (*this);938 }939940 CDataStream& ignore(int nSize)941 {942 // Ignore from the beginning of the buffer943 assert(nSize >= 0);944 unsigned int nReadPosNext = nReadPos + nSize;945 if (nReadPosNext >= vch.size())946 {947 if (nReadPosNext > vch.size())948 {949 setstate(ios::failbit, "CDataStream::ignore() : end of data");950 nSize = vch.size() - nReadPos;951 }952 nReadPos = 0;953 vch.clear();954 return (*this);955 }956 nReadPos = nReadPosNext;957 return (*this);958 }959960 CDataStream& write(const char* pch, int nSize)961 {962 // Write to the end of the buffer963 assert(nSize >= 0);964 vch.insert(vch.end(), pch, pch + nSize);965 return (*this);966 }967968 template<typename Stream>969 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const970 {971 // Special case: stream << stream concatenates like stream += stream972 if (!vch.empty())973 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));974 }975976 template<typename T>977 unsigned int GetSerializeSize(const T& obj)978 {979 // Tells the size of the object if serialized to this stream980 return ::GetSerializeSize(obj, nType, nVersion);981 }982983 template<typename T>984 CDataStream& operator<<(const T& obj)985 {986 // Serialize to this stream987 ::Serialize(*this, obj, nType, nVersion);988 return (*this);989 }990991 template<typename T>992 CDataStream& operator>>(T& obj)993 {994 // Unserialize from this stream995 ::Unserialize(*this, obj, nType, nVersion);996 return (*this);997 }998};9991000#ifdef TESTCDATASTREAM1001// VC6sp61002// CDataStream:1003// n=1000 0 seconds1004// n=2000 0 seconds1005// n=4000 0 seconds1006// n=8000 0 seconds1007// n=16000 0 seconds1008// n=32000 0 seconds1009// n=64000 1 seconds1010// n=128000 1 seconds1011// n=256000 2 seconds1012// n=512000 4 seconds1013// n=1024000 8 seconds1014// n=2048000 16 seconds1015// n=4096000 32 seconds1016// stringstream:1017// n=1000 1 seconds1018// n=2000 1 seconds1019// n=4000 13 seconds1020// n=8000 87 seconds1021// n=16000 400 seconds1022// n=32000 1660 seconds1023// n=64000 6749 seconds1024// n=128000 27241 seconds1025// n=256000 109804 seconds1026#include <iostream>1027int main(int argc, char *argv[])1028{1029 vector<unsigned char> vch(0xcc, 250);1030 printf("CDataStream:\n");1031 for (int n = 1000; n <= 4500000; n *= 2)1032 {1033 CDataStream ss;1034 time_t nStart = time(NULL);1035 for (int i = 0; i < n; i++)1036 ss.write((char*)&vch[0], vch.size());1037 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);1038 }1039 printf("stringstream:\n");1040 for (int n = 1000; n <= 4500000; n *= 2)1041 {1042 stringstream ss;1043 time_t nStart = time(NULL);1044 for (int i = 0; i < n; i++)1045 ss.write((char*)&vch[0], vch.size());1046 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);1047 }1048}1049#endif10501051105210531054105510561057105810591060//1061// Automatic closing wrapper for FILE*1062// - Will automatically close the file when it goes out of scope if not null.1063// - If you're returning the file pointer, return file.release().1064// - If you need to close the file early, use file.fclose() instead of fclose(file).1065//1066class CAutoFile1067{1068protected:1069 FILE* file;1070 short state;1071 short exceptmask;1072public:1073 int nType;1074 int nVersion;10751076 typedef FILE element_type;10771078 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)1079 {1080 file = filenew;1081 nType = nTypeIn;1082 nVersion = nVersionIn;1083 state = 0;1084 exceptmask = ios::badbit | ios::failbit;1085 }10861087 ~CAutoFile()1088 {1089 fclose();1090 }10911092 void fclose()1093 {1094 if (file != NULL && file != stdin && file != stdout && file != stderr)1095 ::fclose(file);1096 file = NULL;1097 }10981099 FILE* release() { FILE* ret = file; file = NULL; return ret; }1100 operator FILE*() { return file; }1101 FILE* operator->() { return file; }1102 FILE& operator*() { return *file; }1103 FILE** operator&() { return &file; }1104 FILE* operator=(FILE* pnew) { return file = pnew; }1105 bool operator!() { return (file == NULL); }110611071108 //1109 // Stream subset1110 //1111 void setstate(short bits, const char* psz)1112 {1113 state |= bits;1114 if (state & exceptmask)1115 throw std::ios_base::failure(psz);1116 }11171118 bool fail() const { return state & (ios::badbit | ios::failbit); }1119 bool good() const { return state == 0; }1120 void clear(short n = 0) { state = n; }1121 short exceptions() { return exceptmask; }1122 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }11231124 void SetType(int n) { nType = n; }1125 int GetType() { return nType; }1126 void SetVersion(int n) { nVersion = n; }1127 int GetVersion() { return nVersion; }1128 void ReadVersion() { *this >> nVersion; }1129 void WriteVersion() { *this << nVersion; }11301131 CAutoFile& read(char* pch, int nSize)1132 {1133 if (!file)1134 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");1135 if (fread(pch, 1, nSize, file) != nSize)1136 setstate(ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");1137 return (*this);1138 }11391140 CAutoFile& write(const char* pch, int nSize)1141 {1142 if (!file)1143 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");1144 if (fwrite(pch, 1, nSize, file) != nSize)1145 setstate(ios::failbit, "CAutoFile::write : write failed");1146 return (*this);1147 }11481149 template<typename T>1150 unsigned int GetSerializeSize(const T& obj)1151 {1152 // Tells the size of the object if serialized to this stream1153 return ::GetSerializeSize(obj, nType, nVersion);1154 }11551156 template<typename T>1157 CAutoFile& operator<<(const T& obj)1158 {1159 // Serialize to this stream1160 if (!file)1161 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");1162 ::Serialize(*this, obj, nType, nVersion);1163 return (*this);1164 }11651166 template<typename T>1167 CAutoFile& operator>>(T& obj)1168 {1169 // Unserialize from this stream1170 if (!file)1171 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");1172 ::Unserialize(*this, obj, nType, nVersion);1173 return (*this);1174 }1175};
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
