userver: userver/formats/parse/may_parse.hpp Source File
Loading...
Searching...
No Matches
may_parse.hpp
Go to the documentation of this file.
1#pragma once
2
3/// @file userver/formats/parse/may_parse.hpp
4/// @brief Cheap checks that tell when parsing a value is certain to fail, for
5/// skipping alternatives without throwing an exception.
6///
7/// @ingroup userver_universal userver_formats_parse
8
9#include <exception>
10#include <string>
11#include <type_traits>
12
13#include <userver/formats/parse/to.hpp>
14#include <userver/utils/meta_light.hpp>
15
16USERVER_NAMESPACE_BEGIN
17
18namespace formats::json {
19class Value;
20}
21
22namespace formats::parse {
23
24namespace impl {
25
26bool IsJsonNumber(const formats::json::Value& value);
27
28} // namespace impl
29
30/// @brief Fallback for types without a check: returns `true`, so the value has to
31/// be parsed.
32template <typename Value, typename T>
33bool MayParseAs(const Value&, To<T>) noexcept {
34 return true;
35}
36
37/// @brief Built-in check for `std::string`: returns `false` if the JSON value is
38/// not a string.
39bool MayParseAs(const formats::json::Value& value, To<std::string>);
40
41/// @brief Built-in check for `bool`: returns `false` if the JSON value is not a
42/// boolean.
43bool MayParseAs(const formats::json::Value& value, To<bool>);
44
45/// @brief Built-in check for integer and floating point types: returns `false`
46/// if the JSON value is not a number.
47template <typename T>
48requires(meta::IsInteger<T> || std::is_floating_point_v<T>)
49bool MayParseAs(const formats::json::Value& value, To<T>) {
50 return impl::IsJsonNumber(value);
51}
52
53/// @brief Cheap necessary condition for `value.As<T>()` to succeed.
54///
55/// Calls `MayParseAs(value, formats::parse::To<T>{})`: a built-in overload from
56/// this header, an overload found by ADL in the namespace of `T`, usually
57/// declared next to the `Parse` function of `T`, or the fallback that returns
58/// `true`. An overload must return `false` only if `value.As<T>()` is certain to
59/// throw. It should not throw itself: an exception derived from `std::exception`
60/// is treated as `true`, and the value is parsed as usual.
61///
62/// An overload should look only at the value itself, for example at its type,
63/// the presence of required members or the enum value, and should not check
64/// nested values: a recursive check repeats the work of parsing, especially
65/// for nested `std::variant`.
66///
67/// @returns `false` if `value.As<T>()` is certain to throw; `true` if nothing is
68/// known and the value has to be parsed.
69template <typename T, typename Value>
70bool MayParseAs(const Value& value) {
71 try {
72 return MayParseAs(value, To<T>{});
73 } catch (const std::exception&) {
74 return true;
75 }
76}
77
78} // namespace formats::parse
79
80USERVER_NAMESPACE_END