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