1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
/*!
# 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.
[x86 feature level]: https://en.wikipedia.org/wiki/X86-64#Microarchitecture_levels
## 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.
[xoshiro]: https://prng.di.unimi.it/
[very high statistical quality]: https://vigna.di.unimi.it/ftp/papers/ScrambledLinear.pdf
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.
[romurand]: https://romu-random.org/
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].
[Lemire's method]: https://arxiv.org/abs/1805.10941
[Lemire]: https://lemire.me/blog/2017/02/28/how-many-floating-point-numbers-are-in-the-interval-01/
[Vigna]: https://prng.di.unimi.it/#remarks
[Marsaglia polar method]: https://en.wikipedia.org/wiki/Marsaglia_polar_method
[this approach]: https://en.wikipedia.org/wiki/Exponential_distribution#Random_variate_generation
## 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.
[`Too Much Crypto`]: https://eprint.iacr.org/2019/1492
## 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.
*/
extern crate alloc;
pub use SecureGenerator;
pub use ;
pub use RomuQuad;
pub use RomuTrio;
pub use SecureRng;
pub use Xoshiro256pp;
pub use Xoshiro512pp;
/// The recommended generator for all non-cryptographic purposes.
pub type ShiroRng = Xoshiro256pp;
/// The recommended way to create new PRNG instances.
///
/// Identical to calling [`ShiroRng::new`] or [`Xoshiro256pp::new`].
/// The recommended way to create new CRNG instances.
///
/// Identical to calling [`SecureRng::new`].