use from chars when it can

This commit is contained in:
altalk23 2024-02-18 17:19:25 +03:00
parent e7997d6c84
commit 30c9a8ec82

View file

@ -105,8 +105,12 @@ namespace geode {
*/ */
template <class Num> template <class Num>
Result<Num> numFromString(std::string_view const str, int base = 10) { Result<Num> numFromString(std::string_view const str, int base = 10) {
if constexpr (std::is_floating_point_v<Num>) { if constexpr (std::is_floating_point_v<Num>
Num val = {}; #if defined(__cpp_lib_to_chars)
&& false
#endif
) {
Num val;
char* strEnd; char* strEnd;
errno = 0; errno = 0;
if (std::setlocale(LC_NUMERIC, "en_US.utf8")) { if (std::setlocale(LC_NUMERIC, "en_US.utf8")) {
@ -121,13 +125,15 @@ namespace geode {
} }
else { else {
Num result; Num result;
auto [_, ec] = std::from_chars(str.data(), str.data() + str.size(), result, base); std::from_chars_result res;
switch (ec) { if constexpr (std::is_floating_point_v<Num>) res = std::from_chars(str.data(), str.data() + str.size(), result);
case std::errc(): return Ok(result); else res = std::from_chars(str.data(), str.data() + str.size(), result, base);
case std::errc::invalid_argument: return Err("String is not a number");
case std::errc::result_out_of_range: return Err("Number is too large to fit"); auto [_, ec] = res;
default: return Err("Unknown error"); if (ec == std::errc()) return Ok(result);
} else if (ec == std::errc::invalid_argument) return Err("String is not a number");
else if (ec == std::errc::result_out_of_range) return Err("Number is too large to fit");
else return Err("Unknown error");
} }
} }