resource_timeline/storage.rs
1//! Storage strategies: heap-allocated or fixed-capacity, chosen per timeline and plan.
2//!
3//! Every container a timeline, a state timeline or a plan keeps goes through one of two
4//! strategies, selected by a type parameter:
5//!
6//! | Strategy | Containers | Memory | Exhaustion |
7//! | --- | --- | --- | --- |
8//! | [`Heap`] (feature `alloc`, the default) | `Vec` | grows on demand, fallibly | [`Error::OutOfMemory`] |
9//! | [`Fixed<N>`] | inline arrays of `N` (change points: `2 N`) | fixed, no allocator needed | [`Error::CapacityExceeded`] |
10//!
11//! Both run the same code: the algorithms are written once against the [`Seq`] trait, and the
12//! strategies only differ in how a container grows. A plan picks its strategy through
13//! [`PlanStorage`]: [`Heap`] again, or [`FixedPlan<T, S, N>`] for at most `T` numeric and `S`
14//! state timelines with [`Fixed<N>`] each.
15//!
16//! The runtime impact budget of a timeline still applies on top of the capacity: a
17//! [`Fixed<16>`] timeline created with budget 8 accepts 8 impacts and reports
18//! [`Error::BudgetExhausted`] on the ninth.
19//!
20//! ```mermaid
21//! graph LR
22//! algorithms["Timeline, StateTimeline, Plan logic"] --> seq["Seq: push, insert, remove, retain"]
23//! seq --> heap["Heap: Vec, fallible reserve"]
24//! seq --> fixed["Fixed: Inline array, typed capacity errors"]
25//! ```
26//!
27//! # Examples
28//!
29//! An allocation-free battery timeline with room for four impacts:
30//!
31//! ```
32//! use resource_timeline::storage::Fixed;
33//! use resource_timeline::{ActivityId, Bound, Bounds, Container, Error, Impact, Timeline};
34//!
35//! let mut battery = Timeline::<Fixed<4>>::depletable_in(0, 50, Bounds::new(10, 100)?, 4)?;
36//! battery.add(ActivityId(1), Impact::Rate { start: 0, end: 20, per_tick: -3 })?;
37//!
38//! let violation = battery.first_violation()?.expect("the reserve is broken");
39//! assert_eq!((violation.at, violation.bound), (14, Bound::BelowMin(10)));
40//! assert_eq!(&*violation.contributors, [ActivityId(1)]);
41//! # Ok::<(), resource_timeline::Error>(())
42//! ```
43//!
44//! Exceeding the capacity is a typed error that names the full container:
45//!
46//! ```
47//! use resource_timeline::storage::Fixed;
48//! use resource_timeline::{ActivityId, Container, Error, StateImpact, StateTimeline};
49//!
50//! // Budget 8, but only room for 2 impacts.
51//! let mut mode = StateTimeline::<Fixed<2>>::new_in(0, 0, 8);
52//! mode.add(ActivityId(1), StateImpact::Set { at: 1, value: 1 })?;
53//! mode.add(ActivityId(1), StateImpact::Set { at: 2, value: 0 })?;
54//! assert_eq!(
55//! mode.add(ActivityId(2), StateImpact::Set { at: 3, value: 1 }),
56//! Err(Error::CapacityExceeded { container: Container::Impacts, capacity: 2 })
57//! );
58//! # Ok::<(), resource_timeline::Error>(())
59//! ```
60
61mod inline;
62
63use core::fmt::Debug;
64use core::hash::Hash;
65use core::ops::{Deref, DerefMut};
66
67pub use inline::{Buffer, Inline};
68
69use crate::{Container, Error, StateTimeline, Timeline};
70
71/// Restricts the storage traits to the implementations in this crate.
72mod sealed {
73 /// Implemented only inside this crate.
74 pub trait Sealed {}
75}
76
77/// A value that can live in a fixed-capacity container.
78///
79/// Unused slots of an [`Inline`] container hold [`EMPTY`](Self::EMPTY), so the container needs
80/// neither `unsafe` nor `Default`. The trait is sealed: it is implemented for the crate's own
81/// element types only.
82pub trait Slot: Clone + Debug + Eq + Hash + sealed::Sealed {
83 /// The filler of unused slots. Never observable through a container.
84 const EMPTY: Self;
85}
86
87/// A growable sequence with fallible growth: the one interface all algorithms use.
88///
89/// Implemented by `Vec` (heap) and by [`Inline`] (fixed capacity). Reading goes through the
90/// slice the sequence dereferences to. Growing names the [`Container`] it fills, so a full
91/// inline container reports [`Error::CapacityExceeded`] with that name. The trait is sealed.
92pub trait Seq<T: Slot>:
93 Deref<Target = [T]> + DerefMut + Default + Clone + Debug + Eq + Hash + sealed::Sealed
94{
95 /// An empty sequence, usable in `const` contexts.
96 const EMPTY: Self;
97
98 /// The fixed number of elements the sequence can hold, or `None` if it grows on demand.
99 fn capacity(&self) -> Option<usize>;
100
101 /// Makes room for `extra` more elements, so that the next `extra` insertions cannot fail.
102 ///
103 /// # Errors
104 ///
105 /// [`Error::OutOfMemory`] if the heap cannot provide the room,
106 /// [`Error::CapacityExceeded`] naming `container` if a fixed capacity is too small. The
107 /// sequence is unchanged on error.
108 fn try_reserve(&mut self, extra: usize, container: Container) -> Result<(), Error>;
109
110 /// Appends `item`.
111 ///
112 /// # Errors
113 ///
114 /// As for [`try_reserve`](Self::try_reserve) with one extra element.
115 fn try_push(&mut self, item: T, container: Container) -> Result<(), Error>;
116
117 /// Inserts `item` at `index`, shifting later elements up.
118 ///
119 /// # Errors
120 ///
121 /// As for [`try_reserve`](Self::try_reserve) with one extra element.
122 ///
123 /// # Panics
124 ///
125 /// If `index > len`.
126 fn try_insert(&mut self, index: usize, item: T, container: Container) -> Result<(), Error>;
127
128 /// Removes and returns the element at `index`, shifting later elements down.
129 ///
130 /// # Panics
131 ///
132 /// If `index >= len`.
133 fn remove(&mut self, index: usize) -> T;
134
135 /// Removes and returns the last element, if any.
136 fn pop(&mut self) -> Option<T>;
137
138 /// Keeps the elements for which `keep` returns `true`, in order. Visits each element once,
139 /// in order.
140 fn retain(&mut self, keep: impl FnMut(&T) -> bool);
141
142 /// Shortens the sequence to `len` elements; does nothing if it is not longer.
143 fn truncate(&mut self, len: usize);
144
145 /// Removes every element.
146 fn clear(&mut self) {
147 self.truncate(0);
148 }
149
150 /// Removes consecutive repeated elements, as `Vec::dedup` does.
151 fn dedup(&mut self)
152 where
153 T: Copy,
154 {
155 let mut previous: Option<T> = None;
156 self.retain(|&item| {
157 let keep = previous != Some(item);
158 previous = Some(item);
159 keep
160 });
161 }
162
163 /// Appends every element of `items`.
164 ///
165 /// # Errors
166 ///
167 /// As for [`try_reserve`](Self::try_reserve) with `items.len()` extra elements. Nothing is
168 /// appended on error.
169 fn try_extend_from_slice(&mut self, items: &[T], container: Container) -> Result<(), Error> {
170 self.try_reserve(items.len(), container)?;
171 for item in items {
172 self.try_push(item.clone(), container)?;
173 }
174
175 Ok(())
176 }
177}
178
179/// How a timeline or state timeline stores its impacts, change points and explanations.
180///
181/// Implemented by [`Heap`] and [`Fixed<N>`]. The trait is sealed.
182pub trait Storage: Clone + Copy + Debug + Default + Eq + Hash + sealed::Sealed {
183 /// A sequence sized like the impact list: impacts, sets, requirements, contributors.
184 type List<T: Slot>: Seq<T>;
185 /// A sequence sized like twice the impact list: change points.
186 type DoubleList<T: Slot>: Seq<T>;
187}
188
189/// How a [`Plan`](crate::Plan) stores its timelines.
190///
191/// Implemented by [`Heap`] and [`FixedPlan<T, S, N>`]. The trait is sealed.
192pub trait PlanStorage: Clone + Copy + Debug + Default + Eq + Hash + sealed::Sealed {
193 /// The storage of every timeline in the plan.
194 type Line: Storage;
195 /// The numeric timelines.
196 type Timelines: Seq<Timeline<Self::Line>>;
197 /// The state timelines.
198 type States: Seq<StateTimeline<Self::Line>>;
199}
200
201/// Heap storage: every container is a `Vec` that grows on demand.
202///
203/// Growth is fallible: allocation failure is reported as [`Error::OutOfMemory`], never as an
204/// abort. This is the default storage of every type in the crate. It implements [`Storage`]
205/// and [`PlanStorage`] only with the `alloc` feature; without it the marker exists but cannot
206/// be used.
207#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
208pub struct Heap;
209
210/// Fixed-capacity storage for `N` impacts per timeline, without any allocation.
211///
212/// Containers are inline arrays: `N` impacts, sets, requirements, targets and contributors,
213/// `2 N` change points. Exceeding a capacity is reported as [`Error::CapacityExceeded`] and
214/// leaves the timeline unchanged. A `Timeline<Fixed<N>>` occupies `144 N + 96` bytes on
215/// 64-bit targets (32 per impact, 96 for its two change points, 16 per target) and a
216/// `StateTimeline<Fixed<N>>` `72 N + 48`, so large `N` belong in a `static` or on a dedicated
217/// stack. A plan search keeps two change-point and two state scratch lists of the same
218/// capacities on the stack.
219#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
220pub struct Fixed<const N: usize>;
221
222/// Fixed-capacity plan storage: at most `TIMELINES` numeric and `STATES` state timelines, each
223/// with [`Fixed<N>`] storage.
224#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
225pub struct FixedPlan<const TIMELINES: usize, const STATES: usize, const N: usize>;
226
227impl sealed::Sealed for Heap {}
228
229#[cfg(feature = "alloc")]
230impl Storage for Heap {
231 type List<T: Slot> = alloc::vec::Vec<T>;
232 type DoubleList<T: Slot> = alloc::vec::Vec<T>;
233}
234
235#[cfg(feature = "alloc")]
236impl PlanStorage for Heap {
237 type Line = Self;
238 type Timelines = alloc::vec::Vec<Timeline<Self>>;
239 type States = alloc::vec::Vec<StateTimeline<Self>>;
240}
241
242impl<const N: usize> sealed::Sealed for Fixed<N> {}
243
244impl<const N: usize> Storage for Fixed<N> {
245 type List<T: Slot> = Inline<T, [T; N]>;
246 type DoubleList<T: Slot> = Inline<T, [[T; 2]; N]>;
247}
248
249impl<const T: usize, const S: usize, const N: usize> sealed::Sealed for FixedPlan<T, S, N> {}
250
251impl<const T: usize, const S: usize, const N: usize> PlanStorage for FixedPlan<T, S, N> {
252 type Line = Fixed<N>;
253 type Timelines = Inline<Timeline<Fixed<N>>, [Timeline<Fixed<N>>; T]>;
254 type States = Inline<StateTimeline<Fixed<N>>, [StateTimeline<Fixed<N>>; S]>;
255}
256
257#[cfg(feature = "alloc")]
258impl<T> sealed::Sealed for alloc::vec::Vec<T> {}
259
260#[cfg(feature = "alloc")]
261impl<T: Slot> Seq<T> for alloc::vec::Vec<T> {
262 const EMPTY: Self = Self::new();
263
264 fn capacity(&self) -> Option<usize> {
265 None
266 }
267
268 fn try_reserve(&mut self, extra: usize, _container: Container) -> Result<(), Error> {
269 Self::try_reserve(self, extra).map_err(|_| Error::OutOfMemory)
270 }
271
272 fn try_push(&mut self, item: T, container: Container) -> Result<(), Error> {
273 Seq::try_reserve(self, 1, container)?;
274 self.push(item);
275 Ok(())
276 }
277
278 fn try_insert(&mut self, index: usize, item: T, container: Container) -> Result<(), Error> {
279 Seq::try_reserve(self, 1, container)?;
280 self.insert(index, item);
281 Ok(())
282 }
283
284 fn remove(&mut self, index: usize) -> T {
285 Self::remove(self, index)
286 }
287
288 fn pop(&mut self) -> Option<T> {
289 Self::pop(self)
290 }
291
292 fn retain(&mut self, keep: impl FnMut(&T) -> bool) {
293 Self::retain(self, keep);
294 }
295
296 fn truncate(&mut self, len: usize) {
297 Self::truncate(self, len);
298 }
299}
300
301/// Implements [`Slot`] for `Copy` element types with the given filler value.
302macro_rules! slots {
303 ($($ty:ty => $empty:expr),* $(,)?) => {
304 $(
305 impl sealed::Sealed for $ty {}
306
307 impl Slot for $ty {
308 const EMPTY: Self = $empty;
309 }
310 )*
311 };
312}
313
314slots! {
315 crate::ActivityId => crate::ActivityId(0),
316 i64 => 0,
317 (crate::ActivityId, crate::Impact) => (crate::ActivityId(0), crate::Impact::Step { at: 0, delta: 0 }),
318 (crate::ActivityId, crate::StateImpact) => (crate::ActivityId(0), crate::StateImpact::Set { at: 0, value: 0 }),
319 (crate::ActivityId, i128) => (crate::ActivityId(0), 0),
320}
321
322pub(crate) use sealed::Sealed;