initial commit

This commit is contained in:
ddidderr 2024-02-12 09:23:56 +01:00
commit 876f259353
Signed by: ddidderr
GPG Key ID: 3841F1C27E6F0E14
5 changed files with 96 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
/target

16
Cargo.lock generated Normal file
View File

@ -0,0 +1,16 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "ez-urandom"
version = "0.1.0"
dependencies = [
"paste",
]
[[package]]
name = "paste"
version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c"

14
Cargo.toml Normal file
View File

@ -0,0 +1,14 @@
[package]
name = "ez-urandom"
version = "0.1.0"
edition = "2021"
[dependencies]
paste = "1"
[profile.release]
lto = true
debug = false
strip = true
panic = "unwind"
codegen-units = 1

3
rustfmt.toml Normal file
View File

@ -0,0 +1,3 @@
group_imports = "StdExternalCrate"
imports_granularity = "Crate"
imports_layout = "HorizontalVertical"

62
src/main.rs Normal file
View File

@ -0,0 +1,62 @@
use std::{
fs::File,
io::{BufReader, Read},
mem::{size_of, transmute},
};
use ::paste::paste;
pub struct OsRandom {
devurandom: BufReader<File>,
}
impl Default for OsRandom {
fn default() -> Self {
Self::new()
}
}
macro_rules! os_random_get_integer_impls {
($($t:ty),*) => {
$(
::paste::paste! {
pub fn [<get_ $t>](&mut self) -> std::io::Result<$t> {
let mut buf = [0u8; size_of::<$t>()];
self.devurandom.read_exact(&mut buf)?;
Ok(unsafe {transmute::< [u8; size_of::<$t>() ], $t>(buf) })
}
}
)*
};
}
impl OsRandom {
pub fn new() -> Self {
Self {
devurandom: BufReader::new(File::open("/dev/urandom").unwrap()),
}
}
os_random_get_integer_impls!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
}
impl Read for OsRandom {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
self.devurandom.read(buf)
}
}
macro_rules! os_rng_test_impls {
($($t:ty),*) => {
let mut rng = OsRandom::new();
$(
paste! {
println!("{}", rng.[<get_ $t>]().unwrap());
}
)*
}
}
fn main() {
os_rng_test_impls!(u8, u16, u32, u64, u128, usize, i8, i16, i32, i64, i128, isize);
}