From 0c530b46ead7169e91979b8ee18f929a431d65c9 Mon Sep 17 00:00:00 2001 From: Pieter Wuille Date: Sat, 15 Feb 2020 19:48:42 -0800 Subject: [PATCH] Add CustomUintFormatter --- src/serialize.h | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/serialize.h b/src/serialize.h index 0db91ee7037..7245ecc7df9 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -488,6 +488,28 @@ class CVarInt } }; +template +struct CustomUintFormatter +{ + static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range"); + static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes)); + + template 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 void Unser(Stream& s, I& v) + { + static_assert(std::numeric_limits::max() >= MAX && std::numeric_limits::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