smallrand/
lib.rs

1#![allow(clippy::doc_markdown)]
2//! This crate provides a lightweight alternative to rand,
3//! using the "xoshiro256++" (<https://prng.di.unimi.it>)
4//! and "ChaCha12" algorithms (<https://cr.yp.to/chacha.html>),
5//! which are also the ones used by [`rand`](https://crates.io/crates/rand) for its SmallRng
6//! and StdRng, respectively.
7//!
8//! The crate is intended to be easy to audit.
9//! Its only dependency is [`getrandom`](https://crates.io/crates/getrandom),
10//! and that is only used on non-Linux/Unix platforms.
11//! It can also be built as no-std, in which case [`getrandom`](https://crates.io/crates/getrandom)
12//! is not used at all (but you´ll then have to provide the seed yourself).
13//!
14//! Basic usage:
15//!
16//! ```
17//! #[cfg(feature = "std")]
18//! {
19//! use smallrand::StdRng;
20//! let mut rng = StdRng::new();
21//! let coin_flip : bool = rng.random();
22//! let some_int = rng.random::<u32>();
23//! let uniformly_distributed : u32 = rng.range(0..=42);
24//! let a_float : f64 = rng.range(0.0..42.0);
25//! }
26//! ```
27//!
28//! `smallrand` can also be used as "no-std", in which case you can use it like this:
29//! ```rust
30//! use smallrand::{StdRng, SplitMix};
31//! const SEED : u64 = 42;
32//! let mut rng = StdRng::from_entropy(&mut SplitMix::new(SEED));
33//! let some_int = rng.random::<u32>();
34//! ```
35//!
36//! The use of the `SplitMix` may seem cumbersome, but this is done for two reasons:
37//! - Requiring that the `StdRng` is initialized from something that implements `EntropySource`
38//!   (like `SplitMix`) provides an interface independent of the actual algorithm used
39//!   (different algorithms need different amount of entropy when initializing).
40//! - Xoshiro256++ must be initialized with four u64 values. Having that as the interface could
41//!   tempt users to provide only one actual value and use zero for the other three.
42//!   This could cause the algorithm to produce very bad output. The use of `SplitMix`
43//!   generates values that makes most algorithms perform better in this case.
44//!
45//! It is fairly easy to write your own implementation of `EntropySource` for your platform.
46//!
47#![forbid(unsafe_code)]
48extern crate core;
49
50mod chacha;
51mod entropy;
52mod nonces;
53mod ranges;
54mod rng;
55mod secure_entropy;
56mod smallrng;
57mod stdrng;
58mod xoshiro;
59
60pub use chacha::ChaCha12;
61#[cfg(feature = "std")]
62pub use entropy::DefaultEntropy;
63#[cfg(all(unix, feature = "std"))]
64pub use entropy::DevUrandom;
65pub use entropy::EntropySource;
66#[cfg(all(not(unix), feature = "allow-getrandom"))]
67pub use entropy::GetRandom;
68#[cfg(feature = "std")]
69pub use entropy::HashMapEntropy;
70pub use entropy::SplitMix;
71pub use rng::Rng;
72#[cfg(feature = "std")]
73pub use secure_entropy::SecureEntropy;
74pub use smallrng::SmallRng;
75pub use stdrng::StdRng;
76pub use xoshiro::Xoshiro256pp;