Debian Codegraph @

debian/rust-vendor/icu_datetime/src/provider/skeleton/reference.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 //! Reference `Skeleton` implementation for parsing.
6
7 use super::error::SkeletonError;
8 use crate::provider::fields::{self, Field, FieldLength, FieldSymbol};
9 use crate::provider::pattern::reference::Pattern;
10 use alloc::vec::Vec;
11 use core::convert::TryFrom;
12 use smallvec::SmallVec;
13
14 /// A [`Skeleton`] is used to represent what types of `Field`s are present in a [`Pattern`]. The
15 /// ordering of the [`Skeleton`]'s `Field`s have no bearing on the ordering of the `Field`s and
16 /// `Literal`s in the [`Pattern`].
17 ///
18 /// A [`Skeleton`] is a [`Vec`]`<Field>`, but with the invariant that it is sorted according to the canonical
19 /// sort order. This order is sorted according to the most significant `Field` to the least significant.
20 /// For example, a field with a `Minute` symbol would precede a field with a `Second` symbol.
21 /// This order is documented as the order of fields as presented in the
22 /// [UTS 35 Date Field Symbol Table](https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table)
23 ///
24 /// The `Field`s are only sorted in the [`Skeleton`] in order to provide a deterministic
25 /// serialization strategy, and to provide a faster [`Skeleton`] matching operation.
26 ///
27 /// <div class="stab unstable">
28 /// 🚧 This code is considered unstable; it may change at any time, in breaking or non-breaking ways,
29 /// including in SemVer minor releases. While the serde representation of data structs is guaranteed
30 /// to be stable, their Rust representation might not be. Use with caution.
31 /// </div>
32 #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd)]
33 // TODO(#876): Use ZeroVec instead of SmallVec
34 pub struct Skeleton(pub(crate) SmallVec<[Field; 5]>);
35
36 impl Skeleton {
37 pub(crate) fn fields_iter(&self) -> impl Iterator<Item = &Field> {
38 self.0.iter()
39 }
40
41 pub(crate) fn fields_len(&self) -> usize {
42 self.0.len()
43 }
44
45 /// Return the underlying fields as a slice.
46 pub fn as_slice(&self) -> &[Field] {
47 self.0.as_slice()
48 }
49 }
50
51 impl From<SmallVec<[Field; 5]>> for Skeleton {
52 fn from(fields: SmallVec<[Field; 5]>) -> Self {
53 Self(fields)
54 }
55 }
56
57 impl From<Vec<Field>> for Skeleton {
58 fn from(fields: Vec<Field>) -> Self {
59 Self(fields.into())
60 }
61 }
62
63 impl From<&[Field]> for Skeleton {
64 fn from(fields: &[Field]) -> Self {
65 Self(fields.into())
66 }
67 }
68
69 /// Convert a Pattern into a Skeleton. This will remove all of the string literals, and sort
70 /// the fields into the canonical sort order. Not all fields are supported by Skeletons, so map
71 /// fields into skeleton-appropriate ones. For instance, in the "ja" locale the pattern "aK:mm"
72 /// gets transformed into the skeleton "hmm".
73 ///
74 /// At the time of this writing, it's being used for applying hour cycle preferences and should not
75 /// be exposed as a public API for end users.
76 impl From<&Pattern> for Skeleton {
77 fn from(pattern: &Pattern) -> Self {
78 let mut fields: SmallVec<[Field; 5]> = SmallVec::new();
79 for item in pattern.items() {
80 if let crate::provider::pattern::PatternItem::Field(field) = item {
81 let mut field = *field;
82
83 // Skeletons only have a subset of available fields, these are then mapped to more
84 // specific fields for the patterns they expand to.
85 field.symbol = match field.symbol {
86 // Only the format varieties are used in the skeletons, the matched patterns
87 // will be more specific.
88 FieldSymbol::Month(_) => FieldSymbol::Month(fields::Month::Format),
89 FieldSymbol::Weekday(_) => FieldSymbol::Weekday(fields::Weekday::Format),
90
91 // Only flexible day periods are used in skeletons, ignore all others.
92 FieldSymbol::DayPeriod(fields::DayPeriod::AmPm)
93 | FieldSymbol::DayPeriod(fields::DayPeriod::NoonMidnight) => continue,
94 FieldSymbol::DayPeriod(fields::DayPeriod::Flexible) => {
95 FieldSymbol::DayPeriod(fields::DayPeriod::Flexible)
96 }
97
98 // Only the H12 and H23 symbols are used in skeletons, while the patterns may
99 // contain H11 or H23 depending on the localization.
100 FieldSymbol::Hour(fields::Hour::H11) | FieldSymbol::Hour(fields::Hour::H12) => {
101 FieldSymbol::Hour(fields::Hour::H12)
102 }
103 FieldSymbol::Hour(fields::Hour::H23) => FieldSymbol::Hour(fields::Hour::H23),
104
105 // Pass through all of the following preferences unchanged.
106 FieldSymbol::Minute
107 | FieldSymbol::Second(_)
108 | FieldSymbol::TimeZone(_)
109 | FieldSymbol::DecimalSecond(_)
110 | FieldSymbol::Era
111 | FieldSymbol::Year(_)
112 | FieldSymbol::Week(_)
113 | FieldSymbol::Day(_) => field.symbol,
114 };
115
116 // Only insert if it's a unique field.
117 if let Err(pos) = fields.binary_search(&field) {
118 fields.insert(pos, field)
119 }
120 }
121 }
122 Self(fields)
123 }
124 }
125
126 /// Parse a string into a list of fields. This trait implementation validates the input string to
127 /// verify that fields are correct. If the fields are out of order, this returns an error that
128 /// contains the fields, which gives the callee a chance to sort the fields with the
129 /// `From<SmallVec<[Field; 5]>> for Skeleton` trait.
130 impl TryFrom<&str> for Skeleton {
131 type Error = SkeletonError;
132 fn try_from(skeleton_string: &str) -> Result<Self, Self::Error> {
133 let mut fields: SmallVec<[Field; 5]> = SmallVec::new();
134
135 let mut iter = skeleton_string.chars().peekable();
136 while let Some(ch) = iter.next() {
137 // Go through the chars to count how often it's repeated.
138 let mut field_length: u8 = 1;
139 while let Some(next_ch) = iter.peek() {
140 if *next_ch != ch {
141 break;
142 }
143 field_length += 1;
144 iter.next();
145 }
146
147 // Convert the byte to a valid field symbol.
148 let field_symbol = if ch == 'Z' {
149 match field_length {
150 1..=3 => {
151 field_length = 4;
152 FieldSymbol::try_from('x')?
153 }
154 4 => FieldSymbol::try_from('O')?,
155 5 => {
156 field_length = 4;
157 FieldSymbol::try_from('X')?
158 }
159 _ => FieldSymbol::try_from(ch)?,
160 }
161 } else {
162 FieldSymbol::try_from(ch)?
163 };
164 let mut field = Field::from((field_symbol, FieldLength::from_idx(field_length)?));
165
166 // CLDR skeletons in 48.2 use 'c' instead of 'E' (e.g. in Finnish).
167 // We treat them as equivalent for matching purposes by normalizing 'c' to 'E' here.
168 // This avoids missing matches when we request 'E' via synthesis in datagen.
169 //
170 // This will be obsoleted by future CLDR releases
171 // <https://github.com/unicode-org/cldr/pull/5524>
172 if let FieldSymbol::Weekday(fields::Weekday::StandAlone) = field.symbol {
173 field.symbol = FieldSymbol::Weekday(fields::Weekday::Format);
174 }
175
176 match fields.binary_search(&field) {
177 Ok(_) => return Err(SkeletonError::DuplicateField),
178 Err(pos) => fields.insert(pos, field),
179 }
180 }
181
182 Ok(Self::from(fields))
183 }
184 }
185
186 impl core::fmt::Display for Skeleton {
187 fn fmt(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result {
188 use core::fmt::Write;
189 for field in self.fields_iter() {
190 let ch: char = field.symbol.into();
191 for _ in 0..field.length.to_len() {
192 formatter.write_char(ch)?;
193 }
194 }
195 Ok(())
196 }
197 }