diff options
author | Pieter Wuille <pieter.wuille@gmail.com> | 2020-02-15 19:48:42 -0800 |
---|---|---|
committer | Pieter Wuille <pieter.wuille@gmail.com> | 2020-02-25 14:10:38 -0800 |
commit | e574fff53eec4a27c83b765cb69e31d8399047ea (patch) | |
tree | a50fc863df6e4bfaa6d671dcedb43460083528d9 /src/serialize.h | |
parent | 10633398f2dddf929d3f535aa48d138ad5e6c50f (diff) |
Add CustomUintFormatter
Diffstat (limited to 'src/serialize.h')
-rw-r--r-- | src/serialize.h | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/src/serialize.h b/src/serialize.h index d7d1be7c4b..2e4b14e586 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -513,6 +513,28 @@ struct VarIntFormatter } }; +template<int Bytes> +struct CustomUintFormatter +{ + static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range"); + static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes)); + + template <typename Stream, typename I> void Ser(Stream& s, I v) + { + if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range"); + uint64_t raw = htole64(v); + s.write((const char*)&raw, Bytes); + } + + template <typename Stream, typename I> void Unser(Stream& s, I& v) + { + static_assert(std::numeric_limits<I>::max() >= MAX && std::numeric_limits<I>::min() <= 0, "CustomUintFormatter type too small"); + uint64_t raw = 0; + s.read((char*)&raw, Bytes); + v = le64toh(raw); + } +}; + /** Serialization wrapper class for big-endian integers. * * Use this wrapper around integer types that are stored in memory in native |