Skip to main content

nameparser/
unicode.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Java `org.gbif.nameparser.util.UnicodeUtils` — ported subset: `normalizeQuotes`, plus
3//! the homoglyph-replacement table (`HOMOGLYHPS`/`containsHomoglyphs`/`replaceHomoglyphs`)
4//! used by `pipeline::stripandstash`'s step 13. `decompose`/`foldToAscii`/
5//! `replaceSpecialCases`/`removeNonAscii`/`replaceNonAscii`/`unescapeUnicodeChars`/
6//! `decodeUtf8Garbage`/`containsDiacritics`/`findDiacritics` are NOT ported: no call site
7//! anywhere in this crate's (now complete) pipeline reaches them, and the full-corpus
8//! Rust-vs-Java parity cross-validation (see `BENCHMARKS.md`/`cross-validation.md`, 0
9//! mismatches) confirms their absence isn't a gap.
10
11/// Unicode apostrophe / single-quote variants that normalise to the ASCII apostrophe `'`.
12/// Verbatim transcription of Java `UnicodeUtils.SINGLE_QUOTES`
13/// (`"`´ʹʻʼʽˊˋ‘’‘’‚‛′‵❛❜'"`).
14/// Every codepoint is a 4-hex-digit Java `\u` escape, i.e. a single UTF-16 code unit in
15/// the Basic Multilingual Plane outside the surrogate range — so iterating Rust `char`s
16/// (Unicode scalar values) reproduces Java's `char`-at-a-time (UTF-16 code unit) loop
17/// exactly for this fixed table.
18const SINGLE_QUOTES: &[char] = &[
19    '\u{0060}', '\u{00B4}', '\u{02B9}', '\u{02BB}', '\u{02BC}', '\u{02BD}', '\u{02CA}', '\u{02CB}',
20    '\u{0091}', '\u{0092}', '\u{2018}', '\u{2019}', '\u{201A}', '\u{201B}', '\u{2032}', '\u{2035}',
21    '\u{275B}', '\u{275C}', '\u{FF07}',
22];
23
24/// Unicode double-quote / double-prime variants that normalise to the ASCII double quote
25/// `"`. Verbatim transcription of Java `UnicodeUtils.DOUBLE_QUOTES`
26/// (`"“”“”„‟″‶❝❞〝〞〟""`).
27const DOUBLE_QUOTES: &[char] = &[
28    '\u{0093}', '\u{0094}', '\u{201C}', '\u{201D}', '\u{201E}', '\u{201F}', '\u{2033}', '\u{2036}',
29    '\u{275D}', '\u{275E}', '\u{301D}', '\u{301E}', '\u{301F}', '\u{FF02}',
30];
31
32// ---------------------------------------------------------------------------------------
33// Homoglyph table: Java `UnicodeUtils.HOMOGLYHPS`/`containsHomoglyphs`/`replaceHomoglyphs`
34// (`UnicodeUtils.java:58-139` for the static-init loader, `:194-215` and `:239-276` for the
35// public methods). Used by `pipeline::stripandstash`'s step 13 (`replaceHomoglyphs`) to
36// fold Latin look-alike characters from other scripts (e.g. Cyrillic 'а' U+0430) — and a
37// handful of archaic Latin typography, notably U+017F LATIN SMALL LETTER LONG S "ſ" — down
38// to their canonical ASCII/Latin letter.
39// ---------------------------------------------------------------------------------------
40
41use std::borrow::Cow;
42use std::collections::HashMap;
43use std::sync::LazyLock;
44
45/// The homoglyph table, embedded at compile time (copied verbatim from
46/// `name-parser-api/src/main/resources/unicode/homoglyphs.txt`, itself sourced from
47/// <https://raw.githubusercontent.com/codebox/homoglyph/master/raw_data/chars.txt> per the
48/// resource file's own header comment — `diff`-verified byte-for-byte identical to the
49/// Java classpath resource). Each line lists a "canonical" character (the line's first
50/// char) followed by every codepoint the codebox project considers a visual look-alike of
51/// it. 1861 lines total (`\n`-delimited; the file's own last line has no trailing
52/// terminator, the same off-by-one `wc -l` undercounts documented on
53/// `pipeline::blacklisted_epithets`'s `BLACKLIST_TXT`) — but see [`HOMOGLYPHS`]'s own doc
54/// comment: Java's loader, and this port, only ever read a small prefix of it.
55const HOMOGLYPHS_TXT: &str = include_str!("../resources/homoglyphs.txt");
56
57/// U+00D7 MULTIPLICATION SIGN, the botanical hybrid marker ("Abies × Picea"). Java
58/// `NameFormatter.HYBRID_MARKER` (`NameFormatter.java:14`: `public static final char
59/// HYBRID_MARKER = '×';`). Excluded from the table [`HOMOGLYPHS`] builds below — even
60/// though it appears, unremoved, as one of the look-alikes on `homoglyphs.txt`'s `x` row
61/// (line 88) — so a genuine hybrid marker is never folded into a plain "x", which would
62/// silently destroy hybrid-name semantics. Java's own `UnicodeUtilsTest.containsHomoglyphs`
63/// asserts exactly this: `"Abies × Picea"` is NOT flagged as containing a homoglyph.
64const HYBRID_MARKER: char = '\u{00D7}';
65
66/// Java `ignoredCanonicals` (`UnicodeUtils.java:67`): `new CharArraySet(new char[]{' ',
67/// '\'', '-', '﹘'})`. A `homoglyphs.txt` row whose canonical (first) character is one of
68/// these four is skipped ENTIRELY — no homoglyph entries at all are taken from that row.
69/// U+0020 SPACE, U+0027 APOSTROPHE, U+002D HYPHEN-MINUS, U+FE58 SMALL EM DASH.
70const IGNORED_CANONICALS: [char; 4] = [' ', '\'', '-', '\u{FE58}'];
71
72/// Java's local `ignore` set (`UnicodeUtils.java:93-103`, rebuilt from the literal
73/// `"‘’“”"` on every loop iteration but with identical fixed content
74/// each time — a code-style quirk, not per-row-varying data). Curly single/double-quote
75/// variants are never captured as a homoglyph VALUE on ANY row — quote normalisation is
76/// [`normalize_quotes`]'s job, not this table's.
77const QUOTE_IGNORE: [char; 4] = ['\u{2018}', '\u{2019}', '\u{201C}', '\u{201D}'];
78
79/// Java `DIACRITICS` (`UnicodeUtils.java:33-56`, static-init block): standalone
80/// combining/spacing diacritic marks, excluded from ever being captured as a homoglyph
81/// VALUE (a bare combining accent isn't meaningfully "the same as" some base letter, even
82/// where the auto-generated codebox table lists it as a look-alike on some canonical's
83/// row). Verbatim transcription of the Java string literal
84/// `"´˝\` ̏ˆˇ˘ ̑¸¨· ̡ ̢ ̉ ̛ˉ˛ ˚˳῾᾿"` with its 7 embedded literal spaces filtered out
85/// (`.filter(cp -> cp != 32)`, exactly like the Java) — 21 codepoints, extracted
86/// programmatically from the Java source (not hand-transcribed from the hard-to-read
87/// rendered glyphs, several of which are zero-width combining marks that visually vanish
88/// or merge with a neighbour when displayed).
89const DIACRITICS: [char; 21] = [
90    '\u{00B4}', '\u{02DD}', '\u{0060}', '\u{030F}', '\u{02C6}', '\u{02C7}', '\u{02D8}', '\u{0311}',
91    '\u{00B8}', '\u{00A8}', '\u{00B7}', '\u{0321}', '\u{0322}', '\u{0309}', '\u{031B}', '\u{02C9}',
92    '\u{02DB}', '\u{02DA}', '\u{02F3}', '\u{1FFE}', '\u{1FBF}',
93];
94
95/// Java `UnicodeUtils.HOMOGLYHPS` (`UnicodeUtils.java:59-139`, static-init block): a
96/// codepoint -> canonical-char map, built once from [`HOMOGLYPHS_TXT`]. Faithful port of
97/// the loader's exact algorithm, verified against a compiled run of the real Java
98/// `LineReader` over the real resource file (see the loop body comments below for the
99/// specific findings that verification surfaced):
100///
101/// 1. `'ſ'` (U+017F LATIN SMALL LETTER LONG S) -> `'s'` is inserted FIRST, before any table
102///    row loads, so it wins over row `f`'s own listing of `'ſ'` as one of ITS look-alikes
103///    (`homoglyphs.txt` line 72, canonical `f`) — the loop below never overwrites an
104///    existing key. Java `UnicodeUtils.java:71`: `homoglyphs.put(toCodePoint('ſ'), 's');`.
105/// 2. Each remaining `homoglyphs.txt` line is a candidate row, in file order. Java's
106///    `LineReader` (`skipBlank=true, skipComments=true`, the defaults its 1-arg
107///    `InputStream` constructor chains to) skips blank and `#`-comment lines before they
108///    ever reach this loop. A plain `line.is_empty()` check stands in for `LineReader`'s
109///    fuller `StringUtils.isBlank` (which additionally treats any all-whitespace line as
110///    blank): the ONE line in this file that's all-whitespace-but-not-empty (line 9, a run
111///    of Unicode space variants: U+0020 U+0020 U+1680 U+2000-U+200A U+2028 U+2029 U+202F
112///    U+205F) is NOT actually blank under Java's exact `Character.isWhitespace` (which
113///    excludes U+2007 FIGURE SPACE and U+202F NARROW NO-BREAK SPACE, both present on that
114///    line) — so Java's `LineReader` does NOT skip it either, and it reaches
115///    `UnicodeUtils`'s own loop body same as any other row. It's discarded there instead,
116///    by step 3's `IGNORED_CANONICALS` check (its canonical, the first char, is U+0020
117///    SPACE) — so the outcome is identical either way; `line.is_empty()` here is not a
118///    faithfulness gap.
119/// 3. The row's canonical is its first char (`.chars().next()` on a non-empty `str` is
120///    exactly Java's `line.charAt(0)` here — the canonical is never a surrogate pair, and a
121///    Rust `char` is already a full Unicode scalar value). If the canonical is one of
122///    [`IGNORED_CANONICALS`], the entire row is skipped.
123/// 4. Otherwise, every remaining char on the row becomes a candidate homoglyph VALUE,
124///    filtered exactly as `UnicodeUtils.java:104-111` filters it: codepoint > 128 (skip
125///    ASCII/Latin-1-control), not [`HYBRID_MARKER`], not in [`DIACRITICS`], not already a
126///    map key (first row wins — relevant beyond just the `'ſ'` pre-seed whenever the same
127///    look-alike appears on more than one row), not in [`QUOTE_IGNORE`].
128/// 5. After a (non-ignored-canonical) row is fully processed, Java breaks the loop
129///    (`UnicodeUtils.java:128`: `if (lr.getRow() > 175 || 'ɸ' == canonical) break;`,
130///    comment "skip all rare chars"). `lr.getRow()` is the row's own 1-indexed PHYSICAL
131///    line number in the source file (confirmed by compiling and running the real
132///    `LineReader` against the real resource file) — i.e. exactly this loop's `row`
133///    variable below, a straight `enumerate()` index, not a count of rows actually
134///    accepted. The `> 175` numeric fallback is dead code against the actual resource file
135///    — canonical `'ɸ'` (U+0278, physical line 151) always fires first — but ported
136///    verbatim anyway, matching this port's established precedent of preserving
137///    apparently-dead Java guards faithfully (see e.g. `stash_trailing_strain_code`'s
138///    `DIGITS_ONLY` guard in `pipeline::stripandstash`). Net effect: only `homoglyphs.txt`
139///    lines 1-151 are ever consulted — lines 1-8 are the file's own comment header (all
140///    `#`-prefixed), line 9 is the ignored space-canonical row, 2 more rows in range (14,
141///    canonical `'`; 20, canonical `-`) are also [`IGNORED_CANONICALS`], and the remaining
142///    140 rows (lines 10-151, minus those 2) each contribute at least one map entry — lines
143///    152-1861 (the file's long CJK "duplicate codepoint" tail, e.g. `"𦰶𦰶"`) are never
144///    read into the map at all — by Java's own design, not a deferral this port introduces.
145static HOMOGLYPHS: LazyLock<HashMap<char, char>> = LazyLock::new(|| {
146    let mut map = HashMap::new();
147    map.insert('\u{017F}', 's'); // 'ſ' -> 's', pre-seeded (see step 1 above)
148
149    for (idx, line) in HOMOGLYPHS_TXT.lines().enumerate() {
150        let row = idx + 1; // 1-indexed physical line number == Java `lr.getRow()`
151        if line.is_empty() || line.starts_with('#') {
152            continue;
153        }
154        let canonical = line.chars().next().expect("checked non-empty above");
155        if IGNORED_CANONICALS.contains(&canonical) {
156            continue;
157        }
158        for cp in line.chars().skip(1) {
159            if (cp as u32) > 128
160                && cp != HYBRID_MARKER
161                && !DIACRITICS.contains(&cp)
162                && !map.contains_key(&cp)
163                && !QUOTE_IGNORE.contains(&cp)
164            {
165                map.insert(cp, canonical);
166            }
167        }
168        if row > 175 || canonical == 'ɸ' {
169            break;
170        }
171    }
172    map
173});
174
175/// Java `UnicodeUtils.containsHomoglyphs(CharSequence)` (`UnicodeUtils.java:194-196`,
176/// delegating to `findHomoglyph` at `:203-215`). Returns true if `s` contains at least one
177/// character that is a known homoglyph of a Latin letter. Java's version short-circuits via
178/// a codepoint lower/upper-bound check before the map lookup (an `Int2CharMap`-specific
179/// micro-optimisation); a `HashMap<char, _>` lookup here is already O(1) average without
180/// needing that bound check reproduced.
181pub fn contains_homoglyphs(s: &str) -> bool {
182    s.chars().any(|c| HOMOGLYPHS.contains_key(&c))
183}
184
185/// Java `UnicodeUtils.replaceHomoglyphs(CharSequence, boolean)` / its 3-arg sibling
186/// (`UnicodeUtils.java:239-276`), specialised to the only shape any ported call site ever
187/// needs: `inclHyphens=false` and no `keep` set. `pipeline::stripandstash`'s step 13 (the
188/// sole caller) always passes `inclHyphens=false` — Unicode hyphen variants are already
189/// normalised to ASCII `-` by the immediately-preceding step 12 (`normaliseHyphens`), per
190/// that Java method's own comment ("Hyphen homoglyphs are intentionally excluded — those
191/// are normalised above already") — so `HYPHEN_HOMOGLYHPS` (`UnicodeUtils.java:141-167`)
192/// and the `keep`-list parameter are both unreachable dead weight for this port's actual
193/// call graph and are not ported. Replaces every character present as a key in
194/// [`HOMOGLYPHS`] with its mapped canonical; every other character passes through
195/// unchanged.
196pub fn replace_homoglyphs(s: &str) -> String {
197    s.chars()
198        .map(|c| *HOMOGLYPHS.get(&c).unwrap_or(&c))
199        .collect()
200}
201
202/// Faithful port of Java `String.trim()`: strips only leading/trailing chars whose
203/// codepoint is <= U+0020 (NOT the full Unicode White_Space set that Rust's str::trim uses).
204/// Use this everywhere the Java source calls `.trim()`.
205///
206/// Java's `String.trim()` only removes characters with codepoint values 0–32 (space through
207/// control chars), while Rust's `str::trim()` removes the entire Unicode `White_Space` category.
208/// This means non-breaking space (U+00A0) and other Unicode spaces are trimmed by Rust but NOT
209/// by Java, causing empty/length guard logic to diverge.
210pub fn java_trim(s: &str) -> &str {
211    s.trim_matches(|c: char| (c as u32) <= 0x20)
212}
213
214/// Folds every Unicode space separator (category `Zs`: NBSP U+00A0, U+1680, U+2000–U+200A, the
215/// narrow NBSP U+202F, U+205F, U+3000) to an ASCII space. The parser's own whitespace handling is
216/// ASCII-only (Java parity: `String.trim()`, `Character.isWhitespace`, and the `(?-u:\s)` regexes
217/// all skip NBSP), so an NBSP left in place glues words together and hides keywords from every
218/// stage — `Assimineidae\u{a0}incertae\u{a0}sedis` read as a monomial with the author
219/// `incertae sedis`. Runs once on the raw input, before [`java_trim`], so the guards and every
220/// later stage see plain spaces. Borrows when there is nothing to fold (the common case).
221pub fn normalize_spaces(x: &str) -> Cow<'_, str> {
222    if x.chars().any(is_unicode_space) {
223        Cow::Owned(
224            x.chars()
225                .map(|c| if is_unicode_space(c) { ' ' } else { c })
226                .collect(),
227        )
228    } else {
229        Cow::Borrowed(x)
230    }
231}
232
233fn is_unicode_space(c: char) -> bool {
234    matches!(
235        c,
236        '\u{00A0}' | '\u{1680}' | '\u{2000}'..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}'
237    )
238}
239
240/// Normalises the many unicode apostrophe / single-quote variants to the ASCII apostrophe
241/// (') and the unicode double-quote variants to the ASCII double quote ("). Author names
242/// and quoted/provisional names routinely arrive with curly, prime, modifier-letter,
243/// low-9, fullwidth or Windows-1252 quotes; collapsing them to ASCII keeps tokenisation
244/// and the parsed output consistent regardless of the input's quote style.
245///
246/// Faithful port of Java `UnicodeUtils.normalizeQuotes(String)`. Java's `null`-in/`null`-out
247/// case is not ported: this takes and returns non-nullable Rust types, so callers threading
248/// an optional authorship string (e.g. `Option<&str>`) map over it instead
249/// (`authorship.map(normalize_quotes)`), which reproduces the same null-forwarding at the
250/// `Option` level.
251pub fn normalize_quotes(x: &str) -> String {
252    x.chars()
253        .map(|c| {
254            if SINGLE_QUOTES.contains(&c) {
255                '\''
256            } else if DOUBLE_QUOTES.contains(&c) {
257                '"'
258            } else {
259                c
260            }
261        })
262        .collect()
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268
269    // ---- Homoglyph table ----
270
271    /// `homoglyphs.txt` lines 10-151 (142 physical lines) are the candidate data rows once
272    /// the 8-line `#`-comment header and line 9's ignored space-canonical row are behind us
273    /// (see [`HOMOGLYPHS`]'s own doc comment); 2 more of those 142 (line 14, canonical `'`;
274    /// line 20, canonical `-`) are also [`IGNORED_CANONICALS`], leaving 140 rows that each
275    /// contribute at least one homoglyph codepoint (independently verified against the
276    /// source file — no row contributes zero) — plus the `'ſ'` pre-seed, for an exact total
277    /// of 1751 map entries. Asserted exactly (not just "a lot"), as a direct regression
278    /// guard against a bad resource copy or a loader loop that silently stops early/never
279    /// reaches `'ɸ'`/double-counts/under-filters.
280    #[test]
281    fn resource_loads_exactly_1751_entries() {
282        assert_eq!(
283            HOMOGLYPHS.len(),
284            1751,
285            "loaded homoglyph count drifted — see this test's own doc comment"
286        );
287    }
288
289    /// Java `UnicodeUtilsTest.replaceHomoglyphs` (`UnicodeUtilsTest.java:117`): long-s
290    /// folds to plain "s" (NOT "f", even though `ſ` sits on `homoglyphs.txt`'s `f`-canonical
291    /// row too — the manual pre-seed wins), while `æ` — a genuine Latin ligature, not a
292    /// look-alike — is untouched; this table is not `foldToAscii`. Same shape as the
293    /// corpus's `specificEpithet`-affecting rows ("Musca domeſtica", "Amphisbæna
294    /// fuliginoſa") — see the sibling test below and `pipeline::stripandstash`'s golden
295    /// harness `ALLOWLIST` (now empty, see that file's own history).
296    #[test]
297    fn long_s_folds_to_s_but_ae_ligature_is_untouched() {
298        assert_eq!(
299            replace_homoglyphs("Coccinella 2-puſtulata Linnæus, 1758"),
300            "Coccinella 2-pustulata Linnæus, 1758"
301        );
302    }
303
304    /// The two golden-corpus names this port's `replace_homoglyphs` stub used to leave
305    /// untouched (`crates/nameparser/tests/parse_golden.rs`, `specificEpithet`/`warnings`
306    /// mismatches, now 0). `genus="Amphisbæna"` keeps its `æ` — only the specific epithet's
307    /// `ſ` is a homoglyph here.
308    #[test]
309    fn corpus_long_s_names_fold_to_s() {
310        assert_eq!(replace_homoglyphs("Musca domeſtica"), "Musca domestica");
311        assert_eq!(
312            replace_homoglyphs("Amphisbæna fuliginoſa"),
313            "Amphisbæna fuliginosa"
314        );
315    }
316
317    /// Java `UnicodeUtilsTest.containsHomoglyphs` (`UnicodeUtilsTest.java:77`, comment
318    /// "hybrid marker is fine in out domain!"): U+00D7 '×' is excluded from the table even
319    /// though it sits on the `x`-canonical row, so a genuine hybrid-formula name survives
320    /// `replace_homoglyphs` untouched.
321    #[test]
322    fn hybrid_marker_is_not_a_homoglyph() {
323        assert!(!contains_homoglyphs("Abies × Picea"));
324        assert_eq!(replace_homoglyphs("Abies × Picea"), "Abies × Picea");
325    }
326
327    /// Java `UnicodeUtilsTest.replaceHomoglyphs` (`UnicodeUtilsTest.java:119-120`, the
328    /// `composed` string): digraphs/ligatures round-trip unchanged — this table only
329    /// touches genuine cross-script look-alikes, never legitimate distinct Latin letters.
330    #[test]
331    fn ligatures_and_composed_letters_are_untouched() {
332        let composed = "æÆœŒIJijLjljȸȹßstſtfffiflffiffl";
333        assert!(!contains_homoglyphs(composed));
334        assert_eq!(replace_homoglyphs(composed), composed);
335    }
336
337    /// A Cyrillic 'а' (U+0430, `homoglyphs.txt` line 67's `a`-canonical row) look-alike
338    /// mid-word folds to plain "a", flagging as a homoglyph.
339    #[test]
340    fn cyrillic_a_lookalike_folds_to_latin_a() {
341        assert!(contains_homoglyphs("Aus \u{0430}bus"));
342        assert_eq!(replace_homoglyphs("Aus \u{0430}bus"), "Aus abus");
343    }
344
345    /// A plain-ASCII scientific name contains no homoglyphs and round-trips byte-identical.
346    #[test]
347    fn plain_ascii_name_has_no_homoglyphs() {
348        assert!(!contains_homoglyphs("Abies alba Mill."));
349        assert_eq!(replace_homoglyphs("Abies alba Mill."), "Abies alba Mill.");
350    }
351
352    /// `¡` (U+00A1) is a Win-1252 transcription artefact handled by the SEPARATE
353    /// `repairWin1252Artefacts` step (`pipeline::stripandstash`'s `repair_win1252_artefacts`
354    /// step 14) — it is not in the homoglyph table itself. Java
355    /// `UnicodeUtilsTest.replaceHomoglyphs` (`UnicodeUtilsTest.java:115`, comment "should
356    /// this be a homoglyph?") asserts the same non-membership.
357    #[test]
358    fn win1252_artefacts_are_not_homoglyphs() {
359        assert!(!contains_homoglyphs("¡i"));
360        assert_eq!(replace_homoglyphs("¡i"), "¡i");
361    }
362
363    #[test]
364    fn folds_curly_single_quotes_to_ascii_apostrophe() {
365        assert_eq!(normalize_quotes("d\u{2019}Urville"), "d'Urville");
366        assert_eq!(normalize_quotes("\u{2018}Aus\u{2019}"), "'Aus'");
367    }
368
369    #[test]
370    fn normalize_spaces_folds_unicode_space_separators_only() {
371        assert_eq!(
372            normalize_spaces("Abies\u{a0}alba\u{202f}L.\u{3000}x"),
373            "Abies alba L. x"
374        );
375        assert!(matches!(
376            normalize_spaces("Abies alba\tL."),
377            Cow::Borrowed(_)
378        ));
379    }
380
381    #[test]
382    fn folds_curly_double_quotes_to_ascii_double_quote() {
383        assert_eq!(normalize_quotes("\u{201C}Aus bus\u{201D}"), "\"Aus bus\"");
384    }
385
386    #[test]
387    fn folds_backtick_acute_and_fullwidth_apostrophe_variants() {
388        assert_eq!(normalize_quotes("\u{0060}"), "'");
389        assert_eq!(normalize_quotes("\u{00B4}"), "'");
390        assert_eq!(normalize_quotes("\u{FF07}"), "'");
391    }
392
393    #[test]
394    fn folds_low9_and_prime_double_quote_variants() {
395        assert_eq!(normalize_quotes("\u{201E}Aus\u{201F}"), "\"Aus\"");
396        assert_eq!(normalize_quotes("\u{2033}"), "\"");
397    }
398
399    #[test]
400    fn leaves_plain_ascii_and_already_normalised_quotes_untouched() {
401        assert_eq!(normalize_quotes("O'Brien"), "O'Brien");
402        assert_eq!(normalize_quotes("\"Aus bus\" Smith"), "\"Aus bus\" Smith");
403        assert_eq!(normalize_quotes("Abies alba Mill."), "Abies alba Mill.");
404    }
405
406    #[test]
407    fn java_trim_strips_only_up_to_u0020() {
408        assert_eq!(java_trim("  x\t"), "x"); // ASCII space + tab (<=0x20) stripped
409        assert_eq!(java_trim("\n x \r"), "x"); // newline/CR stripped
410        assert_eq!(java_trim("\u{00A0}x\u{00A0}"), "\u{00A0}x\u{00A0}"); // NBSP (>0x20) NOT stripped
411        assert_eq!(java_trim("\u{00A0}"), "\u{00A0}"); // NBSP-only stays non-empty, matching Java
412    }
413}