Kagome
Polkadot Runtime Engine in C++17
outcome.hpp
Go to the documentation of this file.
1 
6 #ifndef KAGOME_OUTCOME_HPP
7 #define KAGOME_OUTCOME_HPP
8 
9 #include <fmt/format.h>
10 #include <libp2p/outcome/outcome.hpp>
11 
12 namespace outcome {
13  using libp2p::outcome::failure;
14  using libp2p::outcome::result;
15  using libp2p::outcome::success;
16 } // namespace outcome
17 
18 template <>
19 struct fmt::formatter<std::error_code> {
20  // Parses format specifications. Must be empty
21  constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) {
22  // Parse the presentation format and store it in the formatter:
23  auto it = ctx.begin(), end = ctx.end();
24 
25  // Check if reached the end of the range:
26  if (it != end && *it != '}') {
27  throw format_error("invalid format");
28  }
29 
30  // Return an iterator past the end of the parsed range:
31  return it;
32  }
33 
34  // Formats the std::error_code
35  template <typename FormatContext>
36  auto format(const std::error_code &ec, FormatContext &ctx)
37  -> decltype(ctx.out()) {
38  // ctx.out() is an output iterator to write to.
39 
40  return format_to(ctx.out(), ec.message());
41  }
42 };
43 
44 template <typename Result, typename Failure>
45 struct fmt::formatter<outcome::result<Result, Failure>> {
46  // Parses format specifications. Must be empty
47  constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin()) {
48  // Parse the presentation format and store it in the formatter:
49  auto it = ctx.begin(), end = ctx.end();
50 
51  // Check if reached the end of the range:
52  if (it != end && *it != '}') {
53  throw format_error("invalid format");
54  }
55 
56  // Return an iterator past the end of the parsed range:
57  return it;
58  }
59 
60  // Formats the outcome
61  template <typename FormatContext>
62  auto format(const outcome::result<Result, Failure> &res, FormatContext &ctx)
63  -> decltype(ctx.out()) {
64  // ctx.out() is an output iterator to write to.
65 
66  if (res.has_value()) {
67  if constexpr (not std::is_same_v<Result, void>) {
68  return format_to(ctx.out(), res.has_value());
69  } else {
70  return format_to(ctx.out(), "success");
71  }
72  } else {
73  return format_to(ctx.out(), res.error().message());
74  }
75  }
76 };
77 
78 #endif // KAGOME_OUTCOME_HPP
auto format(const std::error_code &ec, FormatContext &ctx) -> decltype(ctx.out())
Definition: outcome.hpp:36
constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin())
Definition: outcome.hpp:21
constexpr auto parse(format_parse_context &ctx) -> decltype(ctx.begin())
Definition: outcome.hpp:47
STL namespace.
auto format(const outcome::result< Result, Failure > &res, FormatContext &ctx) -> decltype(ctx.out())
Definition: outcome.hpp:62