Debian Codegraph @

debian/rust-vendor/icu_calendar/src/options.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 used by types in this crate
6
7 /// Options bag for [`Date::try_from_fields`](crate::Date::try_from_fields).
8 #[derive(Copy, Clone, Debug, PartialEq, Default)]
9 #[non_exhaustive]
10 pub struct DateFromFieldsOptions {
11 /// How to behave with out-of-bounds fields.
12 ///
13 /// Defaults to [`Overflow::Reject`].
14 ///
15 /// # Examples
16 ///
17 /// ```
18 /// use icu::calendar::Date;
19 /// use icu::calendar::Iso;
20 /// use icu::calendar::options::DateFromFieldsOptions;
21 /// use icu::calendar::options::Overflow;
22 /// use icu::calendar::types::DateFields;
23 ///
24 /// // There is no day 31 in September.
25 /// let mut fields = DateFields::default();
26 /// fields.extended_year = Some(2025);
27 /// fields.ordinal_month = Some(9);
28 /// fields.day = Some(31);
29 ///
30 /// let options_default = DateFromFieldsOptions::default();
31 /// assert!(Date::try_from_fields(fields, options_default, Iso).is_err());
32 ///
33 /// let mut options_reject = options_default;
34 /// options_reject.overflow = Some(Overflow::Reject);
35 /// assert!(Date::try_from_fields(fields, options_reject, Iso).is_err());
36 ///
37 /// let mut options_constrain = options_default;
38 /// options_constrain.overflow = Some(Overflow::Constrain);
39 /// assert_eq!(
40 /// Date::try_from_fields(fields, options_constrain, Iso).unwrap(),
41 /// Date::try_new_iso(2025, 9, 30).unwrap()
42 /// );
43 /// ```
44 pub overflow: Option<Overflow>,
45 /// How to behave when the fields that are present do not fully constitute a Date.
46 ///
47 /// This option can be used to fill in a missing year given a month and a day according to
48 /// the ECMAScript Temporal specification.
49 ///
50 /// # Examples
51 ///
52 /// ```
53 /// use icu::calendar::Date;
54 /// use icu::calendar::Iso;
55 /// use icu::calendar::options::DateFromFieldsOptions;
56 /// use icu::calendar::options::MissingFieldsStrategy;
57 /// use icu::calendar::types::{DateFields, Month};
58 ///
59 /// // These options are missing a year.
60 /// let mut fields = DateFields::default();
61 /// fields.month = Some(Month::new(2));
62 /// fields.day = Some(1);
63 ///
64 /// let options_default = DateFromFieldsOptions::default();
65 /// assert!(Date::try_from_fields(fields, options_default, Iso).is_err());
66 ///
67 /// let mut options_reject = options_default;
68 /// options_reject.missing_fields_strategy =
69 /// Some(MissingFieldsStrategy::Reject);
70 /// assert!(Date::try_from_fields(fields, options_reject, Iso).is_err());
71 ///
72 /// let mut options_ecma = options_default;
73 /// options_ecma.missing_fields_strategy = Some(MissingFieldsStrategy::Ecma);
74 /// assert_eq!(
75 /// Date::try_from_fields(fields, options_ecma, Iso).unwrap(),
76 /// Date::try_new_iso(1972, 2, 1).unwrap()
77 /// );
78 /// ```
79 pub missing_fields_strategy: Option<MissingFieldsStrategy>,
80 }
81
82 /// Options for adding a duration to a date.
83 #[derive(Copy, Clone, PartialEq, Debug, Default)]
84 #[non_exhaustive]
85 pub struct DateAddOptions {
86 /// How to behave with out-of-bounds fields during arithmetic.
87 ///
88 /// Defaults to [`Overflow::Constrain`].
89 ///
90 /// # Examples
91 ///
92 /// ```
93 /// use icu::calendar::Date;
94 /// use icu::calendar::options::DateAddOptions;
95 /// use icu::calendar::options::Overflow;
96 /// use icu::calendar::types::DateDuration;
97 ///
98 /// // There is a day 31 in October but not in November.
99 /// let d1 = Date::try_new_iso(2025, 10, 31).unwrap();
100 /// let duration = DateDuration::for_months(1);
101 ///
102 /// let options_default = DateAddOptions::default();
103 /// assert_eq!(
104 /// d1.try_added_with_options(duration, options_default)
105 /// .unwrap(),
106 /// Date::try_new_iso(2025, 11, 30).unwrap()
107 /// );
108 ///
109 /// let mut options_reject = options_default;
110 /// options_reject.overflow = Some(Overflow::Reject);
111 /// assert!(d1.try_added_with_options(duration, options_reject).is_err());
112 ///
113 /// let mut options_constrain = options_default;
114 /// options_constrain.overflow = Some(Overflow::Constrain);
115 /// assert_eq!(
116 /// d1.try_added_with_options(duration, options_constrain)
117 /// .unwrap(),
118 /// Date::try_new_iso(2025, 11, 30).unwrap()
119 /// );
120 /// ```
121 pub overflow: Option<Overflow>,
122 }
123
124 /// Options for taking the difference between two dates.
125 #[derive(Copy, Clone, PartialEq, Debug, Default)]
126 #[non_exhaustive]
127 pub struct DateDifferenceOptions {
128 /// Which date field to allow as the largest in a duration when taking the difference.
129 ///
130 /// This defaults to [`DateDurationUnit::Days`].
131 ///
132 /// When choosing [`Months`] or [`Years`], the resulting [`DateDuration`] might not be
133 /// associative or commutative in subsequent arithmetic operations, and it might require
134 /// [`Overflow::Constrain`] in addition.
135 ///
136 /// The resultant duration will not have any `weeks` value unless [`DateDurationUnit::Weeks`]
137 /// is explicitly specified as `largest_unit`.
138 ///
139 /// # Examples
140 ///
141 /// ```
142 /// use icu::calendar::Date;
143 /// use icu::calendar::options::DateDifferenceOptions;
144 /// use icu::calendar::options::DateDurationUnit;
145 /// use icu::calendar::types::DateDuration;
146 ///
147 /// let d1 = Date::try_new_iso(2025, 3, 31).unwrap();
148 /// let d2 = Date::try_new_iso(2026, 5, 15).unwrap();
149 ///
150 /// let options_default = DateDifferenceOptions::default();
151 /// assert_eq!(
152 /// d1.try_until_with_options(&d2, options_default).unwrap(),
153 /// DateDuration::for_days(410)
154 /// );
155 ///
156 /// let mut options_days = options_default;
157 /// options_days.largest_unit = Some(DateDurationUnit::Days);
158 /// assert_eq!(
159 /// d1.try_until_with_options(&d2, options_days).unwrap(),
160 /// DateDuration::for_days(410)
161 /// );
162 ///
163 /// let mut options_weeks = options_default;
164 /// options_weeks.largest_unit = Some(DateDurationUnit::Weeks);
165 /// assert_eq!(
166 /// d1.try_until_with_options(&d2, options_weeks).unwrap(),
167 /// DateDuration {
168 /// // This is the only time there is a `weeks` value.
169 /// weeks: 58,
170 /// days: 4,
171 /// ..Default::default()
172 /// }
173 /// );
174 ///
175 /// let mut options_months = options_default;
176 /// options_months.largest_unit = Some(DateDurationUnit::Months);
177 /// assert_eq!(
178 /// d1.try_until_with_options(&d2, options_months).unwrap(),
179 /// DateDuration {
180 /// months: 13,
181 /// days: 15,
182 /// ..Default::default()
183 /// }
184 /// );
185 ///
186 /// let mut options_years = options_default;
187 /// options_years.largest_unit = Some(DateDurationUnit::Years);
188 /// assert_eq!(
189 /// d1.try_until_with_options(&d2, options_years).unwrap(),
190 /// DateDuration {
191 /// years: 1,
192 /// months: 1,
193 /// days: 15,
194 /// ..Default::default()
195 /// }
196 /// );
197 /// ```
198 ///
199 /// [`Months`]: crate::options::DateDurationUnit::Months
200 /// [`Years`]: crate::options::DateDurationUnit::Years
201 /// [`DateDuration`]: crate::types::DateDuration
202 pub largest_unit: Option<DateDurationUnit>,
203 }
204
205 /// Whether to constrain or reject out-of-bounds values when constructing a Date.
206 ///
207 /// The behavior conforms to the ECMAScript Temporal specification.
208 #[derive(Copy, Clone, Debug, PartialEq, Default)]
209 #[non_exhaustive]
210 pub enum Overflow {
211 /// Constrain out-of-bounds fields to the nearest in-bounds value.
212 ///
213 /// Only the out-of-bounds field is constrained. If the other fields are not themselves
214 /// out of bounds, they are not changed.
215 ///
216 /// This is the [default option](
217 /// https://tc39.es/proposal-temporal/#sec-temporal-gettemporaloverflowoption),
218 /// following the ECMAScript Temporal specification. See also the [docs on MDN](
219 /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDate#invalid_date_clamping).
220 ///
221 /// # Examples
222 ///
223 /// ```
224 /// use icu::calendar::Date;
225 /// use icu::calendar::DateError;
226 /// use icu::calendar::cal::Hebrew;
227 /// use icu::calendar::options::DateFromFieldsOptions;
228 /// use icu::calendar::options::Overflow;
229 /// use icu::calendar::types::{DateFields, Month};
230 ///
231 /// let mut options = DateFromFieldsOptions::default();
232 /// options.overflow = Some(Overflow::Constrain);
233 ///
234 /// // 5784, a leap year, contains M05L, but the day is too big.
235 /// let mut fields = DateFields::default();
236 /// fields.extended_year = Some(5784);
237 /// fields.month = Some(Month::leap(5));
238 /// fields.day = Some(50);
239 ///
240 /// let date = Date::try_from_fields(fields, options, Hebrew).unwrap();
241 ///
242 /// // Constrained to the 30th day of M05L of year 5784
243 /// assert_eq!(date.year().extended_year(), 5784);
244 /// assert_eq!(date.month().to_input().code().0, "M05L");
245 /// assert_eq!(date.day_of_month().0, 30);
246 ///
247 /// // 5785, a common year, does not contain M05L.
248 /// fields.extended_year = Some(5785);
249 ///
250 /// let date = Date::try_from_fields(fields, options, Hebrew).unwrap();
251 ///
252 /// // Constrained to the 29th day of M06 of year 5785
253 /// assert_eq!(date.year().extended_year(), 5785);
254 /// assert_eq!(date.month().to_input().code().0, "M06");
255 /// assert_eq!(date.day_of_month().0, 29);
256 /// ```
257 Constrain,
258 /// Return an error if any fields are out of bounds.
259 ///
260 /// # Examples
261 ///
262 /// ```
263 /// use icu::calendar::Date;
264 /// use icu::calendar::cal::Hebrew;
265 /// use icu::calendar::error::DateFromFieldsError;
266 /// use icu::calendar::options::DateFromFieldsOptions;
267 /// use icu::calendar::options::Overflow;
268 /// use icu::calendar::types::{DateFields, Month};
269 /// use tinystr::tinystr;
270 ///
271 /// let mut options = DateFromFieldsOptions::default();
272 /// options.overflow = Some(Overflow::Reject);
273 ///
274 /// // 5784, a leap year, contains M05L, but the day is too big.
275 /// let mut fields = DateFields::default();
276 /// fields.extended_year = Some(5784);
277 /// fields.month = Some(Month::leap(5));
278 /// fields.day = Some(50);
279 ///
280 /// let err = Date::try_from_fields(fields, options, Hebrew)
281 /// .expect_err("Day is out of bounds");
282 /// assert!(matches!(err, DateFromFieldsError::InvalidDay { .. }));
283 ///
284 /// // Set the day to one that exists
285 /// fields.day = Some(1);
286 /// Date::try_from_fields(fields, options, Hebrew)
287 /// .expect("A valid Hebrew date");
288 ///
289 /// // 5785, a common year, does not contain M05L.
290 /// fields.extended_year = Some(5785);
291 ///
292 /// let err = Date::try_from_fields(fields, options, Hebrew)
293 /// .expect_err("Month is out of bounds");
294 /// assert!(matches!(err, DateFromFieldsError::MonthNotInYear));
295 /// ```
296 #[default]
297 Reject,
298 }
299
300 /// How to infer missing fields when the fields that are present do not fully constitute a Date.
301 ///
302 /// In order for the fields to fully constitute a Date, they must identify a year, a month,
303 /// and a day. The fields `era`, `era_year`, and `extended_year` identify the year:
304 ///
305 /// | Era? | Era Year? | Extended Year? | Outcome |
306 /// |------|-----------|----------------|---------|
307 /// | - | - | - | Error |
308 /// | Some | - | - | Error |
309 /// | - | Some | - | Error |
310 /// | - | - | Some | OK |
311 /// | Some | Some | - | OK |
312 /// | Some | - | Some | Error (era requires era year) |
313 /// | - | Some | Some | Error (era year requires era) |
314 /// | Some | Some | Some | OK (but error if inconsistent) |
315 ///
316 /// The fields `month_code` and `ordinal_month` identify the month:
317 ///
318 /// | Month( Code)? | Ordinal Month? | Outcome |
319 /// |-------------|----------------|---------|
320 /// | - | - | Error |
321 /// | Some | - | OK |
322 /// | - | Some | OK |
323 /// | Some | Some | OK (but error if inconsistent) |
324 ///
325 /// The field `day` identifies the day.
326 ///
327 /// If the fields identify a year, a month, and a day, then there are no missing fields, so
328 /// the strategy chosen here has no effect (fields that are out-of-bounds or inconsistent
329 /// are handled by other errors).
330 #[derive(Copy, Clone, Debug, PartialEq, Default)]
331 #[non_exhaustive]
332 pub enum MissingFieldsStrategy {
333 /// If the fields that are present do not fully constitute a Date,
334 /// return [`DateFromFieldsError::NotEnoughFields`].
335 ///
336 /// [`DateFromFieldsError::NotEnoughFields`]: crate::error::DateFromFieldsError::NotEnoughFields
337 #[default]
338 Reject,
339 /// If the fields that are present do not fully constitute a Date,
340 /// follow the ECMAScript specification when possible.
341 ///
342 /// ⚠️ This option causes a year or day to be implicitly added to the Date!
343 ///
344 /// This strategy makes the following changes:
345 ///
346 /// 1. If the fields identify a year and a month, but not a day, then set `day` to 1.
347 /// 2. If month and day are set but nothing else, then set the year to a
348 /// _reference year_: some year in the calendar that contains the specified month
349 /// and day, according to the ECMAScript specification.
350 ///
351 /// Note that the reference year is _not_ added if an ordinal month is present, since
352 /// the identity of an ordinal month changes from year to year.
353 Ecma,
354 }
355
356 /// A "duration unit" used to specify the minimum or maximum duration of time to
357 /// care about.
358 #[derive(Copy, Clone, Eq, PartialEq, Debug)]
359 #[allow(clippy::exhaustive_enums)] // this type should be stable
360 pub enum DateDurationUnit {
361 /// Duration in years
362 Years,
363 /// Duration in months
364 Months,
365 /// Duration in weeks
366 Weeks,
367 /// Duration in days
368 Days,
369 }
370
371 #[cfg(test)]
372 mod tests {
373 use crate::{
374 Date, Gregorian,
375 error::DateFromFieldsError,
376 types::{DateFields, Month},
377 };
378 use itertools::Itertools;
379 use std::collections::{BTreeMap, BTreeSet};
380
381 use super::*;
382
383 #[test]
384 #[allow(clippy::field_reassign_with_default)] // want out-of-crate code style
385 fn test_missing_fields_strategy() {
386 // The sets of fields that identify a year, according to the table in the docs
387 let valid_year_field_sets = [
388 &["era", "era_year"][..],
389 &["extended_year"][..],
390 &["era", "era_year", "extended_year"][..],
391 ]
392 .into_iter()
393 .map(|field_names| field_names.iter().copied().collect())
394 .collect::<Vec<BTreeSet<&str>>>();
395
396 // The sets of fields that identify a month, according to the table in the docs
397 let valid_month_field_sets = [
398 &["month_code"][..],
399 &["month"][..],
400 &["ordinal_month"][..],
401 &["month_code", "ordinal_month"][..],
402 &["month", "ordinal_month"][..],
403 ]
404 .into_iter()
405 .map(|field_names| field_names.iter().copied().collect())
406 .collect::<Vec<BTreeSet<&str>>>();
407
408 // The sets of fields that identify a day, according to the table in the docs
409 let valid_day_field_sets = [&["day"][..]]
410 .into_iter()
411 .map(|field_names| field_names.iter().copied().collect())
412 .collect::<Vec<BTreeSet<&str>>>();
413
414 // All possible valid sets of fields
415 let all_valid_field_sets = valid_year_field_sets
416 .iter()
417 .cartesian_product(valid_month_field_sets.iter())
418 .cartesian_product(valid_day_field_sets.iter())
419 .map(|((year_fields, month_fields), day_fields)| {
420 year_fields
421 .iter()
422 .chain(month_fields.iter())
423 .chain(day_fields.iter())
424 .copied()
425 .collect::<BTreeSet<&str>>()
426 })
427 .collect::<BTreeSet<BTreeSet<&str>>>();
428
429 // Field sets with year and month but without day that ECMA accepts
430 let field_sets_without_day = valid_year_field_sets
431 .iter()
432 .cartesian_product(valid_month_field_sets.iter())
433 .map(|(year_fields, month_fields)| {
434 year_fields
435 .iter()
436 .chain(month_fields.iter())
437 .copied()
438 .collect::<BTreeSet<&str>>()
439 })
440 .collect::<BTreeSet<BTreeSet<&str>>>();
441
442 // Field sets with month and day but without year that ECMA accepts
443 let field_sets_without_year = [&["month_code", "day"][..], &["month", "day"][..]]
444 .into_iter()
445 .map(|field_names| field_names.iter().copied().collect())
446 .collect::<Vec<BTreeSet<&str>>>();
447
448 // A map from field names to a function that sets that field
449 let mut field_fns = BTreeMap::<&str, &dyn Fn(&mut DateFields)>::new();
450 field_fns.insert("era", &|fields| fields.era = Some(b"ad"));
451 field_fns.insert("era_year", &|fields| fields.era_year = Some(2000));
452 field_fns.insert("extended_year", &|fields| fields.extended_year = Some(2000));
453 field_fns.insert("month", &|fields| fields.month = Some(Month::new(4)));
454 field_fns.insert("month_code", &|fields| fields.month_code = Some(b"M04"));
455 field_fns.insert("ordinal_month", &|fields| fields.ordinal_month = Some(4));
456 field_fns.insert("day", &|fields| fields.day = Some(20));
457
458 for field_set in field_fns.keys().copied().powerset() {
459 let field_set = field_set.into_iter().collect::<BTreeSet<&str>>();
460
461 // Check whether this case should succeed: whether it identifies a year,
462 // a month, and a day.
463 let should_succeed_rejecting = all_valid_field_sets.contains(&field_set);
464
465 // Check whether it should succeed in ECMA mode.
466 let should_succeed_ecma = should_succeed_rejecting
467 || field_sets_without_day.contains(&field_set)
468 || field_sets_without_year.contains(&field_set);
469
470 // Populate the fields in the field set
471 let mut fields = Default::default();
472 for field_name in &field_set {
473 field_fns.get(field_name).unwrap()(&mut fields);
474 }
475
476 // Check whether we were able to successfully construct the date
477 let mut options = DateFromFieldsOptions::default();
478 options.missing_fields_strategy = Some(MissingFieldsStrategy::Reject);
479 match Date::try_from_fields(fields, options, Gregorian) {
480 Ok(_) => assert!(
481 should_succeed_rejecting,
482 "Succeeded, but should have rejected: {fields:?}"
483 ),
484 Err(DateFromFieldsError::NotEnoughFields | DateFromFieldsError::TooManyFields) => {
485 assert!(
486 !should_succeed_rejecting,
487 "Rejected, but should have succeeded: {fields:?}"
488 )
489 }
490 Err(e) => panic!("Unexpected error: {e} for {fields:?}"),
491 }
492
493 // Check ECMA mode
494 let mut options = DateFromFieldsOptions::default();
495 options.missing_fields_strategy = Some(MissingFieldsStrategy::Ecma);
496 match Date::try_from_fields(fields, options, Gregorian) {
497 Ok(_) => assert!(
498 should_succeed_ecma,
499 "Succeeded, but should have rejected (ECMA): {fields:?}"
500 ),
501 Err(DateFromFieldsError::NotEnoughFields | DateFromFieldsError::TooManyFields) => {
502 assert!(
503 !should_succeed_ecma,
504 "Rejected, but should have succeeded (ECMA): {fields:?}"
505 )
506 }
507 Err(e) => panic!("Unexpected error: {e} for {fields:?}"),
508 }
509 }
510 }
511
512 #[test]
513 fn test_constrain_large_months() {
514 let fields = DateFields {
515 extended_year: Some(2004),
516 ordinal_month: Some(15),
517 day: Some(1),
518 ..Default::default()
519 };
520 let options = DateFromFieldsOptions {
521 overflow: Some(Overflow::Constrain),
522 ..Default::default()
523 };
524
525 let _ = Date::try_from_fields(fields, options, crate::cal::Persian).unwrap();
526 }
527 }