From fae1006019188700e0c497a63fc1550fe00ca8bb Mon Sep 17 00:00:00 2001 From: MarcoFalke Date: Wed, 10 Nov 2021 10:49:58 +0100 Subject: [PATCH] util: Add ParseHex() helper --- src/test/fuzz/hex.cpp | 2 ++ src/util/strencodings.cpp | 9 ++++++--- src/util/strencodings.h | 4 +++- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/src/test/fuzz/hex.cpp b/src/test/fuzz/hex.cpp index cc1bc1c8cfa..e637975b48f 100644 --- a/src/test/fuzz/hex.cpp +++ b/src/test/fuzz/hex.cpp @@ -25,6 +25,8 @@ FUZZ_TARGET_INIT(hex, initialize_hex) { const std::string random_hex_string(buffer.begin(), buffer.end()); const std::vector data = ParseHex(random_hex_string); + const std::vector bytes{ParseHex(random_hex_string)}; + assert(AsBytes(Span{data}) == Span{bytes}); const std::string hex_data = HexStr(data); if (IsHex(random_hex_string)) { assert(ToLower(random_hex_string) == hex_data); diff --git a/src/util/strencodings.cpp b/src/util/strencodings.cpp index 3556c0f4b0b..6f034c65a27 100644 --- a/src/util/strencodings.cpp +++ b/src/util/strencodings.cpp @@ -76,9 +76,10 @@ bool IsHexNumber(std::string_view str) return str.size() > 0; } -std::vector ParseHex(std::string_view str) +template +std::vector ParseHex(std::string_view str) { - std::vector vch; + std::vector vch; auto it = str.begin(); while (it != str.end() && it + 1 != str.end()) { if (IsSpace(*it)) { @@ -88,10 +89,12 @@ std::vector ParseHex(std::string_view str) auto c1 = HexDigit(*(it++)); auto c2 = HexDigit(*(it++)); if (c1 < 0 || c2 < 0) break; - vch.push_back(uint8_t(c1 << 4) | c2); + vch.push_back(Byte(c1 << 4) | Byte(c2)); } return vch; } +template std::vector ParseHex(std::string_view); +template std::vector ParseHex(std::string_view); void SplitHostPort(std::string_view in, uint16_t& portOut, std::string& hostOut) { diff --git a/src/util/strencodings.h b/src/util/strencodings.h index ebb6d889520..ee583835281 100644 --- a/src/util/strencodings.h +++ b/src/util/strencodings.h @@ -55,7 +55,9 @@ enum class ByteUnit : uint64_t { * @return A new string without unsafe chars */ std::string SanitizeString(std::string_view str, int rule = SAFE_CHARS_DEFAULT); -std::vector ParseHex(std::string_view str); +/** Parse the hex string into bytes (uint8_t or std::byte). Ignores whitespace. */ +template +std::vector ParseHex(std::string_view str); signed char HexDigit(char c); /* Returns true if each character in str is a hex character, and has an even * number of hex digits.*/