Skip to content

Commit

Permalink
StringUtil: Add FromCharsWithOptionalBase()
Browse files Browse the repository at this point in the history
  • Loading branch information
stenzek committed Oct 13, 2024
1 parent 0d05548 commit 2079bac
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/common/string_util.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,18 @@ std::size_t StringUtil::Strlcpy(char* dst, const std::string_view src, std::size
return len;
}

u8 StringUtil::DecodeHexDigit(char ch)
{
if (ch >= '0' && ch <= '9')
return static_cast<u8>(ch - '0');
else if (ch >= 'a' && ch <= 'f')
return static_cast<u8>(0xa + (ch - 'a'));
else if (ch >= 'A' && ch <= 'F')
return static_cast<u8>(0xa + (ch - 'A'));
else
return 0;
}

std::optional<std::vector<u8>> StringUtil::DecodeHex(const std::string_view in)
{
std::vector<u8> data;
Expand Down
27 changes: 27 additions & 0 deletions src/common/string_util.h
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,32 @@ inline std::optional<T> FromChars(const std::string_view str, int base, std::str
return value;
}

template<typename T, std::enable_if_t<std::is_integral<T>::value, bool> = true>
inline std::optional<T> FromCharsWithOptionalBase(std::string_view str, std::string_view* endptr = nullptr)
{
int base = 10;
if (str.starts_with("0x"))
{
base = 16;
str = str.substr(2);
}
else if (str.starts_with("0b"))
{
base = 2;
str = str.substr(1);
}
else if (str.starts_with("0") && str.length() > 1)
{
base = 8;
str = str.substr(1);
}

if (endptr)
return FromChars<T>(str, base, endptr);
else
return FromChars<T>(str, base);
}

template<typename T, std::enable_if_t<std::is_floating_point<T>::value, bool> = true>
inline std::optional<T> FromChars(const std::string_view str)
{
Expand Down Expand Up @@ -216,6 +242,7 @@ inline std::string ToChars(bool value, int base)
}

/// Encode/decode hexadecimal byte buffers
u8 DecodeHexDigit(char ch);
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 2079bac

Please sign in to comment.