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#![deny(missing_docs)]
174#![no_std]
175
176#[cfg(feature = "alloc")]
177extern crate alloc;
178
179#[cfg(feature = "alloc")]
180mod encoding;
181
182/// Module providing the [`Encoder`](crate::encoding::Encoder) trait and concrete implementations
183/// of the [RFC 4648](https://datatracker.ietf.org/doc/html/rfc4648) encoding schemes.
184#[cfg(feature = "alloc")]
185pub mod ya_rand_encoding {
186    pub use super::encoding::*;
187}
188
189mod rng;
190mod secure;
191mod util;
192mod xoshiro256pp;
193mod xoshiro512pp;
194
195pub use rng::{SecureYARandGenerator, SeedableYARandGenerator, YARandGenerator};
196pub use secure::SecureRng;
197pub use xoshiro256pp::Xoshiro256pp;
198pub use xoshiro512pp::Xoshiro512pp;
199
200/// The recommended generator for all non-cryptographic purposes.
201pub type ShiroRng = Xoshiro256pp;
202
203/// The recommended way to create new PRNG instances.
204///
205/// Identical to calling [`ShiroRng::new`] or [`Xoshiro256pp::new`].
206#[inline]
207pub fn new_rng() -> ShiroRng {
208    ShiroRng::new()
209}
210
211/// The recommended way to create new CRNG instances.
212///
213/// Identical to calling [`SecureRng::new`].
214#[inline]
215pub fn new_rng_secure() -> SecureRng {
216    SecureRng::new()
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use alloc::collections::BTreeSet;
223    use ya_rand_encoding::*;
224
225    const ITERATIONS: usize = 10007;
226    const ITERATIONS_LONG: usize = 1 << 24;
227
228    #[test]
229    pub fn ascii_alphabetic() {
230        let mut rng = new_rng();
231        let mut vals = BTreeSet::new();
232        for _ in 0..ITERATIONS {
233            let result = rng.ascii_alphabetic();
234            assert!(result.is_ascii_alphabetic());
235            vals.insert(result);
236        }
237        assert!(vals.len() == 52);
238    }
239
240    #[test]
241    pub fn ascii_uppercase() {
242        let mut rng = new_rng();
243        let mut vals = BTreeSet::new();
244        for _ in 0..ITERATIONS {
245            let result = rng.ascii_uppercase();
246            assert!(result.is_ascii_uppercase());
247            vals.insert(result);
248        }
249        assert!(vals.len() == 26);
250    }
251
252    #[test]
253    pub fn ascii_lowercase() {
254        let mut rng = new_rng();
255        let mut vals = BTreeSet::new();
256        for _ in 0..ITERATIONS {
257            let result = rng.ascii_lowercase();
258            assert!(result.is_ascii_lowercase());
259            vals.insert(result);
260        }
261        assert!(vals.len() == 26);
262    }
263
264    #[test]
265    pub fn ascii_alphanumeric() {
266        let mut rng = new_rng();
267        let mut vals = BTreeSet::new();
268        for _ in 0..ITERATIONS {
269            let result = rng.ascii_alphanumeric();
270            assert!(result.is_ascii_alphanumeric());
271            vals.insert(result);
272        }
273        assert!(vals.len() == 62);
274    }
275
276    #[test]
277    pub fn ascii_digit() {
278        let mut rng = new_rng();
279        let mut vals = BTreeSet::new();
280        for _ in 0..ITERATIONS {
281            let result = rng.ascii_digit();
282            assert!(result.is_ascii_digit());
283            vals.insert(result);
284        }
285        assert!(vals.len() == 10);
286    }
287
288    #[test]
289    fn text_base64() {
290        test_text::<Base64>();
291    }
292
293    #[test]
294    fn text_base64_url() {
295        test_text::<Base64URL>();
296    }
297
298    #[test]
299    fn text_base62() {
300        test_text::<Base62>();
301    }
302
303    #[test]
304    fn text_base32() {
305        test_text::<Base32>();
306    }
307
308    #[test]
309    fn text_base32_hex() {
310        test_text::<Base32Hex>();
311    }
312
313    #[test]
314    fn text_base16() {
315        test_text::<Base16>();
316    }
317
318    #[test]
319    fn text_base16_lowercase() {
320        test_text::<Base16Lowercase>();
321    }
322
323    fn test_text<E: Encoder>() {
324        let s = new_rng_secure().text::<E>(ITERATIONS).unwrap();
325        let distinct_bytes = s.bytes().collect::<BTreeSet<_>>();
326        let distinct_chars = s.chars().collect::<BTreeSet<_>>();
327
328        let lengths_are_equal = ITERATIONS == s.len()
329            && E::CHARSET.len() == distinct_bytes.len()
330            && E::CHARSET.len() == distinct_chars.len();
331        assert!(lengths_are_equal);
332
333        let contains_all_values = E::CHARSET.iter().all(|c| distinct_bytes.contains(c));
334        assert!(contains_all_values);
335    }
336
337    #[test]
338    fn wide_mul() {
339        const SHIFT: u32 = 48;
340        const EXPECTED_HIGH: u64 = 1 << ((SHIFT * 2) - u64::BITS);
341        const EXPECTED_LOW: u64 = 0;
342        let x = 1 << SHIFT;
343        let y = x;
344        // 2^48 * 2^48 = 2^96
345        let (high, low) = util::wide_mul(x, y);
346        assert!(high == EXPECTED_HIGH);
347        assert!(low == EXPECTED_LOW);
348    }
349
350    #[test]
351    fn f64() {
352        let mut rng = new_rng();
353        for _ in 0..ITERATIONS_LONG {
354            let val = rng.f64();
355            assert!(0.0 <= val && val < 1.0);
356        }
357    }
358
359    #[test]
360    fn f32() {
361        let mut rng = new_rng();
362        for _ in 0..ITERATIONS_LONG {
363            let val = rng.f32();
364            assert!(0.0 <= val && val < 1.0);
365        }
366    }
367
368    #[test]
369    fn f64_nonzero() {
370        let mut rng = new_rng();
371        for _ in 0..ITERATIONS_LONG {
372            let val = rng.f64_nonzero();
373            assert!(0.0 < val && val <= 1.0);
374        }
375    }
376
377    #[test]
378    fn f32_nonzero() {
379        let mut rng = new_rng();
380        for _ in 0..ITERATIONS_LONG {
381            let val = rng.f32_nonzero();
382            assert!(0.0 < val && val <= 1.0);
383        }
384    }
385
386    #[test]
387    fn f64_wide() {
388        let mut rng = new_rng();
389        for _ in 0..ITERATIONS_LONG {
390            let val = rng.f64_wide();
391            assert!(val.abs() < 1.0);
392        }
393    }
394
395    #[test]
396    fn f32_wide() {
397        let mut rng = new_rng();
398        for _ in 0..ITERATIONS_LONG {
399            let val = rng.f32_wide();
400            assert!(val.abs() < 1.0);
401        }
402    }
403}