Bitcoin Core  0.20.99
P2P Digital Currency
serialize.h
Go to the documentation of this file.
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2020 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 <cstdint>
13 #include <cstring>
14 #include <ios>
15 #include <limits>
16 #include <map>
17 #include <memory>
18 #include <set>
19 #include <string>
20 #include <string.h>
21 #include <utility>
22 #include <vector>
23 
24 #include <prevector.h>
25 #include <span.h>
26 
31 static constexpr uint64_t MAX_SIZE = 0x02000000;
32 
34 static const unsigned int MAX_VECTOR_ALLOCATE = 5000000;
35 
47 struct deserialize_type {};
49 
51 inline char* CharCast(char* c) { return c; }
52 inline char* CharCast(unsigned char* c) { return (char*)c; }
53 inline const char* CharCast(const char* c) { return c; }
54 inline const char* CharCast(const unsigned char* c) { return (const char*)c; }
55 
56 /*
57  * Lowest-level serialization and conversion.
58  * @note Sizes of these types are verified in the tests
59  */
60 template<typename Stream> inline void ser_writedata8(Stream &s, uint8_t obj)
61 {
62  s.write((char*)&obj, 1);
63 }
64 template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj)
65 {
66  obj = htole16(obj);
67  s.write((char*)&obj, 2);
68 }
69 template<typename Stream> inline void ser_writedata16be(Stream &s, uint16_t obj)
70 {
71  obj = htobe16(obj);
72  s.write((char*)&obj, 2);
73 }
74 template<typename Stream> inline void ser_writedata32(Stream &s, uint32_t obj)
75 {
76  obj = htole32(obj);
77  s.write((char*)&obj, 4);
78 }
79 template<typename Stream> inline void ser_writedata32be(Stream &s, uint32_t obj)
80 {
81  obj = htobe32(obj);
82  s.write((char*)&obj, 4);
83 }
84 template<typename Stream> inline void ser_writedata64(Stream &s, uint64_t obj)
85 {
86  obj = htole64(obj);
87  s.write((char*)&obj, 8);
88 }
89 template<typename Stream> inline uint8_t ser_readdata8(Stream &s)
90 {
91  uint8_t obj;
92  s.read((char*)&obj, 1);
93  return obj;
94 }
95 template<typename Stream> inline uint16_t ser_readdata16(Stream &s)
96 {
97  uint16_t obj;
98  s.read((char*)&obj, 2);
99  return le16toh(obj);
100 }
101 template<typename Stream> inline uint16_t ser_readdata16be(Stream &s)
102 {
103  uint16_t obj;
104  s.read((char*)&obj, 2);
105  return be16toh(obj);
106 }
107 template<typename Stream> inline uint32_t ser_readdata32(Stream &s)
108 {
109  uint32_t obj;
110  s.read((char*)&obj, 4);
111  return le32toh(obj);
112 }
113 template<typename Stream> inline uint32_t ser_readdata32be(Stream &s)
114 {
115  uint32_t obj;
116  s.read((char*)&obj, 4);
117  return be32toh(obj);
118 }
119 template<typename Stream> inline uint64_t ser_readdata64(Stream &s)
120 {
121  uint64_t obj;
122  s.read((char*)&obj, 8);
123  return le64toh(obj);
124 }
125 inline uint64_t ser_double_to_uint64(double x)
126 {
127  uint64_t tmp;
128  std::memcpy(&tmp, &x, sizeof(x));
129  static_assert(sizeof(tmp) == sizeof(x), "double and uint64_t assumed to have the same size");
130  return tmp;
131 }
132 inline uint32_t ser_float_to_uint32(float x)
133 {
134  uint32_t tmp;
135  std::memcpy(&tmp, &x, sizeof(x));
136  static_assert(sizeof(tmp) == sizeof(x), "float and uint32_t assumed to have the same size");
137  return tmp;
138 }
139 inline double ser_uint64_to_double(uint64_t y)
140 {
141  double tmp;
142  std::memcpy(&tmp, &y, sizeof(y));
143  static_assert(sizeof(tmp) == sizeof(y), "double and uint64_t assumed to have the same size");
144  return tmp;
145 }
146 inline float ser_uint32_to_float(uint32_t y)
147 {
148  float tmp;
149  std::memcpy(&tmp, &y, sizeof(y));
150  static_assert(sizeof(tmp) == sizeof(y), "float and uint32_t assumed to have the same size");
151  return tmp;
152 }
153 
154 
156 //
157 // Templates for serializing to anything that looks like a stream,
158 // i.e. anything that supports .read(char*, size_t) and .write(char*, size_t)
159 //
160 
161 class CSizeComputer;
162 
163 enum
164 {
165  // primary actions
166  SER_NETWORK = (1 << 0),
167  SER_DISK = (1 << 1),
168  SER_GETHASH = (1 << 2),
169 };
170 
172 template<typename X> X& ReadWriteAsHelper(X& x) { return x; }
173 template<typename X> const X& ReadWriteAsHelper(const X& x) { return x; }
174 
175 #define READWRITE(...) (::SerReadWriteMany(s, ser_action, __VA_ARGS__))
176 #define READWRITEAS(type, obj) (::SerReadWriteMany(s, ser_action, ReadWriteAsHelper<type>(obj)))
177 #define SER_READ(obj, code) ::SerRead(s, ser_action, obj, [&](Stream& s, typename std::remove_const<Type>::type& obj) { code; })
178 #define SER_WRITE(obj, code) ::SerWrite(s, ser_action, obj, [&](Stream& s, const Type& obj) { code; })
179 
196 #define FORMATTER_METHODS(cls, obj) \
197  template<typename Stream> \
198  static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, CSerActionSerialize()); } \
199  template<typename Stream> \
200  static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, CSerActionUnserialize()); } \
201  template<typename Stream, typename Type, typename Operation> \
202  static inline void SerializationOps(Type& obj, Stream& s, Operation ser_action) \
203 
204 
211 #define SERIALIZE_METHODS(cls, obj) \
212  template<typename Stream> \
213  void Serialize(Stream& s) const \
214  { \
215  static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \
216  Ser(s, *this); \
217  } \
218  template<typename Stream> \
219  void Unserialize(Stream& s) \
220  { \
221  static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch"); \
222  Unser(s, *this); \
223  } \
224  FORMATTER_METHODS(cls, obj)
225 
226 #ifndef CHAR_EQUALS_INT8
227 template<typename Stream> inline void Serialize(Stream& s, char a ) { ser_writedata8(s, a); } // TODO Get rid of bare char
228 #endif
229 template<typename Stream> inline void Serialize(Stream& s, int8_t a ) { ser_writedata8(s, a); }
230 template<typename Stream> inline void Serialize(Stream& s, uint8_t a ) { ser_writedata8(s, a); }
231 template<typename Stream> inline void Serialize(Stream& s, int16_t a ) { ser_writedata16(s, a); }
232 template<typename Stream> inline void Serialize(Stream& s, uint16_t a) { ser_writedata16(s, a); }
233 template<typename Stream> inline void Serialize(Stream& s, int32_t a ) { ser_writedata32(s, a); }
234 template<typename Stream> inline void Serialize(Stream& s, uint32_t a) { ser_writedata32(s, a); }
235 template<typename Stream> inline void Serialize(Stream& s, int64_t a ) { ser_writedata64(s, a); }
236 template<typename Stream> inline void Serialize(Stream& s, uint64_t a) { ser_writedata64(s, a); }
237 template<typename Stream> inline void Serialize(Stream& s, float a ) { ser_writedata32(s, ser_float_to_uint32(a)); }
238 template<typename Stream> inline void Serialize(Stream& s, double a ) { ser_writedata64(s, ser_double_to_uint64(a)); }
239 template<typename Stream, int N> inline void Serialize(Stream& s, const char (&a)[N]) { s.write(a, N); }
240 template<typename Stream, int N> inline void Serialize(Stream& s, const unsigned char (&a)[N]) { s.write(CharCast(a), N); }
241 template<typename Stream> inline void Serialize(Stream& s, const Span<const unsigned char>& span) { s.write(CharCast(span.data()), span.size()); }
242 template<typename Stream> inline void Serialize(Stream& s, const Span<unsigned char>& span) { s.write(CharCast(span.data()), span.size()); }
243 
244 #ifndef CHAR_EQUALS_INT8
245 template<typename Stream> inline void Unserialize(Stream& s, char& a ) { a = ser_readdata8(s); } // TODO Get rid of bare char
246 #endif
247 template<typename Stream> inline void Unserialize(Stream& s, int8_t& a ) { a = ser_readdata8(s); }
248 template<typename Stream> inline void Unserialize(Stream& s, uint8_t& a ) { a = ser_readdata8(s); }
249 template<typename Stream> inline void Unserialize(Stream& s, int16_t& a ) { a = ser_readdata16(s); }
250 template<typename Stream> inline void Unserialize(Stream& s, uint16_t& a) { a = ser_readdata16(s); }
251 template<typename Stream> inline void Unserialize(Stream& s, int32_t& a ) { a = ser_readdata32(s); }
252 template<typename Stream> inline void Unserialize(Stream& s, uint32_t& a) { a = ser_readdata32(s); }
253 template<typename Stream> inline void Unserialize(Stream& s, int64_t& a ) { a = ser_readdata64(s); }
254 template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a) { a = ser_readdata64(s); }
255 template<typename Stream> inline void Unserialize(Stream& s, float& a ) { a = ser_uint32_to_float(ser_readdata32(s)); }
256 template<typename Stream> inline void Unserialize(Stream& s, double& a ) { a = ser_uint64_to_double(ser_readdata64(s)); }
257 template<typename Stream, int N> inline void Unserialize(Stream& s, char (&a)[N]) { s.read(a, N); }
258 template<typename Stream, int N> inline void Unserialize(Stream& s, unsigned char (&a)[N]) { s.read(CharCast(a), N); }
259 template<typename Stream> inline void Unserialize(Stream& s, Span<unsigned char>& span) { s.read(CharCast(span.data()), span.size()); }
260 
261 template<typename Stream> inline void Serialize(Stream& s, bool a) { char f=a; ser_writedata8(s, f); }
262 template<typename Stream> inline void Unserialize(Stream& s, bool& a) { char f=ser_readdata8(s); a=f; }
263 
264 
265 
266 
267 
268 
276 inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
277 {
278  if (nSize < 253) return sizeof(unsigned char);
279  else if (nSize <= std::numeric_limits<uint16_t>::max()) return sizeof(unsigned char) + sizeof(uint16_t);
280  else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
281  else return sizeof(unsigned char) + sizeof(uint64_t);
282 }
283 
284 inline void WriteCompactSize(CSizeComputer& os, uint64_t nSize);
285 
286 template<typename Stream>
287 void WriteCompactSize(Stream& os, uint64_t nSize)
288 {
289  if (nSize < 253)
290  {
291  ser_writedata8(os, nSize);
292  }
293  else if (nSize <= std::numeric_limits<uint16_t>::max())
294  {
295  ser_writedata8(os, 253);
296  ser_writedata16(os, nSize);
297  }
298  else if (nSize <= std::numeric_limits<unsigned int>::max())
299  {
300  ser_writedata8(os, 254);
301  ser_writedata32(os, nSize);
302  }
303  else
304  {
305  ser_writedata8(os, 255);
306  ser_writedata64(os, nSize);
307  }
308  return;
309 }
310 
317 template<typename Stream>
318 uint64_t ReadCompactSize(Stream& is, bool range_check = true)
319 {
320  uint8_t chSize = ser_readdata8(is);
321  uint64_t nSizeRet = 0;
322  if (chSize < 253)
323  {
324  nSizeRet = chSize;
325  }
326  else if (chSize == 253)
327  {
328  nSizeRet = ser_readdata16(is);
329  if (nSizeRet < 253)
330  throw std::ios_base::failure("non-canonical ReadCompactSize()");
331  }
332  else if (chSize == 254)
333  {
334  nSizeRet = ser_readdata32(is);
335  if (nSizeRet < 0x10000u)
336  throw std::ios_base::failure("non-canonical ReadCompactSize()");
337  }
338  else
339  {
340  nSizeRet = ser_readdata64(is);
341  if (nSizeRet < 0x100000000ULL)
342  throw std::ios_base::failure("non-canonical ReadCompactSize()");
343  }
344  if (range_check && nSizeRet > MAX_SIZE) {
345  throw std::ios_base::failure("ReadCompactSize(): size too large");
346  }
347  return nSizeRet;
348 }
349 
385 
386 template <VarIntMode Mode, typename I>
388  constexpr CheckVarIntMode()
389  {
390  static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned<I>::value, "Unsigned type required with mode DEFAULT.");
391  static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed<I>::value, "Signed type required with mode NONNEGATIVE_SIGNED.");
392  }
393 };
394 
395 template<VarIntMode Mode, typename I>
396 inline unsigned int GetSizeOfVarInt(I n)
397 {
399  int nRet = 0;
400  while(true) {
401  nRet++;
402  if (n <= 0x7F)
403  break;
404  n = (n >> 7) - 1;
405  }
406  return nRet;
407 }
408 
409 template<typename I>
410 inline void WriteVarInt(CSizeComputer& os, I n);
411 
412 template<typename Stream, VarIntMode Mode, typename I>
413 void WriteVarInt(Stream& os, I n)
414 {
416  unsigned char tmp[(sizeof(n)*8+6)/7];
417  int len=0;
418  while(true) {
419  tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
420  if (n <= 0x7F)
421  break;
422  n = (n >> 7) - 1;
423  len++;
424  }
425  do {
426  ser_writedata8(os, tmp[len]);
427  } while(len--);
428 }
429 
430 template<typename Stream, VarIntMode Mode, typename I>
431 I ReadVarInt(Stream& is)
432 {
434  I n = 0;
435  while(true) {
436  unsigned char chData = ser_readdata8(is);
437  if (n > (std::numeric_limits<I>::max() >> 7)) {
438  throw std::ios_base::failure("ReadVarInt(): size too large");
439  }
440  n = (n << 7) | (chData & 0x7F);
441  if (chData & 0x80) {
442  if (n == std::numeric_limits<I>::max()) {
443  throw std::ios_base::failure("ReadVarInt(): size too large");
444  }
445  n++;
446  } else {
447  return n;
448  }
449  }
450 }
451 
453 template<typename Formatter, typename T>
454 class Wrapper
455 {
456  static_assert(std::is_lvalue_reference<T>::value, "Wrapper needs an lvalue reference type T");
457 protected:
458  T m_object;
459 public:
460  explicit Wrapper(T obj) : m_object(obj) {}
461  template<typename Stream> void Serialize(Stream &s) const { Formatter().Ser(s, m_object); }
462  template<typename Stream> void Unserialize(Stream &s) { Formatter().Unser(s, m_object); }
463 };
464 
475 template<typename Formatter, typename T>
476 static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&>(t); }
477 
478 #define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
479 #define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
480 #define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj)
481 #define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj)
482 
484 template<VarIntMode Mode>
486 {
487  template<typename Stream, typename I> void Ser(Stream &s, I v)
488  {
489  WriteVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s, v);
490  }
491 
492  template<typename Stream, typename I> void Unser(Stream& s, I& v)
493  {
494  v = ReadVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s);
495  }
496 };
497 
507 template<int Bytes, bool BigEndian = false>
509 {
510  static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range");
511  static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
512 
513  template <typename Stream, typename I> void Ser(Stream& s, I v)
514  {
515  if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range");
516  if (BigEndian) {
517  uint64_t raw = htobe64(v);
518  s.write(((const char*)&raw) + 8 - Bytes, Bytes);
519  } else {
520  uint64_t raw = htole64(v);
521  s.write((const char*)&raw, Bytes);
522  }
523  }
524 
525  template <typename Stream, typename I> void Unser(Stream& s, I& v)
526  {
527  using U = typename std::conditional<std::is_enum<I>::value, std::underlying_type<I>, std::common_type<I>>::type::type;
528  static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0, "Assigned type too small");
529  uint64_t raw = 0;
530  if (BigEndian) {
531  s.read(((char*)&raw) + 8 - Bytes, Bytes);
532  v = static_cast<I>(be64toh(raw));
533  } else {
534  s.read((char*)&raw, Bytes);
535  v = static_cast<I>(le64toh(raw));
536  }
537  }
538 };
539 
541 
543 template<bool RangeCheck>
545 {
546  template<typename Stream, typename I>
547  void Unser(Stream& s, I& v)
548  {
549  uint64_t n = ReadCompactSize<Stream>(s, RangeCheck);
550  if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
551  throw std::ios_base::failure("CompactSize exceeds limit of type");
552  }
553  v = n;
554  }
555 
556  template<typename Stream, typename I>
557  void Ser(Stream& s, I v)
558  {
559  static_assert(std::is_unsigned<I>::value, "CompactSize only supported for unsigned integers");
560  static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below");
561 
562  WriteCompactSize<Stream>(s, v);
563  }
564 };
565 
566 template<size_t Limit>
568 {
569  template<typename Stream>
570  void Unser(Stream& s, std::string& v)
571  {
572  size_t size = ReadCompactSize(s);
573  if (size > Limit) {
574  throw std::ios_base::failure("String length limit exceeded");
575  }
576  v.resize(size);
577  if (size != 0) s.read((char*)v.data(), size);
578  }
579 
580  template<typename Stream>
581  void Ser(Stream& s, const std::string& v)
582  {
583  s << v;
584  }
585 };
586 
600 template<class Formatter>
602 {
603  template<typename Stream, typename V>
604  void Ser(Stream& s, const V& v)
605  {
606  Formatter formatter;
607  WriteCompactSize(s, v.size());
608  for (const typename V::value_type& elem : v) {
609  formatter.Ser(s, elem);
610  }
611  }
612 
613  template<typename Stream, typename V>
614  void Unser(Stream& s, V& v)
615  {
616  Formatter formatter;
617  v.clear();
618  size_t size = ReadCompactSize(s);
619  size_t allocated = 0;
620  while (allocated < size) {
621  // For DoS prevention, do not blindly allocate as much as the stream claims to contain.
622  // Instead, allocate in 5MiB batches, so that an attacker actually needs to provide
623  // X MiB of data to make us allocate X+5 Mib.
624  static_assert(sizeof(typename V::value_type) <= MAX_VECTOR_ALLOCATE, "Vector element size too large");
625  allocated = std::min(size, allocated + MAX_VECTOR_ALLOCATE / sizeof(typename V::value_type));
626  v.reserve(allocated);
627  while (v.size() < allocated) {
628  v.emplace_back();
629  formatter.Unser(s, v.back());
630  }
631  }
632  };
633 };
634 
642 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
643 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
644 
649 template<typename Stream, unsigned int N, typename T> void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&);
650 template<typename Stream, unsigned int N, typename T, typename V> void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&);
651 template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
652 template<typename Stream, unsigned int N, typename T> void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&);
653 template<typename Stream, unsigned int N, typename T, typename V> void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&);
654 template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
655 
660 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&);
661 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&);
662 template<typename Stream, typename T, typename A, typename V> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&);
663 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
664 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&);
665 template<typename Stream, typename T, typename A, typename V> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&);
666 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
667 
671 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item);
672 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item);
673 
677 template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
678 template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
679 
683 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m);
684 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m);
685 
689 template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p);
690 template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p);
691 
695 template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p);
696 template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p);
697 
698 
699 
703 template<typename Stream, typename T>
704 inline void Serialize(Stream& os, const T& a)
705 {
706  a.Serialize(os);
707 }
708 
709 template<typename Stream, typename T>
710 inline void Unserialize(Stream& is, T&& a)
711 {
712  a.Unserialize(is);
713 }
714 
721 {
722  template<typename Stream, typename T>
723  static void Ser(Stream& s, const T& t) { Serialize(s, t); }
724 
725  template<typename Stream, typename T>
726  static void Unser(Stream& s, T& t) { Unserialize(s, t); }
727 };
728 
729 
730 
731 
732 
736 template<typename Stream, typename C>
737 void Serialize(Stream& os, const std::basic_string<C>& str)
738 {
739  WriteCompactSize(os, str.size());
740  if (!str.empty())
741  os.write((char*)str.data(), str.size() * sizeof(C));
742 }
743 
744 template<typename Stream, typename C>
745 void Unserialize(Stream& is, std::basic_string<C>& str)
746 {
747  unsigned int nSize = ReadCompactSize(is);
748  str.resize(nSize);
749  if (nSize != 0)
750  is.read((char*)str.data(), nSize * sizeof(C));
751 }
752 
753 
754 
758 template<typename Stream, unsigned int N, typename T>
759 void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&)
760 {
761  WriteCompactSize(os, v.size());
762  if (!v.empty())
763  os.write((char*)v.data(), v.size() * sizeof(T));
764 }
765 
766 template<typename Stream, unsigned int N, typename T, typename V>
767 void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&)
768 {
770 }
771 
772 template<typename Stream, unsigned int N, typename T>
773 inline void Serialize(Stream& os, const prevector<N, T>& v)
774 {
775  Serialize_impl(os, v, T());
776 }
777 
778 
779 template<typename Stream, unsigned int N, typename T>
780 void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&)
781 {
782  // Limit size per read so bogus size value won't cause out of memory
783  v.clear();
784  unsigned int nSize = ReadCompactSize(is);
785  unsigned int i = 0;
786  while (i < nSize)
787  {
788  unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
789  v.resize_uninitialized(i + blk);
790  is.read((char*)&v[i], blk * sizeof(T));
791  i += blk;
792  }
793 }
794 
795 template<typename Stream, unsigned int N, typename T, typename V>
796 void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&)
797 {
799 }
800 
801 template<typename Stream, unsigned int N, typename T>
802 inline void Unserialize(Stream& is, prevector<N, T>& v)
803 {
804  Unserialize_impl(is, v, T());
805 }
806 
807 
808 
812 template<typename Stream, typename T, typename A>
813 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&)
814 {
815  WriteCompactSize(os, v.size());
816  if (!v.empty())
817  os.write((char*)v.data(), v.size() * sizeof(T));
818 }
819 
820 template<typename Stream, typename T, typename A>
821 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&)
822 {
823  // A special case for std::vector<bool>, as dereferencing
824  // std::vector<bool>::const_iterator does not result in a const bool&
825  // due to std::vector's special casing for bool arguments.
826  WriteCompactSize(os, v.size());
827  for (bool elem : v) {
828  ::Serialize(os, elem);
829  }
830 }
831 
832 template<typename Stream, typename T, typename A, typename V>
833 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&)
834 {
836 }
837 
838 template<typename Stream, typename T, typename A>
839 inline void Serialize(Stream& os, const std::vector<T, A>& v)
840 {
841  Serialize_impl(os, v, T());
842 }
843 
844 
845 template<typename Stream, typename T, typename A>
846 void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&)
847 {
848  // Limit size per read so bogus size value won't cause out of memory
849  v.clear();
850  unsigned int nSize = ReadCompactSize(is);
851  unsigned int i = 0;
852  while (i < nSize)
853  {
854  unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
855  v.resize(i + blk);
856  is.read((char*)&v[i], blk * sizeof(T));
857  i += blk;
858  }
859 }
860 
861 template<typename Stream, typename T, typename A, typename V>
862 void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&)
863 {
865 }
866 
867 template<typename Stream, typename T, typename A>
868 inline void Unserialize(Stream& is, std::vector<T, A>& v)
869 {
870  Unserialize_impl(is, v, T());
871 }
872 
873 
874 
878 template<typename Stream, typename K, typename T>
879 void Serialize(Stream& os, const std::pair<K, T>& item)
880 {
881  Serialize(os, item.first);
882  Serialize(os, item.second);
883 }
884 
885 template<typename Stream, typename K, typename T>
886 void Unserialize(Stream& is, std::pair<K, T>& item)
887 {
888  Unserialize(is, item.first);
889  Unserialize(is, item.second);
890 }
891 
892 
893 
897 template<typename Stream, typename K, typename T, typename Pred, typename A>
898 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
899 {
900  WriteCompactSize(os, m.size());
901  for (const auto& entry : m)
902  Serialize(os, entry);
903 }
904 
905 template<typename Stream, typename K, typename T, typename Pred, typename A>
906 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
907 {
908  m.clear();
909  unsigned int nSize = ReadCompactSize(is);
910  typename std::map<K, T, Pred, A>::iterator mi = m.begin();
911  for (unsigned int i = 0; i < nSize; i++)
912  {
913  std::pair<K, T> item;
914  Unserialize(is, item);
915  mi = m.insert(mi, item);
916  }
917 }
918 
919 
920 
924 template<typename Stream, typename K, typename Pred, typename A>
925 void Serialize(Stream& os, const std::set<K, Pred, A>& m)
926 {
927  WriteCompactSize(os, m.size());
928  for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
929  Serialize(os, (*it));
930 }
931 
932 template<typename Stream, typename K, typename Pred, typename A>
933 void Unserialize(Stream& is, std::set<K, Pred, A>& m)
934 {
935  m.clear();
936  unsigned int nSize = ReadCompactSize(is);
937  typename std::set<K, Pred, A>::iterator it = m.begin();
938  for (unsigned int i = 0; i < nSize; i++)
939  {
940  K key;
941  Unserialize(is, key);
942  it = m.insert(it, key);
943  }
944 }
945 
946 
947 
951 template<typename Stream, typename T> void
952 Serialize(Stream& os, const std::unique_ptr<const T>& p)
953 {
954  Serialize(os, *p);
955 }
956 
957 template<typename Stream, typename T>
958 void Unserialize(Stream& is, std::unique_ptr<const T>& p)
959 {
960  p.reset(new T(deserialize, is));
961 }
962 
963 
964 
968 template<typename Stream, typename T> void
969 Serialize(Stream& os, const std::shared_ptr<const T>& p)
970 {
971  Serialize(os, *p);
972 }
973 
974 template<typename Stream, typename T>
975 void Unserialize(Stream& is, std::shared_ptr<const T>& p)
976 {
977  p = std::make_shared<const T>(deserialize, is);
978 }
979 
980 
981 
986 {
987  constexpr bool ForRead() const { return false; }
988 };
990 {
991  constexpr bool ForRead() const { return true; }
992 };
993 
994 
995 
996 
997 
998 
999 
1000 
1001 /* ::GetSerializeSize implementations
1002  *
1003  * Computing the serialized size of objects is done through a special stream
1004  * object of type CSizeComputer, which only records the number of bytes written
1005  * to it.
1006  *
1007  * If your Serialize or SerializationOp method has non-trivial overhead for
1008  * serialization, it may be worthwhile to implement a specialized version for
1009  * CSizeComputer, which uses the s.seek() method to record bytes that would
1010  * be written instead.
1011  */
1013 {
1014 protected:
1015  size_t nSize;
1016 
1017  const int nVersion;
1018 public:
1019  explicit CSizeComputer(int nVersionIn) : nSize(0), nVersion(nVersionIn) {}
1020 
1021  void write(const char *psz, size_t _nSize)
1022  {
1023  this->nSize += _nSize;
1024  }
1025 
1027  void seek(size_t _nSize)
1028  {
1029  this->nSize += _nSize;
1030  }
1031 
1032  template<typename T>
1033  CSizeComputer& operator<<(const T& obj)
1034  {
1035  ::Serialize(*this, obj);
1036  return (*this);
1037  }
1038 
1039  size_t size() const {
1040  return nSize;
1041  }
1042 
1043  int GetVersion() const { return nVersion; }
1044 };
1045 
1046 template<typename Stream>
1047 void SerializeMany(Stream& s)
1048 {
1049 }
1050 
1051 template<typename Stream, typename Arg, typename... Args>
1052 void SerializeMany(Stream& s, const Arg& arg, const Args&... args)
1053 {
1054  ::Serialize(s, arg);
1055  ::SerializeMany(s, args...);
1056 }
1057 
1058 template<typename Stream>
1059 inline void UnserializeMany(Stream& s)
1060 {
1061 }
1062 
1063 template<typename Stream, typename Arg, typename... Args>
1064 inline void UnserializeMany(Stream& s, Arg&& arg, Args&&... args)
1065 {
1066  ::Unserialize(s, arg);
1067  ::UnserializeMany(s, args...);
1068 }
1069 
1070 template<typename Stream, typename... Args>
1071 inline void SerReadWriteMany(Stream& s, CSerActionSerialize ser_action, const Args&... args)
1072 {
1073  ::SerializeMany(s, args...);
1074 }
1075 
1076 template<typename Stream, typename... Args>
1077 inline void SerReadWriteMany(Stream& s, CSerActionUnserialize ser_action, Args&&... args)
1078 {
1079  ::UnserializeMany(s, args...);
1080 }
1081 
1082 template<typename Stream, typename Type, typename Fn>
1083 inline void SerRead(Stream& s, CSerActionSerialize ser_action, Type&&, Fn&&)
1084 {
1085 }
1086 
1087 template<typename Stream, typename Type, typename Fn>
1088 inline void SerRead(Stream& s, CSerActionUnserialize ser_action, Type&& obj, Fn&& fn)
1089 {
1090  fn(s, std::forward<Type>(obj));
1091 }
1092 
1093 template<typename Stream, typename Type, typename Fn>
1094 inline void SerWrite(Stream& s, CSerActionSerialize ser_action, Type&& obj, Fn&& fn)
1095 {
1096  fn(s, std::forward<Type>(obj));
1097 }
1098 
1099 template<typename Stream, typename Type, typename Fn>
1100 inline void SerWrite(Stream& s, CSerActionUnserialize ser_action, Type&&, Fn&&)
1101 {
1102 }
1103 
1104 template<typename I>
1105 inline void WriteVarInt(CSizeComputer &s, I n)
1106 {
1107  s.seek(GetSizeOfVarInt<I>(n));
1108 }
1109 
1110 inline void WriteCompactSize(CSizeComputer &s, uint64_t nSize)
1111 {
1112  s.seek(GetSizeOfCompactSize(nSize));
1113 }
1114 
1115 template <typename T>
1116 size_t GetSerializeSize(const T& t, int nVersion = 0)
1117 {
1118  return (CSizeComputer(nVersion) << t).size();
1119 }
1120 
1121 template <typename... T>
1122 size_t GetSerializeSizeMany(int nVersion, const T&... t)
1123 {
1124  CSizeComputer sc(nVersion);
1125  SerializeMany(sc, t...);
1126  return sc.size();
1127 }
1128 
1129 #endif // BITCOIN_SERIALIZE_H
uint64_t ser_double_to_uint64(double x)
Definition: serialize.h:125
CSizeComputer(int nVersionIn)
Definition: serialize.h:1019
X & ReadWriteAsHelper(X &x)
Convert the reference base type to X, without changing constness or reference type.
Definition: serialize.h:172
std::deque< CInv >::iterator it
uint32_t ser_float_to_uint32(float x)
Definition: serialize.h:132
uint8_t ser_readdata8(Stream &s)
Definition: serialize.h:89
void clear()
Definition: prevector.h:343
void ser_writedata64(Stream &s, uint64_t obj)
Definition: serialize.h:84
void WriteVarInt(CSizeComputer &os, I n)
Definition: serialize.h:1105
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:318
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1110
void SerRead(Stream &s, CSerActionSerialize ser_action, Type &&, Fn &&)
Definition: serialize.h:1083
uint64_t htobe64(uint64_t host_64bits)
Definition: endian.h:212
void Unser(Stream &s, I &v)
Definition: serialize.h:547
static const unsigned int MAX_VECTOR_ALLOCATE
Maximum amount of memory (in bytes) to allocate at once when deserializing vectors.
Definition: serialize.h:34
void Unser(Stream &s, I &v)
Definition: serialize.h:492
size_t size() const
Definition: serialize.h:1039
void ser_writedata32(Stream &s, uint32_t obj)
Definition: serialize.h:74
constexpr deserialize_type deserialize
Definition: serialize.h:48
constexpr std::size_t size() const noexcept
Definition: span.h:153
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:276
Formatter for integers in CompactSize format.
Definition: serialize.h:544
uint32_t be32toh(uint32_t big_endian_32bits)
Definition: endian.h:198
void resize_uninitialized(size_type new_size)
Definition: prevector.h:386
const int nVersion
Definition: serialize.h:1017
void UnserializeMany(Stream &s)
Definition: serialize.h:1059
Simple wrapper class to serialize objects using a formatter; used by Using().
Definition: serialize.h:454
void Ser(Stream &s, const V &v)
Definition: serialize.h:604
uint32_t htole32(uint32_t host_32bits)
Definition: endian.h:191
Dummy data type to identify deserializing constructors.
Definition: serialize.h:47
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class...
Definition: serialize.h:476
char * CharCast(char *c)
Safely convert odd char pointer types to standard ones.
Definition: serialize.h:51
value_type * data()
Definition: prevector.h:528
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1116
void Serialize(Stream &s, char a)
Definition: serialize.h:227
uint32_t htobe32(uint32_t host_32bits)
Definition: endian.h:184
void Serialize(Stream &s) const
Definition: serialize.h:461
void Unser(Stream &s, I &v)
Definition: serialize.h:525
CSizeComputer & operator<<(const T &obj)
Definition: serialize.h:1033
uint64_t be64toh(uint64_t big_endian_64bits)
Definition: endian.h:226
Serialization wrapper class for integers in VarInt format.
Definition: serialize.h:485
void SerReadWriteMany(Stream &s, CSerActionSerialize ser_action, const Args &... args)
Definition: serialize.h:1071
void Unser(Stream &s, V &v)
Definition: serialize.h:614
uint16_t ser_readdata16(Stream &s)
Definition: serialize.h:95
uint32_t ser_readdata32(Stream &s)
Definition: serialize.h:107
constexpr CheckVarIntMode()
Definition: serialize.h:388
void ser_writedata16(Stream &s, uint16_t obj)
Definition: serialize.h:64
uint16_t htobe16(uint16_t host_16bits)
Definition: endian.h:156
constexpr bool ForRead() const
Definition: serialize.h:991
VarIntMode
Variable-length integers: bytes are a MSB base-128 encoding of the number.
Definition: serialize.h:384
I ReadVarInt(Stream &is)
Definition: serialize.h:431
uint16_t le16toh(uint16_t little_endian_16bits)
Definition: endian.h:177
void ser_writedata32be(Stream &s, uint32_t obj)
Definition: serialize.h:79
double ser_uint64_to_double(uint64_t y)
Definition: serialize.h:139
Support for SERIALIZE_METHODS and READWRITE macro.
Definition: serialize.h:985
constexpr bool ForRead() const
Definition: serialize.h:987
void SerializeMany(Stream &s)
Definition: serialize.h:1047
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:119
void Ser(Stream &s, I v)
Definition: serialize.h:513
Default formatter.
Definition: serialize.h:720
#define X(name)
Definition: net.cpp:554
void seek(size_t _nSize)
Pretend _nSize bytes are written, without specifying them.
Definition: serialize.h:1027
uint16_t htole16(uint16_t host_16bits)
Definition: endian.h:163
void Ser(Stream &s, const std::string &v)
Definition: serialize.h:581
uint16_t ser_readdata16be(Stream &s)
Definition: serialize.h:101
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:140
int GetVersion() const
Definition: serialize.h:1043
void * memcpy(void *a, const void *b, size_t c)
bool empty() const
Definition: prevector.h:286
Serialization wrapper class for custom integers and enums.
Definition: serialize.h:508
uint64_t htole64(uint64_t host_64bits)
Definition: endian.h:219
void write(const char *psz, size_t _nSize)
Definition: serialize.h:1021
uint32_t ser_readdata32be(Stream &s)
Definition: serialize.h:113
void SerWrite(Stream &s, CSerActionSerialize ser_action, Type &&obj, Fn &&fn)
Definition: serialize.h:1094
unsigned int GetSizeOfVarInt(I n)
Definition: serialize.h:396
size_t GetSerializeSizeMany(int nVersion, const T &... t)
Definition: serialize.h:1122
static constexpr uint64_t MAX_SIZE
The maximum size of a serialized object in bytes or number of elements (for eg vectors) when the size...
Definition: serialize.h:31
void Unserialize(Stream &s, char &a)
Definition: serialize.h:245
void ser_writedata16be(Stream &s, uint16_t obj)
Definition: serialize.h:69
size_type size() const
Definition: prevector.h:282
void Unserialize(Stream &s)
Definition: serialize.h:462
void Unser(Stream &s, std::string &v)
Definition: serialize.h:570
Formatter to serialize/deserialize vector elements using another formatter.
Definition: serialize.h:601
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:82
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:759
void Unserialize_impl(Stream &is, prevector< N, T > &v, const unsigned char &)
Definition: serialize.h:780
T m_object
Definition: serialize.h:456
uint32_t le32toh(uint32_t little_endian_32bits)
Definition: endian.h:205
static void Unser(Stream &s, T &t)
Definition: serialize.h:726
size_t nSize
Definition: serialize.h:1015
static void Ser(Stream &s, const T &t)
Definition: serialize.h:723
void Ser(Stream &s, I v)
Definition: serialize.h:487
void ser_writedata8(Stream &s, uint8_t obj)
Definition: serialize.h:60
void Ser(Stream &s, I v)
Definition: serialize.h:557
float ser_uint32_to_float(uint32_t y)
Definition: serialize.h:146
Wrapper(T obj)
Definition: serialize.h:460