From 02475e05ccd1aa15c6a6163834f28bfebbef796f Mon Sep 17 00:00:00 2001 From: Rutger Broekhoff Date: Mon, 30 Nov 2026 11:47:36 +0100 Subject: RWGPS webhook and such --- server/src/util.cppm | 56 +++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 42 insertions(+), 14 deletions(-) (limited to 'server/src/util.cppm') diff --git a/server/src/util.cppm b/server/src/util.cppm index 2857fe5..986e350 100644 --- a/server/src/util.cppm +++ b/server/src/util.cppm @@ -20,14 +20,9 @@ constexpr auto parse_double( { auto x = 0.0; auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, fmt); - if (ec == std::errc{}) - { - return x; - } - else - { + if (ec != std::errc{}) return std::nullopt; - } + return x; } constexpr auto parse_float( @@ -37,14 +32,20 @@ constexpr auto parse_float( { auto x = 0.0; auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, fmt); - if (ec == std::errc{}) - { - return x; - } - else - { + if (ec != std::errc{}) return std::nullopt; - } + return x; +} + +export template +constexpr auto parse_int(std::string_view s, int base = 10) noexcept + -> std::optional +{ + auto x = T{}; + auto [_, ec] = std::from_chars(s.data(), s.data() + s.size(), x, base); + if (ec != std::errc{}) + return std::nullopt; + return x; } template @@ -107,10 +108,14 @@ public: { } + constexpr zstring_view(std::string s) : zstring_view{s.c_str(), s.length()} {} + constexpr auto length() const -> std::size_t { return length_; } constexpr auto c_str() const -> char const* { return s_; } + constexpr auto empty() const -> bool { return length() == 0; } + constexpr operator std::string_view() const { return std::string_view{s_, length_}; @@ -239,3 +244,26 @@ public: explicit not_null(lazy_zstring_view s) -> not_null; } // namespace routemon::util + +template <> +struct std::formatter +{ + template + constexpr auto parse(ParseContext& ctx) -> ParseContext::iterator + { + auto it = ctx.begin(); + if (it != ctx.end() && *it != '}') + throw std::format_error{ + "unexpected formatting arguments for util::zstring_view" + }; + return it; + } + + template + auto format(routemon::util::zstring_view s, FmtContext& ctx) const + -> FmtContext::iterator + { + return std::ranges::copy(std::string_view{s.c_str(), s.length()}, ctx.out()) + .out; + } +}; -- cgit v1.3.1