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