1mod generated;
31
32use generated::{CANONICAL, CCC, COMPATIBILITY, COMPOSITION, DECOMPOSED};
33
34pub use generated::UNICODE_VERSION;
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
39pub enum NormalForm {
40 Nfc,
41 Nfd,
42 Nfkc,
43 Nfkd,
44}
45
46impl NormalForm {
47 pub fn name(self) -> &'static str {
49 match self {
50 NormalForm::Nfc => "NFC",
51 NormalForm::Nfd => "NFD",
52 NormalForm::Nfkc => "NFKC",
53 NormalForm::Nfkd => "NFKD",
54 }
55 }
56
57 pub fn from_name(word: &str) -> Option<NormalForm> {
61 match word.to_ascii_uppercase().as_str() {
62 "NFC" => Some(NormalForm::Nfc),
63 "NFD" => Some(NormalForm::Nfd),
64 "NFKC" => Some(NormalForm::Nfkc),
65 "NFKD" => Some(NormalForm::Nfkd),
66 _ => None,
67 }
68 }
69
70 fn composes(self) -> bool {
72 matches!(self, NormalForm::Nfc | NormalForm::Nfkc)
73 }
74
75 fn compatibility(self) -> bool {
78 matches!(self, NormalForm::Nfkc | NormalForm::Nfkd)
79 }
80}
81
82const S_BASE: u32 = 0xAC00;
86const L_BASE: u32 = 0x1100;
87const V_BASE: u32 = 0x1161;
88const T_BASE: u32 = 0x11A7;
89const L_COUNT: u32 = 19;
90const V_COUNT: u32 = 21;
91const T_COUNT: u32 = 28;
92const N_COUNT: u32 = V_COUNT * T_COUNT;
93const S_COUNT: u32 = L_COUNT * N_COUNT;
94
95fn ccc(c: char) -> u8 {
97 match CCC.binary_search_by_key(&c, |&(k, _)| k) {
98 Ok(i) => CCC[i].1,
99 Err(_) => 0,
100 }
101}
102
103fn decomposition(c: char, compatibility: bool) -> Option<&'static [char]> {
106 let table = if compatibility {
107 COMPATIBILITY
108 } else {
109 CANONICAL
110 };
111 let i = table.binary_search_by_key(&c, |&(k, _, _)| k).ok()?;
112 let (_, at, len) = table[i];
113 Some(&DECOMPOSED[at as usize..at as usize + len as usize])
114}
115
116fn compose_pair(first: char, second: char) -> Option<char> {
121 let (a, b) = (first as u32, second as u32);
122 if (L_BASE..L_BASE + L_COUNT).contains(&a) && (V_BASE..V_BASE + V_COUNT).contains(&b) {
123 let syllable = S_BASE + ((a - L_BASE) * V_COUNT + (b - V_BASE)) * T_COUNT;
124 return char::from_u32(syllable);
125 }
126 if (S_BASE..S_BASE + S_COUNT).contains(&a)
127 && (a - S_BASE).is_multiple_of(T_COUNT)
128 && (T_BASE + 1..T_BASE + T_COUNT).contains(&b)
129 {
130 return char::from_u32(a + (b - T_BASE));
131 }
132 COMPOSITION
133 .binary_search_by_key(&(first, second), |&(x, y, _)| (x, y))
134 .ok()
135 .map(|i| COMPOSITION[i].2)
136}
137
138fn decompose_char(out: &mut Vec<char>, c: char, compatibility: bool) {
141 let u = c as u32;
142 if (S_BASE..S_BASE + S_COUNT).contains(&u) {
143 let index = u - S_BASE;
144 let (l, v, t) = (
145 L_BASE + index / N_COUNT,
146 V_BASE + (index % N_COUNT) / T_COUNT,
147 index % T_COUNT,
148 );
149 out.extend(char::from_u32(l));
150 out.extend(char::from_u32(v));
151 if t != 0 {
152 out.extend(char::from_u32(T_BASE + t));
153 }
154 return;
155 }
156 match decomposition(c, compatibility) {
157 Some(chars) => out.extend_from_slice(chars),
158 None => out.push(c),
159 }
160}
161
162fn canonical_order(chars: &mut [char]) {
168 for i in 1..chars.len() {
169 let class = ccc(chars[i]);
170 if class == 0 {
171 continue;
172 }
173 let mut j = i;
174 while j > 0 && ccc(chars[j - 1]) > class {
175 chars.swap(j - 1, j);
176 j -= 1;
177 }
178 }
179}
180
181fn compose(chars: Vec<char>) -> Vec<char> {
187 let mut out: Vec<char> = Vec::with_capacity(chars.len());
188 let mut starter: Option<usize> = None;
189 let mut previous = 0u8;
190 let mut anything_since_starter = false;
191 for c in chars {
192 let class = ccc(c);
193 if let Some(at) = starter
194 && !(anything_since_starter && previous >= class)
195 && let Some(composed) = compose_pair(out[at], c)
196 {
197 out[at] = composed;
198 continue;
199 }
200 if class == 0 {
201 starter = Some(out.len());
202 anything_since_starter = false;
203 } else {
204 anything_since_starter = true;
205 }
206 previous = class;
207 out.push(c);
208 }
209 out
210}
211
212pub fn normalize(s: &str, form: NormalForm) -> String {
218 if s.is_ascii() {
219 return s.to_string();
220 }
221 let mut chars = Vec::with_capacity(s.len());
222 for c in s.chars() {
223 decompose_char(&mut chars, c, form.compatibility());
224 }
225 canonical_order(&mut chars);
226 if form.composes() {
227 chars = compose(chars);
228 }
229 chars.into_iter().collect()
230}
231
232pub fn is_normalized(s: &str, form: NormalForm) -> bool {
240 if s.is_ascii() {
241 return true;
242 }
243 normalize(s, form) == s
244}
245
246pub fn is_ident_start(c: char) -> bool {
254 if c.is_ascii() {
255 return c.is_ascii_alphabetic() || c == '_';
256 }
257 in_ranges(generated::IDENT_START, c)
258}
259
260pub fn is_ident_extend(c: char) -> bool {
264 if c.is_ascii() {
265 return c.is_ascii_alphanumeric() || c == '_';
266 }
267 in_ranges(generated::IDENT_EXTEND, c)
268}
269
270fn in_ranges(ranges: &[(char, char)], c: char) -> bool {
274 match ranges.binary_search_by(|(from, _)| from.cmp(&c)) {
275 Ok(_) => true,
276 Err(0) => false,
277 Err(at) => ranges[at - 1].1 >= c,
278 }
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 #[test]
286 fn ascii_is_already_in_every_form() {
287 for form in [
288 NormalForm::Nfc,
289 NormalForm::Nfd,
290 NormalForm::Nfkc,
291 NormalForm::Nfkd,
292 ] {
293 assert_eq!(normalize("ab", form), "ab");
294 assert!(is_normalized("ab", form));
295 }
296 }
297
298 #[test]
299 fn a_letter_and_its_accent_are_one_character_composed_and_two_decomposed() {
300 assert_eq!(normalize("e\u{301}", NormalForm::Nfc), "\u{e9}");
301 assert_eq!(normalize("\u{e9}", NormalForm::Nfd), "e\u{301}");
302 assert!(is_normalized("\u{e9}", NormalForm::Nfc));
303 assert!(!is_normalized("\u{e9}", NormalForm::Nfd));
304 }
305
306 #[test]
307 fn compatibility_is_the_only_form_that_loses_the_formatting() {
308 assert_eq!(normalize("\u{fb01}", NormalForm::Nfc), "\u{fb01}");
312 assert_eq!(normalize("\u{fb01}", NormalForm::Nfkc), "fi");
313 assert_eq!(normalize("\u{bd}", NormalForm::Nfkd), "1\u{2044}2");
314 }
315
316 #[test]
317 fn marks_sort_by_combining_class_and_keep_their_order_inside_a_class() {
318 assert_eq!(
321 normalize("a\u{301}\u{328}", NormalForm::Nfd),
322 "a\u{328}\u{301}"
323 );
324 assert_eq!(
325 normalize("a\u{301}\u{328}", NormalForm::Nfc),
326 normalize("a\u{328}\u{301}", NormalForm::Nfc)
327 );
328 }
329
330 #[test]
331 fn a_hangul_syllable_is_arithmetic_in_both_directions() {
332 assert_eq!(normalize("\u{ac00}", NormalForm::Nfd), "\u{1100}\u{1161}");
333 assert_eq!(normalize("\u{1100}\u{1161}", NormalForm::Nfc), "\u{ac00}");
334 assert_eq!(
335 normalize("\u{d4db}", NormalForm::Nfd),
336 "\u{1111}\u{1171}\u{11b6}"
337 );
338 assert_eq!(
339 normalize("\u{1111}\u{1171}\u{11b6}", NormalForm::Nfc),
340 "\u{d4db}"
341 );
342 }
343
344 #[test]
345 fn an_excluded_composition_stays_apart() {
346 assert_eq!(normalize("\u{958}", NormalForm::Nfc), "\u{915}\u{93c}");
349 assert_eq!(
350 normalize("\u{915}\u{93c}", NormalForm::Nfc),
351 "\u{915}\u{93c}"
352 );
353 }
354
355 #[test]
356 fn a_blocked_mark_does_not_reach_the_starter() {
357 assert_eq!(
360 normalize("a\u{308}\u{301}", NormalForm::Nfc),
361 "\u{e4}\u{301}"
362 );
363 assert_eq!(
364 normalize("a\u{328}\u{301}", NormalForm::Nfc),
365 "\u{105}\u{301}"
366 );
367 }
368
369 #[test]
370 fn every_form_has_a_name_and_answers_to_it() {
371 for form in [
372 NormalForm::Nfc,
373 NormalForm::Nfd,
374 NormalForm::Nfkc,
375 NormalForm::Nfkd,
376 ] {
377 assert_eq!(NormalForm::from_name(form.name()), Some(form));
378 assert_eq!(
379 NormalForm::from_name(&form.name().to_ascii_lowercase()),
380 Some(form)
381 );
382 }
383 assert_eq!(NormalForm::from_name("NFX"), None);
384 }
385}