opening_hours_syntax/rules/
mod.rs

1pub mod day;
2pub mod time;
3
4use std::fmt::Display;
5use std::sync::Arc;
6
7use crate::normalize::frame::Bounded;
8use crate::normalize::paving::{Paving, Paving5D};
9use crate::normalize::{canonical_to_seq, ruleseq_to_selector};
10use crate::sorted_vec::UniqueSortedVec;
11
12// OpeningHoursExpression
13
14#[derive(Clone, Debug, Hash, PartialEq, Eq)]
15pub struct OpeningHoursExpression {
16    pub rules: Vec<RuleSequence>,
17}
18
19impl OpeningHoursExpression {
20    /// Check if this expression is *trivially* constant (ie. always evaluated at the exact same
21    /// status). Note that this may return `false` for an expression that is constant but should
22    /// cover most common cases.
23    ///
24    /// ```
25    /// use opening_hours_syntax::parse;
26    ///
27    /// assert!(parse("24/7").unwrap().is_constant());
28    /// assert!(parse("24/7 closed").unwrap().is_constant());
29    /// assert!(parse("00:00-24:00 open").unwrap().is_constant());
30    /// assert!(!parse("00:00-18:00 open").unwrap().is_constant());
31    /// assert!(!parse("24/7 ; PH off").unwrap().is_constant());
32    /// ```
33    pub fn is_constant(&self) -> bool {
34        let Some(kind) = self.rules.last().map(|rs| rs.kind) else {
35            return true;
36        };
37
38        // Ignores rules from the end as long as they are all evaluated to the same kind.
39        let search_tail_full = self.rules.iter().rev().find(|rs| {
40            rs.day_selector.is_empty() || !rs.time_selector.is_00_24() || rs.kind != kind
41        });
42
43        let Some(tail) = search_tail_full else {
44            return kind == RuleKind::Closed;
45        };
46
47        tail.kind == kind && tail.is_constant()
48    }
49
50    /// Convert the expression into a normalized form. It will not affect the meaning of the
51    /// expression and might impact the performance of evaluations.
52    ///
53    /// ```
54    /// let oh = opening_hours_syntax::parse("24/7 ; Su closed").unwrap();
55    /// assert_eq!(oh.normalize().to_string(), "Mo-Sa");
56    /// ```
57    pub fn normalize(self) -> Self {
58        let mut rules_queue = self.rules.into_iter().peekable();
59        let mut paving = Paving5D::default();
60
61        while let Some(rule) = rules_queue.peek() {
62            if rule.operator == RuleOperator::Fallback {
63                break;
64            }
65
66            let Some(selector) = ruleseq_to_selector(rule) else {
67                break;
68            };
69
70            let rule = rules_queue.next().unwrap();
71
72            // If the rule is not explicitly targeting a closed kind, then it overrides
73            // previous rules for the whole day.
74            if rule.operator == RuleOperator::Normal && rule.kind != RuleKind::Closed {
75                let (_, day_selector) = selector.clone().into_unpack_front();
76                let full_day_selector = day_selector.dim_front([Bounded::bounds()]);
77                paving.set(&full_day_selector, &Default::default());
78            }
79
80            paving.set(&selector, &(rule.kind, rule.comments));
81        }
82
83        Self {
84            rules: canonical_to_seq(paving).chain(rules_queue).collect(),
85        }
86    }
87}
88
89impl Display for OpeningHoursExpression {
90    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
91        let Some(first) = self.rules.first() else {
92            return write!(f, "closed");
93        };
94
95        write!(f, "{first}")?;
96
97        for rule in &self.rules[1..] {
98            let separator = match rule.operator {
99                RuleOperator::Normal => " ; ",
100                RuleOperator::Additional => ", ",
101                RuleOperator::Fallback => " || ",
102            };
103
104            write!(f, "{separator}{rule}")?;
105        }
106
107        Ok(())
108    }
109}
110
111// RuleSequence
112
113#[derive(Clone, Debug, Hash, PartialEq, Eq)]
114pub struct RuleSequence {
115    pub day_selector: day::DaySelector,
116    pub time_selector: time::TimeSelector,
117    pub kind: RuleKind,
118    pub operator: RuleOperator,
119    pub comments: UniqueSortedVec<Arc<str>>,
120}
121
122impl RuleSequence {
123    /// If this returns `true`, then this expression is always open, but it
124    /// can't detect all cases.
125    pub fn is_constant(&self) -> bool {
126        self.day_selector.is_empty() && self.time_selector.is_00_24()
127    }
128}
129
130impl Display for RuleSequence {
131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
132        let mut is_empty = true;
133
134        if self.is_constant() {
135            is_empty = false;
136            write!(f, "24/7")?;
137        } else {
138            is_empty = is_empty && self.day_selector.is_empty();
139            write!(f, "{}", self.day_selector)?;
140
141            if !self.time_selector.is_00_24() {
142                if !is_empty {
143                    write!(f, " ")?;
144                }
145
146                is_empty = is_empty && self.time_selector.is_00_24();
147                write!(f, "{}", self.time_selector)?;
148            }
149        }
150
151        if self.kind != RuleKind::Open {
152            if !is_empty {
153                write!(f, " ")?;
154            }
155
156            is_empty = false;
157            write!(f, "{}", self.kind)?;
158        }
159
160        if !self.comments.is_empty() {
161            if !is_empty {
162                write!(f, " ")?;
163            }
164
165            write!(f, "\"{}\"", self.comments.join(", "))?;
166        }
167
168        Ok(())
169    }
170}
171
172// RuleKind
173
174#[derive(Copy, Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)]
175pub enum RuleKind {
176    Open,
177    Closed,
178    Unknown,
179}
180
181impl RuleKind {
182    pub const fn as_str(self) -> &'static str {
183        match self {
184            Self::Open => "open",
185            Self::Closed => "closed",
186            Self::Unknown => "unknown",
187        }
188    }
189}
190
191impl Default for RuleKind {
192    fn default() -> Self {
193        Self::Closed
194    }
195}
196
197impl Display for RuleKind {
198    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
199        write!(f, "{}", self.as_str())
200    }
201}
202
203// RuleOperator
204
205#[derive(Copy, Clone, Debug, Hash, Eq, PartialEq)]
206pub enum RuleOperator {
207    Normal,
208    Additional,
209    Fallback,
210}