Update License in File Headers
[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 COPYING 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 #define FLATDATA(obj)   REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
269
270 /** Wrapper for serializing arrays and POD.
271  * There's a clever template way to make arrays serialize normally, but MSVC6 doesn't support it.
272  */
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 /** string stored as a fixed length field */
306 template<std::size_t LEN>
307 class CFixedFieldString
308 {
309 protected:
310     const std::string* pcstr;
311     std::string* pstr;
312 public:
313     explicit CFixedFieldString(const std::string& str) : pcstr(&str), pstr(NULL) { }
314     explicit CFixedFieldString(std::string& str) : pcstr(&str), pstr(&str) { }
315
316     unsigned int GetSerializeSize(int, int=0) const
317     {
318         return LEN;
319     }
320
321     template<typename Stream>
322     void Serialize(Stream& s, int, int=0) const
323     {
324         char pszBuf[LEN];
325         strncpy(pszBuf, pcstr->c_str(), LEN);
326         s.write(pszBuf, LEN);
327     }
328
329     template<typename Stream>
330     void Unserialize(Stream& s, int, int=0)
331     {
332         if (pstr == NULL)
333             throw std::ios_base::failure("CFixedFieldString::Unserialize : trying to unserialize to const string");
334         char pszBuf[LEN+1];
335         s.read(pszBuf, LEN);
336         pszBuf[LEN] = '\0';
337         *pstr = pszBuf;
338     }
339 };
340
341
342
343
344
345 //
346 // Forward declarations
347 //
348
349 // string
350 template<typename C> unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int=0);
351 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str, int, int=0);
352 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str, int, int=0);
353
354 // vector
355 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&);
356 template<typename T, typename A> unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&);
357 template<typename T, typename A> inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
358 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&);
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::false_type&);
360 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
361 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&);
362 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&);
363 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion=PROTOCOL_VERSION);
364
365 // others derived from vector
366 extern inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
367 template<typename Stream> void Serialize(Stream& os, const CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
368 template<typename Stream> void Unserialize(Stream& is, CScript& v, int nType, int nVersion=PROTOCOL_VERSION);
369
370 // pair
371 template<typename K, typename T> unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
372 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
373 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion=PROTOCOL_VERSION);
374
375 // 3 tuple
376 template<typename T0, typename T1, typename T2> unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion=PROTOCOL_VERSION);
377 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);
378 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);
379
380 // 4 tuple
381 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);
382 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);
383 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);
384
385 // map
386 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);
387 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);
388 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);
389
390 // set
391 template<typename K, typename Pred, typename A> unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion=PROTOCOL_VERSION);
392 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);
393 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);
394
395
396
397
398
399 //
400 // If none of the specialized versions above matched, default to calling member function.
401 // "int nType" is changed to "long nType" to keep from getting an ambiguous overload error.
402 // The compiler will only cast int to long if none of the other templates matched.
403 // Thanks to Boost serialization for this idea.
404 //
405 template<typename T>
406 inline unsigned int GetSerializeSize(const T& a, long nType, int nVersion=PROTOCOL_VERSION)
407 {
408     return a.GetSerializeSize((int)nType, nVersion);
409 }
410
411 template<typename Stream, typename T>
412 inline void Serialize(Stream& os, const T& a, long nType, int nVersion=PROTOCOL_VERSION)
413 {
414     a.Serialize(os, (int)nType, nVersion);
415 }
416
417 template<typename Stream, typename T>
418 inline void Unserialize(Stream& is, T& a, long nType, int nVersion=PROTOCOL_VERSION)
419 {
420     a.Unserialize(is, (int)nType, nVersion);
421 }
422
423
424
425
426
427 //
428 // string
429 //
430 template<typename C>
431 unsigned int GetSerializeSize(const std::basic_string<C>& str, int, int)
432 {
433     return GetSizeOfCompactSize(str.size()) + str.size() * sizeof(str[0]);
434 }
435
436 template<typename Stream, typename C>
437 void Serialize(Stream& os, const std::basic_string<C>& str, int, int)
438 {
439     WriteCompactSize(os, str.size());
440     if (!str.empty())
441         os.write((char*)&str[0], str.size() * sizeof(str[0]));
442 }
443
444 template<typename Stream, typename C>
445 void Unserialize(Stream& is, std::basic_string<C>& str, int, int)
446 {
447     unsigned int nSize = ReadCompactSize(is);
448     str.resize(nSize);
449     if (nSize != 0)
450         is.read((char*)&str[0], nSize * sizeof(str[0]));
451 }
452
453
454
455 //
456 // vector
457 //
458 template<typename T, typename A>
459 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
460 {
461     return (GetSizeOfCompactSize(v.size()) + v.size() * sizeof(T));
462 }
463
464 template<typename T, typename A>
465 unsigned int GetSerializeSize_impl(const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
466 {
467     unsigned int nSize = GetSizeOfCompactSize(v.size());
468     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
469         nSize += GetSerializeSize((*vi), nType, nVersion);
470     return nSize;
471 }
472
473 template<typename T, typename A>
474 inline unsigned int GetSerializeSize(const std::vector<T, A>& v, int nType, int nVersion)
475 {
476     return GetSerializeSize_impl(v, nType, nVersion, boost::is_fundamental<T>());
477 }
478
479
480 template<typename Stream, typename T, typename A>
481 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
482 {
483     WriteCompactSize(os, v.size());
484     if (!v.empty())
485         os.write((char*)&v[0], v.size() * sizeof(T));
486 }
487
488 template<typename Stream, typename T, typename A>
489 void Serialize_impl(Stream& os, const std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
490 {
491     WriteCompactSize(os, v.size());
492     for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
493         ::Serialize(os, (*vi), nType, nVersion);
494 }
495
496 template<typename Stream, typename T, typename A>
497 inline void Serialize(Stream& os, const std::vector<T, A>& v, int nType, int nVersion)
498 {
499     Serialize_impl(os, v, nType, nVersion, boost::is_fundamental<T>());
500 }
501
502
503 template<typename Stream, typename T, typename A>
504 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::true_type&)
505 {
506     //unsigned int nSize = ReadCompactSize(is);
507     //v.resize(nSize);
508     //is.read((char*)&v[0], nSize * sizeof(T));
509
510     // Limit size per read so bogus size value won't cause out of memory
511     v.clear();
512     unsigned int nSize = ReadCompactSize(is);
513     unsigned int i = 0;
514     while (i < nSize)
515     {
516         unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
517         v.resize(i + blk);
518         is.read((char*)&v[i], blk * sizeof(T));
519         i += blk;
520     }
521 }
522
523 template<typename Stream, typename T, typename A>
524 void Unserialize_impl(Stream& is, std::vector<T, A>& v, int nType, int nVersion, const boost::false_type&)
525 {
526     //unsigned int nSize = ReadCompactSize(is);
527     //v.resize(nSize);
528     //for (std::vector<T, A>::iterator vi = v.begin(); vi != v.end(); ++vi)
529     //    Unserialize(is, (*vi), nType, nVersion);
530
531     v.clear();
532     unsigned int nSize = ReadCompactSize(is);
533     unsigned int i = 0;
534     unsigned int nMid = 0;
535     while (nMid < nSize)
536     {
537         nMid += 5000000 / sizeof(T);
538         if (nMid > nSize)
539             nMid = nSize;
540         v.resize(nMid);
541         for (; i < nMid; i++)
542             Unserialize(is, v[i], nType, nVersion);
543     }
544 }
545
546 template<typename Stream, typename T, typename A>
547 inline void Unserialize(Stream& is, std::vector<T, A>& v, int nType, int nVersion)
548 {
549     Unserialize_impl(is, v, nType, nVersion, boost::is_fundamental<T>());
550 }
551
552
553
554 //
555 // others derived from vector
556 //
557 inline unsigned int GetSerializeSize(const CScript& v, int nType, int nVersion)
558 {
559     return GetSerializeSize((const std::vector<unsigned char>&)v, nType, nVersion);
560 }
561
562 template<typename Stream>
563 void Serialize(Stream& os, const CScript& v, int nType, int nVersion)
564 {
565     Serialize(os, (const std::vector<unsigned char>&)v, nType, nVersion);
566 }
567
568 template<typename Stream>
569 void Unserialize(Stream& is, CScript& v, int nType, int nVersion)
570 {
571     Unserialize(is, (std::vector<unsigned char>&)v, nType, nVersion);
572 }
573
574
575
576 //
577 // pair
578 //
579 template<typename K, typename T>
580 unsigned int GetSerializeSize(const std::pair<K, T>& item, int nType, int nVersion)
581 {
582     return GetSerializeSize(item.first, nType, nVersion) + GetSerializeSize(item.second, nType, nVersion);
583 }
584
585 template<typename Stream, typename K, typename T>
586 void Serialize(Stream& os, const std::pair<K, T>& item, int nType, int nVersion)
587 {
588     Serialize(os, item.first, nType, nVersion);
589     Serialize(os, item.second, nType, nVersion);
590 }
591
592 template<typename Stream, typename K, typename T>
593 void Unserialize(Stream& is, std::pair<K, T>& item, int nType, int nVersion)
594 {
595     Unserialize(is, item.first, nType, nVersion);
596     Unserialize(is, item.second, nType, nVersion);
597 }
598
599
600
601 //
602 // 3 tuple
603 //
604 template<typename T0, typename T1, typename T2>
605 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
606 {
607     unsigned int nSize = 0;
608     nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
609     nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
610     nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
611     return nSize;
612 }
613
614 template<typename Stream, typename T0, typename T1, typename T2>
615 void Serialize(Stream& os, const boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
616 {
617     Serialize(os, boost::get<0>(item), nType, nVersion);
618     Serialize(os, boost::get<1>(item), nType, nVersion);
619     Serialize(os, boost::get<2>(item), nType, nVersion);
620 }
621
622 template<typename Stream, typename T0, typename T1, typename T2>
623 void Unserialize(Stream& is, boost::tuple<T0, T1, T2>& item, int nType, int nVersion)
624 {
625     Unserialize(is, boost::get<0>(item), nType, nVersion);
626     Unserialize(is, boost::get<1>(item), nType, nVersion);
627     Unserialize(is, boost::get<2>(item), nType, nVersion);
628 }
629
630
631
632 //
633 // 4 tuple
634 //
635 template<typename T0, typename T1, typename T2, typename T3>
636 unsigned int GetSerializeSize(const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
637 {
638     unsigned int nSize = 0;
639     nSize += GetSerializeSize(boost::get<0>(item), nType, nVersion);
640     nSize += GetSerializeSize(boost::get<1>(item), nType, nVersion);
641     nSize += GetSerializeSize(boost::get<2>(item), nType, nVersion);
642     nSize += GetSerializeSize(boost::get<3>(item), nType, nVersion);
643     return nSize;
644 }
645
646 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
647 void Serialize(Stream& os, const boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
648 {
649     Serialize(os, boost::get<0>(item), nType, nVersion);
650     Serialize(os, boost::get<1>(item), nType, nVersion);
651     Serialize(os, boost::get<2>(item), nType, nVersion);
652     Serialize(os, boost::get<3>(item), nType, nVersion);
653 }
654
655 template<typename Stream, typename T0, typename T1, typename T2, typename T3>
656 void Unserialize(Stream& is, boost::tuple<T0, T1, T2, T3>& item, int nType, int nVersion)
657 {
658     Unserialize(is, boost::get<0>(item), nType, nVersion);
659     Unserialize(is, boost::get<1>(item), nType, nVersion);
660     Unserialize(is, boost::get<2>(item), nType, nVersion);
661     Unserialize(is, boost::get<3>(item), nType, nVersion);
662 }
663
664
665
666 //
667 // map
668 //
669 template<typename K, typename T, typename Pred, typename A>
670 unsigned int GetSerializeSize(const std::map<K, T, Pred, A>& m, int nType, int nVersion)
671 {
672     unsigned int nSize = GetSizeOfCompactSize(m.size());
673     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
674         nSize += GetSerializeSize((*mi), nType, nVersion);
675     return nSize;
676 }
677
678 template<typename Stream, typename K, typename T, typename Pred, typename A>
679 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m, int nType, int nVersion)
680 {
681     WriteCompactSize(os, m.size());
682     for (typename std::map<K, T, Pred, A>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
683         Serialize(os, (*mi), nType, nVersion);
684 }
685
686 template<typename Stream, typename K, typename T, typename Pred, typename A>
687 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m, int nType, int nVersion)
688 {
689     m.clear();
690     unsigned int nSize = ReadCompactSize(is);
691     typename std::map<K, T, Pred, A>::iterator mi = m.begin();
692     for (unsigned int i = 0; i < nSize; i++)
693     {
694         std::pair<K, T> item;
695         Unserialize(is, item, nType, nVersion);
696         mi = m.insert(mi, item);
697     }
698 }
699
700
701
702 //
703 // set
704 //
705 template<typename K, typename Pred, typename A>
706 unsigned int GetSerializeSize(const std::set<K, Pred, A>& m, int nType, int nVersion)
707 {
708     unsigned int nSize = GetSizeOfCompactSize(m.size());
709     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
710         nSize += GetSerializeSize((*it), nType, nVersion);
711     return nSize;
712 }
713
714 template<typename Stream, typename K, typename Pred, typename A>
715 void Serialize(Stream& os, const std::set<K, Pred, A>& m, int nType, int nVersion)
716 {
717     WriteCompactSize(os, m.size());
718     for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
719         Serialize(os, (*it), nType, nVersion);
720 }
721
722 template<typename Stream, typename K, typename Pred, typename A>
723 void Unserialize(Stream& is, std::set<K, Pred, A>& m, int nType, int nVersion)
724 {
725     m.clear();
726     unsigned int nSize = ReadCompactSize(is);
727     typename std::set<K, Pred, A>::iterator it = m.begin();
728     for (unsigned int i = 0; i < nSize; i++)
729     {
730         K key;
731         Unserialize(is, key, nType, nVersion);
732         it = m.insert(it, key);
733     }
734 }
735
736
737
738 //
739 // Support for IMPLEMENT_SERIALIZE and READWRITE macro
740 //
741 class CSerActionGetSerializeSize { };
742 class CSerActionSerialize { };
743 class CSerActionUnserialize { };
744
745 template<typename Stream, typename T>
746 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionGetSerializeSize ser_action)
747 {
748     return ::GetSerializeSize(obj, nType, nVersion);
749 }
750
751 template<typename Stream, typename T>
752 inline unsigned int SerReadWrite(Stream& s, const T& obj, int nType, int nVersion, CSerActionSerialize ser_action)
753 {
754     ::Serialize(s, obj, nType, nVersion);
755     return 0;
756 }
757
758 template<typename Stream, typename T>
759 inline unsigned int SerReadWrite(Stream& s, T& obj, int nType, int nVersion, CSerActionUnserialize ser_action)
760 {
761     ::Unserialize(s, obj, nType, nVersion);
762     return 0;
763 }
764
765 struct ser_streamplaceholder
766 {
767     int nType;
768     int nVersion;
769 };
770
771
772
773
774
775
776
777
778
779 //
780 // Allocator that locks its contents from being paged
781 // out of memory and clears its contents before deletion.
782 //
783 template<typename T>
784 struct secure_allocator : public std::allocator<T>
785 {
786     // MSVC8 default copy constructor is broken
787     typedef std::allocator<T> base;
788     typedef typename base::size_type size_type;
789     typedef typename base::difference_type  difference_type;
790     typedef typename base::pointer pointer;
791     typedef typename base::const_pointer const_pointer;
792     typedef typename base::reference reference;
793     typedef typename base::const_reference const_reference;
794     typedef typename base::value_type value_type;
795     secure_allocator() throw() {}
796     secure_allocator(const secure_allocator& a) throw() : base(a) {}
797     template <typename U>
798     secure_allocator(const secure_allocator<U>& a) throw() : base(a) {}
799     ~secure_allocator() throw() {}
800     template<typename _Other> struct rebind
801     { typedef secure_allocator<_Other> other; };
802
803     T* allocate(std::size_t n, const void *hint = 0)
804     {
805         T *p;
806         p = std::allocator<T>::allocate(n, hint);
807         if (p != NULL)
808             mlock(p, sizeof(T) * n);
809         return p;
810     }
811
812     void deallocate(T* p, std::size_t n)
813     {
814         if (p != NULL)
815         {
816             memset(p, 0, sizeof(T) * n);
817             munlock(p, sizeof(T) * n);
818         }
819         std::allocator<T>::deallocate(p, n);
820     }
821 };
822
823
824 //
825 // Allocator that clears its contents before deletion.
826 //
827 template<typename T>
828 struct zero_after_free_allocator : public std::allocator<T>
829 {
830     // MSVC8 default copy constructor is broken
831     typedef std::allocator<T> base;
832     typedef typename base::size_type size_type;
833     typedef typename base::difference_type  difference_type;
834     typedef typename base::pointer pointer;
835     typedef typename base::const_pointer const_pointer;
836     typedef typename base::reference reference;
837     typedef typename base::const_reference const_reference;
838     typedef typename base::value_type value_type;
839     zero_after_free_allocator() throw() {}
840     zero_after_free_allocator(const zero_after_free_allocator& a) throw() : base(a) {}
841     template <typename U>
842     zero_after_free_allocator(const zero_after_free_allocator<U>& a) throw() : base(a) {}
843     ~zero_after_free_allocator() throw() {}
844     template<typename _Other> struct rebind
845     { typedef zero_after_free_allocator<_Other> other; };
846
847     void deallocate(T* p, std::size_t n)
848     {
849         if (p != NULL)
850             memset(p, 0, sizeof(T) * n);
851         std::allocator<T>::deallocate(p, n);
852     }
853 };
854
855
856
857 /** Double ended buffer combining vector and stream-like interfaces.
858  *
859  * >> and << read and write unformatted data using the above serialization templates.
860  * Fills with data in linear time; some stringstream implementations take N^2 time.
861  */
862 class CDataStream
863 {
864 protected:
865     typedef std::vector<char, zero_after_free_allocator<char> > vector_type;
866     vector_type vch;
867     unsigned int nReadPos;
868     short state;
869     short exceptmask;
870 public:
871     int nType;
872     int nVersion;
873
874     typedef vector_type::allocator_type   allocator_type;
875     typedef vector_type::size_type        size_type;
876     typedef vector_type::difference_type  difference_type;
877     typedef vector_type::reference        reference;
878     typedef vector_type::const_reference  const_reference;
879     typedef vector_type::value_type       value_type;
880     typedef vector_type::iterator         iterator;
881     typedef vector_type::const_iterator   const_iterator;
882     typedef vector_type::reverse_iterator reverse_iterator;
883
884     explicit CDataStream(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
885     {
886         Init(nTypeIn, nVersionIn);
887     }
888
889     CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
890     {
891         Init(nTypeIn, nVersionIn);
892     }
893
894 #if !defined(_MSC_VER) || _MSC_VER >= 1300
895     CDataStream(const char* pbegin, const char* pend, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(pbegin, pend)
896     {
897         Init(nTypeIn, nVersionIn);
898     }
899 #endif
900
901     CDataStream(const vector_type& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
902     {
903         Init(nTypeIn, nVersionIn);
904     }
905
906     CDataStream(const std::vector<char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch(vchIn.begin(), vchIn.end())
907     {
908         Init(nTypeIn, nVersionIn);
909     }
910
911     CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION) : vch((char*)&vchIn.begin()[0], (char*)&vchIn.end()[0])
912     {
913         Init(nTypeIn, nVersionIn);
914     }
915
916     void Init(int nTypeIn=SER_NETWORK, int nVersionIn=PROTOCOL_VERSION)
917     {
918         nReadPos = 0;
919         nType = nTypeIn;
920         nVersion = nVersionIn;
921         state = 0;
922         exceptmask = std::ios::badbit | std::ios::failbit;
923     }
924
925     CDataStream& operator+=(const CDataStream& b)
926     {
927         vch.insert(vch.end(), b.begin(), b.end());
928         return *this;
929     }
930
931     friend CDataStream operator+(const CDataStream& a, const CDataStream& b)
932     {
933         CDataStream ret = a;
934         ret += b;
935         return (ret);
936     }
937
938     std::string str() const
939     {
940         return (std::string(begin(), end()));
941     }
942
943
944     //
945     // Vector subset
946     //
947     const_iterator begin() const                     { return vch.begin() + nReadPos; }
948     iterator begin()                                 { return vch.begin() + nReadPos; }
949     const_iterator end() const                       { return vch.end(); }
950     iterator end()                                   { return vch.end(); }
951     size_type size() const                           { return vch.size() - nReadPos; }
952     bool empty() const                               { return vch.size() == nReadPos; }
953     void resize(size_type n, value_type c=0)         { vch.resize(n + nReadPos, c); }
954     void reserve(size_type n)                        { vch.reserve(n + nReadPos); }
955     const_reference operator[](size_type pos) const  { return vch[pos + nReadPos]; }
956     reference operator[](size_type pos)              { return vch[pos + nReadPos]; }
957     void clear()                                     { vch.clear(); nReadPos = 0; }
958     iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
959     void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
960
961     void insert(iterator it, const_iterator first, const_iterator last)
962     {
963         if (it == vch.begin() + nReadPos && last - first <= nReadPos)
964         {
965             // special case for inserting at the front when there's room
966             nReadPos -= (last - first);
967             memcpy(&vch[nReadPos], &first[0], last - first);
968         }
969         else
970             vch.insert(it, first, last);
971     }
972
973     void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
974     {
975         if (it == vch.begin() + nReadPos && last - first <= nReadPos)
976         {
977             // special case for inserting at the front when there's room
978             nReadPos -= (last - first);
979             memcpy(&vch[nReadPos], &first[0], last - first);
980         }
981         else
982             vch.insert(it, first, last);
983     }
984
985 #if !defined(_MSC_VER) || _MSC_VER >= 1300
986     void insert(iterator it, const char* first, const char* last)
987     {
988         if (it == vch.begin() + nReadPos && last - first <= nReadPos)
989         {
990             // special case for inserting at the front when there's room
991             nReadPos -= (last - first);
992             memcpy(&vch[nReadPos], &first[0], last - first);
993         }
994         else
995             vch.insert(it, first, last);
996     }
997 #endif
998
999     iterator erase(iterator it)
1000     {
1001         if (it == vch.begin() + nReadPos)
1002         {
1003             // special case for erasing from the front
1004             if (++nReadPos >= vch.size())
1005             {
1006                 // whenever we reach the end, we take the opportunity to clear the buffer
1007                 nReadPos = 0;
1008                 return vch.erase(vch.begin(), vch.end());
1009             }
1010             return vch.begin() + nReadPos;
1011         }
1012         else
1013             return vch.erase(it);
1014     }
1015
1016     iterator erase(iterator first, iterator last)
1017     {
1018         if (first == vch.begin() + nReadPos)
1019         {
1020             // special case for erasing from the front
1021             if (last == vch.end())
1022             {
1023                 nReadPos = 0;
1024                 return vch.erase(vch.begin(), vch.end());
1025             }
1026             else
1027             {
1028                 nReadPos = (last - vch.begin());
1029                 return last;
1030             }
1031         }
1032         else
1033             return vch.erase(first, last);
1034     }
1035
1036     inline void Compact()
1037     {
1038         vch.erase(vch.begin(), vch.begin() + nReadPos);
1039         nReadPos = 0;
1040     }
1041
1042     bool Rewind(size_type n)
1043     {
1044         // Rewind by n characters if the buffer hasn't been compacted yet
1045         if (n > nReadPos)
1046             return false;
1047         nReadPos -= n;
1048         return true;
1049     }
1050
1051
1052     //
1053     // Stream subset
1054     //
1055     void setstate(short bits, const char* psz)
1056     {
1057         state |= bits;
1058         if (state & exceptmask)
1059             throw std::ios_base::failure(psz);
1060     }
1061
1062     bool eof() const             { return size() == 0; }
1063     bool fail() const            { return state & (std::ios::badbit | std::ios::failbit); }
1064     bool good() const            { return !eof() && (state == 0); }
1065     void clear(short n)          { state = n; }  // name conflict with vector clear()
1066     short exceptions()           { return exceptmask; }
1067     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CDataStream"); return prev; }
1068     CDataStream* rdbuf()         { return this; }
1069     int in_avail()               { return size(); }
1070
1071     void SetType(int n)          { nType = n; }
1072     int GetType()                { return nType; }
1073     void SetVersion(int n)       { nVersion = n; }
1074     int GetVersion()             { return nVersion; }
1075     void ReadVersion()           { *this >> nVersion; }
1076     void WriteVersion()          { *this << nVersion; }
1077
1078     CDataStream& read(char* pch, int nSize)
1079     {
1080         // Read from the beginning of the buffer
1081         assert(nSize >= 0);
1082         unsigned int nReadPosNext = nReadPos + nSize;
1083         if (nReadPosNext >= vch.size())
1084         {
1085             if (nReadPosNext > vch.size())
1086             {
1087                 setstate(std::ios::failbit, "CDataStream::read() : end of data");
1088                 memset(pch, 0, nSize);
1089                 nSize = vch.size() - nReadPos;
1090             }
1091             memcpy(pch, &vch[nReadPos], nSize);
1092             nReadPos = 0;
1093             vch.clear();
1094             return (*this);
1095         }
1096         memcpy(pch, &vch[nReadPos], nSize);
1097         nReadPos = nReadPosNext;
1098         return (*this);
1099     }
1100
1101     CDataStream& ignore(int nSize)
1102     {
1103         // Ignore from the beginning of the buffer
1104         assert(nSize >= 0);
1105         unsigned int nReadPosNext = nReadPos + nSize;
1106         if (nReadPosNext >= vch.size())
1107         {
1108             if (nReadPosNext > vch.size())
1109             {
1110                 setstate(std::ios::failbit, "CDataStream::ignore() : end of data");
1111                 nSize = vch.size() - nReadPos;
1112             }
1113             nReadPos = 0;
1114             vch.clear();
1115             return (*this);
1116         }
1117         nReadPos = nReadPosNext;
1118         return (*this);
1119     }
1120
1121     CDataStream& write(const char* pch, int nSize)
1122     {
1123         // Write to the end of the buffer
1124         assert(nSize >= 0);
1125         vch.insert(vch.end(), pch, pch + nSize);
1126         return (*this);
1127     }
1128
1129     template<typename Stream>
1130     void Serialize(Stream& s, int nType=0, int nVersion=PROTOCOL_VERSION) const
1131     {
1132         // Special case: stream << stream concatenates like stream += stream
1133         if (!vch.empty())
1134             s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
1135     }
1136
1137     template<typename T>
1138     unsigned int GetSerializeSize(const T& obj)
1139     {
1140         // Tells the size of the object if serialized to this stream
1141         return ::GetSerializeSize(obj, nType, nVersion);
1142     }
1143
1144     template<typename T>
1145     CDataStream& operator<<(const T& obj)
1146     {
1147         // Serialize to this stream
1148         ::Serialize(*this, obj, nType, nVersion);
1149         return (*this);
1150     }
1151
1152     template<typename T>
1153     CDataStream& operator>>(T& obj)
1154     {
1155         // Unserialize from this stream
1156         ::Unserialize(*this, obj, nType, nVersion);
1157         return (*this);
1158     }
1159 };
1160
1161 #ifdef TESTCDATASTREAM
1162 // VC6sp6
1163 // CDataStream:
1164 // n=1000       0 seconds
1165 // n=2000       0 seconds
1166 // n=4000       0 seconds
1167 // n=8000       0 seconds
1168 // n=16000      0 seconds
1169 // n=32000      0 seconds
1170 // n=64000      1 seconds
1171 // n=128000     1 seconds
1172 // n=256000     2 seconds
1173 // n=512000     4 seconds
1174 // n=1024000    8 seconds
1175 // n=2048000    16 seconds
1176 // n=4096000    32 seconds
1177 // stringstream:
1178 // n=1000       1 seconds
1179 // n=2000       1 seconds
1180 // n=4000       13 seconds
1181 // n=8000       87 seconds
1182 // n=16000      400 seconds
1183 // n=32000      1660 seconds
1184 // n=64000      6749 seconds
1185 // n=128000     27241 seconds
1186 // n=256000     109804 seconds
1187 #include <iostream>
1188 int main(int argc, char *argv[])
1189 {
1190     vector<unsigned char> vch(0xcc, 250);
1191     printf("CDataStream:\n");
1192     for (int n = 1000; n <= 4500000; n *= 2)
1193     {
1194         CDataStream ss;
1195         time_t nStart = time(NULL);
1196         for (int i = 0; i < n; i++)
1197             ss.write((char*)&vch[0], vch.size());
1198         printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1199     }
1200     printf("stringstream:\n");
1201     for (int n = 1000; n <= 4500000; n *= 2)
1202     {
1203         stringstream ss;
1204         time_t nStart = time(NULL);
1205         for (int i = 0; i < n; i++)
1206             ss.write((char*)&vch[0], vch.size());
1207         printf("n=%-10d %d seconds\n", n, time(NULL) - nStart);
1208     }
1209 }
1210 #endif
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221 /** RAII wrapper for FILE*.
1222  *
1223  * Will automatically close the file when it goes out of scope if not null.
1224  * If you're returning the file pointer, return file.release().
1225  * If you need to close the file early, use file.fclose() instead of fclose(file).
1226  */
1227 class CAutoFile
1228 {
1229 protected:
1230     FILE* file;
1231     short state;
1232     short exceptmask;
1233 public:
1234     int nType;
1235     int nVersion;
1236
1237     CAutoFile(FILE* filenew=NULL, int nTypeIn=SER_DISK, int nVersionIn=PROTOCOL_VERSION)
1238     {
1239         file = filenew;
1240         nType = nTypeIn;
1241         nVersion = nVersionIn;
1242         state = 0;
1243         exceptmask = std::ios::badbit | std::ios::failbit;
1244     }
1245
1246     ~CAutoFile()
1247     {
1248         fclose();
1249     }
1250
1251     void fclose()
1252     {
1253         if (file != NULL && file != stdin && file != stdout && file != stderr)
1254             ::fclose(file);
1255         file = NULL;
1256     }
1257
1258     FILE* release()             { FILE* ret = file; file = NULL; return ret; }
1259     operator FILE*()            { return file; }
1260     FILE* operator->()          { return file; }
1261     FILE& operator*()           { return *file; }
1262     FILE** operator&()          { return &file; }
1263     FILE* operator=(FILE* pnew) { return file = pnew; }
1264     bool operator!()            { return (file == NULL); }
1265
1266
1267     //
1268     // Stream subset
1269     //
1270     void setstate(short bits, const char* psz)
1271     {
1272         state |= bits;
1273         if (state & exceptmask)
1274             throw std::ios_base::failure(psz);
1275     }
1276
1277     bool fail() const            { return state & (std::ios::badbit | std::ios::failbit); }
1278     bool good() const            { return state == 0; }
1279     void clear(short n = 0)      { state = n; }
1280     short exceptions()           { return exceptmask; }
1281     short exceptions(short mask) { short prev = exceptmask; exceptmask = mask; setstate(0, "CAutoFile"); return prev; }
1282
1283     void SetType(int n)          { nType = n; }
1284     int GetType()                { return nType; }
1285     void SetVersion(int n)       { nVersion = n; }
1286     int GetVersion()             { return nVersion; }
1287     void ReadVersion()           { *this >> nVersion; }
1288     void WriteVersion()          { *this << nVersion; }
1289
1290     CAutoFile& read(char* pch, int nSize)
1291     {
1292         if (!file)
1293             throw std::ios_base::failure("CAutoFile::read : file handle is NULL");
1294         if (fread(pch, 1, nSize, file) != nSize)
1295             setstate(std::ios::failbit, feof(file) ? "CAutoFile::read : end of file" : "CAutoFile::read : fread failed");
1296         return (*this);
1297     }
1298
1299     CAutoFile& write(const char* pch, int nSize)
1300     {
1301         if (!file)
1302             throw std::ios_base::failure("CAutoFile::write : file handle is NULL");
1303         if (fwrite(pch, 1, nSize, file) != nSize)
1304             setstate(std::ios::failbit, "CAutoFile::write : write failed");
1305         return (*this);
1306     }
1307
1308     template<typename T>
1309     unsigned int GetSerializeSize(const T& obj)
1310     {
1311         // Tells the size of the object if serialized to this stream
1312         return ::GetSerializeSize(obj, nType, nVersion);
1313     }
1314
1315     template<typename T>
1316     CAutoFile& operator<<(const T& obj)
1317     {
1318         // Serialize to this stream
1319         if (!file)
1320             throw std::ios_base::failure("CAutoFile::operator<< : file handle is NULL");
1321         ::Serialize(*this, obj, nType, nVersion);
1322         return (*this);
1323     }
1324
1325     template<typename T>
1326     CAutoFile& operator>>(T& obj)
1327     {
1328         // Unserialize from this stream
1329         if (!file)
1330             throw std::ios_base::failure("CAutoFile::operator>> : file handle is NULL");
1331         ::Unserialize(*this, obj, nType, nVersion);
1332         return (*this);
1333     }
1334 };
1335
1336 #endif