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