From e1eea9d98a8d53d56ce17cb67b320c34b4a8bfc8 Mon Sep 17 00:00:00 2001 From: Max Kellermann Date: Thu, 4 Jan 2024 21:03:25 +0100 Subject: [PATCH] util/NumberParser: new library based on std::from_chars() --- src/util/NumberParser.hxx | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 src/util/NumberParser.hxx diff --git a/src/util/NumberParser.hxx b/src/util/NumberParser.hxx new file mode 100644 index 000000000..101225eba --- /dev/null +++ b/src/util/NumberParser.hxx @@ -0,0 +1,30 @@ +// SPDX-License-Identifier: BSD-2-Clause +// author: Max Kellermann + +#pragma once + +#include +#include +#include +#include + +template +[[gnu::pure]] +std::optional +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 +[[gnu::pure]] +std::optional +ParseInteger(std::string_view src, int base=10) noexcept +{ + return ParseInteger(src.data(), src.data() + src.size(), base); +}