Debian Codegraph @

debian/rust-vendor/icu_datetime/src/provider/fields/mod.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 //! Enums representing the fields in a date pattern, including the field's type, length and symbol.
6
7 #![allow(clippy::exhaustive_structs)] // Field and FieldULE part of data struct
8
9 mod length;
10 pub(crate) mod symbols;
11
12 use displaydoc::Display;
13 pub use length::{FieldLength, FieldNumericOverrides, LengthError};
14 pub use symbols::*;
15 use writeable::Writeable;
16
17 #[cfg(any(feature = "unstable", feature = "datagen"))]
18 pub mod components;
19
20 use core::{
21 cmp::{Ord, PartialOrd},
22 convert::TryFrom,
23 };
24
25 use crate::error::ErrorField;
26
27 /// An error relating to the field for a date pattern field as a whole.
28 ///
29 /// Separate error types exist for parts of a field, like the
30 /// [`LengthError`](error for the field length) and the
31 /// [`SymbolError`](error for the field symbol).
32 #[derive(Display, Debug, Copy, Clone, PartialEq)]
33 #[non_exhaustive]
34 pub enum Error {
35 /// An error originating inside of the [data provider](icu_provider).
36 #[displaydoc("Field {0:?} is not a valid length")]
37 InvalidLength(FieldSymbol),
38 }
39
40 impl core::error::Error for Error {}
41
42 /// A field within a date pattern string, also referred to as a date field.
43 ///
44 /// A date field is the
45 /// repetition of a specific pattern character one or more times within the pattern string.
46 /// The pattern character is known as the field symbol, which indicates the particular meaning for the field.
47 #[derive(Debug, Eq, PartialEq, Clone, Copy, Ord, PartialOrd)]
48 #[cfg_attr(feature = "datagen", derive(serde::Serialize, databake::Bake))]
49 #[cfg_attr(feature = "datagen", databake(path = icu_datetime::fields))]
50 #[cfg_attr(feature = "serde", derive(serde::Deserialize))]
51 #[zerovec::make_ule(FieldULE)]
52 pub struct Field {
53 /// The field symbol for the `Field`, which corresponds to the field's meaning with the
54 /// date pattern.
55 pub symbol: FieldSymbol,
56 /// The length of the `Field`, which in conjunction with the `FieldSymbol` informs the width or
57 /// style of the formatting output corresponding to this field.
58 pub length: FieldLength,
59 }
60
61 impl Field {
62 /// Returns whether the field length represents text or numeric.
63 #[cfg(feature = "datagen")]
64 pub fn get_length_type(self) -> TextOrNumeric {
65 match self.symbol {
66 FieldSymbol::Era => TextOrNumeric::Text,
67 FieldSymbol::Year(year) => year.get_length_type(self.length),
68 FieldSymbol::Month(month) => month.get_length_type(self.length),
69 FieldSymbol::Week(week) => week.get_length_type(self.length),
70 FieldSymbol::Day(day) => day.get_length_type(self.length),
71 FieldSymbol::Weekday(weekday) => weekday.get_length_type(self.length),
72 FieldSymbol::DayPeriod(day_period) => day_period.get_length_type(self.length),
73 FieldSymbol::Hour(hour) => hour.get_length_type(self.length),
74 FieldSymbol::Minute => TextOrNumeric::Numeric,
75 FieldSymbol::Second(second) => second.get_length_type(self.length),
76 FieldSymbol::TimeZone(zone) => zone.get_length_type(self.length),
77 FieldSymbol::DecimalSecond(_) => TextOrNumeric::Numeric,
78 }
79 }
80 }
81
82 impl Writeable for Field {
83 fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
84 let ch: char = self.symbol.into();
85 for _ in 0..self.length.to_len() {
86 sink.write_char(ch)?;
87 }
88 Ok(())
89 }
90 fn writeable_length_hint(&self) -> writeable::LengthHint {
91 writeable::LengthHint::exact(self.length.to_len())
92 }
93 }
94
95 writeable::impl_display_with_writeable!(Field);
96
97 impl FieldULE {
98 #[inline]
99 pub(crate) fn validate_byte_pair(bytes: (u8, u8)) -> Result<(), zerovec::ule::UleError> {
100 FieldSymbolULE::validate_byte(bytes.0)?;
101 length::FieldLengthULE::validate_byte(bytes.1)?;
102 Ok(())
103 }
104 }
105
106 impl From<(FieldSymbol, FieldLength)> for Field {
107 fn from(input: (FieldSymbol, FieldLength)) -> Self {
108 Self {
109 symbol: input.0,
110 length: input.1,
111 }
112 }
113 }
114
115 impl TryFrom<(FieldSymbol, usize)> for Field {
116 type Error = Error;
117 fn try_from(input: (FieldSymbol, usize)) -> Result<Self, Self::Error> {
118 let length = FieldLength::from_idx(input.1 as u8)
119 .map_err(|_| Self::Error::InvalidLength(input.0))?;
120 Ok(Self {
121 symbol: input.0,
122 length,
123 })
124 }
125 }
126
127 impl From<ErrorField> for Field {
128 /// Recover a [`Field`] (unstable) from an [`ErrorField`] (stable wrapper)
129 fn from(value: ErrorField) -> Self {
130 value.0
131 }
132 }
133
134 impl From<Field> for ErrorField {
135 /// Create an [`ErrorField`] (stable wrapper) from a [`Field`] (unstable)
136 fn from(value: Field) -> Self {
137 Self(value)
138 }
139 }
140
141 #[cfg(test)]
142 mod test {
143 use super::*;
144 use crate::provider::fields::{Field, FieldLength, FieldSymbol, Second, Year};
145 use zerovec::ule::{AsULE, ULE};
146
147 #[test]
148 fn test_field_as_ule() {
149 let samples = [
150 (
151 Field::from((FieldSymbol::Minute, FieldLength::Two)),
152 [FieldSymbol::Minute.idx(), FieldLength::Two.idx()],
153 ),
154 (
155 Field::from((FieldSymbol::Year(Year::Calendar), FieldLength::Four)),
156 [
157 FieldSymbol::Year(Year::Calendar).idx(),
158 FieldLength::Four.idx(),
159 ],
160 ),
161 (
162 Field::from((FieldSymbol::Year(Year::Cyclic), FieldLength::Four)),
163 [
164 FieldSymbol::Year(Year::Cyclic).idx(),
165 FieldLength::Four.idx(),
166 ],
167 ),
168 (
169 Field::from((FieldSymbol::Second(Second::MillisInDay), FieldLength::One)),
170 [
171 FieldSymbol::Second(Second::MillisInDay).idx(),
172 FieldLength::One.idx(),
173 ],
174 ),
175 ];
176
177 for (ref_field, ref_bytes) in samples {
178 let ule = ref_field.to_unaligned();
179 assert_eq!(ULE::slice_as_bytes(&[ule]), ref_bytes);
180 let field = Field::from_unaligned(ule);
181 assert_eq!(field, ref_field);
182 }
183 }
184
185 #[test]
186 fn test_field_ule() {
187 let samples = [(
188 [
189 Field::from((FieldSymbol::Year(Year::Calendar), FieldLength::Four)),
190 Field::from((FieldSymbol::Second(Second::MillisInDay), FieldLength::One)),
191 ],
192 [
193 [
194 FieldSymbol::Year(Year::Calendar).idx(),
195 FieldLength::Four.idx(),
196 ],
197 [
198 FieldSymbol::Second(Second::MillisInDay).idx(),
199 FieldLength::One.idx(),
200 ],
201 ],
202 )];
203
204 for (ref_field, ref_bytes) in samples {
205 let mut bytes: Vec<u8> = vec![];
206 for item in ref_field.iter() {
207 let ule = item.to_unaligned();
208 bytes.extend(ULE::slice_as_bytes(&[ule]));
209 }
210
211 let mut bytes2: Vec<u8> = vec![];
212 for seq in ref_bytes.iter() {
213 bytes2.extend_from_slice(seq);
214 }
215
216 assert!(FieldULE::validate_bytes(&bytes).is_ok());
217 assert_eq!(bytes, bytes2);
218 }
219 }
220 }