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