utc-cron-expr 11.2.0

Zero-dependency 5-field and 6-field POSIX/Quartz cron expression parser, O(1) bitmask matcher, and fast civil-calendar next-occurrence calculator.
Documentation
use super::*;

/// Parsing, matching, and next-occurrence computation for [`CronSchedule`].
impl CronSchedule {
    /// Parses a 5-field (`min hr dom mon dow`), 6-field (`sec min hr dom mon dow`), or `@alias` cron expression.
    ///
    /// # Arguments
    ///
    /// - `&str` - Cron expression string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, CronError>` - Compiled bitmask schedule or syntax error.
    pub fn parse(expr: &str) -> Result<Self, CronError> {
        let trimmed: &str = expr.trim();
        if trimmed.as_bytes().first() == Some(&b'@') {
            return match trimmed {
                ALIAS_YEARLY | ALIAS_ANNUALLY => Ok(SCHEDULE_YEARLY),
                ALIAS_MONTHLY => Ok(SCHEDULE_MONTHLY),
                ALIAS_WEEKLY => Ok(SCHEDULE_WEEKLY),
                ALIAS_DAILY | ALIAS_MIDNIGHT => Ok(SCHEDULE_DAILY),
                ALIAS_HOURLY => Ok(SCHEDULE_HOURLY),
                _ => Err(CronError::InvalidFieldCount),
            };
        }
        let mut iter: SplitAsciiWhitespace<'_> = trimmed.split_ascii_whitespace();
        let mut fields: [&str; 6] = [""; 6];
        let mut count: usize = 0;
        for part in iter.by_ref() {
            if count >= 6 {
                return Err(CronError::InvalidFieldCount);
            }
            fields[count] = part;
            count += 1;
        }
        let (seconds, min_f, hr_f, dom_f, mon_f, dow_f): (u64, &str, &str, &str, &str, &str) =
            match count {
                5 => (1, fields[0], fields[1], fields[2], fields[3], fields[4]),
                6 => {
                    let (sec_mask, _): (u64, bool) =
                        parse_cron_field(fields[0], 0, 59, false, false)?;
                    (
                        sec_mask, fields[1], fields[2], fields[3], fields[4], fields[5],
                    )
                }
                _ => return Err(CronError::InvalidFieldCount),
            };
        let (minutes, _): (u64, bool) = parse_cron_field(min_f, 0, 59, false, false)?;
        let (hours, _): (u64, bool) = parse_cron_field(hr_f, 0, 23, false, false)?;
        let (days, dom_wild): (u64, bool) = parse_cron_field(dom_f, 1, 31, false, false)?;
        let (months, _): (u64, bool) = parse_cron_field(mon_f, 1, 12, true, false)?;
        let (weekdays, dow_wild): (u64, bool) = parse_cron_field(dow_f, 0, 6, false, true)?;
        Ok(Self {
            seconds,
            minutes,
            hours,
            days,
            months,
            weekdays,
            day_restricted: !dom_wild,
            weekday_restricted: !dow_wild,
        })
    }

    /// Tests whether a UTC day `(day_of_month, weekday)` matches standard POSIX cron day semantics.
    ///
    /// When both day-of-month and day-of-week are restricted, either matching triggers (OR).
    ///
    /// # Arguments
    ///
    /// - `u8` - Day of month (`1..=31`).
    /// - `u8` - Day of week (`0..=6`).
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when the day matches.
    #[inline(always)]
    fn day_matches(&self, day: u8, weekday: u8) -> bool {
        let Self {
            days,
            weekdays,
            day_restricted,
            weekday_restricted,
            ..
        } = self;
        let dom_hit: bool = (*days & (1u64 << day)) != 0;
        let dow_hit: bool = (*weekdays & (1u64 << weekday)) != 0;
        if *day_restricted && *weekday_restricted {
            dom_hit || dow_hit
        } else {
            dom_hit && dow_hit
        }
    }

    /// Tests in O(1) time whether `dt` matches this cron schedule.
    ///
    /// # Arguments
    ///
    /// - `UtcDateTime` - Decomposed UTC timestamp.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when every field matches.
    #[inline(always)]
    pub fn matches_datetime(&self, dt: UtcDateTime) -> bool {
        let Self {
            seconds,
            minutes,
            hours,
            months,
            ..
        } = self;
        (*seconds & (1u64 << dt.get_second())) != 0
            && (*minutes & (1u64 << dt.get_minute())) != 0
            && (*hours & (1u64 << dt.get_hour())) != 0
            && (*months & (1u64 << dt.get_month())) != 0
            && self.day_matches(dt.get_day(), dt.get_weekday())
    }

    /// Tests in O(1) time whether `unix_secs` matches this cron schedule.
    ///
    /// # Arguments
    ///
    /// - `i64` - Signed Unix timestamp in seconds.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when `unix_secs` matches.
    #[inline(always)]
    pub fn matches_unix_secs(&self, unix_secs: i64) -> bool {
        self.matches_datetime(UtcDateTime::from_unix_secs(unix_secs))
    }

    /// Computes the next Unix timestamp strictly greater than `after_unix_secs` matching this schedule.
    ///
    /// Uses direct bitmask field jumps (O(1) per field carry) rather than second-by-second stepping.
    ///
    /// # Arguments
    ///
    /// - `i64` - Exclusive lower bound Unix timestamp in seconds.
    ///
    /// # Returns
    ///
    /// - `Option<i64>` - Next matching Unix timestamp in seconds, or `None` if unreachable within 100 years.
    pub fn next_after(&self, after_unix_secs: i64) -> Option<i64> {
        let start_secs: i64 = after_unix_secs.checked_add(1)?;
        let start_days: i64 = start_secs.div_euclid(86_400);
        let sod: u32 = start_secs.rem_euclid(86_400) as u32;
        let (mut year, mut month, mut day): (i32, u8, u8) = civil_from_days(start_days);
        let mut hour: u8 = (sod / 3600) as u8;
        let rem: u32 = sod - (hour as u32) * 3600;
        let mut minute: u8 = (rem / 60) as u8;
        let mut second: u8 = (rem - (minute as u32) * 60) as u8;
        let max_year: i32 = year.saturating_add(MAX_SEARCH_YEARS);
        let Self {
            seconds,
            minutes,
            hours,
            days,
            months,
            weekdays,
            day_restricted,
            weekday_restricted,
        } = self;
        let first_sec: u8 = next_set_bit(*seconds, 0)?;
        let first_min: u8 = next_set_bit(*minutes, 0)?;
        let first_hr: u8 = next_set_bit(*hours, 0)?;
        let first_month: u8 = next_set_bit(*months, 1)?;
        let first_hms_secs: i64 =
            i64::from(first_hr) * 3600 + i64::from(first_min) * 60 + i64::from(first_sec);
        let mut month_start_days: i64 = start_days - i64::from(day - 1);
        let mut cached_year: i32 = year;
        let mut cached_month: u8 = month;
        while year <= max_year {
            match next_set_bit(*months, month) {
                Some(next_m) if next_m == month => {}
                Some(next_m) => {
                    month = next_m;
                    day = 1;
                    hour = first_hr;
                    minute = first_min;
                    second = first_sec;
                }
                None => {
                    year += 1;
                    month = first_month;
                    day = 1;
                    hour = first_hr;
                    minute = first_min;
                    second = first_sec;
                    continue;
                }
            }
            if year != cached_year || month != cached_month {
                month_start_days = days_from_civil(year, month, 1);
            }
            let dim: u8 = days_in_month(year, month);
            let first_dow: u8 = weekday_from_days(month_start_days);
            let valid_days: u64 = month_day_mask(
                *days,
                *weekdays,
                *day_restricted,
                *weekday_restricted,
                first_dow,
                dim,
            );
            if let Some(matched_day) = next_set_bit(valid_days, day) {
                if matched_day == day {
                    if let Some((h, m, s)) =
                        next_hms_same_day(self, first_min, first_sec, hour, minute, second)
                    {
                        let day_unix: i64 =
                            (month_start_days + i64::from(matched_day - 1)) * 86_400;
                        return Some(
                            day_unix + i64::from(h) * 3600 + i64::from(m) * 60 + i64::from(s),
                        );
                    }
                    if let Some(next_day) = next_set_bit(valid_days, matched_day + 1) {
                        let day_unix: i64 = (month_start_days + i64::from(next_day - 1)) * 86_400;
                        return Some(day_unix + first_hms_secs);
                    }
                } else {
                    let day_unix: i64 = (month_start_days + i64::from(matched_day - 1)) * 86_400;
                    return Some(day_unix + first_hms_secs);
                }
            }
            month_start_days += i64::from(dim);
            if month == 12 {
                year += 1;
                month = 1;
            } else {
                month += 1;
            }
            cached_year = year;
            cached_month = month;
            day = 1;
            hour = first_hr;
            minute = first_min;
            second = first_sec;
        }
        None
    }
}

/// Parses a [`CronSchedule`] via [`FromStr`].
impl FromStr for CronSchedule {
    type Err = CronError;

    /// Parses `s` into a [`CronSchedule`].
    ///
    /// # Arguments
    ///
    /// - `&str` - Cron expression string.
    ///
    /// # Returns
    ///
    /// - `Result<Self, Self::Err>` - Parsed cron schedule or error.
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s)
    }
}