2 releases
0.2.1 | Feb 23, 2024 |
---|---|
0.2.0 | Aug 30, 2020 |
0.0.1 |
|
#310 in Filesystem
27 downloads per month
14KB
230 lines
Contents
Rationale
There are a number of good random number generator crates in the Rust ecosystem. The point
of this crate is to provide something dead simple with no dependencies beyond std
by
using the OS provided RNG on Unix-like operating systems. Another goal of this crate is
to provide a simple interface for creating random strings - a feature that is surprisingly
lacking in other random oriented crates.
You might want to use this crate if:
- Your application does not require a lot of random data early in the boot process
- You want to attempt to keep the dependency graph for your application small
- You only care to support Unix-like operating systems
Usage
# Cargo.toml
osrand = "0.1"
use osrand::{BufRng, Flags, RandomString};
fn main() {
// Get a one-off random u32
let n = osrand::random_u32().unwrap();
println!("Number: {n}");
// Get a random u64 from the reusable `BufRng` struct
let mut rng = BufRng::new().unwrap();
let n = rng.get_u64().unwrap();
println!("Number: {n}");
// Get a random String using the full dictionary
let mut rs = RandomString::new(&[]).unwrap();
let s = rs.gen(8).unwrap();
assert_eq!(s.len(), 8);
println!("String: {s}");
// Get the dictionary used by the `RandomString` generator
let dict = rs.get_dictionary().clone();
println!("Dictionary: {dict:?}");
// Change the dictionary to only alphanumeric
rs.set_dictionary(Flags::alphanumeric());
println!("Dictionary: {:?}", rs.get_dictionary());
// Convert the previous `BufRng` to a `RandomString` with the full dictionary
let mut rs_new: RandomString = rng.into();
// Convert the previous `RandomString` to a `BufRng`
let mut rng_new: BufRng = rs.into();
}
Features
By default /dev/urandom
is used as it is less resource intensive than pulling from
/dev/random
. If you want a more secure RNG you can go ahead and pull from /dev/random
by building with --no-default-features
or disabling the urandom
feature.