Kagome
Polkadot Runtime Engine in C++17
monadic_utils.hpp
Go to the documentation of this file.
1 
6 #ifndef KAGOME_MONADIC_UTILS_H
7 #define KAGOME_MONADIC_UTILS_H
8 
9 #include <optional>
10 #include <type_traits>
11 
12 #include "outcome/outcome.hpp"
13 
14 namespace kagome::common {
15 
21  template <typename T,
22  typename F,
23  typename R = std::invoke_result_t<F, const T &>>
24  std::optional<R> map_optional(std::optional<T> const &opt, F const &f) {
25  if (opt.has_value()) {
26  return std::optional<R>{f(opt.value())};
27  }
28  return std::nullopt;
29  }
30 
36  template <typename T, typename F, typename R = std::invoke_result_t<F, T &&>>
37  std::optional<R> map_optional(std::optional<T> &&opt, F const &f) {
38  if (opt.has_value()) {
39  return std::optional<R>{f(std::move(opt.value()))};
40  }
41  return std::nullopt;
42  }
43 
50  template <typename T,
51  typename F,
52  typename R = std::invoke_result_t<F, const T &>>
53  outcome::result<R> map_result(outcome::result<T> const &res, F const &f) {
54  if (res.has_value()) {
55  return outcome::result<R>{f(res.value())};
56  }
57  return res.as_failure();
58  }
59 
66  template <typename T, typename F, typename R = std::invoke_result_t<F, T &&>>
67  outcome::result<R> map_result(outcome::result<T> &&res, F const &f) {
68  if (res.has_value()) {
69  return outcome::result<R>{f(std::move(res.value()))};
70  }
71  return res.as_failure();
72  }
73 
81  template <typename T,
82  typename F,
83  typename R = std::invoke_result_t<F, T const &>>
84  outcome::result<std::optional<R>> map_result_optional(
85  outcome::result<std::optional<T>> const &res_opt, F const &f) {
86  return map_result(res_opt, [&f](auto &opt) {
87  return map_optional(opt, [&f](auto &v) { return f(v); });
88  });
89  }
90 
98  template <typename T, typename F, typename R = std::invoke_result_t<F, T &&>>
99  outcome::result<std::optional<R>> map_result_optional(
100  outcome::result<std::optional<T>> &&res_opt, F const &f) {
101  return map_result(res_opt, [&f](auto &opt) {
102  return map_optional(opt, [&f](auto &v) { return f(std::move(v)); });
103  });
104  }
105 
106 } // namespace kagome::common
107 
108 #endif // KAGOME_MONADIC_UTILS_H
outcome::result< R > map_result(outcome::result< T > const &res, F const &f)
std::optional< R > map_optional(std::optional< T > const &opt, F const &f)
outcome::result< std::optional< R > > map_result_optional(outcome::result< std::optional< T >> const &res_opt, F const &f)