mirror of
https://github.com/stenzek/duckstation.git
synced 2025-06-06 19:45:33 +00:00
StringUtil: Add fixed-length DecodeHex()
This commit is contained in:
parent
543704d57c
commit
ca509a8b97
@ -165,21 +165,34 @@ u8 StringUtil::DecodeHexDigit(char ch)
|
|||||||
return 0;
|
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;
|
if ((str.length() % 2) != 0)
|
||||||
data.reserve(in.size() / 2);
|
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())
|
if (byte.has_value())
|
||||||
data.push_back(*byte);
|
dest[i] = byte.value();
|
||||||
else
|
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)
|
std::string StringUtil::EncodeHex(const void* data, size_t length)
|
||||||
|
@ -242,6 +242,7 @@ static inline bool IsWhitespace(char ch)
|
|||||||
|
|
||||||
/// Encode/decode hexadecimal byte buffers
|
/// Encode/decode hexadecimal byte buffers
|
||||||
u8 DecodeHexDigit(char ch);
|
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::optional<std::vector<u8>> DecodeHex(const std::string_view str);
|
||||||
std::string EncodeHex(const void* data, size_t length);
|
std::string EncodeHex(const void* data, size_t length);
|
||||||
template<typename T>
|
template<typename T>
|
||||||
|
Loading…
x
Reference in New Issue
Block a user