ruint/support/
arbitrary.rs

1//! Support for the [`arbitrary`](https://crates.io/crates/arbitrary) crate.
2
3#![cfg(feature = "arbitrary")]
4#![cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))]
5
6use crate::Uint;
7use arbitrary::{Arbitrary, Result, Unstructured};
8
9// TODO: Instead of uniform random sampling, we should use a distribution that
10// exercises different scales more. Something like sum(±2ⁱ for random i). The
11// reduction step can then remove terms or make them smaller.
12
13// TODO: We should use `rand` in tests, not `arbitrary`.
14
15impl<'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}