Debian Codegraph @

debian/rust-vendor/icu_datetime/src/dynamic.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 //! Enumerations over [field sets](crate::fieldsets).
6 //!
7 //! These enumerations can be used when the field set is not known at compile time. However,
8 //! using dynamic field sets in constructors will link data for all possible values
9 //! of the field set, which can significantly increase binary size. Prefer using
10 //! [`cast_into_fset`](crate::DateTimeFormatter::cast_into_fset) on formatters constructed
11 //! using static field sets instead.
12 //!
13 //! The most general type is [`CompositeFieldSet`], which supports all field
14 //! sets in a single enumeration. [`CompositeDateTimeFieldSet`] is a good
15 //! choice when you don't need to format time zones.
16 //!
17 //! The bigger the dynamic field set type, the bigger the required input type. For example,
18 //! `CompositeFieldSet` requires a `ZonedDateTime` input, since the dynamic field set could
19 //! include time zone fields.
20 //!
21 //! Summary of all the types:
22 //!
23 //! | Type | Supported Field Sets | Supported Input Types |
24 //! |---|---|---|
25 //! | [`DateFieldSet`] | Date | [`Date`], [`DateTime`], [`ZonedDateTime`] |
26 //! | [`CalendarPeriodFieldSet`] | Calendar Period | [`Date`], [`DateTime`], [`ZonedDateTime`] |
27 //! | [`TimeFieldSet`] | Time | [`Time`], [`DateTime`], [`ZonedTime`], [`ZonedDateTime`] |
28 //! | [`ZoneFieldSet`] | Zone | [`TimeZoneInfo`], [`ZonedTime`], [`ZonedDateTime`] |
29 //! | [`DateAndTimeFieldSet`] | Date + Time | [`DateTime`], [`ZonedDateTime`] |
30 //! | [`CompositeDateTimeFieldSet`] | Date, Calendar Period, Time, Date + Time | [`DateTime`], [`ZonedDateTime`] |
31 //! | [`CompositeFieldSet`] | All | [`ZonedDateTime`] |
32 //!
33 //! # Examples
34 //!
35 //! Format with the time display depending on a runtime boolean:
36 //!
37 //! ```
38 //! use icu::calendar::Date;
39 //! use icu::datetime::DateTimeFormatter;
40 //! use icu::datetime::fieldsets;
41 //! use icu::datetime::fieldsets::enums::CompositeDateTimeFieldSet;
42 //! use icu::datetime::input::{DateTime, Time};
43 //! use icu::locale::locale;
44 //! use writeable::Writeable;
45 //!
46 //! fn composite_field_set(
47 //! should_display_time: bool,
48 //! ) -> CompositeDateTimeFieldSet {
49 //! if should_display_time {
50 //! let field_set_with_options = fieldsets::MD::medium().with_time_hm();
51 //! CompositeDateTimeFieldSet::DateTime(
52 //! fieldsets::enums::DateAndTimeFieldSet::MDT(
53 //! field_set_with_options,
54 //! ),
55 //! )
56 //! } else {
57 //! let field_set_with_options = fieldsets::MD::medium();
58 //! CompositeDateTimeFieldSet::Date(fieldsets::enums::DateFieldSet::MD(
59 //! field_set_with_options,
60 //! ))
61 //! }
62 //! }
63 //!
64 //! let datetime = DateTime {
65 //! date: Date::try_new_iso(2025, 1, 15).unwrap(),
66 //! time: Time::try_new(16, 0, 0, 0).unwrap(),
67 //! };
68 //!
69 //! let with_time = DateTimeFormatter::try_new(
70 //! locale!("en-US").into(),
71 //! composite_field_set(true),
72 //! )
73 //! .unwrap();
74 //! let without_time = DateTimeFormatter::try_new(
75 //! locale!("en-US").into(),
76 //! composite_field_set(false),
77 //! )
78 //! .unwrap();
79 //!
80 //! assert_eq!(with_time.format(&datetime).to_string(), "Jan 15, 4:00 PM");
81 //! assert_eq!(without_time.format(&datetime).to_string(), "Jan 15");
82 //! ```
83
84 use crate::fieldsets::{Combo, builder};
85 use crate::raw::neo::RawOptions;
86 use crate::scaffold::GetField;
87 use crate::{fieldsets, provider};
88 use icu_provider::prelude::*;
89
90 #[cfg(doc)]
91 use crate::input::*;
92
93 /// An enumeration over all possible date field sets.
94 ///
95 /// This is a dynamic field set. For more information, see [`enums`](crate::fieldsets::enums).
96 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
97 #[non_exhaustive]
98 pub enum DateFieldSet {
99 /// The day of the month, as in
100 /// “on the 1st”.
101 D(fieldsets::D),
102 /// The month and day of the month, as in
103 /// “January 1st”.
104 MD(fieldsets::MD),
105 /// The year, month, and day of the month, as in
106 /// “January 1st, 2000”.
107 YMD(fieldsets::YMD),
108 /// The day of the month and weekday, as in
109 /// “Saturday 1st”.
110 DE(fieldsets::DE),
111 /// The month, day of the month, and weekday, as in
112 /// “Saturday, January 1st”.
113 MDE(fieldsets::MDE),
114 /// The year, month, day of the month, and weekday, as in
115 /// “Saturday, January 1st, 2000”.
116 YMDE(fieldsets::YMDE),
117 /// The weekday alone, as in
118 /// “Saturday”.
119 E(fieldsets::E),
120 }
121
122 /// An enumeration over all possible calendar period field sets.
123 ///
124 /// This is a dynamic field set. For more information, see [`enums`](crate::fieldsets::enums).
125 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
126 #[non_exhaustive]
127 pub enum CalendarPeriodFieldSet {
128 /// A standalone month, as in
129 /// “January”.
130 M(fieldsets::M),
131 /// A month and year, as in
132 /// “January 2000”.
133 YM(fieldsets::YM),
134 /// A year, as in
135 /// “2000”.
136 Y(fieldsets::Y),
137 // TODO(#5643): Add support for week-of-year
138 // /// The year and week of the year, as in
139 // /// “52nd week of 1999”.
140 // YW(fieldsets::YW),
141 // TODO(#501): Consider adding support for Quarter and YearQuarter.
142 }
143
144 /// An enumeration over all possible time field sets.
145 ///
146 /// This is a dynamic field set. For more information, see [`enums`](crate::fieldsets::enums).
147 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
148 #[non_exhaustive]
149 pub enum TimeFieldSet {
150 /// A time of day.
151 T(fieldsets::T),
152 }
153
154 /// An enumeration over all possible zone field sets.
155 ///
156 /// This is a dynamic field set. For more information, see [`enums`](crate::fieldsets::enums).
157 ///
158 /// # Time Zone Data Size
159 ///
160 /// Time zone names contribute a lot of data size. For resource-constrained
161 /// environments, the following formats require the least amount of data:
162 ///
163 /// - [`fieldsets::zone::SpecificShort`]
164 /// - [`fieldsets::zone::LocalizedOffsetLong`]
165 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
166 #[non_exhaustive]
167 pub enum ZoneFieldSet {
168 /// The long specific non-location format, as in
169 /// “Pacific Daylight Time”.
170 SpecificLong(fieldsets::zone::SpecificLong),
171 /// The short specific non-location format, as in
172 /// “PDT”.
173 SpecificShort(fieldsets::zone::SpecificShort),
174 /// The long offset format, as in
175 /// “GMT−8:00”.
176 LocalizedOffsetLong(fieldsets::zone::LocalizedOffsetLong),
177 /// The short offset format, as in
178 /// “GMT−8”.
179 LocalizedOffsetShort(fieldsets::zone::LocalizedOffsetShort),
180 /// The long generic non-location format, as in
181 /// “Pacific Time”.
182 GenericLong(fieldsets::zone::GenericLong),
183 /// The short generic non-location format, as in
184 /// “PT”.
185 GenericShort(fieldsets::zone::GenericShort),
186 /// The location format, as in
187 /// “Los Angeles Time”.
188 Location(fieldsets::zone::Location),
189 /// The exemplar city format, as in
190 /// “Los Angeles.
191 ExemplarCity(fieldsets::zone::ExemplarCity),
192 }
193
194 /// An enumeration over all possible date+time composite field sets.
195 ///
196 /// This is a dynamic field set. For more information, see [`enums`](crate::fieldsets::enums).
197 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
198 #[non_exhaustive]
199 pub enum DateAndTimeFieldSet {
200 /// The day of the month with time of day, as in
201 /// “on the 1st at 10:31 AM”.
202 DT(fieldsets::DT),
203 /// The month and day of the month with time of day, as in
204 /// “January 1st at 10:31 AM”.
205 MDT(fieldsets::MDT),
206 /// The year, month, and day of the month with time of day, as in
207 /// “January 1st, 2000 at 10:31 AM”.
208 YMDT(fieldsets::YMDT),
209 /// The day of the month and weekday with time of day, as in
210 /// “Saturday 1st at 10:31 AM”.
211 DET(fieldsets::DET),
212 /// The month, day of the month, and weekday with time of day, as in
213 /// “Saturday, January 1st at 10:31 AM”.
214 MDET(fieldsets::MDET),
215 /// The year, month, day of the month, and weekday with time of day, as in
216 /// “Saturday, January 1st, 2000 at 10:31 AM”.
217 YMDET(fieldsets::YMDET),
218 /// The weekday alone with time of day, as in
219 /// “Saturday at 10:31 AM”.
220 ET(fieldsets::ET),
221 }
222
223 /// An enum supporting date, calendar period, time, and date+time field sets
224 /// and options.
225 ///
226 /// Time zones are not supported with this enum.
227 ///
228 /// This enum is useful when formatting a type that does not contain a
229 /// time zone or to avoid storing time zone data.
230 ///
231 /// This is a dynamic field set. For more information, see [`enums`](crate::fieldsets::enums).
232 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
233 #[non_exhaustive]
234 pub enum CompositeDateTimeFieldSet {
235 /// Field set for a date.
236 Date(DateFieldSet),
237 /// Field set for a calendar period.
238 CalendarPeriod(CalendarPeriodFieldSet),
239 /// Field set for a time.
240 Time(TimeFieldSet),
241 /// Field set for a date and a time together.
242 DateTime(DateAndTimeFieldSet),
243 }
244
245 impl CompositeDateTimeFieldSet {
246 /// If the [`CompositeFieldSet`] does not contain a time zone,
247 /// returns the corresponding [`CompositeDateTimeFieldSet`].
248 pub fn try_from_composite_field_set(field_set: CompositeFieldSet) -> Option<Self> {
249 match field_set {
250 CompositeFieldSet::Date(v) => Some(Self::Date(v)),
251 CompositeFieldSet::CalendarPeriod(v) => Some(Self::CalendarPeriod(v)),
252 CompositeFieldSet::Time(v) => Some(Self::Time(v)),
253 CompositeFieldSet::Zone(_) => None,
254 CompositeFieldSet::DateTime(v) => Some(Self::DateTime(v)),
255 CompositeFieldSet::DateZone(_) => None,
256 CompositeFieldSet::TimeZone(_) => None,
257 CompositeFieldSet::DateTimeZone(_) => None,
258 }
259 }
260
261 /// Returns the [`CompositeFieldSet`] corresponding to this
262 /// [`CompositeDateTimeFieldSet`].
263 pub fn to_composite_field_set(self) -> CompositeFieldSet {
264 match self {
265 Self::Date(v) => CompositeFieldSet::Date(v),
266 Self::CalendarPeriod(v) => CompositeFieldSet::CalendarPeriod(v),
267 Self::Time(v) => CompositeFieldSet::Time(v),
268 Self::DateTime(v) => CompositeFieldSet::DateTime(v),
269 }
270 }
271 }
272
273 impl GetField<CompositeFieldSet> for CompositeDateTimeFieldSet {
274 fn get_field(&self) -> CompositeFieldSet {
275 self.to_composite_field_set()
276 }
277 }
278
279 /// Type alias representing all possible date + time zone field sets.
280 ///
281 /// This is a dynamic field set. For more information, see [`enums`](crate::fieldsets::enums).
282 pub type ZonedDateFieldSet = Combo<DateFieldSet, ZoneFieldSet>;
283
284 /// Type alias representing all possible time + time zone field sets.
285 ///
286 /// This is a dynamic field set. For more information, see [`enums`](crate::fieldsets::enums).
287 pub type ZonedTimeFieldSet = Combo<TimeFieldSet, ZoneFieldSet>;
288
289 /// Type alias representing all possible date + time + time zone field sets.
290 ///
291 /// This is a dynamic field set. For more information, see [`enums`](crate::fieldsets::enums).
292 pub type ZonedDateAndTimeFieldSet = Combo<DateAndTimeFieldSet, ZoneFieldSet>;
293
294 /// An enum supporting all possible field sets and options.
295 ///
296 /// This is a dynamic field set. For more information, see [`enums`](crate::fieldsets::enums).
297 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
298 #[non_exhaustive]
299 pub enum CompositeFieldSet {
300 /// Field set for a date.
301 Date(DateFieldSet),
302 /// Field set for a calendar period.
303 CalendarPeriod(CalendarPeriodFieldSet),
304 /// Field set for a time.
305 Time(TimeFieldSet),
306 /// Field set for a time zone.
307 Zone(ZoneFieldSet),
308 /// Field set for a date and a time together.
309 DateTime(DateAndTimeFieldSet),
310 /// Field set for a date and a time zone together.
311 DateZone(ZonedDateFieldSet),
312 /// Field set for a time and a time zone together.
313 TimeZone(ZonedTimeFieldSet),
314 /// Field set for a date, a time, and a time zone together.
315 DateTimeZone(ZonedDateAndTimeFieldSet),
316 }
317
318 macro_rules! first {
319 ($first:literal, $($remainder:literal,)*) => {
320 $first
321 };
322 }
323
324 macro_rules! impl_attrs {
325 (@attrs, $type:path, [$(($attr_var:ident, $str_var:ident, $value:literal),)+]) => {
326 impl $type {
327 $(
328 const $attr_var: &'static DataMarkerAttributes = DataMarkerAttributes::from_str_or_panic($value);
329 )+
330 /// All attributes associated with this enum.
331 ///
332 /// # Encoding Details
333 ///
334 /// The string is based roughly on the UTS 35 symbol table with the following exceptions:
335 ///
336 /// 1. Lowercase letters are chosen where there is no ambiguity: `E` becomes `e`
337 /// 2. Capitals are replaced with their lowercase and a number 0: `M` becomes `m0`
338 /// 3. A single symbol is included for each component: length doesn't matter
339 /// 4. Time fields are encoded with their hour field only: `j`, `h`, or `h0`
340 ///
341 /// # Examples
342 ///
343 /// ```
344 #[doc = concat!("use icu::datetime::fieldsets::enums::", stringify!($type), " as FS;")]
345 /// use icu_provider::DataMarkerAttributes;
346 ///
347 /// assert!(FS::ALL_DATA_MARKER_ATTRIBUTES.contains(
348 #[doc = concat!(" &DataMarkerAttributes::from_str_or_panic(\"", first!($($value,)*), "\")")]
349 /// ));
350 /// ```
351 pub const ALL_DATA_MARKER_ATTRIBUTES: &'static [&'static DataMarkerAttributes] = &[
352 $(
353 Self::$attr_var,
354 )+
355 ];
356 }
357 };
358 (@id_str, $type:path, [$(($variant:ident, $attr_var:ident)),+,]) => {
359 impl $type {
360 /// Returns a stable string identifying this set of fields.
361 pub(crate) const fn id_str(self) -> &'static DataMarkerAttributes {
362 match self {
363 $(
364 Self::$variant(_) => Self::$attr_var,
365 )+
366 }
367 }
368 }
369 };
370 (@to_raw_options, $type:path, [$($variant:ident),+,]) => {
371 impl $type {
372 pub(crate) fn to_raw_options(self) -> RawOptions {
373 match self {
374 $(
375 Self::$variant(variant) => variant.to_raw_options(),
376 )+
377 }
378 }
379 }
380 };
381 (@composite, $type:path, $variant:ident) => {
382 impl $type {
383 #[inline]
384 pub(crate) fn to_enum(self) -> $type {
385 self
386 }
387 }
388 impl GetField<CompositeFieldSet> for $type {
389 #[inline]
390 fn get_field(&self) -> CompositeFieldSet {
391 CompositeFieldSet::$variant(self.to_enum())
392 }
393 }
394 };
395 (@date, $type:path, [$(($variant:ident, $attr_var:ident, $str_var:ident, $value:literal)),+,]) => {
396 impl_attrs! { @attrs, $type, [$(($attr_var, $str_var, $value)),+,] }
397 impl_attrs! { @id_str, $type, [$(($variant, $attr_var)),+,] }
398 impl_attrs! { @to_raw_options, $type, [$($variant),+,] }
399 impl_attrs! { @composite, $type, Date }
400 };
401 (@calendar_period, $type:path, [$(($variant:ident, $attr_var:ident, $str_var:ident, $value:literal)),+,]) => {
402 impl_attrs! { @attrs, $type, [$(($attr_var, $str_var, $value)),+,] }
403 impl_attrs! { @to_raw_options, $type, [$($variant),+,] }
404 impl_attrs! { @composite, $type, CalendarPeriod }
405 impl_attrs! { @id_str, $type, [$(($variant, $attr_var)),+,] }
406 };
407 (@time, $type:path, [$(($attr_var:ident, $str_var:ident, $value:literal)),+,]) => {
408 impl_attrs! { @attrs, $type, [$(($attr_var, $str_var, $value)),+,] }
409 impl_attrs! { @to_raw_options, $type, [T,] }
410 impl_attrs! { @composite, $type, Time }
411 };
412 (@zone, $type:path, [$($variant:ident),+,]) => {
413 impl_attrs! { @composite, $type, Zone }
414 impl $type {
415 pub(crate) fn to_field(self) -> (provider::fields::TimeZone, provider::fields::FieldLength) {
416 match self {
417 $(
418 Self::$variant(variant) => variant.to_field(),
419 )+
420 }
421 }
422 pub(crate) fn to_zone_style(self) -> builder::ZoneStyle {
423 match self {
424 $(
425 Self::$variant(_) => builder::ZoneStyle::$variant,
426 )+
427 }
428 }
429 }
430 };
431 (@datetime, $type:path, [$(($d_variant:ident, $variant:ident)),+,]) => {
432 impl_attrs! { @to_raw_options, $type, [$($variant),+,] }
433 impl_attrs! { @composite, $type, DateTime }
434 impl $type {
435 pub(crate) fn to_date_field_set(self) -> DateFieldSet {
436 match self {
437 $(
438 Self::$variant(variant) => DateFieldSet::$d_variant(variant.to_date_field_set()),
439 )+
440 }
441 }
442 pub(crate) fn to_time_field_set(self) -> TimeFieldSet {
443 let (length, time_precision, alignment) = match self {
444 $(
445 Self::$variant(variant) => (variant.length, variant.time_precision, variant.alignment),
446 )+
447 };
448 TimeFieldSet::T(fieldsets::T {
449 length,
450 time_precision,
451 alignment,
452 })
453 }
454 }
455 };
456 }
457
458 impl_attrs! {
459 @date,
460 DateFieldSet,
461 [
462 (D, ATTR_D, STR_D, "d"),
463 (MD, ATTR_MD, STR_MD, "m0d"),
464 (YMD, ATTR_YMD, STR_YMD, "ym0d"),
465 (DE, ATTR_DE, STR_DE, "de"),
466 (MDE, ATTR_MDE, STR_MDE, "m0de"),
467 (YMDE, ATTR_YMDE, STR_YMDE, "ym0de"),
468 (E, ATTR_E, STR_E, "e"),
469 ]
470 }
471
472 impl_attrs! {
473 @calendar_period,
474 CalendarPeriodFieldSet,
475 [
476 (M, ATTR_M, STR_M, "m0"),
477 (YM, ATTR_YM, STR_YM, "ym0"),
478 (Y, ATTR_Y, STR_Y, "y"),
479 ]
480 }
481
482 impl_attrs! {
483 @time,
484 TimeFieldSet,
485 [
486 (ATTR_T, STR_T, "j"),
487 (ATTR_T12, STR_T12, "h"),
488 (ATTR_T24, STR_T24, "h0"),
489 ]
490 }
491
492 impl TimeFieldSet {
493 pub(crate) const fn id_str_for_hour_cycle(
494 self,
495 hour_cycle: Option<provider::fields::Hour>,
496 ) -> &'static DataMarkerAttributes {
497 use provider::fields::Hour::*;
498 match hour_cycle {
499 None => Self::ATTR_T,
500 Some(H11 | H12) => Self::ATTR_T12,
501 Some(H23) => Self::ATTR_T24,
502 }
503 }
504 }
505
506 impl_attrs! {
507 @zone,
508 ZoneFieldSet,
509 [
510 SpecificLong,
511 SpecificShort,
512 LocalizedOffsetLong,
513 LocalizedOffsetShort,
514 GenericLong,
515 GenericShort,
516 Location,
517 ExemplarCity,
518 ]
519 }
520
521 impl_attrs! {
522 @attrs,
523 DateAndTimeFieldSet,
524 [
525 (ATTR_ET, STR_ET, "ej"),
526 ]
527 }
528
529 impl_attrs! {
530 @datetime,
531 DateAndTimeFieldSet,
532 [
533 (D, DT),
534 (MD, MDT),
535 (YMD, YMDT),
536 (DE, DET),
537 (MDE, MDET),
538 (YMDE, YMDET),
539 (E, ET),
540 ]
541 }
542
543 impl DateAndTimeFieldSet {
544 pub(crate) const fn id_str(self) -> Option<&'static DataMarkerAttributes> {
545 match self {
546 DateAndTimeFieldSet::ET(_) => Some(Self::ATTR_ET),
547 _ => None,
548 }
549 }
550 }
551
552 impl CompositeFieldSet {
553 pub(crate) fn to_raw_options(self) -> RawOptions {
554 match self {
555 CompositeFieldSet::Date(field_set) => field_set.to_raw_options(),
556 CompositeFieldSet::CalendarPeriod(field_set) => field_set.to_raw_options(),
557 CompositeFieldSet::Time(field_set) => field_set.to_raw_options(),
558 CompositeFieldSet::DateTime(field_set) => field_set.to_raw_options(),
559 CompositeFieldSet::DateZone(combo) => combo.dt().to_raw_options(),
560 CompositeFieldSet::TimeZone(combo) => combo.dt().to_raw_options(),
561 CompositeFieldSet::DateTimeZone(combo) => combo.dt().to_raw_options(),
562 CompositeFieldSet::Zone(_) => RawOptions {
563 length: None,
564 date_fields: None,
565 year_style: None,
566 alignment: None,
567 time_precision: None,
568 },
569 }
570 }
571
572 pub(crate) fn to_zone(self) -> Option<ZoneFieldSet> {
573 match self {
574 CompositeFieldSet::Zone(field_set) => Some(field_set),
575 CompositeFieldSet::DateZone(combo) => Some(combo.z()),
576 CompositeFieldSet::TimeZone(combo) => Some(combo.z()),
577 CompositeFieldSet::DateTimeZone(combo) => Some(combo.z()),
578 _ => None,
579 }
580 }
581 }