-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathmap.hpp
102 lines (87 loc) · 2.72 KB
/
map.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
/**
* Copyright Quadrivium LLC
* All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_UTILS_MAP_HPP
#define KAGOME_UTILS_MAP_HPP
#include <functional>
#include <optional>
#include <type_traits>
#include <boost/utility/result_of.hpp>
namespace kagome::utils {
template <typename T, typename F>
inline std::optional<typename boost::result_of<
F(typename std::decay_t<T>::value_type &&)>::type>
map(T &&source, F &&func) {
if (source) {
return {std::forward<F>(func)(*std::forward<T>(source))};
}
return std::nullopt;
}
template <typename C>
requires requires { typename C::mapped_type; }
inline std::optional<std::reference_wrapper<const typename C::mapped_type>>
get(const C &container, const typename C::key_type &key) {
if (auto it = container.find(key); it != container.end()) {
return {{it->second}};
}
return std::nullopt;
}
template <typename C>
requires requires { typename C::mapped_type; }
inline std::optional<std::reference_wrapper<typename C::mapped_type>> get(
C &container, const typename C::key_type &key) {
if (auto it = container.find(key); it != container.end()) {
return {{it->second}};
}
return std::nullopt;
}
template <typename>
struct is_pair : std::false_type {};
template <typename T, typename U>
struct is_pair<std::pair<T, U>> : std::true_type {};
template <typename C>
requires requires {
typename C::value_type;
std::is_same_v<is_pair<typename C::value_type>, std::false_type>;
}
inline std::optional<std::reference_wrapper<const typename C::value_type>>
get(const C &container, const size_t &index) {
if (index < container.size()) {
return {{container[index]}};
}
return std::nullopt;
}
template <typename C>
requires requires {
typename C::value_type;
std::is_same_v<is_pair<typename C::value_type>, std::false_type>;
}
inline std::optional<std::reference_wrapper<typename C::value_type>> get(
C &container, const size_t &index) {
if (index < container.size()) {
return {{container[index]}};
}
return std::nullopt;
}
template <typename T>
inline auto fromRefToOwn(
const std::optional<std::reference_wrapper<T>> &opt_ref) {
std::optional<std::decay_t<T>> val{};
if (opt_ref) {
val = opt_ref->get();
}
return val;
}
template <typename C>
requires requires { typename C::mapped_type; }
inline std::optional<typename C::iterator> get_it(
C &container, const typename C::key_type &key) {
if (auto it = container.find(key); it != container.end()) {
return it;
}
return std::nullopt;
}
} // namespace kagome::utils
#endif // KAGOME_UTILS_MAP_HPP