upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

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