Implement Arbitrary for Duration

This commit is contained in:
Sergey Potapov 2022-10-17 17:50:04 +02:00 committed by Dirkjan Ochtman
parent 44cee53a18
commit 87b04c5b91

View File

@ -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};