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