icu_calendar 2.2.1

Date APIs for Gregorian and non-Gregorian calendars
Documentation
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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// 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 ).

//! Options used by types in this crate

/// Options bag for [`Date::try_from_fields`](crate::Date::try_from_fields).
#[derive(Copy, Clone, Debug, PartialEq, Default)]
#[non_exhaustive]
pub struct DateFromFieldsOptions {
    /// How to behave with out-of-bounds fields.
    ///
    /// Defaults to [`Overflow::Reject`].
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::calendar::options::DateFromFieldsOptions;
    /// use icu::calendar::options::Overflow;
    /// use icu::calendar::types::DateFields;
    /// use icu::calendar::Date;
    /// use icu::calendar::Iso;
    ///
    /// // There is no day 31 in September.
    /// let mut fields = DateFields::default();
    /// fields.extended_year = Some(2025);
    /// fields.ordinal_month = Some(9);
    /// fields.day = Some(31);
    ///
    /// let options_default = DateFromFieldsOptions::default();
    /// assert!(Date::try_from_fields(fields, options_default, Iso).is_err());
    ///
    /// let mut options_reject = options_default;
    /// options_reject.overflow = Some(Overflow::Reject);
    /// assert!(Date::try_from_fields(fields, options_reject, Iso).is_err());
    ///
    /// let mut options_constrain = options_default;
    /// options_constrain.overflow = Some(Overflow::Constrain);
    /// assert_eq!(
    ///     Date::try_from_fields(fields, options_constrain, Iso).unwrap(),
    ///     Date::try_new_iso(2025, 9, 30).unwrap()
    /// );
    /// ```
    pub overflow: Option<Overflow>,
    /// How to behave when the fields that are present do not fully constitute a Date.
    ///
    /// This option can be used to fill in a missing year given a month and a day according to
    /// the ECMAScript Temporal specification.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::calendar::options::DateFromFieldsOptions;
    /// use icu::calendar::options::MissingFieldsStrategy;
    /// use icu::calendar::types::{DateFields, Month};
    /// use icu::calendar::Date;
    /// use icu::calendar::Iso;
    ///
    /// // These options are missing a year.
    /// let mut fields = DateFields::default();
    /// fields.month = Some(Month::new(2));
    /// fields.day = Some(1);
    ///
    /// let options_default = DateFromFieldsOptions::default();
    /// assert!(Date::try_from_fields(fields, options_default, Iso).is_err());
    ///
    /// let mut options_reject = options_default;
    /// options_reject.missing_fields_strategy =
    ///     Some(MissingFieldsStrategy::Reject);
    /// assert!(Date::try_from_fields(fields, options_reject, Iso).is_err());
    ///
    /// let mut options_ecma = options_default;
    /// options_ecma.missing_fields_strategy = Some(MissingFieldsStrategy::Ecma);
    /// assert_eq!(
    ///     Date::try_from_fields(fields, options_ecma, Iso).unwrap(),
    ///     Date::try_new_iso(1972, 2, 1).unwrap()
    /// );
    /// ```
    pub missing_fields_strategy: Option<MissingFieldsStrategy>,
}

/// Options for adding a duration to a date.
#[derive(Copy, Clone, PartialEq, Debug, Default)]
#[non_exhaustive]
pub struct DateAddOptions {
    /// How to behave with out-of-bounds fields during arithmetic.
    ///
    /// Defaults to [`Overflow::Constrain`].
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::calendar::options::DateAddOptions;
    /// use icu::calendar::options::Overflow;
    /// use icu::calendar::types::DateDuration;
    /// use icu::calendar::Date;
    ///
    /// // There is a day 31 in October but not in November.
    /// let d1 = Date::try_new_iso(2025, 10, 31).unwrap();
    /// let duration = DateDuration::for_months(1);
    ///
    /// let options_default = DateAddOptions::default();
    /// assert_eq!(
    ///     d1.try_added_with_options(duration, options_default)
    ///         .unwrap(),
    ///     Date::try_new_iso(2025, 11, 30).unwrap()
    /// );
    ///
    /// let mut options_reject = options_default;
    /// options_reject.overflow = Some(Overflow::Reject);
    /// assert!(d1.try_added_with_options(duration, options_reject).is_err());
    ///
    /// let mut options_constrain = options_default;
    /// options_constrain.overflow = Some(Overflow::Constrain);
    /// assert_eq!(
    ///     d1.try_added_with_options(duration, options_constrain)
    ///         .unwrap(),
    ///     Date::try_new_iso(2025, 11, 30).unwrap()
    /// );
    /// ```
    pub overflow: Option<Overflow>,
}

/// Options for taking the difference between two dates.
#[derive(Copy, Clone, PartialEq, Debug, Default)]
#[non_exhaustive]
pub struct DateDifferenceOptions {
    /// Which date field to allow as the largest in a duration when taking the difference.
    ///
    /// This defaults to [`DateDurationUnit::Days`].
    ///
    /// When choosing [`Months`] or [`Years`], the resulting [`DateDuration`] might not be
    /// associative or commutative in subsequent arithmetic operations, and it might require
    /// [`Overflow::Constrain`] in addition.
    ///
    /// The resultant duration will not have any `weeks` value unless [`DateDurationUnit::Weeks`]
    /// is explicitly specified as `largest_unit`.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::calendar::options::DateDifferenceOptions;
    /// use icu::calendar::options::DateDurationUnit;
    /// use icu::calendar::types::DateDuration;
    /// use icu::calendar::Date;
    ///
    /// let d1 = Date::try_new_iso(2025, 3, 31).unwrap();
    /// let d2 = Date::try_new_iso(2026, 5, 15).unwrap();
    ///
    /// let options_default = DateDifferenceOptions::default();
    /// assert_eq!(
    ///     d1.try_until_with_options(&d2, options_default).unwrap(),
    ///     DateDuration::for_days(410)
    /// );
    ///
    /// let mut options_days = options_default;
    /// options_days.largest_unit = Some(DateDurationUnit::Days);
    /// assert_eq!(
    ///     d1.try_until_with_options(&d2, options_days).unwrap(),
    ///     DateDuration::for_days(410)
    /// );
    ///
    /// let mut options_weeks = options_default;
    /// options_weeks.largest_unit = Some(DateDurationUnit::Weeks);
    /// assert_eq!(
    ///     d1.try_until_with_options(&d2, options_weeks).unwrap(),
    ///     DateDuration {
    ///         // This is the only time there is a `weeks` value.
    ///         weeks: 58,
    ///         days: 4,
    ///         ..Default::default()
    ///     }
    /// );
    ///
    /// let mut options_months = options_default;
    /// options_months.largest_unit = Some(DateDurationUnit::Months);
    /// assert_eq!(
    ///     d1.try_until_with_options(&d2, options_months).unwrap(),
    ///     DateDuration {
    ///         months: 13,
    ///         days: 15,
    ///         ..Default::default()
    ///     }
    /// );
    ///
    /// let mut options_years = options_default;
    /// options_years.largest_unit = Some(DateDurationUnit::Years);
    /// assert_eq!(
    ///     d1.try_until_with_options(&d2, options_years).unwrap(),
    ///     DateDuration {
    ///         years: 1,
    ///         months: 1,
    ///         days: 15,
    ///         ..Default::default()
    ///     }
    /// );
    /// ```
    ///
    /// [`Months`]: crate::options::DateDurationUnit::Months
    /// [`Years`]: crate::options::DateDurationUnit::Years
    /// [`DateDuration`]: crate::types::DateDuration
    pub largest_unit: Option<DateDurationUnit>,
}

/// Whether to constrain or reject out-of-bounds values when constructing a Date.
///
/// The behavior conforms to the ECMAScript Temporal specification.
#[derive(Copy, Clone, Debug, PartialEq, Default)]
#[non_exhaustive]
pub enum Overflow {
    /// Constrain out-of-bounds fields to the nearest in-bounds value.
    ///
    /// Only the out-of-bounds field is constrained. If the other fields are not themselves
    /// out of bounds, they are not changed.
    ///
    /// This is the [default option](
    /// https://tc39.es/proposal-temporal/#sec-temporal-gettemporaloverflowoption),
    /// following the ECMAScript Temporal specification. See also the [docs on MDN](
    /// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Temporal/PlainDate#invalid_date_clamping).
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::calendar::cal::Hebrew;
    /// use icu::calendar::options::DateFromFieldsOptions;
    /// use icu::calendar::options::Overflow;
    /// use icu::calendar::types::{DateFields, Month};
    /// use icu::calendar::Date;
    /// use icu::calendar::DateError;
    ///
    /// let mut options = DateFromFieldsOptions::default();
    /// options.overflow = Some(Overflow::Constrain);
    ///
    /// // 5784, a leap year, contains M05L, but the day is too big.
    /// let mut fields = DateFields::default();
    /// fields.extended_year = Some(5784);
    /// fields.month = Some(Month::leap(5));
    /// fields.day = Some(50);
    ///
    /// let date = Date::try_from_fields(fields, options, Hebrew).unwrap();
    ///
    /// // Constrained to the 30th day of M05L of year 5784
    /// assert_eq!(date.year().extended_year(), 5784);
    /// assert_eq!(date.month().to_input().code().0, "M05L");
    /// assert_eq!(date.day_of_month().0, 30);
    ///
    /// // 5785, a common year, does not contain M05L.
    /// fields.extended_year = Some(5785);
    ///
    /// let date = Date::try_from_fields(fields, options, Hebrew).unwrap();
    ///
    /// // Constrained to the 29th day of M06 of year 5785
    /// assert_eq!(date.year().extended_year(), 5785);
    /// assert_eq!(date.month().to_input().code().0, "M06");
    /// assert_eq!(date.day_of_month().0, 29);
    /// ```
    Constrain,
    /// Return an error if any fields are out of bounds.
    ///
    /// # Examples
    ///
    /// ```
    /// use icu::calendar::cal::Hebrew;
    /// use icu::calendar::error::DateFromFieldsError;
    /// use icu::calendar::options::DateFromFieldsOptions;
    /// use icu::calendar::options::Overflow;
    /// use icu::calendar::types::{DateFields, Month};
    /// use icu::calendar::Date;
    /// use tinystr::tinystr;
    ///
    /// let mut options = DateFromFieldsOptions::default();
    /// options.overflow = Some(Overflow::Reject);
    ///
    /// // 5784, a leap year, contains M05L, but the day is too big.
    /// let mut fields = DateFields::default();
    /// fields.extended_year = Some(5784);
    /// fields.month = Some(Month::leap(5));
    /// fields.day = Some(50);
    ///
    /// let err = Date::try_from_fields(fields, options, Hebrew)
    ///     .expect_err("Day is out of bounds");
    /// assert!(matches!(err, DateFromFieldsError::InvalidDay { .. }));
    ///
    /// // Set the day to one that exists
    /// fields.day = Some(1);
    /// Date::try_from_fields(fields, options, Hebrew)
    ///     .expect("A valid Hebrew date");
    ///
    /// // 5785, a common year, does not contain M05L.
    /// fields.extended_year = Some(5785);
    ///
    /// let err = Date::try_from_fields(fields, options, Hebrew)
    ///     .expect_err("Month is out of bounds");
    /// assert!(matches!(err, DateFromFieldsError::MonthNotInYear));
    /// ```
    #[default]
    Reject,
}

/// How to infer missing fields when the fields that are present do not fully constitute a Date.
///
/// In order for the fields to fully constitute a Date, they must identify a year, a month,
/// and a day. The fields `era`, `era_year`, and `extended_year` identify the year:
///
/// | Era? | Era Year? | Extended Year? | Outcome |
/// |------|-----------|----------------|---------|
/// | -    | -         | -              | Error |
/// | Some | -         | -              | Error |
/// | -    | Some      | -              | Error |
/// | -    | -         | Some           | OK |
/// | Some | Some      | -              | OK |
/// | Some | -         | Some           | Error (era requires era year) |
/// | -    | Some      | Some           | Error (era year requires era) |
/// | Some | Some      | Some           | OK (but error if inconsistent) |
///
/// The fields `month_code` and `ordinal_month` identify the month:
///
/// | Month( Code)? | Ordinal Month? | Outcome |
/// |-------------|----------------|---------|
/// | -           | -              | Error |
/// | Some        | -              | OK |
/// | -           | Some           | OK |
/// | Some        | Some           | OK (but error if inconsistent) |
///
/// The field `day` identifies the day.
///
/// If the fields identify a year, a month, and a day, then there are no missing fields, so
/// the strategy chosen here has no effect (fields that are out-of-bounds or inconsistent
/// are handled by other errors).
#[derive(Copy, Clone, Debug, PartialEq, Default)]
#[non_exhaustive]
pub enum MissingFieldsStrategy {
    /// If the fields that are present do not fully constitute a Date,
    /// return [`DateFromFieldsError::NotEnoughFields`].
    ///
    /// [`DateFromFieldsError::NotEnoughFields`]: crate::error::DateFromFieldsError::NotEnoughFields
    #[default]
    Reject,
    /// If the fields that are present do not fully constitute a Date,
    /// follow the ECMAScript specification when possible.
    ///
    /// ⚠️ This option causes a year or day to be implicitly added to the Date!
    ///
    /// This strategy makes the following changes:
    ///
    /// 1. If the fields identify a year and a month, but not a day, then set `day` to 1.
    /// 2. If month and day are set but nothing else, then set the year to a
    ///    _reference year_: some year in the calendar that contains the specified month
    ///    and day, according to the ECMAScript specification.
    ///
    /// Note that the reference year is _not_ added if an ordinal month is present, since
    /// the identity of an ordinal month changes from year to year.
    Ecma,
}

/// A "duration unit" used to specify the minimum or maximum duration of time to
/// care about.
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
#[allow(clippy::exhaustive_enums)] // this type should be stable
pub enum DateDurationUnit {
    /// Duration in years
    Years,
    /// Duration in months
    Months,
    /// Duration in weeks
    Weeks,
    /// Duration in days
    Days,
}

#[cfg(test)]
mod tests {
    use crate::{
        error::DateFromFieldsError,
        types::{DateFields, Month},
        Date, Gregorian,
    };
    use itertools::Itertools;
    use std::collections::{BTreeMap, BTreeSet};

    use super::*;

    #[test]
    #[allow(clippy::field_reassign_with_default)] // want out-of-crate code style
    fn test_missing_fields_strategy() {
        // The sets of fields that identify a year, according to the table in the docs
        let valid_year_field_sets = [
            &["era", "era_year"][..],
            &["extended_year"][..],
            &["era", "era_year", "extended_year"][..],
        ]
        .into_iter()
        .map(|field_names| field_names.iter().copied().collect())
        .collect::<Vec<BTreeSet<&str>>>();

        // The sets of fields that identify a month, according to the table in the docs
        let valid_month_field_sets = [
            &["month_code"][..],
            &["month"][..],
            &["ordinal_month"][..],
            &["month_code", "ordinal_month"][..],
            &["month", "ordinal_month"][..],
        ]
        .into_iter()
        .map(|field_names| field_names.iter().copied().collect())
        .collect::<Vec<BTreeSet<&str>>>();

        // The sets of fields that identify a day, according to the table in the docs
        let valid_day_field_sets = [&["day"][..]]
            .into_iter()
            .map(|field_names| field_names.iter().copied().collect())
            .collect::<Vec<BTreeSet<&str>>>();

        // All possible valid sets of fields
        let all_valid_field_sets = valid_year_field_sets
            .iter()
            .cartesian_product(valid_month_field_sets.iter())
            .cartesian_product(valid_day_field_sets.iter())
            .map(|((year_fields, month_fields), day_fields)| {
                year_fields
                    .iter()
                    .chain(month_fields.iter())
                    .chain(day_fields.iter())
                    .copied()
                    .collect::<BTreeSet<&str>>()
            })
            .collect::<BTreeSet<BTreeSet<&str>>>();

        // Field sets with year and month but without day that ECMA accepts
        let field_sets_without_day = valid_year_field_sets
            .iter()
            .cartesian_product(valid_month_field_sets.iter())
            .map(|(year_fields, month_fields)| {
                year_fields
                    .iter()
                    .chain(month_fields.iter())
                    .copied()
                    .collect::<BTreeSet<&str>>()
            })
            .collect::<BTreeSet<BTreeSet<&str>>>();

        // Field sets with month and day but without year that ECMA accepts
        let field_sets_without_year = [&["month_code", "day"][..], &["month", "day"][..]]
            .into_iter()
            .map(|field_names| field_names.iter().copied().collect())
            .collect::<Vec<BTreeSet<&str>>>();

        // A map from field names to a function that sets that field
        let mut field_fns = BTreeMap::<&str, &dyn Fn(&mut DateFields)>::new();
        field_fns.insert("era", &|fields| fields.era = Some(b"ad"));
        field_fns.insert("era_year", &|fields| fields.era_year = Some(2000));
        field_fns.insert("extended_year", &|fields| fields.extended_year = Some(2000));
        field_fns.insert("month", &|fields| fields.month = Some(Month::new(4)));
        field_fns.insert("month_code", &|fields| fields.month_code = Some(b"M04"));
        field_fns.insert("ordinal_month", &|fields| fields.ordinal_month = Some(4));
        field_fns.insert("day", &|fields| fields.day = Some(20));

        for field_set in field_fns.keys().copied().powerset() {
            let field_set = field_set.into_iter().collect::<BTreeSet<&str>>();

            // Check whether this case should succeed: whether it identifies a year,
            // a month, and a day.
            let should_succeed_rejecting = all_valid_field_sets.contains(&field_set);

            // Check whether it should succeed in ECMA mode.
            let should_succeed_ecma = should_succeed_rejecting
                || field_sets_without_day.contains(&field_set)
                || field_sets_without_year.contains(&field_set);

            // Populate the fields in the field set
            let mut fields = Default::default();
            for field_name in &field_set {
                field_fns.get(field_name).unwrap()(&mut fields);
            }

            // Check whether we were able to successfully construct the date
            let mut options = DateFromFieldsOptions::default();
            options.missing_fields_strategy = Some(MissingFieldsStrategy::Reject);
            match Date::try_from_fields(fields, options, Gregorian) {
                Ok(_) => assert!(
                    should_succeed_rejecting,
                    "Succeeded, but should have rejected: {fields:?}"
                ),
                Err(DateFromFieldsError::NotEnoughFields | DateFromFieldsError::TooManyFields) => {
                    assert!(
                        !should_succeed_rejecting,
                        "Rejected, but should have succeeded: {fields:?}"
                    )
                }
                Err(e) => panic!("Unexpected error: {e} for {fields:?}"),
            }

            // Check ECMA mode
            let mut options = DateFromFieldsOptions::default();
            options.missing_fields_strategy = Some(MissingFieldsStrategy::Ecma);
            match Date::try_from_fields(fields, options, Gregorian) {
                Ok(_) => assert!(
                    should_succeed_ecma,
                    "Succeeded, but should have rejected (ECMA): {fields:?}"
                ),
                Err(DateFromFieldsError::NotEnoughFields | DateFromFieldsError::TooManyFields) => {
                    assert!(
                        !should_succeed_ecma,
                        "Rejected, but should have succeeded (ECMA): {fields:?}"
                    )
                }
                Err(e) => panic!("Unexpected error: {e} for {fields:?}"),
            }
        }
    }

    #[test]
    fn test_constrain_large_months() {
        let fields = DateFields {
            extended_year: Some(2004),
            ordinal_month: Some(15),
            day: Some(1),
            ..Default::default()
        };
        let options = DateFromFieldsOptions {
            overflow: Some(Overflow::Constrain),
            ..Default::default()
        };

        let _ = Date::try_from_fields(fields, options, crate::cal::Persian).unwrap();
    }
}