opening-hours-syntax 2.1.0

A parser for opening_hours fields in OpenStreetMap.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! This module defines a data structure that allows assigning arbitrary values to arbitrary
//! subsets of an n-dimension space. It can then be used to extract maximally expanded
//! selectors of same value.
//!
//! This last problem is hard, so the implementation here only focuses on being convenient and
//! predictable. For example this research paper show that there is no known polytime approximation
//! for this problem in two dimensions and for boolean values :
//! <https://dl.acm.org/doi/10.1145/73833.73871>

use alloc::rc::Rc;
use alloc::vec::Vec;
use core::fmt::Debug;
use core::ops::Range;

use crate::util::rc::{RcCacheMut, RcCacheOwned};

pub(crate) type Paving1D<T, Val> = Dim<T, Cell<Val>>;
pub(crate) type Paving2D<T, U, Val> = Dim<T, Paving1D<U, Val>>;
pub(crate) type Paving3D<T, U, V, Val> = Dim<T, Paving2D<U, V, Val>>;
pub(crate) type Paving4D<T, U, V, W, Val> = Dim<T, Paving3D<U, V, W, Val>>;

pub(crate) type Selector1D<T> = PavingSelector<T, EmptyPavingSelector>;
pub(crate) type Selector2D<T, U> = PavingSelector<T, Selector1D<U>>;
pub(crate) type Selector3D<T, U, V> = PavingSelector<T, Selector2D<U, V>>;
pub(crate) type Selector4D<T, U, V, W> = PavingSelector<T, Selector3D<U, V, W>>;

// --
// -- EmptyPavingSelector
// --

/// A selector for paving of zero dimensions. This is a convenience type
/// intented to be expanded with more dimensions.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct EmptyPavingSelector;

impl EmptyPavingSelector {
    pub(crate) fn dim_front<T>(self, range: impl Into<Vec<Range<T>>>) -> PavingSelector<T, Self> {
        PavingSelector { range: range.into(), tail: self }
    }
}

// --
// -- PavingSelector
// --

/// A selector for a paving for at least one dimension. Recursively built for
/// each dimensions.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct PavingSelector<T, U> {
    range: Vec<Range<T>>,
    tail: U,
}

impl<T, U> PavingSelector<T, U> {
    pub(crate) fn dim_front<V>(self, range: impl Into<Vec<Range<V>>>) -> PavingSelector<V, Self> {
        PavingSelector { range: range.into(), tail: self }
    }

    pub(crate) fn unpack_front(&self) -> (&[Range<T>], &U) {
        (&self.range, &self.tail)
    }

    pub(crate) fn into_unpack_front(self) -> (Vec<Range<T>>, U) {
        (self.range, self.tail)
    }
}

// --
// -- Paving
// --

/// Interface over a n-dim paving.
pub(crate) trait Paving: Clone + Debug + Default {
    type Selector: Clone + Debug;
    type Value: Clone + Default + Eq;
    type Map<X: Clone + Debug + Default + Eq>: Paving;

    /// A bit more performant than calling set(&selector, &Default::default()) that will release
    /// memory when all the columns are empty. It also returns true the resulting paving is empty.
    fn reset(&mut self, selector: &Self::Selector) -> bool;

    fn update(&mut self, selector: &Self::Selector, operation: impl FnMut(&mut Self::Value));

    fn map<X: Clone + Debug + Default + Eq>(
        self,
        map: impl FnMut(Self::Value) -> X,
    ) -> Self::Map<X>;

    fn check_predicate(
        &self,
        selector: &Self::Selector,
        predicate: impl FnMut(&Self::Value) -> bool,
    ) -> bool;

    fn pop_filter(
        &mut self,
        filter: impl Fn(&Self::Value) -> bool,
    ) -> Option<(Self::Value, Self::Selector)>;

    fn is_val(&self, selector: &Self::Selector, val: &Self::Value) -> bool {
        self.check_predicate(selector, move |part| part == val)
    }

    fn set(&mut self, selector: &Self::Selector, val: &Self::Value) {
        self.update(selector, |inner| *inner = val.clone());
    }
}

// --
// -- Cell
// --

/// Just a 0-dimension cell.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(crate) struct Cell<Val: Default + Eq> {
    inner: Val,
}

impl<Val: Clone + Debug + Default + Eq> Paving for Cell<Val> {
    type Selector = EmptyPavingSelector;
    type Value = Val;
    type Map<X: Clone + Debug + Default + Eq> = Cell<X>;

    fn update(&mut self, _selector: &Self::Selector, mut operation: impl FnMut(&mut Self::Value)) {
        operation(&mut self.inner)
    }

    fn check_predicate(
        &self,
        _selector: &Self::Selector,
        mut predicate: impl FnMut(&Self::Value) -> bool,
    ) -> bool {
        predicate(&self.inner)
    }

    fn pop_filter(
        &mut self,
        filter: impl Fn(&Self::Value) -> bool,
    ) -> Option<(Self::Value, Self::Selector)> {
        if filter(&self.inner) {
            Some((core::mem::take(&mut self.inner), EmptyPavingSelector))
        } else {
            None
        }
    }

    fn map<X: Clone + Debug + Default + Eq>(
        self,
        mut map: impl FnMut(Self::Value) -> X,
    ) -> Self::Map<X> {
        Cell { inner: map(self.inner) }
    }

    fn reset(&mut self, _selector: &Self::Selector) -> bool {
        self.inner = Val::default();
        true
    }
}

// --
// -- Dim
// --

/// Add a dimension over a lower dimension paving. It consists of a sequence
/// of n cuts which delimits n-1 cols, as follows:
///
///   cut 0    cut 1    cut 2 ... cut n
///     |  col1  |  col2  |   ...   |
#[derive(Clone)]
pub(crate) struct Dim<T: Clone + Ord, U: Paving> {
    cuts: Vec<T>,     // ordered
    cols: Vec<Rc<U>>, // one less elements than cuts
    /// Keep an instance of the default value which will be used ensure that new values pushed to
    /// cols will always share the same pointer.
    col_default: Rc<U>,
}

impl<T: Clone + Ord, U: Paving> Default for Dim<T, U> {
    fn default() -> Self {
        Self {
            cuts: Vec::new(),
            cols: Vec::new(),
            col_default: Rc::default(),
        }
    }
}

impl<T: Clone + Ord + Debug, U: Paving + Debug> Debug for Dim<T, U> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        if self.cols.is_empty() {
            f.debug_tuple("Dim::Empty").field(&self.cols).finish()?;
        }

        let mut fmt = f.debug_struct("Dim");

        for ((start, end), value) in (self.cuts.iter())
            .zip(self.cuts.iter().skip(1))
            .zip(&self.cols)
        {
            fmt.field(&format!("{start:?}..{end:?}"), value);
        }

        fmt.finish()
    }
}

impl<T: Clone + Ord, U: Paving> Dim<T, U> {
    fn cut_at(&mut self, val: T) {
        let Err(insert_pos) = self.cuts.binary_search(&val) else {
            // Already cut at given position
            return;
        };

        self.cuts.insert(insert_pos, val);
        debug_assert!(self.cuts.is_sorted());

        if self.cuts.len() == 1 {
            // No interval created yet
        } else if self.cuts.len() == 2 {
            // First interval
            self.cols.push(self.col_default.clone())
        } else if insert_pos == self.cuts.len() - 1 {
            // Added the cut at the end
            self.cols.push(self.col_default.clone())
        } else if insert_pos == 0 {
            // Added the cut at the start
            self.cols.insert(0, self.col_default.clone())
        } else {
            let cut_fill = self.cols[insert_pos - 1].clone();
            self.cols.insert(insert_pos, cut_fill);
        }
    }
}

impl<T: Clone + Debug + Ord, U: Debug + Paving> Paving for Dim<T, U> {
    type Selector = PavingSelector<T, U::Selector>;
    type Value = U::Value;
    type Map<X: Clone + Debug + Default + Eq> = Dim<T, U::Map<X>>;

    fn reset(&mut self, selector: &Self::Selector) -> bool {
        let (ranges, selector_tail) = selector.unpack_front();
        let mut rc_reset_col = RcCacheMut::new(|col: &mut U| col.reset(selector_tail));
        let mut is_empty = true;

        for range in ranges {
            self.cut_at(range.start.clone());
            self.cut_at(range.end.clone());

            for (col_start, col_val) in self.cuts.iter().zip(&mut self.cols) {
                if *col_start >= range.start && *col_start < range.end {
                    if rc_reset_col.apply(col_val) {
                        // If the column values is cleaned up into an empty value we can collapse
                        // it into an emtpy value. This will early cleanup some memory as well as
                        // collapse inner columns.
                        *col_val = self.col_default.clone()
                    } else {
                        is_empty = false;
                    }
                } else {
                    is_empty = is_empty && Rc::ptr_eq(col_val, &self.col_default);
                }
            }
        }

        is_empty
    }

    fn update(&mut self, selector: &Self::Selector, mut operation: impl FnMut(&mut Self::Value)) {
        let (ranges, selector_tail) = selector.unpack_front();

        let mut update_rc =
            RcCacheMut::new(|val: &mut U| val.update(selector_tail, &mut operation));

        for range in ranges {
            self.cut_at(range.start.clone());
            self.cut_at(range.end.clone());

            for (col_start, col_val) in self.cuts.iter().zip(&mut self.cols) {
                if *col_start >= range.start && *col_start < range.end {
                    update_rc.apply(col_val);
                }
            }
        }
    }

    /// Check if the *full* range covered by `selector` is set and equals to `val`.
    fn check_predicate(
        &self,
        selector: &Self::Selector,
        mut predicate: impl FnMut(&Self::Value) -> bool,
    ) -> bool {
        let (ranges, selector_tail) = selector.unpack_front();

        for range in ranges {
            // Wrapping ranges are not supported : inverted bounds are
            // considered an empty interval.
            if range.start >= range.end {
                continue;
            }

            // Check if part of the selector covers a part that is outside of
            // the explicitly set values for this paving.
            let partialy_outside_bounds = self.cols.is_empty()
                || range.start
                    < *(self.cuts.first()).expect("there is always on more cuts than columns")
                || range.end
                    > *(self.cuts.last()).expect("there is always on more cuts than columns");

            // If part of the selector is outside of explicitly set values, the
            // expected value must be the default.
            if partialy_outside_bounds && !predicate(&Self::Value::default()) {
                return false;
            }

            // Check value of overlapping columns
            for ((col_start, col_end), col_val) in (self.cuts.iter())
                .zip(self.cuts.iter().skip(1))
                .zip(&self.cols)
            {
                // Column overlaps with the input range
                let col_overlaps = *col_start < range.end && *col_end > range.start;

                if col_overlaps && !col_val.check_predicate(selector_tail, &mut predicate) {
                    return false;
                }
            }
        }

        true
    }

    fn pop_filter(
        &mut self,
        filter: impl Fn(&Self::Value) -> bool,
    ) -> Option<(Self::Value, Self::Selector)> {
        let mut pop_from_col = RcCacheMut::new(|col: &mut U| col.pop_filter(&filter));

        let (mut start_idx, (target_value, selector_tail)) = self
            .cols
            .iter_mut()
            .enumerate()
            .find_map(|(idx, col)| Some((idx, pop_from_col.apply(col)?)))?;

        let mut end_idx = start_idx + 1;
        let mut selector_range = Vec::new();

        while end_idx < self.cols.len() {
            if self.cols[end_idx].is_val(&selector_tail, &target_value) {
                end_idx += 1;
                continue;
            }

            if start_idx < end_idx {
                selector_range.push(self.cuts[start_idx].clone()..self.cuts[end_idx].clone());
            }

            end_idx += 1;
            start_idx = end_idx;
        }

        if start_idx < end_idx {
            selector_range.push(self.cuts[start_idx].clone()..self.cuts[end_idx].clone());
        }

        let selector = PavingSelector { range: selector_range, tail: selector_tail };
        self.reset(&selector);
        // self.set(&selector, &Self::Value::default());
        Some((target_value, selector))
    }

    fn map<X: Clone + Debug + Default + Eq>(
        self,
        mut map: impl FnMut(Self::Value) -> X,
    ) -> Self::Map<X> {
        // Calling Rc::new from inside the cached function ensures that shared input pointers will
        // be mapped to shared output pointers.
        let mut rc_map = RcCacheOwned::new(|col: U| Rc::new(col.map(&mut map)));

        Dim {
            cuts: self.cuts,
            cols: (self.cols.into_iter())
                .map(|col| rc_map.apply(col))
                .collect(),
            col_default: Rc::default(),
        }
    }
}

// NOTE: this is heavily unoptimized, so we ensure that it is only used for tests
#[cfg(test)]
impl<T: Clone + Ord + Debug, U: Paving + PartialEq> PartialEq for Dim<T, U> {
    fn eq(&self, other: &Self) -> bool {
        let mut self_cpy = self.clone();
        let mut other_cpy = other.clone();

        for cut in &self_cpy.cuts {
            other_cpy.cut_at(cut.clone());
        }

        for cut in &other_cpy.cuts {
            self_cpy.cut_at(cut.clone());
        }

        for (col_self, col_other) in self_cpy.cols.into_iter().zip(other_cpy.cols) {
            if col_self != col_other {
                return false;
            }
        }

        true
    }
}