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

Fix possible panic in NaiveDate::from_num_days_from_ce_opt #527

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ Versions with only mechanical changes will be omitted from the following list.
* Add support for microseconds timestamps serde serialization/deserialization (#304)
* Fix `DurationRound` is not TZ aware (#495)
* Implement `DurationRound` for `NaiveDateTime`
* Fix `NaiveDate::from_num_days_from_ce_opt` panic on overflow

## 0.4.19

Expand Down
20 changes: 15 additions & 5 deletions src/naive/date.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,11 +415,13 @@ impl NaiveDate {
/// assert_eq!(from_ndays_opt(-100_000_000), None);
/// ```
pub fn from_num_days_from_ce_opt(days: i32) -> Option<NaiveDate> {
let days = days + 365; // make December 31, 1 BCE equal to day 0
let (year_div_400, cycle) = div_mod_floor(days, 146_097);
let (year_mod_400, ordinal) = internals::cycle_to_yo(cycle as u32);
let flags = YearFlags::from_year_mod_400(year_mod_400 as i32);
NaiveDate::from_of(year_div_400 * 400 + year_mod_400 as i32, Of::new(ordinal, flags))
// make December 31, 1 BCE equal to day 0
days.checked_add(365).and_then(|days| {
let (year_div_400, cycle) = div_mod_floor(days, 146_097);
let (year_mod_400, ordinal) = internals::cycle_to_yo(cycle as u32);
let flags = YearFlags::from_year_mod_400(year_mod_400 as i32);
NaiveDate::from_of(year_div_400 * 400 + year_mod_400 as i32, Of::new(ordinal, flags))
})
}

/// Makes a new `NaiveDate` by counting the number of occurrences of a particular day-of-week
Expand Down Expand Up @@ -2027,6 +2029,14 @@ mod tests {
}
}

#[test]
fn test_date_from_num_days_from_ce_opt() {
let ndays_from_ce = |days| NaiveDate::from_num_days_from_ce_opt(days);
ndays_from_ce(i32::MAX);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can these two checks be moved into test_date_from_num_days_from_ce below?
Also, why not check the return value of the closure ?

assert!(ndays_from_ce(0).is_some());
ndays_from_ce(i32::MIN);
}

#[test]
fn test_date_from_num_days_from_ce() {
let from_ndays_from_ce = |days| NaiveDate::from_num_days_from_ce_opt(days);
Expand Down