Skip to main content

icu_datetime/provider/fields/
components.rs

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//! 🚧 \[Unstable\] Types for specifying fields in a classical datetime skeleton.
6//!
7//! <div class="stab unstable">
8//! 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
9//! including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
10//! of the icu meta-crate. Use with caution.
11//! <a href="https://github.com/unicode-org/icu4x/issues/1317">#1317</a>
12//! </div>
13//!
14//! # Examples
15//!
16//! ```
17//! use icu::datetime::provider::fields::components;
18//!
19//! let mut bag = components::Bag::default();
20//! bag.year = Some(components::Year::Numeric);
21//! bag.month = Some(components::Month::Long);
22//! bag.day = Some(components::Day::NumericDayOfMonth);
23//!
24//! bag.hour = Some(components::Numeric::TwoDigit);
25//! bag.minute = Some(components::Numeric::TwoDigit);
26//! ```
27//!
28//! *Note*: The exact formatted result is a subject to change over
29//! time. Formatted result should be treated as opaque and displayed to the user as-is,
30//! and it is strongly recommended to never write tests that expect a particular formatted output.
31
32use crate::{
33    options::SubsecondDigits,
34    provider::fields::{self, Field, FieldLength, FieldSymbol},
35    provider::pattern::{PatternItem, reference, runtime::Pattern},
36};
37
38use crate::pattern::DateTimePattern;
39use alloc::vec::Vec;
40use icu_locale_core::preferences::extensions::unicode::keywords::HourCycle;
41#[cfg(feature = "serde")]
42use serde::{Deserialize, Serialize};
43
44/// See the [module-level](./index.html) docs for more information.
45///
46/// <div class="stab unstable">
47/// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
48/// including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
49/// of the icu meta-crate. Use with caution.
50/// <a href="https://github.com/unicode-org/icu4x/issues/1317">#1317</a>
51/// </div>
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
53#[non_exhaustive]
54pub struct Bag {
55    /// Include the era, such as "AD" or "CE".
56    pub era: Option<Text>,
57    /// Include the year, such as "1970" or "70".
58    pub year: Option<Year>,
59    /// Include the month, such as "April" or "Apr".
60    pub month: Option<Month>,
61    /// Include the week number, such as "51st" or "51" for week 51.
62    pub week: Option<Week>,
63    /// Include the day of the month/year, such as "07" or "7".
64    pub day: Option<Day>,
65    /// Include the weekday, such as "Wednesday" or "Wed".
66    pub weekday: Option<Text>,
67
68    /// Include the hour such as "2" or "14".
69    pub hour: Option<Numeric>,
70    /// Include the minute such as "3" or "03".
71    pub minute: Option<Numeric>,
72    /// Include the second such as "3" or "03".
73    pub second: Option<Numeric>,
74    /// Specify the number of fractional second digits such as 1 (".3") or 3 (".003").
75    pub subsecond: Option<SubsecondDigits>,
76
77    /// Include the time zone, such as "GMT+05:00".
78    pub time_zone_name: Option<TimeZoneName>,
79
80    /// An override of the hour cycle.
81    //
82    // TODO: This should probably not be the preferences [HourCycle] type. It directly sets the
83    // hour cycle, without support for Clock12 and Clock24, which will panic.
84    pub hour_cycle: Option<HourCycle>,
85}
86
87impl Bag {
88    /// Creates an empty components bag
89    ///
90    /// Has the same behavior as the [`Default`] implementation on this type.
91    pub fn empty() -> Self {
92        Self::default()
93    }
94
95    /// Merges the fields of other into self if non-None. If both fields are set, `other` is kept.
96    pub fn merge(self, other: Self) -> Self {
97        Self {
98            era: other.era.or(self.era),
99            year: other.year.or(self.year),
100            month: other.month.or(self.month),
101            week: other.week.or(self.week),
102            day: other.day.or(self.day),
103            weekday: other.weekday.or(self.weekday),
104            hour: other.hour.or(self.hour),
105            minute: other.minute.or(self.minute),
106            second: other.second.or(self.second),
107            subsecond: other.subsecond.or(self.subsecond),
108            time_zone_name: other.time_zone_name.or(self.time_zone_name),
109            hour_cycle: other.hour_cycle.or(self.hour_cycle),
110        }
111    }
112
113    /// Converts the [`Bag`] into a [`Vec<Field>`]. The fields will be ordered in from most
114    /// significant field to least significant. This is the order the fields are listed in
115    /// the UTS 35 table - <https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table>
116    ///
117    /// Arguments:
118    ///
119    /// - `default_hour_cycle` specifies the hour cycle to use for the hour field if not in the Bag.
120    ///   `preferences::Bag::hour_cycle` takes precedence over this argument.
121    pub fn to_vec_fields(&self, default_hour_cycle: HourCycle) -> Vec<Field> {
122        let mut fields = Vec::new();
123        if let Some(era) = self.era {
124            fields.push(Field {
125                symbol: FieldSymbol::Era,
126                length: match era {
127                    // Era name, format length.
128                    //
129                    // G..GGG  AD           Abbreviated
130                    // GGGG    Anno Domini  Wide
131                    // GGGGG   A            Narrow
132                    Text::Short => FieldLength::Three,
133                    Text::Long => FieldLength::Four,
134                    Text::Narrow => FieldLength::Five,
135                },
136            })
137        }
138
139        if let Some(year) = self.year {
140            // Unimplemented year fields:
141            // u - Extended year
142            // U - Cyclic year name
143            // r - Related Gregorian year
144            fields.push(Field {
145                symbol: FieldSymbol::Year(match year {
146                    Year::Numeric | Year::TwoDigit => fields::Year::Calendar,
147                    Year::NumericWeekOf | Year::TwoDigitWeekOf => {
148                        unimplemented!("#5643 fields::Year::WeekOf")
149                    }
150                }),
151                length: match year {
152                    // Calendar year (numeric).
153                    // y       2, 20, 201, 2017, 20173
154                    // yy      02, 20, 01, 17, 73
155                    // yyy     002, 020, 201, 2017, 20173    (not implemented)
156                    // yyyy    0002, 0020, 0201, 2017, 20173 (not implemented)
157                    // yyyyy+  ...                           (not implemented)
158                    Year::Numeric | Year::NumericWeekOf => FieldLength::One,
159                    Year::TwoDigit | Year::TwoDigitWeekOf => FieldLength::Two,
160                },
161            });
162        }
163
164        // TODO(#501) - Unimplemented quarter fields:
165        // Q - Quarter number/name
166        // q - Stand-alone quarter
167
168        if let Some(month) = self.month {
169            fields.push(Field {
170                // Always choose Month::Format as Month::StandAlone is not used in skeletons.
171                symbol: FieldSymbol::Month(fields::Month::Format),
172                length: match month {
173                    // (intended to be used in conjunction with ‘d’ for day number).
174                    // M      9, 12      Numeric: minimum digits
175                    // MM     09, 12     Numeric: 2 digits, zero pad if needed
176                    // MMM    Sep        Abbreviated
177                    // MMMM   September  Wide
178                    // MMMMM  S          Narrow
179                    Month::Numeric => FieldLength::One,
180                    Month::TwoDigit => FieldLength::Two,
181                    Month::Long => FieldLength::Four,
182                    Month::Short => FieldLength::Three,
183                    Month::Narrow => FieldLength::Five,
184                },
185            });
186        }
187
188        if let Some(week) = self.week {
189            #[allow(
190                unreachable_code,
191                reason = "Uninhabited MultipleVariants (due to pivot_field), see #7118"
192            )]
193            fields.push(Field {
194                symbol: FieldSymbol::Week(match week {
195                    Week::WeekOfMonth => unimplemented!("#5643 fields::Week::WeekOfMonth"),
196                    Week::NumericWeekOfYear | Week::TwoDigitWeekOfYear => {
197                        unimplemented!("#5643 fields::Week::WeekOfYear")
198                    }
199                }),
200                length: match week {
201                    Week::WeekOfMonth | Week::NumericWeekOfYear => FieldLength::One,
202                    Week::TwoDigitWeekOfYear => FieldLength::Two,
203                },
204            });
205        }
206
207        if let Some(day) = self.day {
208            // TODO(#591) Unimplemented day fields:
209            // g - Modified Julian day.
210            fields.push(Field {
211                symbol: FieldSymbol::Day(match day {
212                    Day::NumericDayOfMonth | Day::TwoDigitDayOfMonth => fields::Day::DayOfMonth,
213                    Day::DayOfWeekInMonth => fields::Day::DayOfWeekInMonth,
214                    Day::DayOfYear => fields::Day::DayOfYear,
215                    Day::ModifiedJulianDay => fields::Day::ModifiedJulianDay,
216                }),
217                length: match day {
218                    // d    1 	  Numeric day of month: minimum digits
219                    // dd   01 	  Numeric day of month: 2 digits, zero pad if needed
220                    // F    1  	  Numeric day of week in month: minimum digits
221                    // D    1     Numeric day of year: minimum digits
222                    Day::NumericDayOfMonth
223                    | Day::DayOfWeekInMonth
224                    | Day::DayOfYear
225                    | Day::ModifiedJulianDay => FieldLength::One,
226                    Day::TwoDigitDayOfMonth => FieldLength::Two,
227                },
228            });
229        }
230
231        if let Some(weekday) = self.weekday {
232            // TODO(#593) Unimplemented fields
233            // e - Local day of week.
234            // c - Stand-alone local day of week.
235            fields.push(Field {
236                symbol: FieldSymbol::Weekday(fields::Weekday::Format),
237                length: match weekday {
238                    // Day of week name, format length.
239                    //
240                    // E..EEE   Tue      Abbreviated
241                    // EEEE     Tuesday  Wide
242                    // EEEEE    T 	     Narrow
243                    // EEEEEE   Tu       Short
244                    Text::Long => FieldLength::Four,
245                    Text::Short => FieldLength::One,
246                    Text::Narrow => FieldLength::Five,
247                },
248            });
249        }
250
251        // The period fields are not included in skeletons:
252        // a - AM, PM
253        // b - am, pm, noon, midnight
254        // c - flexible day periods
255
256        if let Some(hour) = self.hour {
257            // fields::Hour::H11
258            // fields::Hour::H12
259            // fields::Hour::H23
260
261            let hour_cycle = self.hour_cycle.unwrap_or(default_hour_cycle);
262
263            // When used in skeleton data or in a skeleton passed in an API for flexible date
264            // pattern generation, it should match the 12-hour-cycle format preferred by the
265            // locale (h or K); it should not match a 24-hour-cycle format (H or k).
266            fields.push(Field {
267                symbol: FieldSymbol::Hour(match hour_cycle {
268                    // Skeletons only contain the h12, not h11. The pattern that is matched
269                    // is free to use h11 or h12.
270                    HourCycle::H11 | HourCycle::H12 => {
271                        // h - symbol
272                        fields::Hour::H12
273                    }
274                    // Skeletons only contain the h23, not h24. The pattern that is matched
275                    // is free to use h23 or h24.
276                    HourCycle::H23 => {
277                        // H - symbol
278                        fields::Hour::H23
279                    }
280                    _ => unreachable!(),
281                }),
282                length: match hour {
283                    // Example for h: (note that this is the same for k, K, and H)
284                    // h     1, 12  Numeric: minimum digits
285                    // hh   01, 12  Numeric: 2 digits, zero pad if needed
286                    Numeric::Numeric => FieldLength::One,
287                    Numeric::TwoDigit => FieldLength::Two,
288                },
289            });
290        }
291
292        if let Some(minute) = self.minute {
293            // m   8, 59    Numeric: minimum digits
294            // mm  08, 59   Numeric: 2 digits, zero pad if needed
295            fields.push(Field {
296                symbol: FieldSymbol::Minute,
297                length: match minute {
298                    Numeric::Numeric => FieldLength::One,
299                    Numeric::TwoDigit => FieldLength::Two,
300                },
301            });
302        }
303
304        if let Some(second) = self.second {
305            let symbol = match self.subsecond {
306                None => FieldSymbol::Second(fields::Second::Second),
307                Some(subsecond) => FieldSymbol::from_subsecond_digits(subsecond),
308            };
309            // s    8, 12    Numeric: minimum digits
310            // ss  08, 12    Numeric: 2 digits, zero pad if needed
311            fields.push(Field {
312                symbol,
313                length: match second {
314                    Numeric::Numeric => FieldLength::One,
315                    Numeric::TwoDigit => FieldLength::Two,
316                },
317            });
318            // S - Fractional seconds. Represented as DecimalSecond.
319            // A - Milliseconds in day. Not used in skeletons.
320        }
321
322        if self.time_zone_name.is_some() {
323            // Only the lower "v" field is used in skeletons.
324            fields.push(Field {
325                symbol: FieldSymbol::TimeZone(fields::TimeZone::GenericNonLocation),
326                length: FieldLength::One,
327            });
328        }
329
330        {
331            #![allow(clippy::indexing_slicing)] // debug
332            debug_assert!(
333                fields.windows(2).all(|f| f[0] < f[1]),
334                "The fields are sorted and unique."
335            );
336        }
337
338        fields
339    }
340}
341
342/// A numeric component for the `components::`[`Bag`]. It is used for the year, day, hour, minute,
343/// and second.
344///
345/// <div class="stab unstable">
346/// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
347/// including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
348/// of the icu meta-crate. Use with caution.
349/// <a href="https://github.com/unicode-org/icu4x/issues/1317">#1317</a>
350/// </div>
351#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
352#[cfg_attr(
353    feature = "serde",
354    derive(Serialize, Deserialize),
355    serde(rename_all = "kebab-case")
356)]
357#[non_exhaustive]
358pub enum Numeric {
359    /// Display the numeric value. For instance in a year this would be "1970".
360    Numeric,
361    /// Display the two digit value. For instance in a year this would be "70".
362    TwoDigit,
363}
364
365/// A text component for the `components::`[`Bag`]. It is used for the era and weekday.
366///
367/// <div class="stab unstable">
368/// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
369/// including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
370/// of the icu meta-crate. Use with caution.
371/// <a href="https://github.com/unicode-org/icu4x/issues/1317">#1317</a>
372/// </div>
373#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
374#[cfg_attr(
375    feature = "serde",
376    derive(Serialize, Deserialize),
377    serde(rename_all = "kebab-case")
378)]
379#[non_exhaustive]
380pub enum Text {
381    /// Display the long form of the text, such as "Wednesday" for the weekday.
382    /// In UTS-35, known as "Wide" (4 letters)
383    Long,
384    /// Display the short form of the text, such as "Wed" for the weekday.
385    /// In UTS-35, known as "Abbreviated" (3 letters)
386    Short,
387    /// Display the narrow form of the text, such as "W" for the weekday.
388    /// In UTS-35, known as "Narrow" (5 letters)
389    Narrow,
390}
391
392/// Options for displaying a Year for the `components::`[`Bag`].
393///
394/// <div class="stab unstable">
395/// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
396/// including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
397/// of the icu meta-crate. Use with caution.
398/// <a href="https://github.com/unicode-org/icu4x/issues/1317">#1317</a>
399/// </div>
400#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
401#[cfg_attr(
402    feature = "serde",
403    derive(Serialize, Deserialize),
404    serde(rename_all = "kebab-case")
405)]
406#[non_exhaustive]
407pub enum Year {
408    /// The numeric value of the year, such as "2018" for 2018-12-31.
409    Numeric,
410    /// The two-digit value of the year, such as "18" for 2018-12-31.
411    TwoDigit,
412    /// The numeric value of the year in "week-of-year", such as "2019" in
413    /// "week 01 of 2019" for the week of 2018-12-31 according to the ISO calendar.
414    NumericWeekOf,
415    /// The numeric value of the year in "week-of-year", such as "19" in
416    /// "week 01 '19" for the week of 2018-12-31 according to the ISO calendar.
417    TwoDigitWeekOf,
418}
419
420/// Options for displaying a Month for the `components::`[`Bag`].
421///
422/// <div class="stab unstable">
423/// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
424/// including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
425/// of the icu meta-crate. Use with caution.
426/// <a href="https://github.com/unicode-org/icu4x/issues/1317">#1317</a>
427/// </div>
428#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
429#[cfg_attr(
430    feature = "serde",
431    derive(Serialize, Deserialize),
432    serde(rename_all = "kebab-case")
433)]
434#[non_exhaustive]
435pub enum Month {
436    /// The numeric value of the month, such as "4".
437    Numeric,
438    /// The two-digit value of the month, such as "04".
439    TwoDigit,
440    /// The long value of the month, such as "April".
441    Long,
442    /// The short value of the month, such as "Apr".
443    Short,
444    /// The narrow value of the month, such as "A".
445    Narrow,
446}
447
448// Each enum variant is documented with the UTS 35 field information from:
449// https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
450
451/// Options for displaying the current week number for the `components::`[`Bag`].
452///
453/// Week numbers are relative to either a month or year, e.g. 'week 3 of January' or 'week 40 of 2000'.
454///
455/// <div class="stab unstable">
456/// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
457/// including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
458/// of the icu meta-crate. Use with caution.
459/// <a href="https://github.com/unicode-org/icu4x/issues/1317">#1317</a>
460/// </div>
461#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
462#[cfg_attr(
463    feature = "serde",
464    derive(Serialize, Deserialize),
465    serde(rename_all = "kebab-case")
466)]
467#[non_exhaustive]
468pub enum Week {
469    /// The week of the month, such as the "3" in "week 3 of January".
470    WeekOfMonth,
471    /// The numeric value of the week of the year, such as the "8" in "week 8 of 2000".
472    NumericWeekOfYear,
473    /// The two-digit value of the week of the year, such as the "08" in "2000-W08".
474    TwoDigitWeekOfYear,
475}
476
477/// Options for displaying the current day of the month or year.
478///
479/// <div class="stab unstable">
480/// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
481/// including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
482/// of the icu meta-crate. Use with caution.
483/// <a href="https://github.com/unicode-org/icu4x/issues/1317">#1317</a>
484/// </div>
485#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
486#[cfg_attr(
487    feature = "serde",
488    derive(Serialize, Deserialize),
489    serde(rename_all = "kebab-case")
490)]
491#[non_exhaustive]
492pub enum Day {
493    /// The numeric value of the day of month, such as the "2" in July 2 1984.
494    NumericDayOfMonth,
495    /// The two digit value of the day of month, such as the "02" in 1984-07-02.
496    TwoDigitDayOfMonth,
497    /// The day of week in this month, such as the "2" in 2nd Wednesday of July.
498    DayOfWeekInMonth,
499    /// The day of year (numeric).
500    DayOfYear,
501    /// The modified Julian day (numeric)
502    ModifiedJulianDay,
503}
504
505/// Options for displaying a time zone for the `components::`[`Bag`].
506///
507/// Note that the initial implementation is focusing on only supporting ECMA-402 compatible
508/// options.
509///
510/// <div class="stab unstable">
511/// 🚧 This code is unstable; it may change at any time, in breaking or non-breaking ways,
512/// including in SemVer minor releases. It can be enabled with the `unstable` Cargo feature
513/// of the icu meta-crate. Use with caution.
514/// <a href="https://github.com/unicode-org/icu4x/issues/1317">#1317</a>
515/// </div>
516#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
517#[cfg_attr(
518    feature = "serde",
519    derive(Serialize, Deserialize),
520    serde(rename_all = "kebab-case")
521)]
522#[non_exhaustive]
523pub enum TimeZoneName {
524    // UTS-35 fields: z..zzz
525    /// Short localized form, without the location. (e.g.: PST, GMT-8)
526    ShortSpecific,
527
528    // UTS-35 fields: zzzz
529    // Per UTS-35: [long form] specific non-location (falling back to long localized offset)
530    /// Long localized form, without the location (e.g., Pacific Standard Time, Nordamerikanische Westküsten-Normalzeit)
531    LongSpecific,
532
533    // UTS-35 fields: OOOO
534    // Per UTS-35: The long localized offset format. This is equivalent to the "OOOO" specifier
535    /// Long localized offset form, e.g. GMT-08:00
536    LongOffset,
537
538    // UTS-35 fields: O
539    // Per UTS-35: Short localized offset format
540    /// Short localized offset form, e.g. GMT-8
541    ShortOffset,
542
543    // UTS-35 fields: v
544    //   * falling back to generic location (See UTS 35 for more specific rules)
545    //   * falling back to short localized offset
546    /// Short generic non-location format (e.g.: PT, Los Angeles, Zeit).
547    ShortGeneric,
548
549    // UTS-35 fields: vvvv
550    //  * falling back to generic location (See UTS 35 for more specific rules)
551    //  * falling back to long localized offset
552    /// Long generic non-location format (e.g.: Pacific Time, Nordamerikanische Westküstenzeit),
553    LongGeneric,
554}
555
556impl From<TimeZoneName> for Field {
557    fn from(time_zone_name: TimeZoneName) -> Self {
558        match time_zone_name {
559            TimeZoneName::ShortSpecific => Field {
560                symbol: FieldSymbol::TimeZone(fields::TimeZone::SpecificNonLocation),
561                length: FieldLength::One,
562            },
563            TimeZoneName::LongSpecific => Field {
564                symbol: FieldSymbol::TimeZone(fields::TimeZone::SpecificNonLocation),
565                length: FieldLength::Four,
566            },
567            TimeZoneName::LongOffset => Field {
568                symbol: FieldSymbol::TimeZone(fields::TimeZone::LocalizedOffset),
569                length: FieldLength::Four,
570            },
571            TimeZoneName::ShortOffset => Field {
572                symbol: FieldSymbol::TimeZone(fields::TimeZone::LocalizedOffset),
573                length: FieldLength::One,
574            },
575            TimeZoneName::ShortGeneric => Field {
576                symbol: FieldSymbol::TimeZone(fields::TimeZone::GenericNonLocation),
577                length: FieldLength::One,
578            },
579            TimeZoneName::LongGeneric => Field {
580                symbol: FieldSymbol::TimeZone(fields::TimeZone::GenericNonLocation),
581                length: FieldLength::Four,
582            },
583        }
584    }
585}
586
587impl From<&DateTimePattern> for Bag {
588    fn from(value: &DateTimePattern) -> Self {
589        Self::from(value.as_borrowed().0)
590    }
591}
592
593impl From<&Pattern<'_>> for Bag {
594    fn from(pattern: &Pattern) -> Self {
595        Self::from_pattern_items(pattern.items.iter())
596    }
597}
598
599impl From<&reference::Pattern> for Bag {
600    fn from(pattern: &reference::Pattern) -> Self {
601        Self::from_pattern_items(pattern.items.iter().copied())
602    }
603}
604
605impl Bag {
606    fn from_pattern_items(pattern_items: impl Iterator<Item = PatternItem>) -> Self {
607        let mut bag: Bag = Default::default();
608
609        // Transform the fields into components per:
610        // https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
611        for item in pattern_items {
612            let field = match item {
613                PatternItem::Field(ref field) => field,
614                PatternItem::Literal(_) => continue,
615            };
616            match field.symbol {
617                FieldSymbol::Era => {
618                    bag.era = Some(match field.length {
619                        FieldLength::One
620                        | FieldLength::NumericOverride(_)
621                        | FieldLength::Two
622                        | FieldLength::Three => Text::Short,
623                        FieldLength::Four => Text::Long,
624                        FieldLength::Five | FieldLength::Six => Text::Narrow,
625                    });
626                }
627                FieldSymbol::Year(year) => {
628                    bag.year = Some(match year {
629                        fields::Year::Calendar => match field.length {
630                            FieldLength::Two => Year::TwoDigit,
631                            _ => Year::Numeric,
632                        },
633                        // fields::Year::WeekOf => match field.length {
634                        //     FieldLength::TwoDigit => Year::TwoDigitWeekOf,
635                        //     _ => Year::NumericWeekOf,
636                        // },
637                        // TODO(#3762): Add support for U and r
638                        _ => Year::Numeric,
639                    });
640                }
641                FieldSymbol::Month(_) => {
642                    // `Month::StandAlone` is only relevant in the pattern, so only differentiate
643                    // on the field length.
644                    bag.month = Some(match field.length {
645                        FieldLength::One => Month::Numeric,
646                        FieldLength::NumericOverride(_) => Month::Numeric,
647                        FieldLength::Two => Month::TwoDigit,
648                        FieldLength::Three => Month::Short,
649                        FieldLength::Four => Month::Long,
650                        FieldLength::Five | FieldLength::Six => Month::Narrow,
651                    });
652                }
653                FieldSymbol::Week(_week) => {
654                    // TODO(#5643): Add week fields back
655                    // bag.week = Some(match week {
656                    //     fields::Week::WeekOfYear => match field.length {
657                    //         FieldLength::TwoDigit => Week::TwoDigitWeekOfYear,
658                    //         _ => Week::NumericWeekOfYear,
659                    //     },
660                    //     fields::Week::WeekOfMonth => Week::WeekOfMonth,
661                    // });
662                }
663                FieldSymbol::Day(day) => {
664                    bag.day = Some(match day {
665                        fields::Day::DayOfMonth => match field.length {
666                            FieldLength::Two => Day::TwoDigitDayOfMonth,
667                            _ => Day::NumericDayOfMonth,
668                        },
669                        fields::Day::DayOfYear => Day::DayOfYear,
670                        fields::Day::DayOfWeekInMonth => Day::DayOfWeekInMonth,
671                        fields::Day::ModifiedJulianDay => Day::ModifiedJulianDay,
672                    });
673                }
674                FieldSymbol::Weekday(weekday) => {
675                    bag.weekday = Some(match weekday {
676                        fields::Weekday::Format => match field.length {
677                            FieldLength::One | FieldLength::Two | FieldLength::Three => Text::Short,
678                            FieldLength::Four => Text::Long,
679                            _ => Text::Narrow,
680                        },
681                        fields::Weekday::StandAlone => match field.length {
682                            FieldLength::One
683                            | FieldLength::Two
684                            | FieldLength::NumericOverride(_) => {
685                                // Stand-alone fields also support a numeric 1 digit per UTS-35, but there is
686                                // no way to request it using the current system. As of 2021-12-06
687                                // no skeletons resolve to patterns containing this symbol.
688                                //
689                                // All resolved patterns from cldr-json:
690                                // https://github.com/gregtatum/cldr-json/blob/d4779f9611a4cc1e3e6a0a4597e92ead32d9f118/stand-alone-week.js
691                                //     'ccc',
692                                //     'ccc d. MMM',
693                                //     'ccc d. MMMM',
694                                //     'cccc d. MMMM y',
695                                //     'd, ccc',
696                                //     'cccနေ့',
697                                //     'ccc, d MMM',
698                                //     "ccc, d 'de' MMMM",
699                                //     "ccc, d 'de' MMMM 'de' y",
700                                //     'ccc, h:mm B',
701                                //     'ccc, h:mm:ss B',
702                                //     'ccc, d',
703                                //     "ccc, dd.MM.y 'г'.",
704                                //     'ccc, d.MM.y',
705                                //     'ccc, MMM d. y'
706                                unimplemented!("Numeric stand-alone fields are not supported.")
707                            }
708                            FieldLength::Three => Text::Short,
709                            FieldLength::Four => Text::Long,
710                            FieldLength::Five | FieldLength::Six => Text::Narrow,
711                        },
712                        fields::Weekday::Local => unimplemented!("fields::Weekday::Local"),
713                    });
714                }
715                FieldSymbol::DayPeriod(_) => {
716                    // Day period does not affect the resolved components.
717                }
718                FieldSymbol::Hour(hour) => {
719                    bag.hour = Some(match field.length {
720                        FieldLength::Two => Numeric::TwoDigit,
721                        _ => Numeric::Numeric,
722                    });
723                    bag.hour_cycle = Some(match hour {
724                        fields::Hour::H11 => HourCycle::H11,
725                        fields::Hour::H12 => HourCycle::H12,
726                        fields::Hour::H23 => HourCycle::H23,
727                    });
728                }
729                FieldSymbol::Minute => {
730                    bag.minute = Some(match field.length {
731                        FieldLength::Two => Numeric::TwoDigit,
732                        _ => Numeric::Numeric,
733                    });
734                }
735                FieldSymbol::Second(second) => match second {
736                    fields::Second::Second => {
737                        bag.second = Some(match field.length {
738                            FieldLength::Two => Numeric::TwoDigit,
739                            _ => Numeric::Numeric,
740                        });
741                    }
742                    fields::Second::MillisInDay => unimplemented!("fields::Second::MillisInDay"),
743                },
744                FieldSymbol::DecimalSecond(decimal_second) => {
745                    use SubsecondDigits::*;
746                    bag.second = Some(match field.length {
747                        FieldLength::Two => Numeric::TwoDigit,
748                        _ => Numeric::Numeric,
749                    });
750                    bag.subsecond = Some(match decimal_second {
751                        fields::DecimalSecond::Subsecond1 => S1,
752                        fields::DecimalSecond::Subsecond2 => S2,
753                        fields::DecimalSecond::Subsecond3 => S3,
754                        fields::DecimalSecond::Subsecond4 => S4,
755                        fields::DecimalSecond::Subsecond5 => S5,
756                        fields::DecimalSecond::Subsecond6 => S6,
757                        fields::DecimalSecond::Subsecond7 => S7,
758                        fields::DecimalSecond::Subsecond8 => S8,
759                        fields::DecimalSecond::Subsecond9 => S9,
760                    });
761                }
762                FieldSymbol::TimeZone(time_zone_name) => {
763                    bag.time_zone_name = Some(match time_zone_name {
764                        fields::TimeZone::SpecificNonLocation => match field.length {
765                            FieldLength::One => TimeZoneName::ShortSpecific,
766                            _ => TimeZoneName::LongSpecific,
767                        },
768                        fields::TimeZone::GenericNonLocation => match field.length {
769                            FieldLength::One => TimeZoneName::ShortGeneric,
770                            _ => TimeZoneName::LongGeneric,
771                        },
772                        fields::TimeZone::LocalizedOffset => match field.length {
773                            FieldLength::One => TimeZoneName::ShortOffset,
774                            _ => TimeZoneName::LongOffset,
775                        },
776                        fields::TimeZone::Location => unimplemented!("fields::TimeZone::Location"),
777                        fields::TimeZone::Iso => unimplemented!("fields::TimeZone::IsoZ"),
778                        fields::TimeZone::IsoWithZ => unimplemented!("fields::TimeZone::Iso"),
779                    });
780                }
781            }
782        }
783
784        bag
785    }
786}
787
788#[cfg(test)]
789mod test {
790    use super::*;
791
792    // Shorten these for terser tests.
793    type Symbol = FieldSymbol;
794    type Length = FieldLength;
795
796    #[test]
797    fn test_component_bag_to_vec_field() {
798        let bag = Bag {
799            year: Some(Year::Numeric),
800            month: Some(Month::Long),
801            // TODO(#5643): Add week fields back
802            week: None,
803            day: Some(Day::NumericDayOfMonth),
804
805            hour: Some(Numeric::Numeric),
806            minute: Some(Numeric::Numeric),
807            second: Some(Numeric::Numeric),
808            subsecond: Some(SubsecondDigits::S3),
809
810            ..Default::default()
811        };
812        assert_eq!(
813            bag.to_vec_fields(HourCycle::H23),
814            [
815                (Symbol::Year(fields::Year::Calendar), Length::One).into(),
816                (Symbol::Month(fields::Month::Format), Length::Four).into(),
817                (Symbol::Day(fields::Day::DayOfMonth), Length::One).into(),
818                (Symbol::Hour(fields::Hour::H23), Length::One).into(),
819                (Symbol::Minute, Length::One).into(),
820                (
821                    Symbol::DecimalSecond(fields::DecimalSecond::Subsecond3),
822                    Length::One
823                )
824                    .into(),
825            ]
826        );
827    }
828
829    #[test]
830    fn test_component_bag_to_vec_field2() {
831        let bag = Bag {
832            year: Some(Year::Numeric),
833            month: Some(Month::TwoDigit),
834            day: Some(Day::NumericDayOfMonth),
835            ..Default::default()
836        };
837        assert_eq!(
838            bag.to_vec_fields(HourCycle::H23),
839            [
840                (Symbol::Year(fields::Year::Calendar), Length::One).into(),
841                (Symbol::Month(fields::Month::Format), Length::Two).into(),
842                (Symbol::Day(fields::Day::DayOfMonth), Length::One).into(),
843            ]
844        );
845    }
846}