icu_datetime/pattern/names.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
5use super::{
6 DateTimePattern, DateTimePatternFormatter, GetNameForCyclicYearError, GetNameForDayPeriodError,
7 GetNameForEraError, GetNameForMonthError, GetNameForWeekdayError, MonthPlaceholderValue,
8 PatternLoadError, UnsupportedCalendarError,
9};
10use crate::FixedCalendarDateTimeFormatter;
11use crate::error::ErrorField;
12use crate::fieldsets::enums::{CompositeDateTimeFieldSet, CompositeFieldSet};
13use crate::provider::fields::{self, FieldLength, FieldSymbol};
14use crate::provider::names::*;
15use crate::provider::pattern::PatternItem;
16use crate::provider::semantic_skeletons::marker_attrs;
17use crate::provider::time_zones::tz;
18use crate::size_test_macro::size_test;
19use crate::{DateTimeFormatter, DateTimeFormatterLoadError, scaffold::*};
20use crate::{DateTimeFormatterPreferences, external_loaders::*};
21use core::fmt;
22use core::marker::PhantomData;
23use icu_calendar::AnyCalendar;
24use icu_calendar::types::{EraYear, LeapStatus, MonthInfo};
25use icu_decimal::DecimalFormatter;
26use icu_decimal::options::DecimalFormatterOptions;
27use icu_decimal::options::GroupingStrategy;
28use icu_decimal::provider::{DecimalDigitsV1, DecimalSymbolsV1};
29use icu_pattern::SinglePlaceholderPattern;
30use icu_provider::prelude::*;
31
32/// Choices for loading year names.
33#[derive(Debug, Copy, Clone, PartialEq, Eq)]
34#[non_exhaustive]
35pub enum YearNameLength {
36 /// An abbreviated calendar-dependent year or era name.
37 ///
38 /// Examples:
39 ///
40 /// - "AD"
41 /// - "甲子"
42 Abbreviated,
43 /// A wide calendar-dependent year or era name.
44 ///
45 /// Examples:
46 ///
47 /// - "Anno Domini"
48 /// - "甲子"
49 Wide,
50 /// A narrow calendar-dependent year or era name. Not necesarily unique.
51 ///
52 /// Examples:
53 ///
54 /// - "A"
55 /// - "甲子"
56 Narrow,
57}
58
59impl YearNameLength {
60 pub(crate) fn to_attributes(self) -> &'static DataMarkerAttributes {
61 use marker_attrs::Length;
62 let length = match self {
63 YearNameLength::Abbreviated => Length::Abbr,
64 YearNameLength::Wide => Length::Wide,
65 YearNameLength::Narrow => Length::Narrow,
66 };
67 marker_attrs::name_attr_for(marker_attrs::Context::Format, length)
68 }
69
70 pub(crate) fn from_field_length(field_length: FieldLength) -> Option<Self> {
71 // UTS 35 says that "G..GGG" and "U..UUU" are all Abbreviated
72 let field_length = field_length.numeric_to_abbr();
73 match field_length {
74 FieldLength::Three | FieldLength::NumericOverride(_) => {
75 Some(YearNameLength::Abbreviated)
76 }
77 FieldLength::Four => Some(YearNameLength::Wide),
78 FieldLength::Five => Some(YearNameLength::Narrow),
79 _ => None,
80 }
81 }
82
83 /// Returns an [`ErrorField`] sufficient for error reporting.
84 pub(crate) fn to_approximate_error_field(self) -> ErrorField {
85 let field_length = match self {
86 YearNameLength::Abbreviated => FieldLength::Three,
87 YearNameLength::Wide => FieldLength::Four,
88 YearNameLength::Narrow => FieldLength::Five,
89 };
90 ErrorField(fields::Field {
91 symbol: FieldSymbol::Era,
92 length: field_length,
93 })
94 }
95}
96
97/// Choices for loading month names.
98///
99/// This enum covers both the length (abbreviated, wide, or narrow)
100/// and the formatting context (format or standalone).
101#[derive(Debug, Copy, Clone, PartialEq, Eq)]
102#[non_exhaustive]
103pub enum MonthNameLength {
104 /// A numeric month for formatting with other fields.
105 ///
106 /// The data here are the leap patterns.
107 Numeric,
108 /// An abbreviated calendar-dependent month name for formatting with other fields.
109 ///
110 /// Example: "Sep"
111 Abbreviated,
112 /// A wide calendar-dependent month name for formatting with other fields.
113 ///
114 /// Example: "September"
115 Wide,
116 /// A narrow calendar-dependent month name for formatting with other fields. Not necesarily unique.
117 ///
118 /// Example: "S"
119 Narrow,
120 /// A numeric month for stand-alone display.
121 ///
122 /// The data here are the leap patterns.
123 StandaloneNumeric,
124 /// An abbreviated calendar-dependent month name for stand-alone display.
125 ///
126 /// Example: "Sep"
127 StandaloneAbbreviated,
128 /// A wide calendar-dependent month name for stand-alone display.
129 ///
130 /// Example: "September"
131 StandaloneWide,
132 /// A narrow calendar-dependent month name for stand-alone display. Not necesarily unique.
133 ///
134 /// Example: "S"
135 StandaloneNarrow,
136}
137
138impl MonthNameLength {
139 pub(crate) fn to_attributes(self) -> &'static DataMarkerAttributes {
140 use marker_attrs::{Context, Length};
141 let (context, length) = match self {
142 MonthNameLength::Numeric => (Context::Format, Length::Numeric),
143 MonthNameLength::Abbreviated => (Context::Format, Length::Abbr),
144 MonthNameLength::Wide => (Context::Format, Length::Wide),
145 MonthNameLength::Narrow => (Context::Format, Length::Narrow),
146 MonthNameLength::StandaloneAbbreviated => (Context::Standalone, Length::Abbr),
147 MonthNameLength::StandaloneWide => (Context::Standalone, Length::Wide),
148 MonthNameLength::StandaloneNarrow => (Context::Standalone, Length::Narrow),
149 MonthNameLength::StandaloneNumeric => (Context::Standalone, Length::Numeric),
150 };
151 marker_attrs::name_attr_for(context, length)
152 }
153
154 pub(crate) fn from_field(
155 field_symbol: fields::Month,
156 field_length: FieldLength,
157 ) -> Option<Self> {
158 use fields::Month;
159 match (field_symbol, field_length) {
160 (Month::Format, FieldLength::One | FieldLength::Two) => Some(MonthNameLength::Numeric),
161 (Month::Format, FieldLength::Three) => Some(MonthNameLength::Abbreviated),
162 (Month::Format, FieldLength::Four) => Some(MonthNameLength::Wide),
163 (Month::Format, FieldLength::Five) => Some(MonthNameLength::Narrow),
164 (Month::StandAlone, FieldLength::One | FieldLength::Two) => {
165 Some(MonthNameLength::StandaloneNumeric)
166 }
167 (Month::StandAlone, FieldLength::Three) => Some(MonthNameLength::StandaloneAbbreviated),
168 (Month::StandAlone, FieldLength::Four) => Some(MonthNameLength::StandaloneWide),
169 (Month::StandAlone, FieldLength::Five) => Some(MonthNameLength::StandaloneNarrow),
170 _ => None,
171 }
172 }
173
174 /// Returns an [`ErrorField`] sufficient for error reporting.
175 pub(crate) fn to_approximate_error_field(self) -> ErrorField {
176 use fields::Month;
177 let (field_symbol, field_length) = match self {
178 MonthNameLength::Numeric => (Month::Format, FieldLength::One),
179 MonthNameLength::Abbreviated => (Month::Format, FieldLength::Three),
180 MonthNameLength::Wide => (Month::Format, FieldLength::Four),
181 MonthNameLength::Narrow => (Month::Format, FieldLength::Five),
182 MonthNameLength::StandaloneAbbreviated => (Month::StandAlone, FieldLength::Three),
183 MonthNameLength::StandaloneWide => (Month::StandAlone, FieldLength::Four),
184 MonthNameLength::StandaloneNarrow => (Month::StandAlone, FieldLength::Five),
185 MonthNameLength::StandaloneNumeric => (Month::StandAlone, FieldLength::One),
186 };
187 ErrorField(fields::Field {
188 symbol: FieldSymbol::Month(field_symbol),
189 length: field_length,
190 })
191 }
192}
193
194/// Choices for loading weekday names.
195///
196/// This enum covers both the length (abbreviated, wide, narrow, or short)
197/// and the formatting context (format or standalone).
198#[derive(Debug, Copy, Clone, PartialEq, Eq)]
199#[non_exhaustive]
200pub enum WeekdayNameLength {
201 /// An abbreviated weekday name for formatting with other fields.
202 ///
203 /// Example: "Tue"
204 Abbreviated,
205 /// A wide weekday name for formatting with other fields.
206 ///
207 /// Example: "Tuesday"
208 Wide,
209 /// A narrow weekday name for formatting with other fields. Not necesarily unique.
210 ///
211 /// Example: "T"
212 Narrow,
213 /// A short weekday name for formatting with other fields.
214 ///
215 /// Example: "Tu"
216 Short,
217 /// An abbreviated weekday name for stand-alone display.
218 ///
219 /// Example: "Tue"
220 StandaloneAbbreviated,
221 /// A wide weekday name for stand-alone display.
222 ///
223 /// Example: "Tuesday"
224 StandaloneWide,
225 /// A narrow weekday name for stand-alone display. Not necesarily unique.
226 ///
227 /// Example: "T"
228 StandaloneNarrow,
229 /// A short weekday name for stand-alone display.
230 ///
231 /// Example: "Tu"
232 StandaloneShort,
233}
234
235impl WeekdayNameLength {
236 pub(crate) fn to_attributes(self) -> &'static DataMarkerAttributes {
237 use marker_attrs::{Context, Length};
238 // UTS 35 says that "e" and "E" have the same non-numeric names
239 let (context, length) = match self {
240 WeekdayNameLength::Abbreviated => (Context::Format, Length::Abbr),
241 WeekdayNameLength::Wide => (Context::Format, Length::Wide),
242 WeekdayNameLength::Narrow => (Context::Format, Length::Narrow),
243 WeekdayNameLength::Short => (Context::Format, Length::Short),
244 WeekdayNameLength::StandaloneAbbreviated => (Context::Standalone, Length::Abbr),
245 WeekdayNameLength::StandaloneWide => (Context::Standalone, Length::Wide),
246 WeekdayNameLength::StandaloneNarrow => (Context::Standalone, Length::Narrow),
247 WeekdayNameLength::StandaloneShort => (Context::Standalone, Length::Short),
248 };
249 marker_attrs::name_attr_for(context, length)
250 }
251
252 pub(crate) fn from_field(
253 field_symbol: fields::Weekday,
254 field_length: FieldLength,
255 ) -> Option<Self> {
256 use fields::Weekday;
257 // UTS 35 says that "e" and "E" have the same non-numeric names
258 let field_symbol = field_symbol.to_format_symbol();
259 // UTS 35 says that "E..EEE" are all Abbreviated
260 // However, this doesn't apply to "e" and "c".
261 let field_length = if matches!(field_symbol, Weekday::Format) {
262 field_length.numeric_to_abbr()
263 } else {
264 field_length
265 };
266 match (field_symbol, field_length) {
267 (Weekday::Format, FieldLength::Three) => Some(WeekdayNameLength::Abbreviated),
268 (Weekday::Format, FieldLength::Four) => Some(WeekdayNameLength::Wide),
269 (Weekday::Format, FieldLength::Five) => Some(WeekdayNameLength::Narrow),
270 (Weekday::Format, FieldLength::Six) => Some(WeekdayNameLength::Short),
271 (Weekday::StandAlone, FieldLength::Three) => {
272 Some(WeekdayNameLength::StandaloneAbbreviated)
273 }
274 (Weekday::StandAlone, FieldLength::Four) => Some(WeekdayNameLength::StandaloneWide),
275 (Weekday::StandAlone, FieldLength::Five) => Some(WeekdayNameLength::StandaloneNarrow),
276 (Weekday::StandAlone, FieldLength::Six) => Some(WeekdayNameLength::StandaloneShort),
277 _ => None,
278 }
279 }
280
281 /// Returns an [`ErrorField`] sufficient for error reporting.
282 pub(crate) fn to_approximate_error_field(self) -> ErrorField {
283 use fields::Weekday;
284 let (field_symbol, field_length) = match self {
285 WeekdayNameLength::Abbreviated => (Weekday::Format, FieldLength::Three),
286 WeekdayNameLength::Wide => (Weekday::Format, FieldLength::Four),
287 WeekdayNameLength::Narrow => (Weekday::Format, FieldLength::Five),
288 WeekdayNameLength::Short => (Weekday::Format, FieldLength::Six),
289 WeekdayNameLength::StandaloneAbbreviated => (Weekday::StandAlone, FieldLength::Three),
290 WeekdayNameLength::StandaloneWide => (Weekday::StandAlone, FieldLength::Four),
291 WeekdayNameLength::StandaloneNarrow => (Weekday::StandAlone, FieldLength::Five),
292 WeekdayNameLength::StandaloneShort => (Weekday::StandAlone, FieldLength::Six),
293 };
294 ErrorField(fields::Field {
295 symbol: FieldSymbol::Weekday(field_symbol),
296 length: field_length,
297 })
298 }
299}
300
301/// Choices for loading day period names.
302#[derive(Debug, Copy, Clone, PartialEq, Eq)]
303#[non_exhaustive]
304pub enum DayPeriodNameLength {
305 /// An abbreviated 12-hour day period name, including display names for 0h and 12h.
306 ///
307 /// Examples:
308 ///
309 /// - "AM"
310 /// - "mid."
311 Abbreviated,
312 /// A wide 12-hour day period name, including display names for 0h and 12h.
313 ///
314 /// The wide form may be the same as the abbreviated form if the "real" long form
315 /// (eg "ante meridiem") is not customarily used.
316 ///
317 /// Examples:
318 ///
319 /// - "AM"
320 /// - "mignight"
321 Wide,
322 /// An abbreviated 12-hour day period name, including display names for 0h and 12h.
323 ///
324 /// The narrow form must be unique, unlike some other fields.
325 ///
326 /// Examples:
327 ///
328 /// - "AM"
329 /// - "md"
330 Narrow,
331}
332
333impl DayPeriodNameLength {
334 pub(crate) fn to_attributes(self) -> &'static DataMarkerAttributes {
335 use marker_attrs::Length;
336 let length = match self {
337 DayPeriodNameLength::Abbreviated => Length::Abbr,
338 DayPeriodNameLength::Wide => Length::Wide,
339 DayPeriodNameLength::Narrow => Length::Narrow,
340 };
341 marker_attrs::name_attr_for(marker_attrs::Context::Format, length)
342 }
343
344 pub(crate) fn from_field(
345 field_symbol: fields::DayPeriod,
346 field_length: FieldLength,
347 ) -> Option<Self> {
348 use fields::DayPeriod;
349 // Names for 'a', 'b', and 'B' are stored in the same data marker
350 let field_symbol = match field_symbol {
351 DayPeriod::NoonMidnight | DayPeriod::Flexible => DayPeriod::AmPm,
352 other => other,
353 };
354 // UTS 35 says that "a..aaa" and "b..bbb" are all Abbreviated
355 let field_length = field_length.numeric_to_abbr();
356 match (field_symbol, field_length) {
357 (DayPeriod::AmPm, FieldLength::Three) => Some(DayPeriodNameLength::Abbreviated),
358 (DayPeriod::AmPm, FieldLength::Four) => Some(DayPeriodNameLength::Wide),
359 (DayPeriod::AmPm, FieldLength::Five) => Some(DayPeriodNameLength::Narrow),
360 _ => None,
361 }
362 }
363
364 /// Returns an [`ErrorField`] sufficient for error reporting.
365 pub(crate) fn to_approximate_error_field(self) -> ErrorField {
366 // Names for 'a' and 'b' are stored in the same data marker
367 let field_symbol = fields::DayPeriod::AmPm;
368 let field_length = match self {
369 DayPeriodNameLength::Abbreviated => FieldLength::Three,
370 DayPeriodNameLength::Wide => FieldLength::Four,
371 DayPeriodNameLength::Narrow => FieldLength::Five,
372 };
373 ErrorField(fields::Field {
374 symbol: FieldSymbol::DayPeriod(field_symbol),
375 length: field_length,
376 })
377 }
378}
379
380pub(crate) struct EmptyDataProvider;
381
382impl<M> DataProvider<M> for EmptyDataProvider
383where
384 M: DataMarker,
385{
386 fn load(&self, base_req: DataRequest) -> Result<DataResponse<M>, DataError> {
387 Err(DataErrorKind::MarkerNotFound.with_req(M::INFO, base_req))
388 }
389}
390
391size_test!(
392 FixedCalendarDateTimeNames<icu_calendar::Gregorian>,
393 typed_date_time_names_size,
394 328
395);
396
397/// A low-level type that formats datetime patterns with localized names.
398/// The calendar should be chosen at compile time.
399#[doc = typed_date_time_names_size!()]
400///
401/// Type parameters:
402///
403/// 1. The calendar chosen at compile time for additional type safety
404/// 2. A field set containing the fields that might be formatted
405///
406/// By default, the field set is set to [`CompositeDateTimeFieldSet`],
407/// meaning that dates and times, but not time zones, are supported. A smaller
408/// field set results in smaller stack size.
409///
410/// To support all fields including time zones, use [`CompositeFieldSet`].
411///
412/// [`CompositeFieldSet`]: crate::fieldsets::enums::CompositeFieldSet
413/// [`CompositeDateTimeFieldSet`]: crate::fieldsets::enums::CompositeDateTimeFieldSet
414///
415/// # Examples
416///
417/// ```
418/// use icu::calendar::Gregorian;
419/// use icu::datetime::input::Date;
420/// use icu::datetime::pattern::FixedCalendarDateTimeNames;
421/// use icu::datetime::pattern::DateTimePattern;
422/// use icu::datetime::pattern::MonthNameLength;
423/// use icu::datetime::pattern::WeekdayNameLength;
424/// use icu::datetime::pattern::DayPeriodNameLength;
425/// use icu::locale::locale;
426/// use icu::datetime::input::{DateTime, Time};
427/// use writeable::assert_try_writeable_eq;
428///
429/// // Create an instance that can format abbreviated month, weekday, and day period names:
430/// let mut names: FixedCalendarDateTimeNames<Gregorian> =
431/// FixedCalendarDateTimeNames::try_new(locale!("uk").into()).unwrap();
432/// names
433/// .include_month_names(MonthNameLength::Abbreviated)
434/// .unwrap()
435/// .include_weekday_names(WeekdayNameLength::Abbreviated)
436/// .unwrap()
437/// .include_day_period_names(DayPeriodNameLength::Abbreviated)
438/// .unwrap();
439///
440/// // Create a pattern from a pattern string (note: K is the hour with h11 hour cycle):
441/// let pattern_str = "E MMM d y -- K:mm a";
442/// let pattern: DateTimePattern = pattern_str.parse().unwrap();
443///
444/// // Test it:
445/// let datetime = DateTime { date: Date::try_new_gregorian(2023, 11, 20).unwrap(), time: Time::try_new(12, 35, 3, 0).unwrap() };
446/// assert_try_writeable_eq!(names.with_pattern_unchecked(&pattern).format(&datetime), "пн лист. 20 2023 -- 0:35 пп");
447/// ```
448///
449/// If the correct data is not loaded, an error will occur:
450///
451/// ```
452/// use icu::calendar::Gregorian;
453/// use icu::datetime::input::Date;
454/// use icu::datetime::pattern::FormattedDateTimePatternError;
455/// use icu::datetime::parts;
456/// use icu::datetime::pattern::FixedCalendarDateTimeNames;
457/// use icu::datetime::pattern::{DateTimePattern, PatternLoadError};
458/// use icu::datetime::fieldsets::enums::CompositeFieldSet;
459/// use icu::locale::locale;
460/// use icu::time::zone::IanaParser;
461/// use icu::datetime::input::{Time, TimeZoneInfo, ZonedDateTime};
462/// use icu_provider_adapters::empty::EmptyDataProvider;
463/// use writeable::{Part, assert_try_writeable_parts_eq};
464///
465/// // Unstable API used only for error construction below
466/// use icu::datetime::provider::fields::{Field, FieldLength, FieldSymbol, Weekday};
467///
468/// // Create an instance that can format all fields (CompositeFieldSet):
469/// let mut names: FixedCalendarDateTimeNames<Gregorian, CompositeFieldSet> =
470/// FixedCalendarDateTimeNames::try_new(locale!("en").into()).unwrap();
471///
472/// // Create a pattern from a pattern string:
473/// let pattern_str = "'It is:' E MMM d y G 'at' h:mm:ssSSS a zzzz";
474/// let pattern: DateTimePattern = pattern_str.parse().unwrap();
475///
476/// // The pattern string contains lots of symbols including "E", "MMM", and "a",
477/// // but we did not load any data!
478///
479/// let mut dtz = ZonedDateTime::try_strict_from_str("2023-11-20T11:35:03+00:00[Europe/London]", Gregorian, IanaParser::new()).unwrap();
480///
481/// // Missing data is filled in on a best-effort basis, and an error is signaled.
482/// assert_try_writeable_parts_eq!(
483/// names.with_pattern_unchecked(&pattern).format(&dtz),
484/// "It is: mon M11 20 2023 ce at 11:35:03.000 AM +0000",
485/// Err(FormattedDateTimePatternError::NamesNotLoaded(Field { symbol: FieldSymbol::Weekday(Weekday::Format), length: FieldLength::One }.into())),
486/// [
487/// (7, 10, Part::ERROR), // mon
488/// (7, 10, parts::WEEKDAY), // mon
489/// (11, 14, Part::ERROR), // M11
490/// (11, 14, parts::MONTH), // M11
491/// (15, 17, icu::decimal::parts::INTEGER), // 20
492/// (15, 17, parts::DAY), // 20
493/// (18, 22, icu::decimal::parts::INTEGER), // 2023
494/// (18, 22, parts::YEAR), // 2023
495/// (23, 25, Part::ERROR), // CE
496/// (23, 25, parts::ERA), // CE
497/// (29, 31, icu::decimal::parts::INTEGER), // 11
498/// (29, 31, parts::HOUR), // 11
499/// (32, 34, icu::decimal::parts::INTEGER), // 35
500/// (32, 34, parts::MINUTE), // 35
501/// (35, 41, parts::SECOND), // 03.000
502/// (35, 37, icu::decimal::parts::INTEGER), // 03
503/// (37, 38, icu::decimal::parts::DECIMAL), // .
504/// (38, 41, icu::decimal::parts::FRACTION), // 000
505/// (42, 44, Part::ERROR), // AM
506/// (42, 44, parts::DAY_PERIOD), // AM
507/// (45, 50, Part::ERROR), // +0000
508/// (45, 50, parts::TIME_ZONE_NAME), // +0000
509/// ]
510/// );
511///
512/// // To make the error occur sooner, one can use an EmptyDataProvider:
513/// let empty = EmptyDataProvider::new();
514/// assert!(matches!(
515/// names.load_for_pattern(&empty, &pattern),
516/// Err(PatternLoadError::Data(_, _)),
517/// ));
518/// ```
519///
520/// If the pattern contains fields inconsistent with the receiver, an error will occur:
521///
522/// ```
523/// use icu::calendar::Gregorian;
524/// use icu::datetime::pattern::FormattedDateTimePatternError;
525/// use icu::datetime::parts;
526/// use icu::datetime::pattern::FixedCalendarDateTimeNames;
527/// use icu::datetime::pattern::DateTimePattern;
528/// use icu::datetime::unchecked::MissingInputFieldKind;
529/// use icu::datetime::fieldsets::zone::LocalizedOffsetLong;
530/// use icu::locale::locale;
531/// use icu::datetime::input::{DateTime, TimeZoneInfo};
532/// use writeable::{Part, assert_try_writeable_parts_eq};
533///
534/// // Create an instance that can format abbreviated month, weekday, and day period names:
535/// let mut names: FixedCalendarDateTimeNames<Gregorian, LocalizedOffsetLong> =
536/// FixedCalendarDateTimeNames::try_new(locale!("en").into()).unwrap();
537///
538/// // Create a pattern from a pattern string:
539/// let pattern_str = "'It is:' E MMM d y G 'at' h:mm:ssSSS a zzzz";
540/// let pattern: DateTimePattern = pattern_str.parse().unwrap();
541///
542/// // The pattern string contains lots of symbols including "E", "MMM", and "a",
543/// // but the `FixedCalendarDateTimeNames` is configured to format only time zones!
544/// // Further, the time zone we provide doesn't contain any offset into!
545/// // Missing data is filled in on a best-effort basis, and an error is signaled.
546/// assert_try_writeable_parts_eq!(
547/// names.with_pattern_unchecked(&pattern).format(&TimeZoneInfo::unknown()),
548/// "It is: {E} {M} {d} {y} {G} at {h}:{m}:{s} {a} {z}",
549/// Err(FormattedDateTimePatternError::MissingInputField(MissingInputFieldKind::Weekday)),
550/// [
551/// (7, 10, Part::ERROR), // {E}
552/// (7, 10, parts::WEEKDAY), // {E}
553/// (11, 14, Part::ERROR), // {M}
554/// (11, 14, parts::MONTH), // {M}
555/// (15, 18, Part::ERROR), // {d}
556/// (15, 18, parts::DAY), // {d}
557/// (19, 22, Part::ERROR), // {y}
558/// (19, 22, parts::YEAR), // {y}
559/// (23, 26, Part::ERROR), // {G}
560/// (23, 26, parts::ERA), // {G}
561/// (30, 33, Part::ERROR), // {h}
562/// (30, 33, parts::HOUR), // {h}
563/// (34, 37, Part::ERROR), // {m}
564/// (34, 37, parts::MINUTE), // {m}
565/// (38, 41, Part::ERROR), // {s}
566/// (38, 41, parts::SECOND), // {s}
567/// (42, 45, Part::ERROR), // {a}
568/// (42, 45, parts::DAY_PERIOD), // {a}
569/// (46, 49, Part::ERROR), // {z}
570/// (46, 49, parts::TIME_ZONE_NAME), // {z}
571/// ]
572/// );
573/// ```
574///
575/// Multiple types of time zone data can be loaded into a [`FixedCalendarDateTimeNames`]:
576///
577/// ```
578/// use icu::datetime::pattern::FixedCalendarDateTimeNames;
579/// use icu::datetime::fieldsets::enums::ZoneFieldSet;
580/// use icu::locale::locale;
581/// use icu::datetime::input::{DateTime, Time};
582/// use writeable::assert_try_writeable_eq;
583///
584/// // Create an instance that can format abbreviated month, weekday, and day period names:
585/// let mut names: FixedCalendarDateTimeNames<(), ZoneFieldSet> =
586/// FixedCalendarDateTimeNames::try_new(locale!("uk").into()).unwrap();
587///
588/// // Load the names for generic short:
589/// names.include_time_zone_essentials().unwrap();
590/// names.include_time_zone_generic_short_names().unwrap();
591/// names.include_time_zone_location_names().unwrap();
592///
593/// // The same functions can be called a second time (nothing will happen):
594/// names.include_time_zone_essentials().unwrap();
595/// names.include_time_zone_generic_short_names().unwrap();
596/// names.include_time_zone_location_names().unwrap();
597///
598/// // We can load names for a different zone style:
599/// names.include_time_zone_generic_long_names().unwrap();
600/// ```
601///
602/// However, new time zone names cannot be added into a formatter that already has them. If you
603/// need this functionality, see <https://github.com/unicode-org/icu4x/issues/6063>
604///
605/// ```
606/// use icu::datetime::NoCalendarFormatter;
607/// use icu::datetime::fieldsets::enums::ZoneFieldSet;
608/// use icu::datetime::fieldsets::zone;
609/// use icu::datetime::pattern::FixedCalendarDateTimeNames;
610/// use icu::datetime::pattern::PatternLoadError;
611/// use icu::locale::locale;
612/// use icu_provider::DataError;
613/// use icu_provider::DataErrorKind;
614///
615/// let prefs = locale!("uk").into();
616///
617/// // Create a formatter for generic long time zones:
618/// let formatter =
619/// NoCalendarFormatter::try_new(prefs, zone::GenericLong).unwrap();
620///
621/// // Convert it to a FixedCalendarDateTimeNames:
622/// let mut names =
623/// FixedCalendarDateTimeNames::from_formatter(prefs, formatter)
624/// .cast_into_fset::<ZoneFieldSet>();
625///
626/// // Specific names cannot be added:
627/// assert!(matches!(
628/// names.include_time_zone_specific_long_names(),
629/// Err(PatternLoadError::Data(
630/// DataError {
631/// kind: DataErrorKind::InconsistentData(_),
632/// ..
633/// },
634/// _
635/// ))
636/// ));
637/// ```
638#[derive(Debug, Clone)]
639pub struct FixedCalendarDateTimeNames<C, FSet: DateTimeNamesMarker = CompositeDateTimeFieldSet> {
640 prefs: DateTimeFormatterPreferences,
641 inner: RawDateTimeNames<FSet>,
642 metadata: DateTimeNamesMetadata,
643 _calendar: PhantomData<C>,
644}
645
646/// Extra metadata associated with [`FixedCalendarDateTimeNames`] but not [`DateTimeFormatter`].
647#[derive(Debug, Clone)]
648pub(crate) struct DateTimeNamesMetadata {
649 zone_checksum: Option<u64>,
650}
651
652impl DateTimeNamesMetadata {
653 /// No impl Default: emphasize when we create a new empty instance
654 #[inline]
655 pub(crate) fn new_empty() -> Self {
656 Self {
657 zone_checksum: None,
658 }
659 }
660 /// If `mz_periods` is already populated, we can't load anything else because
661 /// we can't verify the checksum. Set a blank checksum in this case.
662 #[inline]
663 pub(crate) fn new_from_previous<M: DateTimeNamesMarker>(names: &RawDateTimeNames<M>) -> Self {
664 if names.mz_periods.get().inner.get_option().is_some() {
665 Self {
666 zone_checksum: Some(0),
667 }
668 } else {
669 Self::new_empty()
670 }
671 }
672}
673
674/// A low-level type that formats datetime patterns with localized names.
675/// The calendar is chosen in the constructor at runtime.
676///
677/// Currently this only supports loading of non-calendar-specific names, but
678/// additional functions may be added in the future. If you need this, see
679/// <https://github.com/unicode-org/icu4x/issues/6107>
680#[derive(Debug, Clone)]
681pub struct DateTimeNames<FSet: DateTimeNamesMarker> {
682 inner: FixedCalendarDateTimeNames<(), FSet>,
683 calendar: FormattableAnyCalendar,
684}
685
686pub(crate) struct RawDateTimeNames<FSet: DateTimeNamesMarker> {
687 year_names: <FSet::YearNames as NamesContainer<YearNamesV1, YearNameLength>>::Container,
688 month_names: <FSet::MonthNames as NamesContainer<MonthNamesV1, MonthNameLength>>::Container,
689 weekday_names:
690 <FSet::WeekdayNames as NamesContainer<WeekdayNamesV1, WeekdayNameLength>>::Container,
691 dayperiod_names:
692 <FSet::DayPeriodNames as NamesContainer<DayPeriodNamesV1, DayPeriodNameLength>>::Container,
693 zone_essentials: <FSet::ZoneEssentials as NamesContainer<tz::EssentialsV1, ()>>::Container,
694 locations_root: <FSet::ZoneLocationsRoot as NamesContainer<tz::LocationsRootV1, ()>>::Container,
695 locations: <FSet::ZoneLocations as NamesContainer<tz::LocationsOverrideV1, ()>>::Container,
696 exemplars_root: <FSet::ZoneExemplarsRoot as NamesContainer<tz::CitiesRootV1, ()>>::Container,
697 exemplars: <FSet::ZoneExemplars as NamesContainer<tz::CitiesOverrideV1, ()>>::Container,
698 mz_generic_long: <FSet::ZoneGenericLong as NamesContainer<tz::MzGenericLongV1, ()>>::Container,
699 mz_generic_short:
700 <FSet::ZoneGenericShort as NamesContainer<tz::MzGenericShortV1, ()>>::Container,
701 mz_standard_long:
702 <FSet::ZoneStandardLong as NamesContainer<tz::MzStandardLongV1, ()>>::Container,
703 mz_specific_long:
704 <FSet::ZoneSpecificLong as NamesContainer<tz::MzSpecificLongV1, ()>>::Container,
705 mz_specific_short:
706 <FSet::ZoneSpecificShort as NamesContainer<tz::MzSpecificShortV1, ()>>::Container,
707 mz_periods: <FSet::MetazoneLookup as NamesContainer<tz::MzPeriodV1, ()>>::Container,
708 // TODO(#4340): Make the DecimalFormatter optional
709 decimal_formatter: Option<DecimalFormatter>,
710 _marker: PhantomData<FSet>,
711}
712
713// Need a custom impl because not all of the associated types impl Debug
714impl<FSet: DateTimeNamesMarker> fmt::Debug for RawDateTimeNames<FSet> {
715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
716 f.debug_struct("RawDateTimeNames")
717 .field("year_names", &self.year_names)
718 .field("month_names", &self.month_names)
719 .field("weekday_names", &self.weekday_names)
720 .field("dayperiod_names", &self.dayperiod_names)
721 .field("zone_essentials", &self.zone_essentials)
722 .field("locations_root", &self.locations_root)
723 .field("locations", &self.locations)
724 .field("exemplars_root", &self.exemplars_root)
725 .field("exemplars", &self.exemplars)
726 .field("mz_generic_long", &self.mz_generic_long)
727 .field("mz_generic_short", &self.mz_generic_short)
728 .field("mz_standard_long", &self.mz_standard_long)
729 .field("mz_specific_long", &self.mz_specific_long)
730 .field("mz_specific_short", &self.mz_specific_short)
731 .field("mz_periods", &self.mz_periods)
732 .field("decimal_formatter", &self.decimal_formatter)
733 .finish()
734 }
735}
736
737impl<FSet: DateTimeNamesMarker> Clone for RawDateTimeNames<FSet> {
738 fn clone(&self) -> Self {
739 Self {
740 year_names: self.year_names.clone(),
741 month_names: self.month_names.clone(),
742 weekday_names: self.weekday_names.clone(),
743 dayperiod_names: self.dayperiod_names.clone(),
744 zone_essentials: self.zone_essentials.clone(),
745 locations_root: self.locations_root.clone(),
746 locations: self.locations.clone(),
747 exemplars_root: self.exemplars_root.clone(),
748 exemplars: self.exemplars.clone(),
749 mz_generic_long: self.mz_generic_long.clone(),
750 mz_generic_short: self.mz_generic_short.clone(),
751 mz_standard_long: self.mz_standard_long.clone(),
752 mz_specific_long: self.mz_specific_long.clone(),
753 mz_specific_short: self.mz_specific_short.clone(),
754 mz_periods: self.mz_periods.clone(),
755 decimal_formatter: self.decimal_formatter.clone(),
756 _marker: PhantomData,
757 }
758 }
759}
760
761impl<FSet: DateTimeNamesMarker> RawDateTimeNames<FSet> {
762 pub(crate) fn cast_into_fset<FSet2: DateTimeNamesFrom<FSet>>(self) -> RawDateTimeNames<FSet2> {
763 RawDateTimeNames {
764 year_names: FSet2::map_year_names(self.year_names),
765 month_names: FSet2::map_month_names(self.month_names),
766 weekday_names: FSet2::map_weekday_names(self.weekday_names),
767 dayperiod_names: FSet2::map_day_period_names(self.dayperiod_names),
768 zone_essentials: FSet2::map_zone_essentials(self.zone_essentials),
769 locations_root: FSet2::map_zone_locations_root(self.locations_root),
770 locations: FSet2::map_zone_locations(self.locations),
771 exemplars_root: FSet2::map_zone_exemplars_root(self.exemplars_root),
772 exemplars: FSet2::map_zone_exemplars(self.exemplars),
773 mz_generic_long: FSet2::map_zone_generic_long(self.mz_generic_long),
774 mz_generic_short: FSet2::map_zone_generic_short(self.mz_generic_short),
775 mz_standard_long: FSet2::map_zone_standard_long(self.mz_standard_long),
776 mz_specific_long: FSet2::map_zone_specific_long(self.mz_specific_long),
777 mz_specific_short: FSet2::map_zone_specific_short(self.mz_specific_short),
778 mz_periods: FSet2::map_metazone_lookup(self.mz_periods),
779 decimal_formatter: self.decimal_formatter,
780 _marker: PhantomData,
781 }
782 }
783}
784
785#[derive(Debug, Copy, Clone)]
786pub(crate) struct RawDateTimeNamesBorrowed<'l> {
787 year_names: OptionalNames<YearNameLength, &'l YearNames<'l>>,
788 month_names: OptionalNames<MonthNameLength, &'l MonthNames<'l>>,
789 weekday_names: OptionalNames<WeekdayNameLength, &'l WeekdayNames<'l>>,
790 dayperiod_names: OptionalNames<DayPeriodNameLength, &'l DayPeriodNames<'l>>,
791 zone_essentials: OptionalNames<(), &'l tz::Essentials<'l>>,
792 locations_root: OptionalNames<(), &'l tz::Locations<'l>>,
793 locations: OptionalNames<(), &'l tz::Locations<'l>>,
794 exemplars_root: OptionalNames<(), &'l tz::ExemplarCities<'l>>,
795 exemplars: OptionalNames<(), &'l tz::ExemplarCities<'l>>,
796 mz_generic_long: OptionalNames<(), &'l tz::MzGeneric<'l>>,
797 mz_standard_long: OptionalNames<(), &'l tz::MzGeneric<'l>>,
798 mz_generic_short: OptionalNames<(), &'l tz::MzGeneric<'l>>,
799 mz_specific_long: OptionalNames<(), &'l tz::MzSpecific<'l>>,
800 mz_specific_short: OptionalNames<(), &'l tz::MzSpecific<'l>>,
801 mz_periods: OptionalNames<(), &'l tz::MzPeriod<'l>>,
802 pub(crate) decimal_formatter: Option<&'l DecimalFormatter>,
803}
804
805impl<'l> RawDateTimeNamesBorrowed<'l> {
806 #[cfg(feature = "unstable")]
807 #[allow(dead_code)]
808 pub(crate) fn dayperiod_names(&self) -> Option<&'l DayPeriodNames<'l>> {
809 self.dayperiod_names.get_any()
810 }
811}
812
813impl<C, FSet: DateTimeNamesMarker> FixedCalendarDateTimeNames<C, FSet> {
814 /// Constructor that takes a selected locale and creates an empty instance.
815 ///
816 /// For an example, see [`FixedCalendarDateTimeNames`].
817 ///
818 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
819 ///
820 /// [📚 Help choosing a constructor](icu_provider::constructors)
821 #[cfg(feature = "compiled_data")]
822 pub fn try_new(prefs: DateTimeFormatterPreferences) -> Result<Self, DataError> {
823 let mut names = Self {
824 prefs,
825 inner: RawDateTimeNames::new_without_number_formatting(),
826 metadata: DateTimeNamesMetadata::new_empty(), // OK: this is a constructor
827 _calendar: PhantomData,
828 };
829 names.include_decimal_formatter()?;
830 Ok(names)
831 }
832
833 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
834 pub fn try_new_unstable<P>(
835 provider: &P,
836 prefs: DateTimeFormatterPreferences,
837 ) -> Result<Self, DataError>
838 where
839 P: DataProvider<DecimalSymbolsV1> + DataProvider<DecimalDigitsV1> + ?Sized,
840 {
841 let mut names = Self {
842 prefs,
843 inner: RawDateTimeNames::new_without_number_formatting(),
844 metadata: DateTimeNamesMetadata::new_empty(), // OK: this is a constructor
845 _calendar: PhantomData,
846 };
847 names.load_decimal_formatter(provider)?;
848 Ok(names)
849 }
850
851 icu_provider::gen_buffer_data_constructors!(
852 (prefs: DateTimeFormatterPreferences) -> error: DataError,
853 functions: [
854 try_new: skip,
855 try_new_with_buffer_provider,
856 try_new_unstable,
857 Self,
858 ]
859 );
860
861 /// Creates a completely empty instance, not even with number formatting.
862 ///
863 /// # Examples
864 ///
865 /// Errors occur if a number formatter is not loaded but one is required:
866 ///
867 /// ```
868 /// use icu::calendar::Gregorian;
869 /// use icu::datetime::input::Date;
870 /// use icu::datetime::parts;
871 /// use icu::datetime::pattern::FormattedDateTimePatternError;
872 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
873 /// use icu::datetime::pattern::DateTimePattern;
874 /// use icu::datetime::fieldsets::enums::DateFieldSet;
875 /// use icu::locale::locale;
876 /// use writeable::{Part, assert_try_writeable_parts_eq};
877 ///
878 /// // Create an instance that can format only date fields:
879 /// let names: FixedCalendarDateTimeNames<Gregorian, DateFieldSet> =
880 /// FixedCalendarDateTimeNames::new_without_number_formatting(locale!("en").into());
881 ///
882 /// // Create a pattern from a pattern string:
883 /// let pattern_str = "'It is:' y-MM-dd";
884 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
885 ///
886 /// // The pattern string contains lots of numeric symbols,
887 /// // but we did not load any data!
888 ///
889 /// let date = Date::try_new_gregorian(2024, 7, 1).unwrap();
890 ///
891 /// // Missing data is filled in on a best-effort basis, and an error is signaled.
892 /// // (note that the padding is ignored in this fallback mode)
893 /// assert_try_writeable_parts_eq!(
894 /// names.with_pattern_unchecked(&pattern).format(&date),
895 /// "It is: 2024-M07-01",
896 /// Err(FormattedDateTimePatternError::DecimalFormatterNotLoaded),
897 /// [
898 /// (7, 11, Part::ERROR), // 2024
899 /// (7, 11, parts::YEAR), // 2024
900 /// (12, 15, Part::ERROR), // M07
901 /// (12, 15, parts::MONTH), // M07
902 /// (16, 18, Part::ERROR), // 01
903 /// (16, 18, parts::DAY), // 01
904 /// ]
905 /// );
906 /// ```
907 pub fn new_without_number_formatting(prefs: DateTimeFormatterPreferences) -> Self {
908 Self {
909 prefs,
910 inner: RawDateTimeNames::new_without_number_formatting(),
911 metadata: DateTimeNamesMetadata::new_empty(), // OK: this is a constructor
912 _calendar: PhantomData,
913 }
914 }
915}
916
917impl<C: CldrCalendar, FSet: DateTimeNamesMarker> FixedCalendarDateTimeNames<C, FSet> {
918 /// Creates an instance with the names loaded in a [`FixedCalendarDateTimeFormatter`].
919 ///
920 /// This function requires passing in the [`DateTimeFormatterPreferences`] because it is not
921 /// retained in the formatter. Pass the same value or else unexpected behavior may occur.
922 ///
923 /// # Examples
924 ///
925 /// ```
926 /// use icu::datetime::input::Date;
927 /// use icu::datetime::input::{DateTime, Time};
928 /// use icu::datetime::FixedCalendarDateTimeFormatter;
929 /// use icu::datetime::fieldsets::{YMD, YMDT};
930 /// use icu::datetime::pattern::{FixedCalendarDateTimeNames, DayPeriodNameLength};
931 /// use icu::locale::locale;
932 /// use writeable::assert_writeable_eq;
933 ///
934 /// let prefs = locale!("es-MX").into();
935 ///
936 /// let formatter =
937 /// FixedCalendarDateTimeFormatter::try_new(
938 /// prefs,
939 /// YMD::long(),
940 /// )
941 /// .unwrap();
942 ///
943 /// assert_writeable_eq!(
944 /// formatter.format(&Date::try_new_gregorian(2025, 2, 13).unwrap()),
945 /// "13 de febrero de 2025"
946 /// );
947 ///
948 /// // Change the YMD formatter to a YMDT formatter, after loading day period names.
949 /// // This assumes that the locale uses Abbreviated names for the given semantic skeleton!
950 /// let mut names = FixedCalendarDateTimeNames::from_formatter(prefs, formatter).cast_into_fset::<YMDT>();
951 /// names.include_day_period_names(DayPeriodNameLength::Abbreviated).unwrap();
952 /// let formatter = names.try_into_formatter(YMD::long().with_time_hm()).unwrap();
953 ///
954 /// assert_writeable_eq!(
955 /// formatter.format(&DateTime {
956 /// date: Date::try_new_gregorian(2025, 2, 13).unwrap(),
957 /// time: Time::start_of_day(),
958 /// }),
959 /// "13 de febrero de 2025 a las 12:00 a.m."
960 /// );
961 /// ```
962 pub fn from_formatter(
963 prefs: DateTimeFormatterPreferences,
964 formatter: FixedCalendarDateTimeFormatter<C, FSet>,
965 ) -> Self {
966 let metadata = DateTimeNamesMetadata::new_from_previous(&formatter.names);
967 Self {
968 prefs,
969 inner: formatter.names,
970 metadata,
971 _calendar: PhantomData,
972 }
973 }
974
975 fn from_parts(
976 prefs: DateTimeFormatterPreferences,
977 parts: (RawDateTimeNames<FSet>, DateTimeNamesMetadata),
978 ) -> Self {
979 Self {
980 prefs,
981 inner: parts.0,
982 metadata: parts.1,
983 _calendar: PhantomData,
984 }
985 }
986}
987
988impl<C: CldrCalendar, FSet: DateTimeMarkers> FixedCalendarDateTimeNames<C, FSet>
989where
990 FSet::D: TypedDateDataMarkers<C>,
991 FSet::T: TimeMarkers,
992 FSet::Z: ZoneMarkers,
993 FSet: GetField<CompositeFieldSet>,
994{
995 /// Loads a pattern for the given field set with compiled data and returns a [`FixedCalendarDateTimeFormatter`].
996 ///
997 /// The names in the current [`FixedCalendarDateTimeNames`] _must_ be sufficient for the field set.
998 /// If not, the input object will be returned with an error.
999 ///
1000 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1001 ///
1002 /// [📚 Help choosing a constructor](icu_provider::constructors)
1003 ///
1004 /// # Examples
1005 ///
1006 /// ```
1007 /// use icu::datetime::fieldsets::T;
1008 /// use icu::datetime::input::Time;
1009 /// use icu::datetime::pattern::{
1010 /// DayPeriodNameLength, FixedCalendarDateTimeNames,
1011 /// };
1012 /// use icu::locale::locale;
1013 /// use writeable::assert_writeable_eq;
1014 ///
1015 /// let names =
1016 /// FixedCalendarDateTimeNames::<(), _>::new_without_number_formatting(
1017 /// locale!("es-MX").into(),
1018 /// );
1019 ///
1020 /// let field_set = T::hm();
1021 ///
1022 /// // Cannot convert yet: no names are loaded
1023 /// let mut names = names.try_into_formatter(field_set).unwrap_err().1;
1024 ///
1025 /// // Load the data we need:
1026 /// names
1027 /// .include_day_period_names(DayPeriodNameLength::Abbreviated)
1028 /// .unwrap();
1029 /// names.include_decimal_formatter().unwrap();
1030 ///
1031 /// // Now the conversion is successful:
1032 /// let formatter = names.try_into_formatter(field_set).unwrap();
1033 ///
1034 /// assert_writeable_eq!(formatter.format(&Time::start_of_day()), "12:00 a.m.");
1035 /// ```
1036 #[expect(clippy::result_large_err)] // returning self as the error
1037 #[cfg(feature = "compiled_data")]
1038 pub fn try_into_formatter(
1039 self,
1040 field_set: FSet,
1041 ) -> Result<FixedCalendarDateTimeFormatter<C, FSet>, (DateTimeFormatterLoadError, Self)>
1042 where
1043 crate::provider::Baked: AllFixedCalendarPatternDataMarkers<C, FSet>,
1044 {
1045 FixedCalendarDateTimeFormatter::try_new_internal_with_names(
1046 &crate::provider::Baked,
1047 &EmptyDataProvider,
1048 &ExternalLoaderUnstable(&EmptyDataProvider), // for decimals only
1049 self.prefs,
1050 field_set.get_field(),
1051 self.inner,
1052 self.metadata,
1053 )
1054 .map_err(|e| (e.0, Self::from_parts(self.prefs, e.1)))
1055 }
1056
1057 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_into_formatter)]
1058 #[expect(clippy::result_large_err)] // returning self as the error
1059 pub fn try_into_formatter_unstable<P>(
1060 self,
1061 provider: &P,
1062 field_set: FSet,
1063 ) -> Result<FixedCalendarDateTimeFormatter<C, FSet>, (DateTimeFormatterLoadError, Self)>
1064 where
1065 P: AllFixedCalendarPatternDataMarkers<C, FSet> + ?Sized,
1066 {
1067 FixedCalendarDateTimeFormatter::try_new_internal_with_names(
1068 provider,
1069 &EmptyDataProvider,
1070 &ExternalLoaderUnstable(&EmptyDataProvider), // for decimals only
1071 self.prefs,
1072 field_set.get_field(),
1073 self.inner,
1074 self.metadata,
1075 )
1076 .map_err(|e| (e.0, Self::from_parts(self.prefs, e.1)))
1077 }
1078
1079 #[doc = icu_provider::gen_buffer_unstable_docs!(BUFFER, Self::try_into_formatter)]
1080 #[expect(clippy::result_large_err)] // returning self as the error
1081 #[cfg(feature = "serde")]
1082 pub fn try_into_formatter_with_buffer_provider<P>(
1083 self,
1084 provider: &P,
1085 field_set: FSet,
1086 ) -> Result<FixedCalendarDateTimeFormatter<C, FSet>, (DateTimeFormatterLoadError, Self)>
1087 where
1088 P: BufferProvider + ?Sized,
1089 {
1090 FixedCalendarDateTimeFormatter::try_new_internal_with_names(
1091 &provider.as_deserializing(),
1092 &EmptyDataProvider,
1093 &ExternalLoaderUnstable(&EmptyDataProvider), // for decimals only
1094 self.prefs,
1095 field_set.get_field(),
1096 self.inner,
1097 self.metadata,
1098 )
1099 .map_err(|e| (e.0, Self::from_parts(self.prefs, e.1)))
1100 }
1101}
1102
1103impl<FSet: DateTimeNamesMarker> DateTimeNames<FSet> {
1104 /// Creates a completely empty instance, not even with number formatting,
1105 /// with the specified calendar.
1106 pub fn try_new_with_calendar_without_number_formatting(
1107 prefs: DateTimeFormatterPreferences,
1108 calendar: AnyCalendar,
1109 ) -> Result<Self, UnsupportedCalendarError> {
1110 let calendar = FormattableAnyCalendar::try_from_any_calendar(calendar)
1111 .map_err(|c| UnsupportedCalendarError { kind: c.kind() })?;
1112 Ok(Self {
1113 inner: FixedCalendarDateTimeNames::new_without_number_formatting(prefs),
1114 calendar,
1115 })
1116 }
1117
1118 /// Creates an instance with the names and calendar loaded in a [`DateTimeFormatter`].
1119 ///
1120 /// This function requires passing in the [`DateTimeFormatterPreferences`] because it is not
1121 /// retained in the formatter. Pass the same value or else unexpected behavior may occur.
1122 ///
1123 /// # Examples
1124 ///
1125 /// ```
1126 /// use icu::datetime::input::Date;
1127 /// use icu::datetime::input::{DateTime, Time};
1128 /// use icu::datetime::DateTimeFormatter;
1129 /// use icu::datetime::fieldsets::{YMD, YMDT};
1130 /// use icu::datetime::pattern::{DateTimeNames, DayPeriodNameLength};
1131 /// use icu::locale::locale;
1132 /// use writeable::assert_writeable_eq;
1133 ///
1134 /// let prefs = locale!("es-MX").into();
1135 ///
1136 /// let formatter =
1137 /// DateTimeFormatter::try_new(
1138 /// prefs,
1139 /// YMD::long(),
1140 /// )
1141 /// .unwrap();
1142 ///
1143 /// assert_writeable_eq!(
1144 /// formatter.format(&Date::try_new_iso(2025, 2, 13).unwrap()),
1145 /// "13 de febrero de 2025"
1146 /// );
1147 ///
1148 /// // Change the YMD formatter to a YMDT formatter, after loading day period names.
1149 /// // This assumes that the locale uses Abbreviated names for the given semantic skeleton!
1150 /// let mut names = DateTimeNames::from_formatter(prefs, formatter).cast_into_fset::<YMDT>();
1151 /// names.as_mut().include_day_period_names(DayPeriodNameLength::Abbreviated).unwrap();
1152 /// let formatter = names.try_into_formatter(YMD::long().with_time_hm()).unwrap();
1153 ///
1154 /// assert_writeable_eq!(
1155 /// formatter.format(&DateTime {
1156 /// date: Date::try_new_iso(2025, 2, 13).unwrap(),
1157 /// time: Time::start_of_day(),
1158 /// }),
1159 /// "13 de febrero de 2025 a las 12:00 a.m."
1160 /// );
1161 /// ```
1162 pub fn from_formatter(
1163 prefs: DateTimeFormatterPreferences,
1164 formatter: DateTimeFormatter<FSet>,
1165 ) -> Self {
1166 let metadata = DateTimeNamesMetadata::new_from_previous(&formatter.names);
1167 Self::from_parts(prefs, (formatter.calendar, formatter.names, metadata))
1168 }
1169
1170 fn from_parts(
1171 prefs: DateTimeFormatterPreferences,
1172 parts: (
1173 FormattableAnyCalendar,
1174 RawDateTimeNames<FSet>,
1175 DateTimeNamesMetadata,
1176 ),
1177 ) -> Self {
1178 Self {
1179 inner: FixedCalendarDateTimeNames {
1180 prefs,
1181 inner: parts.1,
1182 metadata: parts.2,
1183 _calendar: PhantomData,
1184 },
1185 calendar: parts.0,
1186 }
1187 }
1188}
1189
1190impl<FSet: DateTimeMarkers> DateTimeNames<FSet>
1191where
1192 FSet::D: DateDataMarkers,
1193 FSet::T: TimeMarkers,
1194 FSet::Z: ZoneMarkers,
1195 FSet: GetField<CompositeFieldSet>,
1196{
1197 /// Loads a pattern for the given field set with compiled data and returns a [`DateTimeFormatter`].
1198 ///
1199 /// The names in the current [`DateTimeNames`] _must_ be sufficient for the field set.
1200 /// If not, the input object will be returned with an error.
1201 ///
1202 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1203 ///
1204 /// [📚 Help choosing a constructor](icu_provider::constructors)
1205 ///
1206 /// # Examples
1207 ///
1208 /// ```
1209 /// use icu::calendar::{AnyCalendar, AnyCalendarKind};
1210 /// use icu::datetime::fieldsets::T;
1211 /// use icu::datetime::input::Time;
1212 /// use icu::datetime::pattern::{DateTimeNames, DayPeriodNameLength};
1213 /// use icu::locale::locale;
1214 /// use writeable::assert_writeable_eq;
1215 ///
1216 /// let kind = AnyCalendarKind::try_new(locale!("es-MX").into()).unwrap();
1217 /// let calendar = AnyCalendar::new(kind);
1218 ///
1219 /// let names = DateTimeNames::try_new_with_calendar_without_number_formatting(
1220 /// locale!("es-MX").into(),
1221 /// calendar,
1222 /// )
1223 /// .expect("All locale-default calendars are supported");
1224 ///
1225 /// let field_set = T::hm();
1226 ///
1227 /// // Cannot convert yet: no names are loaded
1228 /// let mut names = names.try_into_formatter(field_set).unwrap_err().1;
1229 ///
1230 /// // Load the data we need:
1231 /// names
1232 /// .as_mut()
1233 /// .include_day_period_names(DayPeriodNameLength::Abbreviated)
1234 /// .unwrap();
1235 /// names.as_mut().include_decimal_formatter().unwrap();
1236 ///
1237 /// // Now the conversion is successful:
1238 /// let formatter = names.try_into_formatter(field_set).unwrap();
1239 ///
1240 /// assert_writeable_eq!(formatter.format(&Time::start_of_day()), "12:00 a.m.");
1241 /// ```
1242 #[expect(clippy::result_large_err)] // returning self as the error
1243 #[cfg(feature = "compiled_data")]
1244 pub fn try_into_formatter(
1245 self,
1246 field_set: FSet,
1247 ) -> Result<DateTimeFormatter<FSet>, (DateTimeFormatterLoadError, Self)>
1248 where
1249 crate::provider::Baked: AllAnyCalendarPatternDataMarkers<FSet>,
1250 {
1251 DateTimeFormatter::try_new_internal_with_calendar_and_names(
1252 &crate::provider::Baked,
1253 &EmptyDataProvider,
1254 &ExternalLoaderUnstable(&EmptyDataProvider), // for decimals only
1255 self.inner.prefs,
1256 field_set.get_field(),
1257 self.calendar,
1258 self.inner.inner,
1259 self.inner.metadata,
1260 )
1261 .map_err(|e| (e.0, Self::from_parts(self.inner.prefs, e.1)))
1262 }
1263
1264 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_into_formatter)]
1265 #[expect(clippy::result_large_err)] // returning self as the error
1266 pub fn try_into_formatter_unstable<P>(
1267 self,
1268 provider: &P,
1269 field_set: FSet,
1270 ) -> Result<DateTimeFormatter<FSet>, (DateTimeFormatterLoadError, Self)>
1271 where
1272 P: AllAnyCalendarPatternDataMarkers<FSet> + ?Sized,
1273 {
1274 DateTimeFormatter::try_new_internal_with_calendar_and_names(
1275 provider,
1276 &EmptyDataProvider,
1277 &ExternalLoaderUnstable(&EmptyDataProvider), // for decimals only
1278 self.inner.prefs,
1279 field_set.get_field(),
1280 self.calendar,
1281 self.inner.inner,
1282 self.inner.metadata,
1283 )
1284 .map_err(|e| (e.0, Self::from_parts(self.inner.prefs, e.1)))
1285 }
1286
1287 #[doc = icu_provider::gen_buffer_unstable_docs!(BUFFER, Self::try_into_formatter)]
1288 #[expect(clippy::result_large_err)] // returning self as the error
1289 #[cfg(feature = "serde")]
1290 pub fn try_into_formatter_with_buffer_provider<P>(
1291 self,
1292 provider: &P,
1293 field_set: FSet,
1294 ) -> Result<DateTimeFormatter<FSet>, (DateTimeFormatterLoadError, Self)>
1295 where
1296 P: BufferProvider + ?Sized,
1297 {
1298 DateTimeFormatter::try_new_internal_with_calendar_and_names(
1299 &provider.as_deserializing(),
1300 &EmptyDataProvider,
1301 &ExternalLoaderUnstable(&EmptyDataProvider), // for decimals only
1302 self.inner.prefs,
1303 field_set.get_field(),
1304 self.calendar,
1305 self.inner.inner,
1306 self.inner.metadata,
1307 )
1308 .map_err(|e| (e.0, Self::from_parts(self.inner.prefs, e.1)))
1309 }
1310}
1311
1312impl<FSet: DateTimeNamesMarker> AsRef<FixedCalendarDateTimeNames<(), FSet>>
1313 for DateTimeNames<FSet>
1314{
1315 fn as_ref(&self) -> &FixedCalendarDateTimeNames<(), FSet> {
1316 &self.inner
1317 }
1318}
1319
1320impl<FSet: DateTimeNamesMarker> AsMut<FixedCalendarDateTimeNames<(), FSet>>
1321 for DateTimeNames<FSet>
1322{
1323 fn as_mut(&mut self) -> &mut FixedCalendarDateTimeNames<(), FSet> {
1324 &mut self.inner
1325 }
1326}
1327
1328impl<C: CldrCalendar, FSet: DateTimeNamesMarker> FixedCalendarDateTimeNames<C, FSet> {
1329 /// Loads year (era or cycle) names for the specified length.
1330 ///
1331 /// Does not support multiple field symbols or lengths. See [#4337](https://github.com/unicode-org/icu4x/issues/4337)
1332 pub fn load_year_names<P>(
1333 &mut self,
1334 provider: &P,
1335 length: YearNameLength,
1336 ) -> Result<&mut Self, PatternLoadError>
1337 where
1338 P: DataProvider<C::YearNamesV1> + ?Sized,
1339 {
1340 self.inner.load_year_names(
1341 &C::YearNamesV1::bind(provider),
1342 self.prefs,
1343 length,
1344 length.to_approximate_error_field(),
1345 )?;
1346 Ok(self)
1347 }
1348
1349 /// Includes year (era or cycle) names for the specified length with compiled data.
1350 ///
1351 /// Does not support multiple field symbols or lengths. See [#4337](https://github.com/unicode-org/icu4x/issues/4337)
1352 ///
1353 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1354 ///
1355 /// # Examples
1356 ///
1357 /// ```
1358 /// use icu::calendar::Gregorian;
1359 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
1360 /// use icu::datetime::pattern::PatternLoadError;
1361 /// use icu::datetime::pattern::YearNameLength;
1362 /// use icu::locale::locale;
1363 ///
1364 /// let mut names =
1365 /// FixedCalendarDateTimeNames::<Gregorian>::try_new(locale!("und").into())
1366 /// .unwrap();
1367 ///
1368 /// // First length is successful:
1369 /// names.include_year_names(YearNameLength::Wide).unwrap();
1370 ///
1371 /// // Attempting to load the first length a second time will succeed:
1372 /// names.include_year_names(YearNameLength::Wide).unwrap();
1373 ///
1374 /// // But loading a new length fails:
1375 /// assert!(matches!(
1376 /// names.include_year_names(YearNameLength::Abbreviated),
1377 /// Err(PatternLoadError::ConflictingField { .. })
1378 /// ));
1379 /// ```
1380 #[cfg(feature = "compiled_data")]
1381 pub fn include_year_names(
1382 &mut self,
1383 length: YearNameLength,
1384 ) -> Result<&mut Self, PatternLoadError>
1385 where
1386 crate::provider::Baked: DataProvider<<C as CldrCalendar>::YearNamesV1>,
1387 {
1388 self.load_year_names(&crate::provider::Baked, length)
1389 }
1390
1391 /// Loads month names for the specified symbol and length.
1392 ///
1393 /// Does not support multiple field symbols or lengths. See [#4337](https://github.com/unicode-org/icu4x/issues/4337)
1394 pub fn load_month_names<P>(
1395 &mut self,
1396 provider: &P,
1397 length: MonthNameLength,
1398 ) -> Result<&mut Self, PatternLoadError>
1399 where
1400 P: DataProvider<C::MonthNamesV1> + ?Sized,
1401 {
1402 self.inner.load_month_names(
1403 &C::MonthNamesV1::bind(provider),
1404 self.prefs,
1405 length,
1406 length.to_approximate_error_field(),
1407 )?;
1408 Ok(self)
1409 }
1410
1411 /// Includes month names for the specified symbol and length with compiled data.
1412 ///
1413 /// Does not support multiple field symbols or lengths. See [#4337](https://github.com/unicode-org/icu4x/issues/4337)
1414 ///
1415 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1416 ///
1417 /// # Examples
1418 ///
1419 /// ```
1420 /// use icu::calendar::Gregorian;
1421 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
1422 /// use icu::datetime::pattern::MonthNameLength;
1423 /// use icu::datetime::pattern::PatternLoadError;
1424 /// use icu::locale::locale;
1425 ///
1426 /// let mut names =
1427 /// FixedCalendarDateTimeNames::<Gregorian>::try_new(locale!("und").into())
1428 /// .unwrap();
1429 ///
1430 /// // First length is successful:
1431 /// names.include_month_names(MonthNameLength::Wide).unwrap();
1432 ///
1433 /// // Attempting to load the first length a second time will succeed:
1434 /// names.include_month_names(MonthNameLength::Wide).unwrap();
1435 ///
1436 /// // But loading a new symbol or length fails:
1437 /// assert!(matches!(
1438 /// names.include_month_names(MonthNameLength::StandaloneWide),
1439 /// Err(PatternLoadError::ConflictingField { .. })
1440 /// ));
1441 /// assert!(matches!(
1442 /// names.include_month_names(MonthNameLength::Abbreviated),
1443 /// Err(PatternLoadError::ConflictingField { .. })
1444 /// ));
1445 /// ```
1446 #[cfg(feature = "compiled_data")]
1447 pub fn include_month_names(
1448 &mut self,
1449 length: MonthNameLength,
1450 ) -> Result<&mut Self, PatternLoadError>
1451 where
1452 crate::provider::Baked: DataProvider<<C as CldrCalendar>::MonthNamesV1>,
1453 {
1454 self.load_month_names(&crate::provider::Baked, length)
1455 }
1456}
1457
1458impl<C, FSet: DateTimeNamesMarker> FixedCalendarDateTimeNames<C, FSet> {
1459 /// Loads day period names for the specified length.
1460 ///
1461 /// Does not support multiple field symbols or lengths. See [#4337](https://github.com/unicode-org/icu4x/issues/4337)
1462 pub fn load_day_period_names<P>(
1463 &mut self,
1464 provider: &P,
1465 length: DayPeriodNameLength,
1466 ) -> Result<&mut Self, PatternLoadError>
1467 where
1468 P: DataProvider<DayPeriodNamesV1> + ?Sized,
1469 {
1470 let provider = DayPeriodNamesV1::bind(provider);
1471 self.inner.load_day_period_names(
1472 &provider,
1473 self.prefs,
1474 length,
1475 length.to_approximate_error_field(),
1476 )?;
1477 Ok(self)
1478 }
1479
1480 /// Includes day period names for the specified length with compiled data.
1481 ///
1482 /// Does not support multiple field symbols or lengths. See [#4337](https://github.com/unicode-org/icu4x/issues/4337)
1483 ///
1484 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1485 ///
1486 /// # Examples
1487 ///
1488 /// ```
1489 /// use icu::calendar::Gregorian;
1490 /// use icu::datetime::pattern::DayPeriodNameLength;
1491 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
1492 /// use icu::datetime::pattern::PatternLoadError;
1493 /// use icu::locale::locale;
1494 ///
1495 /// let mut names =
1496 /// FixedCalendarDateTimeNames::<Gregorian>::try_new(locale!("und").into())
1497 /// .unwrap();
1498 ///
1499 /// // First length is successful:
1500 /// names
1501 /// .include_day_period_names(DayPeriodNameLength::Wide)
1502 /// .unwrap();
1503 ///
1504 /// // Attempting to load the first length a second time will succeed:
1505 /// names
1506 /// .include_day_period_names(DayPeriodNameLength::Wide)
1507 /// .unwrap();
1508 ///
1509 /// // But loading a new length fails:
1510 /// assert!(matches!(
1511 /// names.include_day_period_names(DayPeriodNameLength::Abbreviated),
1512 /// Err(PatternLoadError::ConflictingField { .. })
1513 /// ));
1514 /// ```
1515 #[cfg(feature = "compiled_data")]
1516 pub fn include_day_period_names(
1517 &mut self,
1518 length: DayPeriodNameLength,
1519 ) -> Result<&mut Self, PatternLoadError> {
1520 self.load_day_period_names(&crate::provider::Baked, length)
1521 }
1522
1523 /// Loads weekday names for the specified symbol and length.
1524 ///
1525 /// Does not support multiple field symbols or lengths. See [#4337](https://github.com/unicode-org/icu4x/issues/4337)
1526 pub fn load_weekday_names<P>(
1527 &mut self,
1528 provider: &P,
1529 length: WeekdayNameLength,
1530 ) -> Result<&mut Self, PatternLoadError>
1531 where
1532 P: DataProvider<WeekdayNamesV1> + ?Sized,
1533 {
1534 self.inner.load_weekday_names(
1535 &WeekdayNamesV1::bind(provider),
1536 self.prefs,
1537 length,
1538 length.to_approximate_error_field(),
1539 )?;
1540 Ok(self)
1541 }
1542
1543 /// Includes weekday names for the specified symbol and length with compiled data.
1544 ///
1545 /// Does not support multiple field symbols or lengths. See [#4337](https://github.com/unicode-org/icu4x/issues/4337)
1546 ///
1547 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1548 ///
1549 /// # Examples
1550 ///
1551 /// ```
1552 /// use icu::calendar::Gregorian;
1553 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
1554 /// use icu::datetime::pattern::PatternLoadError;
1555 /// use icu::datetime::pattern::WeekdayNameLength;
1556 /// use icu::locale::locale;
1557 ///
1558 /// let mut names =
1559 /// FixedCalendarDateTimeNames::<Gregorian>::try_new(locale!("und").into())
1560 /// .unwrap();
1561 ///
1562 /// // First length is successful:
1563 /// names
1564 /// .include_weekday_names(WeekdayNameLength::Wide)
1565 /// .unwrap();
1566 ///
1567 /// // Attempting to load the first length a second time will succeed:
1568 /// names
1569 /// .include_weekday_names(WeekdayNameLength::Wide)
1570 /// .unwrap();
1571 ///
1572 /// // But loading a new symbol or length fails:
1573 /// assert!(matches!(
1574 /// names.include_weekday_names(WeekdayNameLength::StandaloneWide),
1575 /// Err(PatternLoadError::ConflictingField { .. })
1576 /// ));
1577 /// assert!(matches!(
1578 /// names.include_weekday_names(WeekdayNameLength::Abbreviated),
1579 /// Err(PatternLoadError::ConflictingField { .. })
1580 /// ));
1581 /// ```
1582 #[cfg(feature = "compiled_data")]
1583 pub fn include_weekday_names(
1584 &mut self,
1585 length: WeekdayNameLength,
1586 ) -> Result<&mut Self, PatternLoadError> {
1587 self.load_weekday_names(&crate::provider::Baked, length)
1588 }
1589
1590 /// Loads shared essential patterns for time zone formatting.
1591 pub fn load_time_zone_essentials<P>(
1592 &mut self,
1593 provider: &P,
1594 ) -> Result<&mut Self, PatternLoadError>
1595 where
1596 P: DataProvider<tz::EssentialsV1> + ?Sized,
1597 {
1598 self.inner
1599 .load_time_zone_essentials(&tz::EssentialsV1::bind(provider), self.prefs)?;
1600 Ok(self)
1601 }
1602
1603 /// Includes shared essential patterns for time zone formatting with compiled data.
1604 ///
1605 /// This data should always be loaded when performing time zone formatting.
1606 /// By itself, it allows localized offset formats.
1607 ///
1608 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1609 ///
1610 /// # Examples
1611 ///
1612 /// ```
1613 /// use icu::calendar::Gregorian;
1614 /// use icu::datetime::fieldsets::enums::ZoneFieldSet;
1615 /// use icu::datetime::input::ZonedDateTime;
1616 /// use icu::datetime::pattern::DateTimePattern;
1617 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
1618 /// use icu::locale::locale;
1619 /// use icu::time::zone::IanaParser;
1620 /// use writeable::assert_try_writeable_eq;
1621 ///
1622 /// let mut zone_london_winter = ZonedDateTime::try_strict_from_str(
1623 /// "2024-01-01T00:00:00+00:00[Europe/London]",
1624 /// Gregorian,
1625 /// IanaParser::new(),
1626 /// )
1627 /// .unwrap()
1628 /// .zone;
1629 /// let mut zone_london_summer = ZonedDateTime::try_strict_from_str(
1630 /// "2024-07-01T00:00:00+01:00[Europe/London]",
1631 /// Gregorian,
1632 /// IanaParser::new(),
1633 /// )
1634 /// .unwrap()
1635 /// .zone;
1636 ///
1637 /// let mut names =
1638 /// FixedCalendarDateTimeNames::<Gregorian, ZoneFieldSet>::try_new(
1639 /// locale!("en-GB").into(),
1640 /// )
1641 /// .unwrap();
1642 ///
1643 /// names.include_time_zone_essentials().unwrap();
1644 ///
1645 /// // Create a pattern with symbol `OOOO`:
1646 /// let pattern_str = "'Your time zone is:' OOOO";
1647 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
1648 ///
1649 /// assert_try_writeable_eq!(
1650 /// names
1651 /// .with_pattern_unchecked(&pattern)
1652 /// .format(&zone_london_winter),
1653 /// "Your time zone is: GMT+00:00",
1654 /// );
1655 /// assert_try_writeable_eq!(
1656 /// names
1657 /// .with_pattern_unchecked(&pattern)
1658 /// .format(&zone_london_summer),
1659 /// "Your time zone is: GMT+01:00",
1660 /// );
1661 ///
1662 /// // Now try `V`:
1663 /// let pattern_str = "'Your time zone is:' V";
1664 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
1665 ///
1666 /// assert_try_writeable_eq!(
1667 /// names
1668 /// .with_pattern_unchecked(&pattern)
1669 /// .format(&zone_london_winter),
1670 /// "Your time zone is: gblon",
1671 /// );
1672 ///
1673 /// // Now try `Z`:
1674 /// let pattern_str = "'Your time zone is:' Z";
1675 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
1676 ///
1677 /// assert_try_writeable_eq!(
1678 /// names
1679 /// .with_pattern_unchecked(&pattern)
1680 /// .format(&zone_london_winter),
1681 /// "Your time zone is: +0000",
1682 /// );
1683 ///
1684 /// // Now try `ZZZZZ`:
1685 /// let pattern_str = "'Your time zone is:' ZZZZZ";
1686 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
1687 ///
1688 /// assert_try_writeable_eq!(
1689 /// names
1690 /// .with_pattern_unchecked(&pattern)
1691 /// .format(&zone_london_winter),
1692 /// "Your time zone is: Z",
1693 /// );
1694 /// assert_try_writeable_eq!(
1695 /// names
1696 /// .with_pattern_unchecked(&pattern)
1697 /// .format(&zone_london_summer),
1698 /// "Your time zone is: +01:00",
1699 /// );
1700 /// ```
1701 #[cfg(feature = "compiled_data")]
1702 pub fn include_time_zone_essentials(&mut self) -> Result<&mut Self, PatternLoadError> {
1703 self.load_time_zone_essentials(&crate::provider::Baked)
1704 }
1705
1706 /// Loads location names for time zone formatting.
1707 pub fn load_time_zone_location_names<P>(
1708 &mut self,
1709 provider: &P,
1710 ) -> Result<&mut Self, PatternLoadError>
1711 where
1712 P: DataProvider<tz::LocationsOverrideV1> + DataProvider<tz::LocationsRootV1> + ?Sized,
1713 {
1714 self.inner.load_time_zone_location_names(
1715 &tz::LocationsOverrideV1::bind(provider),
1716 &tz::LocationsRootV1::bind(provider),
1717 self.prefs,
1718 )?;
1719 Ok(self)
1720 }
1721
1722 /// Includes location names for time zone formatting with compiled data.
1723 ///
1724 /// Important: When performing manual time zone data loading, in addition to the
1725 /// specific time zone format data, also call either:
1726 ///
1727 /// - [`FixedCalendarDateTimeNames::include_time_zone_essentials`]
1728 /// - [`FixedCalendarDateTimeNames::load_time_zone_essentials`]
1729 ///
1730 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1731 ///
1732 /// # Examples
1733 ///
1734 /// ```
1735 /// use icu::calendar::Gregorian;
1736 /// use icu::datetime::fieldsets::enums::ZoneFieldSet;
1737 /// use icu::datetime::input::ZonedDateTime;
1738 /// use icu::datetime::pattern::DateTimePattern;
1739 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
1740 /// use icu::locale::locale;
1741 /// use icu::time::zone::IanaParser;
1742 /// use writeable::assert_try_writeable_eq;
1743 ///
1744 /// let mut zone_london_winter = ZonedDateTime::try_strict_from_str(
1745 /// "2024-01-01T00:00:00+00:00[Europe/London]",
1746 /// Gregorian,
1747 /// IanaParser::new(),
1748 /// )
1749 /// .unwrap()
1750 /// .zone;
1751 ///
1752 /// let mut names =
1753 /// FixedCalendarDateTimeNames::<Gregorian, ZoneFieldSet>::try_new(
1754 /// locale!("en-GB").into(),
1755 /// )
1756 /// .unwrap();
1757 ///
1758 /// names.include_time_zone_essentials().unwrap();
1759 /// names.include_time_zone_location_names().unwrap();
1760 ///
1761 /// // Try `VVVV`:
1762 /// let pattern_str = "'Your time zone is:' VVVV";
1763 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
1764 ///
1765 /// assert_try_writeable_eq!(
1766 /// names
1767 /// .with_pattern_unchecked(&pattern)
1768 /// .format(&zone_london_winter),
1769 /// "Your time zone is: UK Time",
1770 /// );
1771 /// ```
1772 #[cfg(feature = "compiled_data")]
1773 pub fn include_time_zone_location_names(&mut self) -> Result<&mut Self, PatternLoadError> {
1774 self.load_time_zone_location_names(&crate::provider::Baked)
1775 }
1776
1777 /// Loads exemplar city names for time zone formatting.
1778 pub fn load_time_zone_exemplar_city_names<P>(
1779 &mut self,
1780 provider: &P,
1781 ) -> Result<&mut Self, PatternLoadError>
1782 where
1783 P: DataProvider<tz::CitiesOverrideV1> + DataProvider<tz::CitiesRootV1> + ?Sized,
1784 {
1785 self.inner.load_time_zone_exemplar_city_names(
1786 &tz::CitiesOverrideV1::bind(provider),
1787 &tz::CitiesRootV1::bind(provider),
1788 self.prefs,
1789 )?;
1790 Ok(self)
1791 }
1792
1793 /// Includes exemplar city names for time zone formatting with compiled data.
1794 ///
1795 /// Important: The `VVV` format requires location data in addition to exemplar
1796 /// city data. Also call either:
1797 ///
1798 /// - [`FixedCalendarDateTimeNames::include_time_zone_location_names`]
1799 /// - [`FixedCalendarDateTimeNames::load_time_zone_location_names`]
1800 ///
1801 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1802 ///
1803 /// # Examples
1804 ///
1805 /// ```
1806 /// use icu::calendar::Gregorian;
1807 /// use icu::datetime::fieldsets::enums::ZoneFieldSet;
1808 /// use icu::datetime::input::ZonedDateTime;
1809 /// use icu::datetime::pattern::DateTimePattern;
1810 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
1811 /// use icu::locale::locale;
1812 /// use icu::time::zone::IanaParser;
1813 /// use writeable::assert_try_writeable_eq;
1814 ///
1815 /// let mut zone_london_winter = ZonedDateTime::try_strict_from_str(
1816 /// "2024-01-01T00:00:00+00:00[Europe/London]",
1817 /// Gregorian,
1818 /// IanaParser::new(),
1819 /// )
1820 /// .unwrap()
1821 /// .zone;
1822 ///
1823 /// let mut names =
1824 /// FixedCalendarDateTimeNames::<Gregorian, ZoneFieldSet>::try_new(
1825 /// locale!("en-GB").into(),
1826 /// )
1827 /// .unwrap();
1828 ///
1829 /// names.include_time_zone_location_names().unwrap();
1830 /// names.include_time_zone_exemplar_city_names().unwrap();
1831 ///
1832 /// // Try `VVVV`:
1833 /// let pattern_str = "'Your time zone is:' VVV";
1834 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
1835 ///
1836 /// assert_try_writeable_eq!(
1837 /// names
1838 /// .with_pattern_unchecked(&pattern)
1839 /// .format(&zone_london_winter),
1840 /// "Your time zone is: London",
1841 /// );
1842 /// ```
1843 #[cfg(feature = "compiled_data")]
1844 pub fn include_time_zone_exemplar_city_names(&mut self) -> Result<&mut Self, PatternLoadError> {
1845 self.load_time_zone_exemplar_city_names(&crate::provider::Baked)
1846 }
1847
1848 /// Loads generic non-location long time zone names.
1849 // NOTE: If a buffer version of this fn is added in 2.x, it should use the CompatProvider
1850 pub fn load_time_zone_generic_long_names<P>(
1851 &mut self,
1852 provider: &P,
1853 ) -> Result<&mut Self, PatternLoadError>
1854 where
1855 P: DataProvider<tz::MzGenericLongV1>
1856 + DataProvider<tz::MzStandardLongV1>
1857 + DataProvider<tz::MzPeriodV1>
1858 + ?Sized,
1859 {
1860 self.inner.load_time_zone_generic_long_names(
1861 &tz::MzGenericLongV1::bind(provider),
1862 &tz::MzStandardLongV1::bind(provider),
1863 &tz::MzPeriodV1::bind(provider),
1864 self.prefs,
1865 &mut self.metadata,
1866 )?;
1867 Ok(self)
1868 }
1869
1870 /// Includes generic non-location long time zone names with compiled data.
1871 ///
1872 /// Important: When performing manual time zone data loading, in addition to the
1873 /// specific time zone format data, also call either:
1874 ///
1875 /// - [`FixedCalendarDateTimeNames::include_time_zone_essentials`]
1876 /// - [`FixedCalendarDateTimeNames::load_time_zone_essentials`]
1877 ///
1878 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1879 ///
1880 /// # Examples
1881 ///
1882 /// ```
1883 /// use icu::calendar::Gregorian;
1884 /// use icu::datetime::fieldsets::enums::ZoneFieldSet;
1885 /// use icu::datetime::input::ZonedDateTime;
1886 /// use icu::datetime::pattern::DateTimePattern;
1887 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
1888 /// use icu::locale::locale;
1889 /// use icu::time::zone::IanaParser;
1890 /// use writeable::assert_try_writeable_eq;
1891 ///
1892 /// let mut zone_berlin_winter = ZonedDateTime::try_strict_from_str(
1893 /// "2024-01-01T00:00:00+01:00[Europe/Berlin]",
1894 /// Gregorian,
1895 /// IanaParser::new(),
1896 /// )
1897 /// .unwrap()
1898 /// .zone;
1899 /// let mut zone_berlin_summer = ZonedDateTime::try_strict_from_str(
1900 /// "2024-07-01T00:00:00+02:00[Europe/Berlin]",
1901 /// Gregorian,
1902 /// IanaParser::new(),
1903 /// )
1904 /// .unwrap()
1905 /// .zone;
1906 ///
1907 /// let mut names =
1908 /// FixedCalendarDateTimeNames::<Gregorian, ZoneFieldSet>::try_new(
1909 /// locale!("en-GB").into(),
1910 /// )
1911 /// .unwrap();
1912 ///
1913 /// names.include_time_zone_essentials().unwrap();
1914 /// names.include_time_zone_generic_long_names().unwrap();
1915 /// names.include_time_zone_location_names().unwrap();
1916 ///
1917 /// // Create a pattern with symbol `vvvv`:
1918 /// let pattern_str = "'Your time zone is:' vvvv";
1919 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
1920 ///
1921 /// assert_try_writeable_eq!(
1922 /// names
1923 /// .with_pattern_unchecked(&pattern)
1924 /// .format(&zone_berlin_winter),
1925 /// "Your time zone is: Central European Time",
1926 /// );
1927 /// assert_try_writeable_eq!(
1928 /// names
1929 /// .with_pattern_unchecked(&pattern)
1930 /// .format(&zone_berlin_summer),
1931 /// "Your time zone is: Central European Time",
1932 /// );
1933 /// ```
1934 #[cfg(feature = "compiled_data")]
1935 pub fn include_time_zone_generic_long_names(&mut self) -> Result<&mut Self, PatternLoadError> {
1936 self.load_time_zone_generic_long_names(&crate::provider::Baked)
1937 }
1938
1939 /// Loads generic non-location short time zone names.
1940 // NOTE: If a buffer version of this fn is added in 2.x, it should use the CompatProvider
1941 pub fn load_time_zone_generic_short_names<P>(
1942 &mut self,
1943 provider: &P,
1944 ) -> Result<&mut Self, PatternLoadError>
1945 where
1946 P: DataProvider<tz::MzGenericShortV1> + DataProvider<tz::MzPeriodV1> + ?Sized,
1947 {
1948 self.inner.load_time_zone_generic_short_names(
1949 &tz::MzGenericShortV1::bind(provider),
1950 &tz::MzPeriodV1::bind(provider),
1951 self.prefs,
1952 &mut self.metadata,
1953 )?;
1954 Ok(self)
1955 }
1956
1957 /// Includes generic non-location short time zone names with compiled data.
1958 ///
1959 /// Important: When performing manual time zone data loading, in addition to the
1960 /// specific time zone format data, also call either:
1961 ///
1962 /// - [`FixedCalendarDateTimeNames::include_time_zone_essentials`]
1963 /// - [`FixedCalendarDateTimeNames::load_time_zone_essentials`]
1964 ///
1965 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
1966 ///
1967 /// # Examples
1968 ///
1969 /// ```
1970 /// use icu::calendar::Gregorian;
1971 /// use icu::datetime::fieldsets::enums::ZoneFieldSet;
1972 /// use icu::datetime::input::ZonedDateTime;
1973 /// use icu::datetime::pattern::DateTimePattern;
1974 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
1975 /// use icu::locale::locale;
1976 /// use icu::time::zone::IanaParser;
1977 /// use writeable::assert_try_writeable_eq;
1978 ///
1979 /// let mut zone_berlin_winter = ZonedDateTime::try_strict_from_str(
1980 /// "2024-01-01T00:00:00+01:00[Europe/Berlin]",
1981 /// Gregorian,
1982 /// IanaParser::new(),
1983 /// )
1984 /// .unwrap()
1985 /// .zone;
1986 /// let mut zone_berlin_summer = ZonedDateTime::try_strict_from_str(
1987 /// "2024-07-01T00:00:00+02:00[Europe/Berlin]",
1988 /// Gregorian,
1989 /// IanaParser::new(),
1990 /// )
1991 /// .unwrap()
1992 /// .zone;
1993 ///
1994 /// let mut names =
1995 /// FixedCalendarDateTimeNames::<Gregorian, ZoneFieldSet>::try_new(
1996 /// locale!("en-GB").into(),
1997 /// )
1998 /// .unwrap();
1999 ///
2000 /// names.include_time_zone_essentials().unwrap();
2001 /// names.include_time_zone_generic_short_names().unwrap();
2002 /// names.include_time_zone_location_names().unwrap();
2003 ///
2004 /// // Create a pattern with symbol `v`:
2005 /// let pattern_str = "'Your time zone is:' v";
2006 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
2007 ///
2008 /// assert_try_writeable_eq!(
2009 /// names
2010 /// .with_pattern_unchecked(&pattern)
2011 /// .format(&zone_berlin_winter),
2012 /// "Your time zone is: CET",
2013 /// );
2014 /// assert_try_writeable_eq!(
2015 /// names
2016 /// .with_pattern_unchecked(&pattern)
2017 /// .format(&zone_berlin_summer),
2018 /// "Your time zone is: CET",
2019 /// );
2020 /// ```
2021 #[cfg(feature = "compiled_data")]
2022 pub fn include_time_zone_generic_short_names(&mut self) -> Result<&mut Self, PatternLoadError> {
2023 self.load_time_zone_generic_short_names(&crate::provider::Baked)
2024 }
2025
2026 /// Loads specific non-location long time zone names.
2027 // NOTE: If a buffer version of this fn is added in 2.x, it should use the CompatProvider
2028 pub fn load_time_zone_specific_long_names<P>(
2029 &mut self,
2030 provider: &P,
2031 ) -> Result<&mut Self, PatternLoadError>
2032 where
2033 P: DataProvider<tz::MzSpecificLongV1>
2034 + DataProvider<tz::MzStandardLongV1>
2035 + DataProvider<tz::MzPeriodV1>
2036 + ?Sized,
2037 {
2038 self.inner.load_time_zone_specific_long_names(
2039 &tz::MzSpecificLongV1::bind(provider),
2040 &tz::MzStandardLongV1::bind(provider),
2041 &tz::MzPeriodV1::bind(provider),
2042 self.prefs,
2043 &mut self.metadata,
2044 )?;
2045 Ok(self)
2046 }
2047
2048 /// Includes specific non-location long time zone names with compiled data.
2049 ///
2050 /// Important: When performing manual time zone data loading, in addition to the
2051 /// specific time zone format data, also call either:
2052 ///
2053 /// - [`FixedCalendarDateTimeNames::include_time_zone_essentials`]
2054 /// - [`FixedCalendarDateTimeNames::load_time_zone_essentials`]
2055 ///
2056 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
2057 ///
2058 /// # Examples
2059 ///
2060 /// ```
2061 /// use icu::calendar::Gregorian;
2062 /// use icu::datetime::fieldsets::enums::ZoneFieldSet;
2063 /// use icu::datetime::input::ZonedDateTime;
2064 /// use icu::datetime::pattern::DateTimePattern;
2065 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
2066 /// use icu::locale::locale;
2067 /// use icu::time::zone::IanaParser;
2068 /// use writeable::assert_try_writeable_eq;
2069 ///
2070 /// let mut zone_london_winter = ZonedDateTime::try_strict_from_str(
2071 /// "2024-01-01T00:00:00+00:00[Europe/London]",
2072 /// Gregorian,
2073 /// IanaParser::new(),
2074 /// )
2075 /// .unwrap()
2076 /// .zone;
2077 /// let mut zone_london_summer = ZonedDateTime::try_strict_from_str(
2078 /// "2024-07-01T00:00:00+01:00[Europe/London]",
2079 /// Gregorian,
2080 /// IanaParser::new(),
2081 /// )
2082 /// .unwrap()
2083 /// .zone;
2084 ///
2085 /// let mut names =
2086 /// FixedCalendarDateTimeNames::<Gregorian, ZoneFieldSet>::try_new(
2087 /// locale!("en-GB").into(),
2088 /// )
2089 /// .unwrap();
2090 ///
2091 /// names.include_time_zone_essentials().unwrap();
2092 /// names.include_time_zone_specific_long_names().unwrap();
2093 ///
2094 /// // Create a pattern with symbol `zzzz`:
2095 /// let pattern_str = "'Your time zone is:' zzzz";
2096 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
2097 ///
2098 /// assert_try_writeable_eq!(
2099 /// names
2100 /// .with_pattern_unchecked(&pattern)
2101 /// .format(&zone_london_winter),
2102 /// "Your time zone is: Greenwich Mean Time",
2103 /// );
2104 /// assert_try_writeable_eq!(
2105 /// names
2106 /// .with_pattern_unchecked(&pattern)
2107 /// .format(&zone_london_summer),
2108 /// "Your time zone is: British Summer Time",
2109 /// );
2110 /// ```
2111 #[cfg(feature = "compiled_data")]
2112 pub fn include_time_zone_specific_long_names(&mut self) -> Result<&mut Self, PatternLoadError> {
2113 self.load_time_zone_specific_long_names(&crate::provider::Baked)
2114 }
2115
2116 /// Loads specific non-location short time zone names.
2117 // NOTE: If a buffer version of this fn is added in 2.x, it should use the CompatProvider
2118 pub fn load_time_zone_specific_short_names<P>(
2119 &mut self,
2120 provider: &P,
2121 ) -> Result<&mut Self, PatternLoadError>
2122 where
2123 P: DataProvider<tz::MzSpecificShortV1> + DataProvider<tz::MzPeriodV1> + ?Sized,
2124 {
2125 self.inner.load_time_zone_specific_short_names(
2126 &tz::MzSpecificShortV1::bind(provider),
2127 &tz::MzPeriodV1::bind(provider),
2128 self.prefs,
2129 &mut self.metadata,
2130 )?;
2131 Ok(self)
2132 }
2133
2134 /// Includes specific non-location short time zone names with compiled data.
2135 ///
2136 /// Important: When performing manual time zone data loading, in addition to the
2137 /// specific time zone format data, also call either:
2138 ///
2139 /// - [`FixedCalendarDateTimeNames::include_time_zone_essentials`]
2140 /// - [`FixedCalendarDateTimeNames::load_time_zone_essentials`]
2141 ///
2142 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
2143 ///
2144 /// # Examples
2145 ///
2146 /// ```
2147 /// use icu::calendar::Gregorian;
2148 /// use icu::datetime::fieldsets::enums::ZoneFieldSet;
2149 /// use icu::datetime::input::ZonedDateTime;
2150 /// use icu::datetime::pattern::DateTimePattern;
2151 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
2152 /// use icu::locale::locale;
2153 /// use icu::time::zone::IanaParser;
2154 /// use writeable::assert_try_writeable_eq;
2155 ///
2156 /// let mut zone_london_winter = ZonedDateTime::try_strict_from_str(
2157 /// "2024-01-01T00:00:00+00:00[Europe/London]",
2158 /// Gregorian,
2159 /// IanaParser::new(),
2160 /// )
2161 /// .unwrap()
2162 /// .zone;
2163 /// let mut zone_london_summer = ZonedDateTime::try_strict_from_str(
2164 /// "2024-07-01T00:00:00+01:00[Europe/London]",
2165 /// Gregorian,
2166 /// IanaParser::new(),
2167 /// )
2168 /// .unwrap()
2169 /// .zone;
2170 ///
2171 /// let mut names =
2172 /// FixedCalendarDateTimeNames::<Gregorian, ZoneFieldSet>::try_new(
2173 /// locale!("en-GB").into(),
2174 /// )
2175 /// .unwrap();
2176 ///
2177 /// names.include_time_zone_essentials().unwrap();
2178 /// names.include_time_zone_specific_short_names().unwrap();
2179 ///
2180 /// // Create a pattern with symbol `z`:
2181 /// let pattern_str = "'Your time zone is:' z";
2182 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
2183 ///
2184 /// assert_try_writeable_eq!(
2185 /// names
2186 /// .with_pattern_unchecked(&pattern)
2187 /// .format(&zone_london_winter),
2188 /// "Your time zone is: GMT",
2189 /// );
2190 /// assert_try_writeable_eq!(
2191 /// names
2192 /// .with_pattern_unchecked(&pattern)
2193 /// .format(&zone_london_summer),
2194 /// "Your time zone is: BST",
2195 /// );
2196 /// ```
2197 #[cfg(feature = "compiled_data")]
2198 pub fn include_time_zone_specific_short_names(
2199 &mut self,
2200 ) -> Result<&mut Self, PatternLoadError> {
2201 self.load_time_zone_specific_short_names(&crate::provider::Baked)
2202 }
2203
2204 /// Loads generic non-location short time zone names
2205 /// and all data required for its fallback formats.
2206 ///
2207 /// See [`GenericShort`](crate::fieldsets::zone::GenericShort)
2208 // NOTE: If a buffer version of this fn is added in 2.x, it should use the CompatProvider
2209 pub fn load_time_zone_generic_short_names_with_fallback<P>(
2210 &mut self,
2211 provider: &P,
2212 ) -> Result<&mut Self, PatternLoadError>
2213 where
2214 P: DataProvider<DecimalSymbolsV1>
2215 + DataProvider<DecimalDigitsV1>
2216 + DataProvider<tz::EssentialsV1>
2217 + DataProvider<tz::LocationsOverrideV1>
2218 + DataProvider<tz::LocationsRootV1>
2219 + DataProvider<tz::MzGenericShortV1>
2220 + DataProvider<tz::MzPeriodV1>
2221 + ?Sized,
2222 {
2223 let error_field = self.inner.load_time_zone_field_v_except_decimals(
2224 &tz::EssentialsV1::bind(provider),
2225 &tz::LocationsOverrideV1::bind(provider),
2226 &tz::LocationsRootV1::bind(provider),
2227 &tz::MzGenericShortV1::bind(provider),
2228 &tz::MzPeriodV1::bind(provider),
2229 self.prefs,
2230 &mut self.metadata,
2231 )?;
2232 self.load_decimal_formatter(provider)
2233 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2234 Ok(self)
2235 }
2236
2237 /// Includes generic non-location short time zone names
2238 /// and all data required for its fallback formats, with compiled data.
2239 ///
2240 /// See [`GenericShort`](crate::fieldsets::zone::GenericShort)
2241 ///
2242 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
2243 #[cfg(feature = "compiled_data")]
2244 pub fn include_time_zone_generic_short_names_with_fallback(
2245 &mut self,
2246 ) -> Result<&mut Self, PatternLoadError> {
2247 let error_field = self.inner.load_time_zone_field_v_except_decimals(
2248 &tz::EssentialsV1::bind(&crate::provider::Baked),
2249 &tz::LocationsOverrideV1::bind(&crate::provider::Baked),
2250 &tz::LocationsRootV1::bind(&crate::provider::Baked),
2251 &tz::MzGenericShortV1::bind(&crate::provider::Baked),
2252 &tz::MzPeriodV1::bind(&crate::provider::Baked),
2253 self.prefs,
2254 &mut self.metadata,
2255 )?;
2256 self.include_decimal_formatter()
2257 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2258 Ok(self)
2259 }
2260
2261 /// Loads generic non-location long time zone names
2262 /// and all data required for its fallback formats.
2263 ///
2264 /// See [`GenericLong`](crate::fieldsets::zone::GenericLong)
2265 // NOTE: If a buffer version of this fn is added in 2.x, it should use the CompatProvider
2266 pub fn load_time_zone_generic_long_names_with_fallback<P>(
2267 &mut self,
2268 provider: &P,
2269 ) -> Result<&mut Self, PatternLoadError>
2270 where
2271 P: DataProvider<DecimalSymbolsV1>
2272 + DataProvider<DecimalDigitsV1>
2273 + DataProvider<tz::EssentialsV1>
2274 + DataProvider<tz::LocationsOverrideV1>
2275 + DataProvider<tz::LocationsRootV1>
2276 + DataProvider<tz::MzGenericLongV1>
2277 + DataProvider<tz::MzStandardLongV1>
2278 + DataProvider<tz::MzPeriodV1>
2279 + ?Sized,
2280 {
2281 let error_field = self.inner.load_time_zone_field_vvvv_except_decimals(
2282 &tz::EssentialsV1::bind(provider),
2283 &tz::LocationsOverrideV1::bind(provider),
2284 &tz::LocationsRootV1::bind(provider),
2285 &tz::MzGenericLongV1::bind(provider),
2286 &tz::MzStandardLongV1::bind(provider),
2287 &tz::MzPeriodV1::bind(provider),
2288 self.prefs,
2289 &mut self.metadata,
2290 )?;
2291 self.load_decimal_formatter(provider)
2292 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2293 Ok(self)
2294 }
2295
2296 /// Includes generic non-location long time zone names
2297 /// and all data required for its fallback formats, with compiled data.
2298 ///
2299 /// See [`GenericLong`](crate::fieldsets::zone::GenericLong)
2300 ///
2301 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
2302 #[cfg(feature = "compiled_data")]
2303 pub fn include_time_zone_generic_long_names_with_fallback(
2304 &mut self,
2305 ) -> Result<&mut Self, PatternLoadError> {
2306 let error_field = self.inner.load_time_zone_field_vvvv_except_decimals(
2307 &tz::EssentialsV1::bind(&crate::provider::Baked),
2308 &tz::LocationsOverrideV1::bind(&crate::provider::Baked),
2309 &tz::LocationsRootV1::bind(&crate::provider::Baked),
2310 &tz::MzGenericLongV1::bind(&crate::provider::Baked),
2311 &tz::MzStandardLongV1::bind(&crate::provider::Baked),
2312 &tz::MzPeriodV1::bind(&crate::provider::Baked),
2313 self.prefs,
2314 &mut self.metadata,
2315 )?;
2316 self.include_decimal_formatter()
2317 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2318 Ok(self)
2319 }
2320
2321 /// Loads specific non-location short time zone names
2322 /// and all data required for its fallback formats
2323 /// except for decimal formatting.
2324 ///
2325 /// See [`SpecificShort`](crate::fieldsets::zone::SpecificShort)
2326 // NOTE: If a buffer version of this fn is added in 2.x, it should use the CompatProvider
2327 pub fn load_time_zone_specific_short_names_with_fallback<P>(
2328 &mut self,
2329 provider: &P,
2330 ) -> Result<&mut Self, PatternLoadError>
2331 where
2332 P: DataProvider<DecimalSymbolsV1>
2333 + DataProvider<DecimalDigitsV1>
2334 + DataProvider<tz::EssentialsV1>
2335 + DataProvider<tz::LocationsOverrideV1>
2336 + DataProvider<tz::LocationsRootV1>
2337 + DataProvider<tz::MzSpecificShortV1>
2338 + DataProvider<tz::MzPeriodV1>
2339 + ?Sized,
2340 {
2341 let error_field = self.inner.load_time_zone_field_z_except_decimals(
2342 &tz::EssentialsV1::bind(provider),
2343 &tz::MzSpecificShortV1::bind(provider),
2344 &tz::MzPeriodV1::bind(provider),
2345 self.prefs,
2346 &mut self.metadata,
2347 )?;
2348 self.load_decimal_formatter(provider)
2349 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2350 Ok(self)
2351 }
2352
2353 /// Includes specific non-location short time zone names
2354 /// and all data required for its fallback formats
2355 /// except for decimal formatting, with compiled data.
2356 ///
2357 /// See [`SpecificShort`](crate::fieldsets::zone::SpecificShort)
2358 ///
2359 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
2360 #[cfg(feature = "compiled_data")]
2361 pub fn include_time_zone_specific_short_names_with_fallback(
2362 &mut self,
2363 ) -> Result<&mut Self, PatternLoadError> {
2364 let error_field = self.inner.load_time_zone_field_z_except_decimals(
2365 &tz::EssentialsV1::bind(&crate::provider::Baked),
2366 &tz::MzSpecificShortV1::bind(&crate::provider::Baked),
2367 &tz::MzPeriodV1::bind(&crate::provider::Baked),
2368 self.prefs,
2369 &mut self.metadata,
2370 )?;
2371 self.include_decimal_formatter()
2372 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2373 Ok(self)
2374 }
2375
2376 /// Loads specific non-location long time zone names
2377 /// and all data required for its fallback formats
2378 /// except for decimal formatting.
2379 ///
2380 /// See [`SpecificLong`](crate::fieldsets::zone::SpecificLong)
2381 // NOTE: If a buffer version of this fn is added in 2.x, it should use the CompatProvider
2382 pub fn load_time_zone_specific_long_names_with_fallback<P>(
2383 &mut self,
2384 provider: &P,
2385 ) -> Result<&mut Self, PatternLoadError>
2386 where
2387 P: DataProvider<DecimalSymbolsV1>
2388 + DataProvider<DecimalDigitsV1>
2389 + DataProvider<tz::EssentialsV1>
2390 + DataProvider<tz::LocationsOverrideV1>
2391 + DataProvider<tz::LocationsRootV1>
2392 + DataProvider<tz::MzSpecificLongV1>
2393 + DataProvider<tz::MzStandardLongV1>
2394 + DataProvider<tz::MzPeriodV1>
2395 + ?Sized,
2396 {
2397 let error_field = self.inner.load_time_zone_field_zzzz_except_decimals(
2398 &tz::EssentialsV1::bind(provider),
2399 &tz::LocationsOverrideV1::bind(provider),
2400 &tz::LocationsRootV1::bind(provider),
2401 &tz::MzStandardLongV1::bind(provider),
2402 &tz::MzSpecificLongV1::bind(provider),
2403 &tz::MzPeriodV1::bind(provider),
2404 self.prefs,
2405 &mut self.metadata,
2406 )?;
2407 self.load_decimal_formatter(provider)
2408 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2409 Ok(self)
2410 }
2411
2412 /// Includes specific non-location long time zone names
2413 /// and all data required for its fallback formats
2414 /// except for decimal formatting, with compiled data.
2415 ///
2416 /// See [`SpecificLong`](crate::fieldsets::zone::SpecificLong)
2417 ///
2418 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
2419 #[cfg(feature = "compiled_data")]
2420 pub fn include_time_zone_specific_long_names_with_fallback(
2421 &mut self,
2422 ) -> Result<&mut Self, PatternLoadError> {
2423 let error_field = self.inner.load_time_zone_field_zzzz_except_decimals(
2424 &tz::EssentialsV1::bind(&crate::provider::Baked),
2425 &tz::LocationsOverrideV1::bind(&crate::provider::Baked),
2426 &tz::LocationsRootV1::bind(&crate::provider::Baked),
2427 &tz::MzStandardLongV1::bind(&crate::provider::Baked),
2428 &tz::MzSpecificLongV1::bind(&crate::provider::Baked),
2429 &tz::MzPeriodV1::bind(&crate::provider::Baked),
2430 self.prefs,
2431 &mut self.metadata,
2432 )?;
2433 self.include_decimal_formatter()
2434 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2435 Ok(self)
2436 }
2437
2438 /// Loads all data for short and long localized offset time zone formatting
2439 /// except for decimal formatting.
2440 ///
2441 /// See:
2442 ///
2443 /// - [`LocalizedOffsetShort`](crate::fieldsets::zone::LocalizedOffsetShort)
2444 /// - [`LocalizedOffsetLong`](crate::fieldsets::zone::LocalizedOffsetLong)
2445 pub fn load_time_zone_localized_offset_names_with_fallback<P>(
2446 &mut self,
2447 provider: &P,
2448 ) -> Result<&mut Self, PatternLoadError>
2449 where
2450 P: DataProvider<DecimalSymbolsV1>
2451 + DataProvider<DecimalDigitsV1>
2452 + DataProvider<tz::EssentialsV1>
2453 + ?Sized,
2454 {
2455 let error_field = self.inner.load_time_zone_field_O_except_decimals(
2456 &tz::EssentialsV1::bind(provider),
2457 self.prefs,
2458 )?;
2459 self.load_decimal_formatter(provider)
2460 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2461 Ok(self)
2462 }
2463
2464 /// Includes all data for short and long localized offset time zone formatting
2465 /// except for decimal formatting, with compiled data.
2466 ///
2467 /// See:
2468 ///
2469 /// - [`LocalizedOffsetShort`](crate::fieldsets::zone::LocalizedOffsetShort)
2470 /// - [`LocalizedOffsetLong`](crate::fieldsets::zone::LocalizedOffsetLong)
2471 ///
2472 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
2473 #[cfg(feature = "compiled_data")]
2474 pub fn include_time_zone_localized_offset_names_with_fallback(
2475 &mut self,
2476 ) -> Result<&mut Self, PatternLoadError> {
2477 let error_field = self.inner.load_time_zone_field_O_except_decimals(
2478 &tz::EssentialsV1::bind(&crate::provider::Baked),
2479 self.prefs,
2480 )?;
2481 self.include_decimal_formatter()
2482 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2483 Ok(self)
2484 }
2485
2486 /// Loads a [`DecimalFormatter`] from a data provider.
2487 #[inline]
2488 pub fn load_decimal_formatter<P>(&mut self, provider: &P) -> Result<&mut Self, DataError>
2489 where
2490 P: DataProvider<DecimalSymbolsV1> + DataProvider<DecimalDigitsV1> + ?Sized,
2491 {
2492 self.inner
2493 .load_decimal_formatter(&ExternalLoaderUnstable(provider), self.prefs)?;
2494 Ok(self)
2495 }
2496
2497 /// Loads a [`DecimalFormatter`] with compiled data.
2498 ///
2499 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
2500 ///
2501 /// # Examples
2502 ///
2503 /// ```
2504 /// use icu::datetime::fieldsets::enums::TimeFieldSet;
2505 /// use icu::datetime::input::Time;
2506 /// use icu::datetime::pattern::DateTimePattern;
2507 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
2508 /// use icu::locale::locale;
2509 /// use writeable::assert_try_writeable_eq;
2510 ///
2511 /// let mut names = FixedCalendarDateTimeNames::<(), TimeFieldSet>::try_new(
2512 /// locale!("bn").into(),
2513 /// )
2514 /// .unwrap();
2515 /// names.include_decimal_formatter();
2516 ///
2517 /// // Create a pattern for the time, which is all numbers
2518 /// let pattern_str = "'The current 24-hour time is:' HH:mm";
2519 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
2520 ///
2521 /// let time = Time::try_new(6, 40, 33, 0).unwrap();
2522 ///
2523 /// assert_try_writeable_eq!(
2524 /// names.with_pattern_unchecked(&pattern).format(&time),
2525 /// "The current 24-hour time is: ০৬:৪০",
2526 /// );
2527 /// ```
2528 #[cfg(feature = "compiled_data")]
2529 #[inline]
2530 pub fn include_decimal_formatter(&mut self) -> Result<&mut Self, DataError> {
2531 self.inner
2532 .load_decimal_formatter(&ExternalLoaderCompiledData, self.prefs)?;
2533 Ok(self)
2534 }
2535}
2536
2537impl<C: CldrCalendar, FSet: DateTimeNamesMarker> FixedCalendarDateTimeNames<C, FSet> {
2538 /// Associates this [`FixedCalendarDateTimeNames`] with a pattern
2539 /// without checking that all necessary data is loaded.
2540 ///
2541 /// Use this function if you know at compile time what fields your pattern contains.
2542 #[inline]
2543 pub fn with_pattern_unchecked<'l>(
2544 &'l self,
2545 pattern: &'l DateTimePattern,
2546 ) -> DateTimePatternFormatter<'l, C, FSet> {
2547 DateTimePatternFormatter::new(pattern.as_borrowed(), self.inner.as_borrowed())
2548 }
2549
2550 /// Associates this [`FixedCalendarDateTimeNames`] with a datetime pattern
2551 /// and loads all data required for that pattern.
2552 ///
2553 /// Does not duplicate textual field symbols. See [#4337](https://github.com/unicode-org/icu4x/issues/4337)
2554 // NOTE: If a buffer version of this fn is added in 2.x, it should use the CompatProvider
2555 pub fn load_for_pattern<'l, P>(
2556 &'l mut self,
2557 provider: &P,
2558 pattern: &'l DateTimePattern,
2559 ) -> Result<DateTimePatternFormatter<'l, C, FSet>, PatternLoadError>
2560 where
2561 P: DataProvider<C::YearNamesV1>
2562 + DataProvider<C::MonthNamesV1>
2563 + DataProvider<WeekdayNamesV1>
2564 + DataProvider<DayPeriodNamesV1>
2565 + DataProvider<tz::EssentialsV1>
2566 + DataProvider<tz::LocationsOverrideV1>
2567 + DataProvider<tz::LocationsRootV1>
2568 + DataProvider<tz::CitiesOverrideV1>
2569 + DataProvider<tz::CitiesRootV1>
2570 + DataProvider<tz::MzGenericLongV1>
2571 + DataProvider<tz::MzGenericShortV1>
2572 + DataProvider<tz::MzStandardLongV1>
2573 + DataProvider<tz::MzSpecificLongV1>
2574 + DataProvider<tz::MzSpecificShortV1>
2575 + DataProvider<tz::MzPeriodV1>
2576 + DataProvider<DecimalSymbolsV1>
2577 + DataProvider<DecimalDigitsV1>
2578 + ?Sized,
2579 {
2580 let locale = self.prefs;
2581 self.inner.load_for_pattern(
2582 &C::YearNamesV1::bind(provider),
2583 &C::MonthNamesV1::bind(provider),
2584 &WeekdayNamesV1::bind(provider),
2585 &DayPeriodNamesV1::bind(provider),
2586 &tz::EssentialsV1::bind(provider),
2587 &tz::LocationsRootV1::bind(provider),
2588 &tz::LocationsOverrideV1::bind(provider),
2589 &tz::CitiesRootV1::bind(provider),
2590 &tz::CitiesOverrideV1::bind(provider),
2591 &tz::MzGenericLongV1::bind(provider),
2592 &tz::MzGenericShortV1::bind(provider),
2593 &tz::MzStandardLongV1::bind(provider),
2594 &tz::MzSpecificLongV1::bind(provider),
2595 &tz::MzSpecificShortV1::bind(provider),
2596 &tz::MzPeriodV1::bind(provider),
2597 &ExternalLoaderUnstable(provider),
2598 locale,
2599 pattern.iter_items(),
2600 &mut self.metadata,
2601 )?;
2602 Ok(DateTimePatternFormatter::new(
2603 pattern.as_borrowed(),
2604 self.inner.as_borrowed(),
2605 ))
2606 }
2607
2608 /// Associates this [`FixedCalendarDateTimeNames`] with a pattern
2609 /// and includes all data required for that pattern, from compiled data.
2610 ///
2611 /// Does not support duplicate textual field symbols. See [#4337](https://github.com/unicode-org/icu4x/issues/4337)
2612 ///
2613 /// ✨ *Enabled with the `compiled_data` Cargo feature.*
2614 ///
2615 /// # Examples
2616 ///
2617 /// ```
2618 /// use icu::calendar::Gregorian;
2619 /// use icu::datetime::input::Date;
2620 /// use icu::datetime::input::{DateTime, Time};
2621 /// use icu::datetime::pattern::DateTimePattern;
2622 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
2623 /// use icu::locale::locale;
2624 /// use writeable::assert_try_writeable_eq;
2625 ///
2626 /// let mut names =
2627 /// FixedCalendarDateTimeNames::<Gregorian>::try_new(locale!("en").into())
2628 /// .unwrap();
2629 ///
2630 /// // Create a pattern from a pattern string:
2631 /// let pattern_str = "MMM d (EEEE) 'of year' y G 'at' h:mm a";
2632 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
2633 ///
2634 /// // Load data for the pattern and format:
2635 /// let datetime = DateTime {
2636 /// date: Date::try_new_gregorian(2023, 12, 5).unwrap(),
2637 /// time: Time::try_new(17, 43, 12, 0).unwrap(),
2638 /// };
2639 /// assert_try_writeable_eq!(
2640 /// names
2641 /// .include_for_pattern(&pattern)
2642 /// .unwrap()
2643 /// .format(&datetime),
2644 /// "Dec 5 (Tuesday) of year 2023 AD at 5:43 PM"
2645 /// );
2646 /// ```
2647 #[cfg(feature = "compiled_data")]
2648 pub fn include_for_pattern<'l>(
2649 &'l mut self,
2650 pattern: &'l DateTimePattern,
2651 ) -> Result<DateTimePatternFormatter<'l, C, FSet>, PatternLoadError>
2652 where
2653 crate::provider::Baked: DataProvider<C::YearNamesV1> + DataProvider<C::MonthNamesV1>,
2654 crate::provider::Baked: DataProvider<C::YearNamesV1> + DataProvider<C::MonthNamesV1>,
2655 {
2656 let locale = self.prefs;
2657 self.inner.load_for_pattern(
2658 &C::YearNamesV1::bind(&crate::provider::Baked),
2659 &C::MonthNamesV1::bind(&crate::provider::Baked),
2660 &WeekdayNamesV1::bind(&crate::provider::Baked),
2661 &DayPeriodNamesV1::bind(&crate::provider::Baked),
2662 &tz::EssentialsV1::bind(&crate::provider::Baked),
2663 &tz::LocationsOverrideV1::bind(&crate::provider::Baked),
2664 &tz::LocationsRootV1::bind(&crate::provider::Baked),
2665 &tz::CitiesOverrideV1::bind(&crate::provider::Baked),
2666 &tz::CitiesRootV1::bind(&crate::provider::Baked),
2667 &tz::MzGenericLongV1::bind(&crate::provider::Baked),
2668 &tz::MzGenericShortV1::bind(&crate::provider::Baked),
2669 &tz::MzStandardLongV1::bind(&crate::provider::Baked),
2670 &tz::MzSpecificLongV1::bind(&crate::provider::Baked),
2671 &tz::MzSpecificShortV1::bind(&crate::provider::Baked),
2672 &tz::MzPeriodV1::bind(&crate::provider::Baked),
2673 &ExternalLoaderCompiledData,
2674 locale,
2675 pattern.iter_items(),
2676 &mut self.metadata,
2677 )?;
2678 Ok(DateTimePatternFormatter::new(
2679 pattern.as_borrowed(),
2680 self.inner.as_borrowed(),
2681 ))
2682 }
2683}
2684
2685impl<C, FSet: DateTimeNamesMarker> FixedCalendarDateTimeNames<C, FSet> {
2686 /// Maps a [`FixedCalendarDateTimeNames`] of a specific `FSet` to a more general `FSet`.
2687 ///
2688 /// For example, this can transform a formatter for [`DateFieldSet`] to one for
2689 /// [`CompositeDateTimeFieldSet`].
2690 ///
2691 /// To learn why this function is useful, see [`DateTimeFormatter::cast_into_fset`].
2692 ///
2693 /// [`DateFieldSet`]: crate::fieldsets::enums::DateFieldSet
2694 /// [`CompositeDateTimeFieldSet`]: crate::fieldsets::enums::CompositeDateTimeFieldSet
2695 ///
2696 /// # Examples
2697 ///
2698 /// ```
2699 /// use icu::calendar::Gregorian;
2700 /// use icu::datetime::fieldsets::enums::{
2701 /// CompositeDateTimeFieldSet, DateFieldSet,
2702 /// };
2703 /// use icu::datetime::input::Date;
2704 /// use icu::datetime::input::{DateTime, Time};
2705 /// use icu::datetime::pattern::DateTimePattern;
2706 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
2707 /// use icu::datetime::pattern::MonthNameLength;
2708 /// use icu::locale::locale;
2709 /// use writeable::assert_try_writeable_eq;
2710 ///
2711 /// // Create an instance that can format abbreviated month names:
2712 /// let mut names: FixedCalendarDateTimeNames<Gregorian, DateFieldSet> =
2713 /// FixedCalendarDateTimeNames::try_new(locale!("uk").into()).unwrap();
2714 /// names
2715 /// .include_month_names(MonthNameLength::Abbreviated)
2716 /// .unwrap();
2717 ///
2718 /// // Test it with a pattern:
2719 /// let pattern_str = "MMM d y";
2720 /// let pattern: DateTimePattern = pattern_str.parse().unwrap();
2721 /// let datetime = DateTime {
2722 /// date: Date::try_new_gregorian(2023, 11, 20).unwrap(),
2723 /// time: Time::start_of_day(),
2724 /// };
2725 /// assert_try_writeable_eq!(
2726 /// names.with_pattern_unchecked(&pattern).format(&datetime),
2727 /// "лист. 20 2023"
2728 /// );
2729 ///
2730 /// // Convert the field set to `CompositeDateTimeFieldSet`:
2731 /// let composite_names = names.cast_into_fset::<CompositeDateTimeFieldSet>();
2732 ///
2733 /// // It should still work:
2734 /// assert_try_writeable_eq!(
2735 /// composite_names
2736 /// .with_pattern_unchecked(&pattern)
2737 /// .format(&datetime),
2738 /// "лист. 20 2023"
2739 /// );
2740 /// ```
2741 ///
2742 /// Converting into a narrower type is not supported:
2743 ///
2744 /// ```compile_fail,E0277
2745 /// use icu::calendar::Gregorian;
2746 /// use icu::datetime::pattern::FixedCalendarDateTimeNames;
2747 /// use icu::datetime::fieldsets::enums::{DateFieldSet, CompositeDateTimeFieldSet};
2748 ///
2749 /// let composite_names: FixedCalendarDateTimeNames<Gregorian, CompositeDateTimeFieldSet> = todo!();
2750 ///
2751 /// // error[E0277]: the trait bound `(): From<DataPayloadWithVariables<DayPeriodNamesV1, FieldLength>>` is not satisfied
2752 /// let narrow_names = composite_names.cast_into_fset::<DateFieldSet>();
2753 /// ```
2754 pub fn cast_into_fset<FSet2: DateTimeNamesFrom<FSet>>(
2755 self,
2756 ) -> FixedCalendarDateTimeNames<C, FSet2> {
2757 FixedCalendarDateTimeNames {
2758 prefs: self.prefs,
2759 inner: self.inner.cast_into_fset(),
2760 metadata: self.metadata,
2761 _calendar: PhantomData,
2762 }
2763 }
2764}
2765
2766#[cfg(feature = "unstable")]
2767impl<C, FSet: DateTimeNamesMarker> FixedCalendarDateTimeNames<C, FSet>
2768where
2769 FSet::DayPeriodNames: NamesContainer<
2770 DayPeriodNamesV1,
2771 DayPeriodNameLength,
2772 Container = DataPayloadWithVariables<DayPeriodNamesV1, DayPeriodNameLength>,
2773 >,
2774{
2775 /// Gets the "AM" day period symbol for the specified length if the data is loaded.
2776 ///
2777 /// Returns `Some` if the data for the specified length is loaded, or `None` if not loaded.
2778 ///
2779 /// # Examples
2780 ///
2781 /// ```
2782 /// use icu::calendar::Gregorian;
2783 /// use icu::datetime::pattern::{
2784 /// DayPeriodNameLength, FixedCalendarDateTimeNames,
2785 /// };
2786 /// use icu::locale::locale;
2787 ///
2788 /// let mut names =
2789 /// FixedCalendarDateTimeNames::<Gregorian>::try_new(locale!("en").into())
2790 /// .unwrap();
2791 ///
2792 /// // Before loading data, the getter returns None:
2793 /// assert_eq!(names.get_am(DayPeriodNameLength::Abbreviated), None);
2794 ///
2795 /// // Load the day period names:
2796 /// names
2797 /// .include_day_period_names(DayPeriodNameLength::Abbreviated)
2798 /// .unwrap();
2799 ///
2800 /// // Now we can get the AM symbol for the loaded length:
2801 /// assert_eq!(names.get_am(DayPeriodNameLength::Abbreviated), Some("AM"));
2802 ///
2803 /// // But other lengths are not loaded:
2804 /// assert_eq!(names.get_am(DayPeriodNameLength::Wide), None);
2805 /// ```
2806 ///
2807 /// <div class="stab unstable">
2808 /// 🚧 This method is considered unstable; it may change at any time, in breaking or non-breaking ways,
2809 /// including in SemVer minor releases. Do not implement this trait in userland unless you are prepared for things to occasionally break.
2810 /// </div>
2811 pub fn get_am(&self, length: DayPeriodNameLength) -> Option<&str> {
2812 let borrowed = self.inner.as_borrowed();
2813 borrowed
2814 .dayperiod_names
2815 .get_with_variables(length)
2816 .and_then(|names| names.am())
2817 }
2818
2819 /// Gets the "PM" day period symbol for the specified length if the data is loaded.
2820 ///
2821 /// Returns `Some` if the data for the specified length is loaded, or `None` if not loaded.
2822 ///
2823 /// # Examples
2824 ///
2825 /// ```
2826 /// use icu::calendar::Gregorian;
2827 /// use icu::datetime::pattern::{
2828 /// DayPeriodNameLength, FixedCalendarDateTimeNames,
2829 /// };
2830 /// use icu::locale::locale;
2831 ///
2832 /// let mut names =
2833 /// FixedCalendarDateTimeNames::<Gregorian>::try_new(locale!("en").into())
2834 /// .unwrap();
2835 ///
2836 /// // Before loading data, the getter returns None:
2837 /// assert_eq!(names.get_pm(DayPeriodNameLength::Wide), None);
2838 ///
2839 /// // Load the day period names:
2840 /// names
2841 /// .include_day_period_names(DayPeriodNameLength::Wide)
2842 /// .unwrap();
2843 ///
2844 /// // Now we can get the PM symbol for the loaded length:
2845 /// assert_eq!(names.get_pm(DayPeriodNameLength::Wide), Some("PM"));
2846 ///
2847 /// // But other lengths are not loaded:
2848 /// assert_eq!(names.get_pm(DayPeriodNameLength::Abbreviated), None);
2849 /// ```
2850 ///
2851 /// <div class="stab unstable">
2852 /// 🚧 This method is considered unstable; it may change at any time, in breaking or non-breaking ways,
2853 /// including in SemVer minor releases. Do not implement this trait in userland unless you are prepared for things to occasionally break.
2854 /// </div>
2855 pub fn get_pm(&self, length: DayPeriodNameLength) -> Option<&str> {
2856 let borrowed = self.inner.as_borrowed();
2857 borrowed
2858 .dayperiod_names
2859 .get_with_variables(length)
2860 .and_then(|names| names.pm())
2861 }
2862}
2863
2864impl<FSet: DateTimeNamesMarker> DateTimeNames<FSet> {
2865 /// Maps a [`FixedCalendarDateTimeNames`] of a specific `FSet` to a more general `FSet`.
2866 ///
2867 /// For example, this can transform a formatter for [`DateFieldSet`] to one for
2868 /// [`CompositeDateTimeFieldSet`].
2869 ///
2870 /// To learn why this function is useful, see [`DateTimeFormatter::cast_into_fset`].
2871 ///
2872 /// [`DateFieldSet`]: crate::fieldsets::enums::DateFieldSet
2873 /// [`CompositeDateTimeFieldSet`]: crate::fieldsets::enums::CompositeDateTimeFieldSet
2874 pub fn cast_into_fset<FSet2: DateTimeNamesFrom<FSet>>(self) -> DateTimeNames<FSet2> {
2875 DateTimeNames {
2876 inner: self.inner.cast_into_fset(),
2877 calendar: self.calendar,
2878 }
2879 }
2880}
2881
2882impl<FSet: DateTimeNamesMarker> RawDateTimeNames<FSet> {
2883 pub(crate) fn new_without_number_formatting() -> Self {
2884 Self {
2885 year_names: <FSet::YearNames as NamesContainer<
2886 YearNamesV1,
2887 YearNameLength,
2888 >>::Container::new_empty(),
2889 month_names: <FSet::MonthNames as NamesContainer<
2890 MonthNamesV1,
2891 MonthNameLength,
2892 >>::Container::new_empty(),
2893 weekday_names: <FSet::WeekdayNames as NamesContainer<
2894 WeekdayNamesV1,
2895 WeekdayNameLength,
2896 >>::Container::new_empty(),
2897 dayperiod_names: <FSet::DayPeriodNames as NamesContainer<
2898 DayPeriodNamesV1,
2899 DayPeriodNameLength,
2900 >>::Container::new_empty(),
2901 zone_essentials: <FSet::ZoneEssentials as NamesContainer<
2902 tz::EssentialsV1,
2903 (),
2904 >>::Container::new_empty(),
2905 locations_root: <FSet::ZoneLocationsRoot as NamesContainer<
2906 tz::LocationsRootV1,
2907 (),
2908 >>::Container::new_empty(),
2909 locations: <FSet::ZoneLocations as NamesContainer<
2910 tz::LocationsOverrideV1,
2911 (),
2912 >>::Container::new_empty(),
2913 exemplars: <FSet::ZoneExemplars as NamesContainer<
2914 tz::CitiesOverrideV1,
2915 (),
2916 >>::Container::new_empty(),
2917 exemplars_root: <FSet::ZoneExemplarsRoot as NamesContainer<
2918 tz::CitiesRootV1,
2919 (),
2920 >>::Container::new_empty(),
2921 mz_generic_long: <FSet::ZoneGenericLong as NamesContainer<
2922 tz::MzGenericLongV1,
2923 (),
2924 >>::Container::new_empty(),
2925 mz_generic_short: <FSet::ZoneGenericShort as NamesContainer<
2926 tz::MzGenericShortV1,
2927 (),
2928 >>::Container::new_empty(),
2929 mz_standard_long: <FSet::ZoneStandardLong as NamesContainer<
2930 tz::MzStandardLongV1,
2931 (),
2932 >>::Container::new_empty(),
2933 mz_specific_long: <FSet::ZoneSpecificLong as NamesContainer<
2934 tz::MzSpecificLongV1,
2935 (),
2936 >>::Container::new_empty(),
2937 mz_specific_short: <FSet::ZoneSpecificShort as NamesContainer<
2938 tz::MzSpecificShortV1,
2939 (),
2940 >>::Container::new_empty(),
2941 mz_periods: <FSet::MetazoneLookup as NamesContainer<
2942 tz::MzPeriodV1,
2943 (),
2944 >>::Container::new_empty(),
2945 decimal_formatter: None,
2946 _marker: PhantomData,
2947 }
2948 }
2949
2950 pub(crate) fn as_borrowed(&self) -> RawDateTimeNamesBorrowed<'_> {
2951 RawDateTimeNamesBorrowed {
2952 year_names: self.year_names.get().inner,
2953 month_names: self.month_names.get().inner,
2954 weekday_names: self.weekday_names.get().inner,
2955 dayperiod_names: self.dayperiod_names.get().inner,
2956 zone_essentials: self.zone_essentials.get().inner,
2957 locations_root: self.locations_root.get().inner,
2958 locations: self.locations.get().inner,
2959 exemplars_root: self.exemplars_root.get().inner,
2960 exemplars: self.exemplars.get().inner,
2961 mz_generic_long: self.mz_generic_long.get().inner,
2962 mz_generic_short: self.mz_generic_short.get().inner,
2963 mz_standard_long: self.mz_standard_long.get().inner,
2964 mz_specific_long: self.mz_specific_long.get().inner,
2965 mz_specific_short: self.mz_specific_short.get().inner,
2966 mz_periods: self.mz_periods.get().inner,
2967 decimal_formatter: self.decimal_formatter.as_ref(),
2968 }
2969 }
2970
2971 pub(crate) fn load_year_names<P>(
2972 &mut self,
2973 provider: &P,
2974 prefs: DateTimeFormatterPreferences,
2975 length: YearNameLength,
2976 error_field: ErrorField,
2977 ) -> Result<(), PatternLoadError>
2978 where
2979 P: BoundDataProvider<YearNamesV1> + ?Sized,
2980 {
2981 let attributes = length.to_attributes();
2982 let locale = provider
2983 .bound_marker()
2984 .make_locale(prefs.locale_preferences);
2985 let req = DataRequest {
2986 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(attributes, &locale),
2987 ..Default::default()
2988 };
2989 self.year_names
2990 .load_put(provider, req, length)
2991 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
2992 .map_err(|e| PatternLoadError::Data(e, error_field))?;
2993 Ok(())
2994 }
2995
2996 pub(crate) fn load_month_names<P>(
2997 &mut self,
2998 provider: &P,
2999 prefs: DateTimeFormatterPreferences,
3000 length: MonthNameLength,
3001 error_field: ErrorField,
3002 ) -> Result<(), PatternLoadError>
3003 where
3004 P: BoundDataProvider<MonthNamesV1> + ?Sized,
3005 {
3006 let attributes = length.to_attributes();
3007 let locale = provider
3008 .bound_marker()
3009 .make_locale(prefs.locale_preferences);
3010 let req = DataRequest {
3011 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(attributes, &locale),
3012 ..Default::default()
3013 };
3014 self.month_names
3015 .load_put(provider, req, length)
3016 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3017 .map_err(|e| PatternLoadError::Data(e, error_field))?;
3018 Ok(())
3019 }
3020
3021 pub(crate) fn load_day_period_names<P>(
3022 &mut self,
3023 provider: &P,
3024 prefs: DateTimeFormatterPreferences,
3025 length: DayPeriodNameLength,
3026 error_field: ErrorField,
3027 ) -> Result<(), PatternLoadError>
3028 where
3029 P: BoundDataProvider<DayPeriodNamesV1> + ?Sized,
3030 {
3031 let attributes = length.to_attributes();
3032 let locale = provider
3033 .bound_marker()
3034 .make_locale(prefs.locale_preferences);
3035 let req = DataRequest {
3036 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(attributes, &locale),
3037 ..Default::default()
3038 };
3039 self.dayperiod_names
3040 .load_put(provider, req, length)
3041 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3042 .map_err(|e| PatternLoadError::Data(e, error_field))?;
3043 Ok(())
3044 }
3045
3046 pub(crate) fn load_weekday_names<P>(
3047 &mut self,
3048 provider: &P,
3049 prefs: DateTimeFormatterPreferences,
3050 length: WeekdayNameLength,
3051 error_field: ErrorField,
3052 ) -> Result<(), PatternLoadError>
3053 where
3054 P: BoundDataProvider<WeekdayNamesV1> + ?Sized,
3055 {
3056 let attributes = length.to_attributes();
3057 let locale = provider
3058 .bound_marker()
3059 .make_locale(prefs.locale_preferences);
3060 let req = DataRequest {
3061 id: DataIdentifierBorrowed::for_marker_attributes_and_locale(attributes, &locale),
3062 ..Default::default()
3063 };
3064 self.weekday_names
3065 .load_put(provider, req, length)
3066 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3067 .map_err(|e| PatternLoadError::Data(e, error_field))?;
3068 Ok(())
3069 }
3070
3071 pub(crate) fn load_time_zone_essentials<P>(
3072 &mut self,
3073 provider: &P,
3074 prefs: DateTimeFormatterPreferences,
3075 ) -> Result<ErrorField, PatternLoadError>
3076 where
3077 P: BoundDataProvider<tz::EssentialsV1> + ?Sized,
3078 {
3079 let locale = provider
3080 .bound_marker()
3081 .make_locale(prefs.locale_preferences);
3082 let error_field = ErrorField(fields::Field {
3083 symbol: FieldSymbol::TimeZone(fields::TimeZone::LocalizedOffset),
3084 length: FieldLength::Four,
3085 });
3086 let variables = ();
3087 let req = DataRequest {
3088 id: DataIdentifierBorrowed::for_locale(&locale),
3089 ..Default::default()
3090 };
3091 self.zone_essentials
3092 .load_put(provider, req, variables)
3093 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3094 .map_err(|e| PatternLoadError::Data(e, error_field))?;
3095 Ok(error_field)
3096 }
3097
3098 pub(crate) fn load_time_zone_location_names<P, P2>(
3099 &mut self,
3100 provider: &P,
3101 root_provider: &P2,
3102 prefs: DateTimeFormatterPreferences,
3103 ) -> Result<ErrorField, PatternLoadError>
3104 where
3105 P: BoundDataProvider<tz::LocationsOverrideV1> + ?Sized,
3106 P2: BoundDataProvider<tz::LocationsRootV1> + ?Sized,
3107 {
3108 let locale = provider
3109 .bound_marker()
3110 .make_locale(prefs.locale_preferences);
3111 let error_field = ErrorField(fields::Field {
3112 symbol: FieldSymbol::TimeZone(fields::TimeZone::Location),
3113 length: FieldLength::Four,
3114 });
3115 let variables = ();
3116 let req = DataRequest {
3117 id: DataIdentifierBorrowed::for_locale(&locale),
3118 ..Default::default()
3119 };
3120 self.locations_root
3121 .load_put(root_provider, req, variables)
3122 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3123 .map_err(|e| PatternLoadError::Data(e, error_field))?;
3124 self.locations
3125 .load_put(provider, req, variables)
3126 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3127 .map_err(|e| PatternLoadError::Data(e, error_field))?;
3128 Ok(error_field)
3129 }
3130
3131 pub(crate) fn load_time_zone_exemplar_city_names<P, P2>(
3132 &mut self,
3133 provider: &P,
3134 root_provider: &P2,
3135 prefs: DateTimeFormatterPreferences,
3136 ) -> Result<ErrorField, PatternLoadError>
3137 where
3138 P: BoundDataProvider<tz::CitiesOverrideV1> + ?Sized,
3139 P2: BoundDataProvider<tz::CitiesRootV1> + ?Sized,
3140 {
3141 let locale = provider
3142 .bound_marker()
3143 .make_locale(prefs.locale_preferences);
3144 let error_field = ErrorField(fields::Field {
3145 symbol: FieldSymbol::TimeZone(fields::TimeZone::Location),
3146 length: FieldLength::Three,
3147 });
3148 let variables = ();
3149 let req = DataRequest {
3150 id: DataIdentifierBorrowed::for_locale(&locale),
3151 ..Default::default()
3152 };
3153 self.exemplars_root
3154 .load_put(root_provider, req, variables)
3155 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3156 .map_err(|e| PatternLoadError::Data(e, error_field))?;
3157 self.exemplars
3158 .load_put(provider, req, variables)
3159 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3160 .map_err(|e| PatternLoadError::Data(e, error_field))?;
3161 Ok(error_field)
3162 }
3163
3164 pub(crate) fn load_time_zone_generic_long_names(
3165 &mut self,
3166 mz_generic_provider: &(impl BoundDataProvider<tz::MzGenericLongV1> + ?Sized),
3167 mz_standard_provider: &(impl BoundDataProvider<tz::MzStandardLongV1> + ?Sized),
3168 mz_period_provider: &(impl BoundDataProvider<tz::MzPeriodV1> + ?Sized),
3169 prefs: DateTimeFormatterPreferences,
3170 names_metadata: &mut DateTimeNamesMetadata,
3171 ) -> Result<ErrorField, PatternLoadError> {
3172 let locale = mz_generic_provider
3173 .bound_marker()
3174 .make_locale(prefs.locale_preferences);
3175 let error_field = ErrorField(fields::Field {
3176 symbol: FieldSymbol::TimeZone(fields::TimeZone::GenericNonLocation),
3177 length: FieldLength::Four,
3178 });
3179 let variables = ();
3180 let req = DataRequest {
3181 id: DataIdentifierBorrowed::for_locale(&locale),
3182 ..Default::default()
3183 };
3184 let mut save_checksum = |cs: &u64| {
3185 // get_or_insert saves the value only if the Option is None.
3186 names_metadata.zone_checksum.get_or_insert(*cs);
3187 };
3188 let cs1 = self
3189 .mz_generic_long
3190 .load_put(mz_generic_provider, req, variables)
3191 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3192 .map_err(|e| PatternLoadError::Data(e, error_field))?
3193 .checksum
3194 .inspect(&mut save_checksum);
3195 let cs2 = self
3196 .mz_standard_long
3197 .load_put(mz_standard_provider, req, variables)
3198 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3199 .map_err(|e| PatternLoadError::Data(e, error_field))?
3200 .checksum
3201 .inspect(&mut save_checksum);
3202 let cs3 = self
3203 .mz_periods
3204 .load_put(mz_period_provider, Default::default(), ())
3205 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3206 .map_err(|e| PatternLoadError::Data(e, error_field))?
3207 .checksum
3208 .inspect(&mut save_checksum);
3209 // Error if any two of the checksum Options are Some and not equal.
3210 let cs = names_metadata.zone_checksum;
3211 if cs1.or(cs) != cs || cs2.or(cs) != cs || cs3.or(cs) != cs {
3212 return Err(PatternLoadError::Data(
3213 DataErrorKind::InconsistentData(tz::MzPeriodV1::INFO)
3214 .with_req(tz::MzGenericLongV1::INFO, req),
3215 error_field,
3216 ));
3217 }
3218 Ok(error_field)
3219 }
3220
3221 pub(crate) fn load_time_zone_generic_short_names(
3222 &mut self,
3223 provider: &(impl BoundDataProvider<tz::MzGenericShortV1> + ?Sized),
3224 mz_period_provider: &(impl BoundDataProvider<tz::MzPeriodV1> + ?Sized),
3225 prefs: DateTimeFormatterPreferences,
3226 names_metadata: &mut DateTimeNamesMetadata,
3227 ) -> Result<ErrorField, PatternLoadError> {
3228 let locale = provider
3229 .bound_marker()
3230 .make_locale(prefs.locale_preferences);
3231 let error_field = ErrorField(fields::Field {
3232 symbol: FieldSymbol::TimeZone(fields::TimeZone::GenericNonLocation),
3233 length: FieldLength::One,
3234 });
3235 let variables = ();
3236 let req = DataRequest {
3237 id: DataIdentifierBorrowed::for_locale(&locale),
3238 ..Default::default()
3239 };
3240 let mut save_checksum = |cs: &u64| {
3241 // get_or_insert saves the value only if the Option is None.
3242 names_metadata.zone_checksum.get_or_insert(*cs);
3243 };
3244 let cs1 = self
3245 .mz_generic_short
3246 .load_put(provider, req, variables)
3247 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3248 .map_err(|e| PatternLoadError::Data(e, error_field))?
3249 .checksum
3250 .inspect(&mut save_checksum);
3251 let cs2 = self
3252 .mz_periods
3253 .load_put(mz_period_provider, Default::default(), ())
3254 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3255 .map_err(|e| PatternLoadError::Data(e, error_field))?
3256 .checksum
3257 .inspect(&mut save_checksum);
3258 // Error if any two of the checksum Options are Some and not equal.
3259 let cs = names_metadata.zone_checksum;
3260 if cs1.or(cs) != cs || cs2.or(cs) != cs {
3261 return Err(PatternLoadError::Data(
3262 DataErrorKind::InconsistentData(tz::MzPeriodV1::INFO)
3263 .with_req(tz::MzGenericLongV1::INFO, req),
3264 error_field,
3265 ));
3266 }
3267 Ok(error_field)
3268 }
3269
3270 pub(crate) fn load_time_zone_specific_long_names(
3271 &mut self,
3272 mz_specific_provider: &(impl BoundDataProvider<tz::MzSpecificLongV1> + ?Sized),
3273 mz_standard_provider: &(impl BoundDataProvider<tz::MzStandardLongV1> + ?Sized),
3274 mz_period_provider: &(impl BoundDataProvider<tz::MzPeriodV1> + ?Sized),
3275 prefs: DateTimeFormatterPreferences,
3276 names_metadata: &mut DateTimeNamesMetadata,
3277 ) -> Result<ErrorField, PatternLoadError> {
3278 let locale = mz_specific_provider
3279 .bound_marker()
3280 .make_locale(prefs.locale_preferences);
3281 let error_field = ErrorField(fields::Field {
3282 symbol: FieldSymbol::TimeZone(fields::TimeZone::SpecificNonLocation),
3283 length: FieldLength::Four,
3284 });
3285 let variables = ();
3286 let req = DataRequest {
3287 id: DataIdentifierBorrowed::for_locale(&locale),
3288 ..Default::default()
3289 };
3290 let mut save_checksum = |cs: &u64| {
3291 // get_or_insert saves the value only if the Option is None.
3292 names_metadata.zone_checksum.get_or_insert(*cs);
3293 };
3294 let cs1 = self
3295 .mz_specific_long
3296 .load_put(mz_specific_provider, req, variables)
3297 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3298 .map_err(|e| PatternLoadError::Data(e, error_field))?
3299 .checksum
3300 .inspect(&mut save_checksum);
3301 let cs2 = self
3302 .mz_standard_long
3303 .load_put(mz_standard_provider, req, variables)
3304 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3305 .map_err(|e| PatternLoadError::Data(e, error_field))?
3306 .checksum
3307 .inspect(&mut save_checksum);
3308 let cs3 = self
3309 .mz_periods
3310 .load_put(mz_period_provider, Default::default(), ())
3311 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3312 .map_err(|e| PatternLoadError::Data(e, error_field))?
3313 .checksum
3314 .inspect(&mut save_checksum);
3315 // Error if any two of the checksum Options are Some and not equal.
3316 let cs = names_metadata.zone_checksum;
3317 if cs1.or(cs) != cs || cs2.or(cs) != cs || cs3.or(cs) != cs {
3318 return Err(PatternLoadError::Data(
3319 DataErrorKind::InconsistentData(tz::MzPeriodV1::INFO)
3320 .with_req(tz::MzSpecificLongV1::INFO, req),
3321 error_field,
3322 ));
3323 }
3324 Ok(error_field)
3325 }
3326
3327 pub(crate) fn load_time_zone_specific_short_names(
3328 &mut self,
3329 provider: &(impl BoundDataProvider<tz::MzSpecificShortV1> + ?Sized),
3330 mz_period_provider: &(impl BoundDataProvider<tz::MzPeriodV1> + ?Sized),
3331 prefs: DateTimeFormatterPreferences,
3332 names_metadata: &mut DateTimeNamesMetadata,
3333 ) -> Result<ErrorField, PatternLoadError> {
3334 let locale = provider
3335 .bound_marker()
3336 .make_locale(prefs.locale_preferences);
3337 let error_field = ErrorField(fields::Field {
3338 symbol: FieldSymbol::TimeZone(fields::TimeZone::SpecificNonLocation),
3339 length: FieldLength::One,
3340 });
3341 let variables = ();
3342 let req = DataRequest {
3343 id: DataIdentifierBorrowed::for_locale(&locale),
3344 ..Default::default()
3345 };
3346 let mut save_checksum = |cs: &u64| {
3347 // get_or_insert saves the value only if the Option is None.
3348 names_metadata.zone_checksum.get_or_insert(*cs);
3349 };
3350 let cs1 = self
3351 .mz_specific_short
3352 .load_put(provider, req, variables)
3353 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3354 .map_err(|e| PatternLoadError::Data(e, error_field))?
3355 .checksum
3356 .inspect(&mut save_checksum);
3357 let cs2 = self
3358 .mz_periods
3359 .load_put(mz_period_provider, Default::default(), ())
3360 .map_err(|e| MaybePayloadError::into_load_error(e, error_field))?
3361 .map_err(|e| PatternLoadError::Data(e, error_field))?
3362 .checksum
3363 .inspect(&mut save_checksum);
3364 // Error if any two of the checksum Options are Some and not equal.
3365 let cs = names_metadata.zone_checksum;
3366 if cs1.or(cs) != cs || cs2.or(cs) != cs {
3367 return Err(PatternLoadError::Data(
3368 DataErrorKind::InconsistentData(tz::MzPeriodV1::INFO)
3369 .with_req(tz::MzSpecificShortV1::INFO, req),
3370 error_field,
3371 ));
3372 }
3373 Ok(error_field)
3374 }
3375
3376 pub(crate) fn load_time_zone_field_z_except_decimals(
3377 &mut self,
3378 zone_essentials_provider: &(impl BoundDataProvider<tz::EssentialsV1> + ?Sized),
3379 mz_specific_short_provider: &(impl BoundDataProvider<tz::MzSpecificShortV1> + ?Sized),
3380 mz_period_provider: &(impl BoundDataProvider<tz::MzPeriodV1> + ?Sized),
3381 prefs: DateTimeFormatterPreferences,
3382 names_metadata: &mut DateTimeNamesMetadata,
3383 ) -> Result<ErrorField, PatternLoadError> {
3384 self.load_time_zone_essentials(zone_essentials_provider, prefs)?;
3385 self.load_time_zone_specific_short_names(
3386 mz_specific_short_provider,
3387 mz_period_provider,
3388 prefs,
3389 names_metadata,
3390 )
3391 }
3392
3393 #[expect(clippy::too_many_arguments)]
3394 pub(crate) fn load_time_zone_field_zzzz_except_decimals(
3395 &mut self,
3396 zone_essentials_provider: &(impl BoundDataProvider<tz::EssentialsV1> + ?Sized),
3397 locations_provider: &(impl BoundDataProvider<tz::LocationsOverrideV1> + ?Sized),
3398 locations_root_provider: &(impl BoundDataProvider<tz::LocationsRootV1> + ?Sized),
3399 mz_standard_long_provider: &(impl BoundDataProvider<tz::MzStandardLongV1> + ?Sized),
3400 mz_specific_long_provider: &(impl BoundDataProvider<tz::MzSpecificLongV1> + ?Sized),
3401 mz_period_provider: &(impl BoundDataProvider<tz::MzPeriodV1> + ?Sized),
3402 prefs: DateTimeFormatterPreferences,
3403 names_metadata: &mut DateTimeNamesMetadata,
3404 ) -> Result<ErrorField, PatternLoadError> {
3405 self.load_time_zone_essentials(zone_essentials_provider, prefs)?;
3406 self.load_time_zone_location_names(locations_provider, locations_root_provider, prefs)?;
3407 self.load_time_zone_specific_long_names(
3408 mz_specific_long_provider,
3409 mz_standard_long_provider,
3410 mz_period_provider,
3411 prefs,
3412 names_metadata,
3413 )
3414 }
3415
3416 #[expect(clippy::too_many_arguments)] // internal function with lots of generics
3417 pub(crate) fn load_time_zone_field_v_except_decimals(
3418 &mut self,
3419 zone_essentials_provider: &(impl BoundDataProvider<tz::EssentialsV1> + ?Sized),
3420 locations_provider: &(impl BoundDataProvider<tz::LocationsOverrideV1> + ?Sized),
3421 locations_root_provider: &(impl BoundDataProvider<tz::LocationsRootV1> + ?Sized),
3422 mz_generic_short_provider: &(impl BoundDataProvider<tz::MzGenericShortV1> + ?Sized),
3423 mz_period_provider: &(impl BoundDataProvider<tz::MzPeriodV1> + ?Sized),
3424 prefs: DateTimeFormatterPreferences,
3425 names_metadata: &mut DateTimeNamesMetadata,
3426 ) -> Result<ErrorField, PatternLoadError> {
3427 self.load_time_zone_essentials(zone_essentials_provider, prefs)?;
3428 // For fallback:
3429 self.load_time_zone_location_names(locations_provider, locations_root_provider, prefs)?;
3430 self.load_time_zone_generic_short_names(
3431 mz_generic_short_provider,
3432 mz_period_provider,
3433 prefs,
3434 names_metadata,
3435 )
3436 }
3437
3438 #[expect(clippy::too_many_arguments)]
3439 pub(crate) fn load_time_zone_field_vvvv_except_decimals(
3440 &mut self,
3441 zone_essentials_provider: &(impl BoundDataProvider<tz::EssentialsV1> + ?Sized),
3442 locations_provider: &(impl BoundDataProvider<tz::LocationsOverrideV1> + ?Sized),
3443 locations_root_provider: &(impl BoundDataProvider<tz::LocationsRootV1> + ?Sized),
3444 mz_generic_long_provider: &(impl BoundDataProvider<tz::MzGenericLongV1> + ?Sized),
3445 mz_standard_long_provider: &(impl BoundDataProvider<tz::MzStandardLongV1> + ?Sized),
3446 mz_period_provider: &(impl BoundDataProvider<tz::MzPeriodV1> + ?Sized),
3447 prefs: DateTimeFormatterPreferences,
3448 names_metadata: &mut DateTimeNamesMetadata,
3449 ) -> Result<ErrorField, PatternLoadError> {
3450 self.load_time_zone_essentials(zone_essentials_provider, prefs)?;
3451 // For fallback:
3452 self.load_time_zone_location_names(locations_provider, locations_root_provider, prefs)?;
3453 self.load_time_zone_generic_long_names(
3454 mz_generic_long_provider,
3455 mz_standard_long_provider,
3456 mz_period_provider,
3457 prefs,
3458 names_metadata,
3459 )
3460 }
3461
3462 #[allow(non_snake_case)] // this is a private function named after the case-sensitive CLDR field
3463 #[allow(clippy::unnecessary_wraps)] // consistency
3464 pub(crate) fn load_time_zone_field_V(
3465 &mut self,
3466 _prefs: DateTimeFormatterPreferences,
3467 ) -> Result<(), PatternLoadError> {
3468 // no data required
3469 Ok(())
3470 }
3471
3472 #[allow(non_snake_case)] // this is a private function named after the case-sensitive CLDR field
3473 pub(crate) fn load_time_zone_field_VVV(
3474 &mut self,
3475 locations_provider: &(impl BoundDataProvider<tz::LocationsOverrideV1> + ?Sized),
3476 locations_root_provider: &(impl BoundDataProvider<tz::LocationsRootV1> + ?Sized),
3477 exemplar_cities_provider: &(impl BoundDataProvider<tz::CitiesOverrideV1> + ?Sized),
3478 exemplar_cities_root_provider: &(impl BoundDataProvider<tz::CitiesRootV1> + ?Sized),
3479 prefs: DateTimeFormatterPreferences,
3480 ) -> Result<ErrorField, PatternLoadError> {
3481 self.load_time_zone_location_names(locations_provider, locations_root_provider, prefs)?;
3482 self.load_time_zone_exemplar_city_names(
3483 exemplar_cities_provider,
3484 exemplar_cities_root_provider,
3485 prefs,
3486 )
3487 }
3488
3489 #[allow(non_snake_case)] // this is a private function named after the case-sensitive CLDR field
3490 pub(crate) fn load_time_zone_field_VVVV_except_decimals(
3491 &mut self,
3492 zone_essentials_provider: &(impl BoundDataProvider<tz::EssentialsV1> + ?Sized),
3493 locations_provider: &(impl BoundDataProvider<tz::LocationsOverrideV1> + ?Sized),
3494 locations_root_provider: &(impl BoundDataProvider<tz::LocationsRootV1> + ?Sized),
3495 prefs: DateTimeFormatterPreferences,
3496 ) -> Result<ErrorField, PatternLoadError> {
3497 self.load_time_zone_essentials(zone_essentials_provider, prefs)?;
3498 self.load_time_zone_location_names(locations_provider, locations_root_provider, prefs)
3499 }
3500
3501 #[allow(non_snake_case)] // this is a private function named after the case-sensitive CLDR field
3502 pub(crate) fn load_time_zone_field_O_except_decimals(
3503 &mut self,
3504 zone_essentials_provider: &(impl BoundDataProvider<tz::EssentialsV1> + ?Sized),
3505 prefs: DateTimeFormatterPreferences,
3506 ) -> Result<ErrorField, PatternLoadError> {
3507 self.load_time_zone_essentials(zone_essentials_provider, prefs)
3508 }
3509
3510 #[allow(non_snake_case)] // this is a private function named after the case-sensitive CLDR field
3511 #[allow(clippy::unnecessary_wraps)] // consistency
3512 pub(crate) fn load_time_zone_field_X(
3513 &mut self,
3514 _prefs: DateTimeFormatterPreferences,
3515 ) -> Result<(), PatternLoadError> {
3516 // no data required
3517 Ok(())
3518 }
3519
3520 pub(crate) fn load_decimal_formatter(
3521 &mut self,
3522 loader: &impl DecimalFormatterLoader,
3523 prefs: DateTimeFormatterPreferences,
3524 ) -> Result<(), DataError> {
3525 if self.decimal_formatter.is_some() {
3526 return Ok(());
3527 }
3528 let mut options = DecimalFormatterOptions::default();
3529 options.grouping_strategy = Some(GroupingStrategy::Never);
3530 self.decimal_formatter = Some(DecimalFormatterLoader::load(
3531 loader,
3532 (&prefs).into(),
3533 options,
3534 )?);
3535 Ok(())
3536 }
3537
3538 /// Loads all data required for formatting the given [`PatternItem`]s.
3539 ///
3540 /// This function has a lot of arguments because many of the arguments are generic,
3541 /// and pulling them out to an options struct would be cumbersome.
3542 #[expect(clippy::too_many_arguments)]
3543 pub(crate) fn load_for_pattern(
3544 &mut self,
3545 year_provider: &(impl BoundDataProvider<YearNamesV1> + ?Sized),
3546 month_provider: &(impl BoundDataProvider<MonthNamesV1> + ?Sized),
3547 weekday_provider: &(impl BoundDataProvider<WeekdayNamesV1> + ?Sized),
3548 dayperiod_provider: &(impl BoundDataProvider<DayPeriodNamesV1> + ?Sized),
3549 zone_essentials_provider: &(impl BoundDataProvider<tz::EssentialsV1> + ?Sized),
3550 locations_provider: &(impl BoundDataProvider<tz::LocationsOverrideV1> + ?Sized),
3551 locations_root_provider: &(impl BoundDataProvider<tz::LocationsRootV1> + ?Sized),
3552 exemplar_cities_provider: &(impl BoundDataProvider<tz::CitiesOverrideV1> + ?Sized),
3553 exemplar_cities_root_provider: &(impl BoundDataProvider<tz::CitiesRootV1> + ?Sized),
3554 mz_generic_long_provider: &(impl BoundDataProvider<tz::MzGenericLongV1> + ?Sized),
3555 mz_generic_short_provider: &(impl BoundDataProvider<tz::MzGenericShortV1> + ?Sized),
3556 mz_standard_long_provider: &(impl BoundDataProvider<tz::MzStandardLongV1> + ?Sized),
3557 mz_specific_long_provider: &(impl BoundDataProvider<tz::MzSpecificLongV1> + ?Sized),
3558 mz_specific_short_provider: &(impl BoundDataProvider<tz::MzSpecificShortV1> + ?Sized),
3559 mz_period_provider: &(impl BoundDataProvider<tz::MzPeriodV1> + ?Sized),
3560 decimal_formatter_loader: &impl DecimalFormatterLoader,
3561 prefs: DateTimeFormatterPreferences,
3562 pattern_items: impl Iterator<Item = PatternItem>,
3563 names_metadata: &mut DateTimeNamesMetadata,
3564 ) -> Result<(), PatternLoadError> {
3565 let mut numeric_field = None;
3566
3567 for item in pattern_items {
3568 let PatternItem::Field(field) = item else {
3569 continue;
3570 };
3571 let error_field = ErrorField(field);
3572
3573 use crate::provider::fields::*;
3574 use FieldLength::*;
3575 use FieldSymbol as FS;
3576
3577 match (field.symbol, field.length) {
3578 ///// Textual symbols /////
3579
3580 // G..GGGGG
3581 (FS::Era, One | Two | Three | Four | Five) => {
3582 self.load_year_names(
3583 year_provider,
3584 prefs,
3585 YearNameLength::from_field_length(field.length)
3586 .ok_or(PatternLoadError::UnsupportedLength(error_field))?,
3587 error_field,
3588 )?;
3589 }
3590
3591 // U..UUUUU
3592 (FS::Year(Year::Cyclic), One | Two | Three | Four | Five) => {
3593 numeric_field = Some(field);
3594 self.load_year_names(
3595 year_provider,
3596 prefs,
3597 YearNameLength::from_field_length(field.length)
3598 .ok_or(PatternLoadError::UnsupportedLength(error_field))?,
3599 error_field,
3600 )?;
3601 }
3602
3603 // MMM..MMMMM, LLL..LLLLL
3604 (
3605 FS::Month(field_symbol @ Month::Format | field_symbol @ Month::StandAlone),
3606 Three | Four | Five,
3607 ) => {
3608 self.load_month_names(
3609 month_provider,
3610 prefs,
3611 MonthNameLength::from_field(field_symbol, field.length)
3612 .ok_or(PatternLoadError::UnsupportedLength(error_field))?,
3613 error_field,
3614 )?;
3615 }
3616
3617 // e..ee, c..cc
3618 (FS::Weekday(Weekday::Local | Weekday::StandAlone), One | Two) => {
3619 // TODO(#5643): Requires locale-aware day-of-week calculation
3620 return Err(PatternLoadError::UnsupportedLength(ErrorField(field)));
3621 }
3622
3623 // E..EEEEEE, eee..eeeeee, ccc..cccccc
3624 (FS::Weekday(field_symbol), One | Two | Three | Four | Five | Six) => {
3625 self.load_weekday_names(
3626 weekday_provider,
3627 prefs,
3628 WeekdayNameLength::from_field(field_symbol, field.length)
3629 .ok_or(PatternLoadError::UnsupportedLength(error_field))?,
3630 error_field,
3631 )?;
3632 }
3633
3634 // a..aaaaa, b..bbbbb
3635 (FS::DayPeriod(field_symbol), One | Two | Three | Four | Five) => {
3636 self.load_day_period_names(
3637 dayperiod_provider,
3638 prefs,
3639 DayPeriodNameLength::from_field(field_symbol, field.length)
3640 .ok_or(PatternLoadError::UnsupportedLength(error_field))?,
3641 error_field,
3642 )?;
3643 }
3644
3645 ///// Time zone symbols /////
3646
3647 // z..zzz
3648 (FS::TimeZone(TimeZone::SpecificNonLocation), One | Two | Three) => {
3649 self.load_time_zone_field_z_except_decimals(
3650 zone_essentials_provider,
3651 mz_specific_short_provider,
3652 mz_period_provider,
3653 prefs,
3654 names_metadata,
3655 )?;
3656 numeric_field = Some(field);
3657 }
3658 // zzzz
3659 (FS::TimeZone(TimeZone::SpecificNonLocation), Four) => {
3660 self.load_time_zone_field_zzzz_except_decimals(
3661 zone_essentials_provider,
3662 locations_provider,
3663 locations_root_provider,
3664 mz_standard_long_provider,
3665 mz_specific_long_provider,
3666 mz_period_provider,
3667 prefs,
3668 names_metadata,
3669 )?;
3670 numeric_field = Some(field);
3671 }
3672 // v
3673 (FS::TimeZone(TimeZone::GenericNonLocation), One) => {
3674 self.load_time_zone_field_v_except_decimals(
3675 zone_essentials_provider,
3676 locations_provider,
3677 locations_root_provider,
3678 mz_generic_short_provider,
3679 mz_period_provider,
3680 prefs,
3681 names_metadata,
3682 )?;
3683 numeric_field = Some(field);
3684 }
3685 // vvvv
3686 (FS::TimeZone(TimeZone::GenericNonLocation), Four) => {
3687 self.load_time_zone_field_vvvv_except_decimals(
3688 zone_essentials_provider,
3689 locations_provider,
3690 locations_root_provider,
3691 mz_generic_long_provider,
3692 mz_standard_long_provider,
3693 mz_period_provider,
3694 prefs,
3695 names_metadata,
3696 )?;
3697 numeric_field = Some(field);
3698 }
3699
3700 // V
3701 (FS::TimeZone(TimeZone::Location), One) => {
3702 self.load_time_zone_field_V(prefs)?;
3703 }
3704 // VVV
3705 (FS::TimeZone(TimeZone::Location), Three) => {
3706 self.load_time_zone_field_VVV(
3707 locations_provider,
3708 locations_root_provider,
3709 exemplar_cities_provider,
3710 exemplar_cities_root_provider,
3711 prefs,
3712 )?;
3713 }
3714 // VVVV
3715 (FS::TimeZone(TimeZone::Location), Four) => {
3716 self.load_time_zone_field_VVVV_except_decimals(
3717 zone_essentials_provider,
3718 locations_provider,
3719 locations_root_provider,
3720 prefs,
3721 )?;
3722 numeric_field = Some(field);
3723 }
3724 // O, OOOO
3725 (FS::TimeZone(TimeZone::LocalizedOffset), One | Four) => {
3726 self.load_time_zone_field_O_except_decimals(zone_essentials_provider, prefs)?;
3727 numeric_field = Some(field);
3728 }
3729 // X..XXXXX, x..xxxxx
3730 (
3731 FS::TimeZone(TimeZone::IsoWithZ | TimeZone::Iso),
3732 One | Two | Three | Four | Five,
3733 ) => {
3734 self.load_time_zone_field_X(prefs)?;
3735 }
3736
3737 ///// Numeric symbols /////
3738
3739 // Don't need data for numeric overrides
3740 (_, NumericOverride(_)) => (),
3741
3742 // y+
3743 (FS::Year(Year::Calendar), _) => numeric_field = Some(field),
3744 // u+
3745 (FS::Year(Year::Extended), _) => numeric_field = Some(field),
3746 // r+
3747 (FS::Year(Year::RelatedIso), _) => {
3748 // always formats as ASCII
3749 }
3750
3751 // M..MM, L..LL
3752 (FS::Month(m), One | Two) => {
3753 self.load_month_names(
3754 month_provider,
3755 prefs,
3756 MonthNameLength::from_field(m, field.length)
3757 .ok_or(PatternLoadError::UnsupportedLength(error_field))?,
3758 error_field,
3759 )?;
3760 numeric_field = Some(field)
3761 }
3762
3763 // d..dd
3764 (FS::Day(Day::DayOfMonth), One | Two) => numeric_field = Some(field),
3765 // D..DDD
3766 (FS::Day(Day::DayOfYear), One | Two | Three) => numeric_field = Some(field),
3767 // F
3768 (FS::Day(Day::DayOfWeekInMonth), One) => numeric_field = Some(field),
3769 // g
3770 (FS::Day(Day::ModifiedJulianDay), One) => numeric_field = Some(field),
3771
3772 // K..KK, h..hh, H..HH, k..kk
3773 (FS::Hour(_), One | Two) => numeric_field = Some(field),
3774
3775 // m..mm
3776 (FS::Minute, One | Two) => numeric_field = Some(field),
3777
3778 // s..ss
3779 (FS::Second(Second::Second), One | Two) => numeric_field = Some(field),
3780
3781 // A+
3782 (FS::Second(Second::MillisInDay), _) => numeric_field = Some(field),
3783
3784 // s.S+, ss.S+ (s is modelled by length, S+ by symbol)
3785 (FS::DecimalSecond(_), One | Two) => numeric_field = Some(field),
3786
3787 ///// Unsupported symbols /////
3788 _ => {
3789 return Err(PatternLoadError::UnsupportedLength(ErrorField(field)));
3790 }
3791 }
3792 }
3793
3794 if let Some(field) = numeric_field {
3795 self.load_decimal_formatter(decimal_formatter_loader, prefs)
3796 .map_err(|e| PatternLoadError::Data(e, ErrorField(field)))?;
3797 }
3798
3799 Ok(())
3800 }
3801}
3802
3803impl RawDateTimeNamesBorrowed<'_> {
3804 pub(crate) fn get_name_for_month(
3805 &self,
3806 field_symbol: fields::Month,
3807 field_length: FieldLength,
3808 month: MonthInfo,
3809 ) -> Result<MonthPlaceholderValue<'_>, GetNameForMonthError> {
3810 let month_name_length = MonthNameLength::from_field(field_symbol, field_length)
3811 .ok_or(GetNameForMonthError::InvalidFieldLength)?;
3812 let month_names = self
3813 .month_names
3814 .get_with_variables(month_name_length)
3815 .ok_or(GetNameForMonthError::NotLoaded)?;
3816 let month_index = usize::from(month.number() - 1);
3817 match month_names {
3818 MonthNames::Numeric => Some(MonthPlaceholderValue::Numeric),
3819 MonthNames::Linear(linear) => {
3820 if month.leap_status() != LeapStatus::Normal {
3821 None
3822 } else {
3823 linear
3824 .get(month_index)
3825 .map(MonthPlaceholderValue::PlainString)
3826 }
3827 }
3828 #[cfg(feature = "serde")]
3829 MonthNames::LeapLinear(leap_linear) => {
3830 let num_months = leap_linear.len() / 2;
3831 if month.leap_status() == LeapStatus::Leap {
3832 leap_linear.get(month_index + num_months)
3833 } else if month.leap_status() == LeapStatus::Base && month.number() < month.ordinal
3834 {
3835 // Detects Hebrew (base after leap) vs Chinese (base before leap).
3836 // In Hebrew, we use leap names for LeapBase months.
3837 leap_linear.get(month_index + num_months)
3838 } else if month_index < num_months {
3839 leap_linear.get(month_index)
3840 } else {
3841 None
3842 }
3843 .map(MonthPlaceholderValue::PlainString)
3844 }
3845 MonthNames::LeapNumeric(leap_numeric) => {
3846 if month.leap_status() == LeapStatus::Leap {
3847 Some(MonthPlaceholderValue::NumericPattern(leap_numeric, 0))
3848 } else {
3849 Some(MonthPlaceholderValue::Numeric)
3850 }
3851 }
3852 MonthNames::LeapNumericWithBase(patterns) => {
3853 if month.leap_status() == LeapStatus::Leap {
3854 let Some(tuple) = patterns.get(0) else {
3855 return Ok(MonthPlaceholderValue::Numeric);
3856 };
3857 Some(MonthPlaceholderValue::NumericPattern(
3858 &tuple.variable,
3859 tuple.sized,
3860 ))
3861 } else if month.leap_status() == LeapStatus::Base {
3862 let Some(tuple) = patterns.get(1) else {
3863 return Ok(MonthPlaceholderValue::Numeric);
3864 };
3865 Some(MonthPlaceholderValue::NumericPattern(
3866 &tuple.variable,
3867 tuple.sized,
3868 ))
3869 } else {
3870 Some(MonthPlaceholderValue::Numeric)
3871 }
3872 }
3873 MonthNames::LeapPattern(data) => if month_index < data.len() - 2 {
3874 data.get(month_index)
3875 } else {
3876 None
3877 }
3878 .and_then(|normal_name| {
3879 Some(match month.leap_status() {
3880 LeapStatus::Normal => MonthPlaceholderValue::PlainString(normal_name),
3881 LeapStatus::Leap => MonthPlaceholderValue::StringPattern(
3882 normal_name,
3883 SinglePlaceholderPattern::from_ref_store(&data[data.len() - 2]).ok()?,
3884 ),
3885 LeapStatus::Base => MonthPlaceholderValue::StringPattern(
3886 normal_name,
3887 SinglePlaceholderPattern::from_ref_store(&data[data.len() - 1]).ok()?,
3888 ),
3889 _ => {
3890 debug_assert!(false, "unhandled LeapStatus");
3891 MonthPlaceholderValue::PlainString(normal_name)
3892 }
3893 })
3894 }),
3895 }
3896 // Note: Always return `false` for the second argument since neo MonthNames
3897 // knows how to handle leap months and we don't need the fallback logic
3898 .ok_or(GetNameForMonthError::InvalidMonthCode)
3899 }
3900
3901 pub(crate) fn get_name_for_weekday(
3902 &self,
3903 field_symbol: fields::Weekday,
3904 field_length: FieldLength,
3905 day: icu_calendar::types::Weekday,
3906 ) -> Result<&str, GetNameForWeekdayError> {
3907 let weekday_name_length = WeekdayNameLength::from_field(field_symbol, field_length)
3908 .ok_or(GetNameForWeekdayError::InvalidFieldLength)?;
3909 self.weekday_names
3910 .get_with_variables(weekday_name_length)
3911 .ok_or(GetNameForWeekdayError::NotLoaded)?
3912 .get(day)
3913 // Note: WeekdayNames does not guarantee names for all days
3914 .ok_or(GetNameForWeekdayError::NotLoaded)
3915 }
3916
3917 /// Gets the era symbol, or `None` if data is loaded but symbol isn't found.
3918 ///
3919 /// `None` should fall back to the era code directly, if, for example,
3920 /// a japanext datetime is formatted with a `DateTimeFormat<Japanese>`
3921 pub(crate) fn get_name_for_era(
3922 &self,
3923 field_length: FieldLength,
3924 era_year: EraYear,
3925 ) -> Result<&str, GetNameForEraError> {
3926 let year_name_length = YearNameLength::from_field_length(field_length)
3927 .ok_or(GetNameForEraError::InvalidFieldLength)?;
3928 let year_names = self
3929 .year_names
3930 .get_with_variables(year_name_length)
3931 .ok_or(GetNameForEraError::NotLoaded)?;
3932
3933 match year_names {
3934 #[cfg(feature = "serde")]
3935 YearNames::VariableEras(era_names) => {
3936 get_year_name_from_map(era_names, era_year.era.as_str().into())
3937 .ok_or(GetNameForEraError::InvalidEraCode)
3938 }
3939 YearNames::FixedEras(era_names) => era_names
3940 .get(if let Some(i) = era_year.era_index {
3941 i as usize
3942 } else {
3943 debug_assert!(false, "missing era index");
3944 usize::MAX
3945 })
3946 .ok_or(GetNameForEraError::InvalidEraCode),
3947 YearNames::Cyclic(_) => Err(GetNameForEraError::InvalidEraCode),
3948 }
3949 }
3950
3951 pub(crate) fn get_name_for_cyclic(
3952 &self,
3953 field_length: FieldLength,
3954 cyclic: u8,
3955 ) -> Result<&str, GetNameForCyclicYearError> {
3956 let year_name_length = YearNameLength::from_field_length(field_length)
3957 .ok_or(GetNameForCyclicYearError::InvalidFieldLength)?;
3958 let year_names = self
3959 .year_names
3960 .get_with_variables(year_name_length)
3961 .ok_or(GetNameForCyclicYearError::NotLoaded)?;
3962
3963 let YearNames::Cyclic(cyclics) = year_names else {
3964 return Err(GetNameForCyclicYearError::InvalidYearNumber { max: 0 });
3965 };
3966
3967 cyclics
3968 .get(cyclic as usize - 1)
3969 .ok_or(GetNameForCyclicYearError::InvalidYearNumber {
3970 max: cyclics.len() as u8 + 1,
3971 })
3972 }
3973
3974 pub(crate) fn get_name_for_day_period(
3975 &self,
3976 field_symbol: fields::DayPeriod,
3977 field_length: FieldLength,
3978 hour: icu_time::Hour,
3979 is_top_of_hour: bool,
3980 ) -> Result<&str, GetNameForDayPeriodError> {
3981 use fields::DayPeriod::{Flexible, NoonMidnight};
3982 let day_period_name_length = DayPeriodNameLength::from_field(field_symbol, field_length)
3983 .ok_or(GetNameForDayPeriodError::InvalidFieldLength)?;
3984 let dayperiod_names = self
3985 .dayperiod_names
3986 .get_with_variables(day_period_name_length)
3987 .ok_or(GetNameForDayPeriodError::NotLoaded)?;
3988
3989 if field_symbol == Flexible {
3990 if let Some(name) = dayperiod_names.flexible_day_period(hour) {
3991 return Ok(name);
3992 } else {
3993 // No flexible names for locale, fall through
3994 }
3995 }
3996
3997 if field_symbol == NoonMidnight && is_top_of_hour && hour.number() == 0 {
3998 if let Some(midnight) = dayperiod_names.midnight() {
3999 return Ok(midnight);
4000 } else {
4001 // No midnight name for locale, fall through
4002 }
4003 }
4004
4005 if field_symbol == NoonMidnight && is_top_of_hour && hour.number() == 12 {
4006 if let Some(noon) = dayperiod_names.noon() {
4007 return Ok(noon);
4008 } else {
4009 // No noon name for locale, fall through
4010 }
4011 }
4012
4013 if hour.number() < 12 {
4014 dayperiod_names.am()
4015 } else {
4016 dayperiod_names.pm()
4017 }
4018 .ok_or(GetNameForDayPeriodError::NotLoaded)
4019 }
4020}
4021
4022/// A container contains all data payloads for time zone formatting (borrowed version).
4023#[derive(Debug, Copy, Clone, Default)]
4024pub(crate) struct TimeZoneDataPayloadsBorrowed<'a> {
4025 /// The data that contains meta information about how to display content.
4026 pub(crate) essentials: Option<&'a tz::Essentials<'a>>,
4027 /// The root location names, e.g. Italy
4028 pub(crate) locations_root: Option<&'a tz::Locations<'a>>,
4029 /// The language specific location names, e.g. Italia
4030 pub(crate) locations: Option<&'a tz::Locations<'a>>,
4031 /// The root exemplar city names, e.g. Rome
4032 pub(crate) exemplars_root: Option<&'a tz::ExemplarCities<'a>>,
4033 /// The language specific exemplar names, e.g. Roma
4034 pub(crate) exemplars: Option<&'a tz::ExemplarCities<'a>>,
4035 /// The generic long metazone names, e.g. Pacific Time
4036 pub(crate) mz_generic_long: Option<&'a tz::MzGeneric<'a>>,
4037 /// The long metazone names shared between generic and standard, e.g. Gulf Standard Time
4038 pub(crate) mz_standard_long: Option<&'a tz::MzGeneric<'a>>,
4039 /// The generic short metazone names, e.g. PT
4040 pub(crate) mz_generic_short: Option<&'a tz::MzGeneric<'a>>,
4041 /// The specific long metazone names, e.g. Pacific Daylight Time
4042 pub(crate) mz_specific_long: Option<&'a tz::MzSpecific<'a>>,
4043 /// The specific short metazone names, e.g. Pacific Daylight Time
4044 pub(crate) mz_specific_short: Option<&'a tz::MzSpecific<'a>>,
4045 /// The metazone lookup
4046 pub(crate) mz_periods: Option<&'a tz::MzPeriod<'a>>,
4047}
4048
4049impl<'data> RawDateTimeNamesBorrowed<'data> {
4050 pub(crate) fn get_payloads(&self) -> TimeZoneDataPayloadsBorrowed<'data> {
4051 TimeZoneDataPayloadsBorrowed {
4052 essentials: self.zone_essentials.get_option(),
4053 locations_root: self.locations_root.get_option(),
4054 locations: self.locations.get_option(),
4055 exemplars: self.exemplars.get_option(),
4056 exemplars_root: self.exemplars_root.get_option(),
4057 mz_generic_long: self.mz_generic_long.get_option(),
4058 mz_standard_long: self.mz_standard_long.get_option(),
4059 mz_generic_short: self.mz_generic_short.get_option(),
4060 mz_specific_long: self.mz_specific_long.get_option(),
4061 mz_specific_short: self.mz_specific_short.get_option(),
4062 mz_periods: self.mz_periods.get_option(),
4063 }
4064 }
4065}