grippo 0.2.4

Parse, match and scrub data faster and more efficiently.
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
    }
}

#[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""));
    }

    proptest! {
        #[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));
        }
    }
}