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/io/write.rs
// Purpose:   Records framed for a stream split, the scanner's mirror
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`Writer`] frames records for the split a [`Scanner`](super::Scanner)
//! reads, and refuses any record that wouldn't read back as itself.

use memchr::memchr;
use thiserror::Error;

use crate::parse::{CarriageReturns, RS, Scan, ScanStep, StreamConfig, StreamSplit};

/// Why [`Writer::frame`] refused a record. A [`Scanner`](super::Scanner)
/// with the same config would have read it back as something else.
#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum Refused {
    /// The record is empty, which a stream holds no record for.
    #[error("an empty record")]
    Empty,
    /// The record holds its own delimiter: an LF in an LF line, a NUL in a
    /// NUL frame.
    #[error("a record holding its delimiter")]
    Delimiter,
    /// An LF line ends in a `\r`, which a reader stripping carriage returns
    /// drops.
    #[error("an LF line ending in a carriage return")]
    CarriageReturn,
    /// An octet-counted record doesn't start with `<`, so it would read as an
    /// LF line.
    #[error("an octet-counted record that doesn't start with `<`")]
    NotCounted,
    /// A JSON split's record isn't one JSON value with nothing around it.
    #[error("a record that isn't one JSON value")]
    NotOneValue,
    /// The stream's first record starts with a UTF-8 byte order mark, which
    /// a reader with `strip_bom` drops.
    #[error("a first record starting with a byte order mark")]
    ByteOrderMark,
    /// The record is over `max_bytes`.
    #[error("a record of {len} bytes is over max_bytes {max}")]
    TooLong {
        /// Its length.
        len: usize,
        /// The cap.
        max: usize,
    },
}

/// Frames records for a [`StreamConfig`] split.
///
/// An LF or a NUL after each record, `<len> ` before an octet-counted one,
/// an RS before and an LF after a JSON sequence text, an LF after each JSON
/// value back to back, and `[`, commas and `]` around a JSON array's
/// elements.
///
/// ```
/// use grippo::io::Writer;
/// use grippo::parse::{StreamConfig, StreamSplit};
///
/// let mut config = StreamConfig::default();
/// config.split = StreamSplit::JsonArray;
/// let mut writer = Writer::new(&config);
/// let mut out = Vec::new();
/// writer.frame(br#"{"a":1}"#, &mut out)?;
/// writer.frame(b"2", &mut out)?;
/// writer.finish(&mut out);
/// assert_eq!(out, br#"[{"a":1},2]"#);
/// assert!(writer.frame(b"1 2", &mut out).is_err());
/// # Ok::<(), grippo::io::Refused>(())
/// ```
#[derive(Debug, Clone)]
pub struct Writer {
    split: StreamSplit,
    max: usize,
    strip: bool,
    /// Whether a reader drops a byte order mark at the stream's start.
    bom: bool,
    /// Whether a record of this stream is out, and so a JSON array's `[`.
    started: bool,
}

/// The bytes around one framed record.
pub(super) struct Around {
    head: [u8; 24],
    head_len: usize,
    pub(super) tail: &'static [u8],
}

impl Around {
    pub(super) fn head(&self) -> &[u8] {
        &self.head[..self.head_len]
    }
}

impl Writer {
    /// A writer for `config`.
    #[must_use]
    pub fn new(config: &StreamConfig) -> Self {
        Self {
            split: config.split,
            max: config.max_bytes,
            strip: config.carriage_returns == CarriageReturns::Strip,
            bom: config.strip_bom,
            started: false,
        }
    }

    /// Append `record` to `out`, framed.
    ///
    /// # Errors
    ///
    /// [`Refused`] when a scanner with the same config wouldn't read the
    /// record back as itself. `out` is left as it was.
    pub fn frame(&mut self, record: &[u8], out: &mut Vec<u8>) -> Result<(), Refused> {
        let around = self.around(record)?;
        out.reserve(around.head_len + record.len() + around.tail.len());
        out.extend_from_slice(around.head());
        out.extend_from_slice(record);
        out.extend_from_slice(around.tail);
        Ok(())
    }

    /// End the stream: append the `]` a JSON array needs, or `[]` when it had
    /// no element. A frame after this starts a new stream.
    pub fn finish(&mut self, out: &mut Vec<u8>) {
        out.extend_from_slice(self.closing());
    }

    /// What closes the stream, the writer then ready for a new one.
    pub(super) const fn closing(&mut self) -> &'static [u8] {
        let opened = self.started;
        self.started = false;
        if !matches!(self.split, StreamSplit::JsonArray) {
            return b"";
        }
        if opened { b"]" } else { b"[]" }
    }

    /// Check `record` and say what goes before and after it.
    pub(super) fn around(&mut self, record: &[u8]) -> Result<Around, Refused> {
        if record.is_empty() {
            return Err(Refused::Empty);
        }
        if record.len() > self.max {
            return Err(Refused::TooLong {
                len: record.len(),
                max: self.max,
            });
        }
        if self.bom && !self.started && record.starts_with(b"\xef\xbb\xbf") {
            return Err(Refused::ByteOrderMark);
        }
        let mut around = Around {
            head: [0; 24],
            head_len: 0,
            tail: b"",
        };
        match self.split {
            StreamSplit::Lf => {
                if memchr(b'\n', record).is_some() {
                    return Err(Refused::Delimiter);
                }
                if self.strip && record.last() == Some(&b'\r') {
                    return Err(Refused::CarriageReturn);
                }
                around.tail = b"\n";
            }
            StreamSplit::Nul => {
                if memchr(0, record).is_some() {
                    return Err(Refused::Delimiter);
                }
                around.tail = b"\0";
            }
            StreamSplit::OctetCounted => {
                if record[0] != b'<' {
                    return Err(Refused::NotCounted);
                }
                let mut n = record.len();
                let mut digits = [0_u8; 20];
                let mut at = digits.len();
                loop {
                    at -= 1;
                    digits[at] = b"0123456789"[n % 10];
                    n /= 10;
                    if n == 0 {
                        break;
                    }
                }
                let count = &digits[at..];
                around.head[..count.len()].copy_from_slice(count);
                around.head[count.len()] = b' ';
                around.head_len = count.len() + 1;
            }
            StreamSplit::JsonConcat => {
                one_value(record, false)?;
                around.tail = b"\n";
            }
            StreamSplit::JsonSeq => {
                one_value(record, true)?;
                around.head[0] = RS;
                around.head_len = 1;
                around.tail = b"\n";
            }
            StreamSplit::JsonArray => {
                one_value(record, false)?;
                around.head[0] = if self.started { b',' } else { b'[' };
                around.head_len = 1;
            }
        }
        self.started = true;
        Ok(around)
    }
}

/// Whether `record` is one JSON value as the scanner reads one, with nothing
/// before or after it.
fn one_value(record: &[u8], seq: bool) -> Result<(), Refused> {
    let mut scan = record
        .first()
        .and_then(|&b| Scan::open(b))
        .ok_or(Refused::NotOneValue)?;
    let scalar = scan.scalar();
    match scan.run(record, 1, seq) {
        ScanStep::End(end) if end == record.len() => Ok(()),
        ScanStep::More if scalar => Ok(()),
        _ => Err(Refused::NotOneValue),
    }
}