blob: dad180ff8e522d8ebe4178cdd6ed6d00b23e5d68 [file] [log] [blame]
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -08001/*
2 * Copyright 2020 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 <future>
20#include <type_traits>
21#include <utility>
Dominik Laskowskib17c6212022-05-09 09:36:19 -070022#include <variant>
23
24#include <ftl/details/future.h>
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080025
26namespace android::ftl {
27
Dominik Laskowskib17c6212022-05-09 09:36:19 -070028// Thin wrapper around FutureImpl<T> (concretely std::future<T> or std::shared_future<T>) with
29// extensions for pure values (created via ftl::yield) and continuations.
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080030//
Dominik Laskowskib17c6212022-05-09 09:36:19 -070031// See also SharedFuture<T> shorthand below.
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -080032//
Dominik Laskowskib17c6212022-05-09 09:36:19 -070033template <typename T, template <typename> class FutureImpl = std::future>
34class Future final : public details::BaseFuture<Future<T, FutureImpl>, T, FutureImpl> {
35 using Base = details::BaseFuture<Future, T, FutureImpl>;
36
37 friend Base; // For BaseFuture<...>::self.
38 friend details::BaseFuture<Future<T>, T, std::future>; // For BaseFuture<...>::share.
39
40 public:
41 // Constructs an invalid future.
42 Future() : future_(std::in_place_type<FutureImpl<T>>) {}
43
44 // Constructs a future from its standard counterpart, implicitly.
45 Future(FutureImpl<T>&& f) : future_(std::move(f)) {}
46
47 bool valid() const {
48 return std::holds_alternative<T>(future_) || std::get<FutureImpl<T>>(future_).valid();
49 }
50
51 // Forwarding functions. Base::share is only defined when FutureImpl is std::future, whereas the
52 // following are defined for either FutureImpl:
53 using Base::get;
Alec Mouri9892aac2023-12-11 21:16:59 +000054 using Base::wait_for;
Dominik Laskowskib17c6212022-05-09 09:36:19 -070055
56 // Attaches a continuation to the future. The continuation is a function that maps T to either R
57 // or ftl::Future<R>. In the former case, the chain wraps the result in a future as if by
58 // ftl::yield.
59 //
60 // auto future = ftl::yield(123);
61 // ftl::Future<char> futures[] = {ftl::yield('a'), ftl::yield('b')};
62 //
63 // auto chain =
64 // ftl::Future(std::move(future))
65 // .then([](int x) { return static_cast<std::size_t>(x % 2); })
66 // .then([&futures](std::size_t i) { return std::move(futures[i]); });
67 //
68 // assert(chain.get() == 'b');
69 //
70 template <typename F, typename R = std::invoke_result_t<F, T>>
71 auto then(F&& op) && -> Future<details::future_result_t<R>> {
72 return defer(
73 [](auto&& f, F&& op) {
74 R r = op(f.get());
75 if constexpr (std::is_same_v<R, details::future_result_t<R>>) {
76 return r;
77 } else {
78 return r.get();
79 }
80 },
81 std::move(*this), std::forward<F>(op));
82 }
83
84 private:
85 template <typename V>
86 friend Future<V> yield(V&&);
87
88 template <typename V, typename... Args>
89 friend Future<V> yield(Args&&...);
90
91 template <typename... Args>
92 Future(details::ValueTag, Args&&... args)
93 : future_(std::in_place_type<T>, std::forward<Args>(args)...) {}
94
95 std::variant<T, FutureImpl<T>> future_;
96};
97
98template <typename T>
99using SharedFuture = Future<T, std::shared_future>;
100
101// Deduction guide for implicit conversion.
102template <typename T, template <typename> class FutureImpl>
103Future(FutureImpl<T>&&) -> Future<T, FutureImpl>;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800104
105// Creates a future that wraps a value.
106//
107// auto future = ftl::yield(42);
108// assert(future.get() == 42);
109//
110// auto ptr = std::make_unique<char>('!');
111// auto future = ftl::yield(std::move(ptr));
112// assert(*future.get() == '!');
113//
Dominik Laskowskib17c6212022-05-09 09:36:19 -0700114template <typename V>
115inline Future<V> yield(V&& value) {
116 return {details::ValueTag{}, std::move(value)};
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800117}
118
Dominik Laskowskib17c6212022-05-09 09:36:19 -0700119template <typename V, typename... Args>
120inline Future<V> yield(Args&&... args) {
121 return {details::ValueTag{}, std::forward<Args>(args)...};
122}
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800123
Dominik Laskowskib17c6212022-05-09 09:36:19 -0700124// Creates a future that defers a function call until its result is queried.
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800125//
Dominik Laskowskib17c6212022-05-09 09:36:19 -0700126// auto future = ftl::defer([](int x) { return x + 1; }, 99);
127// assert(future.get() == 100);
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800128//
Dominik Laskowskib17c6212022-05-09 09:36:19 -0700129template <typename F, typename... Args>
130inline auto defer(F&& f, Args&&... args) {
131 return Future(std::async(std::launch::deferred, std::forward<F>(f), std::forward<Args>(args)...));
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800132}
133
134} // namespace android::ftl