Debian Codegraph @

debian/rust-vendor/icu_datetime/src/options/mod.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 //! Options types for date/time formatting.
6
7 use icu_time::scaffold::IntoOption;
8
9 /// The length of a formatted date/time string.
10 ///
11 /// Length settings are always a hint, not a guarantee. For example, certain locales and
12 /// calendar systems do not define numeric names, so spelled-out names could occur even if a
13 /// short length was requested, and likewise with numeric names with a medium or long length.
14 ///
15 /// # Examples
16 ///
17 /// ```
18 /// use icu::calendar::Gregorian;
19 /// use icu::datetime::FixedCalendarDateTimeFormatter;
20 /// use icu::datetime::fieldsets::YMD;
21 /// use icu::datetime::input::Date;
22 /// use icu::locale::locale;
23 /// use writeable::assert_writeable_eq;
24 ///
25 /// let short_formatter = FixedCalendarDateTimeFormatter::try_new(
26 /// locale!("en-US").into(),
27 /// YMD::short(),
28 /// )
29 /// .unwrap();
30 ///
31 /// let medium_formatter = FixedCalendarDateTimeFormatter::try_new(
32 /// locale!("en-US").into(),
33 /// YMD::medium(),
34 /// )
35 /// .unwrap();
36 ///
37 /// let long_formatter = FixedCalendarDateTimeFormatter::try_new(
38 /// locale!("en-US").into(),
39 /// YMD::long(),
40 /// )
41 /// .unwrap();
42 ///
43 /// assert_writeable_eq!(
44 /// short_formatter.format(&Date::try_new_gregorian(2000, 1, 1).unwrap()),
45 /// "1/1/00"
46 /// );
47 ///
48 /// assert_writeable_eq!(
49 /// medium_formatter.format(&Date::try_new_gregorian(2000, 1, 1).unwrap()),
50 /// "Jan 1, 2000"
51 /// );
52 ///
53 /// assert_writeable_eq!(
54 /// long_formatter.format(&Date::try_new_gregorian(2000, 1, 1).unwrap()),
55 /// "January 1, 2000"
56 /// );
57 /// ```
58 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default)]
59 #[cfg_attr(
60 all(feature = "serde", feature = "unstable"),
61 derive(serde::Serialize, serde::Deserialize)
62 )]
63 #[cfg_attr(
64 all(feature = "serde", feature = "unstable"),
65 serde(rename_all = "lowercase")
66 )]
67 #[non_exhaustive]
68 pub enum Length {
69 /// A long date; typically spelled-out, as in “January 1, 2000”.
70 Long,
71 /// A medium-sized date; typically abbreviated, as in “Jan. 1, 2000”.
72 ///
73 /// This is the default.
74 #[default]
75 Medium,
76 /// A short date; typically numeric, as in “1/1/2000”.
77 Short,
78 }
79
80 impl IntoOption<Length> for Length {
81 #[inline]
82 fn into_option(self) -> Option<Self> {
83 Some(self)
84 }
85 }
86
87 /// The alignment context of the formatted string.
88 ///
89 /// By default, datetimes are formatted for a variable-width context. You can
90 /// give a hint that the strings will be displayed in a column-like context,
91 /// which will coerce numerics to be padded with zeros.
92 ///
93 /// # Examples
94 ///
95 /// ```
96 /// use icu::calendar::Gregorian;
97 /// use icu::datetime::FixedCalendarDateTimeFormatter;
98 /// use icu::datetime::fieldsets::YMD;
99 /// use icu::datetime::input::Date;
100 /// use icu::datetime::options::Alignment;
101 /// use icu::locale::locale;
102 /// use writeable::assert_writeable_eq;
103 ///
104 /// let plain_formatter =
105 /// FixedCalendarDateTimeFormatter::<Gregorian, _>::try_new(
106 /// locale!("en-US").into(),
107 /// YMD::short(),
108 /// )
109 /// .unwrap();
110 ///
111 /// let column_formatter =
112 /// FixedCalendarDateTimeFormatter::<Gregorian, _>::try_new(
113 /// locale!("en-US").into(),
114 /// YMD::short().with_alignment(Alignment::Column),
115 /// )
116 /// .unwrap();
117 ///
118 /// // By default, en-US does not pad the month and day with zeros.
119 /// assert_writeable_eq!(
120 /// plain_formatter.format(&Date::try_new_gregorian(2025, 1, 1).unwrap()),
121 /// "1/1/25"
122 /// );
123 ///
124 /// // The column alignment option hints that they should be padded.
125 /// assert_writeable_eq!(
126 /// column_formatter.format(&Date::try_new_gregorian(2025, 1, 1).unwrap()),
127 /// "01/01/25"
128 /// );
129 /// ```
130 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default)]
131 #[cfg_attr(
132 all(feature = "serde", feature = "unstable"),
133 derive(serde::Serialize, serde::Deserialize)
134 )]
135 #[cfg_attr(
136 all(feature = "serde", feature = "unstable"),
137 serde(rename_all = "lowercase")
138 )]
139 #[non_exhaustive]
140 pub enum Alignment {
141 /// Align fields as the locale specifies them to be aligned.
142 ///
143 /// This is the default option.
144 #[default]
145 Auto,
146 /// Align fields as appropriate for a column layout. For example:
147 ///
148 /// | US Holiday | Date |
149 /// |--------------|------------|
150 /// | Memorial Day | 05/26/2025 |
151 /// | Labor Day | 09/01/2025 |
152 /// | Veterans Day | 11/11/2025 |
153 ///
154 /// This option causes numeric fields to be padded when necessary. It does
155 /// not impact whether a numeric or spelled-out field is chosen.
156 Column,
157 }
158
159 impl IntoOption<Alignment> for Alignment {
160 #[inline]
161 fn into_option(self) -> Option<Self> {
162 Some(self)
163 }
164 }
165
166 /// A specification for how the year should be displayed.
167 ///
168 /// Under the hood, this controls two internal aspects of year and era formatting:
169 /// 1. Whether the era (e.g., AD/BC) is displayed.
170 /// 2. Whether the century (e.g., 2025 vs 25) is displayed.
171 ///
172 /// The choices may grow over time; to follow along and offer feedback, see
173 /// <https://github.com/unicode-org/icu4x/issues/6010>.
174 ///
175 /// | `YearStyle` | -1000 | 77 | 1900 | 2025 |
176 /// |---|---|---|---|---|
177 /// | [`Auto`](YearStyle::Auto) | 1001 BC | 77 AD | 1900 | 25 |
178 /// | [`Full`](YearStyle::Full) | 1001 BC | 77 AD | 1900 | 2025 |
179 /// | [`WithEra`](YearStyle::WithEra) | 1001 BC | 77 AD | 1900 AD | 2025 AD |
180 /// | [`NoEra`](YearStyle::NoEra) | 1001 | 77 | 1900 | 25 |
181 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default)]
182 #[cfg_attr(
183 all(feature = "serde", feature = "unstable"),
184 derive(serde::Serialize, serde::Deserialize)
185 )]
186 #[cfg_attr(
187 all(feature = "serde", feature = "unstable"),
188 serde(rename_all = "camelCase")
189 )]
190 #[non_exhaustive]
191 pub enum YearStyle {
192 /// Display the century and/or era when needed to disambiguate the year,
193 /// based on locale preferences.
194 ///
195 /// This is the default option.
196 ///
197 /// # Examples
198 ///
199 /// ```
200 /// use icu::calendar::Gregorian;
201 /// use icu::datetime::FixedCalendarDateTimeFormatter;
202 /// use icu::datetime::fieldsets::YMD;
203 /// use icu::datetime::input::Date;
204 /// use icu::datetime::options::YearStyle;
205 /// use icu::locale::locale;
206 /// use writeable::assert_writeable_eq;
207 ///
208 /// let formatter = FixedCalendarDateTimeFormatter::<Gregorian, _>::try_new(
209 /// locale!("en-US").into(),
210 /// YMD::short().with_year_style(YearStyle::Auto),
211 /// )
212 /// .unwrap();
213 ///
214 /// assert_writeable_eq!(
215 /// formatter.format(&Date::try_new_gregorian(-1000, 1, 1).unwrap()),
216 /// "1/1/1001 BC"
217 /// );
218 /// assert_writeable_eq!(
219 /// formatter.format(&Date::try_new_gregorian(2025, 1, 1).unwrap()),
220 /// "1/1/25"
221 /// );
222 /// ```
223 #[default]
224 Auto,
225 /// Always display the century, and display the era when needed to
226 /// disambiguate the year, based on locale preferences.
227 ///
228 /// # Examples
229 ///
230 /// ```
231 /// use icu::calendar::Gregorian;
232 /// use icu::datetime::FixedCalendarDateTimeFormatter;
233 /// use icu::datetime::fieldsets::YMD;
234 /// use icu::datetime::input::Date;
235 /// use icu::datetime::options::YearStyle;
236 /// use icu::locale::locale;
237 /// use writeable::assert_writeable_eq;
238 ///
239 /// let formatter = FixedCalendarDateTimeFormatter::<Gregorian, _>::try_new(
240 /// locale!("en-US").into(),
241 /// YMD::short().with_year_style(YearStyle::Full),
242 /// )
243 /// .unwrap();
244 ///
245 /// assert_writeable_eq!(
246 /// formatter.format(&Date::try_new_gregorian(-1000, 1, 1).unwrap()),
247 /// "1/1/1001 BC"
248 /// );
249 /// assert_writeable_eq!(
250 /// formatter.format(&Date::try_new_gregorian(2025, 1, 1).unwrap()),
251 /// "1/1/2025"
252 /// );
253 /// ```
254 Full,
255 /// Always display the century and era.
256 ///
257 /// # Examples
258 ///
259 /// ```
260 /// use icu::calendar::Gregorian;
261 /// use icu::datetime::FixedCalendarDateTimeFormatter;
262 /// use icu::datetime::fieldsets::YMD;
263 /// use icu::datetime::input::Date;
264 /// use icu::datetime::options::YearStyle;
265 /// use icu::locale::locale;
266 /// use writeable::assert_writeable_eq;
267 ///
268 /// let formatter = FixedCalendarDateTimeFormatter::<Gregorian, _>::try_new(
269 /// locale!("en-US").into(),
270 /// YMD::short().with_year_style(YearStyle::WithEra),
271 /// )
272 /// .unwrap();
273 ///
274 /// assert_writeable_eq!(
275 /// formatter.format(&Date::try_new_gregorian(2025, 1, 1).unwrap()),
276 /// "1/1/2025 AD"
277 /// );
278 /// ```
279 WithEra,
280 /// Display the century but never display the era.
281 ///
282 /// Corresponds to `eraDisplay: "never"` in the ECMA-402 Intl.eraDisplay proposal.
283 ///
284 /// Examples:
285 ///
286 /// - `1000`
287 /// - `77`
288 /// - `1900`
289 /// - `2024`
290 ///
291 /// # Examples
292 ///
293 /// ```
294 /// use icu::calendar::Gregorian;
295 /// use icu::datetime::FixedCalendarDateTimeFormatter;
296 /// use icu::datetime::fieldsets::YMD;
297 /// use icu::datetime::input::Date;
298 /// use icu::datetime::options::YearStyle;
299 /// use icu::locale::locale;
300 /// use writeable::assert_writeable_eq;
301 ///
302 /// let formatter = FixedCalendarDateTimeFormatter::<Gregorian, _>::try_new(
303 /// locale!("en-US").into(),
304 /// YMD::short().with_year_style(YearStyle::NoEra),
305 /// )
306 /// .unwrap();
307 ///
308 /// // Era elided even for dates before year 0:
309 /// assert_writeable_eq!(
310 /// formatter.format(&Date::try_new_gregorian(-1000, 1, 1).unwrap()),
311 /// "1/1/1001"
312 /// );
313 /// assert_writeable_eq!(
314 /// formatter.format(&Date::try_new_gregorian(77, 1, 1).unwrap()),
315 /// "1/1/77"
316 /// );
317 /// assert_writeable_eq!(
318 /// formatter.format(&Date::try_new_gregorian(1900, 1, 1).unwrap()),
319 /// "1/1/1900"
320 /// );
321 /// // Era and century both elided for nearby years:
322 /// assert_writeable_eq!(
323 /// formatter.format(&Date::try_new_gregorian(2025, 1, 1).unwrap()),
324 /// "1/1/25"
325 /// );
326 /// ```
327 NoEra,
328 }
329
330 impl IntoOption<YearStyle> for YearStyle {
331 #[inline]
332 fn into_option(self) -> Option<Self> {
333 Some(self)
334 }
335 }
336
337 /// A specification for how precisely to display the time of day.
338 ///
339 /// The time can be displayed with hour, minute, or second precision, and
340 /// zero-valued fields can be automatically hidden.
341 ///
342 /// The examples in the discriminants are based on the following inputs and hour cycles:
343 ///
344 /// 1. 11 o'clock with 12-hour time
345 /// 2. 16:00 (4:00 pm) with 24-hour time
346 /// 3. 7:15:01.85 with 24-hour time
347 ///
348 /// Fractional second digits can be displayed with a fixed precision. If you would like
349 /// additional options for fractional second digit display, please leave a comment in
350 /// <https://github.com/unicode-org/icu4x/issues/6008>.
351 ///
352 /// # Examples
353 ///
354 /// Comparison of all time precision options:
355 ///
356 /// ```
357 /// use icu::datetime::input::Time;
358 /// use icu::datetime::fieldsets::T;
359 /// use icu::datetime::options::SubsecondDigits;
360 /// use icu::datetime::options::TimePrecision;
361 /// use icu::datetime::NoCalendarFormatter;
362 /// use icu::locale::locale;
363 /// use writeable::assert_writeable_eq;
364 ///
365 /// let formatters = [
366 /// TimePrecision::Hour,
367 /// TimePrecision::Minute,
368 /// TimePrecision::Second,
369 /// TimePrecision::Subsecond(SubsecondDigits::S2),
370 /// TimePrecision::MinuteOptional,
371 /// ]
372 /// .map(|time_precision| {
373 /// NoCalendarFormatter::try_new(
374 /// locale!("en-US").into(),
375 /// T::short().with_time_precision(time_precision),
376 /// )
377 /// .unwrap()
378 /// });
379 ///
380 /// let times = [
381 /// Time::try_new(7, 0, 0, 0).unwrap(),
382 /// Time::try_new(7, 0, 10, 0).unwrap(),
383 /// Time::try_new(7, 12, 20, 543_200_000).unwrap(),
384 /// ];
385 ///
386 /// let expected_value_table = [
387 /// // 7:00:00, 7:00:10, 7:12:20.5432
388 /// ["7 AM", "7 AM", "7 AM"], // Hour
389 /// ["7:00 AM", "7:00 AM", "7:12 AM"], // Minute
390 /// ["7:00:00 AM", "7:00:10 AM", "7:12:20 AM"], // Second
391 /// ["7:00:00.00 AM", "7:00:10.00 AM", "7:12:20.54 AM"], // Subsecond(F2)
392 /// ["7 AM", "7 AM", "7:12 AM"], // MinuteOptional
393 /// ];
394 ///
395 /// for (expected_value_row, formatter) in
396 /// expected_value_table.iter().zip(formatters.iter())
397 /// {
398 /// for (expected_value, time) in
399 /// expected_value_row.iter().zip(times.iter())
400 /// {
401 /// assert_writeable_eq!(
402 /// formatter.format(time),
403 /// *expected_value,
404 /// "{formatter:?} @ {time:?}"
405 /// );
406 /// }
407 /// }
408 /// ```
409 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, Default)]
410 #[cfg_attr(
411 all(feature = "serde", feature = "unstable"),
412 derive(serde::Serialize, serde::Deserialize)
413 )]
414 #[cfg_attr(
415 all(feature = "serde", feature = "unstable"),
416 serde(from = "TimePrecisionSerde", into = "TimePrecisionSerde")
417 )]
418 #[non_exhaustive]
419 pub enum TimePrecision {
420 /// Display the hour. Hide all other time fields.
421 ///
422 /// Examples:
423 ///
424 /// 1. `11 am`
425 /// 2. `16h`
426 /// 3. `07h`
427 Hour,
428 /// Display the hour and minute. Hide the second.
429 ///
430 /// Examples:
431 ///
432 /// 1. `11:00 am`
433 /// 2. `16:00`
434 /// 3. `07:15`
435 Minute,
436 /// Display the hour, minute, and second. Hide fractional seconds.
437 ///
438 /// This is currently the default, but the default is subject to change.
439 ///
440 /// Examples:
441 ///
442 /// 1. `11:00:00 am`
443 /// 2. `16:00:00`
444 /// 3. `07:15:01`
445 #[default]
446 Second,
447 /// Display the hour, minute, and second with the given number of
448 /// fractional second digits.
449 ///
450 /// Examples with [`SubsecondDigits::S1`]:
451 ///
452 /// 1. `11:00:00.0 am`
453 /// 2. `16:00:00.0`
454 /// 3. `07:15:01.8`
455 Subsecond(SubsecondDigits),
456 /// Display the hour; display the minute if nonzero or if the pattern/hour cycle retains 0 minutes (such as in 24-hour time). Hide the second.
457 ///
458 /// Examples:
459 ///
460 /// 1. `11 am`
461 /// 2. `16:00`
462 /// 3. `07:15`
463 MinuteOptional,
464 }
465
466 impl IntoOption<TimePrecision> for TimePrecision {
467 #[inline]
468 fn into_option(self) -> Option<Self> {
469 Some(self)
470 }
471 }
472
473 #[cfg(all(feature = "serde", feature = "unstable"))]
474 #[derive(Copy, Clone, serde::Serialize, serde::Deserialize)]
475 #[serde(rename_all = "camelCase")]
476 enum TimePrecisionSerde {
477 Hour,
478 Minute,
479 Second,
480 Subsecond1,
481 Subsecond2,
482 Subsecond3,
483 Subsecond4,
484 Subsecond5,
485 Subsecond6,
486 Subsecond7,
487 Subsecond8,
488 Subsecond9,
489 MinuteOptional,
490 }
491
492 #[cfg(all(feature = "serde", feature = "unstable"))]
493 impl From<TimePrecision> for TimePrecisionSerde {
494 fn from(value: TimePrecision) -> Self {
495 match value {
496 TimePrecision::Hour => TimePrecisionSerde::Hour,
497 TimePrecision::Minute => TimePrecisionSerde::Minute,
498 TimePrecision::Second => TimePrecisionSerde::Second,
499 TimePrecision::Subsecond(SubsecondDigits::S1) => TimePrecisionSerde::Subsecond1,
500 TimePrecision::Subsecond(SubsecondDigits::S2) => TimePrecisionSerde::Subsecond2,
501 TimePrecision::Subsecond(SubsecondDigits::S3) => TimePrecisionSerde::Subsecond3,
502 TimePrecision::Subsecond(SubsecondDigits::S4) => TimePrecisionSerde::Subsecond4,
503 TimePrecision::Subsecond(SubsecondDigits::S5) => TimePrecisionSerde::Subsecond5,
504 TimePrecision::Subsecond(SubsecondDigits::S6) => TimePrecisionSerde::Subsecond6,
505 TimePrecision::Subsecond(SubsecondDigits::S7) => TimePrecisionSerde::Subsecond7,
506 TimePrecision::Subsecond(SubsecondDigits::S8) => TimePrecisionSerde::Subsecond8,
507 TimePrecision::Subsecond(SubsecondDigits::S9) => TimePrecisionSerde::Subsecond9,
508 TimePrecision::MinuteOptional => TimePrecisionSerde::MinuteOptional,
509 }
510 }
511 }
512
513 #[cfg(all(feature = "serde", feature = "unstable"))]
514 impl From<TimePrecisionSerde> for TimePrecision {
515 fn from(value: TimePrecisionSerde) -> Self {
516 match value {
517 TimePrecisionSerde::Hour => TimePrecision::Hour,
518 TimePrecisionSerde::Minute => TimePrecision::Minute,
519 TimePrecisionSerde::Second => TimePrecision::Second,
520 TimePrecisionSerde::Subsecond1 => TimePrecision::Subsecond(SubsecondDigits::S1),
521 TimePrecisionSerde::Subsecond2 => TimePrecision::Subsecond(SubsecondDigits::S2),
522 TimePrecisionSerde::Subsecond3 => TimePrecision::Subsecond(SubsecondDigits::S3),
523 TimePrecisionSerde::Subsecond4 => TimePrecision::Subsecond(SubsecondDigits::S4),
524 TimePrecisionSerde::Subsecond5 => TimePrecision::Subsecond(SubsecondDigits::S5),
525 TimePrecisionSerde::Subsecond6 => TimePrecision::Subsecond(SubsecondDigits::S6),
526 TimePrecisionSerde::Subsecond7 => TimePrecision::Subsecond(SubsecondDigits::S7),
527 TimePrecisionSerde::Subsecond8 => TimePrecision::Subsecond(SubsecondDigits::S8),
528 TimePrecisionSerde::Subsecond9 => TimePrecision::Subsecond(SubsecondDigits::S9),
529 TimePrecisionSerde::MinuteOptional => TimePrecision::MinuteOptional,
530 }
531 }
532 }
533
534 /// A specification for how many fractional second digits to display.
535 ///
536 /// For example, to display the time with millisecond precision, use
537 /// [`SubsecondDigits::S3`].
538 ///
539 /// Lower-precision digits will be truncated.
540 ///
541 /// # Examples
542 ///
543 /// Times can be displayed with a custom number of fractional digits from 0-9:
544 ///
545 /// ```
546 /// use icu::calendar::Gregorian;
547 /// use icu::datetime::FixedCalendarDateTimeFormatter;
548 /// use icu::datetime::fieldsets::T;
549 /// use icu::datetime::input::Time;
550 /// use icu::datetime::options::SubsecondDigits;
551 /// use icu::datetime::options::TimePrecision;
552 /// use icu::locale::locale;
553 /// use writeable::assert_writeable_eq;
554 ///
555 /// let formatter = FixedCalendarDateTimeFormatter::<(), _>::try_new(
556 /// locale!("en-US").into(),
557 /// T::short()
558 /// .with_time_precision(TimePrecision::Subsecond(SubsecondDigits::S2)),
559 /// )
560 /// .unwrap();
561 ///
562 /// assert_writeable_eq!(
563 /// formatter.format(&Time::try_new(16, 12, 20, 543200000).unwrap()),
564 /// "4:12:20.54 PM"
565 /// );
566 /// ```
567 #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
568 #[non_exhaustive]
569 pub enum SubsecondDigits {
570 /// One fractional digit (tenths of a second).
571 S1 = 1,
572 /// Two fractional digits (hundredths of a second).
573 S2 = 2,
574 /// Three fractional digits (milliseconds).
575 S3 = 3,
576 /// Four fractional digits.
577 S4 = 4,
578 /// Five fractional digits.
579 S5 = 5,
580 /// Six fractional digits (microseconds).
581 S6 = 6,
582 /// Seven fractional digits.
583 S7 = 7,
584 /// Eight fractional digits.
585 S8 = 8,
586 /// Nine fractional digits (nanoseconds)
587 S9 = 9,
588 }
589
590 impl SubsecondDigits {
591 /// Constructs a [`SubsecondDigits`] from an integer number of digits.
592 pub fn try_from_int(value: u8) -> Option<Self> {
593 use SubsecondDigits::*;
594 match value {
595 1 => Some(S1),
596 2 => Some(S2),
597 3 => Some(S3),
598 4 => Some(S4),
599 5 => Some(S5),
600 6 => Some(S6),
601 7 => Some(S7),
602 8 => Some(S8),
603 9 => Some(S9),
604 _ => None,
605 }
606 }
607 }
608
609 impl From<SubsecondDigits> for u8 {
610 fn from(value: SubsecondDigits) -> u8 {
611 use SubsecondDigits::*;
612 match value {
613 S1 => 1,
614 S2 => 2,
615 S3 => 3,
616 S4 => 4,
617 S5 => 5,
618 S6 => 6,
619 S7 => 7,
620 S8 => 8,
621 S9 => 9,
622 }
623 }
624 }