From 2079bac40bfd4d87bf5b159e650d39d2f1b8b140 Mon Sep 17 00:00:00 2001 From: Stenzek Date: Mon, 7 Oct 2024 21:54:11 +1000 Subject: [PATCH] StringUtil: Add FromCharsWithOptionalBase() --- src/common/string_util.cpp | 12 ++++++++++++ src/common/string_util.h | 27 +++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/src/common/string_util.cpp b/src/common/string_util.cpp index b5dce864d..ccb7b4181 100644 --- a/src/common/string_util.cpp +++ b/src/common/string_util.cpp @@ -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(ch - '0'); + else if (ch >= 'a' && ch <= 'f') + return static_cast(0xa + (ch - 'a')); + else if (ch >= 'A' && ch <= 'F') + return static_cast(0xa + (ch - 'A')); + else + return 0; +} + std::optional> StringUtil::DecodeHex(const std::string_view in) { std::vector data; diff --git a/src/common/string_util.h b/src/common/string_util.h index f95374252..cd259f504 100644 --- a/src/common/string_util.h +++ b/src/common/string_util.h @@ -114,6 +114,32 @@ inline std::optional FromChars(const std::string_view str, int base, std::str return value; } +template::value, bool> = true> +inline std::optional 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(str, base, endptr); + else + return FromChars(str, base); +} + template::value, bool> = true> inline std::optional FromChars(const std::string_view str) { @@ -216,6 +242,7 @@ inline std::string ToChars(bool value, int base) } /// Encode/decode hexadecimal byte buffers +u8 DecodeHexDigit(char ch); std::optional> DecodeHex(const std::string_view str); std::string EncodeHex(const void* data, size_t length); template