Skip to content

Commit 343a3a4

Browse files
committed
Replace stoull/stoll with std::from_chars for integers in cli::Reader
1 parent 6085226 commit 343a3a4

1 file changed

Lines changed: 6 additions & 34 deletions

File tree

include/rfl/cli/Reader.hpp

Lines changed: 6 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
#include <charconv>
55
#include <concepts>
6-
#include <limits>
76
#include <map>
87
#include <optional>
98
#include <set>
@@ -72,45 +71,18 @@ rfl::Result<T> parse_value(
7271
return value;
7372
}
7473

75-
template <class T> requires (std::is_unsigned_v<T> && !std::same_as<T, bool>)
74+
template <class T> requires (std::is_integral_v<T> && !std::same_as<T, bool>)
7675
rfl::Result<T> parse_value(
7776
const std::string& _str, const std::string& _path
7877
) noexcept {
79-
try {
80-
if (!_str.empty() && _str[0] == '-') {
81-
return error(
82-
"Value '" + _str + "' is negative, cannot convert to unsigned integer for key '" + _path + "'.");
83-
}
84-
const auto val = std::stoull(_str);
85-
if (val > static_cast<unsigned long long>(std::numeric_limits<T>::max())) {
86-
return error(
87-
"Value '" + _str + "' is out of range for key '" + _path + "'.");
88-
}
89-
return static_cast<T>(val);
90-
}
91-
catch (...) {
92-
return error(
93-
"Could not cast '" + _str + "' to unsigned integer for key '" + _path + "'.");
94-
}
95-
}
96-
97-
template <class T> requires (std::is_integral_v<T> && std::is_signed_v<T>)
98-
rfl::Result<T> parse_value(
99-
const std::string& _str, const std::string& _path
100-
) noexcept {
101-
try {
102-
const auto val = std::stoll(_str);
103-
if (val < static_cast<long long>(std::numeric_limits<T>::min())
104-
|| val > static_cast<long long>(std::numeric_limits<T>::max())) {
105-
return error(
106-
"Value '" + _str + "' is out of range for key '" + _path + "'.");
107-
}
108-
return static_cast<T>(val);
109-
}
110-
catch (...) {
78+
T value;
79+
const auto [ptr, ec] =
80+
std::from_chars(_str.data(), _str.data() + _str.size(), value);
81+
if (ec != std::errc() || ptr != _str.data() + _str.size()) {
11182
return error(
11283
"Could not cast '" + _str + "' to integer for key '" + _path + "'.");
11384
}
85+
return value;
11486
}
11587

11688
struct Reader {

0 commit comments

Comments
 (0)