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 Jul 27, 2023
1 parent 4894bc9 commit 5911afc
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 @@ -1175,22 +1175,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 @@ -1225,8 +1216,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 5911afc

Please sign in to comment.