C/C++ API Reference
Loading...
Searching...
No Matches
join.h
1// Copyright 2024 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://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, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#pragma once
15
16#include "pw_async2/dispatcher.h"
17
18namespace pw::async2 {
19
21
27template <typename... Pendables>
28class Join {
29 private:
30 static constexpr auto kTupleIndexSequence =
31 std::make_index_sequence<sizeof...(Pendables)>();
32 using TupleOfOutputRvalues = std::tuple<PendOutputOf<Pendables>&&...>;
33
34 public:
36 explicit Join(Pendables&&... pendables)
37 : pendables_(std::move(pendables)...),
38 outputs_(Poll<PendOutputOf<Pendables>>(Pending())...) {}
39
43 if (!PendElements(cx, kTupleIndexSequence)) {
44 return Pending();
45 }
46 return TakeOutputs(kTupleIndexSequence);
47 }
48
49 private:
53 template <size_t... Is>
54 bool PendElements(Context& cx, std::index_sequence<Is...>) {
55 return (... && PendElement<Is>(cx));
56 }
57
59 template <size_t... Is>
60 Poll<TupleOfOutputRvalues> TakeOutputs(std::index_sequence<Is...>) {
61 return Poll<TupleOfOutputRvalues>(
62 std::forward_as_tuple<PendOutputOf<Pendables>...>(TakeOutput<Is>()...));
63 }
64
70 template <size_t kTupleIndex>
71 bool PendElement(Context& cx) {
72 auto& output = std::get<kTupleIndex>(outputs_);
73 if (output.IsReady()) {
74 return true;
75 }
76 output = std::get<kTupleIndex>(pendables_).Pend(cx);
77 return output.IsReady();
78 }
79
81 template <size_t kTupleIndex>
82 PendOutputOf<typename std::tuple_element<kTupleIndex,
83 std::tuple<Pendables...>>::type>&&
84 TakeOutput() {
85 return std::move(std::get<kTupleIndex>(outputs_).value());
86 }
87
88 std::tuple<Pendables...> pendables_;
89 std::tuple<Poll<PendOutputOf<Pendables>>...> outputs_;
90};
91
92template <typename... Pendables>
93Join(Pendables&&...) -> Join<Pendables...>;
94
95} // namespace pw::async2
Definition: context.h:55
Definition: join.h:28
Definition: poll.h:60
Join(Pendables &&... pendables)
Creates a Join from a series of pendable values.
Definition: join.h:36
Poll< TupleOfOutputRvalues > Pend(Context &cx)
Definition: join.h:42
constexpr PendingType Pending()
Returns a value indicating that an operation was not yet able to complete.
Definition: poll.h:271