grippo 0.1.2

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/scrub/json.rs
// Purpose:   Scrub a JSON record in place, field by field with its key path
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`Scrubber::scrub_value`]: the record's structure rules, then every string
//! through [`Scrubber::scrub_field`] with its key path. An array element
//! takes the array's key as its name, so `passwords: [..]` redacts each
//! element. Both walks keep their own stack, so nesting depth can't overflow
//! the thread's.

use std::borrow::Cow;
use std::fmt::Write as _;

use serde_json::Value;

use super::walk::{Event, Shape, Values};
use super::{Report, ScrubScratch, Scrubber};

impl Scrubber {
    /// Scrub `value` in place. `true` when anything changed.
    ///
    /// A redacted number or boolean becomes its token, a string. A number or
    /// boolean is redacted only under a credential field name, never for its
    /// digits.
    pub fn scrub_value(
        &self,
        value: &mut Value,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> bool {
        let mut edits: Vec<(usize, Vec<u8>)> = Vec::new();
        let root: &Value = value;
        let mut events = events(root);
        let read = self.scrub_events(&mut events, &ValueReads, scratch, report, |at, out| {
            edits.push((std::ptr::from_ref(at).addr(), out));
        });
        // A Value's reads can't fail.
        debug_assert!(read.is_ok());
        drop(events);
        if edits.is_empty() {
            return false;
        }
        replace(value, &edits);
        true
    }
}

/// Every value in `root`, in document order.
fn events(root: &Value) -> Vec<Event<'_, &Value>> {
    let mut out = Vec::new();
    let mut todo: Vec<(&Value, usize, Option<&str>)> = vec![(root, 0, None)];
    while let Some((v, depth, key)) = todo.pop() {
        let shape = match v {
            Value::Null => Shape::Null,
            Value::Bool(_) | Value::Number(_) => Shape::Scalar,
            Value::String(_) => Shape::Str,
            Value::Array(items) => {
                todo.extend(items.iter().rev().map(|c| (c, depth + 1, None)));
                Shape::List
            }
            Value::Object(map) => {
                todo.extend(
                    map.iter()
                        .rev()
                        .map(|(k, c)| (c, depth + 1, Some(k.as_str()))),
                );
                Shape::Map
            }
        };
        out.push(Event::new(depth, key.map(Cow::Borrowed), shape, v));
    }
    out
}

/// Replaces each value at an address in `edits` with its string, the edits
/// in the order [`events`] walks.
fn replace(root: &mut Value, edits: &[(usize, Vec<u8>)]) {
    let mut next = edits.iter().peekable();
    let mut todo: Vec<&mut Value> = vec![root];
    while let Some(node) = todo.pop() {
        let Some((addr, out)) = next.peek() else {
            break;
        };
        if std::ptr::from_ref::<Value>(node).addr() == *addr {
            *node = Value::String(String::from_utf8_lossy(out).into_owned());
            next.next();
            continue;
        }
        match node {
            Value::Object(map) => todo.extend(map.values_mut().rev()),
            Value::Array(items) => todo.extend(items.iter_mut().rev()),
            _ => {}
        }
    }
}

/// The rules' reads over a `Value`.
struct ValueReads;

impl<'a> Values<'a, &'a Value> for ValueReads {
    fn bytes(&self, at: &'a Value) -> Option<Cow<'a, [u8]>> {
        match at {
            Value::String(s) => Some(Cow::Borrowed(s.as_bytes())),
            _ => None,
        }
    }

    fn scalar(&self, at: &'a Value, out: &mut String) -> Option<()> {
        match at {
            // Writing to a String can't fail.
            Value::Number(n) => write!(out, "{n}").ok(),
            Value::Bool(b) => {
                out.push_str(if *b { "true" } else { "false" });
                Some(())
            }
            _ => None,
        }
    }

    fn container(&self, at: &'a Value) -> Option<String> {
        serde_json::to_string(at).ok()
    }
}