diff --git a/src/utility.h b/src/utility.h index d9a4dfa2d..9d3188720 100644 --- a/src/utility.h +++ b/src/utility.h @@ -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::ranges::count_if(hex, is_convertable) / 2, sizeof(T)); + auto digits_left = std::ranges::count_if(hex, is_convertable); + auto buf_size = std::min((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; }); diff --git a/tests/unit/test_utility.cpp b/tests/unit/test_utility.cpp index c5069795a..e14f64764 100644 --- a/tests/unit/test_utility.cpp +++ b/tests/unit/test_utility.cpp @@ -411,6 +411,13 @@ TEST(UtilityFromHexTests, LongInputKeepsTheLowOrderBytes) { EXPECT_EQ(util::from_hex("123456789A", true), util::endian::big(std::uint32_t {0x3456789A})); } +TEST(UtilityFromHexTests, OddDigitCountReadsTheLeadingDigitAsTheHighNibble) { + EXPECT_EQ(util::from_hex("8"), util::endian::little(std::uint32_t {0x8})); + EXPECT_EQ(util::from_hex("ABC"), util::endian::little(std::uint16_t {0xABC})); + EXPECT_EQ(util::from_hex("ABC", true), util::endian::big(std::uint16_t {0xABC})); + EXPECT_EQ(util::from_hex("1:2:3"), util::endian::little(std::uint16_t {0x123})); +} + TEST(UtilityFromHexTests, DecodesIntoAByteArrayWithoutPointerTypePunning) { const auto bytes = util::from_hex>("12:34:56:78", true); EXPECT_EQ(bytes, (std::array {0x12, 0x34, 0x56, 0x78}));