Debian Codegraph @

debian/rust-vendor/icu_properties/src/names.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 crate::props::*;
6 use crate::provider::names::*;
7 use core::marker::PhantomData;
8 use icu_collections::codepointtrie::TrieValue;
9 use icu_provider::marker::ErasedMarker;
10 use icu_provider::prelude::*;
11 use yoke::Yokeable;
12 use zerotrie::cursor::ZeroTrieSimpleAsciiCursor;
13
14 /// A struct capable of looking up a property value from a string name.
15 /// Access its data by calling [`Self::as_borrowed()`] and using the methods on
16 /// [`PropertyParserBorrowed`].
17 ///
18 /// The name can be a short name (`Lu`), a long name(`Uppercase_Letter`),
19 /// or an alias.
20 ///
21 /// Property names can be looked up using "strict" matching (looking for a name
22 /// that matches exactly), or "loose matching", where the name is allowed to deviate
23 /// in terms of ASCII casing, whitespace, underscores, and hyphens.
24 ///
25 /// # Example
26 ///
27 /// ```
28 /// use icu::properties::PropertyParser;
29 /// use icu::properties::props::GeneralCategory;
30 ///
31 /// let lookup = PropertyParser::<GeneralCategory>::new();
32 /// // short name for value
33 /// assert_eq!(
34 /// lookup.get_strict("Lu"),
35 /// Some(GeneralCategory::UppercaseLetter)
36 /// );
37 /// assert_eq!(
38 /// lookup.get_strict("Pd"),
39 /// Some(GeneralCategory::DashPunctuation)
40 /// );
41 /// // long name for value
42 /// assert_eq!(
43 /// lookup.get_strict("Uppercase_Letter"),
44 /// Some(GeneralCategory::UppercaseLetter)
45 /// );
46 /// assert_eq!(
47 /// lookup.get_strict("Dash_Punctuation"),
48 /// Some(GeneralCategory::DashPunctuation)
49 /// );
50 /// // name has incorrect casing
51 /// assert_eq!(lookup.get_strict("dashpunctuation"), None);
52 /// // loose matching of name
53 /// assert_eq!(
54 /// lookup.get_loose("dash-punctuation"),
55 /// Some(GeneralCategory::DashPunctuation)
56 /// );
57 /// // fake property
58 /// assert_eq!(lookup.get_strict("Animated_Gif"), None);
59 /// ```
60 #[derive(Debug)]
61 pub struct PropertyParser<T> {
62 map: DataPayload<ErasedMarker<PropertyValueNameToEnumMap<'static>>>,
63 markers: PhantomData<fn() -> T>,
64 }
65
66 /// A borrowed wrapper around property value name-to-enum data, returned by
67 /// [`PropertyParser::as_borrowed()`]. More efficient to query.
68 #[derive(Debug)]
69 pub struct PropertyParserBorrowed<'a, T> {
70 map: &'a PropertyValueNameToEnumMap<'a>,
71 markers: PhantomData<fn() -> T>,
72 }
73
74 impl<T> Clone for PropertyParserBorrowed<'_, T> {
75 fn clone(&self) -> Self {
76 *self
77 }
78 }
79 impl<T> Copy for PropertyParserBorrowed<'_, T> {}
80
81 impl<T> PropertyParser<T> {
82 /// Creates a new instance of `PropertyParser<T>` using compiled data.
83 ///
84 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
85 ///
86 /// [📚 Help choosing a constructor](icu_provider::constructors)
87 #[cfg(feature = "compiled_data")]
88 #[expect(clippy::new_ret_no_self)]
89 pub const fn new() -> PropertyParserBorrowed<'static, T>
90 where
91 T: ParseableEnumeratedProperty,
92 {
93 PropertyParserBorrowed::new()
94 }
95
96 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new)]
97 pub fn try_new_unstable(
98 provider: &(impl DataProvider<T::DataMarker> + ?Sized),
99 ) -> Result<Self, DataError>
100 where
101 T: ParseableEnumeratedProperty,
102 {
103 Ok(Self {
104 map: provider.load(Default::default())?.payload.cast(),
105 markers: PhantomData,
106 })
107 }
108
109 /// Construct a borrowed version of this type that can be queried.
110 ///
111 /// This avoids a potential small underlying cost per API call (like `get_strict()`) by consolidating it
112 /// up front.
113 #[inline]
114 pub fn as_borrowed(&self) -> PropertyParserBorrowed<'_, T> {
115 PropertyParserBorrowed {
116 map: self.map.get(),
117 markers: PhantomData,
118 }
119 }
120
121 #[doc(hidden)] // used by FFI code
122 pub fn erase(self) -> PropertyParser<u16> {
123 PropertyParser {
124 map: self.map.cast(),
125 markers: PhantomData,
126 }
127 }
128 }
129
130 impl<T: TrieValue> PropertyParserBorrowed<'_, T> {
131 /// Get the property value as a u16, doing a strict search looking for
132 /// names that match exactly
133 ///
134 /// # Example
135 ///
136 /// ```
137 /// use icu::properties::PropertyParser;
138 /// use icu::properties::props::GeneralCategory;
139 ///
140 /// let lookup = PropertyParser::<GeneralCategory>::new();
141 /// assert_eq!(
142 /// lookup.get_strict_u16("Lu"),
143 /// Some(GeneralCategory::UppercaseLetter as u16)
144 /// );
145 /// assert_eq!(
146 /// lookup.get_strict_u16("Uppercase_Letter"),
147 /// Some(GeneralCategory::UppercaseLetter as u16)
148 /// );
149 /// // does not do loose matching
150 /// assert_eq!(lookup.get_strict_u16("UppercaseLetter"), None);
151 /// ```
152 #[inline]
153 pub fn get_strict_u16(self, name: &str) -> Option<u16> {
154 self.get_strict_u16_utf8(name.as_bytes())
155 }
156
157 #[doc(hidden)]
158 pub fn get_strict_u16_utf8(self, name: &[u8]) -> Option<u16> {
159 get_strict_u16(self.map, name)
160 }
161
162 /// Get the property value as a `T`, doing a strict search looking for
163 /// names that match exactly
164 ///
165 /// # Example
166 ///
167 /// ```
168 /// use icu::properties::PropertyParser;
169 /// use icu::properties::props::GeneralCategory;
170 ///
171 /// let lookup = PropertyParser::<GeneralCategory>::new();
172 /// assert_eq!(
173 /// lookup.get_strict("Lu"),
174 /// Some(GeneralCategory::UppercaseLetter)
175 /// );
176 /// assert_eq!(
177 /// lookup.get_strict("Uppercase_Letter"),
178 /// Some(GeneralCategory::UppercaseLetter)
179 /// );
180 /// // does not do loose matching
181 /// assert_eq!(lookup.get_strict("UppercaseLetter"), None);
182 /// ```
183 #[inline]
184 pub fn get_strict(self, name: &str) -> Option<T> {
185 self.get_strict_utf8(name.as_bytes())
186 }
187
188 #[doc(hidden)]
189 pub fn get_strict_utf8(self, name: &[u8]) -> Option<T> {
190 T::try_from_u32(self.get_strict_u16_utf8(name)? as u32).ok()
191 }
192
193 /// Get the property value as a u16, doing a loose search looking for
194 /// names that match case-insensitively, ignoring ASCII hyphens, underscores, and
195 /// whitespaces.
196 ///
197 /// # Example
198 ///
199 /// ```
200 /// use icu::properties::PropertyParser;
201 /// use icu::properties::props::GeneralCategory;
202 ///
203 /// let lookup = PropertyParser::<GeneralCategory>::new();
204 /// assert_eq!(
205 /// lookup.get_loose_u16("Lu"),
206 /// Some(GeneralCategory::UppercaseLetter as u16)
207 /// );
208 /// assert_eq!(
209 /// lookup.get_loose_u16("Uppercase_Letter"),
210 /// Some(GeneralCategory::UppercaseLetter as u16)
211 /// );
212 /// // does do loose matching
213 /// assert_eq!(
214 /// lookup.get_loose_u16("UppercaseLetter"),
215 /// Some(GeneralCategory::UppercaseLetter as u16)
216 /// );
217 /// ```
218 #[inline]
219 pub fn get_loose_u16(self, name: &str) -> Option<u16> {
220 self.get_loose_u16_utf8(name.as_bytes())
221 }
222
223 #[doc(hidden)]
224 pub fn get_loose_u16_utf8(self, name: &[u8]) -> Option<u16> {
225 get_loose_u16(self.map, name)
226 }
227
228 /// Get the property value as a `T`, doing a loose search looking for
229 /// names that match case-insensitively, ignoring ASCII hyphens, underscores, and
230 /// whitespaces.
231 ///
232 /// # Example
233 ///
234 /// ```
235 /// use icu::properties::PropertyParser;
236 /// use icu::properties::props::GeneralCategory;
237 ///
238 /// let lookup = PropertyParser::<GeneralCategory>::new();
239 /// assert_eq!(
240 /// lookup.get_loose("Lu"),
241 /// Some(GeneralCategory::UppercaseLetter)
242 /// );
243 /// assert_eq!(
244 /// lookup.get_loose("Uppercase_Letter"),
245 /// Some(GeneralCategory::UppercaseLetter)
246 /// );
247 /// // does do loose matching
248 /// assert_eq!(
249 /// lookup.get_loose("UppercaseLetter"),
250 /// Some(GeneralCategory::UppercaseLetter)
251 /// );
252 /// ```
253 #[inline]
254 pub fn get_loose(self, name: &str) -> Option<T> {
255 self.get_loose_utf8(name.as_bytes())
256 }
257
258 #[doc(hidden)]
259 pub fn get_loose_utf8(self, name: &[u8]) -> Option<T> {
260 T::try_from_u32(self.get_loose_u16_utf8(name)? as u32).ok()
261 }
262 }
263
264 #[cfg(feature = "compiled_data")]
265 impl<T: ParseableEnumeratedProperty> Default for PropertyParserBorrowed<'static, T> {
266 fn default() -> Self {
267 Self::new()
268 }
269 }
270
271 impl<T: TrieValue> PropertyParserBorrowed<'static, T> {
272 /// Creates a new instance of `PropertyParserBorrowed<T>` using compiled data.
273 ///
274 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
275 ///
276 /// [📚 Help choosing a constructor](icu_provider::constructors)
277 #[cfg(feature = "compiled_data")]
278 pub const fn new() -> Self
279 where
280 T: ParseableEnumeratedProperty,
281 {
282 Self {
283 map: T::SINGLETON,
284 markers: PhantomData,
285 }
286 }
287
288 /// Cheaply converts a [`PropertyParserBorrowed<'static>`] into a [`PropertyParser`].
289 ///
290 /// Note: Due to branching and indirection, using [`PropertyParser`] might inhibit some
291 /// compile-time optimizations that are possible with [`PropertyParserBorrowed`].
292 pub const fn static_to_owned(self) -> PropertyParser<T> {
293 PropertyParser {
294 map: DataPayload::from_static_ref(self.map),
295 markers: PhantomData,
296 }
297 }
298 }
299
300 /// Avoid monomorphizing multiple copies of this function
301 fn get_strict_u16(payload: &PropertyValueNameToEnumMap<'_>, name: &[u8]) -> Option<u16> {
302 payload.map.get(name).and_then(|i| i.try_into().ok())
303 }
304
305 /// Avoid monomorphizing multiple copies of this function
306 fn get_loose_u16(payload: &PropertyValueNameToEnumMap<'_>, name: &[u8]) -> Option<u16> {
307 fn recurse(mut cursor: ZeroTrieSimpleAsciiCursor, mut rest: &[u8]) -> Option<usize> {
308 if cursor.is_empty() {
309 return None;
310 }
311
312 // Skip underscore in trie
313 let mut skip_cursor = cursor.clone();
314 skip_cursor.step(b'_');
315 if let Some(r) = recurse(skip_cursor, rest) {
316 return Some(r);
317 }
318
319 let ascii = loop {
320 let Some((&a, r)) = rest.split_first() else {
321 return cursor.take_value();
322 };
323 rest = r;
324
325 // Skip whitespace, underscore, hyphen in input
326 if !matches!(
327 a,
328 b'\t' | b'\n' | b'\x0C' | b'\r' | b' ' | 0x0B | b'_' | b'-'
329 ) {
330 break a;
331 }
332 };
333
334 // Try matching with the original case first
335 let mut cursor_clone = cursor.clone();
336 cursor_clone.step(ascii);
337 if let Some(r) = recurse(cursor_clone, rest) {
338 return Some(r);
339 }
340
341 // Try matching with the other case
342 let other_case = if ascii.is_ascii_lowercase() {
343 ascii.to_ascii_uppercase()
344 } else {
345 ascii.to_ascii_lowercase()
346 };
347
348 // If the other_case is different then recurse
349 if other_case != ascii {
350 cursor.step(other_case);
351 return recurse(cursor, rest);
352 }
353
354 None
355 }
356
357 recurse(payload.map.cursor(), name).and_then(|i| i.try_into().ok())
358 }
359
360 /// A struct capable of looking up a property name from a value
361 /// Access its data by calling [`Self::as_borrowed()`] and using the methods on
362 /// [`PropertyNamesLongBorrowed`].
363 ///
364 /// # Example
365 ///
366 /// ```
367 /// use icu::properties::PropertyNamesLong;
368 /// use icu::properties::props::CanonicalCombiningClass;
369 ///
370 /// let names = PropertyNamesLong::<CanonicalCombiningClass>::new();
371 /// assert_eq!(
372 /// names.get(CanonicalCombiningClass::KanaVoicing),
373 /// Some("Kana_Voicing")
374 /// );
375 /// assert_eq!(
376 /// names.get(CanonicalCombiningClass::AboveLeft),
377 /// Some("Above_Left")
378 /// );
379 /// ```
380 pub struct PropertyNamesLong<T: NamedEnumeratedProperty> {
381 map: DataPayload<ErasedMarker<T::DataStructLong>>,
382 }
383
384 impl<T: NamedEnumeratedProperty> core::fmt::Debug for PropertyNamesLong<T> {
385 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
386 f.debug_struct("PropertyNamesLong")
387 // .field("map", &self.map)
388 .finish()
389 }
390 }
391
392 /// A borrowed wrapper around property value name-to-enum data, returned by
393 /// [`PropertyNamesLong::as_borrowed()`]. More efficient to query.
394 #[derive(Debug)]
395 pub struct PropertyNamesLongBorrowed<'a, T: NamedEnumeratedProperty> {
396 map: &'a T::DataStructLongBorrowed<'a>,
397 }
398
399 impl<T: NamedEnumeratedProperty> Clone for PropertyNamesLongBorrowed<'_, T> {
400 fn clone(&self) -> Self {
401 *self
402 }
403 }
404 impl<T: NamedEnumeratedProperty> Copy for PropertyNamesLongBorrowed<'_, T> {}
405
406 impl<T: NamedEnumeratedProperty> PropertyNamesLong<T> {
407 /// Creates a new instance of `PropertyNamesLongBorrowed<T>`.
408 ///
409 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
410 ///
411 /// [📚 Help choosing a constructor](icu_provider::constructors)
412 #[cfg(feature = "compiled_data")]
413 #[expect(clippy::new_ret_no_self)]
414 pub const fn new() -> PropertyNamesLongBorrowed<'static, T> {
415 PropertyNamesLongBorrowed::new()
416 }
417
418 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new)]
419 pub fn try_new_unstable(
420 provider: &(impl DataProvider<T::DataMarkerLong> + ?Sized),
421 ) -> Result<Self, DataError> {
422 Ok(Self {
423 map: provider.load(Default::default())?.payload.cast(),
424 })
425 }
426
427 /// Construct a borrowed version of this type that can be queried.
428 ///
429 /// This avoids a potential small underlying cost per API call (like `get_static()`) by consolidating it
430 /// up front.
431 #[inline]
432 pub fn as_borrowed(&self) -> PropertyNamesLongBorrowed<'_, T> {
433 PropertyNamesLongBorrowed {
434 map: T::nep_long_identity(self.map.get()),
435 }
436 }
437 }
438
439 impl<'a, T: NamedEnumeratedProperty> PropertyNamesLongBorrowed<'a, T> {
440 /// Get the property name given a value
441 ///
442 /// # Example
443 ///
444 /// ```rust
445 /// use icu::properties::PropertyNamesLong;
446 /// use icu::properties::props::CanonicalCombiningClass;
447 ///
448 /// let lookup = PropertyNamesLong::<CanonicalCombiningClass>::new();
449 /// assert_eq!(
450 /// lookup.get(CanonicalCombiningClass::KanaVoicing),
451 /// Some("Kana_Voicing")
452 /// );
453 /// assert_eq!(
454 /// lookup.get(CanonicalCombiningClass::AboveLeft),
455 /// Some("Above_Left")
456 /// );
457 /// ```
458 #[inline]
459 pub fn get(self, property: T) -> Option<&'a str> {
460 self.map.get(property.to_u32())
461 }
462 }
463
464 #[cfg(feature = "compiled_data")]
465 impl<T: NamedEnumeratedProperty> Default for PropertyNamesLongBorrowed<'static, T> {
466 fn default() -> Self {
467 Self::new()
468 }
469 }
470
471 impl<T: NamedEnumeratedProperty> PropertyNamesLongBorrowed<'static, T> {
472 /// Creates a new instance of `PropertyNamesLongBorrowed<T>`.
473 ///
474 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
475 ///
476 /// [📚 Help choosing a constructor](icu_provider::constructors)
477 #[cfg(feature = "compiled_data")]
478 pub const fn new() -> Self {
479 Self {
480 map: T::SINGLETON_LONG,
481 }
482 }
483
484 /// Cheaply converts a [`PropertyNamesLongBorrowed<'static>`] into a [`PropertyNamesLong`].
485 ///
486 /// Note: Due to branching and indirection, using [`PropertyNamesLong`] might inhibit some
487 /// compile-time optimizations that are possible with [`PropertyNamesLongBorrowed`].
488 ///
489 /// This is currently not `const` unlike other `static_to_owned()` functions since it needs
490 /// const traits to do that safely
491 pub fn static_to_owned(self) -> PropertyNamesLong<T> {
492 PropertyNamesLong {
493 map: DataPayload::from_static_ref(T::nep_long_identity_static(self.map)),
494 }
495 }
496 }
497
498 /// A struct capable of looking up a property name from a value
499 /// Access its data by calling [`Self::as_borrowed()`] and using the methods on
500 /// [`PropertyNamesShortBorrowed`].
501 ///
502 /// # Example
503 ///
504 /// ```
505 /// use icu::properties::PropertyNamesShort;
506 /// use icu::properties::props::CanonicalCombiningClass;
507 ///
508 /// let names = PropertyNamesShort::<CanonicalCombiningClass>::new();
509 /// assert_eq!(names.get(CanonicalCombiningClass::KanaVoicing), Some("KV"));
510 /// assert_eq!(names.get(CanonicalCombiningClass::AboveLeft), Some("AL"));
511 /// ```
512 pub struct PropertyNamesShort<T: NamedEnumeratedProperty> {
513 map: DataPayload<ErasedMarker<T::DataStructShort>>,
514 }
515
516 impl<T: NamedEnumeratedProperty> core::fmt::Debug for PropertyNamesShort<T> {
517 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
518 f.debug_struct("PropertyNamesShort")
519 // .field("map", &self.map)
520 .finish()
521 }
522 }
523
524 /// A borrowed wrapper around property value name-to-enum data, returned by
525 /// [`PropertyNamesShort::as_borrowed()`]. More efficient to query.
526 #[derive(Debug)]
527 pub struct PropertyNamesShortBorrowed<'a, T: NamedEnumeratedProperty> {
528 map: &'a T::DataStructShortBorrowed<'a>,
529 }
530
531 impl<T: NamedEnumeratedProperty> Clone for PropertyNamesShortBorrowed<'_, T> {
532 fn clone(&self) -> Self {
533 *self
534 }
535 }
536
537 impl<T: NamedEnumeratedProperty> Copy for PropertyNamesShortBorrowed<'_, T> {}
538
539 impl<T: NamedEnumeratedProperty> PropertyNamesShort<T> {
540 /// Creates a new instance of `PropertyNamesShortBorrowed<T>`.
541 ///
542 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
543 ///
544 /// [📚 Help choosing a constructor](icu_provider::constructors)
545 #[cfg(feature = "compiled_data")]
546 #[expect(clippy::new_ret_no_self)]
547 pub const fn new() -> PropertyNamesShortBorrowed<'static, T> {
548 PropertyNamesShortBorrowed::new()
549 }
550
551 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::new)]
552 pub fn try_new_unstable(
553 provider: &(impl DataProvider<T::DataMarkerShort> + ?Sized),
554 ) -> Result<Self, DataError> {
555 Ok(Self {
556 map: provider.load(Default::default())?.payload.cast(),
557 })
558 }
559
560 /// Construct a borrowed version of this type that can be queried.
561 ///
562 /// This avoids a potential small underlying cost per API call (like `get_static()`) by consolidating it
563 /// up front.
564 #[inline]
565 pub fn as_borrowed(&self) -> PropertyNamesShortBorrowed<'_, T> {
566 PropertyNamesShortBorrowed {
567 map: T::nep_short_identity(self.map.get()),
568 }
569 }
570 }
571
572 impl<'a, T: NamedEnumeratedProperty> PropertyNamesShortBorrowed<'a, T> {
573 /// Get the property name given a value
574 ///
575 /// # Example
576 ///
577 /// ```rust
578 /// use icu::properties::PropertyNamesShort;
579 /// use icu::properties::props::CanonicalCombiningClass;
580 ///
581 /// let lookup = PropertyNamesShort::<CanonicalCombiningClass>::new();
582 /// assert_eq!(lookup.get(CanonicalCombiningClass::KanaVoicing), Some("KV"));
583 /// assert_eq!(lookup.get(CanonicalCombiningClass::AboveLeft), Some("AL"));
584 /// ```
585 #[inline]
586 pub fn get(self, property: T) -> Option<&'a str> {
587 self.map.get(property.to_u32())
588 }
589 }
590
591 impl PropertyNamesShortBorrowed<'_, Script> {
592 /// Gets the "name" of a script property as a `icu::locale::subtags::Script`.
593 ///
594 /// This method is available only on `PropertyNamesShortBorrowed<Script>`.
595 ///
596 /// # Example
597 ///
598 /// ```rust
599 /// use icu::locale::subtags::script;
600 /// use icu::properties::PropertyNamesShort;
601 /// use icu::properties::props::Script;
602 ///
603 /// let lookup = PropertyNamesShort::<Script>::new();
604 /// assert_eq!(
605 /// lookup.get_locale_script(Script::Brahmi),
606 /// Some(script!("Brah"))
607 /// );
608 /// assert_eq!(
609 /// lookup.get_locale_script(Script::Hangul),
610 /// Some(script!("Hang"))
611 /// );
612 /// ```
613 ///
614 /// For the reverse direction, use property parsing as normal:
615 /// ```
616 /// use icu::locale::subtags::script;
617 /// use icu::properties::PropertyParser;
618 /// use icu::properties::props::Script;
619 ///
620 /// let parser = PropertyParser::<Script>::new();
621 /// assert_eq!(
622 /// parser.get_strict(script!("Brah").as_str()),
623 /// Some(Script::Brahmi)
624 /// );
625 /// assert_eq!(
626 /// parser.get_strict(script!("Hang").as_str()),
627 /// Some(Script::Hangul)
628 /// );
629 /// ```
630 #[inline]
631 pub fn get_locale_script(self, property: Script) -> Option<icu_locale_core::subtags::Script> {
632 let prop = usize::try_from(property.to_u32()).ok()?;
633 self.map.map.get(prop).and_then(|o| o.0)
634 }
635 }
636
637 #[cfg(feature = "compiled_data")]
638 impl<T: NamedEnumeratedProperty> Default for PropertyNamesShortBorrowed<'static, T> {
639 fn default() -> Self {
640 Self::new()
641 }
642 }
643
644 impl<T: NamedEnumeratedProperty> PropertyNamesShortBorrowed<'static, T> {
645 /// Creates a new instance of `PropertyNamesShortBorrowed<T>`.
646 ///
647 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
648 ///
649 /// [📚 Help choosing a constructor](icu_provider::constructors)
650 #[cfg(feature = "compiled_data")]
651 pub const fn new() -> Self {
652 Self {
653 map: T::SINGLETON_SHORT,
654 }
655 }
656
657 /// Cheaply converts a [`PropertyNamesShortBorrowed<'static>`] into a [`PropertyNamesShort`].
658 ///
659 /// Note: Due to branching and indirection, using [`PropertyNamesShort`] might inhibit some
660 /// compile-time optimizations that are possible with [`PropertyNamesShortBorrowed`].
661 ///
662 /// This is currently not `const` unlike other `static_to_owned()` functions since it needs
663 /// const traits to do that safely
664 pub fn static_to_owned(self) -> PropertyNamesShort<T> {
665 PropertyNamesShort {
666 map: DataPayload::from_static_ref(T::nep_short_identity_static(self.map)),
667 }
668 }
669 }
670
671 /// A property whose value names can be parsed from strings.
672 pub trait ParseableEnumeratedProperty: crate::private::Sealed + TrieValue {
673 #[doc(hidden)]
674 type DataMarker: DataMarker<DataStruct = PropertyValueNameToEnumMap<'static>>;
675 #[doc(hidden)]
676 #[cfg(feature = "compiled_data")]
677 const SINGLETON: &'static PropertyValueNameToEnumMap<'static>;
678 }
679
680 // Abstract over Linear/Sparse/Script representation
681 // This trait is implicitly sealed by not being exported.
682 pub trait PropertyEnumToValueNameLookup {
683 fn get(&self, prop: u32) -> Option<&str>;
684 }
685
686 impl PropertyEnumToValueNameLookup for PropertyEnumToValueNameLinearMap<'_> {
687 fn get(&self, prop: u32) -> Option<&str> {
688 self.map.get(usize::try_from(prop).ok()?)
689 }
690 }
691
692 #[cfg(feature = "alloc")]
693 impl PropertyEnumToValueNameLookup for PropertyEnumToValueNameSparseMap<'_> {
694 fn get(&self, prop: u32) -> Option<&str> {
695 self.map.get(&u16::try_from(prop).ok()?)
696 }
697 }
698
699 impl PropertyEnumToValueNameLookup for PropertyScriptToIcuScriptMap<'_> {
700 fn get(&self, prop: u32) -> Option<&str> {
701 self.map
702 .get_ule_ref(usize::try_from(prop).ok()?)
703 .and_then(|no| no.as_ref())
704 .map(|s| s.as_str())
705 }
706 }
707
708 /// A property whose value names can be represented as strings.
709 pub trait NamedEnumeratedProperty: ParseableEnumeratedProperty {
710 #[doc(hidden)]
711 type DataStructLong: 'static
712 + for<'a> Yokeable<'a, Output = Self::DataStructLongBorrowed<'a>>
713 + PropertyEnumToValueNameLookup;
714 #[doc(hidden)]
715 type DataStructShort: 'static
716 + for<'a> Yokeable<'a, Output = Self::DataStructShortBorrowed<'a>>
717 + PropertyEnumToValueNameLookup;
718 #[doc(hidden)]
719 type DataStructLongBorrowed<'a>: PropertyEnumToValueNameLookup;
720 #[doc(hidden)]
721 type DataStructShortBorrowed<'a>: PropertyEnumToValueNameLookup;
722 #[doc(hidden)]
723 type DataMarkerLong: DataMarker<DataStruct = Self::DataStructLong>;
724 #[doc(hidden)]
725 type DataMarkerShort: DataMarker<DataStruct = Self::DataStructShort>;
726 #[doc(hidden)]
727 #[cfg(feature = "compiled_data")]
728 const SINGLETON_LONG: &'static Self::DataStructLongBorrowed<'static>;
729 #[doc(hidden)]
730 #[cfg(feature = "compiled_data")]
731 const SINGLETON_SHORT: &'static Self::DataStructShortBorrowed<'static>;
732
733 // These wouldn't be necessary if Yoke used GATs (#6057)
734 #[doc(hidden)]
735 fn nep_long_identity<'a>(
736 stat: &'a <Self::DataStructLong as Yokeable<'a>>::Output,
737 ) -> &'a Self::DataStructLongBorrowed<'a>;
738 #[doc(hidden)]
739 fn nep_long_identity_static(
740 stat: &'static Self::DataStructLongBorrowed<'static>,
741 ) -> &'static Self::DataStructLong;
742
743 #[doc(hidden)]
744 fn nep_short_identity<'a>(
745 stat: &'a <Self::DataStructShort as Yokeable<'a>>::Output,
746 ) -> &'a Self::DataStructShortBorrowed<'a>;
747 #[doc(hidden)]
748 fn nep_short_identity_static(
749 stat: &'static Self::DataStructShortBorrowed<'static>,
750 ) -> &'static Self::DataStructShort;
751
752 /// Convenience method for `PropertyParser::new().get_loose(s)`
753 ///
754 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
755 #[cfg(feature = "compiled_data")]
756 fn try_from_str(s: &str) -> Option<Self> {
757 Self::try_from_utf8(s.as_bytes())
758 }
759 #[cfg(feature = "compiled_data")]
760 #[doc(hidden)]
761 fn try_from_utf8(s: &[u8]) -> Option<Self> {
762 PropertyParser::new().get_loose_utf8(s)
763 }
764 /// Convenience method for `PropertyNamesLong::new().get(*self).unwrap()`
765 ///
766 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
767 #[cfg(feature = "compiled_data")]
768 fn long_name(&self) -> &'static str {
769 PropertyNamesLong::new().get(*self).unwrap_or("unreachable")
770 }
771 /// Convenience method for `PropertyNamesShort::new().get(*self).unwrap()`
772 ///
773 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
774 #[cfg(feature = "compiled_data")]
775 fn short_name(&self) -> &'static str {
776 PropertyNamesShort::new()
777 .get(*self)
778 .unwrap_or("unreachable")
779 }
780 }
781
782 macro_rules! impl_value_getter {
783 (
784 impl $ty:ident {
785 $marker_n2e:ident / $singleton_n2e:ident;
786 $(
787 $(#[$meta:meta])*
788 $data_struct_s:ident / $marker_e2sn:ident / $singleton_e2sn:ident;
789 $data_struct_l:ident / $marker_e2ln:ident / $singleton_e2ln:ident;
790 )?
791 }
792 ) => {
793 impl ParseableEnumeratedProperty for $ty {
794 type DataMarker = $marker_n2e;
795 #[cfg(feature = "compiled_data")]
796 const SINGLETON: &'static PropertyValueNameToEnumMap<'static> = crate::provider::Baked::$singleton_n2e;
797 }
798
799 $(
800 $(#[$meta])*
801 impl NamedEnumeratedProperty for $ty {
802 type DataStructLong = $data_struct_l<'static>;
803 type DataStructShort = $data_struct_s<'static>;
804 type DataStructLongBorrowed<'a> = $data_struct_l<'a>;
805 type DataStructShortBorrowed<'a> = $data_struct_s<'a>;
806 type DataMarkerLong = crate::provider::$marker_e2ln;
807 type DataMarkerShort = crate::provider::$marker_e2sn;
808 #[cfg(feature = "compiled_data")]
809 const SINGLETON_LONG: &'static Self::DataStructLong = crate::provider::Baked::$singleton_e2ln;
810 #[cfg(feature = "compiled_data")]
811 const SINGLETON_SHORT: &'static Self::DataStructShort = crate::provider::Baked::$singleton_e2sn;
812 fn nep_long_identity<'a>(yoked: &'a $data_struct_l<'a>) -> &'a Self::DataStructLongBorrowed<'a> {
813 yoked
814 }
815
816 fn nep_long_identity_static(stat: &'static $data_struct_l<'static>) -> &'static $data_struct_l<'static> {
817 stat
818 }
819
820
821 fn nep_short_identity<'a>(yoked: &'a $data_struct_s<'a>) -> &'a Self::DataStructShortBorrowed<'a> {
822 yoked
823 }
824 fn nep_short_identity_static(stat: &'static $data_struct_s<'static>) -> &'static $data_struct_s<'static> {
825 stat
826 }
827
828 }
829
830
831 )?
832 };
833 }
834
835 impl_value_getter! {
836 impl BidiClass {
837 PropertyNameParseBidiClassV1 / SINGLETON_PROPERTY_NAME_PARSE_BIDI_CLASS_V1;
838 PropertyEnumToValueNameLinearMap / PropertyNameShortBidiClassV1 / SINGLETON_PROPERTY_NAME_SHORT_BIDI_CLASS_V1;
839 PropertyEnumToValueNameLinearMap / PropertyNameLongBidiClassV1 / SINGLETON_PROPERTY_NAME_LONG_BIDI_CLASS_V1;
840 }
841 }
842
843 impl_value_getter! {
844 impl NumericType {
845 PropertyNameParseNumericTypeV1 / SINGLETON_PROPERTY_NAME_PARSE_NUMERIC_TYPE_V1;
846 PropertyEnumToValueNameLinearMap / PropertyNameShortNumericTypeV1 / SINGLETON_PROPERTY_NAME_SHORT_NUMERIC_TYPE_V1;
847 PropertyEnumToValueNameLinearMap / PropertyNameLongNumericTypeV1 / SINGLETON_PROPERTY_NAME_LONG_NUMERIC_TYPE_V1;
848 }
849 }
850
851 impl_value_getter! {
852 impl GeneralCategory {
853 PropertyNameParseGeneralCategoryV1 / SINGLETON_PROPERTY_NAME_PARSE_GENERAL_CATEGORY_V1;
854 PropertyEnumToValueNameLinearMap / PropertyNameShortGeneralCategoryV1 / SINGLETON_PROPERTY_NAME_SHORT_GENERAL_CATEGORY_V1;
855 PropertyEnumToValueNameLinearMap / PropertyNameLongGeneralCategoryV1 / SINGLETON_PROPERTY_NAME_LONG_GENERAL_CATEGORY_V1;
856 }
857 }
858
859 impl_value_getter! {
860 impl GeneralCategoryGroup {
861 PropertyNameParseGeneralCategoryMaskV1 / SINGLETON_PROPERTY_NAME_PARSE_GENERAL_CATEGORY_MASK_V1;
862 }
863 }
864
865 impl_value_getter! {
866 impl Script {
867 PropertyNameParseScriptV1 / SINGLETON_PROPERTY_NAME_PARSE_SCRIPT_V1;
868 PropertyScriptToIcuScriptMap / PropertyNameShortScriptV1 / SINGLETON_PROPERTY_NAME_SHORT_SCRIPT_V1;
869 PropertyEnumToValueNameLinearMap / PropertyNameLongScriptV1 / SINGLETON_PROPERTY_NAME_LONG_SCRIPT_V1;
870 }
871 }
872
873 impl_value_getter! {
874 impl HangulSyllableType {
875 PropertyNameParseHangulSyllableTypeV1 / SINGLETON_PROPERTY_NAME_PARSE_HANGUL_SYLLABLE_TYPE_V1;
876 PropertyEnumToValueNameLinearMap / PropertyNameShortHangulSyllableTypeV1 / SINGLETON_PROPERTY_NAME_SHORT_HANGUL_SYLLABLE_TYPE_V1;
877 PropertyEnumToValueNameLinearMap / PropertyNameLongHangulSyllableTypeV1 / SINGLETON_PROPERTY_NAME_LONG_HANGUL_SYLLABLE_TYPE_V1;
878 }
879 }
880
881 impl_value_getter! {
882 impl EastAsianWidth {
883 PropertyNameParseEastAsianWidthV1 / SINGLETON_PROPERTY_NAME_PARSE_EAST_ASIAN_WIDTH_V1;
884 PropertyEnumToValueNameLinearMap / PropertyNameShortEastAsianWidthV1 / SINGLETON_PROPERTY_NAME_SHORT_EAST_ASIAN_WIDTH_V1;
885 PropertyEnumToValueNameLinearMap / PropertyNameLongEastAsianWidthV1 / SINGLETON_PROPERTY_NAME_LONG_EAST_ASIAN_WIDTH_V1;
886 }
887 }
888
889 impl_value_getter! {
890 impl LineBreak {
891 PropertyNameParseLineBreakV1 / SINGLETON_PROPERTY_NAME_PARSE_LINE_BREAK_V1;
892 PropertyEnumToValueNameLinearMap / PropertyNameShortLineBreakV1 / SINGLETON_PROPERTY_NAME_SHORT_LINE_BREAK_V1;
893 PropertyEnumToValueNameLinearMap / PropertyNameLongLineBreakV1 / SINGLETON_PROPERTY_NAME_LONG_LINE_BREAK_V1;
894 }
895 }
896
897 impl_value_getter! {
898 impl GraphemeClusterBreak {
899 PropertyNameParseGraphemeClusterBreakV1 / SINGLETON_PROPERTY_NAME_PARSE_GRAPHEME_CLUSTER_BREAK_V1;
900 PropertyEnumToValueNameLinearMap / PropertyNameShortGraphemeClusterBreakV1 / SINGLETON_PROPERTY_NAME_SHORT_GRAPHEME_CLUSTER_BREAK_V1;
901 PropertyEnumToValueNameLinearMap / PropertyNameLongGraphemeClusterBreakV1 / SINGLETON_PROPERTY_NAME_LONG_GRAPHEME_CLUSTER_BREAK_V1;
902 }
903 }
904
905 impl_value_getter! {
906 impl WordBreak {
907 PropertyNameParseWordBreakV1 / SINGLETON_PROPERTY_NAME_PARSE_WORD_BREAK_V1;
908 PropertyEnumToValueNameLinearMap / PropertyNameShortWordBreakV1 / SINGLETON_PROPERTY_NAME_SHORT_WORD_BREAK_V1;
909 PropertyEnumToValueNameLinearMap / PropertyNameLongWordBreakV1 / SINGLETON_PROPERTY_NAME_LONG_WORD_BREAK_V1;
910 }
911 }
912
913 impl_value_getter! {
914 impl SentenceBreak {
915 PropertyNameParseSentenceBreakV1 / SINGLETON_PROPERTY_NAME_PARSE_SENTENCE_BREAK_V1;
916 PropertyEnumToValueNameLinearMap / PropertyNameShortSentenceBreakV1 / SINGLETON_PROPERTY_NAME_SHORT_SENTENCE_BREAK_V1;
917 PropertyEnumToValueNameLinearMap / PropertyNameLongSentenceBreakV1 / SINGLETON_PROPERTY_NAME_LONG_SENTENCE_BREAK_V1;
918 }
919 }
920
921 impl_value_getter! {
922 impl CanonicalCombiningClass {
923 PropertyNameParseCanonicalCombiningClassV1 / SINGLETON_PROPERTY_NAME_PARSE_CANONICAL_COMBINING_CLASS_V1;
924 #[cfg(feature = "alloc")]
925 /// ✨ *Enabled with the `alloc` Cargo feature.*
926 PropertyEnumToValueNameSparseMap / PropertyNameShortCanonicalCombiningClassV1 / SINGLETON_PROPERTY_NAME_SHORT_CANONICAL_COMBINING_CLASS_V1;
927 PropertyEnumToValueNameSparseMap / PropertyNameLongCanonicalCombiningClassV1 / SINGLETON_PROPERTY_NAME_LONG_CANONICAL_COMBINING_CLASS_V1;
928 }
929 }
930
931 impl_value_getter! {
932 impl IndicSyllabicCategory {
933 PropertyNameParseIndicSyllabicCategoryV1 / SINGLETON_PROPERTY_NAME_PARSE_INDIC_SYLLABIC_CATEGORY_V1;
934 PropertyEnumToValueNameLinearMap / PropertyNameShortIndicSyllabicCategoryV1 / SINGLETON_PROPERTY_NAME_SHORT_INDIC_SYLLABIC_CATEGORY_V1;
935 PropertyEnumToValueNameLinearMap / PropertyNameLongIndicSyllabicCategoryV1 / SINGLETON_PROPERTY_NAME_LONG_INDIC_SYLLABIC_CATEGORY_V1;
936 }
937 }
938
939 impl_value_getter! {
940 impl IndicConjunctBreak {
941 PropertyNameParseIndicConjunctBreakV1 / SINGLETON_PROPERTY_NAME_PARSE_INDIC_CONJUNCT_BREAK_V1;
942 PropertyEnumToValueNameLinearMap / PropertyNameShortIndicConjunctBreakV1 / SINGLETON_PROPERTY_NAME_SHORT_INDIC_CONJUNCT_BREAK_V1;
943 PropertyEnumToValueNameLinearMap / PropertyNameLongIndicConjunctBreakV1 / SINGLETON_PROPERTY_NAME_LONG_INDIC_CONJUNCT_BREAK_V1;
944 }
945 }
946
947 impl_value_getter! {
948 impl JoiningGroup {
949 PropertyNameParseJoiningGroupV1 / SINGLETON_PROPERTY_NAME_PARSE_JOINING_GROUP_V1;
950 PropertyEnumToValueNameLinearMap / PropertyNameShortJoiningGroupV1 / SINGLETON_PROPERTY_NAME_SHORT_JOINING_GROUP_V1;
951 PropertyEnumToValueNameLinearMap / PropertyNameLongJoiningGroupV1 / SINGLETON_PROPERTY_NAME_LONG_JOINING_GROUP_V1;
952 }
953 }
954
955 impl_value_getter! {
956 impl JoiningType {
957 PropertyNameParseJoiningTypeV1 / SINGLETON_PROPERTY_NAME_PARSE_JOINING_TYPE_V1;
958 PropertyEnumToValueNameLinearMap / PropertyNameShortJoiningTypeV1 / SINGLETON_PROPERTY_NAME_SHORT_JOINING_TYPE_V1;
959 PropertyEnumToValueNameLinearMap / PropertyNameLongJoiningTypeV1 / SINGLETON_PROPERTY_NAME_LONG_JOINING_TYPE_V1;
960 }
961 }
962
963 impl_value_getter! {
964 impl VerticalOrientation {
965 PropertyNameParseVerticalOrientationV1 / SINGLETON_PROPERTY_NAME_PARSE_VERTICAL_ORIENTATION_V1;
966 PropertyEnumToValueNameLinearMap / PropertyNameShortVerticalOrientationV1 / SINGLETON_PROPERTY_NAME_SHORT_VERTICAL_ORIENTATION_V1;
967 PropertyEnumToValueNameLinearMap / PropertyNameLongVerticalOrientationV1 / SINGLETON_PROPERTY_NAME_LONG_VERTICAL_ORIENTATION_V1;
968 }
969 }