Bitcoin Core 22.99.0
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
31static constexpr uint64_t MAX_SIZE = 0x02000000;
32
34static const unsigned int MAX_VECTOR_ALLOCATE = 5000000;
35
49
51inline char* CharCast(char* c) { return c; }
52inline char* CharCast(unsigned char* c) { return (char*)c; }
53inline const char* CharCast(const char* c) { return c; }
54inline 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 */
60template<typename Stream> inline void ser_writedata8(Stream &s, uint8_t obj)
61{
62 s.write((char*)&obj, 1);
63}
64template<typename Stream> inline void ser_writedata16(Stream &s, uint16_t obj)
65{
66 obj = htole16(obj);
67 s.write((char*)&obj, 2);
68}
69template<typename Stream> inline void ser_writedata16be(Stream &s, uint16_t obj)
70{
71 obj = htobe16(obj);
72 s.write((char*)&obj, 2);
73}
74template<typename Stream> inline void ser_writedata32(Stream &s, uint32_t obj)
75{
76 obj = htole32(obj);
77 s.write((char*)&obj, 4);
78}
79template<typename Stream> inline void ser_writedata32be(Stream &s, uint32_t obj)
80{
81 obj = htobe32(obj);
82 s.write((char*)&obj, 4);
83}
84template<typename Stream> inline void ser_writedata64(Stream &s, uint64_t obj)
85{
86 obj = htole64(obj);
87 s.write((char*)&obj, 8);
88}
89template<typename Stream> inline uint8_t ser_readdata8(Stream &s)
90{
91 uint8_t obj;
92 s.read((char*)&obj, 1);
93 return obj;
94}
95template<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}
101template<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}
107template<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}
113template<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}
119template<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
126
128//
129// Templates for serializing to anything that looks like a stream,
130// i.e. anything that supports .read(char*, size_t) and .write(char*, size_t)
131//
132
133class CSizeComputer;
134
135enum
136{
137 // primary actions
138 SER_NETWORK = (1 << 0),
139 SER_DISK = (1 << 1),
140 SER_GETHASH = (1 << 2),
141};
142
144template<typename X> X& ReadWriteAsHelper(X& x) { return x; }
145template<typename X> const X& ReadWriteAsHelper(const X& x) { return x; }
146
147#define READWRITE(...) (::SerReadWriteMany(s, ser_action, __VA_ARGS__))
148#define READWRITEAS(type, obj) (::SerReadWriteMany(s, ser_action, ReadWriteAsHelper<type>(obj)))
149#define SER_READ(obj, code) ::SerRead(s, ser_action, obj, [&](Stream& s, typename std::remove_const<Type>::type& obj) { code; })
150#define SER_WRITE(obj, code) ::SerWrite(s, ser_action, obj, [&](Stream& s, const Type& obj) { code; })
151
168#define FORMATTER_METHODS(cls, obj) \
169 template<typename Stream> \
170 static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, CSerActionSerialize()); } \
171 template<typename Stream> \
172 static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, CSerActionUnserialize()); } \
173 template<typename Stream, typename Type, typename Operation> \
174 static inline void SerializationOps(Type& obj, Stream& s, Operation ser_action) \
175
183#define SERIALIZE_METHODS(cls, obj) \
184 template<typename Stream> \
185 void Serialize(Stream& s) const \
186 { \
187 static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \
188 Ser(s, *this); \
189 } \
190 template<typename Stream> \
191 void Unserialize(Stream& s) \
192 { \
193 static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch"); \
194 Unser(s, *this); \
195 } \
196 FORMATTER_METHODS(cls, obj)
197
198#ifndef CHAR_EQUALS_INT8
199template<typename Stream> inline void Serialize(Stream& s, char a ) { ser_writedata8(s, a); } // TODO Get rid of bare char
200#endif
201template<typename Stream> inline void Serialize(Stream& s, int8_t a ) { ser_writedata8(s, a); }
202template<typename Stream> inline void Serialize(Stream& s, uint8_t a ) { ser_writedata8(s, a); }
203template<typename Stream> inline void Serialize(Stream& s, int16_t a ) { ser_writedata16(s, a); }
204template<typename Stream> inline void Serialize(Stream& s, uint16_t a) { ser_writedata16(s, a); }
205template<typename Stream> inline void Serialize(Stream& s, int32_t a ) { ser_writedata32(s, a); }
206template<typename Stream> inline void Serialize(Stream& s, uint32_t a) { ser_writedata32(s, a); }
207template<typename Stream> inline void Serialize(Stream& s, int64_t a ) { ser_writedata64(s, a); }
208template<typename Stream> inline void Serialize(Stream& s, uint64_t a) { ser_writedata64(s, a); }
209template<typename Stream, int N> inline void Serialize(Stream& s, const char (&a)[N]) { s.write(a, N); }
210template<typename Stream, int N> inline void Serialize(Stream& s, const unsigned char (&a)[N]) { s.write(CharCast(a), N); }
211template<typename Stream> inline void Serialize(Stream& s, const Span<const unsigned char>& span) { s.write(CharCast(span.data()), span.size()); }
212template<typename Stream> inline void Serialize(Stream& s, const Span<unsigned char>& span) { s.write(CharCast(span.data()), span.size()); }
213
214#ifndef CHAR_EQUALS_INT8
215template<typename Stream> inline void Unserialize(Stream& s, char& a ) { a = ser_readdata8(s); } // TODO Get rid of bare char
216#endif
217template<typename Stream> inline void Unserialize(Stream& s, int8_t& a ) { a = ser_readdata8(s); }
218template<typename Stream> inline void Unserialize(Stream& s, uint8_t& a ) { a = ser_readdata8(s); }
219template<typename Stream> inline void Unserialize(Stream& s, int16_t& a ) { a = ser_readdata16(s); }
220template<typename Stream> inline void Unserialize(Stream& s, uint16_t& a) { a = ser_readdata16(s); }
221template<typename Stream> inline void Unserialize(Stream& s, int32_t& a ) { a = ser_readdata32(s); }
222template<typename Stream> inline void Unserialize(Stream& s, uint32_t& a) { a = ser_readdata32(s); }
223template<typename Stream> inline void Unserialize(Stream& s, int64_t& a ) { a = ser_readdata64(s); }
224template<typename Stream> inline void Unserialize(Stream& s, uint64_t& a) { a = ser_readdata64(s); }
225template<typename Stream, int N> inline void Unserialize(Stream& s, char (&a)[N]) { s.read(a, N); }
226template<typename Stream, int N> inline void Unserialize(Stream& s, unsigned char (&a)[N]) { s.read(CharCast(a), N); }
227template<typename Stream> inline void Unserialize(Stream& s, Span<unsigned char>& span) { s.read(CharCast(span.data()), span.size()); }
228
229template <typename Stream> inline void Serialize(Stream& s, bool a) { uint8_t f = a; ser_writedata8(s, f); }
230template <typename Stream> inline void Unserialize(Stream& s, bool& a) { uint8_t f = ser_readdata8(s); a = f; }
231
232
240inline unsigned int GetSizeOfCompactSize(uint64_t nSize)
241{
242 if (nSize < 253) return sizeof(unsigned char);
243 else if (nSize <= std::numeric_limits<uint16_t>::max()) return sizeof(unsigned char) + sizeof(uint16_t);
244 else if (nSize <= std::numeric_limits<unsigned int>::max()) return sizeof(unsigned char) + sizeof(unsigned int);
245 else return sizeof(unsigned char) + sizeof(uint64_t);
246}
247
248inline void WriteCompactSize(CSizeComputer& os, uint64_t nSize);
249
250template<typename Stream>
251void WriteCompactSize(Stream& os, uint64_t nSize)
252{
253 if (nSize < 253)
254 {
256 }
257 else if (nSize <= std::numeric_limits<uint16_t>::max())
258 {
259 ser_writedata8(os, 253);
261 }
262 else if (nSize <= std::numeric_limits<unsigned int>::max())
263 {
264 ser_writedata8(os, 254);
266 }
267 else
268 {
269 ser_writedata8(os, 255);
271 }
272 return;
273}
274
281template<typename Stream>
282uint64_t ReadCompactSize(Stream& is, bool range_check = true)
283{
284 uint8_t chSize = ser_readdata8(is);
285 uint64_t nSizeRet = 0;
286 if (chSize < 253)
287 {
288 nSizeRet = chSize;
289 }
290 else if (chSize == 253)
291 {
292 nSizeRet = ser_readdata16(is);
293 if (nSizeRet < 253)
294 throw std::ios_base::failure("non-canonical ReadCompactSize()");
295 }
296 else if (chSize == 254)
297 {
298 nSizeRet = ser_readdata32(is);
299 if (nSizeRet < 0x10000u)
300 throw std::ios_base::failure("non-canonical ReadCompactSize()");
301 }
302 else
303 {
304 nSizeRet = ser_readdata64(is);
305 if (nSizeRet < 0x100000000ULL)
306 throw std::ios_base::failure("non-canonical ReadCompactSize()");
307 }
308 if (range_check && nSizeRet > MAX_SIZE) {
309 throw std::ios_base::failure("ReadCompactSize(): size too large");
310 }
311 return nSizeRet;
312}
313
349
350template <VarIntMode Mode, typename I>
352 constexpr CheckVarIntMode()
353 {
354 static_assert(Mode != VarIntMode::DEFAULT || std::is_unsigned<I>::value, "Unsigned type required with mode DEFAULT.");
355 static_assert(Mode != VarIntMode::NONNEGATIVE_SIGNED || std::is_signed<I>::value, "Signed type required with mode NONNEGATIVE_SIGNED.");
356 }
357};
358
359template<VarIntMode Mode, typename I>
360inline unsigned int GetSizeOfVarInt(I n)
361{
363 int nRet = 0;
364 while(true) {
365 nRet++;
366 if (n <= 0x7F)
367 break;
368 n = (n >> 7) - 1;
369 }
370 return nRet;
371}
372
373template<typename I>
374inline void WriteVarInt(CSizeComputer& os, I n);
375
376template<typename Stream, VarIntMode Mode, typename I>
377void WriteVarInt(Stream& os, I n)
378{
380 unsigned char tmp[(sizeof(n)*8+6)/7];
381 int len=0;
382 while(true) {
383 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
384 if (n <= 0x7F)
385 break;
386 n = (n >> 7) - 1;
387 len++;
388 }
389 do {
390 ser_writedata8(os, tmp[len]);
391 } while(len--);
392}
393
394template<typename Stream, VarIntMode Mode, typename I>
395I ReadVarInt(Stream& is)
396{
398 I n = 0;
399 while(true) {
400 unsigned char chData = ser_readdata8(is);
401 if (n > (std::numeric_limits<I>::max() >> 7)) {
402 throw std::ios_base::failure("ReadVarInt(): size too large");
403 }
404 n = (n << 7) | (chData & 0x7F);
405 if (chData & 0x80) {
406 if (n == std::numeric_limits<I>::max()) {
407 throw std::ios_base::failure("ReadVarInt(): size too large");
408 }
409 n++;
410 } else {
411 return n;
412 }
413 }
414}
415
417template<typename Formatter, typename T>
419{
420 static_assert(std::is_lvalue_reference<T>::value, "Wrapper needs an lvalue reference type T");
421protected:
423public:
424 explicit Wrapper(T obj) : m_object(obj) {}
425 template<typename Stream> void Serialize(Stream &s) const { Formatter().Ser(s, m_object); }
426 template<typename Stream> void Unserialize(Stream &s) { Formatter().Unser(s, m_object); }
427};
428
439template<typename Formatter, typename T>
440static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&>(t); }
441
442#define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
443#define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
444#define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj)
445#define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj)
446
448template<VarIntMode Mode>
450{
451 template<typename Stream, typename I> void Ser(Stream &s, I v)
452 {
453 WriteVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s, v);
454 }
455
456 template<typename Stream, typename I> void Unser(Stream& s, I& v)
457 {
458 v = ReadVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s);
459 }
460};
461
471template<int Bytes, bool BigEndian = false>
473{
474 static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range");
475 static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
476
477 template <typename Stream, typename I> void Ser(Stream& s, I v)
478 {
479 if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range");
480 if (BigEndian) {
481 uint64_t raw = htobe64(v);
482 s.write(((const char*)&raw) + 8 - Bytes, Bytes);
483 } else {
484 uint64_t raw = htole64(v);
485 s.write((const char*)&raw, Bytes);
486 }
487 }
488
489 template <typename Stream, typename I> void Unser(Stream& s, I& v)
490 {
491 using U = typename std::conditional<std::is_enum<I>::value, std::underlying_type<I>, std::common_type<I>>::type::type;
492 static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0, "Assigned type too small");
493 uint64_t raw = 0;
494 if (BigEndian) {
495 s.read(((char*)&raw) + 8 - Bytes, Bytes);
496 v = static_cast<I>(be64toh(raw));
497 } else {
498 s.read((char*)&raw, Bytes);
499 v = static_cast<I>(le64toh(raw));
500 }
501 }
502};
503
505
507template<bool RangeCheck>
509{
510 template<typename Stream, typename I>
511 void Unser(Stream& s, I& v)
512 {
513 uint64_t n = ReadCompactSize<Stream>(s, RangeCheck);
514 if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
515 throw std::ios_base::failure("CompactSize exceeds limit of type");
516 }
517 v = n;
518 }
519
520 template<typename Stream, typename I>
521 void Ser(Stream& s, I v)
522 {
523 static_assert(std::is_unsigned<I>::value, "CompactSize only supported for unsigned integers");
524 static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below");
525
526 WriteCompactSize<Stream>(s, v);
527 }
528};
529
530template<size_t Limit>
532{
533 template<typename Stream>
534 void Unser(Stream& s, std::string& v)
535 {
536 size_t size = ReadCompactSize(s);
537 if (size > Limit) {
538 throw std::ios_base::failure("String length limit exceeded");
539 }
540 v.resize(size);
541 if (size != 0) s.read((char*)v.data(), size);
542 }
543
544 template<typename Stream>
545 void Ser(Stream& s, const std::string& v)
546 {
547 s << v;
548 }
549};
550
564template<class Formatter>
566{
567 template<typename Stream, typename V>
568 void Ser(Stream& s, const V& v)
569 {
570 Formatter formatter;
571 WriteCompactSize(s, v.size());
572 for (const typename V::value_type& elem : v) {
573 formatter.Ser(s, elem);
574 }
575 }
576
577 template<typename Stream, typename V>
578 void Unser(Stream& s, V& v)
579 {
580 Formatter formatter;
581 v.clear();
582 size_t size = ReadCompactSize(s);
583 size_t allocated = 0;
584 while (allocated < size) {
585 // For DoS prevention, do not blindly allocate as much as the stream claims to contain.
586 // Instead, allocate in 5MiB batches, so that an attacker actually needs to provide
587 // X MiB of data to make us allocate X+5 Mib.
588 static_assert(sizeof(typename V::value_type) <= MAX_VECTOR_ALLOCATE, "Vector element size too large");
589 allocated = std::min(size, allocated + MAX_VECTOR_ALLOCATE / sizeof(typename V::value_type));
590 v.reserve(allocated);
591 while (v.size() < allocated) {
592 v.emplace_back();
593 formatter.Unser(s, v.back());
594 }
595 }
596 };
597};
598
606template<typename Stream, typename C> void Serialize(Stream& os, const std::basic_string<C>& str);
607template<typename Stream, typename C> void Unserialize(Stream& is, std::basic_string<C>& str);
608
613template<typename Stream, unsigned int N, typename T> void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&);
614template<typename Stream, unsigned int N, typename T, typename V> void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&);
615template<typename Stream, unsigned int N, typename T> inline void Serialize(Stream& os, const prevector<N, T>& v);
616template<typename Stream, unsigned int N, typename T> void Unserialize_impl(Stream& is, prevector<N, T>& v, const unsigned char&);
617template<typename Stream, unsigned int N, typename T, typename V> void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&);
618template<typename Stream, unsigned int N, typename T> inline void Unserialize(Stream& is, prevector<N, T>& v);
619
624template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&);
625template<typename Stream, typename T, typename A> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&);
626template<typename Stream, typename T, typename A, typename V> void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&);
627template<typename Stream, typename T, typename A> inline void Serialize(Stream& os, const std::vector<T, A>& v);
628template<typename Stream, typename T, typename A> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&);
629template<typename Stream, typename T, typename A, typename V> void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&);
630template<typename Stream, typename T, typename A> inline void Unserialize(Stream& is, std::vector<T, A>& v);
631
635template<typename Stream, typename K, typename T> void Serialize(Stream& os, const std::pair<K, T>& item);
636template<typename Stream, typename K, typename T> void Unserialize(Stream& is, std::pair<K, T>& item);
637
641template<typename Stream, typename K, typename T, typename Pred, typename A> void Serialize(Stream& os, const std::map<K, T, Pred, A>& m);
642template<typename Stream, typename K, typename T, typename Pred, typename A> void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
643
647template<typename Stream, typename K, typename Pred, typename A> void Serialize(Stream& os, const std::set<K, Pred, A>& m);
648template<typename Stream, typename K, typename Pred, typename A> void Unserialize(Stream& is, std::set<K, Pred, A>& m);
649
653template<typename Stream, typename T> void Serialize(Stream& os, const std::shared_ptr<const T>& p);
654template<typename Stream, typename T> void Unserialize(Stream& os, std::shared_ptr<const T>& p);
655
659template<typename Stream, typename T> void Serialize(Stream& os, const std::unique_ptr<const T>& p);
660template<typename Stream, typename T> void Unserialize(Stream& os, std::unique_ptr<const T>& p);
661
662
663
667template<typename Stream, typename T>
668inline void Serialize(Stream& os, const T& a)
669{
670 a.Serialize(os);
671}
672
673template<typename Stream, typename T>
674inline void Unserialize(Stream& is, T&& a)
675{
676 a.Unserialize(is);
677}
678
685{
686 template<typename Stream, typename T>
687 static void Ser(Stream& s, const T& t) { Serialize(s, t); }
688
689 template<typename Stream, typename T>
690 static void Unser(Stream& s, T& t) { Unserialize(s, t); }
691};
692
693
694
695
696
700template<typename Stream, typename C>
701void Serialize(Stream& os, const std::basic_string<C>& str)
702{
703 WriteCompactSize(os, str.size());
704 if (!str.empty())
705 os.write((char*)str.data(), str.size() * sizeof(C));
706}
707
708template<typename Stream, typename C>
709void Unserialize(Stream& is, std::basic_string<C>& str)
710{
711 unsigned int nSize = ReadCompactSize(is);
712 str.resize(nSize);
713 if (nSize != 0)
714 is.read((char*)str.data(), nSize * sizeof(C));
715}
716
717
718
722template<typename Stream, unsigned int N, typename T>
723void Serialize_impl(Stream& os, const prevector<N, T>& v, const unsigned char&)
724{
725 WriteCompactSize(os, v.size());
726 if (!v.empty())
727 os.write((char*)v.data(), v.size() * sizeof(T));
728}
729
730template<typename Stream, unsigned int N, typename T, typename V>
731void Serialize_impl(Stream& os, const prevector<N, T>& v, const V&)
732{
734}
735
736template<typename Stream, unsigned int N, typename T>
737inline void Serialize(Stream& os, const prevector<N, T>& v)
738{
739 Serialize_impl(os, v, T());
740}
741
742
743template<typename Stream, unsigned int N, typename T>
744void Unserialize_impl(Stream& is, prevector<N, T>& 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_uninitialized(i + blk);
754 is.read((char*)&v[i], blk * sizeof(T));
755 i += blk;
756 }
757}
758
759template<typename Stream, unsigned int N, typename T, typename V>
760void Unserialize_impl(Stream& is, prevector<N, T>& v, const V&)
761{
763}
764
765template<typename Stream, unsigned int N, typename T>
766inline void Unserialize(Stream& is, prevector<N, T>& v)
767{
768 Unserialize_impl(is, v, T());
769}
770
771
772
776template<typename Stream, typename T, typename A>
777void Serialize_impl(Stream& os, const std::vector<T, A>& v, const unsigned char&)
778{
779 WriteCompactSize(os, v.size());
780 if (!v.empty())
781 os.write((char*)v.data(), v.size() * sizeof(T));
782}
783
784template<typename Stream, typename T, typename A>
785void Serialize_impl(Stream& os, const std::vector<T, A>& v, const bool&)
786{
787 // A special case for std::vector<bool>, as dereferencing
788 // std::vector<bool>::const_iterator does not result in a const bool&
789 // due to std::vector's special casing for bool arguments.
790 WriteCompactSize(os, v.size());
791 for (bool elem : v) {
792 ::Serialize(os, elem);
793 }
794}
795
796template<typename Stream, typename T, typename A, typename V>
797void Serialize_impl(Stream& os, const std::vector<T, A>& v, const V&)
798{
800}
801
802template<typename Stream, typename T, typename A>
803inline void Serialize(Stream& os, const std::vector<T, A>& v)
804{
805 Serialize_impl(os, v, T());
806}
807
808
809template<typename Stream, typename T, typename A>
810void Unserialize_impl(Stream& is, std::vector<T, A>& v, const unsigned char&)
811{
812 // Limit size per read so bogus size value won't cause out of memory
813 v.clear();
814 unsigned int nSize = ReadCompactSize(is);
815 unsigned int i = 0;
816 while (i < nSize)
817 {
818 unsigned int blk = std::min(nSize - i, (unsigned int)(1 + 4999999 / sizeof(T)));
819 v.resize(i + blk);
820 is.read((char*)&v[i], blk * sizeof(T));
821 i += blk;
822 }
823}
824
825template<typename Stream, typename T, typename A, typename V>
826void Unserialize_impl(Stream& is, std::vector<T, A>& v, const V&)
827{
829}
830
831template<typename Stream, typename T, typename A>
832inline void Unserialize(Stream& is, std::vector<T, A>& v)
833{
834 Unserialize_impl(is, v, T());
835}
836
837
838
842template<typename Stream, typename K, typename T>
843void Serialize(Stream& os, const std::pair<K, T>& item)
844{
845 Serialize(os, item.first);
846 Serialize(os, item.second);
847}
848
849template<typename Stream, typename K, typename T>
850void Unserialize(Stream& is, std::pair<K, T>& item)
851{
852 Unserialize(is, item.first);
853 Unserialize(is, item.second);
854}
855
856
857
861template<typename Stream, typename K, typename T, typename Pred, typename A>
862void Serialize(Stream& os, const std::map<K, T, Pred, A>& m)
863{
864 WriteCompactSize(os, m.size());
865 for (const auto& entry : m)
866 Serialize(os, entry);
867}
868
869template<typename Stream, typename K, typename T, typename Pred, typename A>
870void Unserialize(Stream& is, std::map<K, T, Pred, A>& m)
871{
872 m.clear();
873 unsigned int nSize = ReadCompactSize(is);
874 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
875 for (unsigned int i = 0; i < nSize; i++)
876 {
877 std::pair<K, T> item;
878 Unserialize(is, item);
879 mi = m.insert(mi, item);
880 }
881}
882
883
884
888template<typename Stream, typename K, typename Pred, typename A>
889void Serialize(Stream& os, const std::set<K, Pred, A>& m)
890{
891 WriteCompactSize(os, m.size());
892 for (typename std::set<K, Pred, A>::const_iterator it = m.begin(); it != m.end(); ++it)
893 Serialize(os, (*it));
894}
895
896template<typename Stream, typename K, typename Pred, typename A>
897void Unserialize(Stream& is, std::set<K, Pred, A>& m)
898{
899 m.clear();
900 unsigned int nSize = ReadCompactSize(is);
901 typename std::set<K, Pred, A>::iterator it = m.begin();
902 for (unsigned int i = 0; i < nSize; i++)
903 {
904 K key;
905 Unserialize(is, key);
906 it = m.insert(it, key);
907 }
908}
909
910
911
915template<typename Stream, typename T> void
916Serialize(Stream& os, const std::unique_ptr<const T>& p)
917{
918 Serialize(os, *p);
919}
920
921template<typename Stream, typename T>
922void Unserialize(Stream& is, std::unique_ptr<const T>& p)
923{
924 p.reset(new T(deserialize, is));
925}
926
927
928
932template<typename Stream, typename T> void
933Serialize(Stream& os, const std::shared_ptr<const T>& p)
934{
935 Serialize(os, *p);
936}
937
938template<typename Stream, typename T>
939void Unserialize(Stream& is, std::shared_ptr<const T>& p)
940{
941 p = std::make_shared<const T>(deserialize, is);
942}
943
944
945
950{
951 constexpr bool ForRead() const { return false; }
952};
954{
955 constexpr bool ForRead() const { return true; }
956};
957
958
959
960
961
962
963
964
965/* ::GetSerializeSize implementations
966 *
967 * Computing the serialized size of objects is done through a special stream
968 * object of type CSizeComputer, which only records the number of bytes written
969 * to it.
970 *
971 * If your Serialize or SerializationOp method has non-trivial overhead for
972 * serialization, it may be worthwhile to implement a specialized version for
973 * CSizeComputer, which uses the s.seek() method to record bytes that would
974 * be written instead.
975 */
977{
978protected:
979 size_t nSize;
980
981 const int nVersion;
982public:
983 explicit CSizeComputer(int nVersionIn) : nSize(0), nVersion(nVersionIn) {}
984
985 void write(const char *psz, size_t _nSize)
986 {
987 this->nSize += _nSize;
988 }
989
991 void seek(size_t _nSize)
992 {
993 this->nSize += _nSize;
994 }
995
996 template<typename T>
998 {
999 ::Serialize(*this, obj);
1000 return (*this);
1001 }
1002
1003 size_t size() const {
1004 return nSize;
1005 }
1006
1007 int GetVersion() const { return nVersion; }
1008};
1009
1010template<typename Stream>
1011void SerializeMany(Stream& s)
1012{
1013}
1014
1015template<typename Stream, typename Arg, typename... Args>
1016void SerializeMany(Stream& s, const Arg& arg, const Args&... args)
1017{
1018 ::Serialize(s, arg);
1019 ::SerializeMany(s, args...);
1020}
1021
1022template<typename Stream>
1023inline void UnserializeMany(Stream& s)
1024{
1025}
1026
1027template<typename Stream, typename Arg, typename... Args>
1028inline void UnserializeMany(Stream& s, Arg&& arg, Args&&... args)
1029{
1030 ::Unserialize(s, arg);
1031 ::UnserializeMany(s, args...);
1032}
1033
1034template<typename Stream, typename... Args>
1035inline void SerReadWriteMany(Stream& s, CSerActionSerialize ser_action, const Args&... args)
1036{
1037 ::SerializeMany(s, args...);
1038}
1039
1040template<typename Stream, typename... Args>
1041inline void SerReadWriteMany(Stream& s, CSerActionUnserialize ser_action, Args&&... args)
1042{
1043 ::UnserializeMany(s, args...);
1044}
1045
1046template<typename Stream, typename Type, typename Fn>
1047inline void SerRead(Stream& s, CSerActionSerialize ser_action, Type&&, Fn&&)
1048{
1049}
1050
1051template<typename Stream, typename Type, typename Fn>
1052inline void SerRead(Stream& s, CSerActionUnserialize ser_action, Type&& obj, Fn&& fn)
1053{
1054 fn(s, std::forward<Type>(obj));
1055}
1056
1057template<typename Stream, typename Type, typename Fn>
1058inline void SerWrite(Stream& s, CSerActionSerialize ser_action, Type&& obj, Fn&& fn)
1059{
1060 fn(s, std::forward<Type>(obj));
1061}
1062
1063template<typename Stream, typename Type, typename Fn>
1064inline void SerWrite(Stream& s, CSerActionUnserialize ser_action, Type&&, Fn&&)
1065{
1066}
1067
1068template<typename I>
1069inline void WriteVarInt(CSizeComputer &s, I n)
1070{
1071 s.seek(GetSizeOfVarInt<I>(n));
1072}
1073
1074inline void WriteCompactSize(CSizeComputer &s, uint64_t nSize)
1075{
1076 s.seek(GetSizeOfCompactSize(nSize));
1077}
1078
1079template <typename T>
1080size_t GetSerializeSize(const T& t, int nVersion = 0)
1081{
1082 return (CSizeComputer(nVersion) << t).size();
1083}
1084
1085template <typename... T>
1086size_t GetSerializeSizeMany(int nVersion, const T&... t)
1087{
1088 CSizeComputer sc(nVersion);
1089 SerializeMany(sc, t...);
1090 return sc.size();
1091}
1092
1093#endif // BITCOIN_SERIALIZE_H
CSizeComputer & operator<<(const T &obj)
Definition: serialize.h:997
void write(const char *psz, size_t _nSize)
Definition: serialize.h:985
CSizeComputer(int nVersionIn)
Definition: serialize.h:983
size_t nSize
Definition: serialize.h:979
size_t size() const
Definition: serialize.h:1003
const int nVersion
Definition: serialize.h:981
void seek(size_t _nSize)
Pretend _nSize bytes are written, without specifying them.
Definition: serialize.h:991
int GetVersion() const
Definition: serialize.h:1007
A Span is an object that can refer to a contiguous sequence of objects.
Definition: span.h:93
constexpr std::size_t size() const noexcept
Definition: span.h:182
constexpr C * data() const noexcept
Definition: span.h:169
Simple wrapper class to serialize objects using a formatter; used by Using().
Definition: serialize.h:419
Wrapper(T obj)
Definition: serialize.h:424
T m_object
Definition: serialize.h:420
void Serialize(Stream &s) const
Definition: serialize.h:425
void Unserialize(Stream &s)
Definition: serialize.h:426
Implements a drop-in replacement for std::vector<T> which stores up to N elements directly (without h...
Definition: prevector.h:37
bool empty() const
Definition: prevector.h:286
void clear()
Definition: prevector.h:343
size_type size() const
Definition: prevector.h:282
value_type * data()
Definition: prevector.h:528
void resize_uninitialized(size_type new_size)
Definition: prevector.h:386
uint16_t be16toh(uint16_t big_endian_16bits)
Definition: endian.h:170
uint16_t htobe16(uint16_t host_16bits)
Definition: endian.h:156
uint32_t le32toh(uint32_t little_endian_32bits)
Definition: endian.h:205
uint32_t htobe32(uint32_t host_32bits)
Definition: endian.h:184
uint16_t le16toh(uint16_t little_endian_16bits)
Definition: endian.h:177
uint64_t htobe64(uint64_t host_64bits)
Definition: endian.h:212
uint64_t be64toh(uint64_t big_endian_64bits)
Definition: endian.h:226
uint32_t be32toh(uint32_t big_endian_32bits)
Definition: endian.h:198
uint64_t htole64(uint64_t host_64bits)
Definition: endian.h:219
uint32_t htole32(uint32_t host_32bits)
Definition: endian.h:191
uint16_t htole16(uint16_t host_16bits)
Definition: endian.h:163
uint64_t le64toh(uint64_t little_endian_64bits)
Definition: endian.h:233
#define T(expected, seed, data)
#define X(name)
Definition: net.cpp:574
void SerializeMany(Stream &s)
Definition: serialize.h:1011
@ SER_DISK
Definition: serialize.h:139
@ SER_NETWORK
Definition: serialize.h:138
@ SER_GETHASH
Definition: serialize.h:140
static const unsigned int MAX_VECTOR_ALLOCATE
Maximum amount of memory (in bytes) to allocate at once when deserializing vectors.
Definition: serialize.h:34
uint8_t ser_readdata8(Stream &s)
Definition: serialize.h:89
I ReadVarInt(Stream &is)
Definition: serialize.h:395
void ser_writedata32be(Stream &s, uint32_t obj)
Definition: serialize.h:79
void WriteVarInt(CSizeComputer &os, I n)
Definition: serialize.h:1069
VarIntMode
Variable-length integers: bytes are a MSB base-128 encoding of the number.
Definition: serialize.h:348
@ NONNEGATIVE_SIGNED
void ser_writedata32(Stream &s, uint32_t obj)
Definition: serialize.h:74
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
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 byt...
Definition: serialize.h:240
constexpr deserialize_type deserialize
Definition: serialize.h:48
void Serialize(Stream &s, char a)
Definition: serialize.h:199
void ser_writedata16(Stream &s, uint16_t obj)
Definition: serialize.h:64
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:723
void SerReadWriteMany(Stream &s, CSerActionSerialize ser_action, const Args &... args)
Definition: serialize.h:1035
char * CharCast(char *c)
Safely convert odd char pointer types to standard ones.
Definition: serialize.h:51
void Unserialize_impl(Stream &is, prevector< N, T > &v, const unsigned char &)
Definition: serialize.h:744
void Unserialize(Stream &s, char &a)
Definition: serialize.h:215
X & ReadWriteAsHelper(X &x)
Convert the reference base type to X, without changing constness or reference type.
Definition: serialize.h:144
void SerWrite(Stream &s, CSerActionSerialize ser_action, Type &&obj, Fn &&fn)
Definition: serialize.h:1058
void ser_writedata16be(Stream &s, uint16_t obj)
Definition: serialize.h:69
uint16_t ser_readdata16(Stream &s)
Definition: serialize.h:95
uint64_t ser_readdata64(Stream &s)
Definition: serialize.h:119
void ser_writedata8(Stream &s, uint8_t obj)
Definition: serialize.h:60
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
Definition: serialize.h:282
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class.
Definition: serialize.h:440
unsigned int GetSizeOfVarInt(I n)
Definition: serialize.h:360
uint32_t ser_readdata32(Stream &s)
Definition: serialize.h:107
uint16_t ser_readdata16be(Stream &s)
Definition: serialize.h:101
void SerRead(Stream &s, CSerActionSerialize ser_action, Type &&, Fn &&)
Definition: serialize.h:1047
size_t GetSerializeSize(const T &t, int nVersion=0)
Definition: serialize.h:1080
void UnserializeMany(Stream &s)
Definition: serialize.h:1023
size_t GetSerializeSizeMany(int nVersion, const T &... t)
Definition: serialize.h:1086
void ser_writedata64(Stream &s, uint64_t obj)
Definition: serialize.h:84
uint32_t ser_readdata32be(Stream &s)
Definition: serialize.h:113
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Definition: serialize.h:1074
Support for SERIALIZE_METHODS and READWRITE macro.
Definition: serialize.h:950
constexpr bool ForRead() const
Definition: serialize.h:951
constexpr bool ForRead() const
Definition: serialize.h:955
constexpr CheckVarIntMode()
Definition: serialize.h:352
Formatter for integers in CompactSize format.
Definition: serialize.h:509
void Unser(Stream &s, I &v)
Definition: serialize.h:511
void Ser(Stream &s, I v)
Definition: serialize.h:521
Serialization wrapper class for custom integers and enums.
Definition: serialize.h:473
static constexpr uint64_t MAX
Definition: serialize.h:475
void Ser(Stream &s, I v)
Definition: serialize.h:477
void Unser(Stream &s, I &v)
Definition: serialize.h:489
Default formatter.
Definition: serialize.h:685
static void Ser(Stream &s, const T &t)
Definition: serialize.h:687
static void Unser(Stream &s, T &t)
Definition: serialize.h:690
void Unser(Stream &s, std::string &v)
Definition: serialize.h:534
void Ser(Stream &s, const std::string &v)
Definition: serialize.h:545
Serialization wrapper class for integers in VarInt format.
Definition: serialize.h:450
void Ser(Stream &s, I v)
Definition: serialize.h:451
void Unser(Stream &s, I &v)
Definition: serialize.h:456
Formatter to serialize/deserialize vector elements using another formatter.
Definition: serialize.h:566
void Unser(Stream &s, V &v)
Definition: serialize.h:578
void Ser(Stream &s, const V &v)
Definition: serialize.h:568
Dummy data type to identify deserializing constructors.
Definition: serialize.h:47