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/scrub/prefix.rs
// Purpose:   Rule a text out of a literal set by the literals' first three bytes
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A literal set's first three bytes, looked up a byte pair at a time, so a
//! clean text is ruled out of every literal in one pass with no automaton.

/// The most byte pairs that start a literal: a row number fits a byte.
const MAX_ROWS: usize = u8::MAX as usize;

/// The bytes that follow a pair some literal starts with.
#[derive(Debug, Clone, Default)]
struct Row {
    /// Third bytes of the literals the pair starts, one bit each.
    thirds: [u64; 4],
    /// A literal is the pair alone.
    whole: bool,
}

/// What a set of literals starts with.
#[derive(Debug, Clone)]
pub(super) struct Prefixes {
    /// Per byte pair, one bit: a literal starts with it. At 8 KB it's read
    /// for every pair, and the 64 KB `pairs` only on a hit.
    starts: Box<[u64]>,
    /// Per byte pair, 0 when no literal starts with it, else its row plus 1.
    pairs: Box<[u8]>,
    rows: Vec<Row>,
    /// Literals one byte long, one bit each.
    singles: [u64; 4],
    /// The set has an empty literal or too many pairs: any text may hold one.
    always: bool,
}

fn has(set: &[u64; 4], b: u8) -> bool {
    set[usize::from(b >> 6)] >> (b & 63) & 1 == 1
}

fn add(set: &mut [u64; 4], b: u8) {
    set[usize::from(b >> 6)] |= 1 << (b & 63);
}

impl Prefixes {
    pub(super) fn new<'a>(literals: impl IntoIterator<Item = &'a [u8]>) -> Self {
        let mut set = Self {
            starts: vec![0; 1 << 10].into_boxed_slice(),
            pairs: vec![0; 1 << 16].into_boxed_slice(),
            rows: Vec::new(),
            singles: [0; 4],
            always: false,
        };
        for literal in literals {
            match *literal {
                [] => set.always = true,
                [a] => add(&mut set.singles, a),
                [a, b, ..] => {
                    let pair = usize::from(a) << 8 | usize::from(b);
                    if set.pairs[pair] == 0 {
                        if set.rows.len() == MAX_ROWS {
                            set.always = true;
                            continue;
                        }
                        set.rows.push(Row::default());
                        set.pairs[pair] = u8::try_from(set.rows.len()).unwrap_or(u8::MAX);
                        set.starts[pair >> 6] |= 1 << (pair & 63);
                    }
                    let row = &mut set.rows[usize::from(set.pairs[pair]) - 1];
                    match literal.get(2) {
                        Some(&c) => add(&mut row.thirds, c),
                        None => row.whole = true,
                    }
                }
            }
        }
        set
    }

    /// `false` only when no literal occurs in `text`.
    pub(super) fn may_hold(&self, text: impl IntoIterator<Item = u8>) -> bool {
        if self.always {
            return true;
        }
        let singles = self.singles != [0; 4];
        if !singles && self.rows.is_empty() {
            return false;
        }
        // The third bytes that finish a prefix with the pair ending at the last byte.
        let mut thirds: Option<&[u64; 4]> = None;
        let mut last: Option<u8> = None;
        for c in text {
            if (singles && has(&self.singles, c)) || thirds.is_some_and(|t| has(t, c)) {
                return true;
            }
            thirds = None;
            if let Some(b) = last {
                let pair = usize::from(b) << 8 | usize::from(c);
                if self.starts[pair >> 6] >> (pair & 63) & 1 == 1 {
                    let row = &self.rows[usize::from(self.pairs[pair]) - 1];
                    if row.whole {
                        return true;
                    }
                    thirds = Some(&row.thirds);
                }
            }
            last = Some(c);
        }
        false
    }
}

/// How [`Prefixes::may_hold_folded`] reads each byte before it looks it up.
#[derive(Debug, Clone, Copy)]
pub(super) enum Fold {
    /// Every byte, ASCII lower-cased.
    Lower,
    /// Only the ASCII letters and digits, lower-cased.
    Alnum,
}

/// An ASCII letter or digit as its lower-case form, and 0 for any other byte.
const ALNUM: [u8; 256] = {
    let mut table = [0; 256];
    let mut b = 0_u8;
    loop {
        if b.is_ascii_alphanumeric() {
            table[b as usize] = b.to_ascii_lowercase();
        }
        if b == u8::MAX {
            break table;
        }
        b += 1;
    }
};

/// Bytes folded at a time by [`Prefixes::may_hold_folded`].
const BLOCK: usize = 64;

impl Prefixes {
    /// As [`Prefixes::may_hold`] over `text` read as `fold` says, folding a
    /// block of bytes and then looking its byte pairs up in one tight loop.
    pub(super) fn may_hold_folded(&self, text: &[u8], fold: Fold) -> bool {
        if self.always {
            return true;
        }
        let singles = self.singles != [0; 4];
        if !singles && self.rows.is_empty() {
            return false;
        }
        // `buf[0]` holds the last byte of the block before, so a pair can span two blocks.
        let mut buf = [0_u8; BLOCK + 1];
        let mut carried = false;
        // The third bytes a pair at the end of the last block still owes.
        let mut owed: Option<&[u64; 4]> = None;
        for block in text.chunks(BLOCK) {
            let mut end = 1;
            match fold {
                Fold::Lower => {
                    for (folded, &b) in buf[1..].iter_mut().zip(block) {
                        *folded = b.to_ascii_lowercase();
                    }
                    end += block.len();
                }
                Fold::Alnum => {
                    for &b in block {
                        let folded = ALNUM[usize::from(b)];
                        buf[end] = folded;
                        end += usize::from(folded != 0);
                    }
                }
            }
            if end == 1 {
                continue;
            }
            if let Some(thirds) = owed.take()
                && has(thirds, buf[1])
            {
                return true;
            }
            if singles && buf[1..end].iter().any(|&c| has(&self.singles, c)) {
                return true;
            }
            let pairs = &buf[usize::from(!carried)..end];
            for (at, pair) in pairs.windows(2).enumerate() {
                let key = usize::from(pair[0]) << 8 | usize::from(pair[1]);
                if self.starts[key >> 6] >> (key & 63) & 1 == 0 {
                    continue;
                }
                let row = &self.rows[usize::from(self.pairs[key]) - 1];
                if row.whole {
                    return true;
                }
                match pairs.get(at + 2) {
                    Some(&third) if has(&row.thirds, third) => return true,
                    Some(_) => {}
                    None => owed = Some(&row.thirds),
                }
            }
            buf[0] = buf[end - 1];
            carried = true;
        }
        false
    }
}

#[cfg(test)]
mod tests {
    use proptest::prelude::*;

    use super::*;

    /// What the table answers: a literal's first three bytes, or all of a
    /// shorter one, sit somewhere in `text`.
    fn by_search(literals: &[&[u8]], text: &[u8]) -> bool {
        literals.iter().any(|l| {
            let head = &l[..l.len().min(3)];
            head.is_empty() || text.windows(head.len()).any(|w| w == head)
        })
    }

    #[test]
    fn a_text_holds_a_literal_only_where_its_first_bytes_sit() {
        let rows: &[(&[&[u8]], &str, bool)] = &[
            (&[], "anything", false),
            (&[b"ghp_"], "", false),
            (&[b"ghp_"], "gh", false),
            (&[b"ghp_"], "xghp", true),
            (&[b"ghp_"], "g h p", false),
            (&[b"sk"], "task", true),
            (&[b"sk"], "ends in s", false),
            (&[b"sk"], "s", false),
            (&[b"sk"], "risk", true),
            (&[b"~"], "a~", true),
            (&[b"~"], "a-", false),
            (&[b""], "", true),
            (&[b"abc", b"abd"], "xxabd", true),
            (&[b"abc", b"abd"], "xxabe", false),
            (&[b"abc", b"xy"], "abxy", true),
        ];
        for &(literals, text, want) in rows {
            let set = Prefixes::new(literals.iter().copied());
            assert_eq!(set.may_hold(text.bytes()), want, "{literals:?} in {text:?}");
            assert_eq!(by_search(literals, text.as_bytes()), want, "{text:?}");
        }
    }

    /// One literal past the row limit makes every text a candidate.
    #[test]
    fn too_many_pairs_hold_every_text() {
        let pairs: Vec<[u8; 2]> = (0..=u8::MAX).map(|b| [b'a', b]).collect();
        let set = Prefixes::new(pairs.iter().map(<[u8; 2]>::as_slice));
        assert!(set.may_hold(*b"zz"));
        assert!(set.may_hold(*b""));
    }

    /// A literal at every place in a text of every length around a block edge, so a
    /// pair, its third byte and a single byte each fall on the last byte of a block,
    /// the first of the next and a partial block's end.
    #[test]
    fn folding_a_block_answers_as_the_iterator_does_at_every_block_edge() {
        let sets: &[&[&[u8]]] = &[
            &[b"pas", b"tok"],
            &[b"ab"],
            &[b"x"],
            &[b"pwd", b"pin", b"ssn"],
            &[b"abc", b"abd", b"xy"],
            &[],
        ];
        let fillers: [&[u8]; 3] = [b"-", b"_ .", b"Zz9"];
        let hits: [&[u8]; 6] = [b"pas", b"TOK", b"ab", b"x", b"PwD", b"p-a_s"];
        let mut cases = 0;
        for literals in sets {
            let set = Prefixes::new(literals.iter().copied());
            for filler in fillers {
                for len in [
                    0, 1, 2, 31, 32, 33, 62, 63, 64, 65, 66, 100, 127, 128, 129, 130, 191, 192, 193,
                ] {
                    let base: Vec<u8> = filler.iter().copied().cycle().take(len).collect();
                    for at in 0..=len {
                        for hit in hits {
                            let mut text = base[..at].to_vec();
                            text.extend_from_slice(hit);
                            text.extend_from_slice(&base[at..]);
                            let lower = text.iter().map(u8::to_ascii_lowercase);
                            assert_eq!(
                                set.may_hold_folded(&text, Fold::Lower),
                                set.may_hold(lower),
                                "{literals:?} {text:?}"
                            );
                            let alnum = text
                                .iter()
                                .filter(|b| b.is_ascii_alphanumeric())
                                .map(u8::to_ascii_lowercase);
                            assert_eq!(
                                set.may_hold_folded(&text, Fold::Alnum),
                                set.may_hold(alnum),
                                "{literals:?} {text:?}"
                            );
                            cases += 1;
                        }
                    }
                }
            }
        }
        assert!(cases > 50_000, "{cases}");
    }

    proptest! {
        /// Folding a block at a time answers as reading the bytes one by one does.
        #[test]
        fn folding_a_block_answers_as_the_iterator_does(
            literals in prop::collection::vec(prop::collection::vec(b'a'..=b'e', 0..5), 0..12),
            text in prop::collection::vec(prop::sample::select(b"abcdeABCDE _-9\xc3".to_vec()), 0..200),
        ) {
            let literals: Vec<&[u8]> = literals.iter().map(Vec::as_slice).collect();
            let set = Prefixes::new(literals.iter().copied());
            let lower = text.iter().map(u8::to_ascii_lowercase);
            prop_assert_eq!(set.may_hold_folded(&text, Fold::Lower), set.may_hold(lower));
            let alnum = text.iter().filter(|b| b.is_ascii_alphanumeric()).map(u8::to_ascii_lowercase);
            prop_assert_eq!(set.may_hold_folded(&text, Fold::Alnum), set.may_hold(alnum));
        }

        #[test]
        fn the_table_answers_as_a_search_does(
            literals in prop::collection::vec(prop::collection::vec(b'a'..=b'e', 1..5), 0..12),
            text in prop::collection::vec(b'a'..=b'f', 0..40),
        ) {
            let literals: Vec<&[u8]> = literals.iter().map(Vec::as_slice).collect();
            let set = Prefixes::new(literals.iter().copied());
            prop_assert_eq!(set.may_hold(text.iter().copied()), by_search(&literals, &text));
        }
    }
}