blob: e45c1f5e23ba010acaee438c33c57e4ccaa817e0 [file] [log] [blame]
Dominik Laskowskia957c1c2022-08-03 12:51:43 -07001/*
2 * Copyright 2022 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
19#include <functional>
20#include <optional>
21
22#include <ftl/details/type_traits.h>
23
24namespace android::ftl {
25
26template <typename>
27struct Optional;
28
29namespace details {
30
31template <typename>
32struct is_optional : std::false_type {};
33
34template <typename T>
35struct is_optional<std::optional<T>> : std::true_type {};
36
37template <typename T>
38struct is_optional<Optional<T>> : std::true_type {};
39
40template <typename F, typename T>
41struct transform_result {
42 using type = Optional<std::remove_cv_t<std::invoke_result_t<F, T>>>;
43};
44
45template <typename F, typename T>
46using transform_result_t = typename transform_result<F, T>::type;
47
48template <typename F, typename T>
49struct and_then_result {
50 using type = remove_cvref_t<std::invoke_result_t<F, T>>;
51 static_assert(is_optional<type>{}, "and_then function must return an optional");
52};
53
54template <typename F, typename T>
55using and_then_result_t = typename and_then_result<F, T>::type;
56
Dominik Laskowski07a71cd2022-09-28 10:38:46 -040057template <typename F, typename T>
58struct or_else_result {
59 using type = remove_cvref_t<std::invoke_result_t<F>>;
60 static_assert(std::is_same_v<type, std::optional<T>> || std::is_same_v<type, Optional<T>>,
61 "or_else function must return an optional T");
62};
63
64template <typename F, typename T>
65using or_else_result_t = typename or_else_result<F, T>::type;
66
Dominik Laskowskia957c1c2022-08-03 12:51:43 -070067} // namespace details
68} // namespace android::ftl