1use core::fmt;
8
9#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum TariffLevel {
12 Standard,
14 Low,
16 High,
18}
19
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct TariffWindow {
23 pub start_utc: i64,
25 pub end_utc: i64,
27 pub level: TariffLevel,
29}
30
31#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum ScheduleError {
34 Empty,
36 InvalidInterval { index: usize },
38 Gap { index: usize },
40 OverlapOrOutOfOrder { index: usize },
42}
43
44impl fmt::Display for ScheduleError {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46 match self {
47 Self::Empty => f.write_str("the tariff schedule is empty"),
48 Self::InvalidInterval { index } => {
49 write!(f, "tariff window {index} must end after its start")
50 }
51 Self::Gap { index } => write!(f, "gap before tariff window {index}"),
52 Self::OverlapOrOutOfOrder { index } => write!(
53 f,
54 "tariff window {index} overlaps or precedes the previous window"
55 ),
56 }
57 }
58}
59
60impl core::error::Error for ScheduleError {}
61
62#[derive(Clone, Copy, Debug)]
80pub struct TariffSchedule<'a> {
81 windows: &'a [TariffWindow],
82}
83
84impl<'a> TariffSchedule<'a> {
85 pub fn new(windows: &'a [TariffWindow]) -> Result<Self, ScheduleError> {
87 let first = windows.first().ok_or(ScheduleError::Empty)?;
88 let mut previous_end = first.start_utc;
89 for (index, window) in windows.iter().enumerate() {
90 if window.end_utc <= window.start_utc {
91 return Err(ScheduleError::InvalidInterval { index });
92 }
93 match window.start_utc.cmp(&previous_end) {
94 core::cmp::Ordering::Greater => return Err(ScheduleError::Gap { index }),
95 core::cmp::Ordering::Less => {
96 return Err(ScheduleError::OverlapOrOutOfOrder { index });
97 }
98 core::cmp::Ordering::Equal => previous_end = window.end_utc,
99 }
100 }
101 Ok(Self { windows })
102 }
103
104 pub fn active_at(&self, utc: i64) -> Option<&'a TariffWindow> {
106 let index = self.windows.partition_point(|window| window.end_utc <= utc);
107 self.windows
108 .get(index)
109 .filter(|window| window.start_utc <= utc)
110 }
111}
112
113#[cfg(test)]
114mod tests {
115 use super::*;
116
117 fn window(start_utc: i64, end_utc: i64, level: TariffLevel) -> TariffWindow {
118 TariffWindow {
119 start_utc,
120 end_utc,
121 level,
122 }
123 }
124
125 #[test]
126 fn lookup_uses_half_open_intervals_and_stops_at_coverage_edges() {
127 let windows = [
128 window(-10, 0, TariffLevel::Standard),
129 window(0, 1, TariffLevel::High),
130 window(1, 2, TariffLevel::Low),
131 window(2, 5, TariffLevel::Low),
132 ];
133 let schedule = TariffSchedule::new(&windows).unwrap();
134 for (utc, index) in [(-10, 0), (-1, 0), (0, 1), (1, 2), (2, 3), (4, 3)] {
135 assert_eq!(schedule.active_at(utc), Some(&windows[index]));
136 }
137 for utc in [i64::MIN, -11, 5, 6, i64::MAX] {
138 assert_eq!(schedule.active_at(utc), None);
139 }
140 }
141
142 #[test]
143 fn malformed_schedules_report_the_first_invalid_window() {
144 use ScheduleError::*;
145 let base = window(10, 20, TariffLevel::Standard);
146 assert_eq!(TariffSchedule::new(&[]).unwrap_err(), Empty);
147 for (start, end, error) in [
148 (20, 20, InvalidInterval { index: 1 }),
149 (20, 19, InvalidInterval { index: 1 }),
150 (21, 30, Gap { index: 1 }),
151 (19, 30, OverlapOrOutOfOrder { index: 1 }),
152 (10, 20, OverlapOrOutOfOrder { index: 1 }),
153 (0, 10, OverlapOrOutOfOrder { index: 1 }),
154 ] {
155 assert_eq!(
156 TariffSchedule::new(&[base, window(start, end, TariffLevel::Low)]).unwrap_err(),
157 error
158 );
159 }
160 assert_eq!(
161 TariffSchedule::new(&[window(0, 0, TariffLevel::High)]).unwrap_err(),
162 InvalidInterval { index: 0 }
163 );
164 }
165
166 #[test]
167 fn single_window_supports_full_timestamp_range_without_arithmetic_overflow() {
168 let windows = [window(i64::MIN, i64::MAX, TariffLevel::High)];
169 let schedule = TariffSchedule::new(&windows).unwrap();
170 assert_eq!(schedule.active_at(i64::MIN), Some(&windows[0]));
171 assert_eq!(schedule.active_at(i64::MAX - 1), Some(&windows[0]));
172 assert_eq!(schedule.active_at(i64::MAX), None);
173 }
174}