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