Debian Codegraph @

debian/rust-vendor/icu_datetime/src/raw/neo.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::DateTimeFormatterPreferences;
6 use crate::fieldsets::builder;
7 use crate::fieldsets::enums::{CompositeFieldSet, TimeFieldSet, ZoneFieldSet};
8 use crate::format::DateTimeInputUnchecked;
9 use crate::options::*;
10 use crate::pattern::DateTimePattern;
11 use crate::provider::fields::{self, Field, FieldLength, FieldSymbol};
12 use crate::provider::pattern::CoarseHourCycle;
13 use crate::provider::pattern::{
14 GenericPatternItem, PatternItem,
15 runtime::{self, PatternMetadata},
16 };
17 #[cfg(feature = "unstable")]
18 #[allow(unused_imports)]
19 use crate::provider::range_patterns::{
20 DateGreatestDifferenceField, DatetimePatternsRangeGlueV1, ErasedPackedRangePatterns,
21 RangePatternInfoBorrowed, TimeGreatestDifferenceField,
22 };
23 use crate::provider::{
24 packed_pattern::{ErasedPackedPatterns, PackedSkeletonVariant},
25 semantic_skeletons::{DatetimePatternsGlueV1, GluePattern, marker_attrs},
26 };
27 #[cfg(feature = "unstable")]
28 use crate::range::difference::Difference;
29 use icu_calendar::types::YearAmbiguity;
30 use icu_provider::DataPayloadOr;
31 use icu_provider::prelude::*;
32 use marker_attrs::GlueType;
33 use zerovec::ZeroSlice;
34 use zerovec::ule::AsULE;
35
36 #[derive(Debug, Copy, Clone)]
37 pub(crate) struct RawOptions {
38 pub(crate) length: Option<Length>,
39 pub(crate) date_fields: Option<builder::DateFields>,
40 pub(crate) alignment: Option<Alignment>,
41 pub(crate) year_style: Option<YearStyle>,
42 pub(crate) time_precision: Option<TimePrecision>,
43 }
44
45 impl RawOptions {
46 #[inline]
47 pub(crate) fn length(self) -> Length {
48 self.length.unwrap_or_else(|| {
49 debug_assert!(false, "length not set in a formatter that needs it");
50 Default::default()
51 })
52 }
53 }
54
55 #[derive(Debug, Copy, Clone, Default)]
56 pub(crate) struct RawPreferences {
57 pub(crate) hour_cycle: Option<fields::Hour>,
58 }
59
60 impl RawPreferences {
61 #[inline]
62 pub(crate) fn from_prefs(prefs: DateTimeFormatterPreferences) -> Self {
63 Self {
64 hour_cycle: fields::Hour::from_prefs(prefs),
65 }
66 }
67 }
68
69 #[derive(Debug, Clone)]
70 pub(crate) struct DatePatternSelectionData {
71 payload: DataPayloadOr<ErasedPackedPatterns, ()>,
72 }
73
74 #[derive(Debug, Copy, Clone)]
75 pub(crate) enum DatePatternDataBorrowed<'a> {
76 Resolved(runtime::PatternBorrowed<'a>, Option<Alignment>),
77 }
78
79 /// This enum represents both time patterns and overlap patterns between non-year dates and times.
80 //
81 // TODO(#5387): Consider reducing data size by filtering out explicit overlap patterns when they are
82 // the same as their individual patterns with glue.
83 #[derive(Debug, Clone)]
84 pub(crate) struct TimePatternSelectionData {
85 payload: DataPayloadOr<ErasedPackedPatterns, ()>,
86 }
87
88 #[derive(Debug, Copy, Clone)]
89 pub(crate) enum TimePatternDataBorrowed<'a> {
90 Resolved(
91 runtime::PatternBorrowed<'a>,
92 Option<Alignment>,
93 Option<fields::Hour>,
94 Option<SubsecondDigits>,
95 ),
96 }
97
98 #[derive(Debug, Clone)]
99 pub(crate) enum ZonePatternSelectionData {
100 SinglePatternItem(ZoneFieldSet, <PatternItem as AsULE>::ULE),
101 }
102
103 #[derive(Debug, Copy, Clone)]
104 pub(crate) enum ZonePatternDataBorrowed<'a> {
105 SinglePatternItem(&'a <PatternItem as AsULE>::ULE),
106 }
107
108 #[derive(Debug, Copy, Clone, Default)]
109 pub(crate) struct ItemsAndOptions<'a> {
110 pub(crate) items: &'a ZeroSlice<PatternItem>,
111 pub(crate) alignment: Option<Alignment>,
112 pub(crate) hour_cycle: Option<fields::Hour>,
113 pub(crate) subsecond_digits: Option<SubsecondDigits>,
114 }
115
116 impl ItemsAndOptions<'_> {
117 const fn new_empty() -> Self {
118 Self {
119 items: ZeroSlice::new_empty(),
120 alignment: None,
121 hour_cycle: None,
122 subsecond_digits: None,
123 }
124 }
125 }
126
127 #[derive(Debug, Clone)]
128 pub(crate) struct DateTimeZonePatternSelectionData {
129 pub(crate) options: RawOptions,
130 pub(crate) prefs: RawPreferences,
131 pub(crate) date: DatePatternSelectionData,
132 // The data for the overlap case is the same as for time, so we use the same intermediate
133 // type. This means that we can't have overlap patterns with both a year and a time. This
134 // assumption might need to be revisited.
135 pub(crate) time: TimePatternSelectionData,
136 pub(crate) zone: Option<ZonePatternSelectionData>,
137 pub(crate) glue: Option<DataPayload<DatetimePatternsGlueV1>>,
138 }
139
140 #[derive(Debug, Copy, Clone)]
141 pub(crate) struct DateTimeZonePatternDataBorrowed<'a> {
142 pub(crate) date: Option<DatePatternDataBorrowed<'a>>,
143 pub(crate) time: Option<TimePatternDataBorrowed<'a>>,
144 pub(crate) zone: Option<ZonePatternDataBorrowed<'a>>,
145 pub(crate) glue: Option<&'a GluePattern<'a>>,
146 }
147
148 impl DatePatternSelectionData {
149 pub(crate) fn none() -> Self {
150 Self {
151 payload: DataPayloadOr::none(),
152 }
153 }
154
155 pub(crate) fn try_new_with_skeleton(
156 provider: &(impl BoundDataProvider<ErasedPackedPatterns> + ?Sized),
157 prefs: DateTimeFormatterPreferences,
158 attributes: &DataMarkerAttributes,
159 ) -> Result<Self, DataError> {
160 let locale = provider
161 .bound_marker()
162 .make_locale(prefs.locale_preferences);
163 let payload = provider
164 .load_bound(DataRequest {
165 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(attributes, &locale),
166 ..Default::default()
167 })?
168 .payload;
169 Ok(Self {
170 payload: DataPayloadOr::from_payload(payload),
171 })
172 }
173
174 /// Borrows a pattern containing all of the fields that need to be loaded.
175 #[inline]
176 pub(crate) fn pattern_items_for_data_loading(
177 &self,
178 options: RawOptions,
179 ) -> Option<impl Iterator<Item = PatternItem> + '_> {
180 let payload = self.payload.get_option()?;
181 Some(
182 payload
183 .get(options.length(), PackedSkeletonVariant::Variant1)
184 .items
185 .iter(),
186 )
187 }
188
189 /// Borrows a resolved pattern based on the given datetime
190 pub(crate) fn select(
191 &self,
192 input: &DateTimeInputUnchecked,
193 options: RawOptions,
194 ) -> Option<DatePatternDataBorrowed<'_>> {
195 let payload = self.payload.get_option()?;
196 let variant = input.resolve_date_variant(options);
197 Some(DatePatternDataBorrowed::Resolved(
198 payload.get(options.length(), variant),
199 options.alignment,
200 ))
201 }
202 }
203
204 /// Data required for selecting date range patterns.
205 ///
206 /// This struct holds the patterns used to format the date portion of a range.
207 #[derive(Debug, Clone)]
208 #[cfg(feature = "unstable")]
209 #[allow(dead_code)]
210 pub(crate) struct DateRangePatternSelectionData {
211 /// The loaded date range patterns, or `None` if date range formatting is not supported.
212 pub(crate) payload: DataPayloadOr<ErasedPackedRangePatterns, ()>,
213 }
214
215 #[cfg(feature = "unstable")]
216 #[allow(dead_code)]
217 impl DateRangePatternSelectionData {
218 pub(crate) fn none() -> Self {
219 Self {
220 payload: DataPayloadOr::none(),
221 }
222 }
223
224 pub(crate) fn try_new_with_skeleton(
225 provider: &(impl BoundDataProvider<ErasedPackedRangePatterns> + ?Sized),
226 prefs: DateTimeFormatterPreferences,
227 attributes: &DataMarkerAttributes,
228 ) -> Result<Self, DataError> {
229 let locale = provider
230 .bound_marker()
231 .make_locale(prefs.locale_preferences);
232 let payload = provider
233 .load_bound(DataRequest {
234 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(attributes, &locale),
235 ..Default::default()
236 })?
237 .payload;
238 Ok(Self {
239 payload: DataPayloadOr::from_payload(payload),
240 })
241 }
242
243 pub(crate) fn select<'a>(
244 &'a self,
245 input: &DateTimeInputUnchecked,
246 options: RawOptions,
247 diff: Difference,
248 ) -> Option<RangePatternInfoBorrowed<'a>> {
249 let payload = self.payload.get_option()?;
250 let variant = input.resolve_date_variant(options);
251 let ule = payload.get_element(options.length(), variant)?;
252
253 let field = match diff {
254 Difference::Era => DateGreatestDifferenceField::Era,
255 Difference::Year => DateGreatestDifferenceField::Year,
256 Difference::Month => DateGreatestDifferenceField::Month,
257 Difference::Day => DateGreatestDifferenceField::Day,
258 _ => return None,
259 };
260
261 ule.get_date_pattern(field)
262 }
263 }
264
265 impl DateTimeInputUnchecked {
266 fn resolve_date_variant(&self, options: RawOptions) -> PackedSkeletonVariant {
267 let year_style = options.year_style.unwrap_or_default();
268 let ambiguity = self
269 .year
270 .as_ref()
271 .map(|y| {
272 y.era()
273 .map(|e| e.ambiguity)
274 .unwrap_or(YearAmbiguity::EraRequired)
275 })
276 .unwrap_or(YearAmbiguity::EraAndCenturyRequired);
277
278 match (year_style, ambiguity) {
279 (YearStyle::WithEra, _) => PackedSkeletonVariant::Variant1,
280
281 (
282 YearStyle::Full,
283 YearAmbiguity::EraAndCenturyRequired | YearAmbiguity::EraRequired,
284 ) => PackedSkeletonVariant::Variant1,
285 (YearStyle::Full, YearAmbiguity::CenturyRequired | YearAmbiguity::Unambiguous) => {
286 PackedSkeletonVariant::Variant0
287 }
288
289 (
290 YearStyle::Auto | YearStyle::NoEra,
291 YearAmbiguity::Unambiguous | YearAmbiguity::EraRequired,
292 ) => PackedSkeletonVariant::Standard,
293
294 (YearStyle::Auto, YearAmbiguity::CenturyRequired) => PackedSkeletonVariant::Variant0,
295 (YearStyle::Auto, YearAmbiguity::EraAndCenturyRequired) => {
296 PackedSkeletonVariant::Variant1
297 }
298
299 (
300 YearStyle::NoEra,
301 YearAmbiguity::CenturyRequired | YearAmbiguity::EraAndCenturyRequired,
302 ) => PackedSkeletonVariant::Variant0,
303 }
304 }
305
306 /// Resolve the variant to select based on time precision
307 ///
308 /// In case of range patterns, `range_second_input` should be set to the end input
309 /// of the range. Set to None for non range patterns.
310 fn resolve_time_precision(
311 &self,
312 time_precision: TimePrecision,
313 coarse_hour_cycle: Option<CoarseHourCycle>,
314 range_second_input: Option<&Self>,
315 ) -> (PackedSkeletonVariant, Option<SubsecondDigits>) {
316 match time_precision {
317 TimePrecision::Hour => (PackedSkeletonVariant::Standard, None),
318 TimePrecision::Minute => (PackedSkeletonVariant::Variant0, None),
319 TimePrecision::Second => (PackedSkeletonVariant::Variant1, None),
320 TimePrecision::Subsecond(f) => (PackedSkeletonVariant::Variant1, Some(f)),
321 TimePrecision::MinuteOptional => {
322 let minute = self.minute.unwrap_or_default();
323 let second_range_minute_is_zero = range_second_input
324 .map(|input2| input2.minute.unwrap_or_default().is_zero())
325 .unwrap_or(true);
326 if minute.is_zero()
327 && second_range_minute_is_zero
328 && matches!(coarse_hour_cycle, Some(CoarseHourCycle::H11H12))
329 {
330 (PackedSkeletonVariant::Standard, None)
331 } else {
332 (PackedSkeletonVariant::Variant0, None)
333 }
334 }
335 }
336 }
337 }
338
339 impl<'a> DatePatternDataBorrowed<'a> {
340 pub(crate) fn items_and_options(self) -> ItemsAndOptions<'a> {
341 let Self::Resolved(pattern, alignment) = self;
342 ItemsAndOptions {
343 items: pattern.items,
344 alignment,
345 ..Default::default()
346 }
347 }
348 }
349
350 impl TimePatternSelectionData {
351 pub(crate) fn none() -> Self {
352 Self {
353 payload: DataPayloadOr::none(),
354 }
355 }
356
357 pub(crate) fn try_new_with_skeleton(
358 provider: &(impl BoundDataProvider<ErasedPackedPatterns> + ?Sized),
359 prefs: DateTimeFormatterPreferences,
360 components: TimeFieldSet,
361 ) -> Result<Self, DataError> {
362 let locale = provider
363 .bound_marker()
364 .make_locale(prefs.locale_preferences);
365 let prefs = RawPreferences::from_prefs(prefs);
366 // First try to load with the explicit hour cycle. If there is no explicit hour cycle,
367 // or if loading the explicit hour cycle fails, then load with the default hour cycle.
368 let mut maybe_payload = None;
369 if let Some(hour_cycle) = prefs.hour_cycle {
370 maybe_payload = provider
371 .load_bound(DataRequest {
372 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
373 components.id_str_for_hour_cycle(Some(hour_cycle)),
374 &locale,
375 ),
376 ..Default::default()
377 })
378 .allow_identifier_not_found()?
379 .map(|r| r.payload);
380 }
381 let payload = match maybe_payload {
382 Some(payload) => payload,
383 None => {
384 provider
385 .load_bound(DataRequest {
386 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
387 components.id_str_for_hour_cycle(None),
388 &locale,
389 ),
390 ..Default::default()
391 })?
392 .payload
393 }
394 };
395 Ok(Self {
396 payload: DataPayloadOr::from_payload(payload),
397 })
398 }
399
400 pub(crate) fn try_new_overlap_with_skeleton(
401 provider: &(impl BoundDataProvider<ErasedPackedPatterns> + ?Sized),
402 prefs: DateTimeFormatterPreferences,
403 attributes: &DataMarkerAttributes,
404 options: RawOptions,
405 ) -> Result<Self, DataError> {
406 // Currently, none of the overlap patterns have a year field,
407 // so we can use the variant to select the time precision.
408 //
409 // We do not currently support overlap patterns with both a
410 // year and a time because that would involve 3*3 = 9 variants
411 // instead of 3 variants.
412 debug_assert!(options.year_style.is_none());
413 let locale = provider
414 .bound_marker()
415 .make_locale(prefs.locale_preferences);
416 let payload = provider
417 .load_bound(DataRequest {
418 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(attributes, &locale),
419 ..Default::default()
420 })?
421 .payload;
422 Ok(Self {
423 payload: DataPayloadOr::from_payload(payload),
424 })
425 }
426
427 /// Borrows a pattern containing all of the fields that need to be loaded.
428 #[inline]
429 pub(crate) fn pattern_items_for_data_loading(
430 &self,
431 options: RawOptions,
432 ) -> Option<impl Iterator<Item = PatternItem> + '_> {
433 let payload = self.payload.get_option()?;
434 Some(
435 payload
436 .get(options.length(), PackedSkeletonVariant::Variant1)
437 .items
438 .iter(),
439 )
440 }
441
442 /// Borrows a resolved pattern based on the given datetime
443 pub(crate) fn select(
444 &self,
445 input: &DateTimeInputUnchecked,
446 options: RawOptions,
447 prefs: RawPreferences,
448 ) -> Option<TimePatternDataBorrowed<'_>> {
449 let payload = self.payload.get_option()?;
450 let time_precision = options.time_precision.unwrap_or_default();
451 // To get the hour cycle without reading the whole pattern, we can check the time
452 // granularity of the hour pattern (packed variant `Standard`).
453 let coarse_hour_cycle = payload
454 .get(options.length(), PackedSkeletonVariant::Standard)
455 .metadata
456 .time_granularity()
457 .coarse_hour_cycle();
458 let (variant, subsecond_digits) =
459 input.resolve_time_precision(time_precision, coarse_hour_cycle, None);
460 Some(TimePatternDataBorrowed::Resolved(
461 payload.get(options.length(), variant),
462 options.alignment,
463 prefs.hour_cycle,
464 subsecond_digits,
465 ))
466 }
467 }
468
469 impl<'a> TimePatternDataBorrowed<'a> {
470 pub(crate) fn items_and_options(self) -> ItemsAndOptions<'a> {
471 let Self::Resolved(pattern, alignment, hour_cycle, subsecond_digits) = self;
472 ItemsAndOptions {
473 items: pattern.items,
474 alignment,
475 hour_cycle,
476 subsecond_digits,
477 }
478 }
479 }
480
481 /// Data required for selecting time range patterns.
482 ///
483 /// This struct holds the patterns used to format the time portion of a range.
484 #[derive(Debug, Clone)]
485 #[cfg(feature = "unstable")]
486 #[allow(dead_code)]
487 pub(crate) struct TimeRangePatternSelectionData {
488 /// The loaded time range patterns, or `None` if time range formatting is not supported.
489 pub(crate) payload: DataPayloadOr<ErasedPackedRangePatterns, ()>,
490 }
491
492 #[cfg(feature = "unstable")]
493 #[allow(dead_code)]
494 impl TimeRangePatternSelectionData {
495 pub(crate) fn none() -> Self {
496 Self {
497 payload: DataPayloadOr::none(),
498 }
499 }
500
501 pub(crate) fn try_new_with_skeleton(
502 provider: &(impl BoundDataProvider<ErasedPackedRangePatterns> + ?Sized),
503 prefs: DateTimeFormatterPreferences,
504 components: TimeFieldSet,
505 ) -> Result<Self, DataError> {
506 let locale = provider
507 .bound_marker()
508 .make_locale(prefs.locale_preferences);
509 let prefs = RawPreferences::from_prefs(prefs);
510 // First try to load with the explicit hour cycle. If there is no explicit hour cycle,
511 // or if loading the explicit hour cycle fails, then load with the default hour cycle.
512 let mut maybe_payload = None;
513 if let Some(hour_cycle) = prefs.hour_cycle {
514 maybe_payload = provider
515 .load_bound(DataRequest {
516 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
517 components.id_str_for_hour_cycle(Some(hour_cycle)),
518 &locale,
519 ),
520 ..Default::default()
521 })
522 .allow_identifier_not_found()?
523 .map(|r| r.payload);
524 }
525 let payload = match maybe_payload {
526 Some(payload) => payload,
527 None => {
528 provider
529 .load_bound(DataRequest {
530 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
531 components.id_str_for_hour_cycle(None),
532 &locale,
533 ),
534 ..Default::default()
535 })?
536 .payload
537 }
538 };
539 Ok(Self {
540 payload: DataPayloadOr::from_payload(payload),
541 })
542 }
543
544 pub(crate) fn select<'a>(
545 &'a self,
546 input: &DateTimeInputUnchecked,
547 input2: &DateTimeInputUnchecked,
548 options: RawOptions,
549 diff: Difference,
550 ) -> Option<RangePatternInfoBorrowed<'a>> {
551 let payload = self.payload.get_option()?;
552 let field = match diff {
553 Difference::DayPeriodB => TimeGreatestDifferenceField::DayPeriodB,
554 Difference::DayPeriodA => TimeGreatestDifferenceField::DayPeriodA,
555 Difference::Hour => TimeGreatestDifferenceField::Hour,
556 Difference::Minute => TimeGreatestDifferenceField::Minute,
557 _ => return None,
558 };
559
560 let coarse_hour_cycle = payload.get_coarse_hour_cycle(options.length());
561 let time_precision = options.time_precision.unwrap_or_default();
562 let (variant, _) =
563 input.resolve_time_precision(time_precision, coarse_hour_cycle, Some(input2));
564 let ule = payload.get_element(options.length(), variant)?;
565
566 ule.get_time_pattern(field)
567 }
568 }
569
570 impl ZonePatternSelectionData {
571 pub(crate) fn new_with_skeleton(field_set: ZoneFieldSet) -> Self {
572 let (symbol, length) = field_set.to_field();
573 let pattern_item = PatternItem::Field(Field {
574 symbol: FieldSymbol::TimeZone(symbol),
575 length,
576 });
577 Self::SinglePatternItem(field_set, pattern_item.to_unaligned())
578 }
579
580 /// Borrows a pattern containing all of the fields that need to be loaded.
581 #[inline]
582 pub(crate) fn pattern_items_for_data_loading(&self) -> impl Iterator<Item = PatternItem> + '_ {
583 let Self::SinglePatternItem(_, pattern_item) = self;
584 let pattern_item = PatternItem::from_unaligned(*pattern_item);
585 [pattern_item].into_iter()
586 }
587
588 /// Borrows a resolved pattern based on the given datetime
589 pub(crate) fn select(&self, _input: &DateTimeInputUnchecked) -> ZonePatternDataBorrowed<'_> {
590 let Self::SinglePatternItem(_, pattern_item) = self;
591 ZonePatternDataBorrowed::SinglePatternItem(pattern_item)
592 }
593 }
594
595 impl<'a> ZonePatternDataBorrowed<'a> {
596 pub(crate) fn items_and_options(self) -> ItemsAndOptions<'a> {
597 let Self::SinglePatternItem(item) = self;
598 ItemsAndOptions {
599 items: ZeroSlice::from_ule_slice(core::slice::from_ref(item)),
600 ..Default::default()
601 }
602 }
603 }
604
605 /// Helper function to map a [`CompositeFieldSet`] to loaded date and time pattern selection data.
606 ///
607 /// This function decomposes a composite field set into its date and time components,
608 /// applying the provided loader closures `load_date` and `load_time` respectively to load
609 /// the specific pattern selection data payloads.
610 ///
611 /// If a component (date or time) is not present in the composite field set, `None` is returned
612 /// for that component.
613 #[inline]
614 fn map_composite_skeleton<DateRes, TimeRes, E>(
615 skeleton: CompositeFieldSet,
616 mut load_date: impl FnMut(&DataMarkerAttributes) -> Result<DateRes, E>,
617 mut load_time: impl FnMut(TimeFieldSet) -> Result<TimeRes, E>,
618 ) -> Result<(Option<DateRes>, Option<TimeRes>), E> {
619 let mut date = None;
620 let mut time = None;
621 match skeleton {
622 CompositeFieldSet::Date(field_set) => {
623 date = Some(load_date(field_set.id_str())?);
624 }
625 CompositeFieldSet::CalendarPeriod(field_set) => {
626 date = Some(load_date(field_set.id_str())?);
627 }
628 CompositeFieldSet::Time(field_set) => {
629 time = Some(load_time(field_set)?);
630 }
631 CompositeFieldSet::DateTime(field_set) => {
632 date = Some(load_date(field_set.to_date_field_set().id_str())?);
633 time = Some(load_time(field_set.to_time_field_set())?);
634 }
635 CompositeFieldSet::DateZone(combo) => {
636 date = Some(load_date(combo.dt().id_str())?);
637 }
638 CompositeFieldSet::DateTimeZone(combo) => {
639 date = Some(load_date(combo.dt().to_date_field_set().id_str())?);
640 time = Some(load_time(combo.dt().to_time_field_set())?);
641 }
642 CompositeFieldSet::TimeZone(combo) => {
643 time = Some(load_time(combo.dt())?);
644 }
645 CompositeFieldSet::Zone(_) => {}
646 }
647 Ok((date, time))
648 }
649
650 impl DateTimeZonePatternSelectionData {
651 pub(crate) fn try_new_with_skeleton(
652 date_provider: &(impl BoundDataProvider<ErasedPackedPatterns> + ?Sized),
653 time_provider: &(impl BoundDataProvider<ErasedPackedPatterns> + ?Sized),
654 glue_provider: &(impl BoundDataProvider<DatetimePatternsGlueV1> + ?Sized),
655 prefs: DateTimeFormatterPreferences,
656 skeleton: CompositeFieldSet,
657 ) -> Result<Self, DataError> {
658 // Handle overlap early return.
659 //
660 // Note: For range formatting on overlap skeletons (such as `ej` for short weekday + time),
661 // returning early with `date: DatePatternSelectionData::none()` and `glue: None` causes
662 // time interval differences to drop to fallback range formatting (`format_fallback`).
663 // This relies on the assumption that any locale in CLDR supporting overlap patterns in
664 // standard date/time formatting also defines corresponding interval range pattern data.
665 // This coverage assumption is verified across all locales and calendars in datagen tests:
666 // `icu_provider_source::datetime::range_patterns::tests`.
667 if let CompositeFieldSet::DateTime(field_set) = skeleton {
668 let options = field_set.to_raw_options();
669 // TODO(#5387): load the patterns for custom hour cycles here
670 if let (Some(attributes), None) = (field_set.id_str(), prefs.hour_cycle)
671 // Try loading an overlap pattern.
672 // Note: Overlap patterns are loaded from the date skeleton pattern provider
673 // and then stored as a TimePatternSelectionData.
674 && let Some(overlap) = TimePatternSelectionData::try_new_overlap_with_skeleton(
675 date_provider,
676 prefs,
677 attributes,
678 options,
679 )
680 .allow_identifier_not_found()?
681 {
682 let prefs = RawPreferences::from_prefs(prefs);
683 return Ok(Self {
684 options,
685 prefs,
686 date: DatePatternSelectionData::none(),
687 time: overlap,
688 zone: None,
689 glue: None,
690 });
691 }
692 }
693
694 let options = skeleton.to_raw_options();
695 let zone = skeleton
696 .to_zone()
697 .map(ZonePatternSelectionData::new_with_skeleton);
698
699 let glue_type = match skeleton {
700 CompositeFieldSet::DateTime(_) => Some(GlueType::DateTime),
701 CompositeFieldSet::DateZone(_) => Some(GlueType::DateZone),
702 CompositeFieldSet::TimeZone(_) => Some(GlueType::TimeZone),
703 CompositeFieldSet::DateTimeZone(_) => Some(GlueType::DateTimeZone),
704 _ => None,
705 };
706
707 let glue = if let Some(gt) = glue_type {
708 Some(Self::load_glue(glue_provider, prefs, options, gt)?)
709 } else {
710 None
711 };
712
713 let (date_opt, time_opt) = map_composite_skeleton(
714 skeleton,
715 |d_attrs| {
716 DatePatternSelectionData::try_new_with_skeleton(date_provider, prefs, d_attrs)
717 },
718 |t_field_set| {
719 TimePatternSelectionData::try_new_with_skeleton(time_provider, prefs, t_field_set)
720 },
721 )?;
722
723 let has_time = time_opt.is_some();
724 let date = date_opt.unwrap_or_else(DatePatternSelectionData::none);
725 let time = time_opt.unwrap_or_else(TimePatternSelectionData::none);
726
727 let prefs = if has_time {
728 RawPreferences::from_prefs(prefs)
729 } else {
730 Default::default()
731 };
732
733 Ok(Self {
734 options,
735 prefs,
736 date,
737 time,
738 zone,
739 glue,
740 })
741 }
742
743 fn load_glue(
744 provider: &(impl BoundDataProvider<DatetimePatternsGlueV1> + ?Sized),
745 prefs: DateTimeFormatterPreferences,
746 options: RawOptions,
747 glue_type: GlueType,
748 ) -> Result<DataPayload<DatetimePatternsGlueV1>, DataError> {
749 let locale = provider
750 .bound_marker()
751 .make_locale(prefs.locale_preferences);
752 provider
753 .load_bound(DataRequest {
754 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
755 marker_attrs::pattern_marker_attr_for_glue(
756 // According to UTS 35, use the date length here: use the glue
757 // pattern "whose type matches the type of the date pattern"
758 match options.length() {
759 Length::Long => marker_attrs::PatternLength::Long,
760 Length::Medium => marker_attrs::PatternLength::Medium,
761 Length::Short => marker_attrs::PatternLength::Short,
762 },
763 glue_type,
764 ),
765 &locale,
766 ),
767 ..Default::default()
768 })
769 .map(|r| r.payload)
770 }
771
772 /// Returns an iterator over the pattern items that may need to be loaded.
773 #[inline]
774 pub(crate) fn pattern_items_for_data_loading(&self) -> impl Iterator<Item = PatternItem> + '_ {
775 let Self {
776 date, time, zone, ..
777 } = self;
778 let date_items = date
779 .pattern_items_for_data_loading(self.options)
780 .into_iter()
781 .flatten();
782 let time_items = time
783 .pattern_items_for_data_loading(self.options)
784 .into_iter()
785 .flatten();
786 let zone_items = zone.iter().flat_map(|x| x.pattern_items_for_data_loading());
787 date_items.chain(time_items).chain(zone_items)
788 }
789
790 /// Borrows a resolved pattern based on the given datetime
791 pub(crate) fn select(
792 &self,
793 input: &DateTimeInputUnchecked,
794 ) -> DateTimeZonePatternDataBorrowed<'_> {
795 DateTimeZonePatternDataBorrowed {
796 date: self.date.select(input, self.options),
797 time: self.time.select(input, self.options, self.prefs),
798 zone: self.zone.as_ref().map(|zone| zone.select(input)),
799 glue: self.glue.as_ref().map(|glue| glue.get()),
800 }
801 }
802
803 /// Converts one of these into a corresponding [`builder::FieldSetBuilder`]
804 pub(crate) fn to_builder(&self) -> builder::FieldSetBuilder {
805 let time_precision = if self.time.payload.is_payload() {
806 Some(self.options.time_precision.unwrap_or_default())
807 } else {
808 None
809 };
810 let zone_style = self.zone.as_ref().map(|zone| {
811 let ZonePatternSelectionData::SinglePatternItem(field_set, _) = zone;
812 field_set.to_zone_style()
813 });
814 builder::FieldSetBuilder {
815 length: self.options.length,
816 date_fields: self.options.date_fields,
817 time_precision,
818 zone_style,
819 alignment: self.options.alignment,
820 year_style: self.options.year_style,
821 }
822 }
823 }
824
825 /// Data required for selecting date, time, and zone range patterns.
826 ///
827 /// This struct consolidates the date and time range patterns, as well as the
828 /// fallback range glue used when no specific greatest-difference pattern is available.
829 #[derive(Debug, Clone)]
830 #[cfg(feature = "unstable")]
831 #[allow(dead_code)]
832 pub(crate) struct DateTimeZoneRangePatternSelectionData {
833 /// Data for selecting date range patterns.
834 pub(crate) date_range: DateRangePatternSelectionData,
835 /// Data for selecting time range patterns.
836 pub(crate) time_range: TimeRangePatternSelectionData,
837 /// Fallback range glue patterns.
838 pub(crate) range_glue: DataPayload<DatetimePatternsRangeGlueV1>,
839 }
840
841 #[cfg(feature = "unstable")]
842 #[allow(dead_code)]
843 impl DateTimeZoneRangePatternSelectionData {
844 pub(crate) fn try_new_with_skeleton(
845 date_range_provider: &(impl BoundDataProvider<ErasedPackedRangePatterns> + ?Sized),
846 time_range_provider: &(impl BoundDataProvider<ErasedPackedRangePatterns> + ?Sized),
847 range_glue_provider: &(impl BoundDataProvider<DatetimePatternsRangeGlueV1> + ?Sized),
848 prefs: DateTimeFormatterPreferences,
849 skeleton: CompositeFieldSet,
850 ) -> Result<Self, DataError> {
851 let locale = range_glue_provider
852 .bound_marker()
853 .make_locale(prefs.locale_preferences);
854
855 let range_glue = range_glue_provider
856 .load_bound(DataRequest {
857 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
858 DataMarkerAttributes::empty(),
859 &locale,
860 ),
861 ..Default::default()
862 })?
863 .payload;
864
865 let (date_opt, time_opt) = map_composite_skeleton(
866 skeleton,
867 |d_attrs| {
868 DateRangePatternSelectionData::try_new_with_skeleton(
869 date_range_provider,
870 prefs,
871 d_attrs,
872 )
873 },
874 |t_field_set| {
875 TimeRangePatternSelectionData::try_new_with_skeleton(
876 time_range_provider,
877 prefs,
878 t_field_set,
879 )
880 },
881 )?;
882
883 let date_range = date_opt.unwrap_or_else(DateRangePatternSelectionData::none);
884 let time_range = time_opt.unwrap_or_else(TimeRangePatternSelectionData::none);
885
886 Ok(Self {
887 date_range,
888 time_range,
889 range_glue,
890 })
891 }
892 }
893
894 impl<'a> DateTimeZonePatternDataBorrowed<'a> {
895 #[inline]
896 fn date_pattern(self) -> Option<DatePatternDataBorrowed<'a>> {
897 self.date
898 }
899
900 #[inline]
901 fn time_pattern(self) -> Option<TimePatternDataBorrowed<'a>> {
902 self.time
903 }
904
905 #[inline]
906 fn zone_pattern(self) -> Option<ZonePatternDataBorrowed<'a>> {
907 self.zone
908 }
909
910 #[inline]
911 fn glue_pattern(self) -> Option<&'a ZeroSlice<GenericPatternItem>> {
912 self.glue.map(|glue| glue.pattern.items.as_slice())
913 }
914
915 #[inline]
916 pub(crate) fn metadata(self) -> PatternMetadata {
917 match (self.date, self.time) {
918 (Some(DatePatternDataBorrowed::Resolved(pb, _)), None) => pb.metadata,
919 (None, Some(TimePatternDataBorrowed::Resolved(pb, _, _, _))) => pb.metadata,
920 (
921 Some(DatePatternDataBorrowed::Resolved(date, _)),
922 Some(TimePatternDataBorrowed::Resolved(time, _, _, _)),
923 ) => PatternMetadata::merge_date_and_time_metadata(date.metadata, time.metadata),
924 (None, None) => Default::default(),
925 }
926 }
927
928 pub(crate) fn iter_items(self) -> impl Iterator<Item = PatternItem> + 'a {
929 let glue_pattern_slice = match self.glue_pattern() {
930 Some(glue) => glue.as_ule_slice(),
931 None => runtime::ZERO_ONE_TWO_SLICE.as_ule_slice(),
932 };
933 glue_pattern_slice
934 .iter()
935 .map(
936 move |generic_item_ule| match generic_item_ule.as_pattern_item_ule() {
937 Ok(pattern_item_ule) => ItemsAndOptions {
938 items: ZeroSlice::from_ule_slice(core::slice::from_ref(pattern_item_ule)),
939 ..Default::default()
940 },
941 Err(1) => self
942 .date_pattern()
943 .map(|p| p.items_and_options())
944 .unwrap_or(const { ItemsAndOptions::new_empty() }),
945 Err(0) => self
946 .time_pattern()
947 .map(|p| p.items_and_options())
948 .unwrap_or(const { ItemsAndOptions::new_empty() }),
949 Err(2) => self
950 .zone_pattern()
951 .map(|p| p.items_and_options())
952 .unwrap_or(const { ItemsAndOptions::new_empty() }),
953 _ => ItemsAndOptions::new_empty(),
954 },
955 )
956 .flat_map(|items_and_options| items_and_options.iter_items())
957 }
958
959 pub(crate) fn to_pattern(self) -> DateTimePattern {
960 let pattern = self.iter_items().collect::<runtime::Pattern>();
961 DateTimePattern::from(pattern)
962 }
963 }
964
965 impl<'a> ItemsAndOptions<'a> {
966 pub(crate) fn iter_items(self) -> impl Iterator<Item = PatternItem> + 'a {
967 self.items.iter().map(move |mut pattern_item| {
968 #[expect(clippy::single_match)] // need `ref mut`, which doesn't work in `if let`?
969 match &mut pattern_item {
970 PatternItem::Field(field) => {
971 let alignment = self.alignment.unwrap_or_default();
972 if matches!(alignment, Alignment::Column)
973 && field.length == FieldLength::One
974 && matches!(
975 field.symbol,
976 FieldSymbol::Month(_)
977 | FieldSymbol::Day(_)
978 | FieldSymbol::Week(_)
979 | FieldSymbol::Hour(_)
980 )
981 {
982 field.length = FieldLength::Two;
983 }
984 if let Some(hour_cycle) = self.hour_cycle
985 && let FieldSymbol::Hour(_) = field.symbol
986 {
987 field.symbol = FieldSymbol::Hour(hour_cycle);
988 }
989 if let Some(subsecond_digits) = self.subsecond_digits
990 && matches!(
991 field.symbol,
992 FieldSymbol::Second(fields::Second::Second)
993 | FieldSymbol::DecimalSecond(_)
994 )
995 {
996 field.symbol = FieldSymbol::from_subsecond_digits(subsecond_digits);
997 }
998 }
999 _ => (),
1000 }
1001 pattern_item
1002 })
1003 }
1004 }