diff options
author | MarcoFalke <6399679+MarcoFalke@users.noreply.github.com> | 2023-02-27 13:39:17 +0100 |
---|---|---|
committer | MarcoFalke <6399679+MarcoFalke@users.noreply.github.com> | 2023-02-27 13:39:55 +0100 |
commit | faab273e060d27e166b5fb7fe7692614ec9e5c76 (patch) | |
tree | ed6a59e83261c873885116ae22ae940a8feec996 /src/util | |
parent | fa3549a77bf6a15d8309d36056237f3126baf721 (diff) |
util: Return empty vector on invalid hex encoding
Diffstat (limited to 'src/util')
-rw-r--r-- | src/util/strencodings.cpp | 7 | ||||
-rw-r--r-- | src/util/strencodings.h | 10 |
2 files changed, 12 insertions, 5 deletions
diff --git a/src/util/strencodings.cpp b/src/util/strencodings.cpp index 45a01429e1..03459dcf20 100644 --- a/src/util/strencodings.cpp +++ b/src/util/strencodings.cpp @@ -78,18 +78,19 @@ bool IsHexNumber(std::string_view str) } template <typename Byte> -std::vector<Byte> ParseHex(std::string_view str) +std::optional<std::vector<Byte>> TryParseHex(std::string_view str) { std::vector<Byte> vch; auto it = str.begin(); - while (it != str.end() && it + 1 != str.end()) { + while (it != str.end()) { if (IsSpace(*it)) { ++it; continue; } auto c1 = HexDigit(*(it++)); + if (it == str.end()) return std::nullopt; auto c2 = HexDigit(*(it++)); - if (c1 < 0 || c2 < 0) break; + if (c1 < 0 || c2 < 0) return std::nullopt; vch.push_back(Byte(c1 << 4) | Byte(c2)); } return vch; diff --git a/src/util/strencodings.h b/src/util/strencodings.h index 626e48f499..05e7b957c4 100644 --- a/src/util/strencodings.h +++ b/src/util/strencodings.h @@ -57,9 +57,15 @@ enum class ByteUnit : uint64_t { * @return A new string without unsafe chars */ std::string SanitizeString(std::string_view str, int rule = SAFE_CHARS_DEFAULT); -/** Parse the hex string into bytes (uint8_t or std::byte). Ignores whitespace. */ +/** Parse the hex string into bytes (uint8_t or std::byte). Ignores whitespace. Returns nullopt on invalid input. */ +template <typename Byte = std::byte> +std::optional<std::vector<Byte>> TryParseHex(std::string_view str); +/** Like TryParseHex, but returns an empty vector on invalid input. */ template <typename Byte = uint8_t> -std::vector<Byte> ParseHex(std::string_view str); +std::vector<Byte> ParseHex(std::string_view hex_str) +{ + return TryParseHex<Byte>(hex_str).value_or(std::vector<Byte>{}); +} signed char HexDigit(char c); /* Returns true if each character in str is a hex character, and has an even * number of hex digits.*/ |