Debian Codegraph @

debian/rust-vendor/icu_plurals/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 // Provider structs must be stable
6 #![allow(clippy::exhaustive_structs, clippy::exhaustive_enums)]
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 use crate::provider::rules::runtime::ast::Rule;
19 use crate::{PluralCategory, PluralElements, PluralElementsInner, PluralOperands, PluralRules};
20 use alloc::borrow::{Cow, ToOwned};
21 use alloc::boxed::Box;
22 use alloc::vec::Vec;
23 use core::fmt;
24 use core::marker::PhantomData;
25 use icu_provider::prelude::*;
26 use yoke::Yokeable;
27 use zerofrom::ZeroFrom;
28 use zerovec::VarZeroSlice;
29 use zerovec::ule::AsULE;
30 use zerovec::ule::EncodeAsVarULE;
31 use zerovec::ule::ULE;
32 use zerovec::ule::UleError;
33 use zerovec::ule::VarULE;
34 use zerovec::ule::vartuple::VarTuple;
35 use zerovec::ule::vartuple::VarTupleULE;
36
37 pub mod rules;
38
39 #[cfg(feature = "compiled_data")]
40 #[derive(Debug)]
41 /// Baked data
42 ///
43 /// <div class="stab unstable">
44 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
45 /// including in SemVer minor releases. In particular, the `DataProvider` implementations are only
46 /// guaranteed to match with this version's `*_unstable` providers. Use with caution.
47 /// </div>
48 pub struct Baked;
49
50 #[cfg(feature = "compiled_data")]
51 #[allow(unused_imports)]
52 const _: () = {
53 use icu_plurals_data::*;
54 mod icu {
55 pub use crate as plurals;
56 }
57
58 make_provider!(Baked);
59 impl_plurals_cardinal_v1!(Baked);
60 impl_plurals_ordinal_v1!(Baked);
61 #[cfg(feature = "unstable")]
62 impl_plurals_ranges_v1!(Baked);
63 };
64
65 icu_provider::data_marker!(
66 /// Data for cardinal classification
67 PluralsCardinalV1,
68 "plurals/cardinal/v1",
69 PluralRulesData<'static>,
70 );
71
72 icu_provider::data_marker!(
73 /// Data for ordinal classification
74 PluralsOrdinalV1,
75 "plurals/ordinal/v1",
76 PluralRulesData<'static>,
77 );
78
79 #[cfg(feature = "unstable")]
80 icu_provider::data_marker!(
81 /// Data for plural range formatting
82 PluralsRangesV1,
83 "plurals/ranges/v1",
84 PluralRanges<'static>
85 );
86
87 #[cfg(feature = "datagen")]
88 /// The latest minimum set of markers required by this component.
89 pub const MARKERS: &[DataMarkerInfo] = &[
90 PluralsCardinalV1::INFO,
91 PluralsOrdinalV1::INFO,
92 #[cfg(feature = "unstable")]
93 PluralsRangesV1::INFO,
94 ];
95
96 /// Plural rule strings conforming to UTS 35 syntax. Includes separate fields for five of the six
97 /// standard plural forms. If none of the rules match, the "other" category is assumed.
98 ///
99 /// More information: <https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules>
100 ///
101 /// <div class="stab unstable">
102 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
103 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
104 /// to be stable, their Rust representation might not be. Use with caution.
105 /// </div>
106 #[derive(Default, Clone, PartialEq, Debug, Yokeable, ZeroFrom)]
107 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
108 #[cfg_attr(feature = "datagen", databake(path = icu_plurals::provider))]
109 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
110 pub struct PluralRulesData<'data> {
111 /// Rule that matches [`PluralCategory::Zero`], or `None` if not present.
112 #[cfg_attr(feature = "serde", serde(borrow))]
113 pub zero: Option<Rule<'data>>,
114 /// Rule that matches [`PluralCategory::One`], or `None` if not present.
115 #[cfg_attr(feature = "serde", serde(borrow))]
116 pub one: Option<Rule<'data>>,
117 /// Rule that matches [`PluralCategory::Two`], or `None` if not present.
118 #[cfg_attr(feature = "serde", serde(borrow))]
119 pub two: Option<Rule<'data>>,
120 /// Rule that matches [`PluralCategory::Few`], or `None` if not present.
121 #[cfg_attr(feature = "serde", serde(borrow))]
122 pub few: Option<Rule<'data>>,
123 /// Rule that matches [`PluralCategory::Many`], or `None` if not present.
124 #[cfg_attr(feature = "serde", serde(borrow))]
125 pub many: Option<Rule<'data>>,
126 }
127
128 icu_provider::data_struct!(
129 PluralRulesData<'_>,
130 #[cfg(feature = "datagen")]
131 );
132
133 #[cfg(feature = "unstable")]
134 pub use ranges::*;
135
136 #[cfg(feature = "unstable")]
137 mod ranges {
138 use super::*;
139 use zerovec::ZeroMap;
140
141 /// [`PluralCategory`] but serializable as provider data.
142 ///
143 /// <div class="stab unstable">
144 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
145 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
146 /// to be stable, their Rust representation might not be. Use with caution.
147 /// </div>
148 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Ord, PartialOrd)]
149 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
150 #[cfg_attr(feature = "datagen", databake(path = icu_plurals::provider))]
151 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
152 #[zerovec::make_ule(RawPluralCategoryULE)]
153 #[repr(u8)]
154 #[cfg_attr(
155 any(feature = "datagen", feature = "serde"),
156 serde(rename_all = "lowercase")
157 )]
158 pub enum RawPluralCategory {
159 /// CLDR "other" plural category.
160 Other = 0,
161 /// CLDR "zero" plural category.
162 Zero = 1,
163 /// CLDR "one" plural category.
164 One = 2,
165 /// CLDR "two" plural category.
166 Two = 3,
167 /// CLDR "few" plural category.
168 Few = 4,
169 /// CLDR "many" plural category.
170 Many = 5,
171 }
172
173 impl RawPluralCategory {
174 /// Gets the corresponding variant string of this `RawPluralCategory`.
175 #[cfg(any(feature = "datagen", feature = "serde"))]
176 const fn as_str(self) -> &'static str {
177 match self {
178 Self::Other => "other",
179 Self::Zero => "zero",
180 Self::One => "one",
181 Self::Two => "two",
182 Self::Few => "few",
183 Self::Many => "many",
184 }
185 }
186 }
187
188 impl From<RawPluralCategory> for PluralCategory {
189 fn from(value: RawPluralCategory) -> Self {
190 match value {
191 RawPluralCategory::Other => PluralCategory::Other,
192 RawPluralCategory::Zero => PluralCategory::Zero,
193 RawPluralCategory::One => PluralCategory::One,
194 RawPluralCategory::Two => PluralCategory::Two,
195 RawPluralCategory::Few => PluralCategory::Few,
196 RawPluralCategory::Many => PluralCategory::Many,
197 }
198 }
199 }
200
201 impl From<PluralCategory> for RawPluralCategory {
202 fn from(value: PluralCategory) -> Self {
203 match value {
204 PluralCategory::Zero => RawPluralCategory::Zero,
205 PluralCategory::One => RawPluralCategory::One,
206 PluralCategory::Two => RawPluralCategory::Two,
207 PluralCategory::Few => RawPluralCategory::Few,
208 PluralCategory::Many => RawPluralCategory::Many,
209 PluralCategory::Other => RawPluralCategory::Other,
210 }
211 }
212 }
213
214 /// An `u8` that is expected to be a plural range, but does not enforce this invariant.
215 ///
216 /// <div class="stab unstable">
217 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
218 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
219 /// to be stable, their Rust representation might not be. Use with caution.
220 /// </div>
221 #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Ord, PartialOrd)]
222 #[cfg_attr(feature = "datagen", derive(databake::Bake))]
223 #[cfg_attr(feature = "datagen", databake(path = icu_plurals::provider))]
224 #[zerovec::make_ule(UnvalidatedPluralRangeULE)]
225 pub struct UnvalidatedPluralRange(pub u8);
226
227 impl UnvalidatedPluralRange {
228 /// Creates a new `UnvalidatedPluralRange` from a category range.
229 pub fn from_range(start: RawPluralCategory, end: RawPluralCategory) -> Self {
230 let start = start as u8;
231 let end = end as u8;
232
233 debug_assert!(start < 16);
234 debug_assert!(end < 16);
235
236 let range = (start << 4) | end;
237
238 Self(range)
239 }
240 }
241
242 #[cfg(feature = "datagen")]
243 impl serde::Serialize for UnvalidatedPluralRange {
244 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
245 where
246 S: serde::Serializer,
247 {
248 use serde::ser::Error;
249
250 struct PrettyPrinter(RawPluralCategory, RawPluralCategory);
251
252 impl fmt::Display for PrettyPrinter {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 f.write_str(self.0.as_str())?;
255 f.write_str("--")?;
256 f.write_str(self.1.as_str())
257 }
258 }
259
260 if serializer.is_human_readable() {
261 let start = RawPluralCategory::new_from_u8(self.0 >> 4)
262 .ok_or_else(|| S::Error::custom("invalid tag in UnvalidatedPluralRange"))?;
263 let end = RawPluralCategory::new_from_u8(self.0 & 0x0F)
264 .ok_or_else(|| S::Error::custom("invalid tag in UnvalidatedPluralRange"))?;
265 serializer.collect_str(&PrettyPrinter(start, end))
266 } else {
267 self.0.serialize(serializer)
268 }
269 }
270 }
271
272 #[cfg(feature = "serde")]
273 impl<'de> serde::Deserialize<'de> for UnvalidatedPluralRange {
274 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
275 where
276 D: serde::Deserializer<'de>,
277 {
278 use serde::de::{Error, Visitor};
279
280 struct HumanReadableVisitor;
281
282 impl Visitor<'_> for HumanReadableVisitor {
283 type Value = UnvalidatedPluralRange;
284
285 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
286 write!(
287 formatter,
288 "a plural range of the form <PluralCategory>-<PluralCategory>",
289 )
290 }
291
292 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
293 where
294 E: Error,
295 {
296 const VARIANTS: [&str; 6] = [
297 RawPluralCategory::Other.as_str(),
298 RawPluralCategory::Zero.as_str(),
299 RawPluralCategory::One.as_str(),
300 RawPluralCategory::Two.as_str(),
301 RawPluralCategory::Few.as_str(),
302 RawPluralCategory::Many.as_str(),
303 ];
304
305 let (start, end) = v
306 .split_once("--")
307 .ok_or_else(|| E::custom("expected token `--` in plural range"))?;
308
309 let start = PluralCategory::get_for_cldr_string(start)
310 .ok_or_else(|| E::unknown_variant(start, &VARIANTS))?;
311 let end = PluralCategory::get_for_cldr_string(end)
312 .ok_or_else(|| E::unknown_variant(end, &VARIANTS))?;
313
314 Ok(UnvalidatedPluralRange::from_range(start.into(), end.into()))
315 }
316 }
317
318 if deserializer.is_human_readable() {
319 deserializer.deserialize_str(HumanReadableVisitor)
320 } else {
321 Ok(Self(<u8>::deserialize(deserializer)?))
322 }
323 }
324 }
325
326 /// Plural categories for ranges.
327 ///
328 /// Obtains the plural category of a range from the categories of its endpoints. It is required that
329 /// the start value must be strictly less than the end value, and both values must be strictly positive.
330 ///
331 /// More information: <https://unicode.org/reports/tr35/tr35-numbers.html#Plural_Ranges>
332 ///
333 /// <div class="stab unstable">
334 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
335 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
336 /// to be stable, their Rust representation might not be. Use with caution.
337 /// </div>
338 #[derive(Clone, PartialEq, Debug, Yokeable, ZeroFrom)]
339 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
340 #[cfg_attr(feature = "datagen", databake(path = icu_plurals::provider))]
341 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
342 #[yoke(prove_covariance_manually)]
343 pub struct PluralRanges<'data> {
344 /// Map between the categories of the endpoints of a range and its corresponding
345 /// category.
346 ///
347 /// This is roughly equivalent to a `BTreeMap<(PluralCategory, PluralCategory), PluralCategory>`,
348 /// where the key is `(start category, end category)`.
349 #[cfg_attr(feature = "serde", serde(borrow))]
350 pub ranges: ZeroMap<'data, UnvalidatedPluralRange, RawPluralCategory>,
351 }
352
353 icu_provider::data_struct!(
354 PluralRanges<'_>,
355 #[cfg(feature = "datagen")]
356 );
357 }
358
359 /// A sized packed [`PluralElements`] suitable for use in data structs.
360 ///
361 /// This type has the following limitations:
362 ///
363 /// 1. It only supports `str`
364 /// 2. It does not implement [`VarULE`] so it can't be used in a [`VarZeroSlice`]
365 /// 3. It always serializes the [`FourBitMetadata`] as 0
366 ///
367 /// Use [`PluralElementsPackedULE`] directly if you need these additional features.
368 #[derive(Debug, PartialEq, Yokeable, ZeroFrom)]
369 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
370 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
371 #[cfg_attr(feature = "datagen", databake(path = icu_plurals::provider))]
372 #[cfg_attr(
373 feature = "serde",
374 serde(
375 transparent,
376 bound(
377 serialize = "V: serde::Serialize + PartialEq",
378 deserialize = "Box<PluralElementsPackedULE<V>>: serde::Deserialize<'de>"
379 )
380 )
381 )]
382 pub struct PluralElementsPackedCow<'data, V: VarULE + ?Sized> {
383 /// The encoded elements.
384 #[cfg_attr(
385 feature = "serde",
386 serde(
387 borrow,
388 deserialize_with = "deserialize_plural_elements_packed_cow::<_, V>"
389 )
390 )]
391 pub elements: Cow<'data, PluralElementsPackedULE<V>>,
392 }
393
394 impl<T: VarULE + ?Sized> icu_provider::ule::MaybeAsVarULE for PluralElementsPackedCow<'_, T> {
395 type EncodedStruct = PluralElementsPackedULE<T>;
396 }
397
398 #[cfg(feature = "datagen")]
399 impl<T: VarULE + ?Sized> icu_provider::ule::MaybeEncodeAsVarULE for PluralElementsPackedCow<'_, T> {
400 type EncodeableStruct<'b>
401 = &'b PluralElementsPackedULE<T>
402 where
403 Self: 'b;
404 fn maybe_as_encodeable<'b>(&'b self) -> Option<Self::EncodeableStruct<'b>> {
405 Some(&self.elements)
406 }
407 }
408
409 impl<'a, V: VarULE + ?Sized> ZeroFrom<'a, PluralElementsPackedULE<V>>
410 for PluralElementsPackedCow<'a, V>
411 {
412 fn zero_from(other: &'a PluralElementsPackedULE<V>) -> Self {
413 Self {
414 elements: Cow::Borrowed(other),
415 }
416 }
417 }
418
419 /// A bitpacked DST for [`PluralElements`].
420 ///
421 /// Can be put in a [`Cow`] or a [`VarZeroSlice`].
422 #[derive(PartialEq, Eq)]
423 #[repr(transparent)]
424 pub struct PluralElementsPackedULE<V: VarULE + ?Sized> {
425 _v: PhantomData<V>,
426 /// Invariant Representation:
427 ///
428 /// First byte: `d...mmmm`
429 /// - `d` = 0 if singleton, 1 if a map
430 /// - `...` = padding, should be 0
431 /// - `mmmm` = [`FourBitMetadata`] for the default value
432 ///
433 /// If d is 0:
434 /// - Remainder: the default (plural "other") value `V`
435 ///
436 /// If d is 1:
437 /// - Second byte: L = the length of `V`
438 /// - Bytes 2..(2+L): the default (plural "other") value `V`
439 /// - Remainder: [`PluralElementsTupleSliceVarULE`]
440 bytes: [u8],
441 }
442
443 impl<V: VarULE + fmt::Debug + ?Sized> fmt::Debug for PluralElementsPackedULE<V> {
444 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
445 let unpacked = self.as_parts();
446 f.debug_struct("PluralElementsPackedULE")
447 .field("parts", &unpacked)
448 .field("bytes", &&self.bytes)
449 .finish()
450 }
451 }
452
453 impl<V: VarULE + ?Sized> ToOwned for PluralElementsPackedULE<V> {
454 type Owned = Box<PluralElementsPackedULE<V>>;
455 fn to_owned(&self) -> Self::Owned {
456 self.to_boxed()
457 }
458 }
459
460 // Safety (based on the safety checklist on the VarULE trait):
461 // 1. PluralElementsPackedULE does not include any uninitialized or padding bytes: it is transparent over a VarULE type ([u8])
462 // 2. PluralElementsPackedULE is aligned to 1 byte: it is transparent over a VarULE type ([u8])
463 // 3. The impl of `validate_bytes()` returns an error if any byte is not valid.
464 // 4. The impl of `validate_bytes()` returns an error if the slice cannot be used in its entirety
465 // 5. The impl of `from_bytes_unchecked()` returns a reference to the same data.
466 // 6. `parse_bytes()` is equivalent to `validate_bytes()` followed by `from_bytes_unchecked()`
467 // 7. byte equality is semantic equality
468 unsafe impl<V> VarULE for PluralElementsPackedULE<V>
469 where
470 V: VarULE + ?Sized,
471 {
472 fn validate_bytes(bytes: &[u8]) -> Result<(), UleError> {
473 let unpacked_bytes =
474 Self::unpack_bytes(bytes).ok_or_else(|| UleError::length::<Self>(bytes.len()))?;
475 // The high bit of lead_byte was read in unpack_bytes.
476 // Bits 0-3 are FourBitMetadata.
477 // We expect bits 4-6 to be padding.
478 if unpacked_bytes.lead_byte & 0x70 != 0 {
479 return Err(UleError::parse::<Self>());
480 }
481 // Now validate the two variable-length slices.
482 V::validate_bytes(unpacked_bytes.v_bytes)?;
483 if let Some(specials_bytes) = unpacked_bytes.specials_bytes {
484 PluralElementsTupleSliceVarULE::<V>::validate_bytes(specials_bytes)?;
485 }
486 Ok(())
487 }
488
489 unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
490 // Safety: the bytes are valid by trait invariant, and we are transparent over bytes
491 unsafe { &*(bytes as *const [u8] as *const Self) }
492 }
493 }
494
495 impl<V> PluralElementsPackedULE<V>
496 where
497 V: VarULE + ?Sized,
498 {
499 /// Casts a byte slice to a [`PluralElementsPackedULE`].
500 ///
501 /// # Safety
502 ///
503 /// The bytes must be valid according to [`PluralElementsPackedULE::validate_bytes`].
504 pub const unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
505 // Safety: the bytes are valid by trait invariant, and we are transparent over bytes
506 unsafe { &*(bytes as *const [u8] as *const Self) }
507 }
508
509 /// Returns a tuple with:
510 /// 1. The lead byte
511 /// 2. Bytes corresponding to the default V
512 /// 3. Bytes corresponding to the specials slice, if present
513 #[inline]
514 fn unpack_bytes(bytes: &[u8]) -> Option<PluralElementsUnpackedBytes<'_>> {
515 let (lead_byte, remainder) = bytes.split_first()?;
516 if lead_byte & 0x80 == 0 {
517 Some(PluralElementsUnpackedBytes {
518 lead_byte: *lead_byte,
519 v_bytes: remainder,
520 specials_bytes: None,
521 })
522 } else {
523 let (second_byte, remainder) = remainder.split_first()?;
524 let (v_bytes, remainder) = remainder.split_at_checked(*second_byte as usize)?;
525 Some(PluralElementsUnpackedBytes {
526 lead_byte: *lead_byte,
527 v_bytes,
528 specials_bytes: Some(remainder),
529 })
530 }
531 }
532
533 /// Unpacks this structure into the default value and the optional list of specials.
534 fn as_parts(&self) -> PluralElementsUnpacked<'_, V> {
535 // Safety: the bytes are valid by invariant
536 let unpacked_bytes = unsafe { Self::unpack_bytes(&self.bytes).unwrap_unchecked() };
537 let metadata = FourBitMetadata(unpacked_bytes.lead_byte & 0x0F);
538 // Safety: the bytes are valid by invariant
539 let default = unsafe { V::from_bytes_unchecked(unpacked_bytes.v_bytes) };
540 #[expect(clippy::manual_map)] // more explicit with the unsafe code
541 let specials = if let Some(specials_bytes) = unpacked_bytes.specials_bytes {
542 // Safety: the bytes are valid by invariant
543 Some(unsafe {
544 PluralElementsTupleSliceVarULE::<V>::from_bytes_unchecked(specials_bytes)
545 })
546 } else {
547 None
548 };
549 PluralElementsUnpacked {
550 default: (metadata, default),
551 specials,
552 }
553 }
554
555 /// Returns the value for the given [`PluralOperands`] and [`PluralRules`].
556 pub fn get<'a>(&'a self, op: PluralOperands, rules: &PluralRules) -> (FourBitMetadata, &'a V) {
557 let parts = self.as_parts();
558
559 let category = rules.category_for(op);
560
561 match parts.specials {
562 Some(specials) => {
563 if op.is_exactly_zero()
564 && let Some(value) = get_special(specials, PluralElementsKeys::ExplicitZero)
565 {
566 return value;
567 }
568 if op.is_exactly_one()
569 && let Some(value) = get_special(specials, PluralElementsKeys::ExplicitOne)
570 {
571 return value;
572 }
573 match category {
574 PluralCategory::Zero => Some(PluralElementsKeys::Zero),
575 PluralCategory::One => Some(PluralElementsKeys::One),
576 PluralCategory::Two => Some(PluralElementsKeys::Two),
577 PluralCategory::Few => Some(PluralElementsKeys::Few),
578 PluralCategory::Many => Some(PluralElementsKeys::Many),
579 PluralCategory::Other => None,
580 }
581 .and_then(|key| get_special(specials, key))
582 }
583 None => None,
584 }
585 .unwrap_or(parts.default)
586 }
587
588 /// Recovers the [`PluralElements`] corresponding to this packed structure.
589 #[cfg(feature = "datagen")]
590 pub fn decode(&self) -> PluralElements<(FourBitMetadata, &V)> {
591 PluralElements(PluralElementsInner::from_packed(self))
592 }
593
594 /// Returns the value for the default ("other") plural variant.
595 pub fn get_default(&self) -> (FourBitMetadata, &V) {
596 self.as_parts().default
597 }
598 }
599
600 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
601 #[zerovec::make_ule(PluralCategoryULE)]
602 #[repr(u8)]
603 #[cfg_attr(feature = "datagen", derive(serde::Serialize))]
604 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
605 enum PluralElementsKeys {
606 Zero = 0,
607 One = 1,
608 Two = 2,
609 Few = 3,
610 Many = 4,
611 ExplicitZero = 5,
612 ExplicitOne = 6,
613 }
614
615 impl<T> PluralElementsInner<T>
616 where
617 T: PartialEq,
618 {
619 fn get_specials_tuples(&self) -> impl Iterator<Item = (PluralElementsKeys, &T)> {
620 [
621 self.zero
622 .as_ref()
623 .filter(|&p| *p != self.other)
624 .map(|s| (PluralElementsKeys::Zero, s)),
625 self.one
626 .as_ref()
627 .filter(|&p| *p != self.other)
628 .map(|s| (PluralElementsKeys::One, s)),
629 self.two
630 .as_ref()
631 .filter(|&p| *p != self.other)
632 .map(|s| (PluralElementsKeys::Two, s)),
633 self.few
634 .as_ref()
635 .filter(|&p| *p != self.other)
636 .map(|s| (PluralElementsKeys::Few, s)),
637 self.many
638 .as_ref()
639 .filter(|&p| *p != self.other)
640 .map(|s| (PluralElementsKeys::Many, s)),
641 self.explicit_zero
642 .as_ref()
643 .filter(|&p| *p != self.other)
644 .map(|s| (PluralElementsKeys::ExplicitZero, s)),
645 self.explicit_one
646 .as_ref()
647 .filter(|&p| *p != self.other)
648 .map(|s| (PluralElementsKeys::ExplicitOne, s)),
649 ]
650 .into_iter()
651 .flatten()
652 }
653 }
654
655 /// Four bits of metadata that are stored and retrieved with the plural elements.
656 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
657 #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
658 #[repr(transparent)]
659 pub struct FourBitMetadata(u8);
660
661 impl FourBitMetadata {
662 /// Creates a [`FourBitMetadata`] if the given value fits in 4 bits.
663 pub fn try_from_byte(byte: u8) -> Option<Self> {
664 if byte <= 0x0F { Some(Self(byte)) } else { None }
665 }
666
667 /// Creates a [`FourBitMetadata`] with a zero value.
668 pub const fn zero() -> Self {
669 Self(0)
670 }
671
672 /// Gets the value out of a [`FourBitMetadata`].
673 pub const fn get(self) -> u8 {
674 self.0
675 }
676 }
677
678 /// A pair of [`PluralElementsKeys`] and [`FourBitMetadata`].
679 #[derive(Debug, Copy, Clone)]
680 struct PluralCategoryAndMetadata {
681 pub plural_category: PluralElementsKeys,
682 pub metadata: FourBitMetadata,
683 }
684
685 struct PluralCategoryAndMetadataUnpacked {
686 pub plural_category_byte: u8,
687 pub metadata_byte: u8,
688 }
689
690 /// Bitpacked struct for [`PluralCategoryAndMetadata`].
691 #[derive(Debug, Copy, Clone)]
692 #[repr(transparent)]
693 struct PluralCategoryAndMetadataPackedULE(
694 /// Representation: `ppppmmmm`
695 /// - `pppp` are a valid [`PluralElementsKeys`]
696 /// - `mmmm` are a valid [`FourBitMetadata`]
697 ///
698 /// The valid values are determined by their respective types.
699 u8,
700 );
701
702 impl From<PluralCategoryAndMetadata> for PluralCategoryAndMetadataPackedULE {
703 fn from(value: PluralCategoryAndMetadata) -> Self {
704 let byte = ((value.plural_category as u8) << 4) | value.metadata.get();
705 debug_assert!(
706 PluralCategoryAndMetadata::try_from_unpacked(Self::unpack_byte(byte)).is_some()
707 );
708 Self(byte)
709 }
710 }
711
712 // # Safety
713 //
714 // Safety checklist for `ULE`:
715 //
716 // 1. The type is a single byte, not padding.
717 // 2. The type is a single byte, so it has align(1).
718 // 3. `validate_bytes` checks the validity of every byte.
719 // 4. `validate_bytes` checks the validity of every byte.
720 // 5. All other methods are be left with their default impl.
721 // 6. The represented enums implement Eq by byte equality.
722 unsafe impl ULE for PluralCategoryAndMetadataPackedULE {
723 fn validate_bytes(bytes: &[u8]) -> Result<(), UleError> {
724 bytes
725 .iter()
726 .all(|byte| {
727 let unpacked = Self::unpack_byte(*byte);
728 PluralCategoryAndMetadata::try_from_unpacked(unpacked).is_some()
729 })
730 .then_some(())
731 .ok_or_else(UleError::parse::<Self>)
732 }
733 }
734
735 impl PluralCategoryAndMetadataPackedULE {
736 fn unpack_byte(byte: u8) -> PluralCategoryAndMetadataUnpacked {
737 let plural_category_byte = (byte & 0xF0) >> 4;
738 let metadata_byte = byte & 0x0F;
739 PluralCategoryAndMetadataUnpacked {
740 plural_category_byte,
741 metadata_byte,
742 }
743 }
744
745 fn get(self) -> PluralCategoryAndMetadata {
746 let unpacked = Self::unpack_byte(self.0);
747 // Safety: by invariant, `self.0` contains valid values for PluralCategoryAndMetadata
748 unsafe { PluralCategoryAndMetadata::try_from_unpacked(unpacked).unwrap_unchecked() }
749 }
750 }
751
752 impl PluralCategoryAndMetadata {
753 fn try_from_unpacked(unpacked: PluralCategoryAndMetadataUnpacked) -> Option<Self> {
754 let plural_category = PluralElementsKeys::new_from_u8(unpacked.plural_category_byte)?;
755 let metadata = FourBitMetadata::try_from_byte(unpacked.metadata_byte)?;
756 Some(Self {
757 plural_category,
758 metadata,
759 })
760 }
761 }
762
763 impl AsULE for PluralCategoryAndMetadata {
764 type ULE = PluralCategoryAndMetadataPackedULE;
765 #[inline]
766 fn to_unaligned(self) -> Self::ULE {
767 PluralCategoryAndMetadataPackedULE::from(self)
768 }
769 #[inline]
770 fn from_unaligned(unaligned: Self::ULE) -> Self {
771 unaligned.get()
772 }
773 }
774
775 /// The type of the special patterns list.
776 type PluralElementsTupleSliceVarULE<V> = VarZeroSlice<VarTupleULE<PluralCategoryAndMetadata, V>>;
777
778 /// The type of the default value.
779 type PluralElementWithMetadata<'a, T> = (FourBitMetadata, &'a T);
780
781 /// Internal intermediate type that can be converted into a [`PluralElementsPackedULE`].
782 struct PluralElementsPackedBuilder<'a, T> {
783 pub default: PluralElementWithMetadata<'a, T>,
784 pub specials: Option<Vec<VarTuple<PluralCategoryAndMetadata, &'a T>>>,
785 }
786
787 /// Internal unpacked and deserialized values from a [`PluralElementsPackedULE`].
788 #[derive(Debug)]
789 struct PluralElementsUnpacked<'a, V: VarULE + ?Sized> {
790 pub default: PluralElementWithMetadata<'a, V>,
791 pub specials: Option<&'a PluralElementsTupleSliceVarULE<V>>,
792 }
793
794 /// Internal unpacked bytes from a [`PluralElementsPackedULE`].
795 struct PluralElementsUnpackedBytes<'a> {
796 pub lead_byte: u8,
797 pub v_bytes: &'a [u8],
798 pub specials_bytes: Option<&'a [u8]>,
799 }
800
801 /// Helper function to access a value from [`PluralElementsTupleSliceVarULE`]
802 fn get_special<V: VarULE + ?Sized>(
803 data: &PluralElementsTupleSliceVarULE<V>,
804 key: PluralElementsKeys,
805 ) -> Option<(FourBitMetadata, &V)> {
806 data.iter()
807 .filter_map(|ule| {
808 let PluralCategoryAndMetadata {
809 plural_category,
810 metadata,
811 } = ule.sized.get();
812 (plural_category == key).then_some((metadata, &ule.variable))
813 })
814 .next()
815 }
816
817 impl<T> PluralElementsInner<(FourBitMetadata, T)>
818 where
819 T: PartialEq,
820 {
821 fn to_packed_builder<'a, V>(&'a self) -> PluralElementsPackedBuilder<'a, T>
822 where
823 &'a T: EncodeAsVarULE<V>,
824 V: VarULE + ?Sized,
825 {
826 let specials = self
827 .get_specials_tuples()
828 .map(|(plural_category, (metadata, t))| VarTuple {
829 sized: PluralCategoryAndMetadata {
830 plural_category,
831 metadata: *metadata,
832 },
833 variable: t,
834 })
835 .collect::<Vec<_>>();
836 PluralElementsPackedBuilder {
837 default: (self.other.0, &self.other.1),
838 specials: if specials.is_empty() {
839 None
840 } else {
841 Some(specials)
842 },
843 }
844 }
845 }
846
847 unsafe impl<T, V> EncodeAsVarULE<PluralElementsPackedULE<V>>
848 for PluralElements<(FourBitMetadata, T)>
849 where
850 T: PartialEq + fmt::Debug,
851 for<'a> &'a T: EncodeAsVarULE<V>,
852 V: VarULE + ?Sized,
853 {
854 fn encode_var_ule_as_slices<R>(&self, _cb: impl FnOnce(&[&[u8]]) -> R) -> R {
855 // unnecessary if the other two are implemented
856 unreachable!()
857 }
858
859 fn encode_var_ule_len(&self) -> usize {
860 let builder = self.0.to_packed_builder();
861 1 + builder.default.1.encode_var_ule_len()
862 + match builder.specials {
863 Some(specials) => {
864 1 + EncodeAsVarULE::<PluralElementsTupleSliceVarULE<V>>::encode_var_ule_len(
865 &specials,
866 )
867 }
868 None => 0,
869 }
870 }
871
872 fn encode_var_ule_write(&self, dst: &mut [u8]) {
873 let builder = self.0.to_packed_builder();
874 #[expect(clippy::unwrap_used)] // by trait invariant
875 let (lead_byte, remainder) = dst.split_first_mut().unwrap();
876 *lead_byte = builder.default.0.get();
877 if let Some(specials) = builder.specials {
878 *lead_byte |= 0x80;
879 #[expect(clippy::unwrap_used)] // by trait invariant
880 let (second_byte, remainder) = remainder.split_first_mut().unwrap();
881 *second_byte = match u8::try_from(builder.default.1.encode_var_ule_len()) {
882 Ok(x) => x,
883 // TODO: Inform the user more nicely that their data doesn't fit in our packed structure
884 #[expect(clippy::panic)] // for now okay since it is mostly only during datagen
885 Err(_) => {
886 panic!("other value too long to be packed: {self:?}")
887 }
888 };
889 #[expect(clippy::unwrap_used)] // for now okay since it is mostly only during datagen
890 let (v_bytes, specials_bytes) = remainder
891 .split_at_mut_checked(*second_byte as usize)
892 .unwrap();
893 builder.default.1.encode_var_ule_write(v_bytes);
894 EncodeAsVarULE::<PluralElementsTupleSliceVarULE<V>>::encode_var_ule_write(
895 &specials,
896 specials_bytes,
897 );
898 } else {
899 builder.default.1.encode_var_ule_write(remainder)
900 };
901 }
902 }
903
904 #[cfg(feature = "datagen")]
905 impl<'a, V> PluralElementsInner<(FourBitMetadata, &'a V)>
906 where
907 V: VarULE + ?Sized,
908 {
909 fn from_packed(packed: &'a PluralElementsPackedULE<V>) -> Self {
910 let parts = packed.as_parts();
911 PluralElementsInner {
912 other: parts.default,
913 zero: parts
914 .specials
915 .and_then(|specials| get_special(specials, PluralElementsKeys::Zero)),
916 one: parts
917 .specials
918 .and_then(|specials| get_special(specials, PluralElementsKeys::One)),
919 two: parts
920 .specials
921 .and_then(|specials| get_special(specials, PluralElementsKeys::Two)),
922 few: parts
923 .specials
924 .and_then(|specials| get_special(specials, PluralElementsKeys::Few)),
925 many: parts
926 .specials
927 .and_then(|specials| get_special(specials, PluralElementsKeys::Many)),
928 explicit_zero: parts
929 .specials
930 .and_then(|specials| get_special(specials, PluralElementsKeys::ExplicitZero)),
931 explicit_one: parts
932 .specials
933 .and_then(|specials| get_special(specials, PluralElementsKeys::ExplicitOne)),
934 }
935 }
936 }
937
938 #[cfg(feature = "serde")]
939 impl<T> PluralElementsInner<(FourBitMetadata, T)> {
940 fn into_packed<V>(self) -> Box<PluralElementsPackedULE<V>>
941 where
942 T: PartialEq + fmt::Debug,
943 for<'a> &'a T: EncodeAsVarULE<V>,
944 V: VarULE + ?Sized,
945 {
946 zerovec::ule::encode_varule_to_box(&PluralElements(self))
947 }
948 }
949
950 #[cfg(feature = "serde")]
951 impl<'de, 'data, V> serde::Deserialize<'de> for &'data PluralElementsPackedULE<V>
952 where
953 'de: 'data,
954 V: VarULE + ?Sized,
955 {
956 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
957 where
958 D: serde::Deserializer<'de>,
959 {
960 if deserializer.is_human_readable() {
961 Err(serde::de::Error::custom(
962 "&PluralElementsPackedULE cannot be deserialized from human-readable formats",
963 ))
964 } else {
965 let bytes = <&[u8]>::deserialize(deserializer)?;
966 PluralElementsPackedULE::<V>::parse_bytes(bytes).map_err(serde::de::Error::custom)
967 }
968 }
969 }
970
971 #[cfg(feature = "serde")]
972 impl<'de, V> serde::Deserialize<'de> for Box<PluralElementsPackedULE<V>>
973 where
974 V: VarULE + ?Sized,
975 Box<V>: serde::Deserialize<'de> + PartialEq + fmt::Debug,
976 {
977 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
978 where
979 D: serde::Deserializer<'de>,
980 {
981 if deserializer.is_human_readable() {
982 let plural_elements: PluralElementsInner<(FourBitMetadata, Box<V>)> =
983 PluralElementsInner::deserialize(deserializer)?;
984 Ok(plural_elements.into_packed())
985 } else {
986 let bytes = <&[u8]>::deserialize(deserializer)?;
987 PluralElementsPackedULE::<V>::parse_bytes(bytes)
988 .map(|ule| ule.to_owned())
989 .map_err(serde::de::Error::custom)
990 }
991 }
992 }
993
994 #[cfg(feature = "datagen")]
995 impl<V> serde::Serialize for PluralElementsPackedULE<V>
996 where
997 V: PartialEq + serde::Serialize + VarULE + ?Sized,
998 {
999 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1000 where
1001 S: serde::Serializer,
1002 {
1003 if serializer.is_human_readable() {
1004 let plural_elements: PluralElementsInner<(FourBitMetadata, &V)> =
1005 PluralElementsInner::from_packed(self);
1006 plural_elements.serialize(serializer)
1007 } else {
1008 serializer.serialize_bytes(self.as_bytes())
1009 }
1010 }
1011 }
1012
1013 #[cfg(feature = "datagen")]
1014 impl<'a, V> databake::Bake for &'a PluralElementsPackedULE<V>
1015 where
1016 &'a V: databake::Bake,
1017 V: VarULE + ?Sized,
1018 {
1019 fn bake(&self, ctx: &databake::CrateEnv) -> databake::TokenStream {
1020 ctx.insert("icu_plurals");
1021 let bytes = (&self.bytes).bake(ctx);
1022 databake::quote! {
1023 // Safety: the bytes came directly from self.bytes on the previous line.
1024 unsafe { icu_plurals::provider::PluralElementsPackedULE::from_bytes_unchecked(#bytes) }
1025 }
1026 }
1027 }
1028
1029 #[cfg(feature = "datagen")]
1030 impl<'a, V> databake::BakeSize for &'a PluralElementsPackedULE<V>
1031 where
1032 &'a V: databake::Bake,
1033 V: VarULE + ?Sized,
1034 {
1035 fn borrows_size(&self) -> usize {
1036 self.bytes.len()
1037 }
1038 }
1039
1040 /// Helper function to properly deserialize a `Cow<PluralElementsPackedULE<V>>`
1041 ///
1042 /// Due to <https://github.com/rust-lang/rust/issues/130180>, you may need to qualify
1043 /// `V` when invoking this, like so:
1044 ///
1045 /// `#[serde(deserialize_with = "deserialize_plural_elements_packed_cow::<_, str>")]`
1046 ///
1047 /// See <https://github.com/unicode-org/icu4x/pull/1556>
1048 #[cfg(feature = "serde")]
1049 fn deserialize_plural_elements_packed_cow<'de, 'data, D, V>(
1050 deserializer: D,
1051 ) -> Result<Cow<'data, PluralElementsPackedULE<V>>, D::Error>
1052 where
1053 'de: 'data,
1054 D: serde::Deserializer<'de>,
1055 V: VarULE + ?Sized,
1056 Box<PluralElementsPackedULE<V>>: serde::Deserialize<'de>,
1057 {
1058 use serde::Deserialize;
1059 if deserializer.is_human_readable() {
1060 let value = Box::<PluralElementsPackedULE<V>>::deserialize(deserializer)?;
1061 Ok(Cow::Owned(value))
1062 } else {
1063 let value = <&'de PluralElementsPackedULE<V>>::deserialize(deserializer)?;
1064 Ok(Cow::Borrowed(value))
1065 }
1066 }
1067
1068 // Need a manual impl because the derive(Clone) impl bounds are wrong
1069 impl<V> Clone for PluralElementsPackedCow<'_, V>
1070 where
1071 V: VarULE + ?Sized,
1072 {
1073 fn clone(&self) -> Self {
1074 Self {
1075 elements: self.elements.clone(),
1076 }
1077 }
1078 }
1079
1080 impl<T, V> From<PluralElements<T>> for PluralElementsPackedCow<'static, V>
1081 where
1082 V: VarULE + ?Sized,
1083 T: PartialEq + fmt::Debug,
1084 for<'a> &'a T: EncodeAsVarULE<V>,
1085 {
1086 fn from(value: PluralElements<T>) -> Self {
1087 let elements =
1088 zerovec::ule::encode_varule_to_box(&value.map(|s| (FourBitMetadata::zero(), s)));
1089 Self {
1090 elements: Cow::Owned(elements),
1091 }
1092 }
1093 }
1094
1095 impl<V> PluralElementsPackedCow<'_, V>
1096 where
1097 V: VarULE + ?Sized,
1098 {
1099 /// Returns the value for the given [`PluralOperands`] and [`PluralRules`].
1100 pub fn get<'a>(&'a self, op: PluralOperands, rules: &PluralRules) -> &'a V {
1101 self.elements.get(op, rules).1
1102 }
1103 }
1104
1105 #[test]
1106 fn test_serde_singleton_roundtrip() {
1107 let plural_elements = PluralElements::new((FourBitMetadata::zero(), "abc"));
1108 let ule = zerovec::ule::encode_varule_to_box(&plural_elements);
1109
1110 let postcard_bytes = postcard::to_allocvec(&ule).unwrap();
1111 assert_eq!(
1112 postcard_bytes,
1113 &[
1114 4, // Postcard header
1115 0x00, // Discriminant
1116 b'a', b'b', b'c', // String
1117 ]
1118 );
1119
1120 let postcard_ule: Box<PluralElementsPackedULE<str>> =
1121 postcard::from_bytes(&postcard_bytes).unwrap();
1122 assert_eq!(ule, postcard_ule);
1123
1124 let postcard_borrowed: &PluralElementsPackedULE<str> =
1125 postcard::from_bytes(&postcard_bytes).unwrap();
1126 assert_eq!(&*ule, postcard_borrowed);
1127
1128 let postcard_cow: PluralElementsPackedCow<str> = postcard::from_bytes(&postcard_bytes).unwrap();
1129 assert_eq!(&*ule, &*postcard_cow.elements);
1130 assert!(matches!(postcard_cow.elements, Cow::Borrowed(_)));
1131
1132 let json_str = serde_json::to_string(&ule).unwrap();
1133 let json_ule: Box<PluralElementsPackedULE<str>> = serde_json::from_str(&json_str).unwrap();
1134 assert_eq!(ule, json_ule);
1135 }
1136
1137 #[test]
1138 fn test_serde_nonsingleton_roundtrip() {
1139 let plural_elements = PluralElements::new((FourBitMetadata::zero(), "abc"))
1140 .with_one_value(Some((FourBitMetadata::zero(), "defg")));
1141 let ule = zerovec::ule::encode_varule_to_box(&plural_elements);
1142
1143 let postcard_bytes = postcard::to_allocvec(&ule).unwrap();
1144 assert_eq!(
1145 postcard_bytes,
1146 &[
1147 12, // Postcard header
1148 0x80, // Discriminant
1149 3, b'a', b'b', b'c', // String of length 3
1150 1, 0, // VarZeroVec of length 1
1151 0x10, b'd', b'e', b'f', b'g' // Plural category 1 and string "defg"
1152 ]
1153 );
1154
1155 let postcard_ule: Box<PluralElementsPackedULE<str>> =
1156 postcard::from_bytes(&postcard_bytes).unwrap();
1157 assert_eq!(ule, postcard_ule);
1158
1159 let postcard_borrowed: &PluralElementsPackedULE<str> =
1160 postcard::from_bytes(&postcard_bytes).unwrap();
1161 assert_eq!(&*ule, postcard_borrowed);
1162
1163 let json_str = serde_json::to_string(&ule).unwrap();
1164 let json_ule: Box<PluralElementsPackedULE<str>> = serde_json::from_str(&json_str).unwrap();
1165 assert_eq!(ule, json_ule);
1166 }