grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/grok/date_chrono.rs
// Purpose:   A grok matcher built from a chrono-dialect strptime format
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED
//
// Follows the format grammar and number widths of chrono 0.4.45, src/format/strftime.rs and
// parse.rs, which are MIT OR Apache-2.0, Copyright (c) 2014 Kang Seonghoon and contributors.
// The MIT notice is in LICENSES/chrono-MIT.txt.

//! A regex for the timestamps a [`StrptimeDialect::Chrono`] format reads.
//!
//! chrono reads a number greedily up to its width, trims white space before
//! it, and never gives a digit back. So a number with a digit after it is
//! matched at its full width, and an item that takes any count of digits is
//! refused there.
//!
//! [`StrptimeDialect::Chrono`]: crate::time::StrptimeDialect::Chrono

use std::fmt::Write;

use super::GrokError;
use crate::time::{Item, Name, Number, StrptimeDialect, TimeFormat, Zone};

const MONTHS: [&str; 12] = [
    "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
];
const MONTH_ENDS: [&str; 12] = [
    "uary", "ruary", "ch", "il", "", "e", "y", "ust", "tember", "ober", "ember", "ember",
];
const WEEKDAYS: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
const WEEKDAY_ENDS: [&str; 7] = ["day", "sday", "nesday", "rsday", "day", "urday", "day"];

/// Hours up to 23, as an offset reads to an instant.
const HOURS: &str = "(?:[01][0-9]|2[0-3])";
/// `+`, `-` and U+2212, which chrono reads as a minus.
const SIGN: &str = r"[+\-\x{2212}]";

/// A regex matching the text chrono reads for `format`, in the dialect of
/// [`StrptimeDialect::Chrono`]. Numbers are held to their ranges, and a year
/// to the 0 to 9999 an instant here holds.
///
/// # Errors
///
/// [`GrokError::Date`] for a specifier chrono has no item for, a `%s`, `%.f`
/// or `%#z` that a digit would run into, and a `%Z` before anything but white
/// space.
pub fn chrono_date_pattern(format: &str) -> Result<String, GrokError> {
    let fail = |why: &str| GrokError::Date(format!("{format:?}: {why}"));
    let built = match TimeFormat::strptime(StrptimeDialect::Chrono, format) {
        Ok(TimeFormat::Chrono(built)) => built,
        Ok(_) => return Err(fail("not a chrono format")),
        Err(e) => return Err(fail(&e.to_string())),
    };
    let items = built.items();
    let mut out = String::with_capacity(format.len() * 16);
    let mut i = 0;
    while let Some(item) = items.get(i) {
        let after = &items[i + 1..];
        let digit_next = digit_next(after);
        // Before white space and then a digit, a number takes any count of
        // digits where the white space is there, and its full width where not.
        let spaced = matches!(after.first(), Some(Item::Space)) && digit_next_after(after);
        match item {
            Item::Literal(text) => regex_syntax::escape_into(text, &mut out),
            Item::Space => out.push_str(r"\s*"),
            Item::Number(number) if spaced => {
                let free =
                    numeric(*number, false).ok_or_else(|| fail("a number with no matcher"))?;
                let _ = write!(out, r"\s*(?:(?:{free})\s+");
                if let Some(fixed) = numeric(*number, true) {
                    let _ = write!(out, r"|(?:{fixed})\s*");
                }
                out.push(')');
                i += 1;
            }
            Item::Number(number) => {
                let re = numeric(*number, digit_next)
                    .ok_or_else(|| fail("a digit straight after %s"))?;
                out.push_str(r"\s*(?:");
                out.push_str(re);
                out.push(')');
            }
            Item::DotFraction(None) if spaced => {
                out.push_str(r"(?:\.[0-9]+)?\s+");
                i += 1;
            }
            Item::Name(name) => out.push_str(&names(*name)),
            Item::Meridiem => out.push_str("[AaPp][Mm]"),
            Item::Fraction(n) => {
                let _ = write!(out, "[0-9]{{{n}}}");
            }
            Item::DotFraction(Some(n)) => {
                let _ = write!(out, r"(?:\.[0-9]{{{n}}})?");
            }
            Item::DotFraction(None) => {
                if digit_next {
                    return Err(fail("a digit straight after %.f"));
                }
                out.push_str(r"(?:\.[0-9]+)?");
            }
            Item::ZoneName => {
                if !matches!(items.get(i + 1), None | Some(Item::Space)) {
                    return Err(fail("%Z has to end the format or sit before white space"));
                }
                out.push_str(r"\S*");
            }
            Item::Zone(Zone::Numeric) => {
                let _ = write!(out, r"\s*{SIGN}{HOURS}[:\s]*[0-5][0-9]");
            }
            Item::Zone(Zone::Permissive) => {
                if digit_next {
                    return Err(fail("a digit straight after %#z"));
                }
                let _ = write!(out, r"\s*(?:[Zz]|{SIGN}{HOURS}[:\s]*(?:[0-5][0-9])?)");
            }
            Item::DateTimeSeparator => out.push_str("[Tt ]"),
            Item::RfcZone => {
                let _ = write!(
                    out,
                    r"\s*(?:[Uu][Tt][Cc]|[Zz]|{SIGN}{HOURS}[:\s]*[0-5][0-9])"
                );
            }
        }
        i += 1;
    }
    Ok(out)
}

/// The regex of a number: where no digit can follow, or at its full width
/// where one can. `None` where it takes any count of digits and one follows.
const fn numeric(number: Number, digit_next: bool) -> Option<&'static str> {
    let (free, fixed) = match number {
        Number::Month | Number::Hour12 => ("1[0-2]|0?[1-9]", "1[0-2]|0[1-9]"),
        Number::Day => ("3[01]|[12][0-9]|0?[1-9]", "3[01]|[12][0-9]|0[1-9]"),
        Number::Hour => ("2[0-3]|[01]?[0-9]", "2[0-3]|[01][0-9]"),
        Number::Minute => ("[0-5]?[0-9]", "[0-5][0-9]"),
        Number::Second => ("60|[0-5]?[0-9]", "60|[0-5][0-9]"),
        Number::Ordinal => (
            "36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0?[1-9][0-9]|0{0,2}[1-9]",
            "36[0-6]|3[0-5][0-9]|[12][0-9]{2}|0[1-9][0-9]|00[1-9]",
        ),
        Number::WeekFromSun | Number::WeekFromMon => ("5[0-3]|[0-4]?[0-9]", "5[0-3]|[0-4][0-9]"),
        Number::IsoWeek => ("5[0-3]|[1-4][0-9]|0?[1-9]", "5[0-3]|[1-4][0-9]|0[1-9]"),
        Number::Quarter => ("[1-4]", "[1-4]"),
        Number::DaysFromSun => ("[0-6]", "[0-6]"),
        Number::WeekdayFromMon => ("[1-7]", "[1-7]"),
        Number::YearDiv100 | Number::YearMod100 | Number::IsoYearMod100 => {
            ("[0-9]{1,2}", "[0-9]{2}")
        }
        // After a sign the digits run on, so a digit can't follow one.
        Number::Year | Number::IsoYear => ("[+-]0*[0-9]{1,4}|[0-9]{1,4}", "[0-9]{4}"),
        Number::Nanosecond => ("[0-9]{1,9}", "[0-9]{9}"),
        // Eleven digits reach the year 5138, inside the years an instant holds.
        Number::Timestamp => {
            if digit_next {
                return None;
            }
            return Some("0*[0-9]{1,11}");
        }
    };
    Some(if digit_next { fixed } else { free })
}

/// A word with each letter in either case, as chrono folds ASCII case.
fn folded(word: &str) -> String {
    word.chars()
        .flat_map(|c| ['[', c.to_ascii_uppercase(), c, ']'])
        .collect()
}

/// A name, abbreviated or in full: three letters and then the rest of the
/// name if it is there.
fn names(name: Name) -> String {
    let (short, ends): (&[&str], &[&str]) = match name {
        Name::ShortMonth | Name::LongMonth => (&MONTHS, &MONTH_ENDS),
        Name::ShortWeekday | Name::LongWeekday => (&WEEKDAYS, &WEEKDAY_ENDS),
    };
    let long = matches!(name, Name::LongMonth | Name::LongWeekday);
    let mut out = String::from("(?:");
    for (n, (word, end)) in short.iter().zip(ends).enumerate() {
        if n > 0 {
            out.push('|');
        }
        out.push_str(&folded(word));
        if long && !end.is_empty() {
            let _ = write!(out, "(?:{})?", folded(end));
        }
    }
    out.push(')');
    out
}

/// Whether a digit can follow the white space at the head of `rest`.
fn digit_next_after(rest: &[Item]) -> bool {
    digit_next(rest.get(1..).unwrap_or_default())
}

/// Whether the next item that can't match nothing can start with a digit.
fn digit_next(rest: &[Item]) -> bool {
    for item in rest {
        match item {
            Item::Literal(text) => return text.starts_with(|c: char| c.is_ascii_digit()),
            Item::Number(_) | Item::Fraction(_) | Item::ZoneName => return true,
            Item::Space | Item::DotFraction(_) => {}
            _ => return false,
        }
    }
    false
}

#[cfg(test)]
mod tests {
    use chrono::format::{Parsed, StrftimeItems, parse};
    use chrono::{DateTime, FixedOffset};
    use proptest::prelude::ProptestConfig;
    use proptest::string::string_regex;

    use super::*;

    /// Formats the matcher is held to chrono over, each one chrono can write.
    const FORMATS: &[&str] = &[
        "%Y-%m-%dT%H:%M:%S%.f%:z",
        "%Y-%m-%d %H:%M:%S.%3f %#z",
        "%d/%b/%Y:%H:%M:%S %z",
        "%a, %d %b %Y %H:%M:%S %z",
        "%A, %B %e, %Y %l:%M %P",
        "%a %b %e %T %Y",
        "%Y%m%d%H%M%S",
        "%y%m%d %H%M",
        "%Y-%j",
        "%G-W%V-%u",
        "%Y %U %w",
        "%F %T%.f",
        "%s%.3f",
        "%H:%M:%S.%f",
        "%+",
        "%c",
        "%D %r",
        "%v",
        "%q %Y",
        "%FT%T%.9fZ %Z",
    ];

    fn whole(format: &str) -> regex::Regex {
        let re = chrono_date_pattern(format).unwrap();
        regex::Regex::new(&format!("^(?:{re})$")).unwrap()
    }

    #[test]
    fn a_directive_with_no_matcher_is_refused() {
        for format in [
            "%Q", "%s%H", "%.f%S", "%#z%H", "%Z%H", "%Y-%", "%5Y", "%s%3f", "%.f%3f",
        ] {
            assert!(
                matches!(chrono_date_pattern(format), Err(GrokError::Date(_))),
                "{format} built"
            );
        }
    }

    /// Every text the regex matches, chrono reads as far as its fields go.
    #[test]
    fn chrono_reads_every_match() {
        for format in FORMATS {
            let re = chrono_date_pattern(format).unwrap();
            proptest::proptest!(ProptestConfig::with_cases(256), |(text in string_regex(&re).unwrap())| {
                let mut parsed = Parsed::new();
                let read = parse(&mut parsed, &text, StrftimeItems::new(format));
                proptest::prop_assert!(read.is_ok(), "{} matched {:?}, which chrono refuses: {:?}", format, text, read);
            });
        }
    }

    /// Every text chrono writes in the format, the regex matches.
    #[test]
    fn the_regex_matches_what_chrono_writes() {
        for format in FORMATS {
            let re = whole(format);
            for k in 0..400_i64 {
                // `%s` is unsigned, so chrono reads no text it wrote before 1970.
                let secs = k * 4_000_000;
                let nanos = u32::try_from((k * 7_919_123) % 1_000_000_000).unwrap();
                let offset = i32::try_from(((k * 37) % 95 - 47) * 15 * 60).unwrap();
                let text = DateTime::from_timestamp(secs, nanos)
                    .unwrap()
                    .with_timezone(&FixedOffset::east_opt(offset).unwrap())
                    .format(&format.replace("%#z", "%z"))
                    .to_string();
                assert!(re.is_match(&text), "{format} missed {text:?}");
            }
        }
    }
}