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