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

Implement Arbitrary for nonzero integers #79

Merged
merged 2 commits into from Mar 29, 2021
Merged
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
33 changes: 33 additions & 0 deletions src/lib.rs
Expand Up @@ -37,6 +37,8 @@ pub mod size_hint;
use core::cell::{Cell, RefCell, UnsafeCell};
use core::iter;
use core::mem;
use core::num::{NonZeroI128, NonZeroI16, NonZeroI32, NonZeroI64, NonZeroI8, NonZeroIsize};
use core::num::{NonZeroU128, NonZeroU16, NonZeroU32, NonZeroU64, NonZeroU8, NonZeroUsize};
use core::ops::{Range, RangeBounds, RangeFrom, RangeInclusive, RangeTo, RangeToInclusive};
use core::str;
use core::time::Duration;
Expand Down Expand Up @@ -1010,6 +1012,37 @@ impl<'a, A: Arbitrary<'a>> Arbitrary<'a> for ::std::num::Wrapping<A> {
}
}

macro_rules! implement_nonzero_int {
($nonzero:ty, $int:ty) => {
impl<'a> Arbitrary<'a> for $nonzero {
fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
match Self::new(<$int as Arbitrary<'a>>::arbitrary(u)?) {
Some(n) => Ok(n),
None => Err(Error::IncorrectFormat),
}
}

#[inline]
fn size_hint(depth: usize) -> (usize, Option<usize>) {
<$int as Arbitrary<'a>>::size_hint(depth)
}
}
};
}

implement_nonzero_int! { NonZeroI8, i8 }
implement_nonzero_int! { NonZeroI16, i16 }
implement_nonzero_int! { NonZeroI32, i32 }
implement_nonzero_int! { NonZeroI64, i64 }
implement_nonzero_int! { NonZeroI128, i128 }
implement_nonzero_int! { NonZeroIsize, isize }
implement_nonzero_int! { NonZeroU8, u8 }
implement_nonzero_int! { NonZeroU16, u16 }
implement_nonzero_int! { NonZeroU32, u32 }
implement_nonzero_int! { NonZeroU64, u64 }
implement_nonzero_int! { NonZeroU128, u128 }
implement_nonzero_int! { NonZeroUsize, usize }

#[cfg(test)]
mod test {
use super::*;
Expand Down