ruint/support/
arbitrary.rs1#![cfg(feature = "arbitrary")]
4#![cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))]
5
6use crate::Uint;
7use arbitrary::{Arbitrary, Result, Unstructured};
8
9impl<'a, const BITS: usize, const LIMBS: usize> Arbitrary<'a> for Uint<BITS, LIMBS> {
16 fn arbitrary(u: &mut Unstructured<'a>) -> Result<Self> {
17 let mut limbs = [0; LIMBS];
18 if let Some((last, rest)) = limbs.split_last_mut() {
19 for limb in rest {
20 *limb = u64::arbitrary(u)?;
21 }
22 *last = u.int_in_range(0..=Self::MASK)?;
23 }
24 Ok(Self::from_limbs(limbs))
25 }
26
27 fn size_hint(_depth: usize) -> (usize, Option<usize>) {
28 let bytes = BITS.div_ceil(8);
29 (bytes, Some(bytes))
30 }
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36 use crate::{const_for, nlimbs};
37 use core::iter::repeat_n;
38
39 #[allow(unused_imports)]
40 use alloc::vec::Vec;
41
42 #[test]
43 fn test_arbitrary() {
44 const_for!(BITS in NON_ZERO {
45 const LIMBS: usize = nlimbs(BITS);
46 let (num_bytes, _) = Uint::<BITS, LIMBS>::size_hint(0);
47 let bytes = repeat_n(0x55u8, num_bytes).collect::<Vec<_>>();
48 let mut u = arbitrary::Unstructured::new(&bytes);
49 Uint::<BITS, LIMBS>::arbitrary(&mut u).unwrap();
50 });
51 }
52}