Debian Codegraph @

debian/rust-vendor/icu_plurals/src/lib.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 // https://github.com/unicode-org/icu4x/blob/main/documents/process/boilerplate.md#library-annotations
6 #![cfg_attr(not(any(test, doc)), no_std)]
7 #![cfg_attr(
8 not(test),
9 deny(
10 clippy::indexing_slicing,
11 clippy::unwrap_used,
12 clippy::expect_used,
13 clippy::panic,
14 )
15 )]
16 #![warn(missing_docs)]
17
18 //! Determine the plural category appropriate for a given number in a given language.
19 //!
20 //! This module is published as its own crate ([`icu_plurals`](https://docs.rs/icu_plurals/latest/icu_plurals/))
21 //! and as part of the [`icu`](https://docs.rs/icu/latest/icu/) crate. See the latter for more details on the ICU4X project.
22 //!
23 //! For example in English, when constructing a message
24 //! such as `{ num } items`, the user has to prepare
25 //! two variants of the message:
26 //!
27 //! * `1 item`
28 //! * `0 items`, `2 items`, `5 items`, `0.5 items` etc.
29 //!
30 //! The former variant is used when the placeholder variable has value `1`,
31 //! while the latter is used for all other values of the variable.
32 //!
33 //! Unicode defines [Language Plural Rules] as a mechanism to codify those
34 //! variants and provides data and algorithms to calculate
35 //! appropriate [`PluralCategory`].
36 //!
37 //! # Examples
38 //!
39 //! ```
40 //! use icu::locale::locale;
41 //! use icu::plurals::{PluralCategory, PluralRules};
42 //!
43 //! let pr = PluralRules::try_new(locale!("en").into(), Default::default())
44 //! .expect("locale should be present");
45 //!
46 //! assert_eq!(pr.category_for(5_usize), PluralCategory::Other);
47 //! ```
48 //!
49 //! ## Plural Rules
50 //!
51 //! The crate provides the main struct [`PluralRules`] which handles selection
52 //! of the correct [`PluralCategory`] for a given language and [`PluralRuleType`].
53 //!
54 //! ## Plural Category
55 //!
56 //! Every number in every language belongs to a certain [`PluralCategory`].
57 //! For example, the Polish language uses four:
58 //!
59 //! * [`One`](PluralCategory::One): `1 miesiąc`
60 //! * [`Few`](PluralCategory::Few): `2 miesiące`
61 //! * [`Many`](PluralCategory::Many): `5 miesięcy`
62 //! * [`Other`](PluralCategory::Other): `1.5 miesiąca`
63 //!
64 //! ## `PluralRuleType`
65 //!
66 //! Plural rules depend on the use case. This crate supports two types of plural rules:
67 //!
68 //! * [`Cardinal`](PluralRuleType::Cardinal): `3 doors`, `1 month`, `10 dollars`
69 //! * [`Ordinal`](PluralRuleType::Ordinal): `1st place`, `10th day`, `11th floor`
70 //!
71 //! [Language Plural Rules]: https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules
72
73 extern crate alloc;
74
75 mod operands;
76 mod options;
77 pub mod provider;
78
79 // Need to expose it for datagen, but we don't
80 // have a reason to make it fully public, so hiding docs for now.
81 #[cfg(feature = "unstable")]
82 mod raw_operands;
83
84 #[cfg(feature = "unstable")]
85 pub use raw_operands::RawPluralOperands;
86
87 use core::cmp::{Ord, PartialOrd};
88 use core::convert::Infallible;
89 use icu_locale_core::preferences::define_preferences;
90 use icu_provider::marker::ErasedMarker;
91 use icu_provider::prelude::*;
92 pub use operands::PluralOperands;
93 pub use options::*;
94 use provider::PluralRulesData;
95 use provider::PluralsCardinalV1;
96 use provider::PluralsOrdinalV1;
97 use provider::rules::runtime::test_rule;
98
99 #[cfg(feature = "unstable")]
100 use provider::PluralsRangesV1;
101 #[cfg(feature = "unstable")]
102 use provider::UnvalidatedPluralRange;
103
104 /// The plural categories are used to format messages with numeric placeholders, expressed as decimal numbers.
105 ///
106 /// The fundamental rule for determining plural categories is the existence of minimal pairs: whenever two different
107 /// numbers may require different versions of the same message, then the numbers have different plural categories.
108 ///
109 /// All languages supported by `ICU4X` can match any number to one of the categories.
110 ///
111 /// # Examples
112 ///
113 /// ```
114 /// use icu::locale::locale;
115 /// use icu::plurals::{PluralCategory, PluralRules};
116 ///
117 /// let pr = PluralRules::try_new(locale!("en").into(), Default::default())
118 /// .expect("locale should be present");
119 ///
120 /// assert_eq!(pr.category_for(5_usize), PluralCategory::Other);
121 /// ```
122 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Ord, PartialOrd)]
123 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
124 #[cfg_attr(feature = "datagen", databake(path = icu_plurals))]
125 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
126 #[repr(u8)]
127 #[zerovec::make_ule(PluralCategoryULE)]
128 #[allow(clippy::exhaustive_enums)] // this type is mostly stable. new categories may potentially be added in the future,
129 // but at a cadence slower than the ICU4X release cycle
130 pub enum PluralCategory {
131 /// CLDR "zero" plural category. Used in Arabic and Latvian, among others.
132 ///
133 /// Examples of numbers having this category:
134 ///
135 /// - 0 in Arabic (ar), Latvian (lv)
136 /// - 10~20, 30, 40, 50, ... in Latvian (lv)
137 Zero = 0,
138 /// CLDR "one" plural category. Signifies the singular form in many languages.
139 ///
140 /// Examples of numbers having this category:
141 ///
142 /// - 0 in French (fr), Portuguese (pt), ...
143 /// - 1 in English (en) and most other languages
144 /// - 2.1 in Filipino (fil), Croatian (hr), Latvian (lv), Serbian (sr)
145 /// - 2, 3, 5, 7, 8, ... in Filipino (fil)
146 One = 1,
147 /// CLDR "two" plural category. Used in Arabic, Hebrew, and Slovenian, among others.
148 ///
149 /// Examples of numbers having this category:
150 ///
151 /// - 2 in Arabic (ar), Hebrew (iw), Slovenian (sl)
152 /// - 2.0 in Arabic (ar)
153 Two = 2,
154 /// CLDR "few" plural category. Used in Romanian, Polish, Russian, and others.
155 ///
156 /// Examples of numbers having this category:
157 ///
158 /// - 0 in Romanian (ro)
159 /// - 1.2 in Croatian (hr), Romanian (ro), Slovenian (sl), Serbian (sr)
160 /// - 2 in Polish (pl), Russian (ru), Czech (cs), ...
161 /// - 5 in Arabic (ar), Lithuanian (lt), Romanian (ro)
162 Few = 3,
163 /// CLDR "many" plural category. Used in Polish, Russian, Ukrainian, and others.
164 ///
165 /// Examples of numbers having this category:
166 ///
167 /// - 0 in Polish (pl)
168 /// - 1.0 in Czech (cs), Slovak (sk)
169 /// - 1.1 in Czech (cs), Lithuanian (lt), Slovak (sk)
170 /// - 15 in Arabic (ar), Polish (pl), Russian (ru), Ukrainian (uk)
171 Many = 4,
172 /// CLDR "other" plural category, used as a catch-all. Each language supports it, and it
173 /// is also used as a fail safe result for in case no better match can be identified.
174 ///
175 /// In some languages, such as Japanese, Chinese, Korean, and Thai, this is the only
176 /// plural category.
177 ///
178 /// Examples of numbers having this category:
179 ///
180 /// - 0 in English (en), German (de), Spanish (es), ...
181 /// - 1 in Japanese (ja), Korean (ko), Chinese (zh), Thai (th), ...
182 /// - 2 in English (en), German (de), Spanish (es), ...
183 Other = 5,
184 }
185
186 impl PluralCategory {
187 /// Returns an ordered iterator over variants of [`Plural Categories`].
188 ///
189 /// Categories are returned in alphabetical order.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// use icu::plurals::PluralCategory;
195 ///
196 /// let mut categories = PluralCategory::all();
197 ///
198 /// assert_eq!(categories.next(), Some(PluralCategory::Few));
199 /// assert_eq!(categories.next(), Some(PluralCategory::Many));
200 /// assert_eq!(categories.next(), Some(PluralCategory::One));
201 /// assert_eq!(categories.next(), Some(PluralCategory::Other));
202 /// assert_eq!(categories.next(), Some(PluralCategory::Two));
203 /// assert_eq!(categories.next(), Some(PluralCategory::Zero));
204 /// assert_eq!(categories.next(), None);
205 /// ```
206 ///
207 /// [`Plural Categories`]: PluralCategory
208 pub fn all() -> impl ExactSizeIterator<Item = Self> {
209 [
210 Self::Few,
211 Self::Many,
212 Self::One,
213 Self::Other,
214 Self::Two,
215 Self::Zero,
216 ]
217 .iter()
218 .copied()
219 }
220
221 /// Returns the [`PluralCategory`] corresponding to given TR35 string.
222 pub fn get_for_cldr_string(category: &str) -> Option<PluralCategory> {
223 Self::get_for_cldr_bytes(category.as_bytes())
224 }
225 /// Returns the [`PluralCategory`] corresponding to given TR35 string as bytes
226 pub fn get_for_cldr_bytes(category: &[u8]) -> Option<PluralCategory> {
227 match category {
228 b"zero" => Some(PluralCategory::Zero),
229 b"one" => Some(PluralCategory::One),
230 b"two" => Some(PluralCategory::Two),
231 b"few" => Some(PluralCategory::Few),
232 b"many" => Some(PluralCategory::Many),
233 b"other" => Some(PluralCategory::Other),
234 _ => None,
235 }
236 }
237 }
238
239 define_preferences!(
240 /// The preferences for plural rules.
241 [Copy]
242 PluralRulesPreferences,
243 {}
244 );
245
246 /// A struct which provides an ability to retrieve an appropriate
247 /// [`Plural Category`] for a given number.
248 ///
249 /// # Examples
250 ///
251 /// ```
252 /// use icu::locale::locale;
253 /// use icu::plurals::{PluralCategory, PluralRules};
254 ///
255 /// let pr = PluralRules::try_new(locale!("en").into(), Default::default())
256 /// .expect("locale should be present");
257 ///
258 /// assert_eq!(pr.category_for(5_usize), PluralCategory::Other);
259 /// ```
260 ///
261 /// [`ICU4X`]: ../icu/index.html
262 /// [`Plural Type`]: PluralRuleType
263 /// [`Plural Category`]: PluralCategory
264 #[derive(Debug)]
265 pub struct PluralRules(DataPayload<ErasedMarker<PluralRulesData<'static>>>);
266
267 impl AsRef<PluralRules> for PluralRules {
268 fn as_ref(&self) -> &PluralRules {
269 self
270 }
271 }
272
273 impl PluralRules {
274 icu_provider::gen_buffer_data_constructors!(
275 (prefs: PluralRulesPreferences, options: PluralRulesOptions) -> error: DataError,
276 /// Constructs a new `PluralRules` for a given locale and type using compiled data.
277 ///
278 /// # Examples
279 ///
280 /// ```
281 /// use icu::locale::locale;
282 /// use icu::plurals::PluralRules;
283 ///
284 /// let _ = PluralRules::try_new(
285 /// locale!("en").into(),
286 /// Default::default(),
287 /// ).expect("locale should be present");
288 /// ```
289 ///
290 /// [`data provider`]: icu_provider
291 );
292
293 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
294 pub fn try_new_unstable(
295 provider: &(impl DataProvider<PluralsCardinalV1> + DataProvider<PluralsOrdinalV1> + ?Sized),
296 prefs: PluralRulesPreferences,
297 options: PluralRulesOptions,
298 ) -> Result<Self, DataError> {
299 match options.rule_type.unwrap_or_default() {
300 PluralRuleType::Cardinal => Self::try_new_cardinal_unstable(provider, prefs),
301 PluralRuleType::Ordinal => Self::try_new_ordinal_unstable(provider, prefs),
302 }
303 }
304
305 icu_provider::gen_buffer_data_constructors!(
306 (prefs: PluralRulesPreferences) -> error: DataError,
307 /// Constructs a new `PluralRules` for a given locale for cardinal numbers using compiled data.
308 ///
309 /// Cardinal plural forms express quantities of units such as time, currency or distance,
310 /// used in conjunction with a number expressed in decimal digits (i.e. "2", not "two").
311 ///
312 /// For example, English has two forms for cardinals:
313 ///
314 /// * [`One`]: `1 day`
315 /// * [`Other`]: `0 days`, `2 days`, `10 days`, `0.3 days`
316 ///
317 /// # Examples
318 ///
319 /// ```
320 /// use icu::locale::locale;
321 /// use icu::plurals::{PluralCategory, PluralRules};
322 ///
323 /// let rules = PluralRules::try_new_cardinal(locale!("ru").into()).expect("locale should be present");
324 ///
325 /// assert_eq!(rules.category_for(2_usize), PluralCategory::Few);
326 /// ```
327 ///
328 /// [`One`]: PluralCategory::One
329 /// [`Other`]: PluralCategory::Other
330 functions: [
331 try_new_cardinal,
332 try_new_cardinal_with_buffer_provider,
333 try_new_cardinal_unstable,
334 Self,
335 ]
336 );
337
338 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_cardinal)]
339 pub fn try_new_cardinal_unstable(
340 provider: &(impl DataProvider<PluralsCardinalV1> + ?Sized),
341 prefs: PluralRulesPreferences,
342 ) -> Result<Self, DataError> {
343 let locale = PluralsCardinalV1::make_locale(prefs.locale_preferences);
344 Ok(Self(
345 provider
346 .load(DataRequest {
347 id: DataIdentifierBorrowed::for_locale(&locale),
348 ..Default::default()
349 })?
350 .payload
351 .cast(),
352 ))
353 }
354
355 icu_provider::gen_buffer_data_constructors!(
356 (prefs: PluralRulesPreferences) -> error: DataError,
357 /// Constructs a new `PluralRules` for a given locale for ordinal numbers using compiled data.
358 ///
359 /// Ordinal plural forms denote the order of items in a set and are always integers.
360 ///
361 /// For example, English has four forms for ordinals:
362 ///
363 /// * [`One`]: `1st floor`, `21st floor`, `101st floor`
364 /// * [`Two`]: `2nd floor`, `22nd floor`, `102nd floor`
365 /// * [`Few`]: `3rd floor`, `23rd floor`, `103rd floor`
366 /// * [`Other`]: `4th floor`, `11th floor`, `96th floor`
367 ///
368 /// # Examples
369 ///
370 /// ```
371 /// use icu::locale::locale;
372 /// use icu::plurals::{PluralCategory, PluralRules};
373 ///
374 /// let rules = PluralRules::try_new_ordinal(
375 /// locale!("ru").into(),
376 /// )
377 /// .expect("locale should be present");
378 ///
379 /// assert_eq!(rules.category_for(2_usize), PluralCategory::Other);
380 /// ```
381 ///
382 /// [`One`]: PluralCategory::One
383 /// [`Two`]: PluralCategory::Two
384 /// [`Few`]: PluralCategory::Few
385 /// [`Other`]: PluralCategory::Other
386 functions: [
387 try_new_ordinal,
388 try_new_ordinal_with_buffer_provider,
389 try_new_ordinal_unstable,
390 Self,
391 ]
392 );
393
394 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_ordinal)]
395 pub fn try_new_ordinal_unstable(
396 provider: &(impl DataProvider<PluralsOrdinalV1> + ?Sized),
397 prefs: PluralRulesPreferences,
398 ) -> Result<Self, DataError> {
399 let locale = PluralsOrdinalV1::make_locale(prefs.locale_preferences);
400 Ok(Self(
401 provider
402 .load(DataRequest {
403 id: DataIdentifierBorrowed::for_locale(&locale),
404 ..Default::default()
405 })?
406 .payload
407 .cast(),
408 ))
409 }
410
411 /// Returns the [`Plural Category`] appropriate for the given number.
412 ///
413 /// # Examples
414 ///
415 /// ```
416 /// use icu::locale::locale;
417 /// use icu::plurals::{PluralCategory, PluralRules};
418 ///
419 /// let pr = PluralRules::try_new(locale!("en").into(), Default::default())
420 /// .expect("locale should be present");
421 ///
422 /// match pr.category_for(1_usize) {
423 /// PluralCategory::One => "One item",
424 /// PluralCategory::Other => "Many items",
425 /// _ => unreachable!(),
426 /// };
427 /// ```
428 ///
429 /// The method accepts any input that can be calculated into [`Plural Operands`].
430 /// All unsigned primitive number types can infallibly be converted so they can be
431 /// used as an input.
432 ///
433 /// For signed numbers and strings, [`Plural Operands`] implement [`TryFrom`]
434 /// and [`FromStr`](std::str::FromStr), which should be used before passing the result to
435 /// [`category_for()`](PluralRules::category_for()).
436 ///
437 /// # Examples
438 ///
439 /// ```
440 /// use icu::locale::locale;
441 /// use icu::plurals::{PluralRules, PluralCategory, PluralOperands};
442 /// #
443 /// # let pr = PluralRules::try_new(locale!("en").into(), Default::default())
444 /// # .expect("locale should be present");
445 ///
446 /// let operands = PluralOperands::from(-5);
447 /// let operands2: PluralOperands = "5.10".parse().expect("Failed to parse to operands.");
448 ///
449 /// assert_eq!(pr.category_for(operands), PluralCategory::Other);
450 /// assert_eq!(pr.category_for(operands2), PluralCategory::Other);
451 /// ```
452 ///
453 /// [`Plural Category`]: PluralCategory
454 /// [`Plural Operands`]: operands::PluralOperands
455 pub fn category_for<I: Into<PluralOperands>>(&self, input: I) -> PluralCategory {
456 let rules = self.0.get();
457 let input = input.into();
458
459 macro_rules! test_rule {
460 ($rule:ident, $cat:ident) => {
461 rules
462 .$rule
463 .as_ref()
464 .and_then(|r| test_rule(r, &input).then(|| PluralCategory::$cat))
465 };
466 }
467
468 test_rule!(zero, Zero)
469 .or_else(|| test_rule!(one, One))
470 .or_else(|| test_rule!(two, Two))
471 .or_else(|| test_rule!(few, Few))
472 .or_else(|| test_rule!(many, Many))
473 .unwrap_or(PluralCategory::Other)
474 }
475
476 /// Returns all [`Plural Categories`] appropriate for a [`PluralRules`] object
477 /// based on the [`LanguageIdentifier`](icu::locale::{LanguageIdentifier}) and [`PluralRuleType`].
478 ///
479 /// The [`Plural Categories`] are returned in UTS 35 sorted order.
480 ///
481 /// The category [`PluralCategory::Other`] is always included.
482 ///
483 /// # Examples
484 ///
485 /// ```
486 /// use icu::locale::locale;
487 /// use icu::plurals::{PluralCategory, PluralRules};
488 ///
489 /// let pr = PluralRules::try_new(locale!("fr").into(), Default::default())
490 /// .expect("locale should be present");
491 ///
492 /// let mut categories = pr.categories();
493 /// assert_eq!(categories.next(), Some(PluralCategory::One));
494 /// assert_eq!(categories.next(), Some(PluralCategory::Many));
495 /// assert_eq!(categories.next(), Some(PluralCategory::Other));
496 /// assert_eq!(categories.next(), None);
497 /// ```
498 ///
499 /// [`Plural Categories`]: PluralCategory
500 pub fn categories(&self) -> impl Iterator<Item = PluralCategory> + '_ {
501 let rules = self.0.get();
502
503 macro_rules! test_rule {
504 ($rule:ident, $cat:ident) => {
505 rules
506 .$rule
507 .as_ref()
508 .map(|_| PluralCategory::$cat)
509 .into_iter()
510 };
511 }
512
513 test_rule!(zero, Zero)
514 .chain(test_rule!(one, One))
515 .chain(test_rule!(two, Two))
516 .chain(test_rule!(few, Few))
517 .chain(test_rule!(many, Many))
518 .chain(Some(PluralCategory::Other))
519 }
520 }
521
522 /// A [`PluralRules`] that also has the ability to retrieve an appropriate [`Plural Category`] for a
523 /// range.
524 ///
525 /// ✨ *Enabled with the `unstable` Cargo feature.*
526 ///
527 /// <div class="stab unstable">
528 /// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
529 /// including in SemVer minor releases. Use with caution.
530 /// <a href="https://github.com/unicode-org/icu4x/issues/4140">#4140</a>
531 /// </div>
532 ///
533 /// # Examples
534 ///
535 /// ```
536 /// use icu::locale::locale;
537 /// use icu::plurals::{PluralCategory, PluralOperands, PluralRulesWithRanges};
538 ///
539 /// let ranges = PluralRulesWithRanges::try_new(
540 /// locale!("ar").into(),
541 /// Default::default(),
542 /// )
543 /// .expect("locale should be present");
544 ///
545 /// let operands = PluralOperands::from(1_usize);
546 /// let operands2: PluralOperands =
547 /// "2.0".parse().expect("parsing to operands should succeed");
548 ///
549 /// assert_eq!(
550 /// ranges.category_for_range(operands, operands2),
551 /// PluralCategory::Other
552 /// );
553 /// ```
554 ///
555 /// [`Plural Category`]: PluralCategory
556 #[cfg(feature = "unstable")]
557 #[derive(Debug)]
558 pub struct PluralRulesWithRanges<R> {
559 rules: R,
560 ranges: DataPayload<PluralsRangesV1>,
561 }
562
563 #[cfg(feature = "unstable")]
564 impl PluralRulesWithRanges<PluralRules> {
565 icu_provider::gen_buffer_data_constructors!(
566
567 (prefs: PluralRulesPreferences, options: PluralRulesOptions) -> error: DataError,
568 /// Constructs a new `PluralRulesWithRanges` for a given locale using compiled data.
569 ///
570 /// # Examples
571 ///
572 /// ```
573 /// use icu::locale::locale;
574 /// use icu::plurals::PluralRulesWithRanges;
575 ///
576 /// let _ = PluralRulesWithRanges::try_new(
577 /// locale!("en").into(),
578 /// Default::default(),
579 /// ).expect("locale should be present");
580 /// ```
581 );
582
583 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
584 pub fn try_new_unstable(
585 provider: &(
586 impl DataProvider<PluralsRangesV1>
587 + DataProvider<PluralsCardinalV1>
588 + DataProvider<PluralsOrdinalV1>
589 + ?Sized
590 ),
591 prefs: PluralRulesPreferences,
592 options: PluralRulesOptions,
593 ) -> Result<Self, DataError> {
594 match options.rule_type.unwrap_or_default() {
595 PluralRuleType::Cardinal => Self::try_new_cardinal_unstable(provider, prefs),
596 PluralRuleType::Ordinal => Self::try_new_ordinal_unstable(provider, prefs),
597 }
598 }
599
600 icu_provider::gen_buffer_data_constructors!(
601 (prefs: PluralRulesPreferences) -> error: DataError,
602 /// Constructs a new `PluralRulesWithRanges` for a given locale for cardinal numbers using
603 /// compiled data.
604 ///
605 /// See [`PluralRules::try_new_cardinal`] for more information.
606 ///
607 /// # Examples
608 ///
609 /// ```
610 /// use icu::locale::locale;
611 /// use icu::plurals::{PluralCategory, PluralRulesWithRanges};
612 ///
613 /// let rules = PluralRulesWithRanges::try_new_cardinal(locale!("ru").into())
614 /// .expect("locale should be present");
615 ///
616 /// assert_eq!(rules.category_for_range(0_usize, 2_usize), PluralCategory::Few);
617 /// ```
618 functions: [
619 try_new_cardinal,
620 try_new_cardinal_with_buffer_provider,
621 try_new_cardinal_unstable,
622 Self,
623 ]
624 );
625
626 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_cardinal)]
627 pub fn try_new_cardinal_unstable(
628 provider: &(impl DataProvider<PluralsCardinalV1> + DataProvider<PluralsRangesV1> + ?Sized),
629 prefs: PluralRulesPreferences,
630 ) -> Result<Self, DataError> {
631 let rules = PluralRules::try_new_cardinal_unstable(provider, prefs)?;
632
633 PluralRulesWithRanges::try_new_with_rules_unstable(provider, prefs, rules)
634 }
635
636 icu_provider::gen_buffer_data_constructors!(
637 (prefs: PluralRulesPreferences) -> error: DataError,
638 /// Constructs a new `PluralRulesWithRanges` for a given locale for ordinal numbers using
639 /// compiled data.
640 ///
641 /// See [`PluralRules::try_new_ordinal`] for more information.
642 ///
643 /// # Examples
644 ///
645 /// ```
646 /// use icu::locale::locale;
647 /// use icu::plurals::{PluralCategory, PluralRulesWithRanges};
648 ///
649 /// let rules = PluralRulesWithRanges::try_new_ordinal(
650 /// locale!("ru").into(),
651 /// )
652 /// .expect("locale should be present");
653 ///
654 /// assert_eq!(rules.category_for_range(0_usize, 2_usize), PluralCategory::Other);
655 /// ```
656 functions: [
657 try_new_ordinal,
658 try_new_ordinal_with_buffer_provider,
659 try_new_ordinal_unstable,
660 Self,
661 ]
662 );
663
664 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_ordinal)]
665 pub fn try_new_ordinal_unstable(
666 provider: &(impl DataProvider<PluralsOrdinalV1> + DataProvider<PluralsRangesV1> + ?Sized),
667 prefs: PluralRulesPreferences,
668 ) -> Result<Self, DataError> {
669 let rules = PluralRules::try_new_ordinal_unstable(provider, prefs)?;
670
671 PluralRulesWithRanges::try_new_with_rules_unstable(provider, prefs, rules)
672 }
673 }
674
675 #[cfg(feature = "unstable")]
676 impl<R> PluralRulesWithRanges<R>
677 where
678 R: AsRef<PluralRules>,
679 {
680 icu_provider::gen_buffer_data_constructors!(
681 (prefs: PluralRulesPreferences, rules: R) -> error: DataError,
682 /// Constructs a new `PluralRulesWithRanges` for a given locale from an existing
683 /// `PluralRules` (either owned or as a reference) and compiled data.
684 ///
685 /// # ⚠️ Warning
686 ///
687 /// The provided `locale` **MUST** be the same as the locale provided to the constructor
688 /// of `rules`. Otherwise, [`Self::category_for_range`] will return incorrect results.
689 ///
690 /// # Examples
691 ///
692 /// ```
693 /// use icu::locale::locale;
694 /// use icu::plurals::{PluralRulesWithRanges, PluralRules};
695 ///
696 /// let rules = PluralRules::try_new(locale!("en").into(), Default::default())
697 /// .expect("locale should be present");
698 ///
699 /// let _ =
700 /// PluralRulesWithRanges::try_new_with_rules(locale!("en").into(), rules)
701 /// .expect("locale should be present");
702 /// ```
703 functions: [
704 try_new_with_rules,
705 try_new_with_rules_with_buffer_provider,
706 try_new_with_rules_unstable,
707 Self,
708 ]
709 );
710
711 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_with_rules)]
712 pub fn try_new_with_rules_unstable(
713 provider: &(impl DataProvider<PluralsRangesV1> + ?Sized),
714 prefs: PluralRulesPreferences,
715 rules: R,
716 ) -> Result<Self, DataError> {
717 let locale = PluralsRangesV1::make_locale(prefs.locale_preferences);
718 let ranges = provider
719 .load(DataRequest {
720 id: DataIdentifierBorrowed::for_locale(&locale),
721 ..Default::default()
722 })?
723 .payload;
724
725 Ok(Self { rules, ranges })
726 }
727
728 /// Gets a reference to the inner `PluralRules`.
729 ///
730 /// # Examples
731 ///
732 /// ```
733 /// use icu::locale::locale;
734 /// use icu::plurals::{PluralCategory, PluralRulesWithRanges};
735 ///
736 /// let ranges = PluralRulesWithRanges::try_new_cardinal(locale!("en").into())
737 /// .expect("locale should be present");
738 ///
739 /// let rules = ranges.rules();
740 ///
741 /// assert_eq!(rules.category_for(1u8), PluralCategory::One);
742 /// ```
743 pub fn rules(&self) -> &PluralRules {
744 self.rules.as_ref()
745 }
746
747 /// Returns the [`Plural Category`] appropriate for a range.
748 ///
749 /// Note that the returned category is correct only if the range fulfills the following requirements:
750 /// - The start value is strictly less than the end value.
751 /// - Both values are positive.
752 ///
753 /// # Examples
754 ///
755 /// ```
756 /// use icu::locale::locale;
757 /// use icu::plurals::{PluralCategory, PluralOperands, PluralRulesWithRanges};
758 ///
759 /// let ranges = PluralRulesWithRanges::try_new(
760 /// locale!("ro").into(),
761 /// Default::default(),
762 /// )
763 /// .expect("locale should be present");
764 /// let operands: PluralOperands =
765 /// "0.5".parse().expect("parsing to operands should succeed");
766 /// let operands2 = PluralOperands::from(1_usize);
767 ///
768 /// assert_eq!(
769 /// ranges.category_for_range(operands, operands2),
770 /// PluralCategory::Few
771 /// );
772 /// ```
773 ///
774 /// [`Plural Category`]: PluralCategory
775 pub fn category_for_range<S: Into<PluralOperands>, E: Into<PluralOperands>>(
776 &self,
777 start: S,
778 end: E,
779 ) -> PluralCategory {
780 let rules = self.rules.as_ref();
781 let start = rules.category_for(start);
782 let end = rules.category_for(end);
783
784 self.resolve_range(start, end)
785 }
786
787 /// Returns the [`Plural Category`] appropriate for a range from the categories of its endpoints.
788 ///
789 /// Note that the returned category is correct only if the original numeric range fulfills the
790 /// following requirements:
791 /// - The start value is strictly less than the end value.
792 /// - Both values are positive.
793 ///
794 /// # Examples
795 ///
796 /// ```
797 /// use icu::locale::locale;
798 /// use icu::plurals::{
799 /// PluralCategory, PluralRuleType, PluralRulesOptions,
800 /// PluralRulesWithRanges,
801 /// };
802 ///
803 /// let ranges = PluralRulesWithRanges::try_new(
804 /// locale!("sl").into(),
805 /// PluralRulesOptions::default().with_type(PluralRuleType::Ordinal),
806 /// )
807 /// .expect("locale should be present");
808 ///
809 /// assert_eq!(
810 /// ranges.resolve_range(PluralCategory::Other, PluralCategory::One),
811 /// PluralCategory::Few
812 /// );
813 /// ```
814 ///
815 /// [`Plural Category`]: PluralCategory
816 pub fn resolve_range(&self, start: PluralCategory, end: PluralCategory) -> PluralCategory {
817 self.ranges
818 .get()
819 .ranges
820 .get_copied(&UnvalidatedPluralRange::from_range(
821 start.into(),
822 end.into(),
823 ))
824 .map(PluralCategory::from)
825 .unwrap_or(end)
826 }
827 }
828
829 #[derive(Debug, Clone, PartialEq, Eq)]
830 /// A bag of values for different plural cases.
831 pub struct PluralElements<T>(PluralElementsInner<T>);
832
833 #[derive(Debug, Clone, PartialEq, Eq)]
834 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
835 #[cfg_attr(feature = "datagen", derive(serde::Serialize))]
836 pub(crate) struct PluralElementsInner<T> {
837 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
838 zero: Option<T>,
839 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
840 one: Option<T>,
841 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
842 two: Option<T>,
843 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
844 few: Option<T>,
845 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
846 many: Option<T>,
847 other: T,
848 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
849 explicit_zero: Option<T>,
850 #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
851 explicit_one: Option<T>,
852 }
853
854 impl<'a, T, C> zerofrom::ZeroFrom<'a, PluralElementsInner<C>> for PluralElementsInner<T>
855 where
856 T: zerofrom::ZeroFrom<'a, C>,
857 {
858 fn zero_from(other: &'a PluralElementsInner<C>) -> Self {
859 other.as_ref().map(|x| zerofrom::ZeroFrom::zero_from(x))
860 }
861 }
862
863 impl<T> PluralElementsInner<T> {
864 /// Converts from `&PluralElementsInner<T>` to `PluralElementsInner<&T>`.
865 pub fn as_ref(&self) -> PluralElementsInner<&T> {
866 PluralElementsInner {
867 other: &self.other,
868 zero: self.zero.as_ref(),
869 one: self.one.as_ref(),
870 two: self.two.as_ref(),
871 few: self.few.as_ref(),
872 many: self.many.as_ref(),
873 explicit_zero: self.explicit_zero.as_ref(),
874 explicit_one: self.explicit_one.as_ref(),
875 }
876 }
877
878 pub fn map<B, F: FnMut(T) -> B>(self, mut f: F) -> PluralElementsInner<B> {
879 let Ok(x) = self.try_map(move |x| Ok::<B, Infallible>(f(x)));
880 x
881 }
882
883 pub fn try_map<B, E, F: FnMut(T) -> Result<B, E>>(
884 self,
885 mut f: F,
886 ) -> Result<PluralElementsInner<B>, E> {
887 Ok(PluralElementsInner {
888 other: f(self.other)?,
889 zero: self.zero.map(&mut f).transpose()?,
890 one: self.one.map(&mut f).transpose()?,
891 two: self.two.map(&mut f).transpose()?,
892 few: self.few.map(&mut f).transpose()?,
893 many: self.many.map(&mut f).transpose()?,
894 explicit_zero: self.explicit_zero.map(&mut f).transpose()?,
895 explicit_one: self.explicit_one.map(&mut f).transpose()?,
896 })
897 }
898 }
899
900 impl<'a, T, C> zerofrom::ZeroFrom<'a, PluralElements<C>> for PluralElements<T>
901 where
902 T: zerofrom::ZeroFrom<'a, C>,
903 {
904 fn zero_from(other: &'a PluralElements<C>) -> Self {
905 other.as_ref().map(|x| zerofrom::ZeroFrom::zero_from(x))
906 }
907 }
908
909 impl<T> PluralElements<T> {
910 /// Creates a new [`PluralElements`] with the given default value.
911 pub fn new(other: T) -> Self {
912 Self(PluralElementsInner {
913 other,
914 zero: None,
915 one: None,
916 two: None,
917 few: None,
918 many: None,
919 explicit_zero: None,
920 explicit_one: None,
921 })
922 }
923
924 /// The value for [`PluralCategory::Zero`]
925 pub fn zero(&self) -> &T {
926 self.0.zero.as_ref().unwrap_or(&self.0.other)
927 }
928
929 /// The value for [`PluralCategory::One`]
930 pub fn one(&self) -> &T {
931 self.0.one.as_ref().unwrap_or(&self.0.other)
932 }
933
934 /// The value for [`PluralCategory::Two`]
935 pub fn two(&self) -> &T {
936 self.0.two.as_ref().unwrap_or(&self.0.other)
937 }
938
939 /// The value for [`PluralCategory::Few`]
940 pub fn few(&self) -> &T {
941 self.0.few.as_ref().unwrap_or(&self.0.other)
942 }
943
944 /// The value for [`PluralCategory::Many`]
945 pub fn many(&self) -> &T {
946 self.0.many.as_ref().unwrap_or(&self.0.other)
947 }
948
949 /// The value for [`PluralCategory::Other`]
950 pub fn other(&self) -> &T {
951 &self.0.other
952 }
953
954 /// If the only variant is `other`, returns `Some(other)`.
955 ///
956 /// # Examples
957 ///
958 /// ```
959 /// use icu::plurals::PluralElements;
960 ///
961 /// let mut only_other = PluralElements::new("abc").with_one_value(Some("abc"));
962 /// assert_eq!(only_other.try_into_other(), Some("abc"));
963 ///
964 /// let mut multi = PluralElements::new("abc").with_one_value(Some("def"));
965 /// assert_eq!(multi.try_into_other(), None);
966 /// ```
967 pub fn try_into_other(self) -> Option<T> {
968 match self.0 {
969 PluralElementsInner {
970 zero: None,
971 one: None,
972 two: None,
973 few: None,
974 many: None,
975 other,
976 explicit_zero: None,
977 explicit_one: None,
978 } => Some(other),
979 _ => None,
980 }
981 }
982
983 /// The value used when the [`PluralOperands`] are exactly 0.
984 pub fn explicit_zero(&self) -> Option<&T> {
985 self.0.explicit_zero.as_ref()
986 }
987
988 /// The value used when the [`PluralOperands`] are exactly 1.
989 pub fn explicit_one(&self) -> Option<&T> {
990 self.0.explicit_one.as_ref()
991 }
992
993 /// Applies a function `f` to convert all values to another type.
994 ///
995 /// # Examples
996 ///
997 /// ```
998 /// use icu::plurals::PluralElements;
999 ///
1000 /// let x = PluralElements::new(11).with_one_value(Some(15));
1001 /// let y = x.map(|i| i * 2);
1002 ///
1003 /// assert_eq!(*y.other(), 22);
1004 /// assert_eq!(*y.one(), 30);
1005 /// ```
1006 pub fn map<B, F: FnMut(T) -> B>(self, f: F) -> PluralElements<B> {
1007 PluralElements(self.0.map(f))
1008 }
1009
1010 /// Applies a function `f` to convert all values to another type,
1011 /// propagating a possible error.
1012 pub fn try_map<B, E, F: FnMut(T) -> Result<B, E>>(self, f: F) -> Result<PluralElements<B>, E> {
1013 self.0.try_map(f).map(PluralElements)
1014 }
1015
1016 /// Immutably applies a function `f` to each value.
1017 pub fn for_each<F: FnMut(&T)>(&self, mut f: F) {
1018 #[expect(clippy::unit_arg)] // consistency with map and one-liner
1019 let Ok(()) = self.try_for_each(move |x| Ok::<(), Infallible>(f(x)));
1020 }
1021
1022 /// Immutably applies a function `f` to each value,
1023 /// propagating a possible error.
1024 pub fn try_for_each<E, F: FnMut(&T) -> Result<(), E>>(&self, mut f: F) -> Result<(), E> {
1025 // Use a structure to create compile errors if another field is added
1026 let _ = PluralElements(PluralElementsInner {
1027 other: f(&self.0.other)?,
1028 zero: self.0.zero.as_ref().map(&mut f).transpose()?,
1029 one: self.0.one.as_ref().map(&mut f).transpose()?,
1030 two: self.0.two.as_ref().map(&mut f).transpose()?,
1031 few: self.0.few.as_ref().map(&mut f).transpose()?,
1032 many: self.0.many.as_ref().map(&mut f).transpose()?,
1033 explicit_zero: self.0.explicit_zero.as_ref().map(&mut f).transpose()?,
1034 explicit_one: self.0.explicit_one.as_ref().map(&mut f).transpose()?,
1035 });
1036 Ok(())
1037 }
1038
1039 /// Mutably applies a function `f` to each value.
1040 ///
1041 /// # Examples
1042 ///
1043 /// ```
1044 /// use icu::plurals::PluralElements;
1045 ///
1046 /// let mut x = PluralElements::new(11).with_one_value(Some(15));
1047 /// x.for_each_mut(|i| *i *= 2);
1048 ///
1049 /// assert_eq!(*x.other(), 22);
1050 /// assert_eq!(*x.one(), 30);
1051 /// ```
1052 pub fn for_each_mut<F: FnMut(&mut T)>(&mut self, mut f: F) {
1053 #[expect(clippy::unit_arg)] // consistency with map and one-liner
1054 let Ok(()) = self.try_for_each_mut(move |x| Ok::<(), Infallible>(f(x)));
1055 }
1056
1057 /// Mutably applies a function `f` to each value,
1058 /// propagating a possible error.
1059 pub fn try_for_each_mut<E, F: FnMut(&mut T) -> Result<(), E>>(
1060 &mut self,
1061 mut f: F,
1062 ) -> Result<(), E> {
1063 // Use a structure to create compile errors if another field is added
1064 let _ = PluralElements(PluralElementsInner {
1065 other: f(&mut self.0.other)?,
1066 zero: self.0.zero.as_mut().map(&mut f).transpose()?,
1067 one: self.0.one.as_mut().map(&mut f).transpose()?,
1068 two: self.0.two.as_mut().map(&mut f).transpose()?,
1069 few: self.0.few.as_mut().map(&mut f).transpose()?,
1070 many: self.0.many.as_mut().map(&mut f).transpose()?,
1071 explicit_zero: self.0.explicit_zero.as_mut().map(&mut f).transpose()?,
1072 explicit_one: self.0.explicit_one.as_mut().map(&mut f).transpose()?,
1073 });
1074 Ok(())
1075 }
1076
1077 /// Converts from `&PluralElements<T>` to `PluralElements<&T>`.
1078 pub fn as_ref(&self) -> PluralElements<&T> {
1079 PluralElements(self.0.as_ref())
1080 }
1081
1082 /// Returns the value for the given [`PluralOperands`] and [`PluralRules`].
1083 ///
1084 /// # Example
1085 /// ```
1086 /// use icu::locale::locale;
1087 /// use icu::plurals::{PluralCategory, PluralElements, PluralRules};
1088 ///
1089 /// let rules = PluralRules::try_new_cardinal(locale!("fr").into()).unwrap();
1090 ///
1091 /// let elements = PluralElements::new("chats").with_one_value(Some("chat"));
1092 ///
1093 /// assert_eq!(*elements.get(0_usize.into(), &rules), "chat");
1094 /// assert_eq!(*elements.get(1_usize.into(), &rules), "chat");
1095 /// assert_eq!(*elements.get(12_usize.into(), &rules), "chats");
1096 /// ```
1097 pub fn get<'a>(&'a self, op: PluralOperands, rules: &PluralRules) -> &'a T {
1098 let category = rules.category_for(op);
1099
1100 if op.is_exactly_zero()
1101 && let Some(value) = self.0.explicit_zero.as_ref()
1102 {
1103 return value;
1104 }
1105
1106 if op.is_exactly_one()
1107 && let Some(value) = self.0.explicit_one.as_ref()
1108 {
1109 return value;
1110 }
1111
1112 match category {
1113 PluralCategory::Zero => self.0.zero.as_ref(),
1114 PluralCategory::One => self.0.one.as_ref(),
1115 PluralCategory::Two => self.0.two.as_ref(),
1116 PluralCategory::Few => self.0.few.as_ref(),
1117 PluralCategory::Many => self.0.many.as_ref(),
1118 PluralCategory::Other => return &self.0.other,
1119 }
1120 .unwrap_or(&self.0.other)
1121 }
1122 }
1123
1124 impl<T: PartialEq> PluralElements<T> {
1125 /// Sets the value for [`PluralCategory::Zero`].
1126 pub fn with_zero_value(self, zero: Option<T>) -> Self {
1127 Self(PluralElementsInner {
1128 zero: zero.filter(|t| *t != self.0.other),
1129 ..self.0
1130 })
1131 }
1132
1133 /// Sets the value for [`PluralCategory::One`].
1134 pub fn with_one_value(self, one: Option<T>) -> Self {
1135 Self(PluralElementsInner {
1136 one: one.filter(|t| *t != self.0.other),
1137 ..self.0
1138 })
1139 }
1140
1141 /// Sets the value for [`PluralCategory::Two`].
1142 pub fn with_two_value(self, two: Option<T>) -> Self {
1143 Self(PluralElementsInner {
1144 two: two.filter(|t| *t != self.0.other),
1145 ..self.0
1146 })
1147 }
1148
1149 /// Sets the value for [`PluralCategory::Few`].
1150 pub fn with_few_value(self, few: Option<T>) -> Self {
1151 Self(PluralElementsInner {
1152 few: few.filter(|t| *t != self.0.other),
1153 ..self.0
1154 })
1155 }
1156
1157 /// Sets the value for [`PluralCategory::Many`].
1158 pub fn with_many_value(self, many: Option<T>) -> Self {
1159 Self(PluralElementsInner {
1160 many: many.filter(|t| *t != self.0.other),
1161 ..self.0
1162 })
1163 }
1164
1165 /// Sets the value for explicit 0.
1166 pub fn with_explicit_zero_value(self, explicit_zero: Option<T>) -> Self {
1167 Self(PluralElementsInner {
1168 explicit_zero,
1169 ..self.0
1170 })
1171 }
1172
1173 /// Sets the value for explicit 1.
1174 pub fn with_explicit_one_value(self, explicit_one: Option<T>) -> Self {
1175 Self(PluralElementsInner {
1176 explicit_one,
1177 ..self.0
1178 })
1179 }
1180 }