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