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/closed.rs
// Purpose:   Mask the values of a record that doesn't read, never pass it on
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A record that fails to read, over a lone surrogate escape, an invalid
//! byte or a stray character, is masked rather than handed back as it came.
//! The scan keeps only the delimiters and white space and masks every token,
//! names included, because a read that failed has established no key, element
//! or nesting, so a colon or a `<` before a token is no proof it is a name and
//! not a credential. A quoted value that never closes leaves no token to
//! delimit, and a record with no token has nothing to keep, so in both the
//! whole record is the mask. A record in a format with no scan of its own is
//! the mask whole.

/// The UTF-8 byte order mark, which a scrub leaves at the head of a record.
const BOM: &[u8] = b"\xEF\xBB\xBF";

/// The scan a record that doesn't read is masked with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Unread {
    Json,
    #[cfg(feature = "xml")]
    Xml,
    /// No scan: the record is the mask.
    Whole,
}

/// `bytes` masked by the scan `unread` names, into `out`. Returns how many
/// masks were written, at least 1.
pub(super) fn mask(unread: Unread, bytes: &[u8], mask: &[u8], out: &mut Vec<u8>) -> usize {
    match unread {
        Unread::Json => mask_unparsed(bytes, mask, out),
        #[cfg(feature = "xml")]
        Unread::Xml => mask_unparsed_xml(bytes, mask, out),
        Unread::Whole => {
            out.clear();
            out.extend_from_slice(mask);
            1
        }
    }
}

/// `out` cleared, with the byte order mark `bytes` starts with, and where the
/// record's own bytes start.
fn keep_bom(bytes: &[u8], out: &mut Vec<u8>) -> usize {
    out.clear();
    if bytes.starts_with(BOM) {
        out.extend_from_slice(BOM);
        BOM.len()
    } else {
        0
    }
}

/// `json` written to `out` with every string, number and bare word replaced by
/// `mask` as a JSON string, and the delimiters and white space between them
/// kept. Returns how many masks were written, at least 1: a string that never
/// closes, or a record with no token in it, leaves `out` holding the mask alone.
pub(super) fn mask_unparsed(json: &[u8], mask: &[u8], out: &mut Vec<u8>) -> usize {
    let mut at = keep_bom(json, out);
    let mut masked = 0;
    while let Some(&b) = json.get(at) {
        match b {
            b'"' => {
                let Some(end) = string_end(json, at) else {
                    return whole(mask, out);
                };
                push_mask(out, mask);
                masked += 1;
                at = end;
            }
            b'{' | b'}' | b'[' | b']' | b',' | b':' | b' ' | b'\t' | b'\n' | b'\r' => {
                out.push(b);
                at += 1;
            }
            _ => {
                at += json[at..].iter().take_while(|&&b| !ends_word(b)).count();
                push_mask(out, mask);
                masked += 1;
            }
        }
    }
    if masked == 0 {
        return whole(mask, out);
    }
    masked
}

/// `out` holding `mask` alone, the one mask a record that can't be scanned becomes.
fn whole(mask: &[u8], out: &mut Vec<u8>) -> usize {
    out.clear();
    push_mask(out, mask);
    1
}

/// Where the string opening at `at` ends, past its closing quote, or `None`
/// when it never closes. A backslash escapes the byte after it, whatever it is.
fn string_end(json: &[u8], at: usize) -> Option<usize> {
    let mut i = at + 1;
    loop {
        match json.get(i)? {
            b'"' => return Some(i + 1),
            b'\\' => i += 2,
            _ => i += 1,
        }
    }
}

/// Whether `b` ends a bare word.
const fn ends_word(b: u8) -> bool {
    matches!(
        b,
        b'"' | b'{' | b'}' | b'[' | b']' | b',' | b':' | b' ' | b'\t' | b'\n' | b'\r'
    )
}

/// `mask` as a JSON string.
fn push_mask(out: &mut Vec<u8>, mask: &[u8]) {
    out.push(b'"');
    out.extend_from_slice(mask);
    out.push(b'"');
}

/// Whether `b` is XML white space.
#[cfg(feature = "xml")]
const fn xml_space(b: u8) -> bool {
    matches!(b, b' ' | b'\t' | b'\n' | b'\r')
}

/// Whether `b` ends a name or other run inside markup.
#[cfg(feature = "xml")]
const fn ends_xml_run(b: u8) -> bool {
    matches!(b, b'<' | b'>' | b'/' | b'=') || xml_space(b)
}

/// `xml` written to `out` with every name, quoted attribute value and run of
/// text replaced by `mask`, and markup's `<`, `>`, `/` and `=`, a value's
/// quotes and the white space between them kept. Text that is all white space
/// stays. A quote opens a value only after an `=`, so the `'` in a comment's
/// `don't` is part of its run. Returns how many masks were written, at least
/// 1: a value that never closes, or a document with no token in it, leaves
/// `out` holding the mask alone. `mask` holds no byte XML escapes.
#[cfg(feature = "xml")]
pub(super) fn mask_unparsed_xml(xml: &[u8], mask: &[u8], out: &mut Vec<u8>) -> usize {
    let mut at = keep_bom(xml, out);
    let mut masked = 0;
    let mut tag = false;
    let mut after_equals = false;
    while let Some(&b) = xml.get(at) {
        if !tag {
            if b == b'<' {
                out.push(b);
                tag = true;
                after_equals = false;
                at += 1;
                continue;
            }
            let end = memchr::memchr(b'<', &xml[at..]).map_or(xml.len(), |n| at + n);
            let run = &xml[at..end];
            if run.iter().all(|&b| xml_space(b)) {
                out.extend_from_slice(run);
            } else {
                out.extend_from_slice(mask);
                masked += 1;
            }
            at = end;
            continue;
        }
        match b {
            b'"' | b'\'' if after_equals => {
                let Some(close) = memchr::memchr(b, &xml[at + 1..]) else {
                    return whole_xml(mask, out);
                };
                out.push(b);
                out.extend_from_slice(mask);
                out.push(b);
                masked += 1;
                at += close + 2;
                after_equals = false;
            }
            _ if ends_xml_run(b) => {
                out.push(b);
                tag = b != b'>';
                if !xml_space(b) {
                    after_equals = b == b'=';
                }
                at += 1;
            }
            _ => {
                at += xml[at..].iter().take_while(|&&b| !ends_xml_run(b)).count();
                out.extend_from_slice(mask);
                masked += 1;
                after_equals = false;
            }
        }
    }
    if masked == 0 {
        return whole_xml(mask, out);
    }
    masked
}

/// `out` holding `mask` alone, the one mask a document that can't be scanned becomes.
#[cfg(feature = "xml")]
fn whole_xml(mask: &[u8], out: &mut Vec<u8>) -> usize {
    out.clear();
    out.extend_from_slice(mask);
    1
}