Debian Codegraph @

debian/rust-vendor/icu_collator/src/elements.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 // Various collation-related algorithms and constants in this file are
6 // adapted from ICU4C and, therefore, are subject to the ICU license as
7 // described in LICENSE.
8
9 //! This module holds the 64-bit `CollationElement` struct used for
10 //! the actual comparison, the 32-bit `CollationElement32` struct
11 //! that's used for storage. (Strictly speaking, the storage is
12 //! `RawBytesULE<4>`.) And the `CollationElements` iterator adapter
13 //! that turns an iterator over `char` into an iterator over
14 //! `CollationElement`. (To match the structure of ICU4C, this isn't
15 //! a real Rust `Iterator`. Instead of signaling end by returning
16 //! `None`, it signals end by returning `NO_CE`.)
17 //!
18 //! This module also declares various constants that are also used
19 //! by the `comparison` module.
20
21 use icu_collections::char16trie::TrieResult;
22 use icu_collections::codepointtrie::CodePointTrie;
23 use icu_normalizer::provider::DecompositionData;
24 use icu_normalizer::provider::DecompositionTables;
25 use icu_properties::props::CanonicalCombiningClass;
26 use smallvec::SmallVec;
27 use zerovec::ule::AsULE;
28 use zerovec::ule::RawBytesULE;
29 use zerovec::{ZeroSlice, zeroslice};
30
31 use crate::provider::CollationData;
32
33 // Start `SmallVec` size constants.
34 //
35 // These are the on-stack buffer sizes. If the buffers need
36 // to grow larger, they are spilled to the heap.
37 //
38 // TODO(#2005): Figure out good sizes for these.
39
40 /// The number of full 64-bit collation units that get buffered
41 /// in the primary comparison loop so that they can be examined
42 /// by the subsequent comparison stregths.
43 ///
44 /// Note 1: If a primary difference is found, the comparison
45 /// returns early, so these buffers end up holding all the
46 /// collation elements only if there is no primary difference.
47 ///
48 /// Note 2: Unfortunately for now, a sentinel value signaling
49 /// the end of input gets written into the buffer in addition
50 /// to the real collation elements.
51 ///
52 /// This should probably either be halved to 4 on the logic
53 /// that especially in the presence of the identical prefix
54 /// optimization, most comparisons return after a couple of
55 /// primary comparisons or increased to 32 on the logic that
56 /// such a buffer could better hold a file or human name that
57 /// differs on secordary or higher level.
58 pub(crate) const CE_BUFFER_SIZE: usize = 8;
59
60 /// The number of extra full 64-bit collation units that have
61 /// already been computed as part of an operation that yields
62 /// multiple collation units at a time.
63 const PENDING_CE_BUFFER_SIZE: usize = 6;
64
65 /// Either the identical prefix or the lookahead plus the next
66 /// upcoming character.
67 ///
68 /// The longest contraction suffix in CLDR 40 is 7 characters long.
69 const UPCOMING_CHARACTER_BUFFER_SIZE: usize = 10;
70
71 /// The contiguous sequence of combining characters.
72 const COMBINING_CHARACTER_BUFFER_SIZE: usize = 7;
73
74 /// The sequence of digits in the numeric mode.
75 const DIGIT_BUFFER_SIZE: usize = 8;
76
77 /// The number of combining characters that a contraction has
78 /// matched.
79 const PENDING_REMOVALS_SIZE: usize = 1;
80
81 // End `SmallVec` constants
82
83 /// Marker that the decomposition does not round trip via NFC.
84 ///
85 /// See components/normalizer/trie-value-format.md
86 pub(crate) const NON_ROUND_TRIP_MARKER: u32 = 1 << 30;
87
88 /// Marker that the first character of the decomposition
89 /// can combine backwards.
90 ///
91 /// See components/normalizer/trie-value-format.md
92 pub(crate) const BACKWARD_COMBINING_MARKER: u32 = 1 << 31;
93
94 /// Mask for the bits have to be zero for this to be a BMP
95 /// singleton decomposition, or value baked into the surrogate
96 /// range.
97 ///
98 /// See components/normalizer/trie-value-format.md
99 pub(crate) const HIGH_ZEROS_MASK: u32 = 0x3FFF0000;
100
101 /// Mask for the bits have to be zero for this to be a complex
102 /// decomposition.
103 ///
104 /// See components/normalizer/trie-value-format.md
105 pub(crate) const LOW_ZEROS_MASK: u32 = 0xFFE0;
106
107 /// Marker value for U+FDFA in NFKD. (Unified with
108 /// `HANGUL_SYLLABLE_MARKER`, but they differ by
109 /// `NON_ROUND_TRIP_MARKER`.)
110 ///
111 /// See components/normalizer/trie-value-format.md
112 const FDFA_MARKER: u16 = 1;
113
114 /// Marker value for Hangul syllables. (Unified with `FDFA_MARKER`,
115 /// but they differ by `NON_ROUND_TRIP_MARKER`.)
116 ///
117 /// See components/normalizer/trie-value-format.md
118 pub(crate) const HANGUL_SYLLABLE_MARKER: u32 = 1;
119
120 /// Checks if a trie value carries a (non-zero) canonical
121 /// combining class.
122 ///
123 /// See components/normalizer/trie-value-format.md
124 fn trie_value_has_ccc(trie_value: u32) -> bool {
125 (trie_value & 0x3FFFFE00) == 0xD800
126 }
127
128 /// Checks if the trie signifies a special non-starter decomposition.
129 ///
130 /// See components/normalizer/trie-value-format.md
131 fn trie_value_indicates_special_non_starter_decomposition(trie_value: u32) -> bool {
132 (trie_value & 0x3FFFFF00) == 0xD900
133 }
134
135 /// Checks if a trie value signifies a character whose decomposition
136 /// starts with a non-starter.
137 ///
138 /// See components/normalizer/trie-value-format.md
139 fn decomposition_starts_with_non_starter(trie_value: u32) -> bool {
140 trie_value_has_ccc(trie_value)
141 }
142
143 /// Extracts a canonical combining class (possibly zero) from a trie value.
144 ///
145 /// See components/normalizer/trie-value-format.md
146 fn ccc_from_trie_value(trie_value: u32) -> CanonicalCombiningClass {
147 if trie_value_has_ccc(trie_value) {
148 CanonicalCombiningClass(trie_value as u8)
149 } else {
150 CanonicalCombiningClass::NotReordered
151 }
152 }
153
154 // These constants originate from page 143 of Unicode 14.0
155 const HANGUL_S_BASE: u32 = 0xAC00;
156 const HANGUL_L_BASE: u32 = 0x1100;
157 const HANGUL_V_BASE: u32 = 0x1161;
158 const HANGUL_T_BASE: u32 = 0x11A7;
159 const HANGUL_T_COUNT: u32 = 28;
160 const HANGUL_N_COUNT: u32 = 588;
161 const HANGUL_S_COUNT: u32 = 11172;
162
163 pub(crate) const JAMO_COUNT: usize = 256; // 0x1200 - 0x1100
164
165 const COMBINING_DIACRITICS_BASE: usize = 0x0300;
166 const OPTIMIZED_DIACRITICS_LIMIT: usize = 0x034F;
167 pub(crate) const OPTIMIZED_DIACRITICS_MAX_COUNT: usize =
168 OPTIMIZED_DIACRITICS_LIMIT - COMBINING_DIACRITICS_BASE;
169
170 pub(crate) const CASE_MASK: u16 = 0xC000;
171 pub(crate) const TERTIARY_MASK: u16 = 0x3F3F; // ONLY_TERTIARY_MASK in ICU4C
172 pub(crate) const QUATERNARY_MASK: u16 = 0xC0;
173
174 // A CE32 is special if its low byte is this or greater.
175 // Impossible case bits 11 mark special CE32s.
176 // This value itself is used to indicate a fallback to the root collation.
177 const SPECIAL_CE32_LOW_BYTE: u8 = 0xC0;
178 pub(crate) const FALLBACK_CE32: CollationElement32 =
179 CollationElement32(SPECIAL_CE32_LOW_BYTE as u32);
180 const LONG_PRIMARY_CE32_LOW_BYTE: u8 = 0xC1; // SPECIAL_CE32_LOW_BYTE | LONG_PRIMARY_TAG
181 const COMMON_SECONDARY_CE: u64 = 0x05000000;
182 const COMMON_TERTIARY_CE: u64 = 0x0500;
183 const COMMON_SEC_AND_TER_CE: u64 = COMMON_SECONDARY_CE | COMMON_TERTIARY_CE;
184
185 const UNASSIGNED_IMPLICIT_BYTE: u8 = 0xFE;
186
187 // /// Set if there is no match for the single (no-suffix) character itself.
188 // /// This is only possible if there is a prefix.
189 // /// In this case, discontiguous contraction matching cannot add combining marks
190 // /// starting from an empty suffix.
191 // /// The default CE32 is used anyway if there is no suffix match.
192 // const CONTRACT_SINGLE_CP_NO_MATCH: u32 = 0x100;
193
194 /// Set if the first character of every contraction suffix has lccc!=0.
195 const CONTRACT_NEXT_CCC: u32 = 0x200;
196 /// Set if any contraction suffix ends with lccc!=0.
197 const CONTRACT_TRAILING_CCC: u32 = 0x400;
198 /// Set if at least one contraction suffix contains a starter
199 const CONTRACT_HAS_STARTER: u32 = 0x800;
200
201 // const NO_CE32: CollationElement32 = CollationElement32::default();
202 // constants named NO_CE* : End of input. Only used in runtime code, not stored in data.
203 pub(crate) const NO_CE: CollationElement = CollationElement::default();
204 pub(crate) const NO_CE_PRIMARY: u32 = 1; // not a left-adjusted weight
205 // const NO_CE_NON_PRIMARY: NonPrimary = NonPrimary::default();
206 pub(crate) const NO_CE_SECONDARY: u16 = 0x0100;
207 pub(crate) const NO_CE_TERTIARY: u16 = 0x0100;
208 pub(crate) const NO_CE_QUATERNARY: u16 = 0x0100;
209 const NO_CE_VALUE: u64 =
210 ((NO_CE_PRIMARY as u64) << 32) | ((NO_CE_SECONDARY as u64) << 16) | (NO_CE_TERTIARY as u64); // 0x101000100
211
212 // See ICU4C collation.h and https://www.unicode.org/reports/tr10/#Trailing_Weights
213 const FFFD_PRIMARY: u32 = 0xFFFD0000; // U+FFFD
214 pub(crate) const FFFD_CE_VALUE: u64 = ((FFFD_PRIMARY as u64) << 32) | COMMON_SEC_AND_TER_CE;
215 pub(crate) const FFFD_CE: CollationElement = CollationElement(FFFD_CE_VALUE);
216 pub(crate) const FFFD_CE32_VALUE: u32 = 0xFFFD0505;
217 pub(crate) const FFFD_CE32: CollationElement32 = CollationElement32(FFFD_CE32_VALUE);
218
219 pub(crate) const EMPTY_U16: &ZeroSlice<u16> = zeroslice![];
220 const SINGLE_REPLACEMENT_CHARACTER_U16: &ZeroSlice<u16> =
221 zeroslice!(u16; <u16 as AsULE>::ULE::from_unsigned; [char::REPLACEMENT_CHARACTER as u16]);
222
223 pub(crate) const EMPTY_CHAR: &ZeroSlice<char> = zeroslice![];
224 const SINGLE_REPLACEMENT_CHARACTER_CHAR: &ZeroSlice<char> =
225 zeroslice!(char; <char as AsULE>::ULE::from_aligned; [char::REPLACEMENT_CHARACTER]);
226
227 /// If `opt` is `Some`, unwrap it. If `None`, panic if debug assertions
228 /// are enabled and return `default` if debug assertions are not enabled.
229 ///
230 /// Use this only if the only reason why `opt` could be `None` is bogus
231 /// data from the provider.
232 #[inline(always)]
233 pub(crate) fn unwrap_or_gigo<T>(opt: Option<T>, default: T) -> T {
234 if let Some(val) = opt {
235 val
236 } else {
237 // GIGO case
238 debug_assert!(false);
239 default
240 }
241 }
242
243 /// Convert a `u32` _obtained from data provider data_ to `char`.
244 #[inline(always)]
245 pub(crate) fn char_from_u32(u: u32) -> char {
246 unwrap_or_gigo(char::from_u32(u), char::REPLACEMENT_CHARACTER)
247 }
248
249 /// Convert a `u16` _obtained from data provider data_ to `char`.
250 #[inline(always)]
251 fn char_from_u16(u: u16) -> char {
252 char_from_u32(u32::from(u))
253 }
254
255 #[inline(always)]
256 fn in_inclusive_range(c: char, start: char, end: char) -> bool {
257 u32::from(c).wrapping_sub(u32::from(start)) <= (u32::from(end) - u32::from(start))
258 }
259
260 /// Special-CE32 tags, from bits 3..0 of a special 32-bit CE.
261 /// Bits 31..8 are available for tag-specific data.
262 /// Bits 5..4: Reserved. May be used in the future to indicate lccc!=0 and tccc!=0.
263 #[derive(Eq, PartialEq, Debug)]
264 #[allow(dead_code)]
265 #[repr(u8)] // This repr is necessary for transmute safety
266 pub(crate) enum Tag {
267 /// Fall back to the base collator.
268 /// This is the tag value in [`SPECIAL_CE32_LOW_BYTE`] and [`FALLBACK_CE32`].
269 /// Bits 31..8: Unused, 0.
270 Fallback = 0,
271 /// Long-primary CE with [`COMMON_SEC_AND_TER_CE`].
272 /// Bits 31..8: Three-byte primary.
273 LongPrimary = 1,
274 /// Long-secondary CE with zero primary.
275 /// Bits 31..16: Secondary weight.
276 /// Bits 15.. 8: Tertiary weight.
277 LongSecondary = 2,
278 /// Unused.
279 /// May be used in the future for single-byte secondary CEs (`SHORT_SECONDARY_TAG`),
280 /// storing the secondary in bits 31..24, the ccc in bits 23..16,
281 /// and the tertiary in bits 15..8.
282 Reserved3 = 3,
283 /// Latin mini expansions of two simple CEs [pp, 05, tt] [00, ss, 05].
284 /// Bits 31..24: Single-byte primary weight pp of the first CE.
285 /// Bits 23..16: Tertiary weight tt of the first CE.
286 /// Bits 15.. 8: Secondary weight ss of the second CE.
287 /// Unused by ICU4X, may get repurposed for jamo expansions is Korean search.
288 LatinExpansion = 4,
289 /// Points to one or more simple/long-primary/long-secondary 32-bit CE32s.
290 /// Bits 31..13: Index into `uint32_t` table.
291 /// Bits 12.. 8: Length=1..31.
292 Expansion32 = 5,
293 /// Points to one or more 64-bit CEs.
294 /// Bits 31..13: Index into CE table.
295 /// Bits 12.. 8: Length=1..31.
296 Expansion = 6,
297 /// Builder data, used only in the `CollationDataBuilder`, not in runtime data.
298 ///
299 /// If bit 8 is 0: Builder context, points to a list of context-sensitive mappings.
300 /// Bits 31..13: Index to the builder's list of `ConditionalCE32` for this character.
301 /// Bits 12.. 9: Unused, 0.
302 ///
303 /// If bit 8 is 1 (`IS_BUILDER_JAMO_CE32`): Builder-only jamoCE32 value.
304 /// The builder fetches the Jamo CE32 from the trie.
305 /// Bits 31..13: Jamo code point.
306 /// Bits 12.. 9: Unused, 0.
307 BuilderData = 7,
308 /// Points to prefix trie.
309 /// Bits 31..13: Index into prefix/contraction data.
310 /// Bits 12.. 8: Unused, 0.
311 Prefix = 8,
312 /// Points to contraction data.
313 /// Bits 31..13: Index into prefix/contraction data.
314 /// Bits 12..11: Unused, 0.
315 /// Bit 10: `CONTRACT_TRAILING_CCC` flag.
316 /// Bit 9: `CONTRACT_NEXT_CCC` flag.
317 /// Bit 8: `CONTRACT_SINGLE_CP_NO_MATCH` flag.
318 Contraction = 9,
319 /// Decimal digit.
320 /// Bits 31..13: Index into `uint32_t` table for non-numeric-collation CE32.
321 /// Bit 12: Unused, 0.
322 /// Bits 11.. 8: Digit value 0..9.
323 Digit = 10,
324 /// Tag for U+0000, for moving the NUL-termination handling
325 /// from the regular fastpath into specials-handling code.
326 /// Bits 31..8: Unused, 0.
327 /// Not used by ICU4X.
328 U0000 = 11,
329 /// Tag for a Hangul syllable.
330 /// Bits 31..9: Unused, 0.
331 /// Bit 8: `HANGUL_NO_SPECIAL_JAMO` flag.
332 /// Not used by ICU4X, may get reused for compressing Hanja expansions.
333 Hangul = 12,
334 /// Tag for a lead surrogate code unit.
335 /// Optional optimization for UTF-16 string processing.
336 /// Bits 31..10: Unused, 0.
337 /// 9.. 8: =0: All associated supplementary code points are unassigned-implicit.
338 /// =1: All associated supplementary code points fall back to the base data.
339 /// else: (Normally 2) Look up the data for the supplementary code point.
340 /// Not used by ICU4X.
341 LeadSurrogate = 13,
342 /// Tag for CEs with primary weights in code point order.
343 /// Bits 31..13: Index into CE table, for one data "CE".
344 /// Bits 12.. 8: Unused, 0.
345 ///
346 /// This data "CE" has the following bit fields:
347 /// Bits 63..32: Three-byte primary pppppp00.
348 /// 31.. 8: Start/base code point of the in-order range.
349 /// 7: Flag isCompressible primary.
350 /// 6.. 0: Per-code point primary-weight increment.
351 Offset = 14,
352 /// Implicit CE tag. Compute an unassigned-implicit CE.
353 /// All bits are set (`UNASSIGNED_CE32=0xffffffff`).
354 Implicit = 15,
355 }
356
357 /// A compressed form of a collation element as stored in the collation
358 /// data.
359 ///
360 /// A `CollationElement32` can be "normal" or "special".
361 /// Bits 7 and 6 are case bits for the "normal" case and setting
362 /// both is an impossible case bit combination. Hence, "special"
363 /// `CollationElement32`s are marked by setting both case bits
364 /// to 1. This is equivalent with the low byte being less than
365 /// `SPECIAL_CE32_LOW_BYTE` (0xC0, i.e. 0b11000000) in the "normal"
366 /// case and equal to or greater in the "special" case.
367 ///
368 /// For the normal case:
369 /// Bits: 31..16: Primary weight
370 /// Bits: 15..8: Secondary weight
371 /// Bits: 7..6: Case bits (cannot both be 1 simultaneously)
372 /// Bits: 5..0: The high part of the discontiguous tertiary weight
373 /// (The quaternary weight and the low part of the discontiguous
374 /// tertiary weight are zero.)
375 ///
376 /// For the special case:
377 /// Bits 31..8: tag-specific; see the documentation for `Tag`.
378 /// Bits 7..6: The specialness marker; both bits set to 1
379 /// Bits 5..4: Reserved. May be used in the future to indicate lccc!=0 and tccc!=0.
380 /// Bits 3..0: the tag (bit-compatible with `Tag`)
381 #[derive(Copy, Clone, PartialEq, Debug)]
382 pub(crate) struct CollationElement32(u32);
383
384 impl CollationElement32 {
385 #[inline(always)]
386 pub fn new(bits: u32) -> Self {
387 CollationElement32(bits)
388 }
389
390 #[inline(always)]
391 pub fn new_from_ule(ule: RawBytesULE<4>) -> Self {
392 CollationElement32(u32::from_unaligned(ule))
393 }
394
395 #[inline(always)]
396 fn low_byte(self) -> u8 {
397 self.0 as u8
398 }
399
400 #[inline(always)]
401 pub(crate) fn tag_checked(self) -> Option<Tag> {
402 let t = self.low_byte();
403 if t < SPECIAL_CE32_LOW_BYTE {
404 None
405 } else {
406 Some(self.tag())
407 }
408 }
409
410 /// Returns the tag if this element is special.
411 /// Non-specialness should first be checked by seeing if either
412 /// `to_ce_simple_or_long_primary()` or `to_ce_self_contained()`
413 /// returns non-`None`.
414 ///
415 /// # Panics
416 ///
417 /// Panics in debug mode if called on a non-special element.
418 #[inline(always)]
419 pub(crate) fn tag(self) -> Tag {
420 debug_assert!(self.low_byte() >= SPECIAL_CE32_LOW_BYTE);
421 // Safety: Tag has values 0 to 15, which are filtered for with the 0xF mask.
422 unsafe { core::mem::transmute::<u8, Tag>(self.low_byte() & 0xF) }
423 }
424
425 /// Expands to 64 bits if the expansion is to a single 64-bit collation
426 /// element and is not a long-secondary expansion.
427 #[inline(always)]
428 pub fn to_ce_simple_or_long_primary(self) -> Option<CollationElement> {
429 let t = self.low_byte();
430 if t < SPECIAL_CE32_LOW_BYTE {
431 // Not special
432 let as64 = u64::from(self.0);
433 Some(CollationElement::new(
434 ((as64 & 0xFFFF0000) << 32) | ((as64 & 0xFF00) << 16) | (u64::from(t) << 8),
435 ))
436 } else if t == LONG_PRIMARY_CE32_LOW_BYTE {
437 let as64 = u64::from(self.0);
438 Some(CollationElement::new(
439 ((as64 - u64::from(t)) << 32) | COMMON_SEC_AND_TER_CE,
440 ))
441 } else {
442 // Could still be long secondary (or not self-contained at all).
443 // See `to_ce_self_contained()`.
444 None
445 }
446 }
447
448 /// Expands to 64 bits if the expansion is to a single 64-bit collation
449 /// element.
450 #[inline(always)]
451 pub fn to_ce_self_contained(self) -> Option<CollationElement> {
452 if let Some(ce) = self.to_ce_simple_or_long_primary() {
453 return Some(ce);
454 }
455 if self.tag() == Tag::LongSecondary {
456 Some(CollationElement::new(u64::from(self.0 & 0xffffff00)))
457 } else {
458 None
459 }
460 }
461
462 /// Expands to 64 bits if the expansion is to a single 64-bit collation
463 /// element or otherwise returns the collation element for U+FFFD.
464 #[inline(always)]
465 pub fn to_ce_self_contained_or_gigo(self) -> CollationElement {
466 unwrap_or_gigo(self.to_ce_self_contained(), FFFD_CE)
467 }
468
469 /// Gets the length from this element.
470 ///
471 /// # Panics
472 ///
473 /// In debug builds if this element doesn't have a length.
474 #[inline(always)]
475 pub fn len(self) -> usize {
476 debug_assert!(self.tag() == Tag::Expansion32 || self.tag() == Tag::Expansion);
477 ((self.0 >> 8) & 31) as usize
478 }
479
480 /// Gets the index from this element.
481 ///
482 /// # Panics
483 ///
484 /// In debug builds if this element doesn't have an index.
485 #[inline(always)]
486 pub fn index(self) -> usize {
487 debug_assert!(
488 self.tag() == Tag::Expansion32
489 || self.tag() == Tag::Expansion
490 || self.tag() == Tag::Contraction
491 || self.tag() == Tag::Digit
492 || self.tag() == Tag::Prefix
493 || self.tag() == Tag::Offset
494 );
495 (self.0 >> 13) as usize
496 }
497
498 #[inline(always)]
499 pub fn digit(self) -> u8 {
500 debug_assert!(self.tag() == Tag::Digit);
501 ((self.0 >> 8) & 0xF) as u8
502 }
503
504 #[inline(always)]
505 pub fn every_suffix_starts_with_combining(self) -> bool {
506 debug_assert!(self.tag() == Tag::Contraction);
507 (self.0 & CONTRACT_NEXT_CCC) != 0
508 }
509 #[inline(always)]
510 pub fn at_least_one_suffix_contains_starter(self) -> bool {
511 debug_assert!(self.tag() == Tag::Contraction);
512 (self.0 & CONTRACT_HAS_STARTER) != 0
513 }
514 #[inline(always)]
515 pub fn at_least_one_suffix_ends_with_non_starter(self) -> bool {
516 debug_assert!(self.tag() == Tag::Contraction);
517 (self.0 & CONTRACT_TRAILING_CCC) != 0
518 }
519 }
520
521 impl Default for CollationElement32 {
522 fn default() -> Self {
523 CollationElement32(1) // NO_CE32
524 }
525 }
526
527 /// A collation element is a 64-bit value.
528 ///
529 /// Bits 63..32 are the primary weight.
530 /// Bits 31..16 are the secondary weight.
531 /// Bits 15..14 are the case bits.
532 /// Bits 13..8 and 5..0 are the (bitwise discontiguous) tertiary weight.
533 /// Bits 7..6 the quaternary weight.
534 #[derive(Copy, Clone, Debug, PartialEq)]
535 pub(crate) struct CollationElement(u64);
536
537 impl CollationElement {
538 #[inline(always)]
539 pub fn new(bits: u64) -> Self {
540 CollationElement(bits)
541 }
542
543 #[inline(always)]
544 pub fn new_from_primary(primary: u32) -> Self {
545 CollationElement((u64::from(primary) << 32) | COMMON_SEC_AND_TER_CE)
546 }
547
548 #[inline(always)]
549 pub fn new_from_secondary(secondary: u16) -> Self {
550 CollationElement((u64::from(secondary) << 16) | COMMON_TERTIARY_CE)
551 }
552
553 #[inline(always)]
554 pub fn new_implicit_from_char(c: char) -> Self {
555 // Collation::unassignedPrimaryFromCodePoint
556 // Create a gap before U+0000. Use c-1 for [first unassigned].
557 let mut c_with_offset = u32::from(c) + 1;
558 // Fourth byte: 18 values, every 14th byte value (gap of 13).
559 let mut primary: u32 = 2 + (c_with_offset % 18) * 14;
560 c_with_offset /= 18;
561 // Third byte: 254 values
562 primary |= (2 + (c_with_offset % 254)) << 8;
563 c_with_offset /= 254;
564 // Second byte: 251 values 04..FE excluding the primary compression bytes.
565 primary |= (4 + (c_with_offset % 251)) << 16;
566 // One lead byte covers all code points (c < 0x1182B4 = 1*251*254*18).
567 primary |= u32::from(UNASSIGNED_IMPLICIT_BYTE) << 24;
568 CollationElement::new_from_primary(primary)
569 }
570
571 #[inline(always)]
572 pub fn clone_with_non_primary_zeroed(self) -> Self {
573 CollationElement(self.0 & 0xFFFFFFFF00000000)
574 }
575
576 /// Get the primary weight
577 #[inline(always)]
578 pub fn primary(self) -> u32 {
579 (self.0 >> 32) as u32
580 }
581
582 /// Get the non-primary weights
583 #[inline(always)]
584 pub fn non_primary(self) -> NonPrimary {
585 NonPrimary::new(self.0 as u32)
586 }
587
588 /// Get the secondary weight
589 #[inline(always)]
590 pub fn secondary(self) -> u16 {
591 self.non_primary().secondary()
592 }
593 #[inline(always)]
594 pub fn quaternary(self) -> u32 {
595 self.non_primary().quaternary()
596 }
597 #[inline(always)]
598 pub fn tertiary_ignorable(self) -> bool {
599 self.non_primary().tertiary_ignorable()
600 }
601 #[inline(always)]
602 pub fn either_half_zero(self) -> bool {
603 self.primary() == 0 || (self.0 as u32) == 0
604 }
605
606 #[inline(always)]
607 pub const fn default() -> CollationElement {
608 CollationElement(NO_CE_VALUE) // NO_CE
609 }
610 }
611
612 impl Default for CollationElement {
613 #[inline(always)]
614 fn default() -> Self {
615 CollationElement(NO_CE_VALUE) // NO_CE
616 }
617 }
618
619 impl Default for &CollationElement {
620 #[inline(always)]
621 fn default() -> Self {
622 &CollationElement(NO_CE_VALUE) // NO_CE
623 }
624 }
625
626 /// The purpose of grouping the non-primary bits
627 /// into a struct is to allow for a future optimization
628 /// that specializes code over whether storage for primary
629 /// weights is needed or not. (I.e. whether to specialize
630 /// on `CollationElement` or `NonPrimary`.)
631 #[derive(Copy, Clone, PartialEq, Debug)]
632 pub(crate) struct NonPrimary(u32);
633
634 impl NonPrimary {
635 /// Constructor
636 pub fn new(bits: u32) -> Self {
637 NonPrimary(bits)
638 }
639 /// Get the bits
640 pub fn bits(self) -> u32 {
641 self.0
642 }
643 /// Get the secondary weight
644 #[inline(always)]
645 pub fn secondary(self) -> u16 {
646 (self.0 >> 16) as u16
647 }
648 /// Get the case bits as the high two bits of a u16
649 #[inline(always)]
650 pub fn case(self) -> u16 {
651 (self.0 as u16) & CASE_MASK
652 }
653 /// Get the tertiary weight as u16 with the high
654 /// two bits of each half zeroed.
655 #[inline(always)]
656 pub fn tertiary(self) -> u16 {
657 (self.0 as u16) & TERTIARY_MASK
658 }
659 #[inline(always)]
660 pub fn tertiary_ignorable(self) -> bool {
661 (self.0 as u16) <= NO_CE_TERTIARY
662 }
663 /// Get the quaternary weight in the original
664 /// storage bit positions with the other bits
665 /// set to one.
666 #[inline(always)]
667 pub fn quaternary(self) -> u32 {
668 self.0 | !(QUATERNARY_MASK as u32)
669 }
670 /// Get any combination of tertiary, case, and quaternary
671 /// by mask.
672 #[inline(always)]
673 pub fn tertiary_case_quarternary(self, mask: u16) -> u16 {
674 debug_assert!((mask & CASE_MASK) == CASE_MASK || (mask & CASE_MASK) == 0);
675 debug_assert!((mask & TERTIARY_MASK) == TERTIARY_MASK || (mask & TERTIARY_MASK) == 0);
676 debug_assert!((mask & QUATERNARY_MASK) == QUATERNARY_MASK || (mask & QUATERNARY_MASK) == 0);
677 (self.0 as u16) & mask
678 }
679
680 #[inline(always)]
681 pub fn case_quaternary(self) -> u16 {
682 (self.0 as u16) & (CASE_MASK | QUATERNARY_MASK)
683 }
684
685 #[inline(always)]
686 pub fn ignorable(self) -> bool {
687 self.0 == 0
688 }
689 }
690
691 impl Default for NonPrimary {
692 #[inline(always)]
693 fn default() -> Self {
694 NonPrimary(0x01000100) // Low 32 bits of NO_CE
695 }
696 }
697
698 /// This struct makes the handling of the `upcoming` buffer
699 /// easily so that trie lookups are done at most once. However,
700 /// when `upcoming[0]` is an undecomposed starter, we don't
701 /// need the ccc yet, and when lookahead has already done the
702 /// trie lookups, we don't need `trie_value`, as it is implied
703 /// by ccc.
704 //
705 // TODO(#2386): This struct carries redundant information, and
706 // `upcoming` should be split into a buffer of `CharacterAndClass`
707 // and an `Option<CharacterAndTrieValue>`, but that refactoring
708 // isn't 100% necessary, so focusing on data format stability
709 // for 1.0.
710 //
711 // (Deliberately non-`Copy`, because `CharacterAndClass` is
712 // non-`Copy`.)
713 #[derive(Debug, Clone)]
714 pub(crate) struct CharacterAndClassAndTrieValue {
715 c_and_c: CharacterAndClass,
716 pub trie_val: u32,
717 }
718
719 impl CharacterAndClassAndTrieValue {
720 pub fn new_with_non_decomposing_starter(c: char) -> Self {
721 CharacterAndClassAndTrieValue {
722 c_and_c: CharacterAndClass::new(c, CanonicalCombiningClass::NotReordered),
723 trie_val: 0,
724 }
725 }
726 pub fn new_with_non_zero_ccc(c: char, ccc: CanonicalCombiningClass) -> Self {
727 CharacterAndClassAndTrieValue {
728 c_and_c: CharacterAndClass::new(c, ccc),
729 trie_val: 0xD800 | u32::from(ccc.0),
730 }
731 }
732 pub fn new_with_non_special_decomposition_trie_val(c: char, trie_val: u32) -> Self {
733 debug_assert!(!trie_value_indicates_special_non_starter_decomposition(
734 trie_val
735 ));
736 CharacterAndClassAndTrieValue {
737 c_and_c: CharacterAndClass::new_with_trie_value(c, trie_val),
738 trie_val,
739 }
740 }
741 pub fn new_with_trie_val(c: char, trie_val: u32) -> Self {
742 if !trie_value_indicates_special_non_starter_decomposition(trie_val) {
743 CharacterAndClassAndTrieValue {
744 c_and_c: CharacterAndClass::new_with_trie_value(c, trie_val),
745 trie_val,
746 }
747 } else {
748 CharacterAndClassAndTrieValue {
749 c_and_c: CharacterAndClass::new(c, CanonicalCombiningClass(0xFF)),
750 trie_val,
751 }
752 }
753 }
754
755 pub fn decomposition_starts_with_non_starter(&self) -> bool {
756 decomposition_starts_with_non_starter(self.trie_val)
757 }
758
759 pub fn character(&self) -> char {
760 self.c_and_c.character()
761 }
762
763 fn ccc(&self) -> CanonicalCombiningClass {
764 let ret = self.c_and_c.ccc();
765 debug_assert_ne!(ret, CanonicalCombiningClass(0xFF));
766 ret
767 }
768 }
769
770 /// Pack a `char` and a `CanonicalCombiningClass` in
771 /// 32 bits (the former in the lower 24 bits and the
772 /// latter in the high 8 bits). The latter can be
773 /// initialized to 0xFF upon creation, in which case
774 /// it can be actually set later by calling
775 /// `set_ccc_from_trie_if_not_already_set`. This is
776 /// a micro optimization to avoid the Canonical
777 /// Combining Class trie lookup when there is only
778 /// one combining character in a sequence. This type
779 /// is intentionally non-`Copy` to get compiler help
780 /// in making sure that the class is set on the
781 /// instance on which it is intended to be set
782 /// and not on a temporary copy.
783 ///
784 /// Note that 0xFF is won't be assigned to an actual
785 /// canonical combining class per definition D104
786 /// in The Unicode Standard.
787 //
788 // NOTE: The Pernosco debugger has special knowledge
789 // of this struct. Please do not change the bit layout
790 // or the crate-module-qualified name of this struct
791 // without coordination.
792 #[derive(Debug, Clone)]
793 // Safety invariant: The low 24 bits are a valid char
794 struct CharacterAndClass(u32);
795
796 impl CharacterAndClass {
797 pub fn new(c: char, ccc: CanonicalCombiningClass) -> Self {
798 // Safety invariant upheld here: the first half is a valid char
799 // and the second half does not affect the low 24 bits
800 CharacterAndClass(u32::from(c) | (u32::from(ccc.0) << 24))
801 }
802 pub fn new_with_placeholder(c: char) -> Self {
803 // Safety invariant upheld here: the first half is a valid char
804 // and the second half does not affect the low 24 bits
805 CharacterAndClass(u32::from(c) | ((0xFF) << 24))
806 }
807 pub fn new_with_trie_value(c: char, trie_value: u32) -> Self {
808 Self::new(c, ccc_from_trie_value(trie_value))
809 }
810 pub fn character(&self) -> char {
811 // Safety: from the safety invariant, this extracts the low 24 bits
812 unsafe { char::from_u32_unchecked(self.0 & 0xFF_FFFF) }
813 }
814 pub fn ccc(&self) -> CanonicalCombiningClass {
815 // Safety invariant upheld here: The argument is outside of the low 24 bits,
816 // and \0 is a valid character
817 CanonicalCombiningClass((self.0 >> 24) as u8)
818 }
819 pub fn character_and_ccc(&self) -> (char, CanonicalCombiningClass) {
820 (self.character(), self.ccc())
821 }
822 pub fn set_ccc_from_trie_if_not_already_set(&mut self, trie: &CodePointTrie<u32>) {
823 if self.0 >> 24 != 0xFF {
824 return;
825 }
826 let scalar = self.0 & 0xFF_FFFF;
827 // Safety invariant upheld here: The first half doesn't affect the lower 24 bits,
828 // and the second half was taken from the old `self` which had these invariants upheld already.
829 self.0 = ((ccc_from_trie_value(trie.get32_u32(scalar)).0 as u32) << 24) | scalar;
830 }
831 }
832
833 /// Iterator that transforms an iterator over `char` into an iterator
834 /// over `CollationElement` with a tailoring.
835 /// Not a real Rust iterator: Instead of `None` uses `NO_CE` to indicate
836 /// end of iteration to optimize comparison.
837 ///
838 /// It is _extremely_ important for performance that `SmallVec`s not be
839 /// moved. To facilitate move-avoidance, this struct has the following
840 /// life cycle where `new` returns the struct in a state that is not
841 /// yet valid for a `next` call until `init` is called:
842 ///
843 /// 1. `new`.
844 /// 2. Some number of calls to `iter_next_before_init` and
845 /// `prepend_upcoming_before_init`.
846 /// 3. `init`.
847 /// 4. Some number of calls to `next`.
848 pub(crate) struct CollationElements<'data, I>
849 where
850 I: Iterator<Item = char>,
851 {
852 iter: I,
853 /// Already computed but not yet returned `CollationElement`s.
854 pending: SmallVec<[CollationElement; PENDING_CE_BUFFER_SIZE]>, // TODO(#2005): Figure out good length
855 /// The index of the next item to be returned from `pending`. The purpose
856 /// of this index is to avoid moving the rest of the items.
857 pending_pos: usize,
858 /// The characters most previously seen (or never-matching placeholders)
859 /// CLDR, as of 40, has two kinds of prefixes:
860 /// Prefixes that contain a single starter
861 /// Prefixes that contain a starter followed by either U+3099 or U+309A
862 /// Last-pushed is at index 0 and previously-pushed at index 1
863 prefix: [char; 2],
864 /// `upcoming` holds the characters that have already been read from
865 /// `iter` but haven't yet been mapped to `CollationElement`s.
866 ///
867 /// Typically, `upcoming` holds one character and corresponds semantically
868 /// to `pending_unnormalized_starter` in `icu::normalizer::Decomposition`.
869 /// This is why there isn't a move avoidance optimization similar to
870 /// `pending_pos` above for this buffer. A complex decomposition, a
871 /// Hangul syllable followed by a non-starter, or lookahead can cause
872 /// `pending` to hold more than one `char`.
873 ///
874 /// Invariant: `upcoming` is allowed to become empty only after `iter`
875 /// has been exhausted.
876 ///
877 /// Invariant: (Checked by `debug_assert!`) At the start of `next()` call,
878 /// if `upcoming` isn't empty (with `iter` having been exhausted), the
879 /// first `char` in `upcoming` must have its decomposition start with a
880 /// starter.
881 ///
882 /// TODO: Reverse the order, since now `insert(0, x)` and `remove(0)`
883 /// are used more often than `push()` and `pop()`.
884 upcoming: SmallVec<[CharacterAndClassAndTrieValue; UPCOMING_CHARACTER_BUFFER_SIZE]>,
885 /// The root collation data.
886 root: &'data CollationData<'data>,
887 /// Tailoring if applicable.
888 tailoring: &'data CollationData<'data>,
889 /// The `CollationElement32` mapping for the Hangul Jamo block.
890 ///
891 /// Note: in ICU4C the jamo table contains only modern jamo. Here, the jamo table contains the whole Unicode block.
892 jamo: &'data [<u32 as AsULE>::ULE; JAMO_COUNT],
893 /// The `CollationElement32` mapping for the Combining Diacritical Marks block.
894 diacritics: &'data ZeroSlice<u16>,
895 /// NFD main trie.
896 ///
897 /// See components/normalizer/trie-value-format.md
898 trie: &'data CodePointTrie<'data, u32>,
899 /// NFD complex decompositions on the BMP
900 scalars16: &'data ZeroSlice<u16>,
901 /// NFD complex decompositions on supplementary planes
902 scalars32: &'data ZeroSlice<char>,
903 /// If numeric mode is enabled, the 8 high bits of the numeric primary.
904 /// `None` if disabled.
905 numeric_primary: Option<u8>,
906 /// Whether the Lithuanian combining dot above handling is enabled.
907 lithuanian_dot_above: bool,
908 /// Whether `upcoming` (except the last item) has been normalized already
909 upcoming_normalized: bool,
910 #[cfg(debug_assertions)]
911 /// Whether `iter` has been exhausted
912 iter_exhausted: bool,
913 #[cfg(debug_assertions)]
914 /// Whether `init` has been called
915 initialized: bool,
916 }
917
918 impl<'data, I> CollationElements<'data, I>
919 where
920 I: Iterator<Item = char>,
921 {
922 #[expect(clippy::too_many_arguments)]
923 pub fn new(
924 delegate: I,
925 root: &'data CollationData,
926 tailoring: &'data CollationData,
927 jamo: &'data [<u32 as AsULE>::ULE; JAMO_COUNT],
928 diacritics: &'data ZeroSlice<u16>,
929 decompositions: &'data DecompositionData,
930 tables: &'data DecompositionTables,
931 numeric_primary: Option<u8>,
932 lithuanian_dot_above: bool,
933 ) -> Self {
934 CollationElements::<I> {
935 iter: delegate,
936 pending: SmallVec::new(),
937 pending_pos: 0,
938 prefix: ['\u{FFFF}'; 2],
939 upcoming: SmallVec::new(),
940 root,
941 tailoring,
942 jamo,
943 diacritics,
944 trie: &decompositions.trie,
945 scalars16: &tables.scalars16,
946 scalars32: &tables.scalars24,
947 numeric_primary,
948 lithuanian_dot_above,
949 upcoming_normalized: false,
950 #[cfg(debug_assertions)]
951 iter_exhausted: false,
952 #[cfg(debug_assertions)]
953 initialized: false,
954 }
955 }
956
957 pub fn iter_next_before_init(&mut self) -> Option<CharacterAndClassAndTrieValue> {
958 #[cfg(debug_assertions)]
959 debug_assert!(!self.initialized);
960 self.iter_next()
961 }
962
963 pub fn prepend_upcoming_before_init(&mut self, c: CharacterAndClassAndTrieValue) {
964 #[cfg(debug_assertions)]
965 debug_assert!(!self.initialized);
966 self.upcoming.insert(0, c);
967 }
968
969 pub fn init(&mut self) {
970 #[cfg(debug_assertions)]
971 {
972 debug_assert!(!self.initialized);
973 self.initialized = true;
974 }
975
976 // Ensure the last item is a starter (unless)
977 // iter exhausted.
978 if let Some(last) = self.upcoming.last()
979 && last.decomposition_starts_with_non_starter()
980 {
981 // Not using `while let` to be able to set `iter_exhausted`
982 loop {
983 if let Some(ch) = self.iter_next() {
984 let starter = !ch.decomposition_starts_with_non_starter();
985 self.upcoming.push(ch);
986 if starter {
987 break;
988 }
989 } else {
990 #[cfg(debug_assertions)]
991 {
992 self.iter_exhausted = true;
993 }
994 break;
995 }
996 }
997 }
998
999 let mut starts_with_starter = false;
1000 if let Some(first) = self.upcoming.first()
1001 && !first.decomposition_starts_with_non_starter()
1002 {
1003 starts_with_starter = true;
1004 }
1005 if !starts_with_starter {
1006 self.upcoming.insert(
1007 0,
1008 CharacterAndClassAndTrieValue::new_with_non_decomposing_starter('\u{FFFF}'),
1009 ); // Make sure the process always begins with a starter
1010 let _ = self.next(); // Remove the placeholder starter
1011 }
1012 }
1013
1014 fn iter_next(&mut self) -> Option<CharacterAndClassAndTrieValue> {
1015 let c = self.iter.next()?;
1016 let trie_val = self.trie.get(c);
1017 Some(CharacterAndClassAndTrieValue::new_with_trie_val(
1018 c, trie_val,
1019 ))
1020 }
1021
1022 fn next_internal(&mut self) -> Option<CharacterAndClassAndTrieValue> {
1023 if self.upcoming.is_empty() {
1024 return None;
1025 }
1026 let ret = self.upcoming.remove(0);
1027 if self.upcoming.is_empty() {
1028 if let Some(c) = self.iter_next() {
1029 self.upcoming.push(c);
1030 } else {
1031 #[cfg(debug_assertions)]
1032 {
1033 self.iter_exhausted = true;
1034 }
1035 }
1036 }
1037 Some(ret)
1038 }
1039
1040 fn maybe_gather_combining(&mut self) {
1041 if self.upcoming.len() != 1 {
1042 return;
1043 }
1044 // index has to be in range due to the check above.
1045 // rewriting with `get()` would result in two checks.
1046 #[expect(clippy::indexing_slicing)]
1047 if !self.upcoming[0].decomposition_starts_with_non_starter() {
1048 return;
1049 }
1050 // We now have a single character that decomposes to start with
1051 // a non-starter. Decompose it and assign the real canonical combining class.
1052 let first = self.upcoming.remove(0);
1053 self.push_decomposed_combining(first);
1054 // Not using `while let` to be able to set `iter_exhausted`
1055 loop {
1056 if let Some(ch) = self.iter_next() {
1057 if ch.decomposition_starts_with_non_starter() {
1058 self.push_decomposed_combining(ch);
1059 } else {
1060 // Got a new starter
1061 self.upcoming.push(ch);
1062 break;
1063 }
1064 } else {
1065 #[cfg(debug_assertions)]
1066 {
1067 self.iter_exhausted = true;
1068 }
1069 break;
1070 }
1071 }
1072 }
1073
1074 /// Ensures that `upcoming` is normalized to NFD, except:
1075 /// 1. When the last item is a starter, it isn't necessarily normalized.
1076 /// 2. Hangul syllable are unnormalized.
1077 fn ensure_upcoming_normalized(&mut self) {
1078 if self.upcoming_normalized {
1079 return;
1080 }
1081 self.upcoming_normalized = true;
1082 let without_trailing_starter = if let Some((last, head)) = self.upcoming.split_last() {
1083 if !last.decomposition_starts_with_non_starter() {
1084 if head.is_empty() {
1085 // There is a single starter, which isn't required
1086 // to be normalized.
1087 return;
1088 } else {
1089 head
1090 }
1091 } else {
1092 &self.upcoming[..]
1093 }
1094 } else {
1095 // Make the assertion conditional to make CI happy.
1096 #[cfg(debug_assertions)]
1097 debug_assert!(self.iter_exhausted);
1098 return;
1099 };
1100
1101 // It would be better to attempt to normalize in place, but let's do at
1102 // least this.
1103 if without_trailing_starter.iter().all(|c| {
1104 (c.trie_val
1105 & !(BACKWARD_COMBINING_MARKER | NON_ROUND_TRIP_MARKER | HANGUL_SYLLABLE_MARKER))
1106 == 0
1107 }) {
1108 return;
1109 }
1110
1111 let mut unnormalized = core::mem::take(&mut self.upcoming);
1112 let last_index = unnormalized.len() - 1;
1113 // Indexing is for debug assert only.
1114 #[expect(clippy::indexing_slicing)]
1115 {
1116 debug_assert!(!unnormalized[0].decomposition_starts_with_non_starter());
1117 }
1118 let mut start_combining = 0;
1119 for (i, c) in unnormalized.drain(..).enumerate() {
1120 if c.decomposition_starts_with_non_starter() {
1121 self.push_decomposed_combining(c);
1122 } else if i == last_index {
1123 // Indices are in range by construction, so indexing is OK.
1124 #[expect(clippy::indexing_slicing)]
1125 self.upcoming[start_combining..].sort_by_key(|c| c.ccc());
1126 self.upcoming.push(c);
1127 return;
1128 } else {
1129 // Indices are in range by construction, so indexing is OK.
1130 #[expect(clippy::indexing_slicing)]
1131 self.upcoming[start_combining..].sort_by_key(|c| c.ccc());
1132 start_combining = self.push_decomposed_starter(c);
1133 }
1134 }
1135 // Make the assertion conditional to make CI happy.
1136 #[cfg(debug_assertions)]
1137 debug_assert!(self.iter_exhausted);
1138 // Indices are in range by construction, so indexing is OK.
1139 #[expect(clippy::indexing_slicing)]
1140 self.upcoming[start_combining..].sort_by_key(|c| c.ccc());
1141 }
1142
1143 fn push_decomposed_combining(&mut self, c: CharacterAndClassAndTrieValue) {
1144 if !trie_value_indicates_special_non_starter_decomposition(c.trie_val) {
1145 debug_assert!(trie_value_has_ccc(c.trie_val));
1146 self.upcoming.push(c);
1147 return;
1148 }
1149
1150 // The Tibetan special cases are starters that decompose into non-starters.
1151 match c.character() {
1152 '\u{0340}' => {
1153 // COMBINING GRAVE TONE MARK
1154 self.upcoming
1155 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1156 '\u{0300}',
1157 CanonicalCombiningClass::Above,
1158 ));
1159 }
1160 '\u{0341}' => {
1161 // COMBINING ACUTE TONE MARK
1162 self.upcoming
1163 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1164 '\u{0301}',
1165 CanonicalCombiningClass::Above,
1166 ));
1167 }
1168 '\u{0343}' => {
1169 // COMBINING GREEK KORONIS
1170 self.upcoming
1171 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1172 '\u{0313}',
1173 CanonicalCombiningClass::Above,
1174 ));
1175 }
1176 '\u{0344}' => {
1177 // COMBINING GREEK DIALYTIKA TONOS
1178 self.upcoming
1179 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1180 '\u{0308}',
1181 CanonicalCombiningClass::Above,
1182 ));
1183 self.upcoming
1184 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1185 '\u{0301}',
1186 CanonicalCombiningClass::Above,
1187 ));
1188 }
1189 '\u{0F73}' => {
1190 // TIBETAN VOWEL SIGN II
1191 self.upcoming
1192 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1193 '\u{0F71}',
1194 CanonicalCombiningClass::CCC129,
1195 ));
1196 self.upcoming
1197 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1198 '\u{0F72}',
1199 CanonicalCombiningClass::CCC130,
1200 ));
1201 }
1202 '\u{0F75}' => {
1203 // TIBETAN VOWEL SIGN UU
1204 self.upcoming
1205 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1206 '\u{0F71}',
1207 CanonicalCombiningClass::CCC129,
1208 ));
1209 self.upcoming
1210 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1211 '\u{0F74}',
1212 CanonicalCombiningClass::CCC132,
1213 ));
1214 }
1215 '\u{0F81}' => {
1216 // TIBETAN VOWEL SIGN REVERSED II
1217 self.upcoming
1218 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1219 '\u{0F71}',
1220 CanonicalCombiningClass::CCC129,
1221 ));
1222 self.upcoming
1223 .push(CharacterAndClassAndTrieValue::new_with_non_zero_ccc(
1224 '\u{0F80}',
1225 CanonicalCombiningClass::CCC130,
1226 ));
1227 }
1228 _ => {
1229 // GIGO case
1230 debug_assert!(false);
1231 }
1232 }
1233 }
1234
1235 fn push_decomposed_starter(&mut self, c: CharacterAndClassAndTrieValue) -> usize {
1236 let mut search_start_combining = false;
1237 let old_len = self.upcoming.len();
1238 // Not inserting early returns below to keep the same structure
1239 // as in the ce32 mapping code.
1240
1241 // Hangul syllable check omitted, because it's fine not to decompose
1242 // Hangul syllables in lookahead, because Hangul isn't allowed to
1243 // participate in contractions, and the trie default is that a character
1244 // is its own decomposition.
1245
1246 // See components/normalizer/trie-value-format.md
1247 let decomposition = c.trie_val;
1248 if (decomposition & !(BACKWARD_COMBINING_MARKER | NON_ROUND_TRIP_MARKER))
1249 <= HANGUL_SYLLABLE_MARKER
1250 {
1251 // The character is its own decomposition (or Hangul syllable)
1252 // Set the Canonical Combining Class to zero
1253 self.upcoming.push(
1254 CharacterAndClassAndTrieValue::new_with_non_decomposing_starter(c.character()),
1255 );
1256 } else {
1257 let high_zeros = (decomposition & HIGH_ZEROS_MASK) == 0;
1258 let low_zeros = (decomposition & LOW_ZEROS_MASK) == 0;
1259 if !high_zeros && !low_zeros {
1260 // Decomposition into two BMP characters: starter and non-starter
1261 let starter = char_from_u32(decomposition & 0x7FFF);
1262 let low_c = char_from_u32((decomposition >> 15) & 0x7FFF);
1263 self.upcoming
1264 .push(CharacterAndClassAndTrieValue::new_with_non_decomposing_starter(starter));
1265 let trie_value = self.trie.get(low_c);
1266 self.upcoming.push(
1267 CharacterAndClassAndTrieValue::new_with_non_special_decomposition_trie_val(
1268 low_c, trie_value,
1269 ),
1270 );
1271 } else if high_zeros {
1272 let singleton = decomposition as u16;
1273 debug_assert_ne!(
1274 singleton, FDFA_MARKER,
1275 "How come U+FDFA NFKD marker seen in NFD?"
1276 );
1277 if (singleton & 0xFF00) == 0xD800 {
1278 // We're at the end of the stream, so we aren't dealing with the
1279 // next undecomposed starter but are dealing with an
1280 // already-decomposed non-starter. Just put it back.
1281 self.upcoming.push(c);
1282 // Make the assertion conditional to make CI happy.
1283 #[cfg(debug_assertions)]
1284 debug_assert!(self.iter_exhausted);
1285 } else {
1286 // Decomposition into one BMP character
1287 self.upcoming.push(
1288 CharacterAndClassAndTrieValue::new_with_non_decomposing_starter(
1289 char_from_u16(singleton),
1290 ),
1291 );
1292 }
1293 } else {
1294 debug_assert!(low_zeros);
1295 // Only 12 of 14 bits used as of Unicode 16.
1296 let offset = (((decomposition & !(0b11 << 30)) >> 16) as usize) - 1;
1297 // Only 3 of 4 bits used as of Unicode 16.
1298 let len_bits = decomposition & 0b1111;
1299 let only_non_starters_in_trail = (decomposition & 0b10000) != 0;
1300 if offset < self.scalars16.len() {
1301 let len = (len_bits + 2) as usize;
1302 for u in unwrap_or_gigo(
1303 self.scalars16.get_subslice(offset..offset + len),
1304 SINGLE_REPLACEMENT_CHARACTER_U16, // single instead of empty for consistency with the other code path
1305 )
1306 .iter()
1307 {
1308 let ch = char_from_u16(u);
1309 let trie_value = self.trie.get(ch);
1310 self.upcoming
1311 .push(CharacterAndClassAndTrieValue::new_with_non_special_decomposition_trie_val(ch, trie_value));
1312 }
1313 } else {
1314 let len = (len_bits + 1) as usize;
1315 let offset32 = offset - self.scalars16.len();
1316 for ch in unwrap_or_gigo(
1317 self.scalars32.get_subslice(offset32..offset32 + len),
1318 SINGLE_REPLACEMENT_CHARACTER_CHAR, // single instead of empty for consistency with the other code path
1319 )
1320 .iter()
1321 {
1322 let trie_value = self.trie.get(ch);
1323 self.upcoming
1324 .push(CharacterAndClassAndTrieValue::new_with_non_special_decomposition_trie_val(ch, trie_value));
1325 }
1326 }
1327 search_start_combining = !only_non_starters_in_trail;
1328 }
1329 }
1330 if search_start_combining {
1331 // The decomposition contains starters. As of Unicode 14,
1332 // There are two possible patterns:
1333 // BMP: starter, starter, non-starter
1334 // Plane 1: starter, starter.
1335 // However, for forward compatibility, support any combination
1336 // and search for the last starter.
1337 let mut i = self.upcoming.len() - 1;
1338 loop {
1339 if let Some(ch) = self.upcoming.get(i) {
1340 if ch.decomposition_starts_with_non_starter() {
1341 i -= 1;
1342 continue;
1343 }
1344 break;
1345 }
1346 // GIGO case
1347 debug_assert!(false);
1348 // This will wrap to zero below
1349 i = usize::MAX;
1350 break;
1351 }
1352 i + 1
1353 } else {
1354 old_len + 1
1355 }
1356 }
1357
1358 // Decomposes `c`, pushes it to `self.upcoming` (unless the character is
1359 // a Hangul syllable; Hangul isn't allowed to participate in contractions),
1360 // gathers the following combining characters from `self.iter` and the following starter.
1361 // Sorts the combining characters and leaves the starter at the end
1362 // unnormalized. The trailing unnormalized starter doesn't get appended if
1363 // `self.iter` is exhausted.
1364 fn push_decomposed_and_gather_combining(&mut self, c: CharacterAndClassAndTrieValue) {
1365 let start_combining = self.push_decomposed_starter(c);
1366 // Not using `while let` to be able to set `iter_exhausted`
1367 loop {
1368 if let Some(ch) = self.iter_next() {
1369 if ch.decomposition_starts_with_non_starter() {
1370 self.push_decomposed_combining(ch);
1371 } else {
1372 // Got a new starter
1373 // Indices are in range by construction, so indexing is OK.
1374 #[expect(clippy::indexing_slicing)]
1375 self.upcoming[start_combining..].sort_by_key(|c| c.ccc());
1376 self.upcoming.push(ch);
1377 return;
1378 }
1379 } else {
1380 #[cfg(debug_assertions)]
1381 {
1382 self.iter_exhausted = true;
1383 }
1384 // Indices are in range by construction, so indexing is OK.
1385 #[expect(clippy::indexing_slicing)]
1386 self.upcoming[start_combining..].sort_by_key(|c| c.ccc());
1387 return;
1388 }
1389 }
1390 }
1391
1392 // Assumption: `pos` starts from zero and increases one by one.
1393 // Indexing is OK, because we check against `len()` and the `pos`
1394 // increases one by one by construction.
1395 #[expect(clippy::indexing_slicing)]
1396 fn look_ahead(&mut self, pos: usize) -> Option<CharacterAndClassAndTrieValue> {
1397 debug_assert!(self.upcoming_normalized);
1398 if pos + 1 == self.upcoming.len() {
1399 let c = self.upcoming.remove(pos);
1400 self.push_decomposed_and_gather_combining(c);
1401 Some(self.upcoming[pos].clone())
1402 } else if pos == self.upcoming.len() {
1403 if let Some(c) = self.iter_next() {
1404 debug_assert!(
1405 false,
1406 "The `upcoming` queue should be empty when iteration `pos` at the end"
1407 );
1408 self.push_decomposed_and_gather_combining(c);
1409 Some(self.upcoming[pos].clone())
1410 } else {
1411 #[cfg(debug_assertions)]
1412 {
1413 self.iter_exhausted = true;
1414 }
1415 None
1416 }
1417 } else {
1418 Some(self.upcoming[pos].clone())
1419 }
1420 }
1421
1422 fn is_next_decomposition_starts_with_starter(&self) -> bool {
1423 if let Some(c_c_tv) = self.upcoming.first() {
1424 !c_c_tv.decomposition_starts_with_non_starter()
1425 } else {
1426 true
1427 }
1428 }
1429
1430 fn prepend_and_sort_non_starter_prefix_of_suffix(&mut self, c: CharacterAndClassAndTrieValue) {
1431 // Add one for the insertion afterwards.
1432 let end = 1 + {
1433 let mut iter = self.upcoming.iter().enumerate();
1434 loop {
1435 if let Some((i, ch)) = iter.next() {
1436 if !ch.decomposition_starts_with_non_starter() {
1437 break i;
1438 }
1439 } else {
1440 #[cfg(debug_assertions)]
1441 {
1442 self.iter_exhausted = true;
1443 }
1444 break self.upcoming.len();
1445 }
1446 }
1447 };
1448 let start = c.decomposition_starts_with_non_starter() as usize;
1449 self.upcoming.insert(0, c);
1450 // Indices in range by construction
1451 #[expect(clippy::indexing_slicing)]
1452 {
1453 let slice: &mut [CharacterAndClassAndTrieValue] = &mut self.upcoming[start..end];
1454 slice.sort_by_key(|cc| cc.ccc());
1455 };
1456 }
1457
1458 fn prefix_push(&mut self, c: char) {
1459 self.prefix[1] = self.prefix[0];
1460 self.prefix[0] = c;
1461 }
1462
1463 /// Micro optimization for doing a simpler write when
1464 /// we know the most recent character was a non-starter
1465 /// that is not a kana voicing mark.
1466 fn mark_prefix_unmatchable(&mut self) {
1467 self.prefix[0] = '\u{FFFF}';
1468 }
1469
1470 pub fn next(&mut self) -> CollationElement {
1471 #[cfg(debug_assertions)]
1472 debug_assert!(self.initialized);
1473 debug_assert!(self.is_next_decomposition_starts_with_starter());
1474 if let Some(&ret) = self.pending.get(self.pending_pos) {
1475 self.pending_pos += 1;
1476 if self.pending_pos == self.pending.len() {
1477 self.pending.clear();
1478 self.pending_pos = 0;
1479 }
1480 return ret;
1481 }
1482 debug_assert_eq!(self.pending_pos, 0);
1483 if let Some(c_c_tv) = self.next_internal() {
1484 let mut c = c_c_tv.character();
1485 let mut ce32;
1486 let mut data: &CollationData = self.tailoring;
1487 let mut combining_characters: SmallVec<
1488 [CharacterAndClass; COMBINING_CHARACTER_BUFFER_SIZE],
1489 > = SmallVec::new(); // TODO(#2005): Figure out good length
1490
1491 // Betting that fusing the NFD algorithm into this one at the
1492 // expense of the repetitiveness below, the common cases become
1493 // fast in a way that offsets the lack of the canonical closure.
1494 // The wall of code before the "Slow path" is an attempt to
1495 // optimize based on that bet.
1496 let hangul_offset = u32::from(c).wrapping_sub(HANGUL_S_BASE); // SIndex in the spec
1497 if hangul_offset >= HANGUL_S_COUNT {
1498 // See components/normalizer/trie-value-format.md
1499 let decomposition = c_c_tv.trie_val;
1500 if (decomposition & !(BACKWARD_COMBINING_MARKER | NON_ROUND_TRIP_MARKER)) == 0 {
1501 // The character is its own decomposition
1502 let jamo_index = (c as usize).wrapping_sub(HANGUL_L_BASE as usize);
1503 if let Some(&jamo) = self.jamo.get(jamo_index) {
1504 // The purpose of reading the CE32 from the jamo table instead
1505 // of the trie even in this case is to make it unnecessary
1506 // for all search collation tries to carry a copy of the Hangul
1507 // part of the search root. Instead, all non-Korean tailorings
1508 // can use a shared copy of the non-Korean search jamo table.
1509 //
1510 // TODO(#1941): This isn't actually true with the current jamo
1511 // search expansions!
1512
1513 // TODO(#1941): Instead of having different jamo CE32 table for
1514 // "search" collations, we could instead decompose the archaic
1515 // jamo to the modern approximation sequences here and then map
1516 // those by looking up the modern jamo from the normal root.
1517
1518 // We need to set data to root, because archaic jamo refer to
1519 // the root.
1520 data = self.root;
1521 // Index in range by construction above. Not using `get` with
1522 // `if let` in order to put the likely branch first.
1523 ce32 = CollationElement32::new_from_ule(jamo);
1524 } else {
1525 ce32 = data.ce32_for_char(c);
1526 if ce32 == FALLBACK_CE32 {
1527 data = self.root;
1528 ce32 = data.ce32_for_char(c);
1529 }
1530 }
1531 if self.is_next_decomposition_starts_with_starter() {
1532 if let Some(ce) = ce32.to_ce_simple_or_long_primary() {
1533 self.prefix_push(c);
1534 return ce;
1535 } else if ce32.tag() == Tag::Contraction
1536 && ce32.every_suffix_starts_with_combining()
1537 {
1538 // Avoid falling onto the slow path e.g. that letters that
1539 // may contract with a diacritic when we know that it won't
1540 // contract with the next character.
1541 let default = data.get_default(ce32.index());
1542 if let Some(ce) = default.to_ce_simple_or_long_primary() {
1543 self.prefix_push(c);
1544 return ce;
1545 }
1546 }
1547 // TODO(2003): Figure out if it would be an optimization to
1548 // handle `Implicit` and `Offset` tags here.
1549 }
1550 } else {
1551 let high_zeros = (decomposition & HIGH_ZEROS_MASK) == 0;
1552 let low_zeros = (decomposition & LOW_ZEROS_MASK) == 0;
1553 if !high_zeros && !low_zeros {
1554 // Decomposition into two BMP characters: starter and non-starter
1555 c = char_from_u32(decomposition & 0x7FFF);
1556 ce32 = data.ce32_for_char(c);
1557 if ce32 == FALLBACK_CE32 {
1558 data = self.root;
1559 ce32 = data.ce32_for_char(c);
1560 }
1561 let combining = char_from_u32((decomposition >> 15) & 0x7FFF);
1562 if self.is_next_decomposition_starts_with_starter() {
1563 let diacritic_index =
1564 (combining as usize).wrapping_sub(COMBINING_DIACRITICS_BASE);
1565 if let Some(secondary) = self.diacritics.get(diacritic_index) {
1566 debug_assert_ne!(
1567 combining, '\u{0344}',
1568 "Should never have COMBINING GREEK DIALYTIKA TONOS here, since it should have decomposed further."
1569 );
1570 if let Some(ce) = ce32.to_ce_simple_or_long_primary() {
1571 let ce_for_combining =
1572 CollationElement::new_from_secondary(secondary);
1573 self.pending.push(ce_for_combining);
1574 self.mark_prefix_unmatchable();
1575 return ce;
1576 }
1577 if ce32.tag() == Tag::Contraction
1578 && ce32.every_suffix_starts_with_combining()
1579 {
1580 let (default, mut trie) =
1581 data.get_default_and_trie(ce32.index());
1582 match trie.next(combining) {
1583 TrieResult::NoMatch | TrieResult::NoValue => {
1584 if let Some(ce) = default.to_ce_simple_or_long_primary()
1585 {
1586 let ce_for_combining =
1587 CollationElement::new_from_secondary(secondary);
1588 self.pending.push(ce_for_combining);
1589 self.mark_prefix_unmatchable();
1590 return ce;
1591 }
1592 }
1593 TrieResult::Intermediate(trie_ce32) => {
1594 if !ce32.at_least_one_suffix_contains_starter()
1595 && let Some(ce) =
1596 CollationElement32::new(trie_ce32 as u32)
1597 .to_ce_simple_or_long_primary()
1598 {
1599 self.mark_prefix_unmatchable();
1600 return ce;
1601 }
1602 }
1603 TrieResult::FinalValue(trie_ce32) => {
1604 if let Some(ce) =
1605 CollationElement32::new(trie_ce32 as u32)
1606 .to_ce_simple_or_long_primary()
1607 {
1608 self.mark_prefix_unmatchable();
1609 return ce;
1610 }
1611 }
1612 }
1613 }
1614 }
1615 }
1616 combining_characters
1617 .push(CharacterAndClass::new_with_placeholder(combining));
1618 } else if high_zeros {
1619 let singleton = decomposition as u16;
1620 debug_assert_ne!(
1621 singleton, FDFA_MARKER,
1622 "How come U+FDFA NFKD marker seen in NFD?"
1623 );
1624 // Decomposition into one BMP character
1625 c = char_from_u16(singleton);
1626 ce32 = data.ce32_for_char(c);
1627 if ce32 == FALLBACK_CE32 {
1628 data = self.root;
1629 ce32 = data.ce32_for_char(c);
1630 }
1631 if self.is_next_decomposition_starts_with_starter()
1632 && let Some(ce) = ce32.to_ce_simple_or_long_primary()
1633 {
1634 self.prefix_push(c);
1635 return ce;
1636 }
1637 } else {
1638 debug_assert!(low_zeros);
1639 // Only 12 of 14 bits used as of Unicode 16.
1640 let offset = (((decomposition & !(0b11 << 30)) >> 16) as usize) - 1;
1641 // Only 3 of 4 bits used as of Unicode 16.
1642 let len_bits = decomposition & 0b1111;
1643 let only_non_starters_in_trail = (decomposition & 0b10000) != 0;
1644 if offset < self.scalars16.len() {
1645 let len = (len_bits + 2) as usize;
1646 let (starter, tail) = self
1647 .scalars16
1648 .get_subslice(offset..offset + len)
1649 .and_then(ZeroSlice::split_first)
1650 .map_or_else(
1651 || {
1652 // GIGO case
1653 debug_assert!(false);
1654 (char::REPLACEMENT_CHARACTER, EMPTY_U16)
1655 },
1656 |(first, tail)| (char_from_u16(first), tail),
1657 );
1658 c = starter;
1659 if only_non_starters_in_trail {
1660 for u in tail.iter() {
1661 let char_from_u = char_from_u16(u);
1662 let trie_value = self.trie.get(char_from_u);
1663 let ccc = ccc_from_trie_value(trie_value);
1664 combining_characters
1665 .push(CharacterAndClass::new(char_from_u, ccc));
1666 }
1667 } else {
1668 let mut it = tail.iter();
1669 while let Some(u) = it.next() {
1670 let ch = char_from_u16(u);
1671 let ccc = ccc_from_trie_value(self.trie.get(ch));
1672 if ccc != CanonicalCombiningClass::NotReordered {
1673 // As of Unicode 14, this branch is never taken.
1674 // It exist for forward compatibility.
1675 combining_characters.push(CharacterAndClass::new(ch, ccc));
1676 continue;
1677 }
1678
1679 // At this point, we might have a single newly-read
1680 // combining character in self.upcoming. In that case, we
1681 // need to buffer up the upcoming combining characters, too,
1682 // in order to make `prepend_and_sort_non_starter_prefix_of_suffix`
1683 // sort the right characters.
1684 self.maybe_gather_combining();
1685
1686 while let Some(u) = it.next_back() {
1687 let tail_char = char_from_u16(u);
1688 let trie_value = self.trie.get(tail_char);
1689 self.prepend_and_sort_non_starter_prefix_of_suffix(CharacterAndClassAndTrieValue::new_with_non_special_decomposition_trie_val(tail_char, trie_value));
1690 }
1691 self.prepend_and_sort_non_starter_prefix_of_suffix(CharacterAndClassAndTrieValue::new_with_non_decomposing_starter(ch));
1692 break;
1693 }
1694 }
1695 } else {
1696 let len = (len_bits + 1) as usize;
1697 let offset32 = offset - self.scalars16.len();
1698 let (starter, tail) = self
1699 .scalars32
1700 .get_subslice(offset32..offset32 + len)
1701 .and_then(|slice| slice.split_first())
1702 .unwrap_or_else(|| {
1703 // GIGO case
1704 debug_assert!(false);
1705 (char::REPLACEMENT_CHARACTER, EMPTY_CHAR)
1706 });
1707
1708 c = starter;
1709 if only_non_starters_in_trail {
1710 for ch in tail.iter() {
1711 let trie_value = self.trie.get(ch);
1712 let ccc = ccc_from_trie_value(trie_value);
1713 combining_characters.push(CharacterAndClass::new(ch, ccc));
1714 }
1715 } else {
1716 let mut it = tail.iter();
1717 while let Some(ch) = it.next() {
1718 let ccc = ccc_from_trie_value(self.trie.get(ch));
1719 if ccc != CanonicalCombiningClass::NotReordered {
1720 // As of Unicode 14, this branch is never taken.
1721 // It exist for forward compatibility.
1722 combining_characters.push(CharacterAndClass::new(ch, ccc));
1723 continue;
1724 }
1725 // At this point, we might have a single newly-read
1726 // combining character in self.upcoming. In that case, we
1727 // need to buffer up the upcoming combining characters, too,
1728 // in order to make `prepend_and_sort_non_starter_prefix_of_suffix`
1729 // sort the right characters.
1730 self.maybe_gather_combining();
1731
1732 while let Some(tail_char) = it.next_back() {
1733 let trie_value = self.trie.get(tail_char);
1734 self.prepend_and_sort_non_starter_prefix_of_suffix(CharacterAndClassAndTrieValue::new_with_non_special_decomposition_trie_val(tail_char, trie_value));
1735 }
1736 self.prepend_and_sort_non_starter_prefix_of_suffix(CharacterAndClassAndTrieValue::new_with_non_decomposing_starter(ch));
1737 break;
1738 }
1739 }
1740 }
1741 ce32 = data.ce32_for_char(c);
1742 if ce32 == FALLBACK_CE32 {
1743 data = self.root;
1744 ce32 = data.ce32_for_char(c);
1745 }
1746 }
1747 }
1748 } else {
1749 // Hangul syllable
1750 // The math here comes from page 144 of Unicode 14.0
1751 let l = hangul_offset / HANGUL_N_COUNT;
1752 let v = (hangul_offset % HANGUL_N_COUNT) / HANGUL_T_COUNT;
1753 let t = hangul_offset % HANGUL_T_COUNT;
1754
1755 // No prefix matches on Hangul
1756 self.mark_prefix_unmatchable();
1757 // Indexing OK, because indices in range by construction
1758 #[expect(clippy::indexing_slicing)]
1759 if self.is_next_decomposition_starts_with_starter() {
1760 // TODO(#1941): Assuming self-contained CE32s is OK for the root,
1761 // but not currently OK for search collation, which at this time
1762 // do not support tailored Hangul.
1763 self.pending.push(
1764 CollationElement32::new_from_ule(
1765 self.jamo[(HANGUL_V_BASE - HANGUL_L_BASE + v) as usize],
1766 )
1767 .to_ce_self_contained_or_gigo(),
1768 );
1769 if t != 0 {
1770 self.pending.push(
1771 CollationElement32::new_from_ule(
1772 self.jamo[(HANGUL_T_BASE - HANGUL_L_BASE + t) as usize],
1773 )
1774 .to_ce_self_contained_or_gigo(),
1775 );
1776 }
1777 return CollationElement32::new_from_ule(self.jamo[l as usize])
1778 .to_ce_self_contained_or_gigo();
1779 }
1780
1781 // Uphold the invariant that the upcoming character is a starter (or end of stream)
1782 // at the start of the next `next()` call. We uphold this invariant by leaving the
1783 // last jamo unmapped to `CollationElement` in `pending` and instead prepend it to
1784 // `upcoming`.
1785 //
1786 // Indexing OK, because indices in range by construction
1787 #[expect(clippy::indexing_slicing)]
1788 if t != 0 {
1789 self.pending.push(
1790 CollationElement32::new_from_ule(
1791 self.jamo[(HANGUL_V_BASE - HANGUL_L_BASE + v) as usize],
1792 )
1793 .to_ce_self_contained_or_gigo(),
1794 );
1795 self.upcoming.insert(
1796 0,
1797 // Safety: HANGUL_T_BASE is 0x11A7, t is < HANGUL_T_COUNT = 28, so this is definitely
1798 // in range for a char (≤ 0xD800)
1799 CharacterAndClassAndTrieValue::new_with_non_decomposing_starter(unsafe {
1800 char::from_u32_unchecked(HANGUL_T_BASE + t)
1801 }),
1802 );
1803 } else {
1804 self.upcoming.insert(
1805 0,
1806 // Safety: HANGUL_V_BASE is 0x1161, v is < HANGUL_N_COUNT = 588, so this is definitely
1807 // in range for a char (≤ 0xD800)
1808 CharacterAndClassAndTrieValue::new_with_non_decomposing_starter(unsafe {
1809 char::from_u32_unchecked(HANGUL_V_BASE + v)
1810 }),
1811 );
1812 }
1813
1814 // Indexing OK, because indices in range by construction
1815 #[expect(clippy::indexing_slicing)]
1816 return CollationElement32::new_from_ule(self.jamo[l as usize])
1817 .to_ce_self_contained_or_gigo();
1818 }
1819 let mut may_have_contracted_starter = false;
1820 // Slow path
1821 self.collect_combining(&mut combining_characters);
1822 // Now:
1823 // c is the starter character
1824 // ce32 is the CollationElement32 for the starter
1825 // combining_characters contains all the combining characters before
1826 // the next starter sorted by combining class.
1827 let mut looked_ahead = 0;
1828 let mut drain_from_upcoming = 0;
1829 'outer: loop {
1830 'ce32loop: loop {
1831 // TODO(#2002): Ensure that the CE32 flavors in this loop are checked in the optimal
1832 // order given their frequency in real workloads.
1833 if let Some(ce) = ce32.to_ce_self_contained() {
1834 self.pending.push(ce);
1835 break 'ce32loop;
1836 } else {
1837 match ce32.tag() {
1838 Tag::Expansion32 => {
1839 let ce32s = data.get_ce32s(ce32.index(), ce32.len());
1840 for u in ce32s.iter() {
1841 self.pending.push(
1842 CollationElement32::new(u).to_ce_self_contained_or_gigo(),
1843 );
1844 }
1845 break 'ce32loop;
1846 }
1847 Tag::Expansion => {
1848 let ces = data.get_ces(ce32.index(), ce32.len());
1849 for u in ces.iter() {
1850 self.pending.push(CollationElement::new(u));
1851 }
1852 break 'ce32loop;
1853 }
1854 Tag::Prefix => {
1855 let (default, mut trie) = data.get_default_and_trie(ce32.index());
1856 ce32 = default;
1857 for &ch in self.prefix.iter() {
1858 match trie.next(ch) {
1859 TrieResult::NoValue => {}
1860 TrieResult::NoMatch => {
1861 continue 'ce32loop;
1862 }
1863 TrieResult::Intermediate(ce32_i) => {
1864 ce32 = CollationElement32::new(ce32_i as u32);
1865 }
1866 TrieResult::FinalValue(ce32_i) => {
1867 ce32 = CollationElement32::new(ce32_i as u32);
1868 continue 'ce32loop;
1869 }
1870 }
1871 }
1872 continue 'ce32loop;
1873 }
1874 Tag::Contraction => {
1875 let every_suffix_starts_with_combining =
1876 ce32.every_suffix_starts_with_combining();
1877 let at_least_one_suffix_contains_starter =
1878 ce32.at_least_one_suffix_contains_starter();
1879 let at_least_one_suffix_ends_with_non_starter =
1880 ce32.at_least_one_suffix_ends_with_non_starter();
1881 let (default, mut trie) = data.get_default_and_trie(ce32.index());
1882 ce32 = default;
1883 if every_suffix_starts_with_combining
1884 && combining_characters.is_empty()
1885 {
1886 continue 'ce32loop;
1887 }
1888 let mut longest_matching_state = trie.clone();
1889 let mut longest_matching_index = 0;
1890 let mut attempt = 0;
1891 let mut i = 0;
1892 let mut most_recent_skipped_ccc =
1893 CanonicalCombiningClass::NotReordered;
1894 // TODO(#2001): Pending removals will in practice be small numbers.
1895 // What if we made the item smaller than usize?
1896 let mut pending_removals: SmallVec<[usize; PENDING_REMOVALS_SIZE]> =
1897 SmallVec::new();
1898 while let Some((character, ccc)) =
1899 combining_characters.get(i).map(|c| c.character_and_ccc())
1900 {
1901 match (most_recent_skipped_ccc < ccc, trie.next(character)) {
1902 (true, TrieResult::Intermediate(ce32_i)) => {
1903 let _ = combining_characters.remove(i);
1904 while let Some(idx) = pending_removals.pop() {
1905 combining_characters.remove(idx);
1906 i -= 1; // Adjust for the shortening
1907 }
1908 attempt = 0;
1909 longest_matching_index = i;
1910 longest_matching_state = trie.clone();
1911 ce32 = CollationElement32::new(ce32_i as u32);
1912 }
1913 (true, TrieResult::FinalValue(ce32_i)) => {
1914 let _ = combining_characters.remove(i);
1915 while let Some(idx) = pending_removals.pop() {
1916 combining_characters.remove(idx);
1917 }
1918 ce32 = CollationElement32::new(ce32_i as u32);
1919 continue 'ce32loop;
1920 }
1921 (_, TrieResult::NoValue) => {
1922 pending_removals.push(i);
1923 i += 1;
1924 }
1925 _ => {
1926 pending_removals.clear();
1927 most_recent_skipped_ccc = ccc;
1928 attempt += 1;
1929 i = longest_matching_index + attempt;
1930 trie = longest_matching_state.clone();
1931 }
1932 }
1933 }
1934 if !(at_least_one_suffix_contains_starter
1935 && combining_characters.is_empty())
1936 {
1937 continue 'ce32loop;
1938 }
1939 // Let's just set this flag here instead of trying to make
1940 // it more granular and, therefore, more error-prone.
1941 // After all, this flag is just about optimizing away one
1942 // `CodePointInversionList` check in the common case.
1943 may_have_contracted_starter = true;
1944 debug_assert!(pending_removals.is_empty());
1945 self.ensure_upcoming_normalized();
1946 loop {
1947 let ahead = self.look_ahead(looked_ahead);
1948 looked_ahead += 1;
1949 if let Some(ch) = ahead {
1950 match trie.next(ch.character()) {
1951 TrieResult::NoValue => {}
1952 TrieResult::NoMatch => {
1953 if !at_least_one_suffix_ends_with_non_starter {
1954 continue 'ce32loop;
1955 }
1956 if !ch.decomposition_starts_with_non_starter() {
1957 continue 'ce32loop;
1958 }
1959 // The last-checked character is non-starter
1960 // and at least one contraction suffix ends
1961 // with a non-starter. Try a discontiguous
1962 // match.
1963 trie = longest_matching_state.clone();
1964 // For clarity, mint a new set of variables that
1965 // behave consistently with the
1966 // `combining_characters` case
1967 let mut longest_matching_index = 0;
1968 let mut attempt = 0;
1969 let mut i = 0;
1970 most_recent_skipped_ccc = ch.ccc();
1971 self.ensure_upcoming_normalized();
1972 loop {
1973 let ahead = self.look_ahead(looked_ahead + i);
1974 if let Some(ch) = ahead {
1975 let ccc = ch.ccc();
1976 if ccc
1977 == CanonicalCombiningClass::NotReordered
1978 {
1979 // If we came here, we had an intervening non-matching
1980 // non-starter, after which we cannot contract another
1981 // starter anymore.
1982 continue 'ce32loop;
1983 }
1984 match (
1985 most_recent_skipped_ccc < ccc,
1986 trie.next(ch.character()),
1987 ) {
1988 (
1989 true,
1990 TrieResult::Intermediate(ce32_i),
1991 ) => {
1992 let _ = self
1993 .upcoming
1994 .remove(looked_ahead + i);
1995 while let Some(idx) =
1996 pending_removals.pop()
1997 {
1998 self.upcoming
1999 .remove(looked_ahead + idx);
2000 i -= 1; // Adjust for the shortening
2001 }
2002 attempt = 0;
2003 longest_matching_index = i;
2004 longest_matching_state =
2005 trie.clone();
2006 ce32 = CollationElement32::new(
2007 ce32_i as u32,
2008 );
2009 }
2010 (
2011 true,
2012 TrieResult::FinalValue(ce32_i),
2013 ) => {
2014 let _ = self
2015 .upcoming
2016 .remove(looked_ahead + i);
2017 while let Some(idx) =
2018 pending_removals.pop()
2019 {
2020 self.upcoming
2021 .remove(looked_ahead + idx);
2022 }
2023 ce32 = CollationElement32::new(
2024 ce32_i as u32,
2025 );
2026 continue 'ce32loop;
2027 }
2028 (_, TrieResult::NoValue) => {
2029 pending_removals.push(i);
2030 i += 1;
2031 }
2032 _ => {
2033 pending_removals.clear();
2034 most_recent_skipped_ccc = ccc;
2035 attempt += 1;
2036 i = longest_matching_index
2037 + attempt;
2038 trie =
2039 longest_matching_state.clone();
2040 }
2041 }
2042 } else {
2043 continue 'ce32loop;
2044 }
2045 }
2046 }
2047 TrieResult::Intermediate(ce32_i) => {
2048 longest_matching_state = trie.clone();
2049 drain_from_upcoming = looked_ahead;
2050 ce32 = CollationElement32::new(ce32_i as u32);
2051 }
2052 TrieResult::FinalValue(ce32_i) => {
2053 drain_from_upcoming = looked_ahead;
2054 ce32 = CollationElement32::new(ce32_i as u32);
2055 continue 'ce32loop;
2056 }
2057 }
2058 } else {
2059 continue 'ce32loop;
2060 }
2061 }
2062 // Unreachable
2063 }
2064 Tag::Digit => {
2065 if let Some(high_bits) = self.numeric_primary {
2066 let mut digits: SmallVec<[u8; DIGIT_BUFFER_SIZE]> =
2067 SmallVec::new(); // TODO(#2005): Figure out good length
2068 digits.push(ce32.digit());
2069 let numeric_primary = u32::from(high_bits) << 24;
2070 if combining_characters.is_empty() {
2071 // Numeric collation doesn't work with combining
2072 // characters applied to the digits.
2073 // It's unclear if reading from the tailoring first
2074 // is needed for practical purposes, since it doesn't
2075 // make much sense to tailor the numeric value of digits.
2076 // Performing the usual fallback pattern anyway just in
2077 // case.
2078 may_have_contracted_starter = true;
2079 self.ensure_upcoming_normalized();
2080 while let Some(upcoming) = self.look_ahead(looked_ahead) {
2081 looked_ahead += 1;
2082 ce32 =
2083 self.tailoring.ce32_for_char(upcoming.character());
2084 if ce32 == FALLBACK_CE32 {
2085 ce32 =
2086 self.root.ce32_for_char(upcoming.character());
2087 }
2088 if ce32.tag_checked() != Some(Tag::Digit) {
2089 break;
2090 }
2091 drain_from_upcoming = looked_ahead;
2092 digits.push(ce32.digit());
2093 }
2094 }
2095 let mut remaining = digits.as_slice();
2096 while !remaining.is_empty() {
2097 // Skip leading zeros
2098
2099 // If this isn't our initial loop round and we've truncated
2100 // a chunk to 254 digits on a previous round, the eventual
2101 // comparison result can be wrong, but that replicates an
2102 // ICU4C bug. Let's fix both as a follow-up.
2103 //
2104 // https://unicode-org.atlassian.net/browse/ICU-23351
2105 loop {
2106 let Some((first, tail)) = remaining.split_first()
2107 else {
2108 // Keep one zero
2109 // If we get here, we must have skipped a zero, since
2110 // 1) the while loop condition above meant that we started
2111 // with a non-empty slice AND
2112 // 2) this loop only skips zeros
2113 // Instead of trying to recover the same zero that we already
2114 // skipped, let's just fill in a static slice.
2115 remaining = &[0];
2116 break;
2117 };
2118 if *first != 0 {
2119 break;
2120 }
2121 remaining = tail;
2122 }
2123 // Numeric CEs are generated for segments of
2124 // up to 254 digits.
2125 let (head, tail) = remaining
2126 .split_at_checked(254)
2127 .unwrap_or((remaining, b""));
2128 remaining = tail;
2129 // From ICU4C CollationIterator::appendNumericSegmentCEs
2130 if head.len() <= 7 {
2131 let mut digit_iter = head.iter();
2132 // `unwrap` succeeds, because we always have at least one
2133 // digit to even start numeric processing.
2134 #[expect(clippy::unwrap_used)]
2135 let mut value = u32::from(*digit_iter.next().unwrap());
2136 for &digit in digit_iter {
2137 value *= 10;
2138 value += u32::from(digit);
2139 }
2140 // Primary weight second byte values:
2141 // 74 byte values 2.. 75 for small numbers in two-byte primary weights.
2142 // 40 byte values 76..115 for medium numbers in three-byte primary weights.
2143 // 16 byte values 116..131 for large numbers in four-byte primary weights.
2144 // 124 byte values 132..255 for very large numbers with 4..127 digit pairs.
2145 let mut first_byte = 2u32;
2146 let mut num_bytes = 74u32;
2147 if value < num_bytes {
2148 self.pending.push(
2149 CollationElement::new_from_primary(
2150 numeric_primary
2151 | ((first_byte + value) << 16),
2152 ),
2153 );
2154 continue;
2155 }
2156 value -= num_bytes;
2157 first_byte += num_bytes;
2158 num_bytes = 40;
2159 if value < num_bytes * 254 {
2160 // Three-byte primary for 74..10233=74+40*254-1, good for year numbers and more.
2161 self.pending.push(
2162 CollationElement::new_from_primary(
2163 numeric_primary
2164 | ((first_byte + value / 254) << 16)
2165 | ((2 + value % 254) << 8),
2166 ),
2167 );
2168 continue;
2169 }
2170 value -= num_bytes * 254;
2171 first_byte += num_bytes;
2172 num_bytes = 16;
2173 if value < num_bytes * 254 * 254 {
2174 // Four-byte primary for 10234..1042489=10234+16*254*254-1.
2175 let mut primary =
2176 numeric_primary | (2 + value % 254);
2177 value /= 254;
2178 primary |= (2 + value % 254) << 8;
2179 value /= 254;
2180 primary |= (first_byte + value % 254) << 16;
2181 self.pending.push(
2182 CollationElement::new_from_primary(primary),
2183 );
2184 continue;
2185 }
2186 // original value > 1042489
2187 }
2188 debug_assert!(head.len() >= 7);
2189 // The second primary byte value 132..255 indicates the number of digit pairs (4..127),
2190 // then we generate primary bytes with those pairs.
2191 // Omit trailing 00 pairs.
2192 // Decrement the value for the last pair.
2193
2194 // Set the exponent. 4 pairs->132, 5 pairs->133, ..., 127 pairs->255.
2195 let mut len = head.len();
2196 let num_pairs = (len as u32).div_ceil(2); // as u32 OK, because capped to 254
2197 let mut primary =
2198 numeric_primary | ((132 - 4 + num_pairs) << 16);
2199 // Find the length without trailing 00 pairs.
2200 //
2201 // The indexing below is within bounds due to the following:
2202 //
2203 // * We skipped leading zeros.
2204 // * If `len == 2`: The loop condition is false, because
2205 // `head[len - 2]` isn't a leading zero.
2206 // * If `len == 1`: The loop condition is false, because
2207 // `head[len - 1]` isn't a leading zero, and `&&`
2208 // short-circuits, so the `head[len - 2]` access doesn't
2209 // occur.
2210 #[expect(clippy::indexing_slicing)]
2211 while head[len - 1] == 0 && head[len - 2] == 0 {
2212 len -= 2;
2213 }
2214 // Read the first pair
2215 // Index in bounds by construction above.
2216 #[expect(clippy::indexing_slicing)]
2217 let mut digit_iter = head[..len].iter();
2218 // `unwrap` succeeds by construction
2219 #[expect(clippy::unwrap_used)]
2220 let mut pair = if len & 1 == 1 {
2221 // Only "half a pair" if we have an odd number of digits.
2222 u32::from(*digit_iter.next().unwrap())
2223 } else {
2224 u32::from(*digit_iter.next().unwrap()) * 10
2225 + u32::from(*digit_iter.next().unwrap())
2226 };
2227 pair = 11 + 2 * pair;
2228 let mut shift = 8u32;
2229 while let (Some(&left), Some(&right)) =
2230 (digit_iter.next(), digit_iter.next())
2231 {
2232 if shift == 0 {
2233 primary |= pair;
2234 self.pending.push(
2235 CollationElement::new_from_primary(primary),
2236 );
2237 primary = numeric_primary;
2238 shift = 16;
2239 } else {
2240 primary |= pair << shift;
2241 shift -= 8;
2242 }
2243 pair =
2244 11 + 2 * (u32::from(left) * 10 + u32::from(right));
2245 }
2246 primary |= (pair - 1) << shift;
2247 self.pending
2248 .push(CollationElement::new_from_primary(primary));
2249 }
2250 break 'ce32loop;
2251 }
2252 ce32 = data.get_ce32(ce32.index());
2253 continue 'ce32loop;
2254 }
2255 Tag::Offset => {
2256 self.pending.push(data.ce_from_offset_ce32(c, ce32));
2257 break 'ce32loop;
2258 }
2259 Tag::Implicit => {
2260 self.pending
2261 .push(CollationElement::new_implicit_from_char(c));
2262 break 'ce32loop;
2263 }
2264 Tag::Fallback
2265 | Tag::Reserved3
2266 | Tag::LongPrimary
2267 | Tag::LongSecondary
2268 | Tag::BuilderData
2269 | Tag::LeadSurrogate
2270 | Tag::LatinExpansion
2271 | Tag::U0000
2272 | Tag::Hangul => {
2273 debug_assert!(false);
2274 // GIGO case
2275 self.pending.push(FFFD_CE);
2276 break 'ce32loop;
2277 }
2278 }
2279 }
2280 }
2281 self.prefix_push(c);
2282 'combining_outer: loop {
2283 debug_assert!(drain_from_upcoming == 0 || combining_characters.is_empty());
2284 let mut i = 0;
2285 'combining: while let Some(ch) =
2286 combining_characters.get(i).map(|c| c.character())
2287 {
2288 c = ch;
2289 let diacritic_index = (c as usize).wrapping_sub(COMBINING_DIACRITICS_BASE);
2290 if let Some(secondary) = self.diacritics.get(diacritic_index) {
2291 // TODO(#2006): unlikely annotation
2292 if c == '\u{0307}'
2293 && self.lithuanian_dot_above
2294 && let Some(next_c) =
2295 combining_characters.get(i + 1).map(|c| c.character())
2296 && (next_c == '\u{0300}'
2297 || next_c == '\u{0301}'
2298 || next_c == '\u{0303}')
2299 {
2300 // Lithuanian contracts COMBINING DOT ABOVE with three other diacritics of the
2301 // same combining class such that the COMBINING DOT ABOVE is ignored for
2302 // collation. Since the combining class is the same, it's valid to simply
2303 // look at the next character in `combining_characters`.
2304 i += 1;
2305 continue 'combining;
2306 }
2307 self.pending
2308 .push(CollationElement::new_from_secondary(secondary));
2309 self.mark_prefix_unmatchable();
2310 i += 1;
2311 continue 'combining;
2312 }
2313 // `c` is not a table-optimized diacritic.
2314 // Not bothering to micro optimize away the move of the remaining
2315 // part of `combining_characters`.
2316 let _ = combining_characters.drain(..=i);
2317 data = self.tailoring;
2318 ce32 = data.ce32_for_char(c);
2319 if ce32 == FALLBACK_CE32 {
2320 data = self.root;
2321 ce32 = data.ce32_for_char(c);
2322 }
2323 continue 'outer;
2324 }
2325 // Note: The borrow checker didn't like the iterator formulation
2326 // for the loop below, because the `Drain` would have kept `self`
2327 // mutable borrowed when trying to call `prefix_push`. To change
2328 // this, `prefix` and `prefix_push` would need to be refactored
2329 // into a struct.
2330 i = 0;
2331 while i < drain_from_upcoming {
2332 // By construction, `drain_from_upcoming` doesn't exceed `upcoming.len()`
2333 #[expect(clippy::indexing_slicing)]
2334 let ch = self.upcoming[i].character();
2335 self.prefix_push(ch);
2336 i += 1;
2337 }
2338 // TODO(#2004): The above makes prefix out of sync when starter-contracting
2339 // contractions use `pending_removals` instead of `drain_from_upcoming`.
2340 // Do there exist prefixes that overlap contraction suffixes?
2341 // At least as of CLDR 40, the two possible non-starters in prefixes,
2342 // kana voicing marks, shouldn't be participating in Brahmic contractions.
2343 let _ = self.upcoming.drain(..drain_from_upcoming);
2344 if self.upcoming.is_empty() {
2345 // Make the assertion conditional to make CI happy.
2346 #[cfg(debug_assertions)]
2347 debug_assert!(self.iter_exhausted || may_have_contracted_starter);
2348 if let Some(c_c_tv) = self.iter_next() {
2349 self.upcoming.push(c_c_tv);
2350 } else {
2351 #[cfg(debug_assertions)]
2352 {
2353 self.iter_exhausted = true;
2354 }
2355 }
2356 }
2357 if may_have_contracted_starter {
2358 may_have_contracted_starter = false;
2359 if !self.is_next_decomposition_starts_with_starter() {
2360 // We need to loop back and process another round of
2361 // non-starters in order to maintain the invariant of
2362 // `upcoming` on the next call to `next()`.
2363 drain_from_upcoming = 0;
2364 looked_ahead = 0;
2365 self.collect_combining(&mut combining_characters);
2366 continue 'combining_outer;
2367 }
2368 }
2369 // By construction, we have at least on pending CE by now.
2370 #[expect(clippy::indexing_slicing)]
2371 let ret = self.pending[0];
2372 debug_assert_eq!(self.pending_pos, 0);
2373 if self.pending.len() == 1 {
2374 self.pending.clear();
2375 } else {
2376 self.pending_pos = 1;
2377 }
2378 return ret;
2379 }
2380 }
2381 } else {
2382 NO_CE
2383 }
2384 }
2385
2386 #[inline(always)]
2387 fn collect_combining(
2388 &mut self,
2389 combining_characters: &mut SmallVec<[CharacterAndClass; COMBINING_CHARACTER_BUFFER_SIZE]>,
2390 ) {
2391 while !self.is_next_decomposition_starts_with_starter() {
2392 // `unwrap` is OK, because `!self.is_next_decomposition_starts_with_starter()`
2393 // means the `unwrap()` must succeed.
2394 #[expect(clippy::unwrap_used)]
2395 let combining = self.next_internal().unwrap().c_and_c;
2396 let combining_c = combining.character();
2397 if !in_inclusive_range(combining_c, '\u{0340}', '\u{0F81}') {
2398 combining_characters.push(combining);
2399 } else {
2400 // The Tibetan special cases are starters that decompose into non-starters.
2401 match combining_c {
2402 '\u{0340}' => {
2403 // COMBINING GRAVE TONE MARK
2404 combining_characters.push(CharacterAndClass::new(
2405 '\u{0300}',
2406 CanonicalCombiningClass::Above,
2407 ));
2408 }
2409 '\u{0341}' => {
2410 // COMBINING ACUTE TONE MARK
2411 combining_characters.push(CharacterAndClass::new(
2412 '\u{0301}',
2413 CanonicalCombiningClass::Above,
2414 ));
2415 }
2416 '\u{0343}' => {
2417 // COMBINING GREEK KORONIS
2418 combining_characters.push(CharacterAndClass::new(
2419 '\u{0313}',
2420 CanonicalCombiningClass::Above,
2421 ));
2422 }
2423 '\u{0344}' => {
2424 // COMBINING GREEK DIALYTIKA TONOS
2425 combining_characters.push(CharacterAndClass::new(
2426 '\u{0308}',
2427 CanonicalCombiningClass::Above,
2428 ));
2429 combining_characters.push(CharacterAndClass::new(
2430 '\u{0301}',
2431 CanonicalCombiningClass::Above,
2432 ));
2433 }
2434 '\u{0F73}' => {
2435 // TIBETAN VOWEL SIGN II
2436 combining_characters.push(CharacterAndClass::new(
2437 '\u{0F71}',
2438 CanonicalCombiningClass::CCC129,
2439 ));
2440 combining_characters.push(CharacterAndClass::new(
2441 '\u{0F72}',
2442 CanonicalCombiningClass::CCC130,
2443 ));
2444 }
2445 '\u{0F75}' => {
2446 // TIBETAN VOWEL SIGN UU
2447 combining_characters.push(CharacterAndClass::new(
2448 '\u{0F71}',
2449 CanonicalCombiningClass::CCC129,
2450 ));
2451 combining_characters.push(CharacterAndClass::new(
2452 '\u{0F74}',
2453 CanonicalCombiningClass::CCC132,
2454 ));
2455 }
2456 '\u{0F81}' => {
2457 // TIBETAN VOWEL SIGN REVERSED II
2458 combining_characters.push(CharacterAndClass::new(
2459 '\u{0F71}',
2460 CanonicalCombiningClass::CCC129,
2461 ));
2462 combining_characters.push(CharacterAndClass::new(
2463 '\u{0F80}',
2464 CanonicalCombiningClass::CCC130,
2465 ));
2466 }
2467 _ => {
2468 combining_characters.push(combining);
2469 }
2470 };
2471 }
2472 }
2473 if combining_characters.len() > 1 {
2474 // This optimizes away the class lookup when len() == 1.
2475 // Unclear if this micro optimization is worthwhile.
2476 // In any case, we store the CanonicalCombiningClass in order to
2477 // avoid having to look it up again when deciding whether to proceed
2478 // with a discontiguous match. As a side effect, it also means that
2479 // duplicate lookups aren't needed if the sort below happens to compare
2480 // an item more than once.
2481 combining_characters
2482 .iter_mut()
2483 .for_each(|cc| cc.set_ccc_from_trie_if_not_already_set(self.trie));
2484 combining_characters.sort_by_key(|cc| cc.ccc());
2485 }
2486 }
2487 }