Debian Codegraph @

src/core/lib/promise/race.h

raw
1 // Copyright 2021 gRPC authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef GRPC_CORE_LIB_PROMISE_RACE_H
16 #define GRPC_CORE_LIB_PROMISE_RACE_H
17
18 #include <grpc/support/port_platform.h>
19
20 #include <type_traits>
21
22 #include "absl/types/variant.h"
23
24 #include "src/core/lib/promise/poll.h"
25
26 namespace grpc_core {
27
28 namespace promise_detail {
29
30 // Implementation type for Race combinator.
31 template <typename... Promises>
32 class Race;
33
34 template <typename Promise, typename... Promises>
35 class Race<Promise, Promises...> {
36 public:
37 using Result = decltype(std::declval<Promise>()());
38
39 explicit Race(Promise promise, Promises... promises)
40 : promise_(std::move(promise)), next_(std::move(promises)...) {}
41
42 Result operator()() {
43 // Check our own promise.
44 auto r = promise_();
45 if (absl::holds_alternative<Pending>(r)) {
46 // Check the rest of them.
47 return next_();
48 }
49 // Return the first ready result.
50 return std::move(absl::get<kPollReadyIdx>(std::move(r)));
51 }
52
53 private:
54 // The Promise checked by this instance.
55 Promise promise_;
56 // We recursively expand to check the rest of the instances.
57 Race<Promises...> next_;
58 };
59
60 template <typename Promise>
61 class Race<Promise> {
62 public:
63 using Result = decltype(std::declval<Promise>()());
64 explicit Race(Promise promise) : promise_(std::move(promise)) {}
65 Result operator()() { return promise_(); }
66
67 private:
68 Promise promise_;
69 };
70
71 } // namespace promise_detail
72
73 /// Run all the promises, return the first result that's available.
74 /// If two results are simultaneously available, bias towards the first result
75 /// listed.
76 template <typename... Promises>
77 promise_detail::Race<Promises...> Race(Promises... promises) {
78 return promise_detail::Race<Promises...>(std::move(promises)...);
79 }
80
81 } // namespace grpc_core
82
83 #endif // GRPC_CORE_LIB_PROMISE_RACE_H