1  
//
1  
//
2  
// Copyright (c) 2026 Michael Vandeberg
2  
// Copyright (c) 2026 Michael Vandeberg
3  
//
3  
//
4  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
4  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
5  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
5  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6  
//
6  
//
7  
// Official repository: https://github.com/cppalliance/capy
7  
// Official repository: https://github.com/cppalliance/capy
8  
//
8  
//
9  

9  

10  
#ifndef BOOST_CAPY_WHEN_ANY_HPP
10  
#ifndef BOOST_CAPY_WHEN_ANY_HPP
11  
#define BOOST_CAPY_WHEN_ANY_HPP
11  
#define BOOST_CAPY_WHEN_ANY_HPP
12  

12  

13  
#include <boost/capy/detail/config.hpp>
13  
#include <boost/capy/detail/config.hpp>
 
14 +
#include <boost/capy/detail/void_to_monostate.hpp>
14  
#include <boost/capy/concept/executor.hpp>
15  
#include <boost/capy/concept/executor.hpp>
15  
#include <boost/capy/concept/io_awaitable.hpp>
16  
#include <boost/capy/concept/io_awaitable.hpp>
16  
#include <coroutine>
17  
#include <coroutine>
17  
#include <boost/capy/ex/executor_ref.hpp>
18  
#include <boost/capy/ex/executor_ref.hpp>
18  
#include <boost/capy/ex/frame_allocator.hpp>
19  
#include <boost/capy/ex/frame_allocator.hpp>
19  
#include <boost/capy/ex/io_env.hpp>
20  
#include <boost/capy/ex/io_env.hpp>
20  
#include <boost/capy/task.hpp>
21  
#include <boost/capy/task.hpp>
21  

22  

22  
#include <array>
23  
#include <array>
23  
#include <atomic>
24  
#include <atomic>
24  
#include <exception>
25  
#include <exception>
25  
#include <optional>
26  
#include <optional>
26  
#include <ranges>
27  
#include <ranges>
27  
#include <stdexcept>
28  
#include <stdexcept>
28  
#include <stop_token>
29  
#include <stop_token>
29  
#include <tuple>
30  
#include <tuple>
30  
#include <type_traits>
31  
#include <type_traits>
31  
#include <utility>
32  
#include <utility>
32  
#include <variant>
33  
#include <variant>
33  
#include <vector>
34  
#include <vector>
34  

35  

35  
/*
36  
/*
36  
   when_any - Race multiple tasks, return first completion
37  
   when_any - Race multiple tasks, return first completion
37  
   ========================================================
38  
   ========================================================
38  

39  

39  
   OVERVIEW:
40  
   OVERVIEW:
40  
   ---------
41  
   ---------
41  
   when_any launches N tasks concurrently and completes when the FIRST task
42  
   when_any launches N tasks concurrently and completes when the FIRST task
42  
   finishes (success or failure). It then requests stop for all siblings and
43  
   finishes (success or failure). It then requests stop for all siblings and
43  
   waits for them to acknowledge before returning.
44  
   waits for them to acknowledge before returning.
44  

45  

45  
   ARCHITECTURE:
46  
   ARCHITECTURE:
46  
   -------------
47  
   -------------
47  
   The design mirrors when_all but with inverted completion semantics:
48  
   The design mirrors when_all but with inverted completion semantics:
48  

49  

49  
     when_all:  complete when remaining_count reaches 0 (all done)
50  
     when_all:  complete when remaining_count reaches 0 (all done)
50  
     when_any:  complete when has_winner becomes true (first done)
51  
     when_any:  complete when has_winner becomes true (first done)
51  
                BUT still wait for remaining_count to reach 0 for cleanup
52  
                BUT still wait for remaining_count to reach 0 for cleanup
52  

53  

53  
   Key components:
54  
   Key components:
54  
     - when_any_state:    Shared state tracking winner and completion
55  
     - when_any_state:    Shared state tracking winner and completion
55  
     - when_any_runner:   Wrapper coroutine for each child task
56  
     - when_any_runner:   Wrapper coroutine for each child task
56  
     - when_any_launcher: Awaitable that starts all runners concurrently
57  
     - when_any_launcher: Awaitable that starts all runners concurrently
57  

58  

58  
   CRITICAL INVARIANTS:
59  
   CRITICAL INVARIANTS:
59  
   --------------------
60  
   --------------------
60  
   1. Exactly one task becomes the winner (via atomic compare_exchange)
61  
   1. Exactly one task becomes the winner (via atomic compare_exchange)
61  
   2. All tasks must complete before parent resumes (cleanup safety)
62  
   2. All tasks must complete before parent resumes (cleanup safety)
62  
   3. Stop is requested immediately when winner is determined
63  
   3. Stop is requested immediately when winner is determined
63  
   4. Only the winner's result/exception is stored
64  
   4. Only the winner's result/exception is stored
64  

65  

65  
   POSITIONAL VARIANT:
66  
   POSITIONAL VARIANT:
66  
   -------------------
67  
   -------------------
67  
   The variadic overload returns a std::variant with one alternative per
68  
   The variadic overload returns a std::variant with one alternative per
68  
   input task, preserving positional correspondence. Use .index() on
69  
   input task, preserving positional correspondence. Use .index() on
69  
   the variant to identify which task won.
70  
   the variant to identify which task won.
70  

71  

71  
   Example: when_any(task<int>, task<string>, task<int>)
72  
   Example: when_any(task<int>, task<string>, task<int>)
72  
     - Raw types after void->monostate: int, string, int
73  
     - Raw types after void->monostate: int, string, int
73  
     - Result variant: std::variant<int, string, int>
74  
     - Result variant: std::variant<int, string, int>
74  
     - variant.index() tells you which task won (0, 1, or 2)
75  
     - variant.index() tells you which task won (0, 1, or 2)
75  

76  

76  
   VOID HANDLING:
77  
   VOID HANDLING:
77  
   --------------
78  
   --------------
78  
   void tasks contribute std::monostate to the variant.
79  
   void tasks contribute std::monostate to the variant.
79  
   All-void tasks result in: variant<monostate, monostate, monostate>
80  
   All-void tasks result in: variant<monostate, monostate, monostate>
80  

81  

81  
   MEMORY MODEL:
82  
   MEMORY MODEL:
82  
   -------------
83  
   -------------
83  
   Synchronization chain from winner's write to parent's read:
84  
   Synchronization chain from winner's write to parent's read:
84  

85  

85  
   1. Winner thread writes result_/winner_exception_ (non-atomic)
86  
   1. Winner thread writes result_/winner_exception_ (non-atomic)
86  
   2. Winner thread calls signal_completion() → fetch_sub(acq_rel) on remaining_count_
87  
   2. Winner thread calls signal_completion() → fetch_sub(acq_rel) on remaining_count_
87  
   3. Last task thread (may be winner or non-winner) calls signal_completion()
88  
   3. Last task thread (may be winner or non-winner) calls signal_completion()
88  
      → fetch_sub(acq_rel) on remaining_count_, observing count becomes 0
89  
      → fetch_sub(acq_rel) on remaining_count_, observing count becomes 0
89  
   4. Last task returns caller_ex_.dispatch(continuation_) via symmetric transfer
90  
   4. Last task returns caller_ex_.dispatch(continuation_) via symmetric transfer
90  
   5. Parent coroutine resumes and reads result_/winner_exception_
91  
   5. Parent coroutine resumes and reads result_/winner_exception_
91  

92  

92  
   Synchronization analysis:
93  
   Synchronization analysis:
93  
   - All fetch_sub operations on remaining_count_ form a release sequence
94  
   - All fetch_sub operations on remaining_count_ form a release sequence
94  
   - Winner's fetch_sub releases; subsequent fetch_sub operations participate
95  
   - Winner's fetch_sub releases; subsequent fetch_sub operations participate
95  
     in the modification order of remaining_count_
96  
     in the modification order of remaining_count_
96  
   - Last task's fetch_sub(acq_rel) synchronizes-with prior releases in the
97  
   - Last task's fetch_sub(acq_rel) synchronizes-with prior releases in the
97  
     modification order, establishing happens-before from winner's writes
98  
     modification order, establishing happens-before from winner's writes
98  
   - Executor dispatch() is expected to provide queue-based synchronization
99  
   - Executor dispatch() is expected to provide queue-based synchronization
99  
     (release-on-post, acquire-on-execute) completing the chain to parent
100  
     (release-on-post, acquire-on-execute) completing the chain to parent
100  
   - Even inline executors work (same thread = sequenced-before)
101  
   - Even inline executors work (same thread = sequenced-before)
101  

102  

102  
   Alternative considered: Adding winner_ready_ atomic (set with release after
103  
   Alternative considered: Adding winner_ready_ atomic (set with release after
103  
   storing winner data, acquired before reading) would make synchronization
104  
   storing winner data, acquired before reading) would make synchronization
104  
   self-contained and not rely on executor implementation details. Current
105  
   self-contained and not rely on executor implementation details. Current
105  
   approach is correct but requires careful reasoning about release sequences
106  
   approach is correct but requires careful reasoning about release sequences
106  
   and executor behavior.
107  
   and executor behavior.
107  

108  

108  
   EXCEPTION SEMANTICS:
109  
   EXCEPTION SEMANTICS:
109  
   --------------------
110  
   --------------------
110  
   Unlike when_all (which captures first exception, discards others), when_any
111  
   Unlike when_all (which captures first exception, discards others), when_any
111  
   treats exceptions as valid completions. If the winning task threw, that
112  
   treats exceptions as valid completions. If the winning task threw, that
112  
   exception is rethrown. Exceptions from non-winners are silently discarded.
113  
   exception is rethrown. Exceptions from non-winners are silently discarded.
113  
*/
114  
*/
114  

115  

115  
namespace boost {
116  
namespace boost {
116 -

 
117 -
/** Convert void to monostate for variant storage.
 
118 -

 
119 -
    std::variant<void, ...> is ill-formed, so void tasks contribute
 
120 -
    std::monostate to the result variant instead. Non-void types
 
121 -
    pass through unchanged.
 
122 -

 
123 -
    @tparam T The type to potentially convert (void becomes monostate).
 
124 -
*/
 
125 -
template<typename T>
 
126 -
using void_to_monostate_t = std::conditional_t<std::is_void_v<T>, std::monostate, T>;
 
127  
namespace capy {
117  
namespace capy {
128  

118  

129  
namespace detail {
119  
namespace detail {
130  

120  

131  
/** Core shared state for when_any operations.
121  
/** Core shared state for when_any operations.
132  

122  

133  
    Contains all members and methods common to both heterogeneous (variadic)
123  
    Contains all members and methods common to both heterogeneous (variadic)
134  
    and homogeneous (range) when_any implementations. State classes embed
124  
    and homogeneous (range) when_any implementations. State classes embed
135  
    this via composition to avoid CRTP destructor ordering issues.
125  
    this via composition to avoid CRTP destructor ordering issues.
136  

126  

137  
    @par Thread Safety
127  
    @par Thread Safety
138  
    Atomic operations protect winner selection and completion count.
128  
    Atomic operations protect winner selection and completion count.
139  
*/
129  
*/
140  
struct when_any_core
130  
struct when_any_core
141  
{
131  
{
142  
    std::atomic<std::size_t> remaining_count_;
132  
    std::atomic<std::size_t> remaining_count_;
143  
    std::size_t winner_index_{0};
133  
    std::size_t winner_index_{0};
144  
    std::exception_ptr winner_exception_;
134  
    std::exception_ptr winner_exception_;
145  
    std::stop_source stop_source_;
135  
    std::stop_source stop_source_;
146  

136  

147  
    // Bridges parent's stop token to our stop_source
137  
    // Bridges parent's stop token to our stop_source
148  
    struct stop_callback_fn
138  
    struct stop_callback_fn
149  
    {
139  
    {
150  
        std::stop_source* source_;
140  
        std::stop_source* source_;
151  
        void operator()() const noexcept { source_->request_stop(); }
141  
        void operator()() const noexcept { source_->request_stop(); }
152  
    };
142  
    };
153  
    using stop_callback_t = std::stop_callback<stop_callback_fn>;
143  
    using stop_callback_t = std::stop_callback<stop_callback_fn>;
154  
    std::optional<stop_callback_t> parent_stop_callback_;
144  
    std::optional<stop_callback_t> parent_stop_callback_;
155  

145  

156  
    std::coroutine_handle<> continuation_;
146  
    std::coroutine_handle<> continuation_;
157  
    io_env const* caller_env_ = nullptr;
147  
    io_env const* caller_env_ = nullptr;
158  

148  

159  
    // Placed last to avoid padding (1-byte atomic followed by 8-byte aligned members)
149  
    // Placed last to avoid padding (1-byte atomic followed by 8-byte aligned members)
160  
    std::atomic<bool> has_winner_{false};
150  
    std::atomic<bool> has_winner_{false};
161  

151  

162  
    explicit when_any_core(std::size_t count) noexcept
152  
    explicit when_any_core(std::size_t count) noexcept
163  
        : remaining_count_(count)
153  
        : remaining_count_(count)
164  
    {
154  
    {
165  
    }
155  
    }
166  

156  

167  
    /** Atomically claim winner status; exactly one task succeeds. */
157  
    /** Atomically claim winner status; exactly one task succeeds. */
168  
    bool try_win(std::size_t index) noexcept
158  
    bool try_win(std::size_t index) noexcept
169  
    {
159  
    {
170  
        bool expected = false;
160  
        bool expected = false;
171  
        if(has_winner_.compare_exchange_strong(
161  
        if(has_winner_.compare_exchange_strong(
172  
            expected, true, std::memory_order_acq_rel))
162  
            expected, true, std::memory_order_acq_rel))
173  
        {
163  
        {
174  
            winner_index_ = index;
164  
            winner_index_ = index;
175  
            stop_source_.request_stop();
165  
            stop_source_.request_stop();
176  
            return true;
166  
            return true;
177  
        }
167  
        }
178  
        return false;
168  
        return false;
179  
    }
169  
    }
180  

170  

181  
    /** @pre try_win() returned true. */
171  
    /** @pre try_win() returned true. */
182  
    void set_winner_exception(std::exception_ptr ep) noexcept
172  
    void set_winner_exception(std::exception_ptr ep) noexcept
183  
    {
173  
    {
184  
        winner_exception_ = ep;
174  
        winner_exception_ = ep;
185  
    }
175  
    }
186  

176  

187  
    // Runners signal completion directly via final_suspend; no member function needed.
177  
    // Runners signal completion directly via final_suspend; no member function needed.
188  
};
178  
};
189  

179  

190  
/** Shared state for heterogeneous when_any operation.
180  
/** Shared state for heterogeneous when_any operation.
191  

181  

192  
    Coordinates winner selection, result storage, and completion tracking
182  
    Coordinates winner selection, result storage, and completion tracking
193  
    for all child tasks in a when_any operation. Uses composition with
183  
    for all child tasks in a when_any operation. Uses composition with
194  
    when_any_core for shared functionality.
184  
    when_any_core for shared functionality.
195  

185  

196  
    @par Lifetime
186  
    @par Lifetime
197  
    Allocated on the parent coroutine's frame, outlives all runners.
187  
    Allocated on the parent coroutine's frame, outlives all runners.
198  

188  

199  
    @tparam Ts Task result types.
189  
    @tparam Ts Task result types.
200  
*/
190  
*/
201  
template<typename... Ts>
191  
template<typename... Ts>
202  
struct when_any_state
192  
struct when_any_state
203  
{
193  
{
204  
    static constexpr std::size_t task_count = sizeof...(Ts);
194  
    static constexpr std::size_t task_count = sizeof...(Ts);
205  
    using variant_type = std::variant<void_to_monostate_t<Ts>...>;
195  
    using variant_type = std::variant<void_to_monostate_t<Ts>...>;
206  

196  

207  
    when_any_core core_;
197  
    when_any_core core_;
208  
    std::optional<variant_type> result_;
198  
    std::optional<variant_type> result_;
209  
    std::array<std::coroutine_handle<>, task_count> runner_handles_{};
199  
    std::array<std::coroutine_handle<>, task_count> runner_handles_{};
210  

200  

211  
    when_any_state()
201  
    when_any_state()
212  
        : core_(task_count)
202  
        : core_(task_count)
213  
    {
203  
    {
214  
    }
204  
    }
215  

205  

216  
    // Runners self-destruct in final_suspend. No destruction needed here.
206  
    // Runners self-destruct in final_suspend. No destruction needed here.
217  

207  

218  
    /** @pre core_.try_win() returned true.
208  
    /** @pre core_.try_win() returned true.
219  
        @note Uses in_place_index (not type) for positional variant access.
209  
        @note Uses in_place_index (not type) for positional variant access.
220  
    */
210  
    */
221  
    template<std::size_t I, typename T>
211  
    template<std::size_t I, typename T>
222  
    void set_winner_result(T value)
212  
    void set_winner_result(T value)
223  
        noexcept(std::is_nothrow_move_constructible_v<T>)
213  
        noexcept(std::is_nothrow_move_constructible_v<T>)
224  
    {
214  
    {
225  
        result_.emplace(std::in_place_index<I>, std::move(value));
215  
        result_.emplace(std::in_place_index<I>, std::move(value));
226  
    }
216  
    }
227  

217  

228  
    /** @pre core_.try_win() returned true. */
218  
    /** @pre core_.try_win() returned true. */
229  
    template<std::size_t I>
219  
    template<std::size_t I>
230  
    void set_winner_void() noexcept
220  
    void set_winner_void() noexcept
231  
    {
221  
    {
232  
        result_.emplace(std::in_place_index<I>, std::monostate{});
222  
        result_.emplace(std::in_place_index<I>, std::monostate{});
233  
    }
223  
    }
234  
};
224  
};
235  

225  

236  
/** Wrapper coroutine that runs a single child task for when_any.
226  
/** Wrapper coroutine that runs a single child task for when_any.
237  

227  

238  
    Propagates executor/stop_token to the child, attempts to claim winner
228  
    Propagates executor/stop_token to the child, attempts to claim winner
239  
    status on completion, and signals completion for cleanup coordination.
229  
    status on completion, and signals completion for cleanup coordination.
240  

230  

241  
    @tparam StateType The state type (when_any_state or when_any_homogeneous_state).
231  
    @tparam StateType The state type (when_any_state or when_any_homogeneous_state).
242  
*/
232  
*/
243  
template<typename StateType>
233  
template<typename StateType>
244  
struct when_any_runner
234  
struct when_any_runner
245  
{
235  
{
246  
    struct promise_type // : frame_allocating_base  // DISABLED FOR TESTING
236  
    struct promise_type // : frame_allocating_base  // DISABLED FOR TESTING
247  
    {
237  
    {
248  
        StateType* state_ = nullptr;
238  
        StateType* state_ = nullptr;
249  
        std::size_t index_ = 0;
239  
        std::size_t index_ = 0;
250  
        io_env env_;
240  
        io_env env_;
251  

241  

252  
        when_any_runner get_return_object() noexcept
242  
        when_any_runner get_return_object() noexcept
253  
        {
243  
        {
254  
            return when_any_runner(std::coroutine_handle<promise_type>::from_promise(*this));
244  
            return when_any_runner(std::coroutine_handle<promise_type>::from_promise(*this));
255  
        }
245  
        }
256  

246  

257  
        // Starts suspended; launcher sets up state/ex/token then resumes
247  
        // Starts suspended; launcher sets up state/ex/token then resumes
258  
        std::suspend_always initial_suspend() noexcept
248  
        std::suspend_always initial_suspend() noexcept
259  
        {
249  
        {
260  
            return {};
250  
            return {};
261  
        }
251  
        }
262  

252  

263  
        auto final_suspend() noexcept
253  
        auto final_suspend() noexcept
264  
        {
254  
        {
265  
            struct awaiter
255  
            struct awaiter
266  
            {
256  
            {
267  
                promise_type* p_;
257  
                promise_type* p_;
268  
                bool await_ready() const noexcept { return false; }
258  
                bool await_ready() const noexcept { return false; }
269  
                auto await_suspend(std::coroutine_handle<> h) noexcept
259  
                auto await_suspend(std::coroutine_handle<> h) noexcept
270  
                {
260  
                {
271  
                    // Extract everything needed before self-destruction.
261  
                    // Extract everything needed before self-destruction.
272  
                    auto& core = p_->state_->core_;
262  
                    auto& core = p_->state_->core_;
273  
                    auto* counter = &core.remaining_count_;
263  
                    auto* counter = &core.remaining_count_;
274  
                    auto* caller_env = core.caller_env_;
264  
                    auto* caller_env = core.caller_env_;
275  
                    auto cont = core.continuation_;
265  
                    auto cont = core.continuation_;
276  

266  

277  
                    h.destroy();
267  
                    h.destroy();
278  

268  

279  
                    // If last runner, dispatch parent for symmetric transfer.
269  
                    // If last runner, dispatch parent for symmetric transfer.
280  
                    auto remaining = counter->fetch_sub(1, std::memory_order_acq_rel);
270  
                    auto remaining = counter->fetch_sub(1, std::memory_order_acq_rel);
281  
                    if(remaining == 1)
271  
                    if(remaining == 1)
282  
                        return detail::symmetric_transfer(caller_env->executor.dispatch(cont));
272  
                        return detail::symmetric_transfer(caller_env->executor.dispatch(cont));
283  
                    return detail::symmetric_transfer(std::noop_coroutine());
273  
                    return detail::symmetric_transfer(std::noop_coroutine());
284  
                }
274  
                }
285  
                void await_resume() const noexcept {}
275  
                void await_resume() const noexcept {}
286  
            };
276  
            };
287  
            return awaiter{this};
277  
            return awaiter{this};
288  
        }
278  
        }
289  

279  

290  
        void return_void() noexcept {}
280  
        void return_void() noexcept {}
291  

281  

292  
        // Exceptions are valid completions in when_any (unlike when_all)
282  
        // Exceptions are valid completions in when_any (unlike when_all)
293  
        void unhandled_exception()
283  
        void unhandled_exception()
294  
        {
284  
        {
295  
            if(state_->core_.try_win(index_))
285  
            if(state_->core_.try_win(index_))
296  
                state_->core_.set_winner_exception(std::current_exception());
286  
                state_->core_.set_winner_exception(std::current_exception());
297  
        }
287  
        }
298  

288  

299  
        /** Injects executor and stop token into child awaitables. */
289  
        /** Injects executor and stop token into child awaitables. */
300  
        template<class Awaitable>
290  
        template<class Awaitable>
301  
        struct transform_awaiter
291  
        struct transform_awaiter
302  
        {
292  
        {
303  
            std::decay_t<Awaitable> a_;
293  
            std::decay_t<Awaitable> a_;
304  
            promise_type* p_;
294  
            promise_type* p_;
305  

295  

306  
            bool await_ready() { return a_.await_ready(); }
296  
            bool await_ready() { return a_.await_ready(); }
307  
            auto await_resume() { return a_.await_resume(); }
297  
            auto await_resume() { return a_.await_resume(); }
308  

298  

309  
            template<class Promise>
299  
            template<class Promise>
310  
            auto await_suspend(std::coroutine_handle<Promise> h)
300  
            auto await_suspend(std::coroutine_handle<Promise> h)
311  
            {
301  
            {
312  
                using R = decltype(a_.await_suspend(h, &p_->env_));
302  
                using R = decltype(a_.await_suspend(h, &p_->env_));
313  
                if constexpr (std::is_same_v<R, std::coroutine_handle<>>)
303  
                if constexpr (std::is_same_v<R, std::coroutine_handle<>>)
314  
                    return detail::symmetric_transfer(a_.await_suspend(h, &p_->env_));
304  
                    return detail::symmetric_transfer(a_.await_suspend(h, &p_->env_));
315  
                else
305  
                else
316  
                    return a_.await_suspend(h, &p_->env_);
306  
                    return a_.await_suspend(h, &p_->env_);
317  
            }
307  
            }
318  
        };
308  
        };
319  

309  

320  
        template<class Awaitable>
310  
        template<class Awaitable>
321  
        auto await_transform(Awaitable&& a)
311  
        auto await_transform(Awaitable&& a)
322  
        {
312  
        {
323  
            using A = std::decay_t<Awaitable>;
313  
            using A = std::decay_t<Awaitable>;
324  
            if constexpr (IoAwaitable<A>)
314  
            if constexpr (IoAwaitable<A>)
325  
            {
315  
            {
326  
                return transform_awaiter<Awaitable>{
316  
                return transform_awaiter<Awaitable>{
327  
                    std::forward<Awaitable>(a), this};
317  
                    std::forward<Awaitable>(a), this};
328  
            }
318  
            }
329  
            else
319  
            else
330  
            {
320  
            {
331  
                static_assert(sizeof(A) == 0, "requires IoAwaitable");
321  
                static_assert(sizeof(A) == 0, "requires IoAwaitable");
332  
            }
322  
            }
333  
        }
323  
        }
334  
    };
324  
    };
335  

325  

336  
    std::coroutine_handle<promise_type> h_;
326  
    std::coroutine_handle<promise_type> h_;
337  

327  

338  
    explicit when_any_runner(std::coroutine_handle<promise_type> h) noexcept
328  
    explicit when_any_runner(std::coroutine_handle<promise_type> h) noexcept
339  
        : h_(h)
329  
        : h_(h)
340  
    {
330  
    {
341  
    }
331  
    }
342  

332  

343  
    // Enable move for all clang versions - some versions need it
333  
    // Enable move for all clang versions - some versions need it
344  
    when_any_runner(when_any_runner&& other) noexcept : h_(std::exchange(other.h_, nullptr)) {}
334  
    when_any_runner(when_any_runner&& other) noexcept : h_(std::exchange(other.h_, nullptr)) {}
345  

335  

346  
    // Non-copyable
336  
    // Non-copyable
347  
    when_any_runner(when_any_runner const&) = delete;
337  
    when_any_runner(when_any_runner const&) = delete;
348  
    when_any_runner& operator=(when_any_runner const&) = delete;
338  
    when_any_runner& operator=(when_any_runner const&) = delete;
349  
    when_any_runner& operator=(when_any_runner&&) = delete;
339  
    when_any_runner& operator=(when_any_runner&&) = delete;
350  

340  

351  
    auto release() noexcept
341  
    auto release() noexcept
352  
    {
342  
    {
353  
        return std::exchange(h_, nullptr);
343  
        return std::exchange(h_, nullptr);
354  
    }
344  
    }
355  
};
345  
};
356  

346  

357  
/** Indexed overload for heterogeneous when_any (compile-time index).
347  
/** Indexed overload for heterogeneous when_any (compile-time index).
358  

348  

359  
    Uses compile-time index I for variant construction via in_place_index.
349  
    Uses compile-time index I for variant construction via in_place_index.
360  
    Called from when_any_launcher::launch_one<I>().
350  
    Called from when_any_launcher::launch_one<I>().
361  
*/
351  
*/
362  
template<std::size_t I, IoAwaitable Awaitable, typename StateType>
352  
template<std::size_t I, IoAwaitable Awaitable, typename StateType>
363  
when_any_runner<StateType>
353  
when_any_runner<StateType>
364  
make_when_any_runner(Awaitable inner, StateType* state)
354  
make_when_any_runner(Awaitable inner, StateType* state)
365  
{
355  
{
366  
    using T = awaitable_result_t<Awaitable>;
356  
    using T = awaitable_result_t<Awaitable>;
367  
    if constexpr (std::is_void_v<T>)
357  
    if constexpr (std::is_void_v<T>)
368  
    {
358  
    {
369  
        co_await std::move(inner);
359  
        co_await std::move(inner);
370  
        if(state->core_.try_win(I))
360  
        if(state->core_.try_win(I))
371  
            state->template set_winner_void<I>();
361  
            state->template set_winner_void<I>();
372  
    }
362  
    }
373  
    else
363  
    else
374  
    {
364  
    {
375  
        auto result = co_await std::move(inner);
365  
        auto result = co_await std::move(inner);
376  
        if(state->core_.try_win(I))
366  
        if(state->core_.try_win(I))
377  
        {
367  
        {
378  
            try
368  
            try
379  
            {
369  
            {
380  
                state->template set_winner_result<I>(std::move(result));
370  
                state->template set_winner_result<I>(std::move(result));
381  
            }
371  
            }
382  
            catch(...)
372  
            catch(...)
383  
            {
373  
            {
384  
                state->core_.set_winner_exception(std::current_exception());
374  
                state->core_.set_winner_exception(std::current_exception());
385  
            }
375  
            }
386  
        }
376  
        }
387  
    }
377  
    }
388  
}
378  
}
389  

379  

390  
/** Runtime-index overload for homogeneous when_any (range path).
380  
/** Runtime-index overload for homogeneous when_any (range path).
391  

381  

392  
    Uses requires-expressions to detect state capabilities:
382  
    Uses requires-expressions to detect state capabilities:
393  
    - set_winner_void(): for heterogeneous void tasks (stores monostate)
383  
    - set_winner_void(): for heterogeneous void tasks (stores monostate)
394  
    - set_winner_result(): for non-void tasks
384  
    - set_winner_result(): for non-void tasks
395  
    - Neither: for homogeneous void tasks (no result storage)
385  
    - Neither: for homogeneous void tasks (no result storage)
396  
*/
386  
*/
397  
template<IoAwaitable Awaitable, typename StateType>
387  
template<IoAwaitable Awaitable, typename StateType>
398  
when_any_runner<StateType>
388  
when_any_runner<StateType>
399  
make_when_any_runner(Awaitable inner, StateType* state, std::size_t index)
389  
make_when_any_runner(Awaitable inner, StateType* state, std::size_t index)
400  
{
390  
{
401  
    using T = awaitable_result_t<Awaitable>;
391  
    using T = awaitable_result_t<Awaitable>;
402  
    if constexpr (std::is_void_v<T>)
392  
    if constexpr (std::is_void_v<T>)
403  
    {
393  
    {
404  
        co_await std::move(inner);
394  
        co_await std::move(inner);
405  
        if(state->core_.try_win(index))
395  
        if(state->core_.try_win(index))
406  
        {
396  
        {
407  
            if constexpr (requires { state->set_winner_void(); })
397  
            if constexpr (requires { state->set_winner_void(); })
408  
                state->set_winner_void();
398  
                state->set_winner_void();
409  
        }
399  
        }
410  
    }
400  
    }
411  
    else
401  
    else
412  
    {
402  
    {
413  
        auto result = co_await std::move(inner);
403  
        auto result = co_await std::move(inner);
414  
        if(state->core_.try_win(index))
404  
        if(state->core_.try_win(index))
415  
        {
405  
        {
416  
            try
406  
            try
417  
            {
407  
            {
418  
                state->set_winner_result(std::move(result));
408  
                state->set_winner_result(std::move(result));
419  
            }
409  
            }
420  
            catch(...)
410  
            catch(...)
421  
            {
411  
            {
422  
                state->core_.set_winner_exception(std::current_exception());
412  
                state->core_.set_winner_exception(std::current_exception());
423  
            }
413  
            }
424  
        }
414  
        }
425  
    }
415  
    }
426  
}
416  
}
427  

417  

428  
/** Launches all runners concurrently; see await_suspend for lifetime concerns. */
418  
/** Launches all runners concurrently; see await_suspend for lifetime concerns. */
429  
template<IoAwaitable... Awaitables>
419  
template<IoAwaitable... Awaitables>
430  
class when_any_launcher
420  
class when_any_launcher
431  
{
421  
{
432  
    using state_type = when_any_state<awaitable_result_t<Awaitables>...>;
422  
    using state_type = when_any_state<awaitable_result_t<Awaitables>...>;
433  

423  

434  
    std::tuple<Awaitables...>* tasks_;
424  
    std::tuple<Awaitables...>* tasks_;
435  
    state_type* state_;
425  
    state_type* state_;
436  

426  

437  
public:
427  
public:
438  
    when_any_launcher(
428  
    when_any_launcher(
439  
        std::tuple<Awaitables...>* tasks,
429  
        std::tuple<Awaitables...>* tasks,
440  
        state_type* state)
430  
        state_type* state)
441  
        : tasks_(tasks)
431  
        : tasks_(tasks)
442  
        , state_(state)
432  
        , state_(state)
443  
    {
433  
    {
444  
    }
434  
    }
445  

435  

446  
    bool await_ready() const noexcept
436  
    bool await_ready() const noexcept
447  
    {
437  
    {
448  
        return sizeof...(Awaitables) == 0;
438  
        return sizeof...(Awaitables) == 0;
449  
    }
439  
    }
450  

440  

451  
    /** CRITICAL: If the last task finishes synchronously, parent resumes and
441  
    /** CRITICAL: If the last task finishes synchronously, parent resumes and
452  
        destroys this object before await_suspend returns. Must not reference
442  
        destroys this object before await_suspend returns. Must not reference
453  
        `this` after the final launch_one call.
443  
        `this` after the final launch_one call.
454  
    */
444  
    */
455  
    std::coroutine_handle<> await_suspend(std::coroutine_handle<> continuation, io_env const* caller_env)
445  
    std::coroutine_handle<> await_suspend(std::coroutine_handle<> continuation, io_env const* caller_env)
456  
    {
446  
    {
457  
        state_->core_.continuation_ = continuation;
447  
        state_->core_.continuation_ = continuation;
458  
        state_->core_.caller_env_ = caller_env;
448  
        state_->core_.caller_env_ = caller_env;
459  

449  

460  
        if(caller_env->stop_token.stop_possible())
450  
        if(caller_env->stop_token.stop_possible())
461  
        {
451  
        {
462  
            state_->core_.parent_stop_callback_.emplace(
452  
            state_->core_.parent_stop_callback_.emplace(
463  
                caller_env->stop_token,
453  
                caller_env->stop_token,
464  
                when_any_core::stop_callback_fn{&state_->core_.stop_source_});
454  
                when_any_core::stop_callback_fn{&state_->core_.stop_source_});
465  

455  

466  
            if(caller_env->stop_token.stop_requested())
456  
            if(caller_env->stop_token.stop_requested())
467  
                state_->core_.stop_source_.request_stop();
457  
                state_->core_.stop_source_.request_stop();
468  
        }
458  
        }
469  

459  

470  
        auto token = state_->core_.stop_source_.get_token();
460  
        auto token = state_->core_.stop_source_.get_token();
471  
        [&]<std::size_t... Is>(std::index_sequence<Is...>) {
461  
        [&]<std::size_t... Is>(std::index_sequence<Is...>) {
472  
            (..., launch_one<Is>(caller_env->executor, token));
462  
            (..., launch_one<Is>(caller_env->executor, token));
473  
        }(std::index_sequence_for<Awaitables...>{});
463  
        }(std::index_sequence_for<Awaitables...>{});
474  

464  

475  
        return std::noop_coroutine();
465  
        return std::noop_coroutine();
476  
    }
466  
    }
477  

467  

478  
    void await_resume() const noexcept
468  
    void await_resume() const noexcept
479  
    {
469  
    {
480  
    }
470  
    }
481  

471  

482  
private:
472  
private:
483  
    /** @pre Ex::dispatch() and std::coroutine_handle<>::resume() must not throw (handle may leak). */
473  
    /** @pre Ex::dispatch() and std::coroutine_handle<>::resume() must not throw (handle may leak). */
484  
    template<std::size_t I>
474  
    template<std::size_t I>
485  
    void launch_one(executor_ref caller_ex, std::stop_token token)
475  
    void launch_one(executor_ref caller_ex, std::stop_token token)
486  
    {
476  
    {
487  
        auto runner = make_when_any_runner<I>(
477  
        auto runner = make_when_any_runner<I>(
488  
            std::move(std::get<I>(*tasks_)), state_);
478  
            std::move(std::get<I>(*tasks_)), state_);
489  

479  

490  
        auto h = runner.release();
480  
        auto h = runner.release();
491  
        h.promise().state_ = state_;
481  
        h.promise().state_ = state_;
492  
        h.promise().index_ = I;
482  
        h.promise().index_ = I;
493  
        h.promise().env_ = io_env{caller_ex, token, state_->core_.caller_env_->frame_allocator};
483  
        h.promise().env_ = io_env{caller_ex, token, state_->core_.caller_env_->frame_allocator};
494  

484  

495  
        std::coroutine_handle<> ch{h};
485  
        std::coroutine_handle<> ch{h};
496  
        state_->runner_handles_[I] = ch;
486  
        state_->runner_handles_[I] = ch;
497  
        caller_ex.post(ch);
487  
        caller_ex.post(ch);
498  
    }
488  
    }
499  
};
489  
};
500  

490  

501  
} // namespace detail
491  
} // namespace detail
502  

492  

503  
/** Wait for the first awaitable to complete.
493  
/** Wait for the first awaitable to complete.
504  

494  

505  
    Races multiple heterogeneous awaitables concurrently and returns when the
495  
    Races multiple heterogeneous awaitables concurrently and returns when the
506  
    first one completes. The result is a variant with one alternative per
496  
    first one completes. The result is a variant with one alternative per
507  
    input task, preserving positional correspondence.
497  
    input task, preserving positional correspondence.
508  

498  

509  
    @par Suspends
499  
    @par Suspends
510  
    The calling coroutine suspends when co_await is invoked. All awaitables
500  
    The calling coroutine suspends when co_await is invoked. All awaitables
511  
    are launched concurrently and execute in parallel. The coroutine resumes
501  
    are launched concurrently and execute in parallel. The coroutine resumes
512  
    only after all awaitables have completed, even though the winner is
502  
    only after all awaitables have completed, even though the winner is
513  
    determined by the first to finish.
503  
    determined by the first to finish.
514  

504  

515  
    @par Completion Conditions
505  
    @par Completion Conditions
516  
    @li Winner is determined when the first awaitable completes (success or exception)
506  
    @li Winner is determined when the first awaitable completes (success or exception)
517  
    @li Only one task can claim winner status via atomic compare-exchange
507  
    @li Only one task can claim winner status via atomic compare-exchange
518  
    @li Once a winner exists, stop is requested for all remaining siblings
508  
    @li Once a winner exists, stop is requested for all remaining siblings
519  
    @li Parent coroutine resumes only after all siblings acknowledge completion
509  
    @li Parent coroutine resumes only after all siblings acknowledge completion
520  
    @li The winner's result is returned; if the winner threw, the exception is rethrown
510  
    @li The winner's result is returned; if the winner threw, the exception is rethrown
521  

511  

522  
    @par Cancellation Semantics
512  
    @par Cancellation Semantics
523  
    Cancellation is supported via stop_token propagated through the
513  
    Cancellation is supported via stop_token propagated through the
524  
    IoAwaitable protocol:
514  
    IoAwaitable protocol:
525  
    @li Each child awaitable receives a stop_token derived from a shared stop_source
515  
    @li Each child awaitable receives a stop_token derived from a shared stop_source
526  
    @li When the parent's stop token is activated, the stop is forwarded to all children
516  
    @li When the parent's stop token is activated, the stop is forwarded to all children
527  
    @li When a winner is determined, stop_source_.request_stop() is called immediately
517  
    @li When a winner is determined, stop_source_.request_stop() is called immediately
528  
    @li Siblings must handle cancellation gracefully and complete before parent resumes
518  
    @li Siblings must handle cancellation gracefully and complete before parent resumes
529  
    @li Stop requests are cooperative; tasks must check and respond to them
519  
    @li Stop requests are cooperative; tasks must check and respond to them
530  

520  

531  
    @par Concurrency/Overlap
521  
    @par Concurrency/Overlap
532  
    All awaitables are launched concurrently before any can complete.
522  
    All awaitables are launched concurrently before any can complete.
533  
    The launcher iterates through the arguments, starting each task on the
523  
    The launcher iterates through the arguments, starting each task on the
534  
    caller's executor. Tasks may execute in parallel on multi-threaded
524  
    caller's executor. Tasks may execute in parallel on multi-threaded
535  
    executors or interleave on single-threaded executors. There is no
525  
    executors or interleave on single-threaded executors. There is no
536  
    guaranteed ordering of task completion.
526  
    guaranteed ordering of task completion.
537  

527  

538  
    @par Notable Error Conditions
528  
    @par Notable Error Conditions
539  
    @li Winner exception: if the winning task threw, that exception is rethrown
529  
    @li Winner exception: if the winning task threw, that exception is rethrown
540  
    @li Non-winner exceptions: silently discarded (only winner's result matters)
530  
    @li Non-winner exceptions: silently discarded (only winner's result matters)
541  
    @li Cancellation: tasks may complete via cancellation without throwing
531  
    @li Cancellation: tasks may complete via cancellation without throwing
542  

532  

543  
    @par Example
533  
    @par Example
544  
    @code
534  
    @code
545  
    task<void> example() {
535  
    task<void> example() {
546  
        auto result = co_await when_any(
536  
        auto result = co_await when_any(
547  
            fetch_int(),      // task<int>
537  
            fetch_int(),      // task<int>
548  
            fetch_string()    // task<std::string>
538  
            fetch_string()    // task<std::string>
549  
        );
539  
        );
550  
        // result.index() is 0 or 1
540  
        // result.index() is 0 or 1
551  
        if (result.index() == 0)
541  
        if (result.index() == 0)
552  
            std::cout << "Got int: " << std::get<0>(result) << "\n";
542  
            std::cout << "Got int: " << std::get<0>(result) << "\n";
553  
        else
543  
        else
554  
            std::cout << "Got string: " << std::get<1>(result) << "\n";
544  
            std::cout << "Got string: " << std::get<1>(result) << "\n";
555  
    }
545  
    }
556  
    @endcode
546  
    @endcode
557  

547  

558  
    @param as Awaitables to race concurrently (at least one required; each
548  
    @param as Awaitables to race concurrently (at least one required; each
559  
        must satisfy IoAwaitable).
549  
        must satisfy IoAwaitable).
560  
    @return A task yielding a std::variant with one alternative per awaitable.
550  
    @return A task yielding a std::variant with one alternative per awaitable.
561  
        Use .index() to identify the winner. Void awaitables contribute
551  
        Use .index() to identify the winner. Void awaitables contribute
562  
        std::monostate.
552  
        std::monostate.
563  

553  

564  
    @throws Rethrows the winner's exception if the winning task threw an exception.
554  
    @throws Rethrows the winner's exception if the winning task threw an exception.
565  

555  

566  
    @par Remarks
556  
    @par Remarks
567  
    Awaitables are moved into the coroutine frame; original objects become
557  
    Awaitables are moved into the coroutine frame; original objects become
568  
    empty after the call. The variant preserves one alternative per input
558  
    empty after the call. The variant preserves one alternative per input
569  
    task. Use .index() to determine which awaitable completed first.
559  
    task. Use .index() to determine which awaitable completed first.
570  
    Void awaitables contribute std::monostate to the variant.
560  
    Void awaitables contribute std::monostate to the variant.
571  

561  

572  
    @see when_all, IoAwaitable
562  
    @see when_all, IoAwaitable
573  
*/
563  
*/
574  
template<IoAwaitable... As>
564  
template<IoAwaitable... As>
575  
    requires (sizeof...(As) > 0)
565  
    requires (sizeof...(As) > 0)
576  
[[nodiscard]] auto when_any(As... as)
566  
[[nodiscard]] auto when_any(As... as)
577  
    -> task<std::variant<void_to_monostate_t<awaitable_result_t<As>>...>>
567  
    -> task<std::variant<void_to_monostate_t<awaitable_result_t<As>>...>>
578  
{
568  
{
579  
    detail::when_any_state<awaitable_result_t<As>...> state;
569  
    detail::when_any_state<awaitable_result_t<As>...> state;
580  
    std::tuple<As...> awaitable_tuple(std::move(as)...);
570  
    std::tuple<As...> awaitable_tuple(std::move(as)...);
581  

571  

582  
    co_await detail::when_any_launcher<As...>(&awaitable_tuple, &state);
572  
    co_await detail::when_any_launcher<As...>(&awaitable_tuple, &state);
583  

573  

584  
    if(state.core_.winner_exception_)
574  
    if(state.core_.winner_exception_)
585  
        std::rethrow_exception(state.core_.winner_exception_);
575  
        std::rethrow_exception(state.core_.winner_exception_);
586  

576  

587  
    co_return std::move(*state.result_);
577  
    co_return std::move(*state.result_);
588  
}
578  
}
589  

579  

590  
/** Concept for ranges of full I/O awaitables.
580  
/** Concept for ranges of full I/O awaitables.
591  

581  

592  
    A range satisfies `IoAwaitableRange` if it is a sized input range
582  
    A range satisfies `IoAwaitableRange` if it is a sized input range
593  
    whose value type satisfies @ref IoAwaitable. This enables when_any
583  
    whose value type satisfies @ref IoAwaitable. This enables when_any
594  
    to accept any container or view of awaitables, not just std::vector.
584  
    to accept any container or view of awaitables, not just std::vector.
595  

585  

596  
    @tparam R The range type.
586  
    @tparam R The range type.
597  

587  

598  
    @par Requirements
588  
    @par Requirements
599  
    @li `R` must satisfy `std::ranges::input_range`
589  
    @li `R` must satisfy `std::ranges::input_range`
600  
    @li `R` must satisfy `std::ranges::sized_range`
590  
    @li `R` must satisfy `std::ranges::sized_range`
601  
    @li `std::ranges::range_value_t<R>` must satisfy @ref IoAwaitable
591  
    @li `std::ranges::range_value_t<R>` must satisfy @ref IoAwaitable
602  

592  

603  
    @par Syntactic Requirements
593  
    @par Syntactic Requirements
604  
    Given `r` of type `R`:
594  
    Given `r` of type `R`:
605  
    @li `std::ranges::begin(r)` is valid
595  
    @li `std::ranges::begin(r)` is valid
606  
    @li `std::ranges::end(r)` is valid
596  
    @li `std::ranges::end(r)` is valid
607  
    @li `std::ranges::size(r)` returns `std::ranges::range_size_t<R>`
597  
    @li `std::ranges::size(r)` returns `std::ranges::range_size_t<R>`
608  
    @li `*std::ranges::begin(r)` satisfies @ref IoAwaitable
598  
    @li `*std::ranges::begin(r)` satisfies @ref IoAwaitable
609  

599  

610  
    @par Example
600  
    @par Example
611  
    @code
601  
    @code
612  
    template<IoAwaitableRange R>
602  
    template<IoAwaitableRange R>
613  
    task<void> race_all(R&& awaitables) {
603  
    task<void> race_all(R&& awaitables) {
614  
        auto winner = co_await when_any(std::forward<R>(awaitables));
604  
        auto winner = co_await when_any(std::forward<R>(awaitables));
615  
        // Process winner...
605  
        // Process winner...
616  
    }
606  
    }
617  
    @endcode
607  
    @endcode
618  

608  

619  
    @see when_any, IoAwaitable
609  
    @see when_any, IoAwaitable
620  
*/
610  
*/
621  
template<typename R>
611  
template<typename R>
622  
concept IoAwaitableRange =
612  
concept IoAwaitableRange =
623  
    std::ranges::input_range<R> &&
613  
    std::ranges::input_range<R> &&
624  
    std::ranges::sized_range<R> &&
614  
    std::ranges::sized_range<R> &&
625  
    IoAwaitable<std::ranges::range_value_t<R>>;
615  
    IoAwaitable<std::ranges::range_value_t<R>>;
626  

616  

627  
namespace detail {
617  
namespace detail {
628  

618  

629  
/** Shared state for homogeneous when_any (range overload).
619  
/** Shared state for homogeneous when_any (range overload).
630  

620  

631  
    Uses composition with when_any_core for shared functionality.
621  
    Uses composition with when_any_core for shared functionality.
632  
    Simpler than heterogeneous: optional<T> instead of variant, vector
622  
    Simpler than heterogeneous: optional<T> instead of variant, vector
633  
    instead of array for runner handles.
623  
    instead of array for runner handles.
634  
*/
624  
*/
635  
template<typename T>
625  
template<typename T>
636  
struct when_any_homogeneous_state
626  
struct when_any_homogeneous_state
637  
{
627  
{
638  
    when_any_core core_;
628  
    when_any_core core_;
639  
    std::optional<T> result_;
629  
    std::optional<T> result_;
640  
    std::vector<std::coroutine_handle<>> runner_handles_;
630  
    std::vector<std::coroutine_handle<>> runner_handles_;
641  

631  

642  
    explicit when_any_homogeneous_state(std::size_t count)
632  
    explicit when_any_homogeneous_state(std::size_t count)
643  
        : core_(count)
633  
        : core_(count)
644  
        , runner_handles_(count)
634  
        , runner_handles_(count)
645  
    {
635  
    {
646  
    }
636  
    }
647  

637  

648  
    // Runners self-destruct in final_suspend. No destruction needed here.
638  
    // Runners self-destruct in final_suspend. No destruction needed here.
649  

639  

650  
    /** @pre core_.try_win() returned true. */
640  
    /** @pre core_.try_win() returned true. */
651  
    void set_winner_result(T value)
641  
    void set_winner_result(T value)
652  
        noexcept(std::is_nothrow_move_constructible_v<T>)
642  
        noexcept(std::is_nothrow_move_constructible_v<T>)
653  
    {
643  
    {
654  
        result_.emplace(std::move(value));
644  
        result_.emplace(std::move(value));
655  
    }
645  
    }
656  
};
646  
};
657  

647  

658  
/** Specialization for void tasks (no result storage needed). */
648  
/** Specialization for void tasks (no result storage needed). */
659  
template<>
649  
template<>
660  
struct when_any_homogeneous_state<void>
650  
struct when_any_homogeneous_state<void>
661  
{
651  
{
662  
    when_any_core core_;
652  
    when_any_core core_;
663  
    std::vector<std::coroutine_handle<>> runner_handles_;
653  
    std::vector<std::coroutine_handle<>> runner_handles_;
664  

654  

665  
    explicit when_any_homogeneous_state(std::size_t count)
655  
    explicit when_any_homogeneous_state(std::size_t count)
666  
        : core_(count)
656  
        : core_(count)
667  
        , runner_handles_(count)
657  
        , runner_handles_(count)
668  
    {
658  
    {
669  
    }
659  
    }
670  

660  

671  
    // Runners self-destruct in final_suspend. No destruction needed here.
661  
    // Runners self-destruct in final_suspend. No destruction needed here.
672  

662  

673  
    // No set_winner_result - void tasks have no result to store
663  
    // No set_winner_result - void tasks have no result to store
674  
};
664  
};
675  

665  

676  
/** Launches all runners concurrently; see await_suspend for lifetime concerns. */
666  
/** Launches all runners concurrently; see await_suspend for lifetime concerns. */
677  
template<IoAwaitableRange Range>
667  
template<IoAwaitableRange Range>
678  
class when_any_homogeneous_launcher
668  
class when_any_homogeneous_launcher
679  
{
669  
{
680  
    using Awaitable = std::ranges::range_value_t<Range>;
670  
    using Awaitable = std::ranges::range_value_t<Range>;
681  
    using T = awaitable_result_t<Awaitable>;
671  
    using T = awaitable_result_t<Awaitable>;
682  

672  

683  
    Range* range_;
673  
    Range* range_;
684  
    when_any_homogeneous_state<T>* state_;
674  
    when_any_homogeneous_state<T>* state_;
685  

675  

686  
public:
676  
public:
687  
    when_any_homogeneous_launcher(
677  
    when_any_homogeneous_launcher(
688  
        Range* range,
678  
        Range* range,
689  
        when_any_homogeneous_state<T>* state)
679  
        when_any_homogeneous_state<T>* state)
690  
        : range_(range)
680  
        : range_(range)
691  
        , state_(state)
681  
        , state_(state)
692  
    {
682  
    {
693  
    }
683  
    }
694  

684  

695  
    bool await_ready() const noexcept
685  
    bool await_ready() const noexcept
696  
    {
686  
    {
697  
        return std::ranges::empty(*range_);
687  
        return std::ranges::empty(*range_);
698  
    }
688  
    }
699  

689  

700  
    /** CRITICAL: If the last task finishes synchronously, parent resumes and
690  
    /** CRITICAL: If the last task finishes synchronously, parent resumes and
701  
        destroys this object before await_suspend returns. Must not reference
691  
        destroys this object before await_suspend returns. Must not reference
702  
        `this` after dispatching begins.
692  
        `this` after dispatching begins.
703  

693  

704  
        Two-phase approach:
694  
        Two-phase approach:
705  
        1. Create all runners (safe - no dispatch yet)
695  
        1. Create all runners (safe - no dispatch yet)
706  
        2. Dispatch all runners (any may complete synchronously)
696  
        2. Dispatch all runners (any may complete synchronously)
707  
    */
697  
    */
708  
    std::coroutine_handle<> await_suspend(std::coroutine_handle<> continuation, io_env const* caller_env)
698  
    std::coroutine_handle<> await_suspend(std::coroutine_handle<> continuation, io_env const* caller_env)
709  
    {
699  
    {
710  
        state_->core_.continuation_ = continuation;
700  
        state_->core_.continuation_ = continuation;
711  
        state_->core_.caller_env_ = caller_env;
701  
        state_->core_.caller_env_ = caller_env;
712  

702  

713  
        if(caller_env->stop_token.stop_possible())
703  
        if(caller_env->stop_token.stop_possible())
714  
        {
704  
        {
715  
            state_->core_.parent_stop_callback_.emplace(
705  
            state_->core_.parent_stop_callback_.emplace(
716  
                caller_env->stop_token,
706  
                caller_env->stop_token,
717  
                when_any_core::stop_callback_fn{&state_->core_.stop_source_});
707  
                when_any_core::stop_callback_fn{&state_->core_.stop_source_});
718  

708  

719  
            if(caller_env->stop_token.stop_requested())
709  
            if(caller_env->stop_token.stop_requested())
720  
                state_->core_.stop_source_.request_stop();
710  
                state_->core_.stop_source_.request_stop();
721  
        }
711  
        }
722  

712  

723  
        auto token = state_->core_.stop_source_.get_token();
713  
        auto token = state_->core_.stop_source_.get_token();
724  

714  

725  
        // Phase 1: Create all runners without dispatching.
715  
        // Phase 1: Create all runners without dispatching.
726  
        // This iterates over *range_ safely because no runners execute yet.
716  
        // This iterates over *range_ safely because no runners execute yet.
727  
        std::size_t index = 0;
717  
        std::size_t index = 0;
728  
        for(auto&& a : *range_)
718  
        for(auto&& a : *range_)
729  
        {
719  
        {
730  
            auto runner = make_when_any_runner(
720  
            auto runner = make_when_any_runner(
731  
                std::move(a), state_, index);
721  
                std::move(a), state_, index);
732  

722  

733  
            auto h = runner.release();
723  
            auto h = runner.release();
734  
            h.promise().state_ = state_;
724  
            h.promise().state_ = state_;
735  
            h.promise().index_ = index;
725  
            h.promise().index_ = index;
736  
            h.promise().env_ = io_env{caller_env->executor, token, caller_env->frame_allocator};
726  
            h.promise().env_ = io_env{caller_env->executor, token, caller_env->frame_allocator};
737  

727  

738  
            state_->runner_handles_[index] = std::coroutine_handle<>{h};
728  
            state_->runner_handles_[index] = std::coroutine_handle<>{h};
739  
            ++index;
729  
            ++index;
740  
        }
730  
        }
741  

731  

742  
        // Phase 2: Post all runners. Any may complete synchronously.
732  
        // Phase 2: Post all runners. Any may complete synchronously.
743  
        // After last post, state_ and this may be destroyed.
733  
        // After last post, state_ and this may be destroyed.
744  
        // Use raw pointer/count captured before posting.
734  
        // Use raw pointer/count captured before posting.
745  
        std::coroutine_handle<>* handles = state_->runner_handles_.data();
735  
        std::coroutine_handle<>* handles = state_->runner_handles_.data();
746  
        std::size_t count = state_->runner_handles_.size();
736  
        std::size_t count = state_->runner_handles_.size();
747  
        for(std::size_t i = 0; i < count; ++i)
737  
        for(std::size_t i = 0; i < count; ++i)
748  
            caller_env->executor.post(handles[i]);
738  
            caller_env->executor.post(handles[i]);
749  

739  

750  
        return std::noop_coroutine();
740  
        return std::noop_coroutine();
751  
    }
741  
    }
752  

742  

753  
    void await_resume() const noexcept
743  
    void await_resume() const noexcept
754  
    {
744  
    {
755  
    }
745  
    }
756  
};
746  
};
757  

747  

758  
} // namespace detail
748  
} // namespace detail
759  

749  

760  
/** Wait for the first awaitable to complete (range overload).
750  
/** Wait for the first awaitable to complete (range overload).
761  

751  

762  
    Races a range of awaitables with the same result type. Accepts any
752  
    Races a range of awaitables with the same result type. Accepts any
763  
    sized input range of IoAwaitable types, enabling use with arrays,
753  
    sized input range of IoAwaitable types, enabling use with arrays,
764  
    spans, or custom containers.
754  
    spans, or custom containers.
765  

755  

766  
    @par Suspends
756  
    @par Suspends
767  
    The calling coroutine suspends when co_await is invoked. All awaitables
757  
    The calling coroutine suspends when co_await is invoked. All awaitables
768  
    in the range are launched concurrently and execute in parallel. The
758  
    in the range are launched concurrently and execute in parallel. The
769  
    coroutine resumes only after all awaitables have completed, even though
759  
    coroutine resumes only after all awaitables have completed, even though
770  
    the winner is determined by the first to finish.
760  
    the winner is determined by the first to finish.
771  

761  

772  
    @par Completion Conditions
762  
    @par Completion Conditions
773  
    @li Winner is determined when the first awaitable completes (success or exception)
763  
    @li Winner is determined when the first awaitable completes (success or exception)
774  
    @li Only one task can claim winner status via atomic compare-exchange
764  
    @li Only one task can claim winner status via atomic compare-exchange
775  
    @li Once a winner exists, stop is requested for all remaining siblings
765  
    @li Once a winner exists, stop is requested for all remaining siblings
776  
    @li Parent coroutine resumes only after all siblings acknowledge completion
766  
    @li Parent coroutine resumes only after all siblings acknowledge completion
777  
    @li The winner's index and result are returned; if the winner threw, the exception is rethrown
767  
    @li The winner's index and result are returned; if the winner threw, the exception is rethrown
778  

768  

779  
    @par Cancellation Semantics
769  
    @par Cancellation Semantics
780  
    Cancellation is supported via stop_token propagated through the
770  
    Cancellation is supported via stop_token propagated through the
781  
    IoAwaitable protocol:
771  
    IoAwaitable protocol:
782  
    @li Each child awaitable receives a stop_token derived from a shared stop_source
772  
    @li Each child awaitable receives a stop_token derived from a shared stop_source
783  
    @li When the parent's stop token is activated, the stop is forwarded to all children
773  
    @li When the parent's stop token is activated, the stop is forwarded to all children
784  
    @li When a winner is determined, stop_source_.request_stop() is called immediately
774  
    @li When a winner is determined, stop_source_.request_stop() is called immediately
785  
    @li Siblings must handle cancellation gracefully and complete before parent resumes
775  
    @li Siblings must handle cancellation gracefully and complete before parent resumes
786  
    @li Stop requests are cooperative; tasks must check and respond to them
776  
    @li Stop requests are cooperative; tasks must check and respond to them
787  

777  

788  
    @par Concurrency/Overlap
778  
    @par Concurrency/Overlap
789  
    All awaitables are launched concurrently before any can complete.
779  
    All awaitables are launched concurrently before any can complete.
790  
    The launcher iterates through the range, starting each task on the
780  
    The launcher iterates through the range, starting each task on the
791  
    caller's executor. Tasks may execute in parallel on multi-threaded
781  
    caller's executor. Tasks may execute in parallel on multi-threaded
792  
    executors or interleave on single-threaded executors. There is no
782  
    executors or interleave on single-threaded executors. There is no
793  
    guaranteed ordering of task completion.
783  
    guaranteed ordering of task completion.
794  

784  

795  
    @par Notable Error Conditions
785  
    @par Notable Error Conditions
796  
    @li Empty range: throws std::invalid_argument immediately (not via co_return)
786  
    @li Empty range: throws std::invalid_argument immediately (not via co_return)
797  
    @li Winner exception: if the winning task threw, that exception is rethrown
787  
    @li Winner exception: if the winning task threw, that exception is rethrown
798  
    @li Non-winner exceptions: silently discarded (only winner's result matters)
788  
    @li Non-winner exceptions: silently discarded (only winner's result matters)
799  
    @li Cancellation: tasks may complete via cancellation without throwing
789  
    @li Cancellation: tasks may complete via cancellation without throwing
800  

790  

801  
    @par Example
791  
    @par Example
802  
    @code
792  
    @code
803  
    task<void> example() {
793  
    task<void> example() {
804  
        std::array<task<Response>, 3> requests = {
794  
        std::array<task<Response>, 3> requests = {
805  
            fetch_from_server(0),
795  
            fetch_from_server(0),
806  
            fetch_from_server(1),
796  
            fetch_from_server(1),
807  
            fetch_from_server(2)
797  
            fetch_from_server(2)
808  
        };
798  
        };
809  

799  

810  
        auto [index, response] = co_await when_any(std::move(requests));
800  
        auto [index, response] = co_await when_any(std::move(requests));
811  
    }
801  
    }
812  
    @endcode
802  
    @endcode
813  

803  

814  
    @par Example with Vector
804  
    @par Example with Vector
815  
    @code
805  
    @code
816  
    task<Response> fetch_fastest(std::vector<Server> const& servers) {
806  
    task<Response> fetch_fastest(std::vector<Server> const& servers) {
817  
        std::vector<task<Response>> requests;
807  
        std::vector<task<Response>> requests;
818  
        for (auto const& server : servers)
808  
        for (auto const& server : servers)
819  
            requests.push_back(fetch_from(server));
809  
            requests.push_back(fetch_from(server));
820  

810  

821  
        auto [index, response] = co_await when_any(std::move(requests));
811  
        auto [index, response] = co_await when_any(std::move(requests));
822  
        co_return response;
812  
        co_return response;
823  
    }
813  
    }
824  
    @endcode
814  
    @endcode
825  

815  

826  
    @tparam R Range type satisfying IoAwaitableRange.
816  
    @tparam R Range type satisfying IoAwaitableRange.
827  
    @param awaitables Range of awaitables to race concurrently (must not be empty).
817  
    @param awaitables Range of awaitables to race concurrently (must not be empty).
828  
    @return A task yielding a pair of (winner_index, result).
818  
    @return A task yielding a pair of (winner_index, result).
829  

819  

830  
    @throws std::invalid_argument if range is empty (thrown before coroutine suspends).
820  
    @throws std::invalid_argument if range is empty (thrown before coroutine suspends).
831  
    @throws Rethrows the winner's exception if the winning task threw an exception.
821  
    @throws Rethrows the winner's exception if the winning task threw an exception.
832  

822  

833  
    @par Remarks
823  
    @par Remarks
834  
    Elements are moved from the range; for lvalue ranges, the original
824  
    Elements are moved from the range; for lvalue ranges, the original
835  
    container will have moved-from elements after this call. The range
825  
    container will have moved-from elements after this call. The range
836  
    is moved onto the coroutine frame to ensure lifetime safety. Unlike
826  
    is moved onto the coroutine frame to ensure lifetime safety. Unlike
837  
    the variadic overload, no variant wrapper is needed since all tasks
827  
    the variadic overload, no variant wrapper is needed since all tasks
838  
    share the same return type.
828  
    share the same return type.
839  

829  

840  
    @see when_any, IoAwaitableRange
830  
    @see when_any, IoAwaitableRange
841  
*/
831  
*/
842  
template<IoAwaitableRange R>
832  
template<IoAwaitableRange R>
843  
    requires (!std::is_void_v<awaitable_result_t<std::ranges::range_value_t<R>>>)
833  
    requires (!std::is_void_v<awaitable_result_t<std::ranges::range_value_t<R>>>)
844  
[[nodiscard]] auto when_any(R&& awaitables)
834  
[[nodiscard]] auto when_any(R&& awaitables)
845  
    -> task<std::pair<std::size_t, awaitable_result_t<std::ranges::range_value_t<R>>>>
835  
    -> task<std::pair<std::size_t, awaitable_result_t<std::ranges::range_value_t<R>>>>
846  
{
836  
{
847  
    using Awaitable = std::ranges::range_value_t<R>;
837  
    using Awaitable = std::ranges::range_value_t<R>;
848  
    using T = awaitable_result_t<Awaitable>;
838  
    using T = awaitable_result_t<Awaitable>;
849  
    using result_type = std::pair<std::size_t, T>;
839  
    using result_type = std::pair<std::size_t, T>;
850  
    using OwnedRange = std::remove_cvref_t<R>;
840  
    using OwnedRange = std::remove_cvref_t<R>;
851  

841  

852  
    auto count = std::ranges::size(awaitables);
842  
    auto count = std::ranges::size(awaitables);
853  
    if(count == 0)
843  
    if(count == 0)
854  
        throw std::invalid_argument("when_any requires at least one awaitable");
844  
        throw std::invalid_argument("when_any requires at least one awaitable");
855  

845  

856  
    // Move/copy range onto coroutine frame to ensure lifetime
846  
    // Move/copy range onto coroutine frame to ensure lifetime
857  
    OwnedRange owned_awaitables = std::forward<R>(awaitables);
847  
    OwnedRange owned_awaitables = std::forward<R>(awaitables);
858  

848  

859  
    detail::when_any_homogeneous_state<T> state(count);
849  
    detail::when_any_homogeneous_state<T> state(count);
860  

850  

861  
    co_await detail::when_any_homogeneous_launcher<OwnedRange>(&owned_awaitables, &state);
851  
    co_await detail::when_any_homogeneous_launcher<OwnedRange>(&owned_awaitables, &state);
862  

852  

863  
    if(state.core_.winner_exception_)
853  
    if(state.core_.winner_exception_)
864  
        std::rethrow_exception(state.core_.winner_exception_);
854  
        std::rethrow_exception(state.core_.winner_exception_);
865  

855  

866  
    co_return result_type{state.core_.winner_index_, std::move(*state.result_)};
856  
    co_return result_type{state.core_.winner_index_, std::move(*state.result_)};
867  
}
857  
}
868  

858  

869  
/** Wait for the first awaitable to complete (void range overload).
859  
/** Wait for the first awaitable to complete (void range overload).
870  

860  

871  
    Races a range of void-returning awaitables. Since void awaitables have
861  
    Races a range of void-returning awaitables. Since void awaitables have
872  
    no result value, only the winner's index is returned.
862  
    no result value, only the winner's index is returned.
873  

863  

874  
    @par Suspends
864  
    @par Suspends
875  
    The calling coroutine suspends when co_await is invoked. All awaitables
865  
    The calling coroutine suspends when co_await is invoked. All awaitables
876  
    in the range are launched concurrently and execute in parallel. The
866  
    in the range are launched concurrently and execute in parallel. The
877  
    coroutine resumes only after all awaitables have completed, even though
867  
    coroutine resumes only after all awaitables have completed, even though
878  
    the winner is determined by the first to finish.
868  
    the winner is determined by the first to finish.
879  

869  

880  
    @par Completion Conditions
870  
    @par Completion Conditions
881  
    @li Winner is determined when the first awaitable completes (success or exception)
871  
    @li Winner is determined when the first awaitable completes (success or exception)
882  
    @li Only one task can claim winner status via atomic compare-exchange
872  
    @li Only one task can claim winner status via atomic compare-exchange
883  
    @li Once a winner exists, stop is requested for all remaining siblings
873  
    @li Once a winner exists, stop is requested for all remaining siblings
884  
    @li Parent coroutine resumes only after all siblings acknowledge completion
874  
    @li Parent coroutine resumes only after all siblings acknowledge completion
885  
    @li The winner's index is returned; if the winner threw, the exception is rethrown
875  
    @li The winner's index is returned; if the winner threw, the exception is rethrown
886  

876  

887  
    @par Cancellation Semantics
877  
    @par Cancellation Semantics
888  
    Cancellation is supported via stop_token propagated through the
878  
    Cancellation is supported via stop_token propagated through the
889  
    IoAwaitable protocol:
879  
    IoAwaitable protocol:
890  
    @li Each child awaitable receives a stop_token derived from a shared stop_source
880  
    @li Each child awaitable receives a stop_token derived from a shared stop_source
891  
    @li When the parent's stop token is activated, the stop is forwarded to all children
881  
    @li When the parent's stop token is activated, the stop is forwarded to all children
892  
    @li When a winner is determined, stop_source_.request_stop() is called immediately
882  
    @li When a winner is determined, stop_source_.request_stop() is called immediately
893  
    @li Siblings must handle cancellation gracefully and complete before parent resumes
883  
    @li Siblings must handle cancellation gracefully and complete before parent resumes
894  
    @li Stop requests are cooperative; tasks must check and respond to them
884  
    @li Stop requests are cooperative; tasks must check and respond to them
895  

885  

896  
    @par Concurrency/Overlap
886  
    @par Concurrency/Overlap
897  
    All awaitables are launched concurrently before any can complete.
887  
    All awaitables are launched concurrently before any can complete.
898  
    The launcher iterates through the range, starting each task on the
888  
    The launcher iterates through the range, starting each task on the
899  
    caller's executor. Tasks may execute in parallel on multi-threaded
889  
    caller's executor. Tasks may execute in parallel on multi-threaded
900  
    executors or interleave on single-threaded executors. There is no
890  
    executors or interleave on single-threaded executors. There is no
901  
    guaranteed ordering of task completion.
891  
    guaranteed ordering of task completion.
902  

892  

903  
    @par Notable Error Conditions
893  
    @par Notable Error Conditions
904  
    @li Empty range: throws std::invalid_argument immediately (not via co_return)
894  
    @li Empty range: throws std::invalid_argument immediately (not via co_return)
905  
    @li Winner exception: if the winning task threw, that exception is rethrown
895  
    @li Winner exception: if the winning task threw, that exception is rethrown
906  
    @li Non-winner exceptions: silently discarded (only winner's result matters)
896  
    @li Non-winner exceptions: silently discarded (only winner's result matters)
907  
    @li Cancellation: tasks may complete via cancellation without throwing
897  
    @li Cancellation: tasks may complete via cancellation without throwing
908  

898  

909  
    @par Example
899  
    @par Example
910  
    @code
900  
    @code
911  
    task<void> example() {
901  
    task<void> example() {
912  
        std::vector<task<void>> tasks;
902  
        std::vector<task<void>> tasks;
913  
        for (int i = 0; i < 5; ++i)
903  
        for (int i = 0; i < 5; ++i)
914  
            tasks.push_back(background_work(i));
904  
            tasks.push_back(background_work(i));
915  

905  

916  
        std::size_t winner = co_await when_any(std::move(tasks));
906  
        std::size_t winner = co_await when_any(std::move(tasks));
917  
        // winner is the index of the first task to complete
907  
        // winner is the index of the first task to complete
918  
    }
908  
    }
919  
    @endcode
909  
    @endcode
920  

910  

921  
    @par Example with Timeout
911  
    @par Example with Timeout
922  
    @code
912  
    @code
923  
    task<void> with_timeout() {
913  
    task<void> with_timeout() {
924  
        std::vector<task<void>> tasks;
914  
        std::vector<task<void>> tasks;
925  
        tasks.push_back(long_running_operation());
915  
        tasks.push_back(long_running_operation());
926  
        tasks.push_back(delay(std::chrono::seconds(5)));
916  
        tasks.push_back(delay(std::chrono::seconds(5)));
927  

917  

928  
        std::size_t winner = co_await when_any(std::move(tasks));
918  
        std::size_t winner = co_await when_any(std::move(tasks));
929  
        if (winner == 1) {
919  
        if (winner == 1) {
930  
            // Timeout occurred
920  
            // Timeout occurred
931  
        }
921  
        }
932  
    }
922  
    }
933  
    @endcode
923  
    @endcode
934  

924  

935  
    @tparam R Range type satisfying IoAwaitableRange with void result.
925  
    @tparam R Range type satisfying IoAwaitableRange with void result.
936  
    @param awaitables Range of void awaitables to race concurrently (must not be empty).
926  
    @param awaitables Range of void awaitables to race concurrently (must not be empty).
937  
    @return A task yielding the winner's index (zero-based).
927  
    @return A task yielding the winner's index (zero-based).
938  

928  

939  
    @throws std::invalid_argument if range is empty (thrown before coroutine suspends).
929  
    @throws std::invalid_argument if range is empty (thrown before coroutine suspends).
940  
    @throws Rethrows the winner's exception if the winning task threw an exception.
930  
    @throws Rethrows the winner's exception if the winning task threw an exception.
941  

931  

942  
    @par Remarks
932  
    @par Remarks
943  
    Elements are moved from the range; for lvalue ranges, the original
933  
    Elements are moved from the range; for lvalue ranges, the original
944  
    container will have moved-from elements after this call. The range
934  
    container will have moved-from elements after this call. The range
945  
    is moved onto the coroutine frame to ensure lifetime safety. Unlike
935  
    is moved onto the coroutine frame to ensure lifetime safety. Unlike
946  
    the non-void overload, no result storage is needed since void tasks
936  
    the non-void overload, no result storage is needed since void tasks
947  
    produce no value.
937  
    produce no value.
948  

938  

949  
    @see when_any, IoAwaitableRange
939  
    @see when_any, IoAwaitableRange
950  
*/
940  
*/
951  
template<IoAwaitableRange R>
941  
template<IoAwaitableRange R>
952  
    requires std::is_void_v<awaitable_result_t<std::ranges::range_value_t<R>>>
942  
    requires std::is_void_v<awaitable_result_t<std::ranges::range_value_t<R>>>
953  
[[nodiscard]] auto when_any(R&& awaitables) -> task<std::size_t>
943  
[[nodiscard]] auto when_any(R&& awaitables) -> task<std::size_t>
954  
{
944  
{
955  
    using OwnedRange = std::remove_cvref_t<R>;
945  
    using OwnedRange = std::remove_cvref_t<R>;
956  

946  

957  
    auto count = std::ranges::size(awaitables);
947  
    auto count = std::ranges::size(awaitables);
958  
    if(count == 0)
948  
    if(count == 0)
959  
        throw std::invalid_argument("when_any requires at least one awaitable");
949  
        throw std::invalid_argument("when_any requires at least one awaitable");
960  

950  

961  
    // Move/copy range onto coroutine frame to ensure lifetime
951  
    // Move/copy range onto coroutine frame to ensure lifetime
962  
    OwnedRange owned_awaitables = std::forward<R>(awaitables);
952  
    OwnedRange owned_awaitables = std::forward<R>(awaitables);
963  

953  

964  
    detail::when_any_homogeneous_state<void> state(count);
954  
    detail::when_any_homogeneous_state<void> state(count);
965  

955  

966  
    co_await detail::when_any_homogeneous_launcher<OwnedRange>(&owned_awaitables, &state);
956  
    co_await detail::when_any_homogeneous_launcher<OwnedRange>(&owned_awaitables, &state);
967  

957  

968  
    if(state.core_.winner_exception_)
958  
    if(state.core_.winner_exception_)
969  
        std::rethrow_exception(state.core_.winner_exception_);
959  
        std::rethrow_exception(state.core_.winner_exception_);
970  

960  

971  
    co_return state.core_.winner_index_;
961  
    co_return state.core_.winner_index_;
972  
}
962  
}
973  

963  

974  
} // namespace capy
964  
} // namespace capy
975  
} // namespace boost
965  
} // namespace boost
976  

966  

977  
#endif
967  
#endif