Skip to main content

icu_datetime/
neo.rs

1// This file is part of ICU4X. For terms of use, please see the file
2// called LICENSE at the top level of the ICU4X source tree
3// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5//! High-level entrypoints for Neo [`DateTimeFormatter`]
6
7use crate::MismatchedCalendarError;
8use crate::error::DateTimeFormatterLoadError;
9use crate::external_loaders::*;
10use crate::fieldsets::builder::FieldSetBuilder;
11use crate::fieldsets::enums::CompositeFieldSet;
12use crate::format::DateTimeInputUnchecked;
13use crate::format::datetime::try_write_pattern_items;
14use crate::pattern::*;
15use crate::preferences::{CalendarAlgorithm, HourCycle, NumberingSystem};
16use crate::raw::neo::*;
17use crate::scaffold::*;
18use crate::scaffold::{
19    AllInputMarkers, ConvertCalendar, DateDataMarkers, DateInputMarkers, DateTimeMarkers, GetField,
20    InFixedCalendar, InSameCalendar, TimeMarkers, TypedDateDataMarkers, ZoneMarkers,
21};
22use crate::size_test_macro::size_test;
23use core::fmt;
24use core::marker::PhantomData;
25use icu_calendar::{AnyCalendar, IntoAnyCalendar, preferences::CalendarPreferences};
26use icu_decimal::DecimalFormatterPreferences;
27use icu_locale_core::preferences::{define_preferences, prefs_convert};
28use icu_provider::prelude::*;
29use writeable::{Writeable, impl_display_with_writeable};
30
31define_preferences!(
32    /// The user locale preferences for datetime formatting.
33    ///
34    /// # Examples
35    ///
36    /// Two ways to build a preferences bag with a custom hour cycle and calendar system:
37    ///
38    /// ```
39    /// use icu::datetime::DateTimeFormatterPreferences;
40    /// use icu::locale::Locale;
41    /// use icu::locale::preferences::extensions::unicode::keywords::CalendarAlgorithm;
42    /// use icu::locale::preferences::extensions::unicode::keywords::HourCycle;
43    /// use icu::locale::subtags::Language;
44    ///
45    /// let prefs1: DateTimeFormatterPreferences = Locale::try_from_str("fr-u-ca-buddhist-hc-h12").unwrap().into();
46    ///
47    /// let locale = Locale::try_from_str("fr").unwrap();
48    /// let mut prefs2 = DateTimeFormatterPreferences::default();
49    /// prefs2.locale_preferences = (&locale).into();
50    /// prefs2.hour_cycle = Some(HourCycle::H12);
51    /// prefs2.calendar_algorithm = Some(CalendarAlgorithm::Buddhist);
52    ///
53    /// assert_eq!(prefs1, prefs2);
54    /// ```
55    [Copy]
56    DateTimeFormatterPreferences,
57    {
58        /// The user's preferred numbering system.
59        ///
60        /// Corresponds to the `-u-nu` in Unicode Locale Identifier.
61        ///
62        /// To get the resolved numbering system, you can inspect the data provider.
63        /// See the [`icu_decimal::provider`] module for an example.
64        numbering_system: NumberingSystem,
65        /// The user's preferred hour cycle.
66        ///
67        /// Corresponds to the `-u-hc` in Unicode Locale Identifier.
68        ///
69        /// To get the resolved hour cycle, you can inspect the formatting pattern.
70        /// See [`DateTimePattern`](crate::pattern::DateTimePattern) for an example.
71        hour_cycle: HourCycle,
72        /// The user's preferred calendar system
73        ///
74        /// Corresponds to the `-u-ca` in Unicode Locale Identifier.
75        ///
76        /// To get the resolved calendar system, use [`DateTimeFormatter::calendar_kind()`].
77        calendar_algorithm: CalendarAlgorithm
78    }
79);
80
81#[test]
82fn prefs() {
83    use icu_locale_core::locale;
84    assert_eq!(
85        DateTimeFormatterPreferences::from_locale_strict(&locale!("en-US-u-hc-h23"))
86            .unwrap()
87            .hour_cycle,
88        Some(HourCycle::H23)
89    );
90    assert_eq!(
91        DateTimeFormatterPreferences::from_locale_strict(&locale!("en-US-u-hc-h24"))
92            .unwrap_err()
93            .hour_cycle,
94        None
95    );
96}
97
98prefs_convert!(DateTimeFormatterPreferences, DecimalFormatterPreferences, {
99    numbering_system
100});
101
102prefs_convert!(DateTimeFormatterPreferences, CalendarPreferences, {
103    calendar_algorithm
104});
105
106/// Helper macro for generating any/buffer constructors in this file.
107macro_rules! gen_buffer_constructors_with_external_loader {
108    (@compiletime_fset, $fset:ident, $compiled_fn:ident, $buffer_fn:ident, $internal_fn:ident) => {
109        #[doc = icu_provider::gen_buffer_unstable_docs!(BUFFER, Self::$compiled_fn)]
110        #[cfg(feature = "serde")]
111        pub fn $buffer_fn<P>(
112            provider: &P,
113            prefs: DateTimeFormatterPreferences,
114            field_set_with_options: $fset,
115        ) -> Result<Self, DateTimeFormatterLoadError>
116        where
117            P: BufferProvider + ?Sized,
118        {
119            use crate::provider::compat::CompatProvider;
120            let deser_provider = provider.as_deserializing();
121            let compat_provider = CompatProvider(&deser_provider, &provider);
122            Self::$internal_fn(
123                &compat_provider,
124                &ExternalLoaderBuffer(provider),
125                prefs,
126                field_set_with_options.get_field(),
127            )
128        }
129    };
130}
131
132size_test!(FixedCalendarDateTimeFormatter<icu_calendar::Gregorian, crate::fieldsets::YMD>, typed_neo_year_month_day_formatter_size, 328);
133
134/// [`FixedCalendarDateTimeFormatter`] is a formatter capable of formatting dates and/or times from
135/// a calendar selected at compile time.
136///
137/// For more details, please read the [crate root docs][crate].
138///
139/// # Examples
140///
141/// Basic usage:
142///
143/// ```
144/// use icu::calendar::cal::Japanese;
145/// use icu::datetime::FixedCalendarDateTimeFormatter;
146/// use icu::datetime::fieldsets::YMD;
147/// use icu::datetime::input::Date;
148/// use icu::locale::locale;
149/// use writeable::assert_writeable_eq;
150///
151/// // The Japanese generic is inferred by passing this a Japanese date later
152/// let formatter = FixedCalendarDateTimeFormatter::try_new(
153///     locale!("es-MX").into(),
154///     YMD::long(),
155/// )
156/// .unwrap();
157///
158/// assert_writeable_eq!(
159///     formatter.format(
160///         &Date::try_new_iso(2023, 12, 20)
161///             .unwrap()
162///             .to_calendar(Japanese::new())
163///     ),
164///     "20 de diciembre de 5 Reiwa"
165/// );
166/// ```
167///
168/// Mismatched calendars will not compile:
169///
170/// ```compile_fail,E0271
171/// use icu::calendar::cal::Buddhist;
172/// use icu::datetime::input::Date;
173/// use icu::datetime::FixedCalendarDateTimeFormatter;
174/// use icu::datetime::fieldsets::YMD;
175/// use icu::locale::locale;
176///
177/// let formatter =
178///     FixedCalendarDateTimeFormatter::<Buddhist, _>::try_new(
179///         locale!("es-MX").into(),
180///         YMD::long(),
181///     )
182///     .unwrap();
183///
184/// // type mismatch resolving `<Gregorian as AsCalendar>::Calendar == Buddhist`
185/// formatter.format(&Date::try_new_gregorian(2023, 12, 20).unwrap());
186/// ```
187///
188/// As with [`DateTimeFormatter`], a time cannot be passed into the formatter when a date is expected:
189///
190/// ```compile_fail,E0277
191/// use icu::datetime::input::Time;
192/// use icu::calendar::Gregorian;
193/// use icu::datetime::FixedCalendarDateTimeFormatter;
194/// use icu::datetime::fieldsets::YMD;
195/// use icu::locale::locale;
196///
197/// let formatter =
198///     FixedCalendarDateTimeFormatter::<Gregorian, _>::try_new(
199///         locale!("es-MX").into(),
200///         YMD::long(),
201///     )
202///     .unwrap();
203///
204/// // error[E0277]: the trait bound `Time: AllInputMarkers<fieldsets::YMD>` is not satisfied
205/// formatter.format(&Time::start_of_day());
206/// ```
207#[doc = typed_neo_year_month_day_formatter_size!()]
208#[derive(Debug, Clone)]
209pub struct FixedCalendarDateTimeFormatter<C: CldrCalendar, FSet: DateTimeNamesMarker> {
210    pub(crate) selection: DateTimeZonePatternSelectionData,
211    pub(crate) names: RawDateTimeNames<FSet>,
212    _calendar: PhantomData<C>,
213}
214
215impl<C: CldrCalendar, FSet: DateTimeMarkers> FixedCalendarDateTimeFormatter<C, FSet>
216where
217    FSet::D: TypedDateDataMarkers<C>,
218    FSet::T: TimeMarkers,
219    FSet::Z: ZoneMarkers,
220    FSet: GetField<CompositeFieldSet>,
221{
222    /// Creates a new [`FixedCalendarDateTimeFormatter`] from compiled data with
223    /// datetime components specified at build time.
224    ///
225    /// This ignores the `calendar_kind` preference and instead uses the static calendar type,
226    /// and supports calendars that are not expressible as preferences.
227    ///
228    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
229    ///
230    /// [📚 Help choosing a constructor](icu_provider::constructors)
231    #[cfg(feature = "compiled_data")]
232    pub fn try_new(
233        prefs: DateTimeFormatterPreferences,
234        field_set_with_options: FSet,
235    ) -> Result<Self, DateTimeFormatterLoadError>
236    where
237        crate::provider::Baked: AllFixedCalendarFormattingDataMarkers<C, FSet>,
238    {
239        Self::try_new_internal(
240            &crate::provider::Baked,
241            &ExternalLoaderCompiledData,
242            prefs,
243            field_set_with_options.get_field(),
244        )
245    }
246
247    gen_buffer_constructors_with_external_loader!(
248        @compiletime_fset,
249        FSet,
250        try_new,
251        try_new_with_buffer_provider,
252        try_new_internal
253    );
254
255    #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
256    pub fn try_new_unstable<P>(
257        provider: &P,
258        prefs: DateTimeFormatterPreferences,
259        field_set_with_options: FSet,
260    ) -> Result<Self, DateTimeFormatterLoadError>
261    where
262        P: ?Sized
263            + AllFixedCalendarFormattingDataMarkers<C, FSet>
264            + AllFixedCalendarExternalDataMarkers,
265    {
266        Self::try_new_internal(
267            provider,
268            &ExternalLoaderUnstable(provider),
269            prefs,
270            field_set_with_options.get_field(),
271        )
272    }
273}
274
275impl<C: CldrCalendar, FSet: DateTimeMarkers> FixedCalendarDateTimeFormatter<C, FSet>
276where
277    FSet::D: TypedDateDataMarkers<C>,
278    FSet::T: TimeMarkers,
279    FSet::Z: ZoneMarkers,
280{
281    pub(crate) fn try_new_internal<P, L>(
282        provider: &P,
283        loader: &L,
284        prefs: DateTimeFormatterPreferences,
285        field_set_with_options: CompositeFieldSet,
286    ) -> Result<Self, DateTimeFormatterLoadError>
287    where
288        P: ?Sized + AllFixedCalendarFormattingDataMarkers<C, FSet>,
289        L: DecimalFormatterLoader,
290    {
291        let names = RawDateTimeNames::new_without_number_formatting();
292        Self::try_new_internal_with_names(
293            provider,
294            provider,
295            loader,
296            prefs,
297            field_set_with_options,
298            names,
299            DateTimeNamesMetadata::new_empty(), // OK: this is a constructor
300        )
301        .map_err(|e| e.0)
302    }
303
304    #[expect(clippy::result_large_err)] // returning ownership of an argument to the caller
305    pub(crate) fn try_new_internal_with_names<P0, P1, L>(
306        provider_p: &P0,
307        provider: &P1,
308        loader: &L,
309        prefs: DateTimeFormatterPreferences,
310        field_set_with_options: CompositeFieldSet,
311        mut names: RawDateTimeNames<FSet>,
312        mut names_metadata: DateTimeNamesMetadata,
313    ) -> Result<
314        Self,
315        (
316            DateTimeFormatterLoadError,
317            (RawDateTimeNames<FSet>, DateTimeNamesMetadata),
318        ),
319    >
320    where
321        P0: ?Sized + AllFixedCalendarPatternDataMarkers<C, FSet>,
322        P1: ?Sized + AllFixedCalendarFormattingDataMarkers<C, FSet>,
323        L: DecimalFormatterLoader,
324    {
325        let selection = DateTimeZonePatternSelectionData::try_new_with_skeleton(
326            &<FSet::D as TypedDateDataMarkers<C>>::DateSkeletonPatternsV1::bind(provider_p),
327            &<FSet::T as TimeMarkers>::TimeSkeletonPatternsV1::bind(provider_p),
328            &FSet::GluePatternV1::bind(provider_p),
329            prefs,
330            field_set_with_options,
331        );
332        let selection = match selection {
333            Ok(selection) => selection,
334            Err(e) => return Err((DateTimeFormatterLoadError::Data(e), (names, names_metadata))),
335        };
336        let result = names.load_for_pattern(
337            &<FSet::D as TypedDateDataMarkers<C>>::YearNamesV1::bind(provider),
338            &<FSet::D as TypedDateDataMarkers<C>>::MonthNamesV1::bind(provider),
339            &<FSet::D as TypedDateDataMarkers<C>>::WeekdayNamesV1::bind(provider),
340            &<FSet::T as TimeMarkers>::DayPeriodNamesV1::bind(provider),
341            &<FSet::Z as ZoneMarkers>::EssentialsV1::bind(provider),
342            &<FSet::Z as ZoneMarkers>::LocationsV1::bind(provider),
343            &<FSet::Z as ZoneMarkers>::LocationsRootV1::bind(provider),
344            &<FSet::Z as ZoneMarkers>::ExemplarCitiesV1::bind(provider),
345            &<FSet::Z as ZoneMarkers>::ExemplarCitiesRootV1::bind(provider),
346            &<FSet::Z as ZoneMarkers>::GenericLongV1::bind(provider),
347            &<FSet::Z as ZoneMarkers>::GenericShortV1::bind(provider),
348            &<FSet::Z as ZoneMarkers>::StandardLongV1::bind(provider),
349            &<FSet::Z as ZoneMarkers>::SpecificLongV1::bind(provider),
350            &<FSet::Z as ZoneMarkers>::SpecificShortV1::bind(provider),
351            &<FSet::Z as ZoneMarkers>::MetazonePeriodV1::bind(provider),
352            loader, // fixed decimal formatter
353            prefs,
354            selection.pattern_items_for_data_loading(),
355            &mut names_metadata,
356        );
357        match result {
358            Ok(()) => (),
359            Err(e) => {
360                return Err((
361                    DateTimeFormatterLoadError::Names(e),
362                    (names, names_metadata),
363                ));
364            }
365        };
366        Ok(Self {
367            selection,
368            names,
369            _calendar: PhantomData,
370        })
371    }
372}
373
374impl<C: CldrCalendar, FSet: DateTimeMarkers> FixedCalendarDateTimeFormatter<C, FSet>
375where
376    FSet::D: DateInputMarkers,
377    FSet::T: TimeMarkers,
378    FSet::Z: ZoneMarkers,
379{
380    /// Formats a datetime. Calendars and fields must match at compile time.
381    pub fn format<I>(&self, input: &I) -> FormattedDateTime<'_>
382    where
383        I: ?Sized + InFixedCalendar<C> + AllInputMarkers<FSet>,
384    {
385        let input =
386            DateTimeInputUnchecked::extract_from_neo_input::<FSet::D, FSet::T, FSet::Z, I>(input);
387        FormattedDateTime {
388            pattern: self.selection.select(&input),
389            input,
390            names: self.names.as_borrowed(),
391        }
392    }
393}
394
395size_test!(
396    DateTimeFormatter<crate::fieldsets::YMD>,
397    neo_year_month_day_formatter_size,
398    336
399);
400
401/// [`DateTimeFormatter`] is a formatter capable of formatting dates and/or times from
402/// a calendar selected at runtime.
403///
404/// For more details, please read the [crate root docs][crate].
405///
406/// # Examples
407///
408/// Basic usage:
409///
410/// ```
411/// use icu::datetime::DateTimeFormatter;
412/// use icu::datetime::fieldsets::YMD;
413/// use icu::datetime::input::Date;
414/// use icu::locale::locale;
415/// use writeable::assert_writeable_eq;
416///
417/// let formatter = DateTimeFormatter::try_new(
418///     locale!("en-u-ca-hebrew").into(),
419///     YMD::medium(),
420/// )
421/// .unwrap();
422///
423/// let date = Date::try_new_iso(2024, 5, 8).unwrap();
424///
425/// assert_writeable_eq!(formatter.format(&date), "30 Nisan 5784");
426/// ```
427#[doc = neo_year_month_day_formatter_size!()]
428#[derive(Debug, Clone)]
429pub struct DateTimeFormatter<FSet: DateTimeNamesMarker> {
430    pub(crate) selection: DateTimeZonePatternSelectionData,
431    pub(crate) names: RawDateTimeNames<FSet>,
432    pub(crate) calendar: FormattableAnyCalendar,
433}
434
435impl<FSet: DateTimeMarkers> DateTimeFormatter<FSet>
436where
437    FSet::D: DateDataMarkers,
438    FSet::T: TimeMarkers,
439    FSet::Z: ZoneMarkers,
440    FSet: GetField<CompositeFieldSet>,
441{
442    /// Creates a new [`DateTimeFormatter`] from compiled data with
443    /// datetime components specified at build time.
444    ///
445    /// This method will use the calendar specified in the `calendar_algorithm` preference, or fall back to the default
446    /// calendar for the preferences if unspecified or unsupported. See [`IntoFormattableAnyCalendar`] for a list of supported calendars.
447    ///
448    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
449    ///
450    /// [📚 Help choosing a constructor](icu_provider::constructors)
451    #[inline(never)]
452    #[cfg(feature = "compiled_data")]
453    pub fn try_new(
454        prefs: DateTimeFormatterPreferences,
455        field_set_with_options: FSet,
456    ) -> Result<Self, DateTimeFormatterLoadError>
457    where
458        crate::provider::Baked: AllAnyCalendarFormattingDataMarkers<FSet>,
459    {
460        Self::try_new_internal(
461            &crate::provider::Baked,
462            &ExternalLoaderCompiledData,
463            prefs,
464            field_set_with_options.get_field(),
465        )
466    }
467
468    gen_buffer_constructors_with_external_loader!(
469        @compiletime_fset,
470        FSet,
471        try_new,
472        try_new_with_buffer_provider,
473        try_new_internal
474    );
475
476    #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
477    pub fn try_new_unstable<P>(
478        provider: &P,
479        prefs: DateTimeFormatterPreferences,
480        field_set_with_options: FSet,
481    ) -> Result<Self, DateTimeFormatterLoadError>
482    where
483        P: ?Sized + AllAnyCalendarFormattingDataMarkers<FSet> + AllAnyCalendarExternalDataMarkers,
484    {
485        Self::try_new_internal(
486            provider,
487            &ExternalLoaderUnstable(provider),
488            prefs,
489            field_set_with_options.get_field(),
490        )
491    }
492}
493
494impl<FSet: DateTimeMarkers> DateTimeFormatter<FSet>
495where
496    FSet::D: DateDataMarkers,
497    FSet::T: TimeMarkers,
498    FSet::Z: ZoneMarkers,
499{
500    pub(crate) fn try_new_internal<P, L>(
501        provider: &P,
502        loader: &L,
503        prefs: DateTimeFormatterPreferences,
504        field_set_with_options: CompositeFieldSet,
505    ) -> Result<Self, DateTimeFormatterLoadError>
506    where
507        P: ?Sized + AllAnyCalendarFormattingDataMarkers<FSet>,
508        L: DecimalFormatterLoader + FormattableAnyCalendarLoader,
509    {
510        let calendar = FormattableAnyCalendarLoader::load(loader, (&prefs).into())?;
511        let names = RawDateTimeNames::new_without_number_formatting();
512        Self::try_new_internal_with_calendar_and_names(
513            provider,
514            provider,
515            loader,
516            prefs,
517            field_set_with_options,
518            calendar,
519            names,
520            DateTimeNamesMetadata::new_empty(), // OK: this is a constructor
521        )
522        .map_err(|e| e.0)
523    }
524
525    #[expect(clippy::result_large_err)] // returning ownership of an argument to the caller
526    #[expect(clippy::too_many_arguments)] // internal function with lots of generics
527    #[expect(clippy::type_complexity)] // return type has all the parts inside
528    pub(crate) fn try_new_internal_with_calendar_and_names<P0, P1, L>(
529        provider_p: &P0,
530        provider: &P1,
531        loader: &L,
532        prefs: DateTimeFormatterPreferences,
533        field_set_with_options: CompositeFieldSet,
534        calendar: FormattableAnyCalendar,
535        mut names: RawDateTimeNames<FSet>,
536        mut names_metadata: DateTimeNamesMetadata,
537    ) -> Result<
538        Self,
539        (
540            DateTimeFormatterLoadError,
541            (
542                FormattableAnyCalendar,
543                RawDateTimeNames<FSet>,
544                DateTimeNamesMetadata,
545            ),
546        ),
547    >
548    where
549        P0: ?Sized + AllAnyCalendarPatternDataMarkers<FSet>,
550        P1: ?Sized + AllAnyCalendarFormattingDataMarkers<FSet>,
551        L: DecimalFormatterLoader,
552    {
553        let selection = DateTimeZonePatternSelectionData::try_new_with_skeleton(
554            &FormattableAnyCalendarNamesLoader::<<FSet::D as DateDataMarkers>::Skel, _>::new(
555                provider_p, &calendar,
556            ),
557            &<FSet::T as TimeMarkers>::TimeSkeletonPatternsV1::bind(provider_p),
558            &FSet::GluePatternV1::bind(provider_p),
559            prefs,
560            field_set_with_options,
561        );
562        let selection = match selection {
563            Ok(selection) => selection,
564            Err(e) => {
565                return Err((
566                    DateTimeFormatterLoadError::Data(e),
567                    (calendar, names, names_metadata),
568                ));
569            }
570        };
571        let result = names.load_for_pattern(
572            &FormattableAnyCalendarNamesLoader::<<FSet::D as DateDataMarkers>::Year, _>::new(
573                provider, &calendar,
574            ),
575            &FormattableAnyCalendarNamesLoader::<<FSet::D as DateDataMarkers>::Month, _>::new(
576                provider, &calendar,
577            ),
578            &<FSet::D as DateDataMarkers>::WeekdayNamesV1::bind(provider),
579            &<FSet::T as TimeMarkers>::DayPeriodNamesV1::bind(provider),
580            &<FSet::Z as ZoneMarkers>::EssentialsV1::bind(provider),
581            &<FSet::Z as ZoneMarkers>::LocationsV1::bind(provider),
582            &<FSet::Z as ZoneMarkers>::LocationsRootV1::bind(provider),
583            &<FSet::Z as ZoneMarkers>::ExemplarCitiesRootV1::bind(provider),
584            &<FSet::Z as ZoneMarkers>::ExemplarCitiesV1::bind(provider),
585            &<FSet::Z as ZoneMarkers>::GenericLongV1::bind(provider),
586            &<FSet::Z as ZoneMarkers>::GenericShortV1::bind(provider),
587            &<FSet::Z as ZoneMarkers>::StandardLongV1::bind(provider),
588            &<FSet::Z as ZoneMarkers>::SpecificLongV1::bind(provider),
589            &<FSet::Z as ZoneMarkers>::SpecificShortV1::bind(provider),
590            &<FSet::Z as ZoneMarkers>::MetazonePeriodV1::bind(provider),
591            loader, // fixed decimal formatter
592            prefs,
593            selection.pattern_items_for_data_loading(),
594            &mut names_metadata,
595        );
596        match result {
597            Ok(()) => (),
598            Err(e) => {
599                return Err((
600                    DateTimeFormatterLoadError::Names(e),
601                    (calendar, names, names_metadata),
602                ));
603            }
604        };
605        Ok(Self {
606            selection,
607            names,
608            calendar,
609        })
610    }
611}
612
613impl<FSet: DateTimeMarkers> DateTimeFormatter<FSet>
614where
615    FSet::D: DateInputMarkers,
616    FSet::T: TimeMarkers,
617    FSet::Z: ZoneMarkers,
618{
619    /// Formats a datetime, checking that the calendar system is correct.
620    ///
621    /// If the datetime is not in the same calendar system as the formatter,
622    /// an error is returned.
623    ///
624    /// # Examples
625    ///
626    /// Mismatched calendars will return an error:
627    ///
628    /// ```
629    /// use icu::datetime::DateTimeFormatter;
630    /// use icu::datetime::MismatchedCalendarError;
631    /// use icu::datetime::fieldsets::YMD;
632    /// use icu::datetime::input::Date;
633    /// use icu::locale::locale;
634    ///
635    /// let formatter = DateTimeFormatter::try_new(
636    ///     locale!("en-u-ca-hebrew").into(),
637    ///     YMD::long(),
638    /// )
639    /// .unwrap();
640    ///
641    /// let date = Date::try_new_gregorian(2023, 12, 20).unwrap();
642    ///
643    /// assert!(matches!(
644    ///     formatter.format_same_calendar(&date),
645    ///     Err(MismatchedCalendarError { .. })
646    /// ));
647    /// ```
648    ///
649    /// A time cannot be passed into the formatter when a date is expected:
650    ///
651    /// ```compile_fail,E0277
652    /// use icu::datetime::input::Time;
653    /// use icu::datetime::DateTimeFormatter;
654    /// use icu::datetime::fieldsets::YMD;
655    /// use icu::locale::locale;
656    ///
657    /// let formatter = DateTimeFormatter::try_new(
658    ///     locale!("es-MX").into(),
659    ///     YMD::long(),
660    /// )
661    /// .unwrap();
662    ///
663    /// // error[E0277]: the trait bound `Time: AllInputMarkers<fieldsets::YMD>` is not satisfied
664    /// formatter.format_same_calendar(&Time::start_of_day());
665    /// ```
666    pub fn format_same_calendar<I>(
667        &self,
668        datetime: &I,
669    ) -> Result<FormattedDateTime<'_>, MismatchedCalendarError>
670    where
671        I: ?Sized + InSameCalendar + AllInputMarkers<FSet>,
672    {
673        datetime.check_any_calendar_kind(self.calendar.any_calendar().kind())?;
674        let datetime = DateTimeInputUnchecked::extract_from_neo_input::<FSet::D, FSet::T, FSet::Z, I>(
675            datetime,
676        );
677        Ok(FormattedDateTime {
678            pattern: self.selection.select(&datetime),
679            input: datetime,
680            names: self.names.as_borrowed(),
681        })
682    }
683
684    /// Formats a datetime after first converting it
685    /// to the formatter's calendar.
686    ///
687    /// # Examples
688    ///
689    /// Mismatched calendars convert and format automatically:
690    ///
691    /// ```
692    /// use icu::datetime::DateTimeFormatter;
693    /// use icu::datetime::MismatchedCalendarError;
694    /// use icu::datetime::fieldsets::YMD;
695    /// use icu::datetime::input::Date;
696    /// use icu::locale::locale;
697    /// use writeable::assert_writeable_eq;
698    ///
699    /// let formatter = DateTimeFormatter::try_new(
700    ///     locale!("en-u-ca-hebrew").into(),
701    ///     YMD::long(),
702    /// )
703    /// .unwrap();
704    ///
705    /// let date = Date::try_new_roc(113, 5, 8).unwrap();
706    ///
707    /// assert_writeable_eq!(formatter.format(&date), "30 Nisan 5784");
708    /// ```
709    ///
710    /// A time cannot be passed into the formatter when a date is expected:
711    ///
712    /// ```compile_fail,E0277
713    /// use icu::datetime::input::Time;
714    /// use icu::datetime::DateTimeFormatter;
715    /// use icu::datetime::fieldsets::YMD;
716    /// use icu::locale::locale;
717    ///
718    /// let formatter = DateTimeFormatter::try_new(
719    ///     locale!("es-MX").into(),
720    ///     YMD::long(),
721    /// )
722    /// .unwrap();
723    ///
724    /// // error[E0277]: the trait bound `Time: AllInputMarkers<fieldsets::YMD>` is not satisfied
725    /// formatter.format(&Time::start_of_day());
726    /// ```
727    pub fn format<'a, I>(&'a self, datetime: &I) -> FormattedDateTime<'a>
728    where
729        I: ?Sized + ConvertCalendar,
730        I::Converted<'a>: Sized + AllInputMarkers<FSet>,
731    {
732        let datetime = datetime.to_calendar(self.calendar.any_calendar());
733        let datetime = DateTimeInputUnchecked::extract_from_neo_input::<
734            FSet::D,
735            FSet::T,
736            FSet::Z,
737            I::Converted<'a>,
738        >(&datetime);
739        FormattedDateTime {
740            pattern: self.selection.select(&datetime),
741            input: datetime,
742            names: self.names.as_borrowed(),
743        }
744    }
745}
746
747impl<C: CldrCalendar, FSet: DateTimeMarkers> FixedCalendarDateTimeFormatter<C, FSet> {
748    /// Make this [`FixedCalendarDateTimeFormatter`] adopt a calendar so it can format any date.
749    ///
750    /// This is useful if you need a [`DateTimeFormatter`] but know the calendar system ahead of time,
751    /// so that you do not need to link extra data you aren't using.
752    ///
753    /// [`DateTimeFormatter`] does not necesarily support all calendars that are supported by
754    /// [`FixedCalendarDateTimeFormatter`], which is why this function can fail.
755    ///
756    /// # Examples
757    ///
758    /// ```
759    /// use icu::calendar::cal::Hebrew;
760    /// use icu::datetime::FixedCalendarDateTimeFormatter;
761    /// use icu::datetime::fieldsets::YMD;
762    /// use icu::datetime::input::Date;
763    /// use icu::locale::locale;
764    /// use writeable::assert_writeable_eq;
765    ///
766    /// let formatter = FixedCalendarDateTimeFormatter::try_new(
767    ///     locale!("en").into(),
768    ///     YMD::long(),
769    /// )
770    /// .unwrap()
771    /// .into_formatter(Hebrew::new());
772    ///
773    /// let date = Date::try_new_iso(2024, 10, 14).unwrap();
774    ///
775    /// assert_writeable_eq!(formatter.format(&date), "12 Tishri 5785");
776    /// ```
777    pub fn into_formatter(self, calendar: C) -> DateTimeFormatter<FSet>
778    where
779        C: IntoFormattableAnyCalendar,
780    {
781        DateTimeFormatter {
782            selection: self.selection,
783            names: self.names,
784            calendar: FormattableAnyCalendar::from_calendar(calendar),
785        }
786    }
787
788    /// Maps a [`FixedCalendarDateTimeFormatter`] of a specific `FSet` to a more general `FSet`.
789    ///
790    /// For example, this can transform a formatter for [`YMD`] to one for [`DateFieldSet`].
791    ///
792    /// To learn why this function is useful, see [`DateTimeFormatter::cast_into_fset`].
793    ///
794    /// # Examples
795    ///
796    /// ```
797    /// use icu::calendar::Gregorian;
798    /// use icu::datetime::FixedCalendarDateTimeFormatter;
799    /// use icu::datetime::fieldsets::{YMD, enums::DateFieldSet};
800    /// use icu::datetime::input::Date;
801    /// use icu::locale::locale;
802    /// use writeable::assert_writeable_eq;
803    ///
804    /// let specific_formatter = FixedCalendarDateTimeFormatter::try_new(
805    ///     locale!("fr").into(),
806    ///     YMD::medium(),
807    /// )
808    /// .unwrap();
809    ///
810    /// // Test that the specific formatter works:
811    /// let date = Date::try_new_gregorian(2024, 12, 20).unwrap();
812    /// assert_writeable_eq!(specific_formatter.format(&date), "20 déc. 2024");
813    ///
814    /// // Make a more general formatter:
815    /// let general_formatter = specific_formatter.cast_into_fset::<DateFieldSet>();
816    ///
817    /// // Test that it still works:
818    /// assert_writeable_eq!(general_formatter.format(&date), "20 déc. 2024");
819    /// ```
820    ///
821    /// [`MD`]: crate::fieldsets::MD
822    /// [`YMD`]: crate::fieldsets::YMD
823    /// [`DateFieldSet`]: crate::fieldsets::enums::DateFieldSet
824    pub fn cast_into_fset<FSet2: DateTimeNamesFrom<FSet>>(
825        self,
826    ) -> FixedCalendarDateTimeFormatter<C, FSet2> {
827        FixedCalendarDateTimeFormatter {
828            selection: self.selection,
829            names: self.names.cast_into_fset(),
830            _calendar: PhantomData,
831        }
832    }
833
834    /// Gets a [`FieldSetBuilder`] corresponding to the fields and options configured in this
835    /// formatter. The builder can be used to recreate the formatter.
836    ///
837    /// # Examples
838    ///
839    /// ```
840    /// use icu::datetime::FixedCalendarDateTimeFormatter;
841    /// use icu::datetime::fieldsets::YMD;
842    /// use icu::datetime::fieldsets::builder::*;
843    /// use icu::datetime::input::*;
844    /// use icu::datetime::options::*;
845    /// use icu::locale::locale;
846    /// use writeable::assert_writeable_eq;
847    ///
848    /// // Create a simple YMDT formatter:
849    /// let formatter = FixedCalendarDateTimeFormatter::try_new(
850    ///     locale!("und").into(),
851    ///     YMD::long().with_time_hm().with_alignment(Alignment::Column),
852    /// )
853    /// .unwrap();
854    ///
855    /// // Get the builder corresponding to it:
856    /// let builder = formatter.to_field_set_builder();
857    ///
858    /// // Check that the builder is what we expect:
859    /// let mut equivalent_builder = FieldSetBuilder::default();
860    /// equivalent_builder.length = Some(Length::Long);
861    /// equivalent_builder.date_fields = Some(DateFields::YMD);
862    /// equivalent_builder.time_precision = Some(TimePrecision::Minute);
863    /// equivalent_builder.alignment = Some(Alignment::Column);
864    /// equivalent_builder.year_style = None;
865    /// assert_eq!(builder, equivalent_builder,);
866    ///
867    /// // Check that it creates a formatter with equivalent behavior:
868    /// let built_formatter = FixedCalendarDateTimeFormatter::try_new(
869    ///     locale!("und").into(),
870    ///     builder.build_composite_datetime().unwrap(),
871    /// )
872    /// .unwrap();
873    /// let datetime = DateTime {
874    ///     date: Date::try_new_gregorian(2025, 3, 6).unwrap(),
875    ///     time: Time::try_new(16, 41, 0, 0).unwrap(),
876    /// };
877    /// assert_eq!(
878    ///     formatter.format(&datetime).to_string(),
879    ///     built_formatter.format(&datetime).to_string(),
880    /// );
881    /// ```
882    pub fn to_field_set_builder(&self) -> FieldSetBuilder {
883        self.selection.to_builder()
884    }
885}
886
887impl<FSet: DateTimeMarkers> DateTimeFormatter<FSet> {
888    /// Attempt to convert this [`DateTimeFormatter`] into one with a specific calendar.
889    ///
890    /// Returns an error if the type parameter does not match the inner calendar.
891    ///
892    /// # Examples
893    ///
894    /// ```
895    /// use icu::calendar::cal::Persian;
896    /// use icu::datetime::DateTimeFormatter;
897    /// use icu::datetime::fieldsets::YMD;
898    /// use icu::datetime::input::Date;
899    /// use icu::locale::locale;
900    /// use writeable::assert_writeable_eq;
901    ///
902    /// let formatter = DateTimeFormatter::try_new(
903    ///     locale!("en-u-ca-persian").into(),
904    ///     YMD::long(),
905    /// )
906    /// .unwrap()
907    /// .try_into_typed_formatter::<Persian>()
908    /// .unwrap();
909    ///
910    /// let date = Date::try_new_persian(1584, 1, 12).unwrap();
911    ///
912    /// assert_writeable_eq!(formatter.format(&date), "Farvardin 12, 1584 AP");
913    /// ```
914    ///
915    /// An error occurs if the calendars don't match:
916    ///
917    /// ```
918    /// use icu::calendar::cal::Persian;
919    /// use icu::datetime::DateTimeFormatter;
920    /// use icu::datetime::MismatchedCalendarError;
921    /// use icu::datetime::fieldsets::YMD;
922    /// use icu::datetime::input::Date;
923    /// use icu::locale::locale;
924    ///
925    /// let result = DateTimeFormatter::try_new(
926    ///     locale!("en-u-ca-buddhist").into(),
927    ///     YMD::long(),
928    /// )
929    /// .unwrap()
930    /// .try_into_typed_formatter::<Persian>();
931    ///
932    /// assert!(matches!(result, Err(MismatchedCalendarError { .. })));
933    /// ```
934    pub fn try_into_typed_formatter<C>(
935        self,
936    ) -> Result<FixedCalendarDateTimeFormatter<C, FSet>, MismatchedCalendarError>
937    where
938        C: CldrCalendar + IntoAnyCalendar,
939    {
940        if let Err(cal) = C::from_any(self.calendar.take_any_calendar()) {
941            return Err(MismatchedCalendarError {
942                this_kind: cal.kind(),
943                date_kind: None,
944            });
945        }
946        Ok(FixedCalendarDateTimeFormatter {
947            selection: self.selection,
948            names: self.names,
949            _calendar: PhantomData,
950        })
951    }
952
953    /// Maps a [`DateTimeFormatter`] of a specific `FSet` to a more general `FSet`.
954    ///
955    /// For example, this can transform a formatter for [`YMD`] to one for [`DateFieldSet`].
956    ///
957    /// # Why do you need this function?
958    ///
959    /// The constructor is optimized to link only the data required for the chosen field set.
960    /// This function is useful if you want to work with multiple field sets, but not all of
961    /// them.
962    ///
963    /// For example, to support date formatting with variable fields but not weekdays,
964    /// you can use field-set-specific constructors for [`MD`] and [`YMD`] and then use this
965    /// function to convert the formatter to [`DateFields`].
966    ///
967    /// # Examples
968    ///
969    /// ```
970    /// use icu::calendar::Gregorian;
971    /// use icu::datetime::DateTimeFormatter;
972    /// use icu::datetime::fieldsets::{YMD, enums::DateFieldSet};
973    /// use icu::datetime::input::Date;
974    /// use icu::locale::locale;
975    /// use writeable::assert_writeable_eq;
976    ///
977    /// let specific_formatter =
978    ///     DateTimeFormatter::try_new(locale!("fr").into(), YMD::medium())
979    ///         .unwrap();
980    ///
981    /// // Test that the specific formatter works:
982    /// let date = Date::try_new_gregorian(2024, 12, 20).unwrap();
983    /// assert_writeable_eq!(specific_formatter.format(&date), "20 déc. 2024");
984    ///
985    /// // Make a more general formatter:
986    /// let general_formatter = specific_formatter.cast_into_fset::<DateFieldSet>();
987    ///
988    /// // Test that it still works:
989    /// assert_writeable_eq!(general_formatter.format(&date), "20 déc. 2024");
990    /// ```
991    ///
992    /// [`MD`]: crate::fieldsets::MD
993    /// [`YMD`]: crate::fieldsets::YMD
994    /// [`DateFieldSet`]: crate::fieldsets::enums::DateFieldSet
995    /// [`DateFields`]: crate::fieldsets::builder::DateFields
996    pub fn cast_into_fset<FSet2: DateTimeNamesFrom<FSet>>(self) -> DateTimeFormatter<FSet2> {
997        DateTimeFormatter {
998            selection: self.selection,
999            names: self.names.cast_into_fset(),
1000            calendar: self.calendar,
1001        }
1002    }
1003
1004    /// Returns the calendar used in this formatter.
1005    ///
1006    /// # Examples
1007    ///
1008    /// ```
1009    /// use icu::calendar::AnyCalendarKind;
1010    /// use icu::datetime::DateTimeFormatter;
1011    /// use icu::datetime::fieldsets::YMD;
1012    /// use icu::datetime::input::Date;
1013    /// use icu::locale::locale;
1014    /// use writeable::assert_writeable_eq;
1015    ///
1016    /// let formatter =
1017    ///     DateTimeFormatter::try_new(locale!("th-TH").into(), YMD::long())
1018    ///         .unwrap();
1019    ///
1020    /// assert_writeable_eq!(
1021    ///     formatter.format(&Date::try_new_iso(2024, 12, 16).unwrap()),
1022    ///     "16 ธันวาคม 2567"
1023    /// );
1024    ///
1025    /// assert_eq!(formatter.calendar().kind(), AnyCalendarKind::Buddhist);
1026    /// ```
1027    pub fn calendar(&self) -> icu_calendar::Ref<'_, AnyCalendar> {
1028        icu_calendar::Ref(self.calendar.any_calendar())
1029    }
1030
1031    /// Gets a [`FieldSetBuilder`] corresponding to the fields and options configured in this
1032    /// formatter. The builder can be used to recreate the formatter.
1033    ///
1034    /// # Examples
1035    ///
1036    /// ```
1037    /// use icu::datetime::fieldsets::builder::*;
1038    /// use icu::datetime::fieldsets::YMDT;
1039    /// use icu::datetime::input::*;
1040    /// use icu::datetime::options::*;
1041    /// use icu::datetime::DateTimeFormatter;
1042    /// use icu::locale::locale;
1043    /// use writeable::assert_writeable_eq;
1044    ///
1045    /// // Create a simple YMDT formatter:
1046    /// let formatter = DateTimeFormatter::try_new(
1047    ///     locale!("und").into(),
1048    ///     YMDT::long().with_alignment(Alignment::Column)
1049    /// )
1050    /// .unwrap();
1051    ///
1052    /// // Get the builder corresponding to it:
1053    /// let builder = formatter.to_field_set_builder();
1054    ///
1055    /// // Check that the builder is what we expect:
1056    /// let mut equivalent_builder = FieldSetBuilder::default();
1057    /// equivalent_builder.length = Some(Length::Long);
1058    /// equivalent_builder.date_fields = Some(DateFields::YMD);
1059    /// equivalent_builder.time_precision = Some(TimePrecision::Second); // set automatically
1060    /// equivalent_builder.alignment = Some(Alignment::Column);
1061    /// equivalent_builder.year_style = None;
1062    /// assert_eq!(
1063    ///     builder,
1064    ///     equivalent_builder,
1065    /// );
1066    ///
1067    /// // Check that it creates a formatter with equivalent behavior:
1068    /// let built_formatter = DateTimeFormatter::try_new(
1069    ///     locale!("und").into(),
1070    ///     builder.build_composite_datetime().unwrap(),
1071    /// )
1072    /// .unwrap();
1073    /// let datetime = DateTime {
1074    ///     date: Date::try_new_iso(2025, 3, 6).unwrap(),
1075    ///     time: Time::try_new(16, 41, 0, 0).unwrap(),
1076    /// };
1077    /// assert_eq!(
1078    ///     formatter.format(&datetime).to_string(),
1079    ///     built_formatter.format(&datetime).to_string(),
1080    /// );
1081    /// ```
1082    pub fn to_field_set_builder(&self) -> FieldSetBuilder {
1083        self.selection.to_builder()
1084    }
1085}
1086
1087/// A formatter optimized for time and time zone formatting, when a calendar is not needed.
1088///
1089/// # Examples
1090///
1091/// A [`NoCalendarFormatter`] can be used to format a time:
1092///
1093/// ```
1094/// use icu::datetime::NoCalendarFormatter;
1095/// use icu::datetime::fieldsets::T;
1096/// use icu::datetime::input::Time;
1097/// use icu::locale::locale;
1098///
1099/// let formatter =
1100///     NoCalendarFormatter::try_new(locale!("bn").into(), T::long()).unwrap();
1101/// assert_eq!(
1102///     formatter.format(&Time::start_of_day()).to_string(),
1103///     "১২:০০:০০ AM"
1104/// );
1105/// ```
1106///
1107/// A [`NoCalendarFormatter`] cannot be constructed with a fieldset that involves dates:
1108///
1109/// ```
1110/// use icu::datetime::NoCalendarFormatter;
1111/// use icu::datetime::fieldsets::Y;
1112/// use icu::locale::locale;
1113///
1114/// assert!(
1115///     NoCalendarFormatter::try_new(locale!("und").into(), Y::medium())
1116///         .is_err()
1117/// );
1118/// ```
1119///
1120/// Furthermore, it is a compile error in the format function:
1121///
1122/// ```compile_fail,E0271
1123/// use icu::datetime::NoCalendarFormatter;
1124/// use icu::datetime::fieldsets::Y;
1125/// use icu::locale::locale;
1126///
1127/// let date: icu::calendar::Date<icu::calendar::Gregorian> = unimplemented!();
1128/// let formatter = NoCalendarFormatter::try_new(locale!("und").into(), Y::medium()).unwrap();
1129///
1130/// // error[E0271]: type mismatch resolving `<Gregorian as AsCalendar>::Calendar == ()`
1131/// formatter.format(&date);
1132/// ```
1133pub type NoCalendarFormatter<FSet> = FixedCalendarDateTimeFormatter<(), FSet>;
1134
1135/// An intermediate type during a datetime formatting operation.
1136///
1137/// Not intended to be stored: convert to a string first.
1138#[derive(Debug)]
1139pub struct FormattedDateTime<'a> {
1140    pub(crate) pattern: DateTimeZonePatternDataBorrowed<'a>,
1141    pub(crate) input: DateTimeInputUnchecked,
1142    pub(crate) names: RawDateTimeNamesBorrowed<'a>,
1143}
1144
1145impl Writeable for FormattedDateTime<'_> {
1146    fn write_to_parts<S: writeable::PartsWrite + ?Sized>(
1147        &self,
1148        sink: &mut S,
1149    ) -> Result<(), fmt::Error> {
1150        let result = try_write_pattern_items(
1151            self.pattern.metadata(),
1152            self.pattern.iter_items(),
1153            &self.input,
1154            &self.names,
1155            self.names.decimal_formatter,
1156            sink,
1157        );
1158        // A DateTimeWriteError should not occur in normal usage because DateTimeFormatter
1159        // guarantees that all names for the pattern have been loaded and that the input type
1160        // is compatible with the pattern. However, this code path might be reachable with
1161        // invalid data. In that case, debug-panic and return the fallback string.
1162        match result {
1163            Ok(Ok(())) => Ok(()),
1164            Err(fmt::Error) => Err(fmt::Error),
1165            Ok(Err(e)) => {
1166                debug_assert!(false, "unexpected error in FormattedDateTime: {e:?}");
1167                Ok(())
1168            }
1169        }
1170    }
1171
1172    // TODO(#489): Implement writeable_length_hint
1173}
1174
1175impl_display_with_writeable!(FormattedDateTime<'_>);
1176
1177impl FormattedDateTime<'_> {
1178    /// Gets the pattern used in this formatted value.
1179    ///
1180    /// From the pattern, one can check the properties of the included components, such as
1181    /// the hour cycle being used for formatting. See [`DateTimePattern`].
1182    pub fn pattern(&self) -> DateTimePattern {
1183        self.pattern.to_pattern()
1184    }
1185}