Bitcoin Core  0.19.99
P2P Digital Currency
serialize.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2018 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5 
6 #ifndef BITCOIN_SERIALIZE_H
7 #define BITCOIN_SERIALIZE_H
8 
9 #include <compat/endian.h>
10 
11 #include <algorithm>
12 #include <ios>
13 #include <limits>
14 #include <map>
15 #include <memory>
16 #include <set>
17 #include <stdint.h>
18 #include <string>
19 #include <string.h>
20 #include <utility>
21 #include <vector>
22 
23 #include <prevector.h>
24 #include <span.h>
25 
26 static const unsigned int MAX_SIZE = 0x02000000;
27 
39 struct deserialize_type {};
41 
46 template<typename T>
47 inline T& REF(const T& val)
48 {
49  return const_cast<T&>(val);
50 }
51 
56 template<typename T>
57 inline T* NCONST_PTR(const T* val)
58 {
59  return const_cast<T*>(val);
60 }
61 
63 inline char* CharCast(char* c) { return c; }
64 inline char* CharCast(unsigned char* c) { return (char*)c; }
65 inline const char* CharCast(const char* c) { return c; }
66 inline const char* CharCast(const unsigned char* c) { return (const char*)c; }
67 
68 /*
69  * Lowest-level serialization and conversion.
70  * @note Sizes of these types are verified in the tests
71  */
72 template<typename Stream> inline void ser_writedata8(Stream &s, uint8_t obj)
73 {
74  s.write((char*)&obj, 1);
75 }
76 template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj)
77 {
78  obj = htole16(obj);
79  s.write((char*)&obj, 2);
80 }
81 template<typename Stream> inline void ser_writedata16be(Stream &s, uint16_t obj)
82 {
83  obj = htobe16(obj);
84  s.write((char*)&obj, 2);
85 }
86 template<typename Stream> inline void ser_writedata32(Stream &s, uint32_t obj)
87 {
88  obj = htole32(obj);
89  s.write((char*)&obj, 4);
90 }
91 template<typename Stream> inline void ser_writedata32be(Stream &s, uint32_t obj)
92 {
93  obj = htobe32(obj);
94  s.write((char*)&obj, 4);
95 }
96 template<typename Stream> inline void ser_writedata64(Stream &s, uint64_t obj)
97 {
98  obj = htole64(obj);
99  s.write((char*)&obj, 8);
100 }
101 template<typename Stream> inline uint8_t ser_readdata8(Stream &s)
102 {
103  uint8_t obj;
104  s.read((char*)&obj, 1);
105  return obj;
106 }
107 template<typename Stream> inline uint16_t ser_readdata16(Stream &s)
108 {
109  uint16_t obj;
110  s.read((char*)&obj, 2);
111  return le16toh(obj);
112 }
113 template<typename Stream> inline uint16_t ser_readdata16be(Stream &s)
114 {
115  uint16_t obj;
116  s.read((char*)&obj, 2);
117  return be16toh(obj);
118 }
119 template<typename Stream> inline uint32_t ser_readdata32(Stream &s)
120 {
121  uint32_t obj;
122  s.read((char*)&obj, 4);
123  return le32toh(obj);
124 }
125 template<typename Stream> inline uint32_t ser_readdata32be(Stream &s)
126 {
127  uint32_t obj;
128  s.read((char*)&obj, 4);
129  return be32toh(obj);
130 }
131 template<typename Stream> inline uint64_t ser_readdata64(Stream &s)
132 {
133  uint64_t obj;
134  s.read((char*)&obj, 8);
135  return le64toh(obj);
136 }
137 inline uint64_t ser_double_to_uint64(double x)
138 {
139  union { double x; uint64_t y; } tmp;
140  tmp.x = x;
141  return tmp.y;
142 }
143 inline uint32_t ser_float_to_uint32(float x)
144 {
145  union { float x; uint32_t y; } tmp;
146  tmp.x = x;
147  return tmp.y;
148 }
149 inline double ser_uint64_to_double(uint64_t y)
150 {
151  union { double x; uint64_t y; } tmp;
152  tmp.y = y;
153  return tmp.x;
154 }
155 inline float ser_uint32_to_float(uint32_t y)
156 {
157  union { float x; uint32_t y; } tmp;
158  tmp.y = y;
159  return tmp.x;
160 }
161 
162 
164 //
165 // Templates for serializing to anything that looks like a stream,
166 // i.e. anything that supports .read(char*, size_t) and .write(char*, size_t)
167 //
168 
169 class CSizeComputer;
170 
171 enum
172 {
173  // primary actions
174  SER_NETWORK = (1 << 0),
175  SER_DISK = (1 << 1),
176  SER_GETHASH = (1 << 2),
177 };
178 
180 template<typename X> X& ReadWriteAsHelper(X& x) { return x; }
181 template<typename X> const X& ReadWriteAsHelper(const X& x) { return x; }
182 
183 #define READWRITE(...) (::SerReadWriteMany(s, ser_action, __VA_ARGS__))
184 #define READWRITEAS(type, obj) (::SerReadWriteMany(s, ser_action, ReadWriteAsHelper<type>(obj)))
185 
192 #define ADD_SERIALIZE_METHODS \
193  template<typename Stream> \
194  void Serialize(Stream& s) const { \
195  NCONST_PTR(this)->SerializationOp(s, CSerActionSerialize()); \
196  } \
197  template<typename Stream> \
198  void Unserialize(Stream& s) { \
199  SerializationOp(s, CSerActionUnserialize()); \
200  }
201 
202 #ifndef CHAR_EQUALS_INT8
203 template<typename Stream> inline void Serialize(Stream& s, char a ) { ser_writedata8(s, a); } // TODO Get rid of bare char
204 #endif
205 template<typename Stream> inline void Serialize(Stream& s, int8_t a ) { ser_writedata8(s, a); }
206 template<typename Stream> inline void Serialize(Stream& s, uint8_t a ) { ser_writedata8(s, a); }
207 template<typename Stream> inline void Serialize(Stream& s, int16_t a ) { ser_writedata16(s, a); }
208 template<typename Stream> inline void Serialize(Stream& s, uint16_t a) { ser_writedata16(s, a); }
209 template<typename Stream> inline void Serialize(Stream& s, int32_t a ) { ser_writedata32(s, a); }
210 template<typename Stream> inline void Serialize(Stream& s, uint32_t a) { ser_writedata32(s, a); }
211 template<typename Stream> inline void Serialize(Stream& s, int64_t a ) { ser_writedata64(s, a); }
212 template<typename Stream> inline void Serialize(Stream& s, uint64_t a) { ser_writedata64(s, a); }
213 template<typename Stream> inline void Serialize(Stream& s, float a ) { ser_writedata32(s, ser_float_to_uint32(a)); }
214 template<typename Stream> inline void Serialize(Stream& s, double a ) { ser_writedata64(s, ser_double_to_uint64(a)); }
215 template<typename Stream, int N> inline void Serialize(Stream& s, const char (&a)[N]) { s.write(a, N); }
216 template<typename Stream, int N> inline void Serialize(Stream& s, const unsigned char (&a)[N]) { s.write(CharCast(a), N); }
217 template<typename Stream> inline void Serialize(Stream& s, const Span<const unsigned char>& span) { s.write(CharCast(span.data()), span.size()); }
218 template<typename Stream> inline void Serialize(Stream& s, const Span<unsigned char>& span) { s.write(CharCast(span.data()), span.size()); }
219 
220 #ifndef CHAR_EQUALS_INT8
221 template<typename Stream> inline void Unserialize(Stream& s, char& a ) { a = ser_readdata8(s); } // TODO Get rid of bare char
222 #endif
223 template<typename Stream> inline void Unserialize(Stream& s, int8_t& a ) { a = ser_readdata8(s); }
224 template<typename Stream> inline void Unserialize(Stream& s, uint8_t& a ) { a = ser_readdata8(s); }
225 template<typename Stream> inline void Unserialize(Stream& s, int16_t& a ) { a = ser_readdata16(s); }
226 template<typename Stream> inline void Unserialize(Stream& s, uint16_t& a) { a = ser_readdata16(s); }
227 template<typename Stream> inline void Unserialize(Stream& s, int32_t& a ) { a = ser_readdata32(s); }
228 template<typename Stream> inline void Unserialize(Stream& s, uint32_t& a) { a = ser_readdata32(s); }
229 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a ) { a = ser_readdata64(s); }
230 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a) { a = ser_readdata64(s); }
231 template<typename Stream> inline void Unserialize(Stream& s, float& a ) { a = ser_uint32_to_float(ser_readdata32(s)); }
232 template<typename Stream> inline void Unserialize(Stream& s, double& a ) { a = ser_uint64_to_double(ser_readdata64(s)); }
233 template<typename Stream, int N> inline void Unserialize(Stream& s, char (&a)[N]) { s.read(a, N); }
234 template<typename Stream, int N> inline void Unserialize(Stream& s, unsigned char (&a)[N]) { s.read(CharCast(a), N); }
235 template<typename Stream> inline void Unserialize(Stream& s, Span<unsigned char>& span) { s.read(CharCast(span.data()), span.size()); }
236 
237 template<typename Stream> inline void Serialize(Stream& s, bool a) { char f=a; ser_writedata8(s, f); }
238 template<typename Stream> inline void Unserialize(Stream& s, bool& a) { char f=ser_readdata8(s); a=f; }
239 
240 
241 
242 
243 
244 
252 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
253 {
254  if (nSize < 253) return sizeof(unsigned char);
255  else if (nSize <= std::numeric_limits<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
256  else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
257  else return sizeof(unsigned char) + sizeof(uint64_t);
258 }
259 
260 inline void WriteCompactSize(CSizeComputer& os, uint64_t nSize);
261 
262 template<typename Stream>
263 void WriteCompactSize(Stream& os, uint64_t nSize)
264 {
265  if (nSize < 253)
266  {
267  ser_writedata8(os, nSize);
268  }
269  else if (nSize <= std::numeric_limits<unsigned short>::max())
270  {
271  ser_writedata8(os, 253);
272  ser_writedata16(os, nSize);
273  }
274  else if (nSize <= std::numeric_limits<unsigned int>::max())
275  {
276  ser_writedata8(os, 254);
277  ser_writedata32(os, nSize);
278  }
279  else
280  {
281  ser_writedata8(os, 255);
282  ser_writedata64(os, nSize);
283  }
284  return;
285 }
286 
287 template<typename Stream>
288 uint64_t ReadCompactSize(Stream& is)
289 {
290  uint8_t chSize = ser_readdata8(is);
291  uint64_t nSizeRet = 0;
292  if (chSize < 253)
293  {
294  nSizeRet = chSize;
295  }
296  else if (chSize == 253)
297  {
298  nSizeRet = ser_readdata16(is);
299  if (nSizeRet < 253)
300  throw std::ios_base::failure("non-canonical ReadCompactSize()");
301  }
302  else if (chSize == 254)
303  {
304  nSizeRet = ser_readdata32(is);
305  if (nSizeRet < 0x10000u)
306  throw std::ios_base::failure("non-canonical ReadCompactSize()");
307  }
308  else
309  {
310  nSizeRet = ser_readdata64(is);
311  if (nSizeRet < 0x100000000ULL)
312  throw std::ios_base::failure("non-canonical ReadCompactSize()");
313  }
314  if (nSizeRet > (uint64_t)MAX_SIZE)
315  throw std::ios_base::failure("ReadCompactSize(): size too large");
316  return nSizeRet;
317 }
318 
354 
355 template <VarIntMode Mode, typename I>
357  constexpr CheckVarIntMode()
358  {
359  static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned<I>::value, "Unsigned type required with mode DEFAULT.");
360  static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed<I>::value, "Signed type required with mode NONNEGATIVE_SIGNED.");
361  }
362 };
363 
364 template<VarIntMode Mode, typename I>
365 inline unsigned int GetSizeOfVarInt(I n)
366 {
368  int nRet = 0;
369  while(true) {
370  nRet++;
371  if (n <= 0x7F)
372  break;
373  n = (n >> 7) - 1;
374  }
375  return nRet;
376 }
377 
378 template<typename I>
379 inline void WriteVarInt(CSizeComputer& os, I n);
380 
381 template<typename Stream, VarIntMode Mode, typename I>
382 void WriteVarInt(Stream& os, I n)
383 {
385  unsigned char tmp[(sizeof(n)*8+6)/7];
386  int len=0;
387  while(true) {
388  tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
389  if (n <= 0x7F)
390  break;
391  n = (n >> 7) - 1;
392  len++;
393  }
394  do {
395  ser_writedata8(os, tmp[len]);
396  } while(len--);
397 }
398 
399 template<typename Stream, VarIntMode Mode, typename I>
400 I ReadVarInt(Stream& is)
401 {
403  I n = 0;
404  while(true) {
405  unsigned char chData = ser_readdata8(is);
406  if (n > (std::numeric_limits<I>::max() >> 7)) {
407  throw std::ios_base::failure("ReadVarInt(): size too large");
408  }
409  n = (n << 7) | (chData & 0x7F);
410  if (chData & 0x80) {
411  if (n == std::numeric_limits<I>::max()) {
412  throw std::ios_base::failure("ReadVarInt(): size too large");
413  }
414  n++;
415  } else {
416  return n;
417  }
418  }
419 }
420 
421 #define VARINT(obj, ...) WrapVarInt<__VA_ARGS__>(REF(obj))
422 #define COMPACTSIZE(obj) CCompactSize(REF(obj))
423 #define LIMITED_STRING(obj,n) LimitedString< n >(REF(obj))
424 
425 template<VarIntMode Mode, typename I>
426 class CVarInt
427 {
428 protected:
429  I &n;
430 public:
431  explicit CVarInt(I& nIn) : n(nIn) { }
432 
433  template<typename Stream>
434  void Serialize(Stream &s) const {
435  WriteVarInt<Stream,Mode,I>(s, n);
436  }
437 
438  template<typename Stream>
439  void Unserialize(Stream& s) {
440  n = ReadVarInt<Stream,Mode,I>(s);
441  }
442 };
443 
453 template<typename I>
455 {
456 protected:
457  I& m_val;
458 public:
459  explicit BigEndian(I& val) : m_val(val)
460  {
461  static_assert(std::is_unsigned<I>::value, "BigEndian type must be unsigned integer");
462  static_assert(sizeof(I) == 2 && std::numeric_limits<I>::min() == 0 && std::numeric_limits<I>::max() == std::numeric_limits<uint16_t>::max(), "Unsupported BigEndian size");
463  }
464 
465  template<typename Stream>
466  void Serialize(Stream& s) const
467  {
468  ser_writedata16be(s, m_val);
469  }
470 
471  template<typename Stream>
472  void Unserialize(Stream& s)
473  {
474  m_val = ser_readdata16be(s);
475  }
476 };
477 
479 {
480 protected:
481  uint64_t &n;
482 public:
483  explicit CCompactSize(uint64_t& nIn) : n(nIn) { }
484 
485  template<typename Stream>
486  void Serialize(Stream &s) const {
487  WriteCompactSize<Stream>(s, n);
488  }
489 
490  template<typename Stream>
491  void Unserialize(Stream& s) {
492  n = ReadCompactSize<Stream>(s);
493  }
494 };
495 
496 template<size_t Limit>
498 {
499 protected:
500  std::string& string;
501 public:
502  explicit LimitedString(std::string& _string) : string(_string) {}
503 
504  template<typename Stream>
505  void Unserialize(Stream& s)
506  {
507  size_t size = ReadCompactSize(s);
508  if (size > Limit) {
509  throw std::ios_base::failure("String length limit exceeded");
510  }
511  string.resize(size);
512  if (size != 0)
513  s.read((char*)string.data(), size);
514  }
515 
516  template<typename Stream>
517  void Serialize(Stream& s) const
518  {
519  WriteCompactSize(s, string.size());
520  if (!string.empty())
521  s.write((char*)string.data(), string.size());
522  }
523 };
524 
525 template<VarIntMode Mode=VarIntMode::DEFAULT, typename I>
527 
528 template<typename I>
530 
538 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
539 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
540 
545 template<typename Stream, unsigned int N, typename T> void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&);
546 template<typename Stream, unsigned int N, typename T, typename V> void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&);
547 template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
548 template<typename Stream, unsigned int N, typename T> void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&);
549 template<typename Stream, unsigned int N, typename T, typename V> void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&);
550 template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
551 
556 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&);
557 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&);
558 template<typename Stream, typename T, typename A, typename V> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&);
559 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
560 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&);
561 template<typename Stream, typename T, typename A, typename V> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&);
562 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
563 
567 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item);
568 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item);
569 
573 template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
574 template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
575 
579 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m);
580 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m);
581 
585 template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p);
586 template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p);
587 
591 template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p);
592 template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p);
593 
594 
595 
599 template<typename Stream, typename T>
600 inline void Serialize(Stream& os, const T& a)
601 {
602  a.Serialize(os);
603 }
604 
605 template<typename Stream, typename T>
606 inline void Unserialize(Stream& is, T&& a)
607 {
608  a.Unserialize(is);
609 }
610 
611 
612 
613 
614 
618 template<typename Stream, typename C>
619 void Serialize(Stream& os, const std::basic_string<C>& str)
620 {
621  WriteCompactSize(os, str.size());
622  if (!str.empty())
623  os.write((char*)str.data(), str.size() * sizeof(C));
624 }
625 
626 template<typename Stream, typename C>
627 void Unserialize(Stream& is, std::basic_string<C>& str)
628 {
629  unsigned int nSize = ReadCompactSize(is);
630  str.resize(nSize);
631  if (nSize != 0)
632  is.read((char*)str.data(), nSize * sizeof(C));
633 }
634 
635 
636 
640 template<typename Stream, unsigned int N, typename T>
641 void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&)
642 {
643  WriteCompactSize(os, v.size());
644  if (!v.empty())
645  os.write((char*)v.data(), v.size() * sizeof(T));
646 }
647 
648 template<typename Stream, unsigned int N, typename T, typename V>
649 void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&)
650 {
651  WriteCompactSize(os, v.size());
652  for (typename prevector<N, T>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
653  ::Serialize(os, (*vi));
654 }
655 
656 template<typename Stream, unsigned int N, typename T>
657 inline void Serialize(Stream& os, const prevector<N, T>& v)
658 {
659  Serialize_impl(os, v, T());
660 }
661 
662 
663 template<typename Stream, unsigned int N, typename T>
664 void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&)
665 {
666  // Limit size per read so bogus size value won't cause out of memory
667  v.clear();
668  unsigned int nSize = ReadCompactSize(is);
669  unsigned int i = 0;
670  while (i < nSize)
671  {
672  unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
673  v.resize_uninitialized(i + blk);
674  is.read((char*)&v[i], blk * sizeof(T));
675  i += blk;
676  }
677 }
678 
679 template<typename Stream, unsigned int N, typename T, typename V>
680 void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&)
681 {
682  v.clear();
683  unsigned int nSize = ReadCompactSize(is);
684  unsigned int i = 0;
685  unsigned int nMid = 0;
686  while (nMid < nSize)
687  {
688  nMid += 5000000 / sizeof(T);
689  if (nMid > nSize)
690  nMid = nSize;
691  v.resize_uninitialized(nMid);
692  for (; i < nMid; ++i)
693  Unserialize(is, v[i]);
694  }
695 }
696 
697 template<typename Stream, unsigned int N, typename T>
698 inline void Unserialize(Stream& is, prevector<N, T>& v)
699 {
700  Unserialize_impl(is, v, T());
701 }
702 
703 
704 
708 template<typename Stream, typename T, typename A>
709 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&)
710 {
711  WriteCompactSize(os, v.size());
712  if (!v.empty())
713  os.write((char*)v.data(), v.size() * sizeof(T));
714 }
715 
716 template<typename Stream, typename T, typename A>
717 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&)
718 {
719  // A special case for std::vector<bool>, as dereferencing
720  // std::vector<bool>::const_iterator does not result in a const bool&
721  // due to std::vector's special casing for bool arguments.
722  WriteCompactSize(os, v.size());
723  for (bool elem : v) {
724  ::Serialize(os, elem);
725  }
726 }
727 
728 template<typename Stream, typename T, typename A, typename V>
729 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&)
730 {
731  WriteCompactSize(os, v.size());
732  for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
733  ::Serialize(os, (*vi));
734 }
735 
736 template<typename Stream, typename T, typename A>
737 inline void Serialize(Stream& os, const std::vector<T, A>& v)
738 {
739  Serialize_impl(os, v, T());
740 }
741 
742 
743 template<typename Stream, typename T, typename A>
744 void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&)
745 {
746  // Limit size per read so bogus size value won't cause out of memory
747  v.clear();
748  unsigned int nSize = ReadCompactSize(is);
749  unsigned int i = 0;
750  while (i < nSize)
751  {
752  unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
753  v.resize(i + blk);
754  is.read((char*)&v[i], blk * sizeof(T));
755  i += blk;
756  }
757 }
758 
759 template<typename Stream, typename T, typename A, typename V>
760 void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&)
761 {
762  v.clear();
763  unsigned int nSize = ReadCompactSize(is);
764  unsigned int i = 0;
765  unsigned int nMid = 0;
766  while (nMid < nSize)
767  {
768  nMid += 5000000 / sizeof(T);
769  if (nMid > nSize)
770  nMid = nSize;
771  v.resize(nMid);
772  for (; i < nMid; i++)
773  Unserialize(is, v[i]);
774  }
775 }
776 
777 template<typename Stream, typename T, typename A>
778 inline void Unserialize(Stream& is, std::vector<T, A>& v)
779 {
780  Unserialize_impl(is, v, T());
781 }
782 
783 
784 
788 template<typename Stream, typename K, typename T>
789 void Serialize(Stream& os, const std::pair<K, T>& item)
790 {
791  Serialize(os, item.first);
792  Serialize(os, item.second);
793 }
794 
795 template<typename Stream, typename K, typename T>
796 void Unserialize(Stream& is, std::pair<K, T>& item)
797 {
798  Unserialize(is, item.first);
799  Unserialize(is, item.second);
800 }
801 
802 
803 
807 template<typename Stream, typename K, typename T, typename Pred, typename A>
808 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
809 {
810  WriteCompactSize(os, m.size());
811  for (const auto& entry : m)
812  Serialize(os, entry);
813 }
814 
815 template<typename Stream, typename K, typename T, typename Pred, typename A>
816 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
817 {
818  m.clear();
819  unsigned int nSize = ReadCompactSize(is);
820  typename std::map<K, T, Pred, A>::iterator mi = m.begin();
821  for (unsigned int i = 0; i < nSize; i++)
822  {
823  std::pair<K, T> item;
824  Unserialize(is, item);
825  mi = m.insert(mi, item);
826  }
827 }
828 
829 
830 
834 template<typename Stream, typename K, typename Pred, typename A>
835 void Serialize(Stream& os, const std::set<K, Pred, A>& m)
836 {
837  WriteCompactSize(os, m.size());
838  for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
839  Serialize(os, (*it));
840 }
841 
842 template<typename Stream, typename K, typename Pred, typename A>
843 void Unserialize(Stream& is, std::set<K, Pred, A>& m)
844 {
845  m.clear();
846  unsigned int nSize = ReadCompactSize(is);
847  typename std::set<K, Pred, A>::iterator it = m.begin();
848  for (unsigned int i = 0; i < nSize; i++)
849  {
850  K key;
851  Unserialize(is, key);
852  it = m.insert(it, key);
853  }
854 }
855 
856 
857 
861 template<typename Stream, typename T> void
862 Serialize(Stream& os, const std::unique_ptr<const T>& p)
863 {
864  Serialize(os, *p);
865 }
866 
867 template<typename Stream, typename T>
868 void Unserialize(Stream& is, std::unique_ptr<const T>& p)
869 {
870  p.reset(new T(deserialize, is));
871 }
872 
873 
874 
878 template<typename Stream, typename T> void
879 Serialize(Stream& os, const std::shared_ptr<const T>& p)
880 {
881  Serialize(os, *p);
882 }
883 
884 template<typename Stream, typename T>
885 void Unserialize(Stream& is, std::shared_ptr<const T>& p)
886 {
887  p = std::make_shared<const T>(deserialize, is);
888 }
889 
890 
891 
896 {
897  constexpr bool ForRead() const { return false; }
898 };
900 {
901  constexpr bool ForRead() const { return true; }
902 };
903 
904 
905 
906 
907 
908 
909 
910 
911 /* ::GetSerializeSize implementations
912  *
913  * Computing the serialized size of objects is done through a special stream
914  * object of type CSizeComputer, which only records the number of bytes written
915  * to it.
916  *
917  * If your Serialize or SerializationOp method has non-trivial overhead for
918  * serialization, it may be worthwhile to implement a specialized version for
919  * CSizeComputer, which uses the s.seek() method to record bytes that would
920  * be written instead.
921  */
923 {
924 protected:
925  size_t nSize;
926 
927  const int nVersion;
928 public:
929  explicit CSizeComputer(int nVersionIn) : nSize(0), nVersion(nVersionIn) {}
930 
931  void write(const char *psz, size_t _nSize)
932  {
933  this->nSize += _nSize;
934  }
935 
937  void seek(size_t _nSize)
938  {
939  this->nSize += _nSize;
940  }
941 
942  template<typename T>
943  CSizeComputer& operator<<(const T& obj)
944  {
945  ::Serialize(*this, obj);
946  return (*this);
947  }
948 
949  size_t size() const {
950  return nSize;
951  }
952 
953  int GetVersion() const { return nVersion; }
954 };
955 
956 template<typename Stream>
957 void SerializeMany(Stream& s)
958 {
959 }
960 
961 template<typename Stream, typename Arg, typename... Args>
962 void SerializeMany(Stream& s, const Arg& arg, const Args&... args)
963 {
964  ::Serialize(s, arg);
965  ::SerializeMany(s, args...);
966 }
967 
968 template<typename Stream>
969 inline void UnserializeMany(Stream& s)
970 {
971 }
972 
973 template<typename Stream, typename Arg, typename... Args>
974 inline void UnserializeMany(Stream& s, Arg&& arg, Args&&... args)
975 {
976  ::Unserialize(s, arg);
977  ::UnserializeMany(s, args...);
978 }
979 
980 template<typename Stream, typename... Args>
981 inline void SerReadWriteMany(Stream& s, CSerActionSerialize ser_action, const Args&... args)
982 {
983  ::SerializeMany(s, args...);
984 }
985 
986 template<typename Stream, typename... Args>
987 inline void SerReadWriteMany(Stream& s, CSerActionUnserialize ser_action, Args&&... args)
988 {
989  ::UnserializeMany(s, args...);
990 }
991 
992 template<typename I>
993 inline void WriteVarInt(CSizeComputer &s, I n)
994 {
995  s.seek(GetSizeOfVarInt<I>(n));
996 }
997 
998 inline void WriteCompactSize(CSizeComputer &s, uint64_t nSize)
999 {
1000  s.seek(GetSizeOfCompactSize(nSize));
1001 }
1002 
1003 template <typename T>
1004 size_t GetSerializeSize(const T& t, int nVersion = 0)
1005 {
1006  return (CSizeComputer(nVersion) << t).size();
1007 }
1008 
1009 template <typename... T>
1010 size_t GetSerializeSizeMany(int nVersion, const T&... t)
1011 {
1012  CSizeComputer sc(nVersion);
1013  SerializeMany(sc, t...);
1014  return sc.size();
1015 }
1016 
1017 #endif // BITCOIN_SERIALIZE_H
uint64_t ser_double_to_uint64(double x)
Definition: serialize.h:137
CSizeComputer(int nVersionIn)
Definition: serialize.h:929
std::string & string
Definition: serialize.h:500
X & ReadWriteAsHelper(X &x)
Convert the reference base type to X, without changing constness or reference type.
Definition: serialize.h:180
void Unserialize(Stream &s)
Definition: serialize.h:439
constexpr std::ptrdiff_t size() const noexcept
Definition: span.h:30
uint32_t ser_float_to_uint32(float x)
Definition: serialize.h:143
uint8_t ser_readdata8(Stream &s)
Definition: serialize.h:101
void clear()
Definition: prevector.h:337
void ser_writedata64(Stream &s, uint64_t obj)
Definition: serialize.h:96
uint64_t & n
Definition: serialize.h:481
uint64_t ReadCompactSize(Stream &is)
Definition: serialize.h:288
void WriteVarInt(CSizeComputer &os, I n)
Definition: serialize.h:993
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:998
size_t size() const
Definition: serialize.h:949
void ser_writedata32(Stream &s, uint32_t obj)
Definition: serialize.h:86
constexpr deserialize_type deserialize
Definition: serialize.h:40
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 ...
Definition: serialize.h:252
CCompactSize(uint64_t &nIn)
Definition: serialize.h:483
void Unserialize(Stream &s)
Definition: serialize.h:491
uint32_t be32toh(uint32_t big_endian_32bits)
Definition: endian.h:198
void resize_uninitialized(size_type new_size)
Definition: prevector.h:380
BigEndian(I &val)
Definition: serialize.h:459
const int nVersion
Definition: serialize.h:927
void UnserializeMany(Stream &s)
Definition: serialize.h:969
BigEndian< I > WrapBigEndian(I &n)
Definition: serialize.h:529
uint32_t htole32(uint32_t host_32bits)
Definition: endian.h:191
Dummy data type to identify deserializing constructors.
Definition: serialize.h:39
char * CharCast(char *c)
Safely convert odd char pointer types to standard ones.
Definition: serialize.h:63
value_type * data()
Definition: prevector.h:517
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1004
void Serialize(Stream &s, char a)
Definition: serialize.h:203
uint32_t htobe32(uint32_t host_32bits)
Definition: endian.h:184
CVarInt< Mode, I > WrapVarInt(I &n)
Definition: serialize.h:526
void Unserialize(Stream &s)
Definition: serialize.h:505
CSizeComputer & operator<<(const T &obj)
Definition: serialize.h:943
iterator end()
Definition: prevector.h:286
void Serialize(Stream &s) const
Definition: serialize.h:517
void SerReadWriteMany(Stream &s, CSerActionSerialize ser_action, const Args &... args)
Definition: serialize.h:981
uint16_t ser_readdata16(Stream &s)
Definition: serialize.h:107
uint32_t ser_readdata32(Stream &s)
Definition: serialize.h:119
void Serialize(Stream &s) const
Definition: serialize.h:486
Serialization wrapper class for big-endian integers.
Definition: serialize.h:454
constexpr CheckVarIntMode()
Definition: serialize.h:357
void ser_writedata16(Stream &s, uint16_t obj)
Definition: serialize.h:76
uint16_t htobe16(uint16_t host_16bits)
Definition: endian.h:156
constexpr bool ForRead() const
Definition: serialize.h:901
I & n
Definition: serialize.h:429
VarIntMode
Variable-length integers: bytes are a MSB base-128 encoding of the number.
Definition: serialize.h:353
I ReadVarInt(Stream &is)
Definition: serialize.h:400
uint16_t le16toh(uint16_t little_endian_16bits)
Definition: endian.h:177
void ser_writedata32be(Stream &s, uint32_t obj)
Definition: serialize.h:91
double ser_uint64_to_double(uint64_t y)
Definition: serialize.h:149
Support for ADD_SERIALIZE_METHODS and READWRITE macro.
Definition: serialize.h:895
constexpr bool ForRead() const
Definition: serialize.h:897
void SerializeMany(Stream &s)
Definition: serialize.h:957
Implements a drop-in replacement for std::vector<T> which stores up to N elements directly (without h...
Definition: prevector.h:37
uint64_t ser_readdata64(Stream &s)
Definition: serialize.h:131
CVarInt(I &nIn)
Definition: serialize.h:431
#define X(name)
Definition: net.cpp:495
void seek(size_t _nSize)
Pretend _nSize bytes are written, without specifying them.
Definition: serialize.h:937
uint16_t htole16(uint16_t host_16bits)
Definition: endian.h:163
uint16_t ser_readdata16be(Stream &s)
Definition: serialize.h:113
static const unsigned int MAX_SIZE
Definition: serialize.h:26
uint64_t le64toh(uint64_t little_endian_64bits)
Definition: endian.h:233
uint16_t be16toh(uint16_t big_endian_16bits)
Definition: endian.h:170
constexpr C * data() const noexcept
Definition: span.h:27
int GetVersion() const
Definition: serialize.h:953
void Unserialize(Stream &s)
Definition: serialize.h:472
bool empty() const
Definition: prevector.h:280
uint64_t htole64(uint64_t host_64bits)
Definition: endian.h:219
void write(const char *psz, size_t _nSize)
Definition: serialize.h:931
void Serialize(Stream &s) const
Definition: serialize.h:434
uint32_t ser_readdata32be(Stream &s)
Definition: serialize.h:125
unsigned int GetSizeOfVarInt(I n)
Definition: serialize.h:365
size_t GetSerializeSizeMany(int nVersion, const T &... t)
Definition: serialize.h:1010
I & m_val
Definition: serialize.h:457
void Unserialize(Stream &s, char &a)
Definition: serialize.h:221
iterator begin()
Definition: prevector.h:284
void ser_writedata16be(Stream &s, uint16_t obj)
Definition: serialize.h:81
size_type size() const
Definition: prevector.h:276
void Serialize(Stream &s) const
Definition: serialize.h:466
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:17
void Serialize_impl(Stream &os, const prevector< N, T > &v, const unsigned char &)
prevector prevectors of unsigned char are a special case and are intended to be serialized as a singl...
Definition: serialize.h:641
T * NCONST_PTR(const T *val)
Used to acquire a non-const pointer "this" to generate bodies of const serialization operations from ...
Definition: serialize.h:57
void Unserialize_impl(Stream &is, prevector< N, T > &v, const unsigned char &)
Definition: serialize.h:664
auto it
Definition: validation.cpp:365
uint32_t le32toh(uint32_t little_endian_32bits)
Definition: endian.h:205
T & REF(const T &val)
Used to bypass the rule against non-const reference to temporary where it makes sense with wrappers...
Definition: serialize.h:47
size_t nSize
Definition: serialize.h:925
LimitedString(std::string &_string)
Definition: serialize.h:502
void ser_writedata8(Stream &s, uint8_t obj)
Definition: serialize.h:72
float ser_uint32_to_float(uint32_t y)
Definition: serialize.h:155