100.00% Lines (189/189) 100.00% Functions (45/45)
TLA Baseline Branch
Line Hits Code Line Hits Code
1   // 1   //
2   // Copyright (c) 2026 Steve Gerbino 2   // Copyright (c) 2026 Steve Gerbino
3   // Copyright (c) 2026 Michael Vandeberg 3   // Copyright (c) 2026 Michael Vandeberg
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_ALL_HPP 11   #ifndef BOOST_CAPY_WHEN_ALL_HPP
12   #define BOOST_CAPY_WHEN_ALL_HPP 12   #define BOOST_CAPY_WHEN_ALL_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/abandon.hpp> 20   #include <boost/capy/ex/abandon.hpp>
21   #include <boost/capy/detail/owned_range.hpp> 21   #include <boost/capy/detail/owned_range.hpp>
22   #include <boost/capy/ex/frame_alloc_mixin.hpp> 22   #include <boost/capy/ex/frame_alloc_mixin.hpp>
23   #include <boost/capy/ex/await_context.hpp> 23   #include <boost/capy/ex/await_context.hpp>
24   #include <boost/capy/ex/frame_allocator.hpp> 24   #include <boost/capy/ex/frame_allocator.hpp>
25   #include <boost/capy/task.hpp> 25   #include <boost/capy/task.hpp>
26   26  
27   #include <array> 27   #include <array>
28   #include <atomic> 28   #include <atomic>
29   #include <exception> 29   #include <exception>
30   #include <memory> 30   #include <memory>
31   #include <optional> 31   #include <optional>
32   #include <ranges> 32   #include <ranges>
33   #include <stdexcept> 33   #include <stdexcept>
34   #include <stop_token> 34   #include <stop_token>
35   #include <tuple> 35   #include <tuple>
36   #include <type_traits> 36   #include <type_traits>
37   #include <utility> 37   #include <utility>
38   #include <vector> 38   #include <vector>
39   39  
40   namespace boost { 40   namespace boost {
41   namespace capy { 41   namespace capy {
42   42  
43   namespace detail { 43   namespace detail {
44   44  
45   /** Holds the result of a single task within when_all. 45   /** Holds the result of a single task within when_all.
46   */ 46   */
47   template<typename T> 47   template<typename T>
48   struct result_holder 48   struct result_holder
49   { 49   {
50   std::optional<T> value_; 50   std::optional<T> value_;
51   51  
HITCBC 52   122 void set(T v) 52   173 void set(T v)
53   { 53   {
HITCBC 54   122 value_ = std::move(v); 54   173 value_ = std::move(v);
HITCBC 55   122 } 55   173 }
56   56  
HITCBC 57   105 T get() && 57   156 T get() &&
58   { 58   {
HITCBC 59   105 return std::move(*value_); 59   156 return std::move(*value_);
60   } 60   }
61   }; 61   };
62   62  
63   /** Core shared state for when_all operations. 63   /** Core shared state for when_all operations.
64   64  
65   Contains all members and methods common to both heterogeneous (variadic) 65   Contains all members and methods common to both heterogeneous (variadic)
66   and homogeneous (range) when_all implementations. State classes embed 66   and homogeneous (range) when_all implementations. State classes embed
67   this via composition to avoid CRTP destructor ordering issues. 67   this via composition to avoid CRTP destructor ordering issues.
68   68  
69   @par Thread Safety 69   @par Thread Safety
70   Atomic operations protect exception capture and completion count. 70   Atomic operations protect exception capture and completion count.
71   */ 71   */
72   struct when_all_core 72   struct when_all_core
73   { 73   {
74   std::atomic<std::size_t> remaining_count_; 74   std::atomic<std::size_t> remaining_count_;
75   75  
76   // Exception storage - first error wins, others discarded 76   // Exception storage - first error wins, others discarded
77   std::atomic<bool> has_exception_{false}; 77   std::atomic<bool> has_exception_{false};
78   std::exception_ptr first_exception_; 78   std::exception_ptr first_exception_;
79   79  
80   std::stop_source stop_source_; 80   std::stop_source stop_source_;
81   81  
82   // Bridges parent's stop token to our stop_source 82   // Bridges parent's stop token to our stop_source
83   struct stop_callback_fn 83   struct stop_callback_fn
84   { 84   {
85   std::stop_source* source_; 85   std::stop_source* source_;
HITCBC 86   4 void operator()() const 86   4 void operator()() const
87   { 87   {
88   // Stopping can lose the last branch and destroy the join, 88   // Stopping can lose the last branch and destroy the join,
89   // with its source, before the request returns; the copy 89   // with its source, before the request returns; the copy
90   // keeps the stop state alive until then. 90   // keeps the stop state alive until then.
HITCBC 91   4 std::stop_source keep = *source_; 91   4 std::stop_source keep = *source_;
HITCBC 92   4 keep.request_stop(); 92   4 keep.request_stop();
HITCBC 93   4 } 93   4 }
94   }; 94   };
95   using stop_callback_t = std::stop_callback<stop_callback_fn>; 95   using stop_callback_t = std::stop_callback<stop_callback_fn>;
96   std::optional<stop_callback_t> parent_stop_callback_; 96   std::optional<stop_callback_t> parent_stop_callback_;
97   97  
98   continuation continuation_; 98   continuation continuation_;
99   await_context const* caller_env_ = nullptr; 99   await_context const* caller_env_ = nullptr;
100   100  
101   // Set when a branch is abandoned before finishing: the parent is 101   // Set when a branch is abandoned before finishing: the parent is
102   // then abandoned rather than resumed. 102   // then abandoned rather than resumed.
103   std::atomic<bool> lost_{false}; 103   std::atomic<bool> lost_{false};
104   104  
105   /// Drop a share held by a runner that never finished. 105   /// Drop a share held by a runner that never finished.
HITCBC 106   8 void lose_branch() noexcept 106   8 void lose_branch() noexcept
107   { 107   {
HITCBC 108   8 lost_.store(true, std::memory_order_relaxed); 108   8 lost_.store(true, std::memory_order_relaxed);
HITCBC 109   8 stop_source_.request_stop(); 109   8 stop_source_.request_stop();
HITCBC 110   16 if(remaining_count_.fetch_sub(1, std::memory_order_acq_rel) == 1) 110   16 if(remaining_count_.fetch_sub(1, std::memory_order_acq_rel) == 1)
111   { 111   {
HITCBC 112   4 auto parent = continuation_; 112   4 auto parent = continuation_;
HITCBC 113   4 capy::abandon(parent); 113   4 capy::abandon(parent);
114   } 114   }
HITCBC 115   8 } 115   8 }
116   116  
HITCBC 117   98 explicit when_all_core(std::size_t count) noexcept 117   115 explicit when_all_core(std::size_t count) noexcept
HITCBC 118   98 : remaining_count_(count) 118   115 : remaining_count_(count)
119   { 119   {
HITCBC 120   98 } 120   115 }
121   121  
122   /** Capture an exception (first one wins). */ 122   /** Capture an exception (first one wins). */
HITCBC 123   20 void capture_exception(std::exception_ptr ep) 123   20 void capture_exception(std::exception_ptr ep)
124   { 124   {
HITCBC 125   20 bool expected = false; 125   20 bool expected = false;
HITCBC 126   20 if(has_exception_.compare_exchange_strong( 126   20 if(has_exception_.compare_exchange_strong(
127   expected, true, std::memory_order_relaxed)) 127   expected, true, std::memory_order_relaxed))
HITCBC 128   19 first_exception_ = ep; 128   19 first_exception_ = ep;
HITCBC 129   20 } 129   20 }
130   }; 130   };
131   131  
132   /** Shared state for heterogeneous when_all (variadic overload). 132   /** Shared state for heterogeneous when_all (variadic overload).
133   133  
134   @tparam Ts The result types of the tasks. 134   @tparam Ts The result types of the tasks.
135   */ 135   */
136   template<typename... Ts> 136   template<typename... Ts>
137   struct when_all_state 137   struct when_all_state
138   { 138   {
139   static constexpr std::size_t task_count = sizeof...(Ts); 139   static constexpr std::size_t task_count = sizeof...(Ts);
140   140  
141   when_all_core core_; 141   when_all_core core_;
142   std::tuple<result_holder<Ts>...> results_; 142   std::tuple<result_holder<Ts>...> results_;
143   std::array<continuation, task_count> runner_handles_{}; 143   std::array<continuation, task_count> runner_handles_{};
144   144  
145   std::atomic<bool> has_error_{false}; 145   std::atomic<bool> has_error_{false};
146   std::error_code first_error_; 146   std::error_code first_error_;
147   147  
HITCBC 148   78 when_all_state() 148   95 when_all_state()
HITCBC 149   78 : core_(task_count) 149   95 : core_(task_count)
150   { 150   {
HITCBC 151   78 } 151   95 }
152   152  
153   /** Record the first error (subsequent errors are discarded). */ 153   /** Record the first error (subsequent errors are discarded). */
HITCBC 154   46 void record_error(std::error_code ec) 154   46 void record_error(std::error_code ec)
155   { 155   {
HITCBC 156   46 bool expected = false; 156   46 bool expected = false;
HITCBC 157   46 if(has_error_.compare_exchange_strong( 157   46 if(has_error_.compare_exchange_strong(
158   expected, true, std::memory_order_relaxed)) 158   expected, true, std::memory_order_relaxed))
HITCBC 159   32 first_error_ = ec; 159   32 first_error_ = ec;
HITCBC 160   46 } 160   46 }
161   }; 161   };
162   162  
163   /** Shared state for homogeneous when_all (range overload). 163   /** Shared state for homogeneous when_all (range overload).
164   164  
165   Stores extracted results payloads in a vector indexed by task 165   Stores extracted results payloads in a vector indexed by task
166   position. Tracks the first error_code for error propagation. 166   position. Tracks the first error_code for error propagation.
167   167  
168   @tparam T The payload type extracted from `results`. 168   @tparam T The payload type extracted from `results`.
169   */ 169   */
170   template<typename T> 170   template<typename T>
171   struct when_all_homogeneous_state 171   struct when_all_homogeneous_state
172   { 172   {
173   when_all_core core_; 173   when_all_core core_;
174   std::vector<std::optional<T>> results_; 174   std::vector<std::optional<T>> results_;
175   std::unique_ptr<continuation[]> runner_handles_; 175   std::unique_ptr<continuation[]> runner_handles_;
176   176  
177   std::atomic<bool> has_error_{false}; 177   std::atomic<bool> has_error_{false};
178   std::error_code first_error_; 178   std::error_code first_error_;
179   179  
HITCBC 180   15 explicit when_all_homogeneous_state(std::size_t count) 180   15 explicit when_all_homogeneous_state(std::size_t count)
HITCBC 181   15 : core_(count) 181   15 : core_(count)
HITCBC 182   30 , results_(count) 182   30 , results_(count)
HITCBC 183   15 , runner_handles_(std::make_unique<continuation[]>(count)) 183   15 , runner_handles_(std::make_unique<continuation[]>(count))
184   { 184   {
HITCBC 185   15 } 185   15 }
186   186  
HITCBC 187   27 void set_result(std::size_t index, T value) 187   27 void set_result(std::size_t index, T value)
188   { 188   {
HITCBC 189   27 results_[index].emplace(std::move(value)); 189   27 results_[index].emplace(std::move(value));
HITCBC 190   27 } 190   27 }
191   191  
192   /** Record the first error (subsequent errors are discarded). */ 192   /** Record the first error (subsequent errors are discarded). */
HITCBC 193   7 void record_error(std::error_code ec) 193   7 void record_error(std::error_code ec)
194   { 194   {
HITCBC 195   7 bool expected = false; 195   7 bool expected = false;
HITCBC 196   7 if(has_error_.compare_exchange_strong( 196   7 if(has_error_.compare_exchange_strong(
197   expected, true, std::memory_order_relaxed)) 197   expected, true, std::memory_order_relaxed))
HITCBC 198   5 first_error_ = ec; 198   5 first_error_ = ec;
HITCBC 199   7 } 199   7 }
200   }; 200   };
201   201  
202   /** Specialization for void `results` children (no payload storage). */ 202   /** Specialization for void `results` children (no payload storage). */
203   template<> 203   template<>
204   struct when_all_homogeneous_state<std::tuple<>> 204   struct when_all_homogeneous_state<std::tuple<>>
205   { 205   {
206   when_all_core core_; 206   when_all_core core_;
207   std::unique_ptr<continuation[]> runner_handles_; 207   std::unique_ptr<continuation[]> runner_handles_;
208   208  
209   std::atomic<bool> has_error_{false}; 209   std::atomic<bool> has_error_{false};
210   std::error_code first_error_; 210   std::error_code first_error_;
211   211  
HITCBC 212   5 explicit when_all_homogeneous_state(std::size_t count) 212   5 explicit when_all_homogeneous_state(std::size_t count)
HITCBC 213   5 : core_(count) 213   5 : core_(count)
HITCBC 214   5 , runner_handles_(std::make_unique<continuation[]>(count)) 214   5 , runner_handles_(std::make_unique<continuation[]>(count))
215   { 215   {
HITCBC 216   5 } 216   5 }
217   217  
218   /** Record the first error (subsequent errors are discarded). */ 218   /** Record the first error (subsequent errors are discarded). */
HITCBC 219   1 void record_error(std::error_code ec) 219   1 void record_error(std::error_code ec)
220   { 220   {
HITCBC 221   1 bool expected = false; 221   1 bool expected = false;
HITCBC 222   1 if(has_error_.compare_exchange_strong( 222   1 if(has_error_.compare_exchange_strong(
223   expected, true, std::memory_order_relaxed)) 223   expected, true, std::memory_order_relaxed))
HITCBC 224   1 first_error_ = ec; 224   1 first_error_ = ec;
HITCBC 225   1 } 225   1 }
226   }; 226   };
227   227  
228   /** Wrapper coroutine that intercepts task completion for when_all. 228   /** Wrapper coroutine that intercepts task completion for when_all.
229   229  
230   Parameterized on StateType to work with both heterogeneous (variadic) 230   Parameterized on StateType to work with both heterogeneous (variadic)
231   and homogeneous (range) state types. All state types expose their 231   and homogeneous (range) state types. All state types expose their
232   shared members through a `core_` member of type when_all_core. 232   shared members through a `core_` member of type when_all_core.
233   233  
234   @tparam StateType The state type (when_all_state or when_all_homogeneous_state). 234   @tparam StateType The state type (when_all_state or when_all_homogeneous_state).
235   */ 235   */
236   template<typename StateType> 236   template<typename StateType>
237   struct when_all_runner 237   struct when_all_runner
238   { 238   {
239   struct promise_type 239   struct promise_type
240   : detail::process_frame_mixin 240   : detail::process_frame_mixin
241   { 241   {
242   StateType* state_ = nullptr; 242   StateType* state_ = nullptr;
243   std::size_t index_ = 0; 243   std::size_t index_ = 0;
244   await_context env_; 244   await_context env_;
245   // Owns the branch's segment. 245   // Owns the branch's segment.
246   chain_owner segment_; 246   chain_owner segment_;
247   bool done_ = false; 247   bool done_ = false;
248   248  
HITCBC 249   209 ~promise_type() 249   260 ~promise_type()
250   { 250   {
HITCBC 251   209 if(!done_ && state_) 251   260 if(!done_ && state_)
HITCBC 252   8 state_->core_.lose_branch(); 252   8 state_->core_.lose_branch();
HITCBC 253   209 } 253   260 }
254   254  
HITCBC 255   209 when_all_runner get_return_object() noexcept 255   260 when_all_runner get_return_object() noexcept
256   { 256   {
257   return when_all_runner( 257   return when_all_runner(
HITCBC 258   209 std::coroutine_handle<promise_type>::from_promise(*this)); 258   260 std::coroutine_handle<promise_type>::from_promise(*this));
259   } 259   }
260   260  
HITCBC 261   209 std::suspend_always initial_suspend() noexcept 261   260 std::suspend_always initial_suspend() noexcept
262   { 262   {
HITCBC 263   209 return {}; 263   260 return {};
264   } 264   }
265   265  
HITCBC 266   201 auto final_suspend() noexcept 266   252 auto final_suspend() noexcept
267   { 267   {
268   struct awaiter 268   struct awaiter
269   { 269   {
270   promise_type* p_; 270   promise_type* p_;
HITCBC 271   201 bool await_ready() const noexcept { return false; } 271   252 bool await_ready() const noexcept { return false; }
HITCBC 272   201 auto await_suspend(std::coroutine_handle<> h) noexcept 272   252 auto await_suspend(std::coroutine_handle<> h) noexcept
273   { 273   {
HITCBC 274   201 auto& core = p_->state_->core_; 274   252 auto& core = p_->state_->core_;
HITCBC 275   201 auto* counter = &core.remaining_count_; 275   252 auto* counter = &core.remaining_count_;
HITCBC 276   201 auto* lost = &core.lost_; 276   252 auto* lost = &core.lost_;
HITCBC 277   201 auto* caller_env = core.caller_env_; 277   252 auto* caller_env = core.caller_env_;
HITCBC 278   201 auto& cont = core.continuation_; 278   252 auto& cont = core.continuation_;
279   279  
HITCBC 280   201 p_->done_ = true; 280   252 p_->done_ = true;
281   // Resumed to unwind its abandoned branch: lost, not 281   // Resumed to unwind its abandoned branch: lost, not
282   // finished. Stop is requested while this branch 282   // finished. Stop is requested while this branch
283   // still holds its share. 283   // still holds its share.
HITCBC 284   201 if(p_->segment_.abandoned()) 284   252 if(p_->segment_.abandoned())
285   { 285   {
HITCBC 286   19 lost->store(true, std::memory_order_relaxed); 286   19 lost->store(true, std::memory_order_relaxed);
HITCBC 287   19 core.stop_source_.request_stop(); 287   19 core.stop_source_.request_stop();
288   } 288   }
HITCBC 289   201 h.destroy(); 289   252 h.destroy();
290   290  
HITCBC 291   201 auto remaining = counter->fetch_sub(1, std::memory_order_acq_rel); 291   252 auto remaining = counter->fetch_sub(1, std::memory_order_acq_rel);
HITCBC 292   201 if(remaining != 1) 292   252 if(remaining != 1)
HITCBC 293   107 return detail::symmetric_transfer(std::noop_coroutine()); 293   141 return detail::symmetric_transfer(std::noop_coroutine());
HITCBC 294   94 if(lost->load(std::memory_order_relaxed)) 294   111 if(lost->load(std::memory_order_relaxed))
295   { 295   {
HITCBC 296   10 auto parent = cont; 296   10 auto parent = cont;
HITCBC 297   10 capy::abandon(parent); 297   10 capy::abandon(parent);
HITCBC 298   10 return detail::symmetric_transfer(std::noop_coroutine()); 298   10 return detail::symmetric_transfer(std::noop_coroutine());
299   } 299   }
HITCBC 300   84 return detail::symmetric_transfer(caller_env->executor.dispatch(cont)); 300   101 return detail::symmetric_transfer(caller_env->executor.dispatch(cont));
301   } 301   }
302   void await_resume() const noexcept {} // LCOV_EXCL_LINE final_suspend awaiter, never resumed 302   void await_resume() const noexcept {} // LCOV_EXCL_LINE final_suspend awaiter, never resumed
303   }; 303   };
HITCBC 304   201 return awaiter{this}; 304   252 return awaiter{this};
305   } 305   }
306   306  
HITCBC 307   181 void return_void() noexcept {} 307   232 void return_void() noexcept {}
308   308  
HITCBC 309   20 void unhandled_exception() noexcept 309   20 void unhandled_exception() noexcept
310   { 310   {
HITCBC 311   20 state_->core_.capture_exception(std::current_exception()); 311   20 state_->core_.capture_exception(std::current_exception());
HITCBC 312   20 state_->core_.stop_source_.request_stop(); 312   20 state_->core_.stop_source_.request_stop();
HITCBC 313   20 } 313   20 }
314   314  
315   // Not context_awaiter: a child whose await_suspend throws has 315   // Not context_awaiter: a child whose await_suspend throws has
316   // failed, and must reach unhandled_exception rather than terminate. 316   // failed, and must reach unhandled_exception rather than terminate.
317   template<class Awaitable> 317   template<class Awaitable>
318   struct transform_awaiter 318   struct transform_awaiter
319   { 319   {
320   std::decay_t<Awaitable> a_; 320   std::decay_t<Awaitable> a_;
321   promise_type* p_; 321   promise_type* p_;
322   322  
HITCBC 323   203 bool await_ready() { return a_.await_ready(); } 323   254 bool await_ready() { return a_.await_ready(); }
HITCBC 324   200 decltype(auto) await_resume() { return a_.await_resume(); } 324   251 decltype(auto) await_resume() { return a_.await_resume(); }
325   325  
326   template<class Promise> 326   template<class Promise>
HITCBC 327   203 auto await_suspend(std::coroutine_handle<Promise> h) 327   254 auto await_suspend(std::coroutine_handle<Promise> h)
328   { 328   {
329   using R = decltype(a_.await_suspend(h, &p_->env_)); 329   using R = decltype(a_.await_suspend(h, &p_->env_));
330   if constexpr (std::is_same_v<R, std::coroutine_handle<>>) 330   if constexpr (std::is_same_v<R, std::coroutine_handle<>>)
HITCBC 331   202 return detail::symmetric_transfer(a_.await_suspend(h, &p_->env_)); 331   253 return detail::symmetric_transfer(a_.await_suspend(h, &p_->env_));
332   else 332   else
HITCBC 333   1 return a_.await_suspend(h, &p_->env_); 333   1 return a_.await_suspend(h, &p_->env_);
334   } 334   }
335   }; 335   };
336   336  
337   template<class Awaitable> 337   template<class Awaitable>
HITCBC 338   203 auto await_transform(Awaitable&& a) 338   254 auto await_transform(Awaitable&& a)
339   { 339   {
340   using A = std::decay_t<Awaitable>; 340   using A = std::decay_t<Awaitable>;
341   if constexpr (ContextAwaitable<A>) 341   if constexpr (ContextAwaitable<A>)
342   { 342   {
343   return transform_awaiter<Awaitable>{ 343   return transform_awaiter<Awaitable>{
HITCBC 344   203 std::forward<Awaitable>(a), this}; 344   254 std::forward<Awaitable>(a), this};
345   } 345   }
346   else 346   else
347   { 347   {
348   static_assert(sizeof(A) == 0, "requires ContextAwaitable"); 348   static_assert(sizeof(A) == 0, "requires ContextAwaitable");
349   } 349   }
350   } 350   }
351   }; 351   };
352   352  
353   std::coroutine_handle<promise_type> h_; 353   std::coroutine_handle<promise_type> h_;
354   354  
HITCBC 355   209 explicit when_all_runner(std::coroutine_handle<promise_type> h) noexcept 355   260 explicit when_all_runner(std::coroutine_handle<promise_type> h) noexcept
HITCBC 356   209 : h_(h) 356   260 : h_(h)
357   { 357   {
HITCBC 358   209 } 358   260 }
359   359  
360   // Enable move for all clang versions - some versions need it 360   // Enable move for all clang versions - some versions need it
361   when_all_runner(when_all_runner&& other) noexcept 361   when_all_runner(when_all_runner&& other) noexcept
362   : h_(std::exchange(other.h_, nullptr)) 362   : h_(std::exchange(other.h_, nullptr))
363   { 363   {
364   } 364   }
365   365  
366   when_all_runner(when_all_runner const&) = delete; 366   when_all_runner(when_all_runner const&) = delete;
367   when_all_runner& operator=(when_all_runner const&) = delete; 367   when_all_runner& operator=(when_all_runner const&) = delete;
368   when_all_runner& operator=(when_all_runner&&) = delete; 368   when_all_runner& operator=(when_all_runner&&) = delete;
369   369  
HITCBC 370   209 auto release() noexcept 370   260 auto release() noexcept
371   { 371   {
HITCBC 372   209 return std::exchange(h_, nullptr); 372   260 return std::exchange(h_, nullptr);
373   } 373   }
374   }; 374   };
375   375  
376   /** Create a `results`-aware runner for a single awaitable (range path). 376   /** Create a `results`-aware runner for a single awaitable (range path).
377   377  
378   Checks the error code, records errors and requests stop on failure, 378   Checks the error code, records errors and requests stop on failure,
379   or extracts the payload on success. 379   or extracts the payload on success.
380   */ 380   */
381   template<ContextAwaitable Awaitable, typename StateType> 381   template<ContextAwaitable Awaitable, typename StateType>
382   when_all_runner<StateType> 382   when_all_runner<StateType>
HITCBC 383   48 make_when_all_homogeneous_runner(Awaitable* inner, StateType* state, std::size_t index) 383   48 make_when_all_homogeneous_runner(Awaitable* inner, StateType* state, std::size_t index)
384   { 384   {
385   // Taken from the join's storage only once running, into a local: 385   // Taken from the join's storage only once running, into a local:
386   // a runner destroyed unstarted owns no branch, and one destroyed 386   // a runner destroyed unstarted owns no branch, and one destroyed
387   // unfinished destroys it before its promise reports the loss. 387   // unfinished destroys it before its promise reports the loss.
388   Awaitable a(std::move(*inner)); 388   Awaitable a(std::move(*inner));
389   auto r = co_await abandonable<Awaitable>{a}; 389   auto r = co_await abandonable<Awaitable>{a};
390   if(!r) 390   if(!r)
391   co_return; 391   co_return;
392   auto& result = *r; 392   auto& result = *r;
393   393  
394   if(std::get<0>(result)) 394   if(std::get<0>(result))
395   { 395   {
396   state->record_error(std::get<0>(result)); 396   state->record_error(std::get<0>(result));
397   state->core_.stop_source_.request_stop(); 397   state->core_.stop_source_.request_stop();
398   } 398   }
399   else 399   else
400   { 400   {
401   using PayloadT = results_payload_t< 401   using PayloadT = results_payload_t<
402   awaitable_result_t<Awaitable>>; 402   awaitable_result_t<Awaitable>>;
403   if constexpr (!std::is_same_v<PayloadT, std::tuple<>>) 403   if constexpr (!std::is_same_v<PayloadT, std::tuple<>>)
404   { 404   {
405   state->set_result(index, 405   state->set_result(index,
406   extract_results_payload(std::move(result))); 406   extract_results_payload(std::move(result)));
407   } 407   }
408   } 408   }
HITCBC 409   96 } 409   96 }
410   410  
411   /** Create a runner for `results` children that requests stop on ec. */ 411   /** Create a runner for `results` children that requests stop on ec. */
412   template<std::size_t Index, ContextAwaitable Awaitable, typename... Ts> 412   template<std::size_t Index, ContextAwaitable Awaitable, typename... Ts>
413   when_all_runner<when_all_state<Ts...>> 413   when_all_runner<when_all_state<Ts...>>
HITCBC 414   161 make_when_all_results_runner(Awaitable* inner, when_all_state<Ts...>* state) 414   212 make_when_all_results_runner(Awaitable* inner, when_all_state<Ts...>* state)
415   { 415   {
416   // Taken from the join's storage only once running, into a local: 416   // Taken from the join's storage only once running, into a local:
417   // a runner destroyed unstarted owns no branch, and one destroyed 417   // a runner destroyed unstarted owns no branch, and one destroyed
418   // unfinished destroys it before its promise reports the loss. 418   // unfinished destroys it before its promise reports the loss.
419   Awaitable a(std::move(*inner)); 419   Awaitable a(std::move(*inner));
420   auto r = co_await abandonable<Awaitable>{a}; 420   auto r = co_await abandonable<Awaitable>{a};
421   if(!r) 421   if(!r)
422   co_return; 422   co_return;
423   auto ec = std::get<0>(*r); 423   auto ec = std::get<0>(*r);
424   std::get<Index>(state->results_).set(std::move(*r)); 424   std::get<Index>(state->results_).set(std::move(*r));
425   425  
426   if(ec) 426   if(ec)
427   { 427   {
428   state->record_error(ec); 428   state->record_error(ec);
429   state->core_.stop_source_.request_stop(); 429   state->core_.stop_source_.request_stop();
430   } 430   }
HITCBC 431   322 } 431   424 }
432   432  
433   /** Launcher that uses `results`-aware runners. */ 433   /** Launcher that uses `results`-aware runners. */
434   template<ContextAwaitable... Awaitables> 434   template<ContextAwaitable... Awaitables>
435   class when_all_results_launcher 435   class when_all_results_launcher
436   { 436   {
437   using state_type = when_all_state<awaitable_result_t<Awaitables>...>; 437   using state_type = when_all_state<awaitable_result_t<Awaitables>...>;
438   438  
439   std::tuple<Awaitables...>* awaitables_; 439   std::tuple<Awaitables...>* awaitables_;
440   state_type* state_; 440   state_type* state_;
441   441  
442   public: 442   public:
HITCBC 443   78 when_all_results_launcher( 443   95 when_all_results_launcher(
444   std::tuple<Awaitables...>* awaitables, 444   std::tuple<Awaitables...>* awaitables,
445   state_type* state) 445   state_type* state)
HITCBC 446   78 : awaitables_(awaitables) 446   95 : awaitables_(awaitables)
HITCBC 447   78 , state_(state) 447   95 , state_(state)
448   { 448   {
HITCBC 449   78 } 449   95 }
450   450  
HITCBC 451   78 bool await_ready() const noexcept 451   95 bool await_ready() const noexcept
452   { 452   {
HITCBC 453   78 return sizeof...(Awaitables) == 0; 453   95 return sizeof...(Awaitables) == 0;
454   } 454   }
455   455  
HITCBC 456   78 std::coroutine_handle<> await_suspend( 456   95 std::coroutine_handle<> await_suspend(
457   std::coroutine_handle<> continuation, await_context const* caller_env) 457   std::coroutine_handle<> continuation, await_context const* caller_env)
458   { 458   {
HITCBC 459   78 state_->core_.continuation_.h = continuation; 459   95 state_->core_.continuation_.h = continuation;
HITCBC 460   78 state_->core_.continuation_.owner = caller_env->owner; 460   95 state_->core_.continuation_.owner = caller_env->owner;
HITCBC 461   78 state_->core_.caller_env_ = caller_env; 461   95 state_->core_.caller_env_ = caller_env;
462   462  
HITCBC 463   78 if(caller_env->stop_token.stop_possible()) 463   95 if(caller_env->stop_token.stop_possible())
464   { 464   {
HITCBC 465   6 state_->core_.parent_stop_callback_.emplace( 465   6 state_->core_.parent_stop_callback_.emplace(
HITCBC 466   3 caller_env->stop_token, 466   3 caller_env->stop_token,
HITCBC 467   3 when_all_core::stop_callback_fn{&state_->core_.stop_source_}); 467   3 when_all_core::stop_callback_fn{&state_->core_.stop_source_});
468   468  
HITCBC 469   3 if(caller_env->stop_token.stop_requested()) 469   3 if(caller_env->stop_token.stop_requested())
HITCBC 470   1 state_->core_.stop_source_.request_stop(); 470   1 state_->core_.stop_source_.request_stop();
471   } 471   }
472   472  
HITCBC 473   78 auto token = state_->core_.stop_source_.get_token(); 473   95 auto token = state_->core_.stop_source_.get_token();
HITCBC 474   78 launch_all(std::index_sequence_for<Awaitables...>{}, 474   95 launch_all(std::index_sequence_for<Awaitables...>{},
475   caller_env->executor, token); 475   caller_env->executor, token);
476   476  
HITCBC 477   156 return std::noop_coroutine(); 477   190 return std::noop_coroutine();
HITCBC 478   78 } 478   95 }
479   479  
HITCBC 480   66 void await_resume() const noexcept {} 480   83 void await_resume() const noexcept {}
481   481  
482   private: 482   private:
483   template<std::size_t... Is> 483   template<std::size_t... Is>
HITCBC 484   78 void launch_all(std::index_sequence<Is...>, 484   95 void launch_all(std::index_sequence<Is...>,
485   executor_ref ex, std::stop_token token) 485   executor_ref ex, std::stop_token token)
486   { 486   {
HITCBC 487   78 (..., launch_one<Is>(ex, token)); 487   95 (..., launch_one<Is>(ex, token));
HITCBC 488   78 } 488   95 }
489   489  
490   template<std::size_t I> 490   template<std::size_t I>
HITCBC 491   161 void launch_one(executor_ref caller_ex, std::stop_token token) 491   212 void launch_one(executor_ref caller_ex, std::stop_token token)
492   { 492   {
HITCBC 493   161 auto runner = make_when_all_results_runner<I>( 493   212 auto runner = make_when_all_results_runner<I>(
HITCBC 494   161 &std::get<I>(*awaitables_), state_); 494   212 &std::get<I>(*awaitables_), state_);
495   495  
HITCBC 496   161 auto h = runner.release(); 496   212 auto h = runner.release();
HITCBC 497   161 h.promise().state_ = state_; 497   212 h.promise().state_ = state_;
HITCBC 498   161 h.promise().segment_.bind(h, caller_ex); 498   212 h.promise().segment_.bind(h, caller_ex);
HITCBC 499   161 h.promise().env_ = await_context{caller_ex, token, 499   212 h.promise().env_ = await_context{caller_ex, token,
HITCBC 500   161 state_->core_.caller_env_->frame_allocator, 500   212 state_->core_.caller_env_->frame_allocator,
HITCBC 501   322 &h.promise().segment_}; 501   424 &h.promise().segment_};
502   502  
HITCBC 503   161 state_->runner_handles_[I].h = std::coroutine_handle<>{h}; 503   212 state_->runner_handles_[I].h = std::coroutine_handle<>{h};
HITCBC 504   161 state_->core_.caller_env_->executor.post(state_->runner_handles_[I]); 504   212 state_->core_.caller_env_->executor.post(state_->runner_handles_[I]);
HITCBC 505   322 } 505   424 }
506   }; 506   };
507   507  
508   /** Helper to extract a single result from state. 508   /** Helper to extract a single result from state.
509   This is a separate function to work around a GCC-11 ICE that occurs 509   This is a separate function to work around a GCC-11 ICE that occurs
510   when using nested immediately-invoked lambdas with pack expansion. 510   when using nested immediately-invoked lambdas with pack expansion.
511   */ 511   */
512   template<std::size_t I, typename... Ts> 512   template<std::size_t I, typename... Ts>
HITCBC 513   105 auto extract_single_result(when_all_state<Ts...>& state) 513   156 auto extract_single_result(when_all_state<Ts...>& state)
514   { 514   {
HITCBC 515   105 return std::move(std::get<I>(state.results_)).get(); 515   156 return std::move(std::get<I>(state.results_)).get();
516   } 516   }
517   517  
518   /** Extract all results from state as a tuple. 518   /** Extract all results from state as a tuple.
519   */ 519   */
520   template<typename... Ts> 520   template<typename... Ts>
HITCBC 521   50 auto extract_results(when_all_state<Ts...>& state) 521   67 auto extract_results(when_all_state<Ts...>& state)
522   { 522   {
HITCBC 523   82 return [&]<std::size_t... Is>(std::index_sequence<Is...>) { 523   99 return [&]<std::size_t... Is>(std::index_sequence<Is...>) {
524   // Explicit element types: CTAD would collapse a single 524   // Explicit element types: CTAD would collapse a single
525   // `results` child via the tuple copy deduction guide 525   // `results` child via the tuple copy deduction guide
526   return std::tuple< 526   return std::tuple<
527   decltype(extract_single_result<Is>(state))...>( 527   decltype(extract_single_result<Is>(state))...>(
HITCBC 528   50 extract_single_result<Is>(state)...); 528   67 extract_single_result<Is>(state)...);
HITCBC 529   100 }(std::index_sequence_for<Ts...>{}); 529   134 }(std::index_sequence_for<Ts...>{});
530   } 530   }
531   531  
532   /** Starts all homogeneous runners concurrently. 532   /** Starts all homogeneous runners concurrently.
533   533  
534   Two-phase approach: create all runners first, then post all. 534   Two-phase approach: create all runners first, then post all.
535   This avoids lifetime issues if a task completes synchronously. 535   This avoids lifetime issues if a task completes synchronously.
536   */ 536   */
537   template<typename Range> 537   template<typename Range>
538   class when_all_homogeneous_launcher 538   class when_all_homogeneous_launcher
539   { 539   {
540   using Awaitable = std::ranges::range_value_t<Range>; 540   using Awaitable = std::ranges::range_value_t<Range>;
541   using PayloadT = results_payload_t<awaitable_result_t<Awaitable>>; 541   using PayloadT = results_payload_t<awaitable_result_t<Awaitable>>;
542   542  
543   Range* range_; 543   Range* range_;
544   when_all_homogeneous_state<PayloadT>* state_; 544   when_all_homogeneous_state<PayloadT>* state_;
545   545  
546   public: 546   public:
HITCBC 547   20 when_all_homogeneous_launcher( 547   20 when_all_homogeneous_launcher(
548   Range* range, 548   Range* range,
549   when_all_homogeneous_state<PayloadT>* state) 549   when_all_homogeneous_state<PayloadT>* state)
HITCBC 550   20 : range_(range) 550   20 : range_(range)
HITCBC 551   20 , state_(state) 551   20 , state_(state)
552   { 552   {
HITCBC 553   20 } 553   20 }
554   554  
HITCBC 555   20 bool await_ready() const noexcept 555   20 bool await_ready() const noexcept
556   { 556   {
HITCBC 557   20 return std::ranges::empty(*range_); 557   20 return std::ranges::empty(*range_);
558   } 558   }
559   559  
HITCBC 560   20 std::coroutine_handle<> await_suspend(std::coroutine_handle<> continuation, await_context const* caller_env) 560   20 std::coroutine_handle<> await_suspend(std::coroutine_handle<> continuation, await_context const* caller_env)
561   { 561   {
HITCBC 562   20 state_->core_.continuation_.h = continuation; 562   20 state_->core_.continuation_.h = continuation;
HITCBC 563   20 state_->core_.continuation_.owner = caller_env->owner; 563   20 state_->core_.continuation_.owner = caller_env->owner;
HITCBC 564   20 state_->core_.caller_env_ = caller_env; 564   20 state_->core_.caller_env_ = caller_env;
565   565  
HITCBC 566   20 if(caller_env->stop_token.stop_possible()) 566   20 if(caller_env->stop_token.stop_possible())
567   { 567   {
HITCBC 568   4 state_->core_.parent_stop_callback_.emplace( 568   4 state_->core_.parent_stop_callback_.emplace(
HITCBC 569   2 caller_env->stop_token, 569   2 caller_env->stop_token,
HITCBC 570   2 when_all_core::stop_callback_fn{&state_->core_.stop_source_}); 570   2 when_all_core::stop_callback_fn{&state_->core_.stop_source_});
571   571  
HITCBC 572   2 if(caller_env->stop_token.stop_requested()) 572   2 if(caller_env->stop_token.stop_requested())
HITCBC 573   1 state_->core_.stop_source_.request_stop(); 573   1 state_->core_.stop_source_.request_stop();
574   } 574   }
575   575  
HITCBC 576   20 auto token = state_->core_.stop_source_.get_token(); 576   20 auto token = state_->core_.stop_source_.get_token();
577   577  
578   // Phase 1: Create all runners without dispatching. 578   // Phase 1: Create all runners without dispatching.
HITCBC 579   20 std::size_t index = 0; 579   20 std::size_t index = 0;
HITCBC 580   68 for(auto&& a : *range_) 580   68 for(auto&& a : *range_)
581   { 581   {
HITCBC 582   48 auto runner = make_when_all_homogeneous_runner( 582   48 auto runner = make_when_all_homogeneous_runner(
583   &a, state_, index); 583   &a, state_, index);
584   584  
HITCBC 585   48 auto h = runner.release(); 585   48 auto h = runner.release();
HITCBC 586   48 h.promise().state_ = state_; 586   48 h.promise().state_ = state_;
HITCBC 587   48 h.promise().index_ = index; 587   48 h.promise().index_ = index;
HITCBC 588   48 h.promise().segment_.bind(h, caller_env->executor); 588   48 h.promise().segment_.bind(h, caller_env->executor);
HITCBC 589   48 h.promise().env_ = await_context{caller_env->executor, token, 589   48 h.promise().env_ = await_context{caller_env->executor, token,
HITCBC 590   96 caller_env->frame_allocator, &h.promise().segment_}; 590   96 caller_env->frame_allocator, &h.promise().segment_};
591   591  
HITCBC 592   48 state_->runner_handles_[index].h = std::coroutine_handle<>{h}; 592   48 state_->runner_handles_[index].h = std::coroutine_handle<>{h};
HITCBC 593   48 ++index; 593   48 ++index;
594   } 594   }
595   595  
596   // Phase 2: Post all runners. Any may complete synchronously. 596   // Phase 2: Post all runners. Any may complete synchronously.
597   // After last post, state_ and this may be destroyed. 597   // After last post, state_ and this may be destroyed.
HITCBC 598   20 auto* handles = state_->runner_handles_.get(); 598   20 auto* handles = state_->runner_handles_.get();
HITCBC 599   20 std::size_t count = state_->core_.remaining_count_.load(std::memory_order_relaxed); 599   20 std::size_t count = state_->core_.remaining_count_.load(std::memory_order_relaxed);
HITCBC 600   68 for(std::size_t i = 0; i < count; ++i) 600   68 for(std::size_t i = 0; i < count; ++i)
HITCBC 601   48 caller_env->executor.post(handles[i]); 601   48 caller_env->executor.post(handles[i]);
602   602  
HITCBC 603   40 return std::noop_coroutine(); 603   40 return std::noop_coroutine();
HITCBC 604   68 } 604   68 }
605   605  
HITCBC 606   18 void await_resume() const noexcept 606   18 void await_resume() const noexcept
607   { 607   {
HITCBC 608   18 } 608   18 }
609   }; 609   };
610   610  
611   } // namespace detail 611   } // namespace detail
612   612  
613 - /** Execute a range of `results`-returning awaitables concurrently. 613 + /** Asynchronously execute a range of `results`-returning awaitables concurrently.
614   614  
615 - Starts all awaitables simultaneously and waits for all to complete. 615 + Posts every awaitable to the caller's executor, in input order, and
  616 + waits for all to complete. The executor decides the order they start.
616   On success, extracted payloads are collected in a vector preserving 617   On success, extracted payloads are collected in a vector preserving
617   input order. The first error_code makes a stop request that every 618   input order. The first error_code makes a stop request that every
618   sibling observes, and is propagated in the outer results. 619   sibling observes, and is propagated in the outer results.
619   Exceptions always beat error codes. 620   Exceptions always beat error codes.
620   621  
621   @li All child awaitables run concurrently on the caller's executor. 622   @li All child awaitables run concurrently on the caller's executor.
622   @li Payloads are returned as a vector in input order. 623   @li Payloads are returned as a vector in input order.
623   @li First error_code wins and makes a stop request that siblings observe. 624   @li First error_code wins and makes a stop request that siblings observe.
624   @li Exception always beats error_code. 625   @li Exception always beats error_code.
625   @li Completes only after all children have finished. 626   @li Completes only after all children have finished.
626   627  
627   @par Await-effects 628   @par Await-effects
628   629  
629   Takes ownership of the range, creates one wrapper coroutine per 630   Takes ownership of the range, creates one wrapper coroutine per
630   element, then posts every wrapper to the caller's executor. All 631   element, then posts every wrapper to the caller's executor. All
631   children therefore run concurrently, each awaited with the caller's 632   children therefore run concurrently, each awaited with the caller's
632   executor and frame allocator and with a stop token owned by this 633   executor and frame allocator and with a stop token owned by this
633   operation. 634   operation.
634   635  
635   Awaiting an empty range throws `std::invalid_argument` before any 636   Awaiting an empty range throws `std::invalid_argument` before any
636   child is started. 637   child is started.
637   638  
638   A stop request is made on the operation's own stop token when: 639   A stop request is made on the operation's own stop token when:
639   640  
640   @li a child await-returns a non-zero `ec`, or 641   @li a child await-returns a non-zero `ec`, or
641   @li a child exits via an exception, or 642   @li a child exits via an exception, or
642   @li the caller's stop token is triggered. 643   @li the caller's stop token is triggered.
643   644  
644   Every sibling observes that request through the stop token it was 645   Every sibling observes that request through the stop token it was
645   awaited with. The request does not end the operation: the await 646   awaited with. The request does not end the operation: the await
646   completes only after every child has finished. 647   completes only after every child has finished.
647   648  
648   @par Await-returns 649   @par Await-returns
649   An object of type `results<std::vector<PayloadT>>` destructuring as 650   An object of type `results<std::vector<PayloadT>>` destructuring as
650   `[ec, values]`, where `PayloadT` is the payload of one child's 651   `[ec, values]`, where `PayloadT` is the payload of one child's
651 - `results`. 652 + `results`. The payload of `results<T>` is `T`. The payload of any
  653 + other `results<Ts...>` is `std::tuple<Ts...>`.
652   654  
653   `ec` is the first non-zero `ec` await-returned by a child, in 655   `ec` is the first non-zero `ec` await-returned by a child, in
654   completion order rather than input order. The `ec` of every other 656   completion order rather than input order. The `ec` of every other
655   child is discarded. 657   child is discarded.
656   658  
657   On success, `values` holds one payload per element of the input 659   On success, `values` holds one payload per element of the input
658   range, in input order. If `ec` is set, `values` is empty: the 660   range, in input order. If `ec` is set, `values` is empty: the
659   payloads of the children that did succeed are discarded. 661   payloads of the children that did succeed are discarded.
660   662  
661   If any child exits via an exception, the first such exception is 663   If any child exits via an exception, the first such exception is
662   rethrown instead of await-returning, even when a child also reported 664   rethrown instead of await-returning, even when a child also reported
663   an `ec`. 665   an `ec`.
664   666  
665   @par Await-postcondition 667   @par Await-postcondition
666   Every child has finished. `ec` is success only if every child 668   Every child has finished. `ec` is success only if every child
667   await-returned success. If `ec` is success, `values` holds one 669   await-returned success. If `ec` is success, `values` holds one
668   payload per input awaitable; otherwise `values` is empty. 670   payload per input awaitable; otherwise `values` is empty.
669   671  
670   @par Remarks 672   @par Remarks
671 - Supports _ContextAwaitable cancellation_. 673 + Cancellation follows the stop token of the caller's
  674 + @ref await_context.
672   675  
673   @par Thread Safety 676   @par Thread Safety
674   The returned task must be awaited from a single execution context. 677   The returned task must be awaited from a single execution context.
675   Child awaitables execute concurrently but complete through the caller's 678   Child awaitables execute concurrently but complete through the caller's
676   executor. 679   executor.
677 - @param awaitables Range of `results`-returning awaitables to execute  
678 - concurrently (must not be empty).  
679 -  
680 - @return A task yielding `results<vector<PayloadT>>` where PayloadT  
681 - is the payload extracted from each child's results.  
682 -  
683 - @throws std::invalid_argument if range is empty (thrown before  
684 - coroutine suspends).  
685 -  
686   680  
687   @par Exception Safety 681   @par Exception Safety
688   If a child throws, the first child exception is rethrown after 682   If a child throws, the first child exception is rethrown after
689   all children complete (exception beats error_code). 683   all children complete (exception beats error_code).
690   684  
691 - @note If a branch's coroutine is abandoned before it finishes, for 685 + @throws std::invalid_argument From the await, if the range is empty.
692 - example by teardown of its execution context, `when_all` 686 +
693 - requests stop on the remaining branches, and the awaiting 687 + @note If a branch's coroutine is abandoned before it finishes,
694 - parent is abandoned rather than resumed once the last branch 688 + `when_all` requests stop on the remaining branches. Teardown
695 - has finished or been abandoned. 689 + of the branch's execution context is one such case. Once the
  690 + last branch has finished or been abandoned, the awaiting
  691 + parent is abandoned rather than resumed.
696   692  
697   @par Example 693   @par Example
698   @par !example example_1 694   @par !example example_1
699   695  
700   696  
  697 + @param awaitables Range of `results`-returning awaitables to execute
  698 + concurrently (must not be empty).
  699 + The task refers to the range until the await starts. If the
  700 + range is a temporary and the task is awaited after the
  701 + full-expression that created it, the behavior is undefined.
  702 + A forward range whose elements are lvalues is copied, or moved
  703 + when passed as an rvalue. The elements of any other range are
  704 + moved into a vector. Copying an owning container of move-only
  705 + elements, such as `std::vector<task<...>>`, is ill-formed, so
  706 + pass it as an rvalue. A view such as `std::span` is copied and
  707 + its elements are moved from, so their storage must remain valid
  708 + until the await completes.
  709 +
  710 + @return A task yielding `results<std::vector<PayloadT>>`.
  711 +
701   @see @ref ContextAwaitableRange, @ref when_all 712   @see @ref ContextAwaitableRange, @ref when_all
702   */ 713   */
703   template<ContextAwaitableRange R> 714   template<ContextAwaitableRange R>
704   requires detail::is_results_v< 715   requires detail::is_results_v<
705   awaitable_result_t<std::ranges::range_value_t<R>>> 716   awaitable_result_t<std::ranges::range_value_t<R>>>
706   && (!std::is_same_v< 717   && (!std::is_same_v<
707   detail::results_payload_t< 718   detail::results_payload_t<
708   awaitable_result_t<std::ranges::range_value_t<R>>>, 719   awaitable_result_t<std::ranges::range_value_t<R>>>,
709   std::tuple<>>) 720   std::tuple<>>)
HITCBC 710   17 [[nodiscard]] auto when_all(R&& awaitables) 721   17 [[nodiscard]] auto when_all(R&& awaitables)
711   -> task<results<std::vector< 722   -> task<results<std::vector<
712   detail::results_payload_t< 723   detail::results_payload_t<
713   awaitable_result_t<std::ranges::range_value_t<R>>>>>> 724   awaitable_result_t<std::ranges::range_value_t<R>>>>>>
714   { 725   {
715   using Awaitable = std::ranges::range_value_t<R>; 726   using Awaitable = std::ranges::range_value_t<R>;
716   using PayloadT = detail::results_payload_t< 727   using PayloadT = detail::results_payload_t<
717   awaitable_result_t<Awaitable>>; 728   awaitable_result_t<Awaitable>>;
718   using OwnedRange = detail::owned_range_t<R>; 729   using OwnedRange = detail::owned_range_t<R>;
719   730  
720   auto count = std::ranges::size(awaitables); 731   auto count = std::ranges::size(awaitables);
721   if(count == 0) 732   if(count == 0)
722   throw std::invalid_argument("when_all requires at least one awaitable"); 733   throw std::invalid_argument("when_all requires at least one awaitable");
723   734  
724   OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables)); 735   OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
725   736  
726   detail::when_all_homogeneous_state<PayloadT> state(count); 737   detail::when_all_homogeneous_state<PayloadT> state(count);
727   738  
728   co_await detail::when_all_homogeneous_launcher<OwnedRange>( 739   co_await detail::when_all_homogeneous_launcher<OwnedRange>(
729   &owned_awaitables, &state); 740   &owned_awaitables, &state);
730   741  
731   if(state.core_.first_exception_) 742   if(state.core_.first_exception_)
732   std::rethrow_exception(state.core_.first_exception_); 743   std::rethrow_exception(state.core_.first_exception_);
733   744  
734   if(state.has_error_.load(std::memory_order_relaxed)) 745   if(state.has_error_.load(std::memory_order_relaxed))
735   co_return results<std::vector<PayloadT>>{state.first_error_, {}}; 746   co_return results<std::vector<PayloadT>>{state.first_error_, {}};
736   747  
737   std::vector<PayloadT> values; 748   std::vector<PayloadT> values;
738   values.reserve(count); 749   values.reserve(count);
739   for(auto& opt : state.results_) 750   for(auto& opt : state.results_)
740   values.push_back(std::move(*opt)); 751   values.push_back(std::move(*opt));
741   752  
742   co_return results<std::vector<PayloadT>>{std::error_code(), std::move(values)}; 753   co_return results<std::vector<PayloadT>>{std::error_code(), std::move(values)};
HITCBC 743   34 } 754   34 }
744   755  
745 - /** Execute a range of void `results`-returning awaitables concurrently. 756 + /** Asynchronously execute a range of void `results`-returning awaitables concurrently.
746   757  
747 - Starts all awaitables simultaneously and waits for all to complete. 758 + Posts every awaitable to the caller's executor, in input order, and
  759 + waits for all to complete. The executor decides the order they start.
748   Since all awaitables return results<>, no payload values are 760   Since all awaitables return results<>, no payload values are
749   collected. The first error_code makes a stop request that every 761   collected. The first error_code makes a stop request that every
750   sibling observes, and is propagated. Exceptions always beat error 762   sibling observes, and is propagated. Exceptions always beat error
751   codes. 763   codes.
752   764  
753   @par Await-effects 765   @par Await-effects
754   766  
755   Takes ownership of the range, creates one wrapper coroutine per 767   Takes ownership of the range, creates one wrapper coroutine per
756   element, then posts every wrapper to the caller's executor. All 768   element, then posts every wrapper to the caller's executor. All
757   children therefore run concurrently, each awaited with the caller's 769   children therefore run concurrently, each awaited with the caller's
758   executor and frame allocator and with a stop token owned by this 770   executor and frame allocator and with a stop token owned by this
759   operation. 771   operation.
760   772  
761   Awaiting an empty range throws `std::invalid_argument` before any 773   Awaiting an empty range throws `std::invalid_argument` before any
762   child is started. 774   child is started.
763   775  
764   A stop request is made on the operation's own stop token when: 776   A stop request is made on the operation's own stop token when:
765   777  
766   @li a child await-returns a non-zero `ec`, or 778   @li a child await-returns a non-zero `ec`, or
767   @li a child exits via an exception, or 779   @li a child exits via an exception, or
768   @li the caller's stop token is triggered. 780   @li the caller's stop token is triggered.
769   781  
770   Every sibling observes that request through the stop token it was 782   Every sibling observes that request through the stop token it was
771   awaited with. The request does not end the operation: the await 783   awaited with. The request does not end the operation: the await
772   completes only after every child has finished. 784   completes only after every child has finished.
773   785  
774   @par Await-returns 786   @par Await-returns
775   An object of type `results<>` destructuring as `[ec]`. The children 787   An object of type `results<>` destructuring as `[ec]`. The children
776   have no payloads, so nothing else is reported. 788   have no payloads, so nothing else is reported.
777   789  
778   `ec` is the first non-zero `ec` await-returned by a child, in 790   `ec` is the first non-zero `ec` await-returned by a child, in
779   completion order rather than input order. The `ec` of every other 791   completion order rather than input order. The `ec` of every other
780   child is discarded. 792   child is discarded.
781   793  
782   If any child exits via an exception, the first such exception is 794   If any child exits via an exception, the first such exception is
783   rethrown instead of await-returning, even when a child also reported 795   rethrown instead of await-returning, even when a child also reported
784   an `ec`. 796   an `ec`.
785   797  
786   @par Await-postcondition 798   @par Await-postcondition
787   Every child has finished. `ec` is success only if every child 799   Every child has finished. `ec` is success only if every child
788   await-returned success. 800   await-returned success.
789   801  
790   @par Remarks 802   @par Remarks
791 - Supports _ContextAwaitable cancellation_. 803 + Cancellation follows the stop token of the caller's
  804 + @ref await_context.
792   805  
793   @par Thread Safety 806   @par Thread Safety
794   The returned task must be awaited from a single execution context. 807   The returned task must be awaited from a single execution context.
795   Child awaitables execute concurrently but complete through the caller's 808   Child awaitables execute concurrently but complete through the caller's
796   executor. 809   executor.
797 - @param awaitables Range of `results<>`-returning awaitables to  
798 - execute concurrently (must not be empty).  
799 -  
800 - @return A task yielding `results<>` whose ec is the first child  
801 - error, or default-constructed on success.  
802 -  
803 - @throws std::invalid_argument if range is empty.  
804 -  
805   810  
806   @par Exception Safety 811   @par Exception Safety
807   If a child throws, the first child exception is rethrown after 812   If a child throws, the first child exception is rethrown after
808   all children complete (exception beats error_code). 813   all children complete (exception beats error_code).
809   814  
810 - @note If a branch's coroutine is abandoned before it finishes, for 815 + @throws std::invalid_argument From the await, if the range is empty.
811 - example by teardown of its execution context, `when_all` 816 +
812 - requests stop on the remaining branches, and the awaiting 817 + @note If a branch's coroutine is abandoned before it finishes,
813 - parent is abandoned rather than resumed once the last branch 818 + `when_all` requests stop on the remaining branches. Teardown
814 - has finished or been abandoned. 819 + of the branch's execution context is one such case. Once the
  820 + last branch has finished or been abandoned, the awaiting
  821 + parent is abandoned rather than resumed.
815   822  
816   @par Example 823   @par Example
817   @par !example example_2 824   @par !example example_2
818   825  
819   826  
  827 + @param awaitables Range of `results<>`-returning awaitables to
  828 + execute concurrently (must not be empty).
  829 + The task refers to the range until the await starts. If the
  830 + range is a temporary and the task is awaited after the
  831 + full-expression that created it, the behavior is undefined.
  832 + A forward range whose elements are lvalues is copied, or moved
  833 + when passed as an rvalue. The elements of any other range are
  834 + moved into a vector. Copying an owning container of move-only
  835 + elements, such as `std::vector<task<...>>`, is ill-formed, so
  836 + pass it as an rvalue. A view such as `std::span` is copied and
  837 + its elements are moved from, so their storage must remain valid
  838 + until the await completes.
  839 +
  840 + @return A task yielding `results<>` whose `ec` is the first child error, if any.
  841 +
820   @see @ref ContextAwaitableRange, @ref when_all 842   @see @ref ContextAwaitableRange, @ref when_all
821   */ 843   */
822   template<ContextAwaitableRange R> 844   template<ContextAwaitableRange R>
823   requires detail::is_results_v< 845   requires detail::is_results_v<
824   awaitable_result_t<std::ranges::range_value_t<R>>> 846   awaitable_result_t<std::ranges::range_value_t<R>>>
825   && std::is_same_v< 847   && std::is_same_v<
826   detail::results_payload_t< 848   detail::results_payload_t<
827   awaitable_result_t<std::ranges::range_value_t<R>>>, 849   awaitable_result_t<std::ranges::range_value_t<R>>>,
828   std::tuple<>> 850   std::tuple<>>
HITCBC 829   6 [[nodiscard]] auto when_all(R&& awaitables) -> task<results<>> 851   6 [[nodiscard]] auto when_all(R&& awaitables) -> task<results<>>
830   { 852   {
831   using OwnedRange = detail::owned_range_t<R>; 853   using OwnedRange = detail::owned_range_t<R>;
832   854  
833   auto count = std::ranges::size(awaitables); 855   auto count = std::ranges::size(awaitables);
834   if(count == 0) 856   if(count == 0)
835   throw std::invalid_argument("when_all requires at least one awaitable"); 857   throw std::invalid_argument("when_all requires at least one awaitable");
836   858  
837   OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables)); 859   OwnedRange owned_awaitables = detail::own_range(std::forward<R>(awaitables));
838   860  
839   detail::when_all_homogeneous_state<std::tuple<>> state(count); 861   detail::when_all_homogeneous_state<std::tuple<>> state(count);
840   862  
841   co_await detail::when_all_homogeneous_launcher<OwnedRange>( 863   co_await detail::when_all_homogeneous_launcher<OwnedRange>(
842   &owned_awaitables, &state); 864   &owned_awaitables, &state);
843   865  
844   if(state.core_.first_exception_) 866   if(state.core_.first_exception_)
845   std::rethrow_exception(state.core_.first_exception_); 867   std::rethrow_exception(state.core_.first_exception_);
846   868  
847   if(state.has_error_.load(std::memory_order_relaxed)) 869   if(state.has_error_.load(std::memory_order_relaxed))
848   co_return results<>{state.first_error_}; 870   co_return results<>{state.first_error_};
849   871  
850   co_return results<>{}; 872   co_return results<>{};
HITCBC 851   12 } 873   12 }
852   874  
853 - /** Execute `results`-returning awaitables concurrently, inspecting error codes. 875 + /** Asynchronously execute `results`-returning awaitables concurrently, inspecting error codes.
854   876  
855   Overload selected when all children return results<Ts...>. 877   Overload selected when all children return results<Ts...>.
856   The error_code is lifted out of each child into a single outer 878   The error_code is lifted out of each child into a single outer
857   results. On success all values are returned; on failure the 879   results. On success all values are returned; on failure the
858   first error_code wins. 880   first error_code wins.
859   881  
860   @par Await-effects 882   @par Await-effects
861   883  
862   Creates and posts one wrapper coroutine per argument to the caller's 884   Creates and posts one wrapper coroutine per argument to the caller's
863   executor, in argument order. All children therefore run concurrently, 885   executor, in argument order. All children therefore run concurrently,
864   each awaited with the caller's executor and frame allocator and with 886   each awaited with the caller's executor and frame allocator and with
865   a stop token owned by this operation. The overload requires at least 887   a stop token owned by this operation. The overload requires at least
866   one awaitable, so there is no empty case. 888   one awaitable, so there is no empty case.
867   889  
868   A stop request is made on the operation's own stop token when: 890   A stop request is made on the operation's own stop token when:
869   891  
870   @li a child await-returns a non-zero `ec`, or 892   @li a child await-returns a non-zero `ec`, or
871   @li a child exits via an exception, or 893   @li a child exits via an exception, or
872   @li the caller's stop token is triggered. 894   @li the caller's stop token is triggered.
873   895  
874   Every sibling observes that request through the stop token it was 896   Every sibling observes that request through the stop token it was
875   awaited with. The request does not end the operation: the await 897   awaited with. The request does not end the operation: the await
876   completes only after every child has finished. 898   completes only after every child has finished.
877   899  
878   @par Await-returns 900   @par Await-returns
879   An object of type `results<P1, ..., Pn>` destructuring as 901   An object of type `results<P1, ..., Pn>` destructuring as
880   `[ec, v1, ..., vn]`, where `Pi` is the payload of the i-th child's 902   `[ec, v1, ..., vn]`, where `Pi` is the payload of the i-th child's
881 - `results`. 903 + `results`. The payload of `results<T>` is `T`. The payload of any
  904 + other `results<Ts...>` is `std::tuple<Ts...>`.
882   905  
883   `ec` is the first non-zero `ec` await-returned by a child, in 906   `ec` is the first non-zero `ec` await-returned by a child, in
884   completion order rather than argument order. The `ec` of every other 907   completion order rather than argument order. The `ec` of every other
885   child is discarded. 908   child is discarded.
886   909  
887   Each `vi` is the payload the i-th child itself await-returned, even 910   Each `vi` is the payload the i-th child itself await-returned, even
888   when that child or a sibling reported an `ec`. A failed child 911   when that child or a sibling reported an `ec`. A failed child
889   therefore still contributes whatever payload it produced. This 912   therefore still contributes whatever payload it produced. This
890   differs from the range overloads, which discard all payloads once any 913   differs from the range overloads, which discard all payloads once any
891   child fails. 914   child fails.
892   915  
893   If any child exits via an exception, the first such exception is 916   If any child exits via an exception, the first such exception is
894   rethrown instead of await-returning, even when a child also reported 917   rethrown instead of await-returning, even when a child also reported
895   an `ec`. 918   an `ec`.
896   919  
897   @par Await-postcondition 920   @par Await-postcondition
898   Every child has finished. Each `vi` holds the i-th child's payload, 921   Every child has finished. Each `vi` holds the i-th child's payload,
899   and `ec` is success only if every child await-returned success. 922   and `ec` is success only if every child await-returned success.
900   923  
901   @par Remarks 924   @par Remarks
902 - Supports _ContextAwaitable cancellation_. 925 + Cancellation follows the stop token of the caller's
  926 + @ref await_context.
903   927  
904   @par Thread Safety 928   @par Thread Safety
905   The returned task must be awaited from a single execution context. 929   The returned task must be awaited from a single execution context.
906   Child awaitables execute concurrently but complete through the caller's 930   Child awaitables execute concurrently but complete through the caller's
907   executor. 931   executor.
908   932  
909   @par Exception Safety 933   @par Exception Safety
910   If a child throws, the first child exception is rethrown after 934   If a child throws, the first child exception is rethrown after
911   all children complete (exception beats error_code). 935   all children complete (exception beats error_code).
912   936  
913 - @note If a branch's coroutine is abandoned before it finishes, for 937 + @note If a branch's coroutine is abandoned before it finishes,
914 - example by teardown of its execution context, `when_all` 938 + `when_all` requests stop on the remaining branches. Teardown
915 - requests stop on the remaining branches, and the awaiting 939 + of the branch's execution context is one such case. Once the
916 - parent is abandoned rather than resumed once the last branch 940 + last branch has finished or been abandoned, the awaiting
917 - has finished or been abandoned. 941 + parent is abandoned rather than resumed.
  942 +
  943 + @par Example
  944 + @par !example example_3
918   945  
919   @param awaitables One or more awaitables each returning 946   @param awaitables One or more awaitables each returning
920   results<Ts...>. 947   results<Ts...>.
921   948  
922 - @return A task yielding `results<R1, R2, ..., Rn>` where each Ri 949 + @return A task yielding `results<P1, ..., Pn>`.
923 - follows the payload flattening rules. 950 +
  951 + @see @ref ContextAwaitable, @ref when_any
924   */ 952   */
925   template<ContextAwaitable... As> 953   template<ContextAwaitable... As>
926   requires (sizeof...(As) > 0) 954   requires (sizeof...(As) > 0)
927   && detail::all_results_awaitables<As...> 955   && detail::all_results_awaitables<As...>
HITCBC 928   78 [[nodiscard]] auto when_all(As... awaitables) 956   95 [[nodiscard]] auto when_all(As... awaitables)
929   -> task<results< 957   -> task<results<
930   detail::results_payload_t<awaitable_result_t<As>>...>> 958   detail::results_payload_t<awaitable_result_t<As>>...>>
931   { 959   {
932   using result_type = results< 960   using result_type = results<
933   detail::results_payload_t<awaitable_result_t<As>>...>; 961   detail::results_payload_t<awaitable_result_t<As>>...>;
934   962  
935   detail::when_all_state<awaitable_result_t<As>...> state; 963   detail::when_all_state<awaitable_result_t<As>...> state;
936   std::tuple<As...> awaitable_tuple(std::move(awaitables)...); 964   std::tuple<As...> awaitable_tuple(std::move(awaitables)...);
937   965  
938   co_await detail::when_all_results_launcher<As...>(&awaitable_tuple, &state); 966   co_await detail::when_all_results_launcher<As...>(&awaitable_tuple, &state);
939   967  
940   // Exception always wins over error_code 968   // Exception always wins over error_code
941   if(state.core_.first_exception_) 969   if(state.core_.first_exception_)
942   std::rethrow_exception(state.core_.first_exception_); 970   std::rethrow_exception(state.core_.first_exception_);
943   971  
944   auto r = detail::build_when_all_results<result_type>( 972   auto r = detail::build_when_all_results<result_type>(
945   detail::extract_results(state)); 973   detail::extract_results(state));
946   if(state.has_error_.load(std::memory_order_relaxed)) 974   if(state.has_error_.load(std::memory_order_relaxed))
947   std::get<0>(r) = state.first_error_; 975   std::get<0>(r) = state.first_error_;
948   co_return r; 976   co_return r;
HITCBC 949   156 } 977   190 }
950   978  
951   } // namespace capy 979   } // namespace capy
952   } // namespace boost 980   } // namespace boost
953   981  
954   #endif 982   #endif