Skip to content

Commit

Permalink
Fix to_varint
Browse files Browse the repository at this point in the history
  • Loading branch information
dsharlet committed Nov 20, 2024
1 parent badd8f0 commit 192314f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 6 deletions.
7 changes: 4 additions & 3 deletions proto.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,13 @@ constexpr uint8_t varint_continuation = 0x80;
// Convert an integer to a varint. May overflow if the result doesn't fit in 64 bits, but can be used constexpr.
static inline constexpr uint64_t to_varint(uint64_t value) {
uint64_t result = 0;
uint64_t shift = 0;
while (value > 0x7f) {
result |= static_cast<uint8_t>(value | varint_continuation);
result <<= 8;
result |= (static_cast<uint8_t>(value) | varint_continuation) << shift;
value >>= 7;
shift += 8;
}
result |= static_cast<uint8_t>(value);
result |= static_cast<uint8_t>(value) << shift;
return result;
}

Expand Down
19 changes: 16 additions & 3 deletions test/proto_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,19 @@ uint64_t decode_varint(const std::vector<uint8_t>& bytes) {
return result;
}

uint64_t decode_varint(uint64_t bytes) {
uint64_t result = 0;
read_varint(result, reinterpret_cast<uint8_t*>(&bytes), sizeof(bytes));
return result;
}

TEST(proto, to_varint) {
for (uint64_t i = 0; i <= 0x7f; ++i) {
ASSERT_EQ(to_varint(i), i);
}
ASSERT_EQ(to_varint(0x80), 0x8001);
ASSERT_EQ(to_varint(0x81), 0x8101);
ASSERT_EQ(to_varint(0x82), 0x8201);
ASSERT_EQ(to_varint(0x80), 0x0180);
ASSERT_EQ(to_varint(0x81), 0x0181);
ASSERT_EQ(to_varint(0x82), 0x0182);
}

// Wrappers that make testing easier.
Expand Down Expand Up @@ -59,6 +65,13 @@ TEST(proto, write_varint) {
ASSERT_EQ(decode_varint(varint), std::numeric_limits<uint64_t>::max());
}

TEST(proto, to_varint_matches_write_varint) {
for (size_t i = 0; i < 1ull << 20; ++i) {
uint64_t to = to_varint(i);
ASSERT_EQ(decode_varint(to), i) << i;
}
}

TEST(proto, write_padding) {
std::array<uint8_t, 32> buffer;
for (uint64_t i = 2; i <= 0x7f; ++i) {
Expand Down

0 comments on commit 192314f

Please sign in to comment.