Skip to content

Commit

Permalink
feat: Add parsing utils
Browse files Browse the repository at this point in the history
BENCH: 21337504
  • Loading branch information
IbaiBuR committed Oct 15, 2024
1 parent d9bb420 commit 0b8fd6a
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/utils/parsing.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#pragma once

#include <charconv>
#include <optional>
#include <string>
#include <string_view>
#include <type_traits>

namespace utils::parsing {

namespace internal {

template <typename T>
concept NumberInput = std::is_same_v<T, std::string> || std::is_same_v<T, std::string_view>;

template <typename T>
concept NumberOutput = std::is_integral_v<T> || std::is_floating_point_v<T>;

} // namespace internal

template <internal::NumberInput Input, internal::NumberOutput Output>
constexpr std::optional<Output> to_number(const Input& s) {
Output value{};
const auto result = std::from_chars(s.data(), s.data() + s.size(), value);

if (result.ec == std::errc())
return value;

return std::nullopt;
}

} // namespace utils::parsing

0 comments on commit 0b8fd6a

Please sign in to comment.