resource_timeline/timeline.rs
1//! Numeric resource timelines and their bound checks.
2
3pub(crate) mod extract;
4pub(crate) mod profile;
5pub(crate) mod sweep;
6
7#[cfg(feature = "alloc")]
8use crate::storage::Heap;
9use crate::storage::{Seq, Slot, Storage};
10use crate::{ActivityId, Container, Error, Impact, Level, Target, Tick, Violation};
11use profile::{Point, Profile};
12use sweep::{Breach, Frame};
13
14/// The inclusive range `[min, max]` a resource level must stay in.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub struct Bounds {
17 /// The lowest allowed level, for example an energy reserve. Never greater than `max`.
18 min: Level,
19 /// The highest allowed level, for example a battery or storage capacity.
20 max: Level,
21}
22
23impl Bounds {
24 /// Creates the range `[min, max]`.
25 ///
26 /// # Errors
27 ///
28 /// Returns [`Error::InvalidBounds`] if `min > max`.
29 pub const fn new(min: Level, max: Level) -> Result<Self, Error> {
30 if min > max {
31 return Err(Error::InvalidBounds { min, max });
32 }
33
34 Ok(Self { min, max })
35 }
36
37 /// The lowest allowed level.
38 #[must_use]
39 pub const fn min(&self) -> Level {
40 self.min
41 }
42
43 /// The highest allowed level.
44 #[must_use]
45 pub const fn max(&self) -> Level {
46 self.max
47 }
48}
49
50/// How impacts change a timeline's level.
51///
52/// | Resource | Kind | Impacts |
53/// | --- | --- | --- |
54/// | Energy, data volume, propellant (consumable, cumulative) | [`Depletable`](Self::Depletable) | [`Impact::Step`] for lumps, [`Impact::Rate`] for charge, discharge or drift |
55/// | Power bus share, comm channel, instrument (reusable) | [`Claimable`](Self::Claimable) | [`Impact::Claim`] |
56/// | Mode, visibility window | not numeric | see [`StateTimeline`](crate::StateTimeline) |
57#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
58#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
59pub enum Kind {
60 /// Consumed and produced by permanent changes, for example energy or data volume.
61 ///
62 /// Accepts every [`Impact`]. Steps and rates persist after the activity; claims model a
63 /// temporary hold such as a reserved margin.
64 Depletable,
65 /// Borrowed for an interval and returned, for example an instrument or a transmitter.
66 ///
67 /// Accepts [`Impact::Claim`] only.
68 Claimable,
69}
70
71/// The level of one resource over time, built from activity impacts.
72///
73/// The storage `S` is [`storage::Heap`](crate::storage::Heap) by default; with
74/// [`Fixed<N>`](crate::storage::Fixed) the timeline holds at most `N` impacts and never
75/// allocates (see [`storage`](crate::storage)). Heap timelines are created with
76/// [`depletable`] and [`claimable`], timelines with any
77/// storage with [`depletable_in`](Self::depletable_in) and [`claimable_in`](Self::claimable_in).
78///
79/// The level starts at an initial value at the start tick and changes only through impacts. It
80/// is piecewise linear: steps and claims make it jump, rates give it a slope. Checks cover
81/// every tick from the start onward; after the last impact ends the level is constant.
82///
83/// The timeline keeps its impacts and, alongside them, a sorted list of change points that is
84/// updated on every [`add`](Self::add) and [`remove`](Self::remove). A check sweeps the change
85/// points once without sorting or allocating.
86///
87/// # Examples
88///
89/// ```
90/// use resource_timeline::{ActivityId, Bound, Bounds, Impact, Timeline};
91///
92/// // Battery at 50 units, reserve 10. A drive drains 3 units per tick from tick 0 to tick 20.
93/// let mut battery = Timeline::depletable(0, 50, Bounds::new(10, 100)?, 8)?;
94/// battery.add(ActivityId(1), Impact::Rate { start: 0, end: 20, per_tick: -3 })?;
95///
96/// let violation = battery.first_violation()?.expect("the reserve is broken");
97/// assert_eq!(violation.at, 14); // 50 - 3 * 14 = 8 < 10
98/// assert_eq!(violation.level, 8);
99/// assert_eq!(violation.bound, Bound::BelowMin(10));
100///
101/// // Cancelling the drive restores the battery.
102/// assert_eq!(battery.remove(ActivityId(1)), 1);
103/// assert_eq!(battery.first_violation()?, None);
104/// # Ok::<(), resource_timeline::Error>(())
105/// ```
106///
107#[cfg_attr(feature = "alloc", doc = "[`depletable`]: Self::depletable")]
108#[cfg_attr(not(feature = "alloc"), doc = "[`depletable`]: crate#features")]
109#[cfg_attr(feature = "alloc", doc = "[`claimable`]: Self::claimable")]
110#[cfg_attr(not(feature = "alloc"), doc = "[`claimable`]: crate#features")]
111#[derive(Debug, Clone, PartialEq, Eq, Hash)]
112pub struct Timeline<
113 #[cfg(feature = "alloc")] S: Storage = Heap,
114 #[cfg(not(feature = "alloc"))] S: Storage,
115> {
116 /// Which impacts the timeline accepts.
117 kind: Kind,
118 /// The first tick of the timeline. No impact may take effect earlier.
119 start: Tick,
120 /// The level at the start tick, before impacts at the start tick apply.
121 initial: Level,
122 /// The range the level must stay in.
123 bounds: Bounds,
124 /// The maximum number of impacts the timeline accepts.
125 budget: usize,
126 /// The impacts in insertion order. Never longer than `budget`.
127 impacts: S::List<(ActivityId, Impact)>,
128 /// The change points of all impacts, kept in sync with `impacts`.
129 profile: Profile<S>,
130 /// The end-state targets, sorted by [`Target::key`]. None before `start`.
131 targets: S::List<Target>,
132}
133
134#[cfg(feature = "alloc")]
135impl Timeline {
136 /// Creates a heap timeline for a depletable resource such as battery energy or storage.
137 ///
138 /// `initial` is the level at `start`. `budget` caps the number of impacts.
139 ///
140 /// # Errors
141 ///
142 /// Never fails today; returns `Result` so later validation does not break callers.
143 pub const fn depletable(
144 start: Tick,
145 initial: Level,
146 bounds: Bounds,
147 budget: usize,
148 ) -> Result<Self, Error> {
149 Self::depletable_in(start, initial, bounds, budget)
150 }
151
152 /// Creates a heap timeline for a claimable resource with `capacity` units, all available
153 /// at `start`.
154 ///
155 /// The bounds are `[0, capacity]`, so overlapping claims may never hold more than
156 /// `capacity` units. `budget` caps the number of impacts.
157 ///
158 /// # Errors
159 ///
160 /// Returns [`Error::InvalidBounds`] if `capacity` is negative.
161 pub const fn claimable(start: Tick, capacity: Level, budget: usize) -> Result<Self, Error> {
162 Self::claimable_in(start, capacity, budget)
163 }
164}
165
166impl<S: Storage> Timeline<S> {
167 /// Creates a timeline with storage `S` for a depletable resource such as battery energy.
168 ///
169 /// As [`Timeline::depletable`], for any [`Storage`]. With [`Fixed<N>`](crate::storage::Fixed)
170 /// a `budget` above `N` is allowed, but adds beyond `N` fail with
171 /// [`Error::CapacityExceeded`].
172 ///
173 #[cfg_attr(
174 feature = "alloc",
175 doc = "[`Timeline::depletable`]: Timeline::depletable"
176 )]
177 #[cfg_attr(
178 not(feature = "alloc"),
179 doc = "[`Timeline::depletable`]: crate#features"
180 )]
181 ///
182 /// # Errors
183 ///
184 /// Never fails today; returns `Result` so later validation does not break callers.
185 ///
186 /// # Examples
187 ///
188 /// ```
189 /// use resource_timeline::storage::Fixed;
190 /// use resource_timeline::{Bounds, Timeline};
191 ///
192 /// let battery = Timeline::<Fixed<32>>::depletable_in(0, 100, Bounds::new(20, 120)?, 32)?;
193 /// assert_eq!(battery.level_at(1_000)?, 100);
194 /// # Ok::<(), resource_timeline::Error>(())
195 /// ```
196 pub const fn depletable_in(
197 start: Tick,
198 initial: Level,
199 bounds: Bounds,
200 budget: usize,
201 ) -> Result<Self, Error> {
202 Ok(Self::new(Kind::Depletable, start, initial, bounds, budget))
203 }
204
205 /// Creates a timeline with storage `S` for a claimable resource with `capacity` units.
206 ///
207 /// As [`Timeline::claimable`], for any [`Storage`].
208 ///
209 #[cfg_attr(
210 feature = "alloc",
211 doc = "[`Timeline::claimable`]: Timeline::claimable"
212 )]
213 #[cfg_attr(
214 not(feature = "alloc"),
215 doc = "[`Timeline::claimable`]: crate#features"
216 )]
217 ///
218 /// # Errors
219 ///
220 /// Returns [`Error::InvalidBounds`] if `capacity` is negative.
221 pub const fn claimable_in(start: Tick, capacity: Level, budget: usize) -> Result<Self, Error> {
222 match Bounds::new(0, capacity) {
223 Ok(bounds) => Ok(Self::new(Kind::Claimable, start, capacity, bounds, budget)),
224 Err(error) => Err(error),
225 }
226 }
227
228 /// Creates an empty timeline from its validated parts.
229 const fn new(kind: Kind, start: Tick, initial: Level, bounds: Bounds, budget: usize) -> Self {
230 Self {
231 kind,
232 start,
233 initial,
234 bounds,
235 budget,
236 impacts: <S::List<(ActivityId, Impact)> as Seq<_>>::EMPTY,
237 profile: Profile::EMPTY,
238 targets: <S::List<Target> as Seq<_>>::EMPTY,
239 }
240 }
241
242 /// Which impacts the timeline accepts.
243 #[must_use]
244 pub const fn kind(&self) -> Kind {
245 self.kind
246 }
247
248 /// The first tick of the timeline.
249 #[must_use]
250 pub const fn start(&self) -> Tick {
251 self.start
252 }
253
254 /// The level at the start tick, before impacts at the start tick apply.
255 #[must_use]
256 pub const fn initial(&self) -> Level {
257 self.initial
258 }
259
260 /// The range the level must stay in.
261 #[must_use]
262 pub const fn bounds(&self) -> Bounds {
263 self.bounds
264 }
265
266 /// The maximum number of impacts the timeline accepts.
267 #[must_use]
268 pub const fn budget(&self) -> usize {
269 self.budget
270 }
271
272 /// The impacts added so far, in insertion order.
273 #[must_use]
274 pub fn impacts(&self) -> &[(ActivityId, Impact)] {
275 &self.impacts
276 }
277
278 /// Adds an impact of `activity` to the timeline.
279 ///
280 /// The impact is validated but not checked against the bounds; call
281 /// [`first_violation`](Self::first_violation) for that.
282 ///
283 /// # Errors
284 ///
285 /// - [`Error::KindMismatch`] if a step or rate is added to a claimable timeline.
286 /// - [`Error::BeforeStart`] if the impact takes effect before the timeline start.
287 /// - [`Error::EmptyInterval`] if a claim or rate has `end <= start`.
288 /// - [`Error::NonPositiveAmount`] if a claim amount is zero or negative.
289 /// - [`Error::BudgetExhausted`] if the timeline already holds `budget` impacts.
290 /// - [`Error::OutOfMemory`] if the impact list cannot grow (heap storage).
291 /// - [`Error::CapacityExceeded`] if the impact list or the change points are full
292 /// (fixed storage).
293 ///
294 /// The timeline is unchanged on error.
295 pub fn add(&mut self, activity: ActivityId, impact: Impact) -> Result<(), Error> {
296 self.validate(impact)?;
297 self.ensure_room(1)?;
298 self.impacts.try_reserve(1, Container::Impacts)?;
299 self.profile.add(&impact)?;
300 self.impacts
301 .try_push((activity, impact), Container::Impacts)
302 }
303
304 /// Removes every impact of `activity` and returns how many there were.
305 ///
306 /// Never allocates. Costs `O(n)` for the impact list plus `O(n)` per removed impact for
307 /// the change points. Removing an activity without impacts is a no-op that returns `0`.
308 pub fn remove(&mut self, activity: ActivityId) -> usize {
309 let before = self.impacts.len();
310 let profile = &mut self.profile;
311 self.impacts.retain(|&(owner, impact)| {
312 let keep = owner != activity;
313 if !keep {
314 profile.remove(&impact);
315 }
316
317 keep
318 });
319
320 before - self.impacts.len()
321 }
322
323 /// Requires the level at `target.at` to be at least `target.min`.
324 ///
325 /// Targets do not count against the impact budget. Several targets may share a tick; the
326 /// strictest one is reported first. See [`Target`] for an example.
327 ///
328 /// # Errors
329 ///
330 /// - [`Error::BeforeStart`] if the target precedes the timeline start.
331 /// - [`Error::OutOfMemory`] if the target list cannot grow (heap storage).
332 /// - [`Error::CapacityExceeded`] naming [`Container::Targets`] if it is full (fixed
333 /// storage).
334 pub fn add_target(&mut self, target: Target) -> Result<(), Error> {
335 if target.at < self.start {
336 return Err(Error::BeforeStart {
337 at: target.at,
338 start: self.start,
339 });
340 }
341
342 let index = self
343 .targets
344 .partition_point(|other| other.key() <= target.key());
345 self.targets.try_insert(index, target, Container::Targets)
346 }
347
348 /// The end-state targets, sorted by tick and, within a tick, strictest first.
349 #[must_use]
350 pub fn targets(&self) -> &[Target] {
351 &self.targets
352 }
353
354 /// Removes every target at tick `at` and returns how many there were. Never allocates.
355 pub fn remove_targets_at(&mut self, at: Tick) -> usize {
356 let before = self.targets.len();
357 self.targets.retain(|target| target.at != at);
358 before - self.targets.len()
359 }
360
361 /// Removes the most recently added impact, if any. Never allocates.
362 pub(crate) fn undo_last(&mut self) {
363 if let Some((_, impact)) = self.impacts.pop() {
364 self.profile.remove(&impact);
365 }
366 }
367
368 /// The ticks at which a check outcome can change: every change point and every target.
369 /// Not sorted across the two kinds, possibly with duplicates.
370 #[cfg(feature = "alloc")]
371 pub(crate) fn change_ticks(&self) -> impl Iterator<Item = Tick> + '_ {
372 let points = self.profile.points().iter().map(|point| point.at);
373 points.chain(self.targets.iter().map(|target| target.at))
374 }
375
376 /// The first tick `>= x` among the start, the change points and the targets, if any.
377 ///
378 /// Costs `O(log n)`.
379 pub(crate) fn first_change_from(&self, x: i128) -> Option<Tick> {
380 let points = self.profile.points();
381 let point = points.get(points.partition_point(|point| i128::from(point.at) < x));
382 let target = self.targets.get(
383 self.targets
384 .partition_point(|target| i128::from(target.at) < x),
385 );
386 let start = (i128::from(self.start) >= x).then_some(self.start);
387 [
388 start,
389 point.map(|point| point.at),
390 target.map(|target| target.at),
391 ]
392 .into_iter()
393 .flatten()
394 .min()
395 }
396
397 /// `Ok` while the timeline has room for `extra` more impacts, by budget and by capacity.
398 ///
399 /// A fixed change-point list has room for two points per impact, so the impact capacity
400 /// covers it.
401 ///
402 /// # Errors
403 ///
404 /// - [`Error::BudgetExhausted`] if `extra` more impacts would exceed the budget.
405 /// - [`Error::CapacityExceeded`] if they would exceed a fixed impact capacity.
406 pub(crate) fn ensure_room(&self, extra: usize) -> Result<(), Error> {
407 let needed = self.impacts.len().saturating_add(extra);
408 if needed > self.budget {
409 return Err(Error::BudgetExhausted { limit: self.budget });
410 }
411
412 match self.impacts.capacity() {
413 Some(capacity) if needed > capacity => Err(Error::CapacityExceeded {
414 container: Container::Impacts,
415 capacity,
416 }),
417 _ => Ok(()),
418 }
419 }
420
421 /// Checks that `impact` fits this timeline's kind and start, and is well formed.
422 ///
423 /// # Errors
424 ///
425 /// The validation errors listed on [`add`](Self::add).
426 pub(crate) fn validate(&self, impact: Impact) -> Result<(), Error> {
427 if self.kind == Kind::Claimable && !matches!(impact, Impact::Claim { .. }) {
428 return Err(Error::KindMismatch);
429 }
430
431 match impact {
432 Impact::Claim { start, end, amount } => {
433 if end <= start {
434 return Err(Error::EmptyInterval { start, end });
435 }
436
437 if amount <= 0 {
438 return Err(Error::NonPositiveAmount { amount });
439 }
440 }
441 Impact::Rate { start, end, .. } if end <= start => {
442 return Err(Error::EmptyInterval { start, end });
443 }
444 Impact::Step { .. } | Impact::Rate { .. } => {}
445 }
446
447 let at = impact.first_tick();
448 if at < self.start {
449 return Err(Error::BeforeStart {
450 at,
451 start: self.start,
452 });
453 }
454
455 Ok(())
456 }
457
458 /// The level at tick `t`, with all impacts at `t` applied.
459 ///
460 /// Costs `O(n)` for `n` impacts.
461 ///
462 /// # Errors
463 ///
464 /// - [`Error::BeforeStart`] if `t` precedes the timeline start, where no level is defined.
465 /// - [`Error::Overflow`] if the level does not fit a [`Level`].
466 pub fn level_at(&self, t: Tick) -> Result<Level, Error> {
467 if t < self.start {
468 return Err(Error::BeforeStart {
469 at: t,
470 start: self.start,
471 });
472 }
473
474 let level = self
475 .impacts
476 .iter()
477 .try_fold(i128::from(self.initial), |level, (_, impact)| {
478 level.checked_add(impact.contribution_at(t)?)
479 })
480 .ok_or(Error::Overflow)?;
481 Level::try_from(level).map_err(|_| Error::Overflow)
482 }
483
484 /// Whether any impact on this timeline is a [`Impact::Rate`] with a non-zero rate.
485 #[must_use]
486 pub fn has_rates(&self) -> bool {
487 self.profile.has_slope()
488 }
489
490 /// Finds the earliest tick at which the level is outside the bounds or misses a
491 /// [`Target`].
492 ///
493 /// At the same tick, a broken bound is reported before a missed target.
494 /// All impacts at a tick are netted before the level is compared, so a claim ending at `t`
495 /// and another starting at `t` never overlap. Along a rate the exact crossing tick is
496 /// found by integer division, not by stepping tick by tick. Runs in `O(n)` time over the
497 /// change points; only the explanation of a violation allocates `O(n)` memory. The result
498 /// does not depend on insertion order.
499 ///
500 /// Returns `Ok(None)` if the level stays within the bounds forever.
501 ///
502 /// # Errors
503 ///
504 /// - [`Error::Overflow`] if a running sum exceeds `i128`, or if the level at the first
505 /// violation does not fit a [`Level`]. A violation exists in the second case, but it
506 /// cannot be reported exactly.
507 /// - [`Error::OutOfMemory`] if the working memory cannot be allocated (heap storage).
508 /// Fixed storage has room for its explanation by construction.
509 pub fn first_violation(&self) -> Result<Option<Violation<S>>, Error> {
510 match self.breach_with(&[])? {
511 Some(breach) => sweep::explain::<S>(&self.impacts, breach).map(Some),
512 None => Ok(None),
513 }
514 }
515
516 /// The activities whose net effect in force at `t` pushes towards `bound`, sorted.
517 ///
518 /// # Errors
519 ///
520 /// [`Error::Overflow`] or [`Error::OutOfMemory`] as for
521 /// [`first_violation`](Self::first_violation).
522 #[cfg(feature = "alloc")]
523 pub(crate) fn contributors_at(
524 &self,
525 t: Tick,
526 bound: crate::Bound,
527 ) -> Result<S::List<ActivityId>, Error> {
528 sweep::contributors::<S>(&self.impacts, t, bound)
529 }
530
531 /// Narrows `offsets` to the start offsets `k` at which a tentative activity keeps this
532 /// timeline valid, given its change points `first` at offset 0 and `second` at offset 1.
533 ///
534 /// Both point lists must produce the same segment structure, so that every evaluated level
535 /// is affine in `k` (see the search module). Never allocates.
536 ///
537 /// # Errors
538 ///
539 /// [`Error::Overflow`] if a level exceeds `i128`.
540 pub(crate) fn narrow(
541 &self,
542 first: &[Point],
543 second: &[Point],
544 offsets: &mut crate::plan::Offsets,
545 ) -> Result<(), Error> {
546 let frame = self.frame();
547 sweep::narrow(&frame, self.profile.points(), [first, second], offsets)
548 }
549
550 /// The fixed parameters of a sweep over this timeline.
551 fn frame(&self) -> Frame<'_> {
552 Frame {
553 start: self.start,
554 initial: self.initial,
555 bounds: self.bounds,
556 targets: &self.targets,
557 }
558 }
559
560 /// The first breach of the bounds if the change points `extra` were added.
561 ///
562 /// `extra` must be sorted by tick and must not reach before the start. Never allocates.
563 ///
564 /// # Errors
565 ///
566 /// [`Error::Overflow`] if a level along a rate segment exceeds `i128`.
567 pub(crate) fn breach_with(&self, extra: &[Point]) -> Result<Option<Breach>, Error> {
568 sweep::first_breach(&self.frame(), self.profile.points(), extra)
569 }
570}
571
572impl<S: Storage> crate::storage::Sealed for Timeline<S> {}
573
574impl<S: Storage> Slot for Timeline<S> {
575 const EMPTY: Self = Self::new(Kind::Depletable, 0, 0, Bounds { min: 0, max: 0 }, 0);
576}