| 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 calendrical_calculations::rata_die::RataDie; |
| 6 |
|
| 7 |
use crate::duration::DateDuration; |
| 8 |
use crate::error::{ |
| 9 |
DateAddError, DateFromFieldsError, DateNewError, EcmaReferenceYearError, LunisolarDateError, |
| 10 |
MonthError, UnknownEraError, range_check, |
| 11 |
}; |
| 12 |
use crate::options::{DateAddOptions, DateDifferenceOptions, DateDurationUnit}; |
| 13 |
use crate::options::{DateFromFieldsOptions, MissingFieldsStrategy, Overflow}; |
| 14 |
use crate::types::{DateFields, Month}; |
| 15 |
use crate::{Calendar, DateError, RangeError, types}; |
| 16 |
use core::cmp::Ordering; |
| 17 |
use core::fmt::Debug; |
| 18 |
use core::hash::{Hash, Hasher}; |
| 19 |
use core::ops::RangeInclusive; |
| 20 |
use core::ops::Sub; |
| 21 |
|
| 22 |
/// This is checked by convenience constructors and `from_codes`. |
| 23 |
/// Internally we don't care about this invariant. |
| 24 |
pub(crate) const CONSTRUCTOR_YEAR_RANGE: RangeInclusive<i32> = -9999..=9999; |
| 25 |
|
| 26 |
/// This is a fundamental invariant of `ArithmeticDate` and by extension all our |
| 27 |
/// date types. Constructors that don't check [`CONSTRUCTOR_YEAR_RANGE`] check this range. |
| 28 |
/// |
| 29 |
/// This is the range used by `Date::from_rata_die`, `Date::try_from_fields`, |
| 30 |
/// and Date arithmetic operations. |
| 31 |
pub(crate) const VALID_RD_RANGE: RangeInclusive<RataDie> = |
| 32 |
calendrical_calculations::gregorian::fixed_from_gregorian(-999999, 1, 1) |
| 33 |
..=calendrical_calculations::gregorian::fixed_from_gregorian(999999, 12, 31); |
| 34 |
|
| 35 |
/// This is a year range that exceeds the RD range for all calendars. |
| 36 |
/// |
| 37 |
/// We *must* ensure dates are within `VALID_RD_RANGE` some point before constructing them. |
| 38 |
/// |
| 39 |
/// However, we may need to perform a fair amount of calendar arithmetic before |
| 40 |
/// getting to the point where we know if we are in range, and the calendar arithmetic |
| 41 |
/// is fragile (chance of math issues, slowness, debug assertions) at high ranges. |
| 42 |
/// |
| 43 |
/// So we try to early-check year values where possible. We use a "generous" year range |
| 44 |
/// which is known to be wider than the valid RD range for any era in any currently |
| 45 |
/// supported calendar. |
| 46 |
/// |
| 47 |
/// `VALID_RD_RANGE` maps to 1031332 BH..=1030050 AH in the Islamic calendars, which have |
| 48 |
/// the shortest years. We pick a slightly wider range so that temporary intermediate |
| 49 |
/// values are not affected by this. |
| 50 |
/// |
| 51 |
/// The tests in `extrema.rs` ensure that all in-range dates can be produced by the APIs that, |
| 52 |
/// use this check, and that these year numbers map to out-of-range values for every era. |
| 53 |
pub(crate) const GENEROUS_YEAR_RANGE: RangeInclusive<i32> = -1_040_000..=1_040_000; |
| 54 |
|
| 55 |
/// These are for early-checking durations in `ArithmeticDate::add` |
| 56 |
/// |
| 57 |
/// They are crate-public so they can be used in tests, but should probably not be used elsewhere. |
| 58 |
pub(crate) const GENEROUS_MAX_YEARS: u32 = |
| 59 |
(*GENEROUS_YEAR_RANGE.end() - *GENEROUS_YEAR_RANGE.start()) as u32; |
| 60 |
pub(crate) const GENEROUS_MAX_MONTHS: u32 = GENEROUS_MAX_YEARS * 13; |
| 61 |
pub(crate) const GENEROUS_MAX_DAYS: u32 = GENEROUS_MAX_MONTHS * 31; |
| 62 |
|
| 63 |
/// This is the year range all calendar specific computation can assume their data to be in. |
| 64 |
/// |
| 65 |
/// It is wider than [`GENEROUS_YEAR_RANGE`]: `GENEROUS_YEAR_RANGE` is used for checking user |
| 66 |
/// input, this is more of an internal invariant for assertions. New calendar implementations |
| 67 |
/// must ensure they do not have overflows or panics for year (era year or extended year) within this range. |
| 68 |
/// |
| 69 |
/// This value is computed by going past the max value producible by adding a duration, |
| 70 |
/// which is preemptively capped at `GENEROUS_MAX_YEARS`, `GENEROUS_MAX_MONTHS`, `GENEROUS_MAX_DAYS` |
| 71 |
/// in `added()`. |
| 72 |
pub(crate) const SAFE_YEAR_RANGE: RangeInclusive<i32> = -8_000_000..=8_000_000; |
| 73 |
|
| 74 |
// Invariant: VALID_RD_RANGE contains the date |
| 75 |
#[derive(Debug)] |
| 76 |
pub(crate) struct ArithmeticDate<C: DateFieldsResolver>(<C::YearInfo as PackWithMD>::Packed); |
| 77 |
|
| 78 |
// Manual impls since the derive will introduce a C: Trait bound |
| 79 |
// and only the year value should be compared |
| 80 |
impl<C: DateFieldsResolver> Copy for ArithmeticDate<C> {} |
| 81 |
impl<C: DateFieldsResolver> Clone for ArithmeticDate<C> { |
| 82 |
fn clone(&self) -> Self { |
| 83 |
*self |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
impl<C: DateFieldsResolver> PartialEq for ArithmeticDate<C> { |
| 88 |
fn eq(&self, other: &Self) -> bool { |
| 89 |
self.year() == other.year() && self.month() == other.month() && self.day() == other.day() |
| 90 |
} |
| 91 |
} |
| 92 |
|
| 93 |
impl<C: DateFieldsResolver> Eq for ArithmeticDate<C> {} |
| 94 |
|
| 95 |
impl<C: DateFieldsResolver> Ord for ArithmeticDate<C> { |
| 96 |
fn cmp(&self, other: &Self) -> Ordering { |
| 97 |
self.year() |
| 98 |
.cmp(&other.year()) |
| 99 |
.then(self.month().cmp(&other.month())) |
| 100 |
.then(self.day().cmp(&other.day())) |
| 101 |
} |
| 102 |
} |
| 103 |
|
| 104 |
impl<C: DateFieldsResolver> PartialOrd for ArithmeticDate<C> { |
| 105 |
fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
| 106 |
Some(self.cmp(other)) |
| 107 |
} |
| 108 |
} |
| 109 |
|
| 110 |
impl<C: DateFieldsResolver> Hash for ArithmeticDate<C> { |
| 111 |
fn hash<H>(&self, state: &mut H) |
| 112 |
where |
| 113 |
H: Hasher, |
| 114 |
{ |
| 115 |
self.year().hash(state); |
| 116 |
self.month().hash(state); |
| 117 |
self.day().hash(state); |
| 118 |
} |
| 119 |
} |
| 120 |
|
| 121 |
/// Same data as [`ArithmeticDate`], but may be out of [`VALID_RD_RANGE`] |
| 122 |
#[derive(Debug)] |
| 123 |
struct UncheckedArithmeticDate<C: DateFieldsResolver> { |
| 124 |
year: C::YearInfo, |
| 125 |
ordinal_month: u8, |
| 126 |
day: u8, |
| 127 |
} |
| 128 |
|
| 129 |
impl<C: DateFieldsResolver> UncheckedArithmeticDate<C> { |
| 130 |
fn into_checked(self) -> Option<ArithmeticDate<C>> { |
| 131 |
let rd = C::to_rata_die_inner(self.year, self.ordinal_month, self.day); |
| 132 |
if !VALID_RD_RANGE.contains(&rd) { |
| 133 |
return None; |
| 134 |
} |
| 135 |
// Invariant checked above |
| 136 |
Some(ArithmeticDate::new_unchecked( |
| 137 |
self.year, |
| 138 |
self.ordinal_month, |
| 139 |
self.day, |
| 140 |
)) |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
/// Maximum number of iterations when iterating through the days of a month; can be increased if necessary |
| 145 |
#[allow(dead_code)] // TODO: Remove dead code tag after use |
| 146 |
pub(crate) const MAX_ITERS_FOR_DAYS_OF_MONTH: u8 = 33; |
| 147 |
|
| 148 |
pub(crate) trait PackWithMD: Copy { |
| 149 |
type Packed: Copy + Debug; |
| 150 |
|
| 151 |
fn pack(self, month: u8, day: u8) -> Self::Packed; |
| 152 |
fn unpack_year(packed: Self::Packed) -> Self; |
| 153 |
fn unpack_month(packed: Self::Packed) -> u8; |
| 154 |
fn unpack_day(packed: Self::Packed) -> u8; |
| 155 |
} |
| 156 |
|
| 157 |
impl PackWithMD for i32 { |
| 158 |
/// 2 bits unused, 21 bits year (`test_validity_ranges`), |
| 159 |
/// 4 bits month (1..13), 5 bits day (1..31) |
| 160 |
type Packed = [u8; 4]; |
| 161 |
|
| 162 |
fn pack(self, month: u8, day: u8) -> Self::Packed { |
| 163 |
(self << 9 | i32::from(month) << 5 | i32::from(day)).to_le_bytes() |
| 164 |
} |
| 165 |
|
| 166 |
fn unpack_year(packed: Self::Packed) -> Self { |
| 167 |
let packed = i32::from_le_bytes(packed); |
| 168 |
packed >> 9 |
| 169 |
} |
| 170 |
|
| 171 |
fn unpack_month(packed: Self::Packed) -> u8 { |
| 172 |
let packed = i32::from_le_bytes(packed); |
| 173 |
(packed >> 5 & 0b1111) as u8 |
| 174 |
} |
| 175 |
|
| 176 |
fn unpack_day(packed: Self::Packed) -> u8 { |
| 177 |
let packed = i32::from_le_bytes(packed); |
| 178 |
(packed & 0b11111) as u8 |
| 179 |
} |
| 180 |
} |
| 181 |
|
| 182 |
/// Trait for converting from era codes, month codes, and other fields to year/month/day ordinals. |
| 183 |
pub(crate) trait DateFieldsResolver: Calendar { |
| 184 |
/// This stores the year as either an i32, or a type containing more |
| 185 |
/// useful computational information. |
| 186 |
type YearInfo: Copy + Debug + Hash + Ord + Sub<Output = i32> + PackWithMD; |
| 187 |
|
| 188 |
fn days_in_provided_month(year: Self::YearInfo, month: u8) -> u8; |
| 189 |
|
| 190 |
/// Converts the era and era year to a [`Self::YearInfo`]. If the calendar does not have eras, |
| 191 |
/// this should always return an Err result. |
| 192 |
/// |
| 193 |
/// Precondition: `era_year` is in [`SAFE_YEAR_RANGE`]. |
| 194 |
fn extended_year_from_era_year_unchecked( |
| 195 |
&self, |
| 196 |
era: &[u8], |
| 197 |
era_year: i32, |
| 198 |
) -> Result<i32, UnknownEraError>; |
| 199 |
|
| 200 |
/// Converts an extended year to a [`Self::YearInfo`]. |
| 201 |
/// |
| 202 |
/// Precondition: `extended_year` is in [`GENEROUS_YEAR_RANGE`]. |
| 203 |
/// |
| 204 |
/// Some calendars with complex calculations use this precondition to |
| 205 |
/// ensure that the year is in a range where their arithmetic code is well-behaved. |
| 206 |
/// |
| 207 |
/// Calendar implementors who need this are encouraged to debug assert that the invariant |
| 208 |
/// is upheld. |
| 209 |
/// |
| 210 |
/// This should primarily be used in constructors that range-check with |
| 211 |
/// the very narrow [`CONSTRUCTOR_YEAR_RANGE`], after that check. If the |
| 212 |
/// constructor checks [`VALID_RD_RANGE`], please use `year_info_from_extended_checked`. |
| 213 |
fn year_info_from_extended(&self, extended_year: i32) -> Self::YearInfo; |
| 214 |
|
| 215 |
/// Inverse operation of [`Self::year_info_from_extended`]. |
| 216 |
fn extended_from_year_info(&self, year_info: Self::YearInfo) -> i32; |
| 217 |
|
| 218 |
/// Calculates the ECMA reference year (represented as an extended year) |
| 219 |
/// for the month code and day, or an error if the month code and day are invalid. |
| 220 |
/// |
| 221 |
/// Note that this is called before any potential `Overflow::Constrain` application, |
| 222 |
/// so this should accept out-of-range day values as if they are the highest possible |
| 223 |
/// day for the given month. |
| 224 |
fn reference_year_from_month_day( |
| 225 |
&self, |
| 226 |
month: Month, |
| 227 |
day: u8, |
| 228 |
) -> Result<Self::YearInfo, EcmaReferenceYearError>; |
| 229 |
|
| 230 |
/// The number of months for the given year. |
| 231 |
/// |
| 232 |
/// The default impl is for non-lunisolar calendars with 12 months! |
| 233 |
fn months_in_provided_year(_year: Self::YearInfo) -> u8 { |
| 234 |
12 |
| 235 |
} |
| 236 |
|
| 237 |
/// A lower bound for the number of months in `years` years, starting from the beginning of this year. |
| 238 |
/// |
| 239 |
/// This may be equal to the number of months, but should never be larger. Ideally, |
| 240 |
/// implementations should be close enough to the actual answer such that the error |
| 241 |
/// is bounded by a constant with respect to `years`. |
| 242 |
/// |
| 243 |
/// The default impl is for non-lunisolar calendars with 12 months! |
| 244 |
/// |
| 245 |
/// `until()` will debug assert if this ever returns a value greater than the |
| 246 |
/// month diff betweeen two dates. |
| 247 |
#[inline] |
| 248 |
fn min_months_from(_start: Self::YearInfo, years: i32) -> i32 { |
| 249 |
12 * years |
| 250 |
} |
| 251 |
|
| 252 |
/// Calculates the ordinal month for the given year and month code. |
| 253 |
/// |
| 254 |
/// The default impl is for non-lunisolar calendars! |
| 255 |
#[inline] |
| 256 |
fn ordinal_from_month( |
| 257 |
&self, |
| 258 |
year: Self::YearInfo, |
| 259 |
month: Month, |
| 260 |
_overflow: Overflow, |
| 261 |
) -> Result<u8, MonthError> { |
| 262 |
match (month.number(), month.is_leap()) { |
| 263 |
(month_number, false) |
| 264 |
if (1..=Self::months_in_provided_year(year)).contains(&month_number) => |
| 265 |
{ |
| 266 |
Ok(month_number) |
| 267 |
} |
| 268 |
_ => Err(MonthError::NotInCalendar), |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
/// Calculates the month code from the given ordinal month and year. |
| 273 |
/// |
| 274 |
/// The caller must ensure that the ordinal is in range. |
| 275 |
/// |
| 276 |
/// The default impl is for non-lunisolar calendars! |
| 277 |
#[inline] |
| 278 |
fn month_from_ordinal(&self, _year: Self::YearInfo, ordinal_month: u8) -> Month { |
| 279 |
Month::new_unchecked(ordinal_month, false) |
| 280 |
} |
| 281 |
|
| 282 |
// Date-to-RD conversion |
| 283 |
// Used internally for implementing date arithmetic |
| 284 |
fn to_rata_die_inner(year: Self::YearInfo, month: u8, day: u8) -> RataDie; |
| 285 |
} |
| 286 |
|
| 287 |
impl<C: DateFieldsResolver> ArithmeticDate<C> { |
| 288 |
pub(crate) fn to_rata_die(self) -> RataDie { |
| 289 |
C::to_rata_die_inner(self.year(), self.month(), self.day()) |
| 290 |
} |
| 291 |
|
| 292 |
pub(crate) fn year(self) -> C::YearInfo { |
| 293 |
C::YearInfo::unpack_year(self.0) |
| 294 |
} |
| 295 |
|
| 296 |
pub(crate) fn month(self) -> u8 { |
| 297 |
C::YearInfo::unpack_month(self.0) |
| 298 |
} |
| 299 |
|
| 300 |
pub(crate) fn day(self) -> u8 { |
| 301 |
C::YearInfo::unpack_day(self.0) |
| 302 |
} |
| 303 |
|
| 304 |
/// Precondition: the date is in `VALID_RD_RANGE`. |
| 305 |
/// |
| 306 |
/// Use `UncheckedArithmeticDate` if you wish to generate intermediate out-of-range dates. |
| 307 |
#[inline] |
| 308 |
pub(crate) fn new_unchecked(year: C::YearInfo, month: u8, day: u8) -> Self { |
| 309 |
ArithmeticDate(C::YearInfo::pack(year, month, day)) |
| 310 |
} |
| 311 |
|
| 312 |
pub(crate) fn cast<C2: DateFieldsResolver<YearInfo = C::YearInfo>>(self) -> ArithmeticDate<C2> { |
| 313 |
ArithmeticDate::new_unchecked(self.year(), self.month(), self.day()) |
| 314 |
} |
| 315 |
|
| 316 |
// Used by `from_codes`, checks `CONSTRUCTOR_YEAR_RANGE` |
| 317 |
pub(crate) fn from_input_year_month_code_day( |
| 318 |
year: types::YearInput, |
| 319 |
month: Month, |
| 320 |
day: u8, |
| 321 |
calendar: &C, |
| 322 |
) -> Result<Self, DateNewError> { |
| 323 |
let extended_year = match year { |
| 324 |
types::YearInput::Extended(y) => { |
| 325 |
if !CONSTRUCTOR_YEAR_RANGE.contains(&y) { |
| 326 |
return Err(DateNewError::InvalidYear); |
| 327 |
} |
| 328 |
y |
| 329 |
} |
| 330 |
types::YearInput::EraYear(era, y) => { |
| 331 |
if !CONSTRUCTOR_YEAR_RANGE.contains(&y) { |
| 332 |
return Err(DateNewError::InvalidYear); |
| 333 |
} |
| 334 |
calendar |
| 335 |
.extended_year_from_era_year_unchecked(era.as_bytes(), y) |
| 336 |
.map_err(|_| DateNewError::InvalidEra)? |
| 337 |
} |
| 338 |
}; |
| 339 |
let year = calendar.year_info_from_extended(extended_year); |
| 340 |
|
| 341 |
let month = calendar |
| 342 |
.ordinal_from_month(year, month, Overflow::Reject) |
| 343 |
.map_err(|e| match e { |
| 344 |
MonthError::NotInCalendar => DateNewError::MonthNotInCalendar, |
| 345 |
MonthError::NotInYear => DateNewError::MonthNotInYear, |
| 346 |
})?; |
| 347 |
|
| 348 |
let max_day = C::days_in_provided_month(year, month); |
| 349 |
if day < 1 || day > max_day { |
| 350 |
return Err(DateNewError::InvalidDay { max: max_day }); |
| 351 |
} |
| 352 |
|
| 353 |
// date is in the valid year range, and therefore in the valid RD range |
| 354 |
Ok(ArithmeticDate::new_unchecked(year, month, day)) |
| 355 |
} |
| 356 |
|
| 357 |
// Used by calendar-specific constructors (lunisolar), checks `CONSTRUCTOR_YEAR_RANGE` |
| 358 |
pub(crate) fn try_from_ymd_lunisolar( |
| 359 |
year: i32, |
| 360 |
month: Month, |
| 361 |
day: u8, |
| 362 |
calendar: &C, |
| 363 |
) -> Result<Self, LunisolarDateError> { |
| 364 |
if !CONSTRUCTOR_YEAR_RANGE.contains(&year) { |
| 365 |
return Err(LunisolarDateError::InvalidYear); |
| 366 |
} |
| 367 |
let year = calendar.year_info_from_extended(year); |
| 368 |
|
| 369 |
let month = match calendar.ordinal_from_month(year, month, Overflow::Reject) { |
| 370 |
Ok(month) => month, |
| 371 |
Err(MonthError::NotInCalendar) => return Err(LunisolarDateError::MonthNotInCalendar), |
| 372 |
Err(MonthError::NotInYear) => return Err(LunisolarDateError::MonthNotInYear), |
| 373 |
}; |
| 374 |
|
| 375 |
let max_day = C::days_in_provided_month(year, month); |
| 376 |
if !(1..=max_day).contains(&day) { |
| 377 |
return Err(LunisolarDateError::InvalidDay { max: max_day }); |
| 378 |
} |
| 379 |
|
| 380 |
// date is in the valid year range, and therefore in the valid RD range |
| 381 |
Ok(Self::new_unchecked(year, month, day)) |
| 382 |
} |
| 383 |
|
| 384 |
pub(crate) fn from_fields( |
| 385 |
fields: DateFields, |
| 386 |
options: DateFromFieldsOptions, |
| 387 |
calendar: &C, |
| 388 |
) -> Result<Self, DateFromFieldsError> { |
| 389 |
let missing_fields_strategy = options.missing_fields_strategy.unwrap_or_default(); |
| 390 |
|
| 391 |
// DateFromFieldsOptions documents the default as reject |
| 392 |
let overflow = options.overflow.unwrap_or(Overflow::Reject); |
| 393 |
|
| 394 |
let day = match fields.day { |
| 395 |
Some(day) => day, |
| 396 |
None => match missing_fields_strategy { |
| 397 |
MissingFieldsStrategy::Reject => return Err(DateFromFieldsError::NotEnoughFields), |
| 398 |
MissingFieldsStrategy::Ecma => { |
| 399 |
if fields.extended_year.is_some() || fields.era_year.is_some() { |
| 400 |
// The ECMAScript strategy is to pick day 1, always, regardless of whether |
| 401 |
// that day exists for the month/year combo |
| 402 |
1 |
| 403 |
} else { |
| 404 |
return Err(DateFromFieldsError::NotEnoughFields); |
| 405 |
} |
| 406 |
} |
| 407 |
}, |
| 408 |
}; |
| 409 |
|
| 410 |
// We're returning these error early so that we return structural type |
| 411 |
// errors before range errors, see comment in the year code below. |
| 412 |
if fields.month_code.is_none() && fields.ordinal_month.is_none() && fields.month.is_none() { |
| 413 |
return Err(DateFromFieldsError::NotEnoughFields); |
| 414 |
} |
| 415 |
if fields.month_code.is_some() && fields.month.is_some() { |
| 416 |
return Err(DateFromFieldsError::TooManyFields); |
| 417 |
} |
| 418 |
|
| 419 |
let mut valid_month = None; |
| 420 |
|
| 421 |
// To better match the Temporal specification's order of operations, we try |
| 422 |
// to return structural type errors (`NotEnoughFields`) before checking for range errors. |
| 423 |
// This isn't behavior we *must* have, but it is not much additional work to maintain |
| 424 |
// so we make an attempt. |
| 425 |
let year = match (fields.era, fields.era_year) { |
| 426 |
(None, None) => match fields.extended_year { |
| 427 |
Some(extended_year) => { |
| 428 |
if !GENEROUS_YEAR_RANGE.contains(&extended_year) { |
| 429 |
return Err(DateFromFieldsError::Overflow); |
| 430 |
} |
| 431 |
calendar.year_info_from_extended(extended_year) |
| 432 |
} |
| 433 |
None => match missing_fields_strategy { |
| 434 |
MissingFieldsStrategy::Reject => { |
| 435 |
return Err(DateFromFieldsError::NotEnoughFields); |
| 436 |
} |
| 437 |
MissingFieldsStrategy::Ecma => { |
| 438 |
let (m, d) = match (fields.month, fields.month_code, fields.ordinal_month) { |
| 439 |
(Some(month), _, None) => (month, day), |
| 440 |
(_, Some(month_code), None) => { |
| 441 |
let validated = Month::try_from_utf8(month_code)?; |
| 442 |
valid_month = Some(validated); |
| 443 |
(validated, day) |
| 444 |
} |
| 445 |
_ => return Err(DateFromFieldsError::NotEnoughFields), |
| 446 |
}; |
| 447 |
let ref_year = calendar.reference_year_from_month_day(m, d); |
| 448 |
if ref_year.err() == Some(EcmaReferenceYearError::UseRegularIfConstrain) |
| 449 |
&& overflow == Overflow::Constrain |
| 450 |
{ |
| 451 |
let new_valid_month = Month::new(m.number()); |
| 452 |
valid_month = Some(new_valid_month); |
| 453 |
calendar.reference_year_from_month_day(new_valid_month, d)? |
| 454 |
} else { |
| 455 |
ref_year? |
| 456 |
} |
| 457 |
} |
| 458 |
}, |
| 459 |
}, |
| 460 |
(Some(era), Some(era_year)) => { |
| 461 |
if !GENEROUS_YEAR_RANGE.contains(&era_year) { |
| 462 |
return Err(DateFromFieldsError::Overflow); |
| 463 |
} |
| 464 |
let extended_year = |
| 465 |
calendar.extended_year_from_era_year_unchecked(era, era_year)?; |
| 466 |
let year = calendar.year_info_from_extended(extended_year); |
| 467 |
if let Some(extended_year) = fields.extended_year |
| 468 |
&& calendar.extended_from_year_info(year) != extended_year |
| 469 |
{ |
| 470 |
return Err(DateFromFieldsError::InconsistentYear); |
| 471 |
} |
| 472 |
year |
| 473 |
} |
| 474 |
// Era and Era Year must be both or neither |
| 475 |
(Some(_), None) | (None, Some(_)) => return Err(DateFromFieldsError::NotEnoughFields), |
| 476 |
}; |
| 477 |
|
| 478 |
let month = match (fields.month_code, fields.month) { |
| 479 |
(_, Some(month)) => { |
| 480 |
let computed_month = calendar.ordinal_from_month(year, month, overflow)?; |
| 481 |
if let Some(ordinal_month) = fields.ordinal_month |
| 482 |
&& computed_month != ordinal_month |
| 483 |
{ |
| 484 |
return Err(DateFromFieldsError::InconsistentMonth); |
| 485 |
} |
| 486 |
computed_month |
| 487 |
} |
| 488 |
(Some(month_code), _) => { |
| 489 |
let validated = match valid_month { |
| 490 |
Some(validated) => validated, |
| 491 |
None => Month::try_from_utf8(month_code)?, |
| 492 |
}; |
| 493 |
let computed_month = calendar.ordinal_from_month(year, validated, overflow)?; |
| 494 |
if let Some(ordinal_month) = fields.ordinal_month |
| 495 |
&& computed_month != ordinal_month |
| 496 |
{ |
| 497 |
return Err(DateFromFieldsError::InconsistentMonth); |
| 498 |
} |
| 499 |
computed_month |
| 500 |
} |
| 501 |
(None, None) => match fields.ordinal_month { |
| 502 |
Some(month) => month, |
| 503 |
None => { |
| 504 |
debug_assert!(false, "Already checked above"); |
| 505 |
return Err(DateFromFieldsError::NotEnoughFields); |
| 506 |
} |
| 507 |
}, |
| 508 |
}; |
| 509 |
|
| 510 |
let max_month = C::months_in_provided_year(year); |
| 511 |
let month = if matches!(overflow, Overflow::Constrain) { |
| 512 |
month.clamp(1, max_month) |
| 513 |
} else if (1..=max_month).contains(&month) { |
| 514 |
month |
| 515 |
} else { |
| 516 |
return Err(DateFromFieldsError::InvalidOrdinalMonth { max: max_month }); |
| 517 |
}; |
| 518 |
|
| 519 |
let max_day = C::days_in_provided_month(year, month); |
| 520 |
let day = if matches!(overflow, Overflow::Constrain) { |
| 521 |
day.clamp(1, max_day) |
| 522 |
} else if (1..=max_day).contains(&day) { |
| 523 |
day |
| 524 |
} else { |
| 525 |
return Err(DateFromFieldsError::InvalidDay { max: max_day }); |
| 526 |
}; |
| 527 |
let rd = C::to_rata_die_inner(year, month, day); |
| 528 |
|
| 529 |
// We early checked for a generous range of years, now we must check |
| 530 |
// to ensure we are actually in range for our core invariant. |
| 531 |
if !VALID_RD_RANGE.contains(&rd) { |
| 532 |
return Err(DateFromFieldsError::Overflow); |
| 533 |
} |
| 534 |
// We just checked the RD range above |
| 535 |
Ok(Self::new_unchecked(year, month, day)) |
| 536 |
} |
| 537 |
|
| 538 |
// Used by calendar-specific constructors (non-lunisolar), checks `CONSTRUCTOR_YEAR_RANGE` |
| 539 |
pub(crate) fn from_year_month_day( |
| 540 |
year: i32, |
| 541 |
month: u8, |
| 542 |
day: u8, |
| 543 |
cal: &C, |
| 544 |
) -> Result<Self, RangeError> { |
| 545 |
range_check(year, "year", CONSTRUCTOR_YEAR_RANGE)?; |
| 546 |
let year_info = cal.year_info_from_extended(year); |
| 547 |
range_check(month, "month", 1..=C::months_in_provided_year(year_info))?; |
| 548 |
range_check(day, "day", 1..=C::days_in_provided_month(year_info, month))?; |
| 549 |
// date is in the valid year range, and therefore in the valid RD range |
| 550 |
Ok(ArithmeticDate::new_unchecked(year_info, month, day)) |
| 551 |
} |
| 552 |
|
| 553 |
// Used by calendar-specific constructors (Japanese), checks `CONSTRUCTOR_YEAR_RANGE` |
| 554 |
pub(crate) fn from_era_year_month_day( |
| 555 |
era: &str, |
| 556 |
year: i32, |
| 557 |
month: u8, |
| 558 |
day: u8, |
| 559 |
cal: &C, |
| 560 |
) -> Result<Self, DateError> { |
| 561 |
range_check(year, "year", CONSTRUCTOR_YEAR_RANGE)?; |
| 562 |
let extended_year = cal.extended_year_from_era_year_unchecked(era.as_bytes(), year)?; |
| 563 |
let year_info = cal.year_info_from_extended(extended_year); |
| 564 |
range_check(month, "month", 1..=C::months_in_provided_year(year_info))?; |
| 565 |
range_check(day, "day", 1..=C::days_in_provided_month(year_info, month))?; |
| 566 |
// date is in the valid year range, and therefore in the valid RD range |
| 567 |
Ok(ArithmeticDate::new_unchecked(year_info, month, day)) |
| 568 |
} |
| 569 |
|
| 570 |
/// Implements the Temporal abstract operation `BalanceNonISODate`. |
| 571 |
/// |
| 572 |
/// This takes a year, month, and day, where the month and day might be out of range, then |
| 573 |
/// balances excess months into the year field and excess days into the month field. |
| 574 |
/// |
| 575 |
/// In addition to specced behavior, this guarantees that it will produce an in-generous-year-range date. |
| 576 |
/// |
| 577 |
/// This does *not* necessarily produce something within [`VALID_RD_RANGE`], but it will ensure things |
| 578 |
/// are within [`GENEROUS_YEAR_RANGE`]. |
| 579 |
fn new_balanced( |
| 580 |
year: C::YearInfo, |
| 581 |
ordinal_month: i32, |
| 582 |
day: i32, |
| 583 |
cal: &C, |
| 584 |
) -> UncheckedArithmeticDate<C> { |
| 585 |
// 1. Let _resolvedYear_ be _arithmeticYear_. |
| 586 |
// 1. Let _resolvedMonth_ be _ordinalMonth_. |
| 587 |
let mut resolved_year = year; |
| 588 |
let mut resolved_month = ordinal_month; |
| 589 |
// 1. Let _monthsInYear_ be CalendarMonthsInYear(_calendar_, _resolvedYear_). |
| 590 |
let mut months_in_year = C::months_in_provided_year(resolved_year); |
| 591 |
// 1. Repeat, while _resolvedMonth_ ≤ 0, |
| 592 |
// 1. Set _resolvedYear_ to _resolvedYear_ - 1. |
| 593 |
// 1. Set _monthsInYear_ to CalendarMonthsInYear(_calendar_, _resolvedYear_). |
| 594 |
// 1. Set _resolvedMonth_ to _resolvedMonth_ + _monthsInYear_. |
| 595 |
while resolved_month <= 0 { |
| 596 |
resolved_year = |
| 597 |
cal.year_info_from_extended(cal.extended_from_year_info(resolved_year) - 1); |
| 598 |
months_in_year = C::months_in_provided_year(resolved_year); |
| 599 |
resolved_month += i32::from(months_in_year); |
| 600 |
} |
| 601 |
// 1. Repeat, while _resolvedMonth_ > _monthsInYear_, |
| 602 |
// 1. Set _resolvedMonth_ to _resolvedMonth_ - _monthsInYear_. |
| 603 |
// 1. Set _resolvedYear_ to _resolvedYear_ + 1. |
| 604 |
// 1. Set _monthsInYear_ to CalendarMonthsInYear(_calendar_, _resolvedYear_). |
| 605 |
while resolved_month > i32::from(months_in_year) { |
| 606 |
resolved_month -= i32::from(months_in_year); |
| 607 |
resolved_year = |
| 608 |
cal.year_info_from_extended(cal.extended_from_year_info(resolved_year) + 1); |
| 609 |
months_in_year = C::months_in_provided_year(resolved_year); |
| 610 |
} |
| 611 |
debug_assert!(u8::try_from(resolved_month).is_ok()); |
| 612 |
let mut resolved_month = resolved_month as u8; |
| 613 |
// 1. Let _resolvedDay_ be _day_. |
| 614 |
let mut resolved_day = day; |
| 615 |
// 1. Let _daysInMonth_ be CalendarDaysInMonth(_calendar_, _resolvedYear_, _resolvedMonth_). |
| 616 |
let mut days_in_month = C::days_in_provided_month(resolved_year, resolved_month); |
| 617 |
// 1. Repeat, while _resolvedDay_ ≤ 0, |
| 618 |
while resolved_day <= 0 { |
| 619 |
// 1. Set _resolvedMonth_ to _resolvedMonth_ - 1. |
| 620 |
// 1. If _resolvedMonth_ is 0, then |
| 621 |
resolved_month -= 1; |
| 622 |
if resolved_month == 0 { |
| 623 |
// 1. Set _resolvedYear_ to _resolvedYear_ - 1. |
| 624 |
// 1. Set _monthsInYear_ to CalendarMonthsInYear(_calendar_, _resolvedYear_). |
| 625 |
// 1. Set _resolvedMonth_ to _monthsInYear_. |
| 626 |
resolved_year = |
| 627 |
cal.year_info_from_extended(cal.extended_from_year_info(resolved_year) - 1); |
| 628 |
months_in_year = C::months_in_provided_year(resolved_year); |
| 629 |
resolved_month = months_in_year; |
| 630 |
} |
| 631 |
// 1. Set _daysInMonth_ to CalendarDaysInMonth(_calendar_, _resolvedYear_, _resolvedMonth_). |
| 632 |
// 1. Set _resolvedDay_ to _resolvedDay_ + _daysInMonth_. |
| 633 |
days_in_month = C::days_in_provided_month(resolved_year, resolved_month); |
| 634 |
resolved_day += i32::from(days_in_month); |
| 635 |
} |
| 636 |
// 1. Repeat, while _resolvedDay_ > _daysInMonth_, |
| 637 |
while resolved_day > i32::from(days_in_month) { |
| 638 |
// 1. Set _resolvedDay_ to _resolvedDay_ - _daysInMonth_. |
| 639 |
// 1. Set _resolvedMonth_ to _resolvedMonth_ + 1. |
| 640 |
// 1. If _resolvedMonth_ > _monthsInYear_, then |
| 641 |
resolved_day -= i32::from(days_in_month); |
| 642 |
resolved_month += 1; |
| 643 |
if resolved_month > months_in_year { |
| 644 |
// 1. Set _resolvedYear_ to _resolvedYear_ + 1. |
| 645 |
// 1. Set _monthsInYear_ to CalendarMonthsInYear(_calendar_, _resolvedYear_). |
| 646 |
// 1. Set _resolvedMonth_ to 1. |
| 647 |
resolved_year = |
| 648 |
cal.year_info_from_extended(cal.extended_from_year_info(resolved_year) + 1); |
| 649 |
months_in_year = C::months_in_provided_year(resolved_year); |
| 650 |
resolved_month = 1; |
| 651 |
} |
| 652 |
// 1. Set _daysInMonth_ to CalendarDaysInMonth(_calendar_, _resolvedYear_, _resolvedMonth_). |
| 653 |
days_in_month = C::days_in_provided_month(resolved_year, resolved_month); |
| 654 |
} |
| 655 |
debug_assert!(u8::try_from(resolved_day).is_ok()); |
| 656 |
let resolved_day = resolved_day as u8; |
| 657 |
// 1. Return the Record { [[Year]]: _resolvedYear_, [[Month]]: _resolvedMonth_, [[Day]]: _resolvedDay_ }. |
| 658 |
UncheckedArithmeticDate { |
| 659 |
year: resolved_year, |
| 660 |
ordinal_month: resolved_month, |
| 661 |
day: resolved_day, |
| 662 |
} |
| 663 |
} |
| 664 |
|
| 665 |
/// Implements the Temporal abstract operation `CompareSurpasses` based on month code |
| 666 |
#[allow(clippy::collapsible_if, clippy::collapsible_else_if)] // to match the spec |
| 667 |
fn compare_surpasses_lexicographic( |
| 668 |
sign: i32, |
| 669 |
year: C::YearInfo, |
| 670 |
month: Month, |
| 671 |
day: u8, |
| 672 |
target: &Self, |
| 673 |
cal: &C, |
| 674 |
) -> bool { |
| 675 |
// 1. If _year_ ≠ _target_.[[Year]], then |
| 676 |
// 1. If _sign_ × (_year_ - _target_.[[Year]]) > 0, return *true*. |
| 677 |
// 1. Else if _monthCode_ ≠ _target_.[[MonthCode]], then |
| 678 |
// 1. If _sign > 0, then |
| 679 |
// 1. If _monthCode_ is lexicographically greater than _target_.[[MonthCode]], return *true*. |
| 680 |
// 1. Else, |
| 681 |
// 1. If _target_.[[MonthCode]] is lexicographically greater than _monthCode_, return *true*. |
| 682 |
// (note: integer steps omitted) |
| 683 |
// 1. Else if _day_ ≠ _target_.[[Day]], then |
| 684 |
// 1. If _sign_ × (_day_ - _target_.[[Day]]) > 0, return *true*. |
| 685 |
if year != target.year() { |
| 686 |
if sign * (year - target.year()) > 0 { |
| 687 |
return true; |
| 688 |
} |
| 689 |
} else { |
| 690 |
let target_month = cal.month_from_ordinal(target.year(), target.month()); |
| 691 |
if month != target_month { |
| 692 |
if sign > 0 { |
| 693 |
if month > target_month { |
| 694 |
return true; |
| 695 |
} |
| 696 |
} else { |
| 697 |
if month <= target_month { |
| 698 |
return true; |
| 699 |
} |
| 700 |
} |
| 701 |
} else if day != target.day() { |
| 702 |
if sign * (i32::from(day) - i32::from(target.day())) > 0 { |
| 703 |
return true; |
| 704 |
} |
| 705 |
} |
| 706 |
} |
| 707 |
false |
| 708 |
} |
| 709 |
|
| 710 |
/// Implements the Temporal abstract operation `CompareSurpasses` based on month ordinal |
| 711 |
#[allow(clippy::collapsible_if, clippy::collapsible_else_if)] // to match the spec |
| 712 |
fn compare_surpasses_ordinal( |
| 713 |
sign: i32, |
| 714 |
year: C::YearInfo, |
| 715 |
month: u8, |
| 716 |
day: u8, |
| 717 |
target: &Self, |
| 718 |
) -> bool { |
| 719 |
// 1. If _year_ ≠ _target_.[[Year]], then |
| 720 |
// 1. If _sign_ × (_year_ - _target_.[[Year]]) > 0, return *true*. |
| 721 |
// (note: month code steps omitted) |
| 722 |
// 1. Else if _month_ ≠ _target_.[[Month]], then |
| 723 |
// 1. If _sign_ × (_month_ - _target_.[[Month]]) > 0, return *true*. |
| 724 |
// 1. Else if _day_ ≠ _target_.[[Day]], then |
| 725 |
// 1. If _sign_ × (_day_ - _target_.[[Day]]) > 0, return *true*. |
| 726 |
if year != target.year() { |
| 727 |
if sign * (year - target.year()) > 0 { |
| 728 |
return true; |
| 729 |
} |
| 730 |
} else if month != target.month() { |
| 731 |
if sign * (i32::from(month) - i32::from(target.month())) > 0 { |
| 732 |
return true; |
| 733 |
} |
| 734 |
} else if day != target.day() { |
| 735 |
if sign * (i32::from(day) - i32::from(target.day())) > 0 { |
| 736 |
return true; |
| 737 |
} |
| 738 |
} |
| 739 |
false |
| 740 |
} |
| 741 |
|
| 742 |
/// Implements the Temporal abstract operation `NonISODateSurpasses`. |
| 743 |
/// |
| 744 |
/// This takes two dates (`self` and `other`), `duration`, and `sign` (either -1 or 1), then |
| 745 |
/// returns whether adding the duration to `self` results in a year/month/day that exceeds |
| 746 |
/// `other` in the direction indicated by `sign`, constraining the month but not the day. |
| 747 |
/// |
| 748 |
/// Note: This function is no longer used, but the code is retained for |
| 749 |
/// reference. The `until()` implementation uses `SurpassesChecker`, which |
| 750 |
/// implements the same spec, but with better performance. |
| 751 |
#[allow(dead_code)] // TODO: remove surpasses() method when no longer needed |
| 752 |
pub(crate) fn surpasses( |
| 753 |
&self, |
| 754 |
other: &Self, |
| 755 |
duration: DateDuration, |
| 756 |
sign: i32, |
| 757 |
cal: &C, |
| 758 |
) -> bool { |
| 759 |
// 1. Let _parts_ be CalendarISOToDate(_calendar_, _fromIsoDate_). |
| 760 |
let parts = self; |
| 761 |
// 1. Let _calDate2_ be CalendarISOToDate(_calendar_, _toIsoDate_). |
| 762 |
let cal_date_2 = other; |
| 763 |
// 1. Let _y0_ be _parts_.[[Year]] + _years_. |
| 764 |
let y0 = cal.year_info_from_extended( |
| 765 |
duration.add_years_to(cal.extended_from_year_info(parts.year())), |
| 766 |
); |
| 767 |
// 1. If CompareSurpasses(_sign_, _y0_, _parts_.[[MonthCode]], _parts_.[[Day]], _calDate2_) is *true*, return *true*. |
| 768 |
let base_month = cal.month_from_ordinal(parts.year(), parts.month()); |
| 769 |
if Self::compare_surpasses_lexicographic(sign, y0, base_month, parts.day(), cal_date_2, cal) |
| 770 |
{ |
| 771 |
return true; |
| 772 |
} |
| 773 |
// 1. Let _m0_ be MonthCodeToOrdinal(_calendar_, _y0_, ! ConstrainMonthCode(_calendar_, _y0_, _parts_.[[MonthCode]], ~constrain~)). |
| 774 |
let m0_result = cal.ordinal_from_month(y0, base_month, Overflow::Constrain); |
| 775 |
let m0 = match m0_result { |
| 776 |
Ok(m0) => m0, |
| 777 |
Err(_) => { |
| 778 |
debug_assert!( |
| 779 |
false, |
| 780 |
"valid month code for calendar, and constrained to the year" |
| 781 |
); |
| 782 |
1 |
| 783 |
} |
| 784 |
}; |
| 785 |
// 1. Let _monthsAdded_ be BalanceNonISODate(_calendar_, _y0_, _m0_ + _months_, 1). |
| 786 |
let months_added = Self::new_balanced(y0, duration.add_months_to(m0), 1, cal); |
| 787 |
|
| 788 |
// 1. If CompareSurpasses(_sign_, _monthsAdded_.[[Year]], _monthsAdded_.[[Month]], _parts_.[[Day]], _calDate2_) is *true*, return *true*. |
| 789 |
if Self::compare_surpasses_ordinal( |
| 790 |
sign, |
| 791 |
months_added.year, |
| 792 |
months_added.ordinal_month, |
| 793 |
parts.day(), |
| 794 |
cal_date_2, |
| 795 |
) { |
| 796 |
return true; |
| 797 |
} |
| 798 |
// 1. If _weeks_ = 0 and _days_ = 0, return *false*. |
| 799 |
if duration.weeks == 0 && duration.days == 0 { |
| 800 |
return false; |
| 801 |
} |
| 802 |
// 1. Let _endOfMonth_ be BalanceNonISODate(_calendar_, _monthsAdded_.[[Year]], _monthsAdded_.[[Month]] + 1, 0). |
| 803 |
let end_of_month = Self::new_balanced( |
| 804 |
months_added.year, |
| 805 |
i32::from(months_added.ordinal_month + 1), |
| 806 |
0, |
| 807 |
cal, |
| 808 |
); |
| 809 |
// 1. Let _baseDay_ be _parts_.[[Day]]. |
| 810 |
let base_day = parts.day(); |
| 811 |
// 1. If _baseDay_ ≤ _endOfMonth_.[[Day]], then |
| 812 |
// 1. Let _regulatedDay_ be _baseDay_. |
| 813 |
// 1. Else, |
| 814 |
// 1. Let _regulatedDay_ be _endOfMonth_.[[Day]]. |
| 815 |
let regulated_day = if base_day < end_of_month.day { |
| 816 |
base_day |
| 817 |
} else { |
| 818 |
end_of_month.day |
| 819 |
}; |
| 820 |
// 1. Let _daysInWeek_ be 7 (the number of days in a week for all supported calendars). |
| 821 |
// 1. Let _balancedDate_ be BalanceNonISODate(_calendar_, _endOfMonth_.[[Year]], _endOfMonth_.[[Month]], _regulatedDay_ + _daysInWeek_ * _weeks_ + _days_). |
| 822 |
// 1. Return CompareSurpasses(_sign_, _balancedDate_.[[Year]], _balancedDate_.[[Month]], _balancedDate_.[[Day]], _calDate2_). |
| 823 |
let balanced_date = Self::new_balanced( |
| 824 |
end_of_month.year, |
| 825 |
i32::from(end_of_month.ordinal_month), |
| 826 |
duration.add_weeks_and_days_to(regulated_day), |
| 827 |
cal, |
| 828 |
); |
| 829 |
|
| 830 |
Self::compare_surpasses_ordinal( |
| 831 |
sign, |
| 832 |
balanced_date.year, |
| 833 |
balanced_date.ordinal_month, |
| 834 |
balanced_date.day, |
| 835 |
cal_date_2, |
| 836 |
) |
| 837 |
} |
| 838 |
|
| 839 |
/// Implements the Temporal abstract operation `NonISODateAdd`. |
| 840 |
/// |
| 841 |
/// This takes a date (`self`) and `duration`, then returns a new date resulting from |
| 842 |
/// adding `duration` to `self`, constrained according to `options`. |
| 843 |
pub(crate) fn added( |
| 844 |
&self, |
| 845 |
duration: DateDuration, |
| 846 |
cal: &C, |
| 847 |
options: DateAddOptions, |
| 848 |
) -> Result<Self, DateAddError> { |
| 849 |
// We preemptively protect ourselves from overly-large values |
| 850 |
// |
| 851 |
// This is mostly needed for avoiding overflows on Duration arithmetic, |
| 852 |
// this could also be handled by updating DateDuration::add_foo_to() |
| 853 |
// to return an error. However, that would lead to more error handling cluttering |
| 854 |
// surpasses(). |
| 855 |
|
| 856 |
if duration.years > GENEROUS_MAX_YEARS |
| 857 |
|| duration.months > GENEROUS_MAX_MONTHS |
| 858 |
|| duration |
| 859 |
.weeks |
| 860 |
.saturating_mul(7) |
| 861 |
.saturating_add(duration.days) |
| 862 |
> GENEROUS_MAX_DAYS |
| 863 |
{ |
| 864 |
return Err(DateAddError::Overflow); |
| 865 |
} |
| 866 |
|
| 867 |
// DateAddOptions documents the default as constrain |
| 868 |
let overflow = options.overflow.unwrap_or(Overflow::Constrain); |
| 869 |
|
| 870 |
// 1. Let _parts_ be CalendarISOToDate(_calendar_, _isoDate_). |
| 871 |
// 1. Let _y0_ be _parts_.[[Year]] + _duration_.[[Years]]. |
| 872 |
let extended_year = duration.add_years_to(cal.extended_from_year_info(self.year())); |
| 873 |
if !GENEROUS_YEAR_RANGE.contains(&extended_year) { |
| 874 |
return Err(DateAddError::Overflow); |
| 875 |
} |
| 876 |
let y0 = cal.year_info_from_extended(extended_year); |
| 877 |
// 1. Let _m0_ be MonthCodeToOrdinal(_calendar_, _y0_, ! ConstrainMonthCode(_calendar_, _y0_, _parts_.[[MonthCode]], _overflow_)). |
| 878 |
let base_month = cal.month_from_ordinal(self.year(), self.month()); |
| 879 |
let m0_result = cal.ordinal_from_month(y0, base_month, overflow); |
| 880 |
let m0 = match m0_result { |
| 881 |
Ok(m0) => m0, |
| 882 |
Err(MonthError::NotInCalendar) => { |
| 883 |
debug_assert!( |
| 884 |
false, |
| 885 |
"Should never get NotInCalendar when performing arithmetic" |
| 886 |
); |
| 887 |
return Err(DateAddError::MonthNotInYear); |
| 888 |
} |
| 889 |
Err(MonthError::NotInYear) => return Err(DateAddError::MonthNotInYear), |
| 890 |
}; |
| 891 |
// 1. Let _endOfMonth_ be BalanceNonISODate(_calendar_, _y0_, _m0_ + _duration_.[[Months]] + 1, 0). |
| 892 |
let end_of_month = Self::new_balanced(y0, duration.add_months_to(m0) + 1, 0, cal); |
| 893 |
// 1. Let _baseDay_ be _parts_.[[Day]]. |
| 894 |
let base_day = self.day(); |
| 895 |
// 1. If _baseDay_ ≤ _endOfMonth_.[[Day]], then |
| 896 |
// 1. Let _regulatedDay_ be _baseDay_. |
| 897 |
let regulated_day = if base_day <= end_of_month.day { |
| 898 |
base_day |
| 899 |
} else { |
| 900 |
// 1. Else, |
| 901 |
// 1. If _overflow_ is ~reject~, throw a *RangeError* exception. |
| 902 |
// Note: ICU4X default is constrain here |
| 903 |
if overflow == Overflow::Reject { |
| 904 |
return Err(DateAddError::InvalidDay { |
| 905 |
max: end_of_month.day, |
| 906 |
}); |
| 907 |
} |
| 908 |
end_of_month.day |
| 909 |
}; |
| 910 |
|
| 911 |
// 1. Let _balancedDate_ be BalanceNonISODate(_calendar_, _endOfMonth_.[[Year]], _endOfMonth_.[[Month]], _regulatedDay_ + 7 * _duration_.[[Weeks]] + _duration_.[[Days]]). |
| 912 |
// 1. Let _result_ be ? CalendarIntegersToISO(_calendar_, _balancedDate_.[[Year]], _balancedDate_.[[Month]], _balancedDate_.[[Day]]). |
| 913 |
// 1. Return _result_. |
| 914 |
let balanced = Self::new_balanced( |
| 915 |
end_of_month.year, |
| 916 |
i32::from(end_of_month.ordinal_month), |
| 917 |
duration.add_weeks_and_days_to(regulated_day), |
| 918 |
cal, |
| 919 |
); |
| 920 |
|
| 921 |
balanced.into_checked().ok_or(DateAddError::Overflow) |
| 922 |
} |
| 923 |
|
| 924 |
/// Implements the Temporal abstract operation `NonISODateUntil`. |
| 925 |
/// |
| 926 |
/// This takes two dates (`self` and `other`), then returns a duration that, when |
| 927 |
/// added to `self`, results in `other`, with largest unit according to `options`. |
| 928 |
pub(crate) fn until( |
| 929 |
&self, |
| 930 |
other: &Self, |
| 931 |
cal: &C, |
| 932 |
options: DateDifferenceOptions, |
| 933 |
) -> DateDuration { |
| 934 |
// Non-spec optimization: fast path for day/week diffs |
| 935 |
// Avoids quadratic behavior in surpasses() for days/weeks |
| 936 |
if matches!( |
| 937 |
options.largest_unit, |
| 938 |
Some(DateDurationUnit::Days) | Some(DateDurationUnit::Weeks) |
| 939 |
) { |
| 940 |
let from = self.to_rata_die(); |
| 941 |
let to = other.to_rata_die(); |
| 942 |
let diff = to - from; |
| 943 |
let diff = match i32::try_from(diff) { |
| 944 |
Ok(d) => d, |
| 945 |
Err(_) => { |
| 946 |
debug_assert!(false, "rata die diff out of i32 range"); |
| 947 |
if diff > 0 { i32::MAX } else { i32::MIN } |
| 948 |
} |
| 949 |
}; |
| 950 |
if matches!(options.largest_unit, Some(DateDurationUnit::Weeks)) { |
| 951 |
return DateDuration::for_weeks_and_days(diff); |
| 952 |
} else { |
| 953 |
return DateDuration::for_days(diff); |
| 954 |
} |
| 955 |
} |
| 956 |
|
| 957 |
// 1. Let sign be -1 × CompareISODate(one, two). |
| 958 |
// 2. If sign = 0, return ZeroDateDuration(). |
| 959 |
let sign = match other.cmp(self) { |
| 960 |
Ordering::Greater => 1, |
| 961 |
Ordering::Equal => return DateDuration::default(), |
| 962 |
Ordering::Less => -1, |
| 963 |
}; |
| 964 |
|
| 965 |
// Non-spec optimization: Instead of calling a stateless |
| 966 |
// NonISODateSurpasses implementation that repeatedly recomputes many |
| 967 |
// values, we use a stateful implementation. It caches intermediate |
| 968 |
// produced by NonISODateSurpasses and reuses them in subsequent calls, |
| 969 |
// to avoid unnecessary recalculations. |
| 970 |
let mut surpasses_checker: SurpassesChecker<'_, C> = |
| 971 |
SurpassesChecker::new(self, other, sign, cal); |
| 972 |
|
| 973 |
// Preparation for non-specced optimization: |
| 974 |
// We don't want to spend time incrementally bumping it up one year |
| 975 |
// at a time, so let's pre-guess a year delta that is guaranteed to not |
| 976 |
// surpass. |
| 977 |
let year_diff = other.year() - self.year(); |
| 978 |
let min_years = if year_diff == 0 { 0 } else { year_diff - sign }; |
| 979 |
|
| 980 |
// clippy rejects: debug_assert!(!surpasses_checker.surpasses_months(min_months)); |
| 981 |
#[cfg(debug_assertions)] |
| 982 |
{ |
| 983 |
let mut debug_checker = SurpassesChecker::new(self, other, sign, cal); |
| 984 |
let min_years_valid = !debug_checker.surpasses_years(min_years); |
| 985 |
debug_assert!(min_years_valid); |
| 986 |
} |
| 987 |
|
| 988 |
// 3. Let years be 0. |
| 989 |
// 4. If largestUnit is year, then |
| 990 |
// a. Let candidateYears be sign. |
| 991 |
// b. Repeat, while NonISODateSurpasses(calendar, sign, one, two, candidateYears, 0, 0, 0) is false, |
| 992 |
// i. Set years to candidateYears. |
| 993 |
// ii. Set candidateYears to candidateYears + sign. |
| 994 |
let mut years = 0; |
| 995 |
if matches!(options.largest_unit, Some(DateDurationUnit::Years)) { |
| 996 |
let mut candidate_years = sign; |
| 997 |
|
| 998 |
// Non-spec optimization: try to fast-forward candidate_years to |
| 999 |
// a year value that does not surpass |
| 1000 |
if min_years != 0 { |
| 1001 |
candidate_years = min_years |
| 1002 |
}; |
| 1003 |
|
| 1004 |
while !surpasses_checker.surpasses_years(candidate_years) { |
| 1005 |
years = candidate_years; |
| 1006 |
candidate_years += sign; |
| 1007 |
} |
| 1008 |
} |
| 1009 |
// Freeze the checker's Years field state. |
| 1010 |
surpasses_checker.set_years(years); |
| 1011 |
|
| 1012 |
// 5. Let months be 0. |
| 1013 |
// 6. If largestUnit is year or largestUnit is month, then |
| 1014 |
// a. Let candidateMonths be sign. |
| 1015 |
// b. Repeat, while NonISODateSurpasses(calendar, sign, one, two, years, candidateMonths, 0, 0) is false, |
| 1016 |
// i. Set months to candidateMonths. |
| 1017 |
// ii. Set candidateMonths to candidateMonths + sign. |
| 1018 |
let mut months = 0; |
| 1019 |
if matches!( |
| 1020 |
options.largest_unit, |
| 1021 |
Some(DateDurationUnit::Years) | Some(DateDurationUnit::Months) |
| 1022 |
) { |
| 1023 |
let mut candidate_months = sign; |
| 1024 |
|
| 1025 |
// Non-spec optimization: try to fast-forward candidate_months to |
| 1026 |
// a month value that does not surpass |
| 1027 |
if options.largest_unit == Some(DateDurationUnit::Months) && min_years != 0 { |
| 1028 |
// If largest_unit = Months, then compute the calendar-specific minimum number of |
| 1029 |
// months corresponding to min_years. |
| 1030 |
let min_months = C::min_months_from(self.year(), min_years); |
| 1031 |
// clippy rejects: debug_assert!(!surpasses_checker.surpasses_months(min_months)); |
| 1032 |
#[cfg(debug_assertions)] |
| 1033 |
{ |
| 1034 |
let mut debug_checker = SurpassesChecker::new(self, other, sign, cal); |
| 1035 |
debug_checker.surpasses_years(years); |
| 1036 |
let min_months_valid = !debug_checker.surpasses_months(min_months); |
| 1037 |
debug_assert!(min_months_valid); |
| 1038 |
} |
| 1039 |
candidate_months = min_months |
| 1040 |
} |
| 1041 |
|
| 1042 |
while !surpasses_checker.surpasses_months(candidate_months) { |
| 1043 |
months = candidate_months; |
| 1044 |
candidate_months += sign; |
| 1045 |
} |
| 1046 |
} |
| 1047 |
// Freeze the checker's Months field state. |
| 1048 |
surpasses_checker.set_months(months); |
| 1049 |
|
| 1050 |
// 7. Let weeks be 0. |
| 1051 |
// 8. If largestUnit is week, then |
| 1052 |
// a. Let candidateWeeks be sign. |
| 1053 |
// b. Repeat, while NonISODateSurpasses(calendar, sign, one, two, years, months, candidateWeeks, 0) is false, |
| 1054 |
// i. Set weeks to candidateWeeks. |
| 1055 |
// ii. Set candidateWeeks to candidateWeeks + sign. |
| 1056 |
let mut weeks = 0; |
| 1057 |
if matches!(options.largest_unit, Some(DateDurationUnit::Weeks)) { |
| 1058 |
let mut candidate_weeks = sign; |
| 1059 |
while !surpasses_checker.surpasses_weeks(candidate_weeks) { |
| 1060 |
weeks = candidate_weeks; |
| 1061 |
candidate_weeks += sign; |
| 1062 |
} |
| 1063 |
} |
| 1064 |
// Freeze the checker's Weeks field state. |
| 1065 |
surpasses_checker.set_weeks(weeks); |
| 1066 |
|
| 1067 |
// 9. Let days be 0. |
| 1068 |
// 10. Let candidateDays be sign. |
| 1069 |
// 11. Repeat, while NonISODateSurpasses(calendar, sign, one, two, years, months, weeks, candidateDays) is false, |
| 1070 |
// a. Set days to candidateDays. |
| 1071 |
// b. Set candidateDays to candidateDays + sign. |
| 1072 |
let mut days = 0; |
| 1073 |
// There is no pressing need to optimize candidate_days here: the early-return RD arithmetic |
| 1074 |
// optimization will be hit if the largest_unit is weeks/days, and if it is months or years we will |
| 1075 |
// arrive here with a candidate date that is at most 31 days off. We can run this loop 31 times. |
| 1076 |
let mut candidate_days = sign; |
| 1077 |
while !surpasses_checker.surpasses_days(candidate_days) { |
| 1078 |
days = candidate_days; |
| 1079 |
candidate_days += sign; |
| 1080 |
} |
| 1081 |
|
| 1082 |
// 12. Return ! CreateDateDurationRecord(years, months, weeks, days). |
| 1083 |
DateDuration::from_signed_ymwd(years, months, weeks, days) |
| 1084 |
} |
| 1085 |
} |
| 1086 |
|
| 1087 |
/// Stateful checker for iterative per-field `surpasses()` checks |
| 1088 |
/// |
| 1089 |
/// This checker for `surpasses()` is designed to iteratively evaluate one field |
| 1090 |
/// at a time, from largest to smallest. After each field value is determined, |
| 1091 |
/// the caller must cache the computed state of the field's value by calling |
| 1092 |
/// `set_<field>(<field_value>)` before moving on to the next smaller field. |
| 1093 |
struct SurpassesChecker<'a, C: DateFieldsResolver> { |
| 1094 |
parts: &'a ArithmeticDate<C>, |
| 1095 |
cal_date_2: &'a ArithmeticDate<C>, |
| 1096 |
sign: i32, |
| 1097 |
cal: &'a C, |
| 1098 |
y0: <C as DateFieldsResolver>::YearInfo, |
| 1099 |
m0: u8, |
| 1100 |
end_of_month: UncheckedArithmeticDate<C>, |
| 1101 |
regulated_day: u8, |
| 1102 |
weeks: i32, |
| 1103 |
} |
| 1104 |
|
| 1105 |
impl<'a, C: DateFieldsResolver> SurpassesChecker<'a, C> { |
| 1106 |
fn new( |
| 1107 |
parts: &'a ArithmeticDate<C>, |
| 1108 |
cal_date_2: &'a ArithmeticDate<C>, |
| 1109 |
sign: i32, |
| 1110 |
cal: &'a C, |
| 1111 |
) -> Self { |
| 1112 |
Self { |
| 1113 |
parts, |
| 1114 |
cal_date_2, |
| 1115 |
sign, |
| 1116 |
cal, |
| 1117 |
y0: cal.year_info_from_extended(0), |
| 1118 |
m0: 0, |
| 1119 |
end_of_month: UncheckedArithmeticDate { |
| 1120 |
year: cal.year_info_from_extended(0), |
| 1121 |
ordinal_month: 0, |
| 1122 |
day: 0, |
| 1123 |
}, |
| 1124 |
regulated_day: 0, |
| 1125 |
weeks: 0, |
| 1126 |
} |
| 1127 |
} |
| 1128 |
|
| 1129 |
// NOTE: Numbered comments refer to the Temporal `NonISODateSurpasses` |
| 1130 |
// spec. A design goal of this code is to mirror the spec as closely as |
| 1131 |
// possible. This dictates the names of variables and the sequence of |
| 1132 |
// operations. |
| 1133 |
|
| 1134 |
fn surpasses_years(&mut self, years: i32) -> bool { |
| 1135 |
// 1. Let parts be CalendarISOToDate(calendar, fromIsoDate). |
| 1136 |
// 2. Let calDate2 be CalendarISOToDate(calendar, toIsoDate). |
| 1137 |
// 3. Let y0 be parts.[[Year]] + years. |
| 1138 |
self.y0 = self |
| 1139 |
.cal |
| 1140 |
.year_info_from_extended(self.cal.extended_from_year_info(self.parts.year()) + years); |
| 1141 |
// 4. If CompareSurpasses(sign, y0, parts.[[MonthCode]], parts.[[Day]], calDate2) is true, return true. |
| 1142 |
let base_month = self |
| 1143 |
.cal |
| 1144 |
.month_from_ordinal(self.parts.year(), self.parts.month()); |
| 1145 |
let surpasses_years = ArithmeticDate::<C>::compare_surpasses_lexicographic( |
| 1146 |
self.sign, |
| 1147 |
self.y0, |
| 1148 |
base_month, |
| 1149 |
self.parts.day(), |
| 1150 |
self.cal_date_2, |
| 1151 |
self.cal, |
| 1152 |
); |
| 1153 |
// 5. Let m0 be MonthCodeToOrdinal(calendar, y0, ! ConstrainMonthCode(calendar, y0, parts.[[MonthCode]], constrain)). |
| 1154 |
|
| 1155 |
let m0_result = self |
| 1156 |
.cal |
| 1157 |
.ordinal_from_month(self.y0, base_month, Overflow::Constrain); |
| 1158 |
self.m0 = match m0_result { |
| 1159 |
Ok(m0) => m0, |
| 1160 |
Err(_) => { |
| 1161 |
debug_assert!( |
| 1162 |
false, |
| 1163 |
"valid month code for calendar, and constrained to the year" |
| 1164 |
); |
| 1165 |
1 |
| 1166 |
} |
| 1167 |
}; |
| 1168 |
|
| 1169 |
// If the lexicographic check returns false, the spec continues to the |
| 1170 |
// ordinal check, which is implemented in `surpasses_months`. |
| 1171 |
surpasses_years || self.surpasses_months(0) |
| 1172 |
} |
| 1173 |
|
| 1174 |
#[inline] |
| 1175 |
fn set_years(&mut self, years: i32) { |
| 1176 |
self.surpasses_years(years); |
| 1177 |
} |
| 1178 |
|
| 1179 |
fn surpasses_months(&mut self, months: i32) -> bool { |
| 1180 |
// 6. Let monthsAdded be BalanceNonISODate(calendar, y0, m0 + months, 1). |
| 1181 |
let months_added = |
| 1182 |
ArithmeticDate::<C>::new_balanced(self.y0, months + i32::from(self.m0), 1, self.cal); |
| 1183 |
|
| 1184 |
// 7. If CompareSurpasses(sign, monthsAdded.[[Year]], monthsAdded.[[Month]], parts.[[Day]], calDate2) is true, return true. |
| 1185 |
// We do not need to perform any other checks because step 8 of the spec |
| 1186 |
// guarantees an early return if weeks and days are 0. |
| 1187 |
ArithmeticDate::<C>::compare_surpasses_ordinal( |
| 1188 |
self.sign, |
| 1189 |
months_added.year, |
| 1190 |
months_added.ordinal_month, |
| 1191 |
self.parts.day(), |
| 1192 |
self.cal_date_2, |
| 1193 |
) |
| 1194 |
} |
| 1195 |
|
| 1196 |
fn set_months(&mut self, months: i32) { |
| 1197 |
// 6. Let monthsAdded be BalanceNonISODate(calendar, y0, m0 + months, 1). |
| 1198 |
let months_added = |
| 1199 |
ArithmeticDate::<C>::new_balanced(self.y0, months + i32::from(self.m0), 1, self.cal); |
| 1200 |
|
| 1201 |
// 9. Let endOfMonth be BalanceNonISODate(calendar, monthsAdded.[[Year]], monthsAdded.[[Month]] + 1, 0). |
| 1202 |
self.end_of_month = ArithmeticDate::<C>::new_balanced( |
| 1203 |
months_added.year, |
| 1204 |
i32::from(months_added.ordinal_month) + 1, |
| 1205 |
0, |
| 1206 |
self.cal, |
| 1207 |
); |
| 1208 |
// 10. Let baseDay be parts.[[Day]]. |
| 1209 |
let base_day = self.parts.day(); |
| 1210 |
// 11. If baseDay ≤ endOfMonth.[[Day]], then |
| 1211 |
// a. Let regulatedDay be baseDay. |
| 1212 |
// 12. Else, |
| 1213 |
// a. Let regulatedDay be endOfMonth.[[Day]]. |
| 1214 |
self.regulated_day = if base_day < self.end_of_month.day { |
| 1215 |
base_day |
| 1216 |
} else { |
| 1217 |
self.end_of_month.day |
| 1218 |
}; |
| 1219 |
} |
| 1220 |
|
| 1221 |
fn surpasses_weeks(&mut self, weeks: i32) -> bool { |
| 1222 |
// 8. If weeks = 0 (*and days = 0*), return false. |
| 1223 |
if weeks == 0 { |
| 1224 |
return false; |
| 1225 |
} |
| 1226 |
|
| 1227 |
// 13. Let daysInWeek be 7 (the number of days in a week for all supported calendars). |
| 1228 |
// 14. Let balancedDate be BalanceNonISODate(calendar, endOfMonth.[[Year]], endOfMonth.[[Month]], regulatedDay + daysInWeek * weeks + days). |
| 1229 |
// 15. Return CompareSurpasses(sign, balancedDate.[[Year]], balancedDate.[[Month]], balancedDate.[[Day]], calDate2). |
| 1230 |
let balanced_date = ArithmeticDate::<C>::new_balanced( |
| 1231 |
self.end_of_month.year, |
| 1232 |
i32::from(self.end_of_month.ordinal_month), |
| 1233 |
7 * weeks + i32::from(self.regulated_day), |
| 1234 |
self.cal, |
| 1235 |
); |
| 1236 |
|
| 1237 |
self.weeks = weeks; |
| 1238 |
|
| 1239 |
ArithmeticDate::<C>::compare_surpasses_ordinal( |
| 1240 |
self.sign, |
| 1241 |
balanced_date.year, |
| 1242 |
balanced_date.ordinal_month, |
| 1243 |
balanced_date.day, |
| 1244 |
self.cal_date_2, |
| 1245 |
) |
| 1246 |
} |
| 1247 |
|
| 1248 |
#[inline] |
| 1249 |
fn set_weeks(&mut self, weeks: i32) { |
| 1250 |
self.surpasses_weeks(weeks); |
| 1251 |
} |
| 1252 |
|
| 1253 |
fn surpasses_days(&mut self, days: i32) -> bool { |
| 1254 |
// 8. If weeks = 0 and days = 0, return false. |
| 1255 |
if self.weeks == 0 && days == 0 { |
| 1256 |
return false; |
| 1257 |
} |
| 1258 |
|
| 1259 |
// 13. Let daysInWeek be 7 (the number of days in a week for all supported calendars). |
| 1260 |
// 14. Let balancedDate be BalanceNonISODate(calendar, endOfMonth.[[Year]], endOfMonth.[[Month]], regulatedDay + daysInWeek * weeks + days). |
| 1261 |
// 15. Return CompareSurpasses(sign, balancedDate.[[Year]], balancedDate.[[Month]], balancedDate.[[Day]], calDate2). |
| 1262 |
let balanced_date = ArithmeticDate::<C>::new_balanced( |
| 1263 |
self.end_of_month.year, |
| 1264 |
i32::from(self.end_of_month.ordinal_month), |
| 1265 |
7 * self.weeks + days + i32::from(self.regulated_day), |
| 1266 |
self.cal, |
| 1267 |
); |
| 1268 |
|
| 1269 |
ArithmeticDate::<C>::compare_surpasses_ordinal( |
| 1270 |
self.sign, |
| 1271 |
balanced_date.year, |
| 1272 |
balanced_date.ordinal_month, |
| 1273 |
balanced_date.day, |
| 1274 |
self.cal_date_2, |
| 1275 |
) |
| 1276 |
} |
| 1277 |
} |
| 1278 |
|
| 1279 |
#[cfg(test)] |
| 1280 |
mod tests { |
| 1281 |
use super::*; |
| 1282 |
use crate::{ |
| 1283 |
Date, |
| 1284 |
cal::{coptic::CopticYear, *}, |
| 1285 |
}; |
| 1286 |
|
| 1287 |
#[test] |
| 1288 |
fn test_ord() { |
| 1289 |
let new_coptic = |coptic_year, month, day| { |
| 1290 |
ArithmeticDate::<Coptic>::new_unchecked( |
| 1291 |
CopticYear::from_coptic_anno_martyrum_year(coptic_year), |
| 1292 |
month, |
| 1293 |
day, |
| 1294 |
) |
| 1295 |
}; |
| 1296 |
let dates_in_order = [ |
| 1297 |
new_coptic(-10, 1, 1), |
| 1298 |
new_coptic(-10, 1, 2), |
| 1299 |
new_coptic(-10, 2, 1), |
| 1300 |
new_coptic(-1, 1, 1), |
| 1301 |
new_coptic(-1, 1, 2), |
| 1302 |
new_coptic(-1, 2, 1), |
| 1303 |
new_coptic(0, 1, 1), |
| 1304 |
new_coptic(0, 1, 2), |
| 1305 |
new_coptic(0, 2, 1), |
| 1306 |
new_coptic(1, 1, 1), |
| 1307 |
new_coptic(1, 1, 2), |
| 1308 |
new_coptic(1, 2, 1), |
| 1309 |
new_coptic(10, 1, 1), |
| 1310 |
new_coptic(10, 1, 2), |
| 1311 |
new_coptic(10, 2, 1), |
| 1312 |
]; |
| 1313 |
for (i, i_date) in dates_in_order.iter().enumerate() { |
| 1314 |
for (j, j_date) in dates_in_order.iter().enumerate() { |
| 1315 |
let result1 = i_date.cmp(j_date); |
| 1316 |
let result2 = j_date.cmp(i_date); |
| 1317 |
assert_eq!(result1.reverse(), result2); |
| 1318 |
assert_eq!(i.cmp(&j), i_date.cmp(j_date)); |
| 1319 |
} |
| 1320 |
} |
| 1321 |
} |
| 1322 |
|
| 1323 |
#[test] |
| 1324 |
pub fn zero() { |
| 1325 |
use crate::Date; |
| 1326 |
Date::try_new_iso(2024, 0, 1).unwrap_err(); |
| 1327 |
Date::try_new_iso(2024, 1, 0).unwrap_err(); |
| 1328 |
Date::try_new_iso(2024, 0, 0).unwrap_err(); |
| 1329 |
} |
| 1330 |
|
| 1331 |
#[test] |
| 1332 |
fn test_validity_ranges() { |
| 1333 |
#[rustfmt::skip] |
| 1334 |
let lowest_years = [ |
| 1335 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Buddhist).year().extended_year(), |
| 1336 |
Date::from_rata_die(*VALID_RD_RANGE.start(), ChineseTraditional::new()).year().extended_year(), |
| 1337 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Coptic).year().extended_year(), |
| 1338 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Ethiopian::new_with_era_style(EthiopianEraStyle::AmeteAlem)).year().extended_year(), |
| 1339 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Ethiopian::new_with_era_style(EthiopianEraStyle::AmeteMihret)).year().extended_year(), |
| 1340 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Gregorian).year().extended_year(), |
| 1341 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Hebrew).year().extended_year(), |
| 1342 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Hijri::new_umm_al_qura()).year().extended_year(), |
| 1343 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Hijri::new_tabular(HijriTabularLeapYears::TypeII, HijriTabularEpoch::Thursday)).year().extended_year(), |
| 1344 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Indian).year().extended_year(), |
| 1345 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Iso).year().extended_year(), |
| 1346 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Japanese::new()).year().extended_year(), |
| 1347 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Julian).year().extended_year(), |
| 1348 |
Date::from_rata_die(*VALID_RD_RANGE.start(), KoreanTraditional::new()).year().extended_year(), |
| 1349 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Persian).year().extended_year(), |
| 1350 |
Date::from_rata_die(*VALID_RD_RANGE.start(), Roc).year().extended_year(), |
| 1351 |
]; |
| 1352 |
|
| 1353 |
#[rustfmt::skip] |
| 1354 |
let highest_years = [ |
| 1355 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Buddhist).year().extended_year(), |
| 1356 |
Date::from_rata_die(*VALID_RD_RANGE.end(), ChineseTraditional::new()).year().extended_year(), |
| 1357 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Coptic).year().extended_year(), |
| 1358 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Ethiopian::new_with_era_style(EthiopianEraStyle::AmeteAlem)).year().extended_year(), |
| 1359 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Ethiopian::new_with_era_style(EthiopianEraStyle::AmeteMihret)).year().extended_year(), |
| 1360 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Gregorian).year().extended_year(), |
| 1361 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Hebrew).year().extended_year(), |
| 1362 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Hijri::new_umm_al_qura()).year().extended_year(), |
| 1363 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Hijri::new_tabular(HijriTabularLeapYears::TypeII, HijriTabularEpoch::Thursday)).year().extended_year(), |
| 1364 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Indian).year().extended_year(), |
| 1365 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Iso).year().extended_year(), |
| 1366 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Japanese::new()).year().extended_year(), |
| 1367 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Julian).year().extended_year(), |
| 1368 |
Date::from_rata_die(*VALID_RD_RANGE.end(), KoreanTraditional::new()).year().extended_year(), |
| 1369 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Persian).year().extended_year(), |
| 1370 |
Date::from_rata_die(*VALID_RD_RANGE.end(), Roc).year().extended_year(), |
| 1371 |
]; |
| 1372 |
|
| 1373 |
// Valid RDs can represent all valid years |
| 1374 |
assert!( |
| 1375 |
lowest_years |
| 1376 |
.iter() |
| 1377 |
.all(|y| y <= CONSTRUCTOR_YEAR_RANGE.start()) |
| 1378 |
); |
| 1379 |
assert!( |
| 1380 |
highest_years |
| 1381 |
.iter() |
| 1382 |
.all(|y| y >= CONSTRUCTOR_YEAR_RANGE.end()) |
| 1383 |
); |
| 1384 |
|
| 1385 |
// All years are 21-bits |
| 1386 |
assert!(-lowest_years.iter().copied().min().unwrap() < 1 << 20); |
| 1387 |
assert!(highest_years.iter().copied().max().unwrap() < 1 << 20); |
| 1388 |
} |
| 1389 |
|
| 1390 |
#[test] |
| 1391 |
fn test_from_fields_consistent_years() { |
| 1392 |
let fields = DateFields { |
| 1393 |
extended_year: Some(0), |
| 1394 |
era_year: Some(0), |
| 1395 |
era: Some(b"be"), |
| 1396 |
ordinal_month: Some(1), |
| 1397 |
day: Some(1), |
| 1398 |
..Default::default() |
| 1399 |
}; |
| 1400 |
|
| 1401 |
let date = Date::try_from_fields(fields, Default::default(), Buddhist).unwrap(); |
| 1402 |
assert_eq!(date.year().extended_year(), 0); |
| 1403 |
} |
| 1404 |
} |