Skip to main content

getrandom/
sys_rng.rs

1use crate::Error;
2use rand_core::{TryCryptoRng, TryRng};
3
4/// A [`TryRng`] interface over the system's preferred random number source
5///
6/// This is a zero-sized struct. It can be freely constructed with just `SysRng`.
7///
8/// This struct is also available as [`rand::rngs::SysRng`] when using [rand].
9///
10/// # Usage example
11///
12/// `SysRng` implements [`TryRng`]:
13/// ```
14/// use getrandom::{rand_core::TryRng, SysRng};
15///
16/// let mut key = [0u8; 32];
17/// SysRng.try_fill_bytes(&mut key).unwrap();
18/// ```
19///
20/// Using it as an [`Rng`] is possible using [`UnwrapErr`]:
21/// ```
22/// use getrandom::rand_core::{Rng, UnwrapErr};
23/// use getrandom::SysRng;
24///
25/// let mut rng = UnwrapErr(SysRng);
26/// let random_u64 = rng.next_u64();
27/// ```
28///
29/// [rand]: https://crates.io/crates/rand
30/// [`rand::rngs::SysRng`]: https://docs.rs/rand/latest/rand/rngs/struct.SysRng.html
31/// [`Rng`]: rand_core::Rng
32/// [`UnwrapErr`]: rand_core::UnwrapErr
33#[derive(Clone, Copy, Debug, Default)]
34pub struct SysRng;
35
36impl TryRng for SysRng {
37    type Error = Error;
38
39    #[inline]
40    fn try_next_u32(&mut self) -> Result<u32, Error> {
41        crate::u32()
42    }
43
44    #[inline]
45    fn try_next_u64(&mut self) -> Result<u64, Error> {
46        crate::u64()
47    }
48
49    #[inline]
50    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
51        crate::fill(dest)
52    }
53}
54
55impl TryCryptoRng for SysRng {}