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

Arbitrary 04x #849

Merged
merged 8 commits into from Oct 18, 2022
Merged
Show file tree
Hide file tree
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
1 change: 1 addition & 0 deletions Cargo.toml
Expand Up @@ -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 }
Expand Down
15 changes: 15 additions & 0 deletions src/date.rs
Expand Up @@ -545,6 +545,21 @@ where
}
}

// Note that implementation of Arbitrary cannot be automatically derived for Date<Tz>, due to
// the nontrivial bound <Tz as TimeZone>::Offset: Arbitrary.
#[cfg(feature = "arbitrary")]
impl<'a, Tz> arbitrary::Arbitrary<'a> for Date<Tz>
where
Tz: TimeZone,
<Tz as TimeZone>::Offset: arbitrary::Arbitrary<'a>,
{
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Date<Tz>> {
let date = NaiveDate::arbitrary(u)?;
let offset = <Tz as TimeZone>::Offset::arbitrary(u)?;
Ok(Date::from_utc(date, offset))
}
}

#[cfg(test)]
mod tests {
use super::Date;
Expand Down
15 changes: 15 additions & 0 deletions src/datetime/mod.rs
Expand Up @@ -1150,6 +1150,21 @@ impl From<DateTime<Utc>> for js_sys::Date {
}
}

// Note that implementation of Arbitrary cannot be simply derived for DateTime<Tz>, due to
// the nontrivial bound <Tz as TimeZone>::Offset: Arbitrary.
#[cfg(feature = "arbitrary")]
impl<'a, Tz> arbitrary::Arbitrary<'a> for DateTime<Tz>
where
Tz: TimeZone,
<Tz as TimeZone>::Offset: arbitrary::Arbitrary<'a>,
{
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<DateTime<Tz>> {
let datetime = NaiveDateTime::arbitrary(u)?;
let offset = <Tz as TimeZone>::Offset::arbitrary(u)?;
Ok(DateTime::from_utc(datetime, offset))
}
}

#[test]
fn test_add_sub_months() {
let utc_dt = Utc.ymd_opt(2018, 9, 5).unwrap().and_hms_opt(23, 58, 0).unwrap();
Expand Down
2 changes: 2 additions & 0 deletions src/month.rs
Expand Up @@ -30,6 +30,7 @@ use rkyv::{Archive, Deserialize, Serialize};
#[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum Month {
/// January
January = 0,
Expand Down Expand Up @@ -191,6 +192,7 @@ impl num_traits::FromPrimitive for Month {

/// A duration in calendar months
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, PartialOrd)]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Months(pub(crate) u32);

impl Months {
Expand Down
10 changes: 10 additions & 0 deletions src/naive/date.rs
Expand Up @@ -193,6 +193,16 @@ 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 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)
}
}

// as it is hard to verify year flags in `NaiveDate::MIN` and `NaiveDate::MAX`,
// we use a separate run-time test.
#[test]
Expand Down
1 change: 1 addition & 0 deletions src/naive/datetime/mod.rs
Expand Up @@ -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,
Expand Down
11 changes: 11 additions & 0 deletions src/naive/time/mod.rs
Expand Up @@ -194,6 +194,17 @@ 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_399)?;
let nano = u.int_in_range(0..=1_999_999_999)?;
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)
}
}

impl NaiveTime {
/// Makes a new `NaiveTime` from hour, minute and second.
///
Expand Down
10 changes: 10 additions & 0 deletions src/offset/fixed.rs
Expand Up @@ -152,6 +152,16 @@ impl fmt::Display for FixedOffset {
}
}

#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary<'_> for FixedOffset {
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<FixedOffset> {
let secs = u.int_in_range(-86_399..=86_399)?;
let fixed_offset = FixedOffset::east_opt(secs)
.expect("Could not generate a valid chrono::FixedOffset. It looks like implementation of Arbitrary for FixedOffset is erroneous.");
Ok(fixed_offset)
}
}

// addition or subtraction of FixedOffset to/from Timelike values is the same as
// adding or subtracting the offset's local_minus_utc value
// but keep keeps the leap second information.
Expand Down
1 change: 1 addition & 0 deletions src/offset/local/mod.rs
Expand Up @@ -52,6 +52,7 @@ mod tz_info;
/// ```
#[derive(Copy, Clone, Debug)]
#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Local;

impl Local {
Expand Down
1 change: 1 addition & 0 deletions src/offset/utc.rs
Expand Up @@ -41,6 +41,7 @@ use crate::{Date, DateTime};
/// ```
#[derive(Copy, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub struct Utc;

#[cfg(feature = "clock")]
Expand Down
18 changes: 18 additions & 0 deletions src/oldtime.rs
Expand Up @@ -482,6 +482,24 @@ fn div_rem_64(this: i64, other: i64) -> (i64, i64) {
(this / other, this % other)
}

#[cfg(feature = "arbitrary")]
impl arbitrary::Arbitrary<'_> for Duration {
fn arbitrary(u: &mut arbitrary::Unstructured) -> arbitrary::Result<Duration> {
const MIN_SECS: i64 = i64::MIN / MILLIS_PER_SEC - 1;
const MAX_SECS: i64 = i64::MAX / MILLIS_PER_SEC;

let secs: i64 = u.int_in_range(MIN_SECS..=MAX_SECS)?;
let nanos: i32 = u.int_in_range(0..=(NANOS_PER_SEC - 1))?;
let duration = Duration { secs, nanos };

if duration < MIN || duration > MAX {
Err(arbitrary::Error::IncorrectFormat)
} else {
Ok(duration)
}
}
}

#[cfg(test)]
mod tests {
use super::{Duration, OutOfRangeError, MAX, MIN};
Expand Down
1 change: 1 addition & 0 deletions src/weekday.rs
Expand Up @@ -11,6 +11,7 @@ use rkyv::{Archive, Deserialize, Serialize};
#[derive(PartialEq, Eq, Copy, Clone, Debug, Hash)]
#[cfg_attr(feature = "rustc-serialize", derive(RustcEncodable, RustcDecodable))]
#[cfg_attr(feature = "rkyv", derive(Archive, Deserialize, Serialize))]
#[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))]
pub enum Weekday {
/// Monday.
Mon = 0,
Expand Down