grippo 0.3.0

Grok, regex, CEL and scrubbing on typed primitives. Up to 9 times faster than the stock Rust regex.
Documentation
// Project:   grippo
// File:      src/parse/frame/stream.rs
// Purpose:   Records split from a byte stream fed a read at a time
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Records split from a stream fed a read at a time: LF lines, RFC 6587
//! octet-counted frames mixed with LF lines, NUL-delimited frames, and JSON
//! values back to back, as an RFC 7464 sequence or as one array.
//!
//! [`crate::io::Scanner`] does the splitting. A record an input holds whole is
//! a slice of it. One cut across inputs is held, never past `max_bytes`, and
//! owned once its end arrives. A record over `max_bytes` is reported as it
//! passes the cap and passed without being held.

use std::borrow::Cow;

use serde::{Deserialize, Serialize};

use super::Frame;
use crate::io::{self, Emit, Feed};
use crate::parse::ParseError;

/// Where [`StreamConfig`] ends one record and starts the next.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum StreamSplit {
    /// Each record then `\n`. The `\r`s before the `\n` are dropped or kept as
    /// [`CarriageReturns`] says, and an empty line is no record.
    #[default]
    Lf,
    /// RFC 6587 octet counting, `<length> <record>`, as RFC 5425 sends
    /// syslog over TLS, mixed with LF lines: a frame that starts with a
    /// count of 1 to 9 then digits, one space and `<` is counted, and any
    /// other is an LF line. A count over `max_frame_bytes` isn't trusted and
    /// reads as an LF line too.
    OctetCounted,
    /// Each record then a NUL byte, as GELF goes over TCP. An empty frame is
    /// no record.
    Nul,
    /// JSON values back to back, with or without whitespace between them.
    JsonConcat,
    /// RFC 7464 JSON text sequences: an RS byte (0x1E) before each value
    /// and an LF after it. A text an RS cuts short, and a top-level number
    /// or literal with no whitespace after it, is dropped as RFC 7464 says.
    JsonSeq,
    /// One top-level JSON array, each element a record the moment it is
    /// complete. The `[`, the `]`, whitespace and the commas between elements
    /// are consumed. Bytes before the `[` or after the `]`, a missing comma and
    /// a stray comma are malformed, and the end of input before the `]` is a
    /// cut.
    JsonArray,
}

/// What an LF line keeps of the `\r`s before its `\n`.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum CarriageReturns {
    /// Drop every one: `a\r\n` is the record `a`, and a line of only `\r`s is
    /// no record.
    #[default]
    Strip,
    /// Keep them: `a\r\n` is the record `a\r`, and `\r\n` is the record `\r`.
    Keep,
}

/// The text encoding of a stream's bytes, read as UTF-8 before it is split.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum StreamEncoding {
    /// UTF-8, or anything ASCII-compatible: no decoding.
    #[default]
    Utf8,
    /// UTF-16 little-endian, as PowerShell 5.1's `>` and `Out-File` write
    /// it. A byte order mark at the start is dropped.
    Utf16Le,
    /// UTF-16 big-endian. A byte order mark at the start is dropped.
    Utf16Be,
    /// Whatever a byte order mark at the start names, UTF-8, UTF-16LE or
    /// UTF-16BE, the mark dropped. UTF-8 with no mark.
    Bom,
}

/// Settings for [`FramingConfig::Stream`](super::FramingConfig::Stream) and
/// for [`crate::io`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
#[serde(default, deny_unknown_fields)]
#[non_exhaustive]
pub struct StreamConfig {
    /// Where one record ends and the next begins.
    pub split: StreamSplit,
    /// Most bytes one record holds. A longer one is reported as oversize and
    /// is skipped without being held.
    pub max_bytes: usize,
    /// Whether an LF line keeps the `\r`s before its `\n`. Nul and JSON
    /// splits ignore it.
    pub carriage_returns: CarriageReturns,
    /// Octet counting only: the largest count taken as a frame, read as at
    /// least `max_bytes`. A frame between `max_bytes` and this is skipped
    /// whole, and a count over it isn't trusted: the bytes from the count to
    /// the next `\n` read as an LF line.
    pub max_frame_bytes: usize,
    /// Whether a UTF-8 byte order mark (EF BB BF) at the start of the stream
    /// is dropped, as a Windows tool often writes one. One anywhere else is
    /// part of a record.
    pub strip_bom: bool,
    /// The bytes' text encoding. Anything but UTF-8 is decoded to UTF-8
    /// before the split, so offsets and lengths count the UTF-8 text and a
    /// record is owned. [`crate::io::frames`], the plan's framing and the
    /// tokio codec decode. [`crate::io::Scanner`] and [`crate::io::Writer`]
    /// read and write UTF-8 only.
    pub encoding: StreamEncoding,
}

impl Default for StreamConfig {
    fn default() -> Self {
        Self {
            split: StreamSplit::Lf,
            max_bytes: 1 << 20,
            carriage_returns: CarriageReturns::Strip,
            max_frame_bytes: 16 << 20,
            strip_bom: true,
            encoding: StreamEncoding::Utf8,
        }
    }
}

/// A source's stream between inputs: its scanner and the bytes of a frame
/// cut across inputs.
#[derive(Debug, Default, Clone)]
pub(super) struct Joined(Option<Feed>);

impl Joined {
    /// Bytes held of a frame cut across inputs.
    #[cfg(test)]
    pub(super) fn held(&self) -> usize {
        self.0.as_ref().map_or(0, Feed::held)
    }
}

/// The error `frame` stands for, when it stands for one, `base` the stream
/// offset of the input it came from.
#[cold]
#[inline(never)]
fn error<B>(frame: &io::Frame<B>, max: usize, base: u64) -> Option<ParseError> {
    match *frame {
        io::Frame::Oversize { len, .. } => Some(ParseError::FrameTooLong { len, max }),
        io::Frame::Malformed { offset, reason } => Some(ParseError::Malformed {
            offset: usize::try_from(offset.saturating_sub(base)).unwrap_or(usize::MAX),
            reason,
        }),
        io::Frame::Record(_) | io::Frame::Cut { .. } => None,
    }
}

/// The records an input gave, and its first error.
struct Records<'o, 'a> {
    out: &'o mut Vec<Frame<'a>>,
    first: Option<ParseError>,
    max: usize,
    /// The stream offset of the input.
    base: u64,
}

impl<'a> Emit<'a> for Records<'_, 'a> {
    #[inline]
    fn borrowed(&mut self, record: &'a [u8]) {
        self.out.push(Frame::new(record));
    }

    fn frame(&mut self, frame: io::Frame<Cow<'a, [u8]>>) {
        match frame {
            io::Frame::Record(bytes) => self.out.push(Frame::new(bytes)),
            other => {
                if self.first.is_none() {
                    self.first = error(&other, self.max, self.base);
                }
            }
        }
    }
}

/// Split `input`, the next bytes of the stream, appending each finished
/// record to `out`, and return the input's first error.
pub(super) fn frame<'a>(
    c: &StreamConfig,
    input: &'a [u8],
    joined: &mut Joined,
    out: &mut Vec<Frame<'a>>,
) -> Result<(), ParseError> {
    let feed = joined.0.get_or_insert_with(|| Feed::new(c));
    let mut records = Records {
        base: feed.fed(),
        out,
        first: None,
        max: c.max_bytes,
    };
    feed.push(input, false, &mut records);
    records.first.map_or(Ok(()), Err)
}

/// End the stream. A last record with no delimiter after it goes to `out`.
/// One cut short, a counted frame or a JSON value, is dropped.
pub(super) fn finish(c: &StreamConfig, joined: &mut Joined, out: &mut Vec<Frame<'static>>) {
    let feed = joined.0.get_or_insert_with(|| Feed::new(c));
    let mut records = Records {
        base: feed.fed(),
        out,
        first: None,
        max: c.max_bytes,
    };
    feed.push(&[], true, &mut records);
}