Expand description
§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.
Structs§
- Pulls random integers from the OS RNG device. This object can be reused to create multiple random numbers and uses an internal
BufReader
around the rng device file in order to keep from doing multiple small reads. - A random string generator which gets it’s entropy from an internal
BufReader
wrapping the OS RNG device. This generator may be re-used as many times as required.
Enums§
- These flags specify the contents of the dictionary used to create random strings.
Functions§
- Gets a
u16
from the RNG device. Do not use this function if you require multiple random numbers, as each use will be a single read. - Gets a
u32
from the RNG device. Do not use this function if you require multiple random numbers, as each use will be a single read. - Gets a
u64
from the RNG device. Do not use this function if you require multiple random numbers, as each use will be a single read.