grippo 0.2.1

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/scrub/target.rs
// Purpose:   One pair of entry points over every record a scrubber scrubs whole
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`Scrubber::scrub_in_place`] and [`Scrubber::scrub`] over any [`Scrub`]
//! record: a serde `Value`, parser `Fields`, or raw bytes named by format with
//! [`TextBytes`], `JsonBytes`, `XmlBytes` or `LayeredBytes`.

use std::borrow::Cow;
use std::convert::Infallible;

use super::{Report, ScrubScratch, Scrubber};

/// A record a [`Scrubber`] scrubs whole, through [`Scrubber::scrub_in_place`]
/// or [`Scrubber::scrub`].
///
/// Each method counts what it finds into `report`, adding to what's there,
/// and may have counted part of a record it returns an error for. Call them
/// through the two [`Scrubber`] methods, which count only a record that
/// scrubs.
pub trait Scrub: Clone {
    /// Why the record couldn't be scrubbed: [`crate::record::Miss`] for bytes
    /// that don't read as their format, [`Infallible`] for a record that
    /// always reads.
    type Error;

    /// Rewrite the record. `true` when anything changed.
    ///
    /// # Errors
    ///
    /// [`Scrub::Error`] when the record doesn't read, or can't be written
    /// back as it reads. Raw bytes are left as they were.
    fn scrub_in_place(
        &mut self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<bool, Self::Error>;

    /// The rewritten record, `None` when nothing changed.
    ///
    /// # Errors
    ///
    /// As [`Scrub::scrub_in_place`].
    fn scrubbed(
        &self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Self>, Self::Error>;
}

/// Free text, scrubbed as [`Scrubber::scrub_text`] scrubs it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TextBytes(pub Vec<u8>);

impl Scrub for TextBytes {
    type Error = Infallible;

    fn scrub_in_place(
        &mut self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<bool, Infallible> {
        let Some(out) = scrubber.scrub_text(&self.0, scratch, report) else {
            return Ok(false);
        };
        self.0.clear();
        self.0.extend_from_slice(&out);
        Ok(true)
    }

    fn scrubbed(
        &self,
        scrubber: &Scrubber,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Option<Self>, Infallible> {
        Ok(scrubber.scrub_text(&self.0, scratch, report).map(Self))
    }
}

impl Scrubber {
    /// Scrub `target` in place, counting into `report`. `true` when anything
    /// changed.
    ///
    /// A clean record is left as it was: raw bytes aren't copied and their
    /// buffer isn't touched. A changed one is rewritten in its own buffer,
    /// whose allocation is kept where it's big enough.
    ///
    /// ```
    /// # #[cfg(feature = "record")] {
    /// use grippo::scrub::{FIELD_RULE, JsonBytes, Kind, RuleConfig, Scrubber};
    ///
    /// let scrubber = Scrubber::new(&RuleConfig::default()).unwrap();
    /// let (mut scratch, mut report) = (scrubber.scratch(), scrubber.report());
    /// let mut line = JsonBytes(br#"{"msg":"login","password":"hunter2"}"#.to_vec());
    /// assert_eq!(scrubber.scrub_in_place(&mut line, &mut scratch, &mut report), Ok(true));
    /// assert_eq!(line.0, br#"{"msg":"login","password":"[CREDENTIAL_FIELD_REDACTED]"}"#);
    /// assert_eq!(report.count(FIELD_RULE, Kind::Redacted), 1);
    /// # }
    /// ```
    ///
    /// # Errors
    ///
    /// [`Scrub::Error`] when the record doesn't read as its format, or can't
    /// be written back as it reads. Raw bytes are left as they were and
    /// `report` counts nothing for the record.
    pub fn scrub_in_place<T: Scrub>(
        &self,
        target: &mut T,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<bool, T::Error> {
        self.counted(scratch, report, |s, r| target.scrub_in_place(self, s, r))
    }

    /// Scrub `target`, counting into `report`: [`Cow::Borrowed`] `target`
    /// when nothing changed, else [`Cow::Owned`], a new copy.
    ///
    /// # Errors
    ///
    /// As [`Scrubber::scrub_in_place`].
    pub fn scrub<'t, T: Scrub>(
        &self,
        target: &'t T,
        scratch: &mut ScrubScratch,
        report: &mut Report,
    ) -> Result<Cow<'t, T>, T::Error> {
        let copy = self.counted(scratch, report, |s, r| target.scrubbed(self, s, r))?;
        Ok(copy.map_or(Cow::Borrowed(target), Cow::Owned))
    }

    /// Run `scrub` counting into the scratch's pending report, and add those
    /// counts to `report` only when it returns `Ok`.
    fn counted<R, E>(
        &self,
        scratch: &mut ScrubScratch,
        report: &mut Report,
        scrub: impl FnOnce(&mut ScrubScratch, &mut Report) -> Result<R, E>,
    ) -> Result<R, E> {
        let mut pending = scratch.pending.take().unwrap_or_else(|| self.report());
        self.own(&mut pending);
        pending.clear();
        let done = scrub(scratch, &mut pending);
        if done.is_ok() {
            self.own(report);
            report.absorb(&pending);
        }
        scratch.pending = Some(pending);
        done
    }
}