uvco 0.1
Loading...
Searching...
No Matches
select.h
Go to the documentation of this file.
1// uvco (c) 2023 Lewin Bormann. See LICENSE for specific terms.
2
3#pragma once
4
5#include <fmt/core.h>
6#include <fmt/ranges.h>
7
9
10#include <coroutine>
11#include <tuple>
12#include <utility>
13#include <variant>
14#include <vector>
15
16namespace uvco {
17
21
39template <typename... Ts> class SelectSet {
40public:
41 using Variant = std::variant<Promise<Ts>...>;
42 using Tuple = std::tuple<Promise<Ts>...>;
43
44 explicit SelectSet(Promise<Ts>... promises)
45 : promises_{std::move(promises)...} {}
46
48 if (!resumed_) {
49 std::apply(
50 [](auto &&...promise) { (promise.core()->resetHandle(), ...); },
51 promises_);
52 }
53 }
54
55 [[nodiscard]] bool await_ready() const noexcept {
56 return resumed_ || std::apply(
57 [](auto &&...promise) -> bool {
58 return (promise.ready() || ...);
59 },
60 promises_);
61 }
62
65 void await_suspend(std::coroutine_handle<> handle) {
66 BOOST_ASSERT_MSG(!resumed_, "A select set can only be used once");
67 std::apply(
68 [handle](auto &&...promise) {
69 ((!promise.core()->stale() ? promise.core()->setHandle(handle)
70 : (void)0),
71 ...);
72 },
73 promises_);
74 }
75
83 std::vector<Variant> await_resume() {
84 resumed_ = true;
85 std::vector<Variant> readyPromises;
86 checkPromises(readyPromises);
87 return readyPromises;
88 }
89
90private:
91 template <size_t Ix = 0>
92 void checkPromises(std::vector<Variant> &readyPromises) {
93 if constexpr (Ix < sizeof...(Ts)) {
94 using PromiseType = std::tuple_element_t<Ix, Tuple>;
95 PromiseType &promise = std::get<Ix>(promises_);
96 if (promise.ready()) {
97 readyPromises.emplace_back(std::in_place_index<Ix>, std::move(promise));
98 } else {
99 promise.core()->resetHandle();
100 }
101 checkPromises<Ix + 1>(readyPromises);
102 }
103 }
104
106 bool resumed_ = false;
107};
108
110
111} // namespace uvco
Definition promise.h:76
Definition select.h:39
std::vector< Variant > await_resume()
Definition select.h:83
SelectSet(Promise< Ts >... promises)
Definition select.h:44
bool await_ready() const noexcept
Definition select.h:55
std::variant< Promise< Ts >... > Variant
Definition select.h:41
std::tuple< Promise< Ts >... > Tuple
Definition select.h:42
~SelectSet()
Definition select.h:47
Tuple promises_
Definition select.h:105
void checkPromises(std::vector< Variant > &readyPromises)
Definition select.h:92
void await_suspend(std::coroutine_handle<> handle)
Definition select.h:65
bool resumed_
Definition select.h:106
Definition async_work.cc:17