Roll our own implementation of parse

This commit is contained in:
Ted John 2021-01-18 18:51:08 +00:00
parent fa1a374a04
commit 2b3e7b98b8

View file

@ -11,7 +11,6 @@
#include "../common.h"
#include <charconv>
#include <cstdarg>
#include <cstddef>
#include <optional>
@ -122,13 +121,31 @@ namespace String
template<typename T> std::optional<T> Parse(std::string_view input)
{
T out;
const std::from_chars_result result = std::from_chars(input.data(), input.data() + input.size(), out);
if (result.ec == std::errc::invalid_argument || result.ec == std::errc::result_out_of_range)
{
if (input.size() == 0)
return std::nullopt;
T result = 0;
for (size_t i = 0; i < input.size(); i++)
{
auto chr = input[i];
if (chr >= '0' && chr <= '9')
{
auto digit = chr - '0';
auto last = result;
result = static_cast<T>((result * 10) + digit);
if (result <= last)
{
// Overflow, number too large for type
return std::nullopt;
}
}
else
{
// Bad character
return std::nullopt;
}
}
return out;
return result;
}
} // namespace String