Debian Codegraph @

debian/rust-vendor/icu_collator/src/provider.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 // The reordering algorithms in this file are adapted from ICU4C and,
6 // therefore, are subject to the ICU license as described in LICENSE.
7
8 //! 🚧 \[Unstable\] Data provider struct definitions for this ICU4X component.
9 //!
10 //! <div class="stab unstable">
11 //! 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
12 //! including in SemVer minor releases. While the serde representation of data structs is guaranteed
13 //! to be stable, their Rust representation might not be. Use with caution.
14 //! </div>
15 //!
16 //! Read more about data providers: [`icu_provider`]
17
18 // Provider structs must be stable
19 #![allow(clippy::exhaustive_structs, clippy::exhaustive_enums)]
20
21 use icu_collections::char16trie::Char16TrieIterator;
22 use icu_collections::codepointtrie::CodePointTrie;
23 use icu_provider::prelude::*;
24 use zerovec::ZeroVec;
25 use zerovec::ule::AsULE;
26 use zerovec::{ZeroSlice, zeroslice};
27
28 use crate::elements::CollationElement;
29 use crate::elements::CollationElement32;
30 use crate::elements::EMPTY_U16;
31 use crate::elements::FFFD_CE;
32 use crate::elements::FFFD_CE_VALUE;
33 use crate::elements::FFFD_CE32;
34 use crate::elements::FFFD_CE32_VALUE;
35 use crate::elements::NO_CE_PRIMARY;
36 use crate::elements::Tag;
37 use crate::preferences::CollationCaseFirst;
38
39 use crate::options::MaxVariable;
40
41 #[cfg(feature = "compiled_data")]
42 #[derive(Debug)]
43 /// Baked data
44 ///
45 /// <div class="stab unstable">
46 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
47 /// including in SemVer minor releases. In particular, the `DataProvider` implementations are only
48 /// guaranteed to match with this version's `*_unstable` providers. Use with caution.
49 /// </div>
50 pub struct Baked;
51
52 #[cfg(feature = "compiled_data")]
53 #[allow(unused_imports, missing_docs)]
54 const _: () = {
55 use icu_collator_data::*;
56 pub mod icu {
57 pub use crate as collator;
58 pub use icu_collections as collections;
59 }
60 make_provider!(Baked);
61 impl_collation_root_v1!(Baked);
62 impl_collation_tailoring_v1!(Baked);
63 impl_collation_diacritics_v1!(Baked);
64 impl_collation_jamo_v1!(Baked);
65 impl_collation_metadata_v1!(Baked);
66 impl_collation_special_primaries_v1!(Baked);
67 impl_collation_reordering_v1!(Baked);
68 };
69
70 const SCRIPT_FALLBACK: icu_provider::fallback::LocaleFallbackConfig = {
71 let mut c = icu_provider::fallback::LocaleFallbackConfig::default();
72 c.priority = icu_provider::fallback::LocaleFallbackPriority::Script;
73 c
74 };
75
76 icu_provider::data_marker!(
77 /// Data marker for singleton root collation data.
78 CollationRootV1,
79 "collation/root/v1",
80 CollationData<'static>,
81 is_singleton = true,
82 );
83 icu_provider::data_marker!(
84 /// Data marker for collation tailorings.
85 CollationTailoringV1,
86 "collation/tailoring/v1",
87 CollationData<'static>,
88 fallback_config = SCRIPT_FALLBACK,
89 #[cfg(feature = "datagen")]
90 attributes_domain = "collator",
91 );
92 icu_provider::data_marker!(
93 /// Data marker for collation diacritics data.
94 CollationDiacriticsV1,
95 "collation/diacritics/v1",
96 CollationDiacritics<'static>,
97 fallback_config = SCRIPT_FALLBACK,
98 #[cfg(feature = "datagen")]
99 attributes_domain = "collator",
100 #[cfg(feature = "datagen")]
101 expose_baked_consts = true,
102 );
103 icu_provider::data_marker!(
104 /// Data marker for collation jamo data.
105 CollationJamoV1,
106 "collation/jamo/v1",
107 CollationJamo<'static>,
108 is_singleton = true,
109 );
110 icu_provider::data_marker!(
111 /// Data marker for collation reordering data.
112 CollationReorderingV1,
113 "collation/reordering/v1",
114 CollationReordering<'static>,
115 fallback_config = SCRIPT_FALLBACK,
116 #[cfg(feature = "datagen")]
117 attributes_domain = "collator",
118 );
119 icu_provider::data_marker!(
120 /// Data marker for collation metadata.
121 CollationMetadataV1,
122 "collation/metadata/v1",
123 CollationMetadata,
124 fallback_config = SCRIPT_FALLBACK,
125 #[cfg(feature = "datagen")]
126 attributes_domain = "collator",
127 #[cfg(feature = "datagen")]
128 expose_baked_consts = true,
129 );
130 icu_provider::data_marker!(
131 /// Data marker for collcation special primaries data.
132 CollationSpecialPrimariesV1,
133 "collation/special/primaries/v1",
134 CollationSpecialPrimaries<'static>,
135 is_singleton = true,
136 );
137
138 #[cfg(feature = "datagen")]
139 /// The latest minimum set of markers required by this component.
140 pub const MARKERS: &[DataMarkerInfo] = &[
141 CollationRootV1::INFO,
142 CollationTailoringV1::INFO,
143 CollationDiacriticsV1::INFO,
144 CollationJamoV1::INFO,
145 CollationMetadataV1::INFO,
146 CollationReorderingV1::INFO,
147 CollationSpecialPrimariesV1::INFO,
148 ];
149
150 const SINGLE_U32: &ZeroSlice<u32> =
151 zeroslice!(u32; <u32 as AsULE>::ULE::from_unsigned; [FFFD_CE32_VALUE]);
152 const SINGLE_U64: &ZeroSlice<u64> =
153 zeroslice!(u64; <u64 as AsULE>::ULE::from_unsigned; [FFFD_CE_VALUE]);
154
155 fn data_ce_to_primary(data_ce: u64, c: char) -> u32 {
156 // Collation::getThreeBytePrimaryForOffsetData
157 let p = (data_ce >> 32) as u32; // three-byte primary pppppp00
158 let lower32 = data_ce as u32 as i32; // base code point b & step s: bbbbbbss (bit 7: isCompressible)
159 let mut offset = ((u32::from(c) as i32) - (lower32 >> 8)) * (lower32 & 0x7F); // delta * increment
160 let is_compressible = (lower32 & 0x80) != 0;
161 // Collation::incThreeBytePrimaryByOffset
162 offset += (((p >> 8) & 0xFF) as i32) - 2;
163 let mut primary = (((offset % 254) + 2) as u32) << 8;
164 offset /= 254;
165 // Same with the second byte,
166 // but reserve the PRIMARY_COMPRESSION_LOW_BYTE and high byte if necessary.
167 if is_compressible {
168 offset += (((p >> 16) & 0xFF) as i32) - 4;
169 primary |= (((offset % 251) + 4) as u32) << 16;
170 offset /= 251;
171 } else {
172 offset += (((p >> 16) & 0xFF) as i32) - 2;
173 primary |= (((offset % 254) + 2) as u32) << 16;
174 offset /= 254;
175 }
176 primary | ((p & 0xFF000000) + ((offset as u32) << 24))
177 }
178
179 /// The main collation data either for the root or for a tailoring
180 ///
181 /// <div class="stab unstable">
182 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
183 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
184 /// to be stable, their Rust representation might not be. Use with caution.
185 /// </div>
186 #[derive(Debug, PartialEq, Clone, yoke::Yokeable, zerofrom::ZeroFrom)]
187 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
188 #[cfg_attr(feature = "datagen", databake(path = icu_collator::provider))]
189 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
190 pub struct CollationData<'data> {
191 /// Mapping from `char` to `CollationElement32` (represented
192 /// as its `u32` bits).
193 #[cfg_attr(feature = "serde", serde(borrow))]
194 pub trie: CodePointTrie<'data, u32>,
195 /// `CollationElement`s used in expansions and offset CE32s
196 /// (represented as their `u64` bits)
197 #[cfg_attr(feature = "serde", serde(borrow))]
198 pub ces: ZeroVec<'data, u64>,
199 /// `CollationElement32`s used in expansions and as defaults
200 /// for digits when the numeric mode is not in use
201 #[cfg_attr(feature = "serde", serde(borrow))]
202 pub ce32s: ZeroVec<'data, u32>,
203 /// Defaults and tries for prefix and contraction matching
204 #[cfg_attr(feature = "serde", serde(borrow))]
205 pub contexts: ZeroVec<'data, u16>,
206 }
207
208 icu_provider::data_struct!(
209 CollationData<'_>,
210 #[cfg(feature = "datagen")]
211 );
212
213 impl<'data> CollationData<'data> {
214 pub(crate) fn ce32_for_char(&self, c: char) -> CollationElement32 {
215 CollationElement32::new(self.trie.get(c))
216 }
217 pub(crate) fn get_ce32(&'data self, index: usize) -> CollationElement32 {
218 CollationElement32::new(if let Some(u) = self.ce32s.get(index) {
219 u
220 } else {
221 // GIGO case
222 debug_assert!(false);
223 FFFD_CE32_VALUE
224 })
225 }
226 pub(crate) fn get_ce32s(&'data self, index: usize, len: usize) -> &'data ZeroSlice<u32> {
227 if len > 0
228 && let Some(slice) = self.ce32s.get_subslice(index..index + len)
229 {
230 return slice;
231 }
232 // GIGO case
233 debug_assert!(false);
234 SINGLE_U32
235 }
236 pub(crate) fn get_ces(&'data self, index: usize, len: usize) -> &'data ZeroSlice<u64> {
237 if len > 0
238 && let Some(slice) = self.ces.get_subslice(index..index + len)
239 {
240 return slice;
241 }
242 // GIGO case
243 debug_assert!(false);
244 SINGLE_U64
245 }
246 fn get_default_and_trie_impl(
247 &'data self,
248 index: usize,
249 ) -> (CollationElement32, &'data ZeroSlice<u16>) {
250 if let Some(slice) = self.contexts.get_subslice(index..self.contexts.len()) {
251 #[expect(clippy::unwrap_used)]
252 if slice.len() >= 2 {
253 // `unwrap` must succeed due to the length check above.
254 let first = slice.get(0).unwrap();
255 let second = slice.get(1).unwrap();
256 let trie = slice.get_subslice(2..slice.len()).unwrap();
257 return (
258 CollationElement32::new((u32::from(first) << 16) | u32::from(second)),
259 trie,
260 );
261 }
262 }
263 // GIGO case
264 debug_assert!(false);
265 (FFFD_CE32, EMPTY_U16)
266 }
267 pub(crate) fn get_default_and_trie(
268 &'data self,
269 index: usize,
270 ) -> (CollationElement32, Char16TrieIterator<'data>) {
271 let (ce32, trie) = self.get_default_and_trie_impl(index);
272 (ce32, Char16TrieIterator::new(trie))
273 }
274 pub(crate) fn get_default(&'data self, index: usize) -> CollationElement32 {
275 let (ce32, _) = self.get_default_and_trie_impl(index);
276 ce32
277 }
278 pub(crate) fn ce_from_offset_ce32(
279 &self,
280 c: char,
281 ce32: CollationElement32,
282 ) -> CollationElement {
283 debug_assert!(ce32.tag() == Tag::Offset);
284 if let Some(data_ce) = self.ces.get(ce32.index()) {
285 CollationElement::new_from_primary(data_ce_to_primary(data_ce, c))
286 } else {
287 // GIGO case
288 debug_assert!(false);
289 FFFD_CE
290 }
291 }
292 }
293
294 /// Secondary weights for the start of the Combining Diacritics block.
295 ///
296 /// <div class="stab unstable">
297 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
298 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
299 /// to be stable, their Rust representation might not be. Use with caution.
300 /// </div>
301 #[derive(Debug, PartialEq, Clone, yoke::Yokeable, zerofrom::ZeroFrom)]
302 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
303 #[cfg_attr(feature = "datagen", databake(path = icu_collator::provider))]
304 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
305 pub struct CollationDiacritics<'data> {
306 /// Secondary weights for characters starting from U+0300 up
307 /// to but not including U+034F. May be shorter than that;
308 /// zero-length when a tailoring opts out of using this
309 /// feature altogether.
310 #[cfg_attr(feature = "serde", serde(borrow))]
311 pub secondaries: ZeroVec<'data, u16>,
312 }
313
314 icu_provider::data_struct!(
315 CollationDiacritics<'_>,
316 #[cfg(feature = "datagen")]
317 );
318
319 /// `CollationElement32`s for the Hangul Jamo Unicode Block
320 ///
321 /// <div class="stab unstable">
322 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
323 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
324 /// to be stable, their Rust representation might not be. Use with caution.
325 /// </div>
326 #[derive(Debug, PartialEq, Clone, yoke::Yokeable, zerofrom::ZeroFrom)]
327 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
328 #[cfg_attr(feature = "datagen", databake(path = icu_collator::provider))]
329 pub struct CollationJamo<'data> {
330 /// `CollationElement32`s (as `u32`s) for the Hangul Jamo Unicode Block.
331 /// The length must be equal to the size of the block (256).
332 pub ce32s: ZeroVec<'data, u32>,
333 }
334
335 impl<'data> CollationJamo<'data> {
336 pub(crate) fn as_array(
337 &'data self,
338 ) -> &'data [<u32 as AsULE>::ULE; crate::elements::JAMO_COUNT] {
339 #[allow(clippy::unwrap_used)] // by invariant
340 self.ce32s.as_ule_slice().try_into().unwrap()
341 }
342 }
343
344 // TODO: redesign Korean search collation handling
345
346 #[cfg(feature = "compiled_data")]
347 const _: () = assert!(
348 Baked::SINGLETON_COLLATION_JAMO_V1.ce32s.as_slice().len() == crate::elements::JAMO_COUNT
349 );
350
351 #[cfg(feature = "serde")]
352 impl<'de> serde::Deserialize<'de> for CollationJamo<'de> {
353 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
354 where
355 D: serde::Deserializer<'de>,
356 {
357 #[derive(serde::Deserialize)]
358 struct Raw<'data> {
359 #[cfg_attr(feature = "serde", serde(borrow))]
360 ce32s: ZeroVec<'data, u32>,
361 }
362
363 let Raw { ce32s } = Raw::deserialize(deserializer)?;
364
365 if ce32s.len() != crate::elements::JAMO_COUNT {
366 return Err(serde::de::Error::custom("invalid"));
367 }
368
369 Ok(Self { ce32s })
370 }
371 }
372
373 icu_provider::data_struct!(
374 CollationJamo<'_>,
375 #[cfg(feature = "datagen")]
376 );
377
378 /// Script reordering data
379 ///
380 /// <div class="stab unstable">
381 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
382 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
383 /// to be stable, their Rust representation might not be. Use with caution.
384 /// </div>
385 #[derive(Debug, PartialEq, Clone, yoke::Yokeable, zerofrom::ZeroFrom)]
386 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
387 #[cfg_attr(feature = "datagen", databake(path = icu_collator::provider))]
388 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
389 pub struct CollationReordering<'data> {
390 /// Limit of last reordered range. 0 if no reordering or no split bytes.
391 ///
392 /// Comment from ICU4C's `collationsettings.h`
393 pub min_high_no_reorder: u32,
394 /// 256-byte table for reordering permutation of primary lead
395 /// bytes; NULL if no reordering. A 0 entry at a non-zero index means
396 /// that the primary lead byte is "split" (there are different offsets
397 /// for primaries that share that lead byte) and the reordering offset
398 /// must be determined via the reorderRanges.
399 ///
400 /// Comment from ICU4C's `collationsettings.h`
401 #[cfg_attr(feature = "serde", serde(borrow))]
402 pub reorder_table: ZeroVec<'data, u8>, // len always 256
403 /// Primary-weight ranges for script reordering, to be used by
404 /// reorder(p) for split-reordered primary lead bytes.
405 ///
406 /// Each entry is a (limit, offset) pair. The upper 16 bits of the
407 /// entry are the upper 16 bits of the exclusive primary limit of
408 /// a range. Primaries between the previous limit and this one have
409 /// their lead bytes modified by the signed offset (-0xff..+0xff)
410 /// stored in the lower 16 bits.
411 ///
412 /// `CollationData::makeReorderRanges()` writes a full list where the
413 /// first range (at least for terminators and separators) has a 0
414 /// offset. The last range has a non-zero offset. minHighNoReorder
415 /// is set to the limit of that last range.
416 ///
417 /// In the settings object, the initial ranges before the first
418 /// split lead byte are omitted for efficiency; they are handled
419 /// by reorder(p) via the reorderTable. If there are no
420 /// split-reordered lead bytes, then no ranges are needed.
421 ///
422 /// Comment from ICU4C's `collationsettings.h`; names refer to
423 /// ICU4C.
424 #[cfg_attr(feature = "serde", serde(borrow))]
425 pub reorder_ranges: ZeroVec<'data, u32>,
426 }
427
428 icu_provider::data_struct!(
429 CollationReordering<'_>,
430 #[cfg(feature = "datagen")]
431 );
432
433 impl CollationReordering<'_> {
434 pub(crate) fn reorder(&self, primary: u32) -> u32 {
435 if let Some(b) = self.reorder_table.get((primary >> 24) as usize) {
436 if b != 0 || primary <= NO_CE_PRIMARY {
437 (u32::from(b) << 24) | (primary & 0x00FFFFFF)
438 } else {
439 self.reorder_ex(primary)
440 }
441 } else {
442 // GIGO case
443 debug_assert!(false);
444 primary
445 }
446 }
447
448 fn reorder_ex(&self, primary: u32) -> u32 {
449 if primary >= self.min_high_no_reorder {
450 return primary;
451 }
452 let q = primary | 0xFFFF;
453 for &range in self.reorder_ranges.as_ule_slice().iter() {
454 let r = u32::from_unaligned(range);
455 if q < r {
456 return primary.wrapping_add(r << 24);
457 }
458 }
459 // GIGO case
460 debug_assert!(false);
461 primary
462 }
463 }
464
465 /// Each non-alias collation that the data provider knows
466 /// about explicitly has an data entry at least for this
467 /// struct.
468 ///
469 /// <div class="stab unstable">
470 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
471 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
472 /// to be stable, their Rust representation might not be. Use with caution.
473 /// </div>
474 #[derive(Debug, PartialEq, Clone, Copy, yoke::Yokeable, zerofrom::ZeroFrom)]
475 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
476 #[cfg_attr(feature = "datagen", databake(path = icu_collator::provider))]
477 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
478 pub struct CollationMetadata {
479 /// See the mask constants in the `impl` block for the
480 /// bit layout. The other bits are ignored: They could
481 /// be from the future if their semantics such that
482 /// old code may ignore them.
483 ///
484 /// Note: At present, it's bogus for the bit for "upper
485 /// first" to be set if "case first" isn't also set.
486 /// However, the methods handle this case gracefully,
487 /// so there is no need for invariant validation.
488 pub bits: u32,
489 }
490
491 icu_provider::data_struct!(
492 CollationMetadata,
493 #[cfg(feature = "datagen")]
494 );
495
496 impl CollationMetadata {
497 const MAX_VARIABLE_MASK: u32 = 0b11;
498 const TAILORED_MASK: u32 = 1 << 3;
499 const TAILORED_DIACRITICS_MASK: u32 = 1 << 4;
500 const REORDERING_MASK: u32 = 1 << 5;
501 const LITHUANIAN_DOT_ABOVE_MASK: u32 = 1 << 6;
502 const BACWARD_SECOND_LEVEL_MASK: u32 = 1 << 7;
503 const ALTERNATE_SHIFTED_MASK: u32 = 1 << 8;
504 const CASE_FIRST_MASK: u32 = 1 << 9;
505 const UPPER_FIRST_MASK: u32 = 1 << 10;
506
507 #[inline(always)]
508 pub(crate) const fn max_variable(self) -> MaxVariable {
509 // Safety: the possible numeric values for `MaxVariable` are from 0 to 3, inclusive,
510 // and it is repr(u8). MAX_VARIABLE_MASK here ensures our values have most 2 bits, which produces
511 // the same range.
512 unsafe {
513 core::mem::transmute::<u8, MaxVariable>(
514 (self.bits & CollationMetadata::MAX_VARIABLE_MASK) as u8,
515 )
516 }
517 }
518
519 #[inline(always)]
520 pub(crate) const fn tailored(self) -> bool {
521 self.bits & CollationMetadata::TAILORED_MASK != 0
522 }
523
524 /// Vietnamese and Ewe
525 #[inline(always)]
526 pub(crate) const fn tailored_diacritics(self) -> bool {
527 self.bits & CollationMetadata::TAILORED_DIACRITICS_MASK != 0
528 }
529
530 /// Lithuanian
531 #[inline(always)]
532 pub(crate) const fn lithuanian_dot_above(self) -> bool {
533 self.bits & CollationMetadata::LITHUANIAN_DOT_ABOVE_MASK != 0
534 }
535
536 /// Canadian French
537 #[inline(always)]
538 pub(crate) const fn backward_second_level(self) -> bool {
539 self.bits & CollationMetadata::BACWARD_SECOND_LEVEL_MASK != 0
540 }
541
542 #[inline(always)]
543 pub(crate) const fn reordering(self) -> bool {
544 self.bits & CollationMetadata::REORDERING_MASK != 0
545 }
546
547 /// Thai
548 #[inline(always)]
549 pub(crate) const fn alternate_shifted(self) -> bool {
550 self.bits & CollationMetadata::ALTERNATE_SHIFTED_MASK != 0
551 }
552
553 #[inline(always)]
554 pub(crate) const fn case_first(self) -> CollationCaseFirst {
555 if self.bits & CollationMetadata::CASE_FIRST_MASK != 0 {
556 if self.bits & CollationMetadata::UPPER_FIRST_MASK != 0 {
557 CollationCaseFirst::Upper
558 } else {
559 CollationCaseFirst::Lower
560 }
561 } else {
562 CollationCaseFirst::False
563 }
564 }
565 }
566
567 /// Root-associated additional data that doesn't change in tailorings
568 ///
569 /// These are the fields that logically belong to the root data but
570 /// don't belong to the tailoring data and that are on this separate
571 /// struct, since we have the same struct for a tailoring and the
572 /// bulk of the root.
573 ///
574 /// As a practical matter, this struct happens to only carry
575 /// information about what concrete numeric values for primary
576 /// weights are special in particular ways. In principle, when the
577 /// root data is built, the root builder is allowed to assign the
578 /// numeric values as it sees fit, which is why these aren't
579 /// hard-coded.
580 ///
581 /// Note: In 2.0.0 and prior, this struct was loaded only if
582 /// it was known at collator construction time (based on options)
583 /// that the data here was going to be needed. With the introduction
584 /// of collation keys and the decision not to introduce a collator
585 /// key generator object separate from the collator, this struct
586 /// is now always loaded.
587 ///
588 /// <div class="stab unstable">
589 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
590 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
591 /// to be stable, their Rust representation might not be. Use with caution.
592 /// </div>
593 #[derive(Debug, PartialEq, Clone, yoke::Yokeable, zerofrom::ZeroFrom)]
594 #[cfg_attr(feature = "datagen", derive(databake::Bake))]
595 #[cfg_attr(feature = "datagen", databake(path = icu_collator::provider))]
596 pub struct CollationSpecialPrimaries<'data> {
597 /// The primaries corresponding to `MaxVariable`
598 /// character classes packed so that each fits in
599 /// 16 bits. Length must match the number of enum
600 /// variants in `MaxVariable`, currently 4.
601 pub last_primaries: ZeroVec<'data, u16>,
602 /// The high 8 bits of the numeric primary
603 pub numeric_primary: u8,
604 /// 256 bits (packed in 16 u16s) to classify every possible
605 /// byte into compressible or non-compressible.
606 ///
607 /// In the serde encoding, this is appended to `last_primaries`,
608 /// or might be missing.
609 pub compressible_bytes: ZeroVec<'data, u16>,
610 }
611
612 #[cfg(feature = "serde")]
613 impl CollationSpecialPrimaries<'_> {
614 /// The length of the compressible bytes array (256 bits packed in `u16`s).
615 pub(crate) const COMPRESSIBLE_BYTES_LEN: usize = 256 / (u16::BITS as usize);
616 }
617
618 #[cfg(feature = "serde")]
619 impl<'de> serde::Deserialize<'de> for CollationSpecialPrimaries<'de> {
620 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
621 where
622 D: serde::Deserializer<'de>,
623 {
624 #[derive(serde::Deserialize)]
625 struct Raw<'data> {
626 #[cfg_attr(feature = "serde", serde(borrow))]
627 concatenated: &'data ZeroSlice<u16>,
628 numeric_primary: u8,
629 }
630
631 let Raw {
632 concatenated,
633 numeric_primary,
634 } = Raw::deserialize(deserializer)?;
635
636 let Some((l, c)) = concatenated
637 .as_ule_slice()
638 .split_at_checked(MaxVariable::VARIANT_COUNT)
639 else {
640 return Err(serde::de::Error::custom("invalid"));
641 };
642
643 let last_primaries = ZeroSlice::from_ule_slice(l).as_zerovec();
644 let mut compressible_bytes = ZeroSlice::from_ule_slice(c).as_zerovec();
645
646 if c.len() != CollationSpecialPrimaries::COMPRESSIBLE_BYTES_LEN {
647 compressible_bytes = zerovec::zerovec!(
648 u16; <u16 as AsULE>::ULE::from_unsigned; [
649 0b0000_0000_0000_0000,
650 0b0000_0000_0000_0000,
651 0b0000_0000_0000_0000,
652 0b0000_0000_0000_0000,
653 0b0000_0000_0000_0000,
654 0b0000_0000_0000_0000,
655 0b1111_1111_1111_1110,
656 0b1111_1111_1111_1111,
657 0b0000_0000_0000_0001,
658 0b0000_0000_0000_0000,
659 0b0000_0000_0000_0000,
660 0b0000_0000_0000_0000,
661 0b0000_0000_0000_0000,
662 0b0000_0000_0000_0000,
663 0b0000_0000_0000_0000,
664 0b0100_0000_0000_0000,
665 ]);
666 }
667
668 Ok(Self {
669 last_primaries,
670 numeric_primary,
671 compressible_bytes,
672 })
673 }
674 }
675
676 #[cfg(feature = "datagen")]
677 impl serde::Serialize for CollationSpecialPrimaries<'_> {
678 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
679 where
680 S: serde::Serializer,
681 {
682 #[derive(serde::Serialize)]
683 struct Raw {
684 #[serde(rename = "last_primaries")]
685 concatenated: ZeroVec<'static, u16>,
686 numeric_primary: u8,
687 }
688
689 Raw {
690 concatenated: self
691 .last_primaries
692 .iter()
693 .chain(self.compressible_bytes.iter())
694 .collect(),
695 numeric_primary: self.numeric_primary,
696 }
697 .serialize(serializer)
698 }
699 }
700
701 icu_provider::data_struct!(
702 CollationSpecialPrimaries<'_>,
703 #[cfg(feature = "datagen")]
704 );
705
706 impl CollationSpecialPrimaries<'_> {
707 #[expect(clippy::unwrap_used)]
708 pub(crate) fn last_primary_for_group(&self, max_variable: MaxVariable) -> u32 {
709 // `unwrap` is OK, because `Collator::try_new` validates the length.
710 //
711 // Minus one to generate the right lower 16 bits from the high 16 bits.
712 // See parse.cpp in genrb and getLastPrimaryForGroup in ICU4C.
713 (u32::from(self.last_primaries.get(max_variable as usize).unwrap()) << 16) - 1
714 }
715
716 #[allow(dead_code)]
717 pub(crate) fn is_compressible(&self, b: u8) -> bool {
718 let field = self
719 .compressible_bytes
720 .get(usize::from(b >> 4))
721 .unwrap_or_default();
722 let mask = 1 << (b & 0b1111);
723 (field & mask) != 0
724 }
725 }