hacspec_lib/
rng.rs

1//! This module provides utilities for providing randomness to cryptographic constructions and protocols.
2
3#[derive(Debug)]
4pub enum Error {
5    InsufficientRandomness,
6}
7
8/// A utility struct for providing random bytes and bits.
9pub struct Randomness {
10    pub(crate) bytes: Vec<u8>,
11    pub(crate) pointer: usize,
12}
13
14impl Randomness {
15    /// Initialize the randomness provider.
16    pub fn new(bytes: Vec<u8>) -> Self {
17        Self { bytes, pointer: 0 }
18    }
19
20    /// Output a random bytes, or error, if more bytes are requested than are
21    /// available.
22    pub fn bytes(&mut self, len: usize) -> Result<&[u8], Error> {
23        if self.pointer + len > self.bytes.len() {
24            return Err(Error::InsufficientRandomness);
25        }
26
27        let out = &self.bytes[self.pointer..self.pointer + len];
28        self.pointer += len;
29        Ok(out)
30    }
31
32    /// Output a random boolean, consuming one byte internally, or error if  no
33    /// random byte is available.
34    pub fn bit(&mut self) -> Result<bool, Error> {
35        if self.pointer + 1 > self.bytes.len() {
36            return Err(Error::InsufficientRandomness);
37        }
38
39        let out = &self.bytes[self.pointer];
40        self.pointer += 1;
41        Ok(out & 0x1 == 0x1)
42    }
43}