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
use crate::errors::LocaleError;
use crate::parser::ParserError;

use std::collections::BTreeMap;
use std::iter::Peekable;
use std::ops::RangeInclusive;

use tinystr::{TinyStr4, TinyStr8};

/// Constants for locale extension key/value handling.
const KEY_LENGTH: usize = 2;
const TYPE_LENGTH: RangeInclusive<usize> = 3..=8;
const ATTR_LENGTH: RangeInclusive<usize> = 3..=8;

/// A list of [`Unicode BCP47 U Extensions`] as defined in [`Unicode Locale
/// Identifier`] specification.
///
/// Unicode extensions provide subtags that specify language and/or locale-based behavior
/// or refinements to language tags, according to work done by the Unicode Consortium.
/// (See [`RFC 6067`] for details).
///
/// # Examples
///
/// ```
/// use unic_locale_impl::Locale;
///
/// let mut loc: Locale = "de-u-hc-h12-ca-buddhist".parse()
///     .expect("Parsing failed.");
///
/// assert_eq!(loc.extensions.unicode.keyword("ca")
///               .expect("Getting keyword failed.")
///               .collect::<Vec<_>>(),
///            &["buddhist"]);
/// ```
/// [`Unicode BCP47 U Extensions`]: https://unicode.org/reports/tr35/#u_Extension
/// [`RFC 6067`]: https://www.ietf.org/rfc/rfc6067.txt
/// [`Unicode Locale Identifier`]: https://unicode.org/reports/tr35/#Unicode_locale_identifier
#[derive(Clone, PartialEq, Eq, Debug, Default, Hash, PartialOrd, Ord)]
pub struct UnicodeExtensionList {
    // Canonical: sort by key (BTreeMap is already sorted) / remove value 'true'
    keywords: BTreeMap<TinyStr4, Vec<TinyStr8>>,

    // Canonical: sort / de-dup
    attributes: Vec<TinyStr8>,
}

fn parse_key(key: &[u8]) -> Result<TinyStr4, ParserError> {
    if key.len() != KEY_LENGTH || !key[0].is_ascii_alphanumeric() || !key[1].is_ascii_alphabetic() {
        return Err(ParserError::InvalidSubtag);
    }
    let key = TinyStr4::from_bytes(key).map_err(|_| ParserError::InvalidSubtag)?;
    Ok(key.to_ascii_lowercase())
}

const TRUE_TYPE: TinyStr8 = tinystr::tinystr!(8, "true"); // "true"

fn parse_type(t: &[u8]) -> Result<Option<TinyStr8>, ParserError> {
    let s = TinyStr8::from_bytes(t).map_err(|_| ParserError::InvalidSubtag)?;
    if !TYPE_LENGTH.contains(&t.len()) || !s.is_ascii_alphanumeric() {
        return Err(ParserError::InvalidSubtag);
    }

    let s = s.to_ascii_lowercase();

    if s == TRUE_TYPE {
        Ok(None)
    } else {
        Ok(Some(s))
    }
}

fn parse_attribute(t: &[u8]) -> Result<TinyStr8, ParserError> {
    let s = TinyStr8::from_bytes(t).map_err(|_| ParserError::InvalidSubtag)?;
    if !ATTR_LENGTH.contains(&t.len()) || !s.is_ascii_alphanumeric() {
        return Err(ParserError::InvalidSubtag);
    }

    Ok(s.to_ascii_lowercase())
}

fn is_type(t: &[u8]) -> bool {
    let slen = t.len();
    TYPE_LENGTH.contains(&slen) && !t.iter().any(|c: &u8| !c.is_ascii_alphanumeric())
}

fn is_attribute(t: &[u8]) -> bool {
    let slen = t.len();
    ATTR_LENGTH.contains(&slen) && !t.iter().any(|c: &u8| !c.is_ascii_alphanumeric())
}

impl UnicodeExtensionList {
    /// Returns `true` if there are no keywords and no attributes in
    /// the `UnicodeExtensionList`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US-u-foo".parse()
    ///     .expect("Parsing failed.");
    ///
    /// assert_eq!(loc.extensions.unicode.is_empty(), false);
    /// ```
    pub fn is_empty(&self) -> bool {
        self.keywords.is_empty() && self.attributes.is_empty()
    }

    /// Returns the value of keyword in the `UnicodeExtensionList`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US-u-ca-buddhist".parse()
    ///     .expect("Parsing failed.");
    ///
    /// assert_eq!(loc.extensions.unicode.keyword("ca")
    ///                .expect("Getting keyword failed.")
    ///                .collect::<Vec<_>>(),
    ///            &["buddhist"]);
    ///
    /// // Here keyword with key "aa" is not available
    /// assert_eq!(loc.extensions.unicode.keyword("aa")
    ///               .expect("Getting keyword failed.")
    ///               .len(),
    ///            0);
    /// ```
    pub fn keyword<S: AsRef<[u8]>>(
        &self,
        key: S,
    ) -> Result<impl ExactSizeIterator<Item = &str>, LocaleError> {
        let keywords: &[_] = match self.keywords.get(&parse_key(key.as_ref())?) {
            Some(v) => v,
            None => &[],
        };

        Ok(keywords.iter().map(|s| s.as_ref()))
    }

    /// Returns an iterator over all keys in the `UnicodeExtensionList`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US-u-ca-buddhist-nu-thai".parse()
    ///     .expect("Parsing failed.");
    ///
    /// assert_eq!(loc.extensions.unicode.keyword_keys().collect::<Vec<_>>(),
    ///            &["ca", "nu"]);
    /// ```
    pub fn keyword_keys(&self) -> impl ExactSizeIterator<Item = &str> {
        self.keywords.keys().map(|s| s.as_ref())
    }

    /// Adds a keyword to the `UnicodeExtensionList` or sets value for key if
    /// keyword is already included in the `UnicodeExtensionList`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US".parse()
    ///     .expect("Parsing failed.");
    ///
    /// loc.extensions.unicode.set_keyword("ca", &["buddhist"])
    ///     .expect("Setting keyword failed.");
    ///
    /// assert_eq!(loc.to_string(), "en-US-u-ca-buddhist");
    ///
    /// loc.extensions.unicode.set_keyword("ca", &["chinese"])
    ///     .expect("Setting keyword failed.");
    ///
    /// assert_eq!(loc.to_string(), "en-US-u-ca-chinese");
    /// ```
    pub fn set_keyword<S: AsRef<[u8]>>(&mut self, key: S, value: &[S]) -> Result<(), LocaleError> {
        let key = parse_key(key.as_ref())?;

        let t = value
            .iter()
            .filter_map(|t| parse_type(t.as_ref()).transpose())
            .collect::<Result<Vec<_>, _>>()?;

        self.keywords.insert(key, t);
        Ok(())
    }

    /// Removes a keyword from the `UnicodeExtensionList`.
    ///
    /// Returns `true` if keyword was included in the `UnicodeExtensionList`
    /// before removal.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US-u-ca-buddhist".parse()
    ///     .expect("Parsing failed.");
    ///
    /// assert_eq!(loc.extensions.unicode.remove_keyword("ca")
    ///               .expect("Removing tag failed."),
    ///            true);
    ///
    /// assert_eq!(loc.to_string(), "en-US");
    /// ```
    pub fn remove_keyword<S: AsRef<[u8]>>(&mut self, key: S) -> Result<bool, LocaleError> {
        Ok(self.keywords.remove(&parse_key(key.as_ref())?).is_some())
    }

    /// Clears all keywords from the `UnicodeExtensionList`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US-u-ca-buddhist".parse()
    ///     .expect("Parsing failed.");
    ///
    /// loc.extensions.unicode.clear_keywords();
    /// assert_eq!(loc.to_string(), "en-US");
    /// ```
    pub fn clear_keywords(&mut self) {
        self.keywords.clear();
    }

    /// Returns `true` if attribute is included in the `UnicodeExtensionList`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US-u-foo".parse()
    ///     .expect("Parsing failed.");
    ///
    /// assert_eq!(loc.extensions.unicode.has_attribute("foo")
    ///               .expect("Getting attribute failed."),
    ///            true);
    /// ```
    pub fn has_attribute<S: AsRef<[u8]>>(&self, attribute: S) -> Result<bool, LocaleError> {
        Ok(self
            .attributes
            .contains(&parse_attribute(attribute.as_ref())?))
    }

    /// Returns an iterator over all attributes in the `UnicodeExtensionList`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US-u-foo-bar".parse()
    ///     .expect("Parsing failed.");
    ///
    /// assert_eq!(loc.extensions.unicode.attributes().collect::<Vec<_>>(),
    ///            &["bar", "foo"]);
    /// ```
    pub fn attributes(&self) -> impl ExactSizeIterator<Item = &str> {
        self.attributes.iter().map(|s| s.as_ref())
    }

    /// Sets an attribute on the `UnicodeExtensionList`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US".parse()
    ///     .expect("Parsing failed.");
    ///
    /// loc.extensions.unicode.set_attribute("foo")
    ///     .expect("Setting attribute failed.");
    ///
    /// assert_eq!(loc.to_string(), "en-US-u-foo");
    /// ```
    pub fn set_attribute<S: AsRef<[u8]>>(&mut self, attribute: S) -> Result<(), LocaleError> {
        let attribute = parse_attribute(attribute.as_ref())?;
        if let Err(idx) = self.attributes.binary_search(&attribute) {
            self.attributes.insert(idx, attribute);
        }
        Ok(())
    }

    /// Removes an attribute from the `UnicodeExtensionList`.
    ///
    /// Returns `true` if attribute was included in the `UnicodeExtensionList`
    /// before removal.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US-u-foo".parse()
    ///     .expect("Parsing failed.");
    ///
    /// assert_eq!(loc.extensions.unicode.remove_attribute("foo")
    ///               .expect("Removing attribute failed."),
    ///            true);
    ///
    /// assert_eq!(loc.to_string(), "en-US");
    /// ```
    pub fn remove_attribute<S: AsRef<[u8]>>(&mut self, attribute: S) -> Result<bool, LocaleError> {
        let attribute = parse_attribute(attribute.as_ref())?;
        match self.attributes.binary_search(&attribute) {
            Ok(idx) => {
                self.attributes.remove(idx);
                Ok(true)
            }
            Err(_) => Ok(false),
        }
    }

    /// Clears all attributes from the `UnicodeExtensionList`.
    ///
    /// # Examples
    ///
    /// ```
    /// use unic_locale_impl::Locale;
    ///
    /// let mut loc: Locale = "en-US-u-foo".parse()
    ///     .expect("Parsing failed.");
    ///
    /// loc.extensions.unicode.clear_attributes();
    /// assert_eq!(loc.to_string(), "en-US");
    /// ```
    pub fn clear_attributes(&mut self) {
        self.attributes.clear();
    }

    pub(crate) fn try_from_iter<'a>(
        iter: &mut Peekable<impl Iterator<Item = &'a [u8]>>,
    ) -> Result<Self, ParserError> {
        let mut uext = Self::default();

        let mut st_peek = iter.peek();

        let mut current_keyword = None;
        let mut current_types = vec![];

        while let Some(subtag) = st_peek {
            let slen = subtag.len();
            if slen == 2 {
                if let Some(current_keyword) = current_keyword {
                    uext.keywords.insert(current_keyword, current_types);
                    current_types = vec![];
                }
                current_keyword = Some(parse_key(subtag)?);
                iter.next();
            } else if current_keyword.is_some() && is_type(subtag) {
                if let Some(ty) = parse_type(subtag)? {
                    current_types.push(ty);
                }
                iter.next();
            } else if is_attribute(subtag) {
                uext.attributes.push(parse_attribute(subtag)?);
                iter.next();
            } else {
                break;
            }
            st_peek = iter.peek();
        }

        if let Some(current_keyword) = current_keyword {
            uext.keywords.insert(current_keyword, current_types);
        }

        uext.attributes.sort_unstable();
        uext.attributes.dedup();

        Ok(uext)
    }
}

impl std::fmt::Display for UnicodeExtensionList {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        if self.is_empty() {
            return Ok(());
        }

        f.write_str("-u")?;

        for attr in &self.attributes {
            write!(f, "-{}", attr)?;
        }

        for (k, t) in &self.keywords {
            write!(f, "-{}", k)?;
            for v in t {
                write!(f, "-{}", v)?;
            }
        }
        Ok(())
    }
}