Skip to main content

iced_cube/data/calendar/
repeat.rs

1//! Repeating entries: how often, and expanding them into occurrences.
2
3use jiff::civil::Date;
4use jiff::tz::TimeZone;
5use jiff::{SignedDuration, Span, Timestamp};
6
7use super::entry::{Entry, Occurrence, When, midnight, next_day};
8
9/// The most occurrences one entry gives for a single range, so a rule
10/// that never ends cannot run away with a very long range.
11pub const MAX_OCCURRENCES: usize = 5_000;
12
13/// The unit an entry 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 entry 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 an entry repeats.
67///
68/// Occurrences are counted from the first, so an entry on the 31st that
69/// repeats monthly lands on the last day of shorter months and returns to
70/// the 31st afterwards. A timed entry 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 `count` repetitions can take, in seconds.
141    fn longest(&self, count: i64) -> i64 {
142        self.frequency
143            .longest()
144            .saturating_mul(i64::from(self.interval))
145            .saturating_mul(count)
146    }
147}
148
149/// Occurrence `index` of `entry`, or `None` once the entry has stopped
150/// repeating or the date is out of range.
151pub fn nth(entry: &Entry, time_zone: &TimeZone, index: u32) -> Option<Occurrence> {
152    let Some(repeat) = entry.repeat_of() else {
153        return (index == 0).then(|| first(entry, time_zone));
154    };
155    if let Ends::After(count) = repeat.ends()
156        && index >= count
157    {
158        return None;
159    }
160    let offset = repeat.offset(index)?;
161    let (start_date, start, end) = match entry.when() {
162        When::Timed { start, end } => {
163            let moved = start
164                .to_zoned_datetime(time_zone.clone())
165                .checked_add(offset)
166                .ok()?;
167            let length = end.duration_since(start);
168            let end = moved.timestamp().checked_add(length).ok()?;
169            (moved.date(), moved.timestamp(), end)
170        }
171        When::AllDay { first, last } => {
172            let moved = first.checked_add(offset).ok()?;
173            let length = last.duration_since(first);
174            let moved_last = moved.checked_add(length).ok()?;
175            (
176                moved,
177                midnight(moved, time_zone),
178                midnight(next_day(moved_last), time_zone),
179            )
180        }
181    };
182    if let Ends::On(date) = repeat.ends()
183        && start_date > date
184    {
185        return None;
186    }
187    Some(Occurrence {
188        entry: entry.id(),
189        index,
190        start,
191        end,
192        all_day: entry.is_all_day(),
193    })
194}
195
196fn first(entry: &Entry, time_zone: &TimeZone) -> Occurrence {
197    let when = entry.when();
198    Occurrence {
199        entry: entry.id(),
200        index: 0,
201        start: when.start(time_zone),
202        end: when.end(time_zone),
203        all_day: when.is_all_day(),
204    }
205}
206
207/// Whether `occurrence` overlaps the time from `from` up to `to`. An
208/// occurrence with no length counts when it starts inside the range.
209fn overlaps(occurrence: &Occurrence, from: Timestamp, to: Timestamp) -> bool {
210    if occurrence.end <= occurrence.start {
211        return occurrence.start >= from && occurrence.start < to;
212    }
213    occurrence.start < to && occurrence.end > from
214}
215
216/// The occurrences of `entry` that overlap the time from `from` up to
217/// `to`, earliest first. At most [`MAX_OCCURRENCES`] are returned.
218pub fn occurrences(
219    entry: &Entry,
220    time_zone: &TimeZone,
221    from: Timestamp,
222    to: Timestamp,
223) -> Vec<Occurrence> {
224    let Some(repeat) = entry.repeat_of() else {
225        let only = first(entry, time_zone);
226        return if overlaps(&only, from, to) {
227            vec![only]
228        } else {
229            Vec::new()
230        };
231    };
232
233    let mut found = Vec::new();
234    let mut index = first_candidate(entry, &repeat, time_zone, from);
235    for _ in 0..2 * MAX_OCCURRENCES {
236        if found.len() == MAX_OCCURRENCES {
237            break;
238        }
239        let Some(occurrence) = nth(entry, time_zone, index) else {
240            break;
241        };
242        if occurrence.start >= to {
243            break;
244        }
245        if overlaps(&occurrence, from, to) {
246            found.push(occurrence);
247        }
248        let Some(next) = index.checked_add(1) else {
249            break;
250        };
251        index = next;
252    }
253    found
254}
255
256/// How many times [`first_candidate`] jumps ahead at most.
257const JUMPS: usize = 48;
258
259fn landing(entry: &Entry, time_zone: &TimeZone, index: u32, jump: u32) -> Option<Occurrence> {
260    nth(entry, time_zone, index.checked_add(jump)?)
261}
262
263/// An index no later than the first occurrence that can reach `from`,
264/// found by jumping ahead by the longest each repetition can be.
265fn first_candidate(entry: &Entry, repeat: &Repeat, time_zone: &TimeZone, from: Timestamp) -> u32 {
266    let mut index: u32 = 0;
267    // Each jump lands short of `from`, and a handful get close enough.
268    for _ in 0..JUMPS {
269        let Some(occurrence) = nth(entry, time_zone, index) else {
270            break;
271        };
272        let short_by = from.duration_since(occurrence.end);
273        if short_by <= SignedDuration::ZERO {
274            break;
275        }
276        let jump = short_by.as_secs() / repeat.longest(1).max(1);
277        let mut jump = u32::try_from(jump).unwrap_or(u32::MAX - index);
278        // A jump past the end of the series is halved until it lands on it.
279        while jump > 0 && landing(entry, time_zone, index, jump).is_none() {
280            jump /= 2;
281        }
282        if jump == 0 {
283            break;
284        }
285        index = index.saturating_add(jump);
286    }
287    index
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293    use crate::data::calendar::entry::EntryId;
294    use jiff::civil::{date, time};
295
296    fn utc(year: i16, month: i8, day: i8, hour: i8) -> Timestamp {
297        zoned(&TimeZone::UTC, year, month, day, hour)
298    }
299
300    fn zoned(time_zone: &TimeZone, year: i16, month: i8, day: i8, hour: i8) -> Timestamp {
301        date(year, month, day)
302            .at(hour, 0, 0, 0)
303            .to_zoned_datetime(time_zone.clone())
304            .map(|zoned| zoned.timestamp())
305            .unwrap_or_default()
306    }
307
308    fn timed(start: Timestamp, repeat: Repeat) -> Entry {
309        let end = start
310            .checked_add(SignedDuration::from_hours(1))
311            .unwrap_or(start);
312        Entry::new(EntryId(1), "Repeats", start, end).repeat(repeat)
313    }
314
315    fn start_dates(entry: &Entry, time_zone: &TimeZone, count: u32) -> Vec<Date> {
316        (0..count)
317            .filter_map(|index| nth(entry, time_zone, index))
318            .map(|occurrence| occurrence.start.to_zoned_datetime(time_zone.clone()).date())
319            .collect()
320    }
321
322    #[test]
323    fn builder_defaults_and_options() {
324        for frequency in Frequency::ALL {
325            let repeat = Repeat::new(frequency);
326            assert_eq!(repeat.frequency(), frequency);
327            assert_eq!(repeat.every(), 1);
328            assert_eq!(repeat.ends(), Ends::Never);
329        }
330        assert_eq!(Repeat::daily().frequency(), Frequency::Daily);
331        assert_eq!(Repeat::weekly().frequency(), Frequency::Weekly);
332        assert_eq!(Repeat::monthly().frequency(), Frequency::Monthly);
333        assert_eq!(Repeat::yearly().frequency(), Frequency::Yearly);
334        assert_eq!(Repeat::daily().interval(0).every(), 1);
335        assert_eq!(Repeat::daily().interval(3).every(), 3);
336        assert_eq!(Repeat::daily().count(4).ends(), Ends::After(4));
337        let stop = date(2026, 12, 1);
338        assert_eq!(Repeat::daily().until(stop).ends(), Ends::On(stop));
339    }
340
341    #[test]
342    fn an_entry_that_does_not_repeat_has_one_occurrence() {
343        let start = utc(2026, 11, 3, 9);
344        let end = utc(2026, 11, 3, 10);
345        let entry = Entry::new(EntryId(1), "Once", start, end);
346        let first = nth(&entry, &TimeZone::UTC, 0);
347        assert_eq!(
348            first.map(|o| (o.index, o.start, o.end)),
349            Some((0, start, end))
350        );
351        assert_eq!(nth(&entry, &TimeZone::UTC, 1), None);
352    }
353
354    #[test]
355    fn daily_and_weekly_step_by_their_interval() {
356        let daily = timed(utc(2026, 11, 3, 9), Repeat::daily().interval(2));
357        assert_eq!(
358            start_dates(&daily, &TimeZone::UTC, 3),
359            vec![date(2026, 11, 3), date(2026, 11, 5), date(2026, 11, 7)]
360        );
361        let weekly = timed(utc(2026, 11, 3, 9), Repeat::weekly());
362        assert_eq!(
363            start_dates(&weekly, &TimeZone::UTC, 3),
364            vec![date(2026, 11, 3), date(2026, 11, 10), date(2026, 11, 17)]
365        );
366    }
367
368    #[test]
369    fn monthly_on_the_31st_uses_the_last_day_of_short_months() {
370        let entry = timed(utc(2027, 1, 31, 9), Repeat::monthly());
371        assert_eq!(
372            start_dates(&entry, &TimeZone::UTC, 4),
373            vec![
374                date(2027, 1, 31),
375                date(2027, 2, 28),
376                date(2027, 3, 31),
377                date(2027, 4, 30)
378            ]
379        );
380    }
381
382    #[test]
383    fn yearly_on_a_leap_day_falls_back_to_the_28th() {
384        let entry = Entry::all_day(EntryId(1), "Leap", date(2028, 2, 29), date(2028, 2, 29))
385            .repeat(Repeat::yearly());
386        assert_eq!(
387            start_dates(&entry, &TimeZone::UTC, 5),
388            vec![
389                date(2028, 2, 29),
390                date(2029, 2, 28),
391                date(2030, 2, 28),
392                date(2031, 2, 28),
393                date(2032, 2, 29)
394            ]
395        );
396    }
397
398    #[test]
399    fn a_timed_entry_keeps_its_local_time_across_a_clock_change() {
400        let Ok(london) = TimeZone::get("Europe/London") else {
401            panic!("the time zone database is bundled for tests");
402        };
403        // The clocks go forward on 28 March 2027.
404        let entry = timed(zoned(&london, 2027, 3, 27, 9), Repeat::daily());
405        for index in 0..3 {
406            let Some(occurrence) = nth(&entry, &london, index) else {
407                panic!("occurrence {index}");
408            };
409            let local = occurrence.start.to_zoned_datetime(london.clone());
410            assert_eq!(local.time(), time(9, 0, 0, 0), "{index}");
411            assert_eq!(occurrence.duration(), SignedDuration::from_hours(1));
412        }
413        let before = nth(&entry, &london, 0).map(|o| o.start);
414        let after = nth(&entry, &london, 1).map(|o| o.start);
415        let (Some(before), Some(after)) = (before, after) else {
416            panic!("two occurrences");
417        };
418        assert_eq!(after.duration_since(before), SignedDuration::from_hours(23));
419    }
420
421    #[test]
422    fn count_and_until_stop_the_series() {
423        let counted = timed(utc(2026, 11, 3, 9), Repeat::daily().count(3));
424        assert!(nth(&counted, &TimeZone::UTC, 2).is_some());
425        assert_eq!(nth(&counted, &TimeZone::UTC, 3), None);
426
427        let until = timed(
428            utc(2026, 11, 3, 9),
429            Repeat::daily().until(date(2026, 11, 5)),
430        );
431        assert_eq!(
432            start_dates(&until, &TimeZone::UTC, 10),
433            vec![date(2026, 11, 3), date(2026, 11, 4), date(2026, 11, 5)]
434        );
435
436        let never = timed(utc(2026, 11, 3, 9), Repeat::daily().count(0));
437        assert_eq!(nth(&never, &TimeZone::UTC, 0), None);
438    }
439
440    #[test]
441    fn whole_day_occurrences_keep_their_length() {
442        let entry = Entry::all_day(EntryId(1), "Sprint", date(2026, 11, 2), date(2026, 11, 4))
443            .repeat(Repeat::weekly().interval(2));
444        let Some(second) = nth(&entry, &TimeZone::UTC, 1) else {
445            panic!("second occurrence");
446        };
447        assert!(second.all_day);
448        assert_eq!(second.start, utc(2026, 11, 16, 0));
449        assert_eq!(second.end, utc(2026, 11, 19, 0));
450    }
451
452    #[test]
453    fn a_range_only_gets_the_occurrences_that_overlap_it() {
454        let entry = timed(utc(2026, 11, 3, 9), Repeat::daily());
455        let found = occurrences(
456            &entry,
457            &TimeZone::UTC,
458            utc(2026, 11, 10, 0),
459            utc(2026, 11, 12, 0),
460        );
461        let indices: Vec<_> = found.iter().map(|o| o.index).collect();
462        assert_eq!(indices, vec![7, 8]);
463
464        let before_it_starts = occurrences(
465            &entry,
466            &TimeZone::UTC,
467            utc(2026, 10, 1, 0),
468            utc(2026, 11, 1, 0),
469        );
470        assert!(before_it_starts.is_empty());
471    }
472
473    #[test]
474    fn a_range_far_from_the_start_is_found_without_walking_there() {
475        let entry = timed(utc(1990, 1, 1, 9), Repeat::daily());
476        let found = occurrences(
477            &entry,
478            &TimeZone::UTC,
479            utc(2026, 11, 3, 0),
480            utc(2026, 11, 4, 0),
481        );
482        assert_eq!(found.len(), 1);
483        assert_eq!(found[0].start, utc(2026, 11, 3, 9));
484
485        let monthly = timed(utc(1990, 1, 31, 9), Repeat::monthly());
486        let found = occurrences(
487            &monthly,
488            &TimeZone::UTC,
489            utc(2026, 11, 1, 0),
490            utc(2026, 12, 1, 0),
491        );
492        assert_eq!(found.len(), 1);
493        assert_eq!(found[0].start, utc(2026, 11, 30, 9));
494    }
495
496    #[test]
497    fn the_first_candidate_never_skips_an_occurrence() {
498        for repeat in [
499            Repeat::daily(),
500            Repeat::weekly().interval(3),
501            Repeat::monthly(),
502            Repeat::yearly(),
503        ] {
504            let entry = timed(utc(2001, 1, 31, 9), repeat);
505            let from = utc(2026, 6, 15, 0);
506            let index = first_candidate(&entry, &repeat, &TimeZone::UTC, from);
507            if index == 0 {
508                continue;
509            }
510            let Some(previous) = nth(&entry, &TimeZone::UTC, index - 1) else {
511                panic!("{repeat:?}");
512            };
513            assert!(previous.end <= from, "{repeat:?}");
514        }
515    }
516
517    #[test]
518    fn a_range_with_too_many_occurrences_is_capped() {
519        let entry = timed(utc(2000, 1, 1, 9), Repeat::daily());
520        let found = occurrences(
521            &entry,
522            &TimeZone::UTC,
523            utc(2000, 1, 1, 0),
524            utc(2100, 1, 1, 0),
525        );
526        assert_eq!(found.len(), MAX_OCCURRENCES);
527    }
528
529    #[test]
530    fn a_finished_series_gives_nothing_later() {
531        let entry = timed(utc(2026, 11, 3, 9), Repeat::weekly().count(2));
532        let found = occurrences(
533            &entry,
534            &TimeZone::UTC,
535            utc(2026, 12, 1, 0),
536            utc(2027, 1, 1, 0),
537        );
538        assert!(found.is_empty());
539    }
540}