6 #ifndef BITCOIN_SERIALIZE_H
7 #define BITCOIN_SERIALIZE_H
31 static constexpr uint64_t
MAX_SIZE = 0x02000000;
52 inline char*
CharCast(
unsigned char* c) {
return (
char*)c; }
53 inline const char*
CharCast(
const char* c) {
return c; }
54 inline const char*
CharCast(
const unsigned char* c) {
return (
const char*)c; }
62 s.write((
char*)&obj, 1);
67 s.write((
char*)&obj, 2);
72 s.write((
char*)&obj, 2);
77 s.write((
char*)&obj, 4);
82 s.write((
char*)&obj, 4);
87 s.write((
char*)&obj, 8);
92 s.read((
char*)&obj, 1);
98 s.read((
char*)&obj, 2);
104 s.read((
char*)&obj, 2);
110 s.read((
char*)&obj, 4);
116 s.read((
char*)&obj, 4);
122 s.read((
char*)&obj, 8);
129 static_assert(
sizeof(tmp) ==
sizeof(x),
"double and uint64_t assumed to have the same size");
136 static_assert(
sizeof(tmp) ==
sizeof(x),
"float and uint32_t assumed to have the same size");
143 static_assert(
sizeof(tmp) ==
sizeof(y),
"double and uint64_t assumed to have the same size");
150 static_assert(
sizeof(tmp) ==
sizeof(y),
"float and uint32_t assumed to have the same size");
175 #define READWRITE(...) (::SerReadWriteMany(s, ser_action, __VA_ARGS__))
176 #define READWRITEAS(type, obj) (::SerReadWriteMany(s, ser_action, ReadWriteAsHelper<type>(obj)))
177 #define SER_READ(obj, code) ::SerRead(s, ser_action, obj, [&](Stream& s, typename std::remove_const<Type>::type& obj) { code; })
178 #define SER_WRITE(obj, code) ::SerWrite(s, ser_action, obj, [&](Stream& s, const Type& obj) { code; })
196 #define FORMATTER_METHODS(cls, obj) \
197 template<typename Stream> \
198 static void Ser(Stream& s, const cls& obj) { SerializationOps(obj, s, CSerActionSerialize()); } \
199 template<typename Stream> \
200 static void Unser(Stream& s, cls& obj) { SerializationOps(obj, s, CSerActionUnserialize()); } \
201 template<typename Stream, typename Type, typename Operation> \
202 static inline void SerializationOps(Type& obj, Stream& s, Operation ser_action) \
211 #define SERIALIZE_METHODS(cls, obj) \
212 template<typename Stream> \
213 void Serialize(Stream& s) const \
215 static_assert(std::is_same<const cls&, decltype(*this)>::value, "Serialize type mismatch"); \
218 template<typename Stream> \
219 void Unserialize(Stream& s) \
221 static_assert(std::is_same<cls&, decltype(*this)>::value, "Unserialize type mismatch"); \
224 FORMATTER_METHODS(cls, obj)
226 #ifndef CHAR_EQUALS_INT8
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); }
244 #ifndef CHAR_EQUALS_INT8
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); }
278 if (nSize < 253)
return sizeof(
unsigned char);
279 else if (nSize <= std::numeric_limits<uint16_t>::max())
return sizeof(
unsigned char) +
sizeof(uint16_t);
280 else if (nSize <= std::numeric_limits<unsigned int>::max())
return sizeof(
unsigned char) +
sizeof(
unsigned int);
281 else return sizeof(
unsigned char) +
sizeof(uint64_t);
286 template<
typename Stream>
293 else if (nSize <= std::numeric_limits<uint16_t>::max())
298 else if (nSize <= std::numeric_limits<unsigned int>::max())
317 template<
typename Stream>
321 uint64_t nSizeRet = 0;
326 else if (chSize == 253)
330 throw std::ios_base::failure(
"non-canonical ReadCompactSize()");
332 else if (chSize == 254)
335 if (nSizeRet < 0x10000u)
336 throw std::ios_base::failure(
"non-canonical ReadCompactSize()");
341 if (nSizeRet < 0x100000000ULL)
342 throw std::ios_base::failure(
"non-canonical ReadCompactSize()");
344 if (range_check && nSizeRet >
MAX_SIZE) {
345 throw std::ios_base::failure(
"ReadCompactSize(): size too large");
386 template <VarIntMode Mode,
typename I>
390 static_assert(Mode !=
VarIntMode::DEFAULT || std::is_unsigned<I>::value,
"Unsigned type required with mode DEFAULT.");
395 template<VarIntMode Mode,
typename I>
412 template<
typename Stream, VarIntMode Mode,
typename I>
416 unsigned char tmp[(
sizeof(n)*8+6)/7];
419 tmp[len] = (n & 0x7F) | (len ? 0x80 : 0x00);
430 template<
typename Stream, VarIntMode Mode,
typename I>
437 if (n > (std::numeric_limits<I>::max() >> 7)) {
438 throw std::ios_base::failure(
"ReadVarInt(): size too large");
440 n = (n << 7) | (chData & 0x7F);
442 if (n == std::numeric_limits<I>::max()) {
443 throw std::ios_base::failure(
"ReadVarInt(): size too large");
453 template<
typename Formatter,
typename T>
456 static_assert(std::is_lvalue_reference<T>::value,
"Wrapper needs an lvalue reference type T");
460 explicit Wrapper(T obj) : m_object(obj) {}
461 template<
typename Stream>
void Serialize(Stream &s)
const { Formatter().Ser(s, m_object); }
462 template<
typename Stream>
void Unserialize(Stream &s) { Formatter().Unser(s, m_object); }
475 template<
typename Formatter,
typename T>
478 #define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
479 #define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
480 #define COMPACTSIZE(obj) Using<CompactSizeFormatter<true>>(obj)
481 #define LIMITED_STRING(obj,n) Using<LimitedStringFormatter<n>>(obj)
484 template<VarIntMode Mode>
487 template<
typename Stream,
typename I>
void Ser(Stream &s, I v)
489 WriteVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s, v);
492 template<
typename Stream,
typename I>
void Unser(Stream& s, I& v)
494 v = ReadVarInt<Stream,Mode,typename std::remove_cv<I>::type>(s);
507 template<
int Bytes,
bool BigEndian = false>
510 static_assert(Bytes > 0 && Bytes <= 8,
"CustomUintFormatter Bytes out of range");
511 static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
513 template <
typename Stream,
typename I>
void Ser(Stream& s, I v)
515 if (v < 0 || v > MAX)
throw std::ios_base::failure(
"CustomUintFormatter value out of range");
518 s.write(((
const char*)&raw) + 8 - Bytes, Bytes);
521 s.write((
const char*)&raw, Bytes);
525 template <
typename Stream,
typename I>
void Unser(Stream& s, I& v)
527 using U =
typename std::conditional<std::is_enum<I>::value, std::underlying_type<I>, std::common_type<I>>::type::type;
528 static_assert(std::numeric_limits<U>::max() >= MAX && std::numeric_limits<U>::min() <= 0,
"Assigned type too small");
531 s.read(((
char*)&raw) + 8 - Bytes, Bytes);
532 v =
static_cast<I
>(
be64toh(raw));
534 s.read((
char*)&raw, Bytes);
535 v =
static_cast<I
>(
le64toh(raw));
543 template<
bool RangeCheck>
546 template<
typename Stream,
typename I>
549 uint64_t n = ReadCompactSize<Stream>(s, RangeCheck);
550 if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
551 throw std::ios_base::failure(
"CompactSize exceeds limit of type");
556 template<
typename Stream,
typename I>
559 static_assert(std::is_unsigned<I>::value,
"CompactSize only supported for unsigned integers");
560 static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(),
"CompactSize only supports 64-bit integers and below");
562 WriteCompactSize<Stream>(s, v);
566 template<
size_t Limit>
569 template<
typename Stream>
570 void Unser(Stream& s, std::string& v)
574 throw std::ios_base::failure(
"String length limit exceeded");
577 if (size != 0) s.read((
char*)v.data(), size);
580 template<
typename Stream>
581 void Ser(Stream& s,
const std::string& v)
600 template<
class Formatter>
603 template<
typename Stream,
typename V>
604 void Ser(Stream& s,
const V& v)
608 for (
const typename V::value_type& elem : v) {
609 formatter.Ser(s, elem);
613 template<
typename Stream,
typename V>
619 size_t allocated = 0;
620 while (allocated < size) {
624 static_assert(
sizeof(
typename V::value_type) <=
MAX_VECTOR_ALLOCATE,
"Vector element size too large");
625 allocated = std::min(size, allocated +
MAX_VECTOR_ALLOCATE /
sizeof(
typename V::value_type));
626 v.reserve(allocated);
627 while (v.size() < allocated) {
629 formatter.Unser(s, v.back());
642 template<
typename Stream,
typename C>
void Serialize(Stream& os,
const std::basic_string<C>& str);
643 template<
typename Stream,
typename C>
void Unserialize(Stream& is, std::basic_string<C>& str);
660 template<
typename Stream,
typename T,
typename A>
void Serialize_impl(Stream& os,
const std::vector<T, A>& v,
const unsigned char&);
661 template<
typename Stream,
typename T,
typename A>
void Serialize_impl(Stream& os,
const std::vector<T, A>& v,
const bool&);
662 template<
typename Stream,
typename T,
typename A,
typename V>
void Serialize_impl(Stream& os,
const std::vector<T, A>& v,
const V&);
663 template<
typename Stream,
typename T,
typename A>
inline void Serialize(Stream& os,
const std::vector<T, A>& v);
664 template<
typename Stream,
typename T,
typename A>
void Unserialize_impl(Stream& is, std::vector<T, A>& v,
const unsigned char&);
665 template<
typename Stream,
typename T,
typename A,
typename V>
void Unserialize_impl(Stream& is, std::vector<T, A>& v,
const V&);
666 template<
typename Stream,
typename T,
typename A>
inline void Unserialize(Stream& is, std::vector<T, A>& v);
671 template<
typename Stream,
typename K,
typename T>
void Serialize(Stream& os,
const std::pair<K, T>& item);
672 template<
typename Stream,
typename K,
typename T>
void Unserialize(Stream& is, std::pair<K, T>& item);
677 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
void Serialize(Stream& os,
const std::map<K, T, Pred, A>& m);
678 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
void Unserialize(Stream& is, std::map<K, T, Pred, A>& m);
683 template<
typename Stream,
typename K,
typename Pred,
typename A>
void Serialize(Stream& os,
const std::set<K, Pred, A>& m);
684 template<
typename Stream,
typename K,
typename Pred,
typename A>
void Unserialize(Stream& is, std::set<K, Pred, A>& m);
689 template<
typename Stream,
typename T>
void Serialize(Stream& os,
const std::shared_ptr<const T>& p);
690 template<
typename Stream,
typename T>
void Unserialize(Stream& os, std::shared_ptr<const T>& p);
695 template<
typename Stream,
typename T>
void Serialize(Stream& os,
const std::unique_ptr<const T>& p);
696 template<
typename Stream,
typename T>
void Unserialize(Stream& os, std::unique_ptr<const T>& p);
703 template<
typename Stream,
typename T>
709 template<
typename Stream,
typename T>
722 template<
typename Stream,
typename T>
725 template<
typename Stream,
typename T>
736 template<
typename Stream,
typename C>
737 void Serialize(Stream& os,
const std::basic_string<C>& str)
741 os.write((
char*)str.data(), str.size() *
sizeof(C));
744 template<
typename Stream,
typename C>
750 is.read((
char*)str.data(), nSize *
sizeof(C));
758 template<
typename Stream,
unsigned int N,
typename T>
763 os.write((
char*)v.data(), v.size() *
sizeof(T));
766 template<
typename Stream,
unsigned int N,
typename T,
typename V>
772 template<
typename Stream,
unsigned int N,
typename T>
779 template<
typename Stream,
unsigned int N,
typename T>
788 unsigned int blk = std::min(nSize - i, (
unsigned int)(1 + 4999999 /
sizeof(T)));
789 v.resize_uninitialized(i + blk);
790 is.read((
char*)&v[i], blk *
sizeof(T));
795 template<
typename Stream,
unsigned int N,
typename T,
typename V>
801 template<
typename Stream,
unsigned int N,
typename T>
812 template<
typename Stream,
typename T,
typename A>
813 void Serialize_impl(Stream& os,
const std::vector<T, A>& v,
const unsigned char&)
817 os.write((
char*)v.data(), v.size() *
sizeof(T));
820 template<
typename Stream,
typename T,
typename A>
827 for (
bool elem : v) {
832 template<
typename Stream,
typename T,
typename A,
typename V>
838 template<
typename Stream,
typename T,
typename A>
839 inline void Serialize(Stream& os,
const std::vector<T, A>& v)
845 template<
typename Stream,
typename T,
typename A>
854 unsigned int blk = std::min(nSize - i, (
unsigned int)(1 + 4999999 /
sizeof(T)));
856 is.read((
char*)&v[i], blk *
sizeof(T));
861 template<
typename Stream,
typename T,
typename A,
typename V>
867 template<
typename Stream,
typename T,
typename A>
878 template<
typename Stream,
typename K,
typename T>
885 template<
typename Stream,
typename K,
typename T>
897 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
898 void Serialize(Stream& os,
const std::map<K, T, Pred, A>& m)
901 for (
const auto& entry : m)
905 template<
typename Stream,
typename K,
typename T,
typename Pred,
typename A>
910 typename std::map<K, T, Pred, A>::iterator mi = m.begin();
911 for (
unsigned int i = 0; i < nSize; i++)
913 std::pair<K, T> item;
915 mi = m.insert(mi, item);
924 template<
typename Stream,
typename K,
typename Pred,
typename A>
925 void Serialize(Stream& os,
const std::set<K, Pred, A>& m)
928 for (
typename std::set<K, Pred, A>::const_iterator
it = m.begin();
it != m.end(); ++
it)
932 template<
typename Stream,
typename K,
typename Pred,
typename A>
937 typename std::set<K, Pred, A>::iterator
it = m.begin();
938 for (
unsigned int i = 0; i < nSize; i++)
942 it = m.insert(it, key);
951 template<
typename Stream,
typename T>
void
952 Serialize(Stream& os,
const std::unique_ptr<const T>& p)
957 template<
typename Stream,
typename T>
968 template<
typename Stream,
typename T>
void
969 Serialize(Stream& os,
const std::shared_ptr<const T>& p)
974 template<
typename Stream,
typename T>
987 constexpr
bool ForRead()
const {
return false; }
991 constexpr
bool ForRead()
const {
return true; }
1021 void write(
const char *psz,
size_t _nSize)
1023 this->nSize += _nSize;
1029 this->nSize += _nSize;
1032 template<
typename T>
1046 template<
typename Stream>
1051 template<
typename Stream,
typename Arg,
typename... Args>
1058 template<
typename Stream>
1063 template<
typename Stream,
typename Arg,
typename... Args>
1070 template<
typename Stream,
typename... Args>
1076 template<
typename Stream,
typename... Args>
1082 template<
typename Stream,
typename Type,
typename Fn>
1087 template<
typename Stream,
typename Type,
typename Fn>
1090 fn(s, std::forward<Type>(obj));
1093 template<
typename Stream,
typename Type,
typename Fn>
1096 fn(s, std::forward<Type>(obj));
1099 template<
typename Stream,
typename Type,
typename Fn>
1104 template<
typename I>
1107 s.
seek(GetSizeOfVarInt<I>(n));
1115 template <
typename T>
1121 template <
typename... T>
1129 #endif // BITCOIN_SERIALIZE_H
uint64_t ser_double_to_uint64(double x)
CSizeComputer(int nVersionIn)
X & ReadWriteAsHelper(X &x)
Convert the reference base type to X, without changing constness or reference type.
uint32_t ser_float_to_uint32(float x)
uint8_t ser_readdata8(Stream &s)
void ser_writedata64(Stream &s, uint64_t obj)
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)
void SerRead(Stream &s, CSerActionSerialize ser_action, Type &&, Fn &&)
uint64_t htobe64(uint64_t host_64bits)
static const unsigned int MAX_VECTOR_ALLOCATE
Maximum amount of memory (in bytes) to allocate at once when deserializing vectors.
void ser_writedata32(Stream &s, uint32_t obj)
constexpr deserialize_type deserialize
constexpr std::size_t size() const noexcept
unsigned int GetSizeOfCompactSize(uint64_t nSize)
Compact Size size < 253 – 1 byte size <= USHRT_MAX – 3 bytes (253 + 2 bytes) size <= UINT_MAX – 5 ...
uint32_t be32toh(uint32_t big_endian_32bits)
void UnserializeMany(Stream &s)
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...
char * CharCast(char *c)
Safely convert odd char pointer types to standard ones.
size_t GetSerializeSize(const T &t, int nVersion=0)
void Serialize(Stream &s, char a)
uint32_t htobe32(uint32_t host_32bits)
CSizeComputer & operator<<(const T &obj)
uint64_t be64toh(uint64_t big_endian_64bits)
uint16_t ser_readdata16(Stream &s)
constexpr bool ForRead() const
uint32_t ser_readdata32(Stream &s)
constexpr CheckVarIntMode()
void ser_writedata16(Stream &s, uint16_t obj)
uint16_t htobe16(uint16_t host_16bits)
size_t GetSerializeSizeMany(int nVersion, const T &...t)
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)
double ser_uint64_to_double(uint64_t y)
Support for SERIALIZE_METHODS and READWRITE macro.
void SerializeMany(Stream &s)
Implements a drop-in replacement for std::vector which stores up to N elements directly (without h...
uint64_t ser_readdata64(Stream &s)
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)
constexpr bool ForRead() const
uint64_t le64toh(uint64_t little_endian_64bits)
uint16_t be16toh(uint16_t big_endian_16bits)
constexpr C * data() const noexcept
void * memcpy(void *a, const void *b, size_t c)
uint64_t htole64(uint64_t host_64bits)
void write(const char *psz, size_t _nSize)
uint32_t ser_readdata32be(Stream &s)
void SerWrite(Stream &s, CSerActionSerialize ser_action, Type &&obj, Fn &&fn)
unsigned int GetSizeOfVarInt(I n)
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 Unserialize(Stream &s, char &a)
void SerReadWriteMany(Stream &s, CSerActionSerialize ser_action, const Args &...args)
void ser_writedata16be(Stream &s, uint16_t obj)
A Span is an object that can refer to a contiguous sequence of objects.
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...
void Unserialize_impl(Stream &is, prevector< N, T > &v, const unsigned char &)
uint32_t le32toh(uint32_t little_endian_32bits)
void ser_writedata8(Stream &s, uint8_t obj)
float ser_uint32_to_float(uint32_t y)