|
| 1 | +#pragma once |
| 2 | + |
| 3 | +#include <cerrno> |
| 4 | +#include <charconv> |
| 5 | +#include <cstdlib> |
| 6 | +#include <optional> |
| 7 | +#include <string> |
| 8 | +#include <string_view> |
| 9 | +#include <system_error> |
| 10 | +#include <type_traits> |
| 11 | + |
| 12 | +namespace PJ { |
| 13 | + |
| 14 | +/// Parse the *entire* @p text as a number of type T, returning nullopt unless |
| 15 | +/// the whole string is a valid, in-range value (empty input, trailing |
| 16 | +/// characters, or overflow all yield nullopt). |
| 17 | +/// |
| 18 | +/// Use this instead of std::from_chars when T may be floating-point: Apple |
| 19 | +/// Clang's libc++ does not implement the std::from_chars floating-point |
| 20 | +/// overloads, so those are routed through std::strto* here. Integral types go |
| 21 | +/// straight to std::from_chars on every toolchain. |
| 22 | +template <typename T> |
| 23 | +[[nodiscard]] std::optional<T> parseNumber(std::string_view text) { |
| 24 | + static_assert( |
| 25 | + std::is_arithmetic_v<T> && !std::is_same_v<T, bool>, |
| 26 | + "parseNumber supports integral and floating-point types, not bool"); |
| 27 | + if (text.empty()) { |
| 28 | + return std::nullopt; |
| 29 | + } |
| 30 | + if constexpr (std::is_floating_point_v<T>) { |
| 31 | + // std::strto* needs a null-terminated buffer and @p text may be a |
| 32 | + // non-terminated view, so copy it. Number strings are short — the |
| 33 | + // allocation is negligible for the config/settings paths this serves. |
| 34 | + const std::string buffer(text); |
| 35 | + const char* begin = buffer.c_str(); |
| 36 | + char* last = nullptr; |
| 37 | + errno = 0; |
| 38 | + T out{}; |
| 39 | + if constexpr (std::is_same_v<T, float>) { |
| 40 | + out = std::strtof(begin, &last); |
| 41 | + } else if constexpr (std::is_same_v<T, long double>) { |
| 42 | + out = std::strtold(begin, &last); |
| 43 | + } else { |
| 44 | + out = std::strtod(begin, &last); |
| 45 | + } |
| 46 | + if (errno != 0 || last != begin + buffer.size()) { |
| 47 | + return std::nullopt; |
| 48 | + } |
| 49 | + return out; |
| 50 | + } else { |
| 51 | + T out{}; |
| 52 | + const char* begin = text.data(); |
| 53 | + const char* end = begin + text.size(); |
| 54 | + const auto [ptr, ec] = std::from_chars(begin, end, out); |
| 55 | + if (ec != std::errc{} || ptr != end) { |
| 56 | + return std::nullopt; |
| 57 | + } |
| 58 | + return out; |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +} // namespace PJ |
0 commit comments