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
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
// 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 ).

use crate::{DataError, DataErrorKind};
use core::cmp::Ordering;
use core::default::Default;
use core::fmt;
use core::fmt::Debug;
use core::hash::Hash;
use core::str::FromStr;
use icu_locid::extensions::unicode as unicode_ext;
use icu_locid::subtags::{Language, Region, Script, Variants};
use icu_locid::{LanguageIdentifier, Locale, SubtagOrderingResult};
use writeable::{LengthHint, Writeable};

#[cfg(feature = "experimental")]
use alloc::string::String;
#[cfg(feature = "experimental")]
use core::ops::Deref;
#[cfg(feature = "experimental")]
use icu_locid::extensions::private::Subtag;
#[cfg(feature = "experimental")]
use tinystr::TinyAsciiStr;

#[cfg(doc)]
use icu_locid::subtags::Variant;

/// The request type passed into all data provider implementations.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq)]
#[allow(clippy::exhaustive_structs)] // this type is stable
pub struct DataRequest<'a> {
    /// The locale for which to load data.
    ///
    /// If locale fallback is enabled, the resulting data may be from a different locale
    /// than the one requested here.
    pub locale: &'a DataLocale,
    /// Metadata that may affect the behavior of the data provider.
    pub metadata: DataRequestMetadata,
}

impl fmt::Display for DataRequest<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.locale, f)
    }
}

/// Metadata for data requests. This is currently empty, but it may be extended with options
/// for tuning locale fallback, buffer layout, and so forth.
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
#[non_exhaustive]
pub struct DataRequestMetadata {
    /// Silent requests do not log errors. This can be used for exploratory querying, such as fallbacks.
    pub silent: bool,
}

/// A locale type optimized for use in fallbacking and the ICU4X data pipeline.
///
/// [`DataLocale`] contains less functionality than [`Locale`] but more than
/// [`LanguageIdentifier`] for better size and performance while still meeting
/// the needs of the ICU4X data pipeline.
///
/// # Examples
///
/// Convert a [`Locale`] to a [`DataLocale`] and back:
///
/// ```
/// use icu_locid::locale;
/// use icu_provider::DataLocale;
///
/// let locale = locale!("en-u-ca-buddhist");
/// let data_locale = DataLocale::from(locale);
/// let locale = data_locale.into_locale();
///
/// assert_eq!(locale, locale!("en-u-ca-buddhist"));
/// ```
///
/// You can alternatively create a [`DataLocale`] from a borrowed [`Locale`], which is more
/// efficient than cloning the [`Locale`], but less efficient than converting an owned
/// [`Locale`]:
///
/// ```
/// use icu_locid::locale;
/// use icu_provider::DataLocale;
///
/// let locale1 = locale!("en-u-ca-buddhist");
/// let data_locale = DataLocale::from(&locale1);
/// let locale2 = data_locale.into_locale();
///
/// assert_eq!(locale1, locale2);
/// ```
///
/// If you are sure that you have no Unicode keywords, start with [`LanguageIdentifier`]:
///
/// ```
/// use icu_locid::langid;
/// use icu_provider::DataLocale;
///
/// let langid = langid!("es-CA-valencia");
/// let data_locale = DataLocale::from(langid);
/// let langid = data_locale.get_langid();
///
/// assert_eq!(langid, langid!("es-CA-valencia"));
/// ```
///
/// [`DataLocale`] only supports `-u` keywords, to reflect the current state of CLDR data
/// lookup and fallback. This may change in the future.
///
/// ```
/// use icu_locid::{locale, Locale};
/// use icu_provider::DataLocale;
///
/// let locale = "hi-t-en-h0-hybrid-u-attr-ca-buddhist"
///     .parse::<Locale>()
///     .unwrap();
/// let data_locale = DataLocale::from(locale);
///
/// assert_eq!(data_locale.into_locale(), locale!("hi-u-ca-buddhist"));
/// ```
#[derive(PartialEq, Clone, Default, Eq, Hash)]
pub struct DataLocale {
    langid: LanguageIdentifier,
    keywords: unicode_ext::Keywords,
    #[cfg(feature = "experimental")]
    aux: Option<AuxiliaryKeys>,
}

impl<'a> Default for &'a DataLocale {
    fn default() -> Self {
        static DEFAULT: DataLocale = DataLocale {
            langid: LanguageIdentifier::UND,
            keywords: unicode_ext::Keywords::new(),
            #[cfg(feature = "experimental")]
            aux: None,
        };
        &DEFAULT
    }
}

impl fmt::Debug for DataLocale {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "DataLocale{{{self}}}")
    }
}

impl Writeable for DataLocale {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
        self.langid.write_to(sink)?;
        if !self.keywords.is_empty() {
            sink.write_str("-u-")?;
            self.keywords.write_to(sink)?;
        }
        #[cfg(feature = "experimental")]
        if let Some(aux) = self.aux.as_ref() {
            sink.write_str("-x-")?;
            aux.write_to(sink)?;
        }
        Ok(())
    }

    fn writeable_length_hint(&self) -> LengthHint {
        let mut length_hint = self.langid.writeable_length_hint();
        if !self.keywords.is_empty() {
            length_hint += self.keywords.writeable_length_hint() + 3;
        }
        #[cfg(feature = "experimental")]
        if let Some(aux) = self.aux.as_ref() {
            length_hint += aux.writeable_length_hint() + 3;
        }
        length_hint
    }

    fn write_to_string(&self) -> alloc::borrow::Cow<str> {
        #[cfg_attr(not(feature = "experimental"), allow(unused_mut))]
        let mut is_only_langid = self.keywords.is_empty();
        #[cfg(feature = "experimental")]
        {
            is_only_langid = is_only_langid && self.aux.is_none();
        }
        if is_only_langid {
            return self.langid.write_to_string();
        }
        let mut string =
            alloc::string::String::with_capacity(self.writeable_length_hint().capacity());
        let _ = self.write_to(&mut string);
        alloc::borrow::Cow::Owned(string)
    }
}

writeable::impl_display_with_writeable!(DataLocale);

impl From<LanguageIdentifier> for DataLocale {
    fn from(langid: LanguageIdentifier) -> Self {
        Self {
            langid,
            keywords: unicode_ext::Keywords::new(),
            #[cfg(feature = "experimental")]
            aux: None,
        }
    }
}

impl From<Locale> for DataLocale {
    fn from(locale: Locale) -> Self {
        Self {
            langid: locale.id,
            keywords: locale.extensions.unicode.keywords,
            #[cfg(feature = "experimental")]
            aux: AuxiliaryKeys::try_from_iter(locale.extensions.private.iter().copied()).ok(),
        }
    }
}

impl From<&LanguageIdentifier> for DataLocale {
    fn from(langid: &LanguageIdentifier) -> Self {
        Self {
            langid: langid.clone(),
            keywords: unicode_ext::Keywords::new(),
            #[cfg(feature = "experimental")]
            aux: None,
        }
    }
}

impl From<&Locale> for DataLocale {
    fn from(locale: &Locale) -> Self {
        Self {
            langid: locale.id.clone(),
            keywords: locale.extensions.unicode.keywords.clone(),
            #[cfg(feature = "experimental")]
            aux: AuxiliaryKeys::try_from_iter(locale.extensions.private.iter().copied()).ok(),
        }
    }
}

impl FromStr for DataLocale {
    type Err = DataError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let locale = Locale::from_str(s).map_err(|e| {
            DataErrorKind::KeyLocaleSyntax
                .into_error()
                .with_display_context(s)
                .with_display_context(&e)
        })?;
        Ok(DataLocale::from(locale))
    }
}

impl DataLocale {
    /// Compare this [`DataLocale`] with BCP-47 bytes.
    ///
    /// The return value is equivalent to what would happen if you first converted this
    /// [`DataLocale`] to a BCP-47 string and then performed a byte comparison.
    ///
    /// This function is case-sensitive and results in a *total order*, so it is appropriate for
    /// binary search. The only argument producing [`Ordering::Equal`] is `self.to_string()`.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_locid::Locale;
    /// use icu_provider::DataLocale;
    /// use std::cmp::Ordering;
    ///
    /// let bcp47_strings: &[&str] = &[
    ///     "ca",
    ///     "ca-ES",
    ///     "ca-ES-u-ca-buddhist",
    ///     "ca-ES-valencia",
    ///     "ca-ES-x-gbp",
    ///     "ca-ES-x-gbp-short",
    ///     "ca-ES-x-usd",
    ///     "ca-ES-xyzabc",
    ///     "ca-x-eur",
    ///     "cat",
    ///     "pl-Latn-PL",
    ///     "und",
    ///     "und-fonipa",
    ///     "und-u-ca-hebrew",
    ///     "und-u-ca-japanese",
    ///     "und-x-mxn",
    ///     "zh",
    /// ];
    ///
    /// for ab in bcp47_strings.windows(2) {
    ///     let a = ab[0];
    ///     let b = ab[1];
    ///     assert_eq!(a.cmp(b), Ordering::Less, "strings: {} < {}", a, b);
    ///     let a_loc: DataLocale = a.parse().unwrap();
    ///     assert_eq!(
    ///         a_loc.strict_cmp(a.as_bytes()),
    ///         Ordering::Equal,
    ///         "strict_cmp: {} == {}",
    ///         a_loc,
    ///         a
    ///     );
    ///     assert_eq!(
    ///         a_loc.strict_cmp(b.as_bytes()),
    ///         Ordering::Less,
    ///         "strict_cmp: {} < {}",
    ///         a_loc,
    ///         b
    ///     );
    ///     let b_loc: DataLocale = b.parse().unwrap();
    ///     assert_eq!(
    ///         b_loc.strict_cmp(b.as_bytes()),
    ///         Ordering::Equal,
    ///         "strict_cmp: {} == {}",
    ///         b_loc,
    ///         b
    ///     );
    ///     assert_eq!(
    ///         b_loc.strict_cmp(a.as_bytes()),
    ///         Ordering::Greater,
    ///         "strict_cmp: {} > {}",
    ///         b_loc,
    ///         a
    ///     );
    /// }
    /// ```
    ///
    /// Comparison against invalid strings:
    ///
    /// ```
    /// use icu_provider::DataLocale;
    ///
    /// let invalid_strings: &[&str] = &[
    ///     // Less than "ca-ES"
    ///     "CA",
    ///     "ar-x-gbp-FOO",
    ///     // Greater than "ca-ES-x-gbp"
    ///     "ca_ES",
    ///     "ca-ES-x-gbp-FOO",
    /// ];
    ///
    /// let data_locale = "ca-ES-x-gbp".parse::<DataLocale>().unwrap();
    ///
    /// for s in invalid_strings.iter() {
    ///     let expected_ordering = "ca-ES-x-gbp".cmp(s);
    ///     let actual_ordering = data_locale.strict_cmp(s.as_bytes());
    ///     assert_eq!(expected_ordering, actual_ordering, "{}", s);
    /// }
    /// ```
    pub fn strict_cmp(&self, other: &[u8]) -> Ordering {
        let subtags = other.split(|b| *b == b'-');
        let mut subtag_result = self.langid.strict_cmp_iter(subtags);
        if self.has_unicode_ext() {
            let mut subtags = match subtag_result {
                SubtagOrderingResult::Subtags(s) => s,
                SubtagOrderingResult::Ordering(o) => return o,
            };
            match subtags.next() {
                Some(b"u") => (),
                Some(s) => return s.cmp(b"u").reverse(),
                None => return Ordering::Greater,
            }
            subtag_result = self.keywords.strict_cmp_iter(subtags);
        }
        #[cfg(feature = "experimental")]
        if let Some(aux) = self.get_aux() {
            let mut subtags = match subtag_result {
                SubtagOrderingResult::Subtags(s) => s,
                SubtagOrderingResult::Ordering(o) => return o,
            };
            match subtags.next() {
                Some(b"x") => (),
                Some(s) => return s.cmp(b"x").reverse(),
                None => return Ordering::Greater,
            }
            subtag_result = aux.strict_cmp_iter(subtags);
        }
        subtag_result.end()
    }
}

impl DataLocale {
    /// Returns whether this [`DataLocale`] has all empty fields (no components).
    ///
    /// See also:
    ///
    /// - [`DataLocale::is_und()`]
    /// - [`DataLocale::is_langid_und()`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::DataLocale;
    ///
    /// assert!("und".parse::<DataLocale>().unwrap().is_empty());
    /// assert!(!"und-u-ca-buddhist"
    ///     .parse::<DataLocale>()
    ///     .unwrap()
    ///     .is_empty());
    /// assert!(!"und-x-aux".parse::<DataLocale>().unwrap().is_empty());
    /// assert!(!"ca-ES".parse::<DataLocale>().unwrap().is_empty());
    /// ```
    pub fn is_empty(&self) -> bool {
        self == <&DataLocale>::default()
    }

    /// Returns whether this [`DataLocale`] is `und` in the locale and extensions portion.
    ///
    /// This ignores auxiliary keys.
    ///
    /// See also:
    ///
    /// - [`DataLocale::is_empty()`]
    /// - [`DataLocale::is_langid_und()`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::DataLocale;
    ///
    /// assert!("und".parse::<DataLocale>().unwrap().is_und());
    /// assert!(!"und-u-ca-buddhist".parse::<DataLocale>().unwrap().is_und());
    /// assert!("und-x-aux".parse::<DataLocale>().unwrap().is_und());
    /// assert!(!"ca-ES".parse::<DataLocale>().unwrap().is_und());
    /// ```
    pub fn is_und(&self) -> bool {
        self.langid == LanguageIdentifier::UND && self.keywords.is_empty()
    }

    /// Returns whether the [`LanguageIdentifier`] associated with this request is `und`.
    ///
    /// This ignores extension keywords and auxiliary keys.
    ///
    /// See also:
    ///
    /// - [`DataLocale::is_empty()`]
    /// - [`DataLocale::is_und()`]
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_provider::DataLocale;
    ///
    /// assert!("und".parse::<DataLocale>().unwrap().is_langid_und());
    /// assert!("und-u-ca-buddhist"
    ///     .parse::<DataLocale>()
    ///     .unwrap()
    ///     .is_langid_und());
    /// assert!("und-x-aux".parse::<DataLocale>().unwrap().is_langid_und());
    /// assert!(!"ca-ES".parse::<DataLocale>().unwrap().is_langid_und());
    /// ```
    pub fn is_langid_und(&self) -> bool {
        self.langid == LanguageIdentifier::UND
    }

    /// Gets the [`LanguageIdentifier`] for this [`DataLocale`].
    ///
    /// This may allocate memory if there are variant subtags. If you need only the language,
    /// script, and/or region subtag, use the specific getters for those subtags:
    ///
    /// - [`DataLocale::language()`]
    /// - [`DataLocale::script()`]
    /// - [`DataLocale::region()`]
    ///
    /// If you have ownership over the `DataLocale`, use [`DataLocale::into_locale()`]
    /// and then access the `id` field.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_locid::langid;
    /// use icu_provider::prelude::*;
    ///
    /// const FOO_BAR: DataKey = icu_provider::data_key!("foo/bar@1");
    ///
    /// let req_no_langid = DataRequest {
    ///     locale: &Default::default(),
    ///     metadata: Default::default(),
    /// };
    ///
    /// let req_with_langid = DataRequest {
    ///     locale: &langid!("ar-EG").into(),
    ///     metadata: Default::default(),
    /// };
    ///
    /// assert_eq!(req_no_langid.locale.get_langid(), langid!("und"));
    /// assert_eq!(req_with_langid.locale.get_langid(), langid!("ar-EG"));
    /// ```
    pub fn get_langid(&self) -> LanguageIdentifier {
        self.langid.clone()
    }

    /// Overrides the entire [`LanguageIdentifier`] portion of this [`DataLocale`].
    #[inline]
    pub fn set_langid(&mut self, lid: LanguageIdentifier) {
        self.langid = lid;
    }

    /// Converts this [`DataLocale`] into a [`Locale`].
    ///
    /// See also [`DataLocale::get_langid()`].
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_locid::{
    ///     langid, locale,
    ///     subtags::{language, region},
    ///     Locale,
    /// };
    /// use icu_provider::prelude::*;
    ///
    /// let locale: DataLocale = locale!("it-IT-u-ca-coptic").into();
    ///
    /// assert_eq!(locale.get_langid(), langid!("it-IT"));
    /// assert_eq!(locale.language(), language!("it"));
    /// assert_eq!(locale.script(), None);
    /// assert_eq!(locale.region(), Some(region!("IT")));
    ///
    /// let locale = locale.into_locale();
    /// assert_eq!(locale, locale!("it-IT-u-ca-coptic"));
    /// ```
    ///
    /// Auxiliary keys are retained:
    ///
    /// ```
    /// use icu_locid::Locale;
    /// use icu_provider::prelude::*;
    /// use writeable::assert_writeable_eq;
    ///
    /// let locale: Locale = "und-u-nu-arab-x-gbp".parse().unwrap();
    /// let data_locale = DataLocale::from(locale);
    /// assert_writeable_eq!(data_locale, "und-u-nu-arab-x-gbp");
    ///
    /// let recovered_locale = data_locale.into_locale();
    /// assert_writeable_eq!(recovered_locale, "und-u-nu-arab-x-gbp");
    /// ```
    pub fn into_locale(self) -> Locale {
        let mut loc = Locale {
            id: self.langid,
            ..Default::default()
        };
        loc.extensions.unicode.keywords = self.keywords;
        #[cfg(feature = "experimental")]
        if let Some(aux) = self.aux {
            loc.extensions.private =
                icu_locid::extensions::private::Private::from_vec_unchecked(aux.iter().collect());
        }
        loc
    }

    /// Returns the [`Language`] for this [`DataLocale`].
    #[inline]
    pub fn language(&self) -> Language {
        self.langid.language
    }

    /// Returns the [`Language`] for this [`DataLocale`].
    #[inline]
    pub fn set_language(&mut self, language: Language) {
        self.langid.language = language;
    }

    /// Returns the [`Script`] for this [`DataLocale`].
    #[inline]
    pub fn script(&self) -> Option<Script> {
        self.langid.script
    }

    /// Sets the [`Script`] for this [`DataLocale`].
    #[inline]
    pub fn set_script(&mut self, script: Option<Script>) {
        self.langid.script = script;
    }

    /// Returns the [`Region`] for this [`DataLocale`].
    #[inline]
    pub fn region(&self) -> Option<Region> {
        self.langid.region
    }

    /// Sets the [`Region`] for this [`DataLocale`].
    #[inline]
    pub fn set_region(&mut self, region: Option<Region>) {
        self.langid.region = region;
    }

    /// Returns whether there are any [`Variant`] subtags in this [`DataLocale`].
    #[inline]
    pub fn has_variants(&self) -> bool {
        !self.langid.variants.is_empty()
    }

    /// Sets all [`Variants`] on this [`DataLocale`], overwriting any that were there previously.
    #[inline]
    pub fn set_variants(&mut self, variants: Variants) {
        self.langid.variants = variants;
    }

    /// Removes all [`Variant`] subtags in this [`DataLocale`].
    #[inline]
    pub fn clear_variants(&mut self) -> Variants {
        self.langid.variants.clear()
    }

    /// Gets the value of the specified Unicode extension keyword for this [`DataLocale`].
    #[inline]
    pub fn get_unicode_ext(&self, key: &unicode_ext::Key) -> Option<unicode_ext::Value> {
        self.keywords.get(key).cloned()
    }

    /// Returns whether there are any Unicode extension keywords in this [`DataLocale`].
    #[inline]
    pub fn has_unicode_ext(&self) -> bool {
        !self.keywords.is_empty()
    }

    /// Returns whether a specific Unicode extension keyword is present in this [`DataLocale`].
    #[inline]
    pub fn contains_unicode_ext(&self, key: &unicode_ext::Key) -> bool {
        self.keywords.contains_key(key)
    }

    /// Returns whether this [`DataLocale`] contains a Unicode extension keyword
    /// with the specified key and value.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_locid::{
    ///     extensions::unicode::{key, value},
    ///     Locale,
    /// };
    /// use icu_provider::prelude::*;
    ///
    /// let locale: Locale = "it-IT-u-ca-coptic".parse().expect("Valid BCP-47");
    /// let locale: DataLocale = locale.into();
    ///
    /// assert_eq!(locale.get_unicode_ext(&key!("hc")), None);
    /// assert_eq!(locale.get_unicode_ext(&key!("ca")), Some(value!("coptic")));
    /// assert!(locale.matches_unicode_ext(&key!("ca"), &value!("coptic"),));
    /// ```
    #[inline]
    pub fn matches_unicode_ext(&self, key: &unicode_ext::Key, value: &unicode_ext::Value) -> bool {
        self.keywords.get(key) == Some(value)
    }

    /// Sets the value for a specific Unicode extension keyword on this [`DataLocale`].
    #[inline]
    pub fn set_unicode_ext(
        &mut self,
        key: unicode_ext::Key,
        value: unicode_ext::Value,
    ) -> Option<unicode_ext::Value> {
        self.keywords.set(key, value)
    }

    /// Removes a specific Unicode extension keyword from this [`DataLocale`], returning
    /// the value if it was present.
    #[inline]
    pub fn remove_unicode_ext(&mut self, key: &unicode_ext::Key) -> Option<unicode_ext::Value> {
        self.keywords.remove(key)
    }

    /// Retains a subset of keywords as specified by the predicate function.
    #[inline]
    pub fn retain_unicode_ext<F>(&mut self, predicate: F)
    where
        F: FnMut(&unicode_ext::Key) -> bool,
    {
        self.keywords.retain_by_key(predicate)
    }

    /// Gets the auxiliary key for this [`DataLocale`].
    ///
    /// For more information and examples, see [`AuxiliaryKeys`].
    #[cfg(feature = "experimental")]
    pub fn get_aux(&self) -> Option<&AuxiliaryKeys> {
        self.aux.as_ref()
    }

    /// Returns whether this [`DataLocale`] has an auxiliary key.
    ///
    /// For more information and examples, see [`AuxiliaryKeys`].
    #[cfg(feature = "experimental")]
    pub fn has_aux(&self) -> bool {
        self.aux.is_some()
    }

    /// Sets an auxiliary key on this [`DataLocale`].
    ///
    /// Returns the previous auxiliary key if present.
    ///
    /// For more information and examples, see [`AuxiliaryKeys`].
    #[cfg(feature = "experimental")]
    pub fn set_aux(&mut self, value: AuxiliaryKeys) -> Option<AuxiliaryKeys> {
        self.aux.replace(value)
    }

    /// Remove an auxiliary key, if present. Returns the removed auxiliary key.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_locid::locale;
    /// use icu_provider::prelude::*;
    /// use writeable::assert_writeable_eq;
    ///
    /// let mut data_locale: DataLocale = locale!("ar-EG").into();
    /// let aux = "gbp"
    ///     .parse::<AuxiliaryKeys>()
    ///     .expect("contains valid characters");
    /// data_locale.set_aux(aux);
    /// assert_writeable_eq!(data_locale, "ar-EG-x-gbp");
    ///
    /// let maybe_aux = data_locale.remove_aux();
    /// assert_writeable_eq!(data_locale, "ar-EG");
    /// assert_writeable_eq!(maybe_aux.unwrap(), "gbp");
    /// ```
    #[cfg(feature = "experimental")]
    pub fn remove_aux(&mut self) -> Option<AuxiliaryKeys> {
        self.aux.take()
    }
}

/// The "auxiliary key" is an annotation on [`DataLocale`] that can contain an arbitrary
/// information that does not fit into the [`LanguageIdentifier`] or [`Keywords`].
///
/// A [`DataLocale`] can have multiple auxiliary keys, represented by this struct. The auxiliary
/// keys are stored as private use subtags following `-x-`.
///
/// An auxiliary key currently allows 1-8 lowercase alphanumerics.
///
/// <div class="stab unstable">
/// 🚧 This code is experimental; it may change at any time, in breaking or non-breaking ways,
/// including in SemVer minor releases. It can be enabled with the "experimental" Cargo feature
/// of the `icu_provider` crate. Use with caution.
/// <a href="https://github.com/unicode-org/icu4x/issues/3632">#3632</a>
/// </div>
///
/// # Examples
///
/// ```
/// use icu_locid::locale;
/// use icu_provider::prelude::*;
/// use writeable::assert_writeable_eq;
///
/// let mut data_locale: DataLocale = locale!("ar-EG").into();
/// assert_writeable_eq!(data_locale, "ar-EG");
/// assert!(!data_locale.has_aux());
/// assert_eq!(data_locale.get_aux(), None);
///
/// let aux = "gbp"
///     .parse::<AuxiliaryKeys>()
///     .expect("contains valid characters");
///
/// data_locale.set_aux(aux);
/// assert_writeable_eq!(data_locale, "ar-EG-x-gbp");
/// assert!(data_locale.has_aux());
/// assert_eq!(data_locale.get_aux(), Some(&"gbp".parse().unwrap()));
/// ```
///
/// Multiple auxiliary keys are allowed:
///
/// ```
/// use icu_locid::locale;
/// use icu_provider::prelude::*;
/// use writeable::assert_writeable_eq;
///
/// let data_locale = "ar-EG-x-gbp-long".parse::<DataLocale>().unwrap();
/// assert_writeable_eq!(data_locale, "ar-EG-x-gbp-long");
/// assert_eq!(data_locale.get_aux().unwrap().iter().count(), 2);
/// ```
///
/// Not all strings are valid auxiliary keys.
/// The string must be well-formed and case-normalized:
///
/// ```
/// use icu_provider::prelude::*;
///
/// assert!("abcdefg".parse::<AuxiliaryKeys>().is_ok());
/// assert!("abc-xyz".parse::<AuxiliaryKeys>().is_ok());
///
/// assert!("".parse::<AuxiliaryKeys>().is_err());
/// assert!("!@#$%".parse::<AuxiliaryKeys>().is_err());
/// assert!("abc_xyz".parse::<AuxiliaryKeys>().is_err());
/// assert!("ABC123".parse::<AuxiliaryKeys>().is_err());
/// ```
///
/// [`Keywords`]: unicode_ext::Keywords
#[derive(Debug, PartialEq, Clone, Eq, Hash)]
#[cfg(feature = "experimental")]
pub struct AuxiliaryKeys {
    value: AuxiliaryKeysInner,
}

#[cfg(feature = "experimental")]
#[derive(Clone)]
enum AuxiliaryKeysInner {
    Boxed(alloc::boxed::Box<str>),
    Stack(TinyAsciiStr<23>),
    // NOTE: In the future, a `Static` variant could be added to allow `data_locale!("...")`
    // Static(&'static str),
}

#[cfg(feature = "experimental")]
impl Deref for AuxiliaryKeysInner {
    type Target = str;
    #[inline]
    fn deref(&self) -> &Self::Target {
        match self {
            Self::Boxed(s) => s.deref(),
            Self::Stack(s) => s.as_str(),
        }
    }
}

#[cfg(feature = "experimental")]
impl PartialEq for AuxiliaryKeysInner {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.deref() == other.deref()
    }
}

#[cfg(feature = "experimental")]
impl Eq for AuxiliaryKeysInner {}

#[cfg(feature = "experimental")]
impl Debug for AuxiliaryKeysInner {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.deref().fmt(f)
    }
}

#[cfg(feature = "experimental")]
impl Hash for AuxiliaryKeysInner {
    #[inline]
    fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
        self.deref().hash(state)
    }
}

#[cfg(feature = "experimental")]
writeable::impl_display_with_writeable!(AuxiliaryKeys);

#[cfg(feature = "experimental")]
impl Writeable for AuxiliaryKeys {
    fn write_to<W: fmt::Write + ?Sized>(&self, sink: &mut W) -> fmt::Result {
        self.value.write_to(sink)
    }
    fn writeable_length_hint(&self) -> LengthHint {
        self.value.writeable_length_hint()
    }
    fn write_to_string(&self) -> alloc::borrow::Cow<str> {
        self.value.write_to_string()
    }
}

#[cfg(feature = "experimental")]
impl FromStr for AuxiliaryKeys {
    type Err = DataError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from_str(s)
    }
}

#[cfg(feature = "experimental")]
impl AuxiliaryKeys {
    /// Creates an [`AuxiliaryKeys`] from an iterator of individual keys.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_locid::extensions::private::subtag;
    /// use icu_provider::prelude::*;
    ///
    /// // Single auxiliary key:
    /// let a = AuxiliaryKeys::try_from_iter([subtag!("abc")]).unwrap();
    /// let b = "abc".parse::<AuxiliaryKeys>().unwrap();
    /// assert_eq!(a, b);
    ///
    /// // Multiple auxiliary keys:
    /// let a = AuxiliaryKeys::try_from_iter([subtag!("abc"), subtag!("defg")])
    ///     .unwrap();
    /// let b = "abc-defg".parse::<AuxiliaryKeys>().unwrap();
    /// assert_eq!(a, b);
    /// ```
    ///
    /// The iterator can't be empty:
    ///
    /// ```
    /// use icu_provider::prelude::*;
    ///
    /// assert!(AuxiliaryKeys::try_from_iter([]).is_err());
    /// ```
    pub fn try_from_iter(iter: impl IntoIterator<Item = Subtag>) -> Result<Self, DataError> {
        // TODO: Avoid the allocation when possible
        let mut builder = String::new();
        for item in iter {
            if !builder.is_empty() {
                builder.push(AuxiliaryKeys::separator());
            }
            builder.push_str(item.as_str())
        }
        if builder.is_empty() {
            return Err(DataErrorKind::KeyLocaleSyntax.with_str_context("empty aux iterator"));
        }
        if builder.len() <= 23 {
            #[allow(clippy::unwrap_used)] // we just checked that the string is ascii
            Ok(Self {
                value: AuxiliaryKeysInner::Stack(builder.parse().unwrap()),
            })
        } else {
            Ok(Self {
                value: AuxiliaryKeysInner::Boxed(builder.into()),
            })
        }
    }

    /// Creates an [`AuxiliaryKeys`] from a single subtag.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_locid::extensions::private::subtag;
    /// use icu_provider::prelude::*;
    ///
    /// // Single auxiliary key:
    /// let a = AuxiliaryKeys::from_subtag(subtag!("abc"));
    /// let b = "abc".parse::<AuxiliaryKeys>().unwrap();
    /// assert_eq!(a, b);
    /// ```
    pub const fn from_subtag(input: Subtag) -> Self {
        Self {
            value: AuxiliaryKeysInner::Stack(input.into_tinystr().resize()),
        }
    }

    pub(crate) fn try_from_str(s: &str) -> Result<Self, DataError> {
        if !s.is_empty()
            && s.split(Self::separator()).all(|b| {
                if let Ok(subtag) = Subtag::from_str(b) {
                    // Enforces normalization:
                    b == subtag.as_str()
                } else {
                    false
                }
            })
        {
            if s.len() <= 23 {
                #[allow(clippy::unwrap_used)] // we just checked that the string is ascii
                Ok(Self {
                    value: AuxiliaryKeysInner::Stack(s.parse().unwrap()),
                })
            } else {
                Ok(Self {
                    value: AuxiliaryKeysInner::Boxed(s.into()),
                })
            }
        } else {
            Err(DataErrorKind::KeyLocaleSyntax
                .into_error()
                .with_display_context(s))
        }
    }

    /// Iterates over the components of the auxiliary key.
    ///
    /// # Example
    ///
    /// ```
    /// use icu_locid::extensions::private::subtag;
    /// use icu_provider::AuxiliaryKeys;
    ///
    /// let aux: AuxiliaryKeys = "abc-defg".parse().unwrap();
    /// assert_eq!(
    ///     aux.iter().collect::<Vec<_>>(),
    ///     vec![subtag!("abc"), subtag!("defg")]
    /// );
    /// ```
    pub fn iter(&self) -> impl Iterator<Item = Subtag> + '_ {
        self.value
            .split(Self::separator())
            .filter_map(|x| match x.parse() {
                Ok(x) => Some(x),
                Err(_) => {
                    debug_assert!(false, "failed to convert to subtag: {x}");
                    None
                }
            })
    }

    pub(crate) fn strict_cmp_iter<'l, I>(&self, mut subtags: I) -> SubtagOrderingResult<I>
    where
        I: Iterator<Item = &'l [u8]>,
    {
        for subtag in self.value.split(Self::separator()) {
            if let Some(other) = subtags.next() {
                match subtag.as_bytes().cmp(other) {
                    Ordering::Equal => (),
                    not_equal => return SubtagOrderingResult::Ordering(not_equal),
                }
            } else {
                return SubtagOrderingResult::Ordering(Ordering::Greater);
            }
        }
        SubtagOrderingResult::Subtags(subtags)
    }

    /// Returns the internal separator byte used for auxiliary keys in data locales.
    ///
    /// This is, according to BCP-47, an ASCII hyphen.
    #[inline]
    pub(crate) const fn separator() -> char {
        '-'
    }
}

#[cfg(feature = "experimental")]
impl From<Subtag> for AuxiliaryKeys {
    fn from(subtag: Subtag) -> Self {
        #[allow(clippy::expect_used)] // subtags definitely fit within auxiliary keys
        Self {
            value: AuxiliaryKeysInner::Stack(
                TinyAsciiStr::from_bytes(subtag.as_str().as_bytes())
                    .expect("Subtags are capped to 8 elements, AuxiliaryKeys supports up to 23"),
            ),
        }
    }
}

#[test]
fn test_data_locale_to_string() {
    use icu_locid::locale;

    struct TestCase {
        pub locale: Locale,
        pub aux: Option<&'static str>,
        pub expected: &'static str,
    }

    for cas in [
        TestCase {
            locale: Locale::UND,
            aux: None,
            expected: "und",
        },
        TestCase {
            locale: locale!("und-u-cu-gbp"),
            aux: None,
            expected: "und-u-cu-gbp",
        },
        TestCase {
            locale: locale!("en-ZA-u-cu-gbp"),
            aux: None,
            expected: "en-ZA-u-cu-gbp",
        },
        #[cfg(feature = "experimental")]
        TestCase {
            locale: locale!("en-ZA-u-nu-arab"),
            aux: Some("gbp"),
            expected: "en-ZA-u-nu-arab-x-gbp",
        },
    ] {
        let mut data_locale = DataLocale::from(cas.locale);
        #[cfg(feature = "experimental")]
        if let Some(aux) = cas.aux {
            data_locale.set_aux(aux.parse().unwrap());
        }
        writeable::assert_writeable_eq!(data_locale, cas.expected);
    }
}

#[test]
fn test_data_locale_from_string() {
    #[derive(Debug)]
    struct TestCase {
        pub input: &'static str,
        pub success: bool,
    }

    for cas in [
        TestCase {
            input: "und",
            success: true,
        },
        TestCase {
            input: "und-u-cu-gbp",
            success: true,
        },
        TestCase {
            input: "en-ZA-u-cu-gbp",
            success: true,
        },
        TestCase {
            input: "en...",
            success: false,
        },
        #[cfg(feature = "experimental")]
        TestCase {
            input: "en-ZA-u-nu-arab-x-gbp",
            success: true,
        },
        #[cfg(not(feature = "experimental"))]
        TestCase {
            input: "en-ZA-u-nu-arab-x-gbp",
            success: false,
        },
    ] {
        let data_locale = match (DataLocale::from_str(cas.input), cas.success) {
            (Ok(l), true) => l,
            (Err(_), false) => {
                continue;
            }
            (Ok(_), false) => {
                panic!("DataLocale parsed but it was supposed to fail: {cas:?}");
            }
            (Err(_), true) => {
                panic!("DataLocale was supposed to parse but it failed: {cas:?}");
            }
        };
        writeable::assert_writeable_eq!(data_locale, cas.input);
    }
}