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/io.rs
// Purpose:   Stream framing at the I/O edge: a sans-IO scanner and writer, and sync helpers
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! Records framed in and out of a byte stream, with no I/O of grippo's own.
//!
//! [`Scanner`] finds frames in a buffer the caller owns and [`Writer`] frames
//! records for the same [`StreamConfig`] split. [`frames`] reads frames from
//! any [`BufRead`] and [`write_frames`] writes records to any [`Write`].
//! With the `tokio` feature, [`tokio`](mod@tokio) has the same two helpers
//! and a tokio-util codec, for a socket on a tokio runtime.
//!
//! A frame over `max_bytes`, bytes that don't frame and the end of input
//! inside a frame are items of the stream, never errors, so one bad frame
//! never ends a long-running reader.

mod scan;
#[cfg(test)]
mod tests;
mod text;
#[cfg(feature = "tokio")]
pub mod tokio;
mod write;

use std::borrow::Cow;
use std::collections::VecDeque;
use std::io::{self, BufRead, Write};
use std::marker::PhantomData;

use crate::parse::StreamConfig;
use text::Text;

pub use scan::{Scanner, Step};
pub use write::{Refused, Writer};

/// One item of a framed stream, its bytes held as `B`.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Frame<B> {
    /// One record.
    Record(B),
    /// A frame over `max_bytes`, left out.
    Oversize {
        /// Its length in the stream, as [`Step::Oversize`] gives it.
        len: u64,
        /// Its first `max_bytes` bytes.
        head: B,
    },
    /// Bytes a JSON split couldn't read.
    Malformed {
        /// Where, as a stream offset.
        offset: u64,
        /// What is wrong there.
        reason: &'static str,
    },
    /// The end of input came inside a frame, after `len` bytes of it.
    Cut {
        /// The bytes seen of it.
        len: u64,
    },
}

impl<B> Frame<B> {
    /// The same frame with its bytes held as `C`.
    pub(crate) fn map<C>(self, mut f: impl FnMut(B) -> C) -> Frame<C> {
        match self {
            Self::Record(bytes) => Frame::Record(f(bytes)),
            Self::Oversize { len, head } => Frame::Oversize { len, head: f(head) },
            Self::Malformed { offset, reason } => Frame::Malformed { offset, reason },
            Self::Cut { len } => Frame::Cut { len },
        }
    }
}

/// The frame a step read from `buf`, with its bytes as `wrap` makes them, or
/// `None` for a step with nothing to report.
pub(crate) fn frame_of<'b, B>(
    step: &Step,
    buf: &'b [u8],
    wrap: impl Fn(&'b [u8]) -> B,
) -> Option<Frame<B>> {
    match step {
        Step::Record { record, .. } => Some(Frame::Record(wrap(&buf[record.clone()]))),
        Step::Oversize { len, head, .. } => Some(Frame::Oversize {
            len: *len,
            head: wrap(&buf[head.clone()]),
        }),
        Step::Malformed { offset, reason, .. } => Some(Frame::Malformed {
            offset: *offset,
            reason,
        }),
        Step::Cut { len } => Some(Frame::Cut { len: *len }),
        Step::Skip { .. } | Step::Need => None,
    }
}

/// Where a [`Feed`] puts what it frames.
pub(crate) trait Emit<'a> {
    /// A record the input held whole.
    fn borrowed(&mut self, record: &'a [u8]);
    /// Any other frame, a record joined across inputs included.
    fn frame(&mut self, frame: Frame<Cow<'a, [u8]>>);
}

impl<'a, F: FnMut(Frame<Cow<'a, [u8]>>)> Emit<'a> for F {
    fn borrowed(&mut self, record: &'a [u8]) {
        self(Frame::Record(Cow::Borrowed(record)));
    }

    fn frame(&mut self, frame: Frame<Cow<'a, [u8]>>) {
        self(frame);
    }
}

/// A scanner fed inputs it doesn't keep: the bytes of a frame cut across
/// inputs are held here, and a record an input holds whole is borrowed.
#[derive(Debug, Clone)]
pub(crate) struct Feed {
    scanner: Scanner,
    held: Vec<u8>,
    /// The decoder of a stream that isn't UTF-8.
    text: Option<Text>,
    /// An input decoded to UTF-8, kept for its capacity.
    decoded: Vec<u8>,
}

/// An [`Emit`] that owns every frame's bytes, for text decoded into a
/// buffer the frames can't borrow.
struct Owned<'e, 'a, E>(&'e mut E, PhantomData<&'a ()>);

impl<'t, 'a, E: Emit<'a>> Emit<'t> for Owned<'_, 'a, E> {
    fn borrowed(&mut self, record: &'t [u8]) {
        self.0.frame(Frame::Record(Cow::Owned(record.to_vec())));
    }

    fn frame(&mut self, frame: Frame<Cow<'t, [u8]>>) {
        self.0
            .frame(frame.map(|bytes| Cow::Owned(bytes.into_owned())));
    }
}

/// The first bytes of an input a held frame takes on before it is scanned
/// again, doubling while it finds no end.
const JOIN_STEP: usize = 256;

impl Feed {
    pub(crate) fn new(config: &StreamConfig) -> Self {
        Self {
            scanner: Scanner::new(config),
            held: Vec::new(),
            text: Text::new(config.encoding),
            decoded: Vec::new(),
        }
    }

    /// Bytes held of a frame cut across inputs.
    #[cfg(test)]
    pub(crate) const fn held(&self) -> usize {
        self.held.len()
    }

    /// Stream bytes fed so far: the stream offset of the next input.
    pub(crate) fn fed(&self) -> u64 {
        self.scanner.consumed() + u64::try_from(self.held.len()).unwrap_or(u64::MAX)
    }

    /// Frame `input`, the next bytes of the stream, `eof` when it is the
    /// last, giving each frame to `emit`.
    #[inline]
    pub(crate) fn push<'a>(&mut self, input: &'a [u8], eof: bool, emit: &mut impl Emit<'a>) {
        if self.text.is_some() {
            self.push_decoded(input, eof, emit);
        } else {
            self.push_utf8(input, eof, emit);
        }
    }

    /// Decode `input` to UTF-8, then frame it with each frame owned.
    #[inline(never)]
    fn push_decoded<'a>(&mut self, input: &[u8], eof: bool, emit: &mut impl Emit<'a>) {
        let mut decoded = std::mem::take(&mut self.decoded);
        decoded.clear();
        if let Some(text) = &mut self.text {
            text.push(input, eof, |bytes| decoded.extend_from_slice(bytes));
        }
        self.push_utf8(&decoded, eof, &mut Owned(emit, PhantomData));
        self.decoded = decoded;
    }

    /// Frame `input`, UTF-8 the scanner reads as it is.
    #[allow(
        clippy::inline_always,
        reason = "with #[inline] alone the plan driver's UTF-8 path took 1% more instructions"
    )]
    #[inline(always)]
    fn push_utf8<'a>(&mut self, input: &'a [u8], eof: bool, emit: &mut impl Emit<'a>) {
        let mut at = 0;
        if !self.held.is_empty() {
            match self.join(input, eof, emit) {
                Some(next) => at = next,
                None => return,
            }
        }
        // A borrowed record goes out as a bare slice, so the caller builds its frame in place.
        at += self.scanner.each(&input[at..], eof, |frame| match frame {
            Frame::Record(record) => emit.borrowed(record),
            other => emit.frame(other.map(Cow::Borrowed)),
        });
        self.held.extend_from_slice(&input[at..]);
    }

    /// Frame the held bytes with as much of `input` as it takes to end them,
    /// returning where in `input` the scan goes on, or `None` when `input`
    /// is spent.
    #[cold]
    #[inline(never)]
    fn join<'a>(&mut self, input: &'a [u8], eof: bool, emit: &mut impl Emit<'a>) -> Option<usize> {
        let base = self.held.len();
        let mut front = 0;
        let mut taken = 0;
        loop {
            let last = eof && taken == input.len();
            let buf = &self.held[front..];
            let step = self.scanner.next(buf, last);
            match step {
                Step::Need => {
                    if taken == input.len() {
                        self.held.drain(..front);
                        return None;
                    }
                    let n = buf.len().max(JOIN_STEP).min(input.len() - taken);
                    self.held.extend_from_slice(&input[taken..taken + n]);
                    taken += n;
                    continue;
                }
                Step::Cut { len } => {
                    self.held.clear();
                    emit.frame(Frame::Cut { len });
                    return None;
                }
                _ => {}
            }
            if let Some(frame) = frame_of(&step, buf, |b| Cow::Owned(b.to_vec())) {
                emit.frame(frame);
            }
            front += step.consume(buf);
            // Past the bytes held before this input, the rest of the buffer is a copy of the input's.
            if front >= base {
                self.held.clear();
                return Some(front - base);
            }
        }
    }
}

/// Read the frames of `config`'s split from `reader`, each one owned.
///
/// ```
/// use grippo::io::{Frame, frames};
/// use grippo::parse::{StreamConfig, StreamSplit};
///
/// let mut config = StreamConfig::default();
/// config.split = StreamSplit::Nul;
/// let got: Vec<Frame<Vec<u8>>> = frames(&b"a\0b\0"[..], &config).collect::<Result<_, _>>()?;
/// assert_eq!(got, [Frame::Record(b"a".to_vec()), Frame::Record(b"b".to_vec())]);
/// # Ok::<(), std::io::Error>(())
/// ```
pub fn frames<R: BufRead>(reader: R, config: &StreamConfig) -> Frames<R> {
    Frames {
        reader,
        feed: Feed::new(config),
        ready: VecDeque::new(),
        done: false,
    }
}

/// The frames [`frames`] reads, in order. A read error is an item, and the
/// next read tries again.
#[derive(Debug)]
pub struct Frames<R> {
    reader: R,
    feed: Feed,
    ready: VecDeque<Frame<Vec<u8>>>,
    done: bool,
}

impl<R> Frames<R> {
    /// The scanner's state, for [`Scanner::consumed`] and the other queries.
    #[must_use]
    pub const fn scanner(&self) -> &Scanner {
        &self.feed.scanner
    }

    /// The reader, given back.
    pub fn into_inner(self) -> R {
        self.reader
    }
}

impl<R: BufRead> Iterator for Frames<R> {
    type Item = io::Result<Frame<Vec<u8>>>;

    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(frame) = self.ready.pop_front() {
                return Some(Ok(frame));
            }
            if self.done {
                return None;
            }
            let input = match self.reader.fill_buf() {
                Ok(input) => input,
                Err(e) if e.kind() == io::ErrorKind::Interrupted => continue,
                Err(e) => return Some(Err(e)),
            };
            let n = input.len();
            self.done = n == 0;
            let ready = &mut self.ready;
            self.feed
                .push(input, self.done, &mut |frame: Frame<Cow<'_, [u8]>>| {
                    ready.push_back(frame.map(Cow::into_owned));
                });
            self.reader.consume(n);
        }
    }
}

/// Write `records` to `writer`, each framed for `config`'s split, then close
/// the stream and flush.
///
/// # Errors
///
/// The writer's error, or [`io::ErrorKind::InvalidInput`] holding the
/// [`Refused`] for a record that wouldn't read back as itself. The records
/// before it are written.
pub fn write_frames<W, I>(mut writer: W, config: &StreamConfig, records: I) -> io::Result<()>
where
    W: Write,
    I: IntoIterator,
    I::Item: AsRef<[u8]>,
{
    const BATCH: usize = 64 * 1024;
    let mut framer = Writer::new(config);
    let mut out = Vec::with_capacity(BATCH);
    for record in records {
        if let Err(refused) = framer.frame(record.as_ref(), &mut out) {
            writer.write_all(&out)?;
            return Err(io::Error::new(io::ErrorKind::InvalidInput, refused));
        }
        if out.len() >= BATCH {
            writer.write_all(&out)?;
            out.clear();
        }
    }
    framer.finish(&mut out);
    writer.write_all(&out)?;
    writer.flush()
}