blob: a80d441a4b4fe61f0b27e4ba700f988410a0042b [file] [log] [blame]
Dominik Laskowski8e89c2a2020-04-27 16:08:19 -07001/*
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
23namespace android::promise {
24namespace impl {
25
26template <typename T>
27struct FutureResult {
28 using Type = T;
29};
30
31template <typename T>
32struct FutureResult<std::future<T>> {
33 using Type = T;
34};
35
36} // namespace impl
37
38template <typename T>
39using FutureResult = typename impl::FutureResult<T>::Type;
40
41template <typename... Args>
42inline auto defer(Args... args) {
43 return std::async(std::launch::deferred, std::forward<Args>(args)...);
44}
45
46template <typename T>
47inline std::future<T> yield(T&& v) {
48 return defer([](T&& v) { return std::forward<T>(v); }, std::forward<T>(v));
49}
50
51template <typename T>
52struct 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
75template <typename T>
76inline Chain<T> chain(std::future<T>&& f) {
77 return std::move(f);
78}
79
80} // namespace android::promise