Debian Codegraph @

debian/rust-vendor/icu_locale_fallback/src/lib.rs

raw
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
5 //! Tools for locale fallback, enabling arbitrary input locales to be mapped into the nearest
6 //! locale with data.
7
8 // https://github.com/unicode-org/icu4x/blob/main/documents/process/boilerplate.md#library-annotations
9 #![cfg_attr(not(any(test, doc)), no_std)]
10 #![cfg_attr(
11 not(test),
12 deny(
13 clippy::indexing_slicing,
14 clippy::unwrap_used,
15 clippy::expect_used,
16 clippy::panic,
17 )
18 )]
19 #![warn(missing_docs)]
20
21 use crate::provider::*;
22 use icu_locale_core::subtags::{Language, Region, Script, Subtag, Variant, region, script};
23 use icu_provider::prelude::*;
24
25 #[doc(inline)]
26 pub use icu_provider::fallback::{LocaleFallbackConfig, LocaleFallbackPriority};
27
28 mod algorithms;
29 pub mod provider;
30
31 /// Implements the algorithm defined in *[UTS #35: Locale Inheritance and Matching]*.
32 ///
33 /// Note that this implementation performs some additional steps compared to the *UTS #35*
34 /// algorithm. See *[the design doc]* for a detailed description and [#2243](
35 /// https://github.com/unicode-org/icu4x/issues/2243) to track alignment with *UTS #35*.
36 ///
37 /// While the first element produced here is *usually* the input locale,
38 /// the fallback iterator normalizes the input locale first, which may strip implied subtags.
39 ///
40 /// If running fallback in a loop, use [`DataLocale::is_unknown()`] to break from the loop.
41 ///
42 /// # Examples
43 ///
44 /// ```
45 /// use icu::locale::fallback::LocaleFallbacker;
46 /// use icu::locale::locale;
47 ///
48 /// // Set up a LocaleFallbacker with data.
49 /// let fallbacker = LocaleFallbacker::new();
50 ///
51 /// // Create a LocaleFallbackerIterator with a default configuration.
52 /// // By default, uses language priority.
53 /// let mut fallback_iterator = fallbacker
54 /// .for_config(Default::default())
55 /// .fallback_for(locale!("hi-Latn-IN").into());
56 ///
57 /// // Run the algorithm and check the results.
58 /// assert_eq!(fallback_iterator.get(), &locale!("hi-Latn-IN").into());
59 /// fallback_iterator.step();
60 /// assert_eq!(fallback_iterator.get(), &locale!("hi-Latn").into());
61 /// fallback_iterator.step();
62 /// assert_eq!(fallback_iterator.get(), &locale!("en-IN").into());
63 /// fallback_iterator.step();
64 /// assert_eq!(fallback_iterator.get(), &locale!("en-001").into());
65 /// fallback_iterator.step();
66 /// assert_eq!(fallback_iterator.get(), &locale!("en").into());
67 /// fallback_iterator.step();
68 /// assert_eq!(fallback_iterator.get(), &locale!("und").into());
69 /// ```
70 ///
71 /// `zh-Hans` normalizes to `zh` because `Hans` is the default script for `zh`:
72 ///
73 /// ```
74 /// use icu::locale::fallback::LocaleFallbacker;
75 /// use icu::locale::locale;
76 ///
77 /// // Set up a LocaleFallbacker with data.
78 /// let fallbacker = LocaleFallbacker::new();
79 ///
80 /// let mut fallback_iterator = fallbacker
81 /// .for_config(Default::default())
82 /// .fallback_for(locale!("zh-Hans").into());
83 ///
84 /// // The origin "zh-Hans" is normalized to "zh" because Hans is the default script.
85 /// assert_eq!(fallback_iterator.get(), &locale!("zh").into());
86 /// fallback_iterator.step();
87 /// assert_eq!(fallback_iterator.get(), &locale!("und").into());
88 /// ```
89 ///
90 /// [UTS #35: Locale Inheritance and Matching]: https://www.unicode.org/reports/tr35/#Locale_Inheritance
91 /// [the design doc]: https://docs.google.com/document/d/1Mp7EUyl-sFh_HZYgyeVwj88vJGpCBIWxzlCwGgLCDwM/edit
92 #[derive(Debug, Clone, PartialEq)]
93 pub struct LocaleFallbacker {
94 likely_subtags: DataPayload<LocaleLikelySubtagsLanguageV1>,
95 parents: DataPayload<LocaleParentsV1>,
96 }
97
98 /// Borrowed version of [`LocaleFallbacker`].
99 #[derive(Debug, Clone, Copy, PartialEq)]
100 pub struct LocaleFallbackerBorrowed<'a> {
101 likely_subtags: &'a LikelySubtagsForLanguage<'a>,
102 parents: &'a Parents<'a>,
103 }
104
105 /// A [`LocaleFallbackerBorrowed`] with an associated [`LocaleFallbackConfig`].
106 #[derive(Debug, Clone, Copy, PartialEq)]
107 pub struct LocaleFallbackerWithConfig<'a> {
108 likely_subtags: &'a LikelySubtagsForLanguage<'a>,
109 parents: &'a Parents<'a>,
110 config: LocaleFallbackConfig,
111 }
112
113 /// Inner iteration type. Does not own the item under fallback.
114 #[derive(Debug)]
115 struct LocaleFallbackIteratorInner<'a> {
116 likely_subtags: &'a LikelySubtagsForLanguage<'a>,
117 parents: &'a Parents<'a>,
118 config: LocaleFallbackConfig,
119 backup_subdivision: Option<Subtag>,
120 backup_variant: Option<Variant>,
121 backup_region: Option<Region>,
122 max_script: Option<Script>,
123 }
124
125 /// Iteration type for locale fallback operations.
126 ///
127 /// Because the `Iterator` trait does not allow items to borrow from the iterator, this class does
128 /// not implement that trait. Instead, use `.step()` and `.get()`.
129 #[derive(Debug)]
130 pub struct LocaleFallbackIterator<'a> {
131 current: DataLocale,
132 inner: LocaleFallbackIteratorInner<'a>,
133 }
134
135 impl LocaleFallbacker {
136 /// Creates a [`LocaleFallbacker`] with compiled fallback data (likely subtags and parent locales).
137 ///
138 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
139 ///
140 /// [📚 Help choosing a constructor](icu_provider::constructors)
141 #[cfg(feature = "compiled_data")]
142 #[expect(clippy::new_ret_no_self)] // keeping constructors together
143 pub const fn new<'a>() -> LocaleFallbackerBorrowed<'a> {
144 // Safety: we're transmuting down from LocaleFallbackerBorrowed<'static> to LocaleFallbackerBorrowed<'a>
145 // ZeroMaps use associated types in a way that confuse the compiler which gives up and marks them
146 // as invariant. However, they are covariant, and in non-const code this covariance can be safely triggered
147 // using Yokeable::transform. In const code we must transmute. In the long run we should
148 // be able to `transform()` in const code, and also we will have hopefully improved map polymorphism (#3128)
149 unsafe {
150 core::mem::transmute::<LocaleFallbackerBorrowed<'static>, LocaleFallbackerBorrowed<'a>>(
151 LocaleFallbackerBorrowed::new(),
152 )
153 }
154 }
155
156 icu_provider::gen_buffer_data_constructors!(() -> error: DataError,
157 functions: [
158 new: skip,
159 try_new_with_buffer_provider,
160 try_new_unstable,
161 Self
162 ]);
163
164 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new)]
165 pub fn try_new_unstable<P>(provider: &P) -> Result<Self, DataError>
166 where
167 P: DataProvider<LocaleLikelySubtagsLanguageV1> + DataProvider<LocaleParentsV1> + ?Sized,
168 {
169 let likely_subtags = provider.load(Default::default())?.payload;
170 let parents = provider.load(Default::default())?.payload;
171 Ok(LocaleFallbacker {
172 likely_subtags,
173 parents,
174 })
175 }
176
177 /// Creates a [`LocaleFallbacker`] without fallback data. Using this constructor may result in
178 /// surprising behavior, especially in multi-script languages.
179 pub fn new_without_data() -> Self {
180 LocaleFallbacker {
181 likely_subtags: DataPayload::from_owned(LikelySubtagsForLanguage {
182 language: Default::default(),
183 language_region: Default::default(),
184 language_script: Default::default(),
185 // Unused
186 und: (Language::UNKNOWN, script!("Zzzz"), region!("ZZ")),
187 }),
188 parents: DataPayload::from_owned(Default::default()),
189 }
190 }
191
192 /// Associates a configuration with this fallbacker.
193 #[inline]
194 pub fn for_config(&self, config: LocaleFallbackConfig) -> LocaleFallbackerWithConfig<'_> {
195 self.as_borrowed().for_config(config)
196 }
197
198 /// Creates a borrowed version of this fallbacker for performance.
199 pub fn as_borrowed(&self) -> LocaleFallbackerBorrowed<'_> {
200 LocaleFallbackerBorrowed {
201 likely_subtags: self.likely_subtags.get(),
202 parents: self.parents.get(),
203 }
204 }
205 }
206
207 impl<'a> LocaleFallbackerBorrowed<'a> {
208 /// Associates a configuration with this fallbacker.
209 #[inline]
210 pub const fn for_config(self, config: LocaleFallbackConfig) -> LocaleFallbackerWithConfig<'a> {
211 LocaleFallbackerWithConfig {
212 likely_subtags: self.likely_subtags,
213 parents: self.parents,
214 config,
215 }
216 }
217 }
218
219 impl LocaleFallbackerBorrowed<'static> {
220 /// Creates a [`LocaleFallbackerBorrowed`] with compiled fallback data (likely subtags and parent locales).
221 ///
222 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
223 ///
224 /// [📚 Help choosing a constructor](icu_provider::constructors)
225 #[cfg(feature = "compiled_data")]
226 #[expect(clippy::new_without_default)]
227 pub const fn new() -> Self {
228 Self {
229 likely_subtags: Baked::SINGLETON_LOCALE_LIKELY_SUBTAGS_LANGUAGE_V1,
230 parents: Baked::SINGLETON_LOCALE_PARENTS_V1,
231 }
232 }
233
234 /// Cheaply converts a [`LocaleFallbackerBorrowed<'static>`] into a [`LocaleFallbacker`].
235 ///
236 /// Note: Due to branching and indirection, using [`LocaleFallbacker`] might inhibit some
237 /// compile-time optimizations that are possible with [`LocaleFallbackerBorrowed`].
238 pub const fn static_to_owned(self) -> LocaleFallbacker {
239 LocaleFallbacker {
240 likely_subtags: DataPayload::from_static_ref(self.likely_subtags),
241 parents: DataPayload::from_static_ref(self.parents),
242 }
243 }
244 }
245
246 impl<'a> LocaleFallbackerWithConfig<'a> {
247 /// Creates an iterator based on a [`DataLocale`].
248 ///
249 /// If you have a [`Locale`], see the [`DataLocale`] docs for information
250 /// on converting it first.
251 ///
252 /// When first initialized, the locale is normalized according to the fallback algorithm.
253 ///
254 /// [`Locale`]: icu_locale_core::Locale
255 pub fn fallback_for(&self, mut locale: DataLocale) -> LocaleFallbackIterator<'a> {
256 let mut default_script = None;
257 self.normalize(&mut locale, &mut default_script);
258 let max_script = locale.script.or(default_script);
259 LocaleFallbackIterator {
260 current: locale,
261 inner: LocaleFallbackIteratorInner {
262 likely_subtags: self.likely_subtags,
263 parents: self.parents,
264 config: self.config,
265 backup_subdivision: None,
266 backup_variant: None,
267 backup_region: None,
268 max_script,
269 },
270 }
271 }
272
273 /// Returns this fallbacker's configuration.
274 pub fn config(&self) -> LocaleFallbackConfig {
275 self.config
276 }
277 }
278
279 impl LocaleFallbackIterator<'_> {
280 /// Borrows the current [`DataLocale`] under fallback.
281 pub fn get(&self) -> &DataLocale {
282 &self.current
283 }
284
285 /// Takes the current [`DataLocale`] under fallback.
286 pub fn take(self) -> DataLocale {
287 self.current
288 }
289
290 /// Performs one step of the locale fallback algorithm.
291 ///
292 /// The fallback is completed once the inner [`DataLocale`] becomes [`DataLocale::default()`].
293 pub fn step(&mut self) -> &mut Self {
294 self.inner.step(&mut self.current);
295 self
296 }
297 }