Skip to content
Closed
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
49 changes: 29 additions & 20 deletions src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ use crate::offset::{FixedOffset, Offset, TimeZone, Utc};
use crate::try_opt;
#[cfg(any(feature = "clock", feature = "std"))]
use crate::OutOfRange;
use crate::{Datelike, Months, TimeDelta, Timelike, Weekday};
use crate::{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 @@ -669,13 +669,21 @@ impl From<DateTime<Local>> for DateTime<FixedOffset> {
}

/// Maps the local datetime to other datetime with given conversion function.
fn map_local<Tz: TimeZone, F>(dt: &DateTime<Tz>, mut f: F) -> Option<DateTime<Tz>>
fn map_local<Tz: TimeZone, F>(dt: &DateTime<Tz>, mut f: F) -> Result<DateTime<Tz>, Error>
where
F: FnMut(NaiveDateTime) -> Option<NaiveDateTime>,
F: FnMut(NaiveDateTime) -> Result<NaiveDateTime, Error>,
{
f(dt.overflowing_naive_local())
.and_then(|datetime| dt.timezone().from_local_datetime(&datetime).single())
.filter(|dt| dt >= &DateTime::<Utc>::MIN_UTC && dt <= &DateTime::<Utc>::MAX_UTC)
let naive_dt = f(dt.overflowing_naive_local())?;
let local_dt = match dt.timezone().from_local_datetime(&naive_dt) {
crate::LocalResult::Single(dt) => dt,
_ => return Err(Error::InvalidArgument),
};

if local_dt < DateTime::<Utc>::MIN_UTC || local_dt > DateTime::<Utc>::MAX_UTC {
return Err(Error::OutOfRange);
}

Ok(local_dt)
}

impl DateTime<FixedOffset> {
Expand Down Expand Up @@ -933,7 +941,7 @@ impl<Tz: TimeZone> Datelike for DateTime<Tz> {
/// - When the `NaiveDateTime` would be out of range.
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
fn with_year(&self, year: i32) -> Option<DateTime<Tz>> {
fn with_year(&self, year: i32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_year(year))
}

Expand All @@ -949,7 +957,7 @@ impl<Tz: TimeZone> Datelike for DateTime<Tz> {
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
#[inline]
fn with_month(&self, month: u32) -> Option<DateTime<Tz>> {
fn with_month(&self, month: u32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_month(month))
}

Expand All @@ -965,7 +973,7 @@ impl<Tz: TimeZone> Datelike for DateTime<Tz> {
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
#[inline]
fn with_month0(&self, month0: u32) -> Option<DateTime<Tz>> {
fn with_month0(&self, month0: u32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_month0(month0))
}

Expand All @@ -981,7 +989,7 @@ impl<Tz: TimeZone> Datelike for DateTime<Tz> {
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
#[inline]
fn with_day(&self, day: u32) -> Option<DateTime<Tz>> {
fn with_day(&self, day: u32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_day(day))
}

Expand All @@ -997,7 +1005,7 @@ impl<Tz: TimeZone> Datelike for DateTime<Tz> {
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
#[inline]
fn with_day0(&self, day0: u32) -> Option<DateTime<Tz>> {
fn with_day0(&self, day0: u32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_day0(day0))
}

Expand All @@ -1013,7 +1021,7 @@ impl<Tz: TimeZone> Datelike for DateTime<Tz> {
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
#[inline]
fn with_ordinal(&self, ordinal: u32) -> Option<DateTime<Tz>> {
fn with_ordinal(&self, ordinal: u32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_ordinal(ordinal))
}

Expand All @@ -1029,7 +1037,7 @@ impl<Tz: TimeZone> Datelike for DateTime<Tz> {
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
#[inline]
fn with_ordinal0(&self, ordinal0: u32) -> Option<DateTime<Tz>> {
fn with_ordinal0(&self, ordinal0: u32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_ordinal0(ordinal0))
}
}
Expand Down Expand Up @@ -1058,12 +1066,12 @@ impl<Tz: TimeZone> Timelike for DateTime<Tz> {
///
/// # Errors
///
/// Returns `None` if:
/// Returns `Err` if:
/// - The value for `hour` is invalid.
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
#[inline]
fn with_hour(&self, hour: u32) -> Option<DateTime<Tz>> {
fn with_hour(&self, hour: u32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_hour(hour))
}

Expand All @@ -1073,11 +1081,12 @@ impl<Tz: TimeZone> Timelike for DateTime<Tz> {
///
/// # Errors
///
/// Returns `Err` if:
/// - The value for `minute` is invalid.
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
#[inline]
fn with_minute(&self, min: u32) -> Option<DateTime<Tz>> {
fn with_minute(&self, min: u32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_minute(min))
}

Expand All @@ -1090,18 +1099,18 @@ impl<Tz: TimeZone> Timelike for DateTime<Tz> {
///
/// # Errors
///
/// Returns `None` if:
/// Returns `Err` if:
/// - The value for `second` is invalid.
/// - The local time at the resulting date does not exist or is ambiguous, for example during a
/// daylight saving time transition.
#[inline]
fn with_second(&self, sec: u32) -> Option<DateTime<Tz>> {
fn with_second(&self, sec: u32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_second(sec))
}

/// Makes a new `DateTime` with nanoseconds since the whole non-leap second changed.
///
/// Returns `None` when the resulting `NaiveDateTime` would be invalid.
/// Returns `Err` when the resulting `NaiveDateTime` would be invalid.
/// As with the [`NaiveDateTime::nanosecond`] method,
/// the input range can exceed 1,000,000,000 for leap seconds.
///
Expand All @@ -1111,7 +1120,7 @@ impl<Tz: TimeZone> Timelike for DateTime<Tz> {
///
/// Returns `None` if `nanosecond >= 2,000,000,000`.
#[inline]
fn with_nanosecond(&self, nano: u32) -> Option<DateTime<Tz>> {
fn with_nanosecond(&self, nano: u32) -> Result<DateTime<Tz>, Error> {
map_local(self, |datetime| datetime.with_nanosecond(nano))
}
}
Expand Down
44 changes: 23 additions & 21 deletions src/datetime/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@ use crate::naive::{NaiveDate, NaiveTime};
use crate::offset::{FixedOffset, TimeZone, Utc};
#[cfg(feature = "clock")]
use crate::offset::{Local, Offset};
use crate::{Datelike, Days, LocalResult, Months, NaiveDateTime, TimeDelta, Timelike, Weekday};
use crate::{
Datelike, Days, Error, LocalResult, Months, NaiveDateTime, TimeDelta, Timelike, Weekday,
};

#[derive(Clone)]
struct DstTester;
Expand Down Expand Up @@ -1343,37 +1345,37 @@ fn test_min_max_setters() {
let beyond_max = offset_max.from_utc_datetime(&NaiveDateTime::MAX);

assert_eq!(beyond_min.with_year(2020).unwrap().year(), 2020);
assert_eq!(beyond_min.with_month(beyond_min.month()), Some(beyond_min));
assert_eq!(beyond_min.with_month(3), None);
assert_eq!(beyond_min.with_month0(beyond_min.month0()), Some(beyond_min));
assert_eq!(beyond_min.with_month0(3), None);
assert_eq!(beyond_min.with_day(beyond_min.day()), Some(beyond_min));
assert_eq!(beyond_min.with_day(15), None);
assert_eq!(beyond_min.with_day0(beyond_min.day0()), Some(beyond_min));
assert_eq!(beyond_min.with_day0(15), None);
assert_eq!(beyond_min.with_ordinal(beyond_min.ordinal()), Some(beyond_min));
assert_eq!(beyond_min.with_ordinal(200), None);
assert_eq!(beyond_min.with_ordinal0(beyond_min.ordinal0()), Some(beyond_min));
assert_eq!(beyond_min.with_ordinal0(200), None);
assert_eq!(beyond_min.with_hour(beyond_min.hour()), Some(beyond_min));
assert_eq!(beyond_min.with_hour(23), beyond_min.checked_add_signed(TimeDelta::hours(1)));
assert_eq!(beyond_min.with_month(beyond_min.month()), Ok(beyond_min));
assert_eq!(beyond_min.with_month(3), Err(Error::OutOfRange));
assert_eq!(beyond_min.with_month0(beyond_min.month0()), Ok(beyond_min));
assert_eq!(beyond_min.with_month0(3), Err(Error::OutOfRange));
assert_eq!(beyond_min.with_day(beyond_min.day()), Ok(beyond_min));
assert_eq!(beyond_min.with_day(15), Err(Error::OutOfRange));
assert_eq!(beyond_min.with_day0(beyond_min.day0()), Ok(beyond_min));
assert_eq!(beyond_min.with_day0(15), Err(Error::OutOfRange));
assert_eq!(beyond_min.with_ordinal(beyond_min.ordinal()), Ok(beyond_min));
assert_eq!(beyond_min.with_ordinal(200), Err(Error::OutOfRange));
assert_eq!(beyond_min.with_ordinal0(beyond_min.ordinal0()), Ok(beyond_min));
assert_eq!(beyond_min.with_ordinal0(200), Err(Error::OutOfRange));
assert_eq!(beyond_min.with_hour(beyond_min.hour()), Ok(beyond_min));
assert_eq!(beyond_min.with_hour(23), Ok(beyond_min.checked_add_signed(TimeDelta::hours(1)).unwrap()));
assert_eq!(beyond_min.with_hour(5), None);
assert_eq!(beyond_min.with_minute(0), Some(beyond_min));
assert_eq!(beyond_min.with_second(0), Some(beyond_min));
assert_eq!(beyond_min.with_nanosecond(0), Some(beyond_min));

assert_eq!(beyond_max.with_year(2020).unwrap().year(), 2020);
assert_eq!(beyond_max.with_month(beyond_max.month()), Some(beyond_max));
assert_eq!(beyond_max.with_month(beyond_max.month()), Ok(beyond_max));
assert_eq!(beyond_max.with_month(3), None);
assert_eq!(beyond_max.with_month0(beyond_max.month0()), Some(beyond_max));
assert_eq!(beyond_max.with_month0(beyond_max.month0()), Ok(beyond_max));
assert_eq!(beyond_max.with_month0(3), None);
assert_eq!(beyond_max.with_day(beyond_max.day()), Some(beyond_max));
assert_eq!(beyond_max.with_day(beyond_max.day()), Ok(beyond_max));
assert_eq!(beyond_max.with_day(15), None);
assert_eq!(beyond_max.with_day0(beyond_max.day0()), Some(beyond_max));
assert_eq!(beyond_max.with_day0(beyond_max.day0()), Ok(beyond_max));
assert_eq!(beyond_max.with_day0(15), None);
assert_eq!(beyond_max.with_ordinal(beyond_max.ordinal()), Some(beyond_max));
assert_eq!(beyond_max.with_ordinal(beyond_max.ordinal()), Ok(beyond_max));
assert_eq!(beyond_max.with_ordinal(200), None);
assert_eq!(beyond_max.with_ordinal0(beyond_max.ordinal0()), Some(beyond_max));
assert_eq!(beyond_max.with_ordinal0(beyond_max.ordinal0()), Ok(beyond_max));
assert_eq!(beyond_max.with_ordinal0(200), None);
assert_eq!(beyond_max.with_hour(beyond_max.hour()), Some(beyond_max));
assert_eq!(beyond_max.with_hour(0), beyond_max.checked_sub_signed(TimeDelta::hours(1)));
Expand Down
Loading