feat(async,time): add injected-clock TimerQueue and clock saturation helpers (M-TIME-03 B1)

- NEW Async/Timer.hpp: TimerQueue (stable (deadline, seq) min-heap, bounded
  tombstones, explicit poll_expired, callbacks outside the lock, close/destroy
  deliver TimerEvent::closed), shared-state TimerHandle safe after queue
  destruction, sleep_until/sleep_for settling exactly once and resuming via
  post_completion; documented sleep-task lifetime and cancel-under-lock rules
- Time/Clock.hpp: saturating_add, deadline_after
- Tests: TimerQueue (15), DeadlineDomains (2), ClockSaturation (1); race loops
  count failures to stay under the runner's 1,000-assertion retention (X-QA-02)

Review: W11-REVIEW-B1 (CHANGES_REQUIRED F1-F3 fixed by root: test counters,
header lifetime/cancel docs)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 5.5 committed 2026-11-29 23:36:37 +03:00
1 parent 95785ed47a
commit 99a1100bb1
5 files changed
+2269

No files matched your search

+686
View File
@@ -0,0 +1,686 @@
#pragma once
#include <Void/Async/Detail/Types.hpp>
#include <Void/Async/Executor.hpp>
#include <Void/Async/Operation.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Functional/Result.hpp>
#include <Void/Time/Clock.hpp>
#include <algorithm>
#include <atomic>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <expected>
#include <functional>
#include <memory>
#include <mutex>
#include <optional>
#include <stop_token>
#include <string>
#include <utility>
#include <vector>
// ── TimerQueue ────────────────────────────────────────────────────────────────
// Injected-clock timer queue for Async code (C-03/C-04).
//
// * Deadlines are interpreted ONLY in the injected `MonotonicClock` domain. The
// host clock is never consulted, so a `ManualClock` starting at epoch 0 (or at
// a far-future point) behaves deterministically.
// * Nothing fires on its own: there is no background thread. A timer expires
// only when an owner calls `poll_expired()` after the injected clock reached
// its deadline. `next_deadline()` / `wait_duration()` tell a driver how long
// it may block before the next poll.
// * Timers are kept in a stable min-heap ordered by `(deadline, submission
// seq)`, so equal deadlines fire in submission order.
// * Callbacks run exactly once, with `TimerEvent::expired` (from
// `poll_expired()`) or `TimerEvent::closed` (from `close()` / destruction),
// or never when `TimerHandle::cancel()` returned true. They are always
// invoked on the polling/closing thread OUTSIDE the queue's internal lock, so
// a callback may schedule, cancel, poll or close without deadlocking.
// * `cancel() == false` means the callback has fired or is firing; it does
// NOT mean the callback has finished running. Callbacks referencing state
// that may be destroyed concurrently must capture shared ownership (or look
// the target up under the owner's lock), never a raw pointer into a frame.
// * `sleep_until` / `sleep_for` suspend a coroutine until the timer fires and
// resume it through `executor().post_completion(...)`, never inline from
// `poll_expired()`, `close()` or a stop callback.
//
// Lifetime: the completion executor and the clock must outlive the queue, and
// the executor must keep accepting completions until every sleeper settled by
// `close()` / `~TimerQueue()` has been resumed. A `TimerHandle` may safely
// outlive the queue. A suspended sleep task may be destroyed only while its
// timer is still pending and the destruction is serialized with poll, close
// and stop; once its timer has been settled (fired, cancelled or closed) the
// task must stay alive until its posted resume has run. Shutdown order:
// `close()`, then drain the completion executor, then destroy sleep tasks.
// `close()` does not wait for callbacks already claimed by a concurrent
// `poll_expired()` or for a stop callback mid-settle; they may still post
// after `close()` returns.
namespace Void::Async
{
struct TimerQueueOptions {
// Maximum number of simultaneously pending timers (sleepers included).
// Zero is rejected by TimerQueue::create with invalid_argument.
std::size_t max_timers{1024};
};
enum class TimerEvent : std::uint8_t {
expired,
closed
};
using TimerCallback = std::move_only_function<void(TimerEvent) noexcept>;
class TimerHandle;
class TimerQueue;
namespace detail
{
enum class TimerEntryState : std::uint8_t {
pending,
fired,
cancelled
};
class TimerCore;
// Shared per-timer state. The single atomic pending -> {fired, cancelled}
// transition decides the timer's fate; the transition winner exclusively owns
// `callback` afterwards (fire/close: invoke then destroy; cancel: destroy).
struct TimerEntry {
TimerEntry(TimerCallback cb, std::weak_ptr<TimerCore> owner) noexcept
: callback(std::move(cb))
, core(std::move(owner))
{
}
TimerEntry(const TimerEntry&) = delete;
TimerEntry& operator=(const TimerEntry&) = delete;
[[nodiscard]] bool try_leave_pending(TimerEntryState to) noexcept
{
TimerEntryState expected = TimerEntryState::pending;
return state.compare_exchange_strong(
expected, to, std::memory_order_acq_rel, std::memory_order_acquire);
}
[[nodiscard]] bool is_pending() const noexcept
{
return state.load(std::memory_order_acquire) == TimerEntryState::pending;
}
std::atomic<TimerEntryState> state{TimerEntryState::pending};
TimerCallback callback;
// Weak: the heap owns entries, so a strong back-reference would form a
// core -> heap -> entry -> core cycle.
std::weak_ptr<TimerCore> core;
};
struct TimerNode {
Void::Time::MonotonicClock::time_point deadline{};
std::uint64_t seq{0};
std::shared_ptr<TimerEntry> entry{};
};
// Heap comparator: std::*_heap build max-heaps, so "later" yields a min-heap
// on (deadline, seq).
struct TimerNodeLater {
[[nodiscard]] bool operator()(const TimerNode& a, const TimerNode& b) const noexcept
{
if (a.deadline != b.deadline) {
return a.deadline > b.deadline;
}
return a.seq > b.seq;
}
};
// Shared queue core. Owned by the TimerQueue and by in-flight sleep frames;
// referenced weakly by entries so TimerHandle::cancel() stays valid after the
// queue is gone.
//
// Invariants (under mu_): every pending entry is in heap_; heap_ holds only
// pending entries and cancelled tombstones; heap_.size() == live_ +
// tombstones_; live_ <= max_timers_; tombstones are compacted away before an
// admission whenever they exceed max_timers_, so heap_.size() <= 2*max_timers_.
// No user code (callbacks, callback destructors, clock reads) runs under mu_.
class TimerCore : public std::enable_shared_from_this<TimerCore>
{
public:
using time_point = Void::Time::MonotonicClock::time_point;
TimerCore(Executor& executor,
const Void::Time::MonotonicClock& clock,
std::size_t max_timers) noexcept
: executor_(executor)
, clock_(clock)
, max_timers_(max_timers)
{
}
TimerCore(const TimerCore&) = delete;
TimerCore& operator=(const TimerCore&) = delete;
[[nodiscard]] Executor& executor() noexcept { return executor_; }
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept { return clock_; }
[[nodiscard]] bool is_closed() const noexcept
{
return closed_.load(std::memory_order_acquire);
}
[[nodiscard]] std::size_t live() const noexcept
{
return live_.load(std::memory_order_acquire);
}
[[nodiscard]] std::expected<std::shared_ptr<TimerEntry>, AdmissionError>
admit(time_point when, TimerCallback callback)
{
if (closed_.load(std::memory_order_acquire)) {
return std::unexpected{AdmissionError::stopped};
}
// Declared before the lock: on rejection the entry (and the caller's
// callback inside it) is destroyed after the lock is released.
auto entry = std::make_shared<TimerEntry>(std::move(callback), weak_from_this());
std::lock_guard lk{mu_};
if (closed_.load(std::memory_order_relaxed)) {
return std::unexpected{AdmissionError::stopped};
}
if (live_.load(std::memory_order_relaxed) >= max_timers_) {
return std::unexpected{AdmissionError::overloaded};
}
if (tombstones_ > max_timers_) {
compact_locked();
}
heap_.push_back(TimerNode{when, next_seq_, entry});
std::push_heap(heap_.begin(), heap_.end(), TimerNodeLater{});
++next_seq_;
live_.fetch_add(1, std::memory_order_acq_rel);
return entry;
}
// pending -> cancelled under the lock (serialized with poll/close/compact).
[[nodiscard]] bool cancel_transition(TimerEntry& entry) noexcept
{
std::lock_guard lk{mu_};
if (!entry.try_leave_pending(TimerEntryState::cancelled)) {
return false;
}
live_.fetch_sub(1, std::memory_order_acq_rel);
++tombstones_;
return true;
}
[[nodiscard]] std::size_t poll_expired()
{
const time_point now = clock_.now();
std::vector<std::shared_ptr<TimerEntry>> due;
{
std::lock_guard lk{mu_};
while (!heap_.empty() && !(now < heap_.front().deadline)) {
if (due.size() == due.capacity()) {
// Reserve before popping so a fired entry always has a
// slot; under allocation failure the rest stays queued for
// the next poll instead of being lost.
try {
due.reserve(due.empty() ? std::size_t{8} : due.size() * 2);
} catch (...) {
break;
}
}
std::pop_heap(heap_.begin(), heap_.end(), TimerNodeLater{});
std::shared_ptr<TimerEntry> entry = std::move(heap_.back().entry);
heap_.pop_back();
if (entry->try_leave_pending(TimerEntryState::fired)) {
live_.fetch_sub(1, std::memory_order_acq_rel);
due.push_back(std::move(entry));
} else {
// Cancelled tombstone; cancel() already took its callback.
--tombstones_;
}
}
}
for (auto& entry : due) {
invoke_and_release(*entry, TimerEvent::expired);
}
return due.size();
}
[[nodiscard]] std::optional<time_point> next_deadline()
{
std::lock_guard lk{mu_};
prune_top_locked();
if (heap_.empty()) {
return std::nullopt;
}
return heap_.front().deadline;
}
void close() noexcept
{
std::vector<TimerNode> drained;
{
std::lock_guard lk{mu_};
if (closed_.load(std::memory_order_relaxed)) {
return;
}
closed_.store(true, std::memory_order_release);
drained.swap(heap_);
tombstones_ = 0;
std::size_t kept = 0;
for (auto& node : drained) {
if (node.entry->try_leave_pending(TimerEntryState::fired)) {
if (&drained[kept] != &node) {
drained[kept] = std::move(node);
}
++kept;
}
}
drained.erase(drained.begin() + static_cast<std::ptrdiff_t>(kept),
drained.end());
live_.store(0, std::memory_order_release);
}
std::sort(drained.begin(), drained.end(),
[](const TimerNode& a, const TimerNode& b) noexcept {
return TimerNodeLater{}(b, a);
});
for (auto& node : drained) {
invoke_and_release(*node.entry, TimerEvent::closed);
}
}
private:
static void invoke_and_release(TimerEntry& entry, TimerEvent event) noexcept
{
// Move the callback to this stack frame so it outlives anything the
// invocation may destroy, and is released after it returns.
TimerCallback callback{std::move(entry.callback)};
entry.callback = nullptr;
if (callback) {
callback(event);
}
}
void prune_top_locked() noexcept
{
while (!heap_.empty() && !heap_.front().entry->is_pending()) {
std::pop_heap(heap_.begin(), heap_.end(), TimerNodeLater{});
heap_.pop_back();
--tombstones_;
}
}
void compact_locked() noexcept
{
std::erase_if(heap_, [](const TimerNode& node) noexcept {
return !node.entry->is_pending();
});
std::make_heap(heap_.begin(), heap_.end(), TimerNodeLater{});
tombstones_ = 0;
}
Executor& executor_;
const Void::Time::MonotonicClock& clock_;
const std::size_t max_timers_;
std::mutex mu_{};
std::vector<TimerNode> heap_{};
std::uint64_t next_seq_{0};
std::size_t tombstones_{0};
std::atomic<std::size_t> live_{0};
std::atomic<bool> closed_{false};
};
[[nodiscard]] inline bool cancel_timer_entry(TimerEntry& entry) noexcept
{
bool won = false;
if (auto core = entry.core.lock()) {
won = core->cancel_transition(entry);
} else {
// The core is gone only after close() moved every pending entry to
// `fired`, so this transition is expected to fail; it is still the
// authoritative check.
won = entry.try_leave_pending(TimerEntryState::cancelled);
}
if (won) {
// The cancel winner owns the callback: release it now, outside the
// queue lock, so a cancelled tombstone retains no user state.
TimerCallback discarded{std::move(entry.callback)};
entry.callback = nullptr;
}
return won;
}
} // namespace detail
// Move-only reference to one scheduled timer. Destroying or overwriting a
// handle does NOT cancel the timer (the timer is detached and still fires).
class TimerHandle
{
public:
TimerHandle() noexcept = default;
TimerHandle(TimerHandle&&) noexcept = default;
TimerHandle& operator=(TimerHandle&&) noexcept = default;
TimerHandle(const TimerHandle&) = delete;
TimerHandle& operator=(const TimerHandle&) = delete;
~TimerHandle() = default;
// Returns true when this call moved the timer from pending to cancelled:
// the callback will never run and has already been destroyed (released
// outside the queue lock) when cancel() returns.
//
// Returns false when the handle is empty, the timer was already cancelled,
// or the callback has fired / is firing (expired or closed). false does
// NOT mean the callback has finished running: it may still be executing on
// the polling or closing thread. A callback that touches state which may
// be destroyed after a failed cancel() (e.g. a waiter node inside a
// coroutine frame) must capture shared ownership of that state, or look it
// up under the owner's own lock; it must never hold a raw pointer into a
// frame. Safe to call after the TimerQueue was destroyed (returns false,
// since destruction already delivered TimerEvent::closed).
//
// WARNING: when cancel() returns true (and when schedule_at() rejects a
// timer) the callback object is destroyed synchronously on the caller's
// thread. Do not call cancel() while holding a lock L if the callback may
// hold the last reference to something whose destructor takes or waits on
// L (e.g. a std::stop_callback whose callback blocks on L): move the
// handle out under the lock and cancel after unlocking, or make the
// callback hold only a weak/non-last reference.
bool cancel() noexcept
{
return entry_ ? detail::cancel_timer_entry(*entry_) : false;
}
// True when the handle refers to a timer (i.e. it was returned by
// schedule_at and not moved from); unaffected by the timer's state.
[[nodiscard]] bool valid() const noexcept { return entry_ != nullptr; }
private:
friend class TimerQueue;
explicit TimerHandle(std::shared_ptr<detail::TimerEntry> entry) noexcept
: entry_(std::move(entry))
{
}
std::shared_ptr<detail::TimerEntry> entry_{};
};
namespace detail
{
struct TimerSleepTarget {
bool relative{false};
Void::Time::MonotonicClock::time_point when{};
std::chrono::nanoseconds delta{};
};
// Stop callback for a pending sleep. The entry's pending -> cancelled
// transition is the arbiter: the sleep settles `cancelled` only when this
// callback won it; otherwise the timer callback (expired/closed) settles it.
class TimerSleepStop
{
public:
TimerSleepStop(std::shared_ptr<TimerEntry> entry,
std::shared_ptr<OperationState<void>> state) noexcept
: entry_(std::move(entry))
, state_(std::move(state))
{
}
void operator()() const noexcept
{
// Copy first: once the continuation is dispatched, the frame that
// owns this callback object may resume and be destroyed.
auto entry = entry_;
auto state = state_;
if (cancel_timer_entry(*entry)) {
if (auto ticket = state->try_commit_cancelled("TimerQueue sleep cancelled");
ticket.has_value()) {
ticket->dispatch();
}
}
}
private:
std::shared_ptr<TimerEntry> entry_;
std::shared_ptr<OperationState<void>> state_;
};
// Cancels the sleep's timer when the frame ends, including destruction of a
// suspended sleep task, so an abandoned frame is never resumed by a later
// poll or close (unless the timer already fired).
struct TimerSleepGuard {
std::shared_ptr<TimerEntry> entry{};
TimerSleepGuard() noexcept = default;
explicit TimerSleepGuard(std::shared_ptr<TimerEntry> e) noexcept : entry(std::move(e)) {}
TimerSleepGuard(const TimerSleepGuard&) = delete;
TimerSleepGuard& operator=(const TimerSleepGuard&) = delete;
~TimerSleepGuard()
{
if (entry) {
(void)cancel_timer_entry(*entry);
}
}
};
[[nodiscard]] inline Void::Result::Error timer_admission_error(AdmissionError error)
{
if (error == AdmissionError::overloaded) {
return make_async_error(AdmissionError::overloaded, "TimerQueue capacity exceeded");
}
if (error == AdmissionError::stopped) {
return make_async_error(AdmissionError::stopped, "TimerQueue is closed");
}
return make_async_error(error);
}
// The sleep body is a free coroutine holding the core by value: it never
// touches the TimerQueue object, so a lazily started or suspended sleep task
// may outlive the queue.
inline Coro::Task<Void::Result::Result<void>> timer_sleep(
std::shared_ptr<TimerCore> core,
TimerSleepTarget target,
OperationOptions options)
{
using Void::Result::Result;
if (options.stop.stop_requested()) {
co_return Result<void>{std::unexpect, make_async_error(
AsyncErrorCode::cancelled, "TimerQueue sleep cancelled before admission")};
}
if (core->is_closed()) {
co_return Result<void>{std::unexpect, timer_admission_error(AdmissionError::stopped)};
}
// Single read of the injected clock; the host clock is never consulted.
const auto now = core->clock().now();
const auto when =
target.relative ? Void::Time::saturating_add(now, target.delta) : target.when;
if (options.deadline.has_value() && now >= *options.deadline) {
co_return Result<void>{std::unexpect, make_async_error(
AsyncErrorCode::timeout, "TimerQueue sleep deadline expired before admission")};
}
// One timer per sleeper at min(when, deadline); the outcome is fixed at
// registration: timeout only when the deadline is strictly earlier.
const bool deadline_first = options.deadline.has_value() && *options.deadline < when;
const auto fire_at = deadline_first ? *options.deadline : when;
// Non-null resume executor: every dispatch goes through post_completion.
auto state = OperationState<void>::create(OperationOptions{}, &core->executor());
auto admitted = core->admit(
fire_at,
TimerCallback{[state, deadline_first](TimerEvent event) noexcept {
std::optional<ResumeTicket> ticket;
if (event == TimerEvent::closed) {
ticket = state->try_commit_error(
make_async_error(AsyncErrorCode::stopped, "TimerQueue closed while sleeping"),
DomainOutcomeKind::cancelled);
} else if (deadline_first) {
ticket = state->try_commit_timeout("TimerQueue sleep deadline expired");
} else {
ticket = state->try_commit_value();
}
if (ticket.has_value()) {
ticket->dispatch();
}
}});
if (!admitted.has_value()) {
co_return Result<void>{std::unexpect, timer_admission_error(admitted.error())};
}
TimerSleepGuard guard{std::move(*admitted)};
// Registered after admission so it can cancel the timer. If stop was
// requested meanwhile, the constructor runs the callback inline; the
// state then settles before suspension and the co_await completes
// without suspending (no inline resume of a suspended frame).
std::optional<std::stop_callback<TimerSleepStop>> stop_cb;
if (options.stop.stop_possible()) {
stop_cb.emplace(options.stop, TimerSleepStop{guard.entry, state});
}
auto result = co_await state->awaitable(nullptr);
// Waits for a concurrently running stop callback before the frame moves on.
stop_cb.reset();
co_return result;
}
} // namespace detail
class TimerQueue
{
public:
using time_point = Void::Time::MonotonicClock::time_point;
// Errors: invalid_argument when options.max_timers == 0.
[[nodiscard]] static Void::Result::Result<std::unique_ptr<TimerQueue>>
create(Executor& completion_executor,
const Void::Time::MonotonicClock& clock,
TimerQueueOptions options = {})
{
if (options.max_timers == 0) {
return std::unexpected{make_async_error(
AsyncErrorCode::invalid_argument,
"TimerQueue max_timers must be greater than zero")};
}
auto core = std::make_shared<detail::TimerCore>(
completion_executor, clock, options.max_timers);
return std::unique_ptr<TimerQueue>(new TimerQueue(std::move(core)));
}
TimerQueue(const TimerQueue&) = delete;
TimerQueue& operator=(const TimerQueue&) = delete;
TimerQueue(TimerQueue&&) = delete;
TimerQueue& operator=(TimerQueue&&) = delete;
// Equivalent to close(): pending callbacks receive TimerEvent::closed and
// pending sleepers settle `stopped` (resumed via the completion executor).
~TimerQueue() { close(); }
// Suspends until `when` (in the injected clock domain) has been reached
// and observed by poll_expired(). A `when` already in the past still needs
// a poll. Results (exactly one):
// {} — the timer fired at `when`;
// cancelled — options.stop requested (before admission or while pending);
// timeout — options.deadline is already expired at admission, or
// is strictly earlier than `when` and fired first;
// overloaded — max_timers pending timers already;
// stopped — the queue is (or becomes) closed.
// Checks before admission complete without suspending. A suspended sleep
// is always resumed via executor().post_completion. Destroying a suspended
// sleep task cancels its timer only while the timer is still pending (see
// the lifetime rules at the top of this header); after settlement the task
// must outlive its posted resume.
[[nodiscard]] Coro::Task<Void::Result::Result<void>>
sleep_until(time_point when, OperationOptions options = {})
{
return detail::timer_sleep(
core_, detail::TimerSleepTarget{false, when, {}}, std::move(options));
}
// sleep_until(saturating_add(clock().now(), duration)); "now" is read when
// the task starts. Negative or huge durations saturate instead of wrapping.
[[nodiscard]] Coro::Task<Void::Result::Result<void>>
sleep_for(std::chrono::nanoseconds duration, OperationOptions options = {})
{
return detail::timer_sleep(
core_, detail::TimerSleepTarget{true, {}, duration}, std::move(options));
}
// Schedules `on_event` to run exactly once with TimerEvent::expired (from
// poll_expired at or after `when`) or TimerEvent::closed (from close or
// destruction), or never when TimerHandle::cancel() returns true.
// Errors: invalid_argument (empty callback), overloaded (max_timers
// pending), stopped (closed). On error the callback is destroyed unrun.
[[nodiscard]] std::expected<TimerHandle, AdmissionError>
schedule_at(time_point when, TimerCallback on_event)
{
if (!on_event) {
return std::unexpected{AdmissionError::invalid_argument};
}
auto admitted = core_->admit(when, std::move(on_event));
if (!admitted.has_value()) {
return std::unexpected{admitted.error()};
}
return TimerHandle{std::move(*admitted)};
}
// Reads clock().now() once, removes every pending timer whose deadline is
// <= now in (deadline, seq) order, then runs their callbacks outside the
// internal lock. Timers scheduled by those callbacks fire on a later poll.
// Returns the number of callbacks fired.
[[nodiscard]] std::size_t poll_expired() { return core_->poll_expired(); }
// Earliest pending deadline (cancelled timers are skipped).
[[nodiscard]] std::optional<time_point> next_deadline() const
{
return core_->next_deadline();
}
// Time until the next pending deadline measured with the injected clock,
// clamped to [0, max_wait]; 0 when a timer is already due; max_wait when
// nothing is pending.
[[nodiscard]] std::chrono::nanoseconds wait_duration(std::chrono::nanoseconds max_wait) const noexcept
{
const auto cap = max_wait < std::chrono::nanoseconds::zero()
? std::chrono::nanoseconds::zero()
: max_wait;
const auto next = core_->next_deadline();
if (!next.has_value()) {
return cap;
}
return std::min(Void::Time::remaining_until(core_->clock(), *next), cap);
}
// Number of pending timers (sleepers included); cancelled timers excluded.
[[nodiscard]] std::size_t active_timers() const noexcept { return core_->live(); }
// Idempotent. Marks the queue closed (later schedule_at/sleep_* return
// stopped), then runs every pending callback once with TimerEvent::closed
// in (deadline, seq) order, outside the internal lock.
void close() noexcept { core_->close(); }
[[nodiscard]] const Void::Time::MonotonicClock& clock() const noexcept
{
return core_->clock();
}
[[nodiscard]] Executor& executor() noexcept { return core_->executor(); }
private:
explicit TimerQueue(std::shared_ptr<detail::TimerCore> core) noexcept
: core_(std::move(core))
{
}
std::shared_ptr<detail::TimerCore> core_;
};
} // namespace Void::Async
+44
View File
@@ -5,6 +5,8 @@
#include <cstdint>
#include <expected>
#include <limits>
#include <ratio>
#include <type_traits>
namespace Void::Time
{
@@ -207,4 +209,46 @@ private:
return std::chrono::nanoseconds{dl_ns - now_ns};
}
/// Overflow-safe `point + delta` in the monotonic domain. A result that would
/// leave the representable range clamps to `time_point::max()` (positive
/// overflow) or `time_point::min()` (negative overflow) instead of wrapping.
/// Negative `delta` values are allowed.
[[nodiscard]] inline MonotonicClock::time_point
saturating_add(MonotonicClock::time_point point,
std::chrono::nanoseconds delta) noexcept
{
using TimePoint = MonotonicClock::time_point;
using Duration = TimePoint::duration;
using Rep = Duration::rep;
static_assert(std::is_integral_v<Rep> && std::is_signed_v<Rep>,
"saturating_add requires a signed integral time_point rep");
static_assert(std::ratio_greater_equal_v<Duration::period, std::nano> &&
std::numeric_limits<Rep>::digits >=
std::numeric_limits<std::chrono::nanoseconds::rep>::digits,
"saturating_add requires a time_point period of at least "
"one nanosecond and a rep at least as wide as nanoseconds");
// Converting to an equal or coarser period only shrinks the magnitude, so
// this cast never overflows.
const Rep step = std::chrono::duration_cast<Duration>(delta).count();
const Rep base = point.time_since_epoch().count();
if (step > 0 && base > std::numeric_limits<Rep>::max() - step) {
return TimePoint::max();
}
if (step < 0 && base < std::numeric_limits<Rep>::min() - step) {
return TimePoint::min();
}
return TimePoint{Duration{base + step}};
}
/// Deadline `timeout` after `clock.now()`, computed in `clock`'s own domain
/// with `saturating_add` (so a huge or `nanoseconds::max()` timeout yields
/// `time_point::max()` rather than an overflowed, already-expired deadline).
[[nodiscard]] inline MonotonicClock::time_point
deadline_after(const MonotonicClock& clock,
std::chrono::nanoseconds timeout) noexcept
{
return saturating_add(clock.now(), timeout);
}
} // namespace Void::Time