mirror of
https://github.com/chronotope/chrono.git
synced 2025-10-02 15:26:12 +00:00
Tweak implementation of Arbitrary for NaiveDate and NaiveTime to make it infallible
This commit is contained in:
parent
2eda0f1a61
commit
c879b18dbf
@ -197,7 +197,8 @@ pub const MAX_DATE: NaiveDate = NaiveDate::MAX;
|
|||||||
impl arbitrary::Arbitrary<'_> for NaiveDate {
|
impl arbitrary::Arbitrary<'_> for NaiveDate {
|
||||||
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<NaiveDate> {
|
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<NaiveDate> {
|
||||||
let year = u.int_in_range(MIN_YEAR..=MAX_YEAR)?;
|
let year = u.int_in_range(MIN_YEAR..=MAX_YEAR)?;
|
||||||
let ord = u.int_in_range(1..=366)?;
|
let max_days = YearFlags::from_year(year).ndays();
|
||||||
|
let ord = u.int_in_range(1..=max_days)?;
|
||||||
NaiveDate::from_yo_opt(year, ord).ok_or(arbitrary::Error::IncorrectFormat)
|
NaiveDate::from_yo_opt(year, ord).ok_or(arbitrary::Error::IncorrectFormat)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -197,9 +197,11 @@ pub struct NaiveTime {
|
|||||||
#[cfg(feature = "arbitrary")]
|
#[cfg(feature = "arbitrary")]
|
||||||
impl arbitrary::Arbitrary<'_> for NaiveTime {
|
impl arbitrary::Arbitrary<'_> for NaiveTime {
|
||||||
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<NaiveTime> {
|
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<NaiveTime> {
|
||||||
let secs = u.int_in_range(0..=86_400)?;
|
let secs = u.int_in_range(0..=86_399)?;
|
||||||
let frac = u.int_in_range(0..=2_000_000_000)?;
|
let nano = u.int_in_range(0..=1_999_999_999)?;
|
||||||
Ok(NaiveTime { secs, frac })
|
let time = NaiveTime::from_num_seconds_from_midnight_opt(secs, nano)
|
||||||
|
.expect("Could not generate a valid chrono::NaiveTime. It looks like implementation of Arbitrary for NaiveTime is erroneous.");
|
||||||
|
Ok(time)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user