ya_rand/
lib.rs

1/*!
2# YA-Rand: Yet Another Rand
3
4Simple and fast pseudo/crypto random number generation.
5
6## Performance considerations for users of [`SecureRng`]
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 an optimized Chacha8
150implementation via the [`chachacha`] crate. It functions identically to the other provided RNGs, but with added
151functionality that wouldn't be safe to use on pseudo RNGs. Why only 8 rounds? Because people who are very
152passionate about cryptography are convinced that's enough, and I have zero reason to doubt them, nor any capacity
153to prove them wrong. See page 14 of the [`Too Much Crypto`] paper if you're interested in the justification.
154
155The security guarantees made to the user are identical to those made by Chacha as an algorithm. It is up
156to you to determine if those guarantees meet the demands of your use case.
157
158I reserve the right to change the backing implementation at any time to another RNG which is at least as secure,
159without changing the API or bumping the major/minor version. Realistically, this just means I'm willing to bump
160this to Chacha12 if Chacha8 is ever compromised.
161
162[`Too Much Crypto`]: https://eprint.iacr.org/2019/1492
163
164## Safety
165
166Generators are seeded using entropy from the underlying OS, and have the potential to fail during creation.
167But in practice this is extraordinarily unlikely, and isn't something the end-user should ever worry about.
168Modern Windows versions (10 and newer) have a crypto subsystem that will never fail during runtime, and
169rustc can trivially remove the failure branch when compiling binaries for those systems.
170*/
171
172#![no_std]
173
174#[cfg(feature = "alloc")]
175extern crate alloc;
176
177#[cfg(feature = "alloc")]
178mod encoding;
179#[cfg(feature = "alloc")]
180pub mod ya_rand_encoding {
181    pub use super::encoding::*;
182}
183
184mod rng;
185mod secure;
186mod util;
187mod xoshiro256pp;
188mod xoshiro512pp;
189
190pub use rng::{SecureYARandGenerator, SeedableYARandGenerator, YARandGenerator};
191pub use secure::SecureRng;
192pub use xoshiro256pp::Xoshiro256pp;
193pub use xoshiro512pp::Xoshiro512pp;
194
195/// The recommended generator for all non-cryptographic purposes.
196pub type ShiroRng = Xoshiro256pp;
197
198/// The recommended way to create new PRNG instances.
199///
200/// Identical to calling [`ShiroRng::new`] or [`Xoshiro256pp::new`].
201#[inline]
202pub fn new_rng() -> ShiroRng {
203    ShiroRng::new()
204}
205
206/// The recommended way to create new CRNG instances.
207///
208/// Identical to calling [`SecureRng::new`].
209#[inline]
210pub fn new_rng_secure() -> SecureRng {
211    SecureRng::new()
212}
213
214#[cfg(test)]
215mod tests {
216    use super::*;
217    use alloc::collections::BTreeSet;
218    use ya_rand_encoding::*;
219
220    const ITERATIONS: usize = 10007;
221    const ITERATIONS_LONG: usize = 1 << 24;
222
223    #[test]
224    pub fn ascii_alphabetic() {
225        let mut rng = new_rng();
226        let mut vals = BTreeSet::new();
227        for _ in 0..ITERATIONS {
228            let result = rng.ascii_alphabetic();
229            assert!(result.is_ascii_alphabetic());
230            vals.insert(result);
231        }
232        assert!(vals.len() == 52);
233    }
234
235    #[test]
236    pub fn ascii_uppercase() {
237        let mut rng = new_rng();
238        let mut vals = BTreeSet::new();
239        for _ in 0..ITERATIONS {
240            let result = rng.ascii_uppercase();
241            assert!(result.is_ascii_uppercase());
242            vals.insert(result);
243        }
244        assert!(vals.len() == 26);
245    }
246
247    #[test]
248    pub fn ascii_lowercase() {
249        let mut rng = new_rng();
250        let mut vals = BTreeSet::new();
251        for _ in 0..ITERATIONS {
252            let result = rng.ascii_lowercase();
253            assert!(result.is_ascii_lowercase());
254            vals.insert(result);
255        }
256        assert!(vals.len() == 26);
257    }
258
259    #[test]
260    pub fn ascii_alphanumeric() {
261        let mut rng = new_rng();
262        let mut vals = BTreeSet::new();
263        for _ in 0..ITERATIONS {
264            let result = rng.ascii_alphanumeric();
265            assert!(result.is_ascii_alphanumeric());
266            vals.insert(result);
267        }
268        assert!(vals.len() == 62);
269    }
270
271    #[test]
272    pub fn ascii_digit() {
273        let mut rng = new_rng();
274        let mut vals = BTreeSet::new();
275        for _ in 0..ITERATIONS {
276            let result = rng.ascii_digit();
277            assert!(result.is_ascii_digit());
278            vals.insert(result);
279        }
280        assert!(vals.len() == 10);
281    }
282
283    #[test]
284    fn text_base64() {
285        test_text::<Base64>();
286    }
287
288    #[test]
289    fn text_base64_url() {
290        test_text::<Base64URL>();
291    }
292
293    #[test]
294    fn text_base62() {
295        test_text::<Base62>();
296    }
297
298    #[test]
299    fn text_base32() {
300        test_text::<Base32>();
301    }
302
303    #[test]
304    fn text_base32_hex() {
305        test_text::<Base32Hex>();
306    }
307
308    #[test]
309    fn text_base16() {
310        test_text::<Base16>();
311    }
312
313    #[test]
314    fn text_base16_lowercase() {
315        test_text::<Base16Lowercase>();
316    }
317
318    fn test_text<E: Encoder>() {
319        let s = new_rng_secure().text::<E>(ITERATIONS).unwrap();
320        let distinct_bytes = s.bytes().collect::<BTreeSet<_>>();
321        let distinct_chars = s.chars().collect::<BTreeSet<_>>();
322
323        let lengths_are_equal = ITERATIONS == s.len()
324            && E::CHARSET.len() == distinct_bytes.len()
325            && E::CHARSET.len() == distinct_chars.len();
326        assert!(lengths_are_equal);
327
328        let contains_all_values = E::CHARSET.iter().all(|c| distinct_bytes.contains(c));
329        assert!(contains_all_values);
330    }
331
332    #[test]
333    fn wide_mul() {
334        const SHIFT: u32 = 48;
335        const EXPECTED_HIGH: u64 = 1 << ((SHIFT * 2) - u64::BITS);
336        const EXPECTED_LOW: u64 = 0;
337        let x = 1 << SHIFT;
338        let y = x;
339        // 2^48 * 2^48 = 2^96
340        let (high, low) = util::wide_mul(x, y);
341        assert!(high == EXPECTED_HIGH);
342        assert!(low == EXPECTED_LOW);
343    }
344
345    #[test]
346    fn f64() {
347        let mut rng = new_rng();
348        for _ in 0..ITERATIONS_LONG {
349            let val = rng.f64();
350            assert!(0.0 <= val && val < 1.0);
351        }
352    }
353
354    #[test]
355    fn f32() {
356        let mut rng = new_rng();
357        for _ in 0..ITERATIONS_LONG {
358            let val = rng.f32();
359            assert!(0.0 <= val && val < 1.0);
360        }
361    }
362
363    #[test]
364    fn f64_nonzero() {
365        let mut rng = new_rng();
366        for _ in 0..ITERATIONS_LONG {
367            let val = rng.f64_nonzero();
368            assert!(0.0 < val && val <= 1.0);
369        }
370    }
371
372    #[test]
373    fn f32_nonzero() {
374        let mut rng = new_rng();
375        for _ in 0..ITERATIONS_LONG {
376            let val = rng.f32_nonzero();
377            assert!(0.0 < val && val <= 1.0);
378        }
379    }
380
381    #[test]
382    fn f64_wide() {
383        let mut rng = new_rng();
384        for _ in 0..ITERATIONS_LONG {
385            let val = rng.f64_wide();
386            assert!(val.abs() < 1.0);
387        }
388    }
389
390    #[test]
391    fn f32_wide() {
392        let mut rng = new_rng();
393        for _ in 0..ITERATIONS_LONG {
394            let val = rng.f32_wide();
395            assert!(val.abs() < 1.0);
396        }
397    }
398}