Bitcoin v0.2.0 · 2009-12-16
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 = 200;23static const char* pszSubVer = " rc2";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 if (chSize < UCHAR_MAX-2)198 {199 return chSize;200 }201 else if (chSize == UCHAR_MAX-2)202 {203 unsigned short nSize;204 READDATA(is, nSize);205 return nSize;206 }207 else if (chSize == UCHAR_MAX-1)208 {209 unsigned int nSize;210 READDATA(is, nSize);211 return nSize;212 }213 else214 {215 uint64 nSize;216 READDATA(is, nSize);217 return nSize;218 }219}220221222223//224// Wrapper for serializing arrays and POD225// There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it226//227#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))228class CFlatData229{230protected:231 char* pbegin;232 char* pend;233public:234 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }235 char* begin() { return pbegin; }236 const char* begin() const { return pbegin; }237 char* end() { return pend; }238 const char* end() const { return pend; }239240 unsigned int GetSerializeSize(int, int=0) const241 {242 return pend - pbegin;243 }244245 template<typename Stream>246 void Serialize(Stream& s, int, int=0) const247 {248 s.write(pbegin, pend - pbegin);249 }250251 template<typename Stream>252 void Unserialize(Stream& s, int, int=0)253 {254 s.read(pbegin, pend - pbegin);255 }256};257258259260//261// string stored as a fixed length field262//263template<std::size_t LEN>264class CFixedFieldString265{266protected:267 const string* pcstr;268 string* pstr;269public:270 explicit CFixedFieldString(const string& str) : pcstr(&str), pstr(NULL) { }271 explicit CFixedFieldString(string& str) : pcstr(&str), pstr(&str) { }272273 unsigned int GetSerializeSize(int, int=0) const274 {275 return LEN;276 }277278 template<typename Stream>279 void Serialize(Stream& s, int, int=0) const280 {281 char pszBuf[LEN];282 strncpy(pszBuf, pcstr->c_str(), LEN);283 s.write(pszBuf, LEN);284 }285286 template<typename Stream>287 void Unserialize(Stream& s, int, int=0)288 {289 if (pstr == NULL)290 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");291 char pszBuf[LEN+1];292 s.read(pszBuf, LEN);293 pszBuf[LEN] = '\0';294 *pstr = pszBuf;295 }296};297298299300301302//303// Forward declarations304//305306// string307template<typename C> unsigned int GetSerializeSize(const basic_string<C>& str, int, int=0);308template<typename Stream, typename C> void Serialize(Stream& os, const basic_string<C>& str, int, int=0);309template<typename Stream, typename C> void Unserialize(Stream& is, basic_string<C>& str, int, int=0);310311// vector312template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);313template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);314template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);315template<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&);316template<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&);317template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);318template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);319template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);320template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);321322// others derived from vector323extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);324template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);325template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);326327// pair328template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);329template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);330template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);331332// map333template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(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 Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion=VERSION);335template<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);336337// set338template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);339template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);340template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);341342343344345346//347// If none of the specialized versions above matched, default to calling member function.348// "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.349// The compiler will only cast int to long if none of the other templates matched.350// Thanks to Boost serialization for this idea.351//352template<typename T>353inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)354{355 return a.GetSerializeSize((int)nType, nVersion);356}357358template<typename Stream, typename T>359inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)360{361 a.Serialize(os, (int)nType, nVersion);362}363364template<typename Stream, typename T>365inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)366{367 a.Unserialize(is, (int)nType, nVersion);368}369370371372373374//375// string376//377template<typename C>378unsigned int GetSerializeSize(const basic_string<C>& str, int, int)379{380 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);381}382383template<typename Stream, typename C>384void Serialize(Stream& os, const basic_string<C>& str, int, int)385{386 WriteCompactSize(os, str.size());387 if (!str.empty())388 os.write((char*)&str[0], str.size() * sizeof(str[0]));389}390391template<typename Stream, typename C>392void Unserialize(Stream& is, basic_string<C>& str, int, int)393{394 unsigned int nSize = ReadCompactSize(is);395 str.resize(nSize);396 if (nSize != 0)397 is.read((char*)&str[0], nSize * sizeof(str[0]));398}399400401402//403// vector404//405template<typename T, typename A>406unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)407{408 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));409}410411template<typename T, typename A>412unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)413{414 unsigned int nSize = GetSizeOfCompactSize(v.size());415 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)416 nSize += GetSerializeSize((*vi), nType, nVersion);417 return nSize;418}419420template<typename T, typename A>421inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)422{423 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());424}425426427template<typename Stream, typename T, typename A>428void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)429{430 WriteCompactSize(os, v.size());431 if (!v.empty())432 os.write((char*)&v[0], v.size() * sizeof(T));433}434435template<typename Stream, typename T, typename A>436void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)437{438 WriteCompactSize(os, v.size());439 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)440 ::Serialize(os, (*vi), nType, nVersion);441}442443template<typename Stream, typename T, typename A>444inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)445{446 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());447}448449450template<typename Stream, typename T, typename A>451void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)452{453 //unsigned int nSize = ReadCompactSize(is);454 //v.resize(nSize);455 //is.read((char*)&v[0], nSize * sizeof(T));456457 // Limit size per read so bogus size value won't cause out of memory458 v.clear();459 unsigned int nSize = ReadCompactSize(is);460 unsigned int i = 0;461 while (i < nSize)462 {463 unsigned int blk = min(nSize - i, 1 + 4999999 / sizeof(T));464 v.resize(i + blk);465 is.read((char*)&v[i], blk * sizeof(T));466 i += blk;467 }468}469470template<typename Stream, typename T, typename A>471void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)472{473 //unsigned int nSize = ReadCompactSize(is);474 //v.resize(nSize);475 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)476 // Unserialize(is, (*vi), nType, nVersion);477478 v.clear();479 unsigned int nSize = ReadCompactSize(is);480 unsigned int i = 0;481 unsigned int nMid = 0;482 while (nMid < nSize)483 {484 nMid += 5000000 / sizeof(T);485 if (nMid > nSize)486 nMid = nSize;487 v.resize(nMid);488 for (; i < nMid; i++)489 Unserialize(is, v[i], nType, nVersion);490 }491}492493template<typename Stream, typename T, typename A>494inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)495{496 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());497}498499500501//502// others derived from vector503//504inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)505{506 return GetSerializeSize((const vector<unsigned char>&)v, nType, nVersion);507}508509template<typename Stream>510void Serialize(Stream& os, const CScript& v, int nType, int nVersion)511{512 Serialize(os, (const vector<unsigned char>&)v, nType, nVersion);513}514515template<typename Stream>516void Unserialize(Stream& is, CScript& v, int nType, int nVersion)517{518 Unserialize(is, (vector<unsigned char>&)v, nType, nVersion);519}520521522523//524// pair525//526template<typename K, typename T>527unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)528{529 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);530}531532template<typename Stream, typename K, typename T>533void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)534{535 Serialize(os, item.first, nType, nVersion);536 Serialize(os, item.second, nType, nVersion);537}538539template<typename Stream, typename K, typename T>540void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)541{542 Unserialize(is, item.first, nType, nVersion);543 Unserialize(is, item.second, nType, nVersion);544}545546547548//549// map550//551template<typename K, typename T, typename Pred, typename A>552unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)553{554 unsigned int nSize = GetSizeOfCompactSize(m.size());555 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)556 nSize += GetSerializeSize((*mi), nType, nVersion);557 return nSize;558}559560template<typename Stream, typename K, typename T, typename Pred, typename A>561void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)562{563 WriteCompactSize(os, m.size());564 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)565 Serialize(os, (*mi), nType, nVersion);566}567568template<typename Stream, typename K, typename T, typename Pred, typename A>569void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)570{571 m.clear();572 unsigned int nSize = ReadCompactSize(is);573 typename std::map<K, T, Pred, A>::iterator mi = m.begin();574 for (unsigned int i = 0; i < nSize; i++)575 {576 pair<K, T> item;577 Unserialize(is, item, nType, nVersion);578 mi = m.insert(mi, item);579 }580}581582583584//585// set586//587template<typename K, typename Pred, typename A>588unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)589{590 unsigned int nSize = GetSizeOfCompactSize(m.size());591 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)592 nSize += GetSerializeSize((*it), nType, nVersion);593 return nSize;594}595596template<typename Stream, typename K, typename Pred, typename A>597void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)598{599 WriteCompactSize(os, m.size());600 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)601 Serialize(os, (*it), nType, nVersion);602}603604template<typename Stream, typename K, typename Pred, typename A>605void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)606{607 m.clear();608 unsigned int nSize = ReadCompactSize(is);609 typename std::set<K, Pred, A>::iterator it = m.begin();610 for (unsigned int i = 0; i < nSize; i++)611 {612 K key;613 Unserialize(is, key, nType, nVersion);614 it = m.insert(it, key);615 }616}617618619620//621// Support for IMPLEMENT_SERIALIZE and READWRITE macro622//623class CSerActionGetSerializeSize { };624class CSerActionSerialize { };625class CSerActionUnserialize { };626627template<typename Stream, typename T>628inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)629{630 return ::GetSerializeSize(obj, nType, nVersion);631}632633template<typename Stream, typename T>634inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)635{636 ::Serialize(s, obj, nType, nVersion);637 return 0;638}639640template<typename Stream, typename T>641inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)642{643 ::Unserialize(s, obj, nType, nVersion);644 return 0;645}646647struct ser_streamplaceholder648{649 int nType;650 int nVersion;651};652653654655656657658659660661//662// Allocator that clears its contents before deletion663//664template<typename T>665struct secure_allocator : public std::allocator<T>666{667 // MSVC8 default copy constructor is broken668 typedef std::allocator<T> base;669 typedef typename base::size_type size_type;670 typedef typename base::difference_type difference_type;671 typedef typename base::pointer pointer;672 typedef typename base::const_pointer const_pointer;673 typedef typename base::reference reference;674 typedef typename base::const_reference const_reference;675 typedef typename base::value_type value_type;676 secure_allocator() throw() {}677 secure_allocator(const secure_allocator& a) throw() : base(a) {}678 ~secure_allocator() throw() {}679 template<typename _Other> struct rebind680 { typedef secure_allocator<_Other> other; };681682 void deallocate(T* p, std::size_t n)683 {684 if (p != NULL)685 memset(p, 0, sizeof(T) * n);686 allocator<T>::deallocate(p, n);687 }688};689690691692//693// Double ended buffer combining vector and stream-like interfaces.694// >> and << read and write unformatted data using the above serialization templates.695// Fills with data in linear time; some stringstream implementations take N^2 time.696//697class CDataStream698{699protected:700 typedef vector<char, secure_allocator<char> > vector_type;701 vector_type vch;702 unsigned int nReadPos;703 short state;704 short exceptmask;705public:706 int nType;707 int nVersion;708709 typedef vector_type::allocator_type allocator_type;710 typedef vector_type::size_type size_type;711 typedef vector_type::difference_type difference_type;712 typedef vector_type::reference reference;713 typedef vector_type::const_reference const_reference;714 typedef vector_type::value_type value_type;715 typedef vector_type::iterator iterator;716 typedef vector_type::const_iterator const_iterator;717 typedef vector_type::reverse_iterator reverse_iterator;718719 explicit CDataStream(int nTypeIn=0, int nVersionIn=VERSION)720 {721 Init(nTypeIn, nVersionIn);722 }723724 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=0, int nVersionIn=VERSION) : vch(pbegin, pend)725 {726 Init(nTypeIn, nVersionIn);727 }728729#if !defined(_MSC_VER) || _MSC_VER >= 1300730 CDataStream(const char* pbegin, const char* pend, int nTypeIn=0, int nVersionIn=VERSION) : vch(pbegin, pend)731 {732 Init(nTypeIn, nVersionIn);733 }734#endif735736 CDataStream(const vector_type& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())737 {738 Init(nTypeIn, nVersionIn);739 }740741 CDataStream(const vector<char>& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())742 {743 Init(nTypeIn, nVersionIn);744 }745746 CDataStream(const vector<unsigned char>& vchIn, int nTypeIn=0, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])747 {748 Init(nTypeIn, nVersionIn);749 }750751 void Init(int nTypeIn=0, int nVersionIn=VERSION)752 {753 nReadPos = 0;754 nType = nTypeIn;755 nVersion = nVersionIn;756 state = 0;757 exceptmask = ios::badbit | ios::failbit;758 }759760 CDataStream& operator+=(const CDataStream& b)761 {762 vch.insert(vch.end(), b.begin(), b.end());763 return *this;764 }765766 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)767 {768 CDataStream ret = a;769 ret += b;770 return (ret);771 }772773 string str() const774 {775 return (string(begin(), end()));776 }777778779 //780 // Vector subset781 //782 const_iterator begin() const { return vch.begin() + nReadPos; }783 iterator begin() { return vch.begin() + nReadPos; }784 const_iterator end() const { return vch.end(); }785 iterator end() { return vch.end(); }786 size_type size() const { return vch.size() - nReadPos; }787 bool empty() const { return vch.size() == nReadPos; }788 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }789 void reserve(size_type n) { vch.reserve(n + nReadPos); }790 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }791 reference operator[](size_type pos) { return vch[pos + nReadPos]; }792 void clear() { vch.clear(); nReadPos = 0; }793 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }794 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }795796 void insert(iterator it, const_iterator first, const_iterator last)797 {798 if (it == vch.begin() + nReadPos && last - first <= nReadPos)799 {800 // special case for inserting at the front when there's room801 nReadPos -= (last - first);802 memcpy(&vch[nReadPos], &first[0], last - first);803 }804 else805 vch.insert(it, first, last);806 }807808#if !defined(_MSC_VER) || _MSC_VER >= 1300809 void insert(iterator it, const char* first, const char* last)810 {811 if (it == vch.begin() + nReadPos && last - first <= nReadPos)812 {813 // special case for inserting at the front when there's room814 nReadPos -= (last - first);815 memcpy(&vch[nReadPos], &first[0], last - first);816 }817 else818 vch.insert(it, first, last);819 }820#endif821822 iterator erase(iterator it)823 {824 if (it == vch.begin() + nReadPos)825 {826 // special case for erasing from the front827 if (++nReadPos >= vch.size())828 {829 // whenever we reach the end, we take the opportunity to clear the buffer830 nReadPos = 0;831 return vch.erase(vch.begin(), vch.end());832 }833 return vch.begin() + nReadPos;834 }835 else836 return vch.erase(it);837 }838839 iterator erase(iterator first, iterator last)840 {841 if (first == vch.begin() + nReadPos)842 {843 // special case for erasing from the front844 if (last == vch.end())845 {846 nReadPos = 0;847 return vch.erase(vch.begin(), vch.end());848 }849 else850 {851 nReadPos = (last - vch.begin());852 return last;853 }854 }855 else856 return vch.erase(first, last);857 }858859 inline void Compact()860 {861 vch.erase(vch.begin(), vch.begin() + nReadPos);862 nReadPos = 0;863 }864865 bool Rewind(size_type n)866 {867 // Rewind by n characters if the buffer hasn't been compacted yet868 if (n > nReadPos)869 return false;870 nReadPos -= n;871 return true;872 }873874875 //876 // Stream subset877 //878 void setstate(short bits, const char* psz)879 {880 state |= bits;881 if (state & exceptmask)882 throw std::ios_base::failure(psz);883 }884885 bool eof() const { return size() == 0; }886 bool fail() const { return state & (ios::badbit | ios::failbit); }887 bool good() const { return !eof() && (state == 0); }888 void clear(short n) { state = n; } // name conflict with vector clear()889 short exceptions() { return exceptmask; }890 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }891 CDataStream* rdbuf() { return this; }892 int in_avail() { return size(); }893894 void SetType(int n) { nType = n; }895 int GetType() { return nType; }896 void SetVersion(int n) { nVersion = n; }897 int GetVersion() { return nVersion; }898 void ReadVersion() { *this >> nVersion; }899 void WriteVersion() { *this << nVersion; }900901 CDataStream& read(char* pch, int nSize)902 {903 // Read from the beginning of the buffer904 assert(nSize >= 0);905 unsigned int nReadPosNext = nReadPos + nSize;906 if (nReadPosNext >= vch.size())907 {908 if (nReadPosNext > vch.size())909 {910 setstate(ios::failbit, "CDataStream::read() : end of data");911 memset(pch, 0, nSize);912 nSize = vch.size() - nReadPos;913 }914 memcpy(pch, &vch[nReadPos], nSize);915 nReadPos = 0;916 vch.clear();917 return (*this);918 }919 memcpy(pch, &vch[nReadPos], nSize);920 nReadPos = nReadPosNext;921 return (*this);922 }923924 CDataStream& ignore(int nSize)925 {926 // Ignore from the beginning of the buffer927 assert(nSize >= 0);928 unsigned int nReadPosNext = nReadPos + nSize;929 if (nReadPosNext >= vch.size())930 {931 if (nReadPosNext > vch.size())932 {933 setstate(ios::failbit, "CDataStream::ignore() : end of data");934 nSize = vch.size() - nReadPos;935 }936 nReadPos = 0;937 vch.clear();938 return (*this);939 }940 nReadPos = nReadPosNext;941 return (*this);942 }943944 CDataStream& write(const char* pch, int nSize)945 {946 // Write to the end of the buffer947 assert(nSize >= 0);948 vch.insert(vch.end(), pch, pch + nSize);949 return (*this);950 }951952 template<typename Stream>953 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const954 {955 // Special case: stream << stream concatenates like stream += stream956 if (!vch.empty())957 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));958 }959960 template<typename T>961 unsigned int GetSerializeSize(const T& obj)962 {963 // Tells the size of the object if serialized to this stream964 return ::GetSerializeSize(obj, nType, nVersion);965 }966967 template<typename T>968 CDataStream& operator<<(const T& obj)969 {970 // Serialize to this stream971 ::Serialize(*this, obj, nType, nVersion);972 return (*this);973 }974975 template<typename T>976 CDataStream& operator>>(T& obj)977 {978 // Unserialize from this stream979 ::Unserialize(*this, obj, nType, nVersion);980 return (*this);981 }982};983984#ifdef TESTCDATASTREAM985// VC6sp6986// CDataStream:987// n=1000 0 seconds988// n=2000 0 seconds989// n=4000 0 seconds990// n=8000 0 seconds991// n=16000 0 seconds992// n=32000 0 seconds993// n=64000 1 seconds994// n=128000 1 seconds995// n=256000 2 seconds996// n=512000 4 seconds997// n=1024000 8 seconds998// n=2048000 16 seconds999// n=4096000 32 seconds1000// stringstream:1001// n=1000 1 seconds1002// n=2000 1 seconds1003// n=4000 13 seconds1004// n=8000 87 seconds1005// n=16000 400 seconds1006// n=32000 1660 seconds1007// n=64000 6749 seconds1008// n=128000 27241 seconds1009// n=256000 109804 seconds1010#include <iostream>1011int main(int argc, char *argv[])1012{1013 vector<unsigned char> vch(0xcc, 250);1014 printf("CDataStream:\n");1015 for (int n = 1000; n <= 4500000; n *= 2)1016 {1017 CDataStream ss;1018 time_t nStart = time(NULL);1019 for (int i = 0; i < n; i++)1020 ss.write((char*)&vch[0], vch.size());1021 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);1022 }1023 printf("stringstream:\n");1024 for (int n = 1000; n <= 4500000; n *= 2)1025 {1026 stringstream ss;1027 time_t nStart = time(NULL);1028 for (int i = 0; i < n; i++)1029 ss.write((char*)&vch[0], vch.size());1030 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);1031 }1032}1033#endif10341035103610371038103910401041104210431044//1045// Automatic closing wrapper for FILE*1046// - Will automatically close the file when it goes out of scope if not null.1047// - If you're returning the file pointer, return file.release().1048// - If you need to close the file early, use file.fclose() instead of fclose(file).1049//1050class CAutoFile1051{1052protected:1053 FILE* file;1054 short state;1055 short exceptmask;1056public:1057 int nType;1058 int nVersion;10591060 typedef FILE element_type;10611062 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)1063 {1064 file = filenew;1065 nType = nTypeIn;1066 nVersion = nVersionIn;1067 state = 0;1068 exceptmask = ios::badbit | ios::failbit;1069 }10701071 ~CAutoFile()1072 {1073 fclose();1074 }10751076 void fclose()1077 {1078 if (file != NULL && file != stdin && file != stdout && file != stderr)1079 ::fclose(file);1080 file = NULL;1081 }10821083 FILE* release() { FILE* ret = file; file = NULL; return ret; }1084 operator FILE*() { return file; }1085 FILE* operator->() { return file; }1086 FILE& operator*() { return *file; }1087 FILE** operator&() { return &file; }1088 FILE* operator=(FILE* pnew) { return file = pnew; }1089 bool operator!() { return (file == NULL); }109010911092 //1093 // Stream subset1094 //1095 void setstate(short bits, const char* psz)1096 {1097 state |= bits;1098 if (state & exceptmask)1099 throw std::ios_base::failure(psz);1100 }11011102 bool fail() const { return state & (ios::badbit | ios::failbit); }1103 bool good() const { return state == 0; }1104 void clear(short n = 0) { state = n; }1105 short exceptions() { return exceptmask; }1106 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }11071108 void SetType(int n) { nType = n; }1109 int GetType() { return nType; }1110 void SetVersion(int n) { nVersion = n; }1111 int GetVersion() { return nVersion; }1112 void ReadVersion() { *this >> nVersion; }1113 void WriteVersion() { *this << nVersion; }11141115 CAutoFile& read(char* pch, int nSize)1116 {1117 if (!file)1118 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");1119 if (fread(pch, 1, nSize, file) != nSize)1120 setstate(ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");1121 return (*this);1122 }11231124 CAutoFile& write(const char* pch, int nSize)1125 {1126 if (!file)1127 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");1128 if (fwrite(pch, 1, nSize, file) != nSize)1129 setstate(ios::failbit, "CAutoFile::write : write failed");1130 return (*this);1131 }11321133 template<typename T>1134 unsigned int GetSerializeSize(const T& obj)1135 {1136 // Tells the size of the object if serialized to this stream1137 return ::GetSerializeSize(obj, nType, nVersion);1138 }11391140 template<typename T>1141 CAutoFile& operator<<(const T& obj)1142 {1143 // Serialize to this stream1144 if (!file)1145 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");1146 ::Serialize(*this, obj, nType, nVersion);1147 return (*this);1148 }11491150 template<typename T>1151 CAutoFile& operator>>(T& obj)1152 {1153 // Unserialize from this stream1154 if (!file)1155 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");1156 ::Unserialize(*this, obj, nType, nVersion);1157 return (*this);1158 }1159};
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
