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};
11
12/// An inclusive `[start, end]` slot range. Construct via [`SlotRange::new`],
13/// which rejects an inverted range, or [`SlotRange::new_unchecked`] where the
14/// ordering is already guaranteed by the caller.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
16pub struct SlotRange {
17    start: u64,
18    end: u64,
19}
20
21/// Why a pair of bounds isn't a valid range.
22#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
23#[error("invalid range: start_slot {start} > end_slot {end}")]
24pub struct InvertedSlotRange {
25    #[allow(missing_docs)]
26    pub start: u64,
27    /// The requested end slot, below `start`.
28    pub end: u64,
29}
30
31impl SlotRange {
32    /// An inclusive range, rejecting `start > end`.
33    pub fn new(start: u64, end: u64) -> Result<Self, InvertedSlotRange> {
34        if start > end {
35            return Err(InvertedSlotRange { start, end });
36        }
37        Ok(Self { start, end })
38    }
39
40    /// A range whose ordering the caller already guarantees — e.g. one derived
41    /// from a `start` plus a non-zero count. Prefer [`SlotRange::new`].
42    pub const fn new_unchecked(start: u64, end: u64) -> Self {
43        Self { start, end }
44    }
45
46    /// The range covering `count` slots from `start`. `count` of 0 yields a
47    /// single-slot range, matching how the callers' slot counts behave.
48    pub const fn from_count(start: u64, count: u64) -> Self {
49        Self {
50            start,
51            end: start.saturating_add(count.saturating_sub(1)),
52        }
53    }
54
55    #[allow(missing_docs)]
56    pub const fn start(&self) -> u64 {
57        self.start
58    }
59
60    /// The last slot, inclusive.
61    pub const fn end(&self) -> u64 {
62        self.end
63    }
64
65    /// Number of slots covered, inclusive of both bounds.
66    pub const fn len(&self) -> u64 {
67        self.end - self.start + 1
68    }
69
70    /// Never true — an inclusive range always covers at least one slot. Present
71    /// so `len()` doesn't trip `clippy::len_without_is_empty`.
72    pub const fn is_empty(&self) -> bool {
73        false
74    }
75
76    #[allow(missing_docs)]
77    pub const fn contains(&self, slot: u64) -> bool {
78        slot >= self.start && slot <= self.end
79    }
80
81    /// Whether the two ranges share at least one slot.
82    pub const fn overlaps(&self, other: SlotRange) -> bool {
83        self.start <= other.end && other.start <= self.end
84    }
85
86    /// Whether `other` lies wholly within this range.
87    pub const fn covers(&self, other: SlotRange) -> bool {
88        self.start <= other.start && other.end <= self.end
89    }
90}
91
92impl fmt::Display for SlotRange {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        write!(f, "{}..={}", self.start, self.end)
95    }
96}
97
98impl From<SlotRange> for std::ops::RangeInclusive<u64> {
99    fn from(range: SlotRange) -> Self {
100        range.start..=range.end
101    }
102}
103
104pub(crate) mod slot_bounds {
105    use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};
106
107    use super::SlotRange;
108
109    #[derive(Serialize, Deserialize)]
110    struct SlotBounds {
111        start_slot: u64,
112        end_slot: u64,
113    }
114
115    pub(crate) fn serialize<S: Serializer>(
116        slots: &SlotRange,
117        serializer: S,
118    ) -> Result<S::Ok, S::Error> {
119        SlotBounds {
120            start_slot: slots.start,
121            end_slot: slots.end,
122        }
123        .serialize(serializer)
124    }
125
126    pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
127        deserializer: D,
128    ) -> Result<SlotRange, D::Error> {
129        let SlotBounds {
130            start_slot,
131            end_slot,
132        } = SlotBounds::deserialize(deserializer)?;
133        SlotRange::new(start_slot, end_slot).map_err(D::Error::custom)
134    }
135}
136
137#[cfg(test)]
138mod tests {
139    use rstest::rstest;
140
141    use super::*;
142
143    #[test]
144    fn an_inverted_range_is_rejected() {
145        assert_eq!(
146            SlotRange::new(10, 9),
147            Err(InvertedSlotRange { start: 10, end: 9 })
148        );
149        assert!(SlotRange::new(10, 10).is_ok());
150    }
151
152    #[test]
153    fn length_is_inclusive_of_both_bounds() {
154        assert_eq!(SlotRange::new(10, 10).expect("range").len(), 1);
155        assert_eq!(SlotRange::new(10, 19).expect("range").len(), 10);
156    }
157
158    #[test]
159    fn from_count_matches_the_start_plus_count_convention() {
160        assert_eq!(
161            SlotRange::from_count(100, 1),
162            SlotRange::new_unchecked(100, 100)
163        );
164        assert_eq!(
165            SlotRange::from_count(100, 10),
166            SlotRange::new_unchecked(100, 109)
167        );
168        // A zero count still covers the anchor slot rather than inverting.
169        assert_eq!(
170            SlotRange::from_count(100, 0),
171            SlotRange::new_unchecked(100, 100)
172        );
173    }
174
175    #[test]
176    fn contains_is_inclusive() {
177        let range = SlotRange::new(10, 12).expect("range");
178        assert!(range.contains(10) && range.contains(12));
179        assert!(!range.contains(9) && !range.contains(13));
180    }
181
182    #[rstest]
183    #[case::shares_the_lower_bound(5, 10, true)]
184    #[case::shares_the_upper_bound(12, 20, true)]
185    #[case::lies_inside(11, 11, true)]
186    #[case::encloses(0, 20, true)]
187    #[case::ends_just_below(5, 9, false)]
188    #[case::starts_just_above(13, 20, false)]
189    fn overlaps_is_inclusive(#[case] start: u64, #[case] end: u64, #[case] expected: bool) {
190        let range = SlotRange::new_unchecked(10, 12);
191        let other = SlotRange::new_unchecked(start, end);
192        assert_eq!(range.overlaps(other), expected);
193        assert_eq!(other.overlaps(range), expected);
194    }
195}