grippo 0.1.1

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/scrub/record.rs
// Purpose:   Scrub any record that walks: raw JSON bytes, parser fields, or a source of your own
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`Scrubber::scrub_record`] runs the structure rules [`Scrubber::scrub_value`]
//! runs over any [`Walk`] record and hands back what it replaced.
//! [`Scrubber::scrub_json_bytes`] and [`Scrubber::scrub_fields`] write those
//! back to raw JSON and to [`Fields`], and `scrub_xml_bytes` to raw XML.

#[cfg(feature = "parse")]
use crate::parse::Fields;
use crate::record::{Json, Miss, Walk};
#[cfg(feature = "xml")]
use crate::record::{Xml, XmlAt};

use super::walk::{Event, Malformed, RecordValues, shape};
use super::{Report, ScrubScratch, Scrubber};

impl Scrubber {
    /// Scrub a record, calling `masked` with each value it replaces and the
    /// bytes that value becomes, a string, in document order.
    ///
    /// The rules are [`Scrubber::scrub_value`]'s: a string goes through
    /// [`Scrubber::scrub_field`] with its key path, a number or bool is
    /// redacted only under a credential field name, a list or object under
    /// one goes whole, and a list element `[name, value]` naming a
    /// credential is a pair.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the record is broken, found before anything
    /// is counted.
    pub fn scrub_record<'a, R: Walk<'a>>(
        &self,
        record: R,
        scratch: &mut ScrubScratch,
        report: &mut Report,
        masked: impl FnMut(R::At, Vec<u8>),
    ) -> Result<(), Miss> {
        let mut events = Vec::new();
        record.walk(|n| events.push(Event::new(n.depth, n.key, shape(n.kind), n.at)))?;
        self.scrub_events(&mut events, &RecordValues(record), scratch, report, masked)
            .map_err(|Malformed| Miss::Malformed)
    }

    /// Scrub a raw JSON record. `None` when nothing changed, else the record
    /// with each replaced value written as a JSON string at its place and
    /// every other byte as it was.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the bytes aren't JSON.
    pub fn scrub_json_bytes(
        &self,
        json: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Vec<u8>>, Miss> {
        let record = Json::new(json);
        let mut edits: Vec<(&str, Vec<u8>)> = Vec::new();
        self.scrub_record(record, scratch, report, |at, out| edits.push((at, out)))?;
        if edits.is_empty() {
            return Ok(None);
        }
        let mut out = Vec::with_capacity(json.len() + 32 * edits.len());
        record.splice_strings(&edits, &mut out)?;
        Ok(Some(out))
    }

    /// Scrub a raw XML document. `None` when nothing changed, else the
    /// document with each replaced value written as escaped text at its
    /// place and every other byte as it was. [`Xml::splice_text`] says how an
    /// element with child elements is replaced.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when the bytes aren't XML a walk reads.
    #[cfg(feature = "xml")]
    pub fn scrub_xml_bytes(
        &self,
        xml: &[u8],
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Vec<u8>>, Miss> {
        let record = Xml::new(xml);
        let mut edits: Vec<(XmlAt, Vec<u8>)> = Vec::new();
        self.scrub_record(record, scratch, report, |at, out| edits.push((at, out)))?;
        if edits.is_empty() {
            return Ok(None);
        }
        let mut out = Vec::with_capacity(xml.len() + 32 * edits.len());
        record.splice_text(&edits, &mut out)?;
        Ok(Some(out))
    }

    /// Scrub the fields a parser chain wrote, in place, read as
    /// [`Walk`] reads them. `true` when anything changed.
    ///
    /// A replaced value becomes a `Hint::Text` field. A list or object under
    /// a credential name becomes one field under that name. A value inside a
    /// `Hint::Json` field is replaced in its JSON.
    ///
    /// # Errors
    ///
    /// [`Miss::Malformed`] when a name nests too deep to walk.
    #[cfg(feature = "parse")]
    pub fn scrub_fields(
        &self,
        fields: &mut Fields<'_>,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<bool, Miss> {
        let view: &Fields<'_> = fields;
        let mut edits = Vec::new();
        self.scrub_record(view, scratch, report, |at, out| edits.push((at, out)))?;
        let spots = edits
            .into_iter()
            .map(|(at, out)| crate::record::spot(view, at).map(|s| (s, out)))
            .collect::<Result<Vec<_>, Miss>>()?;
        if spots.is_empty() {
            return Ok(false);
        }
        crate::record::write_strings(fields, spots)?;
        Ok(true)
    }
}