pub mod encoding;
mod index;
#[cfg(feature = "alloc")]
mod network;
#[cfg(any(test, kani))]
mod proofs;
mod source;
use core::fmt;
use crate::{Ticks, TimePoint};
use source::{Slices, Source};
pub use encoding::{DecodeError, EncodeError};
pub use index::Index;
#[cfg(feature = "alloc")]
pub use network::DispatchableNetwork;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum PointKind {
Executable,
Contingent {
activation: TimePoint,
lo: Ticks,
hi: Ticks,
},
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct DispatchEdge {
pub from: TimePoint,
pub to: TimePoint,
pub weight: Ticks,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Wait {
pub waiter: TimePoint,
pub contingent: TimePoint,
pub delay: Ticks,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DispatchError {
CapacityExceeded,
IndexTypeTooSmall,
InvalidNetwork,
UnknownTimePoint,
TimeWentBackwards,
NotExecutable(TimePoint),
AlreadyHappened(TimePoint),
DeadlineMissed(TimePoint),
ContingentOutOfBounds(TimePoint),
ConstraintViolated(TimePoint),
OutputFull,
Overflow,
}
impl fmt::Display for DispatchError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::CapacityExceeded => f.write_str("dispatcher capacity exceeded"),
Self::IndexTypeTooSmall => f.write_str("network too large for the index type"),
Self::InvalidNetwork => f.write_str("malformed dispatchable network"),
Self::UnknownTimePoint => f.write_str("unknown time point or wrong kind"),
Self::TimeWentBackwards => f.write_str("time went backwards"),
Self::NotExecutable(tp) => write!(f, "time point {} may not execute now", tp.0),
Self::AlreadyHappened(tp) => write!(f, "time point {} already happened", tp.0),
Self::DeadlineMissed(tp) => write!(f, "deadline of time point {} missed", tp.0),
Self::ContingentOutOfBounds(tp) => {
write!(f, "contingent time point {} outside its bounds", tp.0)
}
Self::ConstraintViolated(tp) => write!(f, "constraint on time point {} violated", tp.0),
Self::OutputFull => f.write_str("output buffer full"),
Self::Overflow => f.write_str("tick arithmetic overflowed"),
}
}
}
impl core::error::Error for DispatchError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Kind<I> {
Executable,
Contingent {
activation: I,
lo: Ticks,
hi: Ticks,
},
}
impl<I: Index> Kind<I> {
fn narrow(kind: PointKind) -> Result<Self, DispatchError> {
Ok(match kind {
PointKind::Executable => Self::Executable,
PointKind::Contingent { activation, lo, hi } => Self::Contingent {
activation: index(activation.0)?,
lo,
hi,
},
})
}
fn widen(self) -> PointKind {
match self {
Self::Executable => PointKind::Executable,
Self::Contingent { activation, lo, hi } => PointKind::Contingent {
activation: TimePoint(activation.to_usize()),
lo,
hi,
},
}
}
const fn is_executable(self) -> bool {
matches!(self, Self::Executable)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Entry<I> {
Empty,
Upper {
target: I,
weight: Ticks,
},
Lower {
target: I,
weight: Ticks,
},
Wait {
contingent: I,
delay: Ticks,
},
}
#[derive(Debug, Clone)]
pub struct Dispatcher<const N: usize, const E: usize, I: Index = usize> {
n: usize,
kinds: [Kind<I>; N],
lb: [Option<Ticks>; N],
ub: [Option<Ticks>; N],
time: [Option<Ticks>; N],
pending: [I; N],
start: [I; N],
m: usize,
entries: [Entry<I>; E],
now: Option<Ticks>,
}
impl<const N: usize, const E: usize, I: Index> Dispatcher<N, E, I> {
pub const EMPTY: Self = Self {
n: 0,
kinds: [Kind::Executable; N],
lb: [None; N],
ub: [None; N],
time: [None; N],
pending: [I::ZERO; N],
start: [I::ZERO; N],
m: 0,
entries: [Entry::Empty; E],
now: None,
};
pub fn new(
points: &[PointKind],
edges: &[DispatchEdge],
waits: &[Wait],
) -> Result<Self, DispatchError> {
let mut d = Self::EMPTY;
d.load(points, edges, waits)?;
Ok(d)
}
pub fn load(
&mut self,
points: &[PointKind],
edges: &[DispatchEdge],
waits: &[Wait],
) -> Result<(), DispatchError> {
self.load_from(&Slices {
points,
edges,
waits,
})
}
pub fn load_encoded(&mut self, bytes: &[u8]) -> Result<(), DecodeError> {
let encoded = encoding::Encoded::parse(bytes)?;
self.load_from(&encoded).map_err(DecodeError::Network)
}
fn load_from(&mut self, net: &impl Source) -> Result<(), DispatchError> {
source::validate::<I>(net, N, E)?;
self.clear();
let filled = self.fill(net);
if filled.is_err() {
self.clear();
}
filled
}
pub fn observe(&mut self, tp: TimePoint, now: Ticks) -> Result<(), DispatchError> {
let PointKind::Contingent {
activation, lo, hi, ..
} = self.kind(tp)?
else {
return Err(DispatchError::UnknownTimePoint);
};
self.ensure_unhappened(tp)?;
self.advance_clock(now)?;
let in_bounds = self.time[activation.0].is_some_and(|a| {
a.checked_add(lo).is_some_and(|l| l <= now)
&& a.checked_add(hi).is_none_or(|h| now <= h)
});
let in_window = self.in_window(tp.0, now);
self.happen(tp.0, now)?;
if !in_bounds {
return Err(DispatchError::ContingentOutOfBounds(tp));
}
if !in_window {
return Err(DispatchError::ConstraintViolated(tp));
}
Ok(())
}
#[must_use]
pub fn can_execute(&self, tp: TimePoint, now: Ticks) -> bool {
tp.0 < self.n
&& self.kinds[tp.0].is_executable()
&& self.time[tp.0].is_none()
&& self.now.is_none_or(|t| t <= now)
&& self.pending[tp.0] == I::ZERO
&& self.in_window(tp.0, now)
&& self.waits_satisfied(tp.0, now)
}
pub fn execute(&mut self, tp: TimePoint, now: Ticks) -> Result<(), DispatchError> {
if !self.can_execute(tp, now) {
return Err(DispatchError::NotExecutable(tp));
}
self.now = Some(now);
self.happen(tp.0, now)
}
pub fn check_deadlines(&mut self, now: Ticks) -> Result<(), DispatchError> {
self.advance_clock(now)?;
for p in 0..self.n {
if self.time[p].is_some() {
continue;
}
let deadline = match self.kinds[p] {
Kind::Executable => self.ub[p],
Kind::Contingent { activation, hi, .. } => {
self.time[activation.to_usize()].and_then(|a| a.checked_add(hi))
}
};
if deadline.is_some_and(|d| d < now) {
return Err(match self.kinds[p] {
Kind::Executable => DispatchError::DeadlineMissed(TimePoint(p)),
Kind::Contingent { .. } => DispatchError::ContingentOutOfBounds(TimePoint(p)),
});
}
}
Ok(())
}
pub fn step(
&mut self,
now: Ticks,
observed: &[TimePoint],
out: &mut [TimePoint],
) -> Result<usize, DispatchError> {
for &c in observed {
self.observe(c, now)?;
}
self.check_deadlines(now)?;
let mut count = 0;
while let Some(tp) = self.next_executable(now) {
let slot = out.get_mut(count).ok_or(DispatchError::OutputFull)?;
*slot = tp;
count += 1;
self.execute(tp, now)?;
}
Ok(count)
}
#[must_use]
pub fn next_wakeup(&self) -> Option<Ticks> {
let floor = self.now.unwrap_or(Ticks(i64::MIN));
(0..self.n)
.filter(|&p| self.kinds[p].is_executable() && self.time[p].is_none())
.filter(|&p| self.pending[p] == I::ZERO)
.filter_map(|p| self.earliest_start(p, floor))
.min()
}
#[must_use]
pub fn time(&self, tp: TimePoint) -> Option<Ticks> {
self.time.get(..self.n)?.get(tp.0).copied().flatten()
}
#[must_use]
pub fn window(&self, tp: TimePoint) -> Option<(Option<Ticks>, Option<Ticks>)> {
(tp.0 < self.n).then(|| (self.lb[tp.0], self.ub[tp.0]))
}
#[must_use]
pub fn is_complete(&self) -> bool {
self.time[..self.n].iter().all(Option::is_some)
}
fn kind(&self, tp: TimePoint) -> Result<PointKind, DispatchError> {
self.kinds[..self.n]
.get(tp.0)
.map(|k| k.widen())
.ok_or(DispatchError::UnknownTimePoint)
}
fn ensure_unhappened(&self, tp: TimePoint) -> Result<(), DispatchError> {
if self.time[tp.0].is_some() {
return Err(DispatchError::AlreadyHappened(tp));
}
Ok(())
}
fn advance_clock(&mut self, now: Ticks) -> Result<(), DispatchError> {
if self.now.is_some_and(|t| now < t) {
return Err(DispatchError::TimeWentBackwards);
}
self.now = Some(now);
Ok(())
}
fn in_window(&self, p: usize, now: Ticks) -> bool {
self.lb[p].is_none_or(|l| l <= now) && self.ub[p].is_none_or(|u| now <= u)
}
fn range_of(&self, p: usize) -> core::ops::Range<usize> {
let end = if p + 1 < self.n {
self.start[p + 1].to_usize()
} else {
self.m
};
self.start[p].to_usize()..end
}
fn entries_of(&self, p: usize) -> &[Entry<I>] {
&self.entries[self.range_of(p)]
}
fn waits_satisfied(&self, p: usize, now: Ticks) -> bool {
self.entries_of(p).iter().all(|e| match *e {
Entry::Wait { contingent, delay } => {
self.wait_released(contingent.to_usize(), delay, now)
}
_ => true,
})
}
fn wait_released(&self, contingent: usize, delay: Ticks, now: Ticks) -> bool {
self.wait_release_time(contingent, delay)
.is_some_and(|r| r <= now)
}
fn wait_release_time(&self, contingent: usize, delay: Ticks) -> Option<Ticks> {
if self.time[contingent].is_some() {
return Some(Ticks(i64::MIN));
}
let Kind::Contingent { activation, .. } = self.kinds[contingent] else {
return None;
};
self.time[activation.to_usize()].and_then(|a| a.checked_add(delay))
}
fn earliest_start(&self, p: usize, floor: Ticks) -> Option<Ticks> {
let mut t = self.lb[p].map_or(floor, |l| l.max(floor));
for e in self.entries_of(p) {
if let Entry::Wait { contingent, delay } = *e {
t = t.max(self.wait_release_time(contingent.to_usize(), delay)?);
}
}
self.ub[p].is_none_or(|u| t <= u).then_some(t)
}
fn next_executable(&self, now: Ticks) -> Option<TimePoint> {
(0..self.n)
.map(TimePoint)
.find(|&tp| self.can_execute(tp, now))
}
fn happen(&mut self, p: usize, t: Ticks) -> Result<(), DispatchError> {
self.time[p] = Some(t);
let mut result = Ok(());
for i in self.range_of(p) {
let outcome = match self.entries[i] {
Entry::Upper { target, weight } => self.tighten_upper(target.to_usize(), t, weight),
Entry::Lower { target, weight } => {
self.tighten_lower(p, target.to_usize(), t, weight)
}
Entry::Wait { .. } | Entry::Empty => Ok(()),
};
if result.is_ok() {
result = outcome;
}
}
result
}
fn tighten_upper(
&mut self,
target: usize,
t: Ticks,
weight: Ticks,
) -> Result<(), DispatchError> {
let Some(bound) = t.checked_add(weight) else {
return if weight.0 > 0 {
Ok(())
} else {
Err(DispatchError::Overflow)
};
};
if let Some(s) = self.time[target] {
return ok_or_violated(s <= bound, target);
}
if self.ub[target].is_none_or(|u| bound < u) {
self.ub[target] = Some(bound);
}
ok_or_violated(self.window_nonempty(target), target)
}
fn tighten_lower(
&mut self,
owner: usize,
target: usize,
t: Ticks,
weight: Ticks,
) -> Result<(), DispatchError> {
if is_precedence(target, owner, weight) && self.time[target].is_none() {
self.pending[target] = self.pending[target].saturating_dec();
}
let Some(bound) = weight.checked_neg().and_then(|w| t.checked_add(w)) else {
return if weight.0 > 0 {
Ok(())
} else {
Err(DispatchError::Overflow)
};
};
if let Some(s) = self.time[target] {
return ok_or_violated(bound <= s, target);
}
if self.lb[target].is_none_or(|l| bound > l) {
self.lb[target] = Some(bound);
}
ok_or_violated(self.window_nonempty(target), target)
}
fn window_nonempty(&self, p: usize) -> bool {
match (self.lb[p], self.ub[p]) {
(Some(l), Some(u)) => l <= u,
_ => true,
}
}
fn clear(&mut self) {
self.n = 0;
self.kinds.fill(Kind::Executable);
self.lb.fill(None);
self.ub.fill(None);
self.time.fill(None);
self.pending.fill(I::ZERO);
self.start.fill(I::ZERO);
self.m = 0;
self.entries.fill(Entry::Empty);
self.now = None;
}
fn fill(&mut self, net: &impl Source) -> Result<(), DispatchError> {
for (p, slot) in self.kinds.iter_mut().take(net.point_count()).enumerate() {
*slot = Kind::narrow(record(net.point(p))?)?;
}
self.n = net.point_count();
self.count_entries(net)?;
self.fill_entries(net)
}
fn count_entries(&mut self, net: &impl Source) -> Result<(), DispatchError> {
for i in 0..net.edge_count() {
let e = record(net.edge(i))?;
increment(&mut self.start[e.from.0])?;
increment(&mut self.start[e.to.0])?;
if is_precedence(e.from.0, e.to.0, e.weight) {
increment(&mut self.pending[e.from.0])?;
}
}
for i in 0..net.wait_count() {
increment(&mut self.start[record(net.wait(i))?.waiter.0])?;
}
let mut end = 0usize;
for p in 0..self.n {
end += self.start[p].to_usize();
self.start[p] = index(end)?;
}
self.m = end;
Ok(())
}
fn fill_entries(&mut self, net: &impl Source) -> Result<(), DispatchError> {
for i in (0..net.wait_count()).rev() {
let w = record(net.wait(i))?;
let entry = Entry::Wait {
contingent: index(w.contingent.0)?,
delay: w.delay,
};
self.push_back(w.waiter.0, entry);
}
for i in (0..net.edge_count()).rev() {
let e = record(net.edge(i))?;
let (u, v) = (e.from.0, e.to.0);
let lower = Entry::Lower {
target: index(u)?,
weight: e.weight,
};
let upper = Entry::Upper {
target: index(v)?,
weight: e.weight,
};
self.push_back(v, lower);
self.push_back(u, upper);
}
Ok(())
}
fn push_back(&mut self, owner: usize, entry: Entry<I>) {
let slot = self.start[owner].saturating_dec();
self.start[owner] = slot;
self.entries[slot.to_usize()] = entry;
}
}
fn record<T>(value: Option<T>) -> Result<T, DispatchError> {
value.ok_or(DispatchError::InvalidNetwork)
}
fn index<I: Index>(value: usize) -> Result<I, DispatchError> {
I::from_usize(value).ok_or(DispatchError::IndexTypeTooSmall)
}
fn increment<I: Index>(counter: &mut I) -> Result<(), DispatchError> {
*counter = index(counter.to_usize().saturating_add(1))?;
Ok(())
}
fn is_precedence(from: usize, to: usize, weight: Ticks) -> bool {
weight < Ticks::ZERO && from != to
}
fn ok_or_violated(ok: bool, p: usize) -> Result<(), DispatchError> {
if ok {
Ok(())
} else {
Err(DispatchError::ConstraintViolated(TimePoint(p)))
}
}