use crate::{TryCryptoRng, TryRngCore};
#[derive(Clone, Copy, Debug, Default)]
pub struct OsRng;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OsError(getrandom::Error);
impl core::fmt::Display for OsError {
#[inline]
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
self.0.fmt(f)
}
}
#[cfg(feature = "std")]
impl std::error::Error for OsError {
#[inline]
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
std::error::Error::source(&self.0)
}
}
impl OsError {
#[inline]
pub fn raw_os_error(self) -> Option<i32> {
self.0.raw_os_error()
}
}
impl TryRngCore for OsRng {
type Error = OsError;
#[inline]
fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
getrandom::u32().map_err(OsError)
}
#[inline]
fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
getrandom::u64().map_err(OsError)
}
#[inline]
fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
getrandom::fill(dest).map_err(OsError)
}
}
impl TryCryptoRng for OsRng {}
#[test]
fn test_os_rng() {
let x = OsRng.try_next_u64().unwrap();
let y = OsRng.try_next_u64().unwrap();
assert!(x != 0);
assert!(x != y);
}
#[test]
fn test_construction() {
assert!(OsRng.try_next_u64().unwrap() != 0);
}