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