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