Porytiles
Loading...
Searching...
No Matches
parse_int.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <expected>
4#include <string>
5#include <utility>
6
7namespace porytiles {
8
9// ReSharper disable once CppParameterMayBeConst
10template <typename T>
11std::expected<T, std::string> parse_int(std::string_view int_string, const int base)
12{
13 // Copy into a std::string: stoll needs a null-terminated buffer, and a string_view's data() carries no such
14 // guarantee.
15 const std::string buffer{int_string};
16 long long parsed;
17 std::size_t pos;
18
19 try {
20 parsed = std::stoll(buffer, &pos, base);
21 }
22 catch (const std::exception &) {
23 return std::unexpected{"invalid integral string: " + buffer};
24 }
25
26 if (buffer.size() != pos) {
27 return std::unexpected{"invalid integral string: " + buffer};
28 }
29
30 if (!std::in_range<T>(parsed)) {
31 return std::unexpected{"integral value out of range: " + buffer};
32 }
33
34 return static_cast<T>(parsed);
35}
36
37// ReSharper disable once CppParameterMayBeConst
38template <typename T>
39std::expected<T, std::string> parse_int(std::string_view int_string)
40{
41 return parse_int<T>(int_string, 0);
42}
43
44} // namespace porytiles
std::expected< T, std::string > parse_int(std::string_view int_string, const int base)
Definition parse_int.hpp:11