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 
23 namespace android::promise {
24 namespace impl {
25 
26 template <typename T>
27 struct FutureResult {
28     using Type = T;
29 };
30 
31 template <typename T>
32 struct FutureResult<std::future<T>> {
33     using Type = T;
34 };
35 
36 } // namespace impl
37 
38 template <typename T>
39 using FutureResult = typename impl::FutureResult<T>::Type;
40 
41 template <typename... Args>
42 inline auto defer(Args... args) {
43     return std::async(std::launch::deferred, std::forward<Args>(args)...);
44 }
45 
46 template <typename T>
47 inline std::future<T> yield(T&& v) {
48     return defer([](T&& v) { return std::forward<T>(v); }, std::forward<T>(v));
49 }
50 
51 template <typename T>
52 struct Chain {
53     Chain(std::future<T>&& f) : future(std::move(f)) {}
54     operator std::future<T>&&() && { return std::move(future); }
55 
56     T get() && { return future.get(); }
57 
58     template <typename F, typename R = std::invoke_result_t<F, T>>
59     auto then(F&& op) && -> Chain<FutureResult<R>> {
60         return defer(
61                 [](auto&& f, F&& op) {
62                     R r = op(f.get());
63                     if constexpr (std::is_same_v<R, FutureResult<R>>) {
64                         return r;
65                     } else {
66                         return r.get();
67                     }
68                 },
69                 std::move(future), std::forward<F>(op));
70     }
71 
72     std::future<T> future;
73 };
74 
75 template <typename T>
76 inline Chain<T> chain(std::future<T>&& f) {
77     return std::move(f);
78 }
79 
80 } // namespace android::promise
81