grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/scrub/walk.rs
// Purpose:   The structured scrub rules over one walk of a record, whatever holds it
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The rules a record's structure adds to [`Scrubber::scrub_field`], over a
//! flat list of its values in document order:
//!
//! - A number or bool is redacted only under a credential field name.
//! - A list or object under a credential field name goes whole.
//! - A list element `[name, value]` whose name is a credential is a pair:
//!   the value is scrubbed as a field of that name.
//!
//! A source turns its record into [`Event`]s and reads values through
//! [`Values`], so a serde `Value`, raw JSON and parser fields get the same
//! answers. A number's or container's text is read as `serde_json` writes it,
//! so a hashed token, and a count under a name such as `max_tokens`, read the
//! same from every source.

use std::borrow::Cow;
#[cfg(feature = "record")]
use std::fmt::Write as _;

use super::{FieldLayer, Layer, Report, Scope, ScrubScratch, Scrubber};

/// What a value is, as far as the rules care.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Shape {
    Str,
    /// A number or a bool.
    Scalar,
    Null,
    List,
    Map,
}

/// One value of a record, in document order.
#[derive(Debug)]
pub(super) struct Event<'a, P> {
    depth: usize,
    key: Option<Cow<'a, str>>,
    shape: Shape,
    pos: P,
    /// The index of the first event after its members.
    next: usize,
    /// A pair's name, which is never scrubbed itself.
    name: bool,
}

impl<'a, P> Event<'a, P> {
    pub(super) const fn new(depth: usize, key: Option<Cow<'a, str>>, shape: Shape, pos: P) -> Self {
        Self {
            depth,
            key,
            shape,
            pos,
            next: 0,
            name: false,
        }
    }
}

/// Reads the values the rules need from a source. `None` when the value
/// can't be read.
pub(super) trait Values<'a, P> {
    /// A string's bytes, decoded.
    fn bytes(&self, pos: P) -> Option<Cow<'a, [u8]>>;
    /// A number's or bool's text as `serde_json` writes it, into `out`.
    fn scalar(&self, pos: P, out: &mut String) -> Option<()>;
    /// A list's or object's JSON as `serde_json` writes it.
    fn container(&self, pos: P) -> Option<String>;
}

/// A value a source couldn't read.
#[derive(Debug)]
pub(super) struct Malformed;

impl Scrubber {
    /// Scrub the values in `events`, calling `masked` with each one replaced
    /// and its new bytes, a string, in document order.
    pub(super) fn scrub_events<'a, P: Copy>(
        &self,
        events: &mut [Event<'a, P>],
        values: &impl Values<'a, P>,
        scratch: &mut ScrubScratch,
        report: &mut Report,
        masked: impl FnMut(P, Vec<u8>),
    ) -> Result<(), Malformed> {
        self.own(report);
        let mut stack = std::mem::take(&mut scratch.stack);
        let mut path: Vec<&str> = recycle(std::mem::take(&mut scratch.path));
        link(events, &mut stack);
        self.mark_pairs(events, values, scratch, &mut stack);
        let done = self.scrub_linked(
            events, values, scratch, report, masked, &mut stack, &mut path,
        );
        scratch.stack = stack;
        scratch.path = recycle(path);
        done
    }

    /// [`Scrubber::scrub_events`] once `events` are linked and their pairs
    /// marked, with `lens` and `path` as working space.
    #[allow(clippy::too_many_arguments, reason = "the walk's working buffers")]
    fn scrub_linked<'a, 'e, P: Copy>(
        &self,
        events: &'e [Event<'a, P>],
        values: &impl Values<'a, P>,
        scratch: &mut ScrubScratch,
        report: &mut Report,
        mut masked: impl FnMut(P, Vec<u8>),
        lens: &mut Vec<usize>,
        path: &mut Vec<&'e str>,
    ) -> Result<(), Malformed> {
        // The path's length after the event at each depth.
        lens.clear();
        let mut i = 0;
        while let Some(e) = events.get(i) {
            lens.truncate(e.depth);
            path.truncate(lens.last().copied().unwrap_or(0));
            if let Some(k) = e.key.as_deref() {
                path.push(k);
            }
            lens.push(path.len());
            i += 1;
            if e.name {
                continue;
            }
            match self.scope_of(path) {
                Scope::In => {}
                Scope::Above => continue,
                Scope::Out => {
                    i = e.next;
                    continue;
                }
            }
            let out = match e.shape {
                Shape::Null => None,
                Shape::List | Shape::Map => {
                    if e.key.is_none() {
                        continue;
                    }
                    let excepted = self.exceptions.iter().any(|x| x.covers(path));
                    // A container whose text can't be read is hashed as an empty one.
                    let text = || {
                        values.container(e.pos).unwrap_or_else(|| {
                            let empty = if e.shape == Shape::List { "[]" } else { "{}" };
                            empty.to_owned()
                        })
                    };
                    let layer = self.container_layer(path, excepted, text, scratch, report);
                    match layer {
                        FieldLayer::Replaced(out) => {
                            i = e.next;
                            Some(out)
                        }
                        FieldLayer::Kept if !excepted => {
                            i = e.next;
                            None
                        }
                        FieldLayer::Kept | FieldLayer::NotCredential => None,
                    }
                }
                Shape::Str => {
                    let bytes = values.bytes(e.pos).ok_or(Malformed)?;
                    self.scrub_field(path, &bytes, scratch, report)
                }
                Shape::Scalar => {
                    let mut text = std::mem::take(&mut scratch.number);
                    text.clear();
                    let read = values.scalar(e.pos, &mut text);
                    let out = read
                        .and_then(|()| self.scrub_number(path, text.as_bytes(), scratch, report));
                    scratch.number = text;
                    read.ok_or(Malformed)?;
                    out
                }
            };
            if let Some(out) = out {
                masked(e.pos, out);
            }
        }
        Ok(())
    }

    /// The FIELD layer for a list or object: its JSON is read only when its
    /// name is a credential.
    fn container_layer(
        &self,
        path: &[&str],
        excepted: bool,
        text: impl FnOnce() -> String,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> FieldLayer {
        let name = path.last().copied().unwrap_or_default();
        let parent = path.len().checked_sub(2).map_or("", |i| path[i]);
        if !self.layers.runs(Layer::Field)
            || name.is_empty()
            || !self
                .credentials
                .matches_in(name, parent, &mut scratch.spellings)
        {
            return FieldLayer::NotCredential;
        }
        self.field_layer(path, text().as_bytes(), excepted, scratch, report)
    }

    /// Marks each pair: a list element that is a list of a string naming a
    /// credential, then one value. The value takes the name as its key.
    fn mark_pairs<'a, P: Copy>(
        &self,
        events: &mut [Event<'a, P>],
        values: &impl Values<'a, P>,
        scratch: &mut ScrubScratch,
        keyed: &mut Vec<usize>,
    ) {
        // The keyed events above the current one, innermost last.
        keyed.clear();
        for i in 0..events.len() {
            let (depth, end) = (events[i].depth, events[i].next);
            while keyed.last().is_some_and(|&j| events[j].depth >= depth) {
                keyed.pop();
            }
            if events[i].key.is_some() {
                keyed.push(i);
                continue;
            }
            let first = i + 1;
            let item = depth > 0 && events[i].shape == Shape::List;
            if !item || first >= end || events[first].shape != Shape::Str {
                continue;
            }
            let second = events[first].next;
            if second >= end || events[second].next != end {
                continue;
            }
            let Some(name) = values.bytes(events[first].pos).and_then(utf8) else {
                continue;
            };
            let parent = keyed
                .last()
                .and_then(|&j| events[j].key.as_deref())
                .unwrap_or_default();
            if self
                .credentials
                .matches_in(&name, parent, &mut scratch.spellings)
            {
                events[second].key = Some(name);
                events[first].name = true;
            }
        }
    }
}

/// Sets each event's `next`: the first event that isn't one of its members.
fn link<P>(events: &mut [Event<'_, P>], open: &mut Vec<usize>) {
    open.clear();
    for i in 0..events.len() {
        while let Some(&j) = open.last() {
            if events[j].depth < events[i].depth {
                break;
            }
            events[j].next = i;
            open.pop();
        }
        open.push(i);
    }
    for &j in &*open {
        events[j].next = events.len();
    }
}

/// An empty `Vec<U>` in `v`'s allocation: std's in-place collect keeps it when
/// `T` and `U` share a size and alignment, as one type at two lifetimes does.
pub(super) fn recycle<T, U>(mut v: Vec<T>) -> Vec<U> {
    v.clear();
    v.into_iter().filter_map(|_| None).collect()
}

/// Bytes as text, `None` when they aren't UTF-8.
fn utf8(bytes: Cow<'_, [u8]>) -> Option<Cow<'_, str>> {
    match bytes {
        Cow::Borrowed(b) => std::str::from_utf8(b).ok().map(Cow::Borrowed),
        Cow::Owned(b) => String::from_utf8(b).ok().map(Cow::Owned),
    }
}

/// A number's text as `serde_json` writes the number it parses to, into `out`.
/// Text that isn't a JSON number is written as it is.
#[cfg(feature = "record")]
pub(super) fn number_text(raw: &str, out: &mut String) {
    let digits = raw.strip_prefix('-').unwrap_or(raw);
    let plain = raw == "0"
        || (digits.len() <= 18
            && digits.bytes().all(|b| b.is_ascii_digit())
            && digits.bytes().next().is_some_and(|b| b != b'0'));
    match serde_json::from_str::<serde_json::Number>(raw) {
        Ok(n) if !plain => {
            // Writing to a String can't fail.
            let _ = write!(out, "{n}");
        }
        _ => out.push_str(raw),
    }
}

/// JSON text as `serde_json` writes the value it parses to. Text that doesn't
/// parse is kept as it is.
#[cfg(feature = "record")]
pub(super) fn json_text(text: &str) -> String {
    serde_json::from_str::<serde_json::Value>(text)
        .map_or_else(|_| text.to_owned(), |v| v.to_string())
}

/// The rules' reads over any record that walks.
#[cfg(feature = "record")]
pub(super) struct RecordValues<R>(pub(super) R);

#[cfg(feature = "record")]
impl<'a, R: crate::record::Walk<'a>> Values<'a, R::At> for RecordValues<R> {
    fn bytes(&self, at: R::At) -> Option<Cow<'a, [u8]>> {
        self.0.bytes(at).ok()
    }

    fn scalar(&self, at: R::At, out: &mut String) -> Option<()> {
        number_text(&self.0.text(at).ok()?, out);
        Some(())
    }

    fn container(&self, at: R::At) -> Option<String> {
        self.0.text(at).ok().map(|text| json_text(&text))
    }
}

/// The shape the rules give a kind of record value.
#[cfg(feature = "record")]
pub(super) const fn shape(kind: crate::record::Kind) -> Shape {
    use crate::record::Kind;
    match kind {
        Kind::Str => Shape::Str,
        Kind::Number | Kind::Bool => Shape::Scalar,
        Kind::Null => Shape::Null,
        Kind::List => Shape::List,
        Kind::Map => Shape::Map,
    }
}