blob: 12b6102b6feaa5e78d5416cf436e5b9c4f2a72a2 [file] [log] [blame]
Dominik Laskowski9bb429a2024-01-28 15:20:47 -05001/*
2 * Copyright 2024 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 <android-base/expected.h>
20#include <ftl/optional.h>
21
22#include <utility>
23
24namespace android::ftl {
25
26// Superset of base::expected<T, E> with monadic operations.
27//
28// TODO: Extend std::expected<T, E> in C++23.
29//
30template <typename T, typename E>
31struct Expected final : base::expected<T, E> {
32 using Base = base::expected<T, E>;
33 using Base::expected;
34
35 using Base::error;
36 using Base::has_value;
37 using Base::value;
38
39 template <typename P>
40 constexpr bool has_error(P predicate) const {
41 return !has_value() && predicate(error());
42 }
43
44 constexpr Optional<T> value_opt() const& {
45 return has_value() ? Optional(value()) : std::nullopt;
46 }
47
48 constexpr Optional<T> value_opt() && {
49 return has_value() ? Optional(std::move(value())) : std::nullopt;
50 }
51
52 // Delete new for this class. Its base doesn't have a virtual destructor, and
53 // if it got deleted via base class pointer, it would cause undefined
54 // behavior. There's not a good reason to allocate this object on the heap
55 // anyway.
56 static void* operator new(size_t) = delete;
57 static void* operator new[](size_t) = delete;
58};
59
60template <typename E>
61constexpr auto Unexpected(E&& error) {
62 return base::unexpected(std::forward<E>(error));
63}
64
65} // namespace android::ftl