resource_timeline/envelope/contingent.rs
1//! Activities with uncertain durations: impacts anchored at the start or at the end.
2
3use crate::{ActivityId, Error, Impact, Level, Tick, Window};
4
5/// A tick of an activity, relative to its start or to its (uncertain) end.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
7#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
8pub enum Anchor {
9 /// The given number of ticks after the start (before it for a negative offset).
10 Start(Tick),
11 /// The given number of ticks after the end, which is the start plus the duration.
12 End(Tick),
13}
14
15impl Anchor {
16 /// The tick relative to the start for an activity that lasts `duration` ticks.
17 ///
18 /// Returns `None` if the tick does not fit a [`Tick`].
19 #[must_use]
20 pub const fn resolve(self, duration: Tick) -> Option<Tick> {
21 match self {
22 Self::Start(offset) => Some(offset),
23 Self::End(offset) => duration.checked_add(offset),
24 }
25 }
26}
27
28/// One effect of an activity whose duration is uncertain.
29///
30/// The variants mirror [`Impact`], with ticks given as [`Anchor`]s. A claim from
31/// `Anchor::Start(0)` to `Anchor::End(0)` holds a resource for exactly as long as the activity
32/// runs; a rate over the same interval drains energy for as long as it runs. The interval may
33/// be empty for the shortest duration (a zero-length run), but never inverted.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
36pub enum Uncertain {
37 /// A permanent change of the level at `at`.
38 Step {
39 /// The tick of the change.
40 at: Anchor,
41 /// The change of the level from `at` onward.
42 delta: Level,
43 },
44 /// A hold of `amount` units during `[start, end)`.
45 Claim {
46 /// The first tick of the hold.
47 start: Anchor,
48 /// The first tick after the hold. Not before `start` for any duration.
49 end: Anchor,
50 /// The number of units held. Strictly positive.
51 amount: Level,
52 },
53 /// A change of `per_tick` for every tick elapsed in `[start, end)`.
54 Rate {
55 /// The first tick of the change.
56 start: Anchor,
57 /// The tick at which the change stops. Not before `start` for any duration.
58 end: Anchor,
59 /// The change of the level per elapsed tick.
60 per_tick: Level,
61 },
62}
63
64impl Uncertain {
65 /// The impact, relative to the start, for an activity that lasts `duration` ticks.
66 ///
67 /// The interval of a claim or rate may be empty. Returns `None` if a tick does not fit a
68 /// [`Tick`].
69 #[must_use]
70 pub const fn resolve(&self, duration: Tick) -> Option<Impact> {
71 match *self {
72 Self::Step { at, delta } => match at.resolve(duration) {
73 Some(at) => Some(Impact::Step { at, delta }),
74 None => None,
75 },
76 Self::Claim { start, end, amount } => {
77 match (start.resolve(duration), end.resolve(duration)) {
78 (Some(start), Some(end)) => Some(Impact::Claim { start, end, amount }),
79 _ => None,
80 }
81 }
82 Self::Rate {
83 start,
84 end,
85 per_tick,
86 } => match (start.resolve(duration), end.resolve(duration)) {
87 (Some(start), Some(end)) => Some(Impact::Rate {
88 start,
89 end,
90 per_tick,
91 }),
92 _ => None,
93 },
94 }
95 }
96
97 /// The anchors of the impact.
98 pub(super) const fn anchors(&self) -> [Anchor; 2] {
99 match *self {
100 Self::Step { at, .. } => [at, at],
101 Self::Claim { start, end, .. } | Self::Rate { start, end, .. } => [start, end],
102 }
103 }
104}
105
106/// An activity whose start lies in a window and whose duration lies in a range, as for a
107/// contingent link of a simple temporal network with uncertainty.
108///
109/// The envelope covers every combination of a start in `window` and a duration in `duration`,
110/// chosen independently per activity: the start by the dispatcher, the duration by nature. See
111/// [`Envelope::with_contingent`](super::Envelope::with_contingent) for an example.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub struct Contingent<'a> {
114 /// The activity, reported back in explanations.
115 pub activity: ActivityId,
116 /// The allowed starts.
117 pub window: Window,
118 /// The possible durations `[shortest, longest]`. Never negative.
119 pub duration: Window,
120 /// The effects of the activity, anchored at its start or end.
121 pub impacts: &'a [Uncertain],
122}
123
124/// The impact with an empty interval widened to one tick, so that the checks of
125/// [`Timeline::add`](crate::Timeline::add) that do not concern the length still apply.
126///
127/// # Errors
128///
129/// - [`Error::EmptyInterval`] if the interval is inverted.
130/// - [`Error::Overflow`] if the widened end does not fit a [`Tick`].
131pub(super) fn widened(impact: Impact) -> Result<Impact, Error> {
132 let widen = |start: Tick, end: Tick| -> Result<Tick, Error> {
133 match end.cmp(&start) {
134 core::cmp::Ordering::Less => Err(Error::EmptyInterval { start, end }),
135 core::cmp::Ordering::Equal => start.checked_add(1).ok_or(Error::Overflow),
136 core::cmp::Ordering::Greater => Ok(end),
137 }
138 };
139
140 Ok(match impact {
141 Impact::Step { .. } => impact,
142 Impact::Claim { start, end, amount } => Impact::Claim {
143 start,
144 end: widen(start, end)?,
145 amount,
146 },
147 Impact::Rate {
148 start,
149 end,
150 per_tick,
151 } => Impact::Rate {
152 start,
153 end: widen(start, end)?,
154 per_tick,
155 },
156 })
157}