Rename Random impl to Rng.

Create Random struct providing next_x(range) for all T:Rng.
This commit is contained in:
Bob McWhirter
2021-09-01 09:39:33 -04:00
parent fd7a76c59e
commit 37ceae908b
4 changed files with 69 additions and 42 deletions

View File

@ -19,11 +19,11 @@ pub enum Error {
ClockError,
}
pub struct Random<T: Instance> {
pub struct Rng<T: Instance> {
_inner: T,
}
impl<T: Instance> Random<T> {
impl<T: Instance> Rng<T> {
pub fn new(inner: impl Unborrow<Target = T>) -> Self {
T::enable();
T::reset();
@ -49,7 +49,7 @@ impl<T: Instance> Random<T> {
}
}
impl<T: Instance> RngCore for Random<T> {
impl<T: Instance> RngCore for Rng<T> {
fn next_u32(&mut self) -> u32 {
loop {
let bits = unsafe { T::regs().sr().read() };
@ -80,9 +80,9 @@ impl<T: Instance> RngCore for Random<T> {
}
}
impl<T: Instance> CryptoRng for Random<T> {}
impl<T: Instance> CryptoRng for Rng<T> {}
impl<T: Instance> traits::rng::Rng for Random<T> {
impl<T: Instance> traits::rng::Rng for Rng<T> {
type Error = Error;
#[rustfmt::skip]
type RngFuture<'a> where Self: 'a = impl Future<Output=Result<(), Self::Error>> + 'a;
@ -128,28 +128,6 @@ impl<T: Instance> traits::rng::Rng for Random<T> {
}
}
impl<T: Instance> traits::rng::Random for Random<T> {
#[rustfmt::skip]
type NextFuture<'a> where Self: 'a = impl Future<Output=Result<u32, Self::Error>> + 'a;
fn next<'a>(&'a mut self, range: u32) -> Self::NextFuture<'a> {
async move {
let t = (-(range as i32) % (range as i32)) as u32;
loop {
let mut buf = [0; 4];
traits::rng::Rng::fill_bytes(self, &mut buf).await?;
let x = u32::from_le_bytes(buf);
let m = x as u64 * range as u64;
let l = m as u32;
if l < t {
continue;
}
return Ok((m >> 32) as u32);
}
}
}
}
pub(crate) mod sealed {
use super::*;