Debian Codegraph @

debian/rust-vendor/icu_locale/src/names/script.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 use super::DisplayNamesPreferences;
6 use super::{
7 impl_writeable_for_single_display_name_borrowed, impl_writeable_for_single_display_name_owned,
8 load_one,
9 };
10 use crate::provider::names::{
11 LocaleNamesScriptMediumHeavyV1, LocaleNamesScriptMediumLightV1, LocaleNamesScriptMediumTinyV1,
12 LocaleNamesScriptShortHeavyV1,
13 };
14 use icu_locale_core::subtags::Script;
15 use icu_provider::{DataPayloadOr, prelude::*};
16
17 #[inline]
18 fn make_attributes(subtag: &Script) -> &DataMarkerAttributes {
19 // All script markers use the same attributes.
20 // Valid Script subtags conform to DataMarkerAttributes syntax.
21 DataMarkerAttributes::from_str_or_panic(subtag.as_str())
22 }
23
24 #[inline]
25 fn make_locale(prefs: DisplayNamesPreferences) -> DataLocale {
26 // All script markers use the same locale
27 LocaleNamesScriptMediumTinyV1::make_locale(prefs.locale_preferences)
28 }
29
30 macro_rules! table_row {
31 (try_new_tiny) => {
32 "| [`try_new_tiny`](Self::try_new_tiny) | \"Latin\" | ❌ | ❌ |"
33 };
34 (try_new_light) => {
35 "| [`try_new_light`](Self::try_new_light) | \"Latin\" | \"Unknown Script\" | ❌ |"
36 };
37 (try_new_heavy) => {
38 "| [`try_new_heavy`](Self::try_new_heavy) | \"Latin\" | \"Unknown Script\" | \"Sumero-Akkadian Cuneiform\" |"
39 };
40 (try_new_short_heavy) => {
41 "| [`try_new_short_heavy`](Self::try_new_short_heavy) | \"Latin\" | \"Unknown Script\" | \"S-A Cuneiform\" |"
42 };
43 }
44
45 /// A localized display name for a single script, owned version.
46 ///
47 /// # Constructor Behavior
48 ///
49 /// There are several constructors, each of which links different data and serve
50 /// different use cases. The behavior is illustrated in the table below.
51 ///
52 /// | Constructor | `Latn` | `Zzzz` | `Xsux` |
53 /// | :--- | :--- | :--- | :--- |
54 #[doc = concat!(table_row!(try_new_tiny), "\n")]
55 #[doc = concat!(table_row!(try_new_light), "\n")]
56 #[doc = concat!(table_row!(try_new_heavy), "\n")]
57 #[doc = concat!(table_row!(try_new_short_heavy), "\n")]
58 ///
59 /// > Note: :x: means that the constructor returns an error.
60 ///
61 /// There are fallible (`try_new_*`) and infallible (`new_*_with_fallback`) versions of
62 /// all constructors.
63 ///
64 /// # Example
65 ///
66 /// ```
67 /// use icu::locale::names::ScriptDisplayName;
68 /// use icu::locale::{locale, subtags::script};
69 /// use writeable::assert_writeable_eq;
70 ///
71 /// let display_name =
72 /// ScriptDisplayName::try_new_light(locale!("en").into(), script!("Latn"))
73 /// .expect("Data should load successfully");
74 ///
75 /// assert_writeable_eq!(display_name, "Latin");
76 /// ```
77 #[derive(Debug)]
78 pub struct ScriptDisplayName {
79 pub(crate) payload: DataPayloadOr<LocaleNamesScriptMediumLightV1, Script>,
80 }
81
82 impl ScriptDisplayName {
83 /// Loads a script display name in a formatting locale using compiled data.
84 ///
85 /// The `light` constructor links data for all common scripts.
86 /// See the [class docs](Self) for information on which constructor to use.
87 ///
88 /// If the display name is not found in data, the BCP-47 code is returned. To detect this case
89 /// and return an error instead, use [`ScriptDisplayName::try_new_light()`].
90 ///
91 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
92 ///
93 /// # Examples
94 ///
95 /// ```
96 /// use icu::locale::names::ScriptDisplayName;
97 /// use icu::locale::{locale, subtags::script};
98 /// use writeable::assert_writeable_eq;
99 ///
100 /// assert_writeable_eq!(
101 /// ScriptDisplayName::new_light_with_fallback(
102 /// locale!("bs").into(),
103 /// script!("Cyrl")
104 /// ),
105 /// "ćirilica"
106 /// );
107 ///
108 /// assert_writeable_eq!(
109 /// ScriptDisplayName::new_light_with_fallback(
110 /// locale!("zh").into(),
111 /// script!("Cyrl")
112 /// ),
113 /// "西里尔文"
114 /// );
115 /// ```
116 #[cfg(feature = "compiled_data")]
117 pub fn new_light_with_fallback(prefs: DisplayNamesPreferences, script: Script) -> Self {
118 Self::try_new_light(prefs, script).unwrap_or(Self {
119 payload: DataPayloadOr::from_other(script),
120 })
121 }
122
123 icu_provider::gen_buffer_data_constructors!(
124 (prefs: DisplayNamesPreferences, script: Script) -> result: Result<Self, DataError>,
125 /// Loads a script display name in a formatting locale using compiled data.
126 ///
127 /// The `light` constructor links data for all common scripts.
128 /// See the [class docs](Self) for information on which constructor to use.
129 ///
130 /// Returns an error if the display name is not found in data. To return the BCP-47 code
131 /// instead, use [`ScriptDisplayName::new_light_with_fallback()`].
132 ///
133 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
134 ///
135 /// # Examples
136 ///
137 /// ```
138 /// use icu::locale::names::ScriptDisplayName;
139 /// use icu::locale::{locale, subtags::script};
140 /// use writeable::assert_writeable_eq;
141 ///
142 /// let name = ScriptDisplayName::try_new_light(locale!("bs").into(), script!("Cyrl")).unwrap();
143 /// assert_writeable_eq!(
144 /// name,
145 /// "ćirilica"
146 /// );
147 ///
148 /// let name = ScriptDisplayName::try_new_light(locale!("zh").into(), script!("Cyrl")).unwrap();
149 /// assert_writeable_eq!(
150 /// name,
151 /// "西里尔文"
152 /// );
153 /// ```
154 functions: [
155 try_new_light,
156 try_new_light_with_buffer_provider,
157 try_new_light_unstable,
158 Self
159 ]
160 );
161
162 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_light)]
163 pub fn try_new_light_unstable<D>(
164 provider: &D,
165 prefs: DisplayNamesPreferences,
166 script: Script,
167 ) -> Result<Self, DataError>
168 where
169 D: ?Sized
170 + DataProvider<LocaleNamesScriptMediumLightV1>
171 + DataProvider<LocaleNamesScriptMediumTinyV1>,
172 {
173 let attrs = make_attributes(&script);
174 let locale = make_locale(prefs);
175 let payload = load_one::<LocaleNamesScriptMediumLightV1, _, _>(provider, &locale, attrs)?
176 .map_or_else(
177 || load_one::<LocaleNamesScriptMediumTinyV1, _, _>(provider, &locale, attrs),
178 |p| Ok(Some(p)),
179 )?
180 .map(DataPayloadOr::from_payload)
181 .ok_or_else(|| DataErrorKind::IdentifierNotFound.into_error())?;
182 Ok(Self { payload })
183 }
184
185 /// Loads a script display name in a formatting locale using compiled data.
186 ///
187 /// The `tiny` constructor links an extremely limited amount of data, with a focus on
188 /// scripts associated with the formatting locale. For example, the Cyrillic script
189 /// is included in `bs` (Bosnian) but not `zh` (Chinese).
190 /// See the [class docs](Self) for more information on which constructor to use.
191 ///
192 /// If the display name is not found in data, the BCP-47 code is returned. To detect this case
193 /// and return an error instead, use [`ScriptDisplayName::try_new_tiny()`].
194 ///
195 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
196 ///
197 /// # Examples
198 ///
199 /// ```
200 /// use icu::locale::names::ScriptDisplayName;
201 /// use icu::locale::{locale, subtags::script};
202 /// use writeable::assert_writeable_eq;
203 ///
204 /// assert_writeable_eq!(
205 /// ScriptDisplayName::new_tiny_with_fallback(
206 /// locale!("bs").into(),
207 /// script!("Cyrl")
208 /// ),
209 /// "ćirilica"
210 /// );
211 ///
212 /// // Name for Cyrillic script is NOT included in the Chinese locale
213 /// assert_writeable_eq!(
214 /// ScriptDisplayName::new_tiny_with_fallback(
215 /// locale!("zh").into(),
216 /// script!("Cyrl")
217 /// ),
218 /// "Cyrl"
219 /// );
220 /// ```
221 #[cfg(feature = "compiled_data")]
222 pub fn new_tiny_with_fallback(prefs: DisplayNamesPreferences, script: Script) -> Self {
223 Self::try_new_tiny(prefs, script).unwrap_or(Self {
224 payload: DataPayloadOr::from_other(script),
225 })
226 }
227
228 icu_provider::gen_buffer_data_constructors!(
229 (prefs: DisplayNamesPreferences, script: Script) -> result: Result<Self, DataError>,
230 /// Loads a script display name in a formatting locale using compiled data.
231 ///
232 /// The `tiny` constructor links an extremely limited amount of data, with a focus on
233 /// scripts associated with the formatting locale. For example, the Cyrillic script
234 /// is included in `bs` (Bosnian) but not `zh` (Chinese).
235 /// See the [class docs](Self) for more information on which constructor to use.
236 ///
237 /// Returns an error if the display name is not found in data. To return the BCP-47 code
238 /// instead, use [`ScriptDisplayName::new_tiny_with_fallback()`].
239 ///
240 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
241 ///
242 /// # Examples
243 ///
244 /// ```
245 /// use icu::locale::names::ScriptDisplayName;
246 /// use icu::locale::{locale, subtags::script};
247 /// use writeable::assert_writeable_eq;
248 ///
249 /// let name = ScriptDisplayName::try_new_tiny(locale!("bs").into(), script!("Cyrl")).unwrap();
250 /// assert_writeable_eq!(
251 /// name,
252 /// "ćirilica"
253 /// );
254 ///
255 /// // Name for Cyrillic script is NOT included in the Chinese locale
256 /// ScriptDisplayName::try_new_tiny(locale!("zh").into(), script!("Cyrl")).unwrap_err();
257 /// ```
258 functions: [
259 try_new_tiny,
260 try_new_tiny_with_buffer_provider,
261 try_new_tiny_unstable,
262 Self
263 ]
264 );
265
266 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_tiny)]
267 pub fn try_new_tiny_unstable<D>(
268 provider: &D,
269 prefs: DisplayNamesPreferences,
270 script: Script,
271 ) -> Result<Self, DataError>
272 where
273 D: ?Sized + DataProvider<LocaleNamesScriptMediumTinyV1>,
274 {
275 let attrs = make_attributes(&script);
276 let locale = make_locale(prefs);
277 let payload = load_one::<LocaleNamesScriptMediumTinyV1, _, _>(provider, &locale, attrs)?
278 .map(DataPayloadOr::from_payload)
279 .ok_or_else(|| DataErrorKind::IdentifierNotFound.into_error())?;
280 Ok(Self { payload })
281 }
282
283 /// Loads a script display name in a formatting locale using compiled data.
284 ///
285 /// The `heavy` constructor includes additional data coverage for subtags that are
286 /// less commonly formatted in the target locale.
287 /// See the [class docs](Self) for information on which constructor to use.
288 ///
289 /// If the display name is not found in data, the BCP-47 code is returned. To detect this case
290 /// and return an error instead, use [`ScriptDisplayName::try_new_heavy()`].
291 ///
292 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
293 ///
294 /// # Examples
295 ///
296 /// ```
297 /// use icu::locale::names::ScriptDisplayName;
298 /// use icu::locale::{locale, subtags::script};
299 /// use writeable::assert_writeable_eq;
300 ///
301 /// assert_writeable_eq!(
302 /// ScriptDisplayName::new_heavy_with_fallback(
303 /// locale!("de").into(),
304 /// script!("Latn")
305 /// ),
306 /// "Lateinisch"
307 /// );
308 ///
309 /// assert_writeable_eq!(
310 /// ScriptDisplayName::new_heavy_with_fallback(
311 /// locale!("de").into(),
312 /// script!("Xsux")
313 /// ),
314 /// "Sumerisch-akkadische Keilschrift"
315 /// );
316 /// ```
317 #[cfg(feature = "compiled_data")]
318 pub fn new_heavy_with_fallback(prefs: DisplayNamesPreferences, script: Script) -> Self {
319 Self::try_new_heavy(prefs, script).unwrap_or(Self {
320 payload: DataPayloadOr::from_other(script),
321 })
322 }
323
324 icu_provider::gen_buffer_data_constructors!(
325 (prefs: DisplayNamesPreferences, script: Script) -> result: Result<Self, DataError>,
326 /// Loads a script display name in a formatting locale using compiled data.
327 ///
328 /// The `heavy` constructor includes additional data coverage for subtags that are
329 /// less commonly formatted in the target locale.
330 /// See the [class docs](Self) for information on which constructor to use.
331 ///
332 /// Returns an error if the display name is not found in data. To return the BCP-47 code
333 /// instead, use [`ScriptDisplayName::new_heavy_with_fallback()`].
334 ///
335 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
336 ///
337 /// # Examples
338 ///
339 /// ```
340 /// use icu::locale::names::ScriptDisplayName;
341 /// use icu::locale::{locale, subtags::script};
342 /// use writeable::assert_writeable_eq;
343 ///
344 /// let name = ScriptDisplayName::try_new_heavy(locale!("de").into(), script!("Latn")).unwrap();
345 /// assert_writeable_eq!(
346 /// name,
347 /// "Lateinisch"
348 /// );
349 ///
350 /// let name = ScriptDisplayName::try_new_heavy(locale!("de").into(), script!("Xsux")).unwrap();
351 /// assert_writeable_eq!(
352 /// name,
353 /// "Sumerisch-akkadische Keilschrift"
354 /// );
355 /// ```
356 functions: [
357 try_new_heavy,
358 try_new_heavy_with_buffer_provider,
359 try_new_heavy_unstable,
360 Self
361 ]
362 );
363
364 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_heavy)]
365 pub fn try_new_heavy_unstable<D>(
366 provider: &D,
367 prefs: DisplayNamesPreferences,
368 script: Script,
369 ) -> Result<Self, DataError>
370 where
371 D: ?Sized
372 + DataProvider<LocaleNamesScriptMediumHeavyV1>
373 + DataProvider<LocaleNamesScriptMediumLightV1>
374 + DataProvider<LocaleNamesScriptMediumTinyV1>,
375 {
376 let attrs = make_attributes(&script);
377 let locale = make_locale(prefs);
378 let payload = load_one::<LocaleNamesScriptMediumHeavyV1, _, _>(provider, &locale, attrs)?
379 .map_or_else(
380 || load_one::<LocaleNamesScriptMediumLightV1, _, _>(provider, &locale, attrs),
381 |p| Ok(Some(p)),
382 )?
383 .map_or_else(
384 || load_one::<LocaleNamesScriptMediumTinyV1, _, _>(provider, &locale, attrs),
385 |p| Ok(Some(p)),
386 )?
387 .map(DataPayloadOr::from_payload)
388 .ok_or_else(|| DataErrorKind::IdentifierNotFound.into_error())?;
389 Ok(Self { payload })
390 }
391
392 /// Loads a short script display name in a formatting locale using compiled data.
393 ///
394 /// Falls back to default (medium) length if a short name is not available.
395 ///
396 /// The `heavy` constructor includes additional data coverage for subtags that are
397 /// less commonly formatted in the target locale.
398 /// See the [class docs](Self) for information on which constructor to use.
399 ///
400 /// If the display name is not found in data, the BCP-47 code is returned. To detect this case
401 /// and return an error instead, use [`ScriptDisplayName::try_new_short_heavy()`].
402 ///
403 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
404 ///
405 /// # Examples
406 ///
407 /// ```
408 /// use icu::locale::names::ScriptDisplayName;
409 /// use icu::locale::{locale, subtags::script};
410 /// use writeable::assert_writeable_eq;
411 ///
412 /// assert_writeable_eq!(
413 /// ScriptDisplayName::new_short_heavy_with_fallback(
414 /// locale!("de").into(),
415 /// script!("Latn")
416 /// ),
417 /// "Lateinisch"
418 /// );
419 ///
420 /// // Example short name: script Xsux -> "S-A Cuneiform" in en
421 /// assert_writeable_eq!(
422 /// ScriptDisplayName::new_short_heavy_with_fallback(
423 /// locale!("en").into(),
424 /// script!("Xsux")
425 /// ),
426 /// "S-A Cuneiform"
427 /// );
428 /// ```
429 #[cfg(feature = "compiled_data")]
430 pub fn new_short_heavy_with_fallback(prefs: DisplayNamesPreferences, script: Script) -> Self {
431 Self::try_new_short_heavy(prefs, script).unwrap_or(Self {
432 payload: DataPayloadOr::from_other(script),
433 })
434 }
435
436 icu_provider::gen_buffer_data_constructors!(
437 (prefs: DisplayNamesPreferences, script: Script) -> result: Result<Self, DataError>,
438 /// Loads a short script display name in a formatting locale using compiled data.
439 ///
440 /// Falls back to default (medium) length if a short name is not available.
441 ///
442 /// The `heavy` constructor includes additional data coverage for subtags that are
443 /// less commonly formatted in the target locale.
444 /// See the [class docs](Self) for information on which constructor to use.
445 ///
446 /// Returns an error if the display name is not found in data. To return the BCP-47 code
447 /// instead, use [`ScriptDisplayName::new_short_heavy_with_fallback()`].
448 ///
449 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
450 ///
451 /// # Examples
452 ///
453 /// ```
454 /// use icu::locale::names::ScriptDisplayName;
455 /// use icu::locale::{locale, subtags::script};
456 /// use writeable::assert_writeable_eq;
457 ///
458 /// let name = ScriptDisplayName::try_new_short_heavy(locale!("de").into(), script!("Latn")).unwrap();
459 /// assert_writeable_eq!(
460 /// name,
461 /// "Lateinisch"
462 /// );
463 ///
464 /// // Example short name: script Xsux -> "S-A Cuneiform" in en
465 /// let name = ScriptDisplayName::try_new_short_heavy(locale!("en").into(), script!("Xsux")).unwrap();
466 /// assert_writeable_eq!(
467 /// name,
468 /// "S-A Cuneiform"
469 /// );
470 /// ```
471 functions: [
472 try_new_short_heavy,
473 try_new_short_heavy_with_buffer_provider,
474 try_new_short_heavy_unstable,
475 Self
476 ]
477 );
478
479 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_short_heavy)]
480 pub fn try_new_short_heavy_unstable<D>(
481 provider: &D,
482 prefs: DisplayNamesPreferences,
483 script: Script,
484 ) -> Result<Self, DataError>
485 where
486 D: ?Sized
487 + DataProvider<LocaleNamesScriptShortHeavyV1>
488 + DataProvider<LocaleNamesScriptMediumHeavyV1>
489 + DataProvider<LocaleNamesScriptMediumLightV1>
490 + DataProvider<LocaleNamesScriptMediumTinyV1>,
491 {
492 let attrs = make_attributes(&script);
493 let locale = make_locale(prefs);
494 let payload = load_one::<LocaleNamesScriptShortHeavyV1, _, _>(provider, &locale, attrs)?
495 .map_or_else(
496 || load_one::<LocaleNamesScriptMediumHeavyV1, _, _>(provider, &locale, attrs),
497 |p| Ok(Some(p)),
498 )?
499 .map_or_else(
500 || load_one::<LocaleNamesScriptMediumLightV1, _, _>(provider, &locale, attrs),
501 |p| Ok(Some(p)),
502 )?
503 .map_or_else(
504 || load_one::<LocaleNamesScriptMediumTinyV1, _, _>(provider, &locale, attrs),
505 |p| Ok(Some(p)),
506 )?
507 .map(DataPayloadOr::from_payload)
508 .ok_or_else(|| DataErrorKind::IdentifierNotFound.into_error())?;
509 Ok(Self { payload })
510 }
511
512 #[inline]
513 fn borrow_str(&self) -> &str {
514 match self.payload.get() {
515 Ok(s) => s,
516 Err(subtag) => subtag.as_str(),
517 }
518 }
519
520 /// Returns a borrowed version of this display name.
521 pub fn as_borrowed(&self) -> ScriptDisplayNameBorrowed<'_> {
522 ScriptDisplayNameBorrowed {
523 value: self.borrow_str(),
524 }
525 }
526 }
527
528 impl_writeable_for_single_display_name_owned!(ScriptDisplayName);
529
530 /// A localized display name for a single script.
531 #[derive(Debug, Clone, Copy)]
532 pub struct ScriptDisplayNameBorrowed<'a> {
533 value: &'a str,
534 }
535
536 impl_writeable_for_single_display_name_borrowed!(ScriptDisplayNameBorrowed);
537
538 #[cfg(test)]
539 mod tests {
540 use super::*;
541 use icu_locale_core::{locale, subtags::script};
542
543 #[test]
544 fn test_script_display_name_owned_table() {
545 let prefs_en = DisplayNamesPreferences::from(locale!("en"));
546 let inputs = [script!("Latn"), script!("Zzzz"), script!("Xsux")];
547
548 macro_rules! check_row {
549 ($constructor:ident) => {
550 let items = inputs.iter().map(|id| {
551 ScriptDisplayName::$constructor(prefs_en, *id)
552 .map(|name| Ok::<_, ()>(name.to_string()))
553 });
554 assert_eq!(
555 super::super::format_table_row(stringify!($constructor), items),
556 table_row!($constructor)
557 );
558 };
559 }
560
561 check_row!(try_new_tiny);
562 check_row!(try_new_light);
563 check_row!(try_new_heavy);
564 check_row!(try_new_short_heavy);
565 }
566 }