Skip to main content

resource_timeline/timeline/
extract.rs

1//! Profile extraction: the level as breakpoints, as samples, or as a compact exported struct.
2//!
3//! Display and telemetry need the level over time without the impact list behind it. Three
4//! views cover that, all allocation-free on fixed storage:
5//!
6//! - [`Timeline::breakpoints`] iterates the ticks where the line changes, each with the level
7//!   there and the slope after it;
8//! - [`Timeline::samples`] evaluates the level on a regular tick grid in one pass;
9//! - [`Timeline::export`] copies the breakpoints into a [`LevelProfile`], a self-contained value
10//!   that answers [`level_at`](LevelProfile::level_at) queries without the timeline.
11//!
12//! ```mermaid
13//! graph LR
14//!     timeline["Timeline: change points"] --> breakpoints["breakpoints: tick, level, slope"]
15//!     breakpoints --> export["export: LevelProfile"]
16//!     timeline --> samples["samples: level every step ticks"]
17//!     export --> query["LevelProfile::level_at"]
18//! ```
19
20use super::Timeline;
21use super::sweep::{Frame, Segment, Segments};
22#[cfg(feature = "alloc")]
23use crate::storage::Heap;
24use crate::storage::{Sealed, Seq, Slot, Storage};
25use crate::{Container, Error, Level, Tick};
26
27/// A tick at which the level line of a timeline changes: it jumps, or its slope changes.
28///
29/// Between two consecutive breakpoints the level is `level + slope * (t - at)`; after the last
30/// one it is constant (`slope` is zero there). Three `i64` per breakpoint, so a profile is as
31/// compact as the line it describes.
32#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
33#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34pub struct Breakpoint {
35    /// The tick of the change.
36    pub at: Tick,
37    /// The level at `at`, with every impact at `at` applied.
38    pub level: Level,
39    /// The level change per tick after `at`, until the next breakpoint.
40    pub slope: Level,
41}
42
43impl Breakpoint {
44    /// The level at `t` on the line through this breakpoint.
45    ///
46    /// # Errors
47    ///
48    /// [`Error::Overflow`] if the level does not fit a [`Level`].
49    fn level_at(&self, t: Tick) -> Result<Level, Error> {
50        let elapsed = i128::from(t) - i128::from(self.at);
51        let level = i128::from(self.slope)
52            .checked_mul(elapsed)
53            .and_then(|change| change.checked_add(i128::from(self.level)))
54            .ok_or(Error::Overflow)?;
55        Level::try_from(level).map_err(|_| Error::Overflow)
56    }
57
58    /// The breakpoint of `segment`, if its values fit a [`Level`].
59    ///
60    /// # Errors
61    ///
62    /// [`Error::Overflow`] if the level or the slope does not fit a [`Level`].
63    fn of(segment: &Segment) -> Result<Self, Error> {
64        Ok(Self {
65            at: segment.at,
66            level: Level::try_from(segment.level).map_err(|_| Error::Overflow)?,
67            slope: Level::try_from(segment.slope).map_err(|_| Error::Overflow)?,
68        })
69    }
70}
71
72impl Sealed for Breakpoint {}
73
74impl Slot for Breakpoint {
75    const EMPTY: Self = Self {
76        at: 0,
77        level: 0,
78        slope: 0,
79    };
80}
81
82/// The breakpoints of a timeline in time order; see [`Timeline::breakpoints`].
83pub struct Breakpoints<'a> {
84    /// The pieces of the level line.
85    segments: Segments<'a>,
86    /// The last piece yielded or skipped, to recognise pieces that continue it unchanged.
87    previous: Option<Segment>,
88}
89
90impl Iterator for Breakpoints<'_> {
91    type Item = Result<Breakpoint, Error>;
92
93    fn next(&mut self) -> Option<Self::Item> {
94        loop {
95            let segment = match self.segments.next()? {
96                Ok(segment) => segment,
97                Err(error) => return Some(Err(error)),
98            };
99
100            let previous = self.previous.replace(segment);
101            match previous.map(|previous| continues(&previous, &segment)) {
102                Some(Ok(true)) => {}
103                Some(Err(error)) => return Some(Err(error)),
104                Some(Ok(false)) | None => return Some(Breakpoint::of(&segment)),
105            }
106        }
107    }
108}
109
110/// Whether `segment` lies on the line of `previous`, so it is no breakpoint.
111///
112/// # Errors
113///
114/// [`Error::Overflow`] if the level on the line exceeds `i128`.
115fn continues(previous: &Segment, segment: &Segment) -> Result<bool, Error> {
116    Ok(previous.slope == segment.slope && previous.level_at(segment.at)? == segment.level)
117}
118
119/// The level of a timeline at regular ticks; see [`Timeline::samples`].
120pub struct Samples<'a> {
121    /// The pieces of the level line not yet passed.
122    segments: Segments<'a>,
123    /// The piece containing the next sample tick, once reached.
124    current: Option<Segment>,
125    /// The next sample tick.
126    next: Tick,
127    /// The distance between samples. Positive.
128    step: Tick,
129    /// The number of samples still to yield.
130    remaining: usize,
131}
132
133impl Samples<'_> {
134    /// The level at the next sample tick, moving along the pieces as needed.
135    ///
136    /// # Errors
137    ///
138    /// [`Error::Overflow`] if the level does not fit a [`Level`].
139    fn sample(&mut self) -> Result<Level, Error> {
140        loop {
141            match self.current {
142                Some(segment) if segment.next.is_none_or(|next| self.next < next) => {
143                    let level = segment.level_at(self.next)?;
144                    return Level::try_from(level).map_err(|_| Error::Overflow);
145                }
146                _ => {
147                    let segment = self.segments.next().ok_or(Error::Overflow)??;
148                    self.current = Some(segment);
149                }
150            }
151        }
152    }
153}
154
155impl Iterator for Samples<'_> {
156    type Item = Result<(Tick, Level), Error>;
157
158    fn next(&mut self) -> Option<Self::Item> {
159        self.remaining = self.remaining.checked_sub(1)?;
160        let at = self.next;
161        let level = match self.sample() {
162            Ok(level) => level,
163            Err(error) => {
164                self.remaining = 0;
165                return Some(Err(error));
166            }
167        };
168
169        match at.checked_add(self.step) {
170            Some(next) => self.next = next,
171            None => self.remaining = 0,
172        }
173
174        Some(Ok((at, level)))
175    }
176
177    fn size_hint(&self) -> (usize, Option<usize>) {
178        (0, Some(self.remaining))
179    }
180}
181
182/// A self-contained copy of a timeline's level line, for display and telemetry.
183///
184/// Holds the breakpoints only (three `i64` each), not the impacts, so it is cheap to store,
185/// send or compare. With [`Fixed<N>`](crate::storage::Fixed) storage it never allocates and
186/// always has room for the profile of an `N`-impact timeline.
187#[derive(Debug, Clone, PartialEq, Eq, Hash)]
188pub struct LevelProfile<
189    #[cfg(feature = "alloc")] S: Storage = Heap,
190    #[cfg(not(feature = "alloc"))] S: Storage,
191> {
192    /// The breakpoint at the timeline start.
193    origin: Breakpoint,
194    /// The later breakpoints, sorted by tick, each a real change of the line.
195    changes: S::DoubleList<Breakpoint>,
196}
197
198impl<S: Storage> LevelProfile<S> {
199    /// A profile from its start breakpoint and its later, strictly increasing breakpoints.
200    pub(crate) const fn from_parts(origin: Breakpoint, changes: S::DoubleList<Breakpoint>) -> Self {
201        Self { origin, changes }
202    }
203
204    /// The first tick of the profile, the start of the timeline it was exported from.
205    #[must_use]
206    pub const fn start(&self) -> Tick {
207        self.origin.at
208    }
209
210    /// The breakpoints in time order, the first at [`start`](Self::start).
211    pub fn breakpoints(&self) -> impl Iterator<Item = Breakpoint> + '_ {
212        core::iter::once(self.origin).chain(self.changes.iter().copied())
213    }
214
215    /// The number of breakpoints, at least one.
216    #[must_use]
217    pub fn len(&self) -> usize {
218        self.changes.len() + 1
219    }
220
221    /// Always `false`: a profile has at least the breakpoint at its start.
222    #[must_use]
223    pub const fn is_empty(&self) -> bool {
224        false
225    }
226
227    /// The level at tick `t`, as the exported timeline would report it.
228    ///
229    /// Costs `O(log n)` for `n` breakpoints.
230    ///
231    /// # Errors
232    ///
233    /// - [`Error::BeforeStart`] if `t` precedes the start.
234    /// - [`Error::Overflow`] if the level does not fit a [`Level`].
235    pub fn level_at(&self, t: Tick) -> Result<Level, Error> {
236        if t < self.origin.at {
237            return Err(Error::BeforeStart {
238                at: t,
239                start: self.origin.at,
240            });
241        }
242
243        let index = self.changes.partition_point(|point| point.at <= t);
244        let line = index
245            .checked_sub(1)
246            .map_or(self.origin, |last| self.changes[last]);
247        line.level_at(t)
248    }
249}
250
251impl<S: Storage> Timeline<S> {
252    /// The ticks at which the level line changes, in time order.
253    ///
254    /// The first breakpoint is at the start tick. A tick where impacts net to zero is no
255    /// breakpoint. Costs `O(n)` in total and never allocates. Targets are not part of the line.
256    ///
257    /// # Examples
258    ///
259    /// ```
260    /// use resource_timeline::{ActivityId, Bounds, Breakpoint, Impact, Timeline};
261    ///
262    /// let mut battery = Timeline::depletable(0, 50, Bounds::new(0, 100)?, 8)?;
263    /// battery.add(ActivityId(1), Impact::Rate { start: 10, end: 20, per_tick: -2 })?;
264    /// battery.add(ActivityId(2), Impact::Step { at: 30, delta: 5 })?;
265    ///
266    /// let points: Vec<Breakpoint> = battery.breakpoints().collect::<Result<_, _>>()?;
267    /// assert_eq!(points, [
268    ///     Breakpoint { at: 0, level: 50, slope: 0 },
269    ///     Breakpoint { at: 10, level: 50, slope: -2 },
270    ///     Breakpoint { at: 20, level: 30, slope: 0 },
271    ///     Breakpoint { at: 30, level: 35, slope: 0 },
272    /// ]);
273    /// # Ok::<(), resource_timeline::Error>(())
274    /// ```
275    pub fn breakpoints(&self) -> Breakpoints<'_> {
276        Breakpoints {
277            segments: self.segments(),
278            previous: None,
279        }
280    }
281
282    /// The level at `count` ticks `from`, `from + step`, `from + 2 step`, and so on.
283    ///
284    /// Costs `O(n + count)` and never allocates. The samples stop early if a tick would
285    /// overflow; an item is an error if its level does not fit a [`Level`].
286    ///
287    /// # Errors
288    ///
289    /// - [`Error::BeforeStart`] if `from` precedes the timeline start.
290    /// - [`Error::InvalidStep`] if `step` is not positive.
291    ///
292    /// # Examples
293    ///
294    /// ```
295    /// use resource_timeline::{ActivityId, Bounds, Impact, Timeline};
296    ///
297    /// let mut battery = Timeline::depletable(0, 50, Bounds::new(0, 100)?, 8)?;
298    /// battery.add(ActivityId(1), Impact::Rate { start: 10, end: 20, per_tick: -2 })?;
299    ///
300    /// let telemetry: Vec<(i64, i64)> = battery.samples(0, 5, 6)?.collect::<Result<_, _>>()?;
301    /// assert_eq!(telemetry, [(0, 50), (5, 50), (10, 50), (15, 40), (20, 30), (25, 30)]);
302    /// # Ok::<(), resource_timeline::Error>(())
303    /// ```
304    pub fn samples(&self, from: Tick, step: Tick, count: usize) -> Result<Samples<'_>, Error> {
305        if from < self.start {
306            return Err(Error::BeforeStart {
307                at: from,
308                start: self.start,
309            });
310        }
311
312        if step <= 0 {
313            return Err(Error::InvalidStep { step });
314        }
315
316        Ok(Samples {
317            segments: self.segments(),
318            current: None,
319            next: from,
320            step,
321            remaining: count,
322        })
323    }
324
325    /// A self-contained copy of the level line, with the timeline's storage.
326    ///
327    /// # Errors
328    ///
329    /// - [`Error::Overflow`] if a level or slope does not fit a [`Level`].
330    /// - [`Error::OutOfMemory`] if the breakpoint list cannot be allocated (heap storage).
331    ///   Fixed storage always has room.
332    ///
333    /// # Examples
334    ///
335    /// ```
336    /// use resource_timeline::storage::Fixed;
337    /// use resource_timeline::{ActivityId, Bounds, Impact, Timeline};
338    ///
339    /// let mut battery = Timeline::<Fixed<4>>::depletable_in(0, 50, Bounds::new(0, 100)?, 4)?;
340    /// battery.add(ActivityId(1), Impact::Rate { start: 10, end: 20, per_tick: -2 })?;
341    ///
342    /// let profile = battery.export()?;
343    /// assert_eq!(profile.len(), 3);
344    /// assert_eq!(profile.level_at(15)?, battery.level_at(15)?);
345    /// # Ok::<(), resource_timeline::Error>(())
346    /// ```
347    pub fn export(&self) -> Result<LevelProfile<S>, Error> {
348        let mut breakpoints = self.breakpoints();
349        let origin = breakpoints.next().ok_or(Error::Overflow)??;
350        let mut changes = <S::DoubleList<Breakpoint> as Seq<_>>::EMPTY;
351        for breakpoint in breakpoints {
352            changes.try_push(breakpoint?, Container::ChangePoints)?;
353        }
354
355        Ok(LevelProfile { origin, changes })
356    }
357
358    /// The pieces of the stored level line, without tentative changes.
359    fn segments(&self) -> Segments<'_> {
360        let frame = Frame {
361            start: self.start,
362            initial: self.initial,
363            bounds: self.bounds,
364            targets: &[],
365        };
366        Segments::new(&frame, self.profile.points(), &[])
367    }
368}