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::*;

/// Parses a 1-to-3-digit unsigned ASCII integer into `u8`.
///
/// # Arguments
///
/// - `&str` - Raw numeric token.
///
/// # Returns
///
/// - `Option<u8>` - Parsed value or `None` if malformed or out of `u8` range.
#[inline(always)]
fn parse_u8_ascii(token: &str) -> Option<u8> {
    let bytes: &[u8] = token.as_bytes();
    let len: usize = bytes.len();
    if len == 0 || len > 3 {
        return None;
    }
    let d0: u8 = bytes[0].wrapping_sub(b'0');
    if d0 > 9 {
        return None;
    }
    if len == 1 {
        return Some(d0);
    }
    let d1: u8 = bytes[1].wrapping_sub(b'0');
    if d1 > 9 {
        return None;
    }
    if len == 2 {
        return Some(d0 * 10 + d1);
    }
    let d2: u8 = bytes[2].wrapping_sub(b'0');
    if d2 > 9 {
        return None;
    }
    let val: u16 = u16::from(d0) * 100 + u16::from(d1) * 10 + u16::from(d2);
    if val > 255 {
        return None;
    }
    Some(val as u8)
}

/// Maps a month or weekday mnemonic name to its numeric value when applicable.
///
/// # Arguments
///
/// - `&str` - Token text.
/// - `bool` - Whether month names (`JAN`..`DEC`) are accepted.
/// - `bool` - Whether weekday names (`SUN`..`SAT`) are accepted.
///
/// # Returns
///
/// - `Option<u8>` - Numeric value if matched.
#[inline(always)]
fn parse_name_token(token: &str, allow_months: bool, allow_weekdays: bool) -> Option<u8> {
    let bytes: &[u8] = token.as_bytes();
    if bytes.len() != 3 {
        return None;
    }
    let b0: u8 = bytes[0] | 0x20;
    let b1: u8 = bytes[1] | 0x20;
    let b2: u8 = bytes[2] | 0x20;
    let lower: [u8; 3] = [b0, b1, b2];
    if allow_months {
        return match &lower {
            b"jan" => Some(1),
            b"feb" => Some(2),
            b"mar" => Some(3),
            b"apr" => Some(4),
            b"may" => Some(5),
            b"jun" => Some(6),
            b"jul" => Some(7),
            b"aug" => Some(8),
            b"sep" => Some(9),
            b"oct" => Some(10),
            b"nov" => Some(11),
            b"dec" => Some(12),
            _ => None,
        };
    }
    if allow_weekdays {
        return match &lower {
            b"sun" => Some(0),
            b"mon" => Some(1),
            b"tue" => Some(2),
            b"wed" => Some(3),
            b"thu" => Some(4),
            b"fri" => Some(5),
            b"sat" => Some(6),
            _ => None,
        };
    }
    None
}

/// Parses one numeric or named field endpoint and normalizes Sunday `7` -> `0` for weekdays.
///
/// # Arguments
///
/// - `&str` - Raw token text.
/// - `u8` - Minimum valid value.
/// - `u8` - Maximum valid value.
/// - `bool` - Whether month names are enabled.
/// - `bool` - Whether weekday names and `7 == Sunday` are enabled.
///
/// # Returns
///
/// - `Result<u8, CronError>` - Validated field value.
#[inline(always)]
fn parse_endpoint(
    token: &str,
    min: u8,
    max: u8,
    allow_months: bool,
    allow_weekdays: bool,
) -> Result<u8, CronError> {
    if token.is_empty() {
        return Err(CronError::InvalidFieldSyntax);
    }
    let val: u8 = if let Some(v) = parse_u8_ascii(token) {
        v
    } else if (allow_months || allow_weekdays)
        && let Some(named) = parse_name_token(token, allow_months, allow_weekdays)
    {
        named
    } else {
        return Err(CronError::InvalidFieldSyntax);
    };
    if allow_weekdays && val == 7 {
        return Ok(0);
    }
    if val < min || val > max {
        return Err(CronError::ValueOutOfRange);
    }
    Ok(val)
}

/// Parses one cron field (`*`, `*/n`, `a-b/n`, `a,b,c`) into a 64-bit bitmask.
///
/// # Arguments
///
/// - `&str` - Field text.
/// - `u8` - Minimum allowed numeric value.
/// - `u8` - Maximum allowed numeric value.
/// - `bool` - Whether month names are allowed.
/// - `bool` - Whether weekday names and `7 == 0` are allowed.
///
/// # Returns
///
/// - `Result<(u64, bool), CronError>` - `(bitmask, is_wildcard_unrestricted)` or parse error.
#[inline]
pub(crate) fn parse_cron_field(
    field: &str,
    min: u8,
    max: u8,
    allow_months: bool,
    allow_weekdays: bool,
) -> Result<(u64, bool), CronError> {
    let bytes: &[u8] = field.as_bytes();
    if bytes.is_empty() {
        return Err(CronError::InvalidFieldSyntax);
    }
    if bytes.len() == 1 && (bytes[0] == b'*' || bytes[0] == b'?') {
        let span: u32 = u32::from(max - min) + 1;
        let mask: u64 = ((1u64 << span) - 1) << min;
        return Ok((mask, true));
    }
    if let Some(single) = parse_u8_ascii(field) {
        let val: u8 = if allow_weekdays && single == 7 {
            0
        } else {
            if single < min || single > max {
                return Err(CronError::ValueOutOfRange);
            }
            single
        };
        return Ok((1u64 << val, false));
    }
    let mut mask: u64 = 0;
    for part in field.split(',') {
        if part.is_empty() {
            return Err(CronError::InvalidFieldSyntax);
        }
        let (range_part, step, has_slash): (&str, u8, bool) = match part.split_once('/') {
            Some((lhs, rhs)) => {
                let s: u8 = parse_u8_ascii(rhs).ok_or(CronError::InvalidStep)?;
                if s == 0 {
                    return Err(CronError::InvalidStep);
                }
                (lhs, s, true)
            }
            None => (part, 1, false),
        };
        let range_bytes: &[u8] = range_part.as_bytes();
        let (start, end): (u8, u8) = if range_bytes.len() == 1
            && (range_bytes[0] == b'*' || range_bytes[0] == b'?')
        {
            (min, max)
        } else if let Some((lo_s, hi_s)) = range_part.split_once('-') {
            let lo: u8 = parse_endpoint(lo_s, min, max, allow_months, allow_weekdays)?;
            let hi: u8 = if allow_weekdays && hi_s == "7" {
                7
            } else {
                parse_endpoint(hi_s, min, max, allow_months, allow_weekdays)?
            };
            if lo > hi {
                return Err(CronError::ValueOutOfRange);
            }
            (lo, hi)
        } else {
            let single: u8 = parse_endpoint(range_part, min, max, allow_months, allow_weekdays)?;
            if has_slash {
                (single, max)
            } else {
                (single, single)
            }
        };
        if step == 1 && (!allow_weekdays || end < 7) {
            let span: u32 = u32::from(end - start) + 1;
            mask |= ((1u64 << span) - 1) << start;
        } else {
            let mut cur: u16 = u16::from(start);
            let limit: u16 = u16::from(end);
            let step_u16: u16 = u16::from(step);
            while cur <= limit {
                let bit: u8 = if allow_weekdays && cur == 7 {
                    0
                } else {
                    cur as u8
                };
                mask |= 1u64 << bit;
                cur += step_u16;
            }
        }
    }
    if mask == 0 {
        return Err(CronError::InvalidFieldSyntax);
    }
    Ok((mask, false))
}

/// Computes the exact bitmask of valid matching day numbers (`1..=dim`) for a month in O(1).
///
/// # Arguments
///
/// - `u64` - Day-of-month bitmask (`1..=31`).
/// - `u64` - Day-of-week bitmask (`0..=6`).
/// - `bool` - Whether day-of-month is explicitly restricted.
/// - `bool` - Whether day-of-week is explicitly restricted.
/// - `u8` - Weekday of day `1` of the month (`0..=6`).
/// - `u8` - Number of days in the month (`28..=31`).
///
/// # Returns
///
/// - `u64` - Bitmask with bit `d` set iff day `d` in `1..=dim` matches POSIX day rules.
#[inline(always)]
pub(crate) fn month_day_mask(
    days: u64,
    weekdays: u64,
    day_restricted: bool,
    weekday_restricted: bool,
    first_weekday: u8,
    dim: u8,
) -> u64 {
    let valid_days: u64 = ((1u64 << dim) - 1) << 1;
    if !weekday_restricted {
        return days & valid_days;
    }
    let w7: u64 = weekdays & 0x7F;
    let r14: u64 = w7 | (w7 << 7);
    let r28: u64 = r14 | (r14 << 14);
    let r42: u64 = r28 | (r14 << 28);
    let dow_days: u64 = ((r42 >> first_weekday) << 1) & valid_days;
    if day_restricted {
        (days & valid_days) | dow_days
    } else {
        dow_days
    }
}

/// Computes the next valid `(hour, minute, second)` on the same day, or `None` on day overflow.
///
/// # Arguments
///
/// - `&CronSchedule` - Compiled schedule bitmasks.
/// - `u8` - Minimum allowed minute.
/// - `u8` - Minimum allowed second.
/// - `u8` - Current hour.
/// - `u8` - Current minute.
/// - `u8` - Current second.
///
/// # Returns
///
/// - `Option<(u8, u8, u8)>` - Matching `(hour, minute, second)` on the current day.
#[inline(always)]
pub(crate) fn next_hms_same_day(
    schedule: &CronSchedule,
    first_min: u8,
    first_sec: u8,
    hour: u8,
    minute: u8,
    second: u8,
) -> Option<(u8, u8, u8)> {
    let next_h: u8 = next_set_bit(schedule.hours, hour)?;
    if next_h > hour {
        return Some((next_h, first_min, first_sec));
    }
    if let Some(next_m) = next_set_bit(schedule.minutes, minute) {
        if next_m > minute {
            return Some((next_h, next_m, first_sec));
        }
        if let Some(next_s) = next_set_bit(schedule.seconds, second) {
            return Some((next_h, next_m, next_s));
        }
        if let Some(carry_m) = next_set_bit(schedule.minutes, minute + 1) {
            return Some((next_h, carry_m, first_sec));
        }
    }
    let carry_h: u8 = next_set_bit(schedule.hours, hour + 1)?;
    Some((carry_h, first_min, first_sec))
}

/// Finds the smallest set bit `>= min_val` inside `mask`, or `None` if none exists.
///
/// # Arguments
///
/// - `u64` - Bitmask of permitted values.
/// - `u8` - Inclusive minimum bit index.
///
/// # Returns
///
/// - `Option<u8>` - Smallest matching value `>= min_val`.
#[inline(always)]
pub(crate) fn next_set_bit(mask: u64, min_val: u8) -> Option<u8> {
    if min_val >= 64 {
        return None;
    }
    let shifted: u64 = mask >> min_val;
    if shifted == 0 {
        return None;
    }
    Some(min_val + shifted.trailing_zeros() as u8)
}