use super::ShelfError;
use rand_core::{OsRng, RngCore};
use sha2::{Digest, Sha256};
pub trait RandomSource: Send {
fn fill(&mut self, buf: &mut [u8]) -> Result<(), String>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct SystemRandom;
impl RandomSource for SystemRandom {
fn fill(&mut self, buf: &mut [u8]) -> Result<(), String> {
OsRng.try_fill_bytes(buf).map_err(|e| e.to_string())
}
}
#[derive(Clone, Debug)]
pub struct SeededStream {
seed: Vec<u8>,
block: u64,
buf: Vec<u8>,
}
impl SeededStream {
pub fn new(seed: &str) -> Self {
Self {
seed: seed.as_bytes().to_vec(),
block: 0,
buf: Vec::new(),
}
}
}
impl RandomSource for SeededStream {
fn fill(&mut self, out: &mut [u8]) -> Result<(), String> {
let mut n = 0;
while n < out.len() {
if self.buf.is_empty() {
let mut h = Sha256::new();
h.update(&self.seed);
h.update(self.block.to_be_bytes());
self.buf = h.finalize().to_vec();
self.block += 1;
}
let c = self.buf.len().min(out.len() - n);
out[n..n + c].copy_from_slice(&self.buf[..c]);
self.buf.drain(..c);
n += c;
}
Ok(())
}
}
pub(crate) struct Draws(pub(crate) Box<dyn RandomSource>);
impl Draws {
pub(crate) fn bytes(&mut self, n: usize) -> Result<Vec<u8>, ShelfError> {
let mut b = vec![0; n];
self.0
.fill(&mut b)
.map_err(|e| ShelfError::Random(format!("the shelf's random source: {e}")))?;
Ok(b)
}
pub(crate) fn hex(&mut self, n: usize) -> Result<String, ShelfError> {
Ok(hex::encode(self.bytes(n)?))
}
pub(crate) fn uniform(&mut self, n: u64) -> Result<u64, ShelfError> {
if n == 0 {
return Err(ShelfError::Invalid(
"a uniform draw needs a positive bound".into(),
));
}
let rest = n.wrapping_neg() % n;
loop {
let b = self.bytes(8)?;
let x = u64::from_be_bytes(b.try_into().expect("eight bytes"));
if rest == 0 || x < rest.wrapping_neg() {
return Ok(x % n);
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_seeded_stream_is_its_blocks_in_order() {
let mut s = SeededStream::new("x");
let mut a = [0u8; 40];
s.fill(&mut a).unwrap();
let block = |i: u64| {
let mut h = Sha256::new();
h.update(b"x");
h.update(i.to_be_bytes());
h.finalize().to_vec()
};
assert_eq!(&a[..32], block(0).as_slice());
assert_eq!(&a[32..], &block(1)[..8]);
}
#[test]
fn uniform_refuses_a_zero_bound_and_stays_under_the_bound() {
let mut d = Draws(Box::new(SeededStream::new("u")));
assert!(d.uniform(0).is_err());
for _ in 0..100 {
assert!(d.uniform(7).unwrap() < 7);
}
assert!(d.uniform(1 << 16).unwrap() < 1 << 16);
}
}