icu_locale_core/extensions/unicode/subdivision.rs
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
5use core::str::FromStr;
6
7use crate::parser::ParseError;
8use crate::subtags::{Region, Subtag};
9
10impl_tinystr_subtag!(
11 /// A subdivision suffix used in [`SubdivisionId`].
12 ///
13 /// This suffix represents a specific subdivision code under a given [`Region`].
14 /// For example the value of [`SubdivisionId`] may be `gbsct`, where the [`SubdivisionSuffix`]
15 /// is `sct` for Scotland.
16 ///
17 /// Such a value associated with a key `rg` means that the locale should use Unit Preferences
18 /// (default calendar, currency, week data, time cycle, measurement system) for Scotland, even if the
19 /// [`LanguageIdentifier`](crate::LanguageIdentifier) is `en-US`.
20 ///
21 /// A subdivision suffix has to be a sequence of alphanumerical characters no
22 /// shorter than one and no longer than four characters.
23 ///
24 ///
25 /// # Examples
26 ///
27 /// ```
28 /// use icu::locale::extensions::unicode::{
29 /// SubdivisionSuffix, subdivision_suffix,
30 /// };
31 ///
32 /// let ss: SubdivisionSuffix =
33 /// "sct".parse().expect("Failed to parse a SubdivisionSuffix.");
34 ///
35 /// assert_eq!(ss, subdivision_suffix!("sct"));
36 /// ```
37 SubdivisionSuffix,
38 extensions::unicode,
39 subdivision_suffix,
40 extensions_unicode_subdivision_suffix,
41 1..=4,
42 s,
43 s.is_ascii_alphanumeric(),
44 s.to_ascii_lowercase(),
45 s.is_ascii_alphanumeric() && s.is_ascii_lowercase(),
46 InvalidExtension,
47 ["sct"],
48 ["toolooong"],
49);
50
51impl SubdivisionSuffix {
52 pub(crate) const UNKNOWN: Self = subdivision_suffix!("zzzz");
53
54 pub(crate) fn is_unknown(self) -> bool {
55 self == Self::UNKNOWN
56 }
57}
58
59/// A Subivision Id as defined in [`Unicode Locale Identifier`].
60///
61/// Subdivision Id is used in [`Unicode`] extensions:
62/// * `rg` - Regional Override
63/// * `sd` - Regional Subdivision
64///
65/// In both cases the subdivision is composed of a [`Region`] and a [`SubdivisionSuffix`] which represents
66/// different meaning depending on the key.
67///
68/// [`Unicode Locale Identifier`]: https://unicode.org/reports/tr35/tr35.html#unicode_subdivision_id
69/// [`Unicode`]: crate::extensions::unicode::Unicode
70///
71/// # Examples
72///
73/// ```
74/// use icu::locale::{
75/// extensions::unicode::{SubdivisionId, subdivision_suffix},
76/// subtags::region,
77/// };
78///
79/// // "zzzz" means "unknown subdivision"
80/// let ss = subdivision_suffix!("zzzz");
81/// let region = region!("gb");
82///
83/// let si = SubdivisionId::new(region, ss);
84///
85/// assert_eq!(si.to_string(), "gbzzzz");
86/// ```
87#[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord, Copy)]
88#[non_exhaustive]
89pub struct SubdivisionId {
90 /// A region field of a Subdivision Id.
91 pub region: Region,
92 /// A subdivision suffix field of a Subdivision Id.
93 pub suffix: SubdivisionSuffix,
94}
95
96impl SubdivisionId {
97 /// Returns a new [`SubdivisionId`].
98 ///
99 /// # Examples
100 ///
101 /// ```
102 /// use icu::locale::{
103 /// extensions::unicode::{SubdivisionId, subdivision_suffix},
104 /// subtags::region,
105 /// };
106 ///
107 /// let ss = subdivision_suffix!("zzzz");
108 /// let region = region!("gb");
109 ///
110 /// let si = SubdivisionId::new(region, ss);
111 ///
112 /// assert_eq!(si.to_string(), "gbzzzz");
113 /// ```
114 pub const fn new(region: Region, suffix: SubdivisionSuffix) -> Self {
115 Self { region, suffix }
116 }
117
118 /// A constructor which takes a str slice, parses it and
119 /// produces a well-formed [`SubdivisionId`].
120 ///
121 /// # Examples
122 ///
123 /// ```
124 /// use icu::locale::extensions::unicode::SubdivisionId;
125 /// use writeable::assert_writeable_eq;
126 ///
127 /// let subdivision = SubdivisionId::try_from_str("gbeng").unwrap();
128 ///
129 /// assert_writeable_eq!(subdivision, "gbeng");
130 /// assert_writeable_eq!(subdivision.region, "GB");
131 /// assert_writeable_eq!(subdivision.suffix, "eng");
132 /// ```
133 ///
134 /// When the value can't be parsed:
135 ///
136 /// ```
137 /// use icu::locale::ParseError;
138 /// use icu::locale::extensions::unicode::SubdivisionId;
139 ///
140 /// // Value is too short
141 /// assert!(matches!(
142 /// SubdivisionId::try_from_str("zz"),
143 /// Err(ParseError::InvalidExtension),
144 /// ));
145 ///
146 /// // Value is too long
147 /// assert!(matches!(
148 /// SubdivisionId::try_from_str("abcdefg"),
149 /// Err(ParseError::InvalidExtension),
150 /// ));
151 ///
152 /// // Value does not start with a valid region code
153 /// assert!(matches!(
154 /// SubdivisionId::try_from_str("a0zzzz"),
155 /// Err(ParseError::InvalidExtension),
156 /// ));
157 /// assert!(matches!(
158 /// SubdivisionId::try_from_str("0azzzz"),
159 /// Err(ParseError::InvalidExtension),
160 /// ));
161 /// ```
162 #[inline]
163 pub fn try_from_str(s: &str) -> Result<Self, ParseError> {
164 Self::try_from_utf8(s.as_bytes())
165 }
166
167 /// See [`Self::try_from_str`]
168 pub fn try_from_utf8(code_units: &[u8]) -> Result<Self, ParseError> {
169 Self::try_from_subtag(Subtag::try_from_utf8(code_units)?)
170 }
171
172 pub(crate) const fn try_from_subtag(subtag: Subtag) -> Result<Self, ParseError> {
173 let code_units = subtag.as_str().as_bytes();
174 let Some(first) = code_units.first() else {
175 return Err(ParseError::InvalidExtension);
176 };
177 let region_len = if first.is_ascii_alphabetic() {
178 2
179 } else if first.is_ascii_digit() {
180 3
181 } else {
182 return Err(ParseError::InvalidExtension);
183 };
184 let Some((region_code_units, suffix_code_units)) = code_units.split_at_checked(region_len)
185 else {
186 return Err(ParseError::InvalidExtension);
187 };
188 let Ok(region) = Region::try_from_utf8(region_code_units) else {
189 return Err(ParseError::InvalidExtension);
190 };
191 let Ok(suffix) = SubdivisionSuffix::try_from_utf8(suffix_code_units) else {
192 return Err(ParseError::InvalidExtension);
193 };
194 Ok(Self { region, suffix })
195 }
196
197 /// Convert to [`Subtag`]
198 pub const fn into_subtag(self) -> Subtag {
199 let result = self
200 .region
201 .to_tinystr()
202 .to_ascii_lowercase()
203 .concat(self.suffix.to_tinystr());
204 Subtag::from_tinystr_unvalidated(result)
205 }
206}
207
208impl writeable::Writeable for SubdivisionId {
209 #[inline]
210 fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
211 sink.write_str(self.region.to_tinystr().to_ascii_lowercase().as_str())?;
212 sink.write_str(self.suffix.as_str())
213 }
214
215 #[inline]
216 fn writeable_length_hint(&self) -> writeable::LengthHint {
217 self.region.writeable_length_hint() + self.suffix.writeable_length_hint()
218 }
219}
220
221writeable::impl_display_with_writeable!(SubdivisionId, #[cfg(feature = "alloc")]);
222
223impl FromStr for SubdivisionId {
224 type Err = ParseError;
225
226 #[inline]
227 fn from_str(s: &str) -> Result<Self, Self::Err> {
228 Self::try_from_str(s)
229 }
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235
236 #[test]
237 fn test_subdivisionid_fromstr() {
238 let si: SubdivisionId = "gbzzzz".parse().expect("Failed to parse SubdivisionId");
239 assert_eq!(si.region.to_string(), "GB");
240 assert_eq!(si.suffix.to_string(), "zzzz");
241 assert_eq!(si.to_string(), "gbzzzz");
242
243 for sample in ["", "gb", "o"] {
244 let oe: Result<SubdivisionId, _> = sample.parse();
245 assert!(oe.is_err(), "Should fail: {sample}");
246 }
247 }
248}