ya_rand/
lib.rs

1/*!
2# YA-Rand: Yet Another Rand
3
4Simple and fast pseudo/crypto random number generation.
5
6## Performance considerations
7
8The backing CRNG uses compile-time dispatch, so you'll only get the fastest implementation available to the
9machine if rustc knows what kind of machine to compile for.
10If you know the [x86 feature level] of the processor that will be running your binaries, tell rustc to
11target that feature level. On Windows, this means adding `RUSTFLAGS=-C target-cpu=<level>` to your system
12variables in System Properties -> Advanced -> Environment Variables. You can also manually toggle this for
13a single cmd-prompt instance using the [`set`] command. On Unix-based systems the process should be similar.
14If you're only going to run the final binary on your personal machine, replace `<level>` with `native`.
15
16If you happen to be building with a nightly toolchain, and for a machine supporting AVX512, the **nightly**
17feature provides an AVX512F implementation of the backing ChaCha algorithm.
18
19[x86 feature level]: https://en.wikipedia.org/wiki/X86-64#Microarchitecture_levels
20[`set`]: https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/set_1
21
22## But why?
23
24Because `rand` is very cool and extremely powerful, but kind of an enormous fucking pain in the ass
25to use, and it's far too large and involved for someone who just needs to flip a coin once
26every few minutes. But if you're doing some crazy black magic computational sorcery, it almost
27certainly has something you can use to complete your spell.
28
29Other crates, like `fastrand`, `tinyrand`, or `oorandom`, fall somewhere between "I'm not sure I trust
30the backing RNG" (state size is too small or algorithm is iffy) and "this API is literally just
31`rand` but far less powerful". I wanted something easy, but also fast and statistically robust.
32
33So here we are.
34
35## Usage
36
37Glob import the contents of the library and use [`new_rng`] to create new RNGs wherever
38you need them. Then call whatever method you require on those instances. All methods available
39are directly accessible through any generator instance via the dot operator, and are named
40in a way that should make it easy to quickly identify what you need. See below for a few examples.
41
42If you need cryptographic security, [`new_rng_secure`] will provide you with a [`SecureRng`] instance,
43suitable for use in secure contexts.
44
45"How do I access the thread-local RNG?" There isn't one, and unless Rust improves the performance and
46ergonomics of the TLS implementation, there probably won't ever be. Create a local instance when and
47where you need one and use it while you need it. If you need an RNG to stick around for a while, passing
48it between functions or storing it in structs is a perfectly valid solution.
49
50```
51use ya_rand::*;
52
53// **Correct** instantiation is very easy.
54// Seeds a PRNG instance using operating system entropy,
55// so you never have to worry about the quality of the
56// initial state.
57let mut rng = new_rng();
58
59// Generate a random number with a given upper bound.
60let max: u64 = 420;
61let val = rng.bound(max);
62assert!(val < max);
63
64// Generate a random number in a given range.
65let min: i64 = -69;
66let max: i64 = 69;
67let val = rng.range(min, max);
68assert!(min <= val && val < max);
69
70// Generate a random floating point value.
71let val = rng.f64();
72assert!(0.0 <= val && val < 1.0);
73
74// Generate a random ascii digit: '0'..='9' as a char.
75let digit = rng.ascii_digit();
76assert!(digit.is_ascii_digit());
77
78// Seeds a CRNG instance with OS entropy.
79let mut secure_rng = new_rng_secure();
80
81// We still have access to all the same methods...
82let val = rng.f64();
83assert!(0.0 <= val && val < 1.0);
84
85// ...but since the CRNG is secure, we also
86// get some nice extras.
87// Here, we generate a string of random hexidecimal
88// characters (base 16), with the shortest length guaranteed
89// to be secure.
90use ya_rand_encoding::*;
91let s = secure_rng.text::<Base16>(Base16::MIN_LEN).unwrap();
92assert!(s.len() == Base16::MIN_LEN);
93```
94
95## Features
96
97* **std** -
98    Enabled by default, but can be disabled for use in `no_std` environments. Enables normal/exponential
99    distributions, error type conversions for getrandom, and the **alloc** feature.
100* **alloc** -
101    Enabled by default. Normally enabled through **std**, but can be enabled on it's own for use in
102    `no_std` environments that provide allocation primitives. Enables random generation of secure
103    `String` values when using [`SecureRng`].
104* **inline** -
105    Marks all [`YARandGenerator::u64`] implementations with #\[inline\]. Should generally increase
106    runtime performance at the cost of binary size and compile time.
107    You'll have to test your specific use case to determine if this feature is worth it for you;
108    all the RNGs provided tend to be plenty fast without additional inlining.
109* **nightly** -
110    Enables AVX512F [`SecureRng`] implementation on targets that support it.
111
112## Details
113
114This crate uses the [xoshiro] family for pseudo-random number generators. These generators are
115very fast, of [very high statistical quality], and small. They aren't cryptographically secure,
116but most users don't need their RNG to be secure, they just need it to be random and fast. The default
117generator is xoshiro256++, which should provide a large enough period for most users. The xoshiro512++
118generator is also provided in case you need a longer period.
119
120[xoshiro]: https://prng.di.unimi.it/
121[very high statistical quality]: https://vigna.di.unimi.it/ftp/papers/ScrambledLinear.pdf
122
123All generators output a distinct `u64` value on each call, and the various methods used for transforming
124those outputs into more usable forms are all high-quality and well-understood. Placing an upper bound
125on these values uses [Lemire's method]. Both inclusive bounding and range-based bounding are applications
126of this method, with a few intermediary steps to adjust the bound and apply shifts as needed.
127This approach is unbiased and quite fast, but for very large bounds performance might degrade slightly,
128since the algorithm may need to sample the underlying RNG multiple times to get an unbiased result.
129But this is just a byproduct of how the underlying algorithm works, and isn't something you should ever be
130worried about when using the aforementioned methods, since these resamples are few and far between.
131If your bound happens to be a power of 2, always use [`YARandGenerator::bits`], since it's nothing more
132than a bit-shift of the original `u64` provided by the RNG, and will always be as fast as possible.
133
134Floating point values (besides the normal and exponential distributions) are uniformly distributed,
135with all the possible outputs being equidistant within the given interval. They are **not** maximally dense;
136if that's something you need, you'll have to generate those values yourself. This approach is very fast, and
137endorsed by both [Lemire] and [Vigna] (the author of the RNGs used in this crate). The normal distribution
138implementation uses the [Marsaglia polar method], returning pairs of independently sampled `f64` values.
139Exponential variates are generated using [this approach].
140
141[Lemire's method]: https://arxiv.org/abs/1805.10941
142[Lemire]: https://lemire.me/blog/2017/02/28/how-many-floating-point-numbers-are-in-the-interval-01/
143[Vigna]: https://prng.di.unimi.it/#remarks
144[Marsaglia polar method]: https://en.wikipedia.org/wiki/Marsaglia_polar_method
145[this approach]: https://en.wikipedia.org/wiki/Exponential_distribution#Random_variate_generation
146
147## Security
148
149If you're in the market for secure random number generation, this crate provides a secure generator backed
150by a highly optimized ChaCha8 implementation from the [`chachacha`] crate.
151It functions identically to the other provided RNGs, but with added functionality that wouldn't be safe to
152use on pseudo RNGs. Why only 8 rounds? Because people who are very passionate about cryptography are convinced
153that's enough, and I have zero reason to doubt them, nor any capacity to prove them wrong.
154See page 14 of the [`Too Much Crypto`] paper if you're interested in the justification.
155
156The security guarantees made to the user are identical to those made by ChaCha as an algorithm. It is up
157to you to determine if those guarantees meet the demands of your use case.
158
159I reserve the right to change the backing implementation at any time to another RNG which is at least as secure,
160without changing the API or bumping the major/minor version. Realistically, this just means I'm willing to bump
161this to ChaCha12 if ChaCha8 is ever compromised.
162
163[`Too Much Crypto`]: https://eprint.iacr.org/2019/1492
164
165## Safety
166
167Generators are seeded using entropy from the underlying OS, and have the potential to fail during creation.
168But in practice this is extraordinarily unlikely, and isn't something the end-user should ever worry about.
169Modern Windows versions (10 and newer) have a crypto subsystem that will never fail during runtime, and
170rustc can trivially remove the failure branch when compiling binaries for those systems.
171*/
172
173#![no_std]
174#![warn(missing_docs)]
175
176#[cfg(feature = "alloc")]
177extern crate alloc;
178
179#[cfg(feature = "alloc")]
180mod encoding;
181/// Module providing the [`Encoder`](crate::encoding::Encoder) trait and concrete implementations
182/// of the [RFC 4648](https://datatracker.ietf.org/doc/html/rfc4648) encoding schemes.
183#[cfg(feature = "alloc")]
184pub mod ya_rand_encoding {
185    pub use super::encoding::*;
186}
187
188mod rng;
189mod secure;
190mod util;
191mod xoshiro256pp;
192mod xoshiro512pp;
193
194pub use rng::{SecureYARandGenerator, SeedableYARandGenerator, YARandGenerator};
195pub use secure::SecureRng;
196pub use xoshiro256pp::Xoshiro256pp;
197pub use xoshiro512pp::Xoshiro512pp;
198
199/// The recommended generator for all non-cryptographic purposes.
200pub type ShiroRng = Xoshiro256pp;
201
202/// The recommended way to create new PRNG instances.
203///
204/// Identical to calling [`ShiroRng::new`] or [`Xoshiro256pp::new`].
205#[inline]
206pub fn new_rng() -> ShiroRng {
207    ShiroRng::new()
208}
209
210/// The recommended way to create new CRNG instances.
211///
212/// Identical to calling [`SecureRng::new`].
213#[inline]
214pub fn new_rng_secure() -> SecureRng {
215    SecureRng::new()
216}
217
218#[cfg(test)]
219mod tests {
220    use super::*;
221    use alloc::collections::BTreeSet;
222    use ya_rand_encoding::*;
223
224    const ITERATIONS: usize = 10007;
225    const ITERATIONS_LONG: usize = 1 << 24;
226
227    #[test]
228    pub fn ascii_alphabetic() {
229        let mut rng = new_rng();
230        let mut vals = BTreeSet::new();
231        for _ in 0..ITERATIONS {
232            let result = rng.ascii_alphabetic();
233            assert!(result.is_ascii_alphabetic());
234            vals.insert(result);
235        }
236        assert!(vals.len() == 52);
237    }
238
239    #[test]
240    pub fn ascii_uppercase() {
241        let mut rng = new_rng();
242        let mut vals = BTreeSet::new();
243        for _ in 0..ITERATIONS {
244            let result = rng.ascii_uppercase();
245            assert!(result.is_ascii_uppercase());
246            vals.insert(result);
247        }
248        assert!(vals.len() == 26);
249    }
250
251    #[test]
252    pub fn ascii_lowercase() {
253        let mut rng = new_rng();
254        let mut vals = BTreeSet::new();
255        for _ in 0..ITERATIONS {
256            let result = rng.ascii_lowercase();
257            assert!(result.is_ascii_lowercase());
258            vals.insert(result);
259        }
260        assert!(vals.len() == 26);
261    }
262
263    #[test]
264    pub fn ascii_alphanumeric() {
265        let mut rng = new_rng();
266        let mut vals = BTreeSet::new();
267        for _ in 0..ITERATIONS {
268            let result = rng.ascii_alphanumeric();
269            assert!(result.is_ascii_alphanumeric());
270            vals.insert(result);
271        }
272        assert!(vals.len() == 62);
273    }
274
275    #[test]
276    pub fn ascii_digit() {
277        let mut rng = new_rng();
278        let mut vals = BTreeSet::new();
279        for _ in 0..ITERATIONS {
280            let result = rng.ascii_digit();
281            assert!(result.is_ascii_digit());
282            vals.insert(result);
283        }
284        assert!(vals.len() == 10);
285    }
286
287    #[test]
288    fn text_base64() {
289        test_text::<Base64>();
290    }
291
292    #[test]
293    fn text_base64_url() {
294        test_text::<Base64URL>();
295    }
296
297    #[test]
298    fn text_base62() {
299        test_text::<Base62>();
300    }
301
302    #[test]
303    fn text_base32() {
304        test_text::<Base32>();
305    }
306
307    #[test]
308    fn text_base32_hex() {
309        test_text::<Base32Hex>();
310    }
311
312    #[test]
313    fn text_base16() {
314        test_text::<Base16>();
315    }
316
317    #[test]
318    fn text_base16_lowercase() {
319        test_text::<Base16Lowercase>();
320    }
321
322    fn test_text<E: Encoder>() {
323        let s = new_rng_secure().text::<E>(ITERATIONS).unwrap();
324        let distinct_bytes = s.bytes().collect::<BTreeSet<_>>();
325        let distinct_chars = s.chars().collect::<BTreeSet<_>>();
326
327        let lengths_are_equal = ITERATIONS == s.len()
328            && E::CHARSET.len() == distinct_bytes.len()
329            && E::CHARSET.len() == distinct_chars.len();
330        assert!(lengths_are_equal);
331
332        let contains_all_values = E::CHARSET.iter().all(|c| distinct_bytes.contains(c));
333        assert!(contains_all_values);
334    }
335
336    #[test]
337    fn wide_mul() {
338        const SHIFT: u32 = 48;
339        const EXPECTED_HIGH: u64 = 1 << ((SHIFT * 2) - u64::BITS);
340        const EXPECTED_LOW: u64 = 0;
341        let x = 1 << SHIFT;
342        let y = x;
343        // 2^48 * 2^48 = 2^96
344        let (high, low) = util::wide_mul(x, y);
345        assert!(high == EXPECTED_HIGH);
346        assert!(low == EXPECTED_LOW);
347    }
348
349    #[test]
350    fn f64() {
351        let mut rng = new_rng();
352        for _ in 0..ITERATIONS_LONG {
353            let val = rng.f64();
354            assert!(0.0 <= val && val < 1.0);
355        }
356    }
357
358    #[test]
359    fn f32() {
360        let mut rng = new_rng();
361        for _ in 0..ITERATIONS_LONG {
362            let val = rng.f32();
363            assert!(0.0 <= val && val < 1.0);
364        }
365    }
366
367    #[test]
368    fn f64_nonzero() {
369        let mut rng = new_rng();
370        for _ in 0..ITERATIONS_LONG {
371            let val = rng.f64_nonzero();
372            assert!(0.0 < val && val <= 1.0);
373        }
374    }
375
376    #[test]
377    fn f32_nonzero() {
378        let mut rng = new_rng();
379        for _ in 0..ITERATIONS_LONG {
380            let val = rng.f32_nonzero();
381            assert!(0.0 < val && val <= 1.0);
382        }
383    }
384
385    #[test]
386    fn f64_wide() {
387        let mut rng = new_rng();
388        for _ in 0..ITERATIONS_LONG {
389            let val = rng.f64_wide();
390            assert!(val.abs() < 1.0);
391        }
392    }
393
394    #[test]
395    fn f32_wide() {
396        let mut rng = new_rng();
397        for _ in 0..ITERATIONS_LONG {
398            let val = rng.f32_wide();
399            assert!(val.abs() < 1.0);
400        }
401    }
402}