resource_timeline/state.rs
1//! State timelines: discrete values such as modes, switch positions or visibility windows.
2//!
3//! A numeric [`Timeline`](crate::Timeline) checks that a level stays in a range. A
4//! [`StateTimeline`] checks that a discrete value *equals* what activities require: the
5//! spectrometer must be warm while it analyzes, the antenna must see Earth while it transmits.
6//! Activities change the value with [`StateImpact::Set`] and demand it with
7//! [`StateImpact::Require`].
8//!
9//! Visibility windows (comm passes, daylight) are a state timeline whose value is set by a
10//! ground-provided activity at each window start and end:
11//!
12//! ```
13//! use resource_timeline::{ActivityId, StateImpact, StateTimeline, StateViolation};
14//!
15//! const HIDDEN: u32 = 0;
16//! const VISIBLE: u32 = 1;
17//! let passes = ActivityId(0);
18//! let downlink = ActivityId(7);
19//!
20//! let mut earth = StateTimeline::new(0, HIDDEN, 16);
21//! earth.add(passes, StateImpact::Set { at: 100, value: VISIBLE })?;
22//! earth.add(passes, StateImpact::Set { at: 160, value: HIDDEN })?;
23//! earth.add(downlink, StateImpact::Require { start: 150, end: 170, value: VISIBLE })?;
24//!
25//! let violation = earth.first_violation()?.expect("the pass ends too early");
26//! assert_eq!(
27//! violation,
28//! StateViolation::Mismatch {
29//! at: 160,
30//! required: VISIBLE,
31//! actual: HIDDEN,
32//! requirer: downlink,
33//! setter: Some(passes),
34//! }
35//! );
36//! # Ok::<(), resource_timeline::Error>(())
37//! ```
38
39mod check;
40
41#[cfg(feature = "alloc")]
42use crate::storage::Heap;
43use crate::storage::{Seq, Slot, Storage};
44use crate::{ActivityId, Container, Error, Tick};
45pub(crate) use check::SetPoint;
46use check::Sets;
47
48/// A discrete state value. The meaning of each value is chosen by the mission.
49pub type StateValue = u32;
50
51/// One effect of an activity on a state timeline.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
54pub enum StateImpact {
55 /// The state becomes `value` at tick `at` and keeps it until the next set.
56 Set {
57 /// The tick of the change. Not before the timeline start.
58 at: Tick,
59 /// The new state value.
60 value: StateValue,
61 },
62 /// The state must equal `value` at every tick of the half-open interval `[start, end)`.
63 Require {
64 /// The first tick of the requirement. Not before the timeline start.
65 start: Tick,
66 /// The first tick after the requirement. Strictly greater than `start`.
67 end: Tick,
68 /// The required state value.
69 value: StateValue,
70 },
71}
72
73impl StateImpact {
74 /// The earliest tick the impact refers to.
75 #[must_use]
76 pub const fn first_tick(&self) -> Tick {
77 match *self {
78 Self::Set { at, .. } => at,
79 Self::Require { start, .. } => start,
80 }
81 }
82
83 /// The same impact moved `by` ticks later (earlier for negative `by`).
84 ///
85 /// Returns `None` if a moved tick does not fit a [`Tick`].
86 #[must_use]
87 pub const fn shifted(&self, by: Tick) -> Option<Self> {
88 match *self {
89 Self::Set { at, value } => match at.checked_add(by) {
90 Some(at) => Some(Self::Set { at, value }),
91 None => None,
92 },
93 Self::Require { start, end, value } => {
94 match (start.checked_add(by), end.checked_add(by)) {
95 (Some(start), Some(end)) => Some(Self::Require { start, end, value }),
96 _ => None,
97 }
98 }
99 }
100 }
101}
102
103/// The first tick at which a state timeline is inconsistent, and why.
104///
105/// The setter list of a conflict uses the storage `S` of the timeline that reported it.
106#[derive(Debug, Clone, PartialEq, Eq, Hash)]
107pub enum StateViolation<
108 #[cfg(feature = "alloc")] S: Storage = Heap,
109 #[cfg(not(feature = "alloc"))] S: Storage,
110> {
111 /// A requirement sees a different value.
112 Mismatch {
113 /// The earliest tick at which the requirement fails.
114 at: Tick,
115 /// The value the requirement needs.
116 required: StateValue,
117 /// The value the state has at `at`.
118 actual: StateValue,
119 /// The activity that holds the requirement. The smallest id if several fail at `at`;
120 /// for several failing requirements of that activity, `required` is the smallest value.
121 requirer: ActivityId,
122 /// The activity whose set established `actual`, or `None` for the initial value.
123 /// The smallest id if several set the same value at the same tick.
124 setter: Option<ActivityId>,
125 },
126 /// Activities set different values at the same tick, so the state there is ambiguous.
127 ///
128 /// Reported whether or not a requirement depends on the value, because two commands that
129 /// contradict each other at the same tick are a scheduling conflict in themselves.
130 Conflict {
131 /// The tick of the contradicting sets.
132 at: Tick,
133 /// Every activity that sets a value at `at`. Sorted ascending, without duplicates.
134 setters: S::List<ActivityId>,
135 },
136}
137
138impl<S: Storage> StateViolation<S> {
139 /// The tick of the violation.
140 #[must_use]
141 pub const fn at(&self) -> Tick {
142 match *self {
143 Self::Mismatch { at, .. } | Self::Conflict { at, .. } => at,
144 }
145 }
146}
147
148/// A requirement stored by a state timeline.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150pub(crate) struct Requirement {
151 /// The activity that holds the requirement.
152 pub(crate) activity: ActivityId,
153 /// The first required tick.
154 pub(crate) start: Tick,
155 /// The first tick after the requirement.
156 pub(crate) end: Tick,
157 /// The required value.
158 pub(crate) value: StateValue,
159}
160
161impl crate::storage::Sealed for Requirement {}
162
163impl Slot for Requirement {
164 const EMPTY: Self = Self {
165 activity: ActivityId(0),
166 start: 0,
167 end: 0,
168 value: 0,
169 };
170}
171
172/// A discrete state over time, built from activity sets and checked against requirements.
173///
174/// The state equals the initial value from the start tick until the first set, and the value of
175/// the latest set afterwards. Sets are kept sorted by tick, so a check costs
176/// `O(n + r log n)` for `n` sets and `r` requirements and does not allocate unless it reports a
177/// [`StateViolation::Conflict`].
178///
179/// The storage `S` is [`storage::Heap`](crate::storage::Heap) by default; with
180/// [`Fixed<N>`](crate::storage::Fixed) the timeline holds at most `N` impacts and never
181/// allocates. Heap timelines are created with [`new`], timelines with any storage
182/// with [`new_in`](Self::new_in).
183///
184#[cfg_attr(feature = "alloc", doc = "[`new`]: Self::new")]
185#[cfg_attr(not(feature = "alloc"), doc = "[`new`]: crate#features")]
186#[derive(Debug, Clone, PartialEq, Eq, Hash)]
187pub struct StateTimeline<
188 #[cfg(feature = "alloc")] S: Storage = Heap,
189 #[cfg(not(feature = "alloc"))] S: Storage,
190> {
191 /// The first tick of the timeline. No impact may refer to an earlier tick.
192 start: Tick,
193 /// The value from the start until the first set.
194 initial: StateValue,
195 /// The maximum number of impacts the timeline accepts.
196 budget: usize,
197 /// The impacts in insertion order. Never longer than `budget`.
198 impacts: S::List<(ActivityId, StateImpact)>,
199 /// The sets, sorted by tick and then by activity.
200 sets: S::List<SetPoint>,
201 /// The requirements in insertion order.
202 requires: S::List<Requirement>,
203}
204
205#[cfg(feature = "alloc")]
206impl StateTimeline {
207 /// Creates a heap state timeline that holds `initial` from `start` on, with room for
208 /// `budget` impacts.
209 #[must_use]
210 pub const fn new(start: Tick, initial: StateValue, budget: usize) -> Self {
211 Self::new_in(start, initial, budget)
212 }
213}
214
215impl<S: Storage> StateTimeline<S> {
216 /// Creates a state timeline with storage `S` that holds `initial` from `start` on, with
217 /// room for `budget` impacts.
218 ///
219 /// As [`StateTimeline::new`], for any [`Storage`]. With
220 /// [`Fixed<N>`](crate::storage::Fixed), adds beyond `N` impacts fail with
221 /// [`Error::CapacityExceeded`] even if the budget is larger.
222 ///
223 #[cfg_attr(feature = "alloc", doc = "[`StateTimeline::new`]: StateTimeline::new")]
224 #[cfg_attr(not(feature = "alloc"), doc = "[`StateTimeline::new`]: crate#features")]
225 #[must_use]
226 pub const fn new_in(start: Tick, initial: StateValue, budget: usize) -> Self {
227 Self {
228 start,
229 initial,
230 budget,
231 impacts: <S::List<(ActivityId, StateImpact)> as Seq<_>>::EMPTY,
232 sets: <S::List<SetPoint> as Seq<_>>::EMPTY,
233 requires: <S::List<Requirement> as Seq<_>>::EMPTY,
234 }
235 }
236
237 /// The first tick of the timeline.
238 #[must_use]
239 pub const fn start(&self) -> Tick {
240 self.start
241 }
242
243 /// The value from the start until the first set.
244 #[must_use]
245 pub const fn initial(&self) -> StateValue {
246 self.initial
247 }
248
249 /// The maximum number of impacts the timeline accepts.
250 #[must_use]
251 pub const fn budget(&self) -> usize {
252 self.budget
253 }
254
255 /// The impacts added so far, in insertion order.
256 #[must_use]
257 pub fn impacts(&self) -> &[(ActivityId, StateImpact)] {
258 &self.impacts
259 }
260
261 /// Adds an impact of `activity`.
262 ///
263 /// # Errors
264 ///
265 /// - [`Error::BeforeStart`] if the impact refers to a tick before the start.
266 /// - [`Error::EmptyInterval`] if a requirement has `end <= start`.
267 /// - [`Error::BudgetExhausted`] if the timeline already holds `budget` impacts.
268 /// - [`Error::OutOfMemory`] if the impact lists cannot grow (heap storage).
269 /// - [`Error::CapacityExceeded`] if a fixed impact list is full.
270 ///
271 /// The timeline is unchanged on error.
272 pub fn add(&mut self, activity: ActivityId, impact: StateImpact) -> Result<(), Error> {
273 self.validate(impact)?;
274 self.ensure_room(1)?;
275 self.impacts.try_reserve(1, Container::Impacts)?;
276 match impact {
277 StateImpact::Set { at, value } => {
278 let point = SetPoint {
279 at,
280 activity,
281 value,
282 };
283 let index = self.sets.partition_point(|set| set.key() <= point.key());
284 self.sets.try_insert(index, point, Container::Sets)?;
285 }
286 StateImpact::Require { start, end, value } => {
287 let requirement = Requirement {
288 activity,
289 start,
290 end,
291 value,
292 };
293 self.requires
294 .try_push(requirement, Container::Requirements)?;
295 }
296 }
297
298 self.impacts
299 .try_push((activity, impact), Container::Impacts)
300 }
301
302 /// Removes every impact of `activity` and returns how many there were. Never allocates.
303 pub fn remove(&mut self, activity: ActivityId) -> usize {
304 let before = self.impacts.len();
305 self.impacts.retain(|&(owner, _)| owner != activity);
306 self.sets.retain(|set| set.activity != activity);
307 self.requires.retain(|require| require.activity != activity);
308 before - self.impacts.len()
309 }
310
311 /// Removes the most recently added impact, if any. Never allocates.
312 pub(crate) fn undo_last(&mut self) {
313 match self.impacts.pop() {
314 Some((activity, StateImpact::Set { at, value })) => {
315 let added = SetPoint {
316 at,
317 activity,
318 value,
319 };
320 if let Some(index) = self.sets.iter().rposition(|set| *set == added) {
321 self.sets.remove(index);
322 }
323 }
324 Some((_, StateImpact::Require { .. })) => {
325 self.requires.pop();
326 }
327 None => {}
328 }
329 }
330
331 /// The first tick `>= x` at which the outcome of a check can change: the start, a set, or
332 /// a requirement start or end.
333 ///
334 /// Costs `O(log n)` for the sorted sets plus `O(r)` for `r` requirements.
335 pub(crate) fn first_change_from(&self, x: i128) -> Option<Tick> {
336 let set = self
337 .sets
338 .get(self.sets.partition_point(|set| i128::from(set.at) < x))
339 .map(|set| set.at);
340 let requires = self
341 .requires
342 .iter()
343 .flat_map(|require| [require.start, require.end])
344 .filter(|&tick| i128::from(tick) >= x);
345 let start = (i128::from(self.start) >= x).then_some(self.start);
346 start.into_iter().chain(set).chain(requires).min()
347 }
348
349 /// `Ok` while the timeline has room for `extra` more impacts, by budget and by capacity.
350 ///
351 /// Sets and requirements are never more than impacts, so the impact capacity covers them.
352 ///
353 /// # Errors
354 ///
355 /// - [`Error::BudgetExhausted`] if `extra` more impacts would exceed the budget.
356 /// - [`Error::CapacityExceeded`] if they would exceed a fixed impact capacity.
357 pub(crate) fn ensure_room(&self, extra: usize) -> Result<(), Error> {
358 let needed = self.impacts.len().saturating_add(extra);
359 if needed > self.budget {
360 return Err(Error::BudgetExhausted { limit: self.budget });
361 }
362
363 match self.impacts.capacity() {
364 Some(capacity) if needed > capacity => Err(Error::CapacityExceeded {
365 container: Container::Impacts,
366 capacity,
367 }),
368 _ => Ok(()),
369 }
370 }
371
372 /// Checks that `impact` is well formed and does not precede the start.
373 ///
374 /// # Errors
375 ///
376 /// The validation errors listed on [`add`](Self::add).
377 pub(crate) const fn validate(&self, impact: StateImpact) -> Result<(), Error> {
378 if let StateImpact::Require { start, end, .. } = impact {
379 if end <= start {
380 return Err(Error::EmptyInterval { start, end });
381 }
382 }
383
384 let at = impact.first_tick();
385 if at < self.start {
386 return Err(Error::BeforeStart {
387 at,
388 start: self.start,
389 });
390 }
391
392 Ok(())
393 }
394
395 /// The state value at tick `t`, or `None` if contradicting sets make it ambiguous there.
396 ///
397 /// # Errors
398 ///
399 /// [`Error::BeforeStart`] if `t` precedes the start.
400 pub fn value_at(&self, t: Tick) -> Result<Option<StateValue>, Error> {
401 if t < self.start {
402 return Err(Error::BeforeStart {
403 at: t,
404 start: self.start,
405 });
406 }
407
408 Ok(self.view(&[]).value_at(t, self.initial))
409 }
410
411 /// The value changes over time for display and telemetry: `(tick, value)` pairs in time
412 /// order, starting with the initial value at the start tick.
413 ///
414 /// A tick appears only if the value there differs from the one before; `None` marks a tick
415 /// where contradicting sets make the value ambiguous. Costs `O(n log n)` and never
416 /// allocates.
417 ///
418 /// # Examples
419 ///
420 /// ```
421 /// use resource_timeline::{ActivityId, StateImpact, StateTimeline};
422 ///
423 /// let mut mode = StateTimeline::new(0, 0, 8);
424 /// mode.add(ActivityId(1), StateImpact::Set { at: 5, value: 1 })?;
425 /// mode.add(ActivityId(2), StateImpact::Set { at: 9, value: 1 })?;
426 /// mode.add(ActivityId(3), StateImpact::Set { at: 12, value: 0 })?;
427 ///
428 /// let changes: Vec<_> = mode.values().collect();
429 /// assert_eq!(changes, [(0, Some(0)), (5, Some(1)), (12, Some(0))]);
430 /// # Ok::<(), resource_timeline::Error>(())
431 /// ```
432 pub fn values(&self) -> impl Iterator<Item = (Tick, Option<StateValue>)> + '_ {
433 let mut previous: Option<Option<StateValue>> = None;
434 let view = self.view(&[]);
435 let start = core::iter::once((self.start, view.value_at(self.start, self.initial)));
436 let set_ticks = self
437 .sets
438 .iter()
439 .enumerate()
440 .filter(|&(index, set)| index == 0 || self.sets[index - 1].at != set.at)
441 .map(move |(_, set)| (set.at, view.value_at(set.at, self.initial)));
442 start.chain(set_ticks).filter(move |&(_, value)| {
443 let changed = previous != Some(value);
444 previous = Some(value);
445 changed
446 })
447 }
448
449 /// Finds the earliest violation: a failed requirement or contradicting sets.
450 ///
451 /// A conflict at tick `c` wins over mismatches at `c` or later, since the state is
452 /// undefined from there on. The result does not depend on insertion order.
453 ///
454 /// # Errors
455 ///
456 /// [`Error::OutOfMemory`] if the setter list of a conflict cannot be allocated (heap
457 /// storage). Fixed storage has room for it by construction.
458 pub fn first_violation(&self) -> Result<Option<StateViolation<S>>, Error> {
459 let view = self.view(&[]);
460 match view.first_breach(self.initial, &self.requires, &[]) {
461 Some(breach) => view.explain::<S>(breach).map(Some),
462 None => Ok(None),
463 }
464 }
465
466 /// Whether the timeline would be violated if the sorted `extra_sets` and the
467 /// `extra_requires` were added. Never allocates.
468 pub(crate) fn is_violated_with(
469 &self,
470 extra_sets: &[SetPoint],
471 extra_requires: &[Requirement],
472 ) -> bool {
473 self.view(extra_sets)
474 .first_breach(self.initial, &self.requires, extra_requires)
475 .is_some()
476 }
477
478 /// The stored sets merged with `extra`, for queries.
479 fn view<'a>(&'a self, extra: &'a [SetPoint]) -> Sets<'a> {
480 Sets {
481 base: &self.sets,
482 extra,
483 }
484 }
485}
486
487impl<S: Storage> crate::storage::Sealed for StateTimeline<S> {}
488
489impl<S: Storage> Slot for StateTimeline<S> {
490 const EMPTY: Self = Self::new_in(0, 0, 0);
491}