Skip to content

Commit d6380c4

Browse files
sipafurszy
authored andcommitted
Add CustomUintFormatter
1 parent fd29a50 commit d6380c4

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

src/serialize.h

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,28 @@ struct VarIntFormatter
542542
}
543543
};
544544

545+
template<int Bytes>
546+
struct CustomUintFormatter
547+
{
548+
static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range");
549+
static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
550+
551+
template <typename Stream, typename I> void Ser(Stream& s, I v)
552+
{
553+
if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range");
554+
uint64_t raw = htole64(v);
555+
s.write((const char*)&raw, Bytes);
556+
}
557+
558+
template <typename Stream, typename I> void Unser(Stream& s, I& v)
559+
{
560+
static_assert(std::numeric_limits<I>::max() >= MAX && std::numeric_limits<I>::min() <= 0, "CustomUintFormatter type too small");
561+
uint64_t raw = 0;
562+
s.read((char*)&raw, Bytes);
563+
v = le64toh(raw);
564+
}
565+
};
566+
545567
/** Serialization wrapper class for big-endian integers.
546568
*
547569
* Use this wrapper around integer types that are stored in memory in native

0 commit comments

Comments
 (0)