utc-cron-expr 11.1.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();
        let expanded: &str = match trimmed {
            ALIAS_YEARLY | ALIAS_ANNUALLY => EXPR_YEARLY,
            ALIAS_MONTHLY => EXPR_MONTHLY,
            ALIAS_WEEKLY => EXPR_WEEKLY,
            ALIAS_DAILY | ALIAS_MIDNIGHT => EXPR_DAILY,
            ALIAS_HOURLY => EXPR_HOURLY,
            other => other,
        };
        let fields: Vec<&str> = expanded.split_ascii_whitespace().collect();
        let (sec_f, min_f, hr_f, dom_f, mon_f, dow_f): (&str, &str, &str, &str, &str, &str) =
            match fields.len() {
                5 => ("0", fields[0], fields[1], fields[2], fields[3], fields[4]),
                6 => (
                    fields[0], fields[1], fields[2], fields[3], fields[4], fields[5],
                ),
                _ => return Err(CronError::InvalidFieldCount),
            };
        let (seconds, _): (u64, bool) = parse_cron_field(sec_f, 0, 59, false, false)?;
        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_dt: UtcDateTime = UtcDateTime::from_unix_secs(after_unix_secs.checked_add(1)?);
        let max_year: i32 = start_dt.get_year().saturating_add(MAX_SEARCH_YEARS);
        let Self {
            seconds,
            minutes,
            hours,
            months,
            ..
        } = 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 mut year: i32 = start_dt.get_year();
        let mut month: u8 = start_dt.get_month();
        let mut day: u8 = start_dt.get_day();
        let mut hour: u8 = start_dt.get_hour();
        let mut minute: u8 = start_dt.get_minute();
        let mut second: u8 = start_dt.get_second();
        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 = next_set_bit(*months, 1)?;
                    day = 1;
                    hour = first_hr;
                    minute = first_min;
                    second = first_sec;
                    continue;
                }
            }
            let dim: u8 = days_in_month(year, month);
            if day > dim {
                month += 1;
                if month > 12 {
                    year += 1;
                    month = 1;
                }
                day = 1;
                hour = first_hr;
                minute = first_min;
                second = first_sec;
                continue;
            }
            let weekday: u8 = weekday_from_days(days_from_civil(year, month, day));
            if !self.day_matches(day, weekday) {
                day += 1;
                hour = first_hr;
                minute = first_min;
                second = first_sec;
                continue;
            }
            match next_set_bit(*hours, hour) {
                Some(next_h) if next_h == hour => {}
                Some(next_h) => {
                    hour = next_h;
                    minute = first_min;
                    second = first_sec;
                }
                None => {
                    day += 1;
                    hour = first_hr;
                    minute = first_min;
                    second = first_sec;
                    continue;
                }
            }
            match next_set_bit(*minutes, minute) {
                Some(next_min) if next_min == minute => {}
                Some(next_min) => {
                    minute = next_min;
                    second = first_sec;
                }
                None => {
                    hour += 1;
                    minute = first_min;
                    second = first_sec;
                    continue;
                }
            }
            match next_set_bit(*seconds, second) {
                Some(next_s) => {
                    let candidate: UtcDateTime = UtcDateTime {
                        year,
                        month,
                        day,
                        weekday,
                        hour,
                        minute,
                        second: next_s,
                    };
                    return Some(candidate.to_unix_secs());
                }
                None => {
                    minute += 1;
                    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)
    }
}