Crate ya_rand

Crate ya_rand 

Source
Expand description

§YA-Rand: Yet Another Rand

Simple and fast pseudo/crypto random number generation.

§Performance considerations

The backing CRNG uses compile-time dispatch, so you’ll only get the fastest implementation available to the machine if rust knows what kind of machine to compile for.

Your best bet is to configure your global .cargo/config.toml with rustflags = ["-C", "target-cpu=native"] beneath the [build] directive.

If you know the x86 feature level of the processor that will be executing your binaries, it maybe be better to instead configure this directive at the crate level.

§But why?

Because rand is very cool and extremely powerful, but kind of an enormous fucking pain in the ass to use, and it’s far too large and involved for someone who just needs to flip a coin once every few minutes. But if you’re doing some crazy black magic numerical sorcery, it almost certainly has something you can use to complete your spell. Don’t be afraid to go there if you need to.

Other crates, like fastrand, tinyrand, or oorandom, fall somewhere between “I’m not sure I trust the backing RNG” (state size is too small or algorithm is iffy) and “this API is literally just rand but far less powerful”. I wanted something easy to use, but also fast and statistically robust.

So here we are.

§Usage

Import the contents of the library and use new_rng to create new RNGs wherever you need them. Then call whatever method you require on those instances. All methods available are directly accessible through any generator instance via the dot operator, and are named in a way that should make it easy to quickly identify what you need. See below for a few examples.

If you need cryptographic security, new_rng_secure will provide you with a SecureRng instance, suitable for use in secure contexts.

“How do I access the thread-local RNG?” There isn’t one, and unless Rust improves the performance and ergonomics of the TLS implementation, there probably won’t ever be. Create a local instance when and where you need one and use it while you need it. If you need an RNG to stick around for a while, passing it between functions or storing it in structs is a perfectly valid solution.

use ya_rand::*;

// **Correct** instantiation is very easy.
// Seeds a PRNG instance using operating system entropy,
// so you never have to worry about the quality of the
// initial state.
let mut rng = new_rng();

// Generate a random number with a given upper bound.
let max: u64 = 420;
let val = rng.bound(max);
assert!(val < max);

// Generate a random number in a given range.
let min: i64 = -69;
let max: i64 = 69;
let val = rng.range(min, max);
assert!(min <= val && val < max);

// Generate a random floating point value.
let val = rng.f64();
assert!(0.0 <= val && val < 1.0);

// Generate a random ascii digit: '0'..='9' as a char.
let digit = rng.ascii_digit();
assert!(digit.is_ascii_digit());

// Seeds a CRNG instance with OS entropy.
let mut secure_rng = new_rng_secure();

// We still have access to all the same methods...
let val = rng.f64();
assert!(0.0 <= val && val < 1.0);

// ...but since the CRNG is secure, we also
// get some nice extras.
// Here, we generate a string of random hexidecimal
// characters (base 16), with the shortest length guaranteed
// to be secure.
use ya_rand::encoding::*;
let s = secure_rng.text::<Base16>(Base16::MIN_LEN);
assert!(s.len() == Base16::MIN_LEN);

§Features

  • std - Enabled by default, but can be disabled for use in no_std environments. Enables normal/exponential distributions, error type conversions for getrandom, and the alloc feature.
  • alloc - Enabled by default. Normally enabled through std, but can be enabled on it’s own for use in no_std environments which provide allocation primitives. Enables random generation of secure String values when using SecureRng.
  • secure - Enabled by default. Provides SecureRng, which implements SecureGenerator. The backing generator is ChaCha with 8 rounds and a 64-bit counter.
  • inline - Marks all Generator::u64 implementations with #[inline]. Should generally increase runtime performance at the cost of binary size and compile time. You’ll have to test your specific use case to determine if this feature is worth it for you; all the RNGs provided tend to be plenty fast without additional inlining.

§Details

This crate primarily uses the xoshiro family for pseudo-random number generators. These generators are very fast, of very high statistical quality, and small. They aren’t cryptographically secure, but most users don’t need their RNG to be secure, they just need it to be random and fast. The default generator is xoshiro256++, which should provide a large enough period for most users. The xoshiro512++ generator is also provided in case you need a longer period.

Since version 2.0, RomuTrio and RomuQuad from the romurand family are also provided. These are non-linear generators which can be ever-so-slightly faster than the xoshiro generators, particularly when the inline feature is enabled. But in practice this difference likely won’t be measurable. Unless you’re especially fond of the statistical properties of the romurand generators, this crates default generator should be more than enough.

All generators output a distinct u64 value on each call, and the various methods used for transforming those outputs into more usable forms are all high-quality and well-understood. Placing an upper bound on these values uses Lemire’s method. Both inclusive bounding and range-based bounding are applications of this method, with a few intermediary steps to adjust the bound and apply shifts as needed. This approach is unbiased and quite fast, but for very large bounds performance might degrade slightly, since the algorithm may need to sample the underlying RNG multiple times to get an unbiased result. But this is just a byproduct of how the underlying algorithm works, and isn’t something you should ever be worried about when using the aforementioned methods, since these resamples are few and far between. If your bound happens to be a power of 2, always use Generator::bits, since it’s nothing more than a bit-shift of the original u64 provided by the RNG, and will always be as fast as possible.

Floating point values (besides the normal and exponential distributions) are uniformly distributed, with all the possible outputs being equidistant within the given interval. They are not maximally dense; if that’s something you need, you’ll have to generate those values yourself. This approach is very fast, and endorsed by both Lemire and Vigna (the author of the RNGs used in this crate). The normal distribution implementation uses the Marsaglia polar method, returning pairs of independently sampled f64 values. Exponential variates are generated using this approach.

§Security

If you’re in the market for secure random number generation, this crate provides a secure generator backed by a highly optimized ChaCha8 implementation from the chachacha crate. It functions identically to the other provided RNGs, but with added functionality that wouldn’t be safe to use on pseudo RNGs. Why only 8 rounds? Because people who are very passionate about cryptography are convinced that’s enough, and I have zero reason to doubt them, nor any capacity to prove them wrong. See page 14 of the Too Much Crypto paper if you’re interested in the justification.

The security guarantees made to the user are identical to those made by ChaCha as an algorithm. It is up to you to determine if those guarantees meet the demands of your use case.

I reserve the right to change the backing implementation at any time to another RNG which is at least as secure, without changing the API or bumping the major/minor version. Realistically, this just means I’m willing to bump this to ChaCha12 if ChaCha8 is ever compromised.

§Safety

Generators are seeded using entropy from the underlying OS, and have the potential to fail during creation. But in practice this is extraordinarily unlikely, and isn’t something the end-user should ever worry about. Modern Windows versions (10 and newer) have a crypto subsystem that will never fail during runtime, and rust can trivially remove the failure branch when compiling binaries for those systems.

Modules§

encoding
Provides the Encoder trait, as well as concrete implementations of the RFC 4648 encodings and alphanumeric encoding.

Structs§

RomuQuad
Rust implementation of the RomuQuad PRNG.
RomuTrio
Rust implementation of the RomuTrio PRNG.
SecureRng
A cryptographically secure random number generator.
Xoshiro256pp
Rust implementation of the xoshiro256++ PRNG.
Xoshiro512pp
Rust implementation of the xoshiro512++ PRNG.

Traits§

Generator
Base trait that all RNGs must implement.
SecureGenerator
Trait for RNGs that provide cryptographically secure data.
SeedableGenerator
Trait for RNGs that can be created from a user-provided seed.

Functions§

new_rng
The recommended way to create new PRNG instances.
new_rng_secure
The recommended way to create new CRNG instances.

Type Aliases§

ShiroRng
The recommended generator for all non-cryptographic purposes.