-
Notifications
You must be signed in to change notification settings - Fork 256
Expand file tree
/
Copy pathsys_rng.rs
More file actions
56 lines (49 loc) · 1.38 KB
/
sys_rng.rs
File metadata and controls
56 lines (49 loc) · 1.38 KB
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
//! rand_core adapter
use crate::Error;
use rand_core::{TryCryptoRng, TryRngCore};
/// An RNG over the operating-system's random data source
///
/// This is a zero-sized struct. It can be freely constructed with just `SysRng`.
///
/// This struct is also available as [`rand::rngs::SysRng`] when using [rand].
///
/// # Usage example
///
/// `SysRng` implements [`TryRngCore`]:
/// ```
/// use getrandom::{rand_core::TryRngCore, SysRng};
///
/// let mut key = [0u8; 32];
/// SysRng.try_fill_bytes(&mut key).unwrap();
/// ```
///
/// Using it as an [`RngCore`] is possible using [`TryRngCore::unwrap_err`]:
/// ```
/// use getrandom::rand_core::{TryRngCore, RngCore};
/// use getrandom::SysRng;
///
/// let mut rng = SysRng.unwrap_err();
/// let random_u64 = rng.next_u64();
/// ```
///
/// [rand]: https://crates.io/crates/rand
/// [`rand::rngs::SysRng`]: https://docs.rs/rand/latest/rand/rngs/struct.SysRng.html
/// [`RngCore`]: rand_core::RngCore
#[derive(Clone, Copy, Debug, Default)]
pub struct SysRng;
impl TryRngCore for SysRng {
type Error = Error;
#[inline]
fn try_next_u32(&mut self) -> Result<u32, Error> {
crate::u32()
}
#[inline]
fn try_next_u64(&mut self) -> Result<u64, Error> {
crate::u64()
}
#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
crate::fill(dest)
}
}
impl TryCryptoRng for SysRng {}