TachyonUI 0.1.0
High-performance UI for building tools.
Loading...
Searching...
No Matches
gui_from_chars.h
Go to the documentation of this file.
1#pragma once
2
3#include <charconv>
4#include <locale>
5#include <sstream>
6#include <string>
7#include <system_error>
8#include <version>
9
10namespace tachyon
11{
14
19 template <typename T>
20 std::from_chars_result FromCharsStream(const char* first, const char* last, T& value)
21 {
22 auto digits = [last](const char* p) {
23 while (p != last && *p >= '0' && *p <= '9') ++p;
24 return p;
25 };
26 const char* p = first;
27 if (p != last && *p == '-') ++p;
28 const char* intEnd = digits(p);
29 const char* end = intEnd;
30 if (end != last && *end == '.')
31 end = digits(end + 1);
32 if (intEnd == p && end - intEnd <= 1)
33 return { first, std::errc::invalid_argument }; // no digits
34 if (end != last && (*end == 'e' || *end == 'E'))
35 {
36 const char* exp = end + 1;
37 if (exp != last && (*exp == '+' || *exp == '-')) ++exp;
38 if (const char* expEnd = digits(exp); expEnd != exp)
39 end = expEnd; // otherwise the 'e' isn't part of the number
40 }
41
42 std::istringstream in(std::string(first, end));
43 in.imbue(std::locale::classic());
44 T parsed{};
45 in >> parsed;
46 if (in.fail())
47 return { first, std::errc::result_out_of_range };
48 value = parsed;
49 return { end, std::errc{} };
50 }
51
54 template <typename T>
55 std::from_chars_result FromChars(const char* first, const char* last, T& value)
56 {
57#if defined(__cpp_lib_to_chars) && __cpp_lib_to_chars >= 201611L
58 return std::from_chars(first, last, value);
59#else
60 return FromCharsStream(first, last, value);
61#endif
62 }
63
64}
std::from_chars_result FromChars(const char *first, const char *last, T &value)
std::from_chars, falling back to FromCharsStream on standard libraries without the floating-point ove...
Definition gui_from_chars.h:55
std::from_chars_result FromCharsStream(const char *first, const char *last, T &value)
std::from_chars for a decimal number, through a classic-locale stream.
Definition gui_from_chars.h:20
Definition gui_logging.h:24