• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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>
22 #include <variant>
23 
24 #include <ftl/details/future.h>
25 
26 namespace android::ftl {
27 
28 // 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.
30 //
31 // See also SharedFuture<T> shorthand below.
32 //
33 template <typename T, template <typename> class FutureImpl = std::future>
34 class 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.
Future()42   Future() : future_(std::in_place_type<FutureImpl<T>>) {}
43 
44   // Constructs a future from its standard counterpart, implicitly.
Future(FutureImpl<T> && f)45   Future(FutureImpl<T>&& f) : future_(std::move(f)) {}
46 
valid()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   using Base::wait_for;
55 
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>
Future(details::ValueTag,Args &&...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 
98 template <typename T>
99 using SharedFuture = Future<T, std::shared_future>;
100 
101 // Deduction guide for implicit conversion.
102 template <typename T, template <typename> class FutureImpl>
103 Future(FutureImpl<T>&&) -> Future<T, FutureImpl>;
104 
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 //
114 template <typename V>
yield(V && value)115 inline Future<V> yield(V&& value) {
116   return {details::ValueTag{}, std::move(value)};
117 }
118 
119 template <typename V, typename... Args>
yield(Args &&...args)120 inline Future<V> yield(Args&&... args) {
121   return {details::ValueTag{}, std::forward<Args>(args)...};
122 }
123 
124 // Creates a future that defers a function call until its result is queried.
125 //
126 //   auto future = ftl::defer([](int x) { return x + 1; }, 99);
127 //   assert(future.get() == 100);
128 //
129 template <typename F, typename... Args>
defer(F && f,Args &&...args)130 inline auto defer(F&& f, Args&&... args) {
131   return Future(std::async(std::launch::deferred, std::forward<F>(f), std::forward<Args>(args)...));
132 }
133 
134 }  // namespace android::ftl
135