Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@ use crate::offset::Local;
use crate::offset::{FixedOffset, Offset, TimeZone, Utc};
#[cfg(any(feature = "clock", feature = "std"))]
use crate::OutOfRange;
use crate::{try_err, try_ok_or};
use crate::{Datelike, Error, Months, TimeDelta, Timelike, Weekday};
use crate::{try_err, try_ok_or, Datelike, Error, Months, TimeDelta, Timelike, Weekday};

#[cfg(any(feature = "rkyv", feature = "rkyv-16", feature = "rkyv-32", feature = "rkyv-64"))]
use rkyv::{Archive, Deserialize, Serialize};
Expand Down Expand Up @@ -396,9 +395,10 @@ impl<Tz: TimeZone> DateTime<Tz> {
// `NaiveDate::add_days` has a fast path if the result remains within the same year, that
// does not validate the resulting date. This allows us to return `Some` even for an out of
// range local datetime when adding `Days(0)`.
self.overflowing_naive_local()
.checked_add_days(days)
.and_then(|dt| self.timezone().from_local_datetime(&dt).single())
let naive = self.overflowing_naive_local().checked_add_days(days).ok()?;
self.timezone()
.from_local_datetime(&naive)
.single()
.filter(|dt| dt <= &DateTime::<Utc>::MAX_UTC)
}

Expand All @@ -416,9 +416,10 @@ impl<Tz: TimeZone> DateTime<Tz> {
// `NaiveDate::add_days` has a fast path if the result remains within the same year, that
// does not validate the resulting date. This allows us to return `Some` even for an out of
// range local datetime when adding `Days(0)`.
self.overflowing_naive_local()
.checked_sub_days(days)
.and_then(|dt| self.timezone().from_local_datetime(&dt).single())
let naive = self.overflowing_naive_local().checked_sub_days(days).ok()?;
self.timezone()
.from_local_datetime(&naive)
.single()
.filter(|dt| dt >= &DateTime::<Utc>::MIN_UTC)
}

Expand Down
64 changes: 29 additions & 35 deletions src/naive/date/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -557,89 +557,83 @@ impl NaiveDate {
///
/// # Errors
///
/// Returns `None` if the resulting date would be out of range.
/// Returns [`Error::OutOfRange`] if the resulting date would be out of range.
///
/// # Example
///
/// ```
/// # use chrono::{NaiveDate, Days};
/// assert_eq!(
/// NaiveDate::from_ymd(2022, 2, 20).unwrap().checked_add_days(Days::new(9)),
/// Some(NaiveDate::from_ymd(2022, 3, 1).unwrap())
/// );
/// # use chrono::{NaiveDate, Days, Error};
/// assert_eq!(
/// NaiveDate::from_ymd(2022, 7, 31).unwrap().checked_add_days(Days::new(2)),
/// Some(NaiveDate::from_ymd(2022, 8, 2).unwrap())
/// NaiveDate::from_ymd(2022, 2, 20)?.checked_add_days(Days::new(9)),
/// NaiveDate::from_ymd(2022, 3, 1)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like a more interesting example 👍.

/// );
/// assert_eq!(
/// NaiveDate::from_ymd(2022, 7, 31).unwrap().checked_add_days(Days::new(1000000000000)),
/// None
/// NaiveDate::from_ymd(2022, 7, 31)?.checked_add_days(Days::new(1000000000000)),
/// Err(Error::OutOfRange)
/// );
/// # Ok::<(), Error>(())
/// ```
#[must_use]
pub const fn checked_add_days(self, days: Days) -> Option<Self> {
pub const fn checked_add_days(self, days: Days) -> Result<Self, Error> {
match days.0 <= i32::MAX as u64 {
true => self.add_days(days.0 as i32),
false => None,
false => Err(Error::OutOfRange),
}
}

/// Subtract a duration in [`Days`] from the date
///
/// # Errors
///
/// Returns `None` if the resulting date would be out of range.
/// Returns [`Error::OutOfRange`] if the resulting date would be out of range.
///
/// # Example
///
/// ```
/// # use chrono::{NaiveDate, Days};
/// # use chrono::{NaiveDate, Days, Error};
/// assert_eq!(
/// NaiveDate::from_ymd(2022, 2, 20).unwrap().checked_sub_days(Days::new(6)),
/// Some(NaiveDate::from_ymd(2022, 2, 14).unwrap())
/// NaiveDate::from_ymd(2022, 2, 20)?.checked_sub_days(Days::new(6)),
/// NaiveDate::from_ymd(2022, 2, 14)
/// );
/// assert_eq!(
/// NaiveDate::from_ymd(2022, 2, 20).unwrap().checked_sub_days(Days::new(1000000000000)),
/// None
/// NaiveDate::from_ymd(2022, 2, 20)?.checked_sub_days(Days::new(1000000000000)),
/// Err(Error::OutOfRange)
/// );
/// # Ok::<(), Error>(())
/// ```
#[must_use]
pub const fn checked_sub_days(self, days: Days) -> Option<Self> {
pub const fn checked_sub_days(self, days: Days) -> Result<Self, Error> {
match days.0 <= i32::MAX as u64 {
true => self.add_days(-(days.0 as i32)),
false => None,
false => Err(Error::OutOfRange),
}
}

/// Add a duration of `i32` days to the date.
pub(crate) const fn add_days(self, days: i32) -> Option<Self> {
pub(crate) const fn add_days(self, days: i32) -> Result<Self, Error> {
// Fast path if the result is within the same year.
// Also `DateTime::checked_(add|sub)_days` relies on this path, because if the value remains
// within the year it doesn't do a check if the year is in range.
// This way `DateTime:checked_(add|sub)_days(Days::new(0))` can be a no-op on dates were the
// local datetime is beyond `NaiveDate::{MIN, MAX}.
const ORDINAL_MASK: i32 = 0b1_1111_1111_0000;
if let Some(ordinal) = ((self.yof() & ORDINAL_MASK) >> 4).checked_add(days) {
let ordinal =
try_ok_or!(((self.yof() & ORDINAL_MASK) >> 4).checked_add(days), Error::OutOfRange);
{
if ordinal > 0 && ordinal <= (365 + self.leap_year() as i32) {
let year_and_flags = self.yof() & !ORDINAL_MASK;
return Some(NaiveDate::from_yof(year_and_flags | (ordinal << 4)));
return Ok(NaiveDate::from_yof(year_and_flags | (ordinal << 4)));
}
}
// do the full check
let year = self.year();
let (mut year_div_400, year_mod_400) = div_mod_floor(year, 400);
let cycle = yo_to_cycle(year_mod_400 as u32, self.ordinal());
let cycle = try_opt!((cycle as i32).checked_add(days));
let cycle = try_ok_or!((cycle as i32).checked_add(days), Error::OutOfRange);
let (cycle_div_400y, cycle) = div_mod_floor(cycle, 146_097);
year_div_400 += cycle_div_400y;

let (year_mod_400, ordinal) = cycle_to_yo(cycle as u32);
let flags = YearFlags::from_year_mod_400(year_mod_400 as i32);
ok!(NaiveDate::from_ordinal_and_flags(
year_div_400 * 400 + year_mod_400 as i32,
ordinal,
flags
))
NaiveDate::from_ordinal_and_flags(year_div_400 * 400 + year_mod_400 as i32, ordinal, flags)
}

/// Makes a new `NaiveDateTime` from the current date and given `NaiveTime`.
Expand Down Expand Up @@ -903,7 +897,7 @@ impl NaiveDate {
if days < i32::MIN as i64 || days > i32::MAX as i64 {
return None;
}
self.add_days(days as i32)
ok!(self.add_days(days as i32))
}

/// Subtracts the number of whole days in the given `TimeDelta` from the current date.
Expand Down Expand Up @@ -936,7 +930,7 @@ impl NaiveDate {
if days < i32::MIN as i64 || days > i32::MAX as i64 {
return None;
}
self.add_days(days as i32)
ok!(self.add_days(days as i32))
}

/// Subtracts another `NaiveDate` from the current date.
Expand Down Expand Up @@ -1995,7 +1989,7 @@ impl Iterator for NaiveDateWeeksIterator {

fn next(&mut self) -> Option<Self::Item> {
let current = self.value;
self.value = current.checked_add_days(Days::new(7))?;
self.value = current.checked_add_days(Days::new(7)).ok()?;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unrelated to this PR, so just ignore this comment.
I wonder if the NaiveDateWeeksIterator can cover the complete range of NaiveDate, or if it fails one week before the end.

Some(current)
}

Expand All @@ -2010,7 +2004,7 @@ impl ExactSizeIterator for NaiveDateWeeksIterator {}
impl DoubleEndedIterator for NaiveDateWeeksIterator {
fn next_back(&mut self) -> Option<Self::Item> {
let current = self.value;
self.value = current.checked_sub_days(Days::new(7))?;
self.value = current.checked_sub_days(Days::new(7)).ok()?;
Some(current)
}
}
Expand Down
20 changes: 8 additions & 12 deletions src/naive/date/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -499,10 +499,10 @@ fn test_date_signed_duration_since() {

#[test]
fn test_date_add_days() {
fn check(lhs: Option<NaiveDate>, days: Days, rhs: Option<NaiveDate>) {
fn check(lhs: Result<NaiveDate, Error>, days: Days, rhs: Result<NaiveDate, Error>) {
assert_eq!(lhs.unwrap().checked_add_days(days), rhs);
}
let ymd = |y, m, d| NaiveDate::from_ymd(y, m, d).ok();
let ymd = NaiveDate::from_ymd;

check(ymd(2014, 1, 1), Days::new(0), ymd(2014, 1, 1));
// always round towards zero
Expand All @@ -514,16 +514,16 @@ fn test_date_add_days() {
check(ymd(-7, 1, 1), Days::new(365 * 12 + 3), ymd(5, 1, 1));

// overflow check
check(ymd(0, 1, 1), Days::new(MAX_DAYS_FROM_YEAR_0.try_into().unwrap()), ymd(MAX_YEAR, 12, 31));
check(ymd(0, 1, 1), Days::new(u64::try_from(MAX_DAYS_FROM_YEAR_0).unwrap() + 1), None);
check(ymd(0, 1, 1), Days::new(MAX_DAYS_FROM_YEAR_0 as u64), ymd(MAX_YEAR, 12, 31));
check(ymd(0, 1, 1), Days::new(MAX_DAYS_FROM_YEAR_0 as u64 + 1), Err(Error::OutOfRange));
}

#[test]
fn test_date_sub_days() {
fn check(lhs: Option<NaiveDate>, days: Days, rhs: Option<NaiveDate>) {
fn check(lhs: Result<NaiveDate, Error>, days: Days, rhs: Result<NaiveDate, Error>) {
assert_eq!(lhs.unwrap().checked_sub_days(days), rhs);
}
let ymd = |y, m, d| NaiveDate::from_ymd(y, m, d).ok();
let ymd = NaiveDate::from_ymd;

check(ymd(2014, 1, 1), Days::new(0), ymd(2014, 1, 1));
check(ymd(2014, 1, 2), Days::new(1), ymd(2014, 1, 1));
Expand All @@ -532,12 +532,8 @@ fn test_date_sub_days() {
check(ymd(2018, 1, 1), Days::new(365 * 4 + 1), ymd(2014, 1, 1));
check(ymd(2414, 1, 1), Days::new(365 * 400 + 97), ymd(2014, 1, 1));

check(ymd(MAX_YEAR, 12, 31), Days::new(MAX_DAYS_FROM_YEAR_0.try_into().unwrap()), ymd(0, 1, 1));
check(
ymd(0, 1, 1),
Days::new((-MIN_DAYS_FROM_YEAR_0).try_into().unwrap()),
ymd(MIN_YEAR, 1, 1),
);
check(ymd(MAX_YEAR, 12, 31), Days::new(MAX_DAYS_FROM_YEAR_0 as u64), ymd(0, 1, 1));
check(ymd(0, 1, 1), Days::new((-MIN_DAYS_FROM_YEAR_0) as u64), ymd(MIN_YEAR, 1, 1));
}

#[test]
Expand Down
14 changes: 6 additions & 8 deletions src/naive/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,18 +529,16 @@ impl NaiveDateTime {

/// Add a duration in [`Days`] to the date part of the `NaiveDateTime`
///
/// Returns `None` if the resulting date would be out of range.
#[must_use]
pub const fn checked_add_days(self, days: Days) -> Option<Self> {
Some(Self { date: try_opt!(self.date.checked_add_days(days)), ..self })
/// Returns [`Error::OutOfRange`] if the resulting date would be out of range.
pub const fn checked_add_days(self, days: Days) -> Result<Self, Error> {
Ok(Self { date: try_err!(self.date.checked_add_days(days)), ..self })
}

/// Subtract a duration in [`Days`] from the date part of the `NaiveDateTime`
///
/// Returns `None` if the resulting date would be out of range.
#[must_use]
pub const fn checked_sub_days(self, days: Days) -> Option<Self> {
Some(Self { date: try_opt!(self.date.checked_sub_days(days)), ..self })
/// Returns [`Error::OutOfRange`] if the resulting date would be out of range.
pub const fn checked_sub_days(self, days: Days) -> Result<Self, Error> {
Ok(Self { date: try_err!(self.date.checked_sub_days(days)), ..self })
}

/// Subtracts another `NaiveDateTime` from the current date and time.
Expand Down
6 changes: 3 additions & 3 deletions src/naive/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

use core::ops::RangeInclusive;

use crate::expect;
use crate::Weekday;
use crate::{expect, ok};

pub(crate) mod date;
pub(crate) mod datetime;
Expand Down Expand Up @@ -63,7 +63,7 @@ impl NaiveWeek {
// Do not construct an intermediate date beyond `self.date`, because that may be out of
// range if `date` is close to `NaiveDate::MAX`.
let days = start - ref_day - if start > ref_day { 7 } else { 0 };
expect!(self.date.add_days(days), "first weekday out of range for `NaiveDate`")
expect!(ok!(self.date.add_days(days)), "first weekday out of range for `NaiveDate`")
}

/// Returns a date representing the last day of the week.
Expand Down Expand Up @@ -91,7 +91,7 @@ impl NaiveWeek {
// Do not construct an intermediate date before `self.date` (like with `first_day()`),
// because that may be out of range if `date` is close to `NaiveDate::MIN`.
let days = end - ref_day + if end < ref_day { 7 } else { 0 };
expect!(self.date.add_days(days), "last weekday out of range for `NaiveDate`")
expect!(ok!(self.date.add_days(days)), "last weekday out of range for `NaiveDate`")
}

/// Returns a [`RangeInclusive<T>`] representing the whole week bounded by
Expand Down