Skip to content

Commit e574fff

Browse files
committed
Add CustomUintFormatter
1 parent 1063339 commit e574fff

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
@@ -513,6 +513,28 @@ struct VarIntFormatter
513513
}
514514
};
515515

516+
template<int Bytes>
517+
struct CustomUintFormatter
518+
{
519+
static_assert(Bytes > 0 && Bytes <= 8, "CustomUintFormatter Bytes out of range");
520+
static constexpr uint64_t MAX = 0xffffffffffffffff >> (8 * (8 - Bytes));
521+
522+
template <typename Stream, typename I> void Ser(Stream& s, I v)
523+
{
524+
if (v < 0 || v > MAX) throw std::ios_base::failure("CustomUintFormatter value out of range");
525+
uint64_t raw = htole64(v);
526+
s.write((const char*)&raw, Bytes);
527+
}
528+
529+
template <typename Stream, typename I> void Unser(Stream& s, I& v)
530+
{
531+
static_assert(std::numeric_limits<I>::max() >= MAX && std::numeric_limits<I>::min() <= 0, "CustomUintFormatter type too small");
532+
uint64_t raw = 0;
533+
s.read((char*)&raw, Bytes);
534+
v = le64toh(raw);
535+
}
536+
};
537+
516538
/** Serialization wrapper class for big-endian integers.
517539
*
518540
* Use this wrapper around integer types that are stored in memory in native

0 commit comments

Comments
 (0)