Optionally implement Arbitrary for Naive{Date,Time,DateTime}

This commit is contained in:
Alex Sayers 2021-05-04 20:31:54 +09:00 committed by Dirkjan Ochtman
parent eb1fae64fc
commit 2eda0f1a61
4 changed files with 20 additions and 0 deletions

View File

@ -37,6 +37,7 @@ pure-rust-locales = { version = "0.5.2", optional = true }
criterion = { version = "0.4.0", optional = true }
rkyv = {version = "0.7", optional = true}
iana-time-zone = { version = "0.1.44", optional = true, features = ["fallback"] }
arbitrary = { version = "1.0.0", features = ["derive"], optional = true }
[target.'cfg(all(target_arch = "wasm32", not(any(target_os = "emscripten", target_os = "wasi"))))'.dependencies]
wasm-bindgen = { version = "0.2", optional = true }

View File

@ -193,6 +193,15 @@ pub const MIN_DATE: NaiveDate = NaiveDate::MIN;
#[deprecated(since = "0.4.20", note = "Use NaiveDate::MAX instead")]
pub const MAX_DATE: NaiveDate = NaiveDate::MAX;
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary<'_> for NaiveDate {
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<NaiveDate> {
let year = u.int_in_range(MIN_YEAR..=MAX_YEAR)?;
let ord = u.int_in_range(1..=366)?;
NaiveDate::from_yo_opt(year, ord).ok_or(arbitrary::Error::IncorrectFormat)
}
}
// as it is hard to verify year flags in `NaiveDate::MIN` and `NaiveDate::MAX`,
// we use a separate run-time test.
#[test]

View File

@ -79,6 +79,7 @@ pub const MAX_DATETIME: NaiveDateTime = NaiveDateTime::MAX;
/// ```
#[derive(PartialEq, Eq, Hash, PartialOrd, Ord, Copy, Clone)]
#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct NaiveDateTime {
date: NaiveDate,
time: NaiveTime,

View File

@ -194,6 +194,15 @@ pub struct NaiveTime {
frac: u32,
}
#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary<'_> for NaiveTime {
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<NaiveTime> {
let secs = u.int_in_range(0..=86_400)?;
let frac = u.int_in_range(0..=2_000_000_000)?;
Ok(NaiveTime { secs, frac })
}
}
impl NaiveTime {
/// Makes a new `NaiveTime` from hour, minute and second.
///