Skip to main content

resource_timeline/
impact.rs

1//! Effects of an activity on a single resource timeline.
2
3use crate::{Level, Tick};
4
5/// One effect of an activity on the level of a resource.
6///
7/// The level at tick `t` is the timeline's initial level plus the contribution of every
8/// impact at `t`:
9///
10/// ```text
11/// Step  { at, delta }              contributes  delta                          if at <= t
12/// Claim { start, end, amount }     contributes  -amount                        if start <= t < end
13/// Rate  { start, end, per_tick }   contributes  per_tick * (min(t, end) - start) if start <= t
14/// ```
15///
16/// Steps and rates are permanent (consumption and production persist), claims are returned at
17/// their end.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20pub enum Impact {
21    /// A permanent change of the level, as for a consumable resource.
22    ///
23    /// Consumption (energy drawn, storage filled) is a negative `delta`, production (charging,
24    /// downlinked data freed) a positive one.
25    Step {
26        /// The tick at which the change takes effect. Not before the timeline start.
27        at: Tick,
28        /// The change of the level from `at` onward. May be zero or negative.
29        delta: Level,
30    },
31    /// A temporary hold on a resource during the half-open interval `[start, end)`.
32    ///
33    /// The level is the amount *available*, so a claim lowers it by `amount` while it holds and
34    /// returns it at `end`. A claim ending at `t` and another starting at `t` do not overlap.
35    Claim {
36        /// The first tick of the hold. Not before the timeline start.
37        start: Tick,
38        /// The first tick after the hold. Strictly greater than `start`.
39        end: Tick,
40        /// The number of units held. Strictly positive.
41        amount: Level,
42    },
43    /// A linear change of the level by `per_tick` for every tick elapsed in `[start, end)`.
44    ///
45    /// Models a battery discharging under a power draw (negative), solar charging or thermal
46    /// drift (either sign). The level at `start` is unchanged, at `start + k` it has changed by
47    /// `k * per_tick`, and from `end` onward the total `(end - start) * per_tick` persists.
48    /// Fractional rates are expressed by choosing a finer level unit. The level is never
49    /// clamped (a full battery does not stop charging): exceeding the capacity is reported as a
50    /// violation instead.
51    Rate {
52        /// The first tick of the change. Not before the timeline start.
53        start: Tick,
54        /// The tick at which the change stops. Strictly greater than `start`.
55        end: Tick,
56        /// The change of the level per elapsed tick. May be zero or negative.
57        per_tick: Level,
58    },
59}
60
61impl Impact {
62    /// The earliest tick at which this impact changes the level.
63    #[must_use]
64    pub const fn first_tick(&self) -> Tick {
65        match *self {
66            Self::Step { at, .. } => at,
67            Self::Claim { start, .. } | Self::Rate { start, .. } => start,
68        }
69    }
70
71    /// The last tick at which this impact changes the level or its slope.
72    ///
73    /// From this tick onward the contribution of the impact is constant.
74    #[must_use]
75    pub const fn last_tick(&self) -> Tick {
76        match *self {
77            Self::Step { at, .. } => at,
78            Self::Claim { end, .. } | Self::Rate { end, .. } => end,
79        }
80    }
81
82    /// Whether the impact changes the level linearly rather than in steps.
83    #[must_use]
84    pub const fn is_rate(&self) -> bool {
85        matches!(self, Self::Rate { .. })
86    }
87
88    /// The same impact moved `by` ticks later (earlier for negative `by`).
89    ///
90    /// Returns `None` if a moved tick does not fit a [`Tick`].
91    #[must_use]
92    pub const fn shifted(&self, by: Tick) -> Option<Self> {
93        match *self {
94            Self::Step { at, delta } => match at.checked_add(by) {
95                Some(at) => Some(Self::Step { at, delta }),
96                None => None,
97            },
98            Self::Claim { start, end, amount } => {
99                match (start.checked_add(by), end.checked_add(by)) {
100                    (Some(start), Some(end)) => Some(Self::Claim { start, end, amount }),
101                    _ => None,
102                }
103            }
104            Self::Rate {
105                start,
106                end,
107                per_tick,
108            } => match (start.checked_add(by), end.checked_add(by)) {
109                (Some(start), Some(end)) => Some(Self::Rate {
110                    start,
111                    end,
112                    per_tick,
113                }),
114                _ => None,
115            },
116        }
117    }
118
119    /// The contribution of this impact to the level at tick `t`, widened to avoid overflow.
120    ///
121    /// Returns `None` only if a rate contribution exceeds `i128`, which needs a rate and a
122    /// duration both close to the `i64` limits.
123    #[must_use]
124    pub(crate) fn contribution_at(&self, t: Tick) -> Option<i128> {
125        match *self {
126            Self::Step { at, delta } if at <= t => Some(i128::from(delta)),
127            Self::Claim { start, end, amount } if start <= t && t < end => {
128                Some(-i128::from(amount))
129            }
130            Self::Rate {
131                start,
132                end,
133                per_tick,
134            } if start <= t => {
135                let elapsed = i128::from(t.min(end)) - i128::from(start);
136                i128::from(per_tick).checked_mul(elapsed)
137            }
138            Self::Step { .. } | Self::Claim { .. } | Self::Rate { .. } => Some(0),
139        }
140    }
141
142    /// The changes of level and slope this impact causes, as `(tick, step, slope)` triples.
143    ///
144    /// A step yields one change, a claim or rate two (at its start and its end). Unused entries
145    /// are `None`.
146    pub(crate) fn changes(&self) -> [Option<(Tick, i128, i128)>; 2] {
147        match *self {
148            Self::Step { at, delta } => [Some((at, i128::from(delta), 0)), None],
149            Self::Claim { start, end, amount } => [
150                Some((start, -i128::from(amount), 0)),
151                Some((end, i128::from(amount), 0)),
152            ],
153            Self::Rate {
154                start,
155                end,
156                per_tick,
157            } => [
158                Some((start, 0, i128::from(per_tick))),
159                Some((end, 0, -i128::from(per_tick))),
160            ],
161        }
162    }
163}