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