Skip to main content

opening_hours_syntax/rules/
time.rs

1use alloc::vec::Vec;
2use core::cmp::Ordering;
3use core::fmt::Display;
4use core::ops::Range;
5
6use chrono::Duration;
7
8use crate::display::write_selector;
9use crate::extended_time::ExtendedTime;
10
11// TimeSelector
12
13#[derive(Clone, Debug, Hash, PartialEq, Eq)]
14pub struct TimeSelector {
15    pub time: Vec<TimeSpan>,
16}
17
18impl TimeSelector {
19    /// Note that not all cases can be covered
20    pub(crate) fn is_00_24(&self) -> bool {
21        self.time.len() == 1
22            && self.time.first()
23                == Some(&TimeSpan::fixed_range(
24                    ExtendedTime::MIDNIGHT_00,
25                    ExtendedTime::MIDNIGHT_24,
26                ))
27    }
28}
29
30impl TimeSelector {
31    #[inline]
32    pub fn new(time: Vec<TimeSpan>) -> Self {
33        if time.is_empty() {
34            Self::default()
35        } else {
36            Self { time }
37        }
38    }
39}
40
41impl Default for TimeSelector {
42    #[inline]
43    fn default() -> Self {
44        Self {
45            time: vec![TimeSpan::fixed_range(
46                ExtendedTime::MIDNIGHT_00,
47                ExtendedTime::MIDNIGHT_24,
48            )],
49        }
50    }
51}
52
53impl Display for TimeSelector {
54    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
55        write_selector(f, &self.time)
56    }
57}
58
59// TimeSpan
60
61#[derive(Clone, Debug, Hash, PartialEq, Eq)]
62pub struct TimeSpan {
63    pub range: Range<Time>,
64    pub open_end: bool,
65    pub repeats: Option<Duration>,
66}
67
68impl TimeSpan {
69    #[inline]
70    pub const fn fixed_range(start: ExtendedTime, end: ExtendedTime) -> Self {
71        Self {
72            range: Time::Fixed(start)..Time::Fixed(end),
73            open_end: false,
74            repeats: None,
75        }
76    }
77}
78
79impl Display for TimeSpan {
80    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
81        write!(f, "{}", self.range.start)?;
82
83        if !self.open_end || self.range.end != Time::Fixed(ExtendedTime::MIDNIGHT_24) {
84            write!(f, "-{}", self.range.end)?;
85        }
86
87        if self.open_end {
88            write!(f, "+")?;
89        }
90
91        if let Some(repeat) = self.repeats {
92            write!(f, "/")?;
93
94            if repeat.num_hours() > 0 {
95                write!(f, "{:02}:", repeat.num_hours())?;
96            }
97
98            write!(f, "{:02}", repeat.num_minutes() % 60)?;
99        }
100
101        Ok(())
102    }
103}
104
105// Time
106
107#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
108pub enum Time {
109    Fixed(ExtendedTime),
110    Variable(VariableTime),
111}
112
113impl Display for Time {
114    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
115        match self {
116            Self::Fixed(time) => write!(f, "{time}"),
117            Self::Variable(time) => write!(f, "{time}"),
118        }
119    }
120}
121
122// VariableTime
123
124#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]
125pub struct VariableTime {
126    pub event: TimeEvent,
127    pub offset: i16,
128}
129
130impl Display for VariableTime {
131    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
132        let Self { event, offset } = self;
133        let offset_h = offset.abs() / 60;
134        let offset_m = offset.abs() % 60;
135
136        match offset.cmp(&0) {
137            Ordering::Less => write!(f, "({event}-{offset_h:02}:{offset_m:02})"),
138            Ordering::Greater => write!(f, "({event}+{offset_h:02}:{offset_m:02})"),
139            Ordering::Equal => write!(f, "{event}"),
140        }
141    }
142}
143
144// TimeEvent
145
146#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
147pub enum TimeEvent {
148    Dawn,
149    Sunrise,
150    Sunset,
151    Dusk,
152}
153
154impl TimeEvent {
155    pub const fn as_str(&self) -> &'static str {
156        match self {
157            Self::Dawn => "dawn",
158            Self::Sunrise => "sunrise",
159            Self::Sunset => "sunset",
160            Self::Dusk => "dusk",
161        }
162    }
163}
164
165impl Display for TimeEvent {
166    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
167        write!(f, "{}", self.as_str())
168    }
169}