grippo 0.3.1

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/parse/sink.rs
// Purpose:   Where parsers write fields: the sink trait and a plain sink
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The caller owns the sink, so a receiver can write straight into its own
//! record type. Prefixes are a stack the driver pushes and pops, so a parser
//! costs two calls rather than a string build per field.

use super::FieldValue;

/// A position in a sink's fields, to roll back to.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct SinkMark(pub usize);

/// Receives fields from parsers.
///
/// A name may arrive more than once: the sink collects the values as a list.
/// The full name of a field is every pushed prefix, concatenated, then the
/// name, except that a `.` just before a quoted key, `["a.b"]`, is dropped:
/// `labels.` then `["app.kind"]` is `labels["app.kind"]`, as
/// [`crate::path`] writes a key holding `.`, `[`, `]` or `"`.
/// [`PrefixStack`] does that bookkeeping for an implementation.
pub trait FieldSink<'a> {
    /// Write one field under the current prefix.
    fn field(&mut self, name: &str, value: FieldValue<'a>);

    /// Write a field that holds the input the parser returns as its body, as
    /// syslog's `message` does. `auto*` reads the body and skips this copy.
    fn body_field(&mut self, name: &str, value: FieldValue<'a>) {
        self.field(name, value);
    }

    /// Put later fields under `prefix`, such as `syslog.`, until the matching
    /// [`Self::pop_prefix`].
    fn push_prefix(&mut self, prefix: &str);

    /// Undo the last [`Self::push_prefix`].
    fn pop_prefix(&mut self);

    /// The current position, for [`Self::rollback`].
    fn mark(&self) -> SinkMark;

    /// Drop every field written since `mark`. The driver calls this when a
    /// parser fails partway.
    fn rollback(&mut self, mark: SinkMark);
}

/// The prefix stack a sink keeps, with one reused buffer for full names.
#[derive(Debug, Clone, Default)]
pub struct PrefixStack {
    joined: String,
    /// The length to go back to for each prefix, and whether pushing it
    /// dropped a `.` that goes back on.
    ends: Vec<(usize, bool)>,
}

impl PrefixStack {
    /// An empty stack.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Push `prefix`.
    pub fn push(&mut self, prefix: &str) {
        let end = self.joined.len();
        let dropped = self.drop_dot(prefix);
        self.ends.push((end, dropped));
        self.joined.push_str(prefix);
    }

    /// Pop the last prefix. Does nothing on an empty stack.
    pub fn pop(&mut self) {
        if let Some((end, dropped)) = self.ends.pop() {
            self.restore(end, dropped);
        }
    }

    /// Drop every prefix, keeping the buffers.
    pub fn clear(&mut self) {
        self.joined.clear();
        self.ends.clear();
    }

    /// Every prefix, concatenated.
    #[must_use]
    pub fn current(&self) -> &str {
        &self.joined
    }

    /// Call `f` with the full name of `name`, built in the stack's buffer.
    pub fn with_full<R>(&mut self, name: &str, f: impl FnOnce(&str) -> R) -> R {
        let base = self.joined.len();
        let dropped = self.drop_dot(name);
        self.joined.push_str(name);
        let out = f(&self.joined);
        self.restore(base, dropped);
        out
    }

    /// Drops the `.` the buffer ends with when `next` opens with a quoted key.
    fn drop_dot(&mut self, next: &str) -> bool {
        let drop = next.starts_with("[\"")
            && self.joined.ends_with('.')
            && crate::path::below(next).is_some();
        if drop {
            self.joined.pop();
        }
        drop
    }

    /// Back to `end` bytes, the `.` put back when it was dropped.
    fn restore(&mut self, end: usize, dropped: bool) {
        if dropped {
            self.joined.truncate(end - 1);
            self.joined.push('.');
        } else {
            self.joined.truncate(end);
        }
    }
}

/// A plain sink: every field in write order, under its full name.
#[derive(Debug, Clone, Default)]
pub struct Fields<'a> {
    fields: Vec<(String, FieldValue<'a>)>,
    prefixes: PrefixStack,
}

impl<'a> Fields<'a> {
    /// An empty sink.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Every field in write order.
    #[must_use]
    pub fn as_slice(&self) -> &[(String, FieldValue<'a>)] {
        &self.fields
    }

    /// Every field in write order, to set a value or rename a field in place.
    pub fn as_mut_slice(&mut self) -> &mut [(String, FieldValue<'a>)] {
        &mut self.fields
    }

    /// Keep only the fields `keep` accepts, in write order.
    pub fn retain(&mut self, mut keep: impl FnMut(&str, &FieldValue<'a>) -> bool) {
        self.fields.retain(|(name, value)| keep(name, value));
    }

    /// The first value written under `name`.
    #[must_use]
    pub fn get(&self, name: &str) -> Option<&FieldValue<'a>> {
        self.fields.iter().find(|(n, _)| n == name).map(|(_, v)| v)
    }

    /// Every value written under `name`, in write order.
    pub fn get_all<'s>(&'s self, name: &'s str) -> impl Iterator<Item = &'s FieldValue<'a>> {
        self.fields
            .iter()
            .filter(move |(n, _)| n == name)
            .map(|(_, v)| v)
    }

    /// Number of fields written.
    #[must_use]
    pub const fn len(&self) -> usize {
        self.fields.len()
    }

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

    /// Drop every field and prefix, keeping the sink's own buffers.
    pub fn clear(&mut self) {
        self.fields.clear();
        self.prefixes.clear();
    }
}

impl<'a> FieldSink<'a> for Fields<'a> {
    fn field(&mut self, name: &str, value: FieldValue<'a>) {
        let full = self.prefixes.with_full(name, str::to_owned);
        self.fields.push((full, value));
    }

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

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

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

    fn rollback(&mut self, mark: SinkMark) {
        self.fields.truncate(mark.0);
    }
}