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 Sep 8, 2023
1 parent c9be5ae commit e74dcba
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 @@ -1166,22 +1166,13 @@ impl<Tz: TimeZone> AddAssign<Duration> 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
}

Check warning on line 1176 in src/datetime/mod.rs

View check run for this annotation

Codecov / codecov/patch

src/datetime/mod.rs#L1173-L1176

Added lines #L1173 - L1176 were not covered by tests
}

Expand Down Expand Up @@ -1236,8 +1227,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
}

Check warning on line 1233 in src/datetime/mod.rs

View check run for this annotation

Codecov / codecov/patch

src/datetime/mod.rs#L1230-L1233

Added lines #L1230 - L1233 were not covered by tests
}

Expand Down

0 comments on commit e74dcba

Please sign in to comment.