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

Guard against overflow in NaiveDate::with_*0 methods #1023

Merged
merged 1 commit into from Apr 18, 2023
Merged
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/naive/date.rs
Expand Up @@ -1559,7 +1559,8 @@ impl Datelike for NaiveDate {
/// ```
#[inline]
fn with_month0(&self, month0: u32) -> Option<NaiveDate> {
self.with_mdf(self.mdf().with_month(month0 + 1)?)
let month = month0.checked_add(1)?;
self.with_mdf(self.mdf().with_month(month)?)
}

/// Makes a new `NaiveDate` with the day of month (starting from 1) changed.
Expand Down Expand Up @@ -1597,7 +1598,8 @@ impl Datelike for NaiveDate {
/// ```
#[inline]
fn with_day0(&self, day0: u32) -> Option<NaiveDate> {
self.with_mdf(self.mdf().with_day(day0 + 1)?)
let day = day0.checked_add(1)?;
self.with_mdf(self.mdf().with_day(day)?)
}

/// Makes a new `NaiveDate` with the day of year (starting from 1) changed.
Expand Down Expand Up @@ -1645,7 +1647,8 @@ impl Datelike for NaiveDate {
/// ```
#[inline]
fn with_ordinal0(&self, ordinal0: u32) -> Option<NaiveDate> {
self.with_of(self.of().with_ordinal(ordinal0 + 1)?)
let ordinal = ordinal0.checked_add(1)?;
self.with_of(self.of().with_ordinal(ordinal)?)
}
}

Expand Down Expand Up @@ -3032,4 +3035,12 @@ mod tests {
}
}
}

#[test]
fn test_with_0_overflow() {
let dt = NaiveDate::from_ymd_opt(2023, 4, 18).unwrap();
assert!(dt.with_month0(4294967295).is_none());
assert!(dt.with_day0(4294967295).is_none());
assert!(dt.with_ordinal0(4294967295).is_none());
}
}