rrule 0.14.0

A pure Rust implementation of recurrence rules as defined in the iCalendar RFC.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
use crate::core::datetime::datetime_to_ical_format;
use crate::core::utils::collect_with_error;
use crate::parser::{ContentLine, Grammar};
use crate::{ParseError, RRule, RRuleError, Tz};
use chrono::DateTime;
#[cfg(feature = "serde")]
use serde_with::{serde_as, DeserializeFromStr, SerializeDisplay};
use std::fmt::Display;
use std::str::FromStr;

/// A validated Recurrence Rule that can be used to create an iterator.
#[cfg_attr(feature = "serde", serde_as)]
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(DeserializeFromStr, SerializeDisplay))]
pub struct RRuleSet {
    /// List of rrules.
    pub(crate) rrule: Vec<RRule>,
    /// List of rdates.
    pub(crate) rdate: Vec<DateTime<Tz>>,
    /// List of exules.
    pub(crate) exrule: Vec<RRule>,
    /// List of exdates.
    pub(crate) exdate: Vec<DateTime<Tz>>,
    /// The start datetime of the recurring event.
    pub(crate) dt_start: DateTime<Tz>,
    /// If set, all returned recurrences must be before this date.
    pub(crate) before: Option<DateTime<Tz>>,
    /// If set, all returned recurrences must be after this date.
    pub(crate) after: Option<DateTime<Tz>>,
    /// If validation limits are enabled
    pub(crate) limited: bool,
}

/// The return result of `RRuleSet::all`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RRuleResult {
    /// List of recurrences.
    pub dates: Vec<DateTime<Tz>>,
    /// It is being true if the list of dates is limited.
    /// To indicate that it can potentially contain more dates.
    pub limited: bool,
}

impl RRuleSet {
    /// Creates an empty [`RRuleSet`], starting from `ds_start`.
    #[must_use]
    pub fn new(dt_start: DateTime<Tz>) -> Self {
        Self {
            dt_start,
            rrule: vec![],
            rdate: vec![],
            exrule: vec![],
            exdate: vec![],
            before: None,
            after: None,
            limited: false,
        }
    }

    /// Enable validation limits.
    ///
    /// This is only needed if you are going to use the Iterator api directly.
    #[must_use]
    pub fn limit(mut self) -> Self {
        self.limited = true;
        self
    }

    /// Only return recurrences that comes before this `DateTime`.
    ///
    /// This value will not be used if you use the `Iterator` API directly.
    #[must_use]
    pub fn before(mut self, dt: DateTime<Tz>) -> Self {
        self.before = Some(dt);
        self
    }

    /// Only return recurrences that comes after this `DateTime`.
    ///
    /// This value will not be used if you use the `Iterator` API directly.
    #[must_use]
    pub fn after(mut self, dt: DateTime<Tz>) -> Self {
        self.after = Some(dt);
        self
    }

    /// Adds a new rrule to the set.
    #[must_use]
    pub fn rrule(mut self, rrule: RRule) -> Self {
        self.rrule.push(rrule);
        self
    }

    /// Adds a new exrule to the set.
    #[must_use]
    #[cfg(feature = "exrule")]
    pub fn exrule(mut self, rrule: RRule) -> Self {
        self.exrule.push(rrule);
        self
    }

    /// Adds a new rdate to the set.
    #[must_use]
    pub fn rdate(mut self, rdate: DateTime<Tz>) -> Self {
        self.rdate.push(rdate);
        self
    }

    /// Adds a new exdate to the set.
    #[must_use]
    pub fn exdate(mut self, exdate: DateTime<Tz>) -> Self {
        self.exdate.push(exdate);
        self
    }

    /// Sets the rrules of the set.
    #[must_use]
    pub fn set_rrules(mut self, rrules: Vec<RRule>) -> Self {
        self.rrule = rrules;
        self
    }

    /// Sets the exrules of the set.
    #[must_use]
    #[cfg(feature = "exrule")]
    pub fn set_exrules(mut self, exrules: Vec<RRule>) -> Self {
        self.exrule = exrules;
        self
    }

    /// Sets the rdates of the set.
    #[must_use]
    pub fn set_rdates(mut self, rdates: Vec<DateTime<Tz>>) -> Self {
        self.rdate = rdates;
        self
    }

    /// Set the exdates of the set.
    #[must_use]
    pub fn set_exdates(mut self, exdates: Vec<DateTime<Tz>>) -> Self {
        self.exdate = exdates;
        self
    }

    /// Returns the rrules of the set.
    #[must_use]
    pub fn get_rrule(&self) -> &Vec<RRule> {
        &self.rrule
    }

    /// Returns the exrules of the set.
    #[must_use]
    pub fn get_exrule(&self) -> &Vec<RRule> {
        &self.exrule
    }

    /// Returns the rdates of the set.
    #[must_use]
    pub fn get_rdate(&self) -> &Vec<DateTime<Tz>> {
        &self.rdate
    }

    /// Returns the exdates of the set.
    #[must_use]
    pub fn get_exdate(&self) -> &Vec<DateTime<Tz>> {
        &self.exdate
    }

    /// Returns the start datetime of the recurring event.
    #[must_use]
    pub fn get_dt_start(&self) -> &DateTime<Tz> {
        &self.dt_start
    }

    /// Returns all the recurrences of the rrule.
    ///
    /// Limit must be set in order to prevent infinite loops.
    /// The max limit is `65535`. If you need more please use `into_iter` directly.
    ///
    /// # Usage
    ///
    /// ```
    /// use rrule::RRuleSet;
    ///
    /// let rrule_set: RRuleSet = "DTSTART:20210101T090000Z\nRRULE:FREQ=DAILY".parse().unwrap();
    ///
    /// // Limit the results to 2 recurrences
    /// let result = rrule_set.all(2);
    /// assert_eq!(result.dates.len(), 2);
    /// assert_eq!(result.limited, true);
    /// ```
    #[must_use]
    pub fn all(mut self, limit: u16) -> RRuleResult {
        self.limited = true;
        collect_with_error(
            self.into_iter(),
            &self.after,
            &self.before,
            true,
            Some(limit),
        )
    }

    /// Returns all the recurrences of the rrule.
    ///
    /// # Note
    ///
    /// This method does not enforce any validation limits and might lead to
    /// very long iteration times. Please read the `SECURITY.md` for more information.
    #[must_use]
    pub fn all_unchecked(self) -> Vec<DateTime<Tz>> {
        collect_with_error(self.into_iter(), &self.after, &self.before, true, None).dates
    }

    fn set_from_content_lines(self, content_lines: Vec<ContentLine>) -> Result<Self, RRuleError> {
        let dt_start = self.dt_start;

        content_lines.into_iter().try_fold(
            self,
            |rrule_set, content_line| match content_line {
                ContentLine::RRule(rrule) => rrule
                    .validate(dt_start)
                    .map(|rrule| rrule_set.rrule(rrule)),
                #[allow(unused_variables)]
                ContentLine::ExRule(exrule) => {
                    #[cfg(feature = "exrule")]
                    {
                        exrule
                            .validate(dt_start)
                            .map(|exrule| rrule_set.exrule(exrule))
                    }
                    #[cfg(not(feature = "exrule"))]
                    {
                        log::warn!("Found EXRULE in input, but it will be ignored since the `exrule` feature is not enabled.");
                        Ok(rrule_set)
                    }
                }
                ContentLine::ExDate(exdates) => {
                    Ok(exdates.into_iter().fold(rrule_set, Self::exdate))
                }
                ContentLine::RDate(rdates) => {
                    Ok(rdates.into_iter().fold(rrule_set, Self::rdate))
                }
            },
        )
    }

    /// Set the [`RRuleSet`] properties from a string. If a DTSTART is found, it will be used as the start datetime.
    pub fn set_from_string(mut self, s: &str) -> Result<Self, RRuleError> {
        let Grammar {
            start,
            content_lines,
        } = Grammar::from_str(s)?;

        if let Some(dtstart) = start {
            self.dt_start = dtstart.datetime;
        }

        self.set_from_content_lines(content_lines)
    }
}

impl FromStr for RRuleSet {
    type Err = RRuleError;

    /// Creates an [`RRuleSet`] from a string if input is valid.
    ///
    /// # Errors
    ///
    /// Returns [`RRuleError`], if iCalendar string contains invalid parts.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let Grammar {
            start,
            content_lines,
        } = Grammar::from_str(s)?;

        let start = start.ok_or(ParseError::MissingStartDate)?;

        Self::new(start.datetime).set_from_content_lines(content_lines)
    }
}

impl Display for RRuleSet {
    /// Prints a valid set of iCalendar properties which can be used to create a new [`RRuleSet`] later.
    /// You may use the generated string to create a new iCalendar component, like VEVENT.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let start_datetime = format!("DTSTART{}", datetime_to_ical_format(&self.dt_start));

        let mut rrules = self
            .rrule
            .iter()
            .map(|rrule| format!("RRULE:{rrule}"))
            .collect::<Vec<_>>()
            .join("\n");
        if !rrules.is_empty() {
            rrules = format!("\n{rrules}");
        }

        let mut rdates = self
            .rdate
            .iter()
            .map(|dt| {
                let maybe_zulu = if dt.timezone().is_local() { "" } else { "Z" };

                format!("{}{}", dt.format("%Y%m%dT%H%M%S"), maybe_zulu)
            })
            .collect::<Vec<_>>()
            .join(",");
        if !rdates.is_empty() {
            // TODO: check if original VALUE prop was DATE or PERIOD
            rdates = format!("\nRDATE;VALUE=DATE-TIME:{rdates}");
        }

        let mut exrules = self
            .exrule
            .iter()
            .map(|exrule| format!("EXRULE:{exrule}"))
            .collect::<Vec<_>>()
            .join("\n");
        if !exrules.is_empty() {
            exrules = format!("\n{exrules}");
        }

        let mut exdates = self
            .exdate
            .iter()
            .map(|dt| {
                let maybe_zulu = if dt.timezone().is_local() { "" } else { "Z" };

                format!("{}{}", dt.format("%Y%m%dT%H%M%S"), maybe_zulu)
            })
            .collect::<Vec<_>>()
            .join(",");
        if !exdates.is_empty() {
            // TODO: check if original VALUE prop was DATE or PERIOD
            exdates = format!("\nEXDATE;VALUE=DATE-TIME:{exdates}");
        }

        write!(f, "{start_datetime}{rrules}{rdates}{exrules}{exdates}")
    }
}

#[cfg(feature = "exrule")]
#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use chrono::{Month, TimeZone};

    use crate::{Frequency, RRule, RRuleSet, Tz};

    #[test]
    fn rruleset_string_roundtrip() {
        let rruleset_str = "DTSTART:20120201T093000Z\nRRULE:FREQ=DAILY;COUNT=3;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nRDATE;VALUE=DATE-TIME:19970101T000000Z,19970120T000000Z\nEXRULE:FREQ=YEARLY;COUNT=8;BYMONTH=6,7;BYMONTHDAY=1;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nEXDATE;VALUE=DATE-TIME:19970121T000000Z";
        let rruleset = RRuleSet::from_str(rruleset_str).unwrap();

        // Check start date
        let dt_start = Tz::UTC.with_ymd_and_hms(2012, 2, 1, 9, 30, 0).unwrap();
        assert_eq!(rruleset.dt_start, dt_start);

        // Check rrule
        assert_eq!(
            rruleset.rrule,
            vec![RRule::new(Frequency::Daily)
                .count(3)
                .validate(dt_start)
                .unwrap()]
        );

        // Check rdate
        assert_eq!(
            rruleset.rdate,
            vec![
                Tz::UTC.with_ymd_and_hms(1997, 1, 1, 0, 0, 0).unwrap(),
                Tz::UTC.with_ymd_and_hms(1997, 1, 20, 0, 0, 0).unwrap()
            ]
        );

        // Check exrule
        assert_eq!(
            rruleset.exrule,
            vec![RRule::new(Frequency::Yearly)
                .count(8)
                .by_month(&[Month::June, Month::July])
                .validate(dt_start)
                .unwrap()]
        );

        // Check exdate
        assert_eq!(
            rruleset.exdate,
            vec![Tz::UTC.with_ymd_and_hms(1997, 1, 21, 0, 0, 0).unwrap()]
        );

        // Serialize to string again
        assert_eq!(rruleset.to_string(), rruleset_str);
    }

    #[test]
    fn respect_local_timezone_in_exdates_rdates() {
        let rruleset_str = "DTSTART:20120201T093000Z\nRRULE:FREQ=DAILY;COUNT=3;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nRDATE;VALUE=DATE-TIME:19970101T000000,19970120T000000\nEXRULE:FREQ=YEARLY;COUNT=8;BYMONTH=6,7;BYMONTHDAY=1;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nEXDATE;VALUE=DATE-TIME:19970121T000000";
        let rruleset = RRuleSet::from_str(rruleset_str).unwrap();

        // Serialize to string again
        assert_eq!(rruleset.to_string(), rruleset_str);
    }

    #[test]
    fn respect_utc_timezone_in_exdates_rdates() {
        let rruleset_str = "DTSTART:20120201T093000Z\nRRULE:FREQ=DAILY;COUNT=3;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nRDATE;VALUE=DATE-TIME:19970101T000000Z,19970120T000000Z\nEXRULE:FREQ=YEARLY;COUNT=8;BYMONTH=6,7;BYMONTHDAY=1;BYHOUR=9;BYMINUTE=30;BYSECOND=0\nEXDATE;VALUE=DATE-TIME:19970121T000000Z";
        let rruleset = RRuleSet::from_str(rruleset_str).unwrap();

        // Serialize to string again
        assert_eq!(rruleset.to_string(), rruleset_str);
    }
}