use super::{Demand, Plan};
use crate::state::{Requirement, SetPoint};
use crate::storage::{PlanStorage, Seq, Storage};
use crate::timeline::profile::Point;
use crate::{Container, Error, Impact, StateImpact, Tick, Timeline, Window};
type Line<P> = <P as PlanStorage>::Line;
#[derive(Debug, Clone)]
pub struct SearchScratch<S: Storage> {
points: S::DoubleList<Point>,
points_next: S::DoubleList<Point>,
sets: S::List<SetPoint>,
requires: S::List<Requirement>,
}
impl<S: Storage> SearchScratch<S> {
#[must_use]
pub const fn new() -> Self {
Self {
points: <S::DoubleList<Point> as Seq<_>>::EMPTY,
points_next: <S::DoubleList<Point> as Seq<_>>::EMPTY,
sets: <S::List<SetPoint> as Seq<_>>::EMPTY,
requires: <S::List<Requirement> as Seq<_>>::EMPTY,
}
}
}
impl<S: Storage> Default for SearchScratch<S> {
fn default() -> Self {
Self::new()
}
}
pub(super) struct Probe<'a, P: PlanStorage> {
plan: &'a Plan<P>,
demands: &'a [Demand],
scratch: &'a mut SearchScratch<Line<P>>,
}
impl<'a, P: PlanStorage> Probe<'a, P> {
pub(super) fn new(
plan: &'a Plan<P>,
demands: &'a [Demand],
scratch: &'a mut SearchScratch<Line<P>>,
) -> Result<Self, Error> {
for demand in demands {
let known = match *demand {
Demand::Level { timeline, .. } => plan.timeline(timeline).is_some(),
Demand::State { timeline, .. } => plan.state(timeline).is_some(),
};
if !known {
return Err(Error::UnknownResource);
}
}
let most = most_on_one_timeline(demands);
for points in [&mut scratch.points, &mut scratch.points_next] {
points.clear();
points.try_reserve(most.saturating_mul(2), Container::Scratch)?;
}
scratch.sets.clear();
scratch.requires.clear();
scratch.sets.try_reserve(most, Container::Scratch)?;
scratch.requires.try_reserve(most, Container::Scratch)?;
Ok(Self {
plan,
demands,
scratch,
})
}
pub(super) fn fits(&mut self, start: Tick) -> Result<bool, Error> {
for index in self.representatives() {
if !self.timeline_fits(&self.demands[index], start)? {
return Ok(false);
}
}
Ok(true)
}
fn earliest_in(&mut self, lo: Tick, hi: Tick) -> Result<Option<Tick>, Error> {
if lo == hi {
return Ok(self.fits(lo)?.then_some(lo));
}
let mut offsets = Offsets {
lo: 0,
hi: i128::from(hi) - i128::from(lo),
};
for index in self.representatives() {
let representative = self.demands[index];
let Demand::Level { timeline, .. } = representative else {
if !self.timeline_fits(&representative, lo)? {
return Ok(None);
}
continue;
};
let timeline = &self.plan.timelines[timeline.0];
let first = collect_points(
timeline,
self.demands,
&representative,
lo,
&mut self.scratch.points,
)?;
let second = collect_points(
timeline,
self.demands,
&representative,
lo + 1,
&mut self.scratch.points_next,
)?;
if !(first && second) {
return Ok(None);
}
timeline.narrow(
&self.scratch.points,
&self.scratch.points_next,
&mut offsets,
)?;
if offsets.is_empty() {
return Ok(None);
}
}
let start = i128::from(lo) + offsets.lo;
Ok(Some(Tick::try_from(start).map_err(|_| Error::Overflow)?))
}
fn representatives(&self) -> impl Iterator<Item = usize> + 'a {
let demands = self.demands;
(0..demands.len()).filter(move |&index| {
!demands[..index]
.iter()
.any(|earlier| earlier.same_timeline(&demands[index]))
})
}
fn timeline_fits(&mut self, representative: &Demand, start: Tick) -> Result<bool, Error> {
match *representative {
Demand::Level { timeline, .. } => {
let timeline = &self.plan.timelines[timeline.0];
if !collect_points(
timeline,
self.demands,
representative,
start,
&mut self.scratch.points,
)? {
return Ok(false);
}
Ok(timeline.breach_with(&self.scratch.points)?.is_none())
}
Demand::State { timeline, .. } => {
let timeline = &self.plan.states[timeline.0];
if !self.collect_states(representative, start)? {
return Ok(false);
}
Ok(!timeline.is_violated_with(&self.scratch.sets, &self.scratch.requires))
}
}
}
fn collect_states(&mut self, representative: &Demand, start: Tick) -> Result<bool, Error> {
self.scratch.sets.clear();
self.scratch.requires.clear();
for demand in self.demands {
let Demand::State { timeline, impact } = *demand else {
continue;
};
if !demand.same_timeline(representative) {
continue;
}
let shifted = impact.shifted(start).ok_or(Error::Overflow)?;
match self.plan.states[timeline.0].validate(shifted) {
Ok(()) => {}
Err(Error::BeforeStart { .. }) => return Ok(false),
Err(error) => return Err(error),
}
self.push_state(shifted)?;
}
self.scratch.sets.sort_unstable_by_key(SetPoint::key);
Ok(true)
}
fn push_state(&mut self, impact: StateImpact) -> Result<(), Error> {
let activity = crate::ActivityId(u32::MAX);
match impact {
StateImpact::Set { at, value } => {
let set = SetPoint {
at,
activity,
value,
};
self.scratch.sets.try_push(set, Container::Scratch)
}
StateImpact::Require { start, end, value } => {
let requirement = Requirement {
activity,
start,
end,
value,
};
self.scratch
.requires
.try_push(requirement, Container::Scratch)
}
}
}
}
fn collect_points<S: Storage>(
timeline: &Timeline<S>,
demands: &[Demand],
representative: &Demand,
start: Tick,
points: &mut impl Seq<Point>,
) -> Result<bool, Error> {
points.clear();
for demand in demands {
let Demand::Level { impact, .. } = *demand else {
continue;
};
if !demand.same_timeline(representative) {
continue;
}
let Some(impact) = admissible(timeline, impact, start)? else {
return Ok(false);
};
for (at, step, slope) in impact.changes().into_iter().flatten() {
points.try_push(Point::loose(at, step, slope), Container::Scratch)?;
}
}
points.sort_unstable_by_key(|point| point.at);
Ok(true)
}
fn most_on_one_timeline(demands: &[Demand]) -> usize {
demands
.iter()
.map(|demand| {
demands
.iter()
.filter(|other| other.same_timeline(demand))
.count()
})
.max()
.unwrap_or(0)
}
fn admissible<S: Storage>(
timeline: &Timeline<S>,
impact: Impact,
start: Tick,
) -> Result<Option<Impact>, Error> {
let shifted = impact.shifted(start).ok_or(Error::Overflow)?;
match timeline.validate(shifted) {
Ok(()) => Ok(Some(shifted)),
Err(Error::BeforeStart { .. }) => Ok(None),
Err(error) => Err(error),
}
}
pub(super) fn earliest_start<P: PlanStorage>(
plan: &Plan<P>,
demands: &[Demand],
window: Window,
max_checks: usize,
scratch: &mut SearchScratch<Line<P>>,
) -> Result<Option<Tick>, Error> {
let mut probe = Probe::new(plan, demands, scratch)?;
let Some(window) = admissible_window(plan, demands, window) else {
return Ok(None);
};
let rates = involves_rates(plan, demands);
let mut checks = 0_usize;
let mut piece = Some(window.earliest());
while let Some(lo) = piece {
if checks == max_checks {
return Err(Error::SearchExhausted { checks: max_checks });
}
checks += 1;
let next = next_candidate(plan, demands, lo, window);
let found = if rates {
let hi = next.map_or(window.latest(), |next| next - 1);
probe.earliest_in(lo, hi)?
} else {
probe.fits(lo)?.then_some(lo)
};
if found.is_some() {
return Ok(found);
}
piece = next;
}
Ok(None)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Offsets {
pub(crate) lo: i128,
pub(crate) hi: i128,
}
impl Offsets {
pub(crate) const fn is_empty(&self) -> bool {
self.lo > self.hi
}
pub(crate) fn keep(
&mut self,
value: i128,
slope: i128,
min: i128,
max: Option<i128>,
) -> Result<(), Error> {
let below_min = value < min;
let above_max = max.is_some_and(|max| value > max);
if slope == 0 {
if below_min || above_max {
self.hi = self.lo - 1;
}
return Ok(());
}
let room_min = min.checked_sub(value).ok_or(Error::Overflow)?;
let room_max = max
.map(|max| max.checked_sub(value).ok_or(Error::Overflow))
.transpose()?;
if slope > 0 {
self.lo = self.lo.max(ceil_div(room_min, slope));
if let Some(room) = room_max {
self.hi = self.hi.min(floor_div(room, slope));
}
} else {
self.hi = self.hi.min(floor_div(room_min, slope));
if let Some(room) = room_max {
self.lo = self.lo.max(ceil_div(room, slope));
}
}
Ok(())
}
}
const fn floor_div(a: i128, b: i128) -> i128 {
let quotient = a / b;
if a % b != 0 && ((a < 0) != (b < 0)) {
quotient - 1
} else {
quotient
}
}
const fn ceil_div(a: i128, b: i128) -> i128 {
let quotient = a / b;
if a % b != 0 && ((a < 0) == (b < 0)) {
quotient + 1
} else {
quotient
}
}
fn admissible_window<P: PlanStorage>(
plan: &Plan<P>,
demands: &[Demand],
window: Window,
) -> Option<Window> {
let mut earliest = i128::from(window.earliest());
for demand in demands {
let timeline_start = match *demand {
Demand::Level { timeline, .. } => plan.timelines[timeline.0].start(),
Demand::State { timeline, .. } => plan.states[timeline.0].start(),
};
let first_offset = demand.offsets()[0];
earliest = earliest.max(i128::from(timeline_start) - i128::from(first_offset));
}
Window::new(Tick::try_from(earliest).ok()?, window.latest()).ok()
}
fn involves_rates<P: PlanStorage>(plan: &Plan<P>, demands: &[Demand]) -> bool {
demands.iter().any(|demand| match *demand {
Demand::Level { timeline, impact } => {
impact.is_rate() || plan.timelines[timeline.0].has_rates()
}
Demand::State { .. } => false,
})
}
fn next_candidate<P: PlanStorage>(
plan: &Plan<P>,
demands: &[Demand],
after: Tick,
window: Window,
) -> Option<Tick> {
let mut next: Option<i128> = None;
for demand in demands {
for offset in demand.offsets() {
let threshold = i128::from(after) + i128::from(offset);
let first_from = |x: i128| match *demand {
Demand::Level { timeline, .. } => plan.timelines[timeline.0].first_change_from(x),
Demand::State { timeline, .. } => plan.states[timeline.0].first_change_from(x),
};
let meet = first_from(threshold + 1).map(|p| i128::from(p) - i128::from(offset));
let pass = first_from(threshold).map(|p| i128::from(p) - i128::from(offset) + 1);
for start in [meet, pass].into_iter().flatten() {
if next.is_none_or(|next| start < next) {
next = Some(start);
}
}
}
}
let next = Tick::try_from(next?).ok()?;
window.contains(next).then_some(next)
}
#[cfg(test)]
mod tests {
use super::{Offsets, ceil_div, floor_div};
#[test]
fn rounding_division() {
for a in -20_i128..=20 {
for b in (-6_i128..=6).filter(|&b| b != 0) {
let floor = floor_div(a, b);
let ceil = ceil_div(a, b);
if b > 0 {
assert!(floor * b <= a && a < (floor + 1) * b, "floor {a}/{b}");
assert!((ceil - 1) * b < a && a <= ceil * b, "ceil {a}/{b}");
} else {
assert!(floor * b >= a && a > (floor + 1) * b, "floor {a}/{b}");
assert!((ceil - 1) * b > a && a >= ceil * b, "ceil {a}/{b}");
}
}
}
}
#[test]
fn keep_matches_enumeration() {
for value in -8_i128..=8 {
for slope in -3_i128..=3 {
for max in [None, Some(2_i128), Some(5)] {
let mut offsets = Offsets { lo: 0, hi: 6 };
offsets.keep(value, slope, -1, max).expect("small");
let expected = (0..=6).filter(|k| {
let level = value + slope * k;
level >= -1 && max.is_none_or(|max| level <= max)
});
assert!(
(offsets.lo..=offsets.hi).eq(expected),
"value {value} slope {slope} max {max:?}"
);
}
}
}
}
}