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

@ -17,11 +17,60 @@ pub trait Rng {
fn fill_bytes<'a>(&'a mut self, dest: &'a mut [u8]) -> Self::RngFuture<'a>;
}
pub trait Random: Rng {
#[rustfmt::skip]
type NextFuture<'a>: Future<Output = Result<u32, <Self as Rng>::Error>> + 'a
where
Self: 'a;
fn next<'a>(&'a mut self, range: u32) -> Self::NextFuture<'a>;
pub struct Random<T: Rng> {
rng: T,
}
impl<T: Rng> Random<T> {
pub fn new(rng: T) -> Self {
Self { rng }
}
pub async fn next_u8<'a>(&'a mut self, range: u8) -> Result<u8, T::Error> {
// Lemire's method
let t = (-(range as i8) % (range as i8)) as u8;
loop {
let mut buf = [0; 1];
self.rng.fill_bytes(&mut buf).await?;
let x = u8::from_le_bytes(buf);
let m = x as u16 * range as u16;
let l = m as u8;
if l < t {
continue;
}
return Ok((m >> 8) as u8);
}
}
pub async fn next_u16<'a>(&'a mut self, range: u16) -> Result<u16, T::Error> {
// Lemire's method
let t = (-(range as i16) % (range as i16)) as u16;
loop {
let mut buf = [0; 2];
self.rng.fill_bytes(&mut buf).await?;
let x = u16::from_le_bytes(buf);
let m = x as u32 * range as u32;
let l = m as u16;
if l < t {
continue;
}
return Ok((m >> 16) as u16);
}
}
pub async fn next_u32<'a>(&'a mut self, range: u32) -> Result<u32, T::Error> {
// Lemire's method
let t = (-(range as i32) % (range as i32)) as u32;
loop {
let mut buf = [0; 4];
self.rng.fill_bytes(&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);
}
}
}