util/NumberParser: new library based on std::from_chars()
This commit is contained in:
parent
393d57b387
commit
e1eea9d98a
|
@ -0,0 +1,30 @@
|
|||
// SPDX-License-Identifier: BSD-2-Clause
|
||||
// author: Max Kellermann <max.kellermann@gmail.com>
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <charconv>
|
||||
#include <concepts>
|
||||
#include <optional>
|
||||
#include <string_view>
|
||||
|
||||
template<std::integral T>
|
||||
[[gnu::pure]]
|
||||
std::optional<T>
|
||||
ParseInteger(const char *first, const char *last, int base=10) noexcept
|
||||
{
|
||||
T value;
|
||||
auto [ptr, ec] = std::from_chars(first, last, value, base);
|
||||
if (ptr == last && ec == std::errc{})
|
||||
return value;
|
||||
else
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
template<std::integral T>
|
||||
[[gnu::pure]]
|
||||
std::optional<T>
|
||||
ParseInteger(std::string_view src, int base=10) noexcept
|
||||
{
|
||||
return ParseInteger<T>(src.data(), src.data() + src.size(), base);
|
||||
}
|
Loading…
Reference in New Issue