use super::{DispatchEdge, DispatchError, Index, PointKind, Wait, index};
use crate::Ticks;
pub(super) trait Source {
fn point_count(&self) -> usize;
fn edge_count(&self) -> usize;
fn wait_count(&self) -> usize;
fn point(&self, i: usize) -> Option<PointKind>;
fn edge(&self, i: usize) -> Option<DispatchEdge>;
fn wait(&self, i: usize) -> Option<Wait>;
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Slices<'a> {
pub(super) points: &'a [PointKind],
pub(super) edges: &'a [DispatchEdge],
pub(super) waits: &'a [Wait],
}
impl Source for Slices<'_> {
fn point_count(&self) -> usize {
self.points.len()
}
fn edge_count(&self) -> usize {
self.edges.len()
}
fn wait_count(&self) -> usize {
self.waits.len()
}
fn point(&self, i: usize) -> Option<PointKind> {
self.points.get(i).copied()
}
fn edge(&self, i: usize) -> Option<DispatchEdge> {
self.edges.get(i).copied()
}
fn wait(&self, i: usize) -> Option<Wait> {
self.waits.get(i).copied()
}
}
pub(super) fn entry_count(net: &impl Source) -> Result<usize, DispatchError> {
net.edge_count()
.checked_mul(2)
.and_then(|e| e.checked_add(net.wait_count()))
.ok_or(DispatchError::CapacityExceeded)
}
pub(super) fn validate<I: Index>(
net: &impl Source,
n_cap: usize,
e_cap: usize,
) -> Result<(), DispatchError> {
let n = net.point_count();
let entries = entry_count(net)?;
if n > n_cap || entries > e_cap {
return Err(DispatchError::CapacityExceeded);
}
index::<I>(n)?;
index::<I>(entries)?;
let valid = (0..n).all(|p| valid_point(net, p))
&& (0..net.edge_count()).all(|i| net.edge(i).is_some_and(|e| valid_edge(&e, n)))
&& (0..net.wait_count()).all(|i| net.wait(i).is_some_and(|w| valid_wait(net, &w)));
if !valid {
return Err(DispatchError::InvalidNetwork);
}
Ok(())
}
fn valid_point(net: &impl Source, p: usize) -> bool {
let Some(kind) = net.point(p) else {
return false;
};
let PointKind::Contingent { lo, hi, .. } = kind else {
return true;
};
if lo <= Ticks::ZERO || hi < lo {
return false;
}
let mut current = p;
for _ in 0..net.point_count() {
match net.point(current) {
Some(PointKind::Contingent { activation, .. }) => current = activation.0,
Some(PointKind::Executable) => return true,
None => return false,
}
}
false
}
fn valid_edge(e: &DispatchEdge, n: usize) -> bool {
e.from.0 < n && e.to.0 < n && (e.from != e.to || e.weight >= Ticks::ZERO)
}
fn valid_wait(net: &impl Source, w: &Wait) -> bool {
matches!(net.point(w.waiter.0), Some(PointKind::Executable))
&& matches!(
net.point(w.contingent.0),
Some(PointKind::Contingent { .. })
)
}