Skip to content

Commit c947588

Browse files
committed
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.
1 parent b244b83 commit c947588

File tree

1 file changed

+13
-1
lines changed

1 file changed

+13
-1
lines changed

src/naive/date.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -646,6 +646,10 @@ impl NaiveDate {
646646
/// NaiveDate::from_ymd_opt(2022, 7, 31).unwrap().checked_add_days(Days::new(2)),
647647
/// Some(NaiveDate::from_ymd_opt(2022, 8, 2).unwrap())
648648
/// );
649+
/// assert_eq!(
650+
/// NaiveDate::from_ymd_opt(2022, 7, 31).unwrap().checked_add_days(Days::new(1000000000000)),
651+
/// None
652+
/// );
649653
/// ```
650654
pub fn checked_add_days(self, days: Days) -> Option<Self> {
651655
if days.0 == 0 {
@@ -665,6 +669,10 @@ impl NaiveDate {
665669
/// NaiveDate::from_ymd_opt(2022, 2, 20).unwrap().checked_sub_days(Days::new(6)),
666670
/// Some(NaiveDate::from_ymd_opt(2022, 2, 14).unwrap())
667671
/// );
672+
/// assert_eq!(
673+
/// NaiveDate::from_ymd_opt(2022, 2, 20).unwrap().checked_sub_days(Days::new(1000000000000)),
674+
/// None
675+
/// );
668676
/// ```
669677
pub fn checked_sub_days(self, days: Days) -> Option<Self> {
670678
if days.0 == 0 {
@@ -675,7 +683,11 @@ impl NaiveDate {
675683
}
676684

677685
fn diff_days(self, days: i64) -> Option<Self> {
678-
self.checked_add_signed(Duration::days(days))
686+
let secs = days.checked_mul(86400)?; // 86400 seconds in one day
687+
if secs >= std::i64::MAX / 1000 || secs <= std::i64::MIN / 1000 {
688+
return None; // See the `time` 0.1 crate. Outside these bounds, `Duration::seconds` will panic
689+
}
690+
self.checked_add_signed(Duration::seconds(secs))
679691
}
680692

681693
/// Makes a new `NaiveDateTime` from the current date and given `NaiveTime`.

0 commit comments

Comments
 (0)