1use super::{Demand, Plan};
26use crate::state::{Requirement, SetPoint};
27use crate::storage::{PlanStorage, Seq, Storage};
28use crate::timeline::profile::Point;
29use crate::{Container, Error, Impact, StateImpact, Tick, Timeline, Window};
30
31type Line<P> = <P as PlanStorage>::Line;
33
34#[derive(Debug, Clone)]
70pub struct SearchScratch<S: Storage> {
71 points: S::DoubleList<Point>,
73 points_next: S::DoubleList<Point>,
75 sets: S::List<SetPoint>,
77 requires: S::List<Requirement>,
79}
80
81impl<S: Storage> SearchScratch<S> {
82 #[must_use]
84 pub const fn new() -> Self {
85 Self {
86 points: <S::DoubleList<Point> as Seq<_>>::EMPTY,
87 points_next: <S::DoubleList<Point> as Seq<_>>::EMPTY,
88 sets: <S::List<SetPoint> as Seq<_>>::EMPTY,
89 requires: <S::List<Requirement> as Seq<_>>::EMPTY,
90 }
91 }
92}
93
94impl<S: Storage> Default for SearchScratch<S> {
95 fn default() -> Self {
96 Self::new()
97 }
98}
99
100pub(super) struct Probe<'a, P: PlanStorage> {
102 plan: &'a Plan<P>,
104 demands: &'a [Demand],
106 scratch: &'a mut SearchScratch<Line<P>>,
108}
109
110impl<'a, P: PlanStorage> Probe<'a, P> {
111 pub(super) fn new(
122 plan: &'a Plan<P>,
123 demands: &'a [Demand],
124 scratch: &'a mut SearchScratch<Line<P>>,
125 ) -> Result<Self, Error> {
126 for demand in demands {
127 let known = match *demand {
128 Demand::Level { timeline, .. } => plan.timeline(timeline).is_some(),
129 Demand::State { timeline, .. } => plan.state(timeline).is_some(),
130 };
131 if !known {
132 return Err(Error::UnknownResource);
133 }
134 }
135
136 let most = most_on_one_timeline(demands);
137 for points in [&mut scratch.points, &mut scratch.points_next] {
138 points.clear();
139 points.try_reserve(most.saturating_mul(2), Container::Scratch)?;
140 }
141
142 scratch.sets.clear();
143 scratch.requires.clear();
144 scratch.sets.try_reserve(most, Container::Scratch)?;
145 scratch.requires.try_reserve(most, Container::Scratch)?;
146 Ok(Self {
147 plan,
148 demands,
149 scratch,
150 })
151 }
152
153 pub(super) fn fits(&mut self, start: Tick) -> Result<bool, Error> {
159 for index in self.representatives() {
160 if !self.timeline_fits(&self.demands[index], start)? {
161 return Ok(false);
162 }
163 }
164
165 Ok(true)
166 }
167
168 fn earliest_in(&mut self, lo: Tick, hi: Tick) -> Result<Option<Tick>, Error> {
178 if lo == hi {
179 return Ok(self.fits(lo)?.then_some(lo));
180 }
181
182 let mut offsets = Offsets {
183 lo: 0,
184 hi: i128::from(hi) - i128::from(lo),
185 };
186 for index in self.representatives() {
187 let representative = self.demands[index];
188 let Demand::Level { timeline, .. } = representative else {
189 if !self.timeline_fits(&representative, lo)? {
191 return Ok(None);
192 }
193
194 continue;
195 };
196
197 let timeline = &self.plan.timelines[timeline.0];
198 let first = collect_points(
199 timeline,
200 self.demands,
201 &representative,
202 lo,
203 &mut self.scratch.points,
204 )?;
205 let second = collect_points(
206 timeline,
207 self.demands,
208 &representative,
209 lo + 1,
210 &mut self.scratch.points_next,
211 )?;
212 if !(first && second) {
213 return Ok(None);
214 }
215
216 timeline.narrow(
217 &self.scratch.points,
218 &self.scratch.points_next,
219 &mut offsets,
220 )?;
221 if offsets.is_empty() {
222 return Ok(None);
223 }
224 }
225
226 let start = i128::from(lo) + offsets.lo;
227 Ok(Some(Tick::try_from(start).map_err(|_| Error::Overflow)?))
228 }
229
230 fn representatives(&self) -> impl Iterator<Item = usize> + 'a {
232 let demands = self.demands;
233 (0..demands.len()).filter(move |&index| {
234 !demands[..index]
235 .iter()
236 .any(|earlier| earlier.same_timeline(&demands[index]))
237 })
238 }
239
240 fn timeline_fits(&mut self, representative: &Demand, start: Tick) -> Result<bool, Error> {
242 match *representative {
243 Demand::Level { timeline, .. } => {
244 let timeline = &self.plan.timelines[timeline.0];
245 if !collect_points(
246 timeline,
247 self.demands,
248 representative,
249 start,
250 &mut self.scratch.points,
251 )? {
252 return Ok(false);
253 }
254
255 Ok(timeline.breach_with(&self.scratch.points)?.is_none())
256 }
257 Demand::State { timeline, .. } => {
258 let timeline = &self.plan.states[timeline.0];
259 if !self.collect_states(representative, start)? {
260 return Ok(false);
261 }
262
263 Ok(!timeline.is_violated_with(&self.scratch.sets, &self.scratch.requires))
264 }
265 }
266 }
267
268 fn collect_states(&mut self, representative: &Demand, start: Tick) -> Result<bool, Error> {
271 self.scratch.sets.clear();
272 self.scratch.requires.clear();
273 for demand in self.demands {
274 let Demand::State { timeline, impact } = *demand else {
275 continue;
276 };
277 if !demand.same_timeline(representative) {
278 continue;
279 }
280
281 let shifted = impact.shifted(start).ok_or(Error::Overflow)?;
282 match self.plan.states[timeline.0].validate(shifted) {
283 Ok(()) => {}
284 Err(Error::BeforeStart { .. }) => return Ok(false),
285 Err(error) => return Err(error),
286 }
287
288 self.push_state(shifted)?;
289 }
290
291 self.scratch.sets.sort_unstable_by_key(SetPoint::key);
292 Ok(true)
293 }
294
295 fn push_state(&mut self, impact: StateImpact) -> Result<(), Error> {
301 let activity = crate::ActivityId(u32::MAX);
303 match impact {
304 StateImpact::Set { at, value } => {
305 let set = SetPoint {
306 at,
307 activity,
308 value,
309 };
310 self.scratch.sets.try_push(set, Container::Scratch)
311 }
312 StateImpact::Require { start, end, value } => {
313 let requirement = Requirement {
314 activity,
315 start,
316 end,
317 value,
318 };
319 self.scratch
320 .requires
321 .try_push(requirement, Container::Scratch)
322 }
323 }
324 }
325}
326
327fn collect_points<S: Storage>(
337 timeline: &Timeline<S>,
338 demands: &[Demand],
339 representative: &Demand,
340 start: Tick,
341 points: &mut impl Seq<Point>,
342) -> Result<bool, Error> {
343 points.clear();
344 for demand in demands {
345 let Demand::Level { impact, .. } = *demand else {
346 continue;
347 };
348 if !demand.same_timeline(representative) {
349 continue;
350 }
351
352 let Some(impact) = admissible(timeline, impact, start)? else {
353 return Ok(false);
354 };
355 for (at, step, slope) in impact.changes().into_iter().flatten() {
356 points.try_push(Point::loose(at, step, slope), Container::Scratch)?;
357 }
358 }
359
360 points.sort_unstable_by_key(|point| point.at);
361 Ok(true)
362}
363
364fn most_on_one_timeline(demands: &[Demand]) -> usize {
366 demands
367 .iter()
368 .map(|demand| {
369 demands
370 .iter()
371 .filter(|other| other.same_timeline(demand))
372 .count()
373 })
374 .max()
375 .unwrap_or(0)
376}
377
378fn admissible<S: Storage>(
381 timeline: &Timeline<S>,
382 impact: Impact,
383 start: Tick,
384) -> Result<Option<Impact>, Error> {
385 let shifted = impact.shifted(start).ok_or(Error::Overflow)?;
386 match timeline.validate(shifted) {
387 Ok(()) => Ok(Some(shifted)),
388 Err(Error::BeforeStart { .. }) => Ok(None),
389 Err(error) => Err(error),
390 }
391}
392
393pub(super) fn earliest_start<P: PlanStorage>(
396 plan: &Plan<P>,
397 demands: &[Demand],
398 window: Window,
399 max_checks: usize,
400 scratch: &mut SearchScratch<Line<P>>,
401) -> Result<Option<Tick>, Error> {
402 let mut probe = Probe::new(plan, demands, scratch)?;
403 let Some(window) = admissible_window(plan, demands, window) else {
404 return Ok(None);
405 };
406
407 let rates = involves_rates(plan, demands);
408 let mut checks = 0_usize;
409 let mut piece = Some(window.earliest());
410 while let Some(lo) = piece {
411 if checks == max_checks {
412 return Err(Error::SearchExhausted { checks: max_checks });
413 }
414
415 checks += 1;
416 let next = next_candidate(plan, demands, lo, window);
417 let found = if rates {
418 let hi = next.map_or(window.latest(), |next| next - 1);
419 probe.earliest_in(lo, hi)?
420 } else {
421 probe.fits(lo)?.then_some(lo)
422 };
423 if found.is_some() {
424 return Ok(found);
425 }
426
427 piece = next;
428 }
429
430 Ok(None)
431}
432
433#[derive(Debug, Clone, Copy, PartialEq, Eq)]
435pub(crate) struct Offsets {
436 pub(crate) lo: i128,
438 pub(crate) hi: i128,
440}
441
442impl Offsets {
443 pub(crate) const fn is_empty(&self) -> bool {
445 self.lo > self.hi
446 }
447
448 pub(crate) fn keep(
455 &mut self,
456 value: i128,
457 slope: i128,
458 min: i128,
459 max: Option<i128>,
460 ) -> Result<(), Error> {
461 let below_min = value < min;
462 let above_max = max.is_some_and(|max| value > max);
463 if slope == 0 {
464 if below_min || above_max {
465 self.hi = self.lo - 1;
466 }
467
468 return Ok(());
469 }
470
471 let room_min = min.checked_sub(value).ok_or(Error::Overflow)?;
472 let room_max = max
473 .map(|max| max.checked_sub(value).ok_or(Error::Overflow))
474 .transpose()?;
475 if slope > 0 {
476 self.lo = self.lo.max(ceil_div(room_min, slope));
477 if let Some(room) = room_max {
478 self.hi = self.hi.min(floor_div(room, slope));
479 }
480 } else {
481 self.hi = self.hi.min(floor_div(room_min, slope));
482 if let Some(room) = room_max {
483 self.lo = self.lo.max(ceil_div(room, slope));
484 }
485 }
486
487 Ok(())
488 }
489}
490
491const fn floor_div(a: i128, b: i128) -> i128 {
493 let quotient = a / b;
494 if a % b != 0 && ((a < 0) != (b < 0)) {
495 quotient - 1
496 } else {
497 quotient
498 }
499}
500
501const fn ceil_div(a: i128, b: i128) -> i128 {
503 let quotient = a / b;
504 if a % b != 0 && ((a < 0) == (b < 0)) {
505 quotient + 1
506 } else {
507 quotient
508 }
509}
510
511fn admissible_window<P: PlanStorage>(
514 plan: &Plan<P>,
515 demands: &[Demand],
516 window: Window,
517) -> Option<Window> {
518 let mut earliest = i128::from(window.earliest());
519 for demand in demands {
520 let timeline_start = match *demand {
521 Demand::Level { timeline, .. } => plan.timelines[timeline.0].start(),
522 Demand::State { timeline, .. } => plan.states[timeline.0].start(),
523 };
524 let first_offset = demand.offsets()[0];
525 earliest = earliest.max(i128::from(timeline_start) - i128::from(first_offset));
526 }
527
528 Window::new(Tick::try_from(earliest).ok()?, window.latest()).ok()
529}
530
531fn involves_rates<P: PlanStorage>(plan: &Plan<P>, demands: &[Demand]) -> bool {
533 demands.iter().any(|demand| match *demand {
534 Demand::Level { timeline, impact } => {
535 impact.is_rate() || plan.timelines[timeline.0].has_rates()
536 }
537 Demand::State { .. } => false,
538 })
539}
540
541fn next_candidate<P: PlanStorage>(
550 plan: &Plan<P>,
551 demands: &[Demand],
552 after: Tick,
553 window: Window,
554) -> Option<Tick> {
555 let mut next: Option<i128> = None;
556 for demand in demands {
557 for offset in demand.offsets() {
558 let threshold = i128::from(after) + i128::from(offset);
559 let first_from = |x: i128| match *demand {
560 Demand::Level { timeline, .. } => plan.timelines[timeline.0].first_change_from(x),
561 Demand::State { timeline, .. } => plan.states[timeline.0].first_change_from(x),
562 };
563 let meet = first_from(threshold + 1).map(|p| i128::from(p) - i128::from(offset));
564 let pass = first_from(threshold).map(|p| i128::from(p) - i128::from(offset) + 1);
565 for start in [meet, pass].into_iter().flatten() {
566 if next.is_none_or(|next| start < next) {
567 next = Some(start);
568 }
569 }
570 }
571 }
572
573 let next = Tick::try_from(next?).ok()?;
574 window.contains(next).then_some(next)
575}
576
577#[cfg(test)]
578mod tests {
579 use super::{Offsets, ceil_div, floor_div};
582
583 #[test]
585 fn rounding_division() {
586 for a in -20_i128..=20 {
587 for b in (-6_i128..=6).filter(|&b| b != 0) {
588 let floor = floor_div(a, b);
589 let ceil = ceil_div(a, b);
590 if b > 0 {
592 assert!(floor * b <= a && a < (floor + 1) * b, "floor {a}/{b}");
593 assert!((ceil - 1) * b < a && a <= ceil * b, "ceil {a}/{b}");
594 } else {
595 assert!(floor * b >= a && a > (floor + 1) * b, "floor {a}/{b}");
596 assert!((ceil - 1) * b > a && a >= ceil * b, "ceil {a}/{b}");
597 }
598 }
599 }
600 }
601
602 #[test]
604 fn keep_matches_enumeration() {
605 for value in -8_i128..=8 {
606 for slope in -3_i128..=3 {
607 for max in [None, Some(2_i128), Some(5)] {
608 let mut offsets = Offsets { lo: 0, hi: 6 };
609 offsets.keep(value, slope, -1, max).expect("small");
610 let expected = (0..=6).filter(|k| {
611 let level = value + slope * k;
612 level >= -1 && max.is_none_or(|max| level <= max)
613 });
614 assert!(
615 (offsets.lo..=offsets.hi).eq(expected),
616 "value {value} slope {slope} max {max:?}"
617 );
618 }
619 }
620 }
621 }
622}