hegel/extras/rand/
generators.rs1use std::convert::Infallible;
2
3use rand::Rng;
4use rand::SeedableRng;
5use rand::rand_core::TryRng;
6use rand::rngs::StdRng;
7
8use crate::generators::{Generator, TestCase, binary, integers};
9
10pub struct RandomsGenerator {
16 use_true_random: bool,
17}
18
19impl RandomsGenerator {
20 pub fn use_true_random(mut self, use_true_random: bool) -> Self {
24 self.use_true_random = use_true_random;
25 self
26 }
27}
28
29impl Generator<HegelRandom> for RandomsGenerator {
30 fn do_draw(&self, tc: &TestCase) -> HegelRandom {
31 if self.use_true_random {
32 let seed: u64 = integers().do_draw(tc);
33 HegelRandom::TrueRandom(Box::new(StdRng::seed_from_u64(seed)))
34 } else {
35 HegelRandom::ArtificialRandom(tc.clone())
36 }
37 }
38}
39
40#[derive(Debug)]
44pub enum HegelRandom {
45 ArtificialRandom(TestCase),
47 TrueRandom(Box<StdRng>),
49}
50
51impl TryRng for HegelRandom {
52 type Error = Infallible;
53
54 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
55 Ok(match self {
56 Self::ArtificialRandom(tc) => integers().do_draw(tc),
57 Self::TrueRandom(rng) => rng.next_u32(),
58 })
59 }
60
61 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
62 Ok(match self {
63 Self::ArtificialRandom(tc) => integers().do_draw(tc),
64 Self::TrueRandom(rng) => rng.next_u64(),
65 })
66 }
67
68 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
69 match self {
70 Self::ArtificialRandom(tc) => {
71 let bytes: Vec<u8> = binary()
72 .min_size(dest.len())
73 .max_size(dest.len())
74 .do_draw(tc);
75 dest.copy_from_slice(&bytes);
76 }
77 Self::TrueRandom(rng) => rng.fill_bytes(dest),
78 }
79 Ok(())
80 }
81}
82
83pub fn randoms() -> RandomsGenerator {
103 RandomsGenerator {
104 use_true_random: false,
105 }
106}