• 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 
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>
Future(details::ValueTag,Args &&...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 
97 template <typename T>
98 using SharedFuture = Future<T, std::shared_future>;
99 
100 // Deduction guide for implicit conversion.
101 template <typename T, template <typename> class FutureImpl>
102 Future(FutureImpl<T>&&) -> Future<T, FutureImpl>;
103 
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 //
113 template <typename V>
yield(V && value)114 inline Future<V> yield(V&& value) {
115   return {details::ValueTag{}, std::move(value)};
116 }
117 
118 template <typename V, typename... Args>
yield(Args &&...args)119 inline Future<V> yield(Args&&... args) {
120   return {details::ValueTag{}, std::forward<Args>(args)...};
121 }
122 
123 // Creates a future that defers a function call until its result is queried.
124 //
125 //   auto future = ftl::defer([](int x) { return x + 1; }, 99);
126 //   assert(future.get() == 100);
127 //
128 template <typename F, typename... Args>
defer(F && f,Args &&...args)129 inline auto defer(F&& f, Args&&... args) {
130   return Future(std::async(std::launch::deferred, std::forward<F>(f), std::forward<Args>(args)...));
131 }
132 
133 }  // namespace android::ftl
134