Skip to content

Commit 3ca574c

Browse files
committed
Convert CCompactSize to proper formatter
1 parent 0c20809 commit 3ca574c

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

src/serialize.h

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,7 @@ static inline Wrapper<Formatter, T&> Using(T&& t) { return Wrapper<Formatter, T&
495495

496496
#define VARINT_MODE(obj, mode) Using<VarIntFormatter<mode>>(obj)
497497
#define VARINT(obj) Using<VarIntFormatter<VarIntMode::DEFAULT>>(obj)
498-
#define COMPACTSIZE(obj) CCompactSize(REF(obj))
498+
#define COMPACTSIZE(obj) Using<CompactSizeFormatter>(obj)
499499
#define LIMITED_STRING(obj,n) LimitedString< n >(REF(obj))
500500

501501
/** Serialization wrapper class for integers in VarInt format. */
@@ -547,21 +547,26 @@ class BigEndian
547547
}
548548
};
549549

550-
class CCompactSize
550+
/** Formatter for integers in CompactSize format. */
551+
struct CompactSizeFormatter
551552
{
552-
protected:
553-
uint64_t &n;
554-
public:
555-
explicit CCompactSize(uint64_t& nIn) : n(nIn) { }
556-
557-
template<typename Stream>
558-
void Serialize(Stream &s) const {
559-
WriteCompactSize<Stream>(s, n);
553+
template<typename Stream, typename I>
554+
void Unser(Stream& s, I& v)
555+
{
556+
uint64_t n = ReadCompactSize<Stream>(s);
557+
if (n < std::numeric_limits<I>::min() || n > std::numeric_limits<I>::max()) {
558+
throw std::ios_base::failure("CompactSize exceeds limit of type");
559+
}
560+
v = n;
560561
}
561562

562-
template<typename Stream>
563-
void Unserialize(Stream& s) {
564-
n = ReadCompactSize<Stream>(s);
563+
template<typename Stream, typename I>
564+
void Ser(Stream& s, I v)
565+
{
566+
static_assert(std::is_unsigned<I>::value, "CompactSize only supported for unsigned integers");
567+
static_assert(std::numeric_limits<I>::max() <= std::numeric_limits<uint64_t>::max(), "CompactSize only supports 64-bit integers and below");
568+
569+
WriteCompactSize<Stream>(s, v);
565570
}
566571
};
567572

0 commit comments

Comments
 (0)