icu_locale_core/extensions/unicode/
attributes.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 super::Attribute;
6
7#[cfg(feature = "alloc")]
8use crate::parser::SubtagIterator;
9use crate::shortvec::ShortBoxSlice;
10#[cfg(feature = "alloc")]
11use crate::ParseError;
12#[cfg(feature = "alloc")]
13use alloc::vec::Vec;
14use core::ops::Deref;
15#[cfg(feature = "alloc")]
16use core::str::FromStr;
17
18/// A set of [`Attribute`] elements as defined in [`Unicode Extension Attributes`].
19///
20/// [`Unicode Extension Attributes`]: https://unicode.org/reports/tr35/tr35.html#u_Extension
21///
22/// # Examples
23///
24/// ```
25/// use icu::locale::extensions::unicode::{Attribute, Attributes};
26///
27/// let attribute1: Attribute =
28///     "foobar".parse().expect("Failed to parse a variant subtag.");
29///
30/// let attribute2: Attribute = "testing"
31///     .parse()
32///     .expect("Failed to parse a variant subtag.");
33/// let mut v = vec![attribute1, attribute2];
34/// v.sort();
35/// v.dedup();
36///
37/// let attributes: Attributes = Attributes::from_vec_unchecked(v);
38/// assert_eq!(attributes.to_string(), "foobar-testing");
39/// ```
40#[derive(Default, Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord)]
41pub struct Attributes(ShortBoxSlice<Attribute>);
42
43impl Attributes {
44    /// Returns a new empty set of attributes. Same as [`default()`](Default::default()), but is `const`.
45    ///
46    /// # Examples
47    ///
48    /// ```
49    /// use icu::locale::extensions::unicode::Attributes;
50    ///
51    /// assert_eq!(Attributes::new(), Attributes::default());
52    /// ```
53    #[inline]
54    pub const fn new() -> Self {
55        Self(ShortBoxSlice::new())
56    }
57
58    /// A constructor which takes a str slice, parses it and
59    /// produces a well-formed [`Attributes`].
60    ///
61    /// ✨ *Enabled with the `alloc` Cargo feature.*
62    #[inline]
63    #[cfg(feature = "alloc")]
64    pub fn try_from_str(s: &str) -> Result<Self, ParseError> {
65        Self::try_from_utf8(s.as_bytes())
66    }
67
68    /// See [`Self::try_from_str`]
69    ///
70    /// ✨ *Enabled with the `alloc` Cargo feature.*
71    #[cfg(feature = "alloc")]
72    pub fn try_from_utf8(code_units: &[u8]) -> Result<Self, ParseError> {
73        let mut iter = SubtagIterator::new(code_units);
74        Self::try_from_iter(&mut iter)
75    }
76
77    /// A constructor which takes a pre-sorted list of [`Attribute`] elements.
78    ///
79    /// ✨ *Enabled with the `alloc` Cargo feature.*
80    ///
81    /// # Examples
82    ///
83    /// ```
84    /// use icu::locale::extensions::unicode::{Attribute, Attributes};
85    ///
86    /// let attribute1: Attribute = "foobar".parse().expect("Parsing failed.");
87    /// let attribute2: Attribute = "testing".parse().expect("Parsing failed.");
88    /// let mut v = vec![attribute1, attribute2];
89    /// v.sort();
90    /// v.dedup();
91    ///
92    /// let attributes = Attributes::from_vec_unchecked(v);
93    /// ```
94    ///
95    /// Notice: For performance- and memory-constrained environments, it is recommended
96    /// for the caller to use [`binary_search`](slice::binary_search) instead of [`sort`](slice::sort)
97    /// and [`dedup`](Vec::dedup()).
98    #[cfg(feature = "alloc")]
99    pub fn from_vec_unchecked(input: Vec<Attribute>) -> Self {
100        Self(input.into())
101    }
102
103    /// Empties the [`Attributes`] list.
104    ///
105    /// Returns the old list.
106    ///
107    /// # Examples
108    ///
109    /// ```
110    /// use icu::locale::extensions::unicode::{attribute, Attributes};
111    /// use writeable::assert_writeable_eq;
112    ///
113    /// let mut attributes = Attributes::from_vec_unchecked(vec![
114    ///     attribute!("foobar"),
115    ///     attribute!("testing"),
116    /// ]);
117    ///
118    /// assert_writeable_eq!(attributes, "foobar-testing");
119    ///
120    /// attributes.clear();
121    ///
122    /// assert_writeable_eq!(attributes, "");
123    /// ```
124    pub fn clear(&mut self) -> Self {
125        core::mem::take(self)
126    }
127
128    #[cfg(feature = "alloc")]
129    pub(crate) fn try_from_iter(iter: &mut SubtagIterator) -> Result<Self, ParseError> {
130        let mut attributes = ShortBoxSlice::new();
131
132        while let Some(subtag) = iter.peek() {
133            if let Ok(attr) = Attribute::try_from_utf8(subtag) {
134                if let Err(idx) = attributes.binary_search(&attr) {
135                    attributes.insert(idx, attr);
136                }
137            } else {
138                break;
139            }
140            iter.next();
141        }
142        Ok(Self(attributes))
143    }
144
145    pub(crate) fn for_each_subtag_str<E, F>(&self, f: &mut F) -> Result<(), E>
146    where
147        F: FnMut(&str) -> Result<(), E>,
148    {
149        self.deref().iter().map(|t| t.as_str()).try_for_each(f)
150    }
151
152    /// Extends the `Attributes` with values from another `Attributes`.
153    ///
154    /// # Example
155    ///
156    /// ```
157    /// use icu::locale::extensions::unicode::Attributes;
158    ///
159    /// let mut attrs: Attributes = "foobar-foobaz".parse().unwrap();
160    /// let attrs2: Attributes = "foobar-fooqux".parse().unwrap();
161    ///
162    /// attrs.extend_from_attributes(attrs2);
163    ///
164    /// assert_eq!(attrs, "foobar-foobaz-fooqux".parse().unwrap());
165    /// ```
166    #[cfg(feature = "alloc")]
167    pub fn extend_from_attributes(&mut self, other: Attributes) {
168        for attr in other.0 {
169            if let Err(idx) = self.binary_search(&attr) {
170                self.0.insert(idx, attr);
171            }
172        }
173    }
174}
175
176/// ✨ *Enabled with the `alloc` Cargo feature.*
177#[cfg(feature = "alloc")]
178impl FromStr for Attributes {
179    type Err = ParseError;
180
181    #[inline]
182    fn from_str(s: &str) -> Result<Self, Self::Err> {
183        Self::try_from_str(s)
184    }
185}
186
187impl_writeable_for_subtag_list!(Attributes, "foobar", "testing");
188
189impl Deref for Attributes {
190    type Target = [Attribute];
191
192    fn deref(&self) -> &[Attribute] {
193        self.0.deref()
194    }
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn test_attributes_fromstr() {
203        let attrs: Attributes = "foo-bar".parse().expect("Failed to parse Attributes");
204        assert_eq!(attrs.to_string(), "bar-foo");
205    }
206}