1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use icu_calendar::provider::WeekDataV1Marker;
use icu_decimal::{
    options::{FixedDecimalFormatterOptions, GroupingStrategy},
    provider::DecimalSymbolsV1Marker,
    FixedDecimalFormatter,
};
use icu_plurals::{provider::OrdinalV1Marker, PluralRules};
use icu_provider::prelude::*;

use crate::{
    format::{datetime, zoned_datetime::FormattedZonedDateTime},
    input::{DateTimeInput, ExtractedTimeZoneInput, TimeZoneInput},
    pattern::runtime::PatternPlurals,
    provider::{
        self,
        calendar::{
            patterns::PatternPluralsFromPatternsV1Marker, ErasedDateSymbolsV1Marker,
            TimeLengthsV1Marker, TimeSymbolsV1Marker,
        },
    },
    raw,
    time_zone::{TimeZoneFormatter, TimeZoneFormatterOptions},
    DateTimeError,
};

/// This is the internal "raw" version of [crate::ZonedDateTimeFormatter], i.e. a version of ZonedDateTimeFormatter
/// without the generic parameter. The actual implementation of [crate::ZonedDateTimeFormatter] should live here.
#[derive(Debug)]
pub(crate) struct ZonedDateTimeFormatter {
    pub datetime_format: raw::DateTimeFormatter,
    pub time_zone_format: TimeZoneFormatter,
}

impl ZonedDateTimeFormatter {
    #[inline(never)]
    #[cfg(feature = "compiled_data")]
    pub fn try_new(
        patterns: DataPayload<PatternPluralsFromPatternsV1Marker>,
        symbols_data_fn: impl FnOnce() -> Result<DataPayload<ErasedDateSymbolsV1Marker>, DataError>,
        locale: &DataLocale,
        time_zone_format_options: TimeZoneFormatterOptions,
    ) -> Result<Self, DateTimeError> {
        let required = datetime::analyze_patterns(&patterns.get().0, true)
            .map_err(|field| DateTimeError::UnsupportedField(field.symbol))?;

        let req = DataRequest {
            locale,
            metadata: Default::default(),
        };

        let week_data = if required.week_data {
            Some(icu_calendar::week::WeekCalculator::try_new(locale)?)
        } else {
            None
        };

        let ordinal_rules = if let PatternPlurals::MultipleVariants(_) = &patterns.get().0 {
            Some(PluralRules::try_new_ordinal(locale)?)
        } else {
            None
        };

        let date_symbols_data = if required.date_symbols_data {
            Some(symbols_data_fn()?)
        } else {
            None
        };

        let time_symbols_data = if required.time_symbols_data {
            Some(crate::provider::Baked.load(req)?.take_payload()?)
        } else {
            None
        };

        let mut fixed_decimal_format_options = FixedDecimalFormatterOptions::default();
        fixed_decimal_format_options.grouping_strategy = GroupingStrategy::Never;

        let fixed_decimal_format =
            FixedDecimalFormatter::try_new(locale, fixed_decimal_format_options)?;

        let datetime_format = raw::DateTimeFormatter::new(
            patterns,
            date_symbols_data,
            time_symbols_data,
            week_data,
            ordinal_rules,
            fixed_decimal_format,
        );

        let time_zone_format = TimeZoneFormatter::try_new_for_pattern(
            &crate::provider::Baked,
            locale,
            datetime_format
                // Only dates have plural variants so we can use any of the patterns for the time segment.
                .patterns
                .clone(),
            &time_zone_format_options,
        )?;

        Ok(Self {
            datetime_format,
            time_zone_format,
        })
    }

    #[inline(never)]
    pub fn try_new_unstable<P>(
        provider: &P,
        patterns: DataPayload<PatternPluralsFromPatternsV1Marker>,
        symbols_data_fn: impl FnOnce() -> Result<DataPayload<ErasedDateSymbolsV1Marker>, DataError>,
        locale: &DataLocale,
        time_zone_format_options: TimeZoneFormatterOptions,
    ) -> Result<Self, DateTimeError>
    where
        P: DataProvider<TimeSymbolsV1Marker>
            + DataProvider<TimeLengthsV1Marker>
            + DataProvider<WeekDataV1Marker>
            + DataProvider<provider::time_zones::TimeZoneFormatsV1Marker>
            + DataProvider<provider::time_zones::ExemplarCitiesV1Marker>
            + DataProvider<provider::time_zones::MetazoneGenericNamesLongV1Marker>
            + DataProvider<provider::time_zones::MetazoneGenericNamesShortV1Marker>
            + DataProvider<provider::time_zones::MetazoneSpecificNamesLongV1Marker>
            + DataProvider<provider::time_zones::MetazoneSpecificNamesShortV1Marker>
            + DataProvider<OrdinalV1Marker>
            + DataProvider<DecimalSymbolsV1Marker>
            + ?Sized,
    {
        let required = datetime::analyze_patterns(&patterns.get().0, true)
            .map_err(|field| DateTimeError::UnsupportedField(field.symbol))?;

        let req = DataRequest {
            locale,
            metadata: Default::default(),
        };

        let week_data = if required.week_data {
            Some(
                (*DataProvider::<WeekDataV1Marker>::load(
                    provider,
                    DataRequest {
                        locale,
                        metadata: Default::default(),
                    },
                )?
                .take_payload()?
                .get())
                .into(),
            )
        } else {
            None
        };

        let ordinal_rules = if let PatternPlurals::MultipleVariants(_) = &patterns.get().0 {
            Some(PluralRules::try_new_ordinal_unstable(provider, locale)?)
        } else {
            None
        };

        let date_symbols_data = if required.date_symbols_data {
            Some(symbols_data_fn()?)
        } else {
            None
        };

        let time_symbols_data = if required.time_symbols_data {
            Some(provider.load(req)?.take_payload()?)
        } else {
            None
        };

        let mut fixed_decimal_format_options = FixedDecimalFormatterOptions::default();
        fixed_decimal_format_options.grouping_strategy = GroupingStrategy::Never;

        let fixed_decimal_format = FixedDecimalFormatter::try_new_unstable(
            provider,
            locale,
            fixed_decimal_format_options,
        )?;

        let datetime_format = raw::DateTimeFormatter::new(
            patterns,
            date_symbols_data,
            time_symbols_data,
            week_data,
            ordinal_rules,
            fixed_decimal_format,
        );

        let time_zone_format = TimeZoneFormatter::try_new_for_pattern(
            provider,
            locale,
            datetime_format
                // Only dates have plural variants so we can use any of the patterns for the time segment.
                .patterns
                .clone(),
            &time_zone_format_options,
        )?;

        Ok(Self {
            datetime_format,
            time_zone_format,
        })
    }

    /// Takes a [`ZonedDateTimeInput`] implementer and returns an instance of a [`FormattedZonedDateTime`]
    /// that contains all information necessary to display a formatted zoned datetime and operate on it.
    #[inline]
    pub fn format<'l>(
        &'l self,
        date: &impl DateTimeInput,
        time_zone: &impl TimeZoneInput,
    ) -> FormattedZonedDateTime<'l> {
        // Todo: optimize extraction #2143
        FormattedZonedDateTime {
            formatted_datetime: self.datetime_format.format(date),
            time_zone_format: &self.time_zone_format,
            time_zone: ExtractedTimeZoneInput::extract_from(time_zone),
        }
    }
}