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
// 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 core::str::FromStr;

use crate::parser::ParseError;
use crate::subtags::{Region, Subtag};

impl_tinystr_subtag!(
    /// A subdivision suffix used in [`SubdivisionId`].
    ///
    /// This suffix represents a specific subdivision code under a given [`Region`].
    /// For example the value of [`SubdivisionId`] may be `gbsct`, where the [`SubdivisionSuffix`]
    /// is `sct` for Scotland.
    ///
    /// Such a value associated with a key `rg` means that the locale should use Unit Preferences
    /// (default calendar, currency, week data, time cycle, measurement system) for Scotland, even if the
    /// [`LanguageIdentifier`](crate::LanguageIdentifier) is `en-US`.
    ///
    /// A subdivision suffix has to be a sequence of alphanumerical characters no
    /// shorter than one and no longer than four characters.
    ///
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::locale::extensions::unicode::{subdivision_suffix, SubdivisionSuffix};
    ///
    /// let ss: SubdivisionSuffix =
    ///     "sct".parse().expect("Failed to parse a SubdivisionSuffix.");
    ///
    /// assert_eq!(ss, subdivision_suffix!("sct"));
    /// ```
    SubdivisionSuffix,
    extensions::unicode,
    subdivision_suffix,
    extensions_unicode_subdivision_suffix,
    1..=4,
    s,
    s.is_ascii_alphanumeric(),
    s.to_ascii_lowercase(),
    s.is_ascii_alphanumeric() && s.is_ascii_lowercase(),
    InvalidExtension,
    ["sct"],
    ["toolooong"],
);

/// A Subivision Id as defined in [`Unicode Locale Identifier`].
///
/// Subdivision Id is used in [`Unicode`] extensions:
///  * `rg` - Regional Override
///  * `sd` - Regional Subdivision
///
/// In both cases the subdivision is composed of a [`Region`] and a [`SubdivisionSuffix`] which represents
/// different meaning depending on the key.
///
/// [`Unicode Locale Identifier`]: https://unicode.org/reports/tr35/tr35.html#unicode_subdivision_id
/// [`Unicode`]: crate::extensions::unicode::Unicode
///
/// # Examples
///
/// ```
/// use icu::locale::{
///     extensions::unicode::{subdivision_suffix, SubdivisionId},
///     subtags::region,
/// };
///
/// let ss = subdivision_suffix!("zzzz");
/// let region = region!("gb");
///
/// let si = SubdivisionId::new(region, ss);
///
/// assert_eq!(si.to_string(), "gbzzzz");
/// ```
#[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord, Copy)]
#[non_exhaustive]
pub struct SubdivisionId {
    /// A region field of a Subdivision Id.
    pub region: Region,
    /// A subdivision suffix field of a Subdivision Id.
    pub suffix: SubdivisionSuffix,
}

impl SubdivisionId {
    /// Returns a new [`SubdivisionId`].
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::locale::{
    ///     extensions::unicode::{subdivision_suffix, SubdivisionId},
    ///     subtags::region,
    /// };
    ///
    /// let ss = subdivision_suffix!("zzzz");
    /// let region = region!("gb");
    ///
    /// let si = SubdivisionId::new(region, ss);
    ///
    /// assert_eq!(si.to_string(), "gbzzzz");
    /// ```
    pub const fn new(region: Region, suffix: SubdivisionSuffix) -> Self {
        Self { region, suffix }
    }

    /// A constructor which takes a str slice, parses it and
    /// produces a well-formed [`SubdivisionId`].
    #[inline]
    pub fn try_from_str(s: &str) -> Result<Self, ParseError> {
        Self::try_from_utf8(s.as_bytes())
    }

    /// See [`Self::try_from_str`]
    pub fn try_from_utf8(code_units: &[u8]) -> Result<Self, ParseError> {
        let is_alpha = code_units
            .first()
            .and_then(|b| {
                b.is_ascii_alphabetic()
                    .then_some(true)
                    .or_else(|| b.is_ascii_digit().then_some(false))
            })
            .ok_or(ParseError::InvalidExtension)?;
        let region_len = if is_alpha { 2 } else { 3 };
        if code_units.len() < region_len + 1 {
            return Err(ParseError::InvalidExtension);
        }
        let (region_code_units, suffix_code_units) = code_units.split_at(region_len);
        let region =
            Region::try_from_utf8(region_code_units).map_err(|_| ParseError::InvalidExtension)?;
        let suffix = SubdivisionSuffix::try_from_utf8(suffix_code_units)?;
        Ok(Self { region, suffix })
    }

    /// Convert to [`Subtag`]
    pub fn into_subtag(self) -> Subtag {
        let result = self.region.to_tinystr().concat(self.suffix.to_tinystr());
        Subtag::from_tinystr_unvalidated(result)
    }
}

impl writeable::Writeable for SubdivisionId {
    #[inline]
    fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
        sink.write_str(self.region.to_tinystr().to_ascii_lowercase().as_str())?;
        sink.write_str(self.suffix.as_str())
    }

    #[inline]
    fn writeable_length_hint(&self) -> writeable::LengthHint {
        self.region.writeable_length_hint() + self.suffix.writeable_length_hint()
    }
}

writeable::impl_display_with_writeable!(SubdivisionId);

impl FromStr for SubdivisionId {
    type Err = ParseError;

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

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_subdivisionid_fromstr() {
        let si: SubdivisionId = "gbzzzz".parse().expect("Failed to parse SubdivisionId");
        assert_eq!(si.region.to_string(), "GB");
        assert_eq!(si.suffix.to_string(), "zzzz");
        assert_eq!(si.to_string(), "gbzzzz");

        for sample in ["", "gb", "o"] {
            let oe: Result<SubdivisionId, _> = sample.parse();
            assert!(oe.is_err(), "Should fail: {}", sample);
        }
    }
}