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
// 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 crate::error::DateDurationParseError;

/// A signed length of time in terms of days, weeks, months, and years.
///
/// This type represents the abstract concept of a date duration. For example, a duration of
/// "1 month" is represented as "1 month" in the data model, without any context of how many
/// days the month might be.
///
/// [`DateDuration`] is the input and output type of date arithmetic operations in `icu_calendar`,
/// such as [`Date::try_add_with_options()`] and [`Date::try_until_with_options()`].
/// It is not designed to be used more generally as a duration, such as for parsing,
/// formatting, or storage.
///
/// [`Date::try_add_with_options()`]: crate::Date::try_add_with_options
/// [`Date::try_until_with_options()`]: crate::Date::try_until_with_options
/// [`Date`]: crate::Date
///
/// # Example
///
/// ```rust
/// use icu::calendar::options::DateDifferenceOptions;
/// use icu::calendar::options::DateDurationUnit;
/// use icu::calendar::types::DateDuration;
/// use icu::calendar::types::Weekday;
/// use icu::calendar::Date;
///
/// // Creating ISO date: 1992-09-02.
/// let mut date_iso = Date::try_new_iso(1992, 9, 2)
///     .expect("Failed to initialize ISO Date instance.");
///
/// assert_eq!(date_iso.weekday(), Weekday::Wednesday);
/// assert_eq!(date_iso.era_year().year, 1992);
/// assert_eq!(date_iso.month().ordinal, 9);
/// assert_eq!(date_iso.day_of_month().0, 2);
///
/// // Answering questions about days in month and year.
/// assert_eq!(date_iso.days_in_year(), 366);
/// assert_eq!(date_iso.days_in_month(), 30);
///
/// // Advancing date in-place by 1 year, 2 months, 3 weeks, 4 days.
/// date_iso
///     .try_add_with_options(
///         DateDuration {
///             is_negative: false,
///             years: 1,
///             months: 2,
///             weeks: 3,
///             days: 4,
///         },
///         Default::default(),
///     )
///     .unwrap();
/// assert_eq!(date_iso.era_year().year, 1993);
/// assert_eq!(date_iso.month().ordinal, 11);
/// assert_eq!(date_iso.day_of_month().0, 27);
///
/// // Reverse date advancement.
/// date_iso
///     .try_add_with_options(
///         DateDuration {
///             is_negative: true,
///             years: 1,
///             months: 2,
///             weeks: 3,
///             days: 4,
///         },
///         Default::default(),
///     )
///     .unwrap();
/// assert_eq!(date_iso.era_year().year, 1992);
/// assert_eq!(date_iso.month().ordinal, 9);
/// assert_eq!(date_iso.day_of_month().0, 2);
///
/// // Creating ISO date: 2022-01-30.
/// let newer_date_iso = Date::try_new_iso(2022, 10, 30)
///     .expect("Failed to initialize ISO Date instance.");
///
/// // Comparing dates: 2022-01-30 and 1992-09-02.
/// let mut options = DateDifferenceOptions::default();
/// options.largest_unit = Some(DateDurationUnit::Years);
/// let Ok(duration) =
///     newer_date_iso.try_until_with_options(&date_iso, options);
/// assert_eq!(duration.years, 30);
/// assert_eq!(duration.months, 1);
/// assert_eq!(duration.days, 28);
///
/// // Create new date with date advancement. Reassign to new variable.
/// let mutated_date_iso = date_iso
///     .try_added_with_options(
///         DateDuration {
///             is_negative: false,
///             years: 1,
///             months: 2,
///             weeks: 3,
///             days: 4,
///         },
///         Default::default(),
///     )
///     .unwrap();
/// assert_eq!(mutated_date_iso.era_year().year, 1993);
/// assert_eq!(mutated_date_iso.month().ordinal, 11);
/// assert_eq!(mutated_date_iso.day_of_month().0, 27);
/// ```
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)]
#[allow(clippy::exhaustive_structs)] // spec-defined in Temporal
pub struct DateDuration {
    /// Whether the duration is negative.
    ///
    /// A negative duration is an abstract concept that could result, for example, from
    /// taking the difference between two [`Date`](crate::Date)s in ascending order.
    ///
    /// The fields of the duration are either all positive or all negative. Mixed signs
    /// are not possible.
    ///
    /// By convention, this field should be `false` if the duration is zero.
    pub is_negative: bool,
    /// The number of years
    pub years: u32,
    /// The number of months
    pub months: u32,
    /// The number of weeks
    pub weeks: u32,
    /// The number of days
    pub days: u32,
}

impl DateDuration {
    /// Parses an ISO 8601 date-only duration string into a [`DateDuration`].
    ///
    /// This is a wrapper around [`Self::try_from_utf8`] for UTF-8
    /// string inputs.
    pub fn try_from_str(s: &str) -> Result<Self, DateDurationParseError> {
        Self::try_from_utf8(s.as_bytes())
    }

    /// See [`Self::try_from_str`].
    pub fn try_from_utf8(code_units: &[u8]) -> Result<Self, DateDurationParseError> {
        let mut s = code_units;

        let mut is_negative = false;
        match s {
            [b'-', rest @ ..] => {
                is_negative = true;
                s = rest;
            }
            [b'+', ..] => return Err(DateDurationParseError::PlusNotAllowed),
            _ => {}
        }

        match s {
            [b'P', rest @ ..] => s = rest,
            _ => return Err(DateDurationParseError::InvalidStructure),
        }

        if s.is_empty() {
            return Err(DateDurationParseError::InvalidStructure);
        }

        let mut years: u32 = 0;
        let mut months: u32 = 0;
        let mut weeks: u32 = 0;
        let mut days: u32 = 0;

        let mut seen_years = false;
        let mut seen_months = false;
        let mut seen_weeks = false;
        let mut seen_days = false;

        while !s.is_empty() {
            if matches!(s, [b'T', ..]) {
                return Err(DateDurationParseError::TimeNotSupported);
            }

            let mut value: u64 = 0;
            let mut has_digits = false;

            while let [b @ b'0'..=b'9', rest @ ..] = s {
                value = value
                    .checked_mul(10)
                    .and_then(|v| v.checked_add((b - b'0') as u64))
                    .ok_or(DateDurationParseError::NumberOverflow)?;
                s = rest;
                has_digits = true;
            }

            if !has_digits {
                return Err(DateDurationParseError::MissingValue);
            }

            match s {
                [b'Y', rest @ ..] => {
                    if seen_years {
                        return Err(DateDurationParseError::DuplicateUnit);
                    }
                    years =
                        u32::try_from(value).map_err(|_| DateDurationParseError::NumberOverflow)?;
                    seen_years = true;
                    s = rest;
                }
                [b'M', rest @ ..] => {
                    if seen_months {
                        return Err(DateDurationParseError::DuplicateUnit);
                    }
                    months =
                        u32::try_from(value).map_err(|_| DateDurationParseError::NumberOverflow)?;
                    seen_months = true;
                    s = rest;
                }
                [b'W', rest @ ..] => {
                    if seen_weeks {
                        return Err(DateDurationParseError::DuplicateUnit);
                    }
                    weeks =
                        u32::try_from(value).map_err(|_| DateDurationParseError::NumberOverflow)?;
                    seen_weeks = true;
                    s = rest;
                }
                [b'D', rest @ ..] => {
                    if seen_days {
                        return Err(DateDurationParseError::DuplicateUnit);
                    }
                    days =
                        u32::try_from(value).map_err(|_| DateDurationParseError::NumberOverflow)?;
                    seen_days = true;
                    s = rest;
                }
                _ => return Err(DateDurationParseError::InvalidStructure),
            }
        }

        Ok(Self {
            is_negative,
            years,
            months,
            weeks,
            days,
        })
    }

    /// Returns a new [`DateDuration`] representing a number of years.
    pub fn for_years(years: i32) -> Self {
        Self {
            is_negative: years.is_negative(),
            years: years.unsigned_abs(),
            ..Default::default()
        }
    }

    /// Returns a new [`DateDuration`] representing a number of months.
    pub fn for_months(months: i32) -> Self {
        Self {
            is_negative: months.is_negative(),
            months: months.unsigned_abs(),
            ..Default::default()
        }
    }

    /// Returns a new [`DateDuration`] representing a number of weeks.
    pub fn for_weeks(weeks: i32) -> Self {
        Self {
            is_negative: weeks.is_negative(),
            weeks: weeks.unsigned_abs(),
            ..Default::default()
        }
    }

    /// Returns a new [`DateDuration`] representing a number of days.
    pub fn for_days(days: i32) -> Self {
        Self {
            is_negative: days.is_negative(),
            days: days.unsigned_abs(),
            ..Default::default()
        }
    }

    /// Returns a new [`DateDuration`] representing a number of days
    /// represented as weeks and days
    pub(crate) fn for_weeks_and_days(days: i32) -> Self {
        let weeks = days / 7;
        let days = days % 7;
        Self::from_signed_ymwd(0, 0, weeks, days)
    }

    /// Do NOT pass this function values of mixed signs!
    pub(crate) fn from_signed_ymwd(years: i32, months: i32, weeks: i32, days: i32) -> Self {
        let is_negative = years.is_negative()
            || months.is_negative()
            || weeks.is_negative()
            || days.is_negative();
        if is_negative
            && (years.is_positive()
                || months.is_positive()
                || weeks.is_positive()
                || days.is_positive())
        {
            debug_assert!(false, "mixed signs in from_signed_ymd");
        }
        Self {
            is_negative,
            years: years.unsigned_abs(),
            months: months.unsigned_abs(),
            weeks: weeks.unsigned_abs(),
            days: days.unsigned_abs(),
        }
    }

    #[inline]
    pub(crate) fn add_years_to(&self, year: i32) -> i32 {
        if !self.is_negative {
            match year.checked_add_unsigned(self.years) {
                Some(x) => x,
                None => {
                    debug_assert!(false, "{year} + {self:?} out of year range");
                    i32::MAX
                }
            }
        } else {
            match year.checked_sub_unsigned(self.years) {
                Some(x) => x,
                None => {
                    debug_assert!(false, "{year} - {self:?} out of year range");
                    i32::MIN
                }
            }
        }
    }

    #[inline]
    pub(crate) fn add_months_to(&self, month: u8) -> i32 {
        debug_assert!(i32::try_from(self.months).is_ok());
        if !self.is_negative {
            i32::from(month) + (self.months as i32)
        } else {
            i32::from(month) - (self.months as i32)
        }
    }

    #[inline]
    pub(crate) fn add_weeks_and_days_to(&self, day: u8) -> i32 {
        debug_assert!(i32::try_from(self.weeks).is_ok());
        if !self.is_negative {
            let day = i32::from(day) + (self.weeks as i32) * 7;
            match day.checked_add_unsigned(self.days) {
                Some(x) => x,
                None => {
                    debug_assert!(false, "{day} + {self:?} out of day range");
                    i32::MAX
                }
            }
        } else {
            let day = i32::from(day) - (self.weeks as i32) * 7;
            match day.checked_sub_unsigned(self.days) {
                Some(x) => x,
                None => {
                    debug_assert!(false, "{day} - {self:?} out of day range");
                    i32::MIN
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_single_unit_durations() {
        let d = DateDuration::try_from_str("P1D").unwrap();
        assert_eq!(
            d,
            DateDuration {
                days: 1,
                ..Default::default()
            }
        );

        let d = DateDuration::try_from_str("P3W").unwrap();
        assert_eq!(
            d,
            DateDuration {
                weeks: 3,
                ..Default::default()
            }
        );

        let d = DateDuration::try_from_str("P5M").unwrap();
        assert_eq!(
            d,
            DateDuration {
                months: 5,
                ..Default::default()
            }
        );

        let d = DateDuration::try_from_str("P7Y").unwrap();
        assert_eq!(
            d,
            DateDuration {
                years: 7,
                ..Default::default()
            }
        );
    }

    #[test]
    fn parse_multi_unit_durations() {
        let d = DateDuration::try_from_str("P1Y3M5W7D").unwrap();
        assert_eq!(
            d,
            DateDuration {
                years: 1,
                months: 3,
                weeks: 5,
                days: 7,
                ..Default::default()
            }
        );
    }

    #[test]
    fn parse_negative_durations() {
        let d = DateDuration::try_from_str("-P9W").unwrap();
        assert_eq!(
            d,
            DateDuration {
                is_negative: true,
                weeks: 9,
                ..Default::default()
            }
        );
    }
}