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
// 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 ).

//! Other Use Extensions is a list of extensions other than unicode,
//! transform or private.
//!
//! Those extensions are treated as a pass-through, and no Unicode related
//! behavior depends on them.
//!
//! The main struct for this extension is [`Other`] which is a list of [`Subtag`]s.
//!
//! # Examples
//!
//! ```
//! use icu::locale::extensions::other::Other;
//! use icu::locale::Locale;
//!
//! let mut loc: Locale = "en-US-a-foo-faa".parse().expect("Parsing failed.");
//! ```

use core::str::FromStr;

use super::ExtensionType;
use crate::parser::ParseError;
use crate::parser::SubtagIterator;
use crate::shortvec::ShortBoxSlice;
use crate::subtags::Subtag;
use alloc::vec::Vec;

/// A list of [`Other Use Extensions`] as defined in [`Unicode Locale
/// Identifier`] specification.
///
/// Those extensions are treated as a pass-through, and no Unicode related
/// behavior depends on them.
///
/// # Examples
///
/// ```
/// use icu::locale::extensions::other::Other;
/// use icu::locale::subtags::Subtag;
///
/// let subtag1: Subtag = "foo".parse().expect("Failed to parse a Subtag.");
/// let subtag2: Subtag = "bar".parse().expect("Failed to parse a Subtag.");
///
/// let other = Other::from_vec_unchecked(b'a', vec![subtag1, subtag2]);
/// assert_eq!(&other.to_string(), "a-foo-bar");
/// ```
///
/// [`Other Use Extensions`]: https://unicode.org/reports/tr35/#other_extensions
/// [`Unicode Locale Identifier`]: https://unicode.org/reports/tr35/#Unicode_locale_identifier
#[derive(Clone, PartialEq, Eq, Debug, Default, Hash, PartialOrd, Ord)]
pub struct Other {
    ext: u8,
    keys: ShortBoxSlice<Subtag>,
}

impl Other {
    /// A constructor which takes a str slice, parses it and
    /// produces a well-formed [`Other`].
    #[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 mut iter = SubtagIterator::new(code_units);

        let ext = iter.next().ok_or(ParseError::InvalidExtension)?;
        if let ExtensionType::Other(b) = ExtensionType::try_from_byte_slice(ext)? {
            return Self::try_from_iter(b, &mut iter);
        }

        Err(ParseError::InvalidExtension)
    }

    /// A constructor which takes a pre-sorted list of [`Subtag`].
    ///
    /// # Panics
    ///
    /// Panics if `ext` is not ASCII alphabetic.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::locale::extensions::other::Other;
    /// use icu::locale::subtags::Subtag;
    ///
    /// let subtag1: Subtag = "foo".parse().expect("Failed to parse a Subtag.");
    /// let subtag2: Subtag = "bar".parse().expect("Failed to parse a Subtag.");
    ///
    /// let other = Other::from_vec_unchecked(b'a', vec![subtag1, subtag2]);
    /// assert_eq!(&other.to_string(), "a-foo-bar");
    /// ```
    pub fn from_vec_unchecked(ext: u8, keys: Vec<Subtag>) -> Self {
        Self::from_short_slice_unchecked(ext, keys.into())
    }

    pub(crate) fn from_short_slice_unchecked(ext: u8, keys: ShortBoxSlice<Subtag>) -> Self {
        assert!(ext.is_ascii_alphabetic());
        Self { ext, keys }
    }

    pub(crate) fn try_from_iter(ext: u8, iter: &mut SubtagIterator) -> Result<Self, ParseError> {
        debug_assert!(matches!(
            ExtensionType::try_from_byte(ext),
            Ok(ExtensionType::Other(_)),
        ));

        let mut keys = ShortBoxSlice::new();
        while let Some(subtag) = iter.peek() {
            if !Subtag::valid_key(subtag) {
                break;
            }
            if let Ok(key) = Subtag::try_from_utf8(subtag) {
                keys.push(key);
            }
            iter.next();
        }

        if keys.is_empty() {
            Err(ParseError::InvalidExtension)
        } else {
            Ok(Self::from_short_slice_unchecked(ext, keys))
        }
    }

    /// Gets the tag character for this extension as a &str.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::locale::Locale;
    ///
    /// let loc: Locale = "und-a-hello-world".parse().unwrap();
    /// let other_ext = &loc.extensions.other[0];
    /// assert_eq!(other_ext.get_ext_str(), "a");
    /// ```
    pub fn get_ext_str(&self) -> &str {
        debug_assert!(self.ext.is_ascii_alphabetic());
        unsafe { core::str::from_utf8_unchecked(core::slice::from_ref(&self.ext)) }
    }

    /// Gets the tag character for this extension as a char.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::locale::Locale;
    ///
    /// let loc: Locale = "und-a-hello-world".parse().unwrap();
    /// let other_ext = &loc.extensions.other[0];
    /// assert_eq!(other_ext.get_ext(), 'a');
    /// ```
    pub fn get_ext(&self) -> char {
        self.ext as char
    }

    /// Gets the tag character for this extension as a byte.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::locale::Locale;
    ///
    /// let loc: Locale = "und-a-hello-world".parse().unwrap();
    /// let other_ext = &loc.extensions.other[0];
    /// assert_eq!(other_ext.get_ext_byte(), b'a');
    /// ```
    pub fn get_ext_byte(&self) -> u8 {
        self.ext
    }

    pub(crate) fn for_each_subtag_str<E, F>(&self, f: &mut F, with_ext: bool) -> Result<(), E>
    where
        F: FnMut(&str) -> Result<(), E>,
    {
        if self.keys.is_empty() {
            return Ok(());
        }

        if with_ext {
            f(self.get_ext_str())?;
        }
        self.keys.iter().map(|t| t.as_str()).try_for_each(f)
    }
}

impl FromStr for Other {
    type Err = ParseError;

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

writeable::impl_display_with_writeable!(Other);

impl writeable::Writeable for Other {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
        if self.keys.is_empty() {
            return Ok(());
        }
        sink.write_str(self.get_ext_str())?;
        for key in self.keys.iter() {
            sink.write_char('-')?;
            writeable::Writeable::write_to(key, sink)?;
        }

        Ok(())
    }

    fn writeable_length_hint(&self) -> writeable::LengthHint {
        if self.keys.is_empty() {
            return writeable::LengthHint::exact(0);
        };
        let mut result = writeable::LengthHint::exact(1);
        for key in self.keys.iter() {
            result += writeable::Writeable::writeable_length_hint(key) + 1;
        }
        result
    }

    fn write_to_string(&self) -> alloc::borrow::Cow<str> {
        if self.keys.is_empty() {
            return alloc::borrow::Cow::Borrowed("");
        }
        let mut string =
            alloc::string::String::with_capacity(self.writeable_length_hint().capacity());
        let _ = self.write_to(&mut string);
        alloc::borrow::Cow::Owned(string)
    }
}

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

    #[test]
    fn test_other_extension_fromstr() {
        let oe: Other = "o-foo-bar".parse().expect("Failed to parse Other");
        assert_eq!(oe.to_string(), "o-foo-bar");

        let oe: Result<Other, _> = "o".parse();
        assert!(oe.is_err());
    }
}