Debian Codegraph @

debian/rust-vendor/icu_datetime/src/range/formatter.rs

raw
1 // This file is part of ICU4X. For terms of use, please see the file
2 // called LICENSE at the top level of the ICU4X source tree
3 // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).
4
5 use crate::DateTimeFormatter;
6 use crate::DateTimeFormatterLoadError;
7 use crate::DateTimeFormatterPreferences;
8 use crate::FixedCalendarDateTimeFormatter;
9 #[cfg(feature = "compiled_data")]
10 use crate::external_loaders::ExternalLoaderCompiledData;
11 use crate::external_loaders::{
12 DecimalFormatterLoader, ExternalLoaderUnstable, FormattableAnyCalendarLoader,
13 };
14 use crate::fieldsets::enums::CompositeFieldSet;
15 use crate::format::DateTimeInputUnchecked;
16 use crate::provider::range_patterns::DatetimePatternsRangeGlueV1;
17 use crate::range::formatter_impl::RangeFormatterCore;
18 use crate::range::write::FormattedDateRange;
19 use crate::raw::neo::DateTimeZoneRangePatternSelectionData;
20 use crate::scaffold::{
21 AllAnyCalendarExternalDataMarkers, AllAnyCalendarFormattingDataMarkers,
22 AllAnyCalendarRangePatternDataMarkers, AllFixedCalendarExternalDataMarkers,
23 AllFixedCalendarFormattingDataMarkers, AllFixedCalendarRangePatternDataMarkers,
24 AllInputMarkers, CldrCalendar, ConvertCalendar, DateDataMarkers, DateInputMarkers,
25 DateTimeMarkers, DateTimeNamesFrom, DateTimeNamesMarker, FormattableAnyCalendarNamesLoader,
26 GetField, InFixedCalendar, TimeMarkers, TypedDateDataMarkers, ZoneMarkers,
27 };
28 use icu_provider::prelude::*;
29
30 /// A formatter capable of formatting date/time ranges for any calendar.
31 ///
32 /// This formatter is calendar-agnostic. It dynamically converts the input dates to the
33 /// calendar preferred by the locale before formatting.
34 ///
35 /// # Examples
36 ///
37 /// ```
38 /// use icu::calendar::Date;
39 /// use icu::datetime::fieldsets::YMD;
40 /// use icu::datetime::input::{DateTime, Time};
41 /// use icu::datetime::range::DateRangeFormatter;
42 /// use icu::locale::locale;
43 /// use writeable::assert_writeable_eq;
44 ///
45 /// let fmt = DateRangeFormatter::try_new(
46 /// locale!("th-u-ca-buddhist").into(),
47 /// YMD::medium(),
48 /// )
49 /// .unwrap();
50 ///
51 /// let start = DateTime {
52 /// date: Date::try_new_gregorian(2023, 12, 22).unwrap(),
53 /// time: Time::try_new(9, 0, 0, 0).unwrap(),
54 /// };
55 /// let end = DateTime {
56 /// date: Date::try_new_gregorian(2023, 12, 23).unwrap(),
57 /// time: Time::try_new(17, 0, 0, 0).unwrap(),
58 /// };
59 ///
60 /// // Gregorian input is dynamically converted to Buddhist (2023 -> 2566)
61 /// // Thai day-difference range has no spaces around en-dash:
62 /// assert_writeable_eq!(fmt.format(&start, &end), "22–23 āļ˜.āļ„. 2566");
63 /// ```
64 #[derive(Debug)]
65 pub struct DateRangeFormatter<FSet: DateTimeNamesMarker> {
66 pub(crate) datetime_formatter: DateTimeFormatter<FSet>,
67 pub(crate) range_selection: DateTimeZoneRangePatternSelectionData,
68 }
69
70 impl<FSet: DateTimeMarkers + Clone> DateRangeFormatter<FSet>
71 where
72 FSet::D: DateDataMarkers,
73 FSet::T: TimeMarkers,
74 FSet::Z: ZoneMarkers,
75 FSet: GetField<CompositeFieldSet>,
76 {
77 pub(crate) fn try_new_internal<P>(
78 provider: &P,
79 external_loader: &(impl FormattableAnyCalendarLoader + DecimalFormatterLoader),
80 prefs: DateTimeFormatterPreferences,
81 field_set_with_options: FSet,
82 ) -> Result<Self, DateTimeFormatterLoadError>
83 where
84 P: ?Sized
85 + AllAnyCalendarFormattingDataMarkers<FSet>
86 + AllAnyCalendarRangePatternDataMarkers<FSet>,
87 {
88 let field = field_set_with_options.get_field();
89 let datetime_formatter =
90 DateTimeFormatter::try_new_internal(provider, external_loader, prefs, field)?;
91
92 let range_selection = DateTimeZoneRangePatternSelectionData::try_new_with_skeleton(
93 &FormattableAnyCalendarNamesLoader::<<FSet::D as DateDataMarkers>::RangeSkel, _>::new(
94 provider,
95 &datetime_formatter.calendar,
96 ),
97 &<FSet::T as TimeMarkers>::TimeRangeSkeletonPatternsV1::bind(provider),
98 &DatetimePatternsRangeGlueV1::bind(provider),
99 prefs,
100 field,
101 )
102 .map_err(DateTimeFormatterLoadError::Data)?;
103
104 Ok(Self {
105 datetime_formatter,
106 range_selection,
107 })
108 }
109
110 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
111 pub fn try_new_unstable<P>(
112 provider: &P,
113 prefs: DateTimeFormatterPreferences,
114 field_set_with_options: FSet,
115 ) -> Result<Self, DateTimeFormatterLoadError>
116 where
117 P: ?Sized
118 + AllAnyCalendarFormattingDataMarkers<FSet>
119 + AllAnyCalendarExternalDataMarkers
120 + AllAnyCalendarRangePatternDataMarkers<FSet>,
121 {
122 Self::try_new_internal(
123 provider,
124 &ExternalLoaderUnstable(provider),
125 prefs,
126 field_set_with_options,
127 )
128 }
129
130 #[cfg(feature = "compiled_data")]
131 /// Constructor using compiled data.
132 ///
133 /// âœĻ *Enabled with the `compiled_data` Cargo feature.*
134 ///
135 /// [📚 Help choosing a constructor](icu_provider::constructors)
136 pub fn try_new(
137 prefs: DateTimeFormatterPreferences,
138 field_set_with_options: FSet,
139 ) -> Result<Self, DateTimeFormatterLoadError>
140 where
141 crate::provider::Baked:
142 AllAnyCalendarFormattingDataMarkers<FSet> + AllAnyCalendarRangePatternDataMarkers<FSet>,
143 {
144 Self::try_new_internal(
145 &crate::provider::Baked,
146 &ExternalLoaderCompiledData,
147 prefs,
148 field_set_with_options,
149 )
150 }
151
152 #[cfg(feature = "serde")]
153 #[doc = icu_provider::gen_buffer_unstable_docs!(BUFFER, Self::try_new)]
154 pub fn try_new_with_buffer_provider<P>(
155 provider: &P,
156 prefs: DateTimeFormatterPreferences,
157 field_set_with_options: FSet,
158 ) -> Result<Self, DateTimeFormatterLoadError>
159 where
160 P: BufferProvider + ?Sized,
161 {
162 use crate::provider::compat::CompatProvider;
163 let deser_provider = provider.as_deserializing();
164 let compat_provider = CompatProvider(&deser_provider, provider);
165 Self::try_new_unstable(&compat_provider, prefs, field_set_with_options)
166 }
167
168 /// Casts the field set of this [`DateRangeFormatter`] to a dynamic field set.
169 pub fn cast_into_fset<FSet2: DateTimeNamesFrom<FSet>>(self) -> DateRangeFormatter<FSet2> {
170 DateRangeFormatter {
171 datetime_formatter: self.datetime_formatter.cast_into_fset(),
172 range_selection: self.range_selection,
173 }
174 }
175 }
176
177 impl<FSet: DateTimeMarkers + DateTimeNamesMarker> DateRangeFormatter<FSet>
178 where
179 FSet::D: DateInputMarkers,
180 FSet::T: TimeMarkers,
181 FSet::Z: ZoneMarkers,
182 {
183 /// Formats a date/time range.
184 ///
185 /// This method converts the input dates dynamically to the calendar preferred by the
186 /// locale before formatting them as a range.
187 pub fn format<'a, I>(&'a self, start: &I, end: &I) -> FormattedDateRange<'a>
188 where
189 I: ?Sized + ConvertCalendar,
190 I::Converted<'a>: Sized + AllInputMarkers<FSet>,
191 {
192 let start_cal = start.to_calendar(self.datetime_formatter.calendar.any_calendar());
193 let end_cal = end.to_calendar(self.datetime_formatter.calendar.any_calendar());
194
195 let start_input = DateTimeInputUnchecked::extract_from_neo_input::<
196 FSet::D,
197 FSet::T,
198 FSet::Z,
199 I::Converted<'a>,
200 >(&start_cal);
201 let end_input = DateTimeInputUnchecked::extract_from_neo_input::<
202 FSet::D,
203 FSet::T,
204 FSet::Z,
205 I::Converted<'a>,
206 >(&end_cal);
207
208 let core = RangeFormatterCore {
209 names: self.datetime_formatter.names.as_borrowed(),
210 selection: &self.datetime_formatter.selection,
211 range_selection: &self.range_selection,
212 };
213
214 core.format(&start_input, &end_input)
215 }
216 }
217
218 /// A formatter capable of formatting date/time ranges for a specific calendar.
219 ///
220 /// This formatter is statically typed to a specific calendar `C`. It is highly optimized
221 /// and avoids the overhead of dynamic calendar conversion, but can only format dates
222 /// that are in the calendar `C` (or can be statically converted to it).
223 ///
224 /// # Examples
225 ///
226 /// ```
227 /// use icu::calendar::Date;
228 /// use icu::datetime::input::{DateTime, Time};
229 /// use icu::datetime::fieldsets::YMD;
230 /// use icu::datetime::range::FixedCalendarDateRangeFormatter;
231 /// use icu::locale::locale;
232 /// use writeable::assert_writeable_eq;
233 ///
234 /// let fmt = FixedCalendarDateRangeFormatter::try_new(
235 /// locale!("en").into(),
236 /// YMD::medium(),
237 /// )
238 /// .unwrap();
239 ///
240 /// let start = DateTime {
241 /// date: Date::try_new_gregorian(2023, 12, 22).unwrap(),
242 /// time: Time::try_new(9, 0, 0, 0).unwrap(),
243 /// };
244 /// let end = DateTime {
245 /// date: Date::try_new_gregorian(2023, 12, 23).unwrap(),
246 /// time: Time::try_new(17, 0, 0, 0).unwrap(),
247 /// };
248 ///
249 /// // English medium YMD day-difference range uses thin spaces (\u{2009}) around en-dash:
250 /// assert_writeable_eq!(
251 /// fmt.format(&start, &end),
252 /// "Dec 22\u{2009}–\u{2009}23, 2023"
253 /// );
254 /// ```
255 #[derive(Debug)]
256 pub struct FixedCalendarDateRangeFormatter<C: CldrCalendar, FSet: DateTimeNamesMarker> {
257 pub(crate) datetime_formatter: FixedCalendarDateTimeFormatter<C, FSet>,
258 pub(crate) range_selection: DateTimeZoneRangePatternSelectionData,
259 }
260
261 impl<C: CldrCalendar, FSet: DateTimeMarkers + Clone> FixedCalendarDateRangeFormatter<C, FSet>
262 where
263 FSet::D: TypedDateDataMarkers<C>,
264 FSet::T: TimeMarkers,
265 FSet::Z: ZoneMarkers,
266 FSet: GetField<CompositeFieldSet>,
267 {
268 pub(crate) fn try_new_internal<P>(
269 provider: &P,
270 external_loader: &impl DecimalFormatterLoader,
271 prefs: DateTimeFormatterPreferences,
272 field_set_with_options: FSet,
273 ) -> Result<Self, DateTimeFormatterLoadError>
274 where
275 P: ?Sized
276 + AllFixedCalendarFormattingDataMarkers<C, FSet>
277 + AllFixedCalendarRangePatternDataMarkers<C, FSet>,
278 {
279 let field = field_set_with_options.get_field();
280 let datetime_formatter = FixedCalendarDateTimeFormatter::try_new_internal(
281 provider,
282 external_loader,
283 prefs,
284 field,
285 )?;
286
287 let range_selection = DateTimeZoneRangePatternSelectionData::try_new_with_skeleton(
288 &<FSet::D as TypedDateDataMarkers<C>>::DateRangeSkeletonPatternsV1::bind(provider),
289 &<FSet::T as TimeMarkers>::TimeRangeSkeletonPatternsV1::bind(provider),
290 &DatetimePatternsRangeGlueV1::bind(provider),
291 prefs,
292 field,
293 )
294 .map_err(DateTimeFormatterLoadError::Data)?;
295
296 Ok(Self {
297 datetime_formatter,
298 range_selection,
299 })
300 }
301
302 #[doc = icu_provider::gen_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
303 pub fn try_new_unstable<P>(
304 provider: &P,
305 prefs: DateTimeFormatterPreferences,
306 field_set_with_options: FSet,
307 ) -> Result<Self, DateTimeFormatterLoadError>
308 where
309 P: ?Sized
310 + AllFixedCalendarFormattingDataMarkers<C, FSet>
311 + AllFixedCalendarExternalDataMarkers
312 + AllFixedCalendarRangePatternDataMarkers<C, FSet>,
313 {
314 Self::try_new_internal(
315 provider,
316 &ExternalLoaderUnstable(provider),
317 prefs,
318 field_set_with_options,
319 )
320 }
321
322 #[cfg(feature = "compiled_data")]
323 /// Constructor using compiled data.
324 ///
325 /// âœĻ *Enabled with the `compiled_data` Cargo feature.*
326 ///
327 /// [📚 Help choosing a constructor](icu_provider::constructors)
328 pub fn try_new(
329 prefs: DateTimeFormatterPreferences,
330 field_set_with_options: FSet,
331 ) -> Result<Self, DateTimeFormatterLoadError>
332 where
333 crate::provider::Baked: AllFixedCalendarFormattingDataMarkers<C, FSet>
334 + AllFixedCalendarRangePatternDataMarkers<C, FSet>,
335 {
336 Self::try_new_internal(
337 &crate::provider::Baked,
338 &ExternalLoaderCompiledData,
339 prefs,
340 field_set_with_options,
341 )
342 }
343
344 #[cfg(feature = "serde")]
345 #[doc = icu_provider::gen_buffer_unstable_docs!(BUFFER, Self::try_new)]
346 pub fn try_new_with_buffer_provider<P>(
347 provider: &P,
348 prefs: DateTimeFormatterPreferences,
349 field_set_with_options: FSet,
350 ) -> Result<Self, DateTimeFormatterLoadError>
351 where
352 P: BufferProvider + ?Sized,
353 {
354 use crate::provider::compat::CompatProvider;
355 let deser_provider = provider.as_deserializing();
356 let compat_provider = CompatProvider(&deser_provider, provider);
357 Self::try_new_unstable(&compat_provider, prefs, field_set_with_options)
358 }
359
360 /// Casts the field set of this [`FixedCalendarDateRangeFormatter`] to a dynamic field set.
361 pub fn cast_into_fset<FSet2: DateTimeNamesFrom<FSet>>(
362 self,
363 ) -> FixedCalendarDateRangeFormatter<C, FSet2> {
364 FixedCalendarDateRangeFormatter {
365 datetime_formatter: self.datetime_formatter.cast_into_fset(),
366 range_selection: self.range_selection,
367 }
368 }
369 }
370
371 impl<C: CldrCalendar, FSet: DateTimeMarkers + DateTimeNamesMarker>
372 FixedCalendarDateRangeFormatter<C, FSet>
373 where
374 FSet::D: DateInputMarkers,
375 FSet::T: TimeMarkers,
376 FSet::Z: ZoneMarkers,
377 {
378 /// Formats a date/time range.
379 ///
380 /// This method formats the input dates directly, enforcing that they must be in the
381 /// statically typed calendar `C`.
382 pub fn format<'a, I>(&'a self, start: &I, end: &I) -> FormattedDateRange<'a>
383 where
384 I: ?Sized + InFixedCalendar<C> + AllInputMarkers<FSet>,
385 {
386 let start_input =
387 DateTimeInputUnchecked::extract_from_neo_input::<FSet::D, FSet::T, FSet::Z, I>(start);
388 let end_input =
389 DateTimeInputUnchecked::extract_from_neo_input::<FSet::D, FSet::T, FSet::Z, I>(end);
390
391 let core = RangeFormatterCore {
392 names: self.datetime_formatter.names.as_borrowed(),
393 selection: &self.datetime_formatter.selection,
394 range_selection: &self.range_selection,
395 };
396
397 core.format(&start_input, &end_input)
398 }
399 }