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