seams-core v2.14.0
libyodaLib, the C++ engine of d-SEAMS
Loading...
Searching...
No Matches
number_parse.hpp
Go to the documentation of this file.
1#ifndef SEAMS_NUMBER_PARSE_HPP_
2#define SEAMS_NUMBER_PARSE_HPP_
3
4#include <cerrno>
5#include <cmath>
6#include <cstdlib>
7#include <locale.h>
8#include <string>
9#include <string_view>
10
11namespace seams {
12
13// libc++ from the conda macOS 11 toolchain deletes std::from_chars for
14// a floating value. strtod_l in the C locale follows the same grammar:
15// no leading plus, no hexadecimal form, the whole text consumed, and
16// overflow or underflow to zero rejected.
17
18inline bool parseExactDouble(std::string_view text, double &out) {
19 if (text.empty() || text.front() == '+') {
20 return false;
21 }
22 for (char raw : text) {
23 const auto c = static_cast<unsigned char>(raw);
24 if (raw == 'x' || raw == 'X' || c == ' ' || c == '\t' || c == '\n' ||
25 c == '\v' || c == '\f' || c == '\r') {
26 return false;
27 }
28 }
29#if defined(_WIN32)
30 // MinGW and MSVC spell the C-locale converter this way. newlocale
31 // is not in their headers. The grammar stays the one strtod_l uses.
32 static const _locale_t loc = _create_locale(LC_ALL, "C");
33 if (loc == nullptr) {
34 return false;
35 }
36#else
37 static const locale_t loc =
38 newlocale(LC_ALL_MASK, "C", static_cast<locale_t>(nullptr));
39 if (loc == static_cast<locale_t>(nullptr)) {
40 return false;
41 }
42#endif
43 const std::string token(text);
44 char *end = nullptr;
45 errno = 0;
46#if defined(_WIN32)
47 const double value = _strtod_l(token.c_str(), &end, loc);
48#else
49 const double value = strtod_l(token.c_str(), &end, loc);
50#endif
51 if (end != token.c_str() + token.size()) {
52 return false;
53 }
54 if (errno == ERANGE && (value == 0.0 || !std::isfinite(value))) {
55 return false;
56 }
57 out = value;
58 return true;
59}
60
61} // namespace seams
62
63#endif
bool parseExactDouble(std::string_view text, double &out)