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