1  
//
1  
//
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
2  
// Copyright (c) 2025 Vinnie Falco (vinnie.falco@gmail.com)
3  
// Copyright (c) 2026 Steve Gerbino
3  
// Copyright (c) 2026 Steve Gerbino
4  
//
4  
//
5  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
5  
// Distributed under the Boost Software License, Version 1.0. (See accompanying
6  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
6  
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
7  
//
7  
//
8  
// Official repository: https://github.com/cppalliance/corosio
8  
// Official repository: https://github.com/cppalliance/corosio
9  
//
9  
//
10  

10  

11  
#ifndef BOOST_COROSIO_DETAIL_TIMER_SERVICE_HPP
11  
#ifndef BOOST_COROSIO_DETAIL_TIMER_SERVICE_HPP
12  
#define BOOST_COROSIO_DETAIL_TIMER_SERVICE_HPP
12  
#define BOOST_COROSIO_DETAIL_TIMER_SERVICE_HPP
13  

13  

14  
#include <boost/corosio/timer.hpp>
14  
#include <boost/corosio/timer.hpp>
15  
#include <boost/corosio/io_context.hpp>
15  
#include <boost/corosio/io_context.hpp>
16  
#include <boost/corosio/detail/scheduler_op.hpp>
16  
#include <boost/corosio/detail/scheduler_op.hpp>
17  
#include <boost/corosio/native/native_scheduler.hpp>
17  
#include <boost/corosio/native/native_scheduler.hpp>
18  
#include <boost/corosio/detail/intrusive.hpp>
18  
#include <boost/corosio/detail/intrusive.hpp>
19  
#include <boost/corosio/detail/thread_local_ptr.hpp>
19  
#include <boost/corosio/detail/thread_local_ptr.hpp>
20  
#include <boost/capy/error.hpp>
20  
#include <boost/capy/error.hpp>
21  
#include <boost/capy/ex/execution_context.hpp>
21  
#include <boost/capy/ex/execution_context.hpp>
22  
#include <boost/capy/ex/executor_ref.hpp>
22  
#include <boost/capy/ex/executor_ref.hpp>
23  
#include <system_error>
23  
#include <system_error>
24  

24  

25  
#include <atomic>
25  
#include <atomic>
26  
#include <chrono>
26  
#include <chrono>
27  
#include <coroutine>
27  
#include <coroutine>
28  
#include <cstddef>
28  
#include <cstddef>
29  
#include <limits>
29  
#include <limits>
30  
#include <mutex>
30  
#include <mutex>
31  
#include <optional>
31  
#include <optional>
32  
#include <stop_token>
32  
#include <stop_token>
33  
#include <utility>
33  
#include <utility>
34  
#include <vector>
34  
#include <vector>
35  

35  

36  
namespace boost::corosio::detail {
36  
namespace boost::corosio::detail {
37  

37  

38  
struct scheduler;
38  
struct scheduler;
39  

39  

40  
/*
40  
/*
41  
    Timer Service
41  
    Timer Service
42  
    =============
42  
    =============
43  

43  

44  
    Data Structures
44  
    Data Structures
45  
    ---------------
45  
    ---------------
46  
    waiter_node holds per-waiter state: coroutine handle, executor,
46  
    waiter_node holds per-waiter state: coroutine handle, executor,
47  
    error output, stop_token, embedded completion_op. Each concurrent
47  
    error output, stop_token, embedded completion_op. Each concurrent
48  
    co_await t.wait() allocates one waiter_node.
48  
    co_await t.wait() allocates one waiter_node.
49  

49  

50  
    timer_service::implementation holds per-timer state: expiry,
50  
    timer_service::implementation holds per-timer state: expiry,
51  
    heap index, and an intrusive_list of waiter_nodes. Multiple
51  
    heap index, and an intrusive_list of waiter_nodes. Multiple
52  
    coroutines can wait on the same timer simultaneously.
52  
    coroutines can wait on the same timer simultaneously.
53  

53  

54  
    timer_service owns a min-heap of active timers, a free list
54  
    timer_service owns a min-heap of active timers, a free list
55  
    of recycled impls, and a free list of recycled waiter_nodes. The
55  
    of recycled impls, and a free list of recycled waiter_nodes. The
56  
    heap is ordered by expiry time; the scheduler queries
56  
    heap is ordered by expiry time; the scheduler queries
57  
    nearest_expiry() to set the epoll/timerfd timeout.
57  
    nearest_expiry() to set the epoll/timerfd timeout.
58  

58  

59  
    Optimization Strategy
59  
    Optimization Strategy
60  
    ---------------------
60  
    ---------------------
61  
    1. Deferred heap insertion — expires_after() stores the expiry
61  
    1. Deferred heap insertion — expires_after() stores the expiry
62  
       but does not insert into the heap. Insertion happens in wait().
62  
       but does not insert into the heap. Insertion happens in wait().
63  
    2. Thread-local impl cache — single-slot per-thread cache.
63  
    2. Thread-local impl cache — single-slot per-thread cache.
64  
    3. Embedded completion_op — eliminates heap allocation per fire/cancel.
64  
    3. Embedded completion_op — eliminates heap allocation per fire/cancel.
65  
    4. Cached nearest expiry — atomic avoids mutex in nearest_expiry().
65  
    4. Cached nearest expiry — atomic avoids mutex in nearest_expiry().
66  
    5. might_have_pending_waits_ flag — skips lock when no wait issued.
66  
    5. might_have_pending_waits_ flag — skips lock when no wait issued.
67  
    6. Thread-local waiter cache — single-slot per-thread cache.
67  
    6. Thread-local waiter cache — single-slot per-thread cache.
68  

68  

69  
    Concurrency
69  
    Concurrency
70  
    -----------
70  
    -----------
71  
    stop_token callbacks can fire from any thread. The impl_
71  
    stop_token callbacks can fire from any thread. The impl_
72  
    pointer on waiter_node is used as a "still in list" marker.
72  
    pointer on waiter_node is used as a "still in list" marker.
73  
*/
73  
*/
74  

74  

75  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node;
75  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node;
76  

76  

77  
inline void timer_service_invalidate_cache() noexcept;
77  
inline void timer_service_invalidate_cache() noexcept;
78  

78  

79  
// timer_service class body — member function definitions are
79  
// timer_service class body — member function definitions are
80  
// out-of-class (after implementation and waiter_node are complete)
80  
// out-of-class (after implementation and waiter_node are complete)
81  
class BOOST_COROSIO_DECL timer_service final
81  
class BOOST_COROSIO_DECL timer_service final
82  
    : public capy::execution_context::service
82  
    : public capy::execution_context::service
83  
    , public io_object::io_service
83  
    , public io_object::io_service
84  
{
84  
{
85  
public:
85  
public:
86  
    using clock_type = std::chrono::steady_clock;
86  
    using clock_type = std::chrono::steady_clock;
87  
    using time_point = clock_type::time_point;
87  
    using time_point = clock_type::time_point;
88  

88  

89  
    /// Type-erased callback for earliest-expiry-changed notifications.
89  
    /// Type-erased callback for earliest-expiry-changed notifications.
90  
    class callback
90  
    class callback
91  
    {
91  
    {
92  
        void* ctx_         = nullptr;
92  
        void* ctx_         = nullptr;
93  
        void (*fn_)(void*) = nullptr;
93  
        void (*fn_)(void*) = nullptr;
94  

94  

95  
    public:
95  
    public:
96  
        /// Construct an empty callback.
96  
        /// Construct an empty callback.
97  
        callback() = default;
97  
        callback() = default;
98  

98  

99  
        /// Construct a callback with the given context and function.
99  
        /// Construct a callback with the given context and function.
100  
        callback(void* ctx, void (*fn)(void*)) noexcept : ctx_(ctx), fn_(fn) {}
100  
        callback(void* ctx, void (*fn)(void*)) noexcept : ctx_(ctx), fn_(fn) {}
101  

101  

102  
        /// Return true if the callback is non-empty.
102  
        /// Return true if the callback is non-empty.
103  
        explicit operator bool() const noexcept
103  
        explicit operator bool() const noexcept
104  
        {
104  
        {
105  
            return fn_ != nullptr;
105  
            return fn_ != nullptr;
106  
        }
106  
        }
107  

107  

108  
        /// Invoke the callback.
108  
        /// Invoke the callback.
109  
        void operator()() const
109  
        void operator()() const
110  
        {
110  
        {
111  
            if (fn_)
111  
            if (fn_)
112  
                fn_(ctx_);
112  
                fn_(ctx_);
113  
        }
113  
        }
114  
    };
114  
    };
115  

115  

116  
    struct implementation;
116  
    struct implementation;
117  

117  

118  
private:
118  
private:
119  
    struct heap_entry
119  
    struct heap_entry
120  
    {
120  
    {
121  
        time_point time_;
121  
        time_point time_;
122  
        implementation* timer_;
122  
        implementation* timer_;
123  
    };
123  
    };
124  

124  

125  
    scheduler* sched_ = nullptr;
125  
    scheduler* sched_ = nullptr;
126  
    mutable std::mutex mutex_;
126  
    mutable std::mutex mutex_;
127  
    std::vector<heap_entry> heap_;
127  
    std::vector<heap_entry> heap_;
128  
    implementation* free_list_     = nullptr;
128  
    implementation* free_list_     = nullptr;
129  
    waiter_node* waiter_free_list_ = nullptr;
129  
    waiter_node* waiter_free_list_ = nullptr;
130  
    callback on_earliest_changed_;
130  
    callback on_earliest_changed_;
131  
    bool shutting_down_ = false;
131  
    bool shutting_down_ = false;
132  
    // Avoids mutex in nearest_expiry() and empty()
132  
    // Avoids mutex in nearest_expiry() and empty()
133  
    mutable std::atomic<std::int64_t> cached_nearest_ns_{
133  
    mutable std::atomic<std::int64_t> cached_nearest_ns_{
134  
        (std::numeric_limits<std::int64_t>::max)()};
134  
        (std::numeric_limits<std::int64_t>::max)()};
135  

135  

136  
public:
136  
public:
137  
    /// Construct the timer service bound to a scheduler.
137  
    /// Construct the timer service bound to a scheduler.
138  
    inline timer_service(capy::execution_context&, scheduler& sched)
138  
    inline timer_service(capy::execution_context&, scheduler& sched)
139  
        : sched_(&sched)
139  
        : sched_(&sched)
140  
    {
140  
    {
141  
    }
141  
    }
142  

142  

143  
    /// Return the associated scheduler.
143  
    /// Return the associated scheduler.
144  
    inline scheduler& get_scheduler() noexcept
144  
    inline scheduler& get_scheduler() noexcept
145  
    {
145  
    {
146  
        return *sched_;
146  
        return *sched_;
147  
    }
147  
    }
148  

148  

149  
    /// Destroy the timer service.
149  
    /// Destroy the timer service.
150  
    ~timer_service() override = default;
150  
    ~timer_service() override = default;
151  

151  

152  
    timer_service(timer_service const&)            = delete;
152  
    timer_service(timer_service const&)            = delete;
153  
    timer_service& operator=(timer_service const&) = delete;
153  
    timer_service& operator=(timer_service const&) = delete;
154  

154  

155  
    /// Register a callback invoked when the earliest expiry changes.
155  
    /// Register a callback invoked when the earliest expiry changes.
156  
    inline void set_on_earliest_changed(callback cb)
156  
    inline void set_on_earliest_changed(callback cb)
157  
    {
157  
    {
158  
        on_earliest_changed_ = cb;
158  
        on_earliest_changed_ = cb;
159  
    }
159  
    }
160  

160  

161  
    /// Return true if no timers are in the heap.
161  
    /// Return true if no timers are in the heap.
162  
    inline bool empty() const noexcept
162  
    inline bool empty() const noexcept
163  
    {
163  
    {
164  
        return cached_nearest_ns_.load(std::memory_order_acquire) ==
164  
        return cached_nearest_ns_.load(std::memory_order_acquire) ==
165  
            (std::numeric_limits<std::int64_t>::max)();
165  
            (std::numeric_limits<std::int64_t>::max)();
166  
    }
166  
    }
167  

167  

168  
    /// Return the nearest timer expiry without acquiring the mutex.
168  
    /// Return the nearest timer expiry without acquiring the mutex.
169  
    inline time_point nearest_expiry() const noexcept
169  
    inline time_point nearest_expiry() const noexcept
170  
    {
170  
    {
171  
        auto ns = cached_nearest_ns_.load(std::memory_order_acquire);
171  
        auto ns = cached_nearest_ns_.load(std::memory_order_acquire);
172  
        return time_point(time_point::duration(ns));
172  
        return time_point(time_point::duration(ns));
173  
    }
173  
    }
174  

174  

175  
    /// Cancel all pending timers and free cached resources.
175  
    /// Cancel all pending timers and free cached resources.
176  
    inline void shutdown() override;
176  
    inline void shutdown() override;
177  

177  

178  
    /// Construct a new timer implementation.
178  
    /// Construct a new timer implementation.
179  
    inline io_object::implementation* construct() override;
179  
    inline io_object::implementation* construct() override;
180  

180  

181  
    /// Destroy a timer implementation, cancelling pending waiters.
181  
    /// Destroy a timer implementation, cancelling pending waiters.
182  
    inline void destroy(io_object::implementation* p) override;
182  
    inline void destroy(io_object::implementation* p) override;
183  

183  

184  
    /// Cancel and recycle a timer implementation.
184  
    /// Cancel and recycle a timer implementation.
185  
    inline void destroy_impl(implementation& impl);
185  
    inline void destroy_impl(implementation& impl);
186  

186  

187  
    /// Create or recycle a waiter node.
187  
    /// Create or recycle a waiter node.
188  
    inline waiter_node* create_waiter();
188  
    inline waiter_node* create_waiter();
189  

189  

190  
    /// Return a waiter node to the cache or free list.
190  
    /// Return a waiter node to the cache or free list.
191  
    inline void destroy_waiter(waiter_node* w);
191  
    inline void destroy_waiter(waiter_node* w);
192  

192  

193  
    /// Update the timer expiry, cancelling existing waiters.
193  
    /// Update the timer expiry, cancelling existing waiters.
194  
    inline std::size_t update_timer(implementation& impl, time_point new_time);
194  
    inline std::size_t update_timer(implementation& impl, time_point new_time);
195  

195  

196  
    /// Insert a waiter into the timer's waiter list and the heap.
196  
    /// Insert a waiter into the timer's waiter list and the heap.
197  
    inline void insert_waiter(implementation& impl, waiter_node* w);
197  
    inline void insert_waiter(implementation& impl, waiter_node* w);
198  

198  

199  
    /// Cancel all waiters on a timer.
199  
    /// Cancel all waiters on a timer.
200  
    inline std::size_t cancel_timer(implementation& impl);
200  
    inline std::size_t cancel_timer(implementation& impl);
201  

201  

202  
    /// Cancel a single waiter ( stop_token callback path ).
202  
    /// Cancel a single waiter ( stop_token callback path ).
203  
    inline void cancel_waiter(waiter_node* w);
203  
    inline void cancel_waiter(waiter_node* w);
204  

204  

205  
    /// Cancel one waiter on a timer.
205  
    /// Cancel one waiter on a timer.
206  
    inline std::size_t cancel_one_waiter(implementation& impl);
206  
    inline std::size_t cancel_one_waiter(implementation& impl);
207  

207  

208  
    /// Complete all waiters whose timers have expired.
208  
    /// Complete all waiters whose timers have expired.
209  
    inline std::size_t process_expired();
209  
    inline std::size_t process_expired();
210  

210  

211  
private:
211  
private:
212  
    inline void refresh_cached_nearest() noexcept
212  
    inline void refresh_cached_nearest() noexcept
213  
    {
213  
    {
214  
        auto ns = heap_.empty() ? (std::numeric_limits<std::int64_t>::max)()
214  
        auto ns = heap_.empty() ? (std::numeric_limits<std::int64_t>::max)()
215  
                                : heap_[0].time_.time_since_epoch().count();
215  
                                : heap_[0].time_.time_since_epoch().count();
216  
        cached_nearest_ns_.store(ns, std::memory_order_release);
216  
        cached_nearest_ns_.store(ns, std::memory_order_release);
217  
    }
217  
    }
218  

218  

219  
    inline void remove_timer_impl(implementation& impl);
219  
    inline void remove_timer_impl(implementation& impl);
220  
    inline void up_heap(std::size_t index);
220  
    inline void up_heap(std::size_t index);
221  
    inline void down_heap(std::size_t index);
221  
    inline void down_heap(std::size_t index);
222  
    inline void swap_heap(std::size_t i1, std::size_t i2);
222  
    inline void swap_heap(std::size_t i1, std::size_t i2);
223  
};
223  
};
224  

224  

225  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node
225  
struct BOOST_COROSIO_SYMBOL_VISIBLE waiter_node
226  
    : intrusive_list<waiter_node>::node
226  
    : intrusive_list<waiter_node>::node
227  
{
227  
{
228  
    // Embedded completion op — avoids heap allocation per fire/cancel
228  
    // Embedded completion op — avoids heap allocation per fire/cancel
229  
    struct completion_op final : scheduler_op
229  
    struct completion_op final : scheduler_op
230  
    {
230  
    {
231  
        waiter_node* waiter_ = nullptr;
231  
        waiter_node* waiter_ = nullptr;
232  

232  

233  
        static void do_complete(
233  
        static void do_complete(
234  
            void* owner, scheduler_op* base, std::uint32_t, std::uint32_t);
234  
            void* owner, scheduler_op* base, std::uint32_t, std::uint32_t);
235  

235  

236  
        completion_op() noexcept : scheduler_op(&do_complete) {}
236  
        completion_op() noexcept : scheduler_op(&do_complete) {}
237  

237  

238  
        void operator()() override;
238  
        void operator()() override;
239  
        void destroy() override;
239  
        void destroy() override;
240  
    };
240  
    };
241  

241  

242  
    // Per-waiter stop_token cancellation
242  
    // Per-waiter stop_token cancellation
243  
    struct canceller
243  
    struct canceller
244  
    {
244  
    {
245  
        waiter_node* waiter_;
245  
        waiter_node* waiter_;
246  
        void operator()() const;
246  
        void operator()() const;
247  
    };
247  
    };
248  

248  

249  
    // nullptr once removed from timer's waiter list (concurrency marker)
249  
    // nullptr once removed from timer's waiter list (concurrency marker)
250  
    timer_service::implementation* impl_ = nullptr;
250  
    timer_service::implementation* impl_ = nullptr;
251  
    timer_service* svc_                  = nullptr;
251  
    timer_service* svc_                  = nullptr;
252  
    std::coroutine_handle<> h_;
252  
    std::coroutine_handle<> h_;
253  
    capy::continuation* cont_            = nullptr;
253  
    capy::continuation* cont_            = nullptr;
254  
    capy::executor_ref d_;
254  
    capy::executor_ref d_;
255  
    std::error_code* ec_out_ = nullptr;
255  
    std::error_code* ec_out_ = nullptr;
256  
    std::stop_token token_;
256  
    std::stop_token token_;
257  
    std::optional<std::stop_callback<canceller>> stop_cb_;
257  
    std::optional<std::stop_callback<canceller>> stop_cb_;
258  
    completion_op op_;
258  
    completion_op op_;
259  
    std::error_code ec_value_;
259  
    std::error_code ec_value_;
260  
    waiter_node* next_free_ = nullptr;
260  
    waiter_node* next_free_ = nullptr;
261  

261  

262  
    waiter_node() noexcept
262  
    waiter_node() noexcept
263  
    {
263  
    {
264  
        op_.waiter_ = this;
264  
        op_.waiter_ = this;
265  
    }
265  
    }
266  
};
266  
};
267  

267  

268  
struct timer_service::implementation final : timer::implementation
268  
struct timer_service::implementation final : timer::implementation
269  
{
269  
{
270  
    using clock_type = std::chrono::steady_clock;
270  
    using clock_type = std::chrono::steady_clock;
271  
    using time_point = clock_type::time_point;
271  
    using time_point = clock_type::time_point;
272  
    using duration   = clock_type::duration;
272  
    using duration   = clock_type::duration;
273  

273  

274  
    timer_service* svc_ = nullptr;
274  
    timer_service* svc_ = nullptr;
275  
    intrusive_list<waiter_node> waiters_;
275  
    intrusive_list<waiter_node> waiters_;
276  

276  

277  
    // Free list linkage (reused when impl is on free_list)
277  
    // Free list linkage (reused when impl is on free_list)
278  
    implementation* next_free_ = nullptr;
278  
    implementation* next_free_ = nullptr;
279  

279  

280  
    inline explicit implementation(timer_service& svc) noexcept;
280  
    inline explicit implementation(timer_service& svc) noexcept;
281  

281  

282  
    inline std::coroutine_handle<> wait(
282  
    inline std::coroutine_handle<> wait(
283  
        std::coroutine_handle<>,
283  
        std::coroutine_handle<>,
284  
        capy::executor_ref,
284  
        capy::executor_ref,
285  
        std::stop_token,
285  
        std::stop_token,
286  
        std::error_code*,
286  
        std::error_code*,
287  
        capy::continuation*) override;
287  
        capy::continuation*) override;
288  
};
288  
};
289  

289  

290  
// Thread-local caches avoid hot-path mutex acquisitions:
290  
// Thread-local caches avoid hot-path mutex acquisitions:
291  
// 1. Impl cache — single-slot, validated by comparing svc_
291  
// 1. Impl cache — single-slot, validated by comparing svc_
292  
// 2. Waiter cache — single-slot, no service affinity
292  
// 2. Waiter cache — single-slot, no service affinity
293  
// All caches are cleared by timer_service_invalidate_cache() during shutdown.
293  
// All caches are cleared by timer_service_invalidate_cache() during shutdown.
294  

294  

295  
inline thread_local_ptr<timer_service::implementation> tl_cached_impl;
295  
inline thread_local_ptr<timer_service::implementation> tl_cached_impl;
296  
inline thread_local_ptr<waiter_node> tl_cached_waiter;
296  
inline thread_local_ptr<waiter_node> tl_cached_waiter;
297  

297  

298  
inline timer_service::implementation*
298  
inline timer_service::implementation*
299  
try_pop_tl_cache(timer_service* svc) noexcept
299  
try_pop_tl_cache(timer_service* svc) noexcept
300  
{
300  
{
301  
    auto* impl = tl_cached_impl.get();
301  
    auto* impl = tl_cached_impl.get();
302  
    if (impl)
302  
    if (impl)
303  
    {
303  
    {
304  
        tl_cached_impl.set(nullptr);
304  
        tl_cached_impl.set(nullptr);
305  
        if (impl->svc_ == svc)
305  
        if (impl->svc_ == svc)
306  
            return impl;
306  
            return impl;
307  
        // Stale impl from a destroyed service
307  
        // Stale impl from a destroyed service
308  
        delete impl;
308  
        delete impl;
309  
    }
309  
    }
310  
    return nullptr;
310  
    return nullptr;
311  
}
311  
}
312  

312  

313  
inline bool
313  
inline bool
314  
try_push_tl_cache(timer_service::implementation* impl) noexcept
314  
try_push_tl_cache(timer_service::implementation* impl) noexcept
315  
{
315  
{
316  
    if (!tl_cached_impl.get())
316  
    if (!tl_cached_impl.get())
317  
    {
317  
    {
318  
        tl_cached_impl.set(impl);
318  
        tl_cached_impl.set(impl);
319  
        return true;
319  
        return true;
320  
    }
320  
    }
321  
    return false;
321  
    return false;
322  
}
322  
}
323  

323  

324  
inline waiter_node*
324  
inline waiter_node*
325  
try_pop_waiter_tl_cache() noexcept
325  
try_pop_waiter_tl_cache() noexcept
326  
{
326  
{
327  
    auto* w = tl_cached_waiter.get();
327  
    auto* w = tl_cached_waiter.get();
328  
    if (w)
328  
    if (w)
329  
    {
329  
    {
330  
        tl_cached_waiter.set(nullptr);
330  
        tl_cached_waiter.set(nullptr);
331  
        return w;
331  
        return w;
332  
    }
332  
    }
333  
    return nullptr;
333  
    return nullptr;
334  
}
334  
}
335  

335  

336  
inline bool
336  
inline bool
337  
try_push_waiter_tl_cache(waiter_node* w) noexcept
337  
try_push_waiter_tl_cache(waiter_node* w) noexcept
338  
{
338  
{
339  
    if (!tl_cached_waiter.get())
339  
    if (!tl_cached_waiter.get())
340  
    {
340  
    {
341  
        tl_cached_waiter.set(w);
341  
        tl_cached_waiter.set(w);
342  
        return true;
342  
        return true;
343  
    }
343  
    }
344  
    return false;
344  
    return false;
345  
}
345  
}
346  

346  

347  
inline void
347  
inline void
348  
timer_service_invalidate_cache() noexcept
348  
timer_service_invalidate_cache() noexcept
349  
{
349  
{
350  
    delete tl_cached_impl.get();
350  
    delete tl_cached_impl.get();
351  
    tl_cached_impl.set(nullptr);
351  
    tl_cached_impl.set(nullptr);
352  

352  

353  
    delete tl_cached_waiter.get();
353  
    delete tl_cached_waiter.get();
354  
    tl_cached_waiter.set(nullptr);
354  
    tl_cached_waiter.set(nullptr);
355  
}
355  
}
356  

356  

357  
// timer_service out-of-class member function definitions
357  
// timer_service out-of-class member function definitions
358  

358  

359  
inline timer_service::implementation::implementation(
359  
inline timer_service::implementation::implementation(
360  
    timer_service& svc) noexcept
360  
    timer_service& svc) noexcept
361  
    : svc_(&svc)
361  
    : svc_(&svc)
362  
{
362  
{
363  
}
363  
}
364  

364  

365  
inline void
365  
inline void
366  
timer_service::shutdown()
366  
timer_service::shutdown()
367  
{
367  
{
368  
    timer_service_invalidate_cache();
368  
    timer_service_invalidate_cache();
369  
    shutting_down_ = true;
369  
    shutting_down_ = true;
370  

370  

371  
    // Snapshot impls and detach them from the heap so that
371  
    // Snapshot impls and detach them from the heap so that
372  
    // coroutine-owned timer destructors (triggered by h.destroy()
372  
    // coroutine-owned timer destructors (triggered by h.destroy()
373  
    // below) cannot re-enter remove_timer_impl() and mutate the
373  
    // below) cannot re-enter remove_timer_impl() and mutate the
374  
    // vector during iteration.
374  
    // vector during iteration.
375  
    std::vector<implementation*> impls;
375  
    std::vector<implementation*> impls;
376  
    impls.reserve(heap_.size());
376  
    impls.reserve(heap_.size());
377  
    for (auto& entry : heap_)
377  
    for (auto& entry : heap_)
378  
    {
378  
    {
379  
        entry.timer_->heap_index_ = (std::numeric_limits<std::size_t>::max)();
379  
        entry.timer_->heap_index_ = (std::numeric_limits<std::size_t>::max)();
380  
        impls.push_back(entry.timer_);
380  
        impls.push_back(entry.timer_);
381  
    }
381  
    }
382  
    heap_.clear();
382  
    heap_.clear();
383  
    cached_nearest_ns_.store(
383  
    cached_nearest_ns_.store(
384  
        (std::numeric_limits<std::int64_t>::max)(), std::memory_order_release);
384  
        (std::numeric_limits<std::int64_t>::max)(), std::memory_order_release);
385  

385  

386  
    // Cancel waiting timers. Each waiter called work_started()
386  
    // Cancel waiting timers. Each waiter called work_started()
387  
    // in implementation::wait(). On IOCP the scheduler shutdown
387  
    // in implementation::wait(). On IOCP the scheduler shutdown
388  
    // loop exits when outstanding_work_ reaches zero, so we must
388  
    // loop exits when outstanding_work_ reaches zero, so we must
389  
    // call work_finished() here to balance it. On other backends
389  
    // call work_finished() here to balance it. On other backends
390  
    // this is harmless.
390  
    // this is harmless.
391  
    for (auto* impl : impls)
391  
    for (auto* impl : impls)
392  
    {
392  
    {
393  
        while (auto* w = impl->waiters_.pop_front())
393  
        while (auto* w = impl->waiters_.pop_front())
394  
        {
394  
        {
395  
            w->stop_cb_.reset();
395  
            w->stop_cb_.reset();
396  
            auto h = std::exchange(w->h_, {});
396  
            auto h = std::exchange(w->h_, {});
397  
            sched_->work_finished();
397  
            sched_->work_finished();
398  
            if (h)
398  
            if (h)
399  
                h.destroy();
399  
                h.destroy();
400  
            delete w;
400  
            delete w;
401  
        }
401  
        }
402  
        delete impl;
402  
        delete impl;
403  
    }
403  
    }
404  

404  

405  
    // Delete free-listed impls
405  
    // Delete free-listed impls
406  
    while (free_list_)
406  
    while (free_list_)
407  
    {
407  
    {
408  
        auto* next = free_list_->next_free_;
408  
        auto* next = free_list_->next_free_;
409  
        delete free_list_;
409  
        delete free_list_;
410  
        free_list_ = next;
410  
        free_list_ = next;
411  
    }
411  
    }
412  

412  

413  
    // Delete free-listed waiters
413  
    // Delete free-listed waiters
414  
    while (waiter_free_list_)
414  
    while (waiter_free_list_)
415  
    {
415  
    {
416  
        auto* next = waiter_free_list_->next_free_;
416  
        auto* next = waiter_free_list_->next_free_;
417  
        delete waiter_free_list_;
417  
        delete waiter_free_list_;
418  
        waiter_free_list_ = next;
418  
        waiter_free_list_ = next;
419  
    }
419  
    }
420  
}
420  
}
421  

421  

422  
inline io_object::implementation*
422  
inline io_object::implementation*
423  
timer_service::construct()
423  
timer_service::construct()
424  
{
424  
{
425  
    implementation* impl = try_pop_tl_cache(this);
425  
    implementation* impl = try_pop_tl_cache(this);
426  
    if (impl)
426  
    if (impl)
427  
    {
427  
    {
428  
        impl->svc_        = this;
428  
        impl->svc_        = this;
429  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
429  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
430  
        impl->might_have_pending_waits_ = false;
430  
        impl->might_have_pending_waits_ = false;
431  
        return impl;
431  
        return impl;
432  
    }
432  
    }
433  

433  

434  
    std::lock_guard lock(mutex_);
434  
    std::lock_guard lock(mutex_);
435  
    if (free_list_)
435  
    if (free_list_)
436  
    {
436  
    {
437  
        impl              = free_list_;
437  
        impl              = free_list_;
438  
        free_list_        = impl->next_free_;
438  
        free_list_        = impl->next_free_;
439  
        impl->next_free_  = nullptr;
439  
        impl->next_free_  = nullptr;
440  
        impl->svc_        = this;
440  
        impl->svc_        = this;
441  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
441  
        impl->heap_index_ = (std::numeric_limits<std::size_t>::max)();
442  
        impl->might_have_pending_waits_ = false;
442  
        impl->might_have_pending_waits_ = false;
443  
    }
443  
    }
444  
    else
444  
    else
445  
    {
445  
    {
446  
        impl = new implementation(*this);
446  
        impl = new implementation(*this);
447  
    }
447  
    }
448  
    return impl;
448  
    return impl;
449  
}
449  
}
450  

450  

451  
inline void
451  
inline void
452  
timer_service::destroy(io_object::implementation* p)
452  
timer_service::destroy(io_object::implementation* p)
453  
{
453  
{
454  
    destroy_impl(static_cast<implementation&>(*p));
454  
    destroy_impl(static_cast<implementation&>(*p));
455  
}
455  
}
456  

456  

457  
inline void
457  
inline void
458  
timer_service::destroy_impl(implementation& impl)
458  
timer_service::destroy_impl(implementation& impl)
459  
{
459  
{
460  
    // During shutdown the impl is owned by the shutdown loop.
460  
    // During shutdown the impl is owned by the shutdown loop.
461  
    // Re-entering here (from a coroutine-owned timer destructor
461  
    // Re-entering here (from a coroutine-owned timer destructor
462  
    // triggered by h.destroy()) must not modify the heap or
462  
    // triggered by h.destroy()) must not modify the heap or
463  
    // recycle the impl — shutdown deletes it directly.
463  
    // recycle the impl — shutdown deletes it directly.
464  
    if (shutting_down_)
464  
    if (shutting_down_)
465  
        return;
465  
        return;
466  

466  

467  
    cancel_timer(impl);
467  
    cancel_timer(impl);
468  

468  

469  
    if (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)())
469  
    if (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)())
470  
    {
470  
    {
471  
        std::lock_guard lock(mutex_);
471  
        std::lock_guard lock(mutex_);
472  
        remove_timer_impl(impl);
472  
        remove_timer_impl(impl);
473  
        refresh_cached_nearest();
473  
        refresh_cached_nearest();
474  
    }
474  
    }
475  

475  

476  
    if (try_push_tl_cache(&impl))
476  
    if (try_push_tl_cache(&impl))
477  
        return;
477  
        return;
478  

478  

479  
    std::lock_guard lock(mutex_);
479  
    std::lock_guard lock(mutex_);
480  
    impl.next_free_ = free_list_;
480  
    impl.next_free_ = free_list_;
481  
    free_list_      = &impl;
481  
    free_list_      = &impl;
482  
}
482  
}
483  

483  

484  
inline waiter_node*
484  
inline waiter_node*
485  
timer_service::create_waiter()
485  
timer_service::create_waiter()
486  
{
486  
{
487  
    if (auto* w = try_pop_waiter_tl_cache())
487  
    if (auto* w = try_pop_waiter_tl_cache())
488  
        return w;
488  
        return w;
489  

489  

490  
    std::lock_guard lock(mutex_);
490  
    std::lock_guard lock(mutex_);
491  
    if (waiter_free_list_)
491  
    if (waiter_free_list_)
492  
    {
492  
    {
493  
        auto* w           = waiter_free_list_;
493  
        auto* w           = waiter_free_list_;
494  
        waiter_free_list_ = w->next_free_;
494  
        waiter_free_list_ = w->next_free_;
495  
        w->next_free_     = nullptr;
495  
        w->next_free_     = nullptr;
496  
        return w;
496  
        return w;
497  
    }
497  
    }
498  

498  

499  
    return new waiter_node();
499  
    return new waiter_node();
500  
}
500  
}
501  

501  

502  
inline void
502  
inline void
503  
timer_service::destroy_waiter(waiter_node* w)
503  
timer_service::destroy_waiter(waiter_node* w)
504  
{
504  
{
505  
    if (try_push_waiter_tl_cache(w))
505  
    if (try_push_waiter_tl_cache(w))
506  
        return;
506  
        return;
507  

507  

508  
    std::lock_guard lock(mutex_);
508  
    std::lock_guard lock(mutex_);
509  
    w->next_free_     = waiter_free_list_;
509  
    w->next_free_     = waiter_free_list_;
510  
    waiter_free_list_ = w;
510  
    waiter_free_list_ = w;
511  
}
511  
}
512  

512  

513  
inline std::size_t
513  
inline std::size_t
514  
timer_service::update_timer(implementation& impl, time_point new_time)
514  
timer_service::update_timer(implementation& impl, time_point new_time)
515  
{
515  
{
516  
    bool in_heap =
516  
    bool in_heap =
517  
        (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)());
517  
        (impl.heap_index_ != (std::numeric_limits<std::size_t>::max)());
518  
    if (!in_heap && impl.waiters_.empty())
518  
    if (!in_heap && impl.waiters_.empty())
519  
        return 0;
519  
        return 0;
520  

520  

521  
    bool notify = false;
521  
    bool notify = false;
522  
    intrusive_list<waiter_node> canceled;
522  
    intrusive_list<waiter_node> canceled;
523  

523  

524  
    {
524  
    {
525  
        std::lock_guard lock(mutex_);
525  
        std::lock_guard lock(mutex_);
526  

526  

527  
        while (auto* w = impl.waiters_.pop_front())
527  
        while (auto* w = impl.waiters_.pop_front())
528  
        {
528  
        {
529  
            w->impl_ = nullptr;
529  
            w->impl_ = nullptr;
530  
            canceled.push_back(w);
530  
            canceled.push_back(w);
531  
        }
531  
        }
532  

532  

533  
        if (impl.heap_index_ < heap_.size())
533  
        if (impl.heap_index_ < heap_.size())
534  
        {
534  
        {
535  
            time_point old_time           = heap_[impl.heap_index_].time_;
535  
            time_point old_time           = heap_[impl.heap_index_].time_;
536  
            heap_[impl.heap_index_].time_ = new_time;
536  
            heap_[impl.heap_index_].time_ = new_time;
537  

537  

538  
            if (new_time < old_time)
538  
            if (new_time < old_time)
539  
                up_heap(impl.heap_index_);
539  
                up_heap(impl.heap_index_);
540  
            else
540  
            else
541  
                down_heap(impl.heap_index_);
541  
                down_heap(impl.heap_index_);
542  

542  

543  
            notify = (impl.heap_index_ == 0);
543  
            notify = (impl.heap_index_ == 0);
544  
        }
544  
        }
545  

545  

546  
        refresh_cached_nearest();
546  
        refresh_cached_nearest();
547  
    }
547  
    }
548  

548  

549  
    std::size_t count = 0;
549  
    std::size_t count = 0;
550  
    while (auto* w = canceled.pop_front())
550  
    while (auto* w = canceled.pop_front())
551  
    {
551  
    {
552  
        w->ec_value_ = make_error_code(capy::error::canceled);
552  
        w->ec_value_ = make_error_code(capy::error::canceled);
553  
        sched_->post(&w->op_);
553  
        sched_->post(&w->op_);
554  
        ++count;
554  
        ++count;
555  
    }
555  
    }
556  

556  

557  
    if (notify)
557  
    if (notify)
558  
        on_earliest_changed_();
558  
        on_earliest_changed_();
559  

559  

560  
    return count;
560  
    return count;
561  
}
561  
}
562  

562  

563  
inline void
563  
inline void
564  
timer_service::insert_waiter(implementation& impl, waiter_node* w)
564  
timer_service::insert_waiter(implementation& impl, waiter_node* w)
565  
{
565  
{
566  
    bool notify = false;
566  
    bool notify = false;
567  
    {
567  
    {
568  
        std::lock_guard lock(mutex_);
568  
        std::lock_guard lock(mutex_);
569  
        if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)())
569  
        if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)())
570  
        {
570  
        {
571  
            impl.heap_index_ = heap_.size();
571  
            impl.heap_index_ = heap_.size();
572  
            heap_.push_back({impl.expiry_, &impl});
572  
            heap_.push_back({impl.expiry_, &impl});
573  
            up_heap(heap_.size() - 1);
573  
            up_heap(heap_.size() - 1);
574  
            notify = (impl.heap_index_ == 0);
574  
            notify = (impl.heap_index_ == 0);
575  
            refresh_cached_nearest();
575  
            refresh_cached_nearest();
576  
        }
576  
        }
577  
        impl.waiters_.push_back(w);
577  
        impl.waiters_.push_back(w);
578  
    }
578  
    }
579  
    if (notify)
579  
    if (notify)
580  
        on_earliest_changed_();
580  
        on_earliest_changed_();
581  
}
581  
}
582  

582  

583  
inline std::size_t
583  
inline std::size_t
584  
timer_service::cancel_timer(implementation& impl)
584  
timer_service::cancel_timer(implementation& impl)
585  
{
585  
{
586  
    if (!impl.might_have_pending_waits_)
586  
    if (!impl.might_have_pending_waits_)
587  
        return 0;
587  
        return 0;
588  

588  

589  
    // Not in heap and no waiters — just clear the flag
589  
    // Not in heap and no waiters — just clear the flag
590  
    if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)() &&
590  
    if (impl.heap_index_ == (std::numeric_limits<std::size_t>::max)() &&
591  
        impl.waiters_.empty())
591  
        impl.waiters_.empty())
592  
    {
592  
    {
593  
        impl.might_have_pending_waits_ = false;
593  
        impl.might_have_pending_waits_ = false;
594  
        return 0;
594  
        return 0;
595  
    }
595  
    }
596  

596  

597  
    intrusive_list<waiter_node> canceled;
597  
    intrusive_list<waiter_node> canceled;
598  

598  

599  
    {
599  
    {
600  
        std::lock_guard lock(mutex_);
600  
        std::lock_guard lock(mutex_);
601  
        remove_timer_impl(impl);
601  
        remove_timer_impl(impl);
602  
        while (auto* w = impl.waiters_.pop_front())
602  
        while (auto* w = impl.waiters_.pop_front())
603  
        {
603  
        {
604  
            w->impl_ = nullptr;
604  
            w->impl_ = nullptr;
605  
            canceled.push_back(w);
605  
            canceled.push_back(w);
606  
        }
606  
        }
607  
        refresh_cached_nearest();
607  
        refresh_cached_nearest();
608  
    }
608  
    }
609  

609  

610  
    impl.might_have_pending_waits_ = false;
610  
    impl.might_have_pending_waits_ = false;
611  

611  

612  
    std::size_t count = 0;
612  
    std::size_t count = 0;
613  
    while (auto* w = canceled.pop_front())
613  
    while (auto* w = canceled.pop_front())
614  
    {
614  
    {
615  
        w->ec_value_ = make_error_code(capy::error::canceled);
615  
        w->ec_value_ = make_error_code(capy::error::canceled);
616  
        sched_->post(&w->op_);
616  
        sched_->post(&w->op_);
617  
        ++count;
617  
        ++count;
618  
    }
618  
    }
619  

619  

620  
    return count;
620  
    return count;
621  
}
621  
}
622  

622  

623  
inline void
623  
inline void
624  
timer_service::cancel_waiter(waiter_node* w)
624  
timer_service::cancel_waiter(waiter_node* w)
625  
{
625  
{
626  
    {
626  
    {
627  
        std::lock_guard lock(mutex_);
627  
        std::lock_guard lock(mutex_);
628  
        // Already removed by cancel_timer or process_expired
628  
        // Already removed by cancel_timer or process_expired
629  
        if (!w->impl_)
629  
        if (!w->impl_)
630  
            return;
630  
            return;
631  
        auto* impl = w->impl_;
631  
        auto* impl = w->impl_;
632  
        w->impl_   = nullptr;
632  
        w->impl_   = nullptr;
633  
        impl->waiters_.remove(w);
633  
        impl->waiters_.remove(w);
634  
        if (impl->waiters_.empty())
634  
        if (impl->waiters_.empty())
635  
        {
635  
        {
636  
            remove_timer_impl(*impl);
636  
            remove_timer_impl(*impl);
637  
            impl->might_have_pending_waits_ = false;
637  
            impl->might_have_pending_waits_ = false;
638  
        }
638  
        }
639  
        refresh_cached_nearest();
639  
        refresh_cached_nearest();
640  
    }
640  
    }
641  

641  

642  
    w->ec_value_ = make_error_code(capy::error::canceled);
642  
    w->ec_value_ = make_error_code(capy::error::canceled);
643  
    sched_->post(&w->op_);
643  
    sched_->post(&w->op_);
644  
}
644  
}
645  

645  

646  
inline std::size_t
646  
inline std::size_t
647  
timer_service::cancel_one_waiter(implementation& impl)
647  
timer_service::cancel_one_waiter(implementation& impl)
648  
{
648  
{
649  
    if (!impl.might_have_pending_waits_)
649  
    if (!impl.might_have_pending_waits_)
650  
        return 0;
650  
        return 0;
651  

651  

652  
    waiter_node* w = nullptr;
652  
    waiter_node* w = nullptr;
653  

653  

654  
    {
654  
    {
655  
        std::lock_guard lock(mutex_);
655  
        std::lock_guard lock(mutex_);
656  
        w = impl.waiters_.pop_front();
656  
        w = impl.waiters_.pop_front();
657  
        if (!w)
657  
        if (!w)
658  
            return 0;
658  
            return 0;
659  
        w->impl_ = nullptr;
659  
        w->impl_ = nullptr;
660  
        if (impl.waiters_.empty())
660  
        if (impl.waiters_.empty())
661  
        {
661  
        {
662  
            remove_timer_impl(impl);
662  
            remove_timer_impl(impl);
663  
            impl.might_have_pending_waits_ = false;
663  
            impl.might_have_pending_waits_ = false;
664  
        }
664  
        }
665  
        refresh_cached_nearest();
665  
        refresh_cached_nearest();
666  
    }
666  
    }
667  

667  

668  
    w->ec_value_ = make_error_code(capy::error::canceled);
668  
    w->ec_value_ = make_error_code(capy::error::canceled);
669  
    sched_->post(&w->op_);
669  
    sched_->post(&w->op_);
670  
    return 1;
670  
    return 1;
671  
}
671  
}
672  

672  

673  
inline std::size_t
673  
inline std::size_t
674  
timer_service::process_expired()
674  
timer_service::process_expired()
675  
{
675  
{
676  
    intrusive_list<waiter_node> expired;
676  
    intrusive_list<waiter_node> expired;
677  

677  

678  
    {
678  
    {
679  
        std::lock_guard lock(mutex_);
679  
        std::lock_guard lock(mutex_);
680  
        auto now = clock_type::now();
680  
        auto now = clock_type::now();
681  

681  

682  
        while (!heap_.empty() && heap_[0].time_ <= now)
682  
        while (!heap_.empty() && heap_[0].time_ <= now)
683  
        {
683  
        {
684  
            implementation* t = heap_[0].timer_;
684  
            implementation* t = heap_[0].timer_;
685  
            remove_timer_impl(*t);
685  
            remove_timer_impl(*t);
686  
            while (auto* w = t->waiters_.pop_front())
686  
            while (auto* w = t->waiters_.pop_front())
687  
            {
687  
            {
688  
                w->impl_     = nullptr;
688  
                w->impl_     = nullptr;
689  
                w->ec_value_ = {};
689  
                w->ec_value_ = {};
690  
                expired.push_back(w);
690  
                expired.push_back(w);
691  
            }
691  
            }
692  
            t->might_have_pending_waits_ = false;
692  
            t->might_have_pending_waits_ = false;
693  
        }
693  
        }
694  

694  

695  
        refresh_cached_nearest();
695  
        refresh_cached_nearest();
696  
    }
696  
    }
697  

697  

698  
    std::size_t count = 0;
698  
    std::size_t count = 0;
699  
    while (auto* w = expired.pop_front())
699  
    while (auto* w = expired.pop_front())
700  
    {
700  
    {
701  
        sched_->post(&w->op_);
701  
        sched_->post(&w->op_);
702  
        ++count;
702  
        ++count;
703  
    }
703  
    }
704  

704  

705  
    return count;
705  
    return count;
706  
}
706  
}
707  

707  

708  
inline void
708  
inline void
709  
timer_service::remove_timer_impl(implementation& impl)
709  
timer_service::remove_timer_impl(implementation& impl)
710  
{
710  
{
711  
    std::size_t index = impl.heap_index_;
711  
    std::size_t index = impl.heap_index_;
712  
    if (index >= heap_.size())
712  
    if (index >= heap_.size())
713  
        return; // Not in heap
713  
        return; // Not in heap
714  

714  

715  
    if (index == heap_.size() - 1)
715  
    if (index == heap_.size() - 1)
716  
    {
716  
    {
717  
        // Last element, just pop
717  
        // Last element, just pop
718  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
718  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
719  
        heap_.pop_back();
719  
        heap_.pop_back();
720  
    }
720  
    }
721  
    else
721  
    else
722  
    {
722  
    {
723  
        // Swap with last and reheapify
723  
        // Swap with last and reheapify
724  
        swap_heap(index, heap_.size() - 1);
724  
        swap_heap(index, heap_.size() - 1);
725  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
725  
        impl.heap_index_ = (std::numeric_limits<std::size_t>::max)();
726  
        heap_.pop_back();
726  
        heap_.pop_back();
727  

727  

728  
        if (index > 0 && heap_[index].time_ < heap_[(index - 1) / 2].time_)
728  
        if (index > 0 && heap_[index].time_ < heap_[(index - 1) / 2].time_)
729  
            up_heap(index);
729  
            up_heap(index);
730  
        else
730  
        else
731  
            down_heap(index);
731  
            down_heap(index);
732  
    }
732  
    }
733  
}
733  
}
734  

734  

735  
inline void
735  
inline void
736  
timer_service::up_heap(std::size_t index)
736  
timer_service::up_heap(std::size_t index)
737  
{
737  
{
738  
    while (index > 0)
738  
    while (index > 0)
739  
    {
739  
    {
740  
        std::size_t parent = (index - 1) / 2;
740  
        std::size_t parent = (index - 1) / 2;
741  
        if (!(heap_[index].time_ < heap_[parent].time_))
741  
        if (!(heap_[index].time_ < heap_[parent].time_))
742  
            break;
742  
            break;
743  
        swap_heap(index, parent);
743  
        swap_heap(index, parent);
744  
        index = parent;
744  
        index = parent;
745  
    }
745  
    }
746  
}
746  
}
747  

747  

748  
inline void
748  
inline void
749  
timer_service::down_heap(std::size_t index)
749  
timer_service::down_heap(std::size_t index)
750  
{
750  
{
751  
    std::size_t child = index * 2 + 1;
751  
    std::size_t child = index * 2 + 1;
752  
    while (child < heap_.size())
752  
    while (child < heap_.size())
753  
    {
753  
    {
754  
        std::size_t min_child = (child + 1 == heap_.size() ||
754  
        std::size_t min_child = (child + 1 == heap_.size() ||
755  
                                 heap_[child].time_ < heap_[child + 1].time_)
755  
                                 heap_[child].time_ < heap_[child + 1].time_)
756  
            ? child
756  
            ? child
757  
            : child + 1;
757  
            : child + 1;
758  

758  

759  
        if (heap_[index].time_ < heap_[min_child].time_)
759  
        if (heap_[index].time_ < heap_[min_child].time_)
760  
            break;
760  
            break;
761  

761  

762  
        swap_heap(index, min_child);
762  
        swap_heap(index, min_child);
763  
        index = min_child;
763  
        index = min_child;
764  
        child = index * 2 + 1;
764  
        child = index * 2 + 1;
765  
    }
765  
    }
766  
}
766  
}
767  

767  

768  
inline void
768  
inline void
769  
timer_service::swap_heap(std::size_t i1, std::size_t i2)
769  
timer_service::swap_heap(std::size_t i1, std::size_t i2)
770  
{
770  
{
771  
    heap_entry tmp                = heap_[i1];
771  
    heap_entry tmp                = heap_[i1];
772  
    heap_[i1]                     = heap_[i2];
772  
    heap_[i1]                     = heap_[i2];
773  
    heap_[i2]                     = tmp;
773  
    heap_[i2]                     = tmp;
774  
    heap_[i1].timer_->heap_index_ = i1;
774  
    heap_[i1].timer_->heap_index_ = i1;
775  
    heap_[i2].timer_->heap_index_ = i2;
775  
    heap_[i2].timer_->heap_index_ = i2;
776  
}
776  
}
777  

777  

778  
// waiter_node out-of-class member function definitions
778  
// waiter_node out-of-class member function definitions
779  

779  

780  
inline void
780  
inline void
781  
waiter_node::canceller::operator()() const
781  
waiter_node::canceller::operator()() const
782  
{
782  
{
783  
    waiter_->svc_->cancel_waiter(waiter_);
783  
    waiter_->svc_->cancel_waiter(waiter_);
784  
}
784  
}
785  

785  

786  
inline void
786  
inline void
787  
waiter_node::completion_op::do_complete(
787  
waiter_node::completion_op::do_complete(
788  
    [[maybe_unused]] void* owner,
788  
    [[maybe_unused]] void* owner,
789  
    scheduler_op* base,
789  
    scheduler_op* base,
790  
    std::uint32_t,
790  
    std::uint32_t,
791  
    std::uint32_t)
791  
    std::uint32_t)
792  
{
792  
{
793  
    // owner is always non-null here. The destroy path (owner == nullptr)
793  
    // owner is always non-null here. The destroy path (owner == nullptr)
794  
    // is unreachable because completion_op overrides destroy() directly,
794  
    // is unreachable because completion_op overrides destroy() directly,
795  
    // bypassing scheduler_op::destroy() which would call func_(nullptr, ...).
795  
    // bypassing scheduler_op::destroy() which would call func_(nullptr, ...).
796  
    BOOST_COROSIO_ASSERT(owner);
796  
    BOOST_COROSIO_ASSERT(owner);
797  
    static_cast<completion_op*>(base)->operator()();
797  
    static_cast<completion_op*>(base)->operator()();
798  
}
798  
}
799  

799  

800  
inline void
800  
inline void
801  
waiter_node::completion_op::operator()()
801  
waiter_node::completion_op::operator()()
802  
{
802  
{
803  
    auto* w = waiter_;
803  
    auto* w = waiter_;
804  
    w->stop_cb_.reset();
804  
    w->stop_cb_.reset();
805  
    if (w->ec_out_)
805  
    if (w->ec_out_)
806  
        *w->ec_out_ = w->ec_value_;
806  
        *w->ec_out_ = w->ec_value_;
807  

807  

808  
    auto* cont  = w->cont_;
808  
    auto* cont  = w->cont_;
809  
    auto d      = w->d_;
809  
    auto d      = w->d_;
810  
    auto* svc   = w->svc_;
810  
    auto* svc   = w->svc_;
811  
    auto& sched = svc->get_scheduler();
811  
    auto& sched = svc->get_scheduler();
812  

812  

813  
    svc->destroy_waiter(w);
813  
    svc->destroy_waiter(w);
814  

814  

815  
    d.post(*cont);
815  
    d.post(*cont);
816  
    sched.work_finished();
816  
    sched.work_finished();
817  
}
817  
}
818  

818  

819  
// GCC 14 false-positive: inlining ~optional<stop_callback> through
819  
// GCC 14 false-positive: inlining ~optional<stop_callback> through
820  
// delete loses track that stop_cb_ was already .reset() above.
820  
// delete loses track that stop_cb_ was already .reset() above.
821  
#if defined(__GNUC__) && !defined(__clang__)
821  
#if defined(__GNUC__) && !defined(__clang__)
822  
#pragma GCC diagnostic push
822  
#pragma GCC diagnostic push
823  
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
823  
#pragma GCC diagnostic ignored "-Wmaybe-uninitialized"
824  
#endif
824  
#endif
825  
inline void
825  
inline void
826  
waiter_node::completion_op::destroy()
826  
waiter_node::completion_op::destroy()
827  
{
827  
{
828  
    // Called during scheduler shutdown drain when this completion_op is
828  
    // Called during scheduler shutdown drain when this completion_op is
829  
    // in the scheduler's ready queue (posted by cancel_timer() or
829  
    // in the scheduler's ready queue (posted by cancel_timer() or
830  
    // process_expired()). Balances the work_started() from
830  
    // process_expired()). Balances the work_started() from
831  
    // implementation::wait(). The scheduler drain loop separately
831  
    // implementation::wait(). The scheduler drain loop separately
832  
    // balances the work_started() from post(). On IOCP both decrements
832  
    // balances the work_started() from post(). On IOCP both decrements
833  
    // are required for outstanding_work_ to reach zero; on other
833  
    // are required for outstanding_work_ to reach zero; on other
834  
    // backends this is harmless.
834  
    // backends this is harmless.
835  
    //
835  
    //
836  
    // This override also prevents scheduler_op::destroy() from calling
836  
    // This override also prevents scheduler_op::destroy() from calling
837  
    // do_complete(nullptr, ...). See also: timer_service::shutdown()
837  
    // do_complete(nullptr, ...). See also: timer_service::shutdown()
838  
    // which drains waiters still in the timer heap (the other path).
838  
    // which drains waiters still in the timer heap (the other path).
839  
    auto* w = waiter_;
839  
    auto* w = waiter_;
840  
    w->stop_cb_.reset();
840  
    w->stop_cb_.reset();
841  
    auto h      = std::exchange(w->h_, {});
841  
    auto h      = std::exchange(w->h_, {});
842  
    auto& sched = w->svc_->get_scheduler();
842  
    auto& sched = w->svc_->get_scheduler();
843  
    delete w;
843  
    delete w;
844  
    sched.work_finished();
844  
    sched.work_finished();
845  
    if (h)
845  
    if (h)
846  
        h.destroy();
846  
        h.destroy();
847  
}
847  
}
848  
#if defined(__GNUC__) && !defined(__clang__)
848  
#if defined(__GNUC__) && !defined(__clang__)
849  
#pragma GCC diagnostic pop
849  
#pragma GCC diagnostic pop
850  
#endif
850  
#endif
851  

851  

852  
inline std::coroutine_handle<>
852  
inline std::coroutine_handle<>
853  
timer_service::implementation::wait(
853  
timer_service::implementation::wait(
854  
    std::coroutine_handle<> h,
854  
    std::coroutine_handle<> h,
855  
    capy::executor_ref d,
855  
    capy::executor_ref d,
856  
    std::stop_token token,
856  
    std::stop_token token,
857  
    std::error_code* ec,
857  
    std::error_code* ec,
858  
    capy::continuation* cont)
858  
    capy::continuation* cont)
859  
{
859  
{
860  
    // Already-expired fast path — no waiter_node, no mutex.
860  
    // Already-expired fast path — no waiter_node, no mutex.
861  
    // Post instead of dispatch so the coroutine yields to the
861  
    // Post instead of dispatch so the coroutine yields to the
862  
    // scheduler, allowing other queued work to run.
862  
    // scheduler, allowing other queued work to run.
863  
    if (heap_index_ == (std::numeric_limits<std::size_t>::max)())
863  
    if (heap_index_ == (std::numeric_limits<std::size_t>::max)())
864  
    {
864  
    {
865  
        if (expiry_ == (time_point::min)() || expiry_ <= clock_type::now())
865  
        if (expiry_ == (time_point::min)() || expiry_ <= clock_type::now())
866  
        {
866  
        {
867  
            if (ec)
867  
            if (ec)
868  
                *ec = {};
868  
                *ec = {};
869  
            d.post(*cont);
869  
            d.post(*cont);
870  
            return std::noop_coroutine();
870  
            return std::noop_coroutine();
871  
        }
871  
        }
872  
    }
872  
    }
873  

873  

874  
    auto* w    = svc_->create_waiter();
874  
    auto* w    = svc_->create_waiter();
875  
    w->impl_   = this;
875  
    w->impl_   = this;
876  
    w->svc_    = svc_;
876  
    w->svc_    = svc_;
877  
    w->h_      = h;
877  
    w->h_      = h;
878  
    w->cont_   = cont;
878  
    w->cont_   = cont;
879  
    w->d_      = d;
879  
    w->d_      = d;
880  
    w->token_  = std::move(token);
880  
    w->token_  = std::move(token);
881  
    w->ec_out_ = ec;
881  
    w->ec_out_ = ec;
882  

882  

883  
    svc_->insert_waiter(*this, w);
883  
    svc_->insert_waiter(*this, w);
884  
    might_have_pending_waits_ = true;
884  
    might_have_pending_waits_ = true;
885  
    svc_->get_scheduler().work_started();
885  
    svc_->get_scheduler().work_started();
886  

886  

887  
    if (w->token_.stop_possible())
887  
    if (w->token_.stop_possible())
888  
        w->stop_cb_.emplace(w->token_, waiter_node::canceller{w});
888  
        w->stop_cb_.emplace(w->token_, waiter_node::canceller{w});
889  

889  

890  
    return std::noop_coroutine();
890  
    return std::noop_coroutine();
891  
}
891  
}
892  

892  

893  
// Free functions
893  
// Free functions
894  

894  

895  
struct timer_service_access
895  
struct timer_service_access
896  
{
896  
{
897  
    static native_scheduler& get_scheduler(io_context& ctx) noexcept
897  
    static native_scheduler& get_scheduler(io_context& ctx) noexcept
898  
    {
898  
    {
899  
        return static_cast<native_scheduler&>(*ctx.sched_);
899  
        return static_cast<native_scheduler&>(*ctx.sched_);
900  
    }
900  
    }
901  
};
901  
};
902  

902  

903  
// Bypass find_service() mutex by reading the scheduler's cached pointer
903  
// Bypass find_service() mutex by reading the scheduler's cached pointer
904  
inline io_object::io_service&
904  
inline io_object::io_service&
905  
timer_service_direct(capy::execution_context& ctx) noexcept
905  
timer_service_direct(capy::execution_context& ctx) noexcept
906  
{
906  
{
907  
    return *timer_service_access::get_scheduler(static_cast<io_context&>(ctx))
907  
    return *timer_service_access::get_scheduler(static_cast<io_context&>(ctx))
908  
                .timer_svc_;
908  
                .timer_svc_;
909  
}
909  
}
910  

910  

911  
inline std::size_t
911  
inline std::size_t
912  
timer_service_update_expiry(timer::implementation& base)
912  
timer_service_update_expiry(timer::implementation& base)
913  
{
913  
{
914  
    auto& impl = static_cast<timer_service::implementation&>(base);
914  
    auto& impl = static_cast<timer_service::implementation&>(base);
915  
    return impl.svc_->update_timer(impl, impl.expiry_);
915  
    return impl.svc_->update_timer(impl, impl.expiry_);
916  
}
916  
}
917  

917  

918  
inline std::size_t
918  
inline std::size_t
919  
timer_service_cancel(timer::implementation& base) noexcept
919  
timer_service_cancel(timer::implementation& base) noexcept
920  
{
920  
{
921  
    auto& impl = static_cast<timer_service::implementation&>(base);
921  
    auto& impl = static_cast<timer_service::implementation&>(base);
922  
    return impl.svc_->cancel_timer(impl);
922  
    return impl.svc_->cancel_timer(impl);
923  
}
923  
}
924  

924  

925  
inline std::size_t
925  
inline std::size_t
926  
timer_service_cancel_one(timer::implementation& base) noexcept
926  
timer_service_cancel_one(timer::implementation& base) noexcept
927  
{
927  
{
928  
    auto& impl = static_cast<timer_service::implementation&>(base);
928  
    auto& impl = static_cast<timer_service::implementation&>(base);
929  
    return impl.svc_->cancel_one_waiter(impl);
929  
    return impl.svc_->cancel_one_waiter(impl);
930  
}
930  
}
931  

931  

932  
inline timer_service&
932  
inline timer_service&
933  
get_timer_service(capy::execution_context& ctx, scheduler& sched)
933  
get_timer_service(capy::execution_context& ctx, scheduler& sched)
934  
{
934  
{
935  
    return ctx.make_service<timer_service>(sched);
935  
    return ctx.make_service<timer_service>(sched);
936  
}
936  
}
937  

937  

938  
} // namespace boost::corosio::detail
938  
} // namespace boost::corosio::detail
939  

939  

940  
#endif
940  
#endif