Debian Codegraph @

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