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/tests.rs
// Purpose:   Tests for charsets and the chunked transcoder, on real UTF-16 and code page files
// Language:  Rust
//
// License:   Apache-2.0
// Copyright: (c) 2026 HYPERI PTY LIMITED

use proptest::prelude::*;

use super::{Charset, Malformed, TranscodeError, Transcoder};
use crate::shared_tests::corpus::{file_bytes, for_each_record_of};

/// `bytes` through `transcoder` in pieces of `size`, and the text or the error.
fn run(mut transcoder: Transcoder, bytes: &[u8], size: usize) -> Result<Vec<u8>, TranscodeError> {
    let mut out = Vec::new();
    let mut pieces = bytes.chunks(size.max(1)).peekable();
    if pieces.peek().is_none() {
        transcoder.push(&[], true, &mut out)?;
    }
    while let Some(piece) = pieces.next() {
        transcoder.push(piece, pieces.peek().is_none(), &mut out)?;
    }
    Ok(out)
}

fn text(charset: Charset, malformed: Malformed, bytes: &[u8], size: usize) -> String {
    let out = run(Transcoder::new(charset, malformed), bytes, size).unwrap();
    String::from_utf8(out).unwrap()
}

fn utf16(text: &str, little: bool) -> Vec<u8> {
    text.encode_utf16()
        .flat_map(|u| {
            if little {
                u.to_le_bytes()
            } else {
                u.to_be_bytes()
            }
        })
        .collect()
}

#[test]
fn labels_resolve_as_the_standard_says() {
    let rows: &[(&str, Option<&str>)] = &[
        ("latin1", Some("windows-1252")),
        ("ISO-8859-1", Some("windows-1252")),
        ("WINDOWS-1252", Some("windows-1252")),
        (" utf-8\t", Some("UTF-8")),
        ("unicode-1-1-utf-8", Some("UTF-8")),
        ("utf-16le", Some("UTF-16LE")),
        ("utf-16", Some("UTF-16LE")),
        ("UCS-2", Some("UTF-16LE")),
        ("utf-16be", Some("UTF-16BE")),
        ("shift_jis", Some("Shift_JIS")),
        ("replacement", None),
        ("hz-gb-2312", None),
        ("iso-2022-kr", None),
        ("utf16le", None),
        ("", None),
    ];
    for (label, want) in rows {
        assert_eq!(
            Charset::for_label(label).map(Charset::name),
            *want,
            "{label:?}"
        );
    }
    assert_eq!(Charset::for_label("utf-16le"), Some(Charset::UTF_16LE));
}

#[test]
fn a_byte_order_mark_names_its_charset() {
    let rows: &[(&[u8], Option<(Charset, usize)>)] = &[
        (b"\xEF\xBB\xBFab", Some((Charset::UTF_8, 3))),
        (b"\xFF\xFEa\x00", Some((Charset::UTF_16LE, 2))),
        (b"\xFE\xFF\x00a", Some((Charset::UTF_16BE, 2))),
        (b"\xFF", None),
        (b"a\x00", None),
        (b"", None),
    ];
    for (bytes, want) in rows {
        assert_eq!(Charset::for_bom(bytes), *want, "{bytes:?}");
    }
}

proptest! {
    /// Any text, as either UTF-16, with or without its mark, comes back from
    /// reads of any size.
    #[test]
    fn utf16_text_reads_at_any_read_size(
        s in any::<String>().prop_filter("a leading U+FEFF is read as the mark", |s| {
            !s.starts_with('\u{FEFF}')
        }),
        little in any::<bool>(),
        mark in any::<bool>(),
        size in 1_usize..9,
    ) {
        let charset = if little { Charset::UTF_16LE } else { Charset::UTF_16BE };
        let mut bytes = if little { vec![0xFF, 0xFE] } else { vec![0xFE, 0xFF] };
        if !mark {
            bytes.clear();
        }
        bytes.extend(utf16(&s, little));
        for malformed in [Malformed::Replace, Malformed::Reject] {
            prop_assert_eq!(text(charset, malformed, &bytes, size), s.clone());
        }
    }

    /// Units that are no text, a lone surrogate or a cut-off last byte, read
    /// as std's lossy conversion reads them, whatever the read size.
    #[test]
    fn utf16_damage_reads_as_std_does(
        units in prop::collection::vec(any::<u16>(), 0..48),
        odd in prop::option::of(any::<u8>()),
        little in any::<bool>(),
        size in 1_usize..9,
    ) {
        let charset = if little { Charset::UTF_16LE } else { Charset::UTF_16BE };
        let mut bytes: Vec<u8> = units
            .iter()
            .flat_map(|u| if little { u.to_le_bytes() } else { u.to_be_bytes() })
            .collect();
        bytes.extend(odd);
        let mut want = String::from_utf16_lossy(&units);
        if units.first() == Some(&0xFEFF) {
            want.remove(0);
        }
        // A lone high surrogate and a cut-off byte after it are one bad sequence.
        if odd.is_some() && !matches!(units.last(), Some(0xD800..=0xDBFF)) {
            want.push('\u{FFFD}');
        }
        prop_assert_eq!(text(charset, Malformed::Replace, &bytes, size), want);
        let broken = odd.is_some() || char::decode_utf16(units.iter().copied()).any(|c| c.is_err());
        let rejected = run(Transcoder::new(charset, Malformed::Reject), &bytes, size);
        prop_assert_eq!(rejected.is_err(), broken);
    }
}

#[test]
fn reject_names_where_the_bad_bytes_start_at_any_read_size() {
    let windows_1253 = Charset::for_label("windows-1253").unwrap();
    let rows: &[(Charset, &[u8], u64)] = &[
        (Charset::UTF_16LE, b"a\x00\x00\xD8b\x00", 2),
        (Charset::UTF_16LE, b"a\x00b", 2),
        (Charset::UTF_16BE, b"\x00a\xDC\x00\x00b", 2),
        (Charset::UTF_8, b"ab\xFFcd", 2),
        (Charset::UTF_8, b"caf\xC3", 3),
        (windows_1253, b"ab\xAAcd", 2),
    ];
    for (charset, bytes, offset) in rows {
        for size in 1..=bytes.len() {
            let got = run(Transcoder::new(*charset, Malformed::Reject), bytes, size);
            assert_eq!(
                got,
                Err(TranscodeError::Malformed {
                    charset: charset.name(),
                    offset: *offset
                }),
                "{} {bytes:?} in pieces of {size}",
                charset.name()
            );
        }
    }
}

#[test]
fn reject_leaves_what_decoded_before_the_break() {
    let mut transcoder = Transcoder::new(Charset::UTF_16LE, Malformed::Reject);
    let mut out = b"kept".to_vec();
    let got = transcoder.push(b"o\x00k\x00\x00\xD8", true, &mut out);
    assert!(
        matches!(got, Err(TranscodeError::Malformed { .. })),
        "{got:?}"
    );
    assert_eq!(out, b"keptok");
}

#[test]
fn a_sniffing_transcoder_follows_the_mark_at_any_read_size() {
    let word = "caf\u{e9} \u{20ac}5 \u{1f600}";
    let rows: &[(&str, Vec<u8>, Charset)] = &[
        ("no mark", word.as_bytes().to_vec(), Charset::UTF_8),
        (
            "utf-8 mark",
            [b"\xEF\xBB\xBF".as_slice(), word.as_bytes()].concat(),
            Charset::UTF_8,
        ),
        (
            "utf-16le mark",
            [b"\xFF\xFE".as_slice(), &utf16(word, true)].concat(),
            Charset::UTF_16LE,
        ),
        (
            "utf-16be mark",
            [b"\xFE\xFF".as_slice(), &utf16(word, false)].concat(),
            Charset::UTF_16BE,
        ),
    ];
    for (row, bytes, charset) in rows {
        for size in [1, 2, 3, 5, 64] {
            let mut transcoder = Transcoder::sniffing(Malformed::Reject);
            let mut out = Vec::new();
            let mut pieces = bytes.chunks(size).peekable();
            while let Some(piece) = pieces.next() {
                transcoder
                    .push(piece, pieces.peek().is_none(), &mut out)
                    .unwrap();
            }
            assert_eq!(String::from_utf8(out).unwrap(), word, "{row} by {size}");
            assert_eq!(transcoder.charset(), *charset, "{row} by {size}");
        }
    }
}

#[test]
fn nothing_is_pushed_after_the_last_chunk() {
    let mut transcoder = Transcoder::new(Charset::UTF_16LE, Malformed::Replace);
    let mut out = Vec::new();
    transcoder.push(b"a\x00", true, &mut out).unwrap();
    assert_eq!(
        transcoder.push(b"b\x00", false, &mut out),
        Err(TranscodeError::Finished)
    );
    assert_eq!(out, b"a");
}

/// The corpus file `name` under quick-xml's encoding samples.
fn sample(name: &str) -> Vec<u8> {
    file_bytes(
        "quick-xml-documents",
        &format!("tests/documents/encoding/{name}"),
    )
}

#[test]
fn real_utf16_files_read_as_their_utf8_twin() {
    let twin = String::from_utf8(sample("utf8.xml")).unwrap();
    for name in [
        "utf16le.xml",
        "utf16le-bom.xml",
        "utf16be.xml",
        "utf16be-bom.xml",
    ] {
        let bytes = sample(name);
        let charset = if name.contains("le") {
            Charset::UTF_16LE
        } else {
            Charset::UTF_16BE
        };
        for size in [1, 3, 4096, bytes.len()] {
            assert_eq!(
                text(charset, Malformed::Reject, &bytes, size),
                twin,
                "{name} in pieces of {size}"
            );
        }
        let mut sniffing = Transcoder::sniffing(Malformed::Reject);
        let mut out = Vec::new();
        let sniffed = sniffing.push(&bytes, true, &mut out);
        if name.contains("bom") {
            assert_eq!(sniffed, Ok(()), "{name}");
            assert_eq!(String::from_utf8(out).unwrap(), twin, "{name} sniffed");
        }
    }
}

/// windows-1252 as the WHATWG index gives it for 0x80 to 0x9F. Every other
/// byte is the code point of its own value.
const WINDOWS_1252_HIGH: [char; 32] = [
    '\u{20AC}', '\u{0081}', '\u{201A}', '\u{0192}', '\u{201E}', '\u{2026}', '\u{2020}', '\u{2021}',
    '\u{02C6}', '\u{2030}', '\u{0160}', '\u{2039}', '\u{0152}', '\u{008D}', '\u{017D}', '\u{008F}',
    '\u{0090}', '\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}', '\u{2022}', '\u{2013}', '\u{2014}',
    '\u{02DC}', '\u{2122}', '\u{0161}', '\u{203A}', '\u{0153}', '\u{009D}', '\u{017E}', '\u{0178}',
];

fn windows_1252(bytes: &[u8]) -> String {
    bytes
        .iter()
        .map(|&b| match b {
            0x80..=0x9F => WINDOWS_1252_HIGH[usize::from(b - 0x80)],
            _ => char::from(b),
        })
        .collect()
}

#[test]
fn a_real_windows_1252_file_reads_by_the_standards_table() {
    let bytes = sample("windows-1252.xml");
    assert!(bytes.iter().any(|&b| (0x80..0xA0).contains(&b)));
    let charset = Charset::for_label("windows-1252").unwrap();
    let want = windows_1252(&bytes);
    for malformed in [Malformed::Replace, Malformed::Reject] {
        for size in [1, 7, 4096] {
            assert_eq!(text(charset, malformed, &bytes, size), want, "{size}");
        }
    }
    assert!(want.contains('\u{20AC}') && want.contains('\u{00FF}'));
}

/// The `encoding` of an XML declaration at the start of `bytes`.
fn declared(bytes: &[u8]) -> Option<String> {
    let head = String::from_utf8_lossy(&bytes[..bytes.len().min(200)]).into_owned();
    let rest = head.split("encoding=").nth(1)?;
    let quote = rest.chars().next()?;
    Some(rest[1..].split(quote).next()?.to_owned())
}

#[test]
fn every_real_encoded_xml_reads_whole_and_in_pieces() {
    let mut seen = 0;
    for_each_record_of(&["xml"], |r| {
        let Some((_, name)) = r.file.split_once("/encoding/") else {
            return;
        };
        let charset = if name.starts_with("utf16le") {
            Charset::UTF_16LE
        } else if name.starts_with("utf16be") {
            Charset::UTF_16BE
        } else if name.starts_with("utf8") {
            Charset::UTF_8
        } else {
            let label = declared(r.bytes).unwrap_or_else(|| panic!("{}: no encoding", r.at()));
            Charset::for_label(&label).unwrap_or_else(|| panic!("{}: label {label}", r.at()))
        };
        let whole = text(charset, Malformed::Reject, r.bytes, r.bytes.len());
        assert!(!whole.contains('\u{FFFD}'), "{}", r.at());
        for size in [1, 7, 4096] {
            assert_eq!(
                text(charset, Malformed::Reject, r.bytes, size),
                whole,
                "{} in pieces of {size}",
                r.at()
            );
        }
        let lossy = text(charset, Malformed::Replace, r.bytes, 5);
        assert_eq!(lossy, whole, "{}", r.at());
        seen += 1;
    });
    assert_eq!(seen, 37, "encoded samples");
}