Update all copyrights to 2012
[novacoin.git] / src / serialize.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2012 The Bitcoin developers
3 // Distributed under the MIT/X11 software license, see the accompanying
4 // file license.txt or http://www.opensource.org/licenses/mit-license.php.
5 #ifndef BITCOIN_SERIALIZE_H
6 #define BITCOIN_SERIALIZE_H
7
8 #include <string>
9 #include <vector>
10 #include <map>
11 #include <set>
12 #include <cassert>
13 #include <limits>
14 #include <cstring>
15 #include <cstdio>
16
17 #include <boost/type_traits/is_fundamental.hpp>
18 #include <boost/tuple/tuple.hpp>
19 #include <boost/tuple/tuple_comparison.hpp>
20 #include <boost/tuple/tuple_io.hpp>
21
22 typedef long long  int64;
23 typedef unsigned long long  uint64;
24
25 #ifdef WIN32
26 #include <windows.h>
27 // This is used to attempt to keep keying material out of swap
28 // Note that VirtualLock does not provide this as a guarantee on Windows,
29 // but, in practice, memory that has been VirtualLock'd almost never gets written to
30 // the pagefile except in rare circumstances where memory is extremely low.
31 #include <windows.h>
32 #define mlock(p, n) VirtualLock((p), (n));
33 #define munlock(p, n) VirtualUnlock((p), (n));
34 #else
35 #include <sys/mman.h>
36 #include <limits.h>
37 /* This comes from limits.h if it's not defined there set a sane default */
38 #ifndef PAGESIZE
39 #include <unistd.h>
40 #define PAGESIZE sysconf(_SC_PAGESIZE)
41 #endif
42 #define mlock(a,b) \
43   mlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
44   (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
45 #define munlock(a,b) \
46   munlock(((void *)(((size_t)(a)) & (~((PAGESIZE)-1)))),\
47   (((((size_t)(a)) + (b) - 1) | ((PAGESIZE) - 1)) + 1) - (((size_t)(a)) & (~((PAGESIZE) - 1))))
48 #endif
49
50 class CScript;
51 class CDataStream;
52 class CAutoFile;
53 static const unsigned int MAX_SIZE = 0x02000000;
54
55 static const int PROTOCOL_VERSION = 60000;
56
57 // Used to bypass the rule against non-const reference to temporary
58 // where it makes sense with wrappers such as CFlatData or CTxDB
59 template<typename T>
60 inline T& REF(const T& val)
61 {
62     return const_cast<T&>(val);
63 }
64
65 /////////////////////////////////////////////////////////////////
66 //
67 // Templates for serializing to anything that looks like a stream,
68 // i.e. anything that supports .read(char*, int) and .write(char*, int)
69 //
70
71 enum
72 {
73     // primary actions
74     SER_NETWORK         = (1 << 0),
75     SER_DISK            = (1 << 1),
76     SER_GETHASH         = (1 << 2),
77
78     // modifiers
79     SER_SKIPSIG         = (1 << 16),
80     SER_BLOCKHEADERONLY = (1 << 17),
81 };
82
83 #define IMPLEMENT_SERIALIZE(statements)    \
84     unsigned int GetSerializeSize(int nType=0, int nVersion=PROTOCOL_VERSION) const  \
85     {                                           \
86         CSerActionGetSerializeSize ser_action;  \
87         const bool fGetSize = true;             \
88         const bool fWrite = false;              \
89         const bool fRead = false;               \
90         unsigned int nSerSize = 0;              \
91         ser_streamplaceholder s;                \
92         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
93         s.nType = nType;                        \
94         s.nVersion = nVersion;                  \
95         {statements}                            \
96         return nSerSize;                        \
97     }                                           \
98     template<typename Stream>                   \
99     void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const  \
100     {                                           \
101         CSerActionSerialize ser_action;         \
102         const bool fGetSize = false;            \
103         const bool fWrite = true;               \
104         const bool fRead = false;               \
105         unsigned int nSerSize = 0;              \
106         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
107         {statements}                            \
108     }                                           \
109     template<typename Stream>                   \
110     void Unserialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION)  \
111     {                                           \
112         CSerActionUnserialize ser_action;       \
113         const bool fGetSize = false;            \
114         const bool fWrite = false;              \
115         const bool fRead = true;                \
116         unsigned int nSerSize = 0;              \
117         assert(fGetSize||fWrite||fRead); /* suppress warning */ \
118         {statements}                            \
119     }
120
121 #define READWRITE(obj)      (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action))
122
123
124
125
126
127
128 //
129 // Basic types
130 //
131 #define WRITEDATA(s, obj)   s.write((char*)&(obj), sizeof(obj))
132 #define READDATA(s, obj)    s.read((char*)&(obj), sizeof(obj))
133
134 inline unsigned int GetSerializeSize(char a,           int, int=0) { return sizeof(a); }
135 inline unsigned int GetSerializeSize(signed char a,    int, int=0) { return sizeof(a); }
136 inline unsigned int GetSerializeSize(unsigned char a,  int, int=0) { return sizeof(a); }
137 inline unsigned int GetSerializeSize(signed short a,   int, int=0) { return sizeof(a); }
138 inline unsigned int GetSerializeSize(unsigned short a, int, int=0) { return sizeof(a); }
139 inline unsigned int GetSerializeSize(signed int a,     int, int=0) { return sizeof(a); }
140 inline unsigned int GetSerializeSize(unsigned int a,   int, int=0) { return sizeof(a); }
141 inline unsigned int GetSerializeSize(signed long a,    int, int=0) { return sizeof(a); }
142 inline unsigned int GetSerializeSize(unsigned long a,  int, int=0) { return sizeof(a); }
143 inline unsigned int GetSerializeSize(int64 a,          int, int=0) { return sizeof(a); }
144 inline unsigned int GetSerializeSize(uint64 a,         int, int=0) { return sizeof(a); }
145 inline unsigned int GetSerializeSize(float a,          int, int=0) { return sizeof(a); }
146 inline unsigned int GetSerializeSize(double a,         int, int=0) { return sizeof(a); }
147
148 template<typename Stream> inline void Serialize(Stream& s, char a,           int, int=0) { WRITEDATA(s, a); }
149 template<typename Stream> inline void Serialize(Stream& s, signed char a,    int, int=0) { WRITEDATA(s, a); }
150 template<typename Stream> inline void Serialize(Stream& s, unsigned char a,  int, int=0) { WRITEDATA(s, a); }
151 template<typename Stream> inline void Serialize(Stream& s, signed short a,   int, int=0) { WRITEDATA(s, a); }
152 template<typename Stream> inline void Serialize(Stream& s, unsigned short a, int, int=0) { WRITEDATA(s, a); }
153 template<typename Stream> inline void Serialize(Stream& s, signed int a,     int, int=0) { WRITEDATA(s, a); }
154 template<typename Stream> inline void Serialize(Stream& s, unsigned int a,   int, int=0) { WRITEDATA(s, a); }
155 template<typename Stream> inline void Serialize(Stream& s, signed long a,    int, int=0) { WRITEDATA(s, a); }
156 template<typename Stream> inline void Serialize(Stream& s, unsigned long a,  int, int=0) { WRITEDATA(s, a); }
157 template<typename Stream> inline void Serialize(Stream& s, int64 a,          int, int=0) { WRITEDATA(s, a); }
158 template<typename Stream> inline void Serialize(Stream& s, uint64 a,         int, int=0) { WRITEDATA(s, a); }
159 template<typename Stream> inline void Serialize(Stream& s, float a,          int, int=0) { WRITEDATA(s, a); }
160 template<typename Stream> inline void Serialize(Stream& s, double a,         int, int=0) { WRITEDATA(s, a); }
161
162 template<typename Stream> inline void Unserialize(Stream& s, char& a,           int, int=0) { READDATA(s, a); }
163 template<typename Stream> inline void Unserialize(Stream& s, signed char& a,    int, int=0) { READDATA(s, a); }
164 template<typename Stream> inline void Unserialize(Stream& s, unsigned char& a,  int, int=0) { READDATA(s, a); }
165 template<typename Stream> inline void Unserialize(Stream& s, signed short& a,   int, int=0) { READDATA(s, a); }
166 template<typename Stream> inline void Unserialize(Stream& s, unsigned short& a, int, int=0) { READDATA(s, a); }
167 template<typename Stream> inline void Unserialize(Stream& s, signed int& a,     int, int=0) { READDATA(s, a); }
168 template<typename Stream> inline void Unserialize(Stream& s, unsigned int& a,   int, int=0) { READDATA(s, a); }
169 template<typename Stream> inline void Unserialize(Stream& s, signed long& a,    int, int=0) { READDATA(s, a); }
170 template<typename Stream> inline void Unserialize(Stream& s, unsigned long& a,  int, int=0) { READDATA(s, a); }
171 template<typename Stream> inline void Unserialize(Stream& s, int64& a,          int, int=0) { READDATA(s, a); }
172 template<typename Stream> inline void Unserialize(Stream& s, uint64& a,         int, int=0) { READDATA(s, a); }
173 template<typename Stream> inline void Unserialize(Stream& s, float& a,          int, int=0) { READDATA(s, a); }
174 template<typename Stream> inline void Unserialize(Stream& s, double& a,         int, int=0) { READDATA(s, a); }
175
176 inline unsigned int GetSerializeSize(bool a, int, int=0)                          { return sizeof(char); }
177 template<typename Stream> inline void Serialize(Stream& s, bool a, int, int=0)    { char f=a; WRITEDATA(s, f); }
178 template<typename Stream> inline void Unserialize(Stream& s, bool& a, int, int=0) { char f; READDATA(s, f); a=f; }
179
180
181
182
183
184
185 //
186 // Compact size
187 //  size <  253        -- 1 byte
188 //  size <= USHRT_MAX  -- 3 bytes  (253 + 2 bytes)
189 //  size <= UINT_MAX   -- 5 bytes  (254 + 4 bytes)
190 //  size >  UINT_MAX   -- 9 bytes  (255 + 8 bytes)
191 //
192 inline unsigned int GetSizeOfCompactSize(uint64 nSize)
193 {
194     if (nSize < 253)             return sizeof(unsigned char);
195     else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
196     else if (nSize <= std::numeric_limits<unsigned int>::max())  return sizeof(unsigned char) + sizeof(unsigned int);
197     else                         return sizeof(unsigned char) + sizeof(uint64);
198 }
199
200 template<typename Stream>
201 void WriteCompactSize(Stream& os, uint64 nSize)
202 {
203     if (nSize < 253)
204     {
205         unsigned char chSize = nSize;
206         WRITEDATA(os, chSize);
207     }
208     else if (nSize <= std::numeric_limits<unsigned short>::max())
209     {
210         unsigned char chSize = 253;
211         unsigned short xSize = nSize;
212         WRITEDATA(os, chSize);
213         WRITEDATA(os, xSize);
214     }
215     else if (nSize <= std::numeric_limits<unsigned int>::max())
216     {
217         unsigned char chSize = 254;
218         unsigned int xSize = nSize;
219         WRITEDATA(os, chSize);
220         WRITEDATA(os, xSize);
221     }
222     else
223     {
224         unsigned char chSize = 255;
225         uint64 xSize = nSize;
226         WRITEDATA(os, chSize);
227         WRITEDATA(os, xSize);
228     }
229     return;
230 }
231
232 template<typename Stream>
233 uint64 ReadCompactSize(Stream& is)
234 {
235     unsigned char chSize;
236     READDATA(is, chSize);
237     uint64 nSizeRet = 0;
238     if (chSize < 253)
239     {
240         nSizeRet = chSize;
241     }
242     else if (chSize == 253)
243     {
244         unsigned short xSize;
245         READDATA(is, xSize);
246         nSizeRet = xSize;
247     }
248     else if (chSize == 254)
249     {
250         unsigned int xSize;
251         READDATA(is, xSize);
252         nSizeRet = xSize;
253     }
254     else
255     {
256         uint64 xSize;
257         READDATA(is, xSize);
258         nSizeRet = xSize;
259     }
260     if (nSizeRet > (uint64)MAX_SIZE)
261         throw std::ios_base::failure("ReadCompactSize() : size too large");
262     return nSizeRet;
263 }
264
265
266
267 //
268 // Wrapper for serializing arrays and POD
269 // There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it
270 //
271 #define FLATDATA(obj)   REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
272 class CFlatData
273 {
274 protected:
275     char* pbegin;
276     char* pend;
277 public:
278     CFlatData(void* pbeginIn, void* pendIn) : pbegin((char*)pbeginIn), pend((char*)pendIn) { }
279     char* begin() { return pbegin; }
280     const char* begin() const { return pbegin; }
281     char* end() { return pend; }
282     const char* end() const { return pend; }
283
284     unsigned int GetSerializeSize(int, int=0) const
285     {
286         return pend - pbegin;
287     }
288
289     template<typename Stream>
290     void Serialize(Stream& s, int, int=0) const
291     {
292         s.write(pbegin, pend - pbegin);
293     }
294
295     template<typename Stream>
296     void Unserialize(Stream& s, int, int=0)
297     {
298         s.read(pbegin, pend - pbegin);
299     }
300 };
301
302
303
304 //
305 // string stored as a fixed length field
306 //
307 template<std::size_t LEN>
308 class CFixedFieldString
309 {
310 protected:
311     const std::string* pcstr;
312     std::string* pstr;
313 public:
314     explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
315     explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
316
317     unsigned int GetSerializeSize(int, int=0) const
318     {
319         return LEN;
320     }
321
322     template<typename Stream>
323     void Serialize(Stream& s, int, int=0) const
324     {
325         char pszBuf[LEN];
326         strncpy(pszBuf, pcstr->c_str(), LEN);
327         s.write(pszBuf, LEN);
328     }
329
330     template<typename Stream>
331     void Unserialize(Stream& s, int, int=0)
332     {
333         if (pstr == NULL)
334             throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
335         char pszBuf[LEN+1];
336         s.read(pszBuf, LEN);
337         pszBuf[LEN] = '\0';
338         *pstr = pszBuf;
339     }
340 };
341
342
343
344
345
346 //
347 // Forward declarations
348 //
349
350 // string
351 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
352 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
353 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
354
355 // vector
356 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
357 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
358 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
359 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&);
360 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&);
361 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
362 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&);
363 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&);
364 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
365
366 // others derived from vector
367 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
368 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
369 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
370
371 // pair
372 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
373 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
374 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
375
376 // 3 tuple
377 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
378 template<typename Stream, typename T0, typename T1, typename T2> void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
379 template<typename Stream, typename T0, typename T1, typename T2> void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
380
381 // 4 tuple
382 template<typename T0, typename T1, typename T2, typename T3> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion=PROTOCOL_VERSION);
383 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=PROTOCOL_VERSION);
384 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=PROTOCOL_VERSION);
385
386 // map
387 template<typename K, typename T, typename Pred, typename A> unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
388 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=PROTOCOL_VERSION);
389 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=PROTOCOL_VERSION);
390
391 // set
392 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
393 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
394 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
395
396
397
398
399
400 //
401 // If none of the specialized versions above matched, default to calling member function.
402 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
403 // The compiler will only cast int to long if none of the other templates matched.
404 // Thanks to Boost serialization for this idea.
405 //
406 template<typename T>
407 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=PROTOCOL_VERSION)
408 {
409     return a.GetSerializeSize((int)nType, nVersion);
410 }
411
412 template<typename Stream, typename T>
413 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=PROTOCOL_VERSION)
414 {
415     a.Serialize(os, (int)nType, nVersion);
416 }
417
418 template<typename Stream, typename T>
419 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=PROTOCOL_VERSION)
420 {
421     a.Unserialize(is, (int)nType, nVersion);
422 }
423
424
425
426
427
428 //
429 // string
430 //
431 template<typename C>
432 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
433 {
434     return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
435 }
436
437 template<typename Stream, typename C>
438 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
439 {
440     WriteCompactSize(os, str.size());
441     if (!str.empty())
442         os.write((char*)&str[0], str.size() * sizeof(str[0]));
443 }
444
445 template<typename Stream, typename C>
446 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
447 {
448     unsigned int nSize = ReadCompactSize(is);
449     str.resize(nSize);
450     if (nSize != 0)
451         is.read((char*)&str[0], nSize * sizeof(str[0]));
452 }
453
454
455
456 //
457 // vector
458 //
459 template<typename T, typename A>
460 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
461 {
462     return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
463 }
464
465 template<typename T, typename A>
466 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
467 {
468     unsigned int nSize = GetSizeOfCompactSize(v.size());
469     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
470         nSize += GetSerializeSize((*vi), nType, nVersion);
471     return nSize;
472 }
473
474 template<typename T, typename A>
475 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
476 {
477     return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
478 }
479
480
481 template<typename Stream, typename T, typename A>
482 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
483 {
484     WriteCompactSize(os, v.size());
485     if (!v.empty())
486         os.write((char*)&v[0], v.size() * sizeof(T));
487 }
488
489 template<typename Stream, typename T, typename A>
490 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
491 {
492     WriteCompactSize(os, v.size());
493     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
494         ::Serialize(os, (*vi), nType, nVersion);
495 }
496
497 template<typename Stream, typename T, typename A>
498 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
499 {
500     Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
501 }
502
503
504 template<typename Stream, typename T, typename A>
505 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
506 {
507     //unsigned int nSize = ReadCompactSize(is);
508     //v.resize(nSize);
509     //is.read((char*)&v[0], nSize * sizeof(T));
510
511     // Limit size per read so bogus size value won't cause out of memory
512     v.clear();
513     unsigned int nSize = ReadCompactSize(is);
514     unsigned int i = 0;
515     while (i < nSize)
516     {
517         unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
518         v.resize(i + blk);
519         is.read((char*)&v[i], blk * sizeof(T));
520         i += blk;
521     }
522 }
523
524 template<typename Stream, typename T, typename A>
525 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
526 {
527     //unsigned int nSize = ReadCompactSize(is);
528     //v.resize(nSize);
529     //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
530     //    Unserialize(is, (*vi), nType, nVersion);
531
532     v.clear();
533     unsigned int nSize = ReadCompactSize(is);
534     unsigned int i = 0;
535     unsigned int nMid = 0;
536     while (nMid < nSize)
537     {
538         nMid += 5000000 / sizeof(T);
539         if (nMid > nSize)
540             nMid = nSize;
541         v.resize(nMid);
542         for (; i < nMid; i++)
543             Unserialize(is, v[i], nType, nVersion);
544     }
545 }
546
547 template<typename Stream, typename T, typename A>
548 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
549 {
550     Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
551 }
552
553
554
555 //
556 // others derived from vector
557 //
558 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
559 {
560     return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
561 }
562
563 template<typename Stream>
564 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
565 {
566     Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
567 }
568
569 template<typename Stream>
570 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
571 {
572     Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
573 }
574
575
576
577 //
578 // pair
579 //
580 template<typename K, typename T>
581 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
582 {
583     return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
584 }
585
586 template<typename Stream, typename K, typename T>
587 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
588 {
589     Serialize(os, item.first, nType, nVersion);
590     Serialize(os, item.second, nType, nVersion);
591 }
592
593 template<typename Stream, typename K, typename T>
594 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
595 {
596     Unserialize(is, item.first, nType, nVersion);
597     Unserialize(is, item.second, nType, nVersion);
598 }
599
600
601
602 //
603 // 3 tuple
604 //
605 template<typename T0, typename T1, typename T2>
606 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
607 {
608     unsigned int nSize = 0;
609     nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
610     nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
611     nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
612     return nSize;
613 }
614
615 template<typename Stream, typename T0, typename T1, typename T2>
616 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
617 {
618     Serialize(os, boost::get<0>(item), nType, nVersion);
619     Serialize(os, boost::get<1>(item), nType, nVersion);
620     Serialize(os, boost::get<2>(item), nType, nVersion);
621 }
622
623 template<typename Stream, typename T0, typename T1, typename T2>
624 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
625 {
626     Unserialize(is, boost::get<0>(item), nType, nVersion);
627     Unserialize(is, boost::get<1>(item), nType, nVersion);
628     Unserialize(is, boost::get<2>(item), nType, nVersion);
629 }
630
631
632
633 //
634 // 4 tuple
635 //
636 template<typename T0, typename T1, typename T2, typename T3>
637 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
638 {
639     unsigned int nSize = 0;
640     nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
641     nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
642     nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
643     nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
644     return nSize;
645 }
646
647 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
648 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
649 {
650     Serialize(os, boost::get<0>(item), nType, nVersion);
651     Serialize(os, boost::get<1>(item), nType, nVersion);
652     Serialize(os, boost::get<2>(item), nType, nVersion);
653     Serialize(os, boost::get<3>(item), nType, nVersion);
654 }
655
656 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
657 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
658 {
659     Unserialize(is, boost::get<0>(item), nType, nVersion);
660     Unserialize(is, boost::get<1>(item), nType, nVersion);
661     Unserialize(is, boost::get<2>(item), nType, nVersion);
662     Unserialize(is, boost::get<3>(item), nType, nVersion);
663 }
664
665
666
667 //
668 // map
669 //
670 template<typename K, typename T, typename Pred, typename A>
671 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
672 {
673     unsigned int nSize = GetSizeOfCompactSize(m.size());
674     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
675         nSize += GetSerializeSize((*mi), nType, nVersion);
676     return nSize;
677 }
678
679 template<typename Stream, typename K, typename T, typename Pred, typename A>
680 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
681 {
682     WriteCompactSize(os, m.size());
683     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
684         Serialize(os, (*mi), nType, nVersion);
685 }
686
687 template<typename Stream, typename K, typename T, typename Pred, typename A>
688 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
689 {
690     m.clear();
691     unsigned int nSize = ReadCompactSize(is);
692     typename std::map<K, T, Pred, A>::iterator mi = m.begin();
693     for (unsigned int i = 0; i < nSize; i++)
694     {
695         std::pair<K, T> item;
696         Unserialize(is, item, nType, nVersion);
697         mi = m.insert(mi, item);
698     }
699 }
700
701
702
703 //
704 // set
705 //
706 template<typename K, typename Pred, typename A>
707 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
708 {
709     unsigned int nSize = GetSizeOfCompactSize(m.size());
710     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
711         nSize += GetSerializeSize((*it), nType, nVersion);
712     return nSize;
713 }
714
715 template<typename Stream, typename K, typename Pred, typename A>
716 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
717 {
718     WriteCompactSize(os, m.size());
719     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
720         Serialize(os, (*it), nType, nVersion);
721 }
722
723 template<typename Stream, typename K, typename Pred, typename A>
724 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
725 {
726     m.clear();
727     unsigned int nSize = ReadCompactSize(is);
728     typename std::set<K, Pred, A>::iterator it = m.begin();
729     for (unsigned int i = 0; i < nSize; i++)
730     {
731         K key;
732         Unserialize(is, key, nType, nVersion);
733         it = m.insert(it, key);
734     }
735 }
736
737
738
739 //
740 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
741 //
742 class CSerActionGetSerializeSize { };
743 class CSerActionSerialize { };
744 class CSerActionUnserialize { };
745
746 template<typename Stream, typename T>
747 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
748 {
749     return ::GetSerializeSize(obj, nType, nVersion);
750 }
751
752 template<typename Stream, typename T>
753 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
754 {
755     ::Serialize(s, obj, nType, nVersion);
756     return 0;
757 }
758
759 template<typename Stream, typename T>
760 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
761 {
762     ::Unserialize(s, obj, nType, nVersion);
763     return 0;
764 }
765
766 struct ser_streamplaceholder
767 {
768     int nType;
769     int nVersion;
770 };
771
772
773
774
775
776
777
778
779
780 //
781 // Allocator that locks its contents from being paged
782 // out of memory and clears its contents before deletion.
783 //
784 template<typename T>
785 struct secure_allocator : public std::allocator<T>
786 {
787     // MSVC8 default copy constructor is broken
788     typedef std::allocator<T> base;
789     typedef typename base::size_type size_type;
790     typedef typename base::difference_type  difference_type;
791     typedef typename base::pointer pointer;
792     typedef typename base::const_pointer const_pointer;
793     typedef typename base::reference reference;
794     typedef typename base::const_reference const_reference;
795     typedef typename base::value_type value_type;
796     secure_allocator() throw() {}
797     secure_allocator(const secure_allocator& a) throw() : base(a) {}
798     template <typename U>
799     secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
800     ~secure_allocator() throw() {}
801     template<typename _Other> struct rebind
802     { typedef secure_allocator<_Other> other; };
803
804     T* allocate(std::size_t n, const void *hint = 0)
805     {
806         T *p;
807         p = std::allocator<T>::allocate(n, hint);
808         if (p != NULL)
809             mlock(p, sizeof(T) * n);
810         return p;
811     }
812
813     void deallocate(T* p, std::size_t n)
814     {
815         if (p != NULL)
816         {
817             memset(p, 0, sizeof(T) * n);
818             munlock(p, sizeof(T) * n);
819         }
820         std::allocator<T>::deallocate(p, n);
821     }
822 };
823
824
825 //
826 // Allocator that clears its contents before deletion.
827 //
828 template<typename T>
829 struct zero_after_free_allocator : public std::allocator<T>
830 {
831     // MSVC8 default copy constructor is broken
832     typedef std::allocator<T> base;
833     typedef typename base::size_type size_type;
834     typedef typename base::difference_type  difference_type;
835     typedef typename base::pointer pointer;
836     typedef typename base::const_pointer const_pointer;
837     typedef typename base::reference reference;
838     typedef typename base::const_reference const_reference;
839     typedef typename base::value_type value_type;
840     zero_after_free_allocator() throw() {}
841     zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
842     template <typename U>
843     zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a) {}
844     ~zero_after_free_allocator() throw() {}
845     template<typename _Other> struct rebind
846     { typedef zero_after_free_allocator<_Other> other; };
847
848     void deallocate(T* p, std::size_t n)
849     {
850         if (p != NULL)
851             memset(p, 0, sizeof(T) * n);
852         std::allocator<T>::deallocate(p, n);
853     }
854 };
855
856
857
858 //
859 // Double ended buffer combining vector and stream-like interfaces.
860 // >> and << read and write unformatted data using the above serialization templates.
861 // Fills with data in linear time; some stringstream implementations take N^2 time.
862 //
863 class CDataStream
864 {
865 protected:
866     typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
867     vector_type vch;
868     unsigned int nReadPos;
869     short state;
870     short exceptmask;
871 public:
872     int nType;
873     int nVersion;
874
875     typedef vector_type::allocator_type   allocator_type;
876     typedef vector_type::size_type        size_type;
877     typedef vector_type::difference_type  difference_type;
878     typedef vector_type::reference        reference;
879     typedef vector_type::const_reference  const_reference;
880     typedef vector_type::value_type       value_type;
881     typedef vector_type::iterator         iterator;
882     typedef vector_type::const_iterator   const_iterator;
883     typedef vector_type::reverse_iterator reverse_iterator;
884
885     explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
886     {
887         Init(nTypeIn, nVersionIn);
888     }
889
890     CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
891     {
892         Init(nTypeIn, nVersionIn);
893     }
894
895 #if !defined(_MSC_VER) || _MSC_VER >= 1300
896     CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
897     {
898         Init(nTypeIn, nVersionIn);
899     }
900 #endif
901
902     CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
903     {
904         Init(nTypeIn, nVersionIn);
905     }
906
907     CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
908     {
909         Init(nTypeIn, nVersionIn);
910     }
911
912     CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
913     {
914         Init(nTypeIn, nVersionIn);
915     }
916
917     void Init(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
918     {
919         nReadPos = 0;
920         nType = nTypeIn;
921         nVersion = nVersionIn;
922         state = 0;
923         exceptmask = std::ios::badbit | std::ios::failbit;
924     }
925
926     CDataStream& operator+=(const CDataStream& b)
927     {
928         vch.insert(vch.end(), b.begin(), b.end());
929         return *this;
930     }
931
932     friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
933     {
934         CDataStream ret = a;
935         ret += b;
936         return (ret);
937     }
938
939     std::string str() const
940     {
941         return (std::string(begin(), end()));
942     }
943
944
945     //
946     // Vector subset
947     //
948     const_iterator begin() const                     { return vch.begin() + nReadPos; }
949     iterator begin()                                 { return vch.begin() + nReadPos; }
950     const_iterator end() const                       { return vch.end(); }
951     iterator end()                                   { return vch.end(); }
952     size_type size() const                           { return vch.size() - nReadPos; }
953     bool empty() const                               { return vch.size() == nReadPos; }
954     void resize(size_type n, value_type c=0)         { vch.resize(n + nReadPos, c); }
955     void reserve(size_type n)                        { vch.reserve(n + nReadPos); }
956     const_reference operator[](size_type pos) const  { return vch[pos + nReadPos]; }
957     reference operator[](size_type pos)              { return vch[pos + nReadPos]; }
958     void clear()                                     { vch.clear(); nReadPos = 0; }
959     iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
960     void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
961
962     void insert(iterator it, const_iterator first, const_iterator last)
963     {
964         if (it == vch.begin() + nReadPos && last - first <= nReadPos)
965         {
966             // special case for inserting at the front when there's room
967             nReadPos -= (last - first);
968             memcpy(&vch[nReadPos], &first[0], last - first);
969         }
970         else
971             vch.insert(it, first, last);
972     }
973
974     void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
975     {
976         if (it == vch.begin() + nReadPos && last - first <= nReadPos)
977         {
978             // special case for inserting at the front when there's room
979             nReadPos -= (last - first);
980             memcpy(&vch[nReadPos], &first[0], last - first);
981         }
982         else
983             vch.insert(it, first, last);
984     }
985
986 #if !defined(_MSC_VER) || _MSC_VER >= 1300
987     void insert(iterator it, const char* first, const char* last)
988     {
989         if (it == vch.begin() + nReadPos && last - first <= nReadPos)
990         {
991             // special case for inserting at the front when there's room
992             nReadPos -= (last - first);
993             memcpy(&vch[nReadPos], &first[0], last - first);
994         }
995         else
996             vch.insert(it, first, last);
997     }
998 #endif
999
1000     iterator erase(iterator it)
1001     {
1002         if (it == vch.begin() + nReadPos)
1003         {
1004             // special case for erasing from the front
1005             if (++nReadPos >= vch.size())
1006             {
1007                 // whenever we reach the end, we take the opportunity to clear the buffer
1008                 nReadPos = 0;
1009                 return vch.erase(vch.begin(), vch.end());
1010             }
1011             return vch.begin() + nReadPos;
1012         }
1013         else
1014             return vch.erase(it);
1015     }
1016
1017     iterator erase(iterator first, iterator last)
1018     {
1019         if (first == vch.begin() + nReadPos)
1020         {
1021             // special case for erasing from the front
1022             if (last == vch.end())
1023             {
1024                 nReadPos = 0;
1025                 return vch.erase(vch.begin(), vch.end());
1026             }
1027             else
1028             {
1029                 nReadPos = (last - vch.begin());
1030                 return last;
1031             }
1032         }
1033         else
1034             return vch.erase(first, last);
1035     }
1036
1037     inline void Compact()
1038     {
1039         vch.erase(vch.begin(), vch.begin() + nReadPos);
1040         nReadPos = 0;
1041     }
1042
1043     bool Rewind(size_type n)
1044     {
1045         // Rewind by n characters if the buffer hasn't been compacted yet
1046         if (n > nReadPos)
1047             return false;
1048         nReadPos -= n;
1049         return true;
1050     }
1051
1052
1053     //
1054     // Stream subset
1055     //
1056     void setstate(short bits, const char* psz)
1057     {
1058         state |= bits;
1059         if (state & exceptmask)
1060             throw std::ios_base::failure(psz);
1061     }
1062
1063     bool eof() const             { return size() == 0; }
1064     bool fail() const            { return state & (std::ios::badbit | std::ios::failbit); }
1065     bool good() const            { return !eof() && (state == 0); }
1066     void clear(short n)          { state = n; }  // name conflict with vector clear()
1067     short exceptions()           { return exceptmask; }
1068     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1069     CDataStream* rdbuf()         { return this; }
1070     int in_avail()               { return size(); }
1071
1072     void SetType(int n)          { nType = n; }
1073     int GetType()                { return nType; }
1074     void SetVersion(int n)       { nVersion = n; }
1075     int GetVersion()             { return nVersion; }
1076     void ReadVersion()           { *this >> nVersion; }
1077     void WriteVersion()          { *this << nVersion; }
1078
1079     CDataStream& read(char* pch, int nSize)
1080     {
1081         // Read from the beginning of the buffer
1082         assert(nSize >= 0);
1083         unsigned int nReadPosNext = nReadPos + nSize;
1084         if (nReadPosNext >= vch.size())
1085         {
1086             if (nReadPosNext > vch.size())
1087             {
1088                 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1089                 memset(pch, 0, nSize);
1090                 nSize = vch.size() - nReadPos;
1091             }
1092             memcpy(pch, &vch[nReadPos], nSize);
1093             nReadPos = 0;
1094             vch.clear();
1095             return (*this);
1096         }
1097         memcpy(pch, &vch[nReadPos], nSize);
1098         nReadPos = nReadPosNext;
1099         return (*this);
1100     }
1101
1102     CDataStream& ignore(int nSize)
1103     {
1104         // Ignore from the beginning of the buffer
1105         assert(nSize >= 0);
1106         unsigned int nReadPosNext = nReadPos + nSize;
1107         if (nReadPosNext >= vch.size())
1108         {
1109             if (nReadPosNext > vch.size())
1110             {
1111                 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1112                 nSize = vch.size() - nReadPos;
1113             }
1114             nReadPos = 0;
1115             vch.clear();
1116             return (*this);
1117         }
1118         nReadPos = nReadPosNext;
1119         return (*this);
1120     }
1121
1122     CDataStream& write(const char* pch, int nSize)
1123     {
1124         // Write to the end of the buffer
1125         assert(nSize >= 0);
1126         vch.insert(vch.end(), pch, pch + nSize);
1127         return (*this);
1128     }
1129
1130     template<typename Stream>
1131     void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
1132     {
1133         // Special case: stream << stream concatenates like stream += stream
1134         if (!vch.empty())
1135             s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1136     }
1137
1138     template<typename T>
1139     unsigned int GetSerializeSize(const T& obj)
1140     {
1141         // Tells the size of the object if serialized to this stream
1142         return ::GetSerializeSize(obj, nType, nVersion);
1143     }
1144
1145     template<typename T>
1146     CDataStream& operator<<(const T& obj)
1147     {
1148         // Serialize to this stream
1149         ::Serialize(*this, obj, nType, nVersion);
1150         return (*this);
1151     }
1152
1153     template<typename T>
1154     CDataStream& operator>>(T& obj)
1155     {
1156         // Unserialize from this stream
1157         ::Unserialize(*this, obj, nType, nVersion);
1158         return (*this);
1159     }
1160 };
1161
1162 #ifdef TESTCDATASTREAM
1163 // VC6sp6
1164 // CDataStream:
1165 // n=1000       0 seconds
1166 // n=2000       0 seconds
1167 // n=4000       0 seconds
1168 // n=8000       0 seconds
1169 // n=16000      0 seconds
1170 // n=32000      0 seconds
1171 // n=64000      1 seconds
1172 // n=128000     1 seconds
1173 // n=256000     2 seconds
1174 // n=512000     4 seconds
1175 // n=1024000    8 seconds
1176 // n=2048000    16 seconds
1177 // n=4096000    32 seconds
1178 // stringstream:
1179 // n=1000       1 seconds
1180 // n=2000       1 seconds
1181 // n=4000       13 seconds
1182 // n=8000       87 seconds
1183 // n=16000      400 seconds
1184 // n=32000      1660 seconds
1185 // n=64000      6749 seconds
1186 // n=128000     27241 seconds
1187 // n=256000     109804 seconds
1188 #include <iostream>
1189 int main(int argc, char *argv[])
1190 {
1191     vector<unsigned char> vch(0xcc, 250);
1192     printf("CDataStream:\n");
1193     for (int n = 1000; n <= 4500000; n *= 2)
1194     {
1195         CDataStream ss;
1196         time_t nStart = time(NULL);
1197         for (int i = 0; i < n; i++)
1198             ss.write((char*)&vch[0], vch.size());
1199         printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1200     }
1201     printf("stringstream:\n");
1202     for (int n = 1000; n <= 4500000; n *= 2)
1203     {
1204         stringstream ss;
1205         time_t nStart = time(NULL);
1206         for (int i = 0; i < n; i++)
1207             ss.write((char*)&vch[0], vch.size());
1208         printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1209     }
1210 }
1211 #endif
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222 //
1223 // Automatic closing wrapper for FILE*
1224 //  - Will automatically close the file when it goes out of scope if not null.
1225 //  - If you're returning the file pointer, return file.release().
1226 //  - If you need to close the file early, use file.fclose() instead of fclose(file).
1227 //
1228 class CAutoFile
1229 {
1230 protected:
1231     FILE* file;
1232     short state;
1233     short exceptmask;
1234 public:
1235     int nType;
1236     int nVersion;
1237
1238     typedef FILE element_type;
1239
1240     CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=PROTOCOL_VERSION)
1241     {
1242         file = filenew;
1243         nType = nTypeIn;
1244         nVersion = nVersionIn;
1245         state = 0;
1246         exceptmask = std::ios::badbit | std::ios::failbit;
1247     }
1248
1249     ~CAutoFile()
1250     {
1251         fclose();
1252     }
1253
1254     void fclose()
1255     {
1256         if (file != NULL && file != stdin && file != stdout && file != stderr)
1257             ::fclose(file);
1258         file = NULL;
1259     }
1260
1261     FILE* release()             { FILE* ret = file; file = NULL; return ret; }
1262     operator FILE*()            { return file; }
1263     FILE* operator->()          { return file; }
1264     FILE& operator*()           { return *file; }
1265     FILE** operator&()          { return &file; }
1266     FILE* operator=(FILE* pnew) { return file = pnew; }
1267     bool operator!()            { return (file == NULL); }
1268
1269
1270     //
1271     // Stream subset
1272     //
1273     void setstate(short bits, const char* psz)
1274     {
1275         state |= bits;
1276         if (state & exceptmask)
1277             throw std::ios_base::failure(psz);
1278     }
1279
1280     bool fail() const            { return state & (std::ios::badbit | std::ios::failbit); }
1281     bool good() const            { return state == 0; }
1282     void clear(short n = 0)      { state = n; }
1283     short exceptions()           { return exceptmask; }
1284     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1285
1286     void SetType(int n)          { nType = n; }
1287     int GetType()                { return nType; }
1288     void SetVersion(int n)       { nVersion = n; }
1289     int GetVersion()             { return nVersion; }
1290     void ReadVersion()           { *this >> nVersion; }
1291     void WriteVersion()          { *this << nVersion; }
1292
1293     CAutoFile& read(char* pch, int nSize)
1294     {
1295         if (!file)
1296             throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1297         if (fread(pch, 1, nSize, file) != nSize)
1298             setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1299         return (*this);
1300     }
1301
1302     CAutoFile& write(const char* pch, int nSize)
1303     {
1304         if (!file)
1305             throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1306         if (fwrite(pch, 1, nSize, file) != nSize)
1307             setstate(std::ios::failbit, "CAutoFile::write : write failed");
1308         return (*this);
1309     }
1310
1311     template<typename T>
1312     unsigned int GetSerializeSize(const T& obj)
1313     {
1314         // Tells the size of the object if serialized to this stream
1315         return ::GetSerializeSize(obj, nType, nVersion);
1316     }
1317
1318     template<typename T>
1319     CAutoFile& operator<<(const T& obj)
1320     {
1321         // Serialize to this stream
1322         if (!file)
1323             throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1324         ::Serialize(*this, obj, nType, nVersion);
1325         return (*this);
1326     }
1327
1328     template<typename T>
1329     CAutoFile& operator>>(T& obj)
1330     {
1331         // Unserialize from this stream
1332         if (!file)
1333             throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1334         ::Unserialize(*this, obj, nType, nVersion);
1335         return (*this);
1336     }
1337 };
1338
1339 #endif