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