6 #ifndef BITCOIN_SERIALIZE_H 7 #define BITCOIN_SERIALIZE_H 32 static constexpr uint64_t
MAX_SIZE = 0x02000000;
156 template <
class Out,
class In>
159 static_assert(std::is_base_of_v<Out, In>);
162 template <
class Out,
class In>
165 static_assert(std::is_base_of_v<Out, In>);
169 #define READWRITE(...) (ser_action.SerReadWriteMany(s, __VA_ARGS__)) 170 #define SER_READ(obj, code) ser_action.SerRead(s, obj, [&](Stream& s, typename std::remove_const<Type>::type& obj) { code; }) 171 #define SER_WRITE(obj, code) ser_action.SerWrite(s, obj, [&](Stream& s, const Type& obj) { code; }) 189 #define FORMATTER_METHODS(cls, obj) \ 190 template<typename Stream> \ 191 static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, ActionSerialize{}); } \ 192 template<typename Stream> \ 193 static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, ActionUnserialize{}); } \ 194 template<typename Stream, typename Type, typename Operation> \ 195 static void SerializationOps(Type& obj, Stream& s, Operation ser_action) 230 #define FORMATTER_METHODS_PARAMS(cls, obj, paramcls, paramobj) \ 231 template <typename Stream> \ 232 static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, ActionSerialize{}, s.GetParams()); } \ 233 template <typename Stream> \ 234 static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, ActionUnserialize{}, s.GetParams()); } \ 235 template <typename Stream, typename Type, typename Operation> \ 236 static void SerializationOps(Type& obj, Stream& s, Operation ser_action, const paramcls& paramobj) 238 #define BASE_SERIALIZE_METHODS(cls) \ 239 template <typename Stream> \ 240 void Serialize(Stream& s) const \ 242 static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \ 245 template <typename Stream> \ 246 void Unserialize(Stream& s) \ 248 static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch"); \ 259 #define SERIALIZE_METHODS(cls, obj) \ 260 BASE_SERIALIZE_METHODS(cls) \ 261 FORMATTER_METHODS(cls, obj) 268 #define SERIALIZE_METHODS_PARAMS(cls, obj, paramcls, paramobj) \ 269 BASE_SERIALIZE_METHODS(cls) \ 270 FORMATTER_METHODS_PARAMS(cls, obj, paramcls, paramobj) 273 #ifndef CHAR_EQUALS_INT8 274 template <
typename Stream>
void Serialize(Stream&,
char) =
delete;
286 template<
typename Stream,
int N>
inline void Serialize(Stream& s,
const unsigned char (&a)[N]) { s.write(
MakeByteSpan(a)); }
287 template <
typename Stream,
typename B, std::
size_t N>
void Serialize(Stream& s,
const std::array<B, N>& a) { (void)
UCharCast(a.data()); s.write(
MakeByteSpan(a)); }
290 #ifndef CHAR_EQUALS_INT8 291 template <
typename Stream>
void Unserialize(Stream&,
char) =
delete;
321 if (
nSize < 253)
return sizeof(
unsigned char);
322 else if (
nSize <= std::numeric_limits<uint16_t>::max())
return sizeof(
unsigned char) +
sizeof(uint16_t);
323 else if (
nSize <= std::numeric_limits<unsigned int>::max())
return sizeof(
unsigned char) +
sizeof(
unsigned int);
324 else return sizeof(
unsigned char) +
sizeof(uint64_t);
329 template<
typename Stream>
336 else if (
nSize <= std::numeric_limits<uint16_t>::max())
341 else if (
nSize <= std::numeric_limits<unsigned int>::max())
360 template<
typename Stream>
364 uint64_t nSizeRet = 0;
369 else if (chSize == 253)
373 throw std::ios_base::failure(
"non-canonical ReadCompactSize()");
375 else if (chSize == 254)
378 if (nSizeRet < 0x10000u)
379 throw std::ios_base::failure(
"non-canonical ReadCompactSize()");
384 if (nSizeRet < 0x100000000ULL)
385 throw std::ios_base::failure(
"non-canonical ReadCompactSize()");
387 if (range_check && nSizeRet >
MAX_SIZE) {
388 throw std::ios_base::failure(
"ReadCompactSize(): size too large");
429 template <VarIntMode Mode,
typename I>
433 static_assert(Mode !=
VarIntMode::DEFAULT || std::is_unsigned<I>::value,
"Unsigned type required with mode DEFAULT.");
438 template<VarIntMode Mode,
typename I>
455 template<
typename Stream, VarIntMode Mode,
typename I>
459 unsigned char tmp[(
sizeof(n)*8+6)/7];
462 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
473 template<
typename Stream, VarIntMode Mode,
typename I>
480 if (n > (std::numeric_limits<I>::max() >> 7)) {
481 throw std::ios_base::failure(
"ReadVarInt(): size too large");
483 n = (n << 7) | (chData & 0x7F);
485 if (n == std::numeric_limits<I>::max()) {
486 throw std::ios_base::failure(
"ReadVarInt(): size too large");
496 template<
typename Formatter,
typename T>
499 static_assert(std::is_lvalue_reference<T>::value,
"Wrapper needs an lvalue reference type T");
518 template<
typename Formatter,
typename T>
521 #define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj) 522 #define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj) 523 #define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj) 524 #define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj) 527 template<VarIntMode Mode>
530 template<
typename Stream,
typename I>
void Ser(Stream &s, I v)
532 WriteVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s, v);
535 template<
typename Stream,
typename I>
void Unser(Stream& s, I& v)
537 v = ReadVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s);
550 template<
int Bytes,
bool BigEndian = false>
553 static_assert(Bytes > 0 && Bytes <= 8,
"CustomUintFormatter Bytes out of range");
554 static constexpr uint64_t
MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
556 template <
typename Stream,
typename I>
void Ser(Stream& s, I v)
558 if (v < 0 || v >
MAX)
throw std::ios_base::failure(
"CustomUintFormatter value out of range");
568 template <
typename Stream,
typename I>
void Unser(Stream& s, I& v)
570 using U =
typename std::conditional<std::is_enum<I>::value, std::underlying_type<I>, std::common_type<I>>::type::type;
571 static_assert(std::numeric_limits<U>::max() >=
MAX && std::numeric_limits<U>::min() <= 0,
"Assigned type too small");
575 v =
static_cast<I
>(
be64toh(raw));
578 v =
static_cast<I
>(
le64toh(raw));
586 template<
bool RangeCheck>
589 template<
typename Stream,
typename I>
592 uint64_t n = ReadCompactSize<Stream>(s, RangeCheck);
593 if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
594 throw std::ios_base::failure(
"CompactSize exceeds limit of type");
599 template<
typename Stream,
typename I>
602 static_assert(std::is_unsigned<I>::value,
"CompactSize only supported for unsigned integers");
603 static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(),
"CompactSize only supports 64-bit integers and below");
605 WriteCompactSize<Stream>(s, v);
609 template <
typename U,
bool LOSSY = false>
611 template <
typename Stream,
typename Tp>
617 tp = Tp{
typename Tp::duration{
typename Tp::duration::rep{u}}};
619 template <
typename Stream,
typename Tp>
620 void Ser(Stream& s, Tp tp)
622 if constexpr (LOSSY) {
623 s << U(tp.time_since_epoch().count());
625 s << U{tp.time_since_epoch().count()};
629 template <
typename U>
639 template<
typename Stream>
641 WriteCompactSize<Stream>(s,
n);
645 template<
size_t Limit>
648 template<
typename Stream>
649 void Unser(Stream& s, std::string& v)
653 throw std::ios_base::failure(
"String length limit exceeded");
659 template<
typename Stream>
660 void Ser(Stream& s,
const std::string& v)
679 template<
class Formatter>
682 template<
typename Stream,
typename V>
683 void Ser(Stream& s,
const V& v)
687 for (
const typename V::value_type& elem : v) {
688 formatter.Ser(s, elem);
692 template<
typename Stream,
typename V>
698 size_t allocated = 0;
699 while (allocated < size) {
703 static_assert(
sizeof(
typename V::value_type) <=
MAX_VECTOR_ALLOCATE,
"Vector element size too large");
704 allocated = std::min(size, allocated +
MAX_VECTOR_ALLOCATE /
sizeof(
typename V::value_type));
705 v.reserve(allocated);
706 while (v.size() < allocated) {
708 formatter.Unser(s, v.back());
721 template<
typename Stream,
typename C>
void Serialize(Stream& os,
const std::basic_string<C>& str);
722 template<
typename Stream,
typename C>
void Unserialize(Stream& is, std::basic_string<C>& str);
735 template<
typename Stream,
typename T,
typename A>
inline void Serialize(Stream& os,
const std::vector<T, A>& v);
736 template<
typename Stream,
typename T,
typename A>
inline void Unserialize(Stream& is, std::vector<T, A>& v);
741 template<
typename Stream,
typename K,
typename T>
void Serialize(Stream& os,
const std::pair<K, T>& item);
742 template<
typename Stream,
typename K,
typename T>
void Unserialize(Stream& is, std::pair<K, T>& item);
747 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
void Serialize(Stream& os,
const std::map<K, T, Pred, A>& m);
748 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
753 template<
typename Stream,
typename K,
typename Pred,
typename A>
void Serialize(Stream& os,
const std::set<K, Pred, A>& m);
754 template<
typename Stream,
typename K,
typename Pred,
typename A>
void Unserialize(Stream& is, std::set<K, Pred, A>& m);
759 template<
typename Stream,
typename T>
void Serialize(Stream& os,
const std::shared_ptr<const T>& p);
760 template<
typename Stream,
typename T>
void Unserialize(Stream& os, std::shared_ptr<const T>& p);
765 template<
typename Stream,
typename T>
void Serialize(Stream& os,
const std::unique_ptr<const T>& p);
766 template<
typename Stream,
typename T>
void Unserialize(Stream& os, std::unique_ptr<const T>& p);
773 template<
typename Stream,
typename T>
779 template<
typename Stream,
typename T>
792 template<
typename Stream,
typename T>
795 template<
typename Stream,
typename T>
806 template<
typename Stream,
typename C>
807 void Serialize(Stream& os,
const std::basic_string<C>& str)
814 template<
typename Stream,
typename C>
828 template <
typename Stream,
unsigned int N,
typename T>
831 if constexpr (std::is_same_v<T, unsigned char>) {
841 template <
typename Stream,
unsigned int N,
typename T>
844 if constexpr (std::is_same_v<T, unsigned char>) {
850 unsigned int blk = std::min(nSize - i, (
unsigned int)(1 + 4999999 /
sizeof(
T)));
864 template <
typename Stream,
typename T,
typename A>
867 if constexpr (std::is_same_v<T, unsigned char>) {
871 }
else if constexpr (std::is_same_v<T, bool>) {
876 for (
bool elem : v) {
885 template <
typename Stream,
typename T,
typename A>
888 if constexpr (std::is_same_v<T, unsigned char>) {
894 unsigned int blk = std::min(nSize - i, (
unsigned int)(1 + 4999999 /
sizeof(
T)));
908 template<
typename Stream,
typename K,
typename T>
915 template<
typename Stream,
typename K,
typename T>
927 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
928 void Serialize(Stream& os,
const std::map<K, T, Pred, A>& m)
931 for (
const auto& entry :
m)
935 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
940 typename std::map<K, T, Pred, A>::iterator mi =
m.begin();
941 for (
unsigned int i = 0; i < nSize; i++)
943 std::pair<K, T> item;
945 mi =
m.insert(mi, item);
954 template<
typename Stream,
typename K,
typename Pred,
typename A>
955 void Serialize(Stream& os,
const std::set<K, Pred, A>& m)
958 for (
typename std::set<K, Pred, A>::const_iterator it =
m.begin(); it !=
m.end(); ++it)
962 template<
typename Stream,
typename K,
typename Pred,
typename A>
967 typename std::set<K, Pred, A>::iterator it =
m.begin();
968 for (
unsigned int i = 0; i < nSize; i++)
972 it =
m.insert(it, key);
981 template<
typename Stream,
typename T>
void 982 Serialize(Stream& os,
const std::unique_ptr<const T>& p)
987 template<
typename Stream,
typename T>
998 template<
typename Stream,
typename T>
void 999 Serialize(Stream& os,
const std::shared_ptr<const T>& p)
1004 template<
typename Stream,
typename T>
1014 template <
typename Stream,
typename... Args>
1020 template <
typename Stream,
typename... Args>
1032 template<
typename Stream,
typename... Args>
1038 template<
typename Stream,
typename Type,
typename Fn>
1043 template<
typename Stream,
typename Type,
typename Fn>
1046 fn(s, std::forward<Type>(obj));
1052 template<
typename Stream,
typename... Args>
1058 template<
typename Stream,
typename Type,
typename Fn>
1059 static void SerRead(Stream& s, Type&& obj, Fn&& fn)
1061 fn(s, std::forward<Type>(obj));
1064 template<
typename Stream,
typename Type,
typename Fn>
1098 this->
nSize += _nSize;
1101 template<
typename T>
1115 template<
typename I>
1118 s.
seek(GetSizeOfVarInt<I>(n));
1126 template <
typename T>
1132 template <
typename...
T>
1141 template <
typename Params,
typename SubStream>
1162 template <
typename Params,
typename T>
1171 template <
typename Stream>
1177 template <
typename Stream>
1190 template <
typename Params,
typename T>
1205 #define SER_PARAMS_OPFUNC \ 1206 template <typename T> \ 1207 auto operator()(T&& t) const { return WithParams(*this, t); } 1209 #endif // BITCOIN_SERIALIZE_H Wrapper that overrides the GetParams() function of a stream (and hides GetVersion/GetType).
CSizeComputer(int nVersionIn)
void read(Span< std::byte > dst)
static void SerWrite(Stream &s, Type &&obj, Fn &&fn)
void Serialize(Stream &s) const
uint8_t ser_readdata8(Stream &s)
static void SerWrite(Stream &s, Type &&, Fn &&)
Out & AsBase(In &x)
Convert any argument to a reference to X, maintaining constness.
void ser_writedata64(Stream &s, uint64_t obj)
Span< std::byte > AsWritableBytes(Span< T > s) noexcept
void WriteVarInt(CSizeComputer &os, I n)
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
const Params & GetParams() const
uint64_t htobe64(uint64_t host_64bits)
void Unserialize(Stream &, char)=delete
static const unsigned int MAX_VECTOR_ALLOCATE
Maximum amount of memory (in bytes) to allocate at once when deserializing vectors.
Span< std::byte > MakeWritableByteSpan(V &&v) noexcept
void ser_writedata32(Stream &s, uint32_t obj)
constexpr deserialize_type deserialize
constexpr std::size_t size() const noexcept
static void SerRead(Stream &s, Type &&obj, Fn &&fn)
uint32_t be32toh(uint32_t big_endian_32bits)
void Unserialize(Stream &s)
void resize_uninitialized(size_type new_size)
static constexpr bool ForRead()
Wrapper that serializes objects with the specified parameters.
Simple wrapper class to serialize objects using a formatter; used by Using().
uint32_t htole32(uint32_t host_32bits)
Dummy data type to identify deserializing constructors.
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class...
Support for all macros providing or using the ser_action parameter of the SerializationOps method...
size_t GetSerializeSize(const T &t, int nVersion=0)
static void SerReadWriteMany(Stream &s, Args &&... args)
uint32_t htobe32(uint32_t host_32bits)
void Serialize(Stream &s) const
CSizeComputer & operator<<(const T &obj)
uint64_t be64toh(uint64_t big_endian_64bits)
uint16_t ser_readdata16(Stream &s)
uint32_t ser_readdata32(Stream &s)
constexpr CheckVarIntMode()
void ser_writedata16(Stream &s, uint16_t obj)
void write(Span< const std::byte > src)
uint16_t htobe16(uint16_t host_16bits)
void Serialize(Stream &, char)=delete
static auto WithParams(const Params ¶ms, T &&t)
Return a wrapper around t that (de)serializes it with specified parameter params. ...
VarIntMode
Variable-length integers: bytes are a MSB base-128 encoding of the number.
uint16_t le16toh(uint16_t little_endian_16bits)
void ser_writedata32be(Stream &s, uint32_t obj)
static void SerRead(Stream &s, Type &&, Fn &&)
uint64_t ser_readdata64(Stream &s)
static void SerReadWriteMany(Stream &s, const Args &... args)
void write(Span< const std::byte > src)
void seek(size_t _nSize)
Pretend _nSize bytes are written, without specifying them.
uint16_t htole16(uint16_t host_16bits)
uint16_t ser_readdata16be(Stream &s)
uint64_t le64toh(uint64_t little_endian_64bits)
uint16_t be16toh(uint16_t big_endian_16bits)
constexpr C * data() const noexcept
const CChainParams & Params()
Return the currently selected parameters.
static constexpr bool ForRead()
ParamsStream & operator<<(const U &obj)
ParamsStream(const Params ¶ms LIFETIMEBOUND, SubStream &substream LIFETIMEBOUND)
uint64_t htole64(uint64_t host_64bits)
Span< const std::byte > MakeByteSpan(V &&v) noexcept
ParamsWrapper(const Params ¶ms, T &obj)
uint32_t ser_readdata32be(Stream &s)
unsigned int GetSizeOfVarInt(I n)
size_t GetSerializeSizeMany(int nVersion, const T &... t)
Span< const std::byte > AsBytes(Span< T > s) noexcept
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...
void ser_writedata16be(Stream &s, uint16_t obj)
unsigned char * UCharCast(char *c)
void Unserialize(Stream &s)
void SerializeMany(Stream &s, const Args &... args)
Support for (un)serializing many things at once.
A Span is an object that can refer to a contiguous sequence of objects.
ParamsStream & operator>>(U &&obj)
uint32_t le32toh(uint32_t little_endian_32bits)
constexpr unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX –...
#define T(expected, seed, data)
void UnserializeMany(Stream &s, Args &&... args)
void ser_writedata8(Stream &s, uint8_t obj)
CompactSizeWriter(uint64_t n_in)
void Serialize(Stream &s) const