1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

// Provider structs must be stable
#![allow(clippy::exhaustive_structs, clippy::exhaustive_enums)]

//! 🚧 \[Unstable\] Data provider struct definitions for this ICU4X component.
//!
//! <div class="stab unstable">
//! 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
//! including in SemVer minor releases. While the serde representation of data structs is guaranteed
//! to be stable, their Rust representation might not be. Use with caution.
//! </div>
//!
//! Read more about data providers: [`icu_provider`]

use crate::rules::runtime::ast::Rule;
use crate::{PluralCategory, PluralElements, PluralElementsInner, PluralOperands, PluralRules};
use alloc::borrow::{Cow, ToOwned};
use alloc::boxed::Box;
use alloc::vec::Vec;
use core::fmt;
use core::marker::PhantomData;
use icu_provider::prelude::*;
use yoke::Yokeable;
use zerofrom::ZeroFrom;
use zerovec::ule::vartuple::VarTuple;
use zerovec::ule::vartuple::VarTupleULE;
use zerovec::ule::AsULE;
use zerovec::ule::EncodeAsVarULE;
use zerovec::ule::UleError;
use zerovec::ule::VarULE;
use zerovec::ule::ULE;
use zerovec::VarZeroSlice;

#[cfg(feature = "compiled_data")]
#[derive(Debug)]
/// Baked data
///
/// <div class="stab unstable">
/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
/// including in SemVer minor releases. In particular, the `DataProvider` implementations are only
/// guaranteed to match with this version's `*_unstable` providers. Use with caution.
/// </div>
pub struct Baked;

#[cfg(feature = "compiled_data")]
#[allow(unused_imports)]
const _: () = {
    use icu_plurals_data::*;
    mod icu {
        pub use crate as plurals;
        pub use icu_plurals_data::icu_locale as locale;
    }

    make_provider!(Baked);
    impl_cardinal_v1_marker!(Baked);
    impl_ordinal_v1_marker!(Baked);
    #[cfg(feature = "experimental")]
    impl_plural_ranges_v1_marker!(Baked);
};

#[cfg(feature = "datagen")]
/// The latest minimum set of markers required by this component.
pub const MARKERS: &[DataMarkerInfo] = &[
    CardinalV1Marker::INFO,
    OrdinalV1Marker::INFO,
    #[cfg(feature = "experimental")]
    PluralRangesV1Marker::INFO,
];

/// Plural rule strings conforming to UTS 35 syntax. Includes separate fields for five of the six
/// standard plural forms. If none of the rules match, the "other" category is assumed.
///
/// More information: <https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules>
///
/// <div class="stab unstable">
/// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
/// including in SemVer minor releases. While the serde representation of data structs is guaranteed
/// to be stable, their Rust representation might not be. Use with caution.
/// </div>
#[icu_provider::data_struct(
    CardinalV1Marker = "plurals/cardinal@1",
    OrdinalV1Marker = "plurals/ordinal@1"
)]
#[derive(Default, Clone, PartialEq, Debug)]
#[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
#[cfg_attr(feature = "datagen", databake(path = icu_plurals::provider))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
pub struct PluralRulesV1<'data> {
    /// Rule that matches [`PluralCategory::Zero`](super::PluralCategory::Zero), or `None` if not present.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub zero: Option<Rule<'data>>,
    /// Rule that matches [`PluralCategory::One`](super::PluralCategory::One), or `None` if not present.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub one: Option<Rule<'data>>,
    /// Rule that matches [`PluralCategory::Two`](super::PluralCategory::Two), or `None` if not present.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub two: Option<Rule<'data>>,
    /// Rule that matches [`PluralCategory::Few`](super::PluralCategory::Few), or `None` if not present.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub few: Option<Rule<'data>>,
    /// Rule that matches [`PluralCategory::Many`](super::PluralCategory::Many), or `None` if not present.
    #[cfg_attr(feature = "serde", serde(borrow))]
    pub many: Option<Rule<'data>>,
}

#[cfg(any(feature = "datagen", feature = "experimental"))]
pub use ranges::*;

#[cfg(any(feature = "datagen", feature = "experimental"))]
mod ranges {
    use crate::PluralCategory;
    use icu_provider::prelude::*;
    use zerovec::ZeroMap;

    /// [`PluralCategory`] but serializable as provider data.
    ///
    /// <div class="stab unstable">
    /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
    /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
    /// to be stable, their Rust representation might not be. Use with caution.
    /// </div>
    #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Ord, PartialOrd)]
    #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
    #[cfg_attr(feature = "datagen", databake(path = icu_plurals::provider))]
    #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
    #[zerovec::make_ule(RawPluralCategoryULE)]
    #[repr(u8)]
    #[cfg_attr(
        any(feature = "datagen", feature = "serde"),
        serde(rename_all = "lowercase")
    )]
    pub enum RawPluralCategory {
        /// CLDR "other" plural category.
        Other = 0,
        /// CLDR "zero" plural category.
        Zero = 1,
        /// CLDR "one" plural category.
        One = 2,
        /// CLDR "two" plural category.
        Two = 3,
        /// CLDR "few" plural category.
        Few = 4,
        /// CLDR "many" plural category.
        Many = 5,
    }

    impl RawPluralCategory {
        /// Gets the corresponding variant string of this `RawPluralCategory`.
        #[cfg(any(feature = "datagen", feature = "serde"))]
        const fn as_str(self) -> &'static str {
            match self {
                Self::Other => "other",
                Self::Zero => "zero",
                Self::One => "one",
                Self::Two => "two",
                Self::Few => "few",
                Self::Many => "many",
            }
        }
    }

    impl From<RawPluralCategory> for PluralCategory {
        fn from(value: RawPluralCategory) -> Self {
            match value {
                RawPluralCategory::Other => PluralCategory::Other,
                RawPluralCategory::Zero => PluralCategory::Zero,
                RawPluralCategory::One => PluralCategory::One,
                RawPluralCategory::Two => PluralCategory::Two,
                RawPluralCategory::Few => PluralCategory::Few,
                RawPluralCategory::Many => PluralCategory::Many,
            }
        }
    }

    impl From<PluralCategory> for RawPluralCategory {
        fn from(value: PluralCategory) -> Self {
            match value {
                PluralCategory::Zero => RawPluralCategory::Zero,
                PluralCategory::One => RawPluralCategory::One,
                PluralCategory::Two => RawPluralCategory::Two,
                PluralCategory::Few => RawPluralCategory::Few,
                PluralCategory::Many => RawPluralCategory::Many,
                PluralCategory::Other => RawPluralCategory::Other,
            }
        }
    }

    /// An `u8` that is expected to be a plural range, but does not enforce this invariant.
    ///
    /// <div class="stab unstable">
    /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
    /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
    /// to be stable, their Rust representation might not be. Use with caution.
    /// </div>
    #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash, Ord, PartialOrd)]
    #[cfg_attr(feature = "datagen", derive(databake::Bake))]
    #[cfg_attr(feature = "datagen", databake(path = icu_plurals::provider))]
    #[zerovec::make_ule(UnvalidatedPluralRangeULE)]
    pub struct UnvalidatedPluralRange(pub u8);

    impl UnvalidatedPluralRange {
        /// Creates a new `UnvalidatedPluralRange` from a category range.
        pub fn from_range(start: RawPluralCategory, end: RawPluralCategory) -> Self {
            let start = start as u8;
            let end = end as u8;

            debug_assert!(start < 16);
            debug_assert!(end < 16);

            let range = (start << 4) | end;

            Self(range)
        }
    }

    #[cfg(feature = "datagen")]
    impl serde::Serialize for UnvalidatedPluralRange {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
        {
            use serde::ser::Error;

            struct PrettyPrinter(RawPluralCategory, RawPluralCategory);

            impl core::fmt::Display for PrettyPrinter {
                fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
                    f.write_str(self.0.as_str())?;
                    f.write_str("--")?;
                    f.write_str(self.1.as_str())
                }
            }

            if serializer.is_human_readable() {
                let start = RawPluralCategory::new_from_u8(self.0 >> 4)
                    .ok_or_else(|| S::Error::custom("invalid tag in UnvalidatedPluralRange"))?;
                let end = RawPluralCategory::new_from_u8(self.0 & 0x0F)
                    .ok_or_else(|| S::Error::custom("invalid tag in UnvalidatedPluralRange"))?;
                serializer.collect_str(&PrettyPrinter(start, end))
            } else {
                self.0.serialize(serializer)
            }
        }
    }

    #[cfg(feature = "serde")]
    impl<'de> serde::Deserialize<'de> for UnvalidatedPluralRange {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: serde::Deserializer<'de>,
        {
            use serde::de::{Error, Visitor};

            struct HumanReadableVisitor;

            impl Visitor<'_> for HumanReadableVisitor {
                type Value = UnvalidatedPluralRange;

                fn expecting(&self, formatter: &mut alloc::fmt::Formatter) -> alloc::fmt::Result {
                    write!(
                        formatter,
                        "a plural range of the form <PluralCategory>-<PluralCategory>",
                    )
                }

                fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
                where
                    E: Error,
                {
                    const VARIANTS: [&str; 6] = [
                        RawPluralCategory::Other.as_str(),
                        RawPluralCategory::Zero.as_str(),
                        RawPluralCategory::One.as_str(),
                        RawPluralCategory::Two.as_str(),
                        RawPluralCategory::Few.as_str(),
                        RawPluralCategory::Many.as_str(),
                    ];

                    let (start, end) = v
                        .split_once("--")
                        .ok_or_else(|| E::custom("expected token `--` in plural range"))?;

                    let start = PluralCategory::get_for_cldr_string(start)
                        .ok_or_else(|| E::unknown_variant(start, &VARIANTS))?;
                    let end = PluralCategory::get_for_cldr_string(end)
                        .ok_or_else(|| E::unknown_variant(end, &VARIANTS))?;

                    Ok(UnvalidatedPluralRange::from_range(start.into(), end.into()))
                }
            }

            if deserializer.is_human_readable() {
                deserializer.deserialize_str(HumanReadableVisitor)
            } else {
                Ok(Self(<u8>::deserialize(deserializer)?))
            }
        }
    }

    /// Plural categories for ranges.
    ///
    /// Obtains the plural category of a range from the categories of its endpoints. It is required that
    /// the start value must be strictly less than the end value, and both values must be strictly positive.
    ///
    /// More information: <https://unicode.org/reports/tr35/tr35-numbers.html#Plural_Ranges>
    ///
    /// <div class="stab unstable">
    /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
    /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
    /// to be stable, their Rust representation might not be. Use with caution.
    /// </div>
    #[icu_provider::data_struct(PluralRangesV1Marker = "plurals/ranges@1")]
    #[derive(Clone, PartialEq, Debug)]
    #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
    #[cfg_attr(feature = "datagen", databake(path = icu_plurals::provider))]
    #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
    #[yoke(prove_covariance_manually)]
    pub struct PluralRangesV1<'data> {
        /// Map between the categories of the endpoints of a range and its corresponding
        /// category.
        ///
        /// This is roughly equivalent to a `BTreeMap<(PluralCategory, PluralCategory), PluralCategory>`,
        /// where the key is `(start category, end category)`.
        #[cfg_attr(feature = "serde", serde(borrow))]
        pub ranges: ZeroMap<'data, UnvalidatedPluralRange, RawPluralCategory>,
    }
}

/// A sized packed [`PluralElements`] suitable for use in data structs.
///
/// This type has the following limitations:
///
/// 1. It only supports `str`
/// 2. It does not implement [`VarULE`] so it can't be used in a [`VarZeroSlice`]
/// 3. It always serializes the [`FourBitMetadata`] as 0
///
/// Use [`PluralElementsPackedULE`] directly if you need these additional features.
#[derive(Debug, PartialEq, Yokeable, ZeroFrom)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
#[cfg_attr(feature = "datagen", databake(path = icu_plurals::provider))]
#[cfg_attr(
    feature = "serde",
    serde(
        transparent,
        bound(
            serialize = "V: serde::Serialize + PartialEq",
            deserialize = "Box<PluralElementsPackedULE<V>>: serde::Deserialize<'de>"
        )
    )
)]
pub struct PluralElementsPackedCow<'data, V: VarULE + ?Sized> {
    /// The encoded elements.
    #[cfg_attr(
        feature = "serde",
        serde(
            borrow,
            deserialize_with = "deserialize_plural_elements_packed_cow::<_, V>"
        )
    )]
    pub elements: Cow<'data, PluralElementsPackedULE<V>>,
}

/// A bitpacked DST for [`PluralElements`].
///
/// Can be put in a [`Cow`] or a [`VarZeroSlice`].
#[derive(Debug, PartialEq, Eq)]
#[repr(transparent)]
pub struct PluralElementsPackedULE<V: VarULE + ?Sized> {
    _v: PhantomData<V>,
    /// Invariant Representation:
    ///
    /// First byte: `d...mmmm`
    /// - `d` = 0 if singleton, 1 if a map
    /// - `...` = padding, should be 0
    /// - `mmmm` = [`FourBitMetadata`] for the default value
    ///
    /// If d is 0:
    /// - Remainder: the default (plural "other") value `V`
    ///
    /// If d is 1:
    /// - Second byte: L = the length of `V`
    /// - Bytes 2..(2+L): the default (plural "other") value `V`
    /// - Remainder: [`PluralElementsTupleSliceVarULE`]
    bytes: [u8],
}

impl<V: VarULE + ?Sized> ToOwned for PluralElementsPackedULE<V> {
    type Owned = Box<PluralElementsPackedULE<V>>;
    fn to_owned(&self) -> Self::Owned {
        self.to_boxed()
    }
}

unsafe impl<V> VarULE for PluralElementsPackedULE<V>
where
    V: VarULE + ?Sized,
{
    fn validate_bytes(bytes: &[u8]) -> Result<(), UleError> {
        let unpacked_bytes =
            Self::unpack_bytes(bytes).ok_or_else(|| UleError::length::<Self>(bytes.len()))?;
        // The high bit of lead_byte was read in unpack_bytes.
        // Bits 0-3 are FourBitMetadata.
        // We expect bits 4-6 to be padding.
        if unpacked_bytes.lead_byte & 0x70 != 0 {
            return Err(UleError::parse::<Self>());
        }
        // Now validate the two variable-length slices.
        V::validate_bytes(unpacked_bytes.v_bytes)?;
        if let Some(specials_bytes) = unpacked_bytes.specials_bytes {
            PluralElementsTupleSliceVarULE::<V>::validate_bytes(specials_bytes)?;
        }
        Ok(())
    }

    unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
        // Safety: the bytes are valid by trait invariant, and we are transparent over bytes
        core::mem::transmute(bytes)
    }
}

impl<V> PluralElementsPackedULE<V>
where
    V: VarULE + ?Sized,
{
    /// Casts a byte slice to a [`PluralElementsPackedULE`].
    ///
    /// # Safety
    ///
    /// The bytes must be valid according to [`PluralElementsPackedULE::validate_bytes`].
    pub const unsafe fn from_bytes_unchecked(bytes: &[u8]) -> &Self {
        // Safety: the bytes are valid by trait invariant, and we are transparent over bytes
        core::mem::transmute(bytes)
    }

    /// Returns a tuple with:
    /// 1. The lead byte
    /// 2. Bytes corresponding to the default V
    /// 3. Bytes corresponding to the specials slice, if present
    #[inline]
    fn unpack_bytes(bytes: &[u8]) -> Option<PluralElementsUnpackedBytes> {
        let (lead_byte, remainder) = bytes.split_first()?;
        if lead_byte & 0x80 == 0 {
            Some(PluralElementsUnpackedBytes {
                lead_byte: *lead_byte,
                v_bytes: remainder,
                specials_bytes: None,
            })
        } else {
            let (second_byte, remainder) = remainder.split_first()?;
            // TODO in Rust 1.80: use split_at_checked
            let v_length = *second_byte as usize;
            if remainder.len() < v_length {
                return None;
            }
            let (v_bytes, remainder) = remainder.split_at(v_length);
            Some(PluralElementsUnpackedBytes {
                lead_byte: *lead_byte,
                v_bytes,
                specials_bytes: Some(remainder),
            })
        }
    }

    /// Unpacks this structure into the default value and the optional list of specials.
    fn as_parts(&self) -> PluralElementsUnpacked<V> {
        // Safety: the bytes are valid by invariant
        let unpacked_bytes = unsafe { Self::unpack_bytes(&self.bytes).unwrap_unchecked() };
        let metadata = FourBitMetadata(unpacked_bytes.lead_byte & 0x0F);
        // Safety: the bytes are valid by invariant
        let default = unsafe { V::from_bytes_unchecked(unpacked_bytes.v_bytes) };
        #[allow(clippy::manual_map)] // more explicit with the unsafe code
        let specials = if let Some(specials_bytes) = unpacked_bytes.specials_bytes {
            // Safety: the bytes are valid by invariant
            Some(unsafe {
                PluralElementsTupleSliceVarULE::<V>::from_bytes_unchecked(specials_bytes)
            })
        } else {
            None
        };
        PluralElementsUnpacked {
            default: (metadata, default),
            specials,
        }
    }

    /// Returns the value for the given [`PluralOperands`] and [`PluralRules`].
    pub fn get<'a>(&'a self, op: PluralOperands, rules: &PluralRules) -> (FourBitMetadata, &'a V) {
        let parts = self.as_parts();

        let category = rules.category_for(op);

        match parts.specials {
            Some(specials) => {
                if op.is_exactly_zero() {
                    if let Some(value) = get_special(specials, PluralElementsKeysV1::ExplicitZero) {
                        return value;
                    }
                }
                if op.is_exactly_one() {
                    if let Some(value) = get_special(specials, PluralElementsKeysV1::ExplicitOne) {
                        return value;
                    }
                }
                match category {
                    PluralCategory::Zero => Some(PluralElementsKeysV1::Zero),
                    PluralCategory::One => Some(PluralElementsKeysV1::One),
                    PluralCategory::Two => Some(PluralElementsKeysV1::Two),
                    PluralCategory::Few => Some(PluralElementsKeysV1::Few),
                    PluralCategory::Many => Some(PluralElementsKeysV1::Many),
                    PluralCategory::Other => None,
                }
                .and_then(|key| get_special(specials, key))
            }
            None => None,
        }
        .unwrap_or(parts.default)
    }

    /// Recovers the [`PluralElements`] corresponding to this packed structure.
    #[cfg(feature = "datagen")]
    pub fn decode(&self) -> PluralElements<(FourBitMetadata, &V)> {
        PluralElements(PluralElementsInner::from_packed(self))
    }

    /// Returns the value for the default ("other") plural variant.
    pub fn get_default(&self) -> (FourBitMetadata, &V) {
        self.as_parts().default
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[zerovec::make_ule(PluralCategoryV1ULE)]
#[repr(u8)]
#[cfg_attr(feature = "datagen", derive(serde::Serialize))]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
enum PluralElementsKeysV1 {
    Zero = 0,
    One = 1,
    Two = 2,
    Few = 3,
    Many = 4,
    ExplicitZero = 5,
    ExplicitOne = 6,
}

impl<T> PluralElementsInner<T>
where
    T: PartialEq,
{
    fn get_specials_tuples(&self) -> impl Iterator<Item = (PluralElementsKeysV1, &T)> {
        [
            self.zero
                .as_ref()
                .filter(|&p| *p != self.other)
                .map(|s| (PluralElementsKeysV1::Zero, s)),
            self.one
                .as_ref()
                .filter(|&p| *p != self.other)
                .map(|s| (PluralElementsKeysV1::One, s)),
            self.two
                .as_ref()
                .filter(|&p| *p != self.other)
                .map(|s| (PluralElementsKeysV1::Two, s)),
            self.few
                .as_ref()
                .filter(|&p| *p != self.other)
                .map(|s| (PluralElementsKeysV1::Few, s)),
            self.many
                .as_ref()
                .filter(|&p| *p != self.other)
                .map(|s| (PluralElementsKeysV1::Many, s)),
            self.explicit_zero
                .as_ref()
                .filter(|&p| *p != self.other)
                .map(|s| (PluralElementsKeysV1::ExplicitZero, s)),
            self.explicit_one
                .as_ref()
                .filter(|&p| *p != self.other)
                .map(|s| (PluralElementsKeysV1::ExplicitOne, s)),
        ]
        .into_iter()
        .flatten()
    }
}

/// Four bits of metadata that are stored and retrieved with the plural elements.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[repr(transparent)]
pub struct FourBitMetadata(u8);

impl FourBitMetadata {
    /// Creates a [`FourBitMetadata`] if the given value fits in 4 bits.
    pub fn try_from_byte(byte: u8) -> Option<Self> {
        if byte < 0x80 {
            Some(Self(byte))
        } else {
            None
        }
    }

    /// Creates a [`FourBitMetadata`] with a zero value.
    pub fn zero() -> Self {
        Self(0)
    }

    /// Gets the value out of a [`FourBitMetadata`].
    pub fn get(self) -> u8 {
        self.0
    }
}

/// A pair of [`PluralElementsKeysV1`] and [`FourBitMetadata`].
#[derive(Debug, Copy, Clone)]
struct PluralCategoryAndMetadata {
    pub plural_category: PluralElementsKeysV1,
    pub metadata: FourBitMetadata,
}

struct PluralCategoryAndMetadataUnpacked {
    pub plural_category_byte: u8,
    pub metadata_byte: u8,
}

/// Bitpacked struct for [`PluralCategoryAndMetadata`].
#[derive(Debug, Copy, Clone)]
#[repr(transparent)]
struct PluralCategoryAndMetadataPackedULE(
    /// Representation: `ppppmmmm`
    /// - `pppp` are a valid [`PluralElementsKeysV1`]
    /// - `mmmm` are a valid [`FourBitMetadata`]
    ///
    /// The valid values are determined by their respective types.
    u8,
);

impl From<PluralCategoryAndMetadata> for PluralCategoryAndMetadataPackedULE {
    fn from(value: PluralCategoryAndMetadata) -> Self {
        let byte = ((value.plural_category as u8) << 4) | value.metadata.get();
        debug_assert!(
            PluralCategoryAndMetadata::try_from_unpacked(Self::unpack_byte(byte)).is_some()
        );
        Self(byte)
    }
}

// # Safety
//
// Safety checklist for `ULE`:
//
// 1. The type is a single byte, not padding.
// 2. The type is a single byte, so it has align(1).
// 3. `validate_bytes` checks the validity of every byte.
// 4. `validate_bytes` checks the validity of every byte.
// 5. All other methods are be left with their default impl.
// 6. The represented enums implement Eq by byte equality.
unsafe impl ULE for PluralCategoryAndMetadataPackedULE {
    fn validate_bytes(bytes: &[u8]) -> Result<(), zerovec::ule::UleError> {
        bytes
            .iter()
            .all(|byte| {
                let unpacked = Self::unpack_byte(*byte);
                PluralCategoryAndMetadata::try_from_unpacked(unpacked).is_some()
            })
            .then_some(())
            .ok_or_else(UleError::parse::<Self>)
    }
}

impl PluralCategoryAndMetadataPackedULE {
    fn unpack_byte(byte: u8) -> PluralCategoryAndMetadataUnpacked {
        let plural_category_byte = (byte & 0xF0) >> 4;
        let metadata_byte = byte & 0x0F;
        PluralCategoryAndMetadataUnpacked {
            plural_category_byte,
            metadata_byte,
        }
    }

    fn get(self) -> PluralCategoryAndMetadata {
        let unpacked = Self::unpack_byte(self.0);
        // Safety: by invariant, `self.0` contains valid values for PluralCategoryAndMetadata
        unsafe { PluralCategoryAndMetadata::try_from_unpacked(unpacked).unwrap_unchecked() }
    }
}

impl PluralCategoryAndMetadata {
    fn try_from_unpacked(unpacked: PluralCategoryAndMetadataUnpacked) -> Option<Self> {
        let plural_category = PluralElementsKeysV1::new_from_u8(unpacked.plural_category_byte)?;
        let metadata = FourBitMetadata::try_from_byte(unpacked.metadata_byte)?;
        Some(Self {
            plural_category,
            metadata,
        })
    }
}

impl AsULE for PluralCategoryAndMetadata {
    type ULE = PluralCategoryAndMetadataPackedULE;
    #[inline]
    fn to_unaligned(self) -> Self::ULE {
        PluralCategoryAndMetadataPackedULE::from(self)
    }
    #[inline]
    fn from_unaligned(unaligned: Self::ULE) -> Self {
        unaligned.get()
    }
}

/// The type of the special patterns list.
type PluralElementsTupleSliceVarULE<V> = VarZeroSlice<VarTupleULE<PluralCategoryAndMetadata, V>>;

/// The type of the default value.
type PluralElementWithMetadata<'a, T> = (FourBitMetadata, &'a T);

/// Internal intermediate type that can be converted into a [`PluralElementsPackedULE`].
struct PluralElementsPackedBuilder<'a, T> {
    pub default: PluralElementWithMetadata<'a, T>,
    pub specials: Option<Vec<VarTuple<PluralCategoryAndMetadata, &'a T>>>,
}

/// Internal unpacked and deserialized values from a [`PluralElementsPackedULE`].
struct PluralElementsUnpacked<'a, V: VarULE + ?Sized> {
    pub default: PluralElementWithMetadata<'a, V>,
    pub specials: Option<&'a PluralElementsTupleSliceVarULE<V>>,
}

/// Internal unpacked bytes from a [`PluralElementsPackedULE`].
struct PluralElementsUnpackedBytes<'a> {
    pub lead_byte: u8,
    pub v_bytes: &'a [u8],
    pub specials_bytes: Option<&'a [u8]>,
}

/// Helper function to access a value from [`PluralElementsTupleSliceVarULE`]
fn get_special<V: VarULE + ?Sized>(
    data: &PluralElementsTupleSliceVarULE<V>,
    key: PluralElementsKeysV1,
) -> Option<(FourBitMetadata, &V)> {
    data.iter()
        .filter_map(|ule| {
            let PluralCategoryAndMetadata {
                plural_category,
                metadata,
            } = ule.sized.get();
            (plural_category == key).then_some((metadata, &ule.variable))
        })
        .next()
}

impl<T> PluralElementsInner<(FourBitMetadata, T)>
where
    T: PartialEq,
{
    fn to_packed_builder<'a, V>(&'a self) -> PluralElementsPackedBuilder<'a, T>
    where
        &'a T: EncodeAsVarULE<V>,
        V: VarULE + ?Sized,
    {
        let specials = self
            .get_specials_tuples()
            .map(|(plural_category, (metadata, t))| VarTuple {
                sized: PluralCategoryAndMetadata {
                    plural_category,
                    metadata: *metadata,
                },
                variable: t,
            })
            .collect::<Vec<_>>();
        PluralElementsPackedBuilder {
            default: (self.other.0, &self.other.1),
            specials: if specials.is_empty() {
                None
            } else {
                Some(specials)
            },
        }
    }
}

unsafe impl<T, V> EncodeAsVarULE<PluralElementsPackedULE<V>>
    for PluralElements<(FourBitMetadata, T)>
where
    T: PartialEq + fmt::Debug,
    for<'a> &'a T: EncodeAsVarULE<V>,
    V: VarULE + ?Sized,
{
    fn encode_var_ule_as_slices<R>(&self, _cb: impl FnOnce(&[&[u8]]) -> R) -> R {
        // unnecessary if the other two are implemented
        unreachable!()
    }

    fn encode_var_ule_len(&self) -> usize {
        let builder = self.0.to_packed_builder();
        1 + builder.default.1.encode_var_ule_len()
            + match builder.specials {
                Some(specials) => {
                    1 + EncodeAsVarULE::<PluralElementsTupleSliceVarULE<V>>::encode_var_ule_len(
                        &specials,
                    )
                }
                None => 0,
            }
    }

    fn encode_var_ule_write(&self, dst: &mut [u8]) {
        let builder = self.0.to_packed_builder();
        #[allow(clippy::unwrap_used)] // by trait invariant
        let (lead_byte, remainder) = dst.split_first_mut().unwrap();
        *lead_byte = builder.default.0.get();
        if let Some(specials) = builder.specials {
            *lead_byte |= 0x80;
            #[allow(clippy::unwrap_used)] // by trait invariant
            let (second_byte, remainder) = remainder.split_first_mut().unwrap();
            *second_byte = match u8::try_from(builder.default.1.encode_var_ule_len()) {
                Ok(x) => x,
                // TODO: Inform the user more nicely that their data doesn't fit in our packed structure
                #[allow(clippy::panic)] // for now okay since it is mostly only during datagen
                Err(_) => {
                    panic!("other value too long to be packed: {self:?}")
                }
            };
            let (v_bytes, specials_bytes) = remainder.split_at_mut(*second_byte as usize);
            builder.default.1.encode_var_ule_write(v_bytes);
            EncodeAsVarULE::<PluralElementsTupleSliceVarULE<V>>::encode_var_ule_write(
                &specials,
                specials_bytes,
            );
        } else {
            builder.default.1.encode_var_ule_write(remainder)
        };
    }
}

#[cfg(feature = "datagen")]
impl<'a, V> PluralElementsInner<(FourBitMetadata, &'a V)>
where
    V: VarULE + ?Sized,
{
    fn from_packed(packed: &'a PluralElementsPackedULE<V>) -> Self {
        let parts = packed.as_parts();
        PluralElementsInner {
            other: parts.default,
            zero: parts
                .specials
                .and_then(|specials| get_special(specials, PluralElementsKeysV1::Zero)),
            one: parts
                .specials
                .and_then(|specials| get_special(specials, PluralElementsKeysV1::One)),
            two: parts
                .specials
                .and_then(|specials| get_special(specials, PluralElementsKeysV1::Two)),
            few: parts
                .specials
                .and_then(|specials| get_special(specials, PluralElementsKeysV1::Few)),
            many: parts
                .specials
                .and_then(|specials| get_special(specials, PluralElementsKeysV1::Many)),
            explicit_zero: parts
                .specials
                .and_then(|specials| get_special(specials, PluralElementsKeysV1::ExplicitZero)),
            explicit_one: parts
                .specials
                .and_then(|specials| get_special(specials, PluralElementsKeysV1::ExplicitOne)),
        }
    }
}

#[cfg(feature = "serde")]
impl<T> PluralElementsInner<(FourBitMetadata, T)> {
    fn into_packed<V>(self) -> Box<PluralElementsPackedULE<V>>
    where
        T: PartialEq + fmt::Debug,
        for<'a> &'a T: EncodeAsVarULE<V>,
        V: VarULE + ?Sized,
    {
        zerovec::ule::encode_varule_to_box(&PluralElements(self))
    }
}

#[cfg(feature = "serde")]
impl<'de, 'data, V> serde::Deserialize<'de> for &'data PluralElementsPackedULE<V>
where
    'de: 'data,
    V: VarULE + ?Sized,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            Err(serde::de::Error::custom(
                "&PluralElementsPackedULE cannot be deserialized from human-readable formats",
            ))
        } else {
            let bytes = <&[u8]>::deserialize(deserializer)?;
            PluralElementsPackedULE::<V>::parse_bytes(bytes).map_err(serde::de::Error::custom)
        }
    }
}

#[cfg(feature = "serde")]
impl<'de, V> serde::Deserialize<'de> for Box<PluralElementsPackedULE<V>>
where
    V: VarULE + ?Sized,
    Box<V>: serde::Deserialize<'de> + PartialEq + fmt::Debug,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        if deserializer.is_human_readable() {
            let plural_elements: PluralElementsInner<(FourBitMetadata, Box<V>)> =
                PluralElementsInner::deserialize(deserializer)?;
            Ok(plural_elements.into_packed())
        } else {
            let bytes = <&[u8]>::deserialize(deserializer)?;
            PluralElementsPackedULE::<V>::parse_bytes(bytes)
                .map(|ule| ule.to_owned())
                .map_err(serde::de::Error::custom)
        }
    }
}

#[cfg(feature = "datagen")]
impl<V> serde::Serialize for PluralElementsPackedULE<V>
where
    V: PartialEq + serde::Serialize + VarULE + ?Sized,
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        if serializer.is_human_readable() {
            let plural_elements: PluralElementsInner<(FourBitMetadata, &V)> =
                PluralElementsInner::from_packed(self);
            plural_elements.serialize(serializer)
        } else {
            serializer.serialize_bytes(self.as_bytes())
        }
    }
}

#[cfg(feature = "datagen")]
impl<'a, V> databake::Bake for &'a PluralElementsPackedULE<V>
where
    &'a V: databake::Bake,
    V: VarULE + ?Sized,
{
    fn bake(&self, ctx: &databake::CrateEnv) -> databake::TokenStream {
        ctx.insert("icu_plurals");
        let bytes = (&self.bytes).bake(ctx);
        databake::quote! {
            // Safety: the bytes came directly from self.bytes on the previous line.
            unsafe { icu_plurals::provider::PluralElementsPackedULE::from_bytes_unchecked(#bytes) }
        }
    }
}

#[cfg(feature = "datagen")]
impl<'a, V> databake::BakeSize for &'a PluralElementsPackedULE<V>
where
    &'a V: databake::Bake,
    V: VarULE + ?Sized,
{
    fn borrows_size(&self) -> usize {
        self.bytes.len()
    }
}

/// Helper function to properly deserialize a `Cow<PluralElementsPackedULE<V>>`
///
/// Due to <https://github.com/rust-lang/rust/issues/130180>, you may need to qualify
/// `V` when invoking this, like so:
///
/// `#[serde(deserialize_with = "deserialize_plural_elements_packed_cow::<_, str>")]`
///
/// See <https://github.com/unicode-org/icu4x/pull/1556>
#[cfg(feature = "serde")]
fn deserialize_plural_elements_packed_cow<'de, 'data, D, V>(
    deserializer: D,
) -> Result<Cow<'data, PluralElementsPackedULE<V>>, D::Error>
where
    'de: 'data,
    D: serde::Deserializer<'de>,
    V: VarULE + ?Sized,
    Box<PluralElementsPackedULE<V>>: serde::Deserialize<'de>,
{
    use serde::Deserialize;
    if deserializer.is_human_readable() {
        let value = Box::<PluralElementsPackedULE<V>>::deserialize(deserializer)?;
        Ok(Cow::Owned(value))
    } else {
        let value = <&'de PluralElementsPackedULE<V>>::deserialize(deserializer)?;
        Ok(Cow::Borrowed(value))
    }
}

// Need a manual impl because the derive(Clone) impl bounds are wrong
impl<V> Clone for PluralElementsPackedCow<'_, V>
where
    V: VarULE + ?Sized,
{
    fn clone(&self) -> Self {
        Self {
            elements: self.elements.clone(),
        }
    }
}

impl<T, V> From<PluralElements<T>> for PluralElementsPackedCow<'static, V>
where
    V: VarULE + ?Sized,
    T: PartialEq + fmt::Debug,
    for<'a> &'a T: EncodeAsVarULE<V>,
{
    fn from(value: PluralElements<T>) -> Self {
        let elements =
            zerovec::ule::encode_varule_to_box(&value.map(|s| (FourBitMetadata::zero(), s)));
        Self {
            elements: Cow::Owned(elements),
        }
    }
}

impl<V> PluralElementsPackedCow<'_, V>
where
    V: VarULE + ?Sized,
{
    /// Returns the value for the given [`PluralOperands`] and [`PluralRules`].
    pub fn get<'a>(&'a self, op: PluralOperands, rules: &PluralRules) -> &'a V {
        self.elements.get(op, rules).1
    }
}

#[test]
fn test_serde_singleton_roundtrip() {
    let plural_elements = PluralElements::new((FourBitMetadata::zero(), "abc"));
    let ule = zerovec::ule::encode_varule_to_box(&plural_elements);

    let postcard_bytes = postcard::to_allocvec(&ule).unwrap();
    assert_eq!(
        postcard_bytes,
        &[
            4,    // Postcard header
            0x00, // Discriminant
            b'a', b'b', b'c', // String
        ]
    );

    let postcard_ule: Box<PluralElementsPackedULE<str>> =
        postcard::from_bytes(&postcard_bytes).unwrap();
    assert_eq!(ule, postcard_ule);

    let postcard_borrowed: &PluralElementsPackedULE<str> =
        postcard::from_bytes(&postcard_bytes).unwrap();
    assert_eq!(&*ule, postcard_borrowed);

    let postcard_cow: PluralElementsPackedCow<str> = postcard::from_bytes(&postcard_bytes).unwrap();
    assert_eq!(&*ule, &*postcard_cow.elements);
    assert!(matches!(postcard_cow.elements, Cow::Borrowed(_)));

    let json_str = serde_json::to_string(&ule).unwrap();
    let json_ule: Box<PluralElementsPackedULE<str>> = serde_json::from_str(&json_str).unwrap();
    assert_eq!(ule, json_ule);
}

#[test]
fn test_serde_nonsingleton_roundtrip() {
    let plural_elements = PluralElements::new((FourBitMetadata::zero(), "abc"))
        .with_one_value(Some((FourBitMetadata::zero(), "defg")));
    let ule = zerovec::ule::encode_varule_to_box(&plural_elements);

    let postcard_bytes = postcard::to_allocvec(&ule).unwrap();
    assert_eq!(
        postcard_bytes,
        &[
            12,   // Postcard header
            0x80, // Discriminant
            3, b'a', b'b', b'c', // String of length 3
            1, 0, // VarZeroVec of length 1
            0x10, b'd', b'e', b'f', b'g' // Plural category 1 and string "defg"
        ]
    );

    let postcard_ule: Box<PluralElementsPackedULE<str>> =
        postcard::from_bytes(&postcard_bytes).unwrap();
    assert_eq!(ule, postcard_ule);

    let postcard_borrowed: &PluralElementsPackedULE<str> =
        postcard::from_bytes(&postcard_bytes).unwrap();
    assert_eq!(&*ule, postcard_borrowed);

    let json_str = serde_json::to_string(&ule).unwrap();
    let json_ule: Box<PluralElementsPackedULE<str>> = serde_json::from_str(&json_str).unwrap();
    assert_eq!(ule, json_ule);
}