Bitcoin v0.1.5 · 2009-02-04
serialize.h
1// Copyright (c) 2009 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 = 105;232425262728/////////////////////////////////////////////////////////////////29//30// Templates for serializing to anything that looks like a stream,31// i.e. anything that supports .read(char*, int) and .write(char*, int)32//3334enum35{36 // primary actions37 SER_NETWORK = (1 << 0),38 SER_DISK = (1 << 1),39 SER_GETHASH = (1 << 2),4041 // modifiers42 SER_SKIPSIG = (1 << 16),43 SER_BLOCKHEADERONLY = (1 << 17),44};4546#define IMPLEMENT_SERIALIZE(statements) \47 unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const \48 { \49 CSerActionGetSerializeSize ser_action; \50 const bool fGetSize = true; \51 const bool fWrite = false; \52 const bool fRead = false; \53 unsigned int nSerSize = 0; \54 ser_streamplaceholder s; \55 s.nType = nType; \56 s.nVersion = nVersion; \57 {statements} \58 return nSerSize; \59 } \60 template<typename Stream> \61 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const \62 { \63 CSerActionSerialize ser_action; \64 const bool fGetSize = false; \65 const bool fWrite = true; \66 const bool fRead = false; \67 unsigned int nSerSize = 0; \68 {statements} \69 } \70 template<typename Stream> \71 void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) \72 { \73 CSerActionUnserialize ser_action; \74 const bool fGetSize = false; \75 const bool fWrite = false; \76 const bool fRead = true; \77 unsigned int nSerSize = 0; \78 {statements} \79 }8081#define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))82838485868788//89// Basic types90//91#define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))92#define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))9394inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }95inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }96inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }97inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }98inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }99inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }100inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }101inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }102inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }103inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }104inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }105inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }106inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }107108template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }109template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }110template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }111template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }112template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }113template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }114template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }115template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }116template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }117template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }118template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }119template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }120template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }121122template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }123template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }124template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }125template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }126template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }127template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }128template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }129template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }130template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }131template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }132template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }133template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }134template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }135136inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }137template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }138template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }139140141142143144145//146// Compact size147// size < 253 -- 1 byte148// size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)149// size <= UINT_MAX -- 5 bytes (254 + 4 bytes)150// size > UINT_MAX -- 9 bytes (255 + 8 bytes)151//152inline unsigned int GetSizeOfCompactSize(uint64 nSize)153{154 if (nSize < UCHAR_MAX-2) return sizeof(unsigned char);155 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);156 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);157 else return sizeof(unsigned char) + sizeof(uint64);158}159160template<typename Stream>161void WriteCompactSize(Stream& os, uint64 nSize)162{163 if (nSize < UCHAR_MAX-2)164 {165 unsigned char chSize = nSize;166 WRITEDATA(os, chSize);167 }168 else if (nSize <= USHRT_MAX)169 {170 unsigned char chSize = UCHAR_MAX-2;171 unsigned short xSize = nSize;172 WRITEDATA(os, chSize);173 WRITEDATA(os, xSize);174 }175 else if (nSize <= UINT_MAX)176 {177 unsigned char chSize = UCHAR_MAX-1;178 unsigned int xSize = nSize;179 WRITEDATA(os, chSize);180 WRITEDATA(os, xSize);181 }182 else183 {184 unsigned char chSize = UCHAR_MAX;185 WRITEDATA(os, chSize);186 WRITEDATA(os, nSize);187 }188 return;189}190191template<typename Stream>192uint64 ReadCompactSize(Stream& is)193{194 unsigned char chSize;195 READDATA(is, chSize);196 if (chSize < UCHAR_MAX-2)197 {198 return chSize;199 }200 else if (chSize == UCHAR_MAX-2)201 {202 unsigned short nSize;203 READDATA(is, nSize);204 return nSize;205 }206 else if (chSize == UCHAR_MAX-1)207 {208 unsigned int nSize;209 READDATA(is, nSize);210 return nSize;211 }212 else213 {214 uint64 nSize;215 READDATA(is, nSize);216 return nSize;217 }218}219220221222//223// Wrapper for serializing arrays and POD224// There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it225//226#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))227class CFlatData228{229protected:230 char* pbegin;231 char* pend;232public:233 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }234 char* begin() { return pbegin; }235 const char* begin() const { return pbegin; }236 char* end() { return pend; }237 const char* end() const { return pend; }238239 unsigned int GetSerializeSize(int, int=0) const240 {241 return pend - pbegin;242 }243244 template<typename Stream>245 void Serialize(Stream& s, int, int=0) const246 {247 s.write(pbegin, pend - pbegin);248 }249250 template<typename Stream>251 void Unserialize(Stream& s, int, int=0)252 {253 s.read(pbegin, pend - pbegin);254 }255};256257258259//260// string stored as a fixed length field261//262template<std::size_t LEN>263class CFixedFieldString264{265protected:266 const string* pcstr;267 string* pstr;268public:269 explicit CFixedFieldString(const string& str) : pcstr(&str), pstr(NULL) { }270 explicit CFixedFieldString(string& str) : pcstr(&str), pstr(&str) { }271272 unsigned int GetSerializeSize(int, int=0) const273 {274 return LEN;275 }276277 template<typename Stream>278 void Serialize(Stream& s, int, int=0) const279 {280 char pszBuf[LEN];281 strncpy(pszBuf, pcstr->c_str(), LEN);282 s.write(pszBuf, LEN);283 }284285 template<typename Stream>286 void Unserialize(Stream& s, int, int=0)287 {288 if (pstr == NULL)289 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");290 char pszBuf[LEN+1];291 s.read(pszBuf, LEN);292 pszBuf[LEN] = '\0';293 *pstr = pszBuf;294 }295};296297298299300301//302// Forward declarations303//304305// string306template<typename C> unsigned int GetSerializeSize(const basic_string<C>& str, int, int=0);307template<typename Stream, typename C> void Serialize(Stream& os, const basic_string<C>& str, int, int=0);308template<typename Stream, typename C> void Unserialize(Stream& is, basic_string<C>& str, int, int=0);309310// vector311template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);312template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);313template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);314template<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&);315template<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&);316template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);317template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);318template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);319template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);320321// others derived from vector322extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);323template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);324template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);325326// pair327template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);328template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);329template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);330331// map332template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion=VERSION);333template<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);334template<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);335336// set337template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);338template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);339template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);340341342343344345//346// If none of the specialized versions above matched, default to calling member function.347// "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.348// The compiler will only cast int to long if none of the other templates matched.349// Thanks to Boost serialization for this idea.350//351template<typename T>352inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)353{354 return a.GetSerializeSize((int)nType, nVersion);355}356357template<typename Stream, typename T>358inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)359{360 a.Serialize(os, (int)nType, nVersion);361}362363template<typename Stream, typename T>364inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)365{366 a.Unserialize(is, (int)nType, nVersion);367}368369370371372373//374// string375//376template<typename C>377unsigned int GetSerializeSize(const basic_string<C>& str, int, int)378{379 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);380}381382template<typename Stream, typename C>383void Serialize(Stream& os, const basic_string<C>& str, int, int)384{385 WriteCompactSize(os, str.size());386 if (!str.empty())387 os.write((char*)&str[0], str.size() * sizeof(str[0]));388}389390template<typename Stream, typename C>391void Unserialize(Stream& is, basic_string<C>& str, int, int)392{393 unsigned int nSize = ReadCompactSize(is);394 str.resize(nSize);395 if (nSize != 0)396 is.read((char*)&str[0], nSize * sizeof(str[0]));397}398399400401//402// vector403//404template<typename T, typename A>405unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)406{407 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));408}409410template<typename T, typename A>411unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)412{413 unsigned int nSize = GetSizeOfCompactSize(v.size());414 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)415 nSize += GetSerializeSize((*vi), nType, nVersion);416 return nSize;417}418419template<typename T, typename A>420inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)421{422 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());423}424425426template<typename Stream, typename T, typename A>427void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)428{429 WriteCompactSize(os, v.size());430 if (!v.empty())431 os.write((char*)&v[0], v.size() * sizeof(T));432}433434template<typename Stream, typename T, typename A>435void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)436{437 WriteCompactSize(os, v.size());438 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)439 ::Serialize(os, (*vi), nType, nVersion);440}441442template<typename Stream, typename T, typename A>443inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)444{445 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());446}447448449template<typename Stream, typename T, typename A>450void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)451{452 //unsigned int nSize = ReadCompactSize(is);453 //v.resize(nSize);454 //is.read((char*)&v[0], nSize * sizeof(T));455456 // Limit size per read so bogus size value won't cause out of memory457 v.clear();458 unsigned int nSize = ReadCompactSize(is);459 unsigned int i = 0;460 while (i < nSize)461 {462 unsigned int blk = min(nSize - i, 1 + 4999999 / sizeof(T));463 v.resize(i + blk);464 is.read((char*)&v[i], blk * sizeof(T));465 i += blk;466 }467}468469template<typename Stream, typename T, typename A>470void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)471{472 //unsigned int nSize = ReadCompactSize(is);473 //v.resize(nSize);474 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)475 // Unserialize(is, (*vi), nType, nVersion);476477 v.clear();478 unsigned int nSize = ReadCompactSize(is);479 unsigned int i = 0;480 unsigned int nMid = 0;481 while (nMid < nSize)482 {483 nMid += 5000000 / sizeof(T);484 if (nMid > nSize)485 nMid = nSize;486 v.resize(nMid);487 for (; i < nMid; i++)488 Unserialize(is, v[i], nType, nVersion);489 }490}491492template<typename Stream, typename T, typename A>493inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)494{495 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());496}497498499500//501// others derived from vector502//503inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)504{505 return GetSerializeSize((const vector<unsigned char>&)v, nType, nVersion);506}507508template<typename Stream>509void Serialize(Stream& os, const CScript& v, int nType, int nVersion)510{511 Serialize(os, (const vector<unsigned char>&)v, nType, nVersion);512}513514template<typename Stream>515void Unserialize(Stream& is, CScript& v, int nType, int nVersion)516{517 Unserialize(is, (vector<unsigned char>&)v, nType, nVersion);518}519520521522//523// pair524//525template<typename K, typename T>526unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)527{528 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);529}530531template<typename Stream, typename K, typename T>532void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)533{534 Serialize(os, item.first, nType, nVersion);535 Serialize(os, item.second, nType, nVersion);536}537538template<typename Stream, typename K, typename T>539void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)540{541 Unserialize(is, item.first, nType, nVersion);542 Unserialize(is, item.second, nType, nVersion);543}544545546547//548// map549//550template<typename K, typename T, typename Pred, typename A>551unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)552{553 unsigned int nSize = GetSizeOfCompactSize(m.size());554 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)555 nSize += GetSerializeSize((*mi), nType, nVersion);556 return nSize;557}558559template<typename Stream, typename K, typename T, typename Pred, typename A>560void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)561{562 WriteCompactSize(os, m.size());563 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)564 Serialize(os, (*mi), nType, nVersion);565}566567template<typename Stream, typename K, typename T, typename Pred, typename A>568void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)569{570 m.clear();571 unsigned int nSize = ReadCompactSize(is);572 typename std::map<K, T, Pred, A>::iterator mi = m.begin();573 for (unsigned int i = 0; i < nSize; i++)574 {575 pair<K, T> item;576 Unserialize(is, item, nType, nVersion);577 mi = m.insert(mi, item);578 }579}580581582583//584// set585//586template<typename K, typename Pred, typename A>587unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)588{589 unsigned int nSize = GetSizeOfCompactSize(m.size());590 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)591 nSize += GetSerializeSize((*it), nType, nVersion);592 return nSize;593}594595template<typename Stream, typename K, typename Pred, typename A>596void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)597{598 WriteCompactSize(os, m.size());599 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)600 Serialize(os, (*it), nType, nVersion);601}602603template<typename Stream, typename K, typename Pred, typename A>604void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)605{606 m.clear();607 unsigned int nSize = ReadCompactSize(is);608 typename std::set<K, Pred, A>::iterator it = m.begin();609 for (unsigned int i = 0; i < nSize; i++)610 {611 K key;612 Unserialize(is, key, nType, nVersion);613 it = m.insert(it, key);614 }615}616617618619//620// Support for IMPLEMENT_SERIALIZE and READWRITE macro621//622class CSerActionGetSerializeSize { };623class CSerActionSerialize { };624class CSerActionUnserialize { };625626template<typename Stream, typename T>627inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)628{629 return ::GetSerializeSize(obj, nType, nVersion);630}631632template<typename Stream, typename T>633inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)634{635 ::Serialize(s, obj, nType, nVersion);636 return 0;637}638639template<typename Stream, typename T>640inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)641{642 ::Unserialize(s, obj, nType, nVersion);643 return 0;644}645646struct ser_streamplaceholder647{648 int nType;649 int nVersion;650};651652653654655656657658659660//661// Allocator that clears its contents before deletion662//663template<typename T>664struct secure_allocator : public std::allocator<T>665{666 // MSVC8 default copy constructor is broken667 typedef std::allocator<T> base;668 typedef typename base::size_type size_type;669 typedef typename base::difference_type difference_type;670 typedef typename base::pointer pointer;671 typedef typename base::const_pointer const_pointer;672 typedef typename base::reference reference;673 typedef typename base::const_reference const_reference;674 typedef typename base::value_type value_type;675 secure_allocator() throw() {}676 secure_allocator(const secure_allocator& a) throw() : base(a) {}677 ~secure_allocator() throw() {}678 template<typename _Other> struct rebind679 { typedef secure_allocator<_Other> other; };680681 void deallocate(T* p, std::size_t n)682 {683 if (p != NULL)684 memset(p, 0, sizeof(T) * n);685 allocator<T>::deallocate(p, n);686 }687};688689690691//692// Double ended buffer combining vector and stream-like interfaces.693// >> and << read and write unformatted data using the above serialization templates.694// Fills with data in linear time; some stringstream implementations take N^2 time.695//696class CDataStream697{698protected:699 typedef vector<char, secure_allocator<char> > vector_type;700 vector_type vch;701 unsigned int nReadPos;702 short state;703 short exceptmask;704public:705 int nType;706 int nVersion;707708 typedef vector_type::allocator_type allocator_type;709 typedef vector_type::size_type size_type;710 typedef vector_type::difference_type difference_type;711 typedef vector_type::reference reference;712 typedef vector_type::const_reference const_reference;713 typedef vector_type::value_type value_type;714 typedef vector_type::iterator iterator;715 typedef vector_type::const_iterator const_iterator;716 typedef vector_type::reverse_iterator reverse_iterator;717718 explicit CDataStream(int nTypeIn=0, int nVersionIn=VERSION)719 {720 Init(nTypeIn, nVersionIn);721 }722723 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=0, int nVersionIn=VERSION) : vch(pbegin, pend)724 {725 Init(nTypeIn, nVersionIn);726 }727728#if !defined(_MSC_VER) || _MSC_VER >= 1300729 CDataStream(const char* pbegin, const char* pend, int nTypeIn=0, int nVersionIn=VERSION) : vch(pbegin, pend)730 {731 Init(nTypeIn, nVersionIn);732 }733#endif734735 CDataStream(const vector_type& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())736 {737 Init(nTypeIn, nVersionIn);738 }739740 CDataStream(const vector<char>& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())741 {742 Init(nTypeIn, nVersionIn);743 }744745 CDataStream(const vector<unsigned char>& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])746 {747 Init(nTypeIn, nVersionIn);748 }749750 void Init(int nTypeIn=0, int nVersionIn=VERSION)751 {752 nReadPos = 0;753 nType = nTypeIn;754 nVersion = nVersionIn;755 state = 0;756 exceptmask = ios::badbit | ios::failbit;757 }758759 CDataStream& operator+=(const CDataStream& b)760 {761 vch.insert(vch.end(), b.begin(), b.end());762 return *this;763 }764765 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)766 {767 CDataStream ret = a;768 ret += b;769 return (ret);770 }771772 string str() const773 {774 return (string(begin(), end()));775 }776777778 //779 // Vector subset780 //781 const_iterator begin() const { return vch.begin() + nReadPos; }782 iterator begin() { return vch.begin() + nReadPos; }783 const_iterator end() const { return vch.end(); }784 iterator end() { return vch.end(); }785 size_type size() const { return vch.size() - nReadPos; }786 bool empty() const { return vch.size() == nReadPos; }787 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }788 void reserve(size_type n) { vch.reserve(n + nReadPos); }789 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }790 reference operator[](size_type pos) { return vch[pos + nReadPos]; }791 void clear() { vch.clear(); nReadPos = 0; }792 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }793 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }794795 void insert(iterator it, const_iterator first, const_iterator last)796 {797 if (it == vch.begin() + nReadPos && last - first <= nReadPos)798 {799 // special case for inserting at the front when there's room800 nReadPos -= (last - first);801 memcpy(&vch[nReadPos], &first[0], last - first);802 }803 else804 vch.insert(it, first, last);805 }806807#if !defined(_MSC_VER) || _MSC_VER >= 1300808 void insert(iterator it, const char* first, const char* last)809 {810 if (it == vch.begin() + nReadPos && last - first <= nReadPos)811 {812 // special case for inserting at the front when there's room813 nReadPos -= (last - first);814 memcpy(&vch[nReadPos], &first[0], last - first);815 }816 else817 vch.insert(it, first, last);818 }819#endif820821 iterator erase(iterator it)822 {823 if (it == vch.begin() + nReadPos)824 {825 // special case for erasing from the front826 if (++nReadPos >= vch.size())827 {828 // whenever we reach the end, we take the opportunity to clear the buffer829 nReadPos = 0;830 return vch.erase(vch.begin(), vch.end());831 }832 return vch.begin() + nReadPos;833 }834 else835 return vch.erase(it);836 }837838 iterator erase(iterator first, iterator last)839 {840 if (first == vch.begin() + nReadPos)841 {842 // special case for erasing from the front843 if (last == vch.end())844 {845 nReadPos = 0;846 return vch.erase(vch.begin(), vch.end());847 }848 else849 {850 nReadPos = (last - vch.begin());851 return last;852 }853 }854 else855 return vch.erase(first, last);856 }857858 inline void Compact()859 {860 vch.erase(vch.begin(), vch.begin() + nReadPos);861 nReadPos = 0;862 }863864 bool Rewind(size_type n)865 {866 // Rewind by n characters if the buffer hasn't been compacted yet867 if (n > nReadPos)868 return false;869 nReadPos -= n;870 return true;871 }872873874 //875 // Stream subset876 //877 void setstate(short bits, const char* psz)878 {879 state |= bits;880 if (state & exceptmask)881 throw std::ios_base::failure(psz);882 }883884 bool eof() const { return size() == 0; }885 bool fail() const { return state & (ios::badbit | ios::failbit); }886 bool good() const { return !eof() && (state == 0); }887 void clear(short n) { state = n; } // name conflict with vector clear()888 short exceptions() { return exceptmask; }889 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }890 CDataStream* rdbuf() { return this; }891 int in_avail() { return size(); }892893 void SetType(int n) { nType = n; }894 int GetType() { return nType; }895 void SetVersion(int n) { nVersion = n; }896 int GetVersion() { return nVersion; }897 void ReadVersion() { *this >> nVersion; }898 void WriteVersion() { *this << nVersion; }899900 CDataStream& read(char* pch, int nSize)901 {902 // Read from the beginning of the buffer903 assert(nSize >= 0);904 unsigned int nReadPosNext = nReadPos + nSize;905 if (nReadPosNext >= vch.size())906 {907 if (nReadPosNext > vch.size())908 {909 setstate(ios::failbit, "CDataStream::read() : end of data");910 memset(pch, 0, nSize);911 nSize = vch.size() - nReadPos;912 }913 memcpy(pch, &vch[nReadPos], nSize);914 nReadPos = 0;915 vch.clear();916 return (*this);917 }918 memcpy(pch, &vch[nReadPos], nSize);919 nReadPos = nReadPosNext;920 return (*this);921 }922923 CDataStream& ignore(int nSize)924 {925 // Ignore from the beginning of the buffer926 assert(nSize >= 0);927 unsigned int nReadPosNext = nReadPos + nSize;928 if (nReadPosNext >= vch.size())929 {930 if (nReadPosNext > vch.size())931 {932 setstate(ios::failbit, "CDataStream::ignore() : end of data");933 nSize = vch.size() - nReadPos;934 }935 nReadPos = 0;936 vch.clear();937 return (*this);938 }939 nReadPos = nReadPosNext;940 return (*this);941 }942943 CDataStream& write(const char* pch, int nSize)944 {945 // Write to the end of the buffer946 assert(nSize >= 0);947 vch.insert(vch.end(), pch, pch + nSize);948 return (*this);949 }950951 template<typename Stream>952 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const953 {954 // Special case: stream << stream concatenates like stream += stream955 if (!vch.empty())956 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));957 }958959 template<typename T>960 unsigned int GetSerializeSize(const T& obj)961 {962 // Tells the size of the object if serialized to this stream963 return ::GetSerializeSize(obj, nType, nVersion);964 }965966 template<typename T>967 CDataStream& operator<<(const T& obj)968 {969 // Serialize to this stream970 ::Serialize(*this, obj, nType, nVersion);971 return (*this);972 }973974 template<typename T>975 CDataStream& operator>>(T& obj)976 {977 // Unserialize from this stream978 ::Unserialize(*this, obj, nType, nVersion);979 return (*this);980 }981};982983#ifdef TESTCDATASTREAM984// VC6sp6985// CDataStream:986// n=1000 0 seconds987// n=2000 0 seconds988// n=4000 0 seconds989// n=8000 0 seconds990// n=16000 0 seconds991// n=32000 0 seconds992// n=64000 1 seconds993// n=128000 1 seconds994// n=256000 2 seconds995// n=512000 4 seconds996// n=1024000 8 seconds997// n=2048000 16 seconds998// n=4096000 32 seconds999// stringstream:1000// n=1000 1 seconds1001// n=2000 1 seconds1002// n=4000 13 seconds1003// n=8000 87 seconds1004// n=16000 400 seconds1005// n=32000 1660 seconds1006// n=64000 6749 seconds1007// n=128000 27241 seconds1008// n=256000 109804 seconds1009#include <iostream>1010int main(int argc, char *argv[])1011{1012 vector<unsigned char> vch(0xcc, 250);1013 printf("CDataStream:\n");1014 for (int n = 1000; n <= 4500000; n *= 2)1015 {1016 CDataStream ss;1017 time_t nStart = time(NULL);1018 for (int i = 0; i < n; i++)1019 ss.write((char*)&vch[0], vch.size());1020 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);1021 }1022 printf("stringstream:\n");1023 for (int n = 1000; n <= 4500000; n *= 2)1024 {1025 stringstream ss;1026 time_t nStart = time(NULL);1027 for (int i = 0; i < n; i++)1028 ss.write((char*)&vch[0], vch.size());1029 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);1030 }1031}1032#endif10331034103510361037103810391040104110421043//1044// Automatic closing wrapper for FILE*1045// - Will automatically close the file when it goes out of scope if not null.1046// - If you're returning the file pointer, return file.release().1047// - If you need to close the file early, use file.fclose() instead of fclose(file).1048//1049class CAutoFile1050{1051protected:1052 FILE* file;1053 short state;1054 short exceptmask;1055public:1056 int nType;1057 int nVersion;10581059 typedef FILE element_type;10601061 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)1062 {1063 file = filenew;1064 nType = nTypeIn;1065 nVersion = nVersionIn;1066 state = 0;1067 exceptmask = ios::badbit | ios::failbit;1068 }10691070 ~CAutoFile()1071 {1072 fclose();1073 }10741075 void fclose()1076 {1077 if (file != NULL && file != stdin && file != stdout && file != stderr)1078 ::fclose(file);1079 file = NULL;1080 }10811082 FILE* release() { FILE* ret = file; file = NULL; return ret; }1083 operator FILE*() { return file; }1084 FILE* operator->() { return file; }1085 FILE& operator*() { return *file; }1086 FILE** operator&() { return &file; }1087 FILE* operator=(FILE* pnew) { return file = pnew; }1088 bool operator!() { return (file == NULL); }108910901091 //1092 // Stream subset1093 //1094 void setstate(short bits, const char* psz)1095 {1096 state |= bits;1097 if (state & exceptmask)1098 throw std::ios_base::failure(psz);1099 }11001101 bool fail() const { return state & (ios::badbit | ios::failbit); }1102 bool good() const { return state == 0; }1103 void clear(short n = 0) { state = n; }1104 short exceptions() { return exceptmask; }1105 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }11061107 void SetType(int n) { nType = n; }1108 int GetType() { return nType; }1109 void SetVersion(int n) { nVersion = n; }1110 int GetVersion() { return nVersion; }1111 void ReadVersion() { *this >> nVersion; }1112 void WriteVersion() { *this << nVersion; }11131114 CAutoFile& read(char* pch, int nSize)1115 {1116 if (!file)1117 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");1118 if (fread(pch, 1, nSize, file) != nSize)1119 setstate(ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");1120 return (*this);1121 }11221123 CAutoFile& write(const char* pch, int nSize)1124 {1125 if (!file)1126 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");1127 if (fwrite(pch, 1, nSize, file) != nSize)1128 setstate(ios::failbit, "CAutoFile::write : write failed");1129 return (*this);1130 }11311132 template<typename T>1133 unsigned int GetSerializeSize(const T& obj)1134 {1135 // Tells the size of the object if serialized to this stream1136 return ::GetSerializeSize(obj, nType, nVersion);1137 }11381139 template<typename T>1140 CAutoFile& operator<<(const T& obj)1141 {1142 // Serialize to this stream1143 if (!file)1144 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");1145 ::Serialize(*this, obj, nType, nVersion);1146 return (*this);1147 }11481149 template<typename T>1150 CAutoFile& operator>>(T& obj)1151 {1152 // Unserialize from this stream1153 if (!file)1154 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");1155 ::Unserialize(*this, obj, nType, nVersion);1156 return (*this);1157 }1158};
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
