Skip to main content

simulator_api/
slot_range.rs

1//! An inclusive slot range.
2//!
3//! Slot bounds travel in pairs through most of the pipeline. As two adjacent
4//! `u64` parameters nothing stops a caller transposing them, and the ordering
5//! invariant gets re-checked ad hoc (or not at all) at each layer. This carries
6//! both together and checks once, at construction.
7
8use std::fmt;
9
10use serde::{Deserialize, Serialize};
11use serde_with::{OneOrMany, formats::PreferOne, serde_as};
12
13/// An inclusive `[start, end]` slot range. Construct via [`SlotRange::new`],
14/// which rejects an inverted range, or [`SlotRange::new_unchecked`] where the
15/// ordering is already guaranteed by the caller.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
17pub struct SlotRange {
18    start: u64,
19    end: u64,
20}
21
22/// Why a pair of bounds isn't a valid range.
23#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
24#[error("invalid range: start_slot {start} > end_slot {end}")]
25pub struct InvertedSlotRange {
26    #[allow(missing_docs)]
27    pub start: u64,
28    /// The requested end slot, below `start`.
29    pub end: u64,
30}
31
32impl SlotRange {
33    /// An inclusive range, rejecting `start > end`.
34    pub fn new(start: u64, end: u64) -> Result<Self, InvertedSlotRange> {
35        if start > end {
36            return Err(InvertedSlotRange { start, end });
37        }
38        Ok(Self { start, end })
39    }
40
41    /// A range whose ordering the caller already guarantees — e.g. one derived
42    /// from a `start` plus a non-zero count. Prefer [`SlotRange::new`].
43    pub const fn new_unchecked(start: u64, end: u64) -> Self {
44        Self { start, end }
45    }
46
47    /// The range covering `count` slots from `start`. `count` of 0 yields a
48    /// single-slot range, matching how the callers' slot counts behave.
49    pub const fn from_count(start: u64, count: u64) -> Self {
50        Self {
51            start,
52            end: start.saturating_add(count.saturating_sub(1)),
53        }
54    }
55
56    #[allow(missing_docs)]
57    pub const fn start(&self) -> u64 {
58        self.start
59    }
60
61    /// The last slot, inclusive.
62    pub const fn end(&self) -> u64 {
63        self.end
64    }
65
66    /// Number of slots covered, inclusive of both bounds.
67    pub const fn len(&self) -> u64 {
68        self.end - self.start + 1
69    }
70
71    /// Never true — an inclusive range always covers at least one slot. Present
72    /// so `len()` doesn't trip `clippy::len_without_is_empty`.
73    pub const fn is_empty(&self) -> bool {
74        false
75    }
76
77    #[allow(missing_docs)]
78    pub const fn contains(&self, slot: u64) -> bool {
79        slot >= self.start && slot <= self.end
80    }
81
82    /// Whether the two ranges share at least one slot.
83    pub const fn overlaps(&self, other: SlotRange) -> bool {
84        self.start <= other.end && other.start <= self.end
85    }
86
87    /// Whether `other` lies wholly within this range.
88    pub const fn covers(&self, other: SlotRange) -> bool {
89        self.start <= other.start && other.end <= self.end
90    }
91
92    /// The slots both ranges share.
93    pub fn intersection(self, other: SlotRange) -> Option<SlotRange> {
94        self.overlaps(other).then(|| Self {
95            start: self.start.max(other.start),
96            end: self.end.min(other.end),
97        })
98    }
99}
100
101impl fmt::Display for SlotRange {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        write!(f, "{}..={}", self.start, self.end)
104    }
105}
106
107impl From<SlotRange> for std::ops::RangeInclusive<u64> {
108    fn from(range: SlotRange) -> Self {
109        range.start..=range.end
110    }
111}
112
113/// The slots an action may fire at: one [`SlotRange`] object or a list of them.
114#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
115#[serde(try_from = "SlotWindowsWire", into = "SlotWindowsWire")]
116pub struct SlotWindows(Vec<SlotRange>);
117
118#[serde_as]
119#[derive(Serialize, Deserialize)]
120#[serde(transparent)]
121struct SlotWindowsWire(#[serde_as(as = "OneOrMany<_, PreferOne>")] Vec<SlotRange>);
122
123/// Slot windows were built from no range.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
125#[error("slot windows name no range")]
126pub struct NoSlotWindows;
127
128/// Why a set of ranges from the wire isn't valid slot windows.
129#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
130pub enum InvalidSlotWindows {
131    #[error(transparent)]
132    #[allow(missing_docs)]
133    Empty(#[from] NoSlotWindows),
134    #[error(transparent)]
135    #[allow(missing_docs)]
136    Inverted(#[from] InvertedSlotRange),
137}
138
139impl SlotWindows {
140    /// Sorts the ranges and merges those that overlap or touch.
141    pub fn new(ranges: impl IntoIterator<Item = SlotRange>) -> Result<Self, NoSlotWindows> {
142        let ranges = ranges.into_iter().collect::<Vec<_>>();
143        if ranges.is_empty() {
144            return Err(NoSlotWindows);
145        }
146        Ok(Self(merged(ranges)))
147    }
148
149    fn window_of(&self, slot: u64) -> Option<SlotRange> {
150        let at = self.0.partition_point(|range| range.end < slot);
151        self.0.get(at).copied().filter(|range| range.contains(slot))
152    }
153
154    #[allow(missing_docs)]
155    pub fn contains(&self, slot: u64) -> bool {
156        self.window_of(slot).is_some()
157    }
158
159    /// Whether a single window holds every slot of `range`.
160    pub fn covers(&self, range: SlotRange) -> bool {
161        self.window_of(range.start)
162            .is_some_and(|window| window.covers(range))
163    }
164
165    /// The parts of these windows inside `range`, or `None` when they share no slot.
166    pub fn intersection(&self, range: SlotRange) -> Option<Self> {
167        Self::new(
168            self.0
169                .iter()
170                .filter_map(|window| window.intersection(range)),
171        )
172        .ok()
173    }
174}
175
176fn merged(mut ranges: Vec<SlotRange>) -> Vec<SlotRange> {
177    ranges.sort();
178    ranges
179        .into_iter()
180        .fold(Vec::new(), |mut merged: Vec<SlotRange>, next| {
181            match merged.last_mut() {
182                Some(last) if next.start <= last.end.saturating_add(1) => {
183                    last.end = last.end.max(next.end);
184                }
185                _ => merged.push(next),
186            }
187            merged
188        })
189}
190
191impl From<SlotRange> for SlotWindows {
192    fn from(range: SlotRange) -> Self {
193        Self(vec![range])
194    }
195}
196
197impl TryFrom<SlotWindowsWire> for SlotWindows {
198    type Error = InvalidSlotWindows;
199
200    fn try_from(SlotWindowsWire(ranges): SlotWindowsWire) -> Result<Self, Self::Error> {
201        let ranges = ranges
202            .into_iter()
203            .map(|range| SlotRange::new(range.start, range.end))
204            .collect::<Result<Vec<_>, _>>()?;
205        Ok(Self::new(ranges)?)
206    }
207}
208
209impl From<SlotWindows> for SlotWindowsWire {
210    fn from(SlotWindows(ranges): SlotWindows) -> Self {
211        Self(ranges)
212    }
213}
214
215pub(crate) mod slot_bounds {
216    use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};
217
218    use super::SlotRange;
219
220    #[derive(Serialize, Deserialize)]
221    struct SlotBounds {
222        start_slot: u64,
223        end_slot: u64,
224    }
225
226    pub(crate) fn serialize<S: Serializer>(
227        slots: &SlotRange,
228        serializer: S,
229    ) -> Result<S::Ok, S::Error> {
230        SlotBounds {
231            start_slot: slots.start,
232            end_slot: slots.end,
233        }
234        .serialize(serializer)
235    }
236
237    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
238        deserializer: D,
239    ) -> Result<SlotRange, D::Error> {
240        let SlotBounds {
241            start_slot,
242            end_slot,
243        } = SlotBounds::deserialize(deserializer)?;
244        SlotRange::new(start_slot, end_slot).map_err(D::Error::custom)
245    }
246}
247
248#[cfg(test)]
249mod tests {
250    use rstest::rstest;
251
252    use super::*;
253
254    fn windows(ranges: &[(u64, u64)]) -> SlotWindows {
255        SlotWindows::new(
256            ranges
257                .iter()
258                .map(|&(start, end)| SlotRange::new_unchecked(start, end)),
259        )
260        .expect("windows")
261    }
262
263    #[test]
264    fn one_window_writes_as_a_slot_range_and_several_as_a_list() {
265        let one = windows(&[(5, 9)]);
266        assert_eq!(
267            serde_json::to_value(&one).unwrap(),
268            serde_json::to_value(SlotRange::new_unchecked(5, 9)).unwrap()
269        );
270        let two = windows(&[(5, 9), (20, 30)]);
271        let json = serde_json::to_value(&two).unwrap();
272        assert!(json.is_array(), "{json}");
273        for windows in [one, two] {
274            let json = serde_json::to_string(&windows).unwrap();
275            assert_eq!(serde_json::from_str::<SlotWindows>(&json).unwrap(), windows);
276        }
277        let listed = r#"[{"start":5,"end":9}]"#;
278        assert_eq!(
279            serde_json::from_str::<SlotWindows>(listed).unwrap(),
280            windows(&[(5, 9)])
281        );
282    }
283
284    #[rstest]
285    #[case::empty_list("[]")]
286    #[case::inverted_object(r#"{"start":10,"end":9}"#)]
287    #[case::inverted_in_a_list(r#"[{"start":1,"end":2},{"start":10,"end":9}]"#)]
288    fn windows_that_name_no_valid_range_are_rejected(#[case] json: &str) {
289        assert!(serde_json::from_str::<SlotWindows>(json).is_err());
290    }
291
292    #[rstest]
293    #[case::unsorted(&[(20, 30), (5, 9)], &[(5, 9), (20, 30)])]
294    #[case::touching(&[(5, 9), (10, 12)], &[(5, 12)])]
295    #[case::overlapping(&[(5, 15), (10, 12), (14, 20)], &[(5, 20)])]
296    #[case::apart(&[(5, 9), (11, 12)], &[(5, 9), (11, 12)])]
297    fn new_sorts_and_merges_ranges(#[case] given: &[(u64, u64)], #[case] kept: &[(u64, u64)]) {
298        assert_eq!(windows(given), windows(kept));
299    }
300
301    #[test]
302    fn no_ranges_make_no_windows() {
303        assert_eq!(SlotWindows::new([]), Err(NoSlotWindows));
304    }
305
306    #[rstest]
307    #[case::first_start(5, true)]
308    #[case::first_end(9, true)]
309    #[case::between(10, false)]
310    #[case::second_start(20, true)]
311    #[case::past_all(31, false)]
312    #[case::before_all(4, false)]
313    fn contains_finds_a_slot_in_any_window(#[case] slot: u64, #[case] expected: bool) {
314        assert_eq!(windows(&[(5, 9), (20, 30)]).contains(slot), expected);
315    }
316
317    #[rstest]
318    #[case::inside_one(22, 25, true)]
319    #[case::the_whole_window(5, 9, true)]
320    #[case::spans_the_gap(5, 30, false)]
321    #[case::hangs_over(8, 12, false)]
322    fn covers_needs_one_window_to_hold_the_range(
323        #[case] start: u64,
324        #[case] end: u64,
325        #[case] expected: bool,
326    ) {
327        let range = SlotRange::new_unchecked(start, end);
328        assert_eq!(windows(&[(5, 9), (20, 30)]).covers(range), expected);
329    }
330
331    #[rstest]
332    #[case::clips_both(7, 25, Some(&[(7, 9), (20, 25)][..]))]
333    #[case::inside_one(21, 22, Some(&[(21, 22)][..]))]
334    #[case::in_the_gap(10, 19, None)]
335    fn intersection_keeps_the_parts_inside_the_range(
336        #[case] start: u64,
337        #[case] end: u64,
338        #[case] expected: Option<&[(u64, u64)]>,
339    ) {
340        let range = SlotRange::new_unchecked(start, end);
341        assert_eq!(
342            windows(&[(5, 9), (20, 30)]).intersection(range),
343            expected.map(windows)
344        );
345    }
346
347    #[test]
348    fn an_inverted_range_is_rejected() {
349        assert_eq!(
350            SlotRange::new(10, 9),
351            Err(InvertedSlotRange { start: 10, end: 9 })
352        );
353        assert!(SlotRange::new(10, 10).is_ok());
354    }
355
356    #[test]
357    fn length_is_inclusive_of_both_bounds() {
358        assert_eq!(SlotRange::new(10, 10).expect("range").len(), 1);
359        assert_eq!(SlotRange::new(10, 19).expect("range").len(), 10);
360    }
361
362    #[test]
363    fn from_count_matches_the_start_plus_count_convention() {
364        assert_eq!(
365            SlotRange::from_count(100, 1),
366            SlotRange::new_unchecked(100, 100)
367        );
368        assert_eq!(
369            SlotRange::from_count(100, 10),
370            SlotRange::new_unchecked(100, 109)
371        );
372        // A zero count still covers the anchor slot rather than inverting.
373        assert_eq!(
374            SlotRange::from_count(100, 0),
375            SlotRange::new_unchecked(100, 100)
376        );
377    }
378
379    #[test]
380    fn contains_is_inclusive() {
381        let range = SlotRange::new(10, 12).expect("range");
382        assert!(range.contains(10) && range.contains(12));
383        assert!(!range.contains(9) && !range.contains(13));
384    }
385
386    #[rstest]
387    #[case::shares_the_lower_bound(5, 10, true)]
388    #[case::shares_the_upper_bound(12, 20, true)]
389    #[case::lies_inside(11, 11, true)]
390    #[case::encloses(0, 20, true)]
391    #[case::ends_just_below(5, 9, false)]
392    #[case::starts_just_above(13, 20, false)]
393    fn overlaps_is_inclusive(#[case] start: u64, #[case] end: u64, #[case] expected: bool) {
394        let range = SlotRange::new_unchecked(10, 12);
395        let other = SlotRange::new_unchecked(start, end);
396        assert_eq!(range.overlaps(other), expected);
397        assert_eq!(other.overlaps(range), expected);
398    }
399
400    #[rstest]
401    #[case::shares_the_lower_bound(5, 10, Some((10, 10)))]
402    #[case::lies_inside(11, 11, Some((11, 11)))]
403    #[case::encloses(0, 20, Some((10, 12)))]
404    #[case::overhangs_the_end(11, 30, Some((11, 12)))]
405    #[case::ends_just_below(5, 9, None)]
406    fn intersection_keeps_the_shared_slots(
407        #[case] start: u64,
408        #[case] end: u64,
409        #[case] expected: Option<(u64, u64)>,
410    ) {
411        let range = SlotRange::new_unchecked(10, 12);
412        let other = SlotRange::new_unchecked(start, end);
413        let expected = expected.map(|(start, end)| SlotRange::new_unchecked(start, end));
414        assert_eq!(range.intersection(other), expected);
415        assert_eq!(other.intersection(range), expected);
416    }
417}