Skip to main content

resource_timeline/
plan.rs

1//! Plans: several resource timelines checked together, with placement and search.
2//!
3//! An activity usually touches several resources: a downlink draws power, claims the
4//! transmitter, frees mass memory and needs Earth in view. A [`Plan`] owns one timeline per
5//! resource and treats an activity as a list of [`Demand`]s whose ticks are relative to the
6//! activity start. It places activities atomically, removes them again, reports the earliest
7//! violation across all timelines and finds the earliest start at which an activity fits.
8//!
9//! ```mermaid
10//! graph LR
11//!     demands["Demands, relative to the start"] --> search["earliest_start: candidate starts"]
12//!     search --> fits["fits: tentative check per touched timeline"]
13//!     fits --> place["place: add to every timeline, atomically"]
14//!     place --> check["first_violation across timelines"]
15//! ```
16
17mod search;
18
19pub(crate) use search::Offsets;
20pub use search::SearchScratch;
21
22#[cfg(feature = "alloc")]
23use crate::storage::Heap;
24use crate::storage::{PlanStorage, Seq, Storage};
25use crate::{
26    ActivityId, Container, Error, Impact, StateImpact, StateTimeline, StateViolation, Tick,
27    Timeline, Violation, Window,
28};
29
30/// A handle of a numeric [`Timeline`] in a [`Plan`].
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
32pub struct TimelineId(usize);
33
34impl TimelineId {
35    /// The position of the timeline in [`Plan::timelines`].
36    #[must_use]
37    pub const fn index(self) -> usize {
38        self.0
39    }
40}
41
42/// A handle of a [`StateTimeline`] in a [`Plan`].
43#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
44pub struct StateId(usize);
45
46impl StateId {
47    /// The position of the timeline in [`Plan::states`].
48    #[must_use]
49    pub const fn index(self) -> usize {
50        self.0
51    }
52}
53
54/// One effect of an activity on one timeline of a plan, with ticks relative to the activity
55/// start.
56///
57/// An activity that draws 4 power units for its first 10 ticks is
58/// `Demand::Level { timeline: power, impact: Impact::Claim { start: 0, end: 10, amount: 4 } }`.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
60pub enum Demand {
61    /// An effect on a numeric timeline.
62    Level {
63        /// The timeline affected.
64        timeline: TimelineId,
65        /// The effect, with ticks relative to the activity start.
66        impact: Impact,
67    },
68    /// An effect on a state timeline.
69    State {
70        /// The timeline affected.
71        timeline: StateId,
72        /// The effect, with ticks relative to the activity start.
73        impact: StateImpact,
74    },
75}
76
77impl Demand {
78    /// The ticks of the demand, relative to the activity start, at which it changes something.
79    const fn offsets(&self) -> [Tick; 2] {
80        match *self {
81            Self::Level { impact, .. } => [impact.first_tick(), impact.last_tick()],
82            Self::State {
83                impact: StateImpact::Set { at, .. },
84                ..
85            } => [at, at],
86            Self::State {
87                impact: StateImpact::Require { start, end, .. },
88                ..
89            } => [start, end],
90        }
91    }
92
93    /// Whether the demand addresses the same timeline as `other`.
94    fn same_timeline(&self, other: &Self) -> bool {
95        match (self, other) {
96            (Self::Level { timeline: a, .. }, Self::Level { timeline: b, .. }) => a == b,
97            (Self::State { timeline: a, .. }, Self::State { timeline: b, .. }) => a == b,
98            _ => false,
99        }
100    }
101}
102
103/// The earliest violation of a plan and the timeline it occurs on.
104///
105/// `S` is the storage of the plan's timelines, [`PlanStorage::Line`].
106#[derive(Debug, Clone, PartialEq, Eq, Hash)]
107pub enum PlanViolation<
108    #[cfg(feature = "alloc")] S: Storage = Heap,
109    #[cfg(not(feature = "alloc"))] S: Storage,
110> {
111    /// A numeric timeline leaves its bounds.
112    Level {
113        /// The violated timeline.
114        timeline: TimelineId,
115        /// The explanation.
116        violation: Violation<S>,
117    },
118    /// A state timeline fails a requirement or has contradicting sets.
119    State {
120        /// The violated timeline.
121        timeline: StateId,
122        /// The explanation.
123        violation: StateViolation<S>,
124    },
125}
126
127impl<S: Storage> PlanViolation<S> {
128    /// The tick of the violation.
129    #[must_use]
130    pub const fn at(&self) -> Tick {
131        match self {
132            Self::Level { violation, .. } => violation.at,
133            Self::State { violation, .. } => violation.at(),
134        }
135    }
136}
137
138/// A set of numeric and state timelines, one per resource, checked together.
139///
140/// The storage `P` is [`storage::Heap`](crate::storage::Heap) by default. With
141/// [`FixedPlan<T, S, N>`](crate::storage::FixedPlan) the plan holds at most `T` numeric and `S`
142/// state timelines with [`Fixed<N>`](crate::storage::Fixed) storage each, and placement,
143/// checks and the earliest-start search never allocate.
144///
145/// # Examples
146///
147/// ```
148/// use resource_timeline::{ActivityId, Demand, Impact, Plan, Timeline, Window};
149///
150/// let mut plan = Plan::new();
151/// let transmitter = plan.add_timeline(Timeline::claimable(0, 1, 16)?)?;
152/// let downlink = [Demand::Level {
153///     timeline: transmitter,
154///     impact: Impact::Claim { start: 0, end: 8, amount: 1 },
155/// }];
156///
157/// plan.place(ActivityId(1), 5, &downlink)?;
158/// let window = Window::new(0, 100)?;
159/// // Before tick 5 there is no room for 8 ticks; the transmitter is free again at 13.
160/// assert_eq!(plan.earliest_start(&downlink, window, 1_000)?, Some(13));
161/// # Ok::<(), resource_timeline::Error>(())
162/// ```
163///
164/// The same plan without allocation, for at most two numeric and one state timeline with room
165/// for 16 impacts each:
166///
167/// ```
168/// use resource_timeline::storage::{Fixed, FixedPlan};
169/// use resource_timeline::{ActivityId, Demand, Impact, Plan, Timeline, Window};
170///
171/// let mut plan = Plan::<FixedPlan<2, 1, 16>>::new_in();
172/// let transmitter = plan.add_timeline(Timeline::<Fixed<16>>::claimable_in(0, 1, 16)?)?;
173/// let downlink = [Demand::Level {
174///     timeline: transmitter,
175///     impact: Impact::Claim { start: 0, end: 8, amount: 1 },
176/// }];
177///
178/// plan.place(ActivityId(1), 5, &downlink)?;
179/// assert_eq!(plan.earliest_start(&downlink, Window::new(0, 100)?, 1_000)?, Some(13));
180/// # Ok::<(), resource_timeline::Error>(())
181/// ```
182#[derive(Debug, Clone, Default, PartialEq, Eq, Hash)]
183pub struct Plan<
184    #[cfg(feature = "alloc")] P: PlanStorage = Heap,
185    #[cfg(not(feature = "alloc"))] P: PlanStorage,
186> {
187    /// The numeric timelines, addressed by [`TimelineId`].
188    timelines: P::Timelines,
189    /// The state timelines, addressed by [`StateId`].
190    states: P::States,
191}
192
193#[cfg(feature = "alloc")]
194impl Plan {
195    /// Creates an empty heap plan.
196    #[must_use]
197    pub const fn new() -> Self {
198        Self::new_in()
199    }
200}
201
202impl<P: PlanStorage> Plan<P> {
203    /// Creates an empty plan with storage `P`.
204    #[must_use]
205    pub const fn new_in() -> Self {
206        Self {
207            timelines: <P::Timelines as Seq<_>>::EMPTY,
208            states: <P::States as Seq<_>>::EMPTY,
209        }
210    }
211
212    /// Adds a numeric timeline and returns its handle.
213    ///
214    /// # Errors
215    ///
216    /// [`Error::OutOfMemory`] if the timeline list cannot grow (heap storage),
217    /// [`Error::CapacityExceeded`] naming [`Container::Timelines`] if it is full (fixed
218    /// storage).
219    pub fn add_timeline(&mut self, timeline: Timeline<P::Line>) -> Result<TimelineId, Error> {
220        self.timelines.try_push(timeline, Container::Timelines)?;
221        Ok(TimelineId(self.timelines.len() - 1))
222    }
223
224    /// Adds a state timeline and returns its handle.
225    ///
226    /// # Errors
227    ///
228    /// [`Error::OutOfMemory`] if the timeline list cannot grow (heap storage),
229    /// [`Error::CapacityExceeded`] naming [`Container::States`] if it is full (fixed storage).
230    pub fn add_state(&mut self, timeline: StateTimeline<P::Line>) -> Result<StateId, Error> {
231        self.states.try_push(timeline, Container::States)?;
232        Ok(StateId(self.states.len() - 1))
233    }
234
235    /// The numeric timelines, in the order they were added.
236    #[must_use]
237    pub fn timelines(&self) -> &[Timeline<P::Line>] {
238        &self.timelines
239    }
240
241    /// The state timelines, in the order they were added.
242    #[must_use]
243    pub fn states(&self) -> &[StateTimeline<P::Line>] {
244        &self.states
245    }
246
247    /// The numeric timeline behind `id`, if it belongs to this plan.
248    #[must_use]
249    pub fn timeline(&self, id: TimelineId) -> Option<&Timeline<P::Line>> {
250        self.timelines.get(id.0)
251    }
252
253    /// The state timeline behind `id`, if it belongs to this plan.
254    #[must_use]
255    pub fn state(&self, id: StateId) -> Option<&StateTimeline<P::Line>> {
256        self.states.get(id.0)
257    }
258
259    /// Requires the level of numeric timeline `id` at `target.at` to be at least `target.min`.
260    ///
261    /// See [`Timeline::add_target`]. [`fits`](Self::fits) and
262    /// [`earliest_start`](Self::earliest_start) then reject starts that would miss it.
263    ///
264    /// # Errors
265    ///
266    /// [`Error::UnknownResource`] if `id` is not part of this plan, and the errors of
267    /// [`Timeline::add_target`].
268    pub fn add_target(&mut self, id: TimelineId, target: crate::Target) -> Result<(), Error> {
269        self.timelines
270            .get_mut(id.0)
271            .ok_or(Error::UnknownResource)?
272            .add_target(target)
273    }
274
275    /// Adds every demand of `activity`, shifted to `start`, to its timeline.
276    ///
277    /// The placement is all or nothing. It does not check the bounds; use
278    /// [`fits`](Self::fits) before or [`first_violation`](Self::first_violation) after.
279    /// Placing the same activity id twice is allowed; [`remove`](Self::remove) then removes both.
280    ///
281    /// # Errors
282    ///
283    /// - [`Error::UnknownResource`] if a demand names a timeline outside this plan.
284    /// - [`Error::Overflow`] if a shifted tick does not fit a [`Tick`].
285    /// - The validation errors of [`Timeline::add`] and [`StateTimeline::add`], including
286    ///   [`Error::BudgetExhausted`] and, with fixed storage, [`Error::CapacityExceeded`]. Both
287    ///   are detected before anything is added.
288    /// - [`Error::OutOfMemory`] if an impact list cannot grow.
289    ///
290    /// The plan is unchanged on error.
291    pub fn place(
292        &mut self,
293        activity: ActivityId,
294        start: Tick,
295        demands: &[Demand],
296    ) -> Result<(), Error> {
297        for (index, demand) in demands.iter().enumerate() {
298            let pending = demands[..=index]
299                .iter()
300                .filter(|other| other.same_timeline(demand))
301                .count();
302            self.validate(&self.shift(demand, start)?, pending)?;
303        }
304
305        for (added, demand) in demands.iter().enumerate() {
306            let shifted = self.shift(demand, start)?;
307            if let Err(error) = self.add_unchecked(activity, shifted) {
308                self.undo(&demands[..added]);
309                return Err(error);
310            }
311        }
312
313        Ok(())
314    }
315
316    /// Removes every impact of `activity` from every timeline and returns how many there were.
317    pub fn remove(&mut self, activity: ActivityId) -> usize {
318        let levels: usize = self.timelines.iter_mut().map(|t| t.remove(activity)).sum();
319        let states: usize = self.states.iter_mut().map(|t| t.remove(activity)).sum();
320        levels + states
321    }
322
323    /// The earliest violation over all timelines.
324    ///
325    /// Ties at the same tick go to numeric timelines before state timelines, then to the
326    /// timeline added first.
327    ///
328    /// # Errors
329    ///
330    /// The errors of [`Timeline::first_violation`] and [`StateTimeline::first_violation`].
331    pub fn first_violation(&self) -> Result<Option<PlanViolation<P::Line>>, Error> {
332        let mut earliest: Option<PlanViolation<P::Line>> = None;
333        for (index, timeline) in self.timelines.iter().enumerate() {
334            if let Some(violation) = timeline.first_violation()? {
335                let found = PlanViolation::Level {
336                    timeline: TimelineId(index),
337                    violation,
338                };
339                keep_earlier(&mut earliest, found);
340            }
341        }
342
343        for (index, timeline) in self.states.iter().enumerate() {
344            if let Some(violation) = timeline.first_violation()? {
345                let found = PlanViolation::State {
346                    timeline: StateId(index),
347                    violation,
348                };
349                keep_earlier(&mut earliest, found);
350            }
351        }
352
353        Ok(earliest)
354    }
355
356    /// Whether the activity described by `demands` could start at `start` without violating
357    /// any timeline it touches.
358    ///
359    /// "Without violating" means the touched timelines have no violation at all once the
360    /// demands are added, so a timeline that is already violated admits nothing. Timelines the
361    /// demands do not touch are not checked. A demand that would precede its timeline's start
362    /// does not fit. The impact budgets are not consulted; [`place`](Self::place) does that.
363    ///
364    /// # Errors
365    ///
366    /// - [`Error::UnknownResource`] if a demand names a timeline outside this plan.
367    /// - [`Error::Overflow`] if a shifted tick or a level does not fit.
368    /// - The validation errors of [`Timeline::add`] and [`StateTimeline::add`] other than
369    ///   [`Error::BeforeStart`], which mean the demands are malformed at every start.
370    /// - [`Error::OutOfMemory`] if the scratch buffers cannot be allocated (heap storage).
371    /// - [`Error::CapacityExceeded`] naming [`Container::Scratch`] if more demands address one
372    ///   timeline than its fixed capacity holds (fixed storage); such an activity could not be
373    ///   placed either.
374    pub fn fits(&self, demands: &[Demand], start: Tick) -> Result<bool, Error> {
375        self.fits_with(demands, start, &mut SearchScratch::new())
376    }
377
378    /// [`fits`](Self::fits) with borrowed working memory instead of a stack buffer.
379    ///
380    /// # Errors
381    ///
382    /// As for [`fits`](Self::fits).
383    pub fn fits_with(
384        &self,
385        demands: &[Demand],
386        start: Tick,
387        scratch: &mut SearchScratch<P::Line>,
388    ) -> Result<bool, Error> {
389        search::Probe::new(self, demands, scratch)?.fits(start)
390    }
391
392    /// The earliest start in `window` at which [`fits`](Self::fits) holds, or `None`.
393    ///
394    /// The answer can only change where a demand tick meets a change tick or target of its
395    /// timeline. The search walks the pieces between consecutive such candidates, `O(n k)` of
396    /// them for `n` change ticks and `k` demands, without collecting them. Without rates the
397    /// levels are piecewise constant and one check at the piece start decides the whole piece.
398    /// With rates (in the demands or a touched timeline) the levels are affine in the start
399    /// within a piece, and the earliest fitting start of the piece is solved in closed form
400    /// from two sweeps, so the cost does not grow with the window length. Each piece costs
401    /// `O(n k)`; nothing is allocated beyond the scratch reserved up front.
402    ///
403    /// `max_checks` caps the number of pieces examined.
404    ///
405    /// # Errors
406    ///
407    /// - [`Error::SearchExhausted`] if `max_checks` pieces were examined without an answer.
408    /// - The errors of [`fits`](Self::fits).
409    pub fn earliest_start(
410        &self,
411        demands: &[Demand],
412        window: Window,
413        max_checks: usize,
414    ) -> Result<Option<Tick>, Error> {
415        self.earliest_start_with(demands, window, max_checks, &mut SearchScratch::new())
416    }
417
418    /// [`earliest_start`](Self::earliest_start) with borrowed working memory instead of a
419    /// stack buffer; see [`SearchScratch`] for sizes and an example.
420    ///
421    /// # Errors
422    ///
423    /// As for [`earliest_start`](Self::earliest_start).
424    pub fn earliest_start_with(
425        &self,
426        demands: &[Demand],
427        window: Window,
428        max_checks: usize,
429        scratch: &mut SearchScratch<P::Line>,
430    ) -> Result<Option<Tick>, Error> {
431        search::earliest_start(self, demands, window, max_checks, scratch)
432    }
433
434    /// `demand` moved to absolute ticks for an activity starting at `start`.
435    fn shift(&self, demand: &Demand, start: Tick) -> Result<Demand, Error> {
436        let shifted = match *demand {
437            Demand::Level { timeline, impact } => {
438                self.timeline(timeline).ok_or(Error::UnknownResource)?;
439                impact
440                    .shifted(start)
441                    .map(|impact| Demand::Level { timeline, impact })
442            }
443            Demand::State { timeline, impact } => {
444                self.state(timeline).ok_or(Error::UnknownResource)?;
445                impact
446                    .shifted(start)
447                    .map(|impact| Demand::State { timeline, impact })
448            }
449        };
450
451        shifted.ok_or(Error::Overflow)
452    }
453
454    /// Checks a shifted demand and that its timeline has room for `pending` more impacts.
455    fn validate(&self, demand: &Demand, pending: usize) -> Result<(), Error> {
456        match *demand {
457            Demand::Level { timeline, impact } => {
458                let timeline = &self.timelines[timeline.0];
459                timeline.validate(impact)?;
460                timeline.ensure_room(pending)
461            }
462            Demand::State { timeline, impact } => {
463                let timeline = &self.states[timeline.0];
464                timeline.validate(impact)?;
465                timeline.ensure_room(pending)
466            }
467        }
468    }
469
470    /// Adds an already validated, shifted demand.
471    fn add_unchecked(&mut self, activity: ActivityId, demand: Demand) -> Result<(), Error> {
472        match demand {
473            Demand::Level { timeline, impact } => self.timelines[timeline.0].add(activity, impact),
474            Demand::State { timeline, impact } => self.states[timeline.0].add(activity, impact),
475        }
476    }
477
478    /// Takes back the impacts that the given, already added demands created, newest first.
479    fn undo(&mut self, added: &[Demand]) {
480        for demand in added.iter().rev() {
481            match *demand {
482                Demand::Level { timeline, .. } => self.timelines[timeline.0].undo_last(),
483                Demand::State { timeline, .. } => self.states[timeline.0].undo_last(),
484            }
485        }
486    }
487}
488
489/// Replaces `earliest` with `found` if `found` is strictly earlier or `earliest` is empty.
490fn keep_earlier<S: Storage>(earliest: &mut Option<PlanViolation<S>>, found: PlanViolation<S>) {
491    if earliest
492        .as_ref()
493        .is_none_or(|current| found.at() < current.at())
494    {
495        *earliest = Some(found);
496    }
497}
498
499#[cfg(all(test, feature = "alloc"))]
500mod tests {
501    //! Unit tests of the rollback path, which `place` reaches only on allocation failure.
502
503    use alloc::vec::Vec;
504
505    use super::{Demand, Plan};
506    use crate::{ActivityId, Bounds, Impact, StateImpact, StateTimeline, Timeline};
507
508    /// Undoing freshly added demands restores the plan exactly, including earlier impacts of
509    /// the same activity and duplicate sets.
510    #[test]
511    fn undo_restores_the_plan() {
512        let mut plan = Plan::new();
513        let bounds = Bounds::new(0, 10).expect("valid");
514        let battery = plan
515            .add_timeline(Timeline::depletable(0, 5, bounds, 8).expect("valid"))
516            .expect("memory");
517        let mode = plan.add_state(StateTimeline::new(0, 0, 8)).expect("memory");
518        let demands = [
519            Demand::Level {
520                timeline: battery,
521                impact: Impact::Rate {
522                    start: 0,
523                    end: 4,
524                    per_tick: -1,
525                },
526            },
527            Demand::State {
528                timeline: mode,
529                impact: StateImpact::Set { at: 2, value: 1 },
530            },
531            Demand::State {
532                timeline: mode,
533                impact: StateImpact::Require {
534                    start: 2,
535                    end: 5,
536                    value: 1,
537                },
538            },
539            Demand::Level {
540                timeline: battery,
541                impact: Impact::Step { at: 3, delta: 2 },
542            },
543        ];
544        plan.place(ActivityId(1), 1, &demands).expect("valid");
545        let before = plan.clone();
546
547        plan.place(ActivityId(1), 1, &demands).expect("valid");
548        let shifted: Vec<Demand> = demands
549            .iter()
550            .map(|d| plan.shift(d, 1).expect("small"))
551            .collect();
552        plan.undo(&shifted);
553        assert_eq!(plan, before);
554    }
555}