Skip to content

Commit

Permalink
Use checked_(add|sub)_offset in Add and Sub impls of DateTime
Browse files Browse the repository at this point in the history
  • Loading branch information
pitdicker committed Jun 8, 2023
1 parent db196a7 commit f54d7a8
Showing 1 changed file with 6 additions and 14 deletions.
20 changes: 6 additions & 14 deletions src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1170,22 +1170,13 @@ impl<Tz: TimeZone> AddAssign<OldDuration> for DateTime<Tz> {
}
}

fn add_with_leapsecond<T>(lhs: &T, rhs: i32) -> T
where
T: Timelike + Add<OldDuration, Output = T>,
{
// extract and temporarily remove the fractional part and later recover it
let nanos = lhs.nanosecond();
let lhs = lhs.with_nanosecond(0).unwrap();
(lhs + OldDuration::seconds(i64::from(rhs))).with_nanosecond(nanos).unwrap()
}

impl<Tz: TimeZone> Add<FixedOffset> for DateTime<Tz> {
type Output = DateTime<Tz>;

#[inline]
fn add(self, rhs: FixedOffset) -> DateTime<Tz> {
add_with_leapsecond(&self, rhs.local_minus_utc())
fn add(mut self, rhs: FixedOffset) -> DateTime<Tz> {
self.datetime = self.naive_utc().checked_add_offset(rhs).unwrap();
self
}
}

Expand Down Expand Up @@ -1220,8 +1211,9 @@ impl<Tz: TimeZone> Sub<FixedOffset> for DateTime<Tz> {
type Output = DateTime<Tz>;

#[inline]
fn sub(self, rhs: FixedOffset) -> DateTime<Tz> {
add_with_leapsecond(&self, -rhs.local_minus_utc())
fn sub(mut self, rhs: FixedOffset) -> DateTime<Tz> {
self.datetime = self.naive_utc().checked_sub_offset(rhs).unwrap();
self
}
}

Expand Down

0 comments on commit f54d7a8

Please sign in to comment.