Skip to main content

iced_cube/data/calendar/rules/
when.rs

1//! Spans of time, and the date arithmetic they need.
2
3use jiff::civil::{Date, Time};
4use jiff::tz::TimeZone;
5use jiff::{Span, Timestamp};
6
7/// When something happens.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub enum When {
10    /// From one instant to another. `end` is not part of the span, so a
11    /// span ending at 10:00 does not overlap one starting at 10:00.
12    Timed { start: Timestamp, end: Timestamp },
13    /// Whole days, from `first` to `last` inclusive, in whatever time zone
14    /// the dates are read in.
15    AllDay { first: Date, last: Date },
16}
17
18impl When {
19    /// A timed span. The two instants are put in order.
20    pub fn timed(start: Timestamp, end: Timestamp) -> Self {
21        When::Timed {
22            start: start.min(end),
23            end: start.max(end),
24        }
25    }
26
27    /// Whole days. The two dates are put in order.
28    pub fn all_day(first: Date, last: Date) -> Self {
29        When::AllDay {
30            first: first.min(last),
31            last: first.max(last),
32        }
33    }
34
35    /// A single whole day.
36    pub fn day(date: Date) -> Self {
37        When::AllDay {
38            first: date,
39            last: date,
40        }
41    }
42
43    pub fn is_all_day(&self) -> bool {
44        matches!(self, When::AllDay { .. })
45    }
46
47    /// The first instant of the span in `time_zone`.
48    pub fn start(&self, time_zone: &TimeZone) -> Timestamp {
49        match *self {
50            When::Timed { start, .. } => start,
51            When::AllDay { first, .. } => midnight(first, time_zone),
52        }
53    }
54
55    /// The instant the span stops at in `time_zone`. For whole days this
56    /// is midnight after the last day.
57    pub fn end(&self, time_zone: &TimeZone) -> Timestamp {
58        match *self {
59            When::Timed { end, .. } => end,
60            When::AllDay { last, .. } => midnight(next_day(last), time_zone),
61        }
62    }
63}
64
65/// Midnight at the start of `date` in `time_zone`, or the first instant of
66/// the day when a clock change skips midnight.
67pub fn midnight(date: Date, time_zone: &TimeZone) -> Timestamp {
68    date.to_zoned_datetime(time_zone.clone())
69        .map(|zoned| zoned.timestamp())
70        .unwrap_or(Timestamp::MAX)
71}
72
73/// The instant it is `time` on `date` in `time_zone`. A time a clock
74/// change skips moves forward by the gap, and one that happens twice
75/// takes the first.
76///
77/// ```
78/// use iced_cube::data::calendar::instant;
79/// use jiff::civil::{date, time};
80/// use jiff::tz::TimeZone;
81///
82/// let nine = instant(date(2026, 11, 19), time(9, 0, 0, 0), &TimeZone::UTC);
83/// assert_eq!(nine.to_string(), "2026-11-19T09:00:00Z");
84/// ```
85pub fn instant(date: Date, time: Time, time_zone: &TimeZone) -> Timestamp {
86    date.to_datetime(time)
87        .to_zoned_datetime(time_zone.clone())
88        .map(|zoned| zoned.timestamp())
89        .unwrap_or_else(|_| midnight(date, time_zone))
90}
91
92/// The calendar date of `instant` in `time_zone`.
93pub fn date_of(instant: Timestamp, time_zone: &TimeZone) -> Date {
94    instant.to_zoned_datetime(time_zone.clone()).date()
95}
96
97/// `date` moved by `days`, stopping at the first or last date there is.
98pub fn add_days(date: Date, days: i32) -> Date {
99    match Span::new().try_days(i64::from(days)) {
100        Ok(span) => date.saturating_add(span),
101        Err(_) if days < 0 => Date::MIN,
102        Err(_) => Date::MAX,
103    }
104}
105
106/// The day after `date`, or `date` itself at the end of time.
107pub fn next_day(date: Date) -> Date {
108    add_days(date, 1)
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114    use jiff::civil::date;
115
116    fn at(day: i8, hour: i8) -> Timestamp {
117        instant(
118            date(2026, 11, day),
119            Time::new(hour, 0, 0, 0).unwrap_or_default(),
120            &TimeZone::UTC,
121        )
122    }
123
124    #[test]
125    fn days_are_added_and_stop_at_the_ends_of_time() {
126        let day = date(2026, 11, 3);
127        assert_eq!(add_days(day, 1), date(2026, 11, 4));
128        assert_eq!(add_days(day, -3), date(2026, 10, 31));
129        assert_eq!(add_days(day, i32::MAX), Date::MAX);
130        assert_eq!(add_days(day, i32::MIN), Date::MIN);
131        assert_eq!(next_day(date(2026, 12, 31)), date(2027, 1, 1));
132    }
133
134    #[test]
135    fn spans_are_put_in_order_and_whole_days_run_to_the_next_midnight() {
136        assert_eq!(
137            When::timed(at(3, 10), at(3, 9)),
138            When::Timed {
139                start: at(3, 9),
140                end: at(3, 10)
141            }
142        );
143        let days = When::all_day(date(2026, 11, 4), date(2026, 11, 3));
144        assert_eq!(days.start(&TimeZone::UTC), at(3, 0));
145        assert_eq!(days.end(&TimeZone::UTC), at(5, 0));
146        assert!(days.is_all_day());
147    }
148}