Skip to content

Commit 684f76b

Browse files
committed
fix base32
1 parent 13efe55 commit 684f76b

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

src/utility/base32.cpp

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,23 +18,27 @@ namespace hk {
1818

1919
[[nodiscard]] std::string base32_encode(std::span<char const> value)
2020
{
21-
auto const r_size = (value.size() * 8 + 4) / 5;
2221
auto r = std::string{};
23-
r.resize(r_size);
22+
r.resize((value.size() * 8 + 4) / 5);
2423

2524
auto j = 0uz;
26-
for (auto i = 0uz; i != r_size; ++i, j += 5) {
25+
auto i = 0uz;
26+
while (i != r.size()) {
2727
auto const byte_nr = j / 8;
2828
auto const bit_nr = j % 8;
29-
30-
auto bits = uint16_t{0};
31-
bits |= value[byte_nr + 1];
32-
bits <<= 8;
29+
j += 5;
30+
31+
auto bits = uint16_t{};
32+
if (byte_nr + 1 < value.size()) {
33+
bits |= value[byte_nr + 1];
34+
bits <<= 8;
35+
}
36+
assert(byte_nr < value.size());
3337
bits |= value[byte_nr];
3438
bits >>= bit_nr;
3539
bits &= 0x1f;
3640

37-
r[i] = base32_encode_5bit(static_cast<unsigned char>(bits));
41+
r[i++] = base32_encode_5bit(static_cast<unsigned char>(bits));
3842
}
3943

4044
return r;

0 commit comments

Comments
 (0)