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