grippo 0.1.1

Parse, match and scrub data at scale.
Documentation
// Project:   grippo
// File:      src/parse/capture.rs
// Purpose:   Sinks the driver puts between a parser and the caller: capture, promote, budget
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! A parser writes to the caller's sink. The driver steps in between only
//! when the next hop reads values ([`Capture`]) or the input is a value its
//! parser had to rewrite, which the fields below it can't borrow from
//! ([`Promote`]).

use std::borrow::Cow;
use std::cell::Cell;

use super::FieldValue;
use super::sink::{FieldSink, PrefixStack, SinkMark};
use crate::strmatch::SignatureSet;

/// Room a capture of every value starts with.
const KEPT: usize = 16;

/// What keeping one value for the next hop is charged, on top of any copy,
/// so a flood of tiny values draws on the budget too.
const VALUE_COST: usize = 8;

/// The byte budget and its latch. A `Cell`, so a sink adapter can charge a
/// copy while the executor holds its own state.
#[derive(Debug)]
pub(super) struct Budget {
    left: Cell<usize>,
    spent: Cell<bool>,
}

impl Budget {
    pub(super) const fn new(bytes: usize) -> Self {
        Self {
            left: Cell::new(bytes),
            spent: Cell::new(false),
        }
    }

    pub(super) const fn is_spent(&self) -> bool {
        self.spent.get()
    }

    /// Take `bytes` off the budget. `false` once it has run out, for good.
    pub(super) fn charge(&self, bytes: usize) -> bool {
        if self.spent.get() {
            return false;
        }
        match self.left.get().checked_sub(bytes) {
            Some(left) => self.left.set(left),
            None => self.spent.set(true),
        }
        !self.spent.get()
    }
}

/// What the next hop reads of a parser's output, so the driver keeps it.
#[derive(Debug, Clone, Copy)]
pub(super) enum Want<'p> {
    Nothing,
    /// The first value written under this name.
    Field(&'p str),
    /// Every value, with or without the field that repeats the body. With
    /// `detect`, only the values a signature in that set could fire on.
    Values {
        body_too: bool,
        detect: Option<&'p SignatureSet>,
    },
}

/// A value kept for the next hop.
pub(super) struct Captured<'i> {
    /// The sink's position when it was written.
    mark: SinkMark,
    /// Its name, kept for a trace alone.
    pub(super) name: Option<Box<str>>,
    pub(super) value: FieldValue<'i>,
}

/// Passes fields through to the sink below and keeps the values the next hop
/// reads.
pub(super) struct Capture<'s, 'i> {
    inner: &'s mut dyn FieldSink<'i>,
    want: Want<'s>,
    /// Prefixes the parser pushed, which are part of a field's name.
    prefixes: PrefixStack,
    got: Vec<Captured<'i>>,
    budget: &'s Budget,
    /// Keep names, for a trace.
    named: bool,
}

impl<'s, 'i> Capture<'s, 'i> {
    pub(super) fn new(
        inner: &'s mut dyn FieldSink<'i>,
        want: Want<'s>,
        budget: &'s Budget,
        named: bool,
    ) -> Self {
        let room = match want {
            Want::Nothing => 0,
            Want::Field(_) => 1,
            Want::Values { .. } => KEPT,
        };
        Self {
            inner,
            want,
            prefixes: PrefixStack::new(),
            got: Vec::with_capacity(room),
            budget,
            named,
        }
    }

    /// The values kept, in write order.
    pub(super) fn into_values(self) -> Vec<Captured<'i>> {
        self.got
    }

    /// Keep `value` when the next hop reads it. `false` when keeping it
    /// would overrun the budget, so the write is refused.
    fn keep(&mut self, name: &str, value: &FieldValue<'i>, is_body: bool) -> bool {
        match self.want {
            Want::Nothing => return true,
            Want::Field(wanted) => {
                if !self.got.is_empty() || !self.prefixes.with_full(name, |full| full == wanted) {
                    return true;
                }
            }
            Want::Values { body_too, detect } => {
                let skip = detect.is_some_and(|set| !set.could_fire(&value.bytes));
                if skip || (is_body && !body_too) {
                    return true;
                }
            }
        }
        let copied = match &value.bytes {
            Cow::Borrowed(_) => 0,
            Cow::Owned(bytes) => bytes.len(),
        };
        if !self.budget.charge(VALUE_COST.saturating_add(copied)) {
            return false;
        }
        let name = self
            .named
            .then(|| self.prefixes.with_full(name, |full| Box::from(full)));
        self.got.push(Captured {
            mark: self.inner.mark(),
            name,
            value: value.clone(),
        });
        true
    }
}

impl<'i> FieldSink<'i> for Capture<'_, 'i> {
    fn field(&mut self, name: &str, value: FieldValue<'i>) {
        if !self.budget.is_spent() && self.keep(name, &value, false) {
            self.inner.field(name, value);
        }
    }

    fn body_field(&mut self, name: &str, value: FieldValue<'i>) {
        if !self.budget.is_spent() && self.keep(name, &value, true) {
            self.inner.body_field(name, value);
        }
    }

    fn push_prefix(&mut self, prefix: &str) {
        self.prefixes.push(prefix);
        self.inner.push_prefix(prefix);
    }

    fn pop_prefix(&mut self) {
        self.prefixes.pop();
        self.inner.pop_prefix();
    }

    fn mark(&self) -> SinkMark {
        self.inner.mark()
    }

    fn rollback(&mut self, mark: SinkMark) {
        while self.got.last().is_some_and(|c| c.mark >= mark) {
            self.got.pop();
        }
        self.inner.rollback(mark);
    }
}

/// Writes a subtree parsed from a rewritten value into a sink that outlives
/// the value, by copying each value that borrows from it.
pub(super) struct Promote<'s, 'o> {
    inner: &'s mut dyn FieldSink<'o>,
    budget: &'s Budget,
}

impl<'s, 'o> Promote<'s, 'o> {
    pub(super) fn new(inner: &'s mut dyn FieldSink<'o>, budget: &'s Budget) -> Self {
        Self { inner, budget }
    }

    /// `value` owned, or `None` when the copy would overrun the budget.
    fn own(&self, value: FieldValue<'_>) -> Option<FieldValue<'static>> {
        let copies = match &value.bytes {
            Cow::Borrowed(bytes) => bytes.len(),
            Cow::Owned(_) => 0,
        };
        self.budget.charge(copies).then(|| value.into_owned())
    }
}

impl<'x> FieldSink<'x> for Promote<'_, '_> {
    fn field(&mut self, name: &str, value: FieldValue<'x>) {
        if let Some(value) = self.own(value) {
            self.inner.field(name, value);
        }
    }

    fn body_field(&mut self, name: &str, value: FieldValue<'x>) {
        if let Some(value) = self.own(value) {
            self.inner.body_field(name, value);
        }
    }

    fn push_prefix(&mut self, prefix: &str) {
        self.inner.push_prefix(prefix);
    }

    fn pop_prefix(&mut self) {
        self.inner.pop_prefix();
    }

    fn mark(&self) -> SinkMark {
        self.inner.mark()
    }

    fn rollback(&mut self, mark: SinkMark) {
        self.inner.rollback(mark);
    }
}