Skip to main content

utc_cron_expr/schedule/
impl.rs

1use super::*;
2
3/// Parsing, matching, and next-occurrence computation for [`CronSchedule`].
4impl CronSchedule {
5    /// Parses a 5-field (`min hr dom mon dow`), 6-field (`sec min hr dom mon dow`), or `@alias` cron expression.
6    ///
7    /// # Arguments
8    ///
9    /// - `&str` - Cron expression string.
10    ///
11    /// # Returns
12    ///
13    /// - `Result<Self, CronError>` - Compiled bitmask schedule or syntax error.
14    pub fn parse(expr: &str) -> Result<Self, CronError> {
15        let trimmed: &str = expr.trim();
16        if trimmed.as_bytes().first() == Some(&b'@') {
17            return match trimmed {
18                ALIAS_YEARLY | ALIAS_ANNUALLY => Ok(SCHEDULE_YEARLY),
19                ALIAS_MONTHLY => Ok(SCHEDULE_MONTHLY),
20                ALIAS_WEEKLY => Ok(SCHEDULE_WEEKLY),
21                ALIAS_DAILY | ALIAS_MIDNIGHT => Ok(SCHEDULE_DAILY),
22                ALIAS_HOURLY => Ok(SCHEDULE_HOURLY),
23                _ => Err(CronError::InvalidFieldCount),
24            };
25        }
26        let mut iter: SplitAsciiWhitespace<'_> = trimmed.split_ascii_whitespace();
27        let mut fields: [&str; 6] = [""; 6];
28        let mut count: usize = 0;
29        for part in iter.by_ref() {
30            if count >= 6 {
31                return Err(CronError::InvalidFieldCount);
32            }
33            fields[count] = part;
34            count += 1;
35        }
36        let (seconds, min_f, hr_f, dom_f, mon_f, dow_f): (u64, &str, &str, &str, &str, &str) =
37            match count {
38                5 => (1, fields[0], fields[1], fields[2], fields[3], fields[4]),
39                6 => {
40                    let (sec_mask, _): (u64, bool) =
41                        parse_cron_field(fields[0], 0, 59, false, false)?;
42                    (
43                        sec_mask, fields[1], fields[2], fields[3], fields[4], fields[5],
44                    )
45                }
46                _ => return Err(CronError::InvalidFieldCount),
47            };
48        let (minutes, _): (u64, bool) = parse_cron_field(min_f, 0, 59, false, false)?;
49        let (hours, _): (u64, bool) = parse_cron_field(hr_f, 0, 23, false, false)?;
50        let (days, dom_wild): (u64, bool) = parse_cron_field(dom_f, 1, 31, false, false)?;
51        let (months, _): (u64, bool) = parse_cron_field(mon_f, 1, 12, true, false)?;
52        let (weekdays, dow_wild): (u64, bool) = parse_cron_field(dow_f, 0, 6, false, true)?;
53        Ok(Self {
54            seconds,
55            minutes,
56            hours,
57            days,
58            months,
59            weekdays,
60            day_restricted: !dom_wild,
61            weekday_restricted: !dow_wild,
62        })
63    }
64
65    /// Tests whether a UTC day `(day_of_month, weekday)` matches standard POSIX cron day semantics.
66    ///
67    /// When both day-of-month and day-of-week are restricted, either matching triggers (OR).
68    ///
69    /// # Arguments
70    ///
71    /// - `u8` - Day of month (`1..=31`).
72    /// - `u8` - Day of week (`0..=6`).
73    ///
74    /// # Returns
75    ///
76    /// - `bool` - `true` when the day matches.
77    #[inline(always)]
78    fn day_matches(&self, day: u8, weekday: u8) -> bool {
79        let Self {
80            days,
81            weekdays,
82            day_restricted,
83            weekday_restricted,
84            ..
85        } = self;
86        let dom_hit: bool = (*days & (1u64 << day)) != 0;
87        let dow_hit: bool = (*weekdays & (1u64 << weekday)) != 0;
88        if *day_restricted && *weekday_restricted {
89            dom_hit || dow_hit
90        } else {
91            dom_hit && dow_hit
92        }
93    }
94
95    /// Tests in O(1) time whether `dt` matches this cron schedule.
96    ///
97    /// # Arguments
98    ///
99    /// - `UtcDateTime` - Decomposed UTC timestamp.
100    ///
101    /// # Returns
102    ///
103    /// - `bool` - `true` when every field matches.
104    #[inline(always)]
105    pub fn matches_datetime(&self, dt: UtcDateTime) -> bool {
106        let Self {
107            seconds,
108            minutes,
109            hours,
110            months,
111            ..
112        } = self;
113        (*seconds & (1u64 << dt.get_second())) != 0
114            && (*minutes & (1u64 << dt.get_minute())) != 0
115            && (*hours & (1u64 << dt.get_hour())) != 0
116            && (*months & (1u64 << dt.get_month())) != 0
117            && self.day_matches(dt.get_day(), dt.get_weekday())
118    }
119
120    /// Tests in O(1) time whether `unix_secs` matches this cron schedule.
121    ///
122    /// # Arguments
123    ///
124    /// - `i64` - Signed Unix timestamp in seconds.
125    ///
126    /// # Returns
127    ///
128    /// - `bool` - `true` when `unix_secs` matches.
129    #[inline(always)]
130    pub fn matches_unix_secs(&self, unix_secs: i64) -> bool {
131        self.matches_datetime(UtcDateTime::from_unix_secs(unix_secs))
132    }
133
134    /// Computes the next Unix timestamp strictly greater than `after_unix_secs` matching this schedule.
135    ///
136    /// Uses direct bitmask field jumps (O(1) per field carry) rather than second-by-second stepping.
137    ///
138    /// # Arguments
139    ///
140    /// - `i64` - Exclusive lower bound Unix timestamp in seconds.
141    ///
142    /// # Returns
143    ///
144    /// - `Option<i64>` - Next matching Unix timestamp in seconds, or `None` if unreachable within 100 years.
145    pub fn next_after(&self, after_unix_secs: i64) -> Option<i64> {
146        let start_secs: i64 = after_unix_secs.checked_add(1)?;
147        let start_days: i64 = start_secs.div_euclid(86_400);
148        let sod: u32 = start_secs.rem_euclid(86_400) as u32;
149        let (mut year, mut month, mut day): (i32, u8, u8) = civil_from_days(start_days);
150        let mut hour: u8 = (sod / 3600) as u8;
151        let rem: u32 = sod - (hour as u32) * 3600;
152        let mut minute: u8 = (rem / 60) as u8;
153        let mut second: u8 = (rem - (minute as u32) * 60) as u8;
154        let max_year: i32 = year.saturating_add(MAX_SEARCH_YEARS);
155        let Self {
156            seconds,
157            minutes,
158            hours,
159            days,
160            months,
161            weekdays,
162            day_restricted,
163            weekday_restricted,
164        } = self;
165        let first_sec: u8 = next_set_bit(*seconds, 0)?;
166        let first_min: u8 = next_set_bit(*minutes, 0)?;
167        let first_hr: u8 = next_set_bit(*hours, 0)?;
168        let first_month: u8 = next_set_bit(*months, 1)?;
169        let first_hms_secs: i64 =
170            i64::from(first_hr) * 3600 + i64::from(first_min) * 60 + i64::from(first_sec);
171        let mut month_start_days: i64 = start_days - i64::from(day - 1);
172        let mut cached_year: i32 = year;
173        let mut cached_month: u8 = month;
174        while year <= max_year {
175            match next_set_bit(*months, month) {
176                Some(next_m) if next_m == month => {}
177                Some(next_m) => {
178                    month = next_m;
179                    day = 1;
180                    hour = first_hr;
181                    minute = first_min;
182                    second = first_sec;
183                }
184                None => {
185                    year += 1;
186                    month = first_month;
187                    day = 1;
188                    hour = first_hr;
189                    minute = first_min;
190                    second = first_sec;
191                    continue;
192                }
193            }
194            if year != cached_year || month != cached_month {
195                month_start_days = days_from_civil(year, month, 1);
196            }
197            let dim: u8 = days_in_month(year, month);
198            let first_dow: u8 = weekday_from_days(month_start_days);
199            let valid_days: u64 = month_day_mask(
200                *days,
201                *weekdays,
202                *day_restricted,
203                *weekday_restricted,
204                first_dow,
205                dim,
206            );
207            if let Some(matched_day) = next_set_bit(valid_days, day) {
208                if matched_day == day {
209                    if let Some((h, m, s)) =
210                        next_hms_same_day(self, first_min, first_sec, hour, minute, second)
211                    {
212                        let day_unix: i64 =
213                            (month_start_days + i64::from(matched_day - 1)) * 86_400;
214                        return Some(
215                            day_unix + i64::from(h) * 3600 + i64::from(m) * 60 + i64::from(s),
216                        );
217                    }
218                    if let Some(next_day) = next_set_bit(valid_days, matched_day + 1) {
219                        let day_unix: i64 = (month_start_days + i64::from(next_day - 1)) * 86_400;
220                        return Some(day_unix + first_hms_secs);
221                    }
222                } else {
223                    let day_unix: i64 = (month_start_days + i64::from(matched_day - 1)) * 86_400;
224                    return Some(day_unix + first_hms_secs);
225                }
226            }
227            month_start_days += i64::from(dim);
228            if month == 12 {
229                year += 1;
230                month = 1;
231            } else {
232                month += 1;
233            }
234            cached_year = year;
235            cached_month = month;
236            day = 1;
237            hour = first_hr;
238            minute = first_min;
239            second = first_sec;
240        }
241        None
242    }
243}
244
245/// Parses a [`CronSchedule`] via [`FromStr`].
246impl FromStr for CronSchedule {
247    type Err = CronError;
248
249    /// Parses `s` into a [`CronSchedule`].
250    ///
251    /// # Arguments
252    ///
253    /// - `&str` - Cron expression string.
254    ///
255    /// # Returns
256    ///
257    /// - `Result<Self, Self::Err>` - Parsed cron schedule or error.
258    fn from_str(s: &str) -> Result<Self, Self::Err> {
259        Self::parse(s)
260    }
261}