Struct TickScheduler

pub struct TickScheduler<T> { /* private fields */ }
Expand description

A bounded deadline queue ordered by tick, then original insertion order.

Capacity counts tasks, not payload bytes. Tick values are caller supplied; scheduling or rescheduling into the past makes work ready on the next drain.

Implementations§

§

impl<T> TickScheduler<T>

pub fn new(capacity: usize) -> TickScheduler<T>

Creates an empty queue with a maximum task count. Zero rejects all tasks.

pub fn with_scope_capacity( capacity: usize, scope_capacity: usize, ) -> TickScheduler<T>

Creates a queue with independent task and live-scope count limits.

Allocates fixed scope storage and one shared identity when scope_capacity is nonzero. Scope creation, cloning, validation and cancellation do not grow this storage. Payload bytes and caller-held handle clones are not bounded by these counts. Allocation failure follows ordinary std policy. Self::new remains unscoped and allocates no scope storage. See the module’s runnable respawn recipe.

pub fn create_scope(&mut self) -> Option<ScopeId>

Acquires a scope slot, or returns None without mutation when none is free.

Reuse increments its generation. Slots at generation u64::MAX retire after cancellation rather than wrap and revive stale handles. Empty scopes still occupy a slot; cancelling/draining individual jobs does not free it. Task capacity and task IDs are unaffected. See the module recipe.

pub fn is_scope_active(&self, scope: &ScopeId) -> bool

Whether this scheduler still owns the live generation of scope.

Foreign handles are rejected even if their slot and generation match. See the module recipe for stale-handle rejection across restart.

pub fn schedule_scoped( &mut self, scope: &ScopeId, tick: u64, task: T, ) -> Result<TaskId, T>

Schedules a job belonging to a live scope at an absolute tick.

Returns the payload unchanged for a foreign/stale scope, full queue or exhausted task ID sequence, consuming no ID or capacity on rejection. Scoped and unscoped jobs share one capacity and original FIFO sequence. Rescheduling preserves membership; ready draining returns just the payload and never invokes it. See the module’s runnable respawn recipe.

pub fn cancel_scope(&mut self, scope: &ScopeId) -> Option<usize>

Invalidates a scope and discards all its queued payloads, returning a count.

A live empty scope returns Some(0). Foreign/stale handles return None without mutation. Uses Self::cancel_scope_with with drop; callable payloads are dropped, never executed. Its ordering and panic policy apply. See the module recipe for cancelling a round before resetting its clock.

pub fn cancel_scope_with( &mut self, scope: &ScopeId, cancel: impl FnMut(TaskId, T), ) -> Option<usize>

Invalidates a scope and passes its queued jobs to cancel in deadline/FIFO order, returning their count. Other scopes, unscoped jobs, deadlines and the task ID sequence stay unchanged. Allocates no collection or tree nodes.

The callback owns each payload and can retain, return through caller storage, or discard it. The scope is invalidated before any callback runs. On callback/destructor panic with unwinding, the current job is already removed and all unvisited members are discarded by a guard, without more callbacks. The scope stays invalid. A second destructor panic during unwinding follows Rust’s abort policy; panic=abort has no cleanup guarantee. Callback/destructor allocations and side effects are caller-owned.

A foreign/stale handle returns None and never invokes the callback. Scanning is linear in queued jobs plus tree-removal costs. The scheduler stays exclusively borrowed for the call; callbacks cannot reenter it.

use ferravex_engine::scheduler::TickScheduler;
let mut jobs = TickScheduler::with_scope_capacity(3, 1);
let scope = jobs.create_scope().unwrap();
assert!(jobs.is_scope_active(&scope));
let id = jobs.schedule_scoped(&scope, 10, "respawn").unwrap();
let mut returned = Vec::with_capacity(1);
assert_eq!(jobs.cancel_scope_with(&scope, |id, job| returned.push((id, job))), Some(1));
assert_eq!(returned, [(id, "respawn")]);
assert!(!jobs.is_scope_active(&scope));
assert_eq!(jobs.cancel_scope_with(&scope, |_, _| unreachable!()), None);
ⓘ
use ferravex_engine::scheduler::TickScheduler;
let mut jobs = TickScheduler::<()>::with_scope_capacity(1, 1);
let scope = jobs.create_scope().unwrap();
jobs.cancel_scope_with(&scope, |_, _| { jobs.create_scope(); });

pub fn schedule(&mut self, tick: u64, task: T) -> Result<TaskId, T>

Schedules a task at an absolute tick, returning its stable ID.

Returns the task unchanged if capacity or the ID sequence is exhausted. Equal deadlines run in original insertion order, even after rescheduling.

pub fn cancel(&mut self, id: TaskId) -> Option<T>

Removes a task, returning its payload, or None if it is no longer queued.

pub fn reschedule(&mut self, id: TaskId, tick: u64) -> Option<u64>

Changes a queued task’s absolute deadline and returns the previous tick.

An absent, cancelled or drained ID returns None without changing the queue. Every u64 tick is valid, including past ticks and u64::MAX. Rescheduling to the same tick is a successful no-op.

The task keeps its ID and original insertion order among equal deadlines. No capacity or new ID is consumed, so this works even when the queue is full or the ID sequence is exhausted. Like cancellation, finding the ID takes a linear scan; changing the deadline may allocate tree nodes.

use ferravex_engine::scheduler::TickScheduler;

let mut tasks = TickScheduler::new(2);
let first = tasks.schedule(20, "first").unwrap();
tasks.schedule(10, "second").unwrap();
assert_eq!(tasks.reschedule(first, 10), Some(20));
assert_eq!(tasks.drain_ready(10, 2), ["first", "second"]);
assert_eq!(tasks.reschedule(first, 30), None);

pub fn next_tick(&self) -> Option<u64>

Earliest queued deadline, including work left over from a limited drain.

pub fn drain_ready(&mut self, tick: u64, limit: usize) -> Vec<T>

Collects at most limit due tasks; excess work remains for a later call.

This convenience method collects into a fresh vector, which may allocate. Use Self::drain_ready_iter or Self::drain_ready_into to avoid that allocation. All draining methods preserve deadline and FIFO tie order.

pub fn drain_ready_iter( &mut self, tick: u64, limit: usize, ) -> impl FusedIterator

Lazily removes at most limit tasks with deadlines at or before tick.

The iterator neither allocates nor clones payloads. Only yielded tasks leave the queue: dropping it early leaves all unyielded tasks available for a later drain, cancellation or rescheduling. A zero limit removes nothing. The scheduler stays mutably borrowed until the iterator is dropped, and the iterator remains exhausted after returning None.

use ferravex_engine::scheduler::TickScheduler;

let mut tasks = TickScheduler::new(3);
tasks.schedule(4, "first").unwrap();
let second = tasks.schedule(4, "second").unwrap();
tasks.schedule(8, "later").unwrap();
{
    let mut ready = tasks.drain_ready_iter(4, 2);
    assert_eq!(ready.next(), Some("first"));
} // The unyielded second task is still queued.
assert_eq!(tasks.cancel(second), Some("second"));
assert_eq!(tasks.next_tick(), Some(8));

pub fn drain_ready_into( &mut self, tick: u64, limit: usize, out: &mut Vec<T>, ) -> usize

Appends ready tasks to out without allocating or growing its capacity.

Removes at most limit tasks and at most out.capacity() - out.len() tasks, returning the number appended. Existing output entries are kept. Ready work that does not fit remains queued, including when the buffer has no spare capacity. Clear or consume the buffer between ticks to reuse its storage. Tasks are moved without cloning.

use ferravex_engine::scheduler::TickScheduler;

let mut tasks = TickScheduler::new(3);
tasks.schedule(4, "first").unwrap();
tasks.schedule(4, "second").unwrap();
tasks.schedule(8, "later").unwrap();
let mut ready = Vec::with_capacity(2);
ready.push("already collected");
assert_eq!(tasks.drain_ready_into(4, 1, &mut ready), 1);
assert_eq!(ready, ["already collected", "first"]);
ready.clear();
assert_eq!(tasks.drain_ready_into(4, 2, &mut ready), 1);
assert_eq!(ready, ["second"]);
assert_eq!(tasks.next_tick(), Some(8));

pub fn len(&self) -> usize

Number of queued tasks, including overdue work.

pub fn is_empty(&self) -> bool

Whether no tasks are queued.

Auto Trait Implementations§

§

impl<T> Freeze for TickScheduler<T>

§

impl<T> RefUnwindSafe for TickScheduler<T>
where T: RefUnwindSafe,

§

impl<T> Send for TickScheduler<T>
where T: Send,

§

impl<T> Sync for TickScheduler<T>
where T: Sync,

§

impl<T> Unpin for TickScheduler<T>

§

impl<T> UnwindSafe for TickScheduler<T>
where T: RefUnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.