simulator_client/
ranges.rs1use std::{error::Error, str::FromStr};
2
3use chrono::{DateTime, NaiveDate, TimeZone, Utc};
4use simulator_api::AvailableRange;
5
6#[derive(Debug, Clone)]
8#[expect(missing_docs, reason = "self-explanatory enum variants")]
9pub enum RangeBound {
10 Slot(u64),
11 Time(DateTime<Utc>),
12}
13
14#[derive(Debug)]
16pub struct ParseRangeBoundError(String);
17
18impl std::fmt::Display for ParseRangeBoundError {
19 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 f.write_str(&self.0)
21 }
22}
23
24impl Error for ParseRangeBoundError {}
25
26impl FromStr for RangeBound {
27 type Err = ParseRangeBoundError;
28
29 fn from_str(s: &str) -> Result<Self, Self::Err> {
32 if let Ok(slot) = s.parse::<u64>() {
33 return Ok(Self::Slot(slot));
34 }
35 if let Ok(dt) = DateTime::parse_from_rfc3339(s) {
36 return Ok(Self::Time(dt.with_timezone(&Utc)));
37 }
38 if let Ok(date) = NaiveDate::parse_from_str(s, "%Y-%m-%d") {
39 let dt = Utc.from_utc_datetime(&date.and_time(chrono::NaiveTime::MIN));
40 return Ok(Self::Time(dt));
41 }
42 Err(ParseRangeBoundError(format!(
43 "could not parse {s:?} as a slot number, RFC 3339 timestamp, or YYYY-MM-DD date"
44 )))
45 }
46}
47
48pub fn filter_ranges(
56 ranges: &[AvailableRange],
57 after: Option<&RangeBound>,
58 before: Option<&RangeBound>,
59) -> Vec<AvailableRange> {
60 let mut out = ranges.to_vec();
61
62 if let Some(bound) = after {
63 out.retain(|r| starts_after(r, bound));
64 }
65 if let Some(bound) = before {
66 out.retain(|r| ends_before(r, bound));
67 }
68
69 out
70}
71
72fn ends_before(r: &AvailableRange, bound: &RangeBound) -> bool {
73 match bound {
74 RangeBound::Slot(slot) => r.max_bundle_end_slot.is_none_or(|end| end <= *slot),
75 RangeBound::Time(time) => match &r.max_bundle_end_slot_utc {
76 None => true, Some(utc_str) => parse_utc(utc_str).is_none_or(|end| end <= *time),
78 },
79 }
80}
81
82fn starts_after(r: &AvailableRange, bound: &RangeBound) -> bool {
83 match bound {
84 RangeBound::Slot(slot) => r.bundle_start_slot >= *slot,
85 RangeBound::Time(time) => match &r.bundle_start_slot_utc {
86 None => true, Some(utc_str) => parse_utc(utc_str).is_none_or(|start| start >= *time),
88 },
89 }
90}
91
92fn parse_utc(s: &str) -> Option<DateTime<Utc>> {
93 DateTime::parse_from_rfc3339(s)
94 .ok()
95 .map(|dt| dt.with_timezone(&Utc))
96}