Documentation
extern crate std;

use std::fs::File;
use std::io::{self, BufReader, Read};

use crate::RandomSource;

pub struct RandomDevice {
    file: BufReader<File>,
}

impl RandomDevice {
    pub fn new() -> io::Result<Self> {
        /* Use urandom as the default random device
         * https://web.archive.org/web/20250221155503/https://unix.stackexchange.com/questions/324209/when-to-use-dev-random-vs-dev-urandom */
        Self::new_urandom()
    }

    pub fn new_urandom() -> io::Result<Self>  {
        let file = BufReader::new(File::open("/dev/urandom")?);
        Ok(Self { file })
    }

    pub fn new_random() -> io::Result<Self>  {
        let file = BufReader::new(File::open("/dev/random")?);
        Ok(Self { file })
    }
}

impl RandomSource for RandomDevice {
    fn fill_bytes(&mut self, bytes: &mut [u8]) {
        self.file.read_exact(bytes).expect("Expected /dev/random to succeed");
    }
}