string: add base argument for ToIntegral to operate on hexadecimal

This commit is contained in:
Matthew Zipkin
2025-03-12 13:31:47 -04:00
parent 0b0d9125c1
commit 4e300df712
2 changed files with 37 additions and 3 deletions

View File

@@ -169,17 +169,18 @@ constexpr inline bool IsSpace(char c) noexcept {
/**
* Convert string to integral type T. Leading whitespace, a leading +, or any
* trailing character fail the parsing. The required format expressed as regex
* is `-?[0-9]+`. The minus sign is only permitted for signed integer types.
* is `-?[0-9]+` by default (or `-?[0-9a-fA-F]+` if base = 16).
* The minus sign is only permitted for signed integer types.
*
* @returns std::nullopt if the entire string could not be parsed, or if the
* parsed value is not in the range representable by the type T.
*/
template <typename T>
std::optional<T> ToIntegral(std::string_view str)
std::optional<T> ToIntegral(std::string_view str, size_t base = 10)
{
static_assert(std::is_integral_v<T>);
T result;
const auto [first_nonmatching, error_condition] = std::from_chars(str.data(), str.data() + str.size(), result);
const auto [first_nonmatching, error_condition] = std::from_chars(str.data(), str.data() + str.size(), result, base);
if (first_nonmatching != str.data() + str.size() || error_condition != std::errc{}) {
return std::nullopt;
}