blob: c78f9b76b69a9978fd8da86412c845402eb1df2b [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;
54
55 // Attaches a continuation to the future. The continuation is a function that maps T to either R
56 // or ftl::Future<R>. In the former case, the chain wraps the result in a future as if by
57 // ftl::yield.
58 //
59 // auto future = ftl::yield(123);
60 // ftl::Future<char> futures[] = {ftl::yield('a'), ftl::yield('b')};
61 //
62 // auto chain =
63 // ftl::Future(std::move(future))
64 // .then([](int x) { return static_cast<std::size_t>(x % 2); })
65 // .then([&futures](std::size_t i) { return std::move(futures[i]); });
66 //
67 // assert(chain.get() == 'b');
68 //
69 template <typename F, typename R = std::invoke_result_t<F, T>>
70 auto then(F&& op) && -> Future<details::future_result_t<R>> {
71 return defer(
72 [](auto&& f, F&& op) {
73 R r = op(f.get());
74 if constexpr (std::is_same_v<R, details::future_result_t<R>>) {
75 return r;
76 } else {
77 return r.get();
78 }
79 },
80 std::move(*this), std::forward<F>(op));
81 }
82
83 private:
84 template <typename V>
85 friend Future<V> yield(V&&);
86
87 template <typename V, typename... Args>
88 friend Future<V> yield(Args&&...);
89
90 template <typename... Args>
91 Future(details::ValueTag, Args&&... args)
92 : future_(std::in_place_type<T>, std::forward<Args>(args)...) {}
93
94 std::variant<T, FutureImpl<T>> future_;
95};
96
97template <typename T>
98using SharedFuture = Future<T, std::shared_future>;
99
100// Deduction guide for implicit conversion.
101template <typename T, template <typename> class FutureImpl>
102Future(FutureImpl<T>&&) -> Future<T, FutureImpl>;
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800103
104// Creates a future that wraps a value.
105//
106// auto future = ftl::yield(42);
107// assert(future.get() == 42);
108//
109// auto ptr = std::make_unique<char>('!');
110// auto future = ftl::yield(std::move(ptr));
111// assert(*future.get() == '!');
112//
Dominik Laskowskib17c6212022-05-09 09:36:19 -0700113template <typename V>
114inline Future<V> yield(V&& value) {
115 return {details::ValueTag{}, std::move(value)};
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800116}
117
Dominik Laskowskib17c6212022-05-09 09:36:19 -0700118template <typename V, typename... Args>
119inline Future<V> yield(Args&&... args) {
120 return {details::ValueTag{}, std::forward<Args>(args)...};
121}
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800122
Dominik Laskowskib17c6212022-05-09 09:36:19 -0700123// Creates a future that defers a function call until its result is queried.
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800124//
Dominik Laskowskib17c6212022-05-09 09:36:19 -0700125// auto future = ftl::defer([](int x) { return x + 1; }, 99);
126// assert(future.get() == 100);
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800127//
Dominik Laskowskib17c6212022-05-09 09:36:19 -0700128template <typename F, typename... Args>
129inline auto defer(F&& f, Args&&... args) {
130 return Future(std::async(std::launch::deferred, std::forward<F>(f), std::forward<Args>(args)...));
Dominik Laskowski4e2b71f2020-11-10 15:05:32 -0800131}
132
133} // namespace android::ftl