Cotton code
206 lines · 7.4 KB · RustRaw
//! A vector table (`tests/fixtures/vectors/import.json`, key `text`) covers//! the inputs that actually break a text pass: emoji, a ZWJ sequence, an RTL//! isolate, a BOM at the front and in the middle, a NEL, CJK, a combining//! mark, and an 80,001-character body.//!//! Every fixture here is SYNTHETIC and every invisible character is built from//! its code point, exactly as the TypeScript's own fixtures are: an invisible//! character pasted into source is unreviewable and does not survive a//! careless copy-paste.use super::*;use serde::Deserialize;/// U+200E LEFT-TO-RIGHT MARK — prefixes every line of an iOS export.const LRM: char = '\u{200e}';/// U+200F RIGHT-TO-LEFT MARK.const RLM: char = '\u{200f}';/// U+2067 RIGHT-TO-LEFT ISOLATE / U+2069 POP DIRECTIONAL ISOLATE.const RLI: char = '\u{2067}';const PDI: char = '\u{2069}';/// U+202F NARROW NO-BREAK SPACE — sits before AM/PM in newer exports.const NNBSP: char = '\u{202f}';const BOM: char = '\u{feff}';#[derive(Deserialize)]#[serde(rename_all = "camelCase")]struct TextVector {    input: String,    strip_bidi: String,    normalize_spaces: String,    strip_bom: String,    normalize_export_text: String,    collapse_whitespace: String,}#[derive(Deserialize)]#[serde(rename_all = "camelCase")]struct TextLong {    input_length: usize,    collapsed: usize,    collapsed_middle: String,    normalized: usize,    bidi_stripped: usize,}#[derive(Deserialize)]struct Vectors {    text: Vec<TextVector>,    #[serde(rename = "textLong")]    text_long: TextLong,}fn vectors() -> Vectors {    serde_json::from_str(include_str!("../../vectors/import.json"))        .expect("vectors/import.json")}// ── stripBidi ────────────────────────────────────────────────────────────────#[test]fn removes_the_direction_controls_whatsapp_wraps_lines_in() {    let input = format!("{LRM}[26/07/2025] {RLI}name{PDI}{RLM}");    assert_eq!(strip_bidi(&input), "[26/07/2025] name");}#[test]fn leaves_real_content_including_emoji_and_non_latin_text_untouched() {    let body = "\u{1f44d} शुक्रिया";    assert_eq!(strip_bidi(body), body);}// ── normalizeSpaces ──────────────────────────────────────────────────────────#[test]fn folds_the_narrow_no_break_space_newer_exports_put_before_am_pm() {    assert_eq!(        normalize_spaces(&format!("10:15:00{NNBSP}AM")),        "10:15:00 AM"    );}#[test]fn folds_a_non_breaking_space() {    assert_eq!(normalize_spaces("a\u{00a0}b"), "a b");}// ── stripBom ─────────────────────────────────────────────────────────────────#[test]fn drops_a_leading_bom_and_nothing_else() {    assert_eq!(strip_bom(&format!("{BOM}hello")), "hello");    assert_eq!(strip_bom("hello"), "hello");    // A BOM in the MIDDLE is a zero-width no-break space somebody typed.    assert_eq!(strip_bom(&format!("a{BOM}b")), format!("a{BOM}b"));}// ── normalizeExportText ──────────────────────────────────────────────────────#[test]fn normalizes_crlf_and_cr_to_lf_so_line_splitting_is_one_rule() {    assert_eq!(normalize_export_text("a\r\nb\rc\nd"), "a\nb\nc\nd");}#[test]fn applies_every_pass_in_one_call() {    let input = format!("{BOM}{LRM}10:15{NNBSP}AM\r\n{RLM}next");    assert_eq!(normalize_export_text(&input), "10:15 AM\nnext");}// ── collapseWhitespace ───────────────────────────────────────────────────────#[test]fn collapses_runs_and_trims_so_a_rewrapped_re_export_hashes_the_same() {    assert_eq!(collapse_whitespace("  hello \n  world  "), "hello world");}/// ECMAScript's `\s` is not Rust's, in BOTH directions, and this function is/// the one the content fingerprint runs on a body — so the class is the/// difference between two runs agreeing on an id and not.#[test]fn the_whitespace_class_is_javascripts_not_rusts() {    // U+FEFF: whitespace in JavaScript, not in Rust.    assert_eq!(collapse_whitespace(&format!("a{BOM}b")), "a b");    // U+0085 NEL: whitespace in Rust, not in JavaScript.    assert_eq!(collapse_whitespace("a\u{0085}b"), "a\u{0085}b");    // U+180E: neither runtime trims it — the control case.    assert_eq!(        collapse_whitespace("\u{180e} a \u{180e}"),        "\u{180e} a \u{180e}"    );}// ── the Node vector table ────────────────────────────────────────────────────#[test]fn every_text_pass_matches_the_typescript_on_the_shapes_that_break_one() {    let vectors = vectors();    assert!(vectors.text.len() >= 17, "the table should not shrink");    for case in &vectors.text {        assert_eq!(strip_bidi(&case.input), case.strip_bidi, "{:?}", case.input);        assert_eq!(            normalize_spaces(&case.input),            case.normalize_spaces,            "{:?}",            case.input        );        assert_eq!(strip_bom(&case.input), case.strip_bom, "{:?}", case.input);        assert_eq!(            normalize_export_text(&case.input),            case.normalize_export_text,            "{:?}",            case.input        );        assert_eq!(            collapse_whitespace(&case.input),            case.collapse_whitespace,            "{:?}",            case.input        );    }}/// A 40,000-character paragraph twice over, with nothing to collapse: the/// passes must not quietly rewrite a long body, and the lengths are read out/// of Node rather than reasoned about.#[test]fn a_forty_thousand_character_body_survives_every_pass() {    let long = "x".repeat(40_000);    let input = format!("{long}\n{long}");    let vectors = vectors();    assert_eq!(utf16_len(&input), vectors.text_long.input_length);    assert_eq!(        utf16_len(&collapse_whitespace(&input)),        vectors.text_long.collapsed    );    assert_eq!(        utf16_len(&normalize_export_text(&input)),        vectors.text_long.normalized    );    assert_eq!(        utf16_len(&strip_bidi(&input)),        vectors.text_long.bidi_stripped    );    let collapsed = collapse_whitespace(&input);    assert_eq!(        &collapsed[39_995..40_005],        vectors.text_long.collapsed_middle    );}// ── js_trim ──────────────────────────────────────────────────────────────────#[test]fn js_trim_is_the_ecmascript_class_not_rusts() {    assert_eq!(js_trim(&format!("{BOM} hi {BOM}")), "hi");    assert_eq!(js_trim("\u{0085}hi\u{0085}"), "\u{0085}hi\u{0085}");    assert_eq!(js_trim_start("  hi  "), "hi  ");}#[test]fn utf16_len_counts_code_units_not_characters() {    // An astral emoji is ONE character and TWO UTF-16 code units, and every    // length ported out of this package is a JavaScript `.length`.    assert_eq!(utf16_len("\u{1f44d}"), 2);    assert_eq!("\u{1f44d}".chars().count(), 1);}