From f9f3c7857d31c1c2341a1ddee0e9447f81a61465 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?L=C3=A9o=20Gaspard?= Date: Sun, 22 Jan 2023 20:23:50 +0100 Subject: [PATCH] Fix panic in DateTime::checked_add_days This is a backport of #941, except it needs to work around the fact that we can't modify the `time` crate. --- src/naive/date.rs | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/naive/date.rs b/src/naive/date.rs index 3734460713..79d0a98baa 100644 --- a/src/naive/date.rs +++ b/src/naive/date.rs @@ -646,6 +646,10 @@ impl NaiveDate { /// NaiveDate::from_ymd_opt(2022, 7, 31).unwrap().checked_add_days(Days::new(2)), /// Some(NaiveDate::from_ymd_opt(2022, 8, 2).unwrap()) /// ); + /// assert_eq!( + /// NaiveDate::from_ymd_opt(2022, 7, 31).unwrap().checked_add_days(Days::new(1000000000000)), + /// None + /// ); /// ``` pub fn checked_add_days(self, days: Days) -> Option { if days.0 == 0 { @@ -665,6 +669,10 @@ impl NaiveDate { /// NaiveDate::from_ymd_opt(2022, 2, 20).unwrap().checked_sub_days(Days::new(6)), /// Some(NaiveDate::from_ymd_opt(2022, 2, 14).unwrap()) /// ); + /// assert_eq!( + /// NaiveDate::from_ymd_opt(2022, 2, 20).unwrap().checked_sub_days(Days::new(1000000000000)), + /// None + /// ); /// ``` pub fn checked_sub_days(self, days: Days) -> Option { if days.0 == 0 { @@ -675,7 +683,11 @@ impl NaiveDate { } fn diff_days(self, days: i64) -> Option { - self.checked_add_signed(Duration::days(days)) + let secs = days.checked_mul(86400)?; // 86400 seconds in one day + if secs >= core::i64::MAX / 1000 || secs <= core::i64::MIN / 1000 { + return None; // See the `time` 0.1 crate. Outside these bounds, `Duration::seconds` will panic + } + self.checked_add_signed(Duration::seconds(secs)) } /// Makes a new `NaiveDateTime` from the current date and given `NaiveTime`.