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 Aug 6, 2023
1 parent 942b026 commit 90c8384
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 @@ -1141,22 +1141,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 @@ -1191,8 +1182,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 90c8384

Please sign in to comment.