[][src]Crate nanorand

A library meant for fast, random number generation with quick compile time, and minimal dependencies.

Examples

Generating a number

use nanorand::{RNG, WyRand};

fn main() {
    let mut rng = WyRand::new();
    println!("Random number: {}", rng.generate::<u64>());
}

Generating a number in a range

use nanorand::{RNG, WyRand};

fn main() {
    let mut rng = WyRand::new();
    println!("Random number between 1 and 100: {}", rng.generate_range::<u64>(1, 100));
}

Shuffling a Vec

use nanorand::{RNG, WyRand};

fn main() {
    let mut rng = WyRand::new();
    let mut items = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    rng.shuffle(&mut items);
}

Why should I use this over...

  • rand - The standard rand crate is a complex beast. It contains unsafe code in the core implementations, and while it has much more options than we do, that's kind of the point. We're straight to the point, while rand is everything and the kitchen sink.
  • fastrand, oorandom, random-fast-rng, or randomize - These are all minimal, zero-dep implementations of the PCG family of RNGs (Pcg32 and Pcg64). While these are decent, they are much slower than wyrand (which beats the speed of these Pcg32 implementations while providing 64 random bits), and do not provide CSPRNGs.
  • getrandom - The getrandom crate just provides OS entropy sources. It is not meant for random number generation. In fact, we provide it as an optional entropy source.

RNG Implementations

RNGnanorand typeOutput SizeCryptographically SecureSpeedNotesOriginal Implementation
wyrandnanohash::WyRand64 bits (u64)🚫4 GB/shttps://github.com/lemire/testingRNG/blob/master/source/wyrand.h
Pcg64nanohash::Pcg6464 bits (u64)🚫1 GB/shttps://github.com/rkern/pcg64
ChaChananohash::ChaCha512 bits ([u32; 16])90 MB/s (ChaCha8), 40 MB/s (ChaCha20)Currently only works in Nightly Rust, will work with Stable 1.47 (see rust#74060)https://cr.yp.to/chacha.html

Entropy Sources

  • Unix-like (Linux, Android, macOS, iOS, FreeBSD, OpenBSD) - first /dev/urandom, else /dev/random, else system time. (#[forbid(unsafe_code)])
  • Windows - BCryptGenRandom with system-preferred RNG. (#[deny(unsafe_code)])

Feature Flags

  • std (default) - Enables Rust std lib features, such as seeding from OS entropy sources.
  • wyrand (default) - Enable the wyrand RNG.
  • pcg64 (default) - Enable the Pcg64 RNG.
  • chacha (Nightly-only) - Enable the ChaCha RNG.
  • rdseed - On x86/x86_64 platforms, the rdseed intrinsic will be used when OS entropy isn't available.
  • zeroize - Implement the Zeroize trait for all RNGs.
  • getrandom - Use the getrandom crate as an entropy source. Works on most systems, optional due to the fact that it brings in more dependencies.

Re-exports

pub use gen::*;
pub use rand::*;

Modules

crypto

Implementation of cryptography, for CSPRNGs.

entropy

Sources for obtaining entropy.

gen

Traits for generating types from an RNG.

rand

RNG algorithms.