chrono_parse
Loading...
Searching...
No Matches
charconv.hpp
1/*
2MIT License
3
4Copyright (c) 2024 mguludag
5
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22SOFTWARE.
23*/
24#ifndef MGUTILITY_STD_CHARCONV_HPP
25#define MGUTILITY_STD_CHARCONV_HPP
27#include <system_error>
28
29#if MGUTILITY_CPLUSPLUS >= 201703L
30#include <charconv>
31#endif
32
33namespace mgutility {
34
35#if MGUTILITY_CPLUSPLUS < 201703L
36
41 const char
42 *ptr;
43 std::errc ec;
44};
45
53constexpr auto char_to_int(char c) noexcept -> int {
54 return (c >= '0' && c <= '9') ? c - '0' : -1;
55}
56
65MGUTILITY_CNSTXPR auto from_chars(const char *first, const char *last,
66 int &value) noexcept -> from_chars_result {
67 int result = 0;
68 bool negative = false;
69 const char *it = first;
70
71 if (it == last) {
72 return {first, std::errc::invalid_argument};
73 }
74
75 if (*it == '-') {
76 negative = true;
77 ++it;
78 if (it == last) {
79 return {first, std::errc::invalid_argument};
80 }
81 }
82
83 for (; it != last; ++it) {
84 int digit = char_to_int(*it);
85 if (digit == -1) {
86 break;
87 }
88 result = result * 10 + digit;
89 }
90
91 if (it == first || (negative && it == first + 1)) {
92 return {first, std::errc::invalid_argument};
93 }
94
95 value = negative ? -result : result;
96 return {it, std::errc{}};
97}
98#else
99
100using from_chars_result = std::from_chars_result;
101using std::from_chars;
102
103#endif
104
105} // namespace mgutility
106
107#endif // MGUTILITY_STD_CHARCONV_HPP
Defines macros for compiler and standard support detection.
Result structure for from_chars function.
Definition charconv.hpp:40
const char * ptr
Pointer to the character after the last parsed character.
Definition charconv.hpp:42
std::errc ec
Error code indicating success or failure.
Definition charconv.hpp:43