Back to home page

Bitcoin sources

 
 

    


0001 // Copyright (c) 2009-2010 Satoshi Nakamoto
0002 // Copyright (c) 2009-2012 The Bitcoin developers
0003 // Distributed under the MIT/X11 software license, see the accompanying
0004 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
0005 #ifndef BITCOIN_SERIALIZE_H
0006 #define BITCOIN_SERIALIZE_H
0007 
0008 #include <string>
0009 #include <vector>
0010 #include <map>
0011 #include <set>
0012 #include <cassert>
0013 #include <climits>
0014 #include <cstring>
0015 #include <cstdio>
0016 
0017 #include <boost/type_traits/is_fundamental.hpp>
0018 #include <boost/tuple/tuple.hpp>
0019 #include <boost/tuple/tuple_comparison.hpp>
0020 #include <boost/tuple/tuple_io.hpp>
0021 
0022 typedef long long  int64;
0023 typedef unsigned long long  uint64;
0024 
0025 #include <sys/mman.h>
0026 #include <limits.h>
0027 
0028 #include "knobs.h"
0029 
0030 /* This comes from limits.h if it's not defined there set a sane default */
0031 #ifndef PAGESIZE
0032 #include <unistd.h>
0033 #define PAGESIZE sysconf(_SC_PAGESIZE)
0034 #endif
0035 #define mlock(a,b) \
0036   mlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
0037   (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
0038 #define munlock(a,b) \
0039   munlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
0040   (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
0041 
0042 class CScript;
0043 class CDataStream;
0044 class CAutoFile;
0045 static const unsigned int MAX_SIZE = 0x02000000;
0046 
0047 extern int VERSION;
0048 
0049 // Used to bypass the rule against non-const reference to temporary
0050 // where it makes sense with wrappers such as CFlatData or CTxDB
0051 template<typename T>
0052 inline T& REF(const T& val)
0053 {
0054     return const_cast<T&>(val);
0055 }
0056 
0057 /////////////////////////////////////////////////////////////////
0058 //
0059 // Templates for serializing to anything that looks like a stream,
0060 // i.e. anything that supports .read(char*, int) and .write(char*, int)
0061 //
0062 
0063 enum
0064 {
0065     // primary actions
0066     SER_NETWORK         = (1 << 0),
0067     SER_DISK            = (1 << 1),
0068     SER_GETHASH         = (1 << 2),
0069 
0070     // modifiers
0071     SER_SKIPSIG         = (1 << 16),
0072     SER_BLOCKHEADERONLY = (1 << 17),
0073 };
0074 
0075 #define IMPLEMENT_SERIALIZE(statements)    \
0076     unsigned int GetSerializeSize(int nType=0, int nVersion=VERSION) const  \
0077     {                                           \
0078         CSerActionGetSerializeSize ser_action;  \
0079         const bool fGetSize = true;             \
0080         const bool fWrite = false;              \
0081         const bool fRead = false;               \
0082         unsigned int nSerSize = 0;              \
0083         ser_streamplaceholder s;                \
0084         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
0085         s.nType = nType;                        \
0086         s.nVersion = nVersion;                  \
0087         {statements}                            \
0088         return nSerSize;                        \
0089     }                                           \
0090     template<typename Stream>                   \
0091     void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const  \
0092     {                                           \
0093         CSerActionSerialize ser_action;         \
0094         const bool fGetSize = false;            \
0095         const bool fWrite = true;               \
0096         const bool fRead = false;               \
0097         unsigned int nSerSize = 0;              \
0098         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
0099         {statements}                            \
0100     }                                           \
0101     template<typename Stream>                   \
0102     void Unserialize(Stream& s, int nType=0, int nVersion=VERSION)  \
0103     {                                           \
0104         CSerActionUnserialize ser_action;       \
0105         const bool fGetSize = false;            \
0106         const bool fWrite = false;              \
0107         const bool fRead = true;                \
0108         unsigned int nSerSize = 0;              \
0109         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
0110         {statements}                            \
0111     }
0112 
0113 #define READWRITE(obj)      (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
0114 
0115 
0116 
0117 
0118 
0119 
0120 //
0121 // Basic types
0122 //
0123 #define WRITEDATA(s, obj)   s.write((char*)&(obj), sizeof(obj))
0124 #define READDATA(s, obj)    s.read((char*)&(obj), sizeof(obj))
0125 
0126 inline unsigned int GetSerializeSize(char a,           int, int=0) { return sizeof(a); }
0127 inline unsigned int GetSerializeSize(signed char a,    int, int=0) { return sizeof(a); }
0128 inline unsigned int GetSerializeSize(unsigned char a,  int, int=0) { return sizeof(a); }
0129 inline unsigned int GetSerializeSize(signed short a,   int, int=0) { return sizeof(a); }
0130 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
0131 inline unsigned int GetSerializeSize(signed int a,     int, int=0) { return sizeof(a); }
0132 inline unsigned int GetSerializeSize(unsigned int a,   int, int=0) { return sizeof(a); }
0133 inline unsigned int GetSerializeSize(signed long a,    int, int=0) { return sizeof(a); }
0134 inline unsigned int GetSerializeSize(unsigned long a,  int, int=0) { return sizeof(a); }
0135 inline unsigned int GetSerializeSize(int64 a,          int, int=0) { return sizeof(a); }
0136 inline unsigned int GetSerializeSize(uint64 a,         int, int=0) { return sizeof(a); }
0137 inline unsigned int GetSerializeSize(float a,          int, int=0) { return sizeof(a); }
0138 inline unsigned int GetSerializeSize(double a,         int, int=0) { return sizeof(a); }
0139 
0140 template<typename Stream> inline void Serialize(Stream& s, char a,           int, int=0) { WRITEDATA(s, a); }
0141 template<typename Stream> inline void Serialize(Stream& s, signed char a,    int, int=0) { WRITEDATA(s, a); }
0142 template<typename Stream> inline void Serialize(Stream& s, unsigned char a,  int, int=0) { WRITEDATA(s, a); }
0143 template<typename Stream> inline void Serialize(Stream& s, signed short a,   int, int=0) { WRITEDATA(s, a); }
0144 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
0145 template<typename Stream> inline void Serialize(Stream& s, signed int a,     int, int=0) { WRITEDATA(s, a); }
0146 template<typename Stream> inline void Serialize(Stream& s, unsigned int a,   int, int=0) { WRITEDATA(s, a); }
0147 template<typename Stream> inline void Serialize(Stream& s, signed long a,    int, int=0) { WRITEDATA(s, a); }
0148 template<typename Stream> inline void Serialize(Stream& s, unsigned long a,  int, int=0) { WRITEDATA(s, a); }
0149 template<typename Stream> inline void Serialize(Stream& s, int64 a,          int, int=0) { WRITEDATA(s, a); }
0150 template<typename Stream> inline void Serialize(Stream& s, uint64 a,         int, int=0) { WRITEDATA(s, a); }
0151 template<typename Stream> inline void Serialize(Stream& s, float a,          int, int=0) { WRITEDATA(s, a); }
0152 template<typename Stream> inline void Serialize(Stream& s, double a,         int, int=0) { WRITEDATA(s, a); }
0153 
0154 template<typename Stream> inline void Unserialize(Stream& s, char& a,           int, int=0) { READDATA(s, a); }
0155 template<typename Stream> inline void Unserialize(Stream& s, signed char& a,    int, int=0) { READDATA(s, a); }
0156 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a,  int, int=0) { READDATA(s, a); }
0157 template<typename Stream> inline void Unserialize(Stream& s, signed short& a,   int, int=0) { READDATA(s, a); }
0158 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
0159 template<typename Stream> inline void Unserialize(Stream& s, signed int& a,     int, int=0) { READDATA(s, a); }
0160 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a,   int, int=0) { READDATA(s, a); }
0161 template<typename Stream> inline void Unserialize(Stream& s, signed long& a,    int, int=0) { READDATA(s, a); }
0162 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a,  int, int=0) { READDATA(s, a); }
0163 template<typename Stream> inline void Unserialize(Stream& s, int64& a,          int, int=0) { READDATA(s, a); }
0164 template<typename Stream> inline void Unserialize(Stream& s, uint64& a,         int, int=0) { READDATA(s, a); }
0165 template<typename Stream> inline void Unserialize(Stream& s, float& a,          int, int=0) { READDATA(s, a); }
0166 template<typename Stream> inline void Unserialize(Stream& s, double& a,         int, int=0) { READDATA(s, a); }
0167 
0168 inline unsigned int GetSerializeSize(bool a, int, int=0)                          { return sizeof(char); }
0169 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0)    { char f=a; WRITEDATA(s, f); }
0170 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
0171 
0172 
0173 
0174 
0175 
0176 
0177 //
0178 // Compact size
0179 //  size <  253        -- 1 byte
0180 //  size <= USHRT_MAX  -- 3 bytes  (253 + 2 bytes)
0181 //  size <= UINT_MAX   -- 5 bytes  (254 + 4 bytes)
0182 //  size >  UINT_MAX   -- 9 bytes  (255 + 8 bytes)
0183 //
0184 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
0185 {
0186     if (nSize < 253)             return sizeof(unsigned char);
0187     else if (nSize <= USHRT_MAX) return sizeof(unsigned char) + sizeof(unsigned short);
0188     else if (nSize <= UINT_MAX)  return sizeof(unsigned char) + sizeof(unsigned int);
0189     else                         return sizeof(unsigned char) + sizeof(uint64);
0190 }
0191 
0192 template<typename Stream>
0193 void WriteCompactSize(Stream& os, uint64 nSize)
0194 {
0195     if (nSize < 253)
0196     {
0197         unsigned char chSize = nSize;
0198         WRITEDATA(os, chSize);
0199     }
0200     else if (nSize <= USHRT_MAX)
0201     {
0202         unsigned char chSize = 253;
0203         unsigned short xSize = nSize;
0204         WRITEDATA(os, chSize);
0205         WRITEDATA(os, xSize);
0206     }
0207     else if (nSize <= UINT_MAX)
0208     {
0209         unsigned char chSize = 254;
0210         unsigned int xSize = nSize;
0211         WRITEDATA(os, chSize);
0212         WRITEDATA(os, xSize);
0213     }
0214     else
0215     {
0216         unsigned char chSize = 255;
0217         uint64 xSize = nSize;
0218         WRITEDATA(os, chSize);
0219         WRITEDATA(os, xSize);
0220     }
0221     return;
0222 }
0223 
0224 template<typename Stream>
0225 uint64 ReadCompactSize(Stream& is)
0226 {
0227     unsigned char chSize;
0228     READDATA(is, chSize);
0229     uint64 nSizeRet = 0;
0230     if (chSize < 253)
0231     {
0232         nSizeRet = chSize;
0233     }
0234     else if (chSize == 253)
0235     {
0236         unsigned short xSize;
0237         READDATA(is, xSize);
0238         nSizeRet = xSize;
0239     }
0240     else if (chSize == 254)
0241     {
0242         unsigned int xSize;
0243         READDATA(is, xSize);
0244         nSizeRet = xSize;
0245     }
0246     else
0247     {
0248         uint64 xSize;
0249         READDATA(is, xSize);
0250         nSizeRet = xSize;
0251     }
0252     if (nSizeRet > (uint64)MAX_SIZE)
0253         throw std::ios_base::failure("ReadCompactSize() : size too large");
0254     return nSizeRet;
0255 }
0256 
0257 
0258 
0259 //
0260 // Wrapper for serializing arrays and POD
0261 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
0262 //
0263 #define FLATDATA(obj)   REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
0264 class CFlatData
0265 {
0266 protected:
0267     char* pbegin;
0268     char* pend;
0269 public:
0270     CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
0271     char* begin() { return pbegin; }
0272     const char* begin() const { return pbegin; }
0273     char* end() { return pend; }
0274     const char* end() const { return pend; }
0275 
0276     unsigned int GetSerializeSize(int, int=0) const
0277     {
0278         return pend - pbegin;
0279     }
0280 
0281     template<typename Stream>
0282     void Serialize(Stream& s, int, int=0) const
0283     {
0284         s.write(pbegin, pend - pbegin);
0285     }
0286 
0287     template<typename Stream>
0288     void Unserialize(Stream& s, int, int=0)
0289     {
0290         s.read(pbegin, pend - pbegin);
0291     }
0292 };
0293 
0294 
0295 
0296 //
0297 // string stored as a fixed length field
0298 //
0299 template<std::size_t LEN>
0300 class CFixedFieldString
0301 {
0302 protected:
0303     const std::string* pcstr;
0304     std::string* pstr;
0305 public:
0306     explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
0307     explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
0308 
0309     unsigned int GetSerializeSize(int, int=0) const
0310     {
0311         return LEN;
0312     }
0313 
0314     template<typename Stream>
0315     void Serialize(Stream& s, int, int=0) const
0316     {
0317         char pszBuf[LEN];
0318         strncpy(pszBuf, pcstr->c_str(), LEN);
0319         s.write(pszBuf, LEN);
0320     }
0321 
0322     template<typename Stream>
0323     void Unserialize(Stream& s, int, int=0)
0324     {
0325         if (pstr == NULL)
0326             throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
0327         char pszBuf[LEN+1];
0328         s.read(pszBuf, LEN);
0329         pszBuf[LEN] = '\0';
0330         *pstr = pszBuf;
0331     }
0332 };
0333 
0334 
0335 
0336 
0337 
0338 //
0339 // Forward declarations
0340 //
0341 
0342 // string
0343 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
0344 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
0345 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
0346 
0347 // vector
0348 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
0349 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
0350 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=VERSION);
0351 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
0352 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
0353 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=VERSION);
0354 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
0355 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
0356 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=VERSION);
0357 
0358 // others derived from vector
0359 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=VERSION);
0360 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=VERSION);
0361 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=VERSION);
0362 
0363 // pair
0364 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=VERSION);
0365 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=VERSION);
0366 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=VERSION);
0367 
0368 // 3 tuple
0369 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
0370 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
0371 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=VERSION);
0372 
0373 // 4 tuple
0374 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion=VERSION);
0375 template<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);
0376 template<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);
0377 
0378 // map
0379 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion=VERSION);
0380 template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion=VERSION);
0381 template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion=VERSION);
0382 
0383 // set
0384 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
0385 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
0386 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=VERSION);
0387 
0388 
0389 
0390 
0391 
0392 //
0393 // If none of the specialized versions above matched, default to calling member function.
0394 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
0395 // The compiler will only cast int to long if none of the other templates matched.
0396 // Thanks to Boost serialization for this idea.
0397 //
0398 template<typename T>
0399 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=VERSION)
0400 {
0401     return a.GetSerializeSize((int)nType, nVersion);
0402 }
0403 
0404 template<typename Stream, typename T>
0405 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=VERSION)
0406 {
0407     a.Serialize(os, (int)nType, nVersion);
0408 }
0409 
0410 template<typename Stream, typename T>
0411 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=VERSION)
0412 {
0413     a.Unserialize(is, (int)nType, nVersion);
0414 }
0415 
0416 
0417 
0418 
0419 
0420 //
0421 // string
0422 //
0423 template<typename C>
0424 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
0425 {
0426     return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
0427 }
0428 
0429 template<typename Stream, typename C>
0430 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
0431 {
0432     WriteCompactSize(os, str.size());
0433     if (!str.empty())
0434         os.write((char*)&str[0], str.size() * sizeof(str[0]));
0435 }
0436 
0437 template<typename Stream, typename C>
0438 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
0439 {
0440     unsigned int nSize = ReadCompactSize(is);
0441     str.resize(nSize);
0442     if (nSize != 0)
0443         is.read((char*)&str[0], nSize * sizeof(str[0]));
0444 }
0445 
0446 
0447 
0448 //
0449 // vector
0450 //
0451 template<typename T, typename A>
0452 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
0453 {
0454     return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
0455 }
0456 
0457 template<typename T, typename A>
0458 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
0459 {
0460     unsigned int nSize = GetSizeOfCompactSize(v.size());
0461     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
0462         nSize += GetSerializeSize((*vi), nType, nVersion);
0463     return nSize;
0464 }
0465 
0466 template<typename T, typename A>
0467 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
0468 {
0469     return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
0470 }
0471 
0472 
0473 template<typename Stream, typename T, typename A>
0474 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
0475 {
0476     WriteCompactSize(os, v.size());
0477     if (!v.empty())
0478         os.write((char*)&v[0], v.size() * sizeof(T));
0479 }
0480 
0481 template<typename Stream, typename T, typename A>
0482 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
0483 {
0484     WriteCompactSize(os, v.size());
0485     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
0486         ::Serialize(os, (*vi), nType, nVersion);
0487 }
0488 
0489 template<typename Stream, typename T, typename A>
0490 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
0491 {
0492     Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
0493 }
0494 
0495 
0496 template<typename Stream, typename T, typename A>
0497 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
0498 {
0499     //unsigned int nSize = ReadCompactSize(is);
0500     //v.resize(nSize);
0501     //is.read((char*)&v[0], nSize * sizeof(T));
0502 
0503     // Limit size per read so bogus size value won't cause out of memory
0504     v.clear();
0505     unsigned int nSize = ReadCompactSize(is);
0506     unsigned int i = 0;
0507     while (i < nSize)
0508     {
0509         unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
0510         v.resize(i + blk);
0511         is.read((char*)&v[i], blk * sizeof(T));
0512         i += blk;
0513     }
0514 }
0515 
0516 template<typename Stream, typename T, typename A>
0517 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
0518 {
0519     //unsigned int nSize = ReadCompactSize(is);
0520     //v.resize(nSize);
0521     //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
0522     //    Unserialize(is, (*vi), nType, nVersion);
0523 
0524     v.clear();
0525     unsigned int nSize = ReadCompactSize(is);
0526     unsigned int i = 0;
0527     unsigned int nMid = 0;
0528     while (nMid < nSize)
0529     {
0530         nMid += 5000000 / sizeof(T);
0531         if (nMid > nSize)
0532             nMid = nSize;
0533         v.resize(nMid);
0534         for (; i < nMid; i++)
0535             Unserialize(is, v[i], nType, nVersion);
0536     }
0537 }
0538 
0539 template<typename Stream, typename T, typename A>
0540 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
0541 {
0542     Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
0543 }
0544 
0545 
0546 
0547 //
0548 // others derived from vector
0549 //
0550 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
0551 {
0552     return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
0553 }
0554 
0555 template<typename Stream>
0556 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
0557 {
0558     Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
0559 }
0560 
0561 template<typename Stream>
0562 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
0563 {
0564     Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
0565 }
0566 
0567 
0568 
0569 //
0570 // pair
0571 //
0572 template<typename K, typename T>
0573 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
0574 {
0575     return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
0576 }
0577 
0578 template<typename Stream, typename K, typename T>
0579 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
0580 {
0581     Serialize(os, item.first, nType, nVersion);
0582     Serialize(os, item.second, nType, nVersion);
0583 }
0584 
0585 template<typename Stream, typename K, typename T>
0586 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
0587 {
0588     Unserialize(is, item.first, nType, nVersion);
0589     Unserialize(is, item.second, nType, nVersion);
0590 }
0591 
0592 
0593 
0594 //
0595 // 3 tuple
0596 //
0597 template<typename T0, typename T1, typename T2>
0598 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
0599 {
0600     unsigned int nSize = 0;
0601     nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
0602     nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
0603     nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
0604     return nSize;
0605 }
0606 
0607 template<typename Stream, typename T0, typename T1, typename T2>
0608 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
0609 {
0610     Serialize(os, boost::get<0>(item), nType, nVersion);
0611     Serialize(os, boost::get<1>(item), nType, nVersion);
0612     Serialize(os, boost::get<2>(item), nType, nVersion);
0613 }
0614 
0615 template<typename Stream, typename T0, typename T1, typename T2>
0616 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
0617 {
0618     Unserialize(is, boost::get<0>(item), nType, nVersion);
0619     Unserialize(is, boost::get<1>(item), nType, nVersion);
0620     Unserialize(is, boost::get<2>(item), nType, nVersion);
0621 }
0622 
0623 
0624 
0625 //
0626 // 4 tuple
0627 //
0628 template<typename T0, typename T1, typename T2, typename T3>
0629 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
0630 {
0631     unsigned int nSize = 0;
0632     nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
0633     nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
0634     nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
0635     nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
0636     return nSize;
0637 }
0638 
0639 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
0640 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
0641 {
0642     Serialize(os, boost::get<0>(item), nType, nVersion);
0643     Serialize(os, boost::get<1>(item), nType, nVersion);
0644     Serialize(os, boost::get<2>(item), nType, nVersion);
0645     Serialize(os, boost::get<3>(item), nType, nVersion);
0646 }
0647 
0648 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
0649 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
0650 {
0651     Unserialize(is, boost::get<0>(item), nType, nVersion);
0652     Unserialize(is, boost::get<1>(item), nType, nVersion);
0653     Unserialize(is, boost::get<2>(item), nType, nVersion);
0654     Unserialize(is, boost::get<3>(item), nType, nVersion);
0655 }
0656 
0657 
0658 
0659 //
0660 // map
0661 //
0662 template<typename K, typename T, typename Pred, typename A>
0663 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
0664 {
0665     unsigned int nSize = GetSizeOfCompactSize(m.size());
0666     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
0667         nSize += GetSerializeSize((*mi), nType, nVersion);
0668     return nSize;
0669 }
0670 
0671 template<typename Stream, typename K, typename T, typename Pred, typename A>
0672 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
0673 {
0674     WriteCompactSize(os, m.size());
0675     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
0676         Serialize(os, (*mi), nType, nVersion);
0677 }
0678 
0679 template<typename Stream, typename K, typename T, typename Pred, typename A>
0680 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
0681 {
0682     m.clear();
0683     unsigned int nSize = ReadCompactSize(is);
0684     typename std::map<K, T, Pred, A>::iterator mi = m.begin();
0685     for (unsigned int i = 0; i < nSize; i++)
0686     {
0687         std::pair<K, T> item;
0688         Unserialize(is, item, nType, nVersion);
0689         mi = m.insert(mi, item);
0690     }
0691 }
0692 
0693 
0694 
0695 //
0696 // set
0697 //
0698 template<typename K, typename Pred, typename A>
0699 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
0700 {
0701     unsigned int nSize = GetSizeOfCompactSize(m.size());
0702     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
0703         nSize += GetSerializeSize((*it), nType, nVersion);
0704     return nSize;
0705 }
0706 
0707 template<typename Stream, typename K, typename Pred, typename A>
0708 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
0709 {
0710     WriteCompactSize(os, m.size());
0711     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
0712         Serialize(os, (*it), nType, nVersion);
0713 }
0714 
0715 template<typename Stream, typename K, typename Pred, typename A>
0716 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
0717 {
0718     m.clear();
0719     unsigned int nSize = ReadCompactSize(is);
0720     typename std::set<K, Pred, A>::iterator it = m.begin();
0721     for (unsigned int i = 0; i < nSize; i++)
0722     {
0723         K key;
0724         Unserialize(is, key, nType, nVersion);
0725         it = m.insert(it, key);
0726     }
0727 }
0728 
0729 
0730 
0731 //
0732 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
0733 //
0734 class CSerActionGetSerializeSize { };
0735 class CSerActionSerialize { };
0736 class CSerActionUnserialize { };
0737 
0738 template<typename Stream, typename T>
0739 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
0740 {
0741     return ::GetSerializeSize(obj, nType, nVersion);
0742 }
0743 
0744 template<typename Stream, typename T>
0745 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
0746 {
0747     ::Serialize(s, obj, nType, nVersion);
0748     return 0;
0749 }
0750 
0751 template<typename Stream, typename T>
0752 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
0753 {
0754     ::Unserialize(s, obj, nType, nVersion);
0755     return 0;
0756 }
0757 
0758 struct ser_streamplaceholder
0759 {
0760     int nType;
0761     int nVersion;
0762 };
0763 
0764 
0765 
0766 
0767 
0768 
0769 
0770 
0771 
0772 //
0773 // Allocator that locks its contents from being paged
0774 // out of memory and clears its contents before deletion.
0775 //
0776 template<typename T>
0777 struct secure_allocator : public std::allocator<T>
0778 {
0779     // MSVC8 default copy constructor is broken
0780     typedef std::allocator<T> base;
0781     typedef typename base::size_type size_type;
0782     typedef typename base::difference_type  difference_type;
0783     typedef typename base::pointer pointer;
0784     typedef typename base::const_pointer const_pointer;
0785     typedef typename base::reference reference;
0786     typedef typename base::const_reference const_reference;
0787     typedef typename base::value_type value_type;
0788     secure_allocator() throw() {}
0789     secure_allocator(const secure_allocator& a) throw() : base(a) {}
0790     template <typename U>
0791     secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
0792     ~secure_allocator() throw() {}
0793     template<typename _Other> struct rebind
0794     { typedef secure_allocator<_Other> other; };
0795 
0796     T* allocate(std::size_t n, const void *hint = 0)
0797     {
0798         T *p;
0799         p = std::allocator<T>::allocate(n, hint);
0800         if (p != NULL)
0801             mlock(p, sizeof(T) * n);
0802         return p;
0803     }
0804 
0805     void deallocate(T* p, std::size_t n)
0806     {
0807         if (p != NULL)
0808         {
0809             memset(p, 0, sizeof(T) * n);
0810             munlock(p, sizeof(T) * n);
0811         }
0812         std::allocator<T>::deallocate(p, n);
0813     }
0814 };
0815 
0816 
0817 //
0818 // Allocator that clears its contents before deletion.
0819 //
0820 template<typename T>
0821 struct zero_after_free_allocator : public std::allocator<T>
0822 {
0823     // MSVC8 default copy constructor is broken
0824     typedef std::allocator<T> base;
0825     typedef typename base::size_type size_type;
0826     typedef typename base::difference_type  difference_type;
0827     typedef typename base::pointer pointer;
0828     typedef typename base::const_pointer const_pointer;
0829     typedef typename base::reference reference;
0830     typedef typename base::const_reference const_reference;
0831     typedef typename base::value_type value_type;
0832     zero_after_free_allocator() throw() {}
0833     zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
0834     template <typename U>
0835     zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a) {}
0836     ~zero_after_free_allocator() throw() {}
0837     template<typename _Other> struct rebind
0838     { typedef zero_after_free_allocator<_Other> other; };
0839 
0840     void deallocate(T* p, std::size_t n)
0841     {
0842         if (p != NULL)
0843             memset(p, 0, sizeof(T) * n);
0844         std::allocator<T>::deallocate(p, n);
0845     }
0846 };
0847 
0848 
0849 
0850 //
0851 // Double ended buffer combining vector and stream-like interfaces.
0852 // >> and << read and write unformatted data using the above serialization templates.
0853 // Fills with data in linear time; some stringstream implementations take N^2 time.
0854 //
0855 class CDataStream
0856 {
0857 protected:
0858     typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
0859     vector_type vch;
0860     unsigned int nReadPos;
0861     short state;
0862     short exceptmask;
0863 public:
0864     int nType;
0865     int nVersion;
0866 
0867     typedef vector_type::allocator_type   allocator_type;
0868     typedef vector_type::size_type        size_type;
0869     typedef vector_type::difference_type  difference_type;
0870     typedef vector_type::reference        reference;
0871     typedef vector_type::const_reference  const_reference;
0872     typedef vector_type::value_type       value_type;
0873     typedef vector_type::iterator         iterator;
0874     typedef vector_type::const_iterator   const_iterator;
0875     typedef vector_type::reverse_iterator reverse_iterator;
0876 
0877     explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
0878     {
0879         Init(nTypeIn, nVersionIn);
0880     }
0881 
0882     CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
0883     {
0884         Init(nTypeIn, nVersionIn);
0885     }
0886 
0887     CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(pbegin, pend)
0888     {
0889         Init(nTypeIn, nVersionIn);
0890     }
0891 
0892     CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
0893     {
0894         Init(nTypeIn, nVersionIn);
0895     }
0896 
0897     CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch(vchIn.begin(), vchIn.end())
0898     {
0899         Init(nTypeIn, nVersionIn);
0900     }
0901 
0902     CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
0903     {
0904         Init(nTypeIn, nVersionIn);
0905     }
0906 
0907     void Init(int nTypeIn=SER_NETWORK, int nVersionIn=VERSION)
0908     {
0909         nReadPos = 0;
0910         nType = nTypeIn;
0911         nVersion = nVersionIn;
0912         state = 0;
0913         exceptmask = std::ios::badbit | std::ios::failbit;
0914     }
0915 
0916     CDataStream& operator+=(const CDataStream& b)
0917     {
0918         vch.insert(vch.end(), b.begin(), b.end());
0919         return *this;
0920     }
0921 
0922     friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
0923     {
0924         CDataStream ret = a;
0925         ret += b;
0926         return (ret);
0927     }
0928 
0929     std::string str() const
0930     {
0931         return (std::string(begin(), end()));
0932     }
0933 
0934 
0935     //
0936     // Vector subset
0937     //
0938     const_iterator begin() const                     { return vch.begin() + nReadPos; }
0939     iterator begin()                                 { return vch.begin() + nReadPos; }
0940     const_iterator end() const                       { return vch.end(); }
0941     iterator end()                                   { return vch.end(); }
0942     size_type size() const                           { return vch.size() - nReadPos; }
0943     bool empty() const                               { return vch.size() == nReadPos; }
0944     void resize(size_type n, value_type c=0)         { vch.resize(n + nReadPos, c); }
0945     void reserve(size_type n)                        { vch.reserve(n + nReadPos); }
0946     const_reference operator[](size_type pos) const  { return vch[pos + nReadPos]; }
0947     reference operator[](size_type pos)              { return vch[pos + nReadPos]; }
0948     void clear()                                     { vch.clear(); nReadPos = 0; }
0949     iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
0950     void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
0951 
0952     void insert(iterator it, const_iterator first, const_iterator last)
0953     {
0954         if (it == vch.begin() + nReadPos && last - first <= nReadPos)
0955         {
0956             // special case for inserting at the front when there's room
0957             nReadPos -= (last - first);
0958             memcpy(&vch[nReadPos], &first[0], last - first);
0959         }
0960         else
0961             vch.insert(it, first, last);
0962     }
0963 
0964     void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
0965     {
0966         if (it == vch.begin() + nReadPos && last - first <= nReadPos)
0967         {
0968             // special case for inserting at the front when there's room
0969             nReadPos -= (last - first);
0970             memcpy(&vch[nReadPos], &first[0], last - first);
0971         }
0972         else
0973             vch.insert(it, first, last);
0974     }
0975 
0976     void insert(iterator it, const char* first, const char* last)
0977     {
0978         if (it == vch.begin() + nReadPos && last - first <= nReadPos)
0979         {
0980             // special case for inserting at the front when there's room
0981             nReadPos -= (last - first);
0982             memcpy(&vch[nReadPos], &first[0], last - first);
0983         }
0984         else
0985             vch.insert(it, first, last);
0986     }
0987 
0988     iterator erase(iterator it)
0989     {
0990         if (it == vch.begin() + nReadPos)
0991         {
0992             // special case for erasing from the front
0993             if (++nReadPos >= vch.size())
0994             {
0995                 // whenever we reach the end, we take the opportunity to clear the buffer
0996                 nReadPos = 0;
0997                 return vch.erase(vch.begin(), vch.end());
0998             }
0999             return vch.begin() + nReadPos;
1000         }
1001         else
1002             return vch.erase(it);
1003     }
1004 
1005     iterator erase(iterator first, iterator last)
1006     {
1007         if (first == vch.begin() + nReadPos)
1008         {
1009             // special case for erasing from the front
1010             if (last == vch.end())
1011             {
1012                 nReadPos = 0;
1013                 return vch.erase(vch.begin(), vch.end());
1014             }
1015             else
1016             {
1017                 nReadPos = (last - vch.begin());
1018                 return last;
1019             }
1020         }
1021         else
1022             return vch.erase(first, last);
1023     }
1024 
1025     inline void Compact()
1026     {
1027         vch.erase(vch.begin(), vch.begin() + nReadPos);
1028         nReadPos = 0;
1029     }
1030 
1031     bool Rewind(size_type n)
1032     {
1033         // Rewind by n characters if the buffer hasn't been compacted yet
1034         if (n > nReadPos)
1035             return false;
1036         nReadPos -= n;
1037         return true;
1038     }
1039 
1040 
1041     //
1042     // Stream subset
1043     //
1044     void setstate(short bits, const char* psz)
1045     {
1046         state |= bits;
1047         if (state & exceptmask)
1048             throw std::ios_base::failure(psz);
1049     }
1050 
1051     bool eof() const             { return size() == 0; }
1052     bool fail() const            { return state & (std::ios::badbit | std::ios::failbit); }
1053     bool good() const            { return !eof() && (state == 0); }
1054     void clear(short n)          { state = n; }  // name conflict with vector clear()
1055     short exceptions()           { return exceptmask; }
1056     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1057     CDataStream* rdbuf()         { return this; }
1058     int in_avail()               { return size(); }
1059 
1060     void SetType(int n)          { nType = n; }
1061     int GetType()                { return nType; }
1062     void SetVersion(int n)       { nVersion = n; }
1063     int GetVersion()             { return nVersion; }
1064     void ReadVersion()           { *this >> nVersion; }
1065     void WriteVersion()          { *this << nVersion; }
1066 
1067     CDataStream& read(char* pch, int nSize)
1068     {
1069         // Read from the beginning of the buffer
1070         assert(nSize >= 0);
1071         unsigned int nReadPosNext = nReadPos + nSize;
1072         if (nReadPosNext >= vch.size())
1073         {
1074             if (nReadPosNext > vch.size())
1075             {
1076                 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1077                 memset(pch, 0, nSize);
1078                 nSize = vch.size() - nReadPos;
1079             }
1080             memcpy(pch, &vch[nReadPos], nSize);
1081             nReadPos = 0;
1082             vch.clear();
1083             return (*this);
1084         }
1085         memcpy(pch, &vch[nReadPos], nSize);
1086         nReadPos = nReadPosNext;
1087         return (*this);
1088     }
1089 
1090     CDataStream& ignore(int nSize)
1091     {
1092         // Ignore from the beginning of the buffer
1093         assert(nSize >= 0);
1094         unsigned int nReadPosNext = nReadPos + nSize;
1095         if (nReadPosNext >= vch.size())
1096         {
1097             if (nReadPosNext > vch.size())
1098             {
1099                 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1100                 nSize = vch.size() - nReadPos;
1101             }
1102             nReadPos = 0;
1103             vch.clear();
1104             return (*this);
1105         }
1106         nReadPos = nReadPosNext;
1107         return (*this);
1108     }
1109 
1110     CDataStream& write(const char* pch, int nSize)
1111     {
1112         // Write to the end of the buffer
1113         assert(nSize >= 0);
1114         vch.insert(vch.end(), pch, pch + nSize);
1115         return (*this);
1116     }
1117 
1118     template<typename Stream>
1119     void Serialize(Stream& s, int nType=0, int nVersion=VERSION) const
1120     {
1121         // Special case: stream << stream concatenates like stream += stream
1122         if (!vch.empty())
1123             s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1124     }
1125 
1126     template<typename T>
1127     unsigned int GetSerializeSize(const T& obj)
1128     {
1129         // Tells the size of the object if serialized to this stream
1130         return ::GetSerializeSize(obj, nType, nVersion);
1131     }
1132 
1133     template<typename T>
1134     CDataStream& operator<<(const T& obj)
1135     {
1136         // Serialize to this stream
1137         ::Serialize(*this, obj, nType, nVersion);
1138         return (*this);
1139     }
1140 
1141     template<typename T>
1142     CDataStream& operator>>(T& obj)
1143     {
1144         // Unserialize from this stream
1145         ::Unserialize(*this, obj, nType, nVersion);
1146         return (*this);
1147     }
1148 };
1149 
1150 #ifdef TESTCDATASTREAM
1151 // VC6sp6
1152 // CDataStream:
1153 // n=1000       0 seconds
1154 // n=2000       0 seconds
1155 // n=4000       0 seconds
1156 // n=8000       0 seconds
1157 // n=16000      0 seconds
1158 // n=32000      0 seconds
1159 // n=64000      1 seconds
1160 // n=128000     1 seconds
1161 // n=256000     2 seconds
1162 // n=512000     4 seconds
1163 // n=1024000    8 seconds
1164 // n=2048000    16 seconds
1165 // n=4096000    32 seconds
1166 // stringstream:
1167 // n=1000       1 seconds
1168 // n=2000       1 seconds
1169 // n=4000       13 seconds
1170 // n=8000       87 seconds
1171 // n=16000      400 seconds
1172 // n=32000      1660 seconds
1173 // n=64000      6749 seconds
1174 // n=128000     27241 seconds
1175 // n=256000     109804 seconds
1176 #include <iostream>
1177 int main(int argc, char *argv[])
1178 {
1179     vector<unsigned char> vch(0xcc, 250);
1180     printf("CDataStream:\n");
1181     for (int n = 1000; n <= 4500000; n *= 2)
1182     {
1183         CDataStream ss;
1184         time_t nStart = time(NULL);
1185         for (int i = 0; i < n; i++)
1186             ss.write((char*)&vch[0], vch.size());
1187         printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1188     }
1189     printf("stringstream:\n");
1190     for (int n = 1000; n <= 4500000; n *= 2)
1191     {
1192         stringstream ss;
1193         time_t nStart = time(NULL);
1194         for (int i = 0; i < n; i++)
1195             ss.write((char*)&vch[0], vch.size());
1196         printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1197     }
1198 }
1199 #endif
1200 
1201 
1202 
1203 
1204 
1205 
1206 
1207 
1208 
1209 
1210 //
1211 // Automatic closing wrapper for FILE*
1212 //  - Will automatically close the file when it goes out of scope if not null.
1213 //  - If you're returning the file pointer, return file.release().
1214 //  - If you need to close the file early, use file.fclose() instead of fclose(file).
1215 //
1216 class CAutoFile
1217 {
1218 protected:
1219     FILE* file;
1220     short state;
1221     short exceptmask;
1222 public:
1223     int nType;
1224     int nVersion;
1225 
1226     typedef FILE element_type;
1227 
1228     CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=VERSION)
1229     {
1230         file = filenew;
1231         nType = nTypeIn;
1232         nVersion = nVersionIn;
1233         state = 0;
1234         exceptmask = std::ios::badbit | std::ios::failbit;
1235     }
1236 
1237     ~CAutoFile()
1238     {
1239         fclose();
1240     }
1241 
1242     void fclose()
1243     {
1244         if (file != NULL && file != stdin && file != stdout && file != stderr)
1245             ::fclose(file);
1246         file = NULL;
1247     }
1248 
1249     FILE* release()             { FILE* ret = file; file = NULL; return ret; }
1250     operator FILE*()            { return file; }
1251     FILE* operator->()          { return file; }
1252     FILE& operator*()           { return *file; }
1253     FILE** operator&()          { return &file; }
1254     FILE* operator=(FILE* pnew) { return file = pnew; }
1255     bool operator!()            { return (file == NULL); }
1256 
1257 
1258     //
1259     // Stream subset
1260     //
1261     void setstate(short bits, const char* psz)
1262     {
1263         state |= bits;
1264         if (state & exceptmask)
1265             throw std::ios_base::failure(psz);
1266     }
1267 
1268     bool fail() const            { return state & (std::ios::badbit | std::ios::failbit); }
1269     bool good() const            { return state == 0; }
1270     void clear(short n = 0)      { state = n; }
1271     short exceptions()           { return exceptmask; }
1272     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1273 
1274     void SetType(int n)          { nType = n; }
1275     int GetType()                { return nType; }
1276     void SetVersion(int n)       { nVersion = n; }
1277     int GetVersion()             { return nVersion; }
1278     void ReadVersion()           { *this >> nVersion; }
1279     void WriteVersion()          { *this << nVersion; }
1280 
1281     CAutoFile& read(char* pch, int nSize)
1282     {
1283         if (!file)
1284             throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1285         if (fread(pch, 1, nSize, file) != nSize)
1286             setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1287         return (*this);
1288     }
1289 
1290     CAutoFile& write(const char* pch, int nSize)
1291     {
1292         if (!file)
1293             throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1294         if (fwrite(pch, 1, nSize, file) != nSize)
1295             setstate(std::ios::failbit, "CAutoFile::write : write failed");
1296         return (*this);
1297     }
1298 
1299     template<typename T>
1300     unsigned int GetSerializeSize(const T& obj)
1301     {
1302         // Tells the size of the object if serialized to this stream
1303         return ::GetSerializeSize(obj, nType, nVersion);
1304     }
1305 
1306     template<typename T>
1307     CAutoFile& operator<<(const T& obj)
1308     {
1309         // Serialize to this stream
1310         if (!file)
1311             throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1312         ::Serialize(*this, obj, nType, nVersion);
1313         return (*this);
1314     }
1315 
1316     template<typename T>
1317     CAutoFile& operator>>(T& obj)
1318     {
1319         // Unserialize from this stream
1320         if (!file)
1321             throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1322         ::Unserialize(*this, obj, nType, nVersion);
1323         return (*this);
1324     }
1325 };
1326 
1327 #endif