1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
use super::*;

#[derive(Debug)]
pub struct DirectRng<R: RngCore>(R);

impl<R: RngCore> DirectRng<R> {
    pub fn new(rng: R) -> Self {
        Self(rng)
    }

    #[inline]
    fn fill_bytes(&mut self, bytes: &mut [u8]) -> Option<()> {
        RngCore::try_fill_bytes(&mut self.0, bytes).ok()
    }
}

impl<R: RngCore> FillBytes for DirectRng<R> {
    #[inline]
    fn mode(&self) -> DriverMode {
        DriverMode::Direct
    }

    #[inline]
    fn fill_bytes(&mut self, bytes: &mut [u8]) -> Option<()> {
        RngCore::try_fill_bytes(&mut self.0, bytes).ok()
    }
}

impl<R: RngCore> Driver for DirectRng<R> {
    gen_from_bytes!();
}

#[derive(Debug)]
pub struct ForcedRng<R: RngCore>(R);

impl<R: RngCore> ForcedRng<R> {
    #[inline]
    pub fn new(rng: R) -> Self {
        Self(rng)
    }
}

impl<R: RngCore> FillBytes for ForcedRng<R> {
    #[inline]
    fn mode(&self) -> DriverMode {
        DriverMode::Forced
    }

    #[inline]
    fn fill_bytes(&mut self, bytes: &mut [u8]) -> Option<()> {
        if RngCore::try_fill_bytes(&mut self.0, bytes).is_err() {
            // if the rng fails to fill the remaining bytes, then we just start returning 0s
            for byte in bytes.iter_mut() {
                *byte = 0;
            }
        }
        Some(())
    }
}

impl<R: RngCore> Driver for ForcedRng<R> {
    gen_from_bytes!();
}