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