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:
1 parent
95785ed47a
commit
99a1100bb1
5 files changed
+2269
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
@@ -0,0 +1,244 @@
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/TaskScope.hpp>
|
||||
#include <Void/Async/Timer.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <utility>
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using namespace Void::Async;
|
||||
using namespace std::chrono_literals;
|
||||
using TimePoint = Void::Time::MonotonicClock::time_point;
|
||||
using Void::Time::ManualClock;
|
||||
|
||||
TimePoint at(std::chrono::nanoseconds offset)
|
||||
{
|
||||
return TimePoint{std::chrono::duration_cast<TimePoint::duration>(offset)};
|
||||
}
|
||||
|
||||
void advance_clock(ManualClock& clock, std::chrono::nanoseconds delta)
|
||||
{
|
||||
Void::Testing::require(clock.advance(delta).has_value());
|
||||
}
|
||||
|
||||
std::optional<AsyncErrorCode> code_of(const Void::Result::Result<void>& res)
|
||||
{
|
||||
if (res.has_value()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return static_cast<AsyncErrorCode>(res.error().code().value);
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> schedule_into(Executor* exec,
|
||||
OperationOptions options,
|
||||
const Void::Time::MonotonicClock* clock,
|
||||
std::optional<Void::Result::Result<void>>* out)
|
||||
{
|
||||
*out = co_await schedule_on(*exec, std::move(options), *clock);
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> schedule_host_into(Executor* exec,
|
||||
OperationOptions options,
|
||||
std::optional<Void::Result::Result<void>>* out)
|
||||
{
|
||||
*out = co_await schedule_on(*exec, std::move(options));
|
||||
}
|
||||
|
||||
Void::Coro::Task<void> increment_task(int* counter)
|
||||
{
|
||||
++(*counter);
|
||||
co_return;
|
||||
}
|
||||
|
||||
struct SleepProbe {
|
||||
int resumes{0};
|
||||
std::optional<Void::Result::Result<void>> result{};
|
||||
};
|
||||
|
||||
Void::Coro::Task<void> await_sleep(Void::Coro::Task<Void::Result::Result<void>> sleep,
|
||||
SleepProbe* probe)
|
||||
{
|
||||
auto res = co_await sleep;
|
||||
probe->result = std::move(res);
|
||||
++probe->resumes;
|
||||
}
|
||||
|
||||
void start(Void::Coro::Task<void>& task)
|
||||
{
|
||||
task.handle().resume();
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test deadline_domain_schedule_on_and_scope_admission_injected_clock()
|
||||
{
|
||||
// Precondition: the host steady clock is far past the manual-domain
|
||||
// deadline used below, so host comparisons treat it as expired.
|
||||
Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms);
|
||||
|
||||
ManualExecutor exec;
|
||||
ManualClock clock; // epoch 0
|
||||
const OperationOptions opts{.deadline = at(5ms)};
|
||||
|
||||
// One deadline value, two domains.
|
||||
Void::Testing::expect(is_deadline_expired(opts));
|
||||
Void::Testing::expect(!is_deadline_expired(opts, clock));
|
||||
auto op = OperationState<void>::create(opts);
|
||||
Void::Testing::expect(op->is_deadline_expired());
|
||||
Void::Testing::expect(!op->is_deadline_expired(clock));
|
||||
|
||||
// schedule_on in the manual domain is admitted and runs.
|
||||
std::optional<Void::Result::Result<void>> admitted;
|
||||
auto t1 = schedule_into(&exec, opts, &clock, &admitted);
|
||||
start(t1);
|
||||
Void::Testing::expect(!admitted.has_value());
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::require(admitted.has_value());
|
||||
Void::Testing::expect(admitted->has_value());
|
||||
|
||||
// The default (host) clock rejects the same manual-domain deadline.
|
||||
std::optional<Void::Result::Result<void>> host_rejected;
|
||||
auto t2 = schedule_host_into(&exec, opts, &host_rejected);
|
||||
start(t2);
|
||||
Void::Testing::require(host_rejected.has_value());
|
||||
Void::Testing::expect(code_of(*host_rejected) == AsyncErrorCode::timeout);
|
||||
Void::Testing::expect(exec.empty());
|
||||
|
||||
// Expiry in the manual domain happens only when the manual clock advances.
|
||||
advance_clock(clock, 4ms);
|
||||
std::optional<Void::Result::Result<void>> still_ok;
|
||||
auto t3 = schedule_into(&exec, opts, &clock, &still_ok);
|
||||
start(t3);
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::require(still_ok.has_value());
|
||||
Void::Testing::expect(still_ok->has_value());
|
||||
|
||||
advance_clock(clock, 1ms);
|
||||
std::optional<Void::Result::Result<void>> expired;
|
||||
auto t4 = schedule_into(&exec, opts, &clock, &expired);
|
||||
start(t4);
|
||||
Void::Testing::require(expired.has_value());
|
||||
Void::Testing::expect(code_of(*expired) == AsyncErrorCode::timeout);
|
||||
Void::Testing::expect(exec.empty());
|
||||
|
||||
// Expiry observed between admission and execution is reported on resume.
|
||||
ManualClock hop_clock;
|
||||
std::optional<Void::Result::Result<void>> hop;
|
||||
auto t5 = schedule_into(&exec, opts, &hop_clock, &hop);
|
||||
start(t5);
|
||||
Void::Testing::expect(!hop.has_value());
|
||||
advance_clock(hop_clock, 5ms);
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::require(hop.has_value());
|
||||
Void::Testing::expect(code_of(*hop) == AsyncErrorCode::timeout);
|
||||
|
||||
// TaskScope admission uses the scope's injected clock.
|
||||
ManualClock scope_clock;
|
||||
int ran = 0;
|
||||
{
|
||||
TaskScope scope{exec, TaskScopeOptions{}, scope_clock};
|
||||
auto first = scope.spawn(increment_task(&ran), opts);
|
||||
Void::Testing::expect(first.has_value());
|
||||
advance_clock(scope_clock, 5ms);
|
||||
auto late = scope.spawn(increment_task(&ran), opts);
|
||||
Void::Testing::require(!late.has_value());
|
||||
Void::Testing::expect(late.error() == AdmissionError::deadline_expired);
|
||||
Void::Testing::expect(scope.join_pumping(exec).has_value());
|
||||
}
|
||||
{
|
||||
TaskScope host_scope{exec};
|
||||
auto host_late = host_scope.spawn(increment_task(&ran), opts);
|
||||
Void::Testing::require(!host_late.has_value());
|
||||
Void::Testing::expect(host_late.error() == AdmissionError::deadline_expired);
|
||||
Void::Testing::expect(host_scope.join_pumping(exec).has_value());
|
||||
}
|
||||
Void::Testing::expect_eq(ran, 1);
|
||||
}
|
||||
|
||||
Void::Testing::Test deadline_domain_timer_and_operation_deadline_same_manual_clock()
|
||||
{
|
||||
Void::Testing::require(std::chrono::steady_clock::now().time_since_epoch() > 100ms);
|
||||
|
||||
ManualExecutor exec;
|
||||
ManualClock clock; // epoch 0
|
||||
auto created = TimerQueue::create(exec, clock);
|
||||
Void::Testing::require(created.has_value());
|
||||
auto q = std::move(*created);
|
||||
Void::Testing::expect(&q->clock() == &clock);
|
||||
Void::Testing::expect(&q->executor() == &exec);
|
||||
|
||||
// An OperationOptions deadline in the ManualClock domain bounds the sleep.
|
||||
const OperationOptions opts{.deadline = at(3ms)};
|
||||
SleepProbe probe;
|
||||
auto task = await_sleep(q->sleep_until(at(8ms), opts), &probe);
|
||||
start(task);
|
||||
Void::Testing::expect(!task.done()); // the host clock would call it expired
|
||||
|
||||
Void::Testing::require(q->next_deadline().has_value());
|
||||
Void::Testing::expect(*q->next_deadline() == at(3ms));
|
||||
Void::Testing::expect_eq(q->wait_duration(1s), std::chrono::nanoseconds{3ms});
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{0});
|
||||
Void::Testing::expect(exec.empty());
|
||||
|
||||
advance_clock(clock, 2ms);
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{0});
|
||||
Void::Testing::expect(exec.empty());
|
||||
Void::Testing::expect_eq(probe.resumes, 0);
|
||||
|
||||
// Advance + explicit poll expires it once; the resume goes through the
|
||||
// completion executor.
|
||||
advance_clock(clock, 1ms);
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{1});
|
||||
Void::Testing::expect_eq(probe.resumes, 0);
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::expect_eq(probe.resumes, 1);
|
||||
Void::Testing::require(probe.result.has_value());
|
||||
Void::Testing::expect(code_of(*probe.result) == AsyncErrorCode::timeout);
|
||||
Void::Testing::expect_eq(q->active_timers(), std::size_t{0});
|
||||
|
||||
// Passing `when` later fires nothing and never produces a second result.
|
||||
advance_clock(clock, 10ms);
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{0});
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{0});
|
||||
Void::Testing::expect_eq(probe.resumes, 1);
|
||||
|
||||
// The same deadline is expired for schedule_on in the same manual domain.
|
||||
std::optional<Void::Result::Result<void>> scheduled;
|
||||
auto sched = schedule_into(&exec, opts, &q->clock(), &scheduled);
|
||||
start(sched);
|
||||
Void::Testing::require(scheduled.has_value());
|
||||
Void::Testing::expect(code_of(*scheduled) == AsyncErrorCode::timeout);
|
||||
|
||||
// A deadline equal to `when` is not earlier: the sleep completes normally.
|
||||
SleepProbe equal;
|
||||
const auto target = Void::Time::deadline_after(clock, 5ms);
|
||||
auto equal_task =
|
||||
await_sleep(q->sleep_until(target, OperationOptions{.deadline = target}), &equal);
|
||||
start(equal_task);
|
||||
advance_clock(clock, 5ms);
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{1});
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::require(equal.result.has_value());
|
||||
Void::Testing::expect(equal.result->has_value());
|
||||
|
||||
// A deadline later than `when` does not interfere either.
|
||||
SleepProbe later;
|
||||
auto later_task = await_sleep(
|
||||
q->sleep_for(1ms, OperationOptions{.deadline = Void::Time::deadline_after(clock, 2ms)}),
|
||||
&later);
|
||||
start(later_task);
|
||||
advance_clock(clock, 2ms);
|
||||
Void::Testing::expect_eq(q->poll_expired(), std::size_t{1});
|
||||
Void::Testing::expect_eq(exec.drain(), std::size_t{1});
|
||||
Void::Testing::require(later.result.has_value());
|
||||
Void::Testing::expect(later.result->has_value());
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,112 @@
|
||||
#include <Void/Time/Clock.hpp>
|
||||
#include <Void/Testing/Assert.hpp>
|
||||
#include <Void/Testing/Test.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <utility>
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
|
||||
namespace
|
||||
{
|
||||
|
||||
using TimePoint = Void::Time::MonotonicClock::time_point;
|
||||
|
||||
constexpr std::int64_t kMax = std::numeric_limits<std::int64_t>::max();
|
||||
constexpr std::int64_t kMin = std::numeric_limits<std::int64_t>::min();
|
||||
|
||||
std::int64_t ns_of(TimePoint tp)
|
||||
{
|
||||
return std::chrono::duration_cast<std::chrono::nanoseconds>(
|
||||
tp.time_since_epoch())
|
||||
.count();
|
||||
}
|
||||
|
||||
TimePoint at_ns(std::int64_t ns)
|
||||
{
|
||||
return TimePoint{std::chrono::duration_cast<TimePoint::duration>(
|
||||
std::chrono::nanoseconds{ns})};
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
Void::Testing::Test clock_saturating_add_and_deadline_after_bounds()
|
||||
{
|
||||
using Void::Time::deadline_after;
|
||||
using Void::Time::saturating_add;
|
||||
|
||||
static_assert(noexcept(saturating_add(std::declval<TimePoint>(),
|
||||
std::declval<std::chrono::nanoseconds>())));
|
||||
static_assert(noexcept(
|
||||
deadline_after(std::declval<const Void::Time::MonotonicClock&>(),
|
||||
std::declval<std::chrono::nanoseconds>())));
|
||||
|
||||
// In-range arithmetic, positive and negative steps.
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(0), 5ns)), std::int64_t{5});
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(10), -3ns)), std::int64_t{7});
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(-10), 0ns)), std::int64_t{-10});
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(-1), std::chrono::nanoseconds::max())),
|
||||
kMax - 1);
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(0), std::chrono::nanoseconds::max())),
|
||||
kMax);
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(0), std::chrono::nanoseconds::min())),
|
||||
kMin);
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(at_ns(1), std::chrono::nanoseconds::min())),
|
||||
kMin + 1);
|
||||
|
||||
// Positive overflow clamps to time_point::max().
|
||||
Void::Testing::expect(saturating_add(at_ns(kMax - 1), 2ns) == TimePoint::max());
|
||||
Void::Testing::expect(saturating_add(TimePoint::max(), 1ns) == TimePoint::max());
|
||||
Void::Testing::expect(saturating_add(at_ns(1), std::chrono::nanoseconds::max()) ==
|
||||
TimePoint::max());
|
||||
Void::Testing::expect(saturating_add(TimePoint::max(), std::chrono::nanoseconds::max()) ==
|
||||
TimePoint::max());
|
||||
Void::Testing::expect(saturating_add(TimePoint::max(), 0ns) == TimePoint::max());
|
||||
|
||||
// Negative overflow clamps to time_point::min().
|
||||
Void::Testing::expect(saturating_add(at_ns(kMin + 1), -2ns) == TimePoint::min());
|
||||
Void::Testing::expect(saturating_add(TimePoint::min(), -1ns) == TimePoint::min());
|
||||
Void::Testing::expect(saturating_add(at_ns(-1), std::chrono::nanoseconds::min()) ==
|
||||
TimePoint::min());
|
||||
Void::Testing::expect(saturating_add(TimePoint::min(), std::chrono::nanoseconds::min()) ==
|
||||
TimePoint::min());
|
||||
|
||||
// Extremes in the other direction stay exact.
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(TimePoint::max(), std::chrono::nanoseconds::min())),
|
||||
std::int64_t{-1});
|
||||
Void::Testing::expect_eq(ns_of(saturating_add(TimePoint::min(), std::chrono::nanoseconds::max())),
|
||||
std::int64_t{-1});
|
||||
|
||||
// deadline_after uses the injected clock's own domain, never the host clock.
|
||||
Void::Time::ManualClock epoch_clock;
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(epoch_clock, 1s)),
|
||||
std::int64_t{1'000'000'000});
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(epoch_clock, -5ns)), std::int64_t{-5});
|
||||
Void::Testing::expect(deadline_after(epoch_clock, std::chrono::nanoseconds::max()) ==
|
||||
TimePoint::max());
|
||||
Void::Testing::expect(deadline_after(epoch_clock, std::chrono::nanoseconds::min()) ==
|
||||
TimePoint::min());
|
||||
|
||||
Void::Time::ManualClock offset_clock{at_ns(100)};
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(offset_clock, 50ns)), std::int64_t{150});
|
||||
Void::Testing::require(offset_clock.advance(25ns).has_value());
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(offset_clock, 50ns)), std::int64_t{175});
|
||||
|
||||
Void::Time::ManualClock far_clock{at_ns(kMax - 10)};
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(far_clock, 10ns)), kMax);
|
||||
Void::Testing::expect(deadline_after(far_clock, 1s) == TimePoint::max());
|
||||
Void::Testing::expect(deadline_after(far_clock, std::chrono::nanoseconds::max()) ==
|
||||
TimePoint::max());
|
||||
Void::Testing::expect_eq(ns_of(deadline_after(far_clock, -10ns)), kMax - 20);
|
||||
|
||||
// A saturated deadline is consistent with remaining_until (no wrap to 0).
|
||||
Void::Testing::expect_eq(
|
||||
Void::Time::remaining_until(epoch_clock,
|
||||
deadline_after(epoch_clock, std::chrono::nanoseconds::max())),
|
||||
std::chrono::nanoseconds::max());
|
||||
Void::Testing::expect_eq(
|
||||
Void::Time::remaining_until(far_clock, deadline_after(far_clock, 1h)),
|
||||
std::chrono::nanoseconds{10});
|
||||
}
|
||||
Reference in new issue
Block a user