Debian Codegraph @

debian/rust-vendor/icu_locale/src/names/variant.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::LocaleNamesVariantMediumHeavyV1;
11 use icu_locale_core::subtags::Variant;
12 use icu_provider::{DataPayloadOr, prelude::*};
13
14 #[inline]
15 fn make_attributes(subtag: &Variant) -> &DataMarkerAttributes {
16 // All variant markers use the same attributes.
17 // Valid Variant subtags conform to DataMarkerAttributes syntax.
18 DataMarkerAttributes::from_str_or_panic(subtag.as_str())
19 }
20
21 #[inline]
22 fn make_locale(prefs: DisplayNamesPreferences) -> DataLocale {
23 // All variant markers use the same locale
24 LocaleNamesVariantMediumHeavyV1::make_locale(prefs.locale_preferences)
25 }
26
27 macro_rules! table_row {
28 (try_new_heavy) => {
29 "| [`try_new_heavy`](Self::try_new_heavy) | \"IPA Phonetics\" | \"Computer\" |"
30 };
31 }
32
33 /// A localized display name for a single variant, owned version.
34 ///
35 /// # Constructor Behavior
36 ///
37 /// There is currently just one constructor, which is named "extended"
38 /// since there are no variants with guaranteed display names.
39 ///
40 /// | Constructor | `fonipa` | `posix` |
41 /// | :--- | :--- | :--- |
42 #[doc = concat!(table_row!(try_new_heavy), "\n")]
43 ///
44 /// There are fallible (`try_new_*`) and infallible (`new_*_with_fallback`) versions of
45 /// all constructors.
46 ///
47 /// # Example
48 ///
49 /// ```
50 /// use icu::locale::names::VariantDisplayName;
51 /// use icu::locale::{locale, subtags::variant};
52 /// use writeable::assert_writeable_eq;
53 ///
54 /// let display_name = VariantDisplayName::try_new_heavy(
55 /// locale!("en").into(),
56 /// variant!("fonipa"),
57 /// )
58 /// .expect("Data should load successfully");
59 ///
60 /// assert_writeable_eq!(display_name, "IPA Phonetics");
61 /// ```
62 #[derive(Debug)]
63 pub struct VariantDisplayName {
64 pub(crate) payload: DataPayloadOr<LocaleNamesVariantMediumHeavyV1, Variant>,
65 }
66
67 impl VariantDisplayName {
68 /// Loads a variant display name in a formatting locale using compiled data.
69 ///
70 /// The `heavy` constructor includes additional data coverage for subtags that are
71 /// less commonly formatted in the target locale.
72 /// See the [class docs](Self) for information on which constructor to use.
73 ///
74 /// If the display name is not found in data, the BCP-47 code is returned. To detect this case
75 /// and return an error instead, use [`VariantDisplayName::try_new_heavy()`].
76 ///
77 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
78 ///
79 /// # Examples
80 ///
81 /// ```
82 /// use icu::locale::names::VariantDisplayName;
83 /// use icu::locale::{locale, subtags::variant};
84 /// use writeable::assert_writeable_eq;
85 ///
86 /// assert_writeable_eq!(
87 /// VariantDisplayName::new_heavy_with_fallback(
88 /// locale!("de").into(),
89 /// variant!("fonipa")
90 /// ),
91 /// "IPA Phonetisch"
92 /// );
93 ///
94 /// assert_writeable_eq!(
95 /// VariantDisplayName::new_heavy_with_fallback(
96 /// locale!("fr").into(),
97 /// variant!("fonipa")
98 /// ),
99 /// "alphabet phonétique international"
100 /// );
101 /// ```
102 #[cfg(feature = "compiled_data")]
103 pub fn new_heavy_with_fallback(prefs: DisplayNamesPreferences, variant: Variant) -> Self {
104 Self::try_new_heavy(prefs, variant).unwrap_or(Self {
105 payload: DataPayloadOr::from_other(variant),
106 })
107 }
108
109 icu_provider::gen_buffer_data_constructors!(
110 (prefs: DisplayNamesPreferences, variant: Variant) -> result: Result<Self, DataError>,
111 /// Loads a variant display name in a formatting locale using compiled data.
112 ///
113 /// The `heavy` constructor includes additional data coverage for subtags that are
114 /// less commonly formatted in the target locale.
115 /// See the [class docs](Self) for information on which constructor to use.
116 ///
117 /// Returns an error if the display name is not found in data. To return the BCP-47 code
118 /// instead, use [`VariantDisplayName::new_heavy_with_fallback()`].
119 ///
120 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
121 ///
122 /// # Examples
123 ///
124 /// ```
125 /// use icu::locale::names::VariantDisplayName;
126 /// use icu::locale::{locale, subtags::variant};
127 /// use writeable::assert_writeable_eq;
128 ///
129 /// let name = VariantDisplayName::try_new_heavy(locale!("de").into(), variant!("fonipa")).unwrap();
130 /// assert_writeable_eq!(
131 /// name,
132 /// "IPA Phonetisch"
133 /// );
134 ///
135 /// let name = VariantDisplayName::try_new_heavy(locale!("fr").into(), variant!("fonipa")).unwrap();
136 /// assert_writeable_eq!(
137 /// name,
138 /// "alphabet phonétique international"
139 /// );
140 /// ```
141 functions: [
142 try_new_heavy,
143 try_new_heavy_with_buffer_provider,
144 try_new_heavy_unstable,
145 Self
146 ]
147 );
148
149 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new_heavy)]
150 pub fn try_new_heavy_unstable<D>(
151 provider: &D,
152 prefs: DisplayNamesPreferences,
153 variant: Variant,
154 ) -> Result<Self, DataError>
155 where
156 D: ?Sized + DataProvider<LocaleNamesVariantMediumHeavyV1>,
157 {
158 let attrs = make_attributes(&variant);
159 let locale = make_locale(prefs);
160 let payload = load_one::<LocaleNamesVariantMediumHeavyV1, _, _>(provider, &locale, attrs)?
161 .map(DataPayloadOr::from_payload)
162 .ok_or_else(|| DataErrorKind::IdentifierNotFound.into_error())?;
163 Ok(Self { payload })
164 }
165
166 #[inline]
167 fn borrow_str(&self) -> &str {
168 match self.payload.get() {
169 Ok(s) => s,
170 Err(subtag) => subtag.as_str(),
171 }
172 }
173
174 /// Returns a borrowed version of this display name.
175 pub fn as_borrowed(&self) -> VariantDisplayNameBorrowed<'_> {
176 VariantDisplayNameBorrowed {
177 value: self.borrow_str(),
178 }
179 }
180 }
181
182 impl_writeable_for_single_display_name_owned!(VariantDisplayName);
183
184 /// A localized display name for a single variant.
185 #[derive(Debug, Clone, Copy)]
186 pub struct VariantDisplayNameBorrowed<'a> {
187 value: &'a str,
188 }
189
190 impl_writeable_for_single_display_name_borrowed!(VariantDisplayNameBorrowed);
191
192 #[cfg(test)]
193 mod tests {
194 use super::*;
195 use icu_locale_core::{locale, subtags::variant};
196
197 #[test]
198 fn test_variant_display_name_owned_table() {
199 let prefs_en = DisplayNamesPreferences::from(locale!("en"));
200 let inputs = [variant!("fonipa"), variant!("posix")];
201
202 macro_rules! check_row {
203 ($constructor:ident) => {
204 let items = inputs.iter().map(|id| {
205 VariantDisplayName::$constructor(prefs_en, *id)
206 .map(|name| Ok::<_, ()>(name.to_string()))
207 });
208 assert_eq!(
209 super::super::format_table_row(stringify!($constructor), items),
210 table_row!($constructor)
211 );
212 };
213 }
214
215 check_row!(try_new_heavy);
216 }
217 }