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/field/skeleton.rs
// Purpose:   The form a credential name is compared in, for the field and the text path alike
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A name is matched against the credential terms through its skeleton, so
//! `p<U+0430>ssword` with a Cyrillic a, a full-width `password` and
//! `pass<U+200B>word` with a zero-width space all read as `password`.
//!
//! The skeleton is for matching only: the text a scrub writes is the text it
//! read, never the skeleton. It differs from UTS 39's in one way. ASCII is
//! never remapped, since UTS 39 would read `I` as `l` and `O` as `0`, and a
//! name that matches today has to match tomorrow. Every other character is
//! mapped by UTS 39's table with its case kept, a full-width form first folds
//! to its ASCII one, and characters that print nothing or only mark the one
//! before are dropped.

use std::borrow::Cow;
use std::sync::LazyLock;

use unicode_security::confusable_detection::skeleton as confusable;

use super::is_ignorable;
use crate::scrub::classes::{class_ranges, range_of};

/// The combining marks, which a skeleton drops.
static MARKS: LazyLock<Vec<(u32, u32)>> = LazyLock::new(|| class_ranges(r"\p{M}"));

/// Whether `c` is a combining mark.
pub(in crate::scrub) fn is_mark(c: char) -> bool {
    !c.is_ascii() && range_of(&MARKS, c).is_some()
}

/// The ASCII character a full-width form stands for.
const fn narrow(c: char) -> Option<char> {
    match c {
        '\u{ff01}'..='\u{ff5e}' => char::from_u32(c as u32 - 0xfee0),
        _ => None,
    }
}

/// The four hex digits after a `\u` at the start of `rest`, as a UTF-16 code unit.
fn code_unit(rest: &str) -> Option<u16> {
    let hex = rest.strip_prefix("\\u")?.get(..4)?;
    hex.bytes()
        .all(|b| b.is_ascii_hexdigit())
        .then(|| u16::from_str_radix(hex, 16).ok())
        .flatten()
}

/// The length of the `\uXXXX` escape ending `text`, or 0 when none does.
pub(super) fn escape_before(text: &str) -> usize {
    let at = text.len().saturating_sub(6);
    usize::from(text.is_char_boundary(at) && code_unit(&text[at..]).is_some()) * 6
}

/// Whether `b` may sit in the parameters of an SGR sequence.
const fn is_sgr_param(b: u8) -> bool {
    b.is_ascii_digit() || b == b';'
}

/// The length of the ANSI colour sequence, `ESC [` parameters `m`, at the start of `text`, or 0.
pub(super) fn sgr_len(text: &str) -> usize {
    let bytes = text.as_bytes();
    if !bytes.starts_with(b"\x1b[") {
        return 0;
    }
    let params = bytes[2..].iter().take_while(|&&b| is_sgr_param(b)).count();
    if bytes.get(2 + params) == Some(&b'm') {
        3 + params
    } else {
        0
    }
}

/// The length of the ANSI colour sequence ending `text`, or 0.
pub(super) fn sgr_before(text: &str) -> usize {
    let bytes = text.as_bytes();
    let Some((&b'm', head)) = bytes.split_last() else {
        return 0;
    };
    let params = head.iter().rev().take_while(|&&b| is_sgr_param(b)).count();
    let open = head.len() - params;
    if head[..open].ends_with(b"\x1b[") {
        params + 3
    } else {
        0
    }
}

/// Whether `text` holds a byte that may start an escape or a colour sequence, a `\u` or an ESC.
pub(super) fn may_escape(text: &str) -> bool {
    let bytes = text.as_bytes();
    let mut at = 0;
    while let Some(found) = memchr::memchr2(b'\\', 0x1b, &bytes[at..]) {
        let i = at + found;
        if bytes[i] == 0x1b || bytes.get(i + 1) == Some(&b'u') {
            return true;
        }
        at = i + 1;
    }
    false
}

/// `name` with each JSON `\uXXXX` escape read as the character it writes, a
/// surrogate pair as one character and a lone surrogate as U+FFFD, and each
/// ANSI colour sequence dropped.
fn unescape(name: &str) -> Cow<'_, str> {
    if !may_escape(name) {
        return Cow::Borrowed(name);
    }
    let mut out = String::with_capacity(name.len());
    let mut rest = name;
    while let Some(c) = rest.chars().next() {
        let sgr = sgr_len(rest);
        if sgr > 0 {
            rest = &rest[sgr..];
            continue;
        }
        let Some(unit) = code_unit(rest) else {
            out.push(c);
            rest = &rest[c.len_utf8()..];
            continue;
        };
        rest = &rest[6..];
        let low = code_unit(rest).filter(|l| (0xdc00..0xe000).contains(l));
        match (unit, low) {
            (0xd800..0xdc00, Some(low)) => {
                rest = &rest[6..];
                let pair = [unit, low];
                out.extend(char::decode_utf16(pair).map(|c| c.unwrap_or('\u{fffd}')));
            }
            _ => out.push(char::from_u32(u32::from(unit)).unwrap_or('\u{fffd}')),
        }
    }
    Cow::Owned(out)
}

/// `name` as it is compared, borrowed when it is ASCII with no escape in it
/// and so is its own skeleton.
pub(in crate::scrub) fn skeleton(name: &str) -> Cow<'_, str> {
    let name = unescape(name);
    if name.is_ascii() {
        return name;
    }
    let name = name.as_ref();
    let mut out = String::with_capacity(name.len());
    let mut utf8 = [0; 4];
    for c in name.chars() {
        if c.is_ascii() {
            out.push(c);
        } else if is_ignorable(c) || is_mark(c) {
            // Prints nothing, or only marks the character before.
        } else if let Some(ascii) = narrow(c) {
            out.push(ascii);
        } else if c.is_uppercase() {
            // UTS 39 maps lower-case letters, so an upper-case one is mapped by
            // its lower-case form and its case put back: `P` and `p` in Cyrillic
            // then differ as `P` and `p` do.
            for lower in c.to_lowercase() {
                let mapped = confusable(lower.encode_utf8(&mut utf8));
                out.extend(mapped.filter(|&m| !is_mark(m)).flat_map(char::to_uppercase));
            }
        } else {
            out.extend(confusable(c.encode_utf8(&mut utf8)).filter(|&m| !is_mark(m)));
        }
    }
    Cow::Owned(out)
}