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