util/NumberParser: new library based on std::from_chars()

This commit is contained in:
Max Kellermann 2024-01-04 21:03:25 +01:00
parent 393d57b387
commit e1eea9d98a

30
src/util/NumberParser.hxx Normal file
View File

@ -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);
}