mod search;
pub(crate) use search::Offsets;
pub use search::SearchScratch;
#[cfg(feature = "alloc")]
use crate::storage::Heap;
use crate::storage::{PlanStorage, Seq, Storage};
use crate::{
ActivityId, Container, Error, Impact, StateImpact, StateTimeline, StateViolation, Tick,
Timeline, Violation, Window,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TimelineId(usize);
impl TimelineId {
#[must_use]
pub const fn index(self) -> usize {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct StateId(usize);
impl StateId {
#[must_use]
pub const fn index(self) -> usize {
self.0
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Demand {
Level {
timeline: TimelineId,
impact: Impact,
},
State {
timeline: StateId,
impact: StateImpact,
},
}
impl Demand {
const fn offsets(&self) -> [Tick; 2] {
match *self {
Self::Level { impact, .. } => [impact.first_tick(), impact.last_tick()],
Self::State {
impact: StateImpact::Set { at, .. },
..
} => [at, at],
Self::State {
impact: StateImpact::Require { start, end, .. },
..
} => [start, end],
}
}
fn same_timeline(&self, other: &Self) -> bool {
match (self, other) {
(Self::Level { timeline: a, .. }, Self::Level { timeline: b, .. }) => a == b,
(Self::State { timeline: a, .. }, Self::State { timeline: b, .. }) => a == b,
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum PlanViolation<
#[cfg(feature = "alloc")] S: Storage = Heap,
#[cfg(not(feature = "alloc"))] S: Storage,
> {
Level {
timeline: TimelineId,
violation: Violation<S>,
},
State {
timeline: StateId,
violation: StateViolation<S>,
},
}
impl<S: Storage> PlanViolation<S> {
#[must_use]
pub const fn at(&self) -> Tick {
match self {
Self::Level { violation, .. } => violation.at,
Self::State { violation, .. } => violation.at(),
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
pub struct Plan<
#[cfg(feature = "alloc")] P: PlanStorage = Heap,
#[cfg(not(feature = "alloc"))] P: PlanStorage,
> {
timelines: P::Timelines,
states: P::States,
}
#[cfg(feature = "alloc")]
impl Plan {
#[must_use]
pub const fn new() -> Self {
Self::new_in()
}
}
impl<P: PlanStorage> Plan<P> {
#[must_use]
pub const fn new_in() -> Self {
Self {
timelines: <P::Timelines as Seq<_>>::EMPTY,
states: <P::States as Seq<_>>::EMPTY,
}
}
pub fn add_timeline(&mut self, timeline: Timeline<P::Line>) -> Result<TimelineId, Error> {
self.timelines.try_push(timeline, Container::Timelines)?;
Ok(TimelineId(self.timelines.len() - 1))
}
pub fn add_state(&mut self, timeline: StateTimeline<P::Line>) -> Result<StateId, Error> {
self.states.try_push(timeline, Container::States)?;
Ok(StateId(self.states.len() - 1))
}
#[must_use]
pub fn timelines(&self) -> &[Timeline<P::Line>] {
&self.timelines
}
#[must_use]
pub fn states(&self) -> &[StateTimeline<P::Line>] {
&self.states
}
#[must_use]
pub fn timeline(&self, id: TimelineId) -> Option<&Timeline<P::Line>> {
self.timelines.get(id.0)
}
#[must_use]
pub fn state(&self, id: StateId) -> Option<&StateTimeline<P::Line>> {
self.states.get(id.0)
}
pub fn add_target(&mut self, id: TimelineId, target: crate::Target) -> Result<(), Error> {
self.timelines
.get_mut(id.0)
.ok_or(Error::UnknownResource)?
.add_target(target)
}
pub fn place(
&mut self,
activity: ActivityId,
start: Tick,
demands: &[Demand],
) -> Result<(), Error> {
for (index, demand) in demands.iter().enumerate() {
let pending = demands[..=index]
.iter()
.filter(|other| other.same_timeline(demand))
.count();
self.validate(&self.shift(demand, start)?, pending)?;
}
for (added, demand) in demands.iter().enumerate() {
let shifted = self.shift(demand, start)?;
if let Err(error) = self.add_unchecked(activity, shifted) {
self.undo(&demands[..added]);
return Err(error);
}
}
Ok(())
}
pub fn remove(&mut self, activity: ActivityId) -> usize {
let levels: usize = self.timelines.iter_mut().map(|t| t.remove(activity)).sum();
let states: usize = self.states.iter_mut().map(|t| t.remove(activity)).sum();
levels + states
}
pub fn first_violation(&self) -> Result<Option<PlanViolation<P::Line>>, Error> {
let mut earliest: Option<PlanViolation<P::Line>> = None;
for (index, timeline) in self.timelines.iter().enumerate() {
if let Some(violation) = timeline.first_violation()? {
let found = PlanViolation::Level {
timeline: TimelineId(index),
violation,
};
keep_earlier(&mut earliest, found);
}
}
for (index, timeline) in self.states.iter().enumerate() {
if let Some(violation) = timeline.first_violation()? {
let found = PlanViolation::State {
timeline: StateId(index),
violation,
};
keep_earlier(&mut earliest, found);
}
}
Ok(earliest)
}
pub fn fits(&self, demands: &[Demand], start: Tick) -> Result<bool, Error> {
self.fits_with(demands, start, &mut SearchScratch::new())
}
pub fn fits_with(
&self,
demands: &[Demand],
start: Tick,
scratch: &mut SearchScratch<P::Line>,
) -> Result<bool, Error> {
search::Probe::new(self, demands, scratch)?.fits(start)
}
pub fn earliest_start(
&self,
demands: &[Demand],
window: Window,
max_checks: usize,
) -> Result<Option<Tick>, Error> {
self.earliest_start_with(demands, window, max_checks, &mut SearchScratch::new())
}
pub fn earliest_start_with(
&self,
demands: &[Demand],
window: Window,
max_checks: usize,
scratch: &mut SearchScratch<P::Line>,
) -> Result<Option<Tick>, Error> {
search::earliest_start(self, demands, window, max_checks, scratch)
}
fn shift(&self, demand: &Demand, start: Tick) -> Result<Demand, Error> {
let shifted = match *demand {
Demand::Level { timeline, impact } => {
self.timeline(timeline).ok_or(Error::UnknownResource)?;
impact
.shifted(start)
.map(|impact| Demand::Level { timeline, impact })
}
Demand::State { timeline, impact } => {
self.state(timeline).ok_or(Error::UnknownResource)?;
impact
.shifted(start)
.map(|impact| Demand::State { timeline, impact })
}
};
shifted.ok_or(Error::Overflow)
}
fn validate(&self, demand: &Demand, pending: usize) -> Result<(), Error> {
match *demand {
Demand::Level { timeline, impact } => {
let timeline = &self.timelines[timeline.0];
timeline.validate(impact)?;
timeline.ensure_room(pending)
}
Demand::State { timeline, impact } => {
let timeline = &self.states[timeline.0];
timeline.validate(impact)?;
timeline.ensure_room(pending)
}
}
}
fn add_unchecked(&mut self, activity: ActivityId, demand: Demand) -> Result<(), Error> {
match demand {
Demand::Level { timeline, impact } => self.timelines[timeline.0].add(activity, impact),
Demand::State { timeline, impact } => self.states[timeline.0].add(activity, impact),
}
}
fn undo(&mut self, added: &[Demand]) {
for demand in added.iter().rev() {
match *demand {
Demand::Level { timeline, .. } => self.timelines[timeline.0].undo_last(),
Demand::State { timeline, .. } => self.states[timeline.0].undo_last(),
}
}
}
}
fn keep_earlier<S: Storage>(earliest: &mut Option<PlanViolation<S>>, found: PlanViolation<S>) {
if earliest
.as_ref()
.is_none_or(|current| found.at() < current.at())
{
*earliest = Some(found);
}
}
#[cfg(all(test, feature = "alloc"))]
mod tests {
use alloc::vec::Vec;
use super::{Demand, Plan};
use crate::{ActivityId, Bounds, Impact, StateImpact, StateTimeline, Timeline};
#[test]
fn undo_restores_the_plan() {
let mut plan = Plan::new();
let bounds = Bounds::new(0, 10).expect("valid");
let battery = plan
.add_timeline(Timeline::depletable(0, 5, bounds, 8).expect("valid"))
.expect("memory");
let mode = plan.add_state(StateTimeline::new(0, 0, 8)).expect("memory");
let demands = [
Demand::Level {
timeline: battery,
impact: Impact::Rate {
start: 0,
end: 4,
per_tick: -1,
},
},
Demand::State {
timeline: mode,
impact: StateImpact::Set { at: 2, value: 1 },
},
Demand::State {
timeline: mode,
impact: StateImpact::Require {
start: 2,
end: 5,
value: 1,
},
},
Demand::Level {
timeline: battery,
impact: Impact::Step { at: 3, delta: 2 },
},
];
plan.place(ActivityId(1), 1, &demands).expect("valid");
let before = plan.clone();
plan.place(ActivityId(1), 1, &demands).expect("valid");
let shifted: Vec<Demand> = demands
.iter()
.map(|d| plan.shift(d, 1).expect("small"))
.collect();
plan.undo(&shifted);
assert_eq!(plan, before);
}
}