Skip to main content

brrrty_js/
collate.rs

1//! `String.prototype.localeCompare` with no locale argument, in an English
2//! locale: ICU's root collation at tertiary strength, with normalization
3//! on, as V8 sets it up.
4//!
5//! The data is icu4x's (CLDR 49, Unicode 18). Node 26 ships ICU 78.3
6//! (CLDR 48, Unicode 17). Two kinds of character are refused, because the
7//! order differs:
8//!
9//! - Han ideographs (any character whose compatibility decomposition has
10//!   one: CJK ideographs, compatibility ideographs, Kangxi and CJK
11//!   radicals, `々`). Node's ICU sorts them by radical and stroke count
12//!   from Unihan; icu4x's data sorts them by code point within blocks.
13//!   4,274 adjacent pairs of Node's order of every code point come out the
14//!   other way.
15//! - Characters new in Unicode 18, which Node's ICU leaves unassigned.
16//!
17//! Every other code point sorts as in Node: the review sorted all of them
18//! with Node and checked each neighbouring pair, alone and in 14 contexts.
19
20use std::cmp::Ordering;
21use std::sync::OnceLock;
22
23use icu_collator::options::CollatorOptions;
24use icu_collator::{Collator, CollatorBorrowed};
25
26fn collator() -> &'static CollatorBorrowed<'static> {
27    static C: OnceLock<CollatorBorrowed<'static>> = OnceLock::new();
28    C.get_or_init(|| {
29        Collator::try_new(Default::default(), CollatorOptions::default())
30            .expect("the root collation is compiled in")
31    })
32}
33
34/// Code points assigned in Unicode 18 that Node 26's Unicode 17 leaves
35/// unassigned: icu4x 2.4's general category against Node's `/\p{Cn}/u`,
36/// over every code point (13,007 of them).
37pub const NEW_IN_UNICODE_18: &[(u32, u32)] = &[
38    (0x558, 0x558),
39    (0x58B, 0x58C),
40    (0x5C8, 0x5C9),
41    (0xB53, 0xB54),
42    (0x1ADE, 0x1ADF),
43    (0x1AEC, 0x1AF0),
44    (0x208F, 0x208F),
45    (0x209D, 0x209F),
46    (0x20C2, 0x20C4),
47    (0x2E60, 0x2E63),
48    (0xA7DD, 0xA7DD),
49    (0xA7E2, 0xA7E2),
50    (0xAB6C, 0xAB6D),
51    (0x107BB, 0x107BF),
52    (0x10EC9, 0x10ECF),
53    (0x10ED9, 0x10EEE),
54    (0x10EF0, 0x10EF9),
55    (0x11B0A, 0x11B0A),
56    (0x11DF0, 0x11DF1),
57    (0x1246F, 0x1246F),
58    (0x12475, 0x1247F),
59    (0x12550, 0x12686),
60    (0x18CD6, 0x18CDA),
61    (0x18D1F, 0x18D20),
62    (0x18E00, 0x19191),
63    (0x191A0, 0x191D2),
64    (0x1B123, 0x1B128),
65    (0x1B168, 0x1B168),
66    (0x1CED2, 0x1CED4),
67    (0x1CEDD, 0x1CEDF),
68    (0x1CEF1, 0x1CEFD),
69    (0x1D127, 0x1D128),
70    (0x1D1EB, 0x1D1FF),
71    (0x1D250, 0x1D281),
72    (0x1D6A6, 0x1D6A6),
73    (0x1DB00, 0x1DB1C),
74    (0x1DF1F, 0x1DF24),
75    (0x1DF2B, 0x1DF81),
76    (0x1DF90, 0x1DF96),
77    (0x1DFCD, 0x1DFFF),
78    (0x1F1AE, 0x1F1AE),
79    (0x1F6D9, 0x1F6D9),
80    (0x1F7DA, 0x1F7DB),
81    (0x1F7F1, 0x1F7FF),
82    (0x1FA8B, 0x1FA8D),
83    (0x1FACC, 0x1FACC),
84    (0x1FADD, 0x1FADD),
85    (0x1FAEB, 0x1FAEB),
86    (0x1FAF9, 0x1FAFA),
87    (0x2B81E, 0x2B81E),
88    (0x3D000, 0x3FC3F),
89];
90
91fn is_new(c: char) -> bool {
92    let c = c as u32;
93    NEW_IN_UNICODE_18
94        .binary_search_by(|&(lo, hi)| {
95            if hi < c {
96                Ordering::Less
97            } else if lo > c {
98                Ordering::Greater
99            } else {
100                Ordering::Equal
101            }
102        })
103        .is_ok()
104}
105
106/// Why a pair of strings isn't compared.
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108pub enum CollationRefusal {
109    /// A Han character: Node sorts it by radical and stroke.
110    Han(char),
111    /// A character new in Unicode 18, unassigned in Node 26's ICU.
112    Unicode18(char),
113}
114
115impl std::fmt::Display for CollationRefusal {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        match self {
118            CollationRefusal::Han(c) => write!(
119                f,
120                "`{c}` (U+{:04X}) is a Han character: Node sorts those by radical and stroke count, from data Brrrty doesn't have, so the order can't be matched",
121                *c as u32
122            ),
123            CollationRefusal::Unicode18(c) => write!(
124                f,
125                "U+{:04X} is new in Unicode 18, which Node's ICU doesn't have yet, so its order there can't be matched",
126                *c as u32
127            ),
128        }
129    }
130}
131
132/// Whether `c`, or anything its compatibility decomposition (NFKD) gives,
133/// is in the Han script.
134fn is_han(c: char) -> bool {
135    use icu_properties::CodePointMapData;
136    use icu_properties::props::Script;
137    use unicode_normalization::char::decompose_compatible;
138    if c.is_ascii() {
139        return false;
140    }
141    let script = CodePointMapData::<Script>::new();
142    let mut han = script.get(c) == Script::Han;
143    decompose_compatible(c, |d| han |= script.get(d) == Script::Han);
144    han
145}
146
147/// `a.localeCompare(b)` in Node with an English locale (`en-US`, or `C`):
148/// less, equal or greater, as its -1, 0 or 1. `Err` names a character
149/// whose order in Node can't be matched.
150pub fn js_locale_compare(a: &str, b: &str) -> Result<Ordering, CollationRefusal> {
151    for c in a.chars().chain(b.chars()) {
152        if is_new(c) {
153            return Err(CollationRefusal::Unicode18(c));
154        }
155        if is_han(c) {
156            return Err(CollationRefusal::Han(c));
157        }
158    }
159    Ok(collator().compare(a, b))
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn refuses_han_characters_and_their_compatibility_forms() {
168        // Node: "﨑".localeCompare("嵊") is -1, "缵".localeCompare("纓") is -1;
169        // icu4x's data gives 1 for both.
170        for (a, b, c) in [
171            ("﨑", "嵊", '﨑'),
172            ("缵", "纓", '缵'),
173            ("a", "々", '々'),
174            ("⼀", "b", '⼀'), // Kangxi radical one
175            ("x", "⺠", '⺠'), // CJK radical
176            ("㊀", "y", '㊀'), // NFKD gives 一
177        ] {
178            assert_eq!(
179                js_locale_compare(a, b),
180                Err(CollationRefusal::Han(c)),
181                "{a} {b}"
182            );
183        }
184        // Kana, Hangul and the rest still compare.
185        assert!(js_locale_compare("あ", "ア").is_ok());
186        assert!(js_locale_compare("가", "각").is_ok());
187        assert!(js_locale_compare("〇", "z").is_err());
188    }
189
190    #[test]
191    fn refuses_characters_node_does_not_know() {
192        assert_eq!(js_locale_compare("a", "b"), Ok(Ordering::Less));
193        assert_eq!(
194            js_locale_compare("a\u{20C2}", "b"),
195            Err(CollationRefusal::Unicode18('\u{20C2}'))
196        );
197        assert_eq!(
198            js_locale_compare("a", "\u{3FC3F}"),
199            Err(CollationRefusal::Unicode18('\u{3FC3F}'))
200        );
201        assert!(js_locale_compare("\u{20C1}", "\u{20C5}").is_ok());
202        let mut last = 0;
203        for &(lo, hi) in NEW_IN_UNICODE_18 {
204            assert!(lo >= last && lo <= hi);
205            last = hi + 2;
206        }
207        let count: u32 = NEW_IN_UNICODE_18.iter().map(|(lo, hi)| hi - lo + 1).sum();
208        assert_eq!(count, 13_007);
209    }
210}