use std::fmt;
use serde::{Deserialize, Serialize};
use serde_with::{OneOrMany, formats::PreferOne, serde_as};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub struct SlotRange {
start: u64,
end: u64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("invalid range: start_slot {start} > end_slot {end}")]
pub struct InvertedSlotRange {
#[expect(missing_docs, reason = "self-explanatory")]
pub start: u64,
pub end: u64,
}
impl SlotRange {
pub fn new(start: u64, end: u64) -> Result<Self, InvertedSlotRange> {
if start > end {
return Err(InvertedSlotRange { start, end });
}
Ok(Self { start, end })
}
pub const fn new_unchecked(start: u64, end: u64) -> Self {
Self { start, end }
}
pub const fn from_count(start: u64, count: u64) -> Self {
Self {
start,
end: start.saturating_add(count.saturating_sub(1)),
}
}
#[expect(missing_docs, reason = "self-explanatory")]
pub const fn start(&self) -> u64 {
self.start
}
pub const fn end(&self) -> u64 {
self.end
}
pub const fn len(&self) -> u64 {
self.end - self.start + 1
}
pub const fn is_empty(&self) -> bool {
false
}
#[expect(missing_docs, reason = "self-explanatory")]
pub const fn contains(&self, slot: u64) -> bool {
slot >= self.start && slot <= self.end
}
pub fn slots_before(&self, slot: u64) -> u64 {
slot.min(self.end.saturating_add(1))
.saturating_sub(self.start)
}
pub const fn overlaps(&self, other: SlotRange) -> bool {
self.start <= other.end && other.start <= self.end
}
pub const fn covers(&self, other: SlotRange) -> bool {
self.start <= other.start && other.end <= self.end
}
pub fn intersection(self, other: SlotRange) -> Option<SlotRange> {
self.overlaps(other).then(|| Self {
start: self.start.max(other.start),
end: self.end.min(other.end),
})
}
}
impl fmt::Display for SlotRange {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}..={}", self.start, self.end)
}
}
impl From<SlotRange> for std::ops::RangeInclusive<u64> {
fn from(range: SlotRange) -> Self {
range.start..=range.end
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "SlotWindowsWire", into = "SlotWindowsWire")]
pub struct SlotWindows(Vec<SlotRange>);
#[serde_as]
#[derive(Serialize, Deserialize)]
#[serde(transparent)]
struct SlotWindowsWire(#[serde_as(as = "OneOrMany<_, PreferOne>")] Vec<SlotRange>);
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("slot windows name no range")]
pub struct NoSlotWindows;
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
pub enum InvalidSlotWindows {
#[error(transparent)]
#[expect(missing_docs, reason = "self-explanatory")]
Empty(#[from] NoSlotWindows),
#[error(transparent)]
#[expect(missing_docs, reason = "self-explanatory")]
Inverted(#[from] InvertedSlotRange),
}
impl SlotWindows {
pub fn new(ranges: impl IntoIterator<Item = SlotRange>) -> Result<Self, NoSlotWindows> {
let ranges = ranges.into_iter().collect::<Vec<_>>();
if ranges.is_empty() {
return Err(NoSlotWindows);
}
Ok(Self(merged(ranges)))
}
fn window_of(&self, slot: u64) -> Option<SlotRange> {
let at = self.0.partition_point(|range| range.end < slot);
self.0.get(at).copied().filter(|range| range.contains(slot))
}
#[expect(missing_docs, reason = "self-explanatory")]
pub fn contains(&self, slot: u64) -> bool {
self.window_of(slot).is_some()
}
pub fn covers(&self, range: SlotRange) -> bool {
self.window_of(range.start)
.is_some_and(|window| window.covers(range))
}
pub fn intersection(&self, range: SlotRange) -> Option<Self> {
Self::new(
self.0
.iter()
.filter_map(|window| window.intersection(range)),
)
.ok()
}
}
fn merged(mut ranges: Vec<SlotRange>) -> Vec<SlotRange> {
ranges.sort();
ranges
.into_iter()
.fold(Vec::new(), |mut merged: Vec<SlotRange>, next| {
match merged.last_mut() {
Some(last) if next.start <= last.end.saturating_add(1) => {
last.end = last.end.max(next.end);
}
_ => merged.push(next),
}
merged
})
}
impl From<SlotRange> for SlotWindows {
fn from(range: SlotRange) -> Self {
Self(vec![range])
}
}
impl TryFrom<SlotWindowsWire> for SlotWindows {
type Error = InvalidSlotWindows;
fn try_from(SlotWindowsWire(ranges): SlotWindowsWire) -> Result<Self, Self::Error> {
let ranges = ranges
.into_iter()
.map(|range| SlotRange::new(range.start, range.end))
.collect::<Result<Vec<_>, _>>()?;
Ok(Self::new(ranges)?)
}
}
impl From<SlotWindows> for SlotWindowsWire {
fn from(SlotWindows(ranges): SlotWindows) -> Self {
Self(ranges)
}
}
pub(crate) mod slot_bounds {
use serde::{Deserialize, Deserializer, Serialize, Serializer, de::Error};
use super::SlotRange;
#[derive(Serialize, Deserialize)]
struct SlotBounds {
start_slot: u64,
end_slot: u64,
}
pub(crate) fn serialize<S: Serializer>(
slots: &SlotRange,
serializer: S,
) -> Result<S::Ok, S::Error> {
SlotBounds {
start_slot: slots.start,
end_slot: slots.end,
}
.serialize(serializer)
}
pub(crate) fn deserialize<'de, D: Deserializer<'de>>(
deserializer: D,
) -> Result<SlotRange, D::Error> {
let SlotBounds {
start_slot,
end_slot,
} = SlotBounds::deserialize(deserializer)?;
SlotRange::new(start_slot, end_slot).map_err(D::Error::custom)
}
}
#[cfg(test)]
mod tests {
use rstest::rstest;
use super::*;
fn windows(ranges: &[(u64, u64)]) -> SlotWindows {
SlotWindows::new(
ranges
.iter()
.map(|&(start, end)| SlotRange::new_unchecked(start, end)),
)
.expect("windows")
}
#[test]
fn one_window_writes_as_a_slot_range_and_several_as_a_list() {
let one = windows(&[(5, 9)]);
assert_eq!(
serde_json::to_value(&one).unwrap(),
serde_json::to_value(SlotRange::new_unchecked(5, 9)).unwrap()
);
let two = windows(&[(5, 9), (20, 30)]);
let json = serde_json::to_value(&two).unwrap();
assert!(json.is_array(), "{json}");
for windows in [one, two] {
let json = serde_json::to_string(&windows).unwrap();
assert_eq!(serde_json::from_str::<SlotWindows>(&json).unwrap(), windows);
}
let listed = r#"[{"start":5,"end":9}]"#;
assert_eq!(
serde_json::from_str::<SlotWindows>(listed).unwrap(),
windows(&[(5, 9)])
);
}
#[rstest]
#[case::empty_list("[]")]
#[case::inverted_object(r#"{"start":10,"end":9}"#)]
#[case::inverted_in_a_list(r#"[{"start":1,"end":2},{"start":10,"end":9}]"#)]
fn windows_that_name_no_valid_range_are_rejected(#[case] json: &str) {
assert!(serde_json::from_str::<SlotWindows>(json).is_err());
}
#[rstest]
#[case::unsorted(&[(20, 30), (5, 9)], &[(5, 9), (20, 30)])]
#[case::touching(&[(5, 9), (10, 12)], &[(5, 12)])]
#[case::overlapping(&[(5, 15), (10, 12), (14, 20)], &[(5, 20)])]
#[case::apart(&[(5, 9), (11, 12)], &[(5, 9), (11, 12)])]
fn new_sorts_and_merges_ranges(#[case] given: &[(u64, u64)], #[case] kept: &[(u64, u64)]) {
assert_eq!(windows(given), windows(kept));
}
#[test]
fn no_ranges_make_no_windows() {
assert_eq!(SlotWindows::new([]), Err(NoSlotWindows));
}
#[rstest]
#[case::first_start(5, true)]
#[case::first_end(9, true)]
#[case::between(10, false)]
#[case::second_start(20, true)]
#[case::past_all(31, false)]
#[case::before_all(4, false)]
fn contains_finds_a_slot_in_any_window(#[case] slot: u64, #[case] expected: bool) {
assert_eq!(windows(&[(5, 9), (20, 30)]).contains(slot), expected);
}
#[rstest]
#[case::inside_one(22, 25, true)]
#[case::the_whole_window(5, 9, true)]
#[case::spans_the_gap(5, 30, false)]
#[case::hangs_over(8, 12, false)]
fn covers_needs_one_window_to_hold_the_range(
#[case] start: u64,
#[case] end: u64,
#[case] expected: bool,
) {
let range = SlotRange::new_unchecked(start, end);
assert_eq!(windows(&[(5, 9), (20, 30)]).covers(range), expected);
}
#[rstest]
#[case::clips_both(7, 25, Some(&[(7, 9), (20, 25)][..]))]
#[case::inside_one(21, 22, Some(&[(21, 22)][..]))]
#[case::in_the_gap(10, 19, None)]
fn intersection_keeps_the_parts_inside_the_range(
#[case] start: u64,
#[case] end: u64,
#[case] expected: Option<&[(u64, u64)]>,
) {
let range = SlotRange::new_unchecked(start, end);
assert_eq!(
windows(&[(5, 9), (20, 30)]).intersection(range),
expected.map(windows)
);
}
#[test]
fn an_inverted_range_is_rejected() {
assert_eq!(
SlotRange::new(10, 9),
Err(InvertedSlotRange { start: 10, end: 9 })
);
assert!(SlotRange::new(10, 10).is_ok());
}
#[test]
fn length_is_inclusive_of_both_bounds() {
assert_eq!(SlotRange::new(10, 10).expect("range").len(), 1);
assert_eq!(SlotRange::new(10, 19).expect("range").len(), 10);
}
#[test]
fn from_count_matches_the_start_plus_count_convention() {
assert_eq!(
SlotRange::from_count(100, 1),
SlotRange::new_unchecked(100, 100)
);
assert_eq!(
SlotRange::from_count(100, 10),
SlotRange::new_unchecked(100, 109)
);
assert_eq!(
SlotRange::from_count(100, 0),
SlotRange::new_unchecked(100, 100)
);
}
#[test]
fn contains_is_inclusive() {
let range = SlotRange::new(10, 12).expect("range");
assert!(range.contains(10) && range.contains(12));
assert!(!range.contains(9) && !range.contains(13));
}
#[rstest]
#[case::before_the_start(5, 0)]
#[case::at_the_start(10, 0)]
#[case::in_the_middle(12, 2)]
#[case::at_the_end(19, 9)]
#[case::past_the_end(30, 10)]
fn slots_before_counts_the_range_slots_below_a_slot(#[case] slot: u64, #[case] expected: u64) {
assert_eq!(
SlotRange::new_unchecked(10, 19).slots_before(slot),
expected
);
}
#[rstest]
#[case::shares_the_lower_bound(5, 10, true)]
#[case::shares_the_upper_bound(12, 20, true)]
#[case::lies_inside(11, 11, true)]
#[case::encloses(0, 20, true)]
#[case::ends_just_below(5, 9, false)]
#[case::starts_just_above(13, 20, false)]
fn overlaps_is_inclusive(#[case] start: u64, #[case] end: u64, #[case] expected: bool) {
let range = SlotRange::new_unchecked(10, 12);
let other = SlotRange::new_unchecked(start, end);
assert_eq!(range.overlaps(other), expected);
assert_eq!(other.overlaps(range), expected);
}
#[rstest]
#[case::shares_the_lower_bound(5, 10, Some((10, 10)))]
#[case::lies_inside(11, 11, Some((11, 11)))]
#[case::encloses(0, 20, Some((10, 12)))]
#[case::overhangs_the_end(11, 30, Some((11, 12)))]
#[case::ends_just_below(5, 9, None)]
fn intersection_keeps_the_shared_slots(
#[case] start: u64,
#[case] end: u64,
#[case] expected: Option<(u64, u64)>,
) {
let range = SlotRange::new_unchecked(10, 12);
let other = SlotRange::new_unchecked(start, end);
let expected = expected.map(|(start, end)| SlotRange::new_unchecked(start, end));
assert_eq!(range.intersection(other), expected);
assert_eq!(other.intersection(range), expected);
}
}