#![warn(
missing_docs,
missing_debug_implementations,
missing_copy_implementations,
trivial_casts,
trivial_numeric_casts,
unsafe_code,
unstable_features,
unused_import_braces,
unused_qualifications,
rustdoc::missing_crate_level_docs,
rust_2018_idioms,
clippy::all,
clippy::pedantic,
clippy::nursery,
clippy::cargo
)]
#![allow(clippy::suspicious_else_formatting, clippy::match_like_matches_macro)]
use std::fs::File;
use std::io::{self, Read};
#[derive(Debug)]
pub struct RngSource
{
entropy: [u8; 256],
used: usize,
}
impl Drop for RngSource
{
fn drop(&mut self) {}
}
impl RngSource
{
pub fn new() -> Result<Self, io::Error>
{
let mut rv = Self {
entropy: [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0,
],
used: 256,
};
rv.fill()?;
Ok(rv)
}
pub fn get_u8(&mut self) -> Result<u8, io::Error>
{
if self.used + 1 > 256
{
self.fill()?;
}
let rv = self.entropy[self.used];
self.used += 1;
Ok(rv)
}
pub fn get_u32(&mut self) -> Result<u32, io::Error>
{
if self.used + 4 > 256
{
self.fill()?;
}
let rv = (u32::from(self.entropy[self.used]) << 24)
+ (u32::from(self.entropy[self.used + 1]) << 16)
+ (u32::from(self.entropy[self.used + 2]) << 8)
+ u32::from(self.entropy[self.used + 3]);
self.used += 4;
Ok(rv)
}
fn fill(&mut self) -> Result<(), io::Error>
{
let mut fp = File::open("/dev/urandom")?;
fp.read_exact(&mut self.entropy[0..self.used])?;
self.used = 0;
Ok(())
}
}