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/charset/mod.rs
// Purpose:   UTF-16 and legacy code pages read to UTF-8, a chunk at a time
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

//! UTF-16 and legacy code pages read as UTF-8.
//!
//! A [`Transcoder`] turns bytes in a [`Charset`] into UTF-8 as they arrive.
//! It holds an odd UTF-16 byte, half a surrogate pair or the front of a
//! multi-byte character until the next chunk finishes it, so a read may end
//! anywhere.
//!
//! The charsets are UTF-8, UTF-16LE, UTF-16BE and the WHATWG Encoding
//! Standard's legacy code pages, such as `windows-1252`, found by their
//! label. `encoding_rs` does the decoding.

use encoding_rs::{CoderResult, Decoder, DecoderResult, Encoding, REPLACEMENT};
use thiserror::Error;

/// An encoding text can be read in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Charset(&'static Encoding);

impl Charset {
    /// UTF-8.
    pub const UTF_8: Self = Self(encoding_rs::UTF_8);
    /// UTF-16, little endian: what a PowerShell 5.1 `>` redirect and
    /// `-EncodedCommand` write.
    pub const UTF_16LE: Self = Self(encoding_rs::UTF_16LE);
    /// UTF-16, big endian.
    pub const UTF_16BE: Self = Self(encoding_rs::UTF_16BE);

    /// The charset the WHATWG Encoding Standard gives `label`, ignoring case
    /// and surrounding ASCII whitespace: `windows-1252`, `latin1` and
    /// `iso-8859-1` are one charset. `None` for a label the standard doesn't
    /// list, and for its `replacement` charset, which reads nothing.
    #[must_use]
    pub fn for_label(label: &str) -> Option<Self> {
        let found = Encoding::for_label(label.as_bytes())?;
        (found != REPLACEMENT).then_some(Self(found))
    }

    /// The charset a byte order mark names and how many bytes it takes:
    /// `EF BB BF` is UTF-8, `FF FE` UTF-16LE and `FE FF` UTF-16BE. `None`
    /// when `bytes` don't open with one.
    #[must_use]
    pub fn for_bom(bytes: &[u8]) -> Option<(Self, usize)> {
        Encoding::for_bom(bytes).map(|(found, len)| (Self(found), len))
    }

    /// The standard's name for it, such as `windows-1252` or `UTF-16LE`.
    #[must_use]
    pub fn name(self) -> &'static str {
        self.0.name()
    }
}

/// What a [`Transcoder`] does with bytes that aren't valid in the charset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Malformed {
    /// Write U+FFFD for each malformed sequence and read on. Text that is
    /// partly broken, a lone UTF-16 surrogate in a Windows string, still
    /// decodes around the break.
    #[default]
    Replace,
    /// Stop with [`TranscodeError::Malformed`].
    Reject,
}

/// Why a chunk didn't decode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum TranscodeError {
    /// Under [`Malformed::Reject`], bytes that aren't valid in the charset.
    #[error("bytes that don't decode as {charset}, at byte {offset}")]
    Malformed {
        /// The charset's name.
        charset: &'static str,
        /// Where the bad sequence starts, counted over every chunk pushed.
        offset: u64,
    },
    /// A chunk too long for its output room to be sized.
    #[error("a chunk too long to size its decoded output")]
    TooLarge,
    /// A chunk pushed after the one marked last.
    #[error("a chunk pushed after the last one")]
    Finished,
}

/// A decoder fed one chunk at a time.
#[derive(Debug)]
pub struct Transcoder {
    decoder: Decoder,
    malformed: Malformed,
    read: u64,
    finished: bool,
}

/// Output room taken at least, so a step always has space for one character.
const MIN_ROOM: usize = 16;

impl Transcoder {
    /// A transcoder for `charset`. A byte order mark that names `charset` at
    /// the start is dropped. One that names another charset is read as the
    /// bytes it is.
    #[must_use]
    pub fn new(charset: Charset, malformed: Malformed) -> Self {
        Self::from_decoder(charset.0.new_decoder_with_bom_removal(), malformed)
    }

    /// A transcoder that reads UTF-8, or the charset a byte order mark at the
    /// start names, the mark dropped.
    #[must_use]
    pub fn sniffing(malformed: Malformed) -> Self {
        Self::from_decoder(encoding_rs::UTF_8.new_decoder(), malformed)
    }

    const fn from_decoder(decoder: Decoder, malformed: Malformed) -> Self {
        Self {
            decoder,
            malformed,
            read: 0,
            finished: false,
        }
    }

    /// The charset in use. A transcoder from [`Transcoder::sniffing`] changes
    /// it when it reads a mark.
    #[must_use]
    pub fn charset(&self) -> Charset {
        Charset(self.decoder.encoding())
    }

    /// Appends `chunk` to `out` as UTF-8. `last` is the final chunk: a
    /// character still held then is a malformed sequence. After an error
    /// `out` holds what decoded before it, and the transcoder isn't used again.
    ///
    /// # Errors
    ///
    /// [`TranscodeError`] as it describes.
    pub fn push(
        &mut self,
        chunk: &[u8],
        last: bool,
        out: &mut Vec<u8>,
    ) -> Result<(), TranscodeError> {
        if self.finished {
            return Err(TranscodeError::Finished);
        }
        let mut rest = chunk;
        loop {
            let room = match self.malformed {
                Malformed::Replace => self.decoder.max_utf8_buffer_length(rest.len()),
                Malformed::Reject => self
                    .decoder
                    .max_utf8_buffer_length_without_replacement(rest.len()),
            }
            .ok_or(TranscodeError::TooLarge)?
            .max(MIN_ROOM);
            let start = out.len();
            out.resize(start + room, 0);
            let step = self.step(rest, &mut out[start..], last);
            out.truncate(start + step.written);
            if let Some((bad, after)) = step.bad {
                let offset = (self.read + step.read as u64)
                    .saturating_sub(u64::from(bad) + u64::from(after));
                return Err(TranscodeError::Malformed {
                    charset: self.charset().name(),
                    offset,
                });
            }
            self.read += step.read as u64;
            rest = &rest[step.read..];
            if step.done {
                self.finished = last;
                return Ok(());
            }
        }
    }

    /// One pass of the decoder over `src` into `dst`.
    fn step(&mut self, src: &[u8], dst: &mut [u8], last: bool) -> Step {
        match self.malformed {
            Malformed::Replace => {
                let (result, read, written, _) = self.decoder.decode_to_utf8(src, dst, last);
                Step {
                    done: result == CoderResult::InputEmpty,
                    read,
                    written,
                    bad: None,
                }
            }
            Malformed::Reject => {
                let (result, read, written) = self
                    .decoder
                    .decode_to_utf8_without_replacement(src, dst, last);
                Step {
                    done: result == DecoderResult::InputEmpty,
                    read,
                    written,
                    bad: match result {
                        DecoderResult::Malformed(bad, after) => Some((bad, after)),
                        _ => None,
                    },
                }
            }
        }
    }
}

/// What one pass of the decoder did.
struct Step {
    /// All input read.
    done: bool,
    read: usize,
    written: usize,
    /// The malformed sequence's length and the bytes read after it.
    bad: Option<(u8, u8)>,
}

#[cfg(test)]
mod tests;