Debian Codegraph @

debian/rust-vendor/icu_datetime/src/scaffold/calendar.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 //! Scaffolding traits and impls for calendars.
6
7 use crate::MismatchedCalendarError;
8 use crate::provider::{names::*, packed_pattern::*, range_patterns::*, semantic_skeletons::*};
9 use crate::scaffold::UnstableSealed;
10 use core::marker::PhantomData;
11 use icu_calendar::cal;
12 use icu_calendar::preferences::{CalendarAlgorithm, CalendarPreferences, HijriCalendarAlgorithm};
13 use icu_calendar::provider::CalendarPreferredV1;
14 use icu_calendar::types::Weekday;
15 use icu_calendar::{AnyCalendar, AnyCalendarKind, AsCalendar, Date, IntoAnyCalendar, Ref};
16 use icu_provider::marker::NeverMarker;
17 use icu_provider::prelude::*;
18 #[cfg(feature = "unstable")]
19 use icu_time::ZonedTime;
20 use icu_time::{
21 DateTime, Time, TimeZoneInfo, ZonedDateTime,
22 zone::{UtcOffset, models::TimeZoneModel},
23 };
24
25 /// A calendar that can be found in CLDR.
26 ///
27 /// New implementors of this trait will likely also wish to modify `get_era_code_map()`
28 /// in the CLDR transformer to support any new era maps.
29 ///
30 /// <div class="stab unstable">
31 /// 🚫 This trait is sealed; it cannot be implemented by user code. If an API requests an item that implements this
32 /// trait, please consider using a type from the implementors listed below.
33 /// </div>
34 pub trait CldrCalendar: UnstableSealed {
35 /// The data marker for loading year symbols for this calendar.
36 type YearNamesV1: DataMarker<DataStruct = YearNames<'static>>;
37
38 /// The data marker for loading month symbols for this calendar.
39 type MonthNamesV1: DataMarker<DataStruct = MonthNames<'static>>;
40
41 /// The data marker for loading skeleton patterns for this calendar.
42 type SkeletaV1: DataMarker<DataStruct = PackedPatterns<'static>>;
43
44 /// The data marker for loading range skeleton patterns for this calendar.
45 type RangeSkeletaV1: DataMarker<DataStruct = PackedRangePatterns<'static>>;
46 }
47
48 impl CldrCalendar for () {
49 type YearNamesV1 = NeverMarker<YearNames<'static>>;
50 type MonthNamesV1 = NeverMarker<MonthNames<'static>>;
51 type SkeletaV1 = NeverMarker<PackedPatterns<'static>>;
52 type RangeSkeletaV1 = NeverMarker<PackedRangePatterns<'static>>;
53 }
54
55 impl CldrCalendar for cal::Buddhist {
56 type YearNamesV1 = DatetimeNamesYearBuddhistV1;
57 type MonthNamesV1 = DatetimeNamesMonthBuddhistV1;
58 type SkeletaV1 = DatetimePatternsDateBuddhistV1;
59 type RangeSkeletaV1 = DatetimePatternsRangeDateBuddhistV1;
60 }
61
62 impl CldrCalendar for cal::ChineseTraditional {
63 type YearNamesV1 = DatetimeNamesYearChineseV1;
64 type MonthNamesV1 = DatetimeNamesMonthChineseV1;
65 type SkeletaV1 = DatetimePatternsDateChineseV1;
66 type RangeSkeletaV1 = DatetimePatternsRangeDateChineseV1;
67 }
68
69 impl CldrCalendar for cal::Coptic {
70 type YearNamesV1 = DatetimeNamesYearCopticV1;
71 type MonthNamesV1 = DatetimeNamesMonthCopticV1;
72 type SkeletaV1 = DatetimePatternsDateCopticV1;
73 type RangeSkeletaV1 = DatetimePatternsRangeDateCopticV1;
74 }
75
76 impl CldrCalendar for cal::KoreanTraditional {
77 type YearNamesV1 = DatetimeNamesYearDangiV1;
78 type MonthNamesV1 = DatetimeNamesMonthDangiV1;
79 type SkeletaV1 = DatetimePatternsDateDangiV1;
80 type RangeSkeletaV1 = DatetimePatternsRangeDateDangiV1;
81 }
82
83 impl CldrCalendar for cal::Ethiopian {
84 type YearNamesV1 = DatetimeNamesYearEthiopianV1;
85 type MonthNamesV1 = DatetimeNamesMonthEthiopianV1;
86 type SkeletaV1 = DatetimePatternsDateEthiopianV1;
87 type RangeSkeletaV1 = DatetimePatternsRangeDateEthiopianV1;
88 }
89
90 impl CldrCalendar for cal::Gregorian {
91 type YearNamesV1 = DatetimeNamesYearGregorianV1;
92 type MonthNamesV1 = DatetimeNamesMonthGregorianV1;
93 type SkeletaV1 = DatetimePatternsDateGregorianV1;
94 type RangeSkeletaV1 = DatetimePatternsRangeDateGregorianV1;
95 }
96
97 impl CldrCalendar for cal::Hebrew {
98 type YearNamesV1 = DatetimeNamesYearHebrewV1;
99 type MonthNamesV1 = DatetimeNamesMonthHebrewV1;
100 type SkeletaV1 = DatetimePatternsDateHebrewV1;
101 type RangeSkeletaV1 = DatetimePatternsRangeDateHebrewV1;
102 }
103
104 impl CldrCalendar for cal::Indian {
105 type YearNamesV1 = DatetimeNamesYearIndianV1;
106 type MonthNamesV1 = DatetimeNamesMonthIndianV1;
107 type SkeletaV1 = DatetimePatternsDateIndianV1;
108 type RangeSkeletaV1 = DatetimePatternsRangeDateIndianV1;
109 }
110
111 /// [`hijri::Rules`](cal::hijri::unstable_internal::Rules)-specific formatting options.
112 ///
113 /// See [`CldrCalendar`].
114 ///
115 /// The simplest implementation of this uses the same names
116 /// as some provided [`hijri::Rules`](cal::hijri::unstable_internal::Rules):
117 ///
118 /// ```rust
119 /// use icu::calendar::cal::hijri;
120 /// use icu::datetime::scaffold::FormattableHijriRules;
121 ///
122 /// #[derive(Clone, Debug)]
123 /// struct MyRules;
124 ///
125 /// impl icu::calendar::cal::scaffold::UnstableSealed for MyRules {}
126 /// impl icu::datetime::scaffold::UnstableSealed for MyRules {}
127 ///
128 /// impl hijri::Rules for MyRules {
129 /// // ...
130 /// # fn year(&self, _year: i32) -> hijri::HijriYear {
131 /// # todo!()
132 /// # }
133 /// # type DateCompatibilityError = core::convert::Infallible;
134 /// # fn check_date_compatibility(&self, _: &Self) -> Result<(), Self::DateCompatibilityError> { Ok(()) }
135 /// }
136 ///
137 /// impl FormattableHijriRules for MyRules {
138 /// type YearNamesV1 =
139 /// <hijri::UmmAlQura as FormattableHijriRules>::YearNamesV1;
140 /// type MonthNamesV1 =
141 /// <hijri::UmmAlQura as FormattableHijriRules>::MonthNamesV1;
142 /// type SkeletaV1 = <hijri::UmmAlQura as FormattableHijriRules>::SkeletaV1;
143 /// type RangeSkeletaV1 = <hijri::UmmAlQura as FormattableHijriRules>::RangeSkeletaV1;
144 /// }
145 /// ```
146 // TODO: default associated types would be nice (https://github.com/rust-lang/rust/issues/29661)
147 pub trait FormattableHijriRules: cal::hijri::unstable_internal::Rules + UnstableSealed {
148 /// The data marker for loading year symbols for this calendar.
149 type YearNamesV1: DataMarker<DataStruct = YearNames<'static>>;
150
151 /// The data marker for loading month symbols for this calendar.
152 type MonthNamesV1: DataMarker<DataStruct = MonthNames<'static>>;
153
154 /// The data marker for loading skeleton patterns for this calendar.
155 type SkeletaV1: DataMarker<DataStruct = PackedPatterns<'static>>;
156
157 /// The data marker for loading range skeleton patterns for this calendar.
158 type RangeSkeletaV1: DataMarker<DataStruct = PackedRangePatterns<'static>>;
159 }
160
161 impl UnstableSealed for cal::hijri::TabularAlgorithm {}
162 impl FormattableHijriRules for cal::hijri::TabularAlgorithm {
163 type YearNamesV1 = DatetimeNamesYearHijriV1;
164 type MonthNamesV1 = DatetimeNamesMonthHijriV1;
165 type SkeletaV1 = DatetimePatternsDateHijriV1;
166 type RangeSkeletaV1 = DatetimePatternsRangeDateHijriV1;
167 }
168
169 impl UnstableSealed for cal::hijri::UmmAlQura {}
170 impl FormattableHijriRules for cal::hijri::UmmAlQura {
171 type YearNamesV1 = DatetimeNamesYearHijriV1;
172 type MonthNamesV1 = DatetimeNamesMonthHijriV1;
173 type SkeletaV1 = DatetimePatternsDateHijriV1;
174 type RangeSkeletaV1 = DatetimePatternsRangeDateHijriV1;
175 }
176
177 #[allow(deprecated)]
178 impl UnstableSealed for cal::hijri::AstronomicalSimulation {}
179 #[allow(deprecated)]
180 impl FormattableHijriRules for cal::hijri::AstronomicalSimulation {
181 type YearNamesV1 = DatetimeNamesYearHijriV1;
182 type MonthNamesV1 = DatetimeNamesMonthHijriV1;
183 type SkeletaV1 = DatetimePatternsDateHijriV1;
184 type RangeSkeletaV1 = DatetimePatternsRangeDateHijriV1;
185 }
186
187 impl<R: FormattableHijriRules> CldrCalendar for cal::Hijri<R> {
188 type YearNamesV1 = R::YearNamesV1;
189 type MonthNamesV1 = R::MonthNamesV1;
190 type SkeletaV1 = R::SkeletaV1;
191 type RangeSkeletaV1 = R::RangeSkeletaV1;
192 }
193
194 impl CldrCalendar for cal::Japanese {
195 type YearNamesV1 = DatetimeNamesYearJapaneseV1;
196 type MonthNamesV1 = DatetimeNamesMonthJapaneseV1;
197 type SkeletaV1 = DatetimePatternsDateJapaneseV1;
198 type RangeSkeletaV1 = DatetimePatternsRangeDateJapaneseV1;
199 }
200
201 impl CldrCalendar for cal::Persian {
202 type YearNamesV1 = DatetimeNamesYearPersianV1;
203 type MonthNamesV1 = DatetimeNamesMonthPersianV1;
204 type SkeletaV1 = DatetimePatternsDatePersianV1;
205 type RangeSkeletaV1 = DatetimePatternsRangeDatePersianV1;
206 }
207
208 impl CldrCalendar for cal::Roc {
209 type YearNamesV1 = DatetimeNamesYearRocV1;
210 type MonthNamesV1 = DatetimeNamesMonthRocV1;
211 type SkeletaV1 = DatetimePatternsDateRocV1;
212 type RangeSkeletaV1 = DatetimePatternsRangeDateRocV1;
213 }
214
215 impl UnstableSealed for () {}
216 impl UnstableSealed for cal::Buddhist {}
217 impl UnstableSealed for cal::ChineseTraditional {}
218 impl UnstableSealed for cal::Coptic {}
219 impl UnstableSealed for cal::KoreanTraditional {}
220 impl UnstableSealed for cal::Ethiopian {}
221 impl UnstableSealed for cal::Gregorian {}
222 impl UnstableSealed for cal::Hebrew {}
223 impl UnstableSealed for cal::Indian {}
224 impl<R: cal::hijri::unstable_internal::Rules> UnstableSealed for cal::Hijri<R> {}
225 impl UnstableSealed for cal::Japanese {}
226 impl UnstableSealed for cal::Persian {}
227 impl UnstableSealed for cal::Roc {}
228
229 /// A collection of marker types associated with all formattable calendars.
230 ///
231 /// This is used to group together the calendar-specific marker types that produce a common
232 /// [`DynamicDataMarker`]. For example, this trait can be implemented for [`YearNamesV1`].
233 ///
234 /// This trait serves as a building block for a cross-calendar [`BoundDataProvider`].
235 ///
236 /// <div class="stab unstable">
237 /// 🚧 This trait is considered unstable; it may change at any time, in breaking or non-breaking ways,
238 /// including in SemVer minor releases. Do not implement this trait in userland unless you are prepared for things to occasionally break.
239 /// </div>
240 pub trait CalMarkers<M>: UnstableSealed
241 where
242 M: DynamicDataMarker,
243 {
244 /// The type for a [`Buddhist`](cal::Buddhist) calendar
245 type Buddhist: DataMarker<DataStruct = M::DataStruct>;
246 /// The type for a [`Chinese`](cal::Chinese) calendar
247 type Chinese: DataMarker<DataStruct = M::DataStruct>;
248 /// The type for a [`Coptic`](cal::Coptic) calendar
249 type Coptic: DataMarker<DataStruct = M::DataStruct>;
250 /// The type for a [`Dangi`](cal::Dangi) calendar
251 type Dangi: DataMarker<DataStruct = M::DataStruct>;
252 /// The type for an [`Ethiopian`](cal::Ethiopian) calendar (either era style)
253 type Ethiopian: DataMarker<DataStruct = M::DataStruct>;
254 /// The type for a [`Gregorian`](cal::Gregorian) calendar
255 type Gregorian: DataMarker<DataStruct = M::DataStruct>;
256 /// The type for a [`Hebrew`](cal::Hebrew) calendar
257 type Hebrew: DataMarker<DataStruct = M::DataStruct>;
258 /// The type for a [`Indian`](cal::Indian) calendar
259 type Indian: DataMarker<DataStruct = M::DataStruct>;
260 /// The type for Hirji calendars
261 type Hijri: DataMarker<DataStruct = M::DataStruct>;
262 /// The type for a [`Japanese`](cal::Japanese) calendar
263 type Japanese: DataMarker<DataStruct = M::DataStruct>;
264 /// The type for a [`Persian`](cal::Persian) calendar
265 type Persian: DataMarker<DataStruct = M::DataStruct>;
266 /// The type for a [`Roc`](cal::Roc) calendar
267 type Roc: DataMarker<DataStruct = M::DataStruct>;
268 }
269
270 /// Implementation of [`CalMarkers`] that includes data for all calendars.
271 #[derive(Debug)]
272 #[allow(clippy::exhaustive_enums)] // empty enum
273 pub enum FullDataCalMarkers {}
274
275 impl UnstableSealed for FullDataCalMarkers {}
276
277 /// Implementation of [`CalMarkers`] that includes data for no calendars.
278 #[derive(Debug)]
279 #[allow(clippy::exhaustive_enums)] // empty enum
280 pub enum NoDataCalMarkers {}
281
282 impl UnstableSealed for NoDataCalMarkers {}
283
284 impl<M> CalMarkers<M> for NoDataCalMarkers
285 where
286 M: DynamicDataMarker,
287 {
288 type Buddhist = NeverMarker<M::DataStruct>;
289 type Chinese = NeverMarker<M::DataStruct>;
290 type Coptic = NeverMarker<M::DataStruct>;
291 type Dangi = NeverMarker<M::DataStruct>;
292 type Ethiopian = NeverMarker<M::DataStruct>;
293 type Gregorian = NeverMarker<M::DataStruct>;
294 type Hebrew = NeverMarker<M::DataStruct>;
295 type Indian = NeverMarker<M::DataStruct>;
296 type Hijri = NeverMarker<M::DataStruct>;
297 type Japanese = NeverMarker<M::DataStruct>;
298 type Persian = NeverMarker<M::DataStruct>;
299 type Roc = NeverMarker<M::DataStruct>;
300 }
301
302 /// A calendar type that is supported by [`DateTimeFormatter`](crate::DateTimeFormatter).
303 ///
304 /// [`FixedCalendarDateTimeFormatter`](crate::FixedCalendarDateTimeFormatter) might support additional calendars.
305 pub trait IntoFormattableAnyCalendar: CldrCalendar + IntoAnyCalendar {}
306
307 // keep in sync with FormattableAnyCalendarKind
308 impl IntoFormattableAnyCalendar for cal::Buddhist {}
309 impl IntoFormattableAnyCalendar for cal::ChineseTraditional {}
310 impl IntoFormattableAnyCalendar for cal::Coptic {}
311 impl IntoFormattableAnyCalendar for cal::KoreanTraditional {}
312 impl IntoFormattableAnyCalendar for cal::Ethiopian {}
313 impl IntoFormattableAnyCalendar for cal::Gregorian {}
314 impl IntoFormattableAnyCalendar for cal::Hebrew {}
315 impl IntoFormattableAnyCalendar for cal::Indian {}
316 impl IntoFormattableAnyCalendar for cal::Hijri<cal::hijri::TabularAlgorithm> {}
317 #[allow(deprecated)]
318 impl IntoFormattableAnyCalendar for cal::Hijri<cal::hijri::AstronomicalSimulation> {}
319 impl IntoFormattableAnyCalendar for cal::Hijri<cal::hijri::UmmAlQura> {}
320 // _NOT_ Hijri<S>
321 impl IntoFormattableAnyCalendar for cal::Japanese {}
322 impl IntoFormattableAnyCalendar for cal::Persian {}
323 impl IntoFormattableAnyCalendar for cal::Roc {}
324
325 // keep in sync with IntoFormattableAnyCalendar
326 #[derive(Debug, Clone, Copy, PartialEq)]
327 enum FormattableAnyCalendarKind {
328 Buddhist,
329 Chinese,
330 Coptic,
331 Dangi,
332 Ethiopian,
333 EthiopianAmeteAlem,
334 Gregorian,
335 Hebrew,
336 Indian,
337 HijriTabularTypeIIFriday,
338 // _NOT_ HijriSimulatedMecca
339 HijriTabularTypeIIThursday,
340 HijriUmmAlQura,
341 Japanese,
342 Persian,
343 Roc,
344 }
345
346 impl FormattableAnyCalendarKind {
347 fn try_from_any_calendar(cal: &AnyCalendar) -> Option<Self> {
348 use AnyCalendarKind::*;
349 let res = match cal.kind() {
350 Buddhist => Self::Buddhist,
351 Chinese => Self::Chinese,
352 Coptic => Self::Coptic,
353 Dangi => Self::Dangi,
354 Ethiopian => Self::Ethiopian,
355 EthiopianAmeteAlem => Self::EthiopianAmeteAlem,
356 Gregorian => Self::Gregorian,
357 Hebrew => Self::Hebrew,
358 Indian => Self::Indian,
359 HijriTabularTypeIIFriday => Self::HijriTabularTypeIIFriday,
360 HijriSimulatedMecca => return None,
361 HijriTabularTypeIIThursday => Self::HijriTabularTypeIIThursday,
362 HijriUmmAlQura => Self::HijriUmmAlQura,
363 Iso => return None,
364 #[allow(deprecated)]
365 Japanese | JapaneseExtended => Self::Japanese,
366 Persian => Self::Persian,
367 Roc => Self::Roc,
368 _ => {
369 debug_assert!(false, "cross-crate exhaustive match");
370 return None;
371 }
372 };
373 Some(res)
374 }
375 }
376
377 #[test]
378 fn test_calendar_fallback() {
379 #[allow(non_local_definitions)] // only used in this test
380 impl PartialEq for FormattableAnyCalendar {
381 fn eq(&self, other: &Self) -> bool {
382 self.any_calendar.kind() == other.any_calendar.kind()
383 }
384 }
385
386 use icu_locale_core::{Locale, locale};
387 assert_eq!(
388 FormattableAnyCalendar::try_new(locale!("en-TH-u-ca-iso8601").into()),
389 FormattableAnyCalendar::try_new(locale!("und-u-ca-buddhist").into()),
390 );
391 assert_eq!(
392 FormattableAnyCalendar::try_new(locale!("en-TH").into()),
393 FormattableAnyCalendar::try_new(locale!("und-u-ca-buddhist").into()),
394 );
395 assert_eq!(
396 FormattableAnyCalendar::try_new(locale!("th").into()),
397 FormattableAnyCalendar::try_new(locale!("und-u-ca-buddhist").into()),
398 );
399 assert_eq!(
400 FormattableAnyCalendar::try_new(locale!("fa").into()),
401 FormattableAnyCalendar::try_new(locale!("und-u-ca-persian").into()),
402 );
403 assert_eq!(
404 FormattableAnyCalendar::try_new(locale!("en-SA-u-ca-islamic").into()),
405 FormattableAnyCalendar::try_new(
406 Locale::try_from_str("und-u-ca-islamic-umalqura")
407 .unwrap()
408 .into()
409 ),
410 );
411 assert_eq!(
412 FormattableAnyCalendar::try_new(locale!("en-IL-u-ca-islamic").into()),
413 FormattableAnyCalendar::try_new(
414 Locale::try_from_str("und-u-ca-islamic-civil")
415 .unwrap()
416 .into()
417 ),
418 );
419 }
420
421 /// A version of [`AnyCalendar`] for the calendars supported in the any-calendar formatter.
422 #[derive(Debug, Clone)]
423 pub(crate) struct FormattableAnyCalendar {
424 any_calendar: AnyCalendar,
425 }
426
427 impl FormattableAnyCalendar {
428 pub(crate) fn from_calendar(calendar: impl IntoFormattableAnyCalendar) -> Self {
429 Self {
430 any_calendar: calendar.to_any(),
431 }
432 }
433
434 pub(crate) fn try_from_any_calendar(any_calendar: AnyCalendar) -> Result<Self, AnyCalendar> {
435 match FormattableAnyCalendarKind::try_from_any_calendar(&any_calendar) {
436 Some(_) => Ok(Self { any_calendar }),
437 None => Err(any_calendar),
438 }
439 }
440
441 pub(crate) fn any_calendar(&self) -> &AnyCalendar {
442 &self.any_calendar
443 }
444
445 fn kind(&self) -> FormattableAnyCalendarKind {
446 FormattableAnyCalendarKind::try_from_any_calendar(&self.any_calendar).unwrap_or_else(|| {
447 debug_assert!(false, "unreachable by invariant");
448 // fall back to something non-Gregorian to make errors more obvious
449 FormattableAnyCalendarKind::Coptic
450 })
451 }
452
453 pub(crate) fn take_any_calendar(self) -> AnyCalendar {
454 self.any_calendar
455 }
456
457 #[cfg(feature = "compiled_data")]
458 pub(crate) fn try_new(prefs: CalendarPreferences) -> Result<Self, DataError> {
459 Self::try_new_unstable(&icu_calendar::provider::Baked, prefs)
460 }
461
462 #[cfg(feature = "serde")]
463 pub(crate) fn try_new_with_buffer_provider<P>(
464 provider: &P,
465 prefs: CalendarPreferences,
466 ) -> Result<Self, DataError>
467 where
468 P: ?Sized + BufferProvider,
469 {
470 Self::try_new_unstable(&provider.as_deserializing(), prefs)
471 }
472
473 pub(crate) fn try_new_unstable<P>(
474 provider: &P,
475 mut prefs: CalendarPreferences,
476 ) -> Result<Self, DataError>
477 where
478 P: ?Sized
479 + DataProvider<icu_calendar::provider::CalendarJapaneseModernV1>
480 + DataProvider<CalendarPreferredV1>,
481 {
482 use CalendarAlgorithm::*;
483
484 if prefs.calendar_algorithm == Some(Iso8601) {
485 // Resolve iso8601 to the region's default.
486 prefs.calendar_algorithm = None;
487 }
488 if prefs.calendar_algorithm == Some(Hijri(Some(HijriCalendarAlgorithm::Rgsa))) {
489 // Resolve islamic-rgsa to the region's Hijri default.
490 prefs.calendar_algorithm = Some(Hijri(None));
491 }
492
493 let algorithm = match prefs.calendar_algorithm {
494 Some(algorithm) if !matches!(algorithm, Hijri(None)) => algorithm,
495 unresolved => DataProvider::<CalendarPreferredV1>::load(
496 &provider,
497 DataRequest {
498 id: DataIdentifierBorrowed::for_locale(&CalendarPreferredV1::make_locale(
499 prefs.locale_preferences,
500 )),
501 metadata: Default::default(),
502 },
503 )?
504 .payload
505 .get()
506 .resolve(unresolved),
507 };
508
509 let any_calendar = match algorithm {
510 Buddhist => AnyCalendar::Buddhist(cal::Buddhist),
511 Chinese => AnyCalendar::Chinese(cal::ChineseTraditional::new()),
512 Coptic => AnyCalendar::Coptic(cal::Coptic),
513 Dangi => AnyCalendar::Dangi(cal::KoreanTraditional::new()),
514 Ethiopic => AnyCalendar::Ethiopian(cal::Ethiopian::new()),
515 Ethioaa => AnyCalendar::Ethiopian(cal::Ethiopian::new_with_era_style(
516 cal::EthiopianEraStyle::AmeteAlem,
517 )),
518 Gregory => AnyCalendar::Gregorian(cal::Gregorian),
519 Hebrew => AnyCalendar::Hebrew(cal::Hebrew),
520 Indian => AnyCalendar::Indian(cal::Indian),
521 Hijri(Some(HijriCalendarAlgorithm::Civil)) => {
522 AnyCalendar::HijriTabular(cal::Hijri::new_tabular(
523 cal::hijri::TabularAlgorithmLeapYears::TypeII,
524 cal::hijri::TabularAlgorithmEpoch::Friday,
525 ))
526 }
527 Hijri(Some(HijriCalendarAlgorithm::Tbla)) => {
528 AnyCalendar::HijriTabular(cal::Hijri::new_tabular(
529 cal::hijri::TabularAlgorithmLeapYears::TypeII,
530 cal::hijri::TabularAlgorithmEpoch::Thursday,
531 ))
532 }
533 Hijri(Some(HijriCalendarAlgorithm::Umalqura)) => {
534 AnyCalendar::HijriUmmAlQura(cal::Hijri::new_umm_al_qura())
535 }
536 Japanese => AnyCalendar::Japanese(cal::Japanese::try_new_unstable(provider)?),
537 Persian => AnyCalendar::Persian(cal::Persian),
538 Roc => AnyCalendar::Roc(cal::Roc),
539 Iso8601 | Hijri(_) => {
540 debug_assert!(false, "filtered out before and not default for any region");
541 AnyCalendar::Gregorian(cal::Gregorian)
542 }
543 _ => {
544 // unknown
545 AnyCalendar::Gregorian(cal::Gregorian)
546 }
547 };
548 Ok(Self { any_calendar })
549 }
550 }
551
552 pub(crate) struct FormattableAnyCalendarNamesLoader<'a, H, P> {
553 provider: P,
554 calendar: &'a FormattableAnyCalendar,
555 _helper: PhantomData<H>,
556 }
557
558 impl<'a, H, P> FormattableAnyCalendarNamesLoader<'a, H, P> {
559 pub(crate) fn new(provider: P, calendar: &'a FormattableAnyCalendar) -> Self {
560 Self {
561 provider,
562 calendar,
563 _helper: PhantomData,
564 }
565 }
566 }
567
568 impl<M, H, P> BoundDataProvider<M> for FormattableAnyCalendarNamesLoader<'_, H, P>
569 where
570 M: DynamicDataMarker,
571 H: CalMarkers<M>,
572 P: Sized
573 + DataProvider<H::Buddhist>
574 + DataProvider<H::Chinese>
575 + DataProvider<H::Coptic>
576 + DataProvider<H::Dangi>
577 + DataProvider<H::Ethiopian>
578 + DataProvider<H::Gregorian>
579 + DataProvider<H::Hebrew>
580 + DataProvider<H::Indian>
581 + DataProvider<H::Hijri>
582 + DataProvider<H::Japanese>
583 + DataProvider<H::Persian>
584 + DataProvider<H::Roc>,
585 {
586 fn load_bound(&self, req: DataRequest) -> Result<DataResponse<M>, DataError> {
587 use FormattableAnyCalendarKind::*;
588 let p = &self.provider;
589 match self.calendar.kind() {
590 Buddhist => H::Buddhist::bind(p).load_bound(req),
591 Chinese => H::Chinese::bind(p).load_bound(req),
592 Coptic => H::Coptic::bind(p).load_bound(req),
593 Dangi => H::Dangi::bind(p).load_bound(req),
594 Ethiopian | EthiopianAmeteAlem => H::Ethiopian::bind(p).load_bound(req),
595 Gregorian => H::Gregorian::bind(p).load_bound(req),
596 Hebrew => H::Hebrew::bind(p).load_bound(req),
597 Indian => H::Indian::bind(p).load_bound(req),
598 HijriTabularTypeIIFriday | HijriTabularTypeIIThursday | HijriUmmAlQura => {
599 H::Hijri::bind(p).load_bound(req)
600 }
601 Japanese => H::Japanese::bind(p).load_bound(req),
602 Persian => H::Persian::bind(p).load_bound(req),
603 Roc => H::Roc::bind(p).load_bound(req),
604 }
605 }
606 fn bound_marker(&self) -> DataMarkerInfo {
607 use FormattableAnyCalendarKind::*;
608 match self.calendar.kind() {
609 Buddhist => H::Buddhist::INFO,
610 Chinese => H::Chinese::INFO,
611 Coptic => H::Coptic::INFO,
612 Dangi => H::Dangi::INFO,
613 Ethiopian | EthiopianAmeteAlem => H::Ethiopian::INFO,
614 Gregorian => H::Gregorian::INFO,
615 Hebrew => H::Hebrew::INFO,
616 Indian => H::Indian::INFO,
617 HijriTabularTypeIIFriday | HijriTabularTypeIIThursday | HijriUmmAlQura => {
618 H::Hijri::INFO
619 }
620 Japanese => H::Japanese::INFO,
621 Persian => H::Persian::INFO,
622 Roc => H::Roc::INFO,
623 }
624 }
625 }
626
627 impl CalMarkers<YearNamesV1> for FullDataCalMarkers {
628 type Buddhist = <cal::Buddhist as CldrCalendar>::YearNamesV1;
629 type Chinese = <cal::ChineseTraditional as CldrCalendar>::YearNamesV1;
630 type Coptic = <cal::Coptic as CldrCalendar>::YearNamesV1;
631 type Dangi = <cal::KoreanTraditional as CldrCalendar>::YearNamesV1;
632 type Ethiopian = <cal::Ethiopian as CldrCalendar>::YearNamesV1;
633 type Gregorian = <cal::Gregorian as CldrCalendar>::YearNamesV1;
634 type Hebrew = <cal::Hebrew as CldrCalendar>::YearNamesV1;
635 type Indian = <cal::Indian as CldrCalendar>::YearNamesV1;
636 type Hijri = <cal::Hijri<cal::hijri::UmmAlQura> as CldrCalendar>::YearNamesV1;
637 type Japanese = <cal::Japanese as CldrCalendar>::YearNamesV1;
638 type Persian = <cal::Persian as CldrCalendar>::YearNamesV1;
639 type Roc = <cal::Roc as CldrCalendar>::YearNamesV1;
640 }
641
642 impl CalMarkers<MonthNamesV1> for FullDataCalMarkers {
643 type Buddhist = <cal::Buddhist as CldrCalendar>::MonthNamesV1;
644 type Chinese = <cal::ChineseTraditional as CldrCalendar>::MonthNamesV1;
645 type Coptic = <cal::Coptic as CldrCalendar>::MonthNamesV1;
646 type Dangi = <cal::KoreanTraditional as CldrCalendar>::MonthNamesV1;
647 type Ethiopian = <cal::Ethiopian as CldrCalendar>::MonthNamesV1;
648 type Gregorian = <cal::Gregorian as CldrCalendar>::MonthNamesV1;
649 type Hebrew = <cal::Hebrew as CldrCalendar>::MonthNamesV1;
650 type Indian = <cal::Indian as CldrCalendar>::MonthNamesV1;
651 type Hijri = <cal::Hijri<cal::hijri::UmmAlQura> as CldrCalendar>::MonthNamesV1;
652 type Japanese = <cal::Japanese as CldrCalendar>::MonthNamesV1;
653 type Persian = <cal::Persian as CldrCalendar>::MonthNamesV1;
654 type Roc = <cal::Roc as CldrCalendar>::MonthNamesV1;
655 }
656
657 impl CalMarkers<ErasedPackedPatterns> for FullDataCalMarkers {
658 type Buddhist = <cal::Buddhist as CldrCalendar>::SkeletaV1;
659 type Chinese = <cal::ChineseTraditional as CldrCalendar>::SkeletaV1;
660 type Coptic = <cal::Coptic as CldrCalendar>::SkeletaV1;
661 type Dangi = <cal::KoreanTraditional as CldrCalendar>::SkeletaV1;
662 type Ethiopian = <cal::Ethiopian as CldrCalendar>::SkeletaV1;
663 type Gregorian = <cal::Gregorian as CldrCalendar>::SkeletaV1;
664 type Hebrew = <cal::Hebrew as CldrCalendar>::SkeletaV1;
665 type Indian = <cal::Indian as CldrCalendar>::SkeletaV1;
666 type Hijri = <cal::Hijri<cal::hijri::UmmAlQura> as CldrCalendar>::SkeletaV1;
667 type Japanese = <cal::Japanese as CldrCalendar>::SkeletaV1;
668 type Persian = <cal::Persian as CldrCalendar>::SkeletaV1;
669 type Roc = <cal::Roc as CldrCalendar>::SkeletaV1;
670 }
671
672 impl CalMarkers<ErasedPackedRangePatterns> for FullDataCalMarkers {
673 type Buddhist = <cal::Buddhist as CldrCalendar>::RangeSkeletaV1;
674 type Chinese = <cal::ChineseTraditional as CldrCalendar>::RangeSkeletaV1;
675 type Coptic = <cal::Coptic as CldrCalendar>::RangeSkeletaV1;
676 type Dangi = <cal::KoreanTraditional as CldrCalendar>::RangeSkeletaV1;
677 type Ethiopian = <cal::Ethiopian as CldrCalendar>::RangeSkeletaV1;
678 type Gregorian = <cal::Gregorian as CldrCalendar>::RangeSkeletaV1;
679 type Hebrew = <cal::Hebrew as CldrCalendar>::RangeSkeletaV1;
680 type Indian = <cal::Indian as CldrCalendar>::RangeSkeletaV1;
681 type Hijri = <cal::Hijri<cal::hijri::UmmAlQura> as CldrCalendar>::RangeSkeletaV1;
682 type Japanese = <cal::Japanese as CldrCalendar>::RangeSkeletaV1;
683 type Persian = <cal::Persian as CldrCalendar>::RangeSkeletaV1;
684 type Roc = <cal::Roc as CldrCalendar>::RangeSkeletaV1;
685 }
686
687 /// A type that can be converted into a specific calendar system.
688 ///
689 /// You often want to set `Converted` to an ICU4X built-in type.
690 ///
691 /// If the type is not calendar-specific, such as a time or time zone, set `Converted`
692 /// to the same type and return it in the implementation.
693 // This trait is implementable
694 pub trait ConvertCalendar {
695 /// The converted type. This can be the same as the receiver type.
696 type Converted<'a>: Sized;
697 /// Converts `self` to the specified [`AnyCalendar`].
698 fn to_calendar<'a>(&self, calendar: &'a AnyCalendar) -> Self::Converted<'a>;
699 }
700
701 impl<C: IntoAnyCalendar, A: AsCalendar<Calendar = C>> ConvertCalendar for Date<A> {
702 type Converted<'a> = Date<Ref<'a, AnyCalendar>>;
703 #[inline]
704 fn to_calendar<'a>(&self, calendar: &'a AnyCalendar) -> Self::Converted<'a> {
705 self.to_calendar(Ref(calendar))
706 }
707 }
708
709 impl ConvertCalendar for Time {
710 type Converted<'a> = Time;
711 #[inline]
712 fn to_calendar<'a>(&self, _: &'a AnyCalendar) -> Self::Converted<'a> {
713 *self
714 }
715 }
716
717 impl<C: IntoAnyCalendar, A: AsCalendar<Calendar = C>> ConvertCalendar for DateTime<A> {
718 type Converted<'a> = DateTime<Ref<'a, AnyCalendar>>;
719 #[inline]
720 fn to_calendar<'a>(&self, calendar: &'a AnyCalendar) -> Self::Converted<'a> {
721 DateTime {
722 date: self.date.to_calendar(Ref(calendar)),
723 time: self.time,
724 }
725 }
726 }
727
728 impl<C: IntoAnyCalendar, A: AsCalendar<Calendar = C>, Z: Copy> ConvertCalendar
729 for ZonedDateTime<A, Z>
730 {
731 type Converted<'a> = ZonedDateTime<Ref<'a, AnyCalendar>, Z>;
732 #[inline]
733 fn to_calendar<'a>(&self, calendar: &'a AnyCalendar) -> Self::Converted<'a> {
734 ZonedDateTime {
735 date: self.date.to_calendar(Ref(calendar)),
736 time: self.time,
737 zone: self.zone,
738 }
739 }
740 }
741
742 impl ConvertCalendar for UtcOffset {
743 type Converted<'a> = UtcOffset;
744 #[inline]
745 fn to_calendar<'a>(&self, _: &'a AnyCalendar) -> Self::Converted<'a> {
746 *self
747 }
748 }
749
750 impl<O: TimeZoneModel> ConvertCalendar for TimeZoneInfo<O> {
751 type Converted<'a> = TimeZoneInfo<O>;
752 #[inline]
753 fn to_calendar<'a>(&self, _: &'a AnyCalendar) -> Self::Converted<'a> {
754 *self
755 }
756 }
757
758 impl ConvertCalendar for Weekday {
759 type Converted<'a> = Weekday;
760 #[inline]
761 fn to_calendar<'a>(&self, _: &'a AnyCalendar) -> Self::Converted<'a> {
762 *self
763 }
764 }
765
766 /// An input that may be associated with a specific runtime calendar.
767 // This trait is implementable
768 pub trait InSameCalendar {
769 /// Checks whether this type is compatible with the given calendar.
770 ///
771 /// Types that are agnostic to calendar systems should return `Ok(())`.
772 fn check_any_calendar_kind(
773 &self,
774 any_calendar_kind: AnyCalendarKind,
775 ) -> Result<(), MismatchedCalendarError>;
776 }
777
778 impl<C: IntoAnyCalendar, A: AsCalendar<Calendar = C>> InSameCalendar for Date<A> {
779 #[inline]
780 fn check_any_calendar_kind(
781 &self,
782 any_calendar_kind: AnyCalendarKind,
783 ) -> Result<(), MismatchedCalendarError> {
784 if self.calendar().kind() == any_calendar_kind {
785 Ok(())
786 } else {
787 Err(MismatchedCalendarError {
788 this_kind: any_calendar_kind,
789 date_kind: Some(self.calendar().kind()),
790 })
791 }
792 }
793 }
794
795 impl InSameCalendar for Time {
796 #[inline]
797 fn check_any_calendar_kind(&self, _: AnyCalendarKind) -> Result<(), MismatchedCalendarError> {
798 Ok(())
799 }
800 }
801
802 impl<C: IntoAnyCalendar, A: AsCalendar<Calendar = C>> InSameCalendar for DateTime<A> {
803 #[inline]
804 fn check_any_calendar_kind(
805 &self,
806 any_calendar_kind: AnyCalendarKind,
807 ) -> Result<(), MismatchedCalendarError> {
808 self.date.check_any_calendar_kind(any_calendar_kind)
809 }
810 }
811
812 impl<C: IntoAnyCalendar, A: AsCalendar<Calendar = C>, Z> InSameCalendar for ZonedDateTime<A, Z> {
813 #[inline]
814 fn check_any_calendar_kind(
815 &self,
816 any_calendar_kind: AnyCalendarKind,
817 ) -> Result<(), MismatchedCalendarError> {
818 self.date.check_any_calendar_kind(any_calendar_kind)
819 }
820 }
821
822 impl InSameCalendar for UtcOffset {
823 #[inline]
824 fn check_any_calendar_kind(&self, _: AnyCalendarKind) -> Result<(), MismatchedCalendarError> {
825 Ok(())
826 }
827 }
828
829 impl<O: TimeZoneModel> InSameCalendar for TimeZoneInfo<O> {
830 #[inline]
831 fn check_any_calendar_kind(&self, _: AnyCalendarKind) -> Result<(), MismatchedCalendarError> {
832 Ok(())
833 }
834 }
835
836 impl InSameCalendar for Weekday {
837 #[inline]
838 fn check_any_calendar_kind(&self, _: AnyCalendarKind) -> Result<(), MismatchedCalendarError> {
839 Ok(())
840 }
841 }
842
843 /// An input associated with a fixed, static calendar.
844 ///
845 /// Inputs that are not calendar-specific should blanket-impl this for all `C`.
846 // This trait is implementable
847 pub trait InFixedCalendar<C> {}
848
849 impl<C: CldrCalendar, A: AsCalendar<Calendar = C>> InFixedCalendar<C> for Date<A> {}
850
851 impl<C> InFixedCalendar<C> for Time {}
852
853 impl<C: CldrCalendar, A: AsCalendar<Calendar = C>> InFixedCalendar<C> for DateTime<A> {}
854
855 impl<C: CldrCalendar, A: AsCalendar<Calendar = C>, Z> InFixedCalendar<C> for ZonedDateTime<A, Z> {}
856
857 #[cfg(feature = "unstable")]
858 impl<C, Z> InFixedCalendar<C> for ZonedTime<Z> {}
859
860 impl<C> InFixedCalendar<C> for UtcOffset {}
861
862 impl<C, O: TimeZoneModel> InFixedCalendar<C> for TimeZoneInfo<O> {}
863
864 impl<C> InFixedCalendar<C> for Weekday {}