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