mirror of
https://github.com/bitcoin/bitcoin.git
synced 2026-04-26 23:09:03 +02:00
util: Return empty vector on invalid hex encoding
This commit is contained in:
@@ -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;
|
||||
|
||||
@@ -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.*/
|
||||
|
||||
Reference in New Issue
Block a user