1use jiff::civil::Date;
4use jiff::tz::TimeZone;
5use jiff::{SignedDuration, Span, Timestamp};
6
7use super::when::{When, midnight, next_day};
8
9pub const MAX_OCCURRENCES: usize = 5_000;
12
13#[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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
57pub enum Ends {
58 #[default]
59 Never,
60 After(u32),
62 On(Date),
64}
65
66#[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 pub fn interval(mut self, interval: u32) -> Self {
106 self.interval = interval.max(1);
107 self
108 }
109
110 pub fn count(mut self, count: u32) -> Self {
112 self.ends = Ends::After(count);
113 self
114 }
115
116 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 fn offset(&self, index: u32) -> Option<Span> {
136 self.frequency
137 .span(i64::from(index) * i64::from(self.interval))
138 }
139
140 fn longest(&self) -> i64 {
142 self.frequency
143 .longest()
144 .saturating_mul(i64::from(self.interval))
145 }
146}
147
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
150pub struct Instance {
151 pub index: u32,
153 pub start: Timestamp,
154 pub end: Timestamp,
156 pub all_day: bool,
157}
158
159pub 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
220fn 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
229pub 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
271const JUMPS: usize = 48;
273
274fn 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 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 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}