Skip to main content

OpeningHours

Struct OpeningHours 

Source
pub struct OpeningHours<L: Localize = NoLocation> { /* private fields */ }
Expand description

A parsed opening hours expression and its evaluation context.

Note that all big inner structures are immutable and wrapped by an Arc so this is safe and fast to clone.

ImplementationsΒ§

SourceΒ§

impl OpeningHours<NoLocation>

Source

pub fn parse(raw_oh: &str) -> Result<Self, ParserError>

πŸ‘ŽDeprecated since 2.0.0:

Use OpeningHours::from_str(raw_oh: &str) or raw_oh.parse() via the trait std::str::FromStr

Parse a raw opening hours expression.

use opening_hours::{Context, OpeningHours};

assert!(OpeningHours::parse("24/7 open").is_ok());
assert!(OpeningHours::parse("not a valid expression").is_err());
Source

pub fn parse_with<F: FnMut(Warning<'_>)>( parser: &mut Parser<F>, raw_oh: &str, ) -> Result<Self, ParserError>

Use a specific parser configuration to parse an expression.

SourceΒ§

impl<L: Localize> OpeningHours<L>

Source

pub fn get_context(&self) -> &Context<L>

Get the evaluation context for this expression.

Source

pub fn get_expression(&self) -> Arc<OpeningHoursExpression>

Get the inner expression object.

Source

pub fn with_context<L2: Localize>(self, ctx: Context<L2>) -> OpeningHours<L2>

Set a new evaluation context for this expression.

use opening_hours::{Context, OpeningHours};

let oh = OpeningHours::parse("Mo-Fr open")
    .unwrap()
    .with_context(Context::default());
Source

pub fn normalize(&self) -> Self

Convert the expression into a normalized form. It will not affect the meaning of the expression and might impact the performance of evaluations.

use opening_hours::OpeningHours;

let oh = OpeningHours::parse("24/7 ; Su closed").unwrap();
assert_eq!(oh.normalize().to_string(), "Mo-Sa");
Β§Motivation

Normalization attempts to transform an expression into a minimal sequence of non-overlapping, normal rules. The goal is not to make the expression shorter but instead to make as readable as possible. For example, the additional operator , is less known and can be mistaken with any other kind of sequence (eg. in a day selector Mo,Fr).

Normalization is idempotent, which means that normalizing an already normalized expression won’t change the result.

Β§Examples
inputnormalized
Mo-Su 00:00-24:0024/7
24/7 ; Su closedMo-Sa
Mo-Su 10:00-12:00, Mo-Fr 14:00-18:00Mo-Fr 10:00-12:00,14:00-18:00; Sa-Su 10:00-12:00
10:00-18:00; Jul-Aug 10:00-22:00Jan-Jun,Sep-Dec 10:00-18:00; Jul-Aug 10:00-22:00
Mo-Fr,Su 10:00-18:00; Jul-Aug Su 10:00-22:00Mo-Fr 10:00-18:00; Jan-Jun,Sep-Dec Su 10:00-18:00; Jul-Aug Su 10:00-22:00
Β§Unsupported syntax

Not all syntax can be normalized, but this library will still do some best effort by normalizing the longest prefix possible and keeping all rules after the first unsupported one unchanged.

Here is an exhausting list of the kind of syntax you can’t expect to see normalized by current implementation:

kindbehaviorexample (1)
fallback rulestop normalization (2)Mo-Fr || unknown
any range with stepsstop normalization (2)2000-3000/5
monthday range with fixed datesstop normalization (2)Mar31-Jun01
monthday range with yearstop normalization (2)2025Jun-Aug
weekday range with index in monthstop normalization (2)Mo[2], Mo[2] +1 days
weekday range with a holidaystop normalization (2)easter
time that overlaps with next daystop normalization (2)22:00-06:00, 22:00-28:00
time with a solar eventno time simplification (3)sunrise-18:00
time with an open endno time simplification (3)12:00-16:00+
time with repetitionno time simplification (3)12:00-16:00/02:00

Notes :

  1. All the examples above contain a single rule, so they would be left unchanged by the normalization.
  2. This rule and any following rule won’t be treated.
  3. This won’t halt normalization but the algorithm won’t try to merge this time range with others.

If a feature is not implemented I may have considered it to be too niche for the effort. Feel free to open an issue on Github or open a merge request if you disagree!

Β§How it works
Β§Build a canonical time table

First, create a β€œcanonical” time table over 4 dimensions (year, month, weeknum, daynum), each cell keeps track of time ranges recorded for a single combination of intervals over those 4 dimensions. Cells are always non-overlapping and can be split while processing the expression if necessary.

For example, the resulting structure looks like this (simplified to 2 dimensions for obvious reasons):

    Mo    Sa  Su
Jan ╆━━━━━β”ͺ───┒━━━β”ͺ     Expression:
    ┃ (1) ┃   ┃(1)┃     Mo-Fr,Su 10:00-18:00; Jul-Aug Su 10:00-22:00
Jul β”¨β•Œβ•Œβ•Œβ•Œβ•Œβ”ƒβ”€β”€β”€β”£β”β”β”β”«
    ┃ (1) ┃   ┃(2)┃     Time rules:
Sep β”¨β•Œβ•Œβ•Œβ•Œβ•Œβ”ƒβ”€β”€β”€β”£β”β”β”β”«     (1) 10:00-18:00
    ┃ (1) ┃   ┃(1)┃     (2) 10:00-22:00
    ┗━━━━━┛───┗━━━┛
Β§Extract covering rectangles out of the table

Second, the algorithm will extract maximal rectangle in the table with all inner cells equal to the same value.

Step 1: extracted a rectangle
- weekday: Mo-Fr
- month: Jan-Dec
- time: 10:00-18:00

    Mo    Sa  Su
Jan ╆━━━━━β”ͺ───┒━━━┓     Expression:
    β”ƒβ–šβ–šβ–šβ–šβ–šβ”ƒ   ┃(1)┃     Mo-Fr,Su 10:00-18:00; Jul-Aug Su 10:00-22:00
Jul β”¨β–šβ–šβ–šβ–šβ–šβ”ƒβ”€β”€β”€β”£β”β”β”β”«
    β”ƒβ–šβ–šβ–šβ–šβ–šβ”ƒ   ┃(2)┃     Time rules:
Sep β”¨β–šβ–šβ–šβ–šβ–šβ”ƒβ”€β”€β”€β”£β”β”β”β”«     (1) 10:00-18:00
    β”ƒβ–šβ–šβ–šβ–šβ–šβ”ƒ   ┃(1)┃     (2) 10:00-22:00
    ┗━━━━━┛───┗━━━┛

Step 2: extracted a rectangle
- weekday: Su
- month: Jan-Jun,Sep-Dec
- time: 10:00-18:00

    Mo        Su
Jan ┼─────────┒━━━┓     Expression:
    β”‚         β”ƒβ–šβ–šβ–šβ”ƒ     Mo-Fr,Su 10:00-18:00; Jul-Aug Su 10:00-22:00
Jul ─         ┣━━━┫
    β”‚         ┃(2)┃     Time rules:
Sep ─         ┣━━━┫     (1) 10:00-18:00
    β”‚         β”ƒβ–šβ–šβ–šβ”ƒ     (2) 10:00-22:00
    └─────────┗━━━┛

Step 3: extracted a rectangle
- weekday: Su
- month: Jul-Aug
- time: 10:00-22:00

    Mo        Su
    β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”     Expression:
    β”‚         β”‚   β”‚     Mo-Fr,Su 10:00-18:00; Jul-Aug Su 10:00-22:00
Jul ─         ┏━━━┓
    β”‚         β”ƒβ–šβ–šβ–šβ”ƒ     Time rules:
Sep ─         ┗━━━┛     (1) 10:00-18:00
    β”‚         β”‚   β”‚     (2) 10:00-22:00
    β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”˜

The result is then the concatenation : Mo-Fr 10:00-18:00; Jan-Jun,Sep-Dec Su 10:00-18:00; Jul-Aug Su 10:00-22:00.

Source

pub fn schedule_at(&self, date: NaiveDate) -> Schedule

Get the schedule at a given day.

Source

pub fn iter_range( &self, from: L::DateTime, to: L::DateTime, ) -> impl Iterator<Item = DateTimeRange<L::DateTime>> + Send + Sync + use<L>

Iterate over disjoint intervals of different state restricted to the time interval from..to.

Source

pub fn iter_from( &self, from: L::DateTime, ) -> impl Iterator<Item = DateTimeRange<L::DateTime>> + Send + Sync + use<L>

Source

pub fn next_change(&self, current_time: L::DateTime) -> Option<L::DateTime>

Get the next time where the state will change.

use chrono::NaiveDateTime;
use opening_hours::OpeningHours;
use opening_hours_syntax::RuleKind;

let oh = OpeningHours::parse("12:00-18:00 open, 18:00-20:00 unknown").unwrap();
let date_1 = NaiveDateTime::parse_from_str("2024-11-18 15:00", "%Y-%m-%d %H:%M").unwrap();
let date_2 = NaiveDateTime::parse_from_str("2024-11-18 18:00", "%Y-%m-%d %H:%M").unwrap();
assert_eq!(oh.next_change(date_1), Some(date_2));
Source

pub fn state(&self, current_time: L::DateTime) -> (RuleKind, Arc<str>)

Get the state at given time.

use chrono::NaiveDateTime;
use opening_hours::OpeningHours;
use opening_hours_syntax::RuleKind;

let oh = OpeningHours::parse("12:00-18:00 open, 18:00-20:00 unknown").unwrap();
let date_1 = NaiveDateTime::parse_from_str("2024-11-18 15:00", "%Y-%m-%d %H:%M").unwrap();
let date_2 = NaiveDateTime::parse_from_str("2024-11-18 19:00", "%Y-%m-%d %H:%M").unwrap();
assert_eq!(oh.state(date_1), (RuleKind::Open, "".into()));
assert_eq!(oh.state(date_2), (RuleKind::Unknown, "".into()));
Source

pub fn is_open(&self, current_time: L::DateTime) -> bool

Check if this is open at a given time.

use chrono::NaiveDateTime;
use opening_hours::OpeningHours;

let oh = OpeningHours::parse("12:00-18:00 open, 18:00-20:00 unknown").unwrap();
let date_1 = NaiveDateTime::parse_from_str("2024-11-18 15:00", "%Y-%m-%d %H:%M").unwrap();
let date_2 = NaiveDateTime::parse_from_str("2024-11-18 19:00", "%Y-%m-%d %H:%M").unwrap();
assert!(oh.is_open(date_1));
assert!(!oh.is_open(date_2));
Source

pub fn is_closed(&self, current_time: L::DateTime) -> bool

Check if this is closed at a given time.

use chrono::NaiveDateTime;
use opening_hours::OpeningHours;

let oh = OpeningHours::parse("12:00-18:00 open, 18:00-20:00 unknown").unwrap();
let date_1 = NaiveDateTime::parse_from_str("2024-11-18 10:00", "%Y-%m-%d %H:%M").unwrap();
let date_2 = NaiveDateTime::parse_from_str("2024-11-18 19:00", "%Y-%m-%d %H:%M").unwrap();
assert!(oh.is_closed(date_1));
assert!(!oh.is_closed(date_2));
Source

pub fn is_unknown(&self, current_time: L::DateTime) -> bool

Check if this is unknown at a given time.

use chrono::NaiveDateTime;
use opening_hours::OpeningHours;

let oh = OpeningHours::parse("12:00-18:00 open, 18:00-20:00 unknown").unwrap();
let date_1 = NaiveDateTime::parse_from_str("2024-11-18 19:00", "%Y-%m-%d %H:%M").unwrap();
let date_2 = NaiveDateTime::parse_from_str("2024-11-18 15:00", "%Y-%m-%d %H:%M").unwrap();
assert!(oh.is_unknown(date_1));
assert!(!oh.is_unknown(date_2));

Trait ImplementationsΒ§

SourceΒ§

impl<L: Clone + Localize> Clone for OpeningHours<L>

SourceΒ§

fn clone(&self) -> OpeningHours<L>

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) Β· SourceΒ§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
SourceΒ§

impl<L: Debug + Localize> Debug for OpeningHours<L>

SourceΒ§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
SourceΒ§

impl<L: Localize> Display for OpeningHours<L>

SourceΒ§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
SourceΒ§

impl<L: Eq + Localize> Eq for OpeningHours<L>

SourceΒ§

impl FromStr for OpeningHours

SourceΒ§

type Err = Error

The associated error which can be returned from parsing.
SourceΒ§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
SourceΒ§

impl<L: Hash + Localize> Hash for OpeningHours<L>

SourceΒ§

fn hash<__H: Hasher>(&self, state: &mut __H)

Feeds this value into the given Hasher. Read more
1.3.0 Β· SourceΒ§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
SourceΒ§

impl<L: PartialEq + Localize> PartialEq for OpeningHours<L>

SourceΒ§

fn eq(&self, other: &OpeningHours<L>) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) Β· SourceΒ§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
SourceΒ§

impl<L: PartialEq + Localize> StructuralPartialEq for OpeningHours<L>

Auto Trait ImplementationsΒ§

Β§

impl<L> Freeze for OpeningHours<L>
where L: Freeze,

Β§

impl<L> RefUnwindSafe for OpeningHours<L>
where L: RefUnwindSafe,

Β§

impl<L> Send for OpeningHours<L>

Β§

impl<L> Sync for OpeningHours<L>

Β§

impl<L> Unpin for OpeningHours<L>
where L: Unpin,

Β§

impl<L> UnsafeUnpin for OpeningHours<L>
where L: UnsafeUnpin,

Β§

impl<L> UnwindSafe for OpeningHours<L>
where L: UnwindSafe,

Blanket ImplementationsΒ§

SourceΒ§

impl<T> Any for T
where T: 'static + ?Sized,

SourceΒ§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
SourceΒ§

impl<T> Borrow<T> for T
where T: ?Sized,

SourceΒ§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
SourceΒ§

impl<T> BorrowMut<T> for T
where T: ?Sized,

SourceΒ§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
SourceΒ§

impl<T> CloneToUninit for T
where T: Clone,

SourceΒ§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

πŸ”¬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
SourceΒ§

impl<T> From<T> for T

SourceΒ§

fn from(t: T) -> T

Returns the argument unchanged.

SourceΒ§

impl<T, U> Into<U> for T
where U: From<T>,

SourceΒ§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

SourceΒ§

impl<T> ToOwned for T
where T: Clone,

SourceΒ§

type Owned = T

The resulting type after obtaining ownership.
SourceΒ§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
SourceΒ§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
SourceΒ§

impl<T> ToString for T
where T: Display + ?Sized,

SourceΒ§

fn to_string(&self) -> String

Converts the given value to a String. Read more
SourceΒ§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

SourceΒ§

type Error = Infallible

The type returned in the event of a conversion error.
SourceΒ§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
SourceΒ§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

SourceΒ§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
SourceΒ§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.