Debian Codegraph @

debian/rust-vendor/icu_collator/src/options.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 bit layout of `CollatorOptions` is adapted from ICU4C and, therefore,
6 // is subject to the ICU license as described in LICENSE.
7
8 //! This module contains the types that are part of the API for setting
9 //! the options for the collator.
10
11 use crate::{
12 CollatorPreferences,
13 elements::{CASE_MASK, TERTIARY_MASK},
14 preferences::{CollationCaseFirst, CollationNumericOrdering},
15 provider::CollationMetadata,
16 };
17
18 /// The collation strength that indicates how many levels to compare. The primary
19 /// level considers base letters, i.e. 'a' and 'b' are unequal but 'E' and 'é'
20 /// are equal, with further levels dealing with distinctions such as accents
21 /// and case.
22 ///
23 /// Note that what constitutes a base letter depends on the language and
24 /// not on Unicode character properties. For example, 'ö' is analyzed as a base letter
25 /// for various languages (e.g. Estonian, Finnish, Icelandic, Swedish, and Turkish),
26 /// so it is distinct from 'o' even on the primary level in such languages.
27 /// Inputs that are equal in fold case (as tailored for e.g. Turkish) are expected
28 /// to be equal on the primary level. For example, "ß" is primary-equal with "ss".
29 /// Characters that are graphically ligature-like can be primary-equal with what
30 /// they appear to be ligatures of. For example, in the root collation (but not
31 /// in e.g. Danish and Norwegian) "æ" is primary-equal with "ae".
32 ///
33 /// If an earlier level isn't equal, the earlier level is decisive.
34 /// If the result is equal on a level, but the strength is higher,
35 /// the comparison proceeds to the next level.
36 ///
37 /// Note that lowering the strength means that more user-perceptible differences
38 /// compare as equal. This may make sense when sorting more complex structures
39 /// where the string to be compared is just one field, and ties between strings
40 /// that differ only in case, accent, or similar are resolved by comparing some
41 /// secondary field in the larger structure to be sorted.
42 ///
43 /// Therefore, if the sort is just a string sort without some other field for
44 /// resolving ties, lowering the strength means that factors that don't make
45 /// sense to the user (such as the order of items prior to sorting with a stable
46 /// sort algorithm or the internal details of a sorting algorithm that doesn't
47 /// provide the stability property) affect the relative order of strings that
48 /// do have user-perceptible differences particularly in accents or case.
49 ///
50 /// Lowering the strength is less of a perfomance optimization that it may seem
51 /// directly from the above description. As described above, in the case
52 /// of identical strings to be compared, the algorithm has to work though all
53 /// the levels included in the strength without an early exit. However, this
54 /// collator implements an identical prefix optimization, which examines the
55 /// code units of the strings to be compared to skip the identical prefix before
56 /// starting the actual collation algorithm. When the strings to be compared
57 /// are identical on the byte level, they are found to be equal without the
58 /// actual collation algorithm running at all! Therefore, the strength setting
59 /// only has an effect (whether order effect or performance effect) for
60 /// comparisons where the strings to be compared are not equal on the byte level
61 /// but are equal on the primary level/strength. The common cases are that
62 /// a comparison is decided on the primary level or the strings are byte
63 /// equal, which narrows the performance effect of lowering the strength
64 /// setting.
65 ///
66 /// Note: The bit layout of `CollatorOptionsBitField` requires `Strength`
67 /// to fit in 3 bits.
68 #[derive(Eq, PartialEq, Debug, Copy, Clone, PartialOrd, Ord)]
69 #[repr(u8)]
70 #[non_exhaustive]
71 pub enum Strength {
72 /// Compare only on the level of base letters. This level
73 /// corresponds to the ECMA-402 sensitivity "base" with
74 /// [`CaseLevel::Off`] (the default for [`CaseLevel`]) and
75 /// to ECMA-402 sensitivity "case" with [`CaseLevel::On`].
76 ///
77 /// ```
78 /// use icu::collator::{options::*, *};
79 ///
80 /// let mut options = CollatorOptions::default();
81 /// options.strength = Some(Strength::Primary);
82 /// let collator = Collator::try_new(Default::default(), options).unwrap();
83 /// assert_eq!(collator.compare("E", "é"), core::cmp::Ordering::Equal);
84 /// ```
85 Primary = 0,
86
87 /// Compare also on the secondary level, which corresponds
88 /// to diacritics in scripts that use them. This level corresponds
89 /// to the ECMA-402 sensitivity "accent".
90 ///
91 /// ```
92 /// use icu::collator::{options::*, *};
93 ///
94 /// let mut options = CollatorOptions::default();
95 /// options.strength = Some(Strength::Secondary);
96 /// let collator = Collator::try_new(Default::default(), options).unwrap();
97 /// assert_eq!(collator.compare("E", "e"), core::cmp::Ordering::Equal);
98 /// assert_eq!(collator.compare("e", "é"), core::cmp::Ordering::Less);
99 /// assert_eq!(collator.compare("あ", "ア"), core::cmp::Ordering::Equal);
100 /// assert_eq!(collator.compare("ァ", "ア"), core::cmp::Ordering::Equal);
101 /// assert_eq!(collator.compare("ア", "ア"), core::cmp::Ordering::Equal);
102 /// ```
103 Secondary = 1,
104
105 /// Compare also on the tertiary level. By default, if the separate
106 /// case level is disabled, this corresponds to case for bicameral
107 /// scripts. This level distinguishes Hiragana and Katakana. This
108 /// also captures other minor differences, such as half-width vs.
109 /// full-width when the Japanese tailoring isn't in use.
110 ///
111 /// This is the default comparison level and appropriate for
112 /// most scripts. This level corresponds to the ECMA-402
113 /// sensitivity "variant".
114 ///
115 /// ```
116 /// use icu::collator::{*, options::*};
117 /// use icu::locale::locale;
118 ///
119 /// let mut options = CollatorOptions::default();
120 /// options.strength = Some(Strength::Tertiary);
121 /// let collator =
122 /// Collator::try_new(Default::default(),
123 /// options).unwrap();
124 /// assert_eq!(collator.compare("E", "e"),
125 /// core::cmp::Ordering::Greater);
126 /// assert_eq!(collator.compare("e", "é"),
127 /// core::cmp::Ordering::Less);
128 /// assert_eq!(collator.compare("あ", "ア"),
129 /// core::cmp::Ordering::Less);
130 /// assert_eq!(collator.compare("ァ", "ア"),
131 /// core::cmp::Ordering::Less);
132 /// assert_eq!(collator.compare("ア", "ア"),
133 /// core::cmp::Ordering::Less);
134 /// assert_eq!(collator.compare("e", "e"), // Full-width e
135 /// core::cmp::Ordering::Less);
136 ///
137 /// let ja_collator =
138 /// Collator::try_new(locale!("ja").into(), options).unwrap();
139 /// assert_eq!(ja_collator.compare("E", "e"),
140 /// core::cmp::Ordering::Greater);
141 /// assert_eq!(ja_collator.compare("e", "é"),
142 /// core::cmp::Ordering::Less);
143 /// assert_eq!(ja_collator.compare("あ", "ア"),
144 /// core::cmp::Ordering::Equal); // Unlike root!
145 /// assert_eq!(ja_collator.compare("ァ", "ア"),
146 /// core::cmp::Ordering::Less);
147 /// assert_eq!(ja_collator.compare("ア", "ア"),
148 /// core::cmp::Ordering::Equal); // Unlike root!
149 /// assert_eq!(ja_collator.compare("e", "e"), // Full-width e
150 /// core::cmp::Ordering::Equal); // Unlike root!
151 /// ```
152 Tertiary = 2,
153
154 /// Compare also on the quaternary level. For Japanese, Hiragana
155 /// and Katakana are distinguished at the quaternary level. Also,
156 /// if `AlternateHandling::Shifted` is used, the collation
157 /// elements whose level gets shifted are shifted to this
158 /// level.
159 ///
160 /// ```
161 /// use icu::collator::{*, options::*};
162 /// use icu::locale::locale;
163 ///
164 /// let mut options = CollatorOptions::default();
165 /// options.strength = Some(Strength::Quaternary);
166 ///
167 /// let ja_collator =
168 /// Collator::try_new(locale!("ja").into(), options).unwrap();
169 /// assert_eq!(ja_collator.compare("あ", "ア"),
170 /// core::cmp::Ordering::Less);
171 /// assert_eq!(ja_collator.compare("ア", "ア"),
172 /// core::cmp::Ordering::Equal);
173 /// assert_eq!(ja_collator.compare("e", "e"), // Full-width e
174 /// core::cmp::Ordering::Equal);
175 ///
176 /// // Even this level doesn't distinguish everything,
177 /// // e.g. Hebrew cantillation marks are still ignored.
178 /// let collator =
179 /// Collator::try_new(Default::default(),
180 /// options).unwrap();
181 /// assert_eq!(collator.compare("דחי", "דחי֭"),
182 /// core::cmp::Ordering::Equal);
183 /// ```
184 // TODO: Thai example.
185 Quaternary = 3,
186
187 /// Compare the NFD form by code point order as the quinary
188 /// level. This level makes the comparison slower and should
189 /// not be used in the general case. However, it can be used
190 /// to distinguish full-width and half-width forms when the
191 /// Japanese tailoring is in use and to distinguish e.g.
192 /// Hebrew cantillation markse. Use this level if you need
193 /// JIS X 4061-1996 compliance for Japanese on the level of
194 /// distinguishing full-width and half-width forms.
195 ///
196 /// ```
197 /// use icu::collator::{*, options::*};
198 /// use icu::locale::locale;
199 ///
200 /// let mut options = CollatorOptions::default();
201 /// options.strength = Some(Strength::Identical);
202 ///
203 /// let ja_collator =
204 /// Collator::try_new(locale!("ja").into(), options).unwrap();
205 /// assert_eq!(ja_collator.compare("ア", "ア"),
206 /// core::cmp::Ordering::Less);
207 /// assert_eq!(ja_collator.compare("e", "e"), // Full-width e
208 /// core::cmp::Ordering::Less);
209 ///
210 /// let collator =
211 /// Collator::try_new(Default::default(),
212 /// options).unwrap();
213 /// assert_eq!(collator.compare("דחי", "דחי֭"),
214 /// core::cmp::Ordering::Less);
215 /// ```
216 Identical = 7,
217 }
218
219 /// What to do about characters whose comparison level can be
220 /// varied dynamically.
221 #[derive(Eq, PartialEq, Debug, Copy, Clone, PartialOrd, Ord)]
222 #[repr(u8)]
223 #[non_exhaustive]
224 pub enum AlternateHandling {
225 /// Keep the characters whose level can be varied on the
226 /// primary level.
227 NonIgnorable = 0,
228 /// Shift the characters at or below `MaxVariable` to the
229 /// quaternary level.
230 Shifted = 1,
231 // Possible future values: ShiftTrimmed, Blanked
232 }
233
234 /// What characters get shifted to the quaternary level
235 /// with `AlternateHandling::Shifted`.
236 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
237 #[repr(u8)] // This repr is necessary for transmute safety
238 #[non_exhaustive]
239 pub enum MaxVariable {
240 /// Characters classified as spaces are shifted.
241 Space = 0,
242 /// Characters classified as spaces or punctuation
243 /// are shifted.
244 Punctuation = 1,
245 /// Characters classified as spaces, punctuation,
246 /// or symbols are shifted.
247 Symbol = 2,
248 /// Characters classified as spaces, punctuation,
249 /// symbols, or currency symbols are shifted.
250 Currency = 3,
251 }
252
253 #[cfg(feature = "serde")]
254 impl MaxVariable {
255 /// The number of variants in `MaxVariable` (Space, Punctuation, Symbol, Currency),
256 /// which correspond to the "real" special primaries.
257 ///
258 /// `variant_count` isn't stable yet:
259 /// <https://github.com/rust-lang/rust/issues/73662>
260 pub(crate) const VARIANT_COUNT: usize = MaxVariable::Currency as usize + 1;
261 }
262
263 /// Whether to distinguish case in sorting, even for sorting levels higher
264 /// than tertiary, without having to use tertiary level just to enable case level differences.
265 #[derive(Eq, PartialEq, Debug, Copy, Clone)]
266 #[repr(u8)]
267 #[non_exhaustive]
268 pub enum CaseLevel {
269 /// Leave off the case level option. Case differences will be handled by default
270 /// in tertiary strength.
271 Off = 0,
272 /// Turn on the case level option, thereby making a separate level for case
273 /// differences, positioned between secondary and tertiary.
274 ///
275 /// When used together with [`Strength::Primary`], this corresponds to the
276 /// ECMA-402 sensitivity "case".
277 On = 1,
278 }
279
280 /// Options settable by the user of the API.
281 ///
282 /// With the exception of reordering (BCP47 `kr`), options that can by implied by locale are
283 /// set via [`CollatorPreferences`].
284 ///
285 /// See the [spec](https://www.unicode.org/reports/tr35/tr35-collation.html#Setting_Options).
286 ///
287 /// The setters take an `Option` so that `None` can be used to go back to default.
288 ///
289 /// # Options
290 ///
291 /// Examples for using the different options below can be found in the [crate-level docs](crate).
292 ///
293 /// ## ECMA-402 Sensitivity
294 ///
295 /// ECMA-402 `sensitivity` maps to a combination of [`Strength`] and [`CaseLevel`] as follows:
296 ///
297 /// <dl>
298 /// <dt><code>sensitivity: "base"</code></dt>
299 /// <dd><a href="enum.Strength.html#variant.Primary"><code>Strength::Primary</code></a></dd>
300 /// <dt><code>sensitivity: "accent"</code></dt>
301 /// <dd><a href="enum.Strength.html#variant.Secondary"><code>Strength::Secondary</code></a></dd>
302 /// <dt><code>sensitivity: "case"</code></dt>
303 /// <dd><a href="enum.Strength.html#variant.Primary"><code>Strength::Primary</code></a> and <a href="enum.CaseLevel.html#variant.On"><code>CaseLevel::On</code></a></dd>
304 /// <dt><code>sensitivity: "variant"</code></dt>
305 /// <dd><a href="enum.Strength.html#variant.Tertiary"><code>Strength::Tertiary</code></a></dd>
306 /// </dl>
307 ///
308 /// ## Strength
309 ///
310 /// This is the BCP47 key `ks`. The default is [`Strength::Tertiary`].
311 ///
312 /// ## Alternate Handling
313 ///
314 /// This is the BCP47 key `ka`. Note that `AlternateHandling::ShiftTrimmed` and
315 /// `AlternateHandling::Blanked` are unimplemented. The default is
316 /// [`AlternateHandling::NonIgnorable`], except
317 /// for Thai, whose default is [`AlternateHandling::Shifted`].
318 ///
319 /// ## Case Level
320 ///
321 /// See the [spec](https://www.unicode.org/reports/tr35/tr35-collation.html#Case_Parameters).
322 /// This is the BCP47 key `kc`. The default is [`CaseLevel::Off`].
323 ///
324 /// # Unsupported BCP47 options
325 ///
326 /// Reordering (BCP47 `kr`) currently cannot be set via the API and is implied
327 /// by the locale of the collation. `kr` is prohibited by ECMA-402.
328 ///
329 /// Backward second level (BCP47 `kb`) cannot be set via the API and is implied
330 /// by the locale of the collation (in practice only `fr-CA` turns it on and it's
331 /// off otherwise). `kb` is prohibited by ECMA-402.
332 ///
333 /// Normalization is always enabled and cannot be turned off. Therefore, there
334 /// is no option corresponding to BCP47 `kk`. `kk` is prohibited by ECMA-402.
335 ///
336 /// Hiragana quaternary handling is part of the strength for the Japanese
337 /// tailoring. The BCP47 key `kh` is unsupported. `kh` is deprecated and
338 /// prohibited by ECMA-402.
339 ///
340 /// Variable top (BCP47 `vt`) is unsupported (use Max Variable instead). `vt`
341 /// is deprecated and prohibited by ECMA-402.
342 ///
343 /// ## ECMA-402 Usage
344 ///
345 /// ECMA-402 `usage: "search"` is represented as `-u-co-search` as part of the
346 /// locale in ICU4X. However, neither ECMA-402 nor ICU4X provides prefix matching
347 /// or substring matching API surface. This makes the utility of search collations
348 /// very narrow: With `-u-co-search`, [`Strength::Primary`], and observing whether
349 /// comparison output is [`core::cmp::Ordering::Equal`] (making no distinction between
350 /// [`core::cmp::Ordering::Less`] and [`core::cmp::Ordering::Greater`]), it is
351 /// possible to check if a set of human-readable strings contains a full-string
352 /// fuzzy match of a user-entered string, where "fuzzy" means case-insensitive and
353 /// accent-insensitive for scripts that have such concepts and something roughly
354 /// similar for other scripts.
355 ///
356 /// Due to the very limited utility, ICU4X data does not include search collations
357 /// by default.
358 #[non_exhaustive]
359 #[derive(Debug, Copy, Clone, Default)]
360 pub struct CollatorOptions {
361 /// User-specified strength collation option.
362 pub strength: Option<Strength>,
363 /// User-specified alternate handling collation option.
364 pub alternate_handling: Option<AlternateHandling>,
365 /// User-specified max variable collation option.
366 pub max_variable: Option<MaxVariable>,
367 /// User-specified case level collation option.
368 pub case_level: Option<CaseLevel>,
369 }
370
371 impl CollatorOptions {
372 /// Create a new `CollatorOptions` with the defaults.
373 pub const fn default() -> Self {
374 Self {
375 strength: None,
376 alternate_handling: None,
377 max_variable: None,
378 case_level: None,
379 }
380 }
381 }
382
383 // Make it possible to easily copy the resolved options of
384 // one collator into another collator.
385 impl From<ResolvedCollatorOptions> for CollatorOptions {
386 /// Convenience conversion for copying the options from an
387 /// existing collator into a new one (overriding any locale-provided
388 /// defaults of the new one!).
389 fn from(options: ResolvedCollatorOptions) -> CollatorOptions {
390 Self {
391 strength: Some(options.strength),
392 alternate_handling: Some(options.alternate_handling),
393 max_variable: Some(options.max_variable),
394 case_level: Some(options.case_level),
395 }
396 }
397 }
398
399 // Make it possible to easily copy the resolved preferences of
400 // one collator into another collator.
401 impl From<ResolvedCollatorOptions> for CollatorPreferences {
402 /// Convenience conversion for copying the preferences from an
403 /// existing collator into a new one.
404 ///
405 /// Note that some preferences may not be fully preserved when recovering them
406 /// from an already initialized collator e.g [`LocalePreferences`] and [`CollationType`], because
407 /// those are only relevant when loading the collation data.
408 ///
409 /// [`LocalePreferences`]: icu_locale_core::preferences::LocalePreferences
410 /// [`CollationType`]: crate::preferences::CollationType
411 fn from(options: ResolvedCollatorOptions) -> CollatorPreferences {
412 CollatorPreferences {
413 case_first: Some(options.case_first),
414 numeric_ordering: Some(options.numeric),
415 ..Default::default()
416 }
417 }
418 }
419
420 /// The resolved (actually used) options used by the collator.
421 ///
422 /// See the documentation of `CollatorOptions`.
423 #[non_exhaustive]
424 #[derive(Debug, Copy, Clone)]
425 pub struct ResolvedCollatorOptions {
426 /// Resolved strength collation option.
427 pub strength: Strength,
428 /// Resolved alternate handling collation option.
429 pub alternate_handling: AlternateHandling,
430 /// Resolved case first collation option.
431 pub case_first: CollationCaseFirst,
432 /// Resolved max variable collation option.
433 pub max_variable: MaxVariable,
434 /// Resolved case level collation option.
435 pub case_level: CaseLevel,
436 /// Resolved numeric collation option.
437 pub numeric: CollationNumericOrdering,
438 }
439
440 impl From<CollatorOptionsBitField> for ResolvedCollatorOptions {
441 fn from(options: CollatorOptionsBitField) -> ResolvedCollatorOptions {
442 Self {
443 strength: options.strength(),
444 alternate_handling: options.alternate_handling(),
445 case_first: options.case_first(),
446 max_variable: options.max_variable(),
447 case_level: if options.case_level() {
448 CaseLevel::On
449 } else {
450 CaseLevel::Off
451 },
452 numeric: if options.numeric() {
453 CollationNumericOrdering::True
454 } else {
455 CollationNumericOrdering::False
456 },
457 // `options.backward_second_level()` not exposed.
458 }
459 }
460 }
461
462 #[derive(Copy, Clone, Debug)]
463 pub(crate) struct CollatorOptionsBitField(u32);
464
465 impl Default for CollatorOptionsBitField {
466 fn default() -> Self {
467 Self::default()
468 }
469 }
470
471 impl CollatorOptionsBitField {
472 /// Bits 0..2 : Strength
473 const STRENGTH_MASK: u32 = 0b111;
474 /// Bits 3..4 : Alternate handling: 00 non-ignorable, 01 shifted,
475 /// 10 reserved for shift-trimmed, 11 reserved for blanked.
476 /// In other words, bit 4 is currently always 0.
477 const ALTERNATE_HANDLING_MASK: u32 = 1 << 3;
478 /// Bits 5..6 : 2-bit max variable value to be shifted by `MAX_VARIABLE_SHIFT`.
479 const MAX_VARIABLE_MASK: u32 = 0b01100000;
480 const MAX_VARIABLE_SHIFT: u32 = 5;
481 /// Bit 7 : Reserved for extending max variable.
482 /// Bit 8 : Sort uppercase first if case level or case first is on.
483 const UPPER_FIRST_MASK: u32 = 1 << 8;
484 /// Bit 9 : Keep the case bits in the tertiary weight (they trump
485 /// other tertiary values)
486 /// unless case level is on (when they are *moved* into the separate case level).
487 /// By default, the case bits are removed from the tertiary weight (ignored).
488 /// When `CASE_FIRST` is off, `UPPER_FIRST` must be off too, corresponding to
489 /// the tri-value `UCOL_CASE_FIRST` attribute: `UCOL_OFF` vs. `UCOL_LOWER_FIRST` vs.
490 /// `UCOL_UPPER_FIRST`.
491 const CASE_FIRST_MASK: u32 = 1 << 9;
492 /// Bit 10 : Insert the case level between the secondary and tertiary levels.
493 const CASE_LEVEL_MASK: u32 = 1 << 10;
494 /// Bit 11 : Backward secondary level
495 const BACKWARD_SECOND_LEVEL_MASK: u32 = 1 << 11;
496 /// Bit 12 : Numeric
497 const NUMERIC_MASK: u32 = 1 << 12;
498 /// Bit 13 : Lithuanian dot above
499 const LITHUANIAN_DOT_ABOVE_MASK: u32 = 1 << 13;
500
501 /// Whether strength is explicitly set.
502 const EXPLICIT_STRENGTH_MASK: u32 = 1 << 31;
503 /// Whether max variable is explicitly set.
504 const EXPLICIT_MAX_VARIABLE_MASK: u32 = 1 << 30;
505 /// Whether alternate handling is explicitly set.
506 const EXPLICIT_ALTERNATE_HANDLING_MASK: u32 = 1 << 29;
507 /// Whether case level is explicitly set.
508 const EXPLICIT_CASE_LEVEL_MASK: u32 = 1 << 28;
509 /// Whether case first is explicitly set.
510 const EXPLICIT_CASE_FIRST_MASK: u32 = 1 << 27;
511 /// Whether backward secondary is explicitly set.
512 const EXPLICIT_BACKWARD_SECOND_LEVEL_MASK: u32 = 1 << 26;
513 /// Whether numeric is explicitly set.
514 const EXPLICIT_NUMERIC_MASK: u32 = 1 << 25;
515
516 /// Create a new [`CollatorOptionsBitField`] with the defaults.
517 pub const fn default() -> Self {
518 Self(Strength::Tertiary as u32)
519 }
520
521 /// This is the BCP47 key `ks`.
522 pub fn strength(self) -> Strength {
523 let mut bits = self.0 & CollatorOptionsBitField::STRENGTH_MASK;
524 if !(bits <= 3 || bits == 7) {
525 debug_assert!(false, "Bad value for strength.");
526 // If the bits say higher than `Quaternary` but
527 // lower than `Identical`, clamp to `Quaternary`.
528 bits = 3;
529 }
530 // Safety: Strength is repr(u8) and has discriminants between 0 and 7. The
531 // above code ensures that, since the mask puts us `≤ 8`
532 unsafe { core::mem::transmute::<u8, Strength>(bits as u8) }
533 }
534
535 /// This is the BCP47 key `ks`. See the enum for examples.
536 const fn set_strength(&mut self, strength: Option<Strength>) {
537 self.0 &= !CollatorOptionsBitField::STRENGTH_MASK;
538 if let Some(strength) = strength {
539 self.0 |= CollatorOptionsBitField::EXPLICIT_STRENGTH_MASK;
540 self.0 |= strength as u32;
541 } else {
542 self.0 &= !CollatorOptionsBitField::EXPLICIT_STRENGTH_MASK;
543 }
544 }
545
546 /// The maximum character class that `AlternateHandling::Shifted`
547 /// applies to.
548 pub fn max_variable(self) -> MaxVariable {
549 // Safe, because we mask two bits and shift them to the low
550 // two bits and the enum has values for 0 to 3, inclusive.
551 unsafe {
552 core::mem::transmute::<u8, MaxVariable>(
553 ((self.0 & CollatorOptionsBitField::MAX_VARIABLE_MASK)
554 >> CollatorOptionsBitField::MAX_VARIABLE_SHIFT) as u8,
555 )
556 }
557 }
558
559 /// The maximum character class that `AlternateHandling::Shifted`
560 /// applies to. See the enum for examples.
561 const fn set_max_variable(&mut self, max_variable: Option<MaxVariable>) {
562 self.0 &= !CollatorOptionsBitField::MAX_VARIABLE_MASK;
563 if let Some(max_variable) = max_variable {
564 self.0 |= CollatorOptionsBitField::EXPLICIT_MAX_VARIABLE_MASK;
565 self.0 |= (max_variable as u32) << CollatorOptionsBitField::MAX_VARIABLE_SHIFT;
566 } else {
567 self.0 &= !CollatorOptionsBitField::EXPLICIT_MAX_VARIABLE_MASK;
568 }
569 }
570
571 /// Whether certain characters are moved from the primary level to
572 /// the quaternary level.
573 pub fn alternate_handling(self) -> AlternateHandling {
574 if (self.0 & CollatorOptionsBitField::ALTERNATE_HANDLING_MASK) != 0 {
575 AlternateHandling::Shifted
576 } else {
577 AlternateHandling::NonIgnorable
578 }
579 }
580
581 /// Whether certain characters are moved from the primary level to
582 /// the quaternary level. See the enum for examples.
583 const fn set_alternate_handling(&mut self, alternate_handling: Option<AlternateHandling>) {
584 self.0 &= !CollatorOptionsBitField::ALTERNATE_HANDLING_MASK;
585 if let Some(alternate_handling) = alternate_handling {
586 self.0 |= CollatorOptionsBitField::EXPLICIT_ALTERNATE_HANDLING_MASK;
587 if matches!(alternate_handling, AlternateHandling::Shifted) {
588 self.0 |= CollatorOptionsBitField::ALTERNATE_HANDLING_MASK;
589 }
590 } else {
591 self.0 &= !CollatorOptionsBitField::EXPLICIT_ALTERNATE_HANDLING_MASK;
592 }
593 }
594
595 /// Whether there's a dedicated case level.
596 pub fn case_level(self) -> bool {
597 (self.0 & CollatorOptionsBitField::CASE_LEVEL_MASK) != 0
598 }
599
600 /// Whether there's a dedicated case level. If `true`, detaches
601 /// the case aspect of the tertiary level and inserts it between
602 /// the secondary and tertiary levels. Can be combined with the
603 /// primary-only strength. Setting this to `true` with
604 /// `Strength::Primary` corresponds to the ECMA-402 sensitivity
605 /// "case".
606 ///
607 /// See [the ICU guide](https://unicode-org.github.io/icu/userguide/collation/concepts.html#caselevel).
608 const fn set_case_level(&mut self, case_level: Option<bool>) {
609 self.0 &= !CollatorOptionsBitField::CASE_LEVEL_MASK;
610 if let Some(case_level) = case_level {
611 self.0 |= CollatorOptionsBitField::EXPLICIT_CASE_LEVEL_MASK;
612 if case_level {
613 self.0 |= CollatorOptionsBitField::CASE_LEVEL_MASK;
614 }
615 } else {
616 self.0 &= !CollatorOptionsBitField::EXPLICIT_CASE_LEVEL_MASK;
617 }
618 }
619
620 const fn set_case_level_from_enum(&mut self, case_level: Option<CaseLevel>) {
621 match case_level {
622 Some(CaseLevel::On) => {
623 self.set_case_level(Some(true));
624 }
625 Some(CaseLevel::Off) => {
626 self.set_case_level(Some(false));
627 }
628 _ => self.set_case_level(None),
629 }
630 }
631
632 fn case_first(self) -> CollationCaseFirst {
633 if (self.0 & CollatorOptionsBitField::CASE_FIRST_MASK) != 0 {
634 if (self.0 & CollatorOptionsBitField::UPPER_FIRST_MASK) != 0 {
635 CollationCaseFirst::Upper
636 } else {
637 CollationCaseFirst::Lower
638 }
639 } else {
640 CollationCaseFirst::False
641 }
642 }
643
644 /// Whether case is the most significant part of the tertiary
645 /// level.
646 ///
647 /// See [the ICU guide](https://unicode-org.github.io/icu/userguide/collation/concepts.html#caselevel).
648 const fn set_case_first(&mut self, case_first: Option<CollationCaseFirst>) {
649 self.0 &=
650 !(CollatorOptionsBitField::CASE_FIRST_MASK | CollatorOptionsBitField::UPPER_FIRST_MASK);
651 if let Some(case_first) = case_first {
652 self.0 |= CollatorOptionsBitField::EXPLICIT_CASE_FIRST_MASK;
653 match case_first {
654 CollationCaseFirst::False => {}
655 CollationCaseFirst::Lower => {
656 self.0 |= CollatorOptionsBitField::CASE_FIRST_MASK;
657 }
658 CollationCaseFirst::Upper => {
659 self.0 |= CollatorOptionsBitField::CASE_FIRST_MASK;
660 self.0 |= CollatorOptionsBitField::UPPER_FIRST_MASK;
661 }
662 _ => {
663 debug_assert!(false, "unknown variant");
664 }
665 }
666 } else {
667 self.0 &= !CollatorOptionsBitField::EXPLICIT_CASE_FIRST_MASK;
668 }
669 }
670
671 /// Whether second level compares the last accent difference
672 /// instead of the first accent difference.
673 pub fn backward_second_level(self) -> bool {
674 (self.0 & CollatorOptionsBitField::BACKWARD_SECOND_LEVEL_MASK) != 0
675 }
676
677 /// Whether second level compares the last accent difference
678 /// instead of the first accent difference.
679 const fn set_backward_second_level(&mut self, backward_second_level: Option<bool>) {
680 self.0 &= !CollatorOptionsBitField::BACKWARD_SECOND_LEVEL_MASK;
681 if let Some(backward_second_level) = backward_second_level {
682 self.0 |= CollatorOptionsBitField::EXPLICIT_BACKWARD_SECOND_LEVEL_MASK;
683 if backward_second_level {
684 self.0 |= CollatorOptionsBitField::BACKWARD_SECOND_LEVEL_MASK;
685 }
686 } else {
687 self.0 &= !CollatorOptionsBitField::EXPLICIT_BACKWARD_SECOND_LEVEL_MASK;
688 }
689 }
690
691 /// Whether sequences of decimal digits are compared according
692 /// to their numeric value.
693 pub fn numeric(self) -> bool {
694 (self.0 & CollatorOptionsBitField::NUMERIC_MASK) != 0
695 }
696
697 /// Whether sequences of decimal digits are compared according
698 /// to their numeric value.
699 const fn set_numeric(&mut self, numeric: Option<bool>) {
700 self.0 &= !CollatorOptionsBitField::NUMERIC_MASK;
701 if let Some(numeric) = numeric {
702 self.0 |= CollatorOptionsBitField::EXPLICIT_NUMERIC_MASK;
703 if numeric {
704 self.0 |= CollatorOptionsBitField::NUMERIC_MASK;
705 }
706 } else {
707 self.0 &= !CollatorOptionsBitField::EXPLICIT_NUMERIC_MASK;
708 }
709 }
710
711 const fn set_numeric_from_enum(&mut self, numeric: Option<CollationNumericOrdering>) {
712 match numeric {
713 Some(CollationNumericOrdering::True) => {
714 self.set_numeric(Some(true));
715 }
716 Some(CollationNumericOrdering::False) => {
717 self.set_numeric(Some(false));
718 }
719 Some(_) => {
720 debug_assert!(false, "unknown variant");
721 self.set_numeric(Some(false));
722 }
723 None => self.set_numeric(None),
724 }
725 }
726
727 /// If strength is <= secondary, returns `None`.
728 /// Otherwise, returns the appropriate mask.
729 pub(crate) fn tertiary_mask(self) -> Option<u16> {
730 if self.strength() <= Strength::Secondary {
731 None
732 } else if (self.0
733 & (CollatorOptionsBitField::CASE_FIRST_MASK | CollatorOptionsBitField::CASE_LEVEL_MASK))
734 == CollatorOptionsBitField::CASE_FIRST_MASK
735 {
736 Some(CASE_MASK | TERTIARY_MASK)
737 } else {
738 Some(TERTIARY_MASK)
739 }
740 }
741
742 /// Internal upper first getter
743 pub(crate) fn upper_first(self) -> bool {
744 (self.0 & CollatorOptionsBitField::UPPER_FIRST_MASK) != 0
745 }
746
747 pub fn lithuanian_dot_above(self) -> bool {
748 (self.0 & CollatorOptionsBitField::LITHUANIAN_DOT_ABOVE_MASK) != 0
749 }
750
751 const fn set_lithuanian_dot_above(&mut self, lithuanian_dot_above: bool) {
752 self.0 &= !CollatorOptionsBitField::LITHUANIAN_DOT_ABOVE_MASK;
753 if lithuanian_dot_above {
754 self.0 |= CollatorOptionsBitField::LITHUANIAN_DOT_ABOVE_MASK;
755 }
756 }
757
758 /// For options left as defaults in this `CollatorOptions`,
759 /// set the value from `other`. Values taken from `other`
760 /// are marked as explicitly set if they were explicitly
761 /// set in `other`.
762 const fn set_defaults(&mut self, other: CollatorOptionsBitField) {
763 if self.0 & CollatorOptionsBitField::EXPLICIT_STRENGTH_MASK == 0 {
764 self.0 &= !CollatorOptionsBitField::STRENGTH_MASK;
765 self.0 |= other.0 & CollatorOptionsBitField::STRENGTH_MASK;
766 self.0 |= other.0 & CollatorOptionsBitField::EXPLICIT_STRENGTH_MASK;
767 }
768 if self.0 & CollatorOptionsBitField::EXPLICIT_MAX_VARIABLE_MASK == 0 {
769 self.0 &= !CollatorOptionsBitField::MAX_VARIABLE_MASK;
770 self.0 |= other.0 & CollatorOptionsBitField::MAX_VARIABLE_MASK;
771 self.0 |= other.0 & CollatorOptionsBitField::EXPLICIT_MAX_VARIABLE_MASK;
772 }
773 if self.0 & CollatorOptionsBitField::EXPLICIT_ALTERNATE_HANDLING_MASK == 0 {
774 self.0 &= !CollatorOptionsBitField::ALTERNATE_HANDLING_MASK;
775 self.0 |= other.0 & CollatorOptionsBitField::ALTERNATE_HANDLING_MASK;
776 self.0 |= other.0 & CollatorOptionsBitField::EXPLICIT_ALTERNATE_HANDLING_MASK;
777 }
778 if self.0 & CollatorOptionsBitField::EXPLICIT_CASE_LEVEL_MASK == 0 {
779 self.0 &= !CollatorOptionsBitField::CASE_LEVEL_MASK;
780 self.0 |= other.0 & CollatorOptionsBitField::CASE_LEVEL_MASK;
781 self.0 |= other.0 & CollatorOptionsBitField::EXPLICIT_CASE_LEVEL_MASK;
782 }
783 if self.0 & CollatorOptionsBitField::EXPLICIT_CASE_FIRST_MASK == 0 {
784 self.0 &= !(CollatorOptionsBitField::CASE_FIRST_MASK
785 | CollatorOptionsBitField::UPPER_FIRST_MASK);
786 self.0 |= other.0
787 & (CollatorOptionsBitField::CASE_FIRST_MASK
788 | CollatorOptionsBitField::UPPER_FIRST_MASK);
789 self.0 |= other.0 & CollatorOptionsBitField::EXPLICIT_CASE_FIRST_MASK;
790 }
791 if self.0 & CollatorOptionsBitField::EXPLICIT_BACKWARD_SECOND_LEVEL_MASK == 0 {
792 self.0 &= !CollatorOptionsBitField::BACKWARD_SECOND_LEVEL_MASK;
793 self.0 |= other.0 & CollatorOptionsBitField::BACKWARD_SECOND_LEVEL_MASK;
794 self.0 |= other.0 & CollatorOptionsBitField::EXPLICIT_BACKWARD_SECOND_LEVEL_MASK;
795 }
796 if self.0 & CollatorOptionsBitField::EXPLICIT_NUMERIC_MASK == 0 {
797 self.0 &= !CollatorOptionsBitField::NUMERIC_MASK;
798 self.0 |= other.0 & CollatorOptionsBitField::NUMERIC_MASK;
799 self.0 |= other.0 & CollatorOptionsBitField::EXPLICIT_NUMERIC_MASK;
800 }
801 }
802 }
803
804 impl CollatorOptions {
805 /// Combines options, preferences, and metadata into a `CollatorOptionsBitField`.
806 ///
807 /// Note that some fields that are stored in this bit field are not considered
808 /// options in the API sense, but rather are resolved from the locale, through
809 /// metadata. This includes `backward_second_level` and `lithuanian_dot_above`.
810 pub(crate) const fn resolve(
811 self,
812 metadata: CollationMetadata,
813 case_first: Option<CollationCaseFirst>,
814 numeric_ordering: Option<CollationNumericOrdering>,
815 ) -> CollatorOptionsBitField {
816 let mut altered_defaults = CollatorOptionsBitField::default();
817
818 if metadata.alternate_shifted() {
819 altered_defaults.set_alternate_handling(Some(AlternateHandling::Shifted));
820 }
821 if metadata.backward_second_level() {
822 altered_defaults.set_backward_second_level(Some(true));
823 }
824
825 altered_defaults.set_case_first(Some(metadata.case_first()));
826 altered_defaults.set_max_variable(Some(metadata.max_variable()));
827
828 let mut merged_options = CollatorOptionsBitField::default();
829 merged_options.set_strength(self.strength);
830 merged_options.set_max_variable(self.max_variable);
831 merged_options.set_alternate_handling(self.alternate_handling);
832 merged_options.set_case_level_from_enum(self.case_level);
833 merged_options.set_case_first(case_first);
834 merged_options.set_numeric_from_enum(numeric_ordering);
835 merged_options.set_lithuanian_dot_above(metadata.lithuanian_dot_above());
836 merged_options.set_defaults(altered_defaults);
837 merged_options
838 }
839 }