grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/strmatch/charset.rs
// Purpose:   Character sets as ranges, written out whole as one class
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Character sets for the PCRE2 and JavaScript readers. Each class is built
//! as a set of ranges and written out as a bracketed class of `\x{..}`
//! ranges, so folding and negation happen here, in the order the dialect's
//! engine applies them, and the regex crate's class syntax never reads
//! what the dialect wrote.

use std::fmt::Write as _;

use regex_syntax::hir::{Class, ClassUnicode, ClassUnicodeRange, HirKind};

/// A set of characters.
pub(super) type Set = ClassUnicode;

/// The set of `ranges`, each an inclusive pair of characters.
pub(super) fn set<const N: usize>(ranges: [(char, char); N]) -> Set {
    ClassUnicode::new(ranges.map(|(a, b)| ClassUnicodeRange::new(a, b)))
}

/// The set of `ranges`, each an inclusive pair of characters.
pub(super) fn from_ranges(ranges: &[(char, char)]) -> Set {
    ClassUnicode::new(ranges.iter().map(|(a, z)| ClassUnicodeRange::new(*a, *z)))
}

/// The set holding `c` alone.
pub(super) fn single(c: char) -> Set {
    set([(c, c)])
}

/// The ASCII digits.
pub(super) fn digits() -> Set {
    set([('0', '9')])
}

/// The ASCII letters, digits and `_`.
pub(super) fn word() -> Set {
    set([('0', '9'), ('A', 'Z'), ('_', '_'), ('a', 'z')])
}

/// `set` without what it holds, the rest of Unicode.
pub(super) fn negated(mut set: Set) -> Set {
    set.negate();
    set
}

/// `set` with every character's simple case fold added.
pub(super) fn folded(mut set: Set) -> Set {
    set.case_fold_simple();
    set
}

/// The set a regex-syntax `\p{name}` names, or `None` when it names none.
pub(super) fn property(name: &str) -> Option<Set> {
    let text = format!("\\p{{{name}}}");
    let hir = regex_syntax::ParserBuilder::new()
        .build()
        .parse(&text)
        .ok()?;
    match hir.into_kind() {
        HirKind::Class(Class::Unicode(set)) => Some(set),
        _ => None,
    }
}

/// `set` as a bracketed class of `\x{..}` ranges. An empty set is the
/// negation of every character.
pub(super) fn render(set: &Set) -> String {
    if set.ranges().is_empty() {
        return String::from(r"[^\x{0}-\x{10FFFF}]");
    }
    let mut out = String::from("[");
    for r in set.iter() {
        let _ = if r.start() == r.end() {
            write!(out, "\\x{{{:X}}}", u32::from(r.start()))
        } else {
            write!(
                out,
                "\\x{{{:X}}}-\\x{{{:X}}}",
                u32::from(r.start()),
                u32::from(r.end())
            )
        };
    }
    out.push(']');
    out
}

/// `set` as a class that no `(?i)` around it folds.
pub(super) fn render_exact(set: &Set) -> String {
    format!("(?-i:{})", render(set))
}

/// The characters of the POSIX class `name`, ASCII alone.
pub(super) fn posix(name: &str) -> Option<Set> {
    Some(match name {
        "alpha" => set([('A', 'Z'), ('a', 'z')]),
        "digit" => digits(),
        "alnum" => set([('0', '9'), ('A', 'Z'), ('a', 'z')]),
        "upper" => set([('A', 'Z')]),
        "lower" => set([('a', 'z')]),
        "space" => set([('\t', '\r'), (' ', ' ')]),
        "blank" => set([('\t', '\t'), (' ', ' ')]),
        "punct" => set([('!', '/'), (':', '@'), ('[', '`'), ('{', '~')]),
        "print" => set([(' ', '~')]),
        "graph" => set([('!', '~')]),
        "cntrl" => set([('\0', '\x1F'), ('\x7F', '\x7F')]),
        "xdigit" => set([('0', '9'), ('A', 'F'), ('a', 'f')]),
        "word" => word(),
        "ascii" => set([('\0', '\x7F')]),
        _ => return None,
    })
}

/// Horizontal white space as PCRE2's `\h` reads it.
pub(super) fn horizontal_space() -> Set {
    set([
        ('\t', '\t'),
        (' ', ' '),
        ('\u{A0}', '\u{A0}'),
        ('\u{1680}', '\u{1680}'),
        ('\u{180E}', '\u{180E}'),
        ('\u{2000}', '\u{200A}'),
        ('\u{202F}', '\u{202F}'),
        ('\u{205F}', '\u{205F}'),
        ('\u{3000}', '\u{3000}'),
    ])
}

/// Vertical white space as PCRE2's `\v` reads it.
pub(super) fn vertical_space() -> Set {
    set([('\n', '\r'), ('\u{85}', '\u{85}'), ('\u{2028}', '\u{2029}')])
}