Debian Codegraph @

src/core/rrule.rs

raw symbols SCIP
1 use crate::core::get_day;
2 use crate::core::get_hour;
3 use crate::core::get_minute;
4 use crate::core::get_month;
5 use crate::core::get_second;
6 use crate::iter::RRuleIter;
7 use crate::parser::str_to_weekday;
8 use crate::parser::ContentLineCaptures;
9 use crate::parser::ParseError;
10 use crate::validator::validate_rrule;
11 use crate::validator::ValidationError;
12 use crate::Tz;
13 use crate::{RRuleError, RRuleSet, Unvalidated, Validated};
14 use chrono::DateTime;
15 use chrono::{Datelike, Month, Weekday};
16 #[cfg(feature = "serde")]
17 use serde_with::{serde_as, DeserializeFromStr, SerializeDisplay};
18 use std::cmp::Ordering;
19 use std::fmt::Display;
20 use std::fmt::Formatter;
21 use std::marker::PhantomData;
22 use std::str::FromStr;
23
24 #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)]
25 #[cfg_attr(feature = "serde", derive(DeserializeFromStr, SerializeDisplay))]
26 /// The frequency of a recurrence.
27 pub enum Frequency {
28 /// The recurrence occurs on a yearly basis.
29 Yearly = 0,
30 /// The recurrence occurs on a monthly basis.
31 Monthly = 1,
32 /// The recurrence occurs on a weekly basis.
33 Weekly = 2,
34 /// The recurrence occurs on a daily basis.
35 Daily = 3,
36 /// The recurrence occurs on an hourly basis.
37 Hourly = 4,
38 /// The recurrence occurs on a minutely basis.
39 Minutely = 5,
40 /// The recurrence occurs on a second basis.
41 Secondly = 6,
42 }
43
44 impl Display for Frequency {
45 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
46 let name = match self {
47 Self::Yearly => "YEARLY",
48 Self::Monthly => "MONTHLY",
49 Self::Weekly => "WEEKLY",
50 Self::Daily => "DAILY",
51 Self::Hourly => "HOURLY",
52 Self::Minutely => "MINUTELY",
53 Self::Secondly => "SECONDLY",
54 };
55 write!(f, "{}", name)
56 }
57 }
58
59 impl FromStr for Frequency {
60 type Err = ParseError;
61
62 fn from_str(value: &str) -> Result<Self, Self::Err> {
63 let freq = match &value.to_uppercase()[..] {
64 "YEARLY" => Self::Yearly,
65 "MONTHLY" => Self::Monthly,
66 "WEEKLY" => Self::Weekly,
67 "DAILY" => Self::Daily,
68 "HOURLY" => Self::Hourly,
69 "MINUTELY" => Self::Minutely,
70 "SECONDLY" => Self::Secondly,
71 val => return Err(ParseError::InvalidFrequency(val.to_string())),
72 };
73 Ok(freq)
74 }
75 }
76
77 /// This indicates the nth occurrence of a specific day within a MONTHLY or YEARLY RRULE.
78 ///
79 /// For example, `NWeekday::Nth(1, MO)` represents the first Monday within the month or year,
80 /// whereas `NWeekday::Nth(-1, MO)` represents the last Monday of the month or year.
81 /// And `NWeekday::Every(MO)`, means all Mondays of the month or year.
82 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
83 #[cfg_attr(feature = "serde", derive(DeserializeFromStr, SerializeDisplay))]
84 pub enum NWeekday {
85 /// When it is every weekday of the month or year.
86 Every(Weekday),
87 /// When it is the nth weekday of the month or year.
88 /// The first member's value is from -366 to -1 and 1 to 366 depending on frequency
89 Nth(i16, Weekday),
90 }
91
92 // The ordering here doesn't really matter as it is only used to sort for display purposes
93 fn n_weekday_cmp(val1: NWeekday, val2: NWeekday) -> Ordering {
94 match val1 {
95 NWeekday::Every(wday) => match val2 {
96 NWeekday::Every(other_wday) => wday
97 .num_days_from_monday()
98 .cmp(&other_wday.num_days_from_monday()),
99 NWeekday::Nth(_n, _other_wday) => Ordering::Less,
100 },
101 NWeekday::Nth(n, wday) => match val2 {
102 NWeekday::Every(_) => Ordering::Greater,
103 NWeekday::Nth(other_n, other_wday) => match n.cmp(&other_n) {
104 Ordering::Equal => wday
105 .num_days_from_monday()
106 .cmp(&other_wday.num_days_from_monday()),
107 less_or_greater => less_or_greater,
108 },
109 },
110 }
111 }
112
113 impl PartialOrd for NWeekday {
114 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
115 Some(self.cmp(other))
116 }
117 }
118
119 impl Ord for NWeekday {
120 fn cmp(&self, other: &Self) -> Ordering {
121 n_weekday_cmp(*self, *other)
122 }
123 }
124
125 impl NWeekday {
126 /// Creates a new week occurrence
127 ///
128 /// # Arguments
129 ///
130 /// * `n` - The nth occurrence of the week day. Should be between -366 and 366, and not 0.
131 /// * `weekday` - The week day
132 ///
133 /// # Example
134 ///
135 /// ```
136 /// use chrono::Weekday;
137 /// use rrule::NWeekday;
138 ///
139 /// let nth_weekday = NWeekday::new(Some(1), Weekday::Mon);
140 /// ```
141 #[must_use]
142 pub fn new(number: Option<i16>, weekday: Weekday) -> Self {
143 match number {
144 Some(number) => Self::Nth(number, weekday),
145 None => Self::Every(weekday),
146 }
147 }
148 }
149
150 impl FromStr for NWeekday {
151 type Err = ParseError;
152
153 /// Generates an [`NWeekday`] from a string.
154 fn from_str(value: &str) -> Result<Self, Self::Err> {
155 let length = value.len();
156
157 if length < 2 {
158 return Err(ParseError::InvalidWeekday(value.into()));
159 }
160
161 // it doesn't have any issue, because we checked the string is ASCII above
162 let wd = str_to_weekday(&value[(length - 2)..])
163 .map_err(|_| ParseError::InvalidWeekday(value.into()))?;
164 let nth = value[..(length - 2)].parse::<i16>().unwrap_or_default();
165
166 if nth == 0 {
167 Ok(Self::Every(wd))
168 } else {
169 Ok(Self::new(Some(nth), wd))
170 }
171 }
172 }
173
174 impl Display for NWeekday {
175 /// Returns a string representation of the [`NWeekday`]
176 ///
177 /// ```
178 /// use chrono::Weekday;
179 /// use rrule::NWeekday;
180 ///
181 /// assert_eq!(format!("{}", NWeekday::Every(Weekday::Mon)), "MO");
182 /// assert_eq!(format!("{}", NWeekday::Nth(1, Weekday::Mon)), "MO");
183 /// assert_eq!(format!("{}", NWeekday::Nth(2, Weekday::Mon)), "2MO");
184 /// ```
185 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
186 let weekday = match self {
187 Self::Every(wd) => weekday_to_str(*wd),
188 Self::Nth(number, wd) => {
189 let mut wd_str = weekday_to_str(*wd);
190 if *number != 1 {
191 wd_str = format!("{}{}", number, wd_str);
192 };
193 wd_str
194 }
195 };
196
197 write!(f, "{}", weekday)
198 }
199 }
200
201 fn weekday_to_str(d: Weekday) -> String {
202 match d {
203 Weekday::Mon => "MO".to_string(),
204 Weekday::Tue => "TU".to_string(),
205 Weekday::Wed => "WE".to_string(),
206 Weekday::Thu => "TH".to_string(),
207 Weekday::Fri => "FR".to_string(),
208 Weekday::Sat => "SA".to_string(),
209 Weekday::Sun => "SU".to_string(),
210 }
211 }
212
213 /// Represents a complete RRULE property based on the [iCalendar specification](https://datatracker.ietf.org/doc/html/rfc5545#section-3.8.5.3)
214 /// It has two stages, based on the attached type, `Validated` or `Unvalidated`.
215 /// - `Unvalidated`, which is the raw string representation of the RRULE
216 /// - `Validated`, which is when the `RRule` has been parsed and validated, based on the start date
217 #[derive(Debug, Clone, PartialEq, Eq)]
218 #[cfg_attr(feature = "serde", serde_as)]
219 #[cfg_attr(feature = "serde", derive(DeserializeFromStr, SerializeDisplay))]
220 pub struct RRule<Stage = Validated> {
221 /// The frequency of the rrule.
222 /// For example, yearly, weekly, hourly
223 pub(crate) freq: Frequency,
224 /// The interval between each frequency iteration.
225 /// For example,
226 /// - A yearly frequency with an interval of `2` creates 1 event every two years.
227 /// - An hourly frequency with an interval of `2` created 1 event every two hours.
228 pub(crate) interval: u16,
229 /// How many occurrences will be generated.
230 pub(crate) count: Option<u32>,
231 /// The end date after which new events will no longer be generated.
232 /// If the `DateTime` is equal to an instance of the event, it will be the last event.
233 #[cfg_attr(feature = "serde", serde_as(as = "DisplayFromStr"))]
234 pub(crate) until: Option<DateTime<Tz>>,
235 /// The start day of the week.
236 /// This will affect recurrences based on weekly periods.
237 pub(crate) week_start: Weekday,
238 /// Occurrence number corresponding to the frequency period.
239 /// For example:
240 /// - A monthly frequency with an `by_set_pos` of `-1` meaning the last day of the month.
241 /// - An hourly frequency with an `by_set_pos` of `2` meaning the 2nd hour. (TODO Check)
242 pub(crate) by_set_pos: Vec<i32>,
243 /// The months to apply the recurrence to.
244 /// Can be a value from 1 to 12.
245 pub(crate) by_month: Vec<u8>,
246 /// The month days to apply the recurrence to.
247 /// Can be a value from -31 to -1 and 1 to 31.
248 pub(crate) by_month_day: Vec<i8>,
249 pub(crate) by_n_month_day: Vec<i8>,
250 /// The year days to apply the recurrence to.
251 /// Can be a value from -366 to -1 and 1 to 366.
252 pub(crate) by_year_day: Vec<i16>,
253 /// The week numbers to apply the recurrence to.
254 /// Week numbers have the meaning described in ISO8601, that is,
255 /// the first week of the year is that it contains at least four days of the new year.
256 /// Week day starts counting on from `week_start` value.
257 /// Can be a value from -53 to -1 and 1 to 53.
258 pub(crate) by_week_no: Vec<i8>,
259 /// The days of the week the rules should be recurring.
260 /// Should be a value of `Weekday` and optionally with a prefix of -366 to 366 depending on frequency.
261 /// Corresponds with `BYDAY` field.
262 pub(crate) by_weekday: Vec<NWeekday>,
263 /// The hours to apply the recurrence to.
264 /// Can be a value from 0 to 23.
265 pub(crate) by_hour: Vec<u8>,
266 /// The minutes to apply the recurrence to.
267 /// Can be a value from 0 to 59.
268 pub(crate) by_minute: Vec<u8>,
269 /// The seconds to apply the recurrence to.
270 /// Can be a value from 0 to 59.
271 pub(crate) by_second: Vec<u8>,
272 /// Extension, not part of RFC spec.
273 /// Amount of days/months from Easter Sunday itself.
274 /// Can be a value from -366 to 366.
275 /// Note: Only used when `by-easter` feature flag is set. Otherwise, it is ignored.
276 pub(crate) by_easter: Option<i16>,
277 /// A phantom data to have the stage (unvalidated or validated).
278 #[cfg_attr(feature = "serde", serde_as(as = "ignore"))]
279 pub(crate) stage: PhantomData<Stage>,
280 }
281
282 impl Default for RRule<Unvalidated> {
283 /// Creates a new unvalidated `RRule` with default values and Yearly frequency.
284 fn default() -> Self {
285 Self {
286 freq: Frequency::Yearly,
287 interval: 1,
288 count: None,
289 until: None,
290 week_start: Weekday::Mon,
291 by_set_pos: Vec::new(),
292 by_month: Vec::new(),
293 by_month_day: Vec::new(),
294 by_n_month_day: Vec::new(),
295 by_year_day: Vec::new(),
296 by_week_no: Vec::new(),
297 by_weekday: Vec::new(),
298 by_hour: Vec::new(),
299 by_minute: Vec::new(),
300 by_second: Vec::new(),
301 by_easter: None,
302 stage: PhantomData,
303 }
304 }
305 }
306
307 impl RRule<Unvalidated> {
308 /// Creates a new unvalidated `RRule` with default values and the given frequency.
309 #[must_use]
310 pub fn new(freq: Frequency) -> Self {
311 Self {
312 freq,
313 ..Self::default()
314 }
315 }
316
317 /// The FREQ rule part identifies the type of recurrence rule.
318 #[must_use]
319 pub fn freq(mut self, freq: Frequency) -> Self {
320 self.freq = freq;
321 self
322 }
323
324 /// The interval between each freq iteration.
325 #[must_use]
326 pub fn interval(mut self, interval: u16) -> Self {
327 self.interval = interval;
328 self
329 }
330
331 /// If given, this determines how many occurrences will be generated.
332 #[must_use]
333 pub fn count(mut self, count: u32) -> Self {
334 self.count = Some(count);
335 self
336 }
337
338 /// If given, this must be a datetime instance specifying the
339 /// upper-bound limit of the recurrence.
340 #[must_use]
341 pub fn until(mut self, until: DateTime<Tz>) -> Self {
342 self.until = Some(until);
343 self
344 }
345
346 /// The week start day. This will affect recurrences based on weekly periods.
347 /// The default week start is [`Weekday::Mon`].
348 #[must_use]
349 pub fn week_start(mut self, week_start: Weekday) -> Self {
350 self.week_start = week_start;
351 self
352 }
353
354 /// If given, it must be either an integer, or a sequence of integers, positive or negative.
355 /// Each given integer will specify an occurrence number, corresponding to the nth occurrence
356 /// of the rule inside the frequency period. For example, a `by_set_pos` of -1 if combined with
357 /// a MONTHLY frequency, and a `by_weekday` of (MO, TU, WE, TH, FR), will result in the last
358 /// work day of every month.
359 #[must_use]
360 pub fn by_set_pos(mut self, by_set_pos: Vec<i32>) -> Self {
361 self.by_set_pos = by_set_pos;
362 self
363 }
364
365 /// When given, these variables will define the months to apply the recurrence to.
366 #[must_use]
367 pub fn by_month(mut self, by_month: &[Month]) -> Self {
368 self.by_month = by_month
369 .iter()
370 .map(|month| {
371 u8::try_from(month.number_from_month()).expect("1-12 is within range of u8")
372 })
373 .collect();
374 self
375 }
376
377 /// If given, it must be either an integer, or a sequence of integers, meaning
378 /// the month days to apply the recurrence to.
379 #[must_use]
380 pub fn by_month_day(mut self, by_month_day: Vec<i8>) -> Self {
381 self.by_month_day = by_month_day;
382 self
383 }
384
385 /// If given, it must be either an integer, or a sequence of integers, meaning
386 /// the year days to apply the recurrence to.
387 #[must_use]
388 pub fn by_year_day(mut self, by_year_day: Vec<i16>) -> Self {
389 self.by_year_day = by_year_day;
390 self
391 }
392
393 /// If given, it must be either an integer, or a sequence of integers, meaning
394 /// the week numbers to apply the recurrence to. Week numbers have the meaning
395 /// described in ISO8601, that is, the first week of the year is that it contains
396 /// at least four days of the new year.
397 #[must_use]
398 pub fn by_week_no(mut self, by_week_no: Vec<i8>) -> Self {
399 self.by_week_no = by_week_no;
400 self
401 }
402
403 /// When given, these variables will define the weekdays where the recurrence
404 /// will be applied.
405 #[must_use]
406 pub fn by_weekday(mut self, by_weekday: Vec<NWeekday>) -> Self {
407 self.by_weekday = by_weekday;
408 self
409 }
410
411 /// If given, it must be either an integer, or a sequence of integers,
412 /// meaning the hours to apply the recurrence to.
413 #[must_use]
414 pub fn by_hour(mut self, by_hour: Vec<u8>) -> Self {
415 self.by_hour = by_hour;
416 self
417 }
418
419 /// If given, it must be either an integer, or a sequence of integers,
420 /// meaning the minutes to apply the recurrence to.
421 #[must_use]
422 pub fn by_minute(mut self, by_minute: Vec<u8>) -> Self {
423 self.by_minute = by_minute;
424 self
425 }
426
427 /// If given, it must be either an integer, or a sequence of integers,
428 /// meaning the seconds to apply the recurrence to.
429 #[must_use]
430 pub fn by_second(mut self, by_second: Vec<u8>) -> Self {
431 self.by_second = by_second;
432 self
433 }
434
435 /// If given, it must be either an integer, or a sequence of integers, positive or negative.
436 /// Each integer will define an offset from the Easter Sunday. Passing the offset 0 to
437 /// `by_easter` will yield the Easter Sunday itself. This is an extension to the RFC specification.
438 #[cfg(feature = "by-easter")]
439 #[must_use]
440 pub fn by_easter(mut self, by_easter: i16) -> Self {
441 self.by_easter = Some(by_easter);
442 self
443 }
444
445 /// Fills in some additional fields in order to make iter work correctly.
446 pub(crate) fn finalize_parsed_rrule(mut self, dt_start: &DateTime<Tz>) -> Self {
447 // TEMP: move negative months to another list
448 let mut by_month_day = vec![];
449 let mut by_n_month_day = self.by_n_month_day;
450 for by_month_day_item in self.by_month_day {
451 match by_month_day_item.cmp(&0) {
452 Ordering::Greater => by_month_day.push(by_month_day_item),
453 Ordering::Less => by_n_month_day.push(by_month_day_item),
454 Ordering::Equal => {}
455 }
456 }
457 self.by_month_day = by_month_day;
458 self.by_n_month_day = by_n_month_day;
459
460 // Can only be set to true if the feature flag is set.
461 let by_easter_is_some = if cfg!(feature = "by-easter") {
462 self.by_easter.is_some()
463 } else {
464 false
465 };
466
467 // Add some freq-specific additional properties
468 if !(!self.by_week_no.is_empty()
469 || !self.by_year_day.is_empty()
470 || !self.by_month_day.is_empty()
471 || !self.by_n_month_day.is_empty()
472 || !self.by_weekday.is_empty()
473 || by_easter_is_some)
474 {
475 match self.freq {
476 Frequency::Yearly => {
477 if self.by_month.is_empty() {
478 let month = get_month(dt_start);
479 self.by_month = vec![month];
480 }
481 let day = get_day(dt_start);
482 self.by_month_day = vec![day];
483 }
484 Frequency::Monthly => {
485 let day = get_day(dt_start);
486 self.by_month_day = vec![day];
487 }
488 Frequency::Weekly => {
489 self.by_weekday = vec![NWeekday::Every(dt_start.weekday())];
490 }
491 _ => (),
492 };
493 }
494
495 // by_hour
496 if self.by_hour.is_empty() && self.freq < Frequency::Hourly {
497 let hour = get_hour(dt_start);
498 self.by_hour = vec![hour];
499 }
500
501 // by_minute
502 if self.by_minute.is_empty() && self.freq < Frequency::Minutely {
503 let minute = get_minute(dt_start);
504 self.by_minute = vec![minute];
505 }
506
507 // by_second
508 if self.by_second.is_empty() && self.freq < Frequency::Secondly {
509 let second = get_second(dt_start);
510 self.by_second = vec![second];
511 }
512
513 // make sure all BYXXX are unique and sorted
514 self.by_hour.sort_unstable();
515 self.by_hour.dedup();
516
517 self.by_minute.sort_unstable();
518 self.by_minute.dedup();
519
520 self.by_second.sort_unstable();
521 self.by_second.dedup();
522
523 self.by_month.sort_unstable();
524 self.by_month.dedup();
525
526 self.by_month_day.sort_unstable();
527 self.by_month_day.dedup();
528
529 self.by_n_month_day.sort_unstable();
530 self.by_n_month_day.dedup();
531
532 self.by_year_day.sort_unstable();
533 self.by_year_day.dedup();
534
535 self.by_week_no.sort_unstable();
536 self.by_week_no.dedup();
537
538 self.by_set_pos.sort_unstable();
539 self.by_set_pos.dedup();
540
541 self.by_weekday.sort_unstable();
542 self.by_weekday.dedup();
543
544 self
545 }
546
547 /// Validates the [`RRule`] with the given `dt_start`.
548 ///
549 /// # Errors
550 ///
551 /// If the properties aren't valid, it will return [`RRuleError`].
552 pub fn validate(self, dt_start: DateTime<Tz>) -> Result<RRule<Validated>, RRuleError> {
553 let rrule = self.finalize_parsed_rrule(&dt_start);
554
555 // Validate required checks (defined by RFC 5545)
556 validate_rrule::validate_rrule_forced(&rrule, &dt_start)?;
557
558 // Check if it is possible to generate a timeset
559 match rrule.freq {
560 Frequency::Hourly => {
561 if rrule.by_minute.is_empty() && rrule.by_second.is_empty() {
562 return Err(ValidationError::UnableToGenerateTimeset.into());
563 }
564 }
565 Frequency::Minutely => {
566 if rrule.by_second.is_empty() {
567 return Err(ValidationError::UnableToGenerateTimeset.into());
568 }
569 }
570 Frequency::Secondly => {}
571 _ => {
572 if rrule.by_hour.is_empty()
573 && rrule.by_minute.is_empty()
574 && rrule.by_second.is_empty()
575 {
576 return Err(ValidationError::UnableToGenerateTimeset.into());
577 }
578 }
579 }
580
581 Ok(RRule {
582 freq: rrule.freq,
583 interval: rrule.interval,
584 count: rrule.count,
585 until: rrule.until,
586 week_start: rrule.week_start,
587 by_set_pos: rrule.by_set_pos,
588 by_month: rrule.by_month,
589 by_month_day: rrule.by_month_day,
590 by_n_month_day: rrule.by_n_month_day,
591 by_year_day: rrule.by_year_day,
592 by_week_no: rrule.by_week_no,
593 by_weekday: rrule.by_weekday,
594 by_hour: rrule.by_hour,
595 by_minute: rrule.by_minute,
596 by_second: rrule.by_second,
597 by_easter: rrule.by_easter,
598 stage: PhantomData,
599 })
600 }
601
602 /// Validates the [`RRule`] with the given `dt_start` and creates an [`RRuleSet`] struct.
603 ///
604 /// # Errors
605 ///
606 /// Returns [`RRuleError::ValidationError`] in case the rrule is invalid.
607 pub fn build(self, dt_start: DateTime<Tz>) -> Result<RRuleSet, RRuleError> {
608 let rrule = self.validate(dt_start)?;
609 let rrule_set = RRuleSet::new(dt_start).rrule(rrule);
610 Ok(rrule_set)
611 }
612 }
613
614 impl RRule {
615 pub(crate) fn iter_with_ctx(&self, dt_start: DateTime<Tz>, limited: bool) -> RRuleIter {
616 RRuleIter::new(self, &dt_start, limited)
617 }
618 }
619
620 impl FromStr for RRule<Unvalidated> {
621 type Err = RRuleError;
622
623 fn from_str(s: &str) -> Result<Self, Self::Err> {
624 let parts = ContentLineCaptures::new(s)?;
625 Self::try_from(parts).map_err(From::from)
626 }
627 }
628
629 impl<S> Display for RRule<S> {
630 /// Generates a string based on the [iCalendar RRULE spec](https://datatracker.ietf.org/doc/html/rfc5545#section-3.8.5.3).
631 /// It doesn't prepend "RRULE:" to the string.
632 /// When you call this function on [`RRule<Unvalidated>`], it can generate an invalid string, like 'FREQ=YEARLY;INTERVAL=-1'
633 /// But it is supposed to always generate a valid string on [`RRule<Validated>`].
634 /// So if you want a valid string, it's smarter to always use `rrule.validate(ds_start)?.to_string()`.
635 #[allow(clippy::too_many_lines)]
636 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
637 let mut res = Vec::with_capacity(15);
638 res.push(format!("FREQ={}", &self.freq));
639
640 if let Some(until) = &self.until {
641 let maybe_zulu = if until.timezone().is_local() { "" } else { "Z" };
642 res.push(format!(
643 "UNTIL={}{}",
644 until.format("%Y%m%dT%H%M%S"),
645 maybe_zulu
646 ));
647 }
648
649 if let Some(count) = &self.count {
650 res.push(format!("COUNT={}", count));
651 }
652
653 // One interval is the default, no need to expose it.
654 if self.interval != 1 {
655 res.push(format!("INTERVAL={}", &self.interval));
656 }
657
658 // Monday is the default, no need to expose it.
659 if self.week_start != Weekday::Mon {
660 res.push(format!("WKST={}", weekday_to_str(self.week_start)));
661 }
662
663 if !self.by_set_pos.is_empty() {
664 res.push(format!(
665 "BYSETPOS={}",
666 self.by_set_pos
667 .iter()
668 .map(ToString::to_string)
669 .collect::<Vec<_>>()
670 .join(",")
671 ));
672 }
673
674 if !self.by_month.is_empty() {
675 res.push(format!(
676 "BYMONTH={}",
677 self.by_month
678 .iter()
679 .map(ToString::to_string)
680 .collect::<Vec<_>>()
681 .join(",")
682 ));
683 }
684
685 if !self.by_month_day.is_empty() {
686 res.push(format!(
687 "BYMONTHDAY={}",
688 self.by_month_day
689 .iter()
690 .map(ToString::to_string)
691 .collect::<Vec<_>>()
692 .join(",")
693 ));
694 }
695
696 if !self.by_week_no.is_empty() {
697 res.push(format!(
698 "BYWEEKNO={}",
699 self.by_week_no
700 .iter()
701 .map(ToString::to_string)
702 .collect::<Vec<_>>()
703 .join(",")
704 ));
705 }
706
707 if !self.by_hour.is_empty() {
708 res.push(format!(
709 "BYHOUR={}",
710 self.by_hour
711 .iter()
712 .map(ToString::to_string)
713 .collect::<Vec<_>>()
714 .join(",")
715 ));
716 }
717
718 if !self.by_minute.is_empty() {
719 res.push(format!(
720 "BYMINUTE={}",
721 self.by_minute
722 .iter()
723 .map(ToString::to_string)
724 .collect::<Vec<_>>()
725 .join(",")
726 ));
727 }
728
729 if !self.by_second.is_empty() {
730 res.push(format!(
731 "BYSECOND={}",
732 self.by_second
733 .iter()
734 .map(ToString::to_string)
735 .collect::<Vec<_>>()
736 .join(",")
737 ));
738 }
739
740 if !self.by_year_day.is_empty() {
741 res.push(format!(
742 "BYYEARDAY={}",
743 self.by_year_day
744 .iter()
745 .map(ToString::to_string)
746 .collect::<Vec<_>>()
747 .join(",")
748 ));
749 }
750
751 if !self.by_weekday.is_empty() {
752 res.push(format!(
753 "BYDAY={}",
754 self.by_weekday
755 .iter()
756 .map(ToString::to_string)
757 .collect::<Vec<_>>()
758 .join(",")
759 ));
760 }
761
762 #[cfg(feature = "by-easter")]
763 if let Some(by_easter) = &self.by_easter {
764 res.push(format!("BYEASTER={}", by_easter));
765 }
766
767 write!(f, "{}", res.join(";"))
768 }
769 }
770
771 impl<S> RRule<S> {
772 /// Get the frequency of the recurrence.
773 #[must_use]
774 pub fn get_freq(&self) -> Frequency {
775 self.freq
776 }
777
778 /// Get the interval of the recurrence.
779 #[must_use]
780 pub fn get_interval(&self) -> u16 {
781 self.interval
782 }
783
784 /// Get the count of the recurrence.
785 #[must_use]
786 pub fn get_count(&self) -> Option<u32> {
787 self.count
788 }
789
790 /// Get the until of the recurrence.
791 #[must_use]
792 pub fn get_until(&self) -> Option<&DateTime<Tz>> {
793 self.until.as_ref()
794 }
795
796 /// Get the `by_set_pos` of the recurrence.
797 #[must_use]
798 pub fn get_week_start(&self) -> Weekday {
799 self.week_start
800 }
801
802 /// Get the `by_month` of the recurrence.
803 #[must_use]
804 pub fn get_by_set_pos(&self) -> &[i32] {
805 &self.by_set_pos
806 }
807
808 /// Get the `by_month` of the recurrence.
809 #[must_use]
810 pub fn get_by_month(&self) -> &[u8] {
811 &self.by_month
812 }
813
814 /// Get the `by_month_day` of the recurrence.
815 #[must_use]
816 pub fn get_by_month_day(&self) -> &[i8] {
817 &self.by_month_day
818 }
819
820 /// Get the `by_year_day` of the recurrence.
821 #[must_use]
822 pub fn get_by_year_day(&self) -> &[i16] {
823 &self.by_year_day
824 }
825
826 /// Get the `by_hour` of the recurrence.
827 #[must_use]
828 pub fn get_by_week_no(&self) -> &[i8] {
829 &self.by_week_no
830 }
831
832 /// Get the `by_hour` of the recurrence.
833 #[must_use]
834 pub fn get_by_weekday(&self) -> &[NWeekday] {
835 &self.by_weekday
836 }
837
838 /// Get the `by_hour` of the recurrence.
839 #[must_use]
840 pub fn get_by_hour(&self) -> &[u8] {
841 &self.by_hour
842 }
843
844 /// Get the `by_minute` of the recurrence.
845 #[must_use]
846 pub fn get_by_minute(&self) -> &[u8] {
847 &self.by_minute
848 }
849
850 /// Get the `by_second` of the recurrence.
851 #[must_use]
852 pub fn get_by_second(&self) -> &[u8] {
853 &self.by_second
854 }
855
856 /// Get the `by_easter` of the recurrence.
857 #[cfg(feature = "by-easter")]
858 #[must_use]
859 pub fn get_by_easter(&self) -> Option<&i16> {
860 self.by_easter.as_ref()
861 }
862 }