grippo 0.2.3

Parse, match and scrub data faster and more efficiently.
Documentation
// Project:   grippo
// File:      src/scrub/report.rs
// Purpose:   Per-record counts by rule and kind
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! What a scrub did to one record, counted by rule and kind. Never the
//! matched bytes or where they were.

use std::sync::Arc;

/// What happened to one match.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Kind {
    /// Replaced in the output.
    Redacted,
    /// Found under [`super::Redaction::Observe`], bytes left as they were.
    Observed,
    /// Dropped by a global or rule allowlist.
    AllowlistedValue,
    /// Dropped by the rule's entropy gate.
    LowEntropy,
    /// Left alone because its field path is excepted.
    ExceptedField,
}

impl Kind {
    /// Every kind, in slot order.
    pub const ALL: [Self; 5] = [
        Self::Redacted,
        Self::Observed,
        Self::AllowlistedValue,
        Self::LowEntropy,
        Self::ExceptedField,
    ];

    /// The metric label: `redacted`, `observed`, `allowlisted_value`,
    /// `low_entropy`, `excepted_field`.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Redacted => "redacted",
            Self::Observed => "observed",
            Self::AllowlistedValue => "allowlisted_value",
            Self::LowEntropy => "low_entropy",
            Self::ExceptedField => "excepted_field",
        }
    }

    const fn slot(self) -> usize {
        match self {
            Self::Redacted => 0,
            Self::Observed => 1,
            Self::AllowlistedValue => 2,
            Self::LowEntropy => 3,
            Self::ExceptedField => 4,
        }
    }
}

/// The layer a rule belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Layer {
    /// Credentials found by their own pattern: gitleaks' rules.
    Secret,
    /// Values whose field name says they are credentials.
    Field,
    /// Personal data confirmed by its own check: cards, IBANs, emails,
    /// national ids.
    Pii,
    /// Credential pairs found in free text.
    Text,
}

impl Layer {
    /// The metric label: `secret`, `field`, `pii` or `text`.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Secret => "secret",
            Self::Field => "field",
            Self::Pii => "pii",
            Self::Text => "text",
        }
    }
}

/// A rule as reports name it.
#[derive(Debug)]
pub(super) struct RuleMeta {
    pub id: Box<str>,
    /// `id` upper-cased with `-` as `_`, the stem of a redaction token.
    pub token: Box<str>,
    pub layer: Layer,
}

impl RuleMeta {
    pub fn new(id: &str, layer: Layer) -> Self {
        let token: String = id
            .chars()
            .map(|c| {
                if c == '-' {
                    '_'
                } else {
                    c.to_ascii_uppercase()
                }
            })
            .collect();
        Self {
            id: id.into(),
            token: token.into(),
            layer,
        }
    }
}

/// One line of a [`Report`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Entry<'r> {
    /// The rule id.
    pub rule: &'r str,
    /// The rule's layer.
    pub layer: Layer,
    /// What happened.
    pub kind: Kind,
    /// How many times, in this record.
    pub count: u32,
}

/// Counts for one record. Build it once with [`super::Scrubber::report`]
/// and [`Report::clear`] it between records: counting allocates nothing.
#[derive(Debug, Clone)]
pub struct Report {
    owner: u64,
    rules: Arc<[RuleMeta]>,
    counts: Vec<[u32; Kind::ALL.len()]>,
    touched: Vec<usize>,
    changed: bool,
}

impl Report {
    pub(super) fn new(rules: Arc<[RuleMeta]>, owner: u64) -> Self {
        let n = rules.len();
        Self {
            owner,
            rules,
            counts: vec![[0; Kind::ALL.len()]; n],
            touched: Vec::with_capacity(n),
            changed: false,
        }
    }

    /// Zero every count.
    pub fn clear(&mut self) {
        for &i in &self.touched {
            self.counts[i] = [0; Kind::ALL.len()];
        }
        self.touched.clear();
        self.changed = false;
    }

    /// `true` when a scrub changed the record's bytes.
    #[must_use]
    pub const fn changed(&self) -> bool {
        self.changed
    }

    /// `true` when nothing was counted.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.touched.is_empty()
    }

    /// The non-zero counts, rules in the order first counted, then by kind.
    pub fn entries(&self) -> impl Iterator<Item = Entry<'_>> {
        self.touched.iter().flat_map(move |&i| {
            let meta = &self.rules[i];
            Kind::ALL.into_iter().filter_map(move |kind| {
                let count = self.counts[i][kind.slot()];
                (count > 0).then_some(Entry {
                    rule: &meta.id,
                    layer: meta.layer,
                    kind,
                    count,
                })
            })
        })
    }

    /// The count for one rule id and kind, over every layer that reports it.
    #[must_use]
    pub fn count(&self, rule: &str, kind: Kind) -> u32 {
        self.rules
            .iter()
            .enumerate()
            .filter(|(_, m)| &*m.id == rule)
            .map(|(i, _)| self.counts[i][kind.slot()])
            .sum()
    }

    pub(super) const fn owner(&self) -> u64 {
        self.owner
    }

    pub(super) fn add(&mut self, rule: usize, kind: Kind) {
        self.add_n(rule, kind, 1);
    }

    pub(super) fn add_n(&mut self, rule: usize, kind: Kind, n: usize) {
        if n == 0 {
            return;
        }
        let row = &mut self.counts[rule];
        if row.iter().all(|&c| c == 0) {
            self.touched.push(rule);
        }
        let n = u32::try_from(n).unwrap_or(u32::MAX);
        row[kind.slot()] = row[kind.slot()].saturating_add(n);
    }

    pub(super) const fn set_changed(&mut self) {
        self.changed = true;
    }

    /// Add `other`'s counts to these. Both come from the same scrubber.
    pub(super) fn absorb(&mut self, other: &Self) {
        for &i in &other.touched {
            let row = &mut self.counts[i];
            if row.iter().all(|&c| c == 0) {
                self.touched.push(i);
            }
            for (mine, theirs) in row.iter_mut().zip(other.counts[i]) {
                *mine = mine.saturating_add(theirs);
            }
        }
        self.changed |= other.changed;
    }
}