Skip to main content

iced_cube/data/calendar/rules/
repeat.rs

1//! Repeating spans: how often, and expanding them into occurrences.
2
3use jiff::civil::Date;
4use jiff::tz::TimeZone;
5use jiff::{SignedDuration, Span, Timestamp};
6
7use super::when::{When, midnight, next_day};
8
9/// The most occurrences one span gives for a single range, so a rule that
10/// never ends cannot run away with a very long range.
11pub const MAX_OCCURRENCES: usize = 5_000;
12
13/// The unit a span repeats in.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
15pub enum Frequency {
16    Daily,
17    Weekly,
18    Monthly,
19    Yearly,
20}
21
22impl Frequency {
23    pub const ALL: [Frequency; 4] = [
24        Frequency::Daily,
25        Frequency::Weekly,
26        Frequency::Monthly,
27        Frequency::Yearly,
28    ];
29
30    /// The span of `count` units.
31    fn span(self, count: i64) -> Option<Span> {
32        let span = Span::new();
33        match self {
34            Frequency::Daily => span.try_days(count),
35            Frequency::Weekly => span.try_weeks(count),
36            Frequency::Monthly => span.try_months(count),
37            Frequency::Yearly => span.try_years(count),
38        }
39        .ok()
40    }
41
42    /// The longest one unit can be, in seconds. A day is 25 hours when the
43    /// clocks go back.
44    fn longest(self) -> i64 {
45        const DAY: i64 = 25 * 60 * 60;
46        match self {
47            Frequency::Daily => DAY,
48            Frequency::Weekly => 7 * DAY,
49            Frequency::Monthly => 31 * DAY,
50            Frequency::Yearly => 366 * DAY,
51        }
52    }
53}
54
55/// When a repeating span stops.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
57pub enum Ends {
58    #[default]
59    Never,
60    /// After this many occurrences, counting the first.
61    After(u32),
62    /// No occurrence starts after this date.
63    On(Date),
64}
65
66/// How a span repeats.
67///
68/// Occurrences are counted from the first, so a span on the 31st that
69/// repeats monthly lands on the last day of shorter months and returns to
70/// the 31st afterwards. A timed span keeps its local time across clock
71/// changes.
72#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
73pub struct Repeat {
74    frequency: Frequency,
75    interval: u32,
76    ends: Ends,
77}
78
79impl Repeat {
80    pub fn new(frequency: Frequency) -> Self {
81        Self {
82            frequency,
83            interval: 1,
84            ends: Ends::Never,
85        }
86    }
87
88    pub fn daily() -> Self {
89        Self::new(Frequency::Daily)
90    }
91
92    pub fn weekly() -> Self {
93        Self::new(Frequency::Weekly)
94    }
95
96    pub fn monthly() -> Self {
97        Self::new(Frequency::Monthly)
98    }
99
100    pub fn yearly() -> Self {
101        Self::new(Frequency::Yearly)
102    }
103
104    /// Repeats every `interval` units, such as every 2 weeks. At least 1.
105    pub fn interval(mut self, interval: u32) -> Self {
106        self.interval = interval.max(1);
107        self
108    }
109
110    /// Stops after `count` occurrences, counting the first.
111    pub fn count(mut self, count: u32) -> Self {
112        self.ends = Ends::After(count);
113        self
114    }
115
116    /// Stops once an occurrence would start after `date`.
117    pub fn until(mut self, date: Date) -> Self {
118        self.ends = Ends::On(date);
119        self
120    }
121
122    pub fn frequency(&self) -> Frequency {
123        self.frequency
124    }
125
126    pub fn every(&self) -> u32 {
127        self.interval
128    }
129
130    pub fn ends(&self) -> Ends {
131        self.ends
132    }
133
134    /// The span from the first occurrence to occurrence `index`.
135    fn offset(&self, index: u32) -> Option<Span> {
136        self.frequency
137            .span(i64::from(index) * i64::from(self.interval))
138    }
139
140    /// The longest one repetition can take, in seconds.
141    fn longest(&self) -> i64 {
142        self.frequency
143            .longest()
144            .saturating_mul(i64::from(self.interval))
145    }
146}
147
148/// One time a span happens.
149#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150pub struct Instance {
151    /// Which repetition this is, counted from 0.
152    pub index: u32,
153    pub start: Timestamp,
154    /// The instant the occurrence stops at, which is not part of it.
155    pub end: Timestamp,
156    pub all_day: bool,
157}
158
159/// Occurrence `index` of `when` repeating by `repeat`, or `None` once it
160/// has stopped repeating or the date is out of range. A span that does
161/// not repeat has only occurrence 0.
162pub fn nth(
163    when: When,
164    repeat: Option<Repeat>,
165    time_zone: &TimeZone,
166    index: u32,
167) -> Option<Instance> {
168    let Some(repeat) = repeat else {
169        return (index == 0).then(|| first(when, time_zone));
170    };
171    if let Ends::After(count) = repeat.ends()
172        && index >= count
173    {
174        return None;
175    }
176    let offset = repeat.offset(index)?;
177    let (start_date, start, end) = match when {
178        When::Timed { start, end } => {
179            let moved = start
180                .to_zoned_datetime(time_zone.clone())
181                .checked_add(offset)
182                .ok()?;
183            let length = end.duration_since(start);
184            let end = moved.timestamp().checked_add(length).ok()?;
185            (moved.date(), moved.timestamp(), end)
186        }
187        When::AllDay { first, last } => {
188            let moved = first.checked_add(offset).ok()?;
189            let length = last.duration_since(first);
190            let moved_last = moved.checked_add(length).ok()?;
191            (
192                moved,
193                midnight(moved, time_zone),
194                midnight(next_day(moved_last), time_zone),
195            )
196        }
197    };
198    if let Ends::On(date) = repeat.ends()
199        && start_date > date
200    {
201        return None;
202    }
203    Some(Instance {
204        index,
205        start,
206        end,
207        all_day: when.is_all_day(),
208    })
209}
210
211fn first(when: When, time_zone: &TimeZone) -> Instance {
212    Instance {
213        index: 0,
214        start: when.start(time_zone),
215        end: when.end(time_zone),
216        all_day: when.is_all_day(),
217    }
218}
219
220/// Whether `instance` overlaps the time from `from` up to `to`. One with no
221/// length counts when it starts inside the range.
222fn overlaps(instance: &Instance, from: Timestamp, to: Timestamp) -> bool {
223    if instance.end <= instance.start {
224        return instance.start >= from && instance.start < to;
225    }
226    instance.start < to && instance.end > from
227}
228
229/// The occurrences of `when` repeating by `repeat` that overlap the time
230/// from `from` up to `to`, earliest first. At most [`MAX_OCCURRENCES`] are
231/// returned.
232pub fn occurrences(
233    when: When,
234    repeat: Option<Repeat>,
235    time_zone: &TimeZone,
236    from: Timestamp,
237    to: Timestamp,
238) -> Vec<Instance> {
239    let Some(rule) = repeat else {
240        let only = first(when, time_zone);
241        return if overlaps(&only, from, to) {
242            vec![only]
243        } else {
244            Vec::new()
245        };
246    };
247
248    let mut found = Vec::new();
249    let mut index = first_candidate(when, rule, time_zone, from);
250    for _ in 0..2 * MAX_OCCURRENCES {
251        if found.len() == MAX_OCCURRENCES {
252            break;
253        }
254        let Some(instance) = nth(when, repeat, time_zone, index) else {
255            break;
256        };
257        if instance.start >= to {
258            break;
259        }
260        if overlaps(&instance, from, to) {
261            found.push(instance);
262        }
263        let Some(next) = index.checked_add(1) else {
264            break;
265        };
266        index = next;
267    }
268    found
269}
270
271/// How many times [`first_candidate`] jumps ahead at most.
272const JUMPS: usize = 48;
273
274/// An index no later than the first occurrence that can reach `from`,
275/// found by jumping ahead by the longest each repetition can be.
276fn first_candidate(when: When, repeat: Repeat, time_zone: &TimeZone, from: Timestamp) -> u32 {
277    let at = |index| nth(when, Some(repeat), time_zone, index);
278    let mut index: u32 = 0;
279    // Each jump lands short of `from`, and a handful get close enough.
280    for _ in 0..JUMPS {
281        let Some(instance) = at(index) else {
282            break;
283        };
284        let short_by = from.duration_since(instance.end);
285        if short_by <= SignedDuration::ZERO {
286            break;
287        }
288        let jump = short_by.as_secs() / repeat.longest().max(1);
289        let mut jump = u32::try_from(jump).unwrap_or(u32::MAX - index);
290        // A jump past the end of the series is halved until it lands on it.
291        while jump > 0 && index.checked_add(jump).and_then(at).is_none() {
292            jump /= 2;
293        }
294        if jump == 0 {
295            break;
296        }
297        index = index.saturating_add(jump);
298    }
299    index
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use crate::data::calendar::rules::instant;
306    use jiff::civil::{date, time};
307
308    fn utc(year: i16, month: i8, day: i8, hour: i8) -> Timestamp {
309        instant(date(year, month, day), time(hour, 0, 0, 0), &TimeZone::UTC)
310    }
311
312    fn hour_from(start: Timestamp) -> When {
313        let end = start
314            .checked_add(SignedDuration::from_hours(1))
315            .unwrap_or(start);
316        When::timed(start, end)
317    }
318
319    #[test]
320    fn a_span_that_does_not_repeat_has_one_occurrence() {
321        let when = hour_from(utc(2026, 6, 1, 9));
322        assert_eq!(
323            nth(when, None, &TimeZone::UTC, 0).map(|i| i.start),
324            Some(utc(2026, 6, 1, 9))
325        );
326        assert_eq!(nth(when, None, &TimeZone::UTC, 1), None);
327        let all = occurrences(
328            when,
329            None,
330            &TimeZone::UTC,
331            utc(2026, 1, 1, 0),
332            utc(2027, 1, 1, 0),
333        );
334        assert_eq!(all.len(), 1);
335    }
336
337    #[test]
338    fn whole_days_keep_their_length_and_count_stops_the_series() {
339        let when = When::all_day(date(2026, 6, 1), date(2026, 6, 2));
340        let rule = Repeat::weekly().count(2);
341        let all = occurrences(
342            when,
343            Some(rule),
344            &TimeZone::UTC,
345            utc(2026, 1, 1, 0),
346            utc(2027, 1, 1, 0),
347        );
348        assert_eq!(all.len(), 2);
349        assert!(all.iter().all(|instance| instance.all_day));
350        assert_eq!(all[1].start, utc(2026, 6, 8, 0));
351        assert_eq!(all[1].end, utc(2026, 6, 10, 0));
352    }
353
354    #[test]
355    fn the_first_candidate_never_skips_an_occurrence() {
356        for repeat in [
357            Repeat::daily(),
358            Repeat::weekly().interval(3),
359            Repeat::monthly(),
360            Repeat::yearly(),
361        ] {
362            let when = hour_from(utc(2001, 1, 31, 9));
363            let from = utc(2026, 6, 15, 0);
364            let index = first_candidate(when, repeat, &TimeZone::UTC, from);
365            if index == 0 {
366                continue;
367            }
368            let Some(previous) = nth(when, Some(repeat), &TimeZone::UTC, index - 1) else {
369                panic!("{repeat:?}");
370            };
371            assert!(previous.end <= from, "{repeat:?}");
372        }
373    }
374}