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/xml/input.rs
// Purpose:   Bytes as they arrive, turned to UTF-8 by the declared encoding
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! The first bytes decide the encoding: a UTF-16 byte order mark, else the XML
//! declaration's `encoding`, else UTF-8. A document in another encoding is
//! decoded as it streams, its declaration dropped since it no longer describes
//! the bytes. A byte sequence that doesn't decode is an error, never replaced.

use crate::charset::{Charset, Malformed, TranscodeError, Transcoder};

use super::XmlError;

/// The longest XML declaration read before deciding.
const DECL_MAX: usize = 1024;

#[derive(Debug)]
pub(super) enum Input {
    /// Not yet decided: the bytes so far.
    Sniff(Vec<u8>),
    /// UTF-8, passed through.
    Utf8,
    /// Another encoding, decoded as it arrives. `strip` while the decoded
    /// text may still open with the declaration.
    Decode { decoder: Transcoder, strip: bool },
}

impl Input {
    /// Append `chunk`, as UTF-8, to `buf`. `last` when no more will come.
    pub fn push(&mut self, chunk: &[u8], last: bool, buf: &mut Vec<u8>) -> Result<(), XmlError> {
        if let Self::Sniff(raw) = self {
            raw.extend_from_slice(chunk);
            let Some(decided) = sniff(raw, last)? else {
                return Ok(());
            };
            let raw = std::mem::take(raw);
            *self = decided;
            return self.push(&raw, last, buf);
        }
        match self {
            Self::Sniff(_) | Self::Utf8 => buf.extend_from_slice(chunk),
            Self::Decode { decoder, strip } => {
                transcode(decoder, chunk, last, buf)?;
                // Until the declaration is dropped nothing is read, so it
                // sits at the start of the buffer.
                if *strip && !buf.is_empty() {
                    *strip = !drop_declaration(buf, last);
                }
            }
        }
        Ok(())
    }
}

/// The encoding, once the first bytes say. `None` asks for more.
fn sniff(raw: &[u8], last: bool) -> Result<Option<Input>, XmlError> {
    let decode = |charset: Charset| Input::Decode {
        decoder: Transcoder::new(charset, Malformed::Reject),
        strip: true,
    };
    match raw {
        [0xFF, 0xFE, ..] => return Ok(Some(decode(Charset::UTF_16LE))),
        [0xFE, 0xFF, ..] => return Ok(Some(decode(Charset::UTF_16BE))),
        [_] | [] if !last => return Ok(None),
        _ => {}
    }
    if !raw.starts_with(b"<?xml") {
        return Ok((last || raw.len() >= 5 || !b"<?xml".starts_with(raw)).then_some(Input::Utf8));
    }
    let Some(end) = memchr::memmem::find(raw, b"?>") else {
        return Ok((last || raw.len() > DECL_MAX).then_some(Input::Utf8));
    };
    let Some(label) = declared(&raw[..end]) else {
        return Ok(Some(Input::Utf8));
    };
    match Charset::for_label(&label) {
        Some(charset) if charset == Charset::UTF_8 => Ok(Some(Input::Utf8)),
        Some(charset) => Ok(Some(decode(charset))),
        None => Err(XmlError::Encoding { label }),
    }
}

/// The `encoding` pseudo-attribute of a declaration.
fn declared(decl: &[u8]) -> Option<String> {
    let at = memchr::memmem::find(decl, b"encoding")?;
    let rest = &decl[at + 8..];
    let eq = rest.iter().position(|&b| b == b'=')?;
    let rest = &rest[eq + 1..];
    let open = rest.iter().position(|&b| b == b'"' || b == b'\'')?;
    let quote = rest[open];
    let value = &rest[open + 1..];
    let close = value.iter().position(|&b| b == quote)?;
    Some(String::from_utf8_lossy(&value[..close]).into_owned())
}

/// Decode `src` onto the end of `buf`.
fn transcode(
    decoder: &mut Transcoder,
    src: &[u8],
    last: bool,
    buf: &mut Vec<u8>,
) -> Result<(), XmlError> {
    decoder.push(src, last, buf).map_err(|e| match e {
        TranscodeError::Malformed { charset, .. } => XmlError::Encoding {
            label: format!("{charset} (bytes that don't decode)"),
        },
        TranscodeError::TooLarge => XmlError::RecordTooLarge { max: usize::MAX },
        TranscodeError::Finished => XmlError::Malformed {
            offset: 0,
            reason: "bytes after the last chunk".to_owned(),
        },
    })
}

/// Drop a leading XML declaration from `buf`. `true` once settled: dropped,
/// or the text clearly holds none.
fn drop_declaration(buf: &mut Vec<u8>, last: bool) -> bool {
    let text = &buf[..];
    if !text.starts_with(b"<?xml") {
        return last || text.len() >= 5 || !b"<?xml".starts_with(text);
    }
    let close = memchr::memmem::find(text, b"?>");
    close.map_or(last, |end| {
        buf.drain(..end + 2);
        true
    })
}