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

/// 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.
fn parse_name_token(token: &str, allow_months: bool, allow_weekdays: bool) -> Option<u8> {
    if allow_months && token.len() == 3 {
        let lower: [u8; 3] = [
            token.as_bytes()[0].to_ascii_lowercase(),
            token.as_bytes()[1].to_ascii_lowercase(),
            token.as_bytes()[2].to_ascii_lowercase(),
        ];
        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 && token.len() == 3 {
        let lower: [u8; 3] = [
            token.as_bytes()[0].to_ascii_lowercase(),
            token.as_bytes()[1].to_ascii_lowercase(),
            token.as_bytes()[2].to_ascii_lowercase(),
        ];
        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.
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(named) = parse_name_token(token, allow_months, allow_weekdays) {
        named
    } else {
        token
            .parse::<u8>()
            .map_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.
pub(crate) fn parse_cron_field(
    field: &str,
    min: u8,
    max: u8,
    allow_months: bool,
    allow_weekdays: bool,
) -> Result<(u64, bool), CronError> {
    if field.is_empty() {
        return Err(CronError::InvalidFieldSyntax);
    }
    if field == "*" || field == "?" {
        let mut mask: u64 = 0;
        for v in min..=max {
            mask |= 1u64 << v;
        }
        return Ok((mask, true));
    }
    let mut mask: u64 = 0;
    for part in field.split(',') {
        if part.is_empty() {
            return Err(CronError::InvalidFieldSyntax);
        }
        let (range_part, step): (&str, u8) = match part.split_once('/') {
            Some((lhs, rhs)) => {
                let s: u8 = rhs.parse::<u8>().map_err(|_| CronError::InvalidStep)?;
                if s == 0 {
                    return Err(CronError::InvalidStep);
                }
                (lhs, s)
            }
            None => (part, 1),
        };
        let (start, end): (u8, u8) = if range_part == "*" || range_part == "?" {
            (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 part.contains('/') {
                (single, max)
            } else {
                (single, single)
            }
        };
        let mut cur: u16 = u16::from(start);
        let limit: u16 = u16::from(end);
        while cur <= limit {
            let bit: u8 = if allow_weekdays && cur == 7 {
                0
            } else {
                cur as u8
            };
            mask |= 1u64 << bit;
            cur += u16::from(step);
        }
    }
    if mask == 0 {
        return Err(CronError::InvalidFieldSyntax);
    }
    Ok((mask, false))
}

/// 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)
}