100.00% Lines (192/192) 100.00% Functions (43/43)
TLA Baseline Branch
Line Hits Code Line Hits Code
1   // 1   //
2   // Copyright (c) 2026 Michael Vandeberg 2   // Copyright (c) 2026 Michael Vandeberg
3   // Copyright (c) 2026 Steve Gerbino 3   // Copyright (c) 2026 Steve Gerbino
4   // 4   //
5   // Distributed under the Boost Software License, Version 1.0. (See accompanying 5   // Distributed under the Boost Software License, Version 1.0. (See accompanying
6   // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) 6   // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7   // 7   //
8   // Official repository: https://github.com/cppalliance/capy 8   // Official repository: https://github.com/cppalliance/capy
9   // 9   //
10   10  
11   #ifndef BOOST_CAPY_WHEN_ANY_HPP 11   #ifndef BOOST_CAPY_WHEN_ANY_HPP
12   #define BOOST_CAPY_WHEN_ANY_HPP 12   #define BOOST_CAPY_WHEN_ANY_HPP
13   13  
14   #include <boost/capy/detail/config.hpp> 14   #include <boost/capy/detail/config.hpp>
15   #include <boost/capy/detail/results_combinators.hpp> 15   #include <boost/capy/detail/results_combinators.hpp>
16   #include <boost/capy/continuation.hpp> 16   #include <boost/capy/continuation.hpp>
17   #include <boost/capy/concept/executor.hpp> 17   #include <boost/capy/concept/executor.hpp>
18   #include <boost/capy/concept/context_awaitable.hpp> 18   #include <boost/capy/concept/context_awaitable.hpp>
19   #include <coroutine> 19   #include <coroutine>
20   #include <boost/capy/ex/executor_ref.hpp> 20   #include <boost/capy/ex/executor_ref.hpp>
21   #include <boost/capy/ex/abandon.hpp> 21   #include <boost/capy/ex/abandon.hpp>
22   #include <boost/capy/detail/owned_range.hpp> 22   #include <boost/capy/detail/owned_range.hpp>
23   #include <boost/capy/ex/frame_alloc_mixin.hpp> 23   #include <boost/capy/ex/frame_alloc_mixin.hpp>
24   #include <boost/capy/ex/frame_allocator.hpp> 24   #include <boost/capy/ex/frame_allocator.hpp>
25   #include <boost/capy/ex/await_context.hpp> 25   #include <boost/capy/ex/await_context.hpp>
26   #include <boost/capy/task.hpp> 26   #include <boost/capy/task.hpp>
27   27  
28   #include <array> 28   #include <array>
29   #include <atomic> 29   #include <atomic>
30   #include <exception> 30   #include <exception>
31   #include <memory> 31   #include <memory>
32   #include <mutex> 32   #include <mutex>
33   #include <optional> 33   #include <optional>
34   #include <ranges> 34   #include <ranges>
35   #include <stdexcept> 35   #include <stdexcept>
36   #include <stop_token> 36   #include <stop_token>
37   #include <tuple> 37   #include <tuple>
38   #include <type_traits> 38   #include <type_traits>
39   #include <utility> 39   #include <utility>
40   #include <variant> 40   #include <variant>
41   #include <vector> 41   #include <vector>
42   42  
43   /* 43   /*
44   when_any - Race multiple results tasks, select first success 44   when_any - Race multiple results tasks, select first success
45   ============================================================= 45   =============================================================
46   46  
47   OVERVIEW: 47   OVERVIEW:
48   --------- 48   ---------
49   when_any launches N results-returning tasks concurrently. A task 49   when_any launches N results-returning tasks concurrently. A task
50   wins by returning !ec; errors and exceptions do not win. Once a 50   wins by returning !ec; errors and exceptions do not win. Once a
51   winner is found, stop is requested for siblings and the winner's 51   winner is found, stop is requested for siblings and the winner's
52   payload is returned. If no winner exists (all fail), one of the 52   payload is returned. If no winner exists (all fail), one of the
53   failures is surfaced (an error_code at variant index 0, or a child's 53   failures is surfaced (an error_code at variant index 0, or a child's
54   exception rethrown); which one is unspecified. 54   exception rethrown); which one is unspecified.
55   55  
56   ARCHITECTURE: 56   ARCHITECTURE:
57   ------------- 57   -------------
58   The design mirrors when_all but with inverted completion semantics: 58   The design mirrors when_all but with inverted completion semantics:
59   59  
60   when_all: complete when remaining_count reaches 0 (all done) 60   when_all: complete when remaining_count reaches 0 (all done)
61   when_any: complete when has_winner becomes true (first done) 61   when_any: complete when has_winner becomes true (first done)
62   BUT still wait for remaining_count to reach 0 for cleanup 62   BUT still wait for remaining_count to reach 0 for cleanup
63   63  
64   Key components: 64   Key components:
65   - when_any_core: Shared state tracking winner and completion 65   - when_any_core: Shared state tracking winner and completion
66   - when_any_results_runner: Wrapper coroutine for each child task 66   - when_any_results_runner: Wrapper coroutine for each child task
67   - when_any_results_launcher/when_any_results_homogeneous_launcher: 67   - when_any_results_launcher/when_any_results_homogeneous_launcher:
68   Awaitables that start all runners concurrently 68   Awaitables that start all runners concurrently
69   69  
70   CRITICAL INVARIANTS: 70   CRITICAL INVARIANTS:
71   -------------------- 71   --------------------
72   1. Only a task returning !ec can become the winner (via atomic CAS) 72   1. Only a task returning !ec can become the winner (via atomic CAS)
73   2. All tasks must complete before parent resumes (cleanup safety) 73   2. All tasks must complete before parent resumes (cleanup safety)
74   3. Stop is requested immediately when winner is determined 74   3. Stop is requested immediately when winner is determined
75   4. Exceptions and errors do not claim winner status 75   4. Exceptions and errors do not claim winner status
76   76  
77   POSITIONAL VARIANT: 77   POSITIONAL VARIANT:
78   ------------------- 78   -------------------
79   The variadic overload returns std::variant<error_code, R1, R2, ..., Rn>. 79   The variadic overload returns std::variant<error_code, R1, R2, ..., Rn>.
80   Index 0 is error_code (failure/no-winner). Index 1..N identifies the 80   Index 0 is error_code (failure/no-winner). Index 1..N identifies the
81   winning child and carries its payload. 81   winning child and carries its payload.
82   82  
83   RANGE OVERLOAD: 83   RANGE OVERLOAD:
84   --------------- 84   ---------------
85   The range overload returns variant<error_code, pair<size_t, T>> for 85   The range overload returns variant<error_code, pair<size_t, T>> for
86   non-void children or variant<error_code, size_t> for void children. 86   non-void children or variant<error_code, size_t> for void children.
87   87  
88   MEMORY MODEL: 88   MEMORY MODEL:
89   ------------- 89   -------------
90   Synchronization chain from winner's write to parent's read: 90   Synchronization chain from winner's write to parent's read:
91   91  
92   1. Winner thread writes result_ (non-atomic) 92   1. Winner thread writes result_ (non-atomic)
93   2. Winner thread calls signal_completion() -> fetch_sub(acq_rel) on remaining_count_ 93   2. Winner thread calls signal_completion() -> fetch_sub(acq_rel) on remaining_count_
94   3. Last task thread (may be winner or non-winner) calls signal_completion() 94   3. Last task thread (may be winner or non-winner) calls signal_completion()
95   -> fetch_sub(acq_rel) on remaining_count_, observing count becomes 0 95   -> fetch_sub(acq_rel) on remaining_count_, observing count becomes 0
96   4. Last task returns caller_ex_.dispatch(continuation_) via symmetric transfer 96   4. Last task returns caller_ex_.dispatch(continuation_) via symmetric transfer
97   5. Parent coroutine resumes and reads result_ 97   5. Parent coroutine resumes and reads result_
98   98  
99   Synchronization analysis: 99   Synchronization analysis:
100   - All fetch_sub operations on remaining_count_ form a release sequence 100   - All fetch_sub operations on remaining_count_ form a release sequence
101   - Winner's fetch_sub releases; subsequent fetch_sub operations participate 101   - Winner's fetch_sub releases; subsequent fetch_sub operations participate
102   in the modification order of remaining_count_ 102   in the modification order of remaining_count_
103   - Last task's fetch_sub(acq_rel) synchronizes-with prior releases in the 103   - Last task's fetch_sub(acq_rel) synchronizes-with prior releases in the
104   modification order, establishing happens-before from winner's writes 104   modification order, establishing happens-before from winner's writes
105   - Executor dispatch() is expected to provide queue-based synchronization 105   - Executor dispatch() is expected to provide queue-based synchronization
106   (release-on-post, acquire-on-execute) completing the chain to parent 106   (release-on-post, acquire-on-execute) completing the chain to parent
107   - Even inline executors work (same thread = sequenced-before) 107   - Even inline executors work (same thread = sequenced-before)
108   108  
109   EXCEPTION SEMANTICS: 109   EXCEPTION SEMANTICS:
110   -------------------- 110   --------------------
111   Exceptions do NOT claim winner status. If a child throws, the exception 111   Exceptions do NOT claim winner status. If a child throws, the exception
112   is recorded but the combinator keeps waiting for a success. Only when 112   is recorded but the combinator keeps waiting for a success. Only when
113   all children complete without a winner is a failure surfaced. There is 113   all children complete without a winner is a failure surfaced. There is
114   no priority between errors and exceptions, and no guarantee about which 114   no priority between errors and exceptions, and no guarantee about which
115   child's failure is reported: the result either returns an error_code at 115   child's failure is reported: the result either returns an error_code at
116   variant index 0 or rethrows a child's exception. 116   variant index 0 or rethrows a child's exception.
117   */ 117   */
118   118  
119   namespace boost { 119   namespace boost {
120   namespace capy { 120   namespace capy {
121   121  
122   namespace detail { 122   namespace detail {
123   123  
124   /** Core shared state for when_any operations. 124   /** Core shared state for when_any operations.
125   125  
126   Contains all members and methods common to both heterogeneous (variadic) 126   Contains all members and methods common to both heterogeneous (variadic)
127   and homogeneous (range) when_any implementations. State classes embed 127   and homogeneous (range) when_any implementations. State classes embed
128   this via composition to avoid CRTP destructor ordering issues. 128   this via composition to avoid CRTP destructor ordering issues.
129   129  
130   @par Thread Safety 130   @par Thread Safety
131   Atomic operations protect winner selection and completion count. 131   Atomic operations protect winner selection and completion count.
132   */ 132   */
133   struct when_any_core 133   struct when_any_core
134   { 134   {
135   std::atomic<std::size_t> remaining_count_; 135   std::atomic<std::size_t> remaining_count_;
136   std::size_t winner_index_{0}; 136   std::size_t winner_index_{0};
137   std::exception_ptr winner_exception_; 137   std::exception_ptr winner_exception_;
138   std::stop_source stop_source_; 138   std::stop_source stop_source_;
139   139  
140   // Bridges parent's stop token to our stop_source 140   // Bridges parent's stop token to our stop_source
141   struct stop_callback_fn 141   struct stop_callback_fn
142   { 142   {
143   std::stop_source* source_; 143   std::stop_source* source_;
HITCBC 144   3 void operator()() const noexcept 144   3 void operator()() const noexcept
145   { 145   {
146   // Stopping can lose the last branch and destroy the join, 146   // Stopping can lose the last branch and destroy the join,
147   // with its source, before the request returns; the copy 147   // with its source, before the request returns; the copy
148   // keeps the stop state alive until then. 148   // keeps the stop state alive until then.
HITCBC 149   3 std::stop_source keep = *source_; 149   3 std::stop_source keep = *source_;
HITCBC 150   3 keep.request_stop(); 150   3 keep.request_stop();
HITCBC 151   3 } 151   3 }
152   }; 152   };
153   using stop_callback_t = std::stop_callback<stop_callback_fn>; 153   using stop_callback_t = std::stop_callback<stop_callback_fn>;
154   std::optional<stop_callback_t> parent_stop_callback_; 154   std::optional<stop_callback_t> parent_stop_callback_;
155   155  
156   continuation continuation_; 156   continuation continuation_;
157   await_context const* caller_env_ = nullptr; 157   await_context const* caller_env_ = nullptr;
158   158  
159   // Set when a branch is abandoned before finishing: the parent is 159   // Set when a branch is abandoned before finishing: the parent is
160   // then abandoned rather than resumed. 160   // then abandoned rather than resumed.
161   std::atomic<bool> lost_{false}; 161   std::atomic<bool> lost_{false};
162   162  
163   /// Drop a share held by a runner that never finished. 163   /// Drop a share held by a runner that never finished.
HITCBC 164   8 void lose_branch() noexcept 164   8 void lose_branch() noexcept
165   { 165   {
HITCBC 166   8 lost_.store(true, std::memory_order_relaxed); 166   8 lost_.store(true, std::memory_order_relaxed);
HITCBC 167   8 stop_source_.request_stop(); 167   8 stop_source_.request_stop();
HITCBC 168   16 if(remaining_count_.fetch_sub(1, std::memory_order_acq_rel) == 1) 168   16 if(remaining_count_.fetch_sub(1, std::memory_order_acq_rel) == 1)
169   { 169   {
HITCBC 170   4 auto parent = continuation_; 170   4 auto parent = continuation_;
HITCBC 171   4 capy::abandon(parent); 171   4 capy::abandon(parent);
172   } 172   }
HITCBC 173   8 } 173   8 }
174   174  
175   // Placed last to avoid padding (1-byte atomic followed by 8-byte aligned members) 175   // Placed last to avoid padding (1-byte atomic followed by 8-byte aligned members)
176   std::atomic<bool> has_winner_{false}; 176   std::atomic<bool> has_winner_{false};
177   177  
HITCBC 178   52 explicit when_any_core(std::size_t count) noexcept 178   52 explicit when_any_core(std::size_t count) noexcept
HITCBC 179   52 : remaining_count_(count) 179   52 : remaining_count_(count)
180   { 180   {
HITCBC 181   52 } 181   52 }
182   182  
183   /** Atomically claim winner status; exactly one task succeeds. */ 183   /** Atomically claim winner status; exactly one task succeeds. */
HITCBC 184   67 bool try_win(std::size_t index) noexcept 184   67 bool try_win(std::size_t index) noexcept
185   { 185   {
HITCBC 186   67 bool expected = false; 186   67 bool expected = false;
HITCBC 187   67 if(has_winner_.compare_exchange_strong( 187   67 if(has_winner_.compare_exchange_strong(
188   expected, true, std::memory_order_acq_rel)) 188   expected, true, std::memory_order_acq_rel))
189   { 189   {
HITCBC 190   31 winner_index_ = index; 190   31 winner_index_ = index;
HITCBC 191   31 stop_source_.request_stop(); 191   31 stop_source_.request_stop();
HITCBC 192   31 return true; 192   31 return true;
193   } 193   }
HITCBC 194   36 return false; 194   36 return false;
195   } 195   }
196   196  
197   /** @pre try_win() returned true. */ 197   /** @pre try_win() returned true. */
HITCBC 198   1 void set_winner_exception(std::exception_ptr ep) noexcept 198   1 void set_winner_exception(std::exception_ptr ep) noexcept
199   { 199   {
HITCBC 200   1 winner_exception_ = ep; 200   1 winner_exception_ = ep;
HITCBC 201   1 } 201   1 }
202   202  
203   // Runners signal completion directly via final_suspend; no member function needed. 203   // Runners signal completion directly via final_suspend; no member function needed.
204   }; 204   };
205   205  
206   } // namespace detail 206   } // namespace detail
207   207  
208   namespace detail { 208   namespace detail {
209   209  
210   // State for `results`-aware when_any: only !ec wins. 210   // State for `results`-aware when_any: only !ec wins.
211   template<typename... Ts> 211   template<typename... Ts>
212   struct when_any_results_state 212   struct when_any_results_state
213   { 213   {
214   static constexpr std::size_t task_count = sizeof...(Ts); 214   static constexpr std::size_t task_count = sizeof...(Ts);
215   using variant_type = std::variant<std::error_code, Ts...>; 215   using variant_type = std::variant<std::error_code, Ts...>;
216   216  
217   when_any_core core_; 217   when_any_core core_;
218   std::optional<variant_type> result_; 218   std::optional<variant_type> result_;
219   std::array<continuation, task_count> runner_handles_{}; 219   std::array<continuation, task_count> runner_handles_{};
220   220  
221   // A failure (error or exception) for the all-fail case. record_error 221   // A failure (error or exception) for the all-fail case. record_error
222   // and record_exception overwrite each other, so which one survives is 222   // and record_exception overwrite each other, so which one survives is
223   // unspecified (no priority between errors and exceptions). 223   // unspecified (no priority between errors and exceptions).
224   std::mutex failure_mu_; 224   std::mutex failure_mu_;
225   std::error_code last_error_; 225   std::error_code last_error_;
226   std::exception_ptr last_exception_; 226   std::exception_ptr last_exception_;
227   227  
HITCBC 228   32 when_any_results_state() 228   32 when_any_results_state()
HITCBC 229   32 : core_(task_count) 229   32 : core_(task_count)
230   { 230   {
HITCBC 231   32 } 231   32 }
232   232  
HITCBC 233   16 void record_error(std::error_code ec) 233   16 void record_error(std::error_code ec)
234   { 234   {
HITCBC 235   16 std::lock_guard lk(failure_mu_); 235   16 std::lock_guard lk(failure_mu_);
HITCBC 236   16 last_error_ = ec; 236   16 last_error_ = ec;
HITCBC 237   16 last_exception_ = nullptr; 237   16 last_exception_ = nullptr;
HITCBC 238   16 } 238   16 }
239   239  
HITCBC 240   6 void record_exception(std::exception_ptr ep) 240   6 void record_exception(std::exception_ptr ep)
241   { 241   {
HITCBC 242   6 std::lock_guard lk(failure_mu_); 242   6 std::lock_guard lk(failure_mu_);
HITCBC 243   6 last_exception_ = ep; 243   6 last_exception_ = ep;
HITCBC 244   6 last_error_ = {}; 244   6 last_error_ = {};
HITCBC 245   6 } 245   6 }
246   }; 246   };
247   247  
248   // Wrapper coroutine for `results`-aware when_any children. 248   // Wrapper coroutine for `results`-aware when_any children.
249   // unhandled_exception records the exception but does NOT claim winner status. 249   // unhandled_exception records the exception but does NOT claim winner status.
250   template<typename StateType> 250   template<typename StateType>
251   struct when_any_results_runner 251   struct when_any_results_runner
252   { 252   {
253   struct promise_type 253   struct promise_type
254   : detail::process_frame_mixin 254   : detail::process_frame_mixin
255   { 255   {
256   StateType* state_ = nullptr; 256   StateType* state_ = nullptr;
257   std::size_t index_ = 0; 257   std::size_t index_ = 0;
258   await_context env_; 258   await_context env_;
259   // Owns the branch's segment. 259   // Owns the branch's segment.
260   chain_owner segment_; 260   chain_owner segment_;
261   bool done_ = false; 261   bool done_ = false;
262   262  
HITCBC 263   124 ~promise_type() 263   124 ~promise_type()
264   { 264   {
HITCBC 265   124 if(!done_ && state_) 265   124 if(!done_ && state_)
HITCBC 266   8 state_->core_.lose_branch(); 266   8 state_->core_.lose_branch();
HITCBC 267   124 } 267   124 }
268   268  
HITCBC 269   124 when_any_results_runner get_return_object() noexcept 269   124 when_any_results_runner get_return_object() noexcept
270   { 270   {
271   return when_any_results_runner( 271   return when_any_results_runner(
HITCBC 272   124 std::coroutine_handle<promise_type>::from_promise(*this)); 272   124 std::coroutine_handle<promise_type>::from_promise(*this));
273   } 273   }
274   274  
HITCBC 275   124 std::suspend_always initial_suspend() noexcept { return {}; } 275   124 std::suspend_always initial_suspend() noexcept { return {}; }
276   276  
HITCBC 277   116 auto final_suspend() noexcept 277   116 auto final_suspend() noexcept
278   { 278   {
279   struct awaiter 279   struct awaiter
280   { 280   {
281   promise_type* p_; 281   promise_type* p_;
HITCBC 282   116 bool await_ready() const noexcept { return false; } 282   116 bool await_ready() const noexcept { return false; }
HITCBC 283   116 auto await_suspend(std::coroutine_handle<> h) noexcept 283   116 auto await_suspend(std::coroutine_handle<> h) noexcept
284   { 284   {
HITCBC 285   116 auto& core = p_->state_->core_; 285   116 auto& core = p_->state_->core_;
HITCBC 286   116 auto* counter = &core.remaining_count_; 286   116 auto* counter = &core.remaining_count_;
HITCBC 287   116 auto* lost = &core.lost_; 287   116 auto* lost = &core.lost_;
HITCBC 288   116 auto* caller_env = core.caller_env_; 288   116 auto* caller_env = core.caller_env_;
HITCBC 289   116 auto& cont = core.continuation_; 289   116 auto& cont = core.continuation_;
290   290  
HITCBC 291   116 p_->done_ = true; 291   116 p_->done_ = true;
292   // Resumed to unwind its abandoned branch: lost, not 292   // Resumed to unwind its abandoned branch: lost, not
293   // finished. Stop is requested while this branch 293   // finished. Stop is requested while this branch
294   // still holds its share. 294   // still holds its share.
HITCBC 295   116 if(p_->segment_.abandoned()) 295   116 if(p_->segment_.abandoned())
296   { 296   {
HITCBC 297   14 lost->store(true, std::memory_order_relaxed); 297   14 lost->store(true, std::memory_order_relaxed);
HITCBC 298   14 core.stop_source_.request_stop(); 298   14 core.stop_source_.request_stop();
299   } 299   }
HITCBC 300   116 h.destroy(); 300   116 h.destroy();
301   301  
HITCBC 302   116 auto remaining = counter->fetch_sub(1, std::memory_order_acq_rel); 302   116 auto remaining = counter->fetch_sub(1, std::memory_order_acq_rel);
HITCBC 303   116 if(remaining != 1) 303   116 if(remaining != 1)
HITCBC 304   68 return detail::symmetric_transfer(std::noop_coroutine()); 304   68 return detail::symmetric_transfer(std::noop_coroutine());
HITCBC 305   48 if(lost->load(std::memory_order_relaxed)) 305   48 if(lost->load(std::memory_order_relaxed))
306   { 306   {
HITCBC 307   8 auto parent = cont; 307   8 auto parent = cont;
HITCBC 308   8 capy::abandon(parent); 308   8 capy::abandon(parent);
HITCBC 309   8 return detail::symmetric_transfer(std::noop_coroutine()); 309   8 return detail::symmetric_transfer(std::noop_coroutine());
310   } 310   }
HITCBC 311   40 return detail::symmetric_transfer(caller_env->executor.dispatch(cont)); 311   40 return detail::symmetric_transfer(caller_env->executor.dispatch(cont));
312   } 312   }
313   void await_resume() const noexcept {} // LCOV_EXCL_LINE final_suspend awaiter, never resumed 313   void await_resume() const noexcept {} // LCOV_EXCL_LINE final_suspend awaiter, never resumed
314   }; 314   };
HITCBC 315   116 return awaiter{this}; 315   116 return awaiter{this};
316   } 316   }
317   317  
HITCBC 318   104 void return_void() noexcept {} 318   104 void return_void() noexcept {}
319   319  
320   // Exceptions do NOT win in `results` when_any 320   // Exceptions do NOT win in `results` when_any
HITCBC 321   12 void unhandled_exception() noexcept 321   12 void unhandled_exception() noexcept
322   { 322   {
HITCBC 323   12 state_->record_exception(std::current_exception()); 323   12 state_->record_exception(std::current_exception());
HITCBC 324   12 } 324   12 }
325   325  
326   // Not context_awaiter: a child whose await_suspend throws has 326   // Not context_awaiter: a child whose await_suspend throws has
327   // failed, and must reach unhandled_exception rather than terminate. 327   // failed, and must reach unhandled_exception rather than terminate.
328   template<class Awaitable> 328   template<class Awaitable>
329   struct transform_awaiter 329   struct transform_awaiter
330   { 330   {
331   std::decay_t<Awaitable> a_; 331   std::decay_t<Awaitable> a_;
332   promise_type* p_; 332   promise_type* p_;
333   333  
HITCBC 334   118 bool await_ready() { return a_.await_ready(); } 334   118 bool await_ready() { return a_.await_ready(); }
HITCBC 335   115 decltype(auto) await_resume() { return a_.await_resume(); } 335   115 decltype(auto) await_resume() { return a_.await_resume(); }
336   336  
337   template<class Promise> 337   template<class Promise>
HITCBC 338   117 auto await_suspend(std::coroutine_handle<Promise> h) 338   117 auto await_suspend(std::coroutine_handle<Promise> h)
339   { 339   {
340   using R = decltype(a_.await_suspend(h, &p_->env_)); 340   using R = decltype(a_.await_suspend(h, &p_->env_));
341   if constexpr (std::is_same_v<R, std::coroutine_handle<>>) 341   if constexpr (std::is_same_v<R, std::coroutine_handle<>>)
HITCBC 342   116 return detail::symmetric_transfer(a_.await_suspend(h, &p_->env_)); 342   116 return detail::symmetric_transfer(a_.await_suspend(h, &p_->env_));
343   else 343   else
HITCBC 344   1 return a_.await_suspend(h, &p_->env_); 344   1 return a_.await_suspend(h, &p_->env_);
345   } 345   }
346   }; 346   };
347   347  
348   template<class Awaitable> 348   template<class Awaitable>
HITCBC 349   118 auto await_transform(Awaitable&& a) 349   118 auto await_transform(Awaitable&& a)
350   { 350   {
351   using A = std::decay_t<Awaitable>; 351   using A = std::decay_t<Awaitable>;
352   if constexpr (ContextAwaitable<A>) 352   if constexpr (ContextAwaitable<A>)
353   { 353   {
354   return transform_awaiter<Awaitable>{ 354   return transform_awaiter<Awaitable>{
HITCBC 355   118 std::forward<Awaitable>(a), this}; 355   118 std::forward<Awaitable>(a), this};
356   } 356   }
357   else 357   else
358   { 358   {
359   static_assert(sizeof(A) == 0, "requires ContextAwaitable"); 359   static_assert(sizeof(A) == 0, "requires ContextAwaitable");
360   } 360   }
361   } 361   }
362   }; 362   };
363   363  
364   std::coroutine_handle<promise_type> h_; 364   std::coroutine_handle<promise_type> h_;
365   365  
HITCBC 366   124 explicit when_any_results_runner(std::coroutine_handle<promise_type> h) noexcept 366   124 explicit when_any_results_runner(std::coroutine_handle<promise_type> h) noexcept
HITCBC 367   124 : h_(h) 367   124 : h_(h)
368   { 368   {
HITCBC 369   124 } 369   124 }
370   370  
371   when_any_results_runner(when_any_results_runner&& other) noexcept 371   when_any_results_runner(when_any_results_runner&& other) noexcept
372   : h_(std::exchange(other.h_, nullptr)) 372   : h_(std::exchange(other.h_, nullptr))
373   { 373   {
374   } 374   }
375   375  
376   when_any_results_runner(when_any_results_runner const&) = delete; 376   when_any_results_runner(when_any_results_runner const&) = delete;
377   when_any_results_runner& operator=(when_any_results_runner const&) = delete; 377   when_any_results_runner& operator=(when_any_results_runner const&) = delete;
378   when_any_results_runner& operator=(when_any_results_runner&&) = delete; 378   when_any_results_runner& operator=(when_any_results_runner&&) = delete;
379   379  
HITCBC 380   124 auto release() noexcept 380   124 auto release() noexcept
381   { 381   {
HITCBC 382   124 return std::exchange(h_, nullptr); 382   124 return std::exchange(h_, nullptr);
383   } 383   }
384   }; 384   };
385   385  
386   // Runner coroutine: only tries to win when the child returns !ec. 386   // Runner coroutine: only tries to win when the child returns !ec.
387   template<std::size_t I, ContextAwaitable Awaitable, typename StateType> 387   template<std::size_t I, ContextAwaitable Awaitable, typename StateType>
388   when_any_results_runner<StateType> 388   when_any_results_runner<StateType>
HITCBC 389   59 make_when_any_results_runner(Awaitable* inner, StateType* state) 389   59 make_when_any_results_runner(Awaitable* inner, StateType* state)
390   { 390   {
391   // Taken from the join's storage only once running, into a local: 391   // Taken from the join's storage only once running, into a local:
392   // a runner destroyed unstarted owns no branch, and one destroyed 392   // a runner destroyed unstarted owns no branch, and one destroyed
393   // unfinished destroys it before its promise reports the loss. 393   // unfinished destroys it before its promise reports the loss.
394   Awaitable a(std::move(*inner)); 394   Awaitable a(std::move(*inner));
395   auto r = co_await abandonable<Awaitable>{a}; 395   auto r = co_await abandonable<Awaitable>{a};
396   if(!r) 396   if(!r)
397   co_return; 397   co_return;
398   auto& result = *r; 398   auto& result = *r;
399   399  
400   if(!std::get<0>(result)) 400   if(!std::get<0>(result))
401   { 401   {
402   // Success: try to claim winner 402   // Success: try to claim winner
403   if(state->core_.try_win(I)) 403   if(state->core_.try_win(I))
404   { 404   {
405   try 405   try
406   { 406   {
407   state->result_.emplace( 407   state->result_.emplace(
408   std::in_place_index<I + 1>, 408   std::in_place_index<I + 1>,
409   detail::extract_results_payload(std::move(result))); 409   detail::extract_results_payload(std::move(result)));
410   } 410   }
411   catch(...) 411   catch(...)
412   { 412   {
413   state->core_.set_winner_exception(std::current_exception()); 413   state->core_.set_winner_exception(std::current_exception());
414   } 414   }
415   } 415   }
416   } 416   }
417   else 417   else
418   { 418   {
419   // Error: record but don't win 419   // Error: record but don't win
420   state->record_error(std::get<0>(result)); 420   state->record_error(std::get<0>(result));
421   } 421   }
HITCBC 422   118 } 422   118 }
423   423  
424   // Launcher for `results`-aware when_any. 424   // Launcher for `results`-aware when_any.
425   template<ContextAwaitable... Awaitables> 425   template<ContextAwaitable... Awaitables>
426   class when_any_results_launcher 426   class when_any_results_launcher
427   { 427   {
428   using state_type = when_any_results_state< 428   using state_type = when_any_results_state<
429   results_payload_t<awaitable_result_t<Awaitables>>...>; 429   results_payload_t<awaitable_result_t<Awaitables>>...>;
430   430  
431   std::tuple<Awaitables...>* tasks_; 431   std::tuple<Awaitables...>* tasks_;
432   state_type* state_; 432   state_type* state_;
433   433  
434   public: 434   public:
HITCBC 435   32 when_any_results_launcher( 435   32 when_any_results_launcher(
436   std::tuple<Awaitables...>* tasks, 436   std::tuple<Awaitables...>* tasks,
437   state_type* state) 437   state_type* state)
HITCBC 438   32 : tasks_(tasks) 438   32 : tasks_(tasks)
HITCBC 439   32 , state_(state) 439   32 , state_(state)
440   { 440   {
HITCBC 441   32 } 441   32 }
442   442  
HITCBC 443   32 bool await_ready() const noexcept 443   32 bool await_ready() const noexcept
444   { 444   {
HITCBC 445   32 return sizeof...(Awaitables) == 0; 445   32 return sizeof...(Awaitables) == 0;
446   } 446   }
447   447  
HITCBC 448   32 std::coroutine_handle<> await_suspend( 448   32 std::coroutine_handle<> await_suspend(
449   std::coroutine_handle<> continuation, await_context const* caller_env) 449   std::coroutine_handle<> continuation, await_context const* caller_env)
450   { 450   {
HITCBC 451   32 state_->core_.continuation_.h = continuation; 451   32 state_->core_.continuation_.h = continuation;
HITCBC 452   32 state_->core_.continuation_.owner = caller_env->owner; 452   32 state_->core_.continuation_.owner = caller_env->owner;
HITCBC 453   32 state_->core_.caller_env_ = caller_env; 453   32 state_->core_.caller_env_ = caller_env;
454   454  
HITCBC 455   32 if(caller_env->stop_token.stop_possible()) 455   32 if(caller_env->stop_token.stop_possible())
456   { 456   {
HITCBC 457   4 state_->core_.parent_stop_callback_.emplace( 457   4 state_->core_.parent_stop_callback_.emplace(
HITCBC 458   2 caller_env->stop_token, 458   2 caller_env->stop_token,
HITCBC 459   2 when_any_core::stop_callback_fn{&state_->core_.stop_source_}); 459   2 when_any_core::stop_callback_fn{&state_->core_.stop_source_});
460   460  
HITCBC 461   2 if(caller_env->stop_token.stop_requested()) 461   2 if(caller_env->stop_token.stop_requested())
HITCBC 462   1 state_->core_.stop_source_.request_stop(); 462   1 state_->core_.stop_source_.request_stop();
463   } 463   }
464   464  
HITCBC 465   32 auto token = state_->core_.stop_source_.get_token(); 465   32 auto token = state_->core_.stop_source_.get_token();
HITCBC 466   32 launch_all(std::index_sequence_for<Awaitables...>{}, 466   32 launch_all(std::index_sequence_for<Awaitables...>{},
467   caller_env->executor, token); 467   caller_env->executor, token);
468   468  
HITCBC 469   64 return std::noop_coroutine(); 469   64 return std::noop_coroutine();
HITCBC 470   32 } 470   32 }
471   471  
HITCBC 472   22 void await_resume() const noexcept {} 472   22 void await_resume() const noexcept {}
473   473  
474   private: 474   private:
475   template<std::size_t... Is> 475   template<std::size_t... Is>
HITCBC 476   32 void launch_all(std::index_sequence<Is...>, 476   32 void launch_all(std::index_sequence<Is...>,
477   executor_ref ex, std::stop_token token) 477   executor_ref ex, std::stop_token token)
478   { 478   {
HITCBC 479   32 (..., launch_one<Is>(ex, token)); 479   32 (..., launch_one<Is>(ex, token));
HITCBC 480   32 } 480   32 }
481   481  
482   template<std::size_t I> 482   template<std::size_t I>
HITCBC 483   59 void launch_one(executor_ref caller_ex, std::stop_token token) 483   59 void launch_one(executor_ref caller_ex, std::stop_token token)
484   { 484   {
HITCBC 485   59 auto runner = make_when_any_results_runner<I>( 485   59 auto runner = make_when_any_results_runner<I>(
HITCBC 486   59 &std::get<I>(*tasks_), state_); 486   59 &std::get<I>(*tasks_), state_);
487   487  
HITCBC 488   59 auto h = runner.release(); 488   59 auto h = runner.release();
HITCBC 489   59 h.promise().state_ = state_; 489   59 h.promise().state_ = state_;
HITCBC 490   59 h.promise().index_ = I; 490   59 h.promise().index_ = I;
HITCBC 491   59 h.promise().segment_.bind(h, caller_ex); 491   59 h.promise().segment_.bind(h, caller_ex);
HITCBC 492   59 h.promise().env_ = await_context{caller_ex, token, 492   59 h.promise().env_ = await_context{caller_ex, token,
HITCBC 493   59 state_->core_.caller_env_->frame_allocator, 493   59 state_->core_.caller_env_->frame_allocator,
HITCBC 494   118 &h.promise().segment_}; 494   118 &h.promise().segment_};
495   495  
HITCBC 496   59 state_->runner_handles_[I].h = std::coroutine_handle<>{h}; 496   59 state_->runner_handles_[I].h = std::coroutine_handle<>{h};
HITCBC 497   59 caller_ex.post(state_->runner_handles_[I]); 497   59 caller_ex.post(state_->runner_handles_[I]);
HITCBC 498   118 } 498   118 }
499   }; 499   };
500   500  
501   /** Shared state for homogeneous `results`-aware when_any (range overload). 501   /** Shared state for homogeneous `results`-aware when_any (range overload).
502   502  
503   @tparam T The payload type extracted from `results`. 503   @tparam T The payload type extracted from `results`.
504   */ 504   */
505   template<typename T> 505   template<typename T>
506   struct when_any_results_homogeneous_state 506   struct when_any_results_homogeneous_state
507   { 507   {
508   when_any_core core_; 508   when_any_core core_;
509   std::optional<T> result_; 509   std::optional<T> result_;
510   std::unique_ptr<continuation[]> runner_handles_; 510   std::unique_ptr<continuation[]> runner_handles_;
511   511  
512   std::mutex failure_mu_; 512   std::mutex failure_mu_;
513   std::error_code last_error_; 513   std::error_code last_error_;
514   std::exception_ptr last_exception_; 514   std::exception_ptr last_exception_;
515   515  
HITCBC 516   15 explicit when_any_results_homogeneous_state(std::size_t count) 516   15 explicit when_any_results_homogeneous_state(std::size_t count)
HITCBC 517   15 : core_(count) 517   15 : core_(count)
HITCBC 518   15 , runner_handles_(std::make_unique<continuation[]>(count)) 518   15 , runner_handles_(std::make_unique<continuation[]>(count))
519   { 519   {
HITCBC 520   15 } 520   15 }
521   521  
HITCBC 522   6 void record_error(std::error_code ec) 522   6 void record_error(std::error_code ec)
523   { 523   {
HITCBC 524   6 std::lock_guard lk(failure_mu_); 524   6 std::lock_guard lk(failure_mu_);
HITCBC 525   6 last_error_ = ec; 525   6 last_error_ = ec;
HITCBC 526   6 last_exception_ = nullptr; 526   6 last_exception_ = nullptr;
HITCBC 527   6 } 527   6 }
528   528  
HITCBC 529   4 void record_exception(std::exception_ptr ep) 529   4 void record_exception(std::exception_ptr ep)
530   { 530   {
HITCBC 531   4 std::lock_guard lk(failure_mu_); 531   4 std::lock_guard lk(failure_mu_);
HITCBC 532   4 last_exception_ = ep; 532   4 last_exception_ = ep;
HITCBC 533   4 last_error_ = {}; 533   4 last_error_ = {};
HITCBC 534   4 } 534   4 }
535   }; 535   };
536   536  
537   /** Specialization for void `results` children (no payload storage). */ 537   /** Specialization for void `results` children (no payload storage). */
538   template<> 538   template<>
539   struct when_any_results_homogeneous_state<std::tuple<>> 539   struct when_any_results_homogeneous_state<std::tuple<>>
540   { 540   {
541   when_any_core core_; 541   when_any_core core_;
542   std::unique_ptr<continuation[]> runner_handles_; 542   std::unique_ptr<continuation[]> runner_handles_;
543   543  
544   std::mutex failure_mu_; 544   std::mutex failure_mu_;
545   std::error_code last_error_; 545   std::error_code last_error_;
546   std::exception_ptr last_exception_; 546   std::exception_ptr last_exception_;
547   547  
HITCBC 548   5 explicit when_any_results_homogeneous_state(std::size_t count) 548   5 explicit when_any_results_homogeneous_state(std::size_t count)
HITCBC 549   5 : core_(count) 549   5 : core_(count)
HITCBC 550   5 , runner_handles_(std::make_unique<continuation[]>(count)) 550   5 , runner_handles_(std::make_unique<continuation[]>(count))
551   { 551   {
HITCBC 552   5 } 552   5 }
553   553  
HITCBC 554   1 void record_error(std::error_code ec) 554   1 void record_error(std::error_code ec)
555   { 555   {
HITCBC 556   1 std::lock_guard lk(failure_mu_); 556   1 std::lock_guard lk(failure_mu_);
HITCBC 557   1 last_error_ = ec; 557   1 last_error_ = ec;
HITCBC 558   1 last_exception_ = nullptr; 558   1 last_exception_ = nullptr;
HITCBC 559   1 } 559   1 }
560   560  
HITCBC 561   2 void record_exception(std::exception_ptr ep) 561   2 void record_exception(std::exception_ptr ep)
562   { 562   {
HITCBC 563   2 std::lock_guard lk(failure_mu_); 563   2 std::lock_guard lk(failure_mu_);
HITCBC 564   2 last_exception_ = ep; 564   2 last_exception_ = ep;
HITCBC 565   2 last_error_ = {}; 565   2 last_error_ = {};
HITCBC 566   2 } 566   2 }
567   }; 567   };
568   568  
569   /** Create a `results`-aware runner for homogeneous when_any (range path). 569   /** Create a `results`-aware runner for homogeneous when_any (range path).
570   570  
571   Only tries to win when the child returns !ec. 571   Only tries to win when the child returns !ec.
572   */ 572   */
573   template<ContextAwaitable Awaitable, typename StateType> 573   template<ContextAwaitable Awaitable, typename StateType>
574   when_any_results_runner<StateType> 574   when_any_results_runner<StateType>
HITCBC 575   65 make_when_any_results_homogeneous_runner( 575   65 make_when_any_results_homogeneous_runner(
576   Awaitable* inner, StateType* state, std::size_t index) 576   Awaitable* inner, StateType* state, std::size_t index)
577   { 577   {
578   // Taken from the join's storage only once running, into a local: 578   // Taken from the join's storage only once running, into a local:
579   // a runner destroyed unstarted owns no branch, and one destroyed 579   // a runner destroyed unstarted owns no branch, and one destroyed
580   // unfinished destroys it before its promise reports the loss. 580   // unfinished destroys it before its promise reports the loss.
581   Awaitable a(std::move(*inner)); 581   Awaitable a(std::move(*inner));
582   auto r = co_await abandonable<Awaitable>{a}; 582   auto r = co_await abandonable<Awaitable>{a};
583   if(!r) 583   if(!r)
584   co_return; 584   co_return;
585   auto& result = *r; 585   auto& result = *r;
586   586  
587   if(!std::get<0>(result)) 587   if(!std::get<0>(result))
588   { 588   {
589   if(state->core_.try_win(index)) 589   if(state->core_.try_win(index))
590   { 590   {
591   using PayloadT = results_payload_t< 591   using PayloadT = results_payload_t<
592   awaitable_result_t<Awaitable>>; 592   awaitable_result_t<Awaitable>>;
593   if constexpr (!std::is_same_v<PayloadT, std::tuple<>>) 593   if constexpr (!std::is_same_v<PayloadT, std::tuple<>>)
594   { 594   {
595   try 595   try
596   { 596   {
597   state->result_.emplace( 597   state->result_.emplace(
598   extract_results_payload(std::move(result))); 598   extract_results_payload(std::move(result)));
599   } 599   }
600   catch(...) 600   catch(...)
601   { 601   {
602   state->core_.set_winner_exception( 602   state->core_.set_winner_exception(
603   std::current_exception()); 603   std::current_exception());
604   } 604   }
605   } 605   }
606   } 606   }
607   } 607   }
608   else 608   else
609   { 609   {
610   state->record_error(std::get<0>(result)); 610   state->record_error(std::get<0>(result));
611   } 611   }
HITCBC 612   130 } 612   130 }
613   613  
614   /** Starts all `results`-aware homogeneous runners concurrently. */ 614   /** Starts all `results`-aware homogeneous runners concurrently. */
615   template<ContextAwaitableRange Range> 615   template<ContextAwaitableRange Range>
616   class when_any_results_homogeneous_launcher 616   class when_any_results_homogeneous_launcher
617   { 617   {
618   using Awaitable = std::ranges::range_value_t<Range>; 618   using Awaitable = std::ranges::range_value_t<Range>;
619   using PayloadT = results_payload_t<awaitable_result_t<Awaitable>>; 619   using PayloadT = results_payload_t<awaitable_result_t<Awaitable>>;
620   620  
621   Range* range_; 621   Range* range_;
622   when_any_results_homogeneous_state<PayloadT>* state_; 622   when_any_results_homogeneous_state<PayloadT>* state_;
623   623  
624   public: 624   public:
HITCBC 625   20 when_any_results_homogeneous_launcher( 625   20 when_any_results_homogeneous_launcher(
626   Range* range, 626   Range* range,
627   when_any_results_homogeneous_state<PayloadT>* state) 627   when_any_results_homogeneous_state<PayloadT>* state)
HITCBC 628   20 : range_(range) 628   20 : range_(range)
HITCBC 629   20 , state_(state) 629   20 , state_(state)
630   { 630   {
HITCBC 631   20 } 631   20 }
632   632  
HITCBC 633   20 bool await_ready() const noexcept 633   20 bool await_ready() const noexcept
634   { 634   {
HITCBC 635   20 return std::ranges::empty(*range_); 635   20 return std::ranges::empty(*range_);
636   } 636   }
637   637  
HITCBC 638   20 std::coroutine_handle<> await_suspend( 638   20 std::coroutine_handle<> await_suspend(
639   std::coroutine_handle<> continuation, await_context const* caller_env) 639   std::coroutine_handle<> continuation, await_context const* caller_env)
640   { 640   {
HITCBC 641   20 state_->core_.continuation_.h = continuation; 641   20 state_->core_.continuation_.h = continuation;
HITCBC 642   20 state_->core_.continuation_.owner = caller_env->owner; 642   20 state_->core_.continuation_.owner = caller_env->owner;
HITCBC 643   20 state_->core_.caller_env_ = caller_env; 643   20 state_->core_.caller_env_ = caller_env;
644   644  
HITCBC 645   20 if(caller_env->stop_token.stop_possible()) 645   20 if(caller_env->stop_token.stop_possible())
646   { 646   {
HITCBC 647   4 state_->core_.parent_stop_callback_.emplace( 647   4 state_->core_.parent_stop_callback_.emplace(
HITCBC 648   2 caller_env->stop_token, 648   2 caller_env->stop_token,
HITCBC 649   2 when_any_core::stop_callback_fn{&state_->core_.stop_source_}); 649   2 when_any_core::stop_callback_fn{&state_->core_.stop_source_});
650   650  
HITCBC 651   2 if(caller_env->stop_token.stop_requested()) 651   2 if(caller_env->stop_token.stop_requested())
HITCBC 652   1 state_->core_.stop_source_.request_stop(); 652   1 state_->core_.stop_source_.request_stop();
653   } 653   }
654   654  
HITCBC 655   20 auto token = state_->core_.stop_source_.get_token(); 655   20 auto token = state_->core_.stop_source_.get_token();
656   656  
657   // Phase 1: Create all runners without dispatching. 657   // Phase 1: Create all runners without dispatching.
HITCBC 658   20 std::size_t index = 0; 658   20 std::size_t index = 0;
HITCBC 659   85 for(auto&& a : *range_) 659   85 for(auto&& a : *range_)
660   { 660   {
HITCBC 661   65 auto runner = make_when_any_results_homogeneous_runner( 661   65 auto runner = make_when_any_results_homogeneous_runner(
662   &a, state_, index); 662   &a, state_, index);
663   663  
HITCBC 664   65 auto h = runner.release(); 664   65 auto h = runner.release();
HITCBC 665   65 h.promise().state_ = state_; 665   65 h.promise().state_ = state_;
HITCBC 666   65 h.promise().index_ = index; 666   65 h.promise().index_ = index;
HITCBC 667   65 h.promise().segment_.bind(h, caller_env->executor); 667   65 h.promise().segment_.bind(h, caller_env->executor);
HITCBC 668   65 h.promise().env_ = await_context{caller_env->executor, token, 668   65 h.promise().env_ = await_context{caller_env->executor, token,
HITCBC 669   130 caller_env->frame_allocator, &h.promise().segment_}; 669   130 caller_env->frame_allocator, &h.promise().segment_};
670   670  
HITCBC 671   65 state_->runner_handles_[index].h = std::coroutine_handle<>{h}; 671   65 state_->runner_handles_[index].h = std::coroutine_handle<>{h};
HITCBC 672   65 ++index; 672   65 ++index;
673   } 673   }
674   674  
675   // Phase 2: Post all runners. Any may complete synchronously. 675   // Phase 2: Post all runners. Any may complete synchronously.
HITCBC 676   20 auto* handles = state_->runner_handles_.get(); 676   20 auto* handles = state_->runner_handles_.get();
HITCBC 677   20 std::size_t count = state_->core_.remaining_count_.load(std::memory_order_relaxed); 677   20 std::size_t count = state_->core_.remaining_count_.load(std::memory_order_relaxed);
HITCBC 678   85 for(std::size_t i = 0; i < count; ++i) 678   85 for(std::size_t i = 0; i < count; ++i)
HITCBC 679   65 caller_env->executor.post(handles[i]); 679   65 caller_env->executor.post(handles[i]);
680   680  
HITCBC 681   40 return std::noop_coroutine(); 681   40 return std::noop_coroutine();
HITCBC 682   85 } 682   85 }
683   683  
HITCBC 684   18 void await_resume() const noexcept {} 684   18 void await_resume() const noexcept {}
685   }; 685   };
686   686  
687   } // namespace detail 687   } // namespace detail
688   688  
689   /** Race a range of `results`-returning awaitables (non-void payloads). 689   /** Race a range of `results`-returning awaitables (non-void payloads).
690   690  
691   Only a child returning !ec can win. Errors and exceptions do not 691   Only a child returning !ec can win. Errors and exceptions do not
692   claim winner status. If all children fail, an unspecified one of 692   claim winner status. If all children fail, an unspecified one of
693   the failures is reported — either an error_code at variant index 0, 693   the failures is reported — either an error_code at variant index 0,
694   or a child's exception rethrown. 694   or a child's exception rethrown.
695   695  
696   @par Await-effects 696   @par Await-effects
697   697  
698   Takes ownership of the range, creates one wrapper coroutine per 698   Takes ownership of the range, creates one wrapper coroutine per
699   element, then posts every wrapper to the caller's executor. All 699   element, then posts every wrapper to the caller's executor. All
700   children therefore run concurrently, each awaited with the caller's 700   children therefore run concurrently, each awaited with the caller's
701   executor and frame allocator and with a stop token owned by this 701   executor and frame allocator and with a stop token owned by this
702   operation. 702   operation.
703   703  
704   Awaiting an empty range throws `std::invalid_argument` before any 704   Awaiting an empty range throws `std::invalid_argument` before any
705   child is started. 705   child is started.
706   706  
707   The first child to await-return a zero `ec` claims the win. Claiming 707   The first child to await-return a zero `ec` claims the win. Claiming
708   the win requests stop on the operation's own stop token, which every 708   the win requests stop on the operation's own stop token, which every
709   sibling observes through the stop token it was awaited with. A child 709   sibling observes through the stop token it was awaited with. A child
710   that await-returns a non-zero `ec`, or that exits via an exception, 710   that await-returns a non-zero `ec`, or that exits via an exception,
711   does not claim the win and does not request stop. The operation keeps 711   does not claim the win and does not request stop. The operation keeps
712   waiting for a success. A stop request on the caller's stop token is 712   waiting for a success. A stop request on the caller's stop token is
713   also forwarded to every child. 713   also forwarded to every child.
714   714  
715   The await completes only after every child has finished, regardless of 715   The await completes only after every child has finished, regardless of
716   whether a win was claimed. 716   whether a win was claimed.
717   717  
718   @par Await-returns 718   @par Await-returns
719   An object of type 719   An object of type
720   `std::variant<std::error_code, std::pair<std::size_t, PayloadT>>`, 720   `std::variant<std::error_code, std::pair<std::size_t, PayloadT>>`,
721   where `PayloadT` is the payload of one child's `results`. 721   where `PayloadT` is the payload of one child's `results`.
722   722  
723   @li Index 1 holds the winner's position in the input range paired 723   @li Index 1 holds the winner's position in the input range paired
724   with its payload. 724   with its payload.
725   @li Index 0 holds a non-zero `error_code` when no child won, that is, 725   @li Index 0 holds a non-zero `error_code` when no child won, that is,
726   when every child failed. It is the `ec` of one of the failed 726   when every child failed. It is the `ec` of one of the failed
727   children; which one is unspecified. 727   children; which one is unspecified.
728   728  
729   A child that succeeds after the win has already been claimed 729   A child that succeeds after the win has already been claimed
730   contributes nothing: its payload is discarded. 730   contributes nothing: its payload is discarded.
731   731  
732   If no child won and the failure selected for reporting is an 732   If no child won and the failure selected for reporting is an
733   exception rather than an `ec`, that exception is rethrown instead of 733   exception rather than an `ec`, that exception is rethrown instead of
734   await-returning. The choice of child is unspecified. 734   await-returning. The choice of child is unspecified.
735   735  
736   @par Await-postcondition 736   @par Await-postcondition
737   Every child has finished. If at least one child await-returned a zero 737   Every child has finished. If at least one child await-returned a zero
738   `ec`, the result holds index 1. If producing the winner's payload 738   `ec`, the result holds index 1. If producing the winner's payload
739   threw, that exception is rethrown. Otherwise the result holds index 0, 739   threw, that exception is rethrown. Otherwise the result holds index 0,
740   or a failed child's exception is rethrown. 740   or a failed child's exception is rethrown.
741   741  
742   @par Remarks 742   @par Remarks
743   Supports _ContextAwaitable cancellation_. A canceled child await-returns a 743   Supports _ContextAwaitable cancellation_. A canceled child await-returns a
744   non-zero `ec` and so cannot win; if no child has already succeeded, 744   non-zero `ec` and so cannot win; if no child has already succeeded,
745   the result settles at index 0. 745   the result settles at index 0.
746   746  
747   @par Thread Safety 747   @par Thread Safety
748   The returned task must be awaited from a single execution context. 748   The returned task must be awaited from a single execution context.
749   Child awaitables execute concurrently but complete through the caller's 749   Child awaitables execute concurrently but complete through the caller's
750   executor. 750   executor.
751   751  
752   @param awaitables Range of `results`-returning awaitables (must 752   @param awaitables Range of `results`-returning awaitables (must
753   not be empty). 753   not be empty).
754   754  
755   @return A task yielding variant<error_code, pair<size_t, PayloadT>> 755   @return A task yielding variant<error_code, pair<size_t, PayloadT>>
756   where index 0 is failure and index 1 carries the winner's 756   where index 0 is failure and index 1 carries the winner's
757   index and payload. 757   index and payload.
758   758  
759   @throws std::invalid_argument if range is empty. 759   @throws std::invalid_argument if range is empty.
760   760  
761   @par Exception Safety 761   @par Exception Safety
762   The winner's exception is rethrown if extracting or 762   The winner's exception is rethrown if extracting or
763   move-constructing the winning payload throws. In that case a winner 763   move-constructing the winning payload throws. In that case a winner
764   was found, but its result could not be produced. If all children 764   was found, but its result could not be produced. If all children
765   fail and the reported failure is an exception, that child's 765   fail and the reported failure is an exception, that child's
766   exception is rethrown (which child is unspecified). 766   exception is rethrown (which child is unspecified).
767   767  
768   @note If a branch's coroutine is abandoned before it finishes, for 768   @note If a branch's coroutine is abandoned before it finishes, for
769   example by teardown of its execution context, `when_any` 769   example by teardown of its execution context, `when_any`
770   requests stop on the remaining branches, and the awaiting 770   requests stop on the remaining branches, and the awaiting
771   parent is abandoned rather than resumed once the last branch 771   parent is abandoned rather than resumed once the last branch
772   has finished or been abandoned. 772   has finished or been abandoned.
773   773  
774   @par Example 774   @par Example
775   @par !example example_1 775   @par !example example_1
776   776  
777   777  
778   @see @ref ContextAwaitableRange, @ref when_any 778   @see @ref ContextAwaitableRange, @ref when_any
779   */ 779   */
780   template<ContextAwaitableRange R> 780   template<ContextAwaitableRange R>
781   requires detail::is_results_v< 781   requires detail::is_results_v<
782   awaitable_result_t<std::ranges::range_value_t<R>>> 782   awaitable_result_t<std::ranges::range_value_t<R>>>
783   && (!std::is_same_v< 783   && (!std::is_same_v<
784   detail::results_payload_t< 784   detail::results_payload_t<
785   awaitable_result_t<std::ranges::range_value_t<R>>>, 785   awaitable_result_t<std::ranges::range_value_t<R>>>,
786   std::tuple<>>) 786   std::tuple<>>)
HITCBC 787   16 [[nodiscard]] auto when_any(R&& awaitables) 787   16 [[nodiscard]] auto when_any(R&& awaitables)
788   -> task<std::variant<std::error_code, 788   -> task<std::variant<std::error_code,
789   std::pair<std::size_t, 789   std::pair<std::size_t,
790   detail::results_payload_t< 790   detail::results_payload_t<
791   awaitable_result_t<std::ranges::range_value_t<R>>>>>> 791   awaitable_result_t<std::ranges::range_value_t<R>>>>>>
792   { 792   {
793   using Awaitable = std::ranges::range_value_t<R>; 793   using Awaitable = std::ranges::range_value_t<R>;
794   using PayloadT = detail::results_payload_t< 794   using PayloadT = detail::results_payload_t<
795   awaitable_result_t<Awaitable>>; 795   awaitable_result_t<Awaitable>>;
796   using result_type = std::variant<std::error_code, 796   using result_type = std::variant<std::error_code,
797   std::pair<std::size_t, PayloadT>>; 797   std::pair<std::size_t, PayloadT>>;
798   using OwnedRange = detail::owned_range_t<R>; 798   using OwnedRange = detail::owned_range_t<R>;
799   799  
800   auto count = std::ranges::size(awaitables); 800   auto count = std::ranges::size(awaitables);
801   if(count == 0) 801   if(count == 0)
802   throw std::invalid_argument("when_any requires at least one awaitable"); 802   throw std::invalid_argument("when_any requires at least one awaitable");
803   803  
804   OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables)); 804   OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
805   805  
806   detail::when_any_results_homogeneous_state<PayloadT> state(count); 806   detail::when_any_results_homogeneous_state<PayloadT> state(count);
807   807  
808   co_await detail::when_any_results_homogeneous_launcher<OwnedRange>( 808   co_await detail::when_any_results_homogeneous_launcher<OwnedRange>(
809   &owned_awaitables, &state); 809   &owned_awaitables, &state);
810   810  
811   // Winner found 811   // Winner found
812   if(state.core_.has_winner_.load(std::memory_order_acquire)) 812   if(state.core_.has_winner_.load(std::memory_order_acquire))
813   { 813   {
814   if(state.core_.winner_exception_) 814   if(state.core_.winner_exception_)
815   std::rethrow_exception(state.core_.winner_exception_); 815   std::rethrow_exception(state.core_.winner_exception_);
816   co_return result_type{std::in_place_index<1>, 816   co_return result_type{std::in_place_index<1>,
817   std::pair{state.core_.winner_index_, std::move(*state.result_)}}; 817   std::pair{state.core_.winner_index_, std::move(*state.result_)}};
818   } 818   }
819   819  
820   // No winner — report the recorded failure 820   // No winner — report the recorded failure
821   if(state.last_exception_) 821   if(state.last_exception_)
822   std::rethrow_exception(state.last_exception_); 822   std::rethrow_exception(state.last_exception_);
823   co_return result_type{std::in_place_index<0>, state.last_error_}; 823   co_return result_type{std::in_place_index<0>, state.last_error_};
HITCBC 824   32 } 824   32 }
825   825  
826   /** Race a range of void `results`-returning awaitables. 826   /** Race a range of void `results`-returning awaitables.
827   827  
828   Only a child returning !ec can win. Returns the winner's index 828   Only a child returning !ec can win. Returns the winner's index
829   at variant index 1, or error_code at index 0 on all-fail. 829   at variant index 1, or error_code at index 0 on all-fail.
830   830  
831   @par Await-effects 831   @par Await-effects
832   832  
833   Takes ownership of the range, creates one wrapper coroutine per 833   Takes ownership of the range, creates one wrapper coroutine per
834   element, then posts every wrapper to the caller's executor. All 834   element, then posts every wrapper to the caller's executor. All
835   children therefore run concurrently, each awaited with the caller's 835   children therefore run concurrently, each awaited with the caller's
836   executor and frame allocator and with a stop token owned by this 836   executor and frame allocator and with a stop token owned by this
837   operation. 837   operation.
838   838  
839   Awaiting an empty range throws `std::invalid_argument` before any 839   Awaiting an empty range throws `std::invalid_argument` before any
840   child is started. 840   child is started.
841   841  
842   The first child to await-return a zero `ec` claims the win. Claiming 842   The first child to await-return a zero `ec` claims the win. Claiming
843   the win requests stop on the operation's own stop token, which every 843   the win requests stop on the operation's own stop token, which every
844   sibling observes through the stop token it was awaited with. A child 844   sibling observes through the stop token it was awaited with. A child
845   that await-returns a non-zero `ec`, or that exits via an exception, 845   that await-returns a non-zero `ec`, or that exits via an exception,
846   does not claim the win and does not request stop. The operation keeps 846   does not claim the win and does not request stop. The operation keeps
847   waiting for a success. A stop request on the caller's stop token is 847   waiting for a success. A stop request on the caller's stop token is
848   also forwarded to every child. 848   also forwarded to every child.
849   849  
850   The await completes only after every child has finished, regardless of 850   The await completes only after every child has finished, regardless of
851   whether a win was claimed. 851   whether a win was claimed.
852   852  
853   @par Await-returns 853   @par Await-returns
854   An object of type `std::variant<std::error_code, std::size_t>`. 854   An object of type `std::variant<std::error_code, std::size_t>`.
855   855  
856   @li Index 1 holds the winner's position in the input range. The 856   @li Index 1 holds the winner's position in the input range. The
857   children have no payloads, so nothing else is reported. 857   children have no payloads, so nothing else is reported.
858   @li Index 0 holds a non-zero `error_code` when no child won, that is, 858   @li Index 0 holds a non-zero `error_code` when no child won, that is,
859   when every child failed. It is the `ec` of one of the failed 859   when every child failed. It is the `ec` of one of the failed
860   children; which one is unspecified. 860   children; which one is unspecified.
861   861  
862   If no child won and the failure selected for reporting is an 862   If no child won and the failure selected for reporting is an
863   exception rather than an `ec`, that exception is rethrown instead of 863   exception rather than an `ec`, that exception is rethrown instead of
864   await-returning. The choice of child is unspecified. 864   await-returning. The choice of child is unspecified.
865   865  
866   @par Await-postcondition 866   @par Await-postcondition
867   Every child has finished. The result holds index 1 if at least one 867   Every child has finished. The result holds index 1 if at least one
868   child await-returned a zero `ec`. Otherwise the result holds index 0, 868   child await-returned a zero `ec`. Otherwise the result holds index 0,
869   or a failed child's exception is rethrown. 869   or a failed child's exception is rethrown.
870   870  
871   @par Remarks 871   @par Remarks
872   Supports _ContextAwaitable cancellation_. A canceled child await-returns a 872   Supports _ContextAwaitable cancellation_. A canceled child await-returns a
873   non-zero `ec` and so cannot win; if no child has already succeeded, 873   non-zero `ec` and so cannot win; if no child has already succeeded,
874   the result settles at index 0. 874   the result settles at index 0.
875   875  
876   @par Thread Safety 876   @par Thread Safety
877   The returned task must be awaited from a single execution context. 877   The returned task must be awaited from a single execution context.
878   Child awaitables execute concurrently but complete through the caller's 878   Child awaitables execute concurrently but complete through the caller's
879   executor. 879   executor.
880   880  
881   @param awaitables Range of `results<>`-returning awaitables (must 881   @param awaitables Range of `results<>`-returning awaitables (must
882   not be empty). 882   not be empty).
883   883  
884   @return A task yielding variant<error_code, size_t> where index 0 884   @return A task yielding variant<error_code, size_t> where index 0
885   is failure and index 1 carries the winner's index. 885   is failure and index 1 carries the winner's index.
886   886  
887   @throws std::invalid_argument if range is empty. 887   @throws std::invalid_argument if range is empty.
888   888  
889   @par Exception Safety 889   @par Exception Safety
890   If all children fail and the reported failure is an exception, 890   If all children fail and the reported failure is an exception,
891   that child's exception is rethrown (which child is unspecified). 891   that child's exception is rethrown (which child is unspecified).
892   892  
893   @note If a branch's coroutine is abandoned before it finishes, for 893   @note If a branch's coroutine is abandoned before it finishes, for
894   example by teardown of its execution context, `when_any` 894   example by teardown of its execution context, `when_any`
895   requests stop on the remaining branches, and the awaiting 895   requests stop on the remaining branches, and the awaiting
896   parent is abandoned rather than resumed once the last branch 896   parent is abandoned rather than resumed once the last branch
897   has finished or been abandoned. 897   has finished or been abandoned.
898   898  
899   @par Example 899   @par Example
900   @par !example example_2 900   @par !example example_2
901   901  
902   902  
903   @see @ref ContextAwaitableRange, @ref when_any 903   @see @ref ContextAwaitableRange, @ref when_any
904   */ 904   */
905   template<ContextAwaitableRange R> 905   template<ContextAwaitableRange R>
906   requires detail::is_results_v< 906   requires detail::is_results_v<
907   awaitable_result_t<std::ranges::range_value_t<R>>> 907   awaitable_result_t<std::ranges::range_value_t<R>>>
908   && std::is_same_v< 908   && std::is_same_v<
909   detail::results_payload_t< 909   detail::results_payload_t<
910   awaitable_result_t<std::ranges::range_value_t<R>>>, 910   awaitable_result_t<std::ranges::range_value_t<R>>>,
911   std::tuple<>> 911   std::tuple<>>
HITCBC 912   5 [[nodiscard]] auto when_any(R&& awaitables) 912   5 [[nodiscard]] auto when_any(R&& awaitables)
913   -> task<std::variant<std::error_code, std::size_t>> 913   -> task<std::variant<std::error_code, std::size_t>>
914   { 914   {
915   using OwnedRange = detail::owned_range_t<R>; 915   using OwnedRange = detail::owned_range_t<R>;
916   using result_type = std::variant<std::error_code, std::size_t>; 916   using result_type = std::variant<std::error_code, std::size_t>;
917   917  
918   auto count = std::ranges::size(awaitables); 918   auto count = std::ranges::size(awaitables);
919   if(count == 0) 919   if(count == 0)
920   throw std::invalid_argument("when_any requires at least one awaitable"); 920   throw std::invalid_argument("when_any requires at least one awaitable");
921   921  
922   OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables)); 922   OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
923   923  
924   detail::when_any_results_homogeneous_state<std::tuple<>> state(count); 924   detail::when_any_results_homogeneous_state<std::tuple<>> state(count);
925   925  
926   co_await detail::when_any_results_homogeneous_launcher<OwnedRange>( 926   co_await detail::when_any_results_homogeneous_launcher<OwnedRange>(
927   &owned_awaitables, &state); 927   &owned_awaitables, &state);
928   928  
929   // Winner found 929   // Winner found
930   if(state.core_.has_winner_.load(std::memory_order_acquire)) 930   if(state.core_.has_winner_.load(std::memory_order_acquire))
931   { 931   {
932   if(state.core_.winner_exception_) 932   if(state.core_.winner_exception_)
933   std::rethrow_exception(state.core_.winner_exception_); 933   std::rethrow_exception(state.core_.winner_exception_);
934   co_return result_type{std::in_place_index<1>, 934   co_return result_type{std::in_place_index<1>,
935   state.core_.winner_index_}; 935   state.core_.winner_index_};
936   } 936   }
937   937  
938   // No winner — report the recorded failure 938   // No winner — report the recorded failure
939   if(state.last_exception_) 939   if(state.last_exception_)
940   std::rethrow_exception(state.last_exception_); 940   std::rethrow_exception(state.last_exception_);
941   co_return result_type{std::in_place_index<0>, state.last_error_}; 941   co_return result_type{std::in_place_index<0>, state.last_error_};
HITCBC 942   10 } 942   10 }
943   943  
944   /** Race `results`-returning awaitables, selecting the first success. 944   /** Race `results`-returning awaitables, selecting the first success.
945   945  
946   Overload selected when all children return results<Ts...>. 946   Overload selected when all children return results<Ts...>.
947   Only a child returning !ec can win. Errors and exceptions do 947   Only a child returning !ec can win. Errors and exceptions do
948   not claim winner status. 948   not claim winner status.
949   949  
950   @par Await-effects 950   @par Await-effects
951   951  
952   Creates and posts one wrapper coroutine per argument to the caller's 952   Creates and posts one wrapper coroutine per argument to the caller's
953   executor, in argument order. All children therefore run concurrently, 953   executor, in argument order. All children therefore run concurrently,
954   each awaited with the caller's executor and frame allocator and with 954   each awaited with the caller's executor and frame allocator and with
955   a stop token owned by this operation. The overload requires at least 955   a stop token owned by this operation. The overload requires at least
956   one awaitable, so there is no empty case. 956   one awaitable, so there is no empty case.
957   957  
958   The first child to await-return a zero `ec` claims the win. Claiming 958   The first child to await-return a zero `ec` claims the win. Claiming
959   the win requests stop on the operation's own stop token, which every 959   the win requests stop on the operation's own stop token, which every
960   sibling observes through the stop token it was awaited with. A child 960   sibling observes through the stop token it was awaited with. A child
961   that await-returns a non-zero `ec`, or that exits via an exception, 961   that await-returns a non-zero `ec`, or that exits via an exception,
962   does not claim the win and does not request stop. The operation keeps 962   does not claim the win and does not request stop. The operation keeps
963   waiting for a success. A stop request on the caller's stop token is 963   waiting for a success. A stop request on the caller's stop token is
964   also forwarded to every child. 964   also forwarded to every child.
965   965  
966   The await completes only after every child has finished, regardless of 966   The await completes only after every child has finished, regardless of
967   whether a win was claimed. 967   whether a win was claimed.
968   968  
969   @par Await-returns 969   @par Await-returns
970   An object of type `std::variant<std::error_code, P1, ..., Pn>`, where 970   An object of type `std::variant<std::error_code, P1, ..., Pn>`, where
971   `Pi` is the payload of the i-th child's `results`. 971   `Pi` is the payload of the i-th child's `results`.
972   972  
973   @li Index i+1 identifies the i-th argument as the winner and holds 973   @li Index i+1 identifies the i-th argument as the winner and holds
974   its payload. 974   its payload.
975   @li Index 0 holds a non-zero `error_code` when no child won, that is, 975   @li Index 0 holds a non-zero `error_code` when no child won, that is,
976   when every child failed. It is the `ec` of one of the failed 976   when every child failed. It is the `ec` of one of the failed
977   children; which one is unspecified. 977   children; which one is unspecified.
978   978  
979   A child that succeeds after the win has already been claimed 979   A child that succeeds after the win has already been claimed
980   contributes nothing: its payload is discarded. 980   contributes nothing: its payload is discarded.
981   981  
982   If no child won and the failure selected for reporting is an 982   If no child won and the failure selected for reporting is an
983   exception rather than an `ec`, that exception is rethrown instead of 983   exception rather than an `ec`, that exception is rethrown instead of
984   await-returning. The choice of child is unspecified. 984   await-returning. The choice of child is unspecified.
985   985  
986   @par Await-postcondition 986   @par Await-postcondition
987   Every child has finished. If at least one child await-returned a zero 987   Every child has finished. If at least one child await-returned a zero
988   `ec`, the result holds the index of the winning child. If producing 988   `ec`, the result holds the index of the winning child. If producing
989   the winner's payload threw, that exception is rethrown. Otherwise the 989   the winner's payload threw, that exception is rethrown. Otherwise the
990   result holds index 0, or a failed child's exception is rethrown. 990   result holds index 0, or a failed child's exception is rethrown.
991   991  
992   @par Remarks 992   @par Remarks
993   Supports _ContextAwaitable cancellation_. A canceled child await-returns a 993   Supports _ContextAwaitable cancellation_. A canceled child await-returns a
994   non-zero `ec` and so cannot win; if no child has already succeeded, 994   non-zero `ec` and so cannot win; if no child has already succeeded,
995   the result settles at index 0. 995   the result settles at index 0.
996   996  
997   @par Thread Safety 997   @par Thread Safety
998   The returned task must be awaited from a single execution context. 998   The returned task must be awaited from a single execution context.
999   Child awaitables execute concurrently but complete through the caller's 999   Child awaitables execute concurrently but complete through the caller's
1000   executor. 1000   executor.
1001   1001  
1002   @param as The awaitables to race. Each must satisfy @ref 1002   @param as The awaitables to race. Each must satisfy @ref
1003   ContextAwaitable and is consumed (moved-from) when `when_any` 1003   ContextAwaitable and is consumed (moved-from) when `when_any`
1004   is awaited. 1004   is awaited.
1005   1005  
1006   @return A task yielding variant<error_code, R1, ..., Rn> where 1006   @return A task yielding variant<error_code, R1, ..., Rn> where
1007   index 0 is the failure/no-winner case and index i+1 1007   index 0 is the failure/no-winner case and index i+1
1008   identifies the winning child. On all-fail, index 0 holds 1008   identifies the winning child. On all-fail, index 0 holds
1009   an error_code from one of the failed children (unspecified 1009   an error_code from one of the failed children (unspecified
1010   which; no priority between errors and exceptions). 1010   which; no priority between errors and exceptions).
1011   1011  
1012   @par Exception Safety 1012   @par Exception Safety
1013   The winner's exception is rethrown if extracting or constructing 1013   The winner's exception is rethrown if extracting or constructing
1014   the winning payload throws. In that case a winner was found, but 1014   the winning payload throws. In that case a winner was found, but
1015   its result could not be produced. If all children fail and the 1015   its result could not be produced. If all children fail and the
1016   reported failure is an exception, that child's exception is 1016   reported failure is an exception, that child's exception is
1017   rethrown (which child is unspecified). 1017   rethrown (which child is unspecified).
1018   1018  
1019   @note A failing child does not cancel its siblings; `when_any` 1019   @note A failing child does not cancel its siblings; `when_any`
1020   waits for a success or for every child to finish. To make a 1020   waits for a success or for every child to finish. To make a
1021   benign error (e.g. @c cond::canceled) count as a win, wrap 1021   benign error (e.g. @c cond::canceled) count as a win, wrap
1022   the child to translate the error into success. See the 1022   the child to translate the error into success. See the
1023   Concurrent Composition tutorial. 1023   Concurrent Composition tutorial.
1024   1024  
1025   @note If a branch's coroutine is abandoned before it finishes, for 1025   @note If a branch's coroutine is abandoned before it finishes, for
1026   example by teardown of its execution context, `when_any` 1026   example by teardown of its execution context, `when_any`
1027   requests stop on the remaining branches, and the awaiting 1027   requests stop on the remaining branches, and the awaiting
1028   parent is abandoned rather than resumed once the last branch 1028   parent is abandoned rather than resumed once the last branch
1029   has finished or been abandoned. 1029   has finished or been abandoned.
1030   */ 1030   */
1031   template<ContextAwaitable... As> 1031   template<ContextAwaitable... As>
1032   requires (sizeof...(As) > 0) 1032   requires (sizeof...(As) > 0)
1033   && detail::all_results_awaitables<As...> 1033   && detail::all_results_awaitables<As...>
HITCBC 1034   32 [[nodiscard]] auto when_any(As... as) 1034   32 [[nodiscard]] auto when_any(As... as)
1035   -> task<std::variant< 1035   -> task<std::variant<
1036   std::error_code, 1036   std::error_code,
1037   detail::results_payload_t<awaitable_result_t<As>>...>> 1037   detail::results_payload_t<awaitable_result_t<As>>...>>
1038   { 1038   {
1039   using result_type = std::variant< 1039   using result_type = std::variant<
1040   std::error_code, 1040   std::error_code,
1041   detail::results_payload_t<awaitable_result_t<As>>...>; 1041   detail::results_payload_t<awaitable_result_t<As>>...>;
1042   1042  
1043   detail::when_any_results_state< 1043   detail::when_any_results_state<
1044   detail::results_payload_t<awaitable_result_t<As>>...> state; 1044   detail::results_payload_t<awaitable_result_t<As>>...> state;
1045   std::tuple<As...> awaitable_tuple(std::move(as)...); 1045   std::tuple<As...> awaitable_tuple(std::move(as)...);
1046   1046  
1047   co_await detail::when_any_results_launcher<As...>( 1047   co_await detail::when_any_results_launcher<As...>(
1048   &awaitable_tuple, &state); 1048   &awaitable_tuple, &state);
1049   1049  
1050   // Winner found: return their result 1050   // Winner found: return their result
1051   if(state.result_.has_value()) 1051   if(state.result_.has_value())
1052   co_return std::move(*state.result_); 1052   co_return std::move(*state.result_);
1053   1053  
1054   // Winner claimed but payload construction failed 1054   // Winner claimed but payload construction failed
1055   if(state.core_.winner_exception_) 1055   if(state.core_.winner_exception_)
1056   std::rethrow_exception(state.core_.winner_exception_); 1056   std::rethrow_exception(state.core_.winner_exception_);
1057   1057  
1058   // No winner — report the recorded failure 1058   // No winner — report the recorded failure
1059   if(state.last_exception_) 1059   if(state.last_exception_)
1060   std::rethrow_exception(state.last_exception_); 1060   std::rethrow_exception(state.last_exception_);
1061   co_return result_type{std::in_place_index<0>, state.last_error_}; 1061   co_return result_type{std::in_place_index<0>, state.last_error_};
HITCBC 1062   64 } 1062   64 }
1063   1063  
1064   } // namespace capy 1064   } // namespace capy
1065   } // namespace boost 1065   } // namespace boost
1066   1066  
1067   #endif 1067   #endif