| 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::error::DateDurationParseError; |
| 6 |
|
| 7 |
/// A signed length of time in terms of days, weeks, months, and years. |
| 8 |
/// |
| 9 |
/// This type represents the abstract concept of a date duration. For example, a duration of |
| 10 |
/// "1 month" is represented as "1 month" in the data model, without any context of how many |
| 11 |
/// days the month might be. |
| 12 |
/// |
| 13 |
/// [`DateDuration`] is the input and output type of date arithmetic operations in `icu_calendar`, |
| 14 |
/// such as [`Date::try_add_with_options()`] and [`Date::try_until_with_options()`]. |
| 15 |
/// It is not designed to be used more generally as a duration, such as for parsing, |
| 16 |
/// formatting, or storage. |
| 17 |
/// |
| 18 |
/// [`Date::try_add_with_options()`]: crate::Date::try_add_with_options |
| 19 |
/// [`Date::try_until_with_options()`]: crate::Date::try_until_with_options |
| 20 |
/// [`Date`]: crate::Date |
| 21 |
/// |
| 22 |
/// # Example |
| 23 |
/// |
| 24 |
/// ```rust |
| 25 |
/// use icu::calendar::Date; |
| 26 |
/// use icu::calendar::options::DateDifferenceOptions; |
| 27 |
/// use icu::calendar::options::DateDurationUnit; |
| 28 |
/// use icu::calendar::types::DateDuration; |
| 29 |
/// use icu::calendar::types::Weekday; |
| 30 |
/// |
| 31 |
/// // Creating ISO date: 1992-09-02. |
| 32 |
/// let mut date_iso = Date::try_new_iso(1992, 9, 2) |
| 33 |
/// .expect("Failed to initialize ISO Date instance."); |
| 34 |
/// |
| 35 |
/// assert_eq!(date_iso.weekday(), Weekday::Wednesday); |
| 36 |
/// assert_eq!(date_iso.era_year().year, 1992); |
| 37 |
/// assert_eq!(date_iso.month().ordinal, 9); |
| 38 |
/// assert_eq!(date_iso.day_of_month().0, 2); |
| 39 |
/// |
| 40 |
/// // Answering questions about days in month and year. |
| 41 |
/// assert_eq!(date_iso.days_in_year(), 366); |
| 42 |
/// assert_eq!(date_iso.days_in_month(), 30); |
| 43 |
/// |
| 44 |
/// // Advancing date in-place by 1 year, 2 months, 3 weeks, 4 days. |
| 45 |
/// date_iso |
| 46 |
/// .try_add_with_options( |
| 47 |
/// DateDuration { |
| 48 |
/// is_negative: false, |
| 49 |
/// years: 1, |
| 50 |
/// months: 2, |
| 51 |
/// weeks: 3, |
| 52 |
/// days: 4, |
| 53 |
/// }, |
| 54 |
/// Default::default(), |
| 55 |
/// ) |
| 56 |
/// .unwrap(); |
| 57 |
/// assert_eq!(date_iso.era_year().year, 1993); |
| 58 |
/// assert_eq!(date_iso.month().ordinal, 11); |
| 59 |
/// assert_eq!(date_iso.day_of_month().0, 27); |
| 60 |
/// |
| 61 |
/// // Reverse date advancement. |
| 62 |
/// date_iso |
| 63 |
/// .try_add_with_options( |
| 64 |
/// DateDuration { |
| 65 |
/// is_negative: true, |
| 66 |
/// years: 1, |
| 67 |
/// months: 2, |
| 68 |
/// weeks: 3, |
| 69 |
/// days: 4, |
| 70 |
/// }, |
| 71 |
/// Default::default(), |
| 72 |
/// ) |
| 73 |
/// .unwrap(); |
| 74 |
/// assert_eq!(date_iso.era_year().year, 1992); |
| 75 |
/// assert_eq!(date_iso.month().ordinal, 9); |
| 76 |
/// assert_eq!(date_iso.day_of_month().0, 2); |
| 77 |
/// |
| 78 |
/// // Creating ISO date: 2022-01-30. |
| 79 |
/// let newer_date_iso = Date::try_new_iso(2022, 10, 30) |
| 80 |
/// .expect("Failed to initialize ISO Date instance."); |
| 81 |
/// |
| 82 |
/// // Comparing dates: 2022-01-30 and 1992-09-02. |
| 83 |
/// let mut options = DateDifferenceOptions::default(); |
| 84 |
/// options.largest_unit = Some(DateDurationUnit::Years); |
| 85 |
/// let Ok(duration) = |
| 86 |
/// newer_date_iso.try_until_with_options(&date_iso, options); |
| 87 |
/// assert_eq!(duration.years, 30); |
| 88 |
/// assert_eq!(duration.months, 1); |
| 89 |
/// assert_eq!(duration.days, 28); |
| 90 |
/// |
| 91 |
/// // Create new date with date advancement. Reassign to new variable. |
| 92 |
/// let mutated_date_iso = date_iso |
| 93 |
/// .try_added_with_options( |
| 94 |
/// DateDuration { |
| 95 |
/// is_negative: false, |
| 96 |
/// years: 1, |
| 97 |
/// months: 2, |
| 98 |
/// weeks: 3, |
| 99 |
/// days: 4, |
| 100 |
/// }, |
| 101 |
/// Default::default(), |
| 102 |
/// ) |
| 103 |
/// .unwrap(); |
| 104 |
/// assert_eq!(mutated_date_iso.era_year().year, 1993); |
| 105 |
/// assert_eq!(mutated_date_iso.month().ordinal, 11); |
| 106 |
/// assert_eq!(mutated_date_iso.day_of_month().0, 27); |
| 107 |
/// ``` |
| 108 |
#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)] |
| 109 |
#[allow(clippy::exhaustive_structs)] // spec-defined in Temporal |
| 110 |
pub struct DateDuration { |
| 111 |
/// Whether the duration is negative. |
| 112 |
/// |
| 113 |
/// A negative duration is an abstract concept that could result, for example, from |
| 114 |
/// taking the difference between two [`Date`](crate::Date)s in ascending order. |
| 115 |
/// |
| 116 |
/// The fields of the duration are either all positive or all negative. Mixed signs |
| 117 |
/// are not possible. |
| 118 |
/// |
| 119 |
/// By convention, this field should be `false` if the duration is zero. |
| 120 |
pub is_negative: bool, |
| 121 |
/// The number of years |
| 122 |
pub years: u32, |
| 123 |
/// The number of months |
| 124 |
pub months: u32, |
| 125 |
/// The number of weeks |
| 126 |
pub weeks: u32, |
| 127 |
/// The number of days |
| 128 |
pub days: u32, |
| 129 |
} |
| 130 |
|
| 131 |
impl DateDuration { |
| 132 |
/// Parses an ISO 8601 date-only duration string into a [`DateDuration`]. |
| 133 |
/// |
| 134 |
/// This is a wrapper around [`Self::try_from_utf8`] for UTF-8 |
| 135 |
/// string inputs. |
| 136 |
pub fn try_from_str(s: &str) -> Result<Self, DateDurationParseError> { |
| 137 |
Self::try_from_utf8(s.as_bytes()) |
| 138 |
} |
| 139 |
|
| 140 |
/// See [`Self::try_from_str`]. |
| 141 |
pub fn try_from_utf8(code_units: &[u8]) -> Result<Self, DateDurationParseError> { |
| 142 |
let mut s = code_units; |
| 143 |
|
| 144 |
let mut is_negative = false; |
| 145 |
match s { |
| 146 |
[b'-', rest @ ..] => { |
| 147 |
is_negative = true; |
| 148 |
s = rest; |
| 149 |
} |
| 150 |
[b'+', ..] => return Err(DateDurationParseError::PlusNotAllowed), |
| 151 |
_ => {} |
| 152 |
} |
| 153 |
|
| 154 |
match s { |
| 155 |
[b'P', rest @ ..] => s = rest, |
| 156 |
_ => return Err(DateDurationParseError::InvalidStructure), |
| 157 |
} |
| 158 |
|
| 159 |
if s.is_empty() { |
| 160 |
return Err(DateDurationParseError::InvalidStructure); |
| 161 |
} |
| 162 |
|
| 163 |
let mut years: u32 = 0; |
| 164 |
let mut months: u32 = 0; |
| 165 |
let mut weeks: u32 = 0; |
| 166 |
let mut days: u32 = 0; |
| 167 |
|
| 168 |
let mut seen_years = false; |
| 169 |
let mut seen_months = false; |
| 170 |
let mut seen_weeks = false; |
| 171 |
let mut seen_days = false; |
| 172 |
|
| 173 |
while !s.is_empty() { |
| 174 |
if matches!(s, [b'T', ..]) { |
| 175 |
return Err(DateDurationParseError::TimeNotSupported); |
| 176 |
} |
| 177 |
|
| 178 |
let mut value: u64 = 0; |
| 179 |
let mut has_digits = false; |
| 180 |
|
| 181 |
while let [b @ b'0'..=b'9', rest @ ..] = s { |
| 182 |
value = value |
| 183 |
.checked_mul(10) |
| 184 |
.and_then(|v| v.checked_add((b - b'0') as u64)) |
| 185 |
.ok_or(DateDurationParseError::NumberOverflow)?; |
| 186 |
s = rest; |
| 187 |
has_digits = true; |
| 188 |
} |
| 189 |
|
| 190 |
if !has_digits { |
| 191 |
return Err(DateDurationParseError::MissingValue); |
| 192 |
} |
| 193 |
|
| 194 |
match s { |
| 195 |
[b'Y', rest @ ..] => { |
| 196 |
if seen_years { |
| 197 |
return Err(DateDurationParseError::DuplicateUnit); |
| 198 |
} |
| 199 |
years = |
| 200 |
u32::try_from(value).map_err(|_| DateDurationParseError::NumberOverflow)?; |
| 201 |
seen_years = true; |
| 202 |
s = rest; |
| 203 |
} |
| 204 |
[b'M', rest @ ..] => { |
| 205 |
if seen_months { |
| 206 |
return Err(DateDurationParseError::DuplicateUnit); |
| 207 |
} |
| 208 |
months = |
| 209 |
u32::try_from(value).map_err(|_| DateDurationParseError::NumberOverflow)?; |
| 210 |
seen_months = true; |
| 211 |
s = rest; |
| 212 |
} |
| 213 |
[b'W', rest @ ..] => { |
| 214 |
if seen_weeks { |
| 215 |
return Err(DateDurationParseError::DuplicateUnit); |
| 216 |
} |
| 217 |
weeks = |
| 218 |
u32::try_from(value).map_err(|_| DateDurationParseError::NumberOverflow)?; |
| 219 |
seen_weeks = true; |
| 220 |
s = rest; |
| 221 |
} |
| 222 |
[b'D', rest @ ..] => { |
| 223 |
if seen_days { |
| 224 |
return Err(DateDurationParseError::DuplicateUnit); |
| 225 |
} |
| 226 |
days = |
| 227 |
u32::try_from(value).map_err(|_| DateDurationParseError::NumberOverflow)?; |
| 228 |
seen_days = true; |
| 229 |
s = rest; |
| 230 |
} |
| 231 |
_ => return Err(DateDurationParseError::InvalidStructure), |
| 232 |
} |
| 233 |
} |
| 234 |
|
| 235 |
Ok(Self { |
| 236 |
is_negative, |
| 237 |
years, |
| 238 |
months, |
| 239 |
weeks, |
| 240 |
days, |
| 241 |
}) |
| 242 |
} |
| 243 |
|
| 244 |
/// Returns a new [`DateDuration`] representing a number of years. |
| 245 |
pub fn for_years(years: i32) -> Self { |
| 246 |
Self { |
| 247 |
is_negative: years.is_negative(), |
| 248 |
years: years.unsigned_abs(), |
| 249 |
..Default::default() |
| 250 |
} |
| 251 |
} |
| 252 |
|
| 253 |
/// Returns a new [`DateDuration`] representing a number of months. |
| 254 |
pub fn for_months(months: i32) -> Self { |
| 255 |
Self { |
| 256 |
is_negative: months.is_negative(), |
| 257 |
months: months.unsigned_abs(), |
| 258 |
..Default::default() |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
/// Returns a new [`DateDuration`] representing a number of weeks. |
| 263 |
pub fn for_weeks(weeks: i32) -> Self { |
| 264 |
Self { |
| 265 |
is_negative: weeks.is_negative(), |
| 266 |
weeks: weeks.unsigned_abs(), |
| 267 |
..Default::default() |
| 268 |
} |
| 269 |
} |
| 270 |
|
| 271 |
/// Returns a new [`DateDuration`] representing a number of days. |
| 272 |
pub fn for_days(days: i32) -> Self { |
| 273 |
Self { |
| 274 |
is_negative: days.is_negative(), |
| 275 |
days: days.unsigned_abs(), |
| 276 |
..Default::default() |
| 277 |
} |
| 278 |
} |
| 279 |
|
| 280 |
/// Returns a new [`DateDuration`] representing a number of days |
| 281 |
/// represented as weeks and days |
| 282 |
pub(crate) fn for_weeks_and_days(days: i32) -> Self { |
| 283 |
let weeks = days / 7; |
| 284 |
let days = days % 7; |
| 285 |
Self::from_signed_ymwd(0, 0, weeks, days) |
| 286 |
} |
| 287 |
|
| 288 |
/// Do NOT pass this function values of mixed signs! |
| 289 |
pub(crate) fn from_signed_ymwd(years: i32, months: i32, weeks: i32, days: i32) -> Self { |
| 290 |
let is_negative = years.is_negative() |
| 291 |
|| months.is_negative() |
| 292 |
|| weeks.is_negative() |
| 293 |
|| days.is_negative(); |
| 294 |
if is_negative |
| 295 |
&& (years.is_positive() |
| 296 |
|| months.is_positive() |
| 297 |
|| weeks.is_positive() |
| 298 |
|| days.is_positive()) |
| 299 |
{ |
| 300 |
debug_assert!(false, "mixed signs in from_signed_ymd"); |
| 301 |
} |
| 302 |
Self { |
| 303 |
is_negative, |
| 304 |
years: years.unsigned_abs(), |
| 305 |
months: months.unsigned_abs(), |
| 306 |
weeks: weeks.unsigned_abs(), |
| 307 |
days: days.unsigned_abs(), |
| 308 |
} |
| 309 |
} |
| 310 |
|
| 311 |
#[inline] |
| 312 |
pub(crate) fn add_years_to(&self, year: i32) -> i32 { |
| 313 |
if !self.is_negative { |
| 314 |
match year.checked_add_unsigned(self.years) { |
| 315 |
Some(x) => x, |
| 316 |
None => { |
| 317 |
debug_assert!(false, "{year} + {self:?} out of year range"); |
| 318 |
i32::MAX |
| 319 |
} |
| 320 |
} |
| 321 |
} else { |
| 322 |
match year.checked_sub_unsigned(self.years) { |
| 323 |
Some(x) => x, |
| 324 |
None => { |
| 325 |
debug_assert!(false, "{year} - {self:?} out of year range"); |
| 326 |
i32::MIN |
| 327 |
} |
| 328 |
} |
| 329 |
} |
| 330 |
} |
| 331 |
|
| 332 |
#[inline] |
| 333 |
pub(crate) fn add_months_to(&self, month: u8) -> i32 { |
| 334 |
debug_assert!(i32::try_from(self.months).is_ok()); |
| 335 |
if !self.is_negative { |
| 336 |
i32::from(month) + (self.months as i32) |
| 337 |
} else { |
| 338 |
i32::from(month) - (self.months as i32) |
| 339 |
} |
| 340 |
} |
| 341 |
|
| 342 |
#[inline] |
| 343 |
pub(crate) fn add_weeks_and_days_to(&self, day: u8) -> i32 { |
| 344 |
debug_assert!(i32::try_from(self.weeks).is_ok()); |
| 345 |
if !self.is_negative { |
| 346 |
let day = i32::from(day) + (self.weeks as i32) * 7; |
| 347 |
match day.checked_add_unsigned(self.days) { |
| 348 |
Some(x) => x, |
| 349 |
None => { |
| 350 |
debug_assert!(false, "{day} + {self:?} out of day range"); |
| 351 |
i32::MAX |
| 352 |
} |
| 353 |
} |
| 354 |
} else { |
| 355 |
let day = i32::from(day) - (self.weeks as i32) * 7; |
| 356 |
match day.checked_sub_unsigned(self.days) { |
| 357 |
Some(x) => x, |
| 358 |
None => { |
| 359 |
debug_assert!(false, "{day} - {self:?} out of day range"); |
| 360 |
i32::MIN |
| 361 |
} |
| 362 |
} |
| 363 |
} |
| 364 |
} |
| 365 |
} |
| 366 |
|
| 367 |
#[cfg(test)] |
| 368 |
mod tests { |
| 369 |
use super::*; |
| 370 |
|
| 371 |
#[test] |
| 372 |
fn parse_single_unit_durations() { |
| 373 |
let d = DateDuration::try_from_str("P1D").unwrap(); |
| 374 |
assert_eq!( |
| 375 |
d, |
| 376 |
DateDuration { |
| 377 |
days: 1, |
| 378 |
..Default::default() |
| 379 |
} |
| 380 |
); |
| 381 |
|
| 382 |
let d = DateDuration::try_from_str("P3W").unwrap(); |
| 383 |
assert_eq!( |
| 384 |
d, |
| 385 |
DateDuration { |
| 386 |
weeks: 3, |
| 387 |
..Default::default() |
| 388 |
} |
| 389 |
); |
| 390 |
|
| 391 |
let d = DateDuration::try_from_str("P5M").unwrap(); |
| 392 |
assert_eq!( |
| 393 |
d, |
| 394 |
DateDuration { |
| 395 |
months: 5, |
| 396 |
..Default::default() |
| 397 |
} |
| 398 |
); |
| 399 |
|
| 400 |
let d = DateDuration::try_from_str("P7Y").unwrap(); |
| 401 |
assert_eq!( |
| 402 |
d, |
| 403 |
DateDuration { |
| 404 |
years: 7, |
| 405 |
..Default::default() |
| 406 |
} |
| 407 |
); |
| 408 |
} |
| 409 |
|
| 410 |
#[test] |
| 411 |
fn parse_multi_unit_durations() { |
| 412 |
let d = DateDuration::try_from_str("P1Y3M5W7D").unwrap(); |
| 413 |
assert_eq!( |
| 414 |
d, |
| 415 |
DateDuration { |
| 416 |
years: 1, |
| 417 |
months: 3, |
| 418 |
weeks: 5, |
| 419 |
days: 7, |
| 420 |
..Default::default() |
| 421 |
} |
| 422 |
); |
| 423 |
} |
| 424 |
|
| 425 |
#[test] |
| 426 |
fn parse_negative_durations() { |
| 427 |
let d = DateDuration::try_from_str("-P9W").unwrap(); |
| 428 |
assert_eq!( |
| 429 |
d, |
| 430 |
DateDuration { |
| 431 |
is_negative: true, |
| 432 |
weeks: 9, |
| 433 |
..Default::default() |
| 434 |
} |
| 435 |
); |
| 436 |
} |
| 437 |
} |