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