6 #ifndef BITCOIN_SERIALIZE_H
7 #define BITCOIN_SERIALIZE_H
31 static constexpr uint64_t
MAX_SIZE = 0x02000000;
140 #define READWRITE(...) (::SerReadWriteMany(s, ser_action, __VA_ARGS__))
141 #define READWRITEAS(type, obj) (::SerReadWriteMany(s, ser_action, ReadWriteAsHelper<type>(obj)))
142 #define SER_READ(obj, code) ::SerRead(s, ser_action, obj, [&](Stream& s, typename std::remove_const<Type>::type& obj) { code; })
143 #define SER_WRITE(obj, code) ::SerWrite(s, ser_action, obj, [&](Stream& s, const Type& obj) { code; })
161 #define FORMATTER_METHODS(cls, obj) \
162 template<typename Stream> \
163 static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, CSerActionSerialize()); } \
164 template<typename Stream> \
165 static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, CSerActionUnserialize()); } \
166 template<typename Stream, typename Type, typename Operation> \
167 static inline void SerializationOps(Type& obj, Stream& s, Operation ser_action) \
176 #define SERIALIZE_METHODS(cls, obj) \
177 template<typename Stream> \
178 void Serialize(Stream& s) const \
180 static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \
183 template<typename Stream> \
184 void Unserialize(Stream& s) \
186 static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch"); \
189 FORMATTER_METHODS(cls, obj)
191 #ifndef CHAR_EQUALS_INT8
192 template <
typename Stream>
void Serialize(Stream&,
char) =
delete;
203 template<
typename Stream,
int N>
inline void Serialize(Stream& s,
const unsigned char (&a)[N]) { s.write(
MakeByteSpan(a)); }
207 #ifndef CHAR_EQUALS_INT8
208 template <
typename Stream>
void Unserialize(Stream&,
char) =
delete;
235 if (
nSize < 253)
return sizeof(
unsigned char);
236 else if (
nSize <= std::numeric_limits<uint16_t>::max())
return sizeof(
unsigned char) +
sizeof(uint16_t);
237 else if (
nSize <= std::numeric_limits<unsigned int>::max())
return sizeof(
unsigned char) +
sizeof(
unsigned int);
238 else return sizeof(
unsigned char) +
sizeof(uint64_t);
243 template<
typename Stream>
250 else if (
nSize <= std::numeric_limits<uint16_t>::max())
255 else if (
nSize <= std::numeric_limits<unsigned int>::max())
274 template<
typename Stream>
278 uint64_t nSizeRet = 0;
283 else if (chSize == 253)
287 throw std::ios_base::failure(
"non-canonical ReadCompactSize()");
289 else if (chSize == 254)
292 if (nSizeRet < 0x10000u)
293 throw std::ios_base::failure(
"non-canonical ReadCompactSize()");
298 if (nSizeRet < 0x100000000ULL)
299 throw std::ios_base::failure(
"non-canonical ReadCompactSize()");
301 if (range_check && nSizeRet >
MAX_SIZE) {
302 throw std::ios_base::failure(
"ReadCompactSize(): size too large");
343 template <VarIntMode Mode,
typename I>
347 static_assert(Mode !=
VarIntMode::DEFAULT || std::is_unsigned<I>::value,
"Unsigned type required with mode DEFAULT.");
352 template<VarIntMode Mode,
typename I>
369 template<
typename Stream, VarIntMode Mode,
typename I>
373 unsigned char tmp[(
sizeof(n)*8+6)/7];
376 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
387 template<
typename Stream, VarIntMode Mode,
typename I>
394 if (n > (std::numeric_limits<I>::max() >> 7)) {
395 throw std::ios_base::failure(
"ReadVarInt(): size too large");
397 n = (n << 7) | (chData & 0x7F);
399 if (n == std::numeric_limits<I>::max()) {
400 throw std::ios_base::failure(
"ReadVarInt(): size too large");
410 template<
typename Formatter,
typename T>
413 static_assert(std::is_lvalue_reference<T>::value,
"Wrapper needs an lvalue reference type T");
432 template<
typename Formatter,
typename T>
435 #define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
436 #define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
437 #define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj)
438 #define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj)
441 template<VarIntMode Mode>
444 template<
typename Stream,
typename I>
void Ser(Stream &s, I v)
446 WriteVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s, v);
449 template<
typename Stream,
typename I>
void Unser(Stream& s, I& v)
451 v = ReadVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s);
464 template<
int Bytes,
bool BigEndian = false>
467 static_assert(Bytes > 0 && Bytes <= 8,
"CustomUintFormatter Bytes out of range");
468 static constexpr uint64_t
MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
470 template <
typename Stream,
typename I>
void Ser(Stream& s, I v)
472 if (v < 0 || v >
MAX)
throw std::ios_base::failure(
"CustomUintFormatter value out of range");
475 s.write({
AsBytePtr(&raw) + 8 - Bytes, Bytes});
482 template <
typename Stream,
typename I>
void Unser(Stream& s, I& v)
484 using U =
typename std::conditional<std::is_enum<I>::value, std::underlying_type<I>, std::common_type<I>>::type::type;
485 static_assert(std::numeric_limits<U>::max() >=
MAX && std::numeric_limits<U>::min() <= 0,
"Assigned type too small");
488 s.read({
AsBytePtr(&raw) + 8 - Bytes, Bytes});
489 v =
static_cast<I
>(
be64toh(raw));
492 v =
static_cast<I
>(
le64toh(raw));
500 template<
bool RangeCheck>
503 template<
typename Stream,
typename I>
506 uint64_t n = ReadCompactSize<Stream>(s, RangeCheck);
507 if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
508 throw std::ios_base::failure(
"CompactSize exceeds limit of type");
513 template<
typename Stream,
typename I>
516 static_assert(std::is_unsigned<I>::value,
"CompactSize only supported for unsigned integers");
517 static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(),
"CompactSize only supports 64-bit integers and below");
519 WriteCompactSize<Stream>(s, v);
523 template <
typename U,
bool LOSSY = false>
525 template <
typename Stream,
typename Tp>
531 tp = Tp{
typename Tp::duration{
typename Tp::duration::rep{u}}};
533 template <
typename Stream,
typename Tp>
534 void Ser(Stream& s, Tp tp)
536 if constexpr (LOSSY) {
537 s << U(tp.time_since_epoch().count());
539 s << U{tp.time_since_epoch().count()};
543 template <
typename U>
553 template<
typename Stream>
555 WriteCompactSize<Stream>(s,
n);
559 template<
size_t Limit>
562 template<
typename Stream>
563 void Unser(Stream& s, std::string& v)
567 throw std::ios_base::failure(
"String length limit exceeded");
573 template<
typename Stream>
574 void Ser(Stream& s,
const std::string& v)
593 template<
class Formatter>
596 template<
typename Stream,
typename V>
597 void Ser(Stream& s,
const V& v)
601 for (
const typename V::value_type& elem : v) {
602 formatter.Ser(s, elem);
606 template<
typename Stream,
typename V>
612 size_t allocated = 0;
613 while (allocated < size) {
617 static_assert(
sizeof(
typename V::value_type) <=
MAX_VECTOR_ALLOCATE,
"Vector element size too large");
618 allocated = std::min(size, allocated +
MAX_VECTOR_ALLOCATE /
sizeof(
typename V::value_type));
619 v.reserve(allocated);
620 while (v.size() < allocated) {
622 formatter.Unser(s, v.back());
635 template<
typename Stream,
typename C>
void Serialize(Stream& os,
const std::basic_string<C>& str);
636 template<
typename Stream,
typename C>
void Unserialize(Stream& is, std::basic_string<C>& str);
653 template<
typename Stream,
typename T,
typename A>
void Serialize_impl(Stream& os,
const std::vector<T, A>& v,
const unsigned char&);
654 template<
typename Stream,
typename T,
typename A>
void Serialize_impl(Stream& os,
const std::vector<T, A>& v,
const bool&);
655 template<
typename Stream,
typename T,
typename A,
typename V>
void Serialize_impl(Stream& os,
const std::vector<T, A>& v,
const V&);
656 template<
typename Stream,
typename T,
typename A>
inline void Serialize(Stream& os,
const std::vector<T, A>& v);
657 template<
typename Stream,
typename T,
typename A>
void Unserialize_impl(Stream& is, std::vector<T, A>& v,
const unsigned char&);
658 template<
typename Stream,
typename T,
typename A,
typename V>
void Unserialize_impl(Stream& is, std::vector<T, A>& v,
const V&);
659 template<
typename Stream,
typename T,
typename A>
inline void Unserialize(Stream& is, std::vector<T, A>& v);
664 template<
typename Stream,
typename K,
typename T>
void Serialize(Stream& os,
const std::pair<K, T>& item);
665 template<
typename Stream,
typename K,
typename T>
void Unserialize(Stream& is, std::pair<K, T>& item);
670 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
void Serialize(Stream& os,
const std::map<K, T, Pred, A>& m);
671 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
676 template<
typename Stream,
typename K,
typename Pred,
typename A>
void Serialize(Stream& os,
const std::set<K, Pred, A>& m);
677 template<
typename Stream,
typename K,
typename Pred,
typename A>
void Unserialize(Stream& is, std::set<K, Pred, A>& m);
682 template<
typename Stream,
typename T>
void Serialize(Stream& os,
const std::shared_ptr<const T>& p);
683 template<
typename Stream,
typename T>
void Unserialize(Stream& os, std::shared_ptr<const T>& p);
688 template<
typename Stream,
typename T>
void Serialize(Stream& os,
const std::unique_ptr<const T>& p);
689 template<
typename Stream,
typename T>
void Unserialize(Stream& os, std::unique_ptr<const T>& p);
696 template<
typename Stream,
typename T>
702 template<
typename Stream,
typename T>
715 template<
typename Stream,
typename T>
718 template<
typename Stream,
typename T>
729 template<
typename Stream,
typename C>
730 void Serialize(Stream& os,
const std::basic_string<C>& str)
737 template<
typename Stream,
typename C>
751 template<
typename Stream,
unsigned int N,
typename T>
759 template<
typename Stream,
unsigned int N,
typename T,
typename V>
765 template<
typename Stream,
unsigned int N,
typename T>
772 template<
typename Stream,
unsigned int N,
typename T>
781 unsigned int blk = std::min(nSize - i, (
unsigned int)(1 + 4999999 /
sizeof(
T)));
788 template<
typename Stream,
unsigned int N,
typename T,
typename V>
794 template<
typename Stream,
unsigned int N,
typename T>
805 template<
typename Stream,
typename T,
typename A>
806 void Serialize_impl(Stream& os,
const std::vector<T, A>& v,
const unsigned char&)
813 template<
typename Stream,
typename T,
typename A>
820 for (
bool elem : v) {
825 template<
typename Stream,
typename T,
typename A,
typename V>
831 template<
typename Stream,
typename T,
typename A>
832 inline void Serialize(Stream& os,
const std::vector<T, A>& v)
838 template<
typename Stream,
typename T,
typename A>
847 unsigned int blk = std::min(nSize - i, (
unsigned int)(1 + 4999999 /
sizeof(
T)));
854 template<
typename Stream,
typename T,
typename A,
typename V>
860 template<
typename Stream,
typename T,
typename A>
871 template<
typename Stream,
typename K,
typename T>
878 template<
typename Stream,
typename K,
typename T>
890 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
891 void Serialize(Stream& os,
const std::map<K, T, Pred, A>& m)
894 for (
const auto& entry :
m)
898 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
903 typename std::map<K, T, Pred, A>::iterator mi =
m.begin();
904 for (
unsigned int i = 0; i < nSize; i++)
906 std::pair<K, T> item;
908 mi =
m.insert(mi, item);
917 template<
typename Stream,
typename K,
typename Pred,
typename A>
918 void Serialize(Stream& os,
const std::set<K, Pred, A>& m)
921 for (
typename std::set<K, Pred, A>::const_iterator it =
m.begin(); it !=
m.end(); ++it)
925 template<
typename Stream,
typename K,
typename Pred,
typename A>
930 typename std::set<K, Pred, A>::iterator it =
m.begin();
931 for (
unsigned int i = 0; i < nSize; i++)
935 it =
m.insert(it, key);
944 template<
typename Stream,
typename T>
void
945 Serialize(Stream& os,
const std::unique_ptr<const T>& p)
950 template<
typename Stream,
typename T>
961 template<
typename Stream,
typename T>
void
962 Serialize(Stream& os,
const std::shared_ptr<const T>& p)
967 template<
typename Stream,
typename T>
980 constexpr
bool ForRead()
const {
return false; }
984 constexpr
bool ForRead()
const {
return true; }
1022 this->
nSize += _nSize;
1025 template<
typename T>
1039 template<
typename Stream>
1044 template<
typename Stream,
typename Arg,
typename... Args>
1051 template<
typename Stream>
1056 template<
typename Stream,
typename Arg,
typename... Args>
1063 template<
typename Stream,
typename... Args>
1069 template<
typename Stream,
typename... Args>
1075 template<
typename Stream,
typename Type,
typename Fn>
1080 template<
typename Stream,
typename Type,
typename Fn>
1083 fn(s, std::forward<Type>(obj));
1086 template<
typename Stream,
typename Type,
typename Fn>
1089 fn(s, std::forward<Type>(obj));
1092 template<
typename Stream,
typename Type,
typename Fn>
1097 template<
typename I>
1100 s.
seek(GetSizeOfVarInt<I>(n));
1108 template <
typename T>
1114 template <
typename...
T>
CSizeComputer & operator<<(const T &obj)
void write(Span< const std::byte > src)
CSizeComputer(int nVersionIn)
void seek(size_t _nSize)
Pretend _nSize bytes are written, without specifying them.
void Serialize(Stream &s) const
CompactSizeWriter(uint64_t n_in)
A Span is an object that can refer to a contiguous sequence of objects.
constexpr std::size_t size() const noexcept
Simple wrapper class to serialize objects using a formatter; used by Using().
void Serialize(Stream &s) const
void Unserialize(Stream &s)
Implements a drop-in replacement for std::vector<T> which stores up to N elements directly (without h...
void resize_uninitialized(size_type new_size)
uint16_t be16toh(uint16_t big_endian_16bits)
uint16_t htobe16(uint16_t host_16bits)
uint32_t le32toh(uint32_t little_endian_32bits)
uint32_t htobe32(uint32_t host_32bits)
uint16_t le16toh(uint16_t little_endian_16bits)
uint64_t htobe64(uint64_t host_64bits)
uint64_t be64toh(uint64_t big_endian_64bits)
uint32_t be32toh(uint32_t big_endian_32bits)
uint64_t htole64(uint64_t host_64bits)
uint32_t htole32(uint32_t host_32bits)
uint16_t htole16(uint16_t host_16bits)
uint64_t le64toh(uint64_t little_endian_64bits)
#define T(expected, seed, data)
void SerializeMany(Stream &s)
static const unsigned int MAX_VECTOR_ALLOCATE
Maximum amount of memory (in bytes) to allocate at once when deserializing vectors.
uint8_t ser_readdata8(Stream &s)
void ser_writedata32be(Stream &s, uint32_t obj)
void WriteVarInt(CSizeComputer &os, I n)
VarIntMode
Variable-length integers: bytes are a MSB base-128 encoding of the number.
void ser_writedata32(Stream &s, uint32_t obj)
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...
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...
constexpr deserialize_type deserialize
void ser_writedata16(Stream &s, uint16_t obj)
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...
X & ReadWriteAsHelper(X &x)
Convert the reference base type to X, without changing constness or reference type.
void SerReadWriteMany(Stream &s, CSerActionSerialize ser_action, const Args &... args)
void Unserialize(Stream &, char)=delete
static Wrapper< Formatter, T & > Using(T &&t)
Cause serialization/deserialization of an object to be done using a specified formatter class.
void Unserialize_impl(Stream &is, prevector< N, T > &v, const unsigned char &)
void SerWrite(Stream &s, CSerActionSerialize ser_action, Type &&obj, Fn &&fn)
void ser_writedata16be(Stream &s, uint16_t obj)
uint16_t ser_readdata16(Stream &s)
uint64_t ser_readdata64(Stream &s)
void ser_writedata8(Stream &s, uint8_t obj)
uint64_t ReadCompactSize(Stream &is, bool range_check=true)
Decode a CompactSize-encoded variable-length integer.
unsigned int GetSizeOfVarInt(I n)
uint32_t ser_readdata32(Stream &s)
uint16_t ser_readdata16be(Stream &s)
void SerRead(Stream &s, CSerActionSerialize ser_action, Type &&, Fn &&)
size_t GetSerializeSize(const T &t, int nVersion=0)
void UnserializeMany(Stream &s)
size_t GetSerializeSizeMany(int nVersion, const T &... t)
void ser_writedata64(Stream &s, uint64_t obj)
uint32_t ser_readdata32be(Stream &s)
void Serialize(Stream &, char)=delete
void WriteCompactSize(CSizeComputer &os, uint64_t nSize)
Span< std::byte > AsWritableBytes(Span< T > s) noexcept
Span< const std::byte > MakeByteSpan(V &&v) noexcept
Span< const std::byte > AsBytes(Span< T > s) noexcept
const std::byte * AsBytePtr(const void *data)
Convert a data pointer to a std::byte data pointer.
Span< std::byte > MakeWritableByteSpan(V &&v) noexcept
Support for SERIALIZE_METHODS and READWRITE macro.
constexpr bool ForRead() const
constexpr bool ForRead() const
constexpr CheckVarIntMode()
Dummy data type to identify deserializing constructors.