Skip to main content

smgw_cls/fnn/
tariff.rs

1//! Look up the advisory Module 3 grid tariff level in a network operator's schedule.
2//!
3//! Supply explicit windows, including standard-tariff periods. Expand the operator's
4//! dates and local times to UTC upstream, applying the local time zone's rules for
5//! skipped and repeated hours. The lookup only identifies the active level.
6
7use core::fmt;
8
9/// The three Module 3 grid tariff levels.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub enum TariffLevel {
12    /// Standard tariff (ST).
13    Standard,
14    /// Low-load tariff (NT).
15    Low,
16    /// High-load tariff (HT).
17    High,
18}
19
20/// An operator-supplied interval measured in whole Unix seconds.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub struct TariffWindow {
23    /// First second in this window.
24    pub start_utc: i64,
25    /// First second after this window.
26    pub end_utc: i64,
27    /// Advisory level during this window.
28    pub level: TariffLevel,
29}
30
31/// Why the supplied set of windows cannot be used. Indexes are zero-based.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33pub enum ScheduleError {
34    /// No interval was supplied.
35    Empty,
36    /// The end of this interval is at or before its start.
37    InvalidInterval { index: usize },
38    /// This interval starts after the preceding interval ends.
39    Gap { index: usize },
40    /// This interval starts before the preceding interval ends.
41    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/// A finite, contiguous sequence of validated UTC tariff windows.
63///
64/// Construction checks the borrowed slice once. Lookups take logarithmic time.
65/// Times outside the supplied coverage return `None`.
66///
67/// ```
68/// use smgw_cls::fnn::tariff::{TariffLevel, TariffSchedule, TariffWindow};
69///
70/// let windows = [
71///     TariffWindow { start_utc: 0, end_utc: 3600, level: TariffLevel::Low },
72///     TariffWindow { start_utc: 3600, end_utc: 7200, level: TariffLevel::Standard },
73/// ];
74/// let schedule = TariffSchedule::new(&windows)?;
75/// assert_eq!(schedule.active_at(3600), Some(&windows[1]));
76/// assert_eq!(schedule.active_at(7200), None);
77/// # Ok::<(), smgw_cls::fnn::tariff::ScheduleError>(())
78/// ```
79#[derive(Clone, Copy, Debug)]
80pub struct TariffSchedule<'a> {
81    windows: &'a [TariffWindow],
82}
83
84impl<'a> TariffSchedule<'a> {
85    /// Validate the windows in the order supplied.
86    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    /// Return the window whose half-open interval contains this Unix second.
105    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}