Skip to content

Commit

Permalink
StringUtil: Add fixed-length DecodeHex()
Browse files Browse the repository at this point in the history
  • Loading branch information
stenzek committed Jan 25, 2025
1 parent 543704d commit ca509a8
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 8 deletions.
29 changes: 21 additions & 8 deletions src/common/string_util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -165,21 +165,34 @@ u8 StringUtil::DecodeHexDigit(char ch)
return 0;
}

std::optional<std::vector<u8>> StringUtil::DecodeHex(const std::string_view in)
size_t StringUtil::DecodeHex(std::span<u8> dest, const std::string_view str)
{
std::vector<u8> data;
data.reserve(in.size() / 2);
if ((str.length() % 2) != 0)
return 0;

for (size_t i = 0; i < in.size() / 2; i++)
const size_t bytes = str.length() / 2;
if (dest.size() != bytes)
return 0;

for (size_t i = 0; i < bytes; i++)
{
std::optional<u8> byte = StringUtil::FromChars<u8>(in.substr(i * 2, 2), 16);
std::optional<u8> byte = StringUtil::FromChars<u8>(str.substr(i * 2, 2), 16);
if (byte.has_value())
data.push_back(*byte);
dest[i] = byte.value();
else
return std::nullopt;
return i;
}

return {data};
return bytes;
}

std::optional<std::vector<u8>> StringUtil::DecodeHex(const std::string_view in)
{
std::optional<std::vector<u8>> ret;
ret = std::vector<u8>(in.size() / 2);
if (DecodeHex(ret.value(), in) != ret->size())
ret.reset();
return ret;
}

std::string StringUtil::EncodeHex(const void* data, size_t length)
Expand Down
1 change: 1 addition & 0 deletions src/common/string_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,7 @@ static inline bool IsWhitespace(char ch)

/// Encode/decode hexadecimal byte buffers
u8 DecodeHexDigit(char ch);
size_t DecodeHex(std::span<u8> dest, const std::string_view str);
std::optional<std::vector<u8>> DecodeHex(const std::string_view str);
std::string EncodeHex(const void* data, size_t length);
template<typename T>
Expand Down

0 comments on commit ca509a8

Please sign in to comment.