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-2019 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 
209 #define SERIALIZE_METHODS(cls, obj) \
210  template<typename Stream> \
211  void Serialize(Stream& s) const \
212  { \
213  static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \
214  SerializationOps(*this, s, CSerActionSerialize()); \
215  } \
216  template<typename Stream> \
217  void Unserialize(Stream& s) \
218  { \
219  static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch"); \
220  SerializationOps(*this, s, CSerActionUnserialize()); \
221  } \
222  template<typename Stream, typename Type, typename Operation> \
223  static inline void SerializationOps(Type& obj, Stream& s, Operation ser_action) \
224 
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<unsigned short>::max()) return sizeof(unsigned char) + sizeof(unsigned short);
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<unsigned short>::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 
311 template<typename Stream>
312 uint64_t ReadCompactSize(Stream& is)
313 {
314  uint8_t chSize = ser_readdata8(is);
315  uint64_t nSizeRet = 0;
316  if (chSize < 253)
317  {
318  nSizeRet = chSize;
319  }
320  else if (chSize == 253)
321  {
322  nSizeRet = ser_readdata16(is);
323  if (nSizeRet < 253)
324  throw std::ios_base::failure("non-canonical ReadCompactSize()");
325  }
326  else if (chSize == 254)
327  {
328  nSizeRet = ser_readdata32(is);
329  if (nSizeRet < 0x10000u)
330  throw std::ios_base::failure("non-canonical ReadCompactSize()");
331  }
332  else
333  {
334  nSizeRet = ser_readdata64(is);
335  if (nSizeRet < 0x100000000ULL)
336  throw std::ios_base::failure("non-canonical ReadCompactSize()");
337  }
338  if (nSizeRet > (uint64_t)MAX_SIZE)
339  throw std::ios_base::failure("ReadCompactSize(): size too large");
340  return nSizeRet;
341 }
342 
378 
379 template <VarIntMode Mode, typename I>
381  constexpr CheckVarIntMode()
382  {
383  static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned<I>::value, "Unsigned type required with mode DEFAULT.");
384  static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed<I>::value, "Signed type required with mode NONNEGATIVE_SIGNED.");
385  }
386 };
387 
388 template<VarIntMode Mode, typename I>
389 inline unsigned int GetSizeOfVarInt(I n)
390 {
392  int nRet = 0;
393  while(true) {
394  nRet++;
395  if (n <= 0x7F)
396  break;
397  n = (n >> 7) - 1;
398  }
399  return nRet;
400 }
401 
402 template<typename I>
403 inline void WriteVarInt(CSizeComputer& os, I n);
404 
405 template<typename Stream, VarIntMode Mode, typename I>
406 void WriteVarInt(Stream& os, I n)
407 {
409  unsigned char tmp[(sizeof(n)*8+6)/7];
410  int len=0;
411  while(true) {
412  tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
413  if (n <= 0x7F)
414  break;
415  n = (n >> 7) - 1;
416  len++;
417  }
418  do {
419  ser_writedata8(os, tmp[len]);
420  } while(len--);
421 }
422 
423 template<typename Stream, VarIntMode Mode, typename I>
424 I ReadVarInt(Stream& is)
425 {
427  I n = 0;
428  while(true) {
429  unsigned char chData = ser_readdata8(is);
430  if (n > (std::numeric_limits<I>::max() >> 7)) {
431  throw std::ios_base::failure("ReadVarInt(): size too large");
432  }
433  n = (n << 7) | (chData & 0x7F);
434  if (chData & 0x80) {
435  if (n == std::numeric_limits<I>::max()) {
436  throw std::ios_base::failure("ReadVarInt(): size too large");
437  }
438  n++;
439  } else {
440  return n;
441  }
442  }
443 }
444 
446 template<typename Formatter, typename T>
447 class Wrapper
448 {
449  static_assert(std::is_lvalue_reference<T>::value, "Wrapper needs an lvalue reference type T");
450 protected:
451  T m_object;
452 public:
453  explicit Wrapper(T obj) : m_object(obj) {}
454  template<typename Stream> void Serialize(Stream &s) const { Formatter().Ser(s, m_object); }
455  template<typename Stream> void Unserialize(Stream &s) { Formatter().Unser(s, m_object); }
456 };
457 
468 template<typename Formatter, typename T>
469 static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&>(t); }
470 
471 #define VARINT(obj, ...) Using<VarIntFormatter<__VA_ARGS__>>(obj)
472 #define COMPACTSIZE(obj) CCompactSize(REF(obj))
473 #define LIMITED_STRING(obj,n) LimitedString< n >(REF(obj))
474 
476 template<VarIntMode Mode=VarIntMode::DEFAULT>
478 {
479  template<typename Stream, typename I> void Ser(Stream &s, I v)
480  {
481  WriteVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s, v);
482  }
483 
484  template<typename Stream, typename I> void Unser(Stream& s, I& v)
485  {
486  v = ReadVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s);
487  }
488 };
489 
499 template<typename I>
501 {
502 protected:
503  I& m_val;
504 public:
505  explicit BigEndian(I& val) : m_val(val)
506  {
507  static_assert(std::is_unsigned<I>::value, "BigEndian type must be unsigned integer");
508  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");
509  }
510 
511  template<typename Stream>
512  void Serialize(Stream& s) const
513  {
514  ser_writedata16be(s, m_val);
515  }
516 
517  template<typename Stream>
518  void Unserialize(Stream& s)
519  {
520  m_val = ser_readdata16be(s);
521  }
522 };
523 
525 {
526 protected:
527  uint64_t &n;
528 public:
529  explicit CCompactSize(uint64_t& nIn) : n(nIn) { }
530 
531  template<typename Stream>
532  void Serialize(Stream &s) const {
533  WriteCompactSize<Stream>(s, n);
534  }
535 
536  template<typename Stream>
537  void Unserialize(Stream& s) {
538  n = ReadCompactSize<Stream>(s);
539  }
540 };
541 
542 template<size_t Limit>
544 {
545 protected:
546  std::string& string;
547 public:
548  explicit LimitedString(std::string& _string) : string(_string) {}
549 
550  template<typename Stream>
551  void Unserialize(Stream& s)
552  {
553  size_t size = ReadCompactSize(s);
554  if (size > Limit) {
555  throw std::ios_base::failure("String length limit exceeded");
556  }
557  string.resize(size);
558  if (size != 0)
559  s.read((char*)string.data(), size);
560  }
561 
562  template<typename Stream>
563  void Serialize(Stream& s) const
564  {
565  WriteCompactSize(s, string.size());
566  if (!string.empty())
567  s.write((char*)string.data(), string.size());
568  }
569 };
570 
571 template<typename I>
573 
581 template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
582 template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
583 
588 template<typename Stream, unsigned int N, typename T> void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&);
589 template<typename Stream, unsigned int N, typename T, typename V> void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&);
590 template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
591 template<typename Stream, unsigned int N, typename T> void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&);
592 template<typename Stream, unsigned int N, typename T, typename V> void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&);
593 template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
594 
599 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&);
600 template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&);
601 template<typename Stream, typename T, typename A, typename V> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&);
602 template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
603 template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&);
604 template<typename Stream, typename T, typename A, typename V> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&);
605 template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
606 
610 template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item);
611 template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item);
612 
616 template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
617 template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
618 
622 template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m);
623 template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m);
624 
628 template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p);
629 template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p);
630 
634 template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p);
635 template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p);
636 
637 
638 
642 template<typename Stream, typename T>
643 inline void Serialize(Stream& os, const T& a)
644 {
645  a.Serialize(os);
646 }
647 
648 template<typename Stream, typename T>
649 inline void Unserialize(Stream& is, T&& a)
650 {
651  a.Unserialize(is);
652 }
653 
654 
655 
656 
657 
661 template<typename Stream, typename C>
662 void Serialize(Stream& os, const std::basic_string<C>& str)
663 {
664  WriteCompactSize(os, str.size());
665  if (!str.empty())
666  os.write((char*)str.data(), str.size() * sizeof(C));
667 }
668 
669 template<typename Stream, typename C>
670 void Unserialize(Stream& is, std::basic_string<C>& str)
671 {
672  unsigned int nSize = ReadCompactSize(is);
673  str.resize(nSize);
674  if (nSize != 0)
675  is.read((char*)str.data(), nSize * sizeof(C));
676 }
677 
678 
679 
683 template<typename Stream, unsigned int N, typename T>
684 void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&)
685 {
686  WriteCompactSize(os, v.size());
687  if (!v.empty())
688  os.write((char*)v.data(), v.size() * sizeof(T));
689 }
690 
691 template<typename Stream, unsigned int N, typename T, typename V>
692 void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&)
693 {
694  WriteCompactSize(os, v.size());
695  for (typename prevector<N, T>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
696  ::Serialize(os, (*vi));
697 }
698 
699 template<typename Stream, unsigned int N, typename T>
700 inline void Serialize(Stream& os, const prevector<N, T>& v)
701 {
702  Serialize_impl(os, v, T());
703 }
704 
705 
706 template<typename Stream, unsigned int N, typename T>
707 void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&)
708 {
709  // Limit size per read so bogus size value won't cause out of memory
710  v.clear();
711  unsigned int nSize = ReadCompactSize(is);
712  unsigned int i = 0;
713  while (i < nSize)
714  {
715  unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
716  v.resize_uninitialized(i + blk);
717  is.read((char*)&v[i], blk * sizeof(T));
718  i += blk;
719  }
720 }
721 
722 template<typename Stream, unsigned int N, typename T, typename V>
723 void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&)
724 {
725  v.clear();
726  unsigned int nSize = ReadCompactSize(is);
727  unsigned int i = 0;
728  unsigned int nMid = 0;
729  while (nMid < nSize)
730  {
731  nMid += 5000000 / sizeof(T);
732  if (nMid > nSize)
733  nMid = nSize;
734  v.resize_uninitialized(nMid);
735  for (; i < nMid; ++i)
736  Unserialize(is, v[i]);
737  }
738 }
739 
740 template<typename Stream, unsigned int N, typename T>
741 inline void Unserialize(Stream& is, prevector<N, T>& v)
742 {
743  Unserialize_impl(is, v, T());
744 }
745 
746 
747 
751 template<typename Stream, typename T, typename A>
752 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&)
753 {
754  WriteCompactSize(os, v.size());
755  if (!v.empty())
756  os.write((char*)v.data(), v.size() * sizeof(T));
757 }
758 
759 template<typename Stream, typename T, typename A>
760 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&)
761 {
762  // A special case for std::vector<bool>, as dereferencing
763  // std::vector<bool>::const_iterator does not result in a const bool&
764  // due to std::vector's special casing for bool arguments.
765  WriteCompactSize(os, v.size());
766  for (bool elem : v) {
767  ::Serialize(os, elem);
768  }
769 }
770 
771 template<typename Stream, typename T, typename A, typename V>
772 void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&)
773 {
774  WriteCompactSize(os, v.size());
775  for (typename std::vector<T, A>::const_iterator vi = v.begin(); vi != v.end(); ++vi)
776  ::Serialize(os, (*vi));
777 }
778 
779 template<typename Stream, typename T, typename A>
780 inline void Serialize(Stream& os, const std::vector<T, A>& v)
781 {
782  Serialize_impl(os, v, T());
783 }
784 
785 
786 template<typename Stream, typename T, typename A>
787 void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&)
788 {
789  // Limit size per read so bogus size value won't cause out of memory
790  v.clear();
791  unsigned int nSize = ReadCompactSize(is);
792  unsigned int i = 0;
793  while (i < nSize)
794  {
795  unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
796  v.resize(i + blk);
797  is.read((char*)&v[i], blk * sizeof(T));
798  i += blk;
799  }
800 }
801 
802 template<typename Stream, typename T, typename A, typename V>
803 void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&)
804 {
805  v.clear();
806  unsigned int nSize = ReadCompactSize(is);
807  unsigned int i = 0;
808  unsigned int nMid = 0;
809  while (nMid < nSize)
810  {
811  nMid += 5000000 / sizeof(T);
812  if (nMid > nSize)
813  nMid = nSize;
814  v.resize(nMid);
815  for (; i < nMid; i++)
816  Unserialize(is, v[i]);
817  }
818 }
819 
820 template<typename Stream, typename T, typename A>
821 inline void Unserialize(Stream& is, std::vector<T, A>& v)
822 {
823  Unserialize_impl(is, v, T());
824 }
825 
826 
827 
831 template<typename Stream, typename K, typename T>
832 void Serialize(Stream& os, const std::pair<K, T>& item)
833 {
834  Serialize(os, item.first);
835  Serialize(os, item.second);
836 }
837 
838 template<typename Stream, typename K, typename T>
839 void Unserialize(Stream& is, std::pair<K, T>& item)
840 {
841  Unserialize(is, item.first);
842  Unserialize(is, item.second);
843 }
844 
845 
846 
850 template<typename Stream, typename K, typename T, typename Pred, typename A>
851 void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
852 {
853  WriteCompactSize(os, m.size());
854  for (const auto& entry : m)
855  Serialize(os, entry);
856 }
857 
858 template<typename Stream, typename K, typename T, typename Pred, typename A>
859 void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
860 {
861  m.clear();
862  unsigned int nSize = ReadCompactSize(is);
863  typename std::map<K, T, Pred, A>::iterator mi = m.begin();
864  for (unsigned int i = 0; i < nSize; i++)
865  {
866  std::pair<K, T> item;
867  Unserialize(is, item);
868  mi = m.insert(mi, item);
869  }
870 }
871 
872 
873 
877 template<typename Stream, typename K, typename Pred, typename A>
878 void Serialize(Stream& os, const std::set<K, Pred, A>& m)
879 {
880  WriteCompactSize(os, m.size());
881  for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
882  Serialize(os, (*it));
883 }
884 
885 template<typename Stream, typename K, typename Pred, typename A>
886 void Unserialize(Stream& is, std::set<K, Pred, A>& m)
887 {
888  m.clear();
889  unsigned int nSize = ReadCompactSize(is);
890  typename std::set<K, Pred, A>::iterator it = m.begin();
891  for (unsigned int i = 0; i < nSize; i++)
892  {
893  K key;
894  Unserialize(is, key);
895  it = m.insert(it, key);
896  }
897 }
898 
899 
900 
904 template<typename Stream, typename T> void
905 Serialize(Stream& os, const std::unique_ptr<const T>& p)
906 {
907  Serialize(os, *p);
908 }
909 
910 template<typename Stream, typename T>
911 void Unserialize(Stream& is, std::unique_ptr<const T>& p)
912 {
913  p.reset(new T(deserialize, is));
914 }
915 
916 
917 
921 template<typename Stream, typename T> void
922 Serialize(Stream& os, const std::shared_ptr<const T>& p)
923 {
924  Serialize(os, *p);
925 }
926 
927 template<typename Stream, typename T>
928 void Unserialize(Stream& is, std::shared_ptr<const T>& p)
929 {
930  p = std::make_shared<const T>(deserialize, is);
931 }
932 
933 
934 
939 {
940  constexpr bool ForRead() const { return false; }
941 };
943 {
944  constexpr bool ForRead() const { return true; }
945 };
946 
947 
948 
949 
950 
951 
952 
953 
954 /* ::GetSerializeSize implementations
955  *
956  * Computing the serialized size of objects is done through a special stream
957  * object of type CSizeComputer, which only records the number of bytes written
958  * to it.
959  *
960  * If your Serialize or SerializationOp method has non-trivial overhead for
961  * serialization, it may be worthwhile to implement a specialized version for
962  * CSizeComputer, which uses the s.seek() method to record bytes that would
963  * be written instead.
964  */
966 {
967 protected:
968  size_t nSize;
969 
970  const int nVersion;
971 public:
972  explicit CSizeComputer(int nVersionIn) : nSize(0), nVersion(nVersionIn) {}
973 
974  void write(const char *psz, size_t _nSize)
975  {
976  this->nSize += _nSize;
977  }
978 
980  void seek(size_t _nSize)
981  {
982  this->nSize += _nSize;
983  }
984 
985  template<typename T>
986  CSizeComputer& operator<<(const T& obj)
987  {
988  ::Serialize(*this, obj);
989  return (*this);
990  }
991 
992  size_t size() const {
993  return nSize;
994  }
995 
996  int GetVersion() const { return nVersion; }
997 };
998 
999 template<typename Stream>
1000 void SerializeMany(Stream& s)
1001 {
1002 }
1003 
1004 template<typename Stream, typename Arg, typename... Args>
1005 void SerializeMany(Stream& s, const Arg& arg, const Args&... args)
1006 {
1007  ::Serialize(s, arg);
1008  ::SerializeMany(s, args...);
1009 }
1010 
1011 template<typename Stream>
1012 inline void UnserializeMany(Stream& s)
1013 {
1014 }
1015 
1016 template<typename Stream, typename Arg, typename... Args>
1017 inline void UnserializeMany(Stream& s, Arg&& arg, Args&&... args)
1018 {
1019  ::Unserialize(s, arg);
1020  ::UnserializeMany(s, args...);
1021 }
1022 
1023 template<typename Stream, typename... Args>
1024 inline void SerReadWriteMany(Stream& s, CSerActionSerialize ser_action, const Args&... args)
1025 {
1026  ::SerializeMany(s, args...);
1027 }
1028 
1029 template<typename Stream, typename... Args>
1030 inline void SerReadWriteMany(Stream& s, CSerActionUnserialize ser_action, Args&&... args)
1031 {
1032  ::UnserializeMany(s, args...);
1033 }
1034 
1035 template<typename I>
1036 inline void WriteVarInt(CSizeComputer &s, I n)
1037 {
1038  s.seek(GetSizeOfVarInt<I>(n));
1039 }
1040 
1041 inline void WriteCompactSize(CSizeComputer &s, uint64_t nSize)
1042 {
1043  s.seek(GetSizeOfCompactSize(nSize));
1044 }
1045 
1046 template <typename T>
1047 size_t GetSerializeSize(const T& t, int nVersion = 0)
1048 {
1049  return (CSizeComputer(nVersion) << t).size();
1050 }
1051 
1052 template <typename... T>
1053 size_t GetSerializeSizeMany(int nVersion, const T&... t)
1054 {
1055  CSizeComputer sc(nVersion);
1056  SerializeMany(sc, t...);
1057  return sc.size();
1058 }
1059 
1060 #endif // BITCOIN_SERIALIZE_H
uint64_t ser_double_to_uint64(double x)
Definition: serialize.h:137
CSizeComputer(int nVersionIn)
Definition: serialize.h:972
std::string & string
Definition: serialize.h:546
X & ReadWriteAsHelper(X &x)
Convert the reference base type to X, without changing constness or reference type.
Definition: serialize.h:180
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:338
void ser_writedata64(Stream &s, uint64_t obj)
Definition: serialize.h:96
uint64_t & n
Definition: serialize.h:527
uint64_t ReadCompactSize(Stream &is)
Definition: serialize.h:312
void WriteVarInt(CSizeComputer &os, I n)
Definition: serialize.h:1036
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1041
void Unser(Stream &s, I &v)
Definition: serialize.h:484
size_t size() const
Definition: serialize.h:992
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:276
CCompactSize(uint64_t &nIn)
Definition: serialize.h:529
void Unserialize(Stream &s)
Definition: serialize.h:537
uint32_t be32toh(uint32_t big_endian_32bits)
Definition: endian.h:198
void resize_uninitialized(size_type new_size)
Definition: prevector.h:381
BigEndian(I &val)
Definition: serialize.h:505
const int nVersion
Definition: serialize.h:970
void UnserializeMany(Stream &s)
Definition: serialize.h:1012
BigEndian< I > WrapBigEndian(I &n)
Definition: serialize.h:572
Simple wrapper class to serialize objects using a formatter; used by Using().
Definition: serialize.h:447
uint32_t htole32(uint32_t host_32bits)
Definition: endian.h:191
Dummy data type to identify deserializing constructors.
Definition: serialize.h:39
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class...
Definition: serialize.h:469
char * CharCast(char *c)
Safely convert odd char pointer types to standard ones.
Definition: serialize.h:63
value_type * data()
Definition: prevector.h:518
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1047
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:454
void Unserialize(Stream &s)
Definition: serialize.h:551
CSizeComputer & operator<<(const T &obj)
Definition: serialize.h:986
Serialization wrapper class for integers in VarInt format.
Definition: serialize.h:477
iterator end()
Definition: prevector.h:287
void Serialize(Stream &s) const
Definition: serialize.h:563
void SerReadWriteMany(Stream &s, CSerActionSerialize ser_action, const Args &... args)
Definition: serialize.h:1024
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:532
Serialization wrapper class for big-endian integers.
Definition: serialize.h:500
constexpr CheckVarIntMode()
Definition: serialize.h:381
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:944
VarIntMode
Variable-length integers: bytes are a MSB base-128 encoding of the number.
Definition: serialize.h:377
I ReadVarInt(Stream &is)
Definition: serialize.h:424
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:938
constexpr bool ForRead() const
Definition: serialize.h:940
void SerializeMany(Stream &s)
Definition: serialize.h:1000
Implements a drop-in replacement for std::vector<T> which stores up to N elements directly (without h...
Definition: prevector.h:38
uint64_t ser_readdata64(Stream &s)
Definition: serialize.h:131
#define X(name)
Definition: net.cpp:499
void seek(size_t _nSize)
Pretend _nSize bytes are written, without specifying them.
Definition: serialize.h:980
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:996
void Unserialize(Stream &s)
Definition: serialize.h:518
bool empty() const
Definition: prevector.h:281
uint64_t htole64(uint64_t host_64bits)
Definition: endian.h:219
void write(const char *psz, size_t _nSize)
Definition: serialize.h:974
uint32_t ser_readdata32be(Stream &s)
Definition: serialize.h:125
unsigned int GetSizeOfVarInt(I n)
Definition: serialize.h:389
size_t GetSerializeSizeMany(int nVersion, const T &... t)
Definition: serialize.h:1053
I & m_val
Definition: serialize.h:503
void Unserialize(Stream &s, char &a)
Definition: serialize.h:245
iterator begin()
Definition: prevector.h:285
void ser_writedata16be(Stream &s, uint16_t obj)
Definition: serialize.h:81
size_type size() const
Definition: prevector.h:277
void Unserialize(Stream &s)
Definition: serialize.h:455
void Serialize(Stream &s) const
Definition: serialize.h:512
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:684
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:707
T m_object
Definition: serialize.h:449
auto it
Definition: validation.cpp:362
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:968
LimitedString(std::string &_string)
Definition: serialize.h:548
void Ser(Stream &s, I v)
Definition: serialize.h:479
void ser_writedata8(Stream &s, uint8_t obj)
Definition: serialize.h:72
float ser_uint32_to_float(uint32_t y)
Definition: serialize.h:155
Wrapper(T obj)
Definition: serialize.h:453