Skip to main content

icu_locale_core/
helpers.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
5macro_rules! impl_tinystr_subtag {
6    (
7        $(#[$doc:meta])*
8        $name:ident,
9        $($path:ident)::+,
10        $macro_name:ident,
11        $internal_macro_name:ident,
12        $len_start:literal..=$len_end:literal,
13        $tinystr_ident:ident,
14        $validate:expr,
15        $normalize:expr,
16        $is_normalized:expr,
17        $error:ident,
18        [$good_example:literal $(,$more_good_examples:literal)*],
19        [$bad_example:literal $(, $more_bad_examples:literal)*],
20    ) => {
21        #[derive(Debug, PartialEq, Eq, Clone, Hash, PartialOrd, Ord, Copy)]
22        #[repr(transparent)]
23        $(#[$doc])*
24        pub struct $name(tinystr::TinyAsciiStr<$len_end>);
25
26        impl $name {
27            /// A constructor which takes a str slice, parses it and
28            #[doc = concat!("produces a well-formed [`", stringify!($name), "`].")]
29            ///
30            /// # Examples
31            ///
32            /// ```
33            #[doc = concat!("use icu_locale_core::", stringify!($($path::)+), stringify!($name), ";")]
34            ///
35            #[doc = concat!("assert!(", stringify!($name), "::try_from_str(", stringify!($good_example), ").is_ok());")]
36            #[doc = concat!("assert!(", stringify!($name), "::try_from_str(", stringify!($bad_example), ").is_err());")]
37            /// ```
38            #[inline]
39            pub const fn try_from_str(s: &str) -> Result<Self, crate::parser::errors::ParseError> {
40                Self::try_from_utf8(s.as_bytes())
41            }
42
43            /// See [`Self::try_from_str`]
44            pub const fn try_from_utf8(
45                code_units: &[u8],
46            ) -> Result<Self, crate::parser::errors::ParseError> {
47                if code_units.len() < $len_start || code_units.len() > $len_end {
48                    return Err(crate::parser::errors::ParseError::$error);
49                }
50
51                match tinystr::TinyAsciiStr::try_from_utf8(code_units) {
52                    Ok($tinystr_ident) if $validate => Ok(Self($normalize)),
53                    _ => Err(crate::parser::errors::ParseError::$error),
54                }
55            }
56
57            #[doc = concat!("Safely creates a [`", stringify!($name), "`] from its raw format")]
58            /// as returned by [`Self::into_raw`]. Unlike [`Self::try_from_utf8`],
59            /// this constructor only takes normalized values.
60            pub const fn try_from_raw(
61                raw: [u8; $len_end],
62            ) -> Result<Self, crate::parser::errors::ParseError> {
63                if let Ok($tinystr_ident) = tinystr::TinyAsciiStr::<$len_end>::try_from_raw(raw) {
64                    if $tinystr_ident.len() >= $len_start && $is_normalized {
65                        Ok(Self($tinystr_ident))
66                    } else {
67                        Err(crate::parser::errors::ParseError::$error)
68                    }
69                } else {
70                    Err(crate::parser::errors::ParseError::$error)
71                }
72            }
73
74            #[doc = concat!("Unsafely creates a [`", stringify!($name), "`] from its raw format")]
75            /// as returned by [`Self::into_raw`]. Unlike [`Self::try_from_utf8`],
76            /// this constructor only takes normalized values.
77            ///
78            /// # Safety
79            ///
80            /// This function is safe iff [`Self::try_from_raw`] returns an `Ok`. This is the case
81            /// for inputs that are correctly normalized.
82            pub const unsafe fn from_raw_unchecked(v: [u8; $len_end]) -> Self { unsafe {
83                Self(tinystr::TinyAsciiStr::from_utf8_unchecked(v))
84            }}
85
86            /// Deconstructs into a raw format to be consumed by
87            /// [`from_raw_unchecked`](Self::from_raw_unchecked()) or
88            /// [`try_from_raw`](Self::try_from_raw()).
89            pub const fn into_raw(self) -> [u8; $len_end] {
90                *self.0.all_bytes()
91            }
92
93            #[inline]
94            /// A helper function for displaying as a `&str`.
95            pub const fn as_str(&self) -> &str {
96                self.0.as_str()
97            }
98
99            #[doc(hidden)]
100            pub const fn to_tinystr(&self) -> tinystr::TinyAsciiStr<$len_end> {
101                self.0
102            }
103
104            /// Compare with BCP-47 bytes.
105            ///
106            /// The return value is equivalent to what would happen if you first converted
107            /// `self` to a BCP-47 string and then performed a byte comparison.
108            ///
109            /// This function is case-sensitive and results in a *total order*, so it is appropriate for
110            /// binary search. The only argument producing [`Ordering::Equal`](core::cmp::Ordering::Equal)
111            /// is `self.as_str().as_bytes()`.
112            #[inline]
113            pub fn strict_cmp(self, other: &[u8]) -> core::cmp::Ordering {
114                self.as_str().as_bytes().cmp(other)
115            }
116
117            /// Compare with a potentially unnormalized BCP-47 string.
118            ///
119            /// The return value is equivalent to what would happen if you first parsed the
120            /// BCP-47 string and then performed a structural comparison.
121            ///
122            #[inline]
123            pub fn normalizing_eq(self, other: &str) -> bool {
124                self.as_str().eq_ignore_ascii_case(other)
125            }
126        }
127
128        impl core::str::FromStr for $name {
129            type Err = crate::parser::errors::ParseError;
130
131            #[inline]
132            fn from_str(s: &str) -> Result<Self, Self::Err> {
133                Self::try_from_str(s)
134            }
135        }
136
137        impl<'l> From<&'l $name> for &'l str {
138            fn from(input: &'l $name) -> Self {
139                input.as_str()
140            }
141        }
142
143        impl From<$name> for tinystr::TinyAsciiStr<$len_end> {
144            fn from(input: $name) -> Self {
145                input.to_tinystr()
146            }
147        }
148
149        writeable::impl_writeable_delegate!($name, |&self| self.as_str(), #[cfg(feature = "alloc")] fn write_to_string);
150        writeable::impl_display_with_writeable!($name, #[cfg(feature = "alloc")]);
151
152        #[doc = concat!("A macro allowing for compile-time construction of valid [`", stringify!($name), "`] subtags.")]
153        ///
154        /// # Examples
155        ///
156        /// Parsing errors don't have to be handled at runtime:
157        /// ```
158        /// assert_eq!(
159        #[doc = concat!("  icu_locale_core::", $(stringify!($path), "::",)+ stringify!($macro_name), "!(", stringify!($good_example) ,"),")]
160        #[doc = concat!("  ", stringify!($good_example), ".parse::<icu_locale_core::", $(stringify!($path), "::",)+ stringify!($name), ">().unwrap()")]
161        /// );
162        /// ```
163        ///
164        /// Invalid input is a compile failure:
165        /// ```compile_fail,E0080
166        #[doc = concat!("icu_locale_core::", $(stringify!($path), "::",)+ stringify!($macro_name), "!(", stringify!($bad_example) ,");")]
167        /// ```
168        ///
169        #[doc = concat!("[`", stringify!($name), "`]: crate::", $(stringify!($path), "::",)+ stringify!($name))]
170        #[macro_export]
171        #[doc(hidden)] // macro
172        macro_rules! $internal_macro_name {
173            ($string:literal) => { const {
174                use $crate::$($path ::)+ $name;
175                match $name::try_from_utf8($string.as_bytes()) {
176                    Ok(r) => r,
177                    _ => panic!(concat!("Invalid ", $(stringify!($path), "::",)+ stringify!($name), ": ", $string)),
178                }
179            }};
180        }
181        #[doc(inline)]
182        pub use $internal_macro_name as $macro_name;
183
184        #[cfg(feature = "databake")]
185        impl databake::Bake for $name {
186            fn bake(&self, env: &databake::CrateEnv) -> databake::TokenStream {
187                env.insert("icu_locale_core");
188                let string = self.as_str();
189                databake::quote! { icu_locale_core::$($path::)+ $macro_name!(#string) }
190            }
191        }
192
193        #[cfg(feature = "databake")]
194        impl databake::BakeSize for $name {
195            fn borrows_size(&self) -> usize {
196                0
197            }
198        }
199
200        #[test]
201        fn test_construction() {
202            let maybe = $name::try_from_utf8($good_example.as_bytes());
203            assert!(maybe.is_ok());
204            assert_eq!(maybe, $name::try_from_raw(maybe.unwrap().into_raw()));
205            assert_eq!(maybe.unwrap().as_str(), $good_example);
206            $(
207                let maybe = $name::try_from_utf8($more_good_examples.as_bytes());
208                assert!(maybe.is_ok());
209                assert_eq!(maybe, $name::try_from_raw(maybe.unwrap().into_raw()));
210                assert_eq!(maybe.unwrap().as_str(), $more_good_examples);
211            )*
212            assert!($name::try_from_utf8($bad_example.as_bytes()).is_err());
213            $(
214                assert!($name::try_from_utf8($more_bad_examples.as_bytes()).is_err());
215            )*
216        }
217
218        #[test]
219        fn test_writeable() {
220            writeable::assert_writeable_eq!(&$good_example.parse::<$name>().unwrap(), $good_example);
221            $(
222                writeable::assert_writeable_eq!($more_good_examples.parse::<$name>().unwrap(), $more_good_examples);
223            )*
224        }
225
226        #[cfg(feature = "serde")]
227        impl serde::Serialize for $name {
228            fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
229            where
230                S: serde::Serializer,
231            {
232                self.0.serialize(serializer)
233            }
234        }
235
236        #[cfg(feature = "serde")]
237        impl<'de> serde::Deserialize<'de> for $name {
238            fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
239            where
240                D: serde::de::Deserializer<'de>,
241            {
242                struct Visitor;
243
244                impl<'de> serde::de::Visitor<'de> for Visitor {
245                    type Value = $name;
246
247                    fn expecting(
248                        &self,
249                        formatter: &mut core::fmt::Formatter<'_>,
250                    ) -> core::fmt::Result {
251                        write!(formatter, "a valid BCP-47 {}", stringify!($name))
252                    }
253
254                    fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Self::Value, E> {
255                        s.parse().map_err(serde::de::Error::custom)
256                    }
257                }
258
259                if deserializer.is_human_readable() {
260                    deserializer.deserialize_string(Visitor)
261                } else {
262                    Self::try_from_raw(serde::de::Deserialize::deserialize(deserializer)?)
263                        .map_err(serde::de::Error::custom)
264                }
265            }
266        }
267
268        // Safety checklist for ULE:
269        //
270        // 1. Must not include any uninitialized or padding bytes (true since transparent over a ULE).
271        // 2. Must have an alignment of 1 byte (true since transparent over a ULE).
272        // 3. ULE::validate_bytes() checks that the given byte slice represents a valid slice.
273        // 4. ULE::validate_bytes() checks that the given byte slice has a valid length.
274        // 5. All other methods must be left with their default impl.
275        // 6. Byte equality is semantic equality.
276        #[cfg(feature = "zerovec")]
277        unsafe impl zerovec::ule::ULE for $name {
278            fn validate_bytes(bytes: &[u8]) -> Result<(), zerovec::ule::UleError> {
279                let it = bytes.chunks_exact(size_of::<Self>());
280                if !it.remainder().is_empty() {
281                    return Err(zerovec::ule::UleError::length::<Self>(bytes.len()));
282                }
283                for v in it {
284                    // The following can be removed once `array_chunks` is stabilized.
285                    let mut a = [0; size_of::<Self>()];
286                    a.copy_from_slice(v);
287                    if Self::try_from_raw(a).is_err() {
288                        return Err(zerovec::ule::UleError::parse::<Self>());
289                    }
290                }
291                Ok(())
292            }
293        }
294
295        #[cfg(feature = "zerovec")]
296        impl zerovec::ule::NicheBytes<$len_end> for $name {
297            const NICHE_BIT_PATTERN: [u8; $len_end] = <tinystr::TinyAsciiStr<$len_end>>::NICHE_BIT_PATTERN;
298        }
299
300        #[cfg(feature = "zerovec")]
301        impl zerovec::ule::AsULE for $name {
302            type ULE = Self;
303            fn to_unaligned(self) -> Self::ULE {
304                self
305            }
306            fn from_unaligned(unaligned: Self::ULE) -> Self {
307                unaligned
308            }
309        }
310
311        #[cfg(feature = "zerovec")]
312        #[cfg(feature = "alloc")]
313        impl<'a> zerovec::maps::ZeroMapKV<'a> for $name {
314            type Container = zerovec::ZeroVec<'a, $name>;
315            type Slice = zerovec::ZeroSlice<$name>;
316            type GetType = $name;
317            type OwnedType = $name;
318        }
319    };
320}
321
322#[macro_export]
323#[doc(hidden)]
324macro_rules! impl_writeable_for_each_subtag_str_no_test {
325    ($type:tt $(, $self:ident, $borrow_cond:expr => $borrow:expr)?) => {
326        impl writeable::Writeable for $type {
327            fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
328                let mut initial = true;
329                self.for_each_subtag_str(&mut |subtag| {
330                    if initial {
331                        initial = false;
332                    } else {
333                        sink.write_char('-')?;
334                    }
335                    sink.write_str(subtag)
336                })
337            }
338
339            #[inline]
340            fn writeable_length_hint(&self) -> writeable::LengthHint {
341                let mut result = writeable::LengthHint::exact(0);
342                let mut initial = true;
343                self.for_each_subtag_str::<core::convert::Infallible, _>(&mut |subtag| {
344                    if initial {
345                        initial = false;
346                    } else {
347                        result += 1;
348                    }
349                    result += subtag.len();
350                    Ok(())
351                })
352                .expect("infallible");
353                result
354            }
355
356            $(
357                fn writeable_borrow(&self) -> Option<&str> {
358                    let $self = self;
359                    if $borrow_cond {
360                        $borrow
361                    } else {
362                        None
363                    }
364                }
365            )?
366        }
367
368        writeable::impl_display_with_writeable!($type, #[cfg(feature = "alloc")]);
369    };
370}
371
372macro_rules! impl_writeable_for_subtag_list {
373    ($type:tt, $sample1:literal, $sample2:literal) => {
374        impl_writeable_for_each_subtag_str_no_test!($type, selff, selff.0.len() == 1 => #[allow(clippy::unwrap_used)] { Some(selff.0.get(0).unwrap().as_str()) } );
375
376        #[test]
377        fn test_writeable() {
378            writeable::assert_writeable_eq!(&$type::default(), "");
379            writeable::assert_writeable_eq!(
380                &$type::from_vec_unchecked(alloc::vec![$sample1.parse().unwrap()]),
381                $sample1,
382            );
383            writeable::assert_writeable_eq!(
384                &$type::from_vec_unchecked(vec![
385                    $sample1.parse().unwrap(),
386                    $sample2.parse().unwrap()
387                ]),
388                core::concat!($sample1, "-", $sample2),
389            );
390        }
391    };
392}
393
394macro_rules! impl_writeable_for_key_value {
395    ($type:tt, $key1:literal, $value1:literal, $key2:literal, $expected2:literal) => {
396        impl_writeable_for_each_subtag_str_no_test!($type);
397
398        #[test]
399        fn test_writeable() {
400            writeable::assert_writeable_eq!(&$type::default(), "");
401            writeable::assert_writeable_eq!(
402                &$type::from_tuple_vec(vec![($key1.parse().unwrap(), $value1.parse().unwrap())]),
403                core::concat!($key1, "-", $value1),
404            );
405            writeable::assert_writeable_eq!(
406                &$type::from_tuple_vec(vec![
407                    ($key1.parse().unwrap(), $value1.parse().unwrap()),
408                    ($key2.parse().unwrap(), "true".parse().unwrap())
409                ]),
410                core::concat!($key1, "-", $value1, "-", $expected2),
411            );
412        }
413    };
414}