fix(utility): read an odd number of hex digits as a leading zero nibble

from_hex sized its buffer as digit_count / 2, so the leading digit of an
odd-length value was dropped. A config value such as min_threads = 0x8
parsed as 0, and keybindings = [0x9, 0xA0] mapped key 0 instead of 0x9.
This commit is contained in:
leoca authored and Dave Lane committed 2026-11-07 09:13:14 -05:00
1 parent 424b37e9c9
commit 71b39e4933
2 files changed
+18 -4

No files matched your search

+11 -4
View File
@@ -625,6 +625,7 @@ namespace util {
* @brief Decode hexadecimal text into an object's byte representation.
*
* Digits beyond the size of the object are ignored, keeping the low-order bytes.
* An odd number of digits is read as if it had a leading zero.
*
* @param hex Hexadecimal text to decode.
* @param rev Whether bytes should be emitted in reverse order.
@@ -642,7 +643,8 @@ namespace util {
return ('a' <= ch && ch <= 'z') || ('A' <= ch && ch <= 'Z');
};
auto buf_size = std::min<std::size_t>(std::ranges::count_if(hex, is_convertable) / 2, sizeof(T));
auto digits_left = std::ranges::count_if(hex, is_convertable);
auto buf_size = std::min<std::size_t>((digits_left + 1) / 2, sizeof(T));
auto padding = sizeof(T) - buf_size;
const char *data = hex.data() + hex.size() - 1;
@@ -663,11 +665,16 @@ namespace util {
--data;
}
const auto ch_r = convert(*data--);
--digits_left;
while (!is_convertable(*data)) {
--data;
auto ch_l = std::byte {0};
if (digits_left > 0) {
while (!is_convertable(*data)) {
--data;
}
ch_l = convert(*data--);
--digits_left;
}
const auto ch_l = convert(*data--);
el = (ch_l << 4) | ch_r;
});
+7
View File
@@ -411,6 +411,13 @@ TEST(UtilityFromHexTests, LongInputKeepsTheLowOrderBytes) {
EXPECT_EQ(util::from_hex<std::uint32_t>("123456789A", true), util::endian::big(std::uint32_t {0x3456789A}));
}
TEST(UtilityFromHexTests, OddDigitCountReadsTheLeadingDigitAsTheHighNibble) {
EXPECT_EQ(util::from_hex<std::uint32_t>("8"), util::endian::little(std::uint32_t {0x8}));
EXPECT_EQ(util::from_hex<std::uint16_t>("ABC"), util::endian::little(std::uint16_t {0xABC}));
EXPECT_EQ(util::from_hex<std::uint16_t>("ABC", true), util::endian::big(std::uint16_t {0xABC}));
EXPECT_EQ(util::from_hex<std::uint16_t>("1:2:3"), util::endian::little(std::uint16_t {0x123}));
}
TEST(UtilityFromHexTests, DecodesIntoAByteArrayWithoutPointerTypePunning) {
const auto bytes = util::from_hex<std::array<std::uint8_t, 4>>("12:34:56:78", true);
EXPECT_EQ(bytes, (std::array<std::uint8_t, 4> {0x12, 0x34, 0x56, 0x78}));