Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Let DateTime::signed_duration_since take argument with Borrow #1119

Merged
merged 2 commits into from
Jun 2, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 14 additions & 3 deletions src/datetime/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ extern crate alloc;

#[cfg(all(not(feature = "std"), feature = "alloc"))]
use alloc::string::{String, ToString};
#[cfg(any(feature = "alloc", feature = "std", test))]
use core::borrow::Borrow;
use core::cmp::Ordering;
use core::fmt::Write;
Expand Down Expand Up @@ -409,8 +408,11 @@ impl<Tz: TimeZone> DateTime<Tz> {
/// This does not overflow or underflow at all.
#[inline]
#[must_use]
pub fn signed_duration_since<Tz2: TimeZone>(self, rhs: DateTime<Tz2>) -> OldDuration {
self.datetime.signed_duration_since(rhs.datetime)
pub fn signed_duration_since<Tz2: TimeZone>(
self,
rhs: impl Borrow<DateTime<Tz2>>,
) -> OldDuration {
self.datetime.signed_duration_since(rhs.borrow().datetime)
}

/// Returns a view to the naive UTC datetime.
Expand Down Expand Up @@ -1046,6 +1048,15 @@ impl<Tz: TimeZone> Sub<DateTime<Tz>> for DateTime<Tz> {
}
}

impl<Tz: TimeZone> Sub<&DateTime<Tz>> for DateTime<Tz> {
type Output = OldDuration;

#[inline]
fn sub(self, rhs: &DateTime<Tz>) -> OldDuration {
self.signed_duration_since(rhs)
}
}

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

Expand Down
13 changes: 13 additions & 0 deletions src/datetime/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,19 @@ fn test_datetime_offset() {
assert!(*edt.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap().offset() != est);
}

#[test]
fn signed_duration_since_autoref() {
let dt1 = Utc.with_ymd_and_hms(2014, 5, 6, 7, 8, 9).unwrap();
let dt2 = Utc.with_ymd_and_hms(2014, 3, 4, 5, 6, 7).unwrap();
let diff1 = dt1.signed_duration_since(dt2); // Copy/consume
let diff2 = dt2.signed_duration_since(&dt1); // Take by reference
assert_eq!(diff1, -diff2);

let diff1 = dt1 - &dt2; // We can choose to substract rhs by reference
let diff2 = dt2 - dt1; // Or consume rhs
assert_eq!(diff1, -diff2);
}

#[test]
fn test_datetime_date_and_time() {
let tz = FixedOffset::east_opt(5 * 60 * 60).unwrap();
Expand Down