util: Return empty vector on invalid hex encoding

This commit is contained in:
MarcoFalke
2023-02-27 13:39:17 +01:00
parent fa3549a77b
commit faab273e06
3 changed files with 34 additions and 17 deletions

View File

@@ -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;