Sourcemeta Core 0.0.0
Loading...
Searching...
No Matches
numeric_varint.h
1#ifndef SOURCEMETA_CORE_NUMERIC_VARINT_H_
2#define SOURCEMETA_CORE_NUMERIC_VARINT_H_
3
4#include <sourcemeta/core/numeric_error.h>
5
6#include <cstddef> // std::byte, std::size_t
7#include <cstdint> // std::uint8_t, std::uint64_t
8#include <utility> // std::unreachable
9
10namespace sourcemeta::core {
11
14inline constexpr std::size_t VARINT_MAXIMUM_BYTES{10};
15
34inline auto varint_encode(const std::uint64_t value,
35 std::byte *const destination) -> std::size_t {
36 // DWARF Debugging Information Format v5, Section 7.6 "Variable Length Data"
37 constexpr std::uint8_t PAYLOAD_MASK{0b01111111};
38 constexpr std::uint8_t CONTINUATION_BIT{0b10000000};
39 constexpr std::uint8_t PAYLOAD_BITS{7};
40 std::uint64_t accumulator{value};
41 for (std::size_t index = 0; index < VARINT_MAXIMUM_BYTES; index++) {
42 if (accumulator <= PAYLOAD_MASK) {
43 destination[index] = static_cast<std::byte>(accumulator);
44 return index + 1;
45 }
46
47 destination[index] = static_cast<std::byte>(
48 static_cast<std::uint8_t>(accumulator & PAYLOAD_MASK) |
49 CONTINUATION_BIT);
50 accumulator >>= PAYLOAD_BITS;
51 }
52
53 std::unreachable();
54}
55
70inline auto varint_decode(const std::byte *const source, const std::size_t size)
71 -> std::uint64_t {
72 // DWARF Debugging Information Format v5, Section 7.6 "Variable Length Data"
73 constexpr std::uint8_t PAYLOAD_MASK{0b01111111};
74 constexpr std::uint8_t CONTINUATION_BIT{0b10000000};
75 constexpr std::uint8_t PAYLOAD_BITS{7};
76 if (size == 0 || size > VARINT_MAXIMUM_BYTES) {
77 throw VarintParseError{};
78 }
79
80 const auto last{static_cast<std::uint8_t>(source[size - 1])};
81 if ((last & CONTINUATION_BIT) != 0) {
82 throw VarintParseError{};
83 }
84
85 // The last byte of the longest possible encoding only has room for the
86 // highest bit of the result
87 if (size == VARINT_MAXIMUM_BYTES && last > 1) {
89 }
90
91 std::uint64_t result{0};
92 for (std::size_t index = 0; index < size; index++) {
93 const auto byte{static_cast<std::uint8_t>(source[index])};
94 if (index + 1 != size && (byte & CONTINUATION_BIT) == 0) {
95 throw VarintParseError{};
96 }
97
98 result |= static_cast<std::uint64_t>(byte & PAYLOAD_MASK)
99 << (PAYLOAD_BITS * index);
100 }
101
102 return result;
103}
104
105} // namespace sourcemeta::core
106
107#endif
Definition numeric_error.h:54
Definition numeric_error.h:23
auto varint_encode(const std::uint64_t value, std::byte *const destination) -> std::size_t
Definition numeric_varint.h:34
constexpr std::size_t VARINT_MAXIMUM_BYTES
Definition numeric_varint.h:14
auto varint_decode(const std::byte *const source, const std::size_t size) -> std::uint64_t
Definition numeric_varint.h:70