Bitcoin r202 (last Satoshi commit) · 2010-12-15
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 <string>6#include <vector>7#include <map>8#include <set>9#include <boost/type_traits/is_fundamental.hpp>10#include <boost/tuple/tuple.hpp>11#include <boost/tuple/tuple_comparison.hpp>12#include <boost/tuple/tuple_io.hpp>13#if defined(_MSC_VER) || defined(__BORLANDC__)14typedef __int64 int64;15typedef unsigned __int64 uint64;16#else17typedef long long int64;18typedef unsigned long long uint64;19#endif20#if defined(_MSC_VER) && _MSC_VER < 130021#define for if (false) ; else for22#endif23class CScript;24class CDataStream;25class CAutoFile;26static const unsigned int MAX_SIZE = 0x02000000;2728static const int VERSION = 31901;29static const char* pszSubVer = "";30313233343536/////////////////////////////////////////////////////////////////37//38// Templates for serializing to anything that looks like a stream,39// i.e. anything that supports .read(char*, int) and .write(char*, int)40//4142enum43{44 // primary actions45 SER_NETWORK = (1 << 0),46 SER_DISK = (1 << 1),47 SER_GETHASH = (1 << 2),4849 // modifiers50 SER_SKIPSIG = (1 << 16),51 SER_BLOCKHEADERONLY = (1 << 17),52};5354#define IMPLEMENT_SERIALIZE(statements) \55 unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const \56 { \57 CSerActionGetSerializeSize ser_action; \58 const bool fGetSize = true; \59 const bool fWrite = false; \60 const bool fRead = false; \61 unsigned int nSerSize = 0; \62 ser_streamplaceholder s; \63 s.nType = nType; \64 s.nVersion = nVersion; \65 {statements} \66 return nSerSize; \67 } \68 template<typename Stream> \69 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const \70 { \71 CSerActionSerialize ser_action; \72 const bool fGetSize = false; \73 const bool fWrite = true; \74 const bool fRead = false; \75 unsigned int nSerSize = 0; \76 {statements} \77 } \78 template<typename Stream> \79 void Unserialize(Stream& s, int nType=0, int nVersion=VERSION) \80 { \81 CSerActionUnserialize ser_action; \82 const bool fGetSize = false; \83 const bool fWrite = false; \84 const bool fRead = true; \85 unsigned int nSerSize = 0; \86 {statements} \87 }8889#define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))90919293949596//97// Basic types98//99#define WRITEDATA(s, obj) s.write((char*)&(obj), sizeof(obj))100#define READDATA(s, obj) s.read((char*)&(obj), sizeof(obj))101102inline unsigned int GetSerializeSize(char a, int, int=0) { return sizeof(a); }103inline unsigned int GetSerializeSize(signed char a, int, int=0) { return sizeof(a); }104inline unsigned int GetSerializeSize(unsigned char a, int, int=0) { return sizeof(a); }105inline unsigned int GetSerializeSize(signed short a, int, int=0) { return sizeof(a); }106inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }107inline unsigned int GetSerializeSize(signed int a, int, int=0) { return sizeof(a); }108inline unsigned int GetSerializeSize(unsigned int a, int, int=0) { return sizeof(a); }109inline unsigned int GetSerializeSize(signed long a, int, int=0) { return sizeof(a); }110inline unsigned int GetSerializeSize(unsigned long a, int, int=0) { return sizeof(a); }111inline unsigned int GetSerializeSize(int64 a, int, int=0) { return sizeof(a); }112inline unsigned int GetSerializeSize(uint64 a, int, int=0) { return sizeof(a); }113inline unsigned int GetSerializeSize(float a, int, int=0) { return sizeof(a); }114inline unsigned int GetSerializeSize(double a, int, int=0) { return sizeof(a); }115116template<typename Stream> inline void Serialize(Stream& s, char a, int, int=0) { WRITEDATA(s, a); }117template<typename Stream> inline void Serialize(Stream& s, signed char a, int, int=0) { WRITEDATA(s, a); }118template<typename Stream> inline void Serialize(Stream& s, unsigned char a, int, int=0) { WRITEDATA(s, a); }119template<typename Stream> inline void Serialize(Stream& s, signed short a, int, int=0) { WRITEDATA(s, a); }120template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }121template<typename Stream> inline void Serialize(Stream& s, signed int a, int, int=0) { WRITEDATA(s, a); }122template<typename Stream> inline void Serialize(Stream& s, unsigned int a, int, int=0) { WRITEDATA(s, a); }123template<typename Stream> inline void Serialize(Stream& s, signed long a, int, int=0) { WRITEDATA(s, a); }124template<typename Stream> inline void Serialize(Stream& s, unsigned long a, int, int=0) { WRITEDATA(s, a); }125template<typename Stream> inline void Serialize(Stream& s, int64 a, int, int=0) { WRITEDATA(s, a); }126template<typename Stream> inline void Serialize(Stream& s, uint64 a, int, int=0) { WRITEDATA(s, a); }127template<typename Stream> inline void Serialize(Stream& s, float a, int, int=0) { WRITEDATA(s, a); }128template<typename Stream> inline void Serialize(Stream& s, double a, int, int=0) { WRITEDATA(s, a); }129130template<typename Stream> inline void Unserialize(Stream& s, char& a, int, int=0) { READDATA(s, a); }131template<typename Stream> inline void Unserialize(Stream& s, signed char& a, int, int=0) { READDATA(s, a); }132template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a, int, int=0) { READDATA(s, a); }133template<typename Stream> inline void Unserialize(Stream& s, signed short& a, int, int=0) { READDATA(s, a); }134template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }135template<typename Stream> inline void Unserialize(Stream& s, signed int& a, int, int=0) { READDATA(s, a); }136template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a, int, int=0) { READDATA(s, a); }137template<typename Stream> inline void Unserialize(Stream& s, signed long& a, int, int=0) { READDATA(s, a); }138template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a, int, int=0) { READDATA(s, a); }139template<typename Stream> inline void Unserialize(Stream& s, int64& a, int, int=0) { READDATA(s, a); }140template<typename Stream> inline void Unserialize(Stream& s, uint64& a, int, int=0) { READDATA(s, a); }141template<typename Stream> inline void Unserialize(Stream& s, float& a, int, int=0) { READDATA(s, a); }142template<typename Stream> inline void Unserialize(Stream& s, double& a, int, int=0) { READDATA(s, a); }143144inline unsigned int GetSerializeSize(bool a, int, int=0) { return sizeof(char); }145template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0) { char f=a; WRITEDATA(s, f); }146template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }147148149150151152153//154// Compact size155// size < 253 -- 1 byte156// size <= USHRT_MAX -- 3 bytes (253 + 2 bytes)157// size <= UINT_MAX -- 5 bytes (254 + 4 bytes)158// size > UINT_MAX -- 9 bytes (255 + 8 bytes)159//160inline unsigned int GetSizeOfCompactSize(uint64 nSize)161{162 if (nSize < 253) return sizeof(unsigned char);163 else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);164 else if (nSize <= UINT_MAX) return sizeof(unsigned char) + sizeof(unsigned int);165 else return sizeof(unsigned char) + sizeof(uint64);166}167168template<typename Stream>169void WriteCompactSize(Stream& os, uint64 nSize)170{171 if (nSize < 253)172 {173 unsigned char chSize = nSize;174 WRITEDATA(os, chSize);175 }176 else if (nSize <= USHRT_MAX)177 {178 unsigned char chSize = 253;179 unsigned short xSize = nSize;180 WRITEDATA(os, chSize);181 WRITEDATA(os, xSize);182 }183 else if (nSize <= UINT_MAX)184 {185 unsigned char chSize = 254;186 unsigned int xSize = nSize;187 WRITEDATA(os, chSize);188 WRITEDATA(os, xSize);189 }190 else191 {192 unsigned char chSize = 255;193 uint64 xSize = nSize;194 WRITEDATA(os, chSize);195 WRITEDATA(os, xSize);196 }197 return;198}199200template<typename Stream>201uint64 ReadCompactSize(Stream& is)202{203 unsigned char chSize;204 READDATA(is, chSize);205 uint64 nSizeRet = 0;206 if (chSize < 253)207 {208 nSizeRet = chSize;209 }210 else if (chSize == 253)211 {212 unsigned short xSize;213 READDATA(is, xSize);214 nSizeRet = xSize;215 }216 else if (chSize == 254)217 {218 unsigned int xSize;219 READDATA(is, xSize);220 nSizeRet = xSize;221 }222 else223 {224 uint64 xSize;225 READDATA(is, xSize);226 nSizeRet = xSize;227 }228 if (nSizeRet > (uint64)MAX_SIZE)229 throw std::ios_base::failure("ReadCompactSize() : size too large");230 return nSizeRet;231}232233234235//236// Wrapper for serializing arrays and POD237// There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it238//239#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))240class CFlatData241{242protected:243 char* pbegin;244 char* pend;245public:246 CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }247 char* begin() { return pbegin; }248 const char* begin() const { return pbegin; }249 char* end() { return pend; }250 const char* end() const { return pend; }251252 unsigned int GetSerializeSize(int, int=0) const253 {254 return pend - pbegin;255 }256257 template<typename Stream>258 void Serialize(Stream& s, int, int=0) const259 {260 s.write(pbegin, pend - pbegin);261 }262263 template<typename Stream>264 void Unserialize(Stream& s, int, int=0)265 {266 s.read(pbegin, pend - pbegin);267 }268};269270271272//273// string stored as a fixed length field274//275template<std::size_t LEN>276class CFixedFieldString277{278protected:279 const string* pcstr;280 string* pstr;281public:282 explicit CFixedFieldString(const string& str) : pcstr(&str), pstr(NULL) { }283 explicit CFixedFieldString(string& str) : pcstr(&str), pstr(&str) { }284285 unsigned int GetSerializeSize(int, int=0) const286 {287 return LEN;288 }289290 template<typename Stream>291 void Serialize(Stream& s, int, int=0) const292 {293 char pszBuf[LEN];294 strncpy(pszBuf, pcstr->c_str(), LEN);295 s.write(pszBuf, LEN);296 }297298 template<typename Stream>299 void Unserialize(Stream& s, int, int=0)300 {301 if (pstr == NULL)302 throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");303 char pszBuf[LEN+1];304 s.read(pszBuf, LEN);305 pszBuf[LEN] = '\0';306 *pstr = pszBuf;307 }308};309310311312313314//315// Forward declarations316//317318// string319template<typename C> unsigned int GetSerializeSize(const basic_string<C>& str, int, int=0);320template<typename Stream, typename C> void Serialize(Stream& os, const basic_string<C>& str, int, int=0);321template<typename Stream, typename C> void Unserialize(Stream& is, basic_string<C>& str, int, int=0);322323// vector324template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);325template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);326template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);327template<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&);328template<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&);329template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);330template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);331template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);332template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);333334// others derived from vector335extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);336template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);337template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);338339// pair340template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);341template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);342template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);343344// 3 tuple345template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);346template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);347template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);348349// 4 tuple350template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion=VERSION);351template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion=VERSION);352template<typename Stream, typename T0, typename T1, typename T2, typename T3> void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion=VERSION);353354// map355template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion=VERSION);356template<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);357template<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);358359// set360template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);361template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);362template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);363364365366367368//369// If none of the specialized versions above matched, default to calling member function.370// "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.371// The compiler will only cast int to long if none of the other templates matched.372// Thanks to Boost serialization for this idea.373//374template<typename T>375inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)376{377 return a.GetSerializeSize((int)nType, nVersion);378}379380template<typename Stream, typename T>381inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)382{383 a.Serialize(os, (int)nType, nVersion);384}385386template<typename Stream, typename T>387inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)388{389 a.Unserialize(is, (int)nType, nVersion);390}391392393394395396//397// string398//399template<typename C>400unsigned int GetSerializeSize(const basic_string<C>& str, int, int)401{402 return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);403}404405template<typename Stream, typename C>406void Serialize(Stream& os, const basic_string<C>& str, int, int)407{408 WriteCompactSize(os, str.size());409 if (!str.empty())410 os.write((char*)&str[0], str.size() * sizeof(str[0]));411}412413template<typename Stream, typename C>414void Unserialize(Stream& is, basic_string<C>& str, int, int)415{416 unsigned int nSize = ReadCompactSize(is);417 str.resize(nSize);418 if (nSize != 0)419 is.read((char*)&str[0], nSize * sizeof(str[0]));420}421422423424//425// vector426//427template<typename T, typename A>428unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)429{430 return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));431}432433template<typename T, typename A>434unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)435{436 unsigned int nSize = GetSizeOfCompactSize(v.size());437 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)438 nSize += GetSerializeSize((*vi), nType, nVersion);439 return nSize;440}441442template<typename T, typename A>443inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)444{445 return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());446}447448449template<typename Stream, typename T, typename A>450void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)451{452 WriteCompactSize(os, v.size());453 if (!v.empty())454 os.write((char*)&v[0], v.size() * sizeof(T));455}456457template<typename Stream, typename T, typename A>458void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)459{460 WriteCompactSize(os, v.size());461 for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)462 ::Serialize(os, (*vi), nType, nVersion);463}464465template<typename Stream, typename T, typename A>466inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)467{468 Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());469}470471472template<typename Stream, typename T, typename A>473void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)474{475 //unsigned int nSize = ReadCompactSize(is);476 //v.resize(nSize);477 //is.read((char*)&v[0], nSize * sizeof(T));478479 // Limit size per read so bogus size value won't cause out of memory480 v.clear();481 unsigned int nSize = ReadCompactSize(is);482 unsigned int i = 0;483 while (i < nSize)484 {485 unsigned int blk = min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));486 v.resize(i + blk);487 is.read((char*)&v[i], blk * sizeof(T));488 i += blk;489 }490}491492template<typename Stream, typename T, typename A>493void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)494{495 //unsigned int nSize = ReadCompactSize(is);496 //v.resize(nSize);497 //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)498 // Unserialize(is, (*vi), nType, nVersion);499500 v.clear();501 unsigned int nSize = ReadCompactSize(is);502 unsigned int i = 0;503 unsigned int nMid = 0;504 while (nMid < nSize)505 {506 nMid += 5000000 / sizeof(T);507 if (nMid > nSize)508 nMid = nSize;509 v.resize(nMid);510 for (; i < nMid; i++)511 Unserialize(is, v[i], nType, nVersion);512 }513}514515template<typename Stream, typename T, typename A>516inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)517{518 Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());519}520521522523//524// others derived from vector525//526inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)527{528 return GetSerializeSize((const vector<unsigned char>&)v, nType, nVersion);529}530531template<typename Stream>532void Serialize(Stream& os, const CScript& v, int nType, int nVersion)533{534 Serialize(os, (const vector<unsigned char>&)v, nType, nVersion);535}536537template<typename Stream>538void Unserialize(Stream& is, CScript& v, int nType, int nVersion)539{540 Unserialize(is, (vector<unsigned char>&)v, nType, nVersion);541}542543544545//546// pair547//548template<typename K, typename T>549unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)550{551 return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);552}553554template<typename Stream, typename K, typename T>555void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)556{557 Serialize(os, item.first, nType, nVersion);558 Serialize(os, item.second, nType, nVersion);559}560561template<typename Stream, typename K, typename T>562void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)563{564 Unserialize(is, item.first, nType, nVersion);565 Unserialize(is, item.second, nType, nVersion);566}567568569570//571// 3 tuple572//573template<typename T0, typename T1, typename T2>574unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)575{576 unsigned int nSize = 0;577 nSize += GetSerializeSize(get<0>(item), nType, nVersion);578 nSize += GetSerializeSize(get<1>(item), nType, nVersion);579 nSize += GetSerializeSize(get<2>(item), nType, nVersion);580 return nSize;581}582583template<typename Stream, typename T0, typename T1, typename T2>584void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)585{586 Serialize(os, get<0>(item), nType, nVersion);587 Serialize(os, get<1>(item), nType, nVersion);588 Serialize(os, get<2>(item), nType, nVersion);589}590591template<typename Stream, typename T0, typename T1, typename T2>592void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)593{594 Unserialize(is, get<0>(item), nType, nVersion);595 Unserialize(is, get<1>(item), nType, nVersion);596 Unserialize(is, get<2>(item), nType, nVersion);597}598599600601//602// 4 tuple603//604template<typename T0, typename T1, typename T2, typename T3>605unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)606{607 unsigned int nSize = 0;608 nSize += GetSerializeSize(get<0>(item), nType, nVersion);609 nSize += GetSerializeSize(get<1>(item), nType, nVersion);610 nSize += GetSerializeSize(get<2>(item), nType, nVersion);611 nSize += GetSerializeSize(get<3>(item), nType, nVersion);612 return nSize;613}614615template<typename Stream, typename T0, typename T1, typename T2, typename T3>616void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)617{618 Serialize(os, get<0>(item), nType, nVersion);619 Serialize(os, get<1>(item), nType, nVersion);620 Serialize(os, get<2>(item), nType, nVersion);621 Serialize(os, get<3>(item), nType, nVersion);622}623624template<typename Stream, typename T0, typename T1, typename T2, typename T3>625void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)626{627 Unserialize(is, get<0>(item), nType, nVersion);628 Unserialize(is, get<1>(item), nType, nVersion);629 Unserialize(is, get<2>(item), nType, nVersion);630 Unserialize(is, get<3>(item), nType, nVersion);631}632633634635//636// map637//638template<typename K, typename T, typename Pred, typename A>639unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)640{641 unsigned int nSize = GetSizeOfCompactSize(m.size());642 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)643 nSize += GetSerializeSize((*mi), nType, nVersion);644 return nSize;645}646647template<typename Stream, typename K, typename T, typename Pred, typename A>648void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)649{650 WriteCompactSize(os, m.size());651 for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)652 Serialize(os, (*mi), nType, nVersion);653}654655template<typename Stream, typename K, typename T, typename Pred, typename A>656void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)657{658 m.clear();659 unsigned int nSize = ReadCompactSize(is);660 typename std::map<K, T, Pred, A>::iterator mi = m.begin();661 for (unsigned int i = 0; i < nSize; i++)662 {663 pair<K, T> item;664 Unserialize(is, item, nType, nVersion);665 mi = m.insert(mi, item);666 }667}668669670671//672// set673//674template<typename K, typename Pred, typename A>675unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)676{677 unsigned int nSize = GetSizeOfCompactSize(m.size());678 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)679 nSize += GetSerializeSize((*it), nType, nVersion);680 return nSize;681}682683template<typename Stream, typename K, typename Pred, typename A>684void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)685{686 WriteCompactSize(os, m.size());687 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)688 Serialize(os, (*it), nType, nVersion);689}690691template<typename Stream, typename K, typename Pred, typename A>692void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)693{694 m.clear();695 unsigned int nSize = ReadCompactSize(is);696 typename std::set<K, Pred, A>::iterator it = m.begin();697 for (unsigned int i = 0; i < nSize; i++)698 {699 K key;700 Unserialize(is, key, nType, nVersion);701 it = m.insert(it, key);702 }703}704705706707//708// Support for IMPLEMENT_SERIALIZE and READWRITE macro709//710class CSerActionGetSerializeSize { };711class CSerActionSerialize { };712class CSerActionUnserialize { };713714template<typename Stream, typename T>715inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)716{717 return ::GetSerializeSize(obj, nType, nVersion);718}719720template<typename Stream, typename T>721inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)722{723 ::Serialize(s, obj, nType, nVersion);724 return 0;725}726727template<typename Stream, typename T>728inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)729{730 ::Unserialize(s, obj, nType, nVersion);731 return 0;732}733734struct ser_streamplaceholder735{736 int nType;737 int nVersion;738};739740741742743744745746747748//749// Allocator that clears its contents before deletion750//751template<typename T>752struct secure_allocator : public std::allocator<T>753{754 // MSVC8 default copy constructor is broken755 typedef std::allocator<T> base;756 typedef typename base::size_type size_type;757 typedef typename base::difference_type difference_type;758 typedef typename base::pointer pointer;759 typedef typename base::const_pointer const_pointer;760 typedef typename base::reference reference;761 typedef typename base::const_reference const_reference;762 typedef typename base::value_type value_type;763 secure_allocator() throw() {}764 secure_allocator(const secure_allocator& a) throw() : base(a) {}765 ~secure_allocator() throw() {}766 template<typename _Other> struct rebind767 { typedef secure_allocator<_Other> other; };768769 void deallocate(T* p, std::size_t n)770 {771 if (p != NULL)772 memset(p, 0, sizeof(T) * n);773 allocator<T>::deallocate(p, n);774 }775};776777778779//780// Double ended buffer combining vector and stream-like interfaces.781// >> and << read and write unformatted data using the above serialization templates.782// Fills with data in linear time; some stringstream implementations take N^2 time.783//784class CDataStream785{786protected:787 typedef vector<char, secure_allocator<char> > vector_type;788 vector_type vch;789 unsigned int nReadPos;790 short state;791 short exceptmask;792public:793 int nType;794 int nVersion;795796 typedef vector_type::allocator_type allocator_type;797 typedef vector_type::size_type size_type;798 typedef vector_type::difference_type difference_type;799 typedef vector_type::reference reference;800 typedef vector_type::const_reference const_reference;801 typedef vector_type::value_type value_type;802 typedef vector_type::iterator iterator;803 typedef vector_type::const_iterator const_iterator;804 typedef vector_type::reverse_iterator reverse_iterator;805806 explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)807 {808 Init(nTypeIn, nVersionIn);809 }810811 CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)812 {813 Init(nTypeIn, nVersionIn);814 }815816#if !defined(_MSC_VER) || _MSC_VER >= 1300817 CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)818 {819 Init(nTypeIn, nVersionIn);820 }821#endif822823 CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())824 {825 Init(nTypeIn, nVersionIn);826 }827828 CDataStream(const vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())829 {830 Init(nTypeIn, nVersionIn);831 }832833 CDataStream(const vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])834 {835 Init(nTypeIn, nVersionIn);836 }837838 void Init(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)839 {840 nReadPos = 0;841 nType = nTypeIn;842 nVersion = nVersionIn;843 state = 0;844 exceptmask = ios::badbit | ios::failbit;845 }846847 CDataStream& operator+=(const CDataStream& b)848 {849 vch.insert(vch.end(), b.begin(), b.end());850 return *this;851 }852853 friend CDataStream operator+(const CDataStream& a, const CDataStream& b)854 {855 CDataStream ret = a;856 ret += b;857 return (ret);858 }859860 string str() const861 {862 return (string(begin(), end()));863 }864865866 //867 // Vector subset868 //869 const_iterator begin() const { return vch.begin() + nReadPos; }870 iterator begin() { return vch.begin() + nReadPos; }871 const_iterator end() const { return vch.end(); }872 iterator end() { return vch.end(); }873 size_type size() const { return vch.size() - nReadPos; }874 bool empty() const { return vch.size() == nReadPos; }875 void resize(size_type n, value_type c=0) { vch.resize(n + nReadPos, c); }876 void reserve(size_type n) { vch.reserve(n + nReadPos); }877 const_reference operator[](size_type pos) const { return vch[pos + nReadPos]; }878 reference operator[](size_type pos) { return vch[pos + nReadPos]; }879 void clear() { vch.clear(); nReadPos = 0; }880 iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }881 void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }882883 void insert(iterator it, const_iterator first, const_iterator last)884 {885 if (it == vch.begin() + nReadPos && last - first <= nReadPos)886 {887 // special case for inserting at the front when there's room888 nReadPos -= (last - first);889 memcpy(&vch[nReadPos], &first[0], last - first);890 }891 else892 vch.insert(it, first, last);893 }894895 void insert(iterator it, vector<char>::const_iterator first, vector<char>::const_iterator last)896 {897 if (it == vch.begin() + nReadPos && last - first <= nReadPos)898 {899 // special case for inserting at the front when there's room900 nReadPos -= (last - first);901 memcpy(&vch[nReadPos], &first[0], last - first);902 }903 else904 vch.insert(it, first, last);905 }906907#if !defined(_MSC_VER) || _MSC_VER >= 1300908 void insert(iterator it, const char* first, const char* last)909 {910 if (it == vch.begin() + nReadPos && last - first <= nReadPos)911 {912 // special case for inserting at the front when there's room913 nReadPos -= (last - first);914 memcpy(&vch[nReadPos], &first[0], last - first);915 }916 else917 vch.insert(it, first, last);918 }919#endif920921 iterator erase(iterator it)922 {923 if (it == vch.begin() + nReadPos)924 {925 // special case for erasing from the front926 if (++nReadPos >= vch.size())927 {928 // whenever we reach the end, we take the opportunity to clear the buffer929 nReadPos = 0;930 return vch.erase(vch.begin(), vch.end());931 }932 return vch.begin() + nReadPos;933 }934 else935 return vch.erase(it);936 }937938 iterator erase(iterator first, iterator last)939 {940 if (first == vch.begin() + nReadPos)941 {942 // special case for erasing from the front943 if (last == vch.end())944 {945 nReadPos = 0;946 return vch.erase(vch.begin(), vch.end());947 }948 else949 {950 nReadPos = (last - vch.begin());951 return last;952 }953 }954 else955 return vch.erase(first, last);956 }957958 inline void Compact()959 {960 vch.erase(vch.begin(), vch.begin() + nReadPos);961 nReadPos = 0;962 }963964 bool Rewind(size_type n)965 {966 // Rewind by n characters if the buffer hasn't been compacted yet967 if (n > nReadPos)968 return false;969 nReadPos -= n;970 return true;971 }972973974 //975 // Stream subset976 //977 void setstate(short bits, const char* psz)978 {979 state |= bits;980 if (state & exceptmask)981 throw std::ios_base::failure(psz);982 }983984 bool eof() const { return size() == 0; }985 bool fail() const { return state & (ios::badbit | ios::failbit); }986 bool good() const { return !eof() && (state == 0); }987 void clear(short n) { state = n; } // name conflict with vector clear()988 short exceptions() { return exceptmask; }989 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }990 CDataStream* rdbuf() { return this; }991 int in_avail() { return size(); }992993 void SetType(int n) { nType = n; }994 int GetType() { return nType; }995 void SetVersion(int n) { nVersion = n; }996 int GetVersion() { return nVersion; }997 void ReadVersion() { *this >> nVersion; }998 void WriteVersion() { *this << nVersion; }9991000 CDataStream& read(char* pch, int nSize)1001 {1002 // Read from the beginning of the buffer1003 assert(nSize >= 0);1004 unsigned int nReadPosNext = nReadPos + nSize;1005 if (nReadPosNext >= vch.size())1006 {1007 if (nReadPosNext > vch.size())1008 {1009 setstate(ios::failbit, "CDataStream::read() : end of data");1010 memset(pch, 0, nSize);1011 nSize = vch.size() - nReadPos;1012 }1013 memcpy(pch, &vch[nReadPos], nSize);1014 nReadPos = 0;1015 vch.clear();1016 return (*this);1017 }1018 memcpy(pch, &vch[nReadPos], nSize);1019 nReadPos = nReadPosNext;1020 return (*this);1021 }10221023 CDataStream& ignore(int nSize)1024 {1025 // Ignore from the beginning of the buffer1026 assert(nSize >= 0);1027 unsigned int nReadPosNext = nReadPos + nSize;1028 if (nReadPosNext >= vch.size())1029 {1030 if (nReadPosNext > vch.size())1031 {1032 setstate(ios::failbit, "CDataStream::ignore() : end of data");1033 nSize = vch.size() - nReadPos;1034 }1035 nReadPos = 0;1036 vch.clear();1037 return (*this);1038 }1039 nReadPos = nReadPosNext;1040 return (*this);1041 }10421043 CDataStream& write(const char* pch, int nSize)1044 {1045 // Write to the end of the buffer1046 assert(nSize >= 0);1047 vch.insert(vch.end(), pch, pch + nSize);1048 return (*this);1049 }10501051 template<typename Stream>1052 void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const1053 {1054 // Special case: stream << stream concatenates like stream += stream1055 if (!vch.empty())1056 s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));1057 }10581059 template<typename T>1060 unsigned int GetSerializeSize(const T& obj)1061 {1062 // Tells the size of the object if serialized to this stream1063 return ::GetSerializeSize(obj, nType, nVersion);1064 }10651066 template<typename T>1067 CDataStream& operator<<(const T& obj)1068 {1069 // Serialize to this stream1070 ::Serialize(*this, obj, nType, nVersion);1071 return (*this);1072 }10731074 template<typename T>1075 CDataStream& operator>>(T& obj)1076 {1077 // Unserialize from this stream1078 ::Unserialize(*this, obj, nType, nVersion);1079 return (*this);1080 }1081};10821083#ifdef TESTCDATASTREAM1084// VC6sp61085// CDataStream:1086// n=1000 0 seconds1087// n=2000 0 seconds1088// n=4000 0 seconds1089// n=8000 0 seconds1090// n=16000 0 seconds1091// n=32000 0 seconds1092// n=64000 1 seconds1093// n=128000 1 seconds1094// n=256000 2 seconds1095// n=512000 4 seconds1096// n=1024000 8 seconds1097// n=2048000 16 seconds1098// n=4096000 32 seconds1099// stringstream:1100// n=1000 1 seconds1101// n=2000 1 seconds1102// n=4000 13 seconds1103// n=8000 87 seconds1104// n=16000 400 seconds1105// n=32000 1660 seconds1106// n=64000 6749 seconds1107// n=128000 27241 seconds1108// n=256000 109804 seconds1109#include <iostream>1110int main(int argc, char *argv[])1111{1112 vector<unsigned char> vch(0xcc, 250);1113 printf("CDataStream:\n");1114 for (int n = 1000; n <= 4500000; n *= 2)1115 {1116 CDataStream ss;1117 time_t nStart = time(NULL);1118 for (int i = 0; i < n; i++)1119 ss.write((char*)&vch[0], vch.size());1120 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);1121 }1122 printf("stringstream:\n");1123 for (int n = 1000; n <= 4500000; n *= 2)1124 {1125 stringstream ss;1126 time_t nStart = time(NULL);1127 for (int i = 0; i < n; i++)1128 ss.write((char*)&vch[0], vch.size());1129 printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);1130 }1131}1132#endif11331134113511361137113811391140114111421143//1144// Automatic closing wrapper for FILE*1145// - Will automatically close the file when it goes out of scope if not null.1146// - If you're returning the file pointer, return file.release().1147// - If you need to close the file early, use file.fclose() instead of fclose(file).1148//1149class CAutoFile1150{1151protected:1152 FILE* file;1153 short state;1154 short exceptmask;1155public:1156 int nType;1157 int nVersion;11581159 typedef FILE element_type;11601161 CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)1162 {1163 file = filenew;1164 nType = nTypeIn;1165 nVersion = nVersionIn;1166 state = 0;1167 exceptmask = ios::badbit | ios::failbit;1168 }11691170 ~CAutoFile()1171 {1172 fclose();1173 }11741175 void fclose()1176 {1177 if (file != NULL && file != stdin && file != stdout && file != stderr)1178 ::fclose(file);1179 file = NULL;1180 }11811182 FILE* release() { FILE* ret = file; file = NULL; return ret; }1183 operator FILE*() { return file; }1184 FILE* operator->() { return file; }1185 FILE& operator*() { return *file; }1186 FILE** operator&() { return &file; }1187 FILE* operator=(FILE* pnew) { return file = pnew; }1188 bool operator!() { return (file == NULL); }118911901191 //1192 // Stream subset1193 //1194 void setstate(short bits, const char* psz)1195 {1196 state |= bits;1197 if (state & exceptmask)1198 throw std::ios_base::failure(psz);1199 }12001201 bool fail() const { return state & (ios::badbit | ios::failbit); }1202 bool good() const { return state == 0; }1203 void clear(short n = 0) { state = n; }1204 short exceptions() { return exceptmask; }1205 short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }12061207 void SetType(int n) { nType = n; }1208 int GetType() { return nType; }1209 void SetVersion(int n) { nVersion = n; }1210 int GetVersion() { return nVersion; }1211 void ReadVersion() { *this >> nVersion; }1212 void WriteVersion() { *this << nVersion; }12131214 CAutoFile& read(char* pch, int nSize)1215 {1216 if (!file)1217 throw std::ios_base::failure("CAutoFile::read : file handle is NULL");1218 if (fread(pch, 1, nSize, file) != nSize)1219 setstate(ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");1220 return (*this);1221 }12221223 CAutoFile& write(const char* pch, int nSize)1224 {1225 if (!file)1226 throw std::ios_base::failure("CAutoFile::write : file handle is NULL");1227 if (fwrite(pch, 1, nSize, file) != nSize)1228 setstate(ios::failbit, "CAutoFile::write : write failed");1229 return (*this);1230 }12311232 template<typename T>1233 unsigned int GetSerializeSize(const T& obj)1234 {1235 // Tells the size of the object if serialized to this stream1236 return ::GetSerializeSize(obj, nType, nVersion);1237 }12381239 template<typename T>1240 CAutoFile& operator<<(const T& obj)1241 {1242 // Serialize to this stream1243 if (!file)1244 throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");1245 ::Serialize(*this, obj, nType, nVersion);1246 return (*this);1247 }12481249 template<typename T>1250 CAutoFile& operator>>(T& obj)1251 {1252 // Unserialize from this stream1253 if (!file)1254 throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");1255 ::Unserialize(*this, obj, nType, nVersion);1256 return (*this);1257 }1258};
Click a line number to link to it; use #L10-L20 for a range. "=" next to a version means the file is identical there.
