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    #[expect(missing_docs, reason = "self-explanatory")]
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    #[expect(missing_docs, reason = "self-explanatory")]
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    #[expect(missing_docs, reason = "self-explanatory")]
78    pub const fn contains(&self, slot: u64) -> bool {
79        slot >= self.start && slot <= self.end
80    }
81
82    /// 0 before the start, `len()` past the end.
83    pub fn slots_before(&self, slot: u64) -> u64 {
84        slot.min(self.end.saturating_add(1))
85            .saturating_sub(self.start)
86    }
87
88    /// Whether the two ranges share at least one slot.
89    pub const fn overlaps(&self, other: SlotRange) -> bool {
90        self.start <= other.end && other.start <= self.end
91    }
92
93    /// Whether `other` lies wholly within this range.
94    pub const fn covers(&self, other: SlotRange) -> bool {
95        self.start <= other.start && other.end <= self.end
96    }
97
98    /// The slots both ranges share.
99    pub fn intersection(self, other: SlotRange) -> Option<SlotRange> {
100        self.overlaps(other).then(|| Self {
101            start: self.start.max(other.start),
102            end: self.end.min(other.end),
103        })
104    }
105}
106
107impl fmt::Display for SlotRange {
108    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
109        write!(f, "{}..={}", self.start, self.end)
110    }
111}
112
113impl From<SlotRange> for std::ops::RangeInclusive<u64> {
114    fn from(range: SlotRange) -> Self {
115        range.start..=range.end
116    }
117}
118
119/// The slots an action may fire at: one [`SlotRange`] object or a list of them.
120#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
121#[serde(try_from = "SlotWindowsWire", into = "SlotWindowsWire")]
122pub struct SlotWindows(Vec<SlotRange>);
123
124#[serde_as]
125#[derive(Serialize, Deserialize)]
126#[serde(transparent)]
127struct SlotWindowsWire(#[serde_as(as = "OneOrMany<_, PreferOne>")] Vec<SlotRange>);
128
129/// Slot windows were built from no range.
130#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
131#[error("slot windows name no range")]
132pub struct NoSlotWindows;
133
134/// Why a set of ranges from the wire isn't valid slot windows.
135#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
136pub enum InvalidSlotWindows {
137    #[error(transparent)]
138    #[expect(missing_docs, reason = "self-explanatory")]
139    Empty(#[from] NoSlotWindows),
140    #[error(transparent)]
141    #[expect(missing_docs, reason = "self-explanatory")]
142    Inverted(#[from] InvertedSlotRange),
143}
144
145impl SlotWindows {
146    /// Sorts the ranges and merges those that overlap or touch.
147    pub fn new(ranges: impl IntoIterator<Item = SlotRange>) -> Result<Self, NoSlotWindows> {
148        let ranges = ranges.into_iter().collect::<Vec<_>>();
149        if ranges.is_empty() {
150            return Err(NoSlotWindows);
151        }
152        Ok(Self(merged(ranges)))
153    }
154
155    fn window_of(&self, slot: u64) -> Option<SlotRange> {
156        let at = self.0.partition_point(|range| range.end < slot);
157        self.0.get(at).copied().filter(|range| range.contains(slot))
158    }
159
160    #[expect(missing_docs, reason = "self-explanatory")]
161    pub fn contains(&self, slot: u64) -> bool {
162        self.window_of(slot).is_some()
163    }
164
165    /// Whether a single window holds every slot of `range`.
166    pub fn covers(&self, range: SlotRange) -> bool {
167        self.window_of(range.start)
168            .is_some_and(|window| window.covers(range))
169    }
170
171    /// The parts of these windows inside `range`, or `None` when they share no slot.
172    pub fn intersection(&self, range: SlotRange) -> Option<Self> {
173        Self::new(
174            self.0
175                .iter()
176                .filter_map(|window| window.intersection(range)),
177        )
178        .ok()
179    }
180}
181
182fn merged(mut ranges: Vec<SlotRange>) -> Vec<SlotRange> {
183    ranges.sort();
184    ranges
185        .into_iter()
186        .fold(Vec::new(), |mut merged: Vec<SlotRange>, next| {
187            match merged.last_mut() {
188                Some(last) if next.start <= last.end.saturating_add(1) => {
189                    last.end = last.end.max(next.end);
190                }
191                _ => merged.push(next),
192            }
193            merged
194        })
195}
196
197impl From<SlotRange> for SlotWindows {
198    fn from(range: SlotRange) -> Self {
199        Self(vec![range])
200    }
201}
202
203impl TryFrom<SlotWindowsWire> for SlotWindows {
204    type Error = InvalidSlotWindows;
205
206    fn try_from(SlotWindowsWire(ranges): SlotWindowsWire) -> Result<Self, Self::Error> {
207        let ranges = ranges
208            .into_iter()
209            .map(|range| SlotRange::new(range.start, range.end))
210            .collect::<Result<Vec<_>, _>>()?;
211        Ok(Self::new(ranges)?)
212    }
213}
214
215impl From<SlotWindows> for SlotWindowsWire {
216    fn from(SlotWindows(ranges): SlotWindows) -> Self {
217        Self(ranges)
218    }
219}
220
221pub(crate) mod slot_bounds {
222    use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};
223
224    use super::SlotRange;
225
226    #[derive(Serialize, Deserialize)]
227    struct SlotBounds {
228        start_slot: u64,
229        end_slot: u64,
230    }
231
232    pub(crate) fn serialize<S: Serializer>(
233        slots: &SlotRange,
234        serializer: S,
235    ) -> Result<S::Ok, S::Error> {
236        SlotBounds {
237            start_slot: slots.start,
238            end_slot: slots.end,
239        }
240        .serialize(serializer)
241    }
242
243    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
244        deserializer: D,
245    ) -> Result<SlotRange, D::Error> {
246        let SlotBounds {
247            start_slot,
248            end_slot,
249        } = SlotBounds::deserialize(deserializer)?;
250        SlotRange::new(start_slot, end_slot).map_err(D::Error::custom)
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use rstest::rstest;
257
258    use super::*;
259
260    fn windows(ranges: &[(u64, u64)]) -> SlotWindows {
261        SlotWindows::new(
262            ranges
263                .iter()
264                .map(|&(start, end)| SlotRange::new_unchecked(start, end)),
265        )
266        .expect("windows")
267    }
268
269    #[test]
270    fn one_window_writes_as_a_slot_range_and_several_as_a_list() {
271        let one = windows(&[(5, 9)]);
272        assert_eq!(
273            serde_json::to_value(&one).unwrap(),
274            serde_json::to_value(SlotRange::new_unchecked(5, 9)).unwrap()
275        );
276        let two = windows(&[(5, 9), (20, 30)]);
277        let json = serde_json::to_value(&two).unwrap();
278        assert!(json.is_array(), "{json}");
279        for windows in [one, two] {
280            let json = serde_json::to_string(&windows).unwrap();
281            assert_eq!(serde_json::from_str::<SlotWindows>(&json).unwrap(), windows);
282        }
283        let listed = r#"[{"start":5,"end":9}]"#;
284        assert_eq!(
285            serde_json::from_str::<SlotWindows>(listed).unwrap(),
286            windows(&[(5, 9)])
287        );
288    }
289
290    #[rstest]
291    #[case::empty_list("[]")]
292    #[case::inverted_object(r#"{"start":10,"end":9}"#)]
293    #[case::inverted_in_a_list(r#"[{"start":1,"end":2},{"start":10,"end":9}]"#)]
294    fn windows_that_name_no_valid_range_are_rejected(#[case] json: &str) {
295        assert!(serde_json::from_str::<SlotWindows>(json).is_err());
296    }
297
298    #[rstest]
299    #[case::unsorted(&[(20, 30), (5, 9)], &[(5, 9), (20, 30)])]
300    #[case::touching(&[(5, 9), (10, 12)], &[(5, 12)])]
301    #[case::overlapping(&[(5, 15), (10, 12), (14, 20)], &[(5, 20)])]
302    #[case::apart(&[(5, 9), (11, 12)], &[(5, 9), (11, 12)])]
303    fn new_sorts_and_merges_ranges(#[case] given: &[(u64, u64)], #[case] kept: &[(u64, u64)]) {
304        assert_eq!(windows(given), windows(kept));
305    }
306
307    #[test]
308    fn no_ranges_make_no_windows() {
309        assert_eq!(SlotWindows::new([]), Err(NoSlotWindows));
310    }
311
312    #[rstest]
313    #[case::first_start(5, true)]
314    #[case::first_end(9, true)]
315    #[case::between(10, false)]
316    #[case::second_start(20, true)]
317    #[case::past_all(31, false)]
318    #[case::before_all(4, false)]
319    fn contains_finds_a_slot_in_any_window(#[case] slot: u64, #[case] expected: bool) {
320        assert_eq!(windows(&[(5, 9), (20, 30)]).contains(slot), expected);
321    }
322
323    #[rstest]
324    #[case::inside_one(22, 25, true)]
325    #[case::the_whole_window(5, 9, true)]
326    #[case::spans_the_gap(5, 30, false)]
327    #[case::hangs_over(8, 12, false)]
328    fn covers_needs_one_window_to_hold_the_range(
329        #[case] start: u64,
330        #[case] end: u64,
331        #[case] expected: bool,
332    ) {
333        let range = SlotRange::new_unchecked(start, end);
334        assert_eq!(windows(&[(5, 9), (20, 30)]).covers(range), expected);
335    }
336
337    #[rstest]
338    #[case::clips_both(7, 25, Some(&[(7, 9), (20, 25)][..]))]
339    #[case::inside_one(21, 22, Some(&[(21, 22)][..]))]
340    #[case::in_the_gap(10, 19, None)]
341    fn intersection_keeps_the_parts_inside_the_range(
342        #[case] start: u64,
343        #[case] end: u64,
344        #[case] expected: Option<&[(u64, u64)]>,
345    ) {
346        let range = SlotRange::new_unchecked(start, end);
347        assert_eq!(
348            windows(&[(5, 9), (20, 30)]).intersection(range),
349            expected.map(windows)
350        );
351    }
352
353    #[test]
354    fn an_inverted_range_is_rejected() {
355        assert_eq!(
356            SlotRange::new(10, 9),
357            Err(InvertedSlotRange { start: 10, end: 9 })
358        );
359        assert!(SlotRange::new(10, 10).is_ok());
360    }
361
362    #[test]
363    fn length_is_inclusive_of_both_bounds() {
364        assert_eq!(SlotRange::new(10, 10).expect("range").len(), 1);
365        assert_eq!(SlotRange::new(10, 19).expect("range").len(), 10);
366    }
367
368    #[test]
369    fn from_count_matches_the_start_plus_count_convention() {
370        assert_eq!(
371            SlotRange::from_count(100, 1),
372            SlotRange::new_unchecked(100, 100)
373        );
374        assert_eq!(
375            SlotRange::from_count(100, 10),
376            SlotRange::new_unchecked(100, 109)
377        );
378        // A zero count still covers the anchor slot rather than inverting.
379        assert_eq!(
380            SlotRange::from_count(100, 0),
381            SlotRange::new_unchecked(100, 100)
382        );
383    }
384
385    #[test]
386    fn contains_is_inclusive() {
387        let range = SlotRange::new(10, 12).expect("range");
388        assert!(range.contains(10) && range.contains(12));
389        assert!(!range.contains(9) && !range.contains(13));
390    }
391
392    #[rstest]
393    #[case::before_the_start(5, 0)]
394    #[case::at_the_start(10, 0)]
395    #[case::in_the_middle(12, 2)]
396    #[case::at_the_end(19, 9)]
397    #[case::past_the_end(30, 10)]
398    fn slots_before_counts_the_range_slots_below_a_slot(#[case] slot: u64, #[case] expected: u64) {
399        assert_eq!(
400            SlotRange::new_unchecked(10, 19).slots_before(slot),
401            expected
402        );
403    }
404
405    #[rstest]
406    #[case::shares_the_lower_bound(5, 10, true)]
407    #[case::shares_the_upper_bound(12, 20, true)]
408    #[case::lies_inside(11, 11, true)]
409    #[case::encloses(0, 20, true)]
410    #[case::ends_just_below(5, 9, false)]
411    #[case::starts_just_above(13, 20, false)]
412    fn overlaps_is_inclusive(#[case] start: u64, #[case] end: u64, #[case] expected: bool) {
413        let range = SlotRange::new_unchecked(10, 12);
414        let other = SlotRange::new_unchecked(start, end);
415        assert_eq!(range.overlaps(other), expected);
416        assert_eq!(other.overlaps(range), expected);
417    }
418
419    #[rstest]
420    #[case::shares_the_lower_bound(5, 10, Some((10, 10)))]
421    #[case::lies_inside(11, 11, Some((11, 11)))]
422    #[case::encloses(0, 20, Some((10, 12)))]
423    #[case::overhangs_the_end(11, 30, Some((11, 12)))]
424    #[case::ends_just_below(5, 9, None)]
425    fn intersection_keeps_the_shared_slots(
426        #[case] start: u64,
427        #[case] end: u64,
428        #[case] expected: Option<(u64, u64)>,
429    ) {
430        let range = SlotRange::new_unchecked(10, 12);
431        let other = SlotRange::new_unchecked(start, end);
432        let expected = expected.map(|(start, end)| SlotRange::new_unchecked(start, end));
433        assert_eq!(range.intersection(other), expected);
434        assert_eq!(other.intersection(range), expected);
435    }
436}