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 25, 2023
1 parent 225cfaa commit 018be06
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 @@ -1247,22 +1247,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 1257 in src/datetime/mod.rs

View check run for this annotation

Codecov / codecov/patch

src/datetime/mod.rs#L1254-L1257

Added lines #L1254 - L1257 were not covered by tests
}

Expand Down Expand Up @@ -1317,8 +1308,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 1314 in src/datetime/mod.rs

View check run for this annotation

Codecov / codecov/patch

src/datetime/mod.rs#L1311-L1314

Added lines #L1311 - L1314 were not covered by tests
}

Expand Down

0 comments on commit 018be06

Please sign in to comment.