From 81484f737f6949bcd62c995515bc414c834f42fa Mon Sep 17 00:00:00 2001 From: ado Date: Fri, 4 Aug 2023 22:31:29 +0200 Subject: [PATCH] Remove std::from_chars from extract.hpp --- include/ss/extract.hpp | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/include/ss/extract.hpp b/include/ss/extract.hpp index f44b73c..e84e3e2 100644 --- a/include/ss/extract.hpp +++ b/include/ss/extract.hpp @@ -12,7 +12,8 @@ #ifndef SSP_DISABLE_FAST_FLOAT #include #else -#include +#include +#include #endif namespace ss { @@ -40,12 +41,32 @@ std::enable_if_t, std::optional> to_num( template std::enable_if_t, std::optional> to_num( const char* const begin, const char* const end) { - T ret; - auto [ptr, ec] = std::from_chars(begin, end, ret); + constexpr static auto buff_max = 64; + char buff[buff_max]; + size_t string_range = std::distance(begin, end); - if (ec != std::errc() || ptr != end) { + if (string_range > buff_max) { return std::nullopt; } + + std::copy_n(begin, string_range, buff); + buff[string_range] = '\0'; + + T ret; + char* parse_end = nullptr; + + if constexpr (std::is_same_v) { + ret = std::strtof(buff, &parse_end); + } else if constexpr (std::is_same_v) { + ret = std::strtod(buff, &parse_end); + } else if constexpr (std::is_same_v) { + ret = std::strtold(buff, &parse_end); + } + + if (parse_end != buff + string_range) { + return std::nullopt; + } + return ret; }