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/text.rs
// Purpose:   A stream's UTF-16 or mark-named encoding decoded to UTF-8 a read at a time
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! [`Text`] decodes a stream's bytes to UTF-8 before the scanner splits
//! them. It holds only bytes, an odd one and the first half of a surrogate
//! pair, so a stream's state stays cloneable: each read's whole code units
//! decode with a fresh decoder.

use encoding_rs::{Encoding, UTF_8, UTF_16BE, UTF_16LE};

use crate::parse::StreamEncoding;

/// A stream being decoded to UTF-8.
#[derive(Debug, Clone)]
pub struct Text {
    /// The encoding, `None` while a byte order mark may still name it.
    encoding: Option<&'static Encoding>,
    /// Whether a mark at the start is still to be dropped.
    start: bool,
    /// Bytes waiting for the rest of their code unit, surrogate pair or mark.
    held: Vec<u8>,
}

impl Text {
    /// A decoder for `encoding`, or `None` for UTF-8, which needs none.
    pub fn new(encoding: StreamEncoding) -> Option<Self> {
        let encoding = match encoding {
            StreamEncoding::Utf16Le => Some(UTF_16LE),
            StreamEncoding::Utf16Be => Some(UTF_16BE),
            StreamEncoding::Bom => None,
            _ => return None,
        };
        Some(Self {
            encoding,
            start: true,
            held: Vec::new(),
        })
    }

    /// Decode `input`, the next bytes of the stream, `eof` when it is the
    /// last, giving the UTF-8 to `out`. A malformed sequence reads as U+FFFD.
    pub fn push(&mut self, input: &[u8], eof: bool, mut out: impl FnMut(&[u8])) {
        self.held.extend_from_slice(input);
        if self.start {
            // A mark may arrive a byte at a time, so wait for all three before reading it.
            let marks: [&[u8]; 3] = [b"\xef\xbb\xbf", b"\xff\xfe", b"\xfe\xff"];
            if !eof && self.held.len() < 3 && marks.iter().any(|m| m.starts_with(&self.held)) {
                return;
            }
            self.start = false;
            let named = Encoding::for_bom(&self.held);
            let encoding = *self
                .encoding
                .get_or_insert_with(|| named.map_or(UTF_8, |(e, _)| e));
            if let Some((mark, len)) = named
                && mark == encoding
            {
                self.held.drain(..len);
            }
        }
        let Some(encoding) = self.encoding.filter(|&e| e != UTF_8) else {
            out(&self.held);
            self.held.clear();
            return;
        };
        let cut = if eof {
            self.held.len()
        } else {
            whole_units(&self.held, encoding == UTF_16BE)
        };
        let (text, _) = encoding.decode_without_bom_handling(&self.held[..cut]);
        out(text.as_bytes());
        self.held.drain(..cut);
    }
}

/// How many bytes of `bytes` are whole UTF-16 code units, a trailing high
/// surrogate left for the low one after it.
fn whole_units(bytes: &[u8], big_endian: bool) -> usize {
    let mut cut = bytes.len() & !1;
    if let Some(&[a, b]) = bytes.get(cut.saturating_sub(2)..cut) {
        let unit = if big_endian {
            u16::from_be_bytes([a, b])
        } else {
            u16::from_le_bytes([a, b])
        };
        if (0xd800..0xdc00).contains(&unit) {
            cut -= 2;
        }
    }
    cut
}