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