mod closure;
mod contingent;
mod cut;
mod member;
mod precedence;
mod state;
use alloc::vec::Vec;
pub use contingent::{Anchor, Contingent, Uncertain};
use member::{Extreme, Member, Shape};
use precedence::Network;
pub use precedence::{Endpoint, Precedence};
pub use state::{FlexibleState, StateEnvelope, StateEnvelopeViolation, StateVerdict};
use crate::storage::{Heap, Storage};
const DEFAULT_CUT_BUDGET: usize = 4096;
use crate::{ActivityId, Bound, Error, Impact, Level, Tick, Timeline, Window};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Flexible<'a> {
pub activity: ActivityId,
pub window: Window,
pub impacts: &'a [Impact],
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum Verdict {
Safe,
Possible(EnvelopeViolation),
Certain(EnvelopeViolation),
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct EnvelopeViolation {
pub at: Tick,
pub level: Level,
pub bound: Bound,
pub contributors: Vec<ActivityId>,
}
#[derive(Debug, Clone)]
pub struct Envelope<'a, S: Storage = Heap> {
timeline: &'a Timeline<S>,
members: Vec<Member<'a>>,
windows: Vec<Window>,
durations: Vec<Window>,
cut_budget: usize,
precedences: Vec<Precedence>,
network: Option<Network>,
}
impl<'a, S: Storage> Envelope<'a, S> {
pub fn new(timeline: &'a Timeline<S>, flexible: &'a [Flexible<'a>]) -> Result<Self, Error> {
for activity in flexible {
for impact in activity.impacts {
for start in [activity.window.earliest(), activity.window.latest()] {
timeline.validate(impact.shifted(start).ok_or(Error::Overflow)?)?;
}
}
}
let mut envelope = Self {
timeline,
members: Vec::new(),
windows: Vec::new(),
durations: Vec::new(),
cut_budget: DEFAULT_CUT_BUDGET,
precedences: Vec::new(),
network: None,
};
envelope.extend(flexible.iter().map(|activity| Member {
activity: activity.activity,
window: activity.window,
shape: Shape::Fixed(activity.impacts),
}))?;
Ok(envelope)
}
pub fn with_contingent(mut self, contingent: &'a [Contingent<'a>]) -> Result<Self, Error> {
for activity in contingent {
self.validate_contingent(activity)?;
}
self.extend(contingent.iter().map(|activity| Member {
activity: activity.activity,
window: activity.window,
shape: Shape::Uncertain {
duration: activity.duration,
impacts: activity.impacts,
},
}))?;
self.couple()?;
Ok(self)
}
pub fn with_precedences(mut self, precedences: &[Precedence]) -> Result<Self, Error> {
self.precedences
.try_reserve(precedences.len())
.map_err(|_| Error::OutOfMemory)?;
self.precedences.extend_from_slice(precedences);
self.couple()?;
Ok(self)
}
pub fn with_cut_budget(mut self, nodes: usize) -> Result<Self, Error> {
self.cut_budget = nodes;
self.couple()?;
Ok(self)
}
#[must_use]
pub fn duration(&self, activity: ActivityId) -> Option<Window> {
self.members
.iter()
.position(|member| member.activity == activity)
.map(|index| self.durations[index])
}
#[must_use]
pub fn window(&self, activity: ActivityId) -> Option<Window> {
self.members
.iter()
.position(|member| member.activity == activity)
.map(|index| self.windows[index])
}
pub fn lower_at(&self, t: Tick) -> Result<Level, Error> {
self.level_at(t, Extreme::Lower)
}
pub fn upper_at(&self, t: Tick) -> Result<Level, Error> {
self.level_at(t, Extreme::Upper)
}
pub fn check(&self) -> Result<Verdict, Error> {
let mut possible = None;
for t in self.evaluation_ticks()? {
let (lower, upper) = (self.lower_at(t)?, self.upper_at(t)?);
for (min, max, target) in self.limits_at(t) {
if let Some((level, bound)) = certain_breach(lower, upper, min, max, target) {
return Ok(Verdict::Certain(self.explain(t, level, bound)?));
}
if possible.is_none() {
if let Some((level, bound)) = possible_breach(lower, upper, min, max, target) {
possible = Some(self.explain(t, level, bound)?);
}
}
}
}
Ok(possible.map_or(Verdict::Safe, Verdict::Possible))
}
fn extend(&mut self, members: impl ExactSizeIterator<Item = Member<'a>>) -> Result<(), Error> {
let extra = members.len();
self.members
.try_reserve(extra)
.map_err(|_| Error::OutOfMemory)?;
self.windows
.try_reserve(extra)
.map_err(|_| Error::OutOfMemory)?;
self.durations
.try_reserve(extra)
.map_err(|_| Error::OutOfMemory)?;
for member in members {
self.windows.push(member.window);
self.durations.push(member.duration());
self.members.push(member);
}
Ok(())
}
fn couple(&mut self) -> Result<(), Error> {
if self.precedences.is_empty() {
return Ok(());
}
let (tightened, network) =
Network::propagate(&self.members, &self.precedences, self.cut_budget)?;
self.windows = tightened.windows;
self.durations = tightened.durations;
self.network = Some(network);
Ok(())
}
fn validate_contingent(&self, activity: &Contingent<'_>) -> Result<(), Error> {
let duration = activity.duration;
if duration.earliest() < 0 {
return Err(Error::NegativeDuration {
shortest: duration.earliest(),
});
}
for impact in activity.impacts {
for length in [duration.earliest(), duration.latest()] {
let relative = impact.resolve(length).ok_or(Error::Overflow)?;
let relative = contingent::widened(relative)?;
for start in [activity.window.earliest(), activity.window.latest()] {
let shifted = relative.shifted(start).ok_or(Error::Overflow)?;
self.timeline.validate(shifted)?;
}
}
}
Ok(())
}
fn limits_at(&self, t: Tick) -> impl Iterator<Item = (Level, Level, bool)> + '_ {
let bounds = self.timeline.bounds();
let targets = self
.timeline
.targets()
.iter()
.filter(move |target| target.at == t)
.map(|target| (target.min, Level::MAX, true));
core::iter::once((bounds.min(), bounds.max(), false)).chain(targets)
}
fn level_at(&self, t: Tick, extreme: Extreme) -> Result<Level, Error> {
let mut level = i128::from(self.timeline.level_at(t)?);
for (index, member) in self.members.iter().enumerate() {
if self
.network
.as_ref()
.is_some_and(|network| network.is_coupled(index))
{
continue;
}
let (window, duration) = (self.windows[index], self.durations[index]);
let contribution = member.extreme_at(window, duration, t, extreme)?;
level = level.checked_add(contribution).ok_or(Error::Overflow)?;
}
if let Some(network) = &self.network {
let coupled = network.coupled_extreme(&self.members, t, extreme)?;
level = level.checked_add(coupled).ok_or(Error::Overflow)?;
}
Level::try_from(level).map_err(|_| Error::Overflow)
}
fn evaluation_ticks(&self) -> Result<Vec<Tick>, Error> {
let start = self.timeline.start();
let mut ticks = Vec::new();
let mut push = |tick: i128| -> Result<(), Error> {
for tick in [tick - 1, tick] {
if let Ok(tick) = Tick::try_from(tick) {
if tick >= start {
ticks.try_reserve(1).map_err(|_| Error::OutOfMemory)?;
ticks.push(tick);
}
}
}
Ok(())
};
push(i128::from(start))?;
for tick in self.timeline.change_ticks() {
push(i128::from(tick))?;
}
for ((member, window), duration) in
self.members.iter().zip(&self.windows).zip(&self.durations)
{
for offset in member.offsets(*duration) {
for start in [window.earliest(), window.latest()] {
push(offset + i128::from(start))?;
}
}
}
if let Some(network) = &self.network {
for (lo, hi) in network.dense_ranges(&self.members) {
for tick in lo..=hi {
push(tick)?;
}
}
}
ticks.sort_unstable();
ticks.dedup();
Ok(ticks)
}
fn explain(&self, t: Tick, level: Level, bound: Bound) -> Result<EnvelopeViolation, Error> {
let towards = if bound.is_lower() {
Extreme::Lower
} else {
Extreme::Upper
};
let mut contributors = Vec::new();
let fixed = self.timeline.contributors_at(t, bound)?;
contributors
.try_reserve_exact(fixed.len() + self.members.len())
.map_err(|_| Error::OutOfMemory)?;
contributors.extend_from_slice(&fixed);
let ranges = self.members.iter().zip(&self.windows).zip(&self.durations);
for ((member, window), duration) in ranges {
if bound.is_pushed_by(member.extreme_at(*window, *duration, t, towards)?) {
contributors.push(member.activity);
}
}
contributors.sort_unstable();
contributors.dedup();
Ok(EnvelopeViolation {
at: t,
level,
bound,
contributors,
})
}
}
const fn lower_bound(min: Level, target: bool) -> Bound {
if target {
Bound::BelowTarget(min)
} else {
Bound::BelowMin(min)
}
}
const fn certain_breach(
lower: Level,
upper: Level,
min: Level,
max: Level,
target: bool,
) -> Option<(Level, Bound)> {
if upper < min {
Some((upper, lower_bound(min, target)))
} else if lower > max {
Some((lower, Bound::AboveMax(max)))
} else {
None
}
}
const fn possible_breach(
lower: Level,
upper: Level,
min: Level,
max: Level,
target: bool,
) -> Option<(Level, Bound)> {
if lower < min {
Some((lower, lower_bound(min, target)))
} else if upper > max {
Some((upper, Bound::AboveMax(max)))
} else {
None
}
}