urandom/
lib.rs

1/*!
2Produce and consume randomness.
3
4This crate provides utilities to generate random numbers, to convert them to useful types and distributions, and some randomness-related algorithms.
5
6This library is inspired by the semi-official [`rand`](https://crates.io/crates/rand) crate and an attempt to provide a better experience.
7
8# Quick Start
9
10To get you started quickly, the easiest and highest-level way to get a random value is to use `urandom::new().next()`.
11
12The [`Random`] struct provides a useful API on all [`Rng`], while the [`distr`] module provide specific distributions on top of Rngs.
13
14```
15let mut rand = urandom::new();
16
17// Generates a random boolean
18if rand.coin_flip() {
19	// Try printing a random unicode code point (probably a bad idea)!
20	println!("char: {}", rand.next::<char>());
21}
22
23// Generates a float between 13.0 and 42.0
24let y: f64 = rand.range(13.0..42.0);
25
26// Shuffles the list of numbers
27let mut numbers: Vec<i32> = (1..100).collect();
28rand.shuffle(&mut numbers);
29```
30*/
31
32// Unsafe code is restricted to certain specific Rng implementations
33#![deny(unsafe_code)]
34
35#![cfg_attr(not(any(test, feature = "std")), no_std)]
36
37mod random;
38
39pub mod rng;
40pub mod distr;
41
42pub use self::rng::Rng;
43pub use self::distr::Distribution;
44pub use self::random::Random;
45
46//----------------------------------------------------------------
47
48/// Creates a new instance of the default PRNG.
49///
50/// The generator is seeded securely from the system entropy source.
51///
52/// # Examples
53///
54/// ```
55/// let mut rand = urandom::new();
56/// let value: i32 = rand.next();
57/// ```
58#[must_use]
59#[inline]
60pub fn new() -> Random<impl Rng + Clone> {
61	crate::rng::Xoshiro256::new()
62}
63
64/// Creates a new instance of the default PRNG with the given seed.
65///
66/// The seed does not need to look random, the PRNG constructor ensures it can handle degenerate seed values.
67///
68/// This function guarantees that the same seed always produces the same sequence of randomness.
69///
70/// # Examples
71///
72/// ```
73/// let mut rand = urandom::seeded(42);
74/// let value: i32 = rand.next();
75/// assert_eq!(value, 368317477);
76/// ```
77#[must_use]
78#[inline]
79pub fn seeded(seed: u64) -> Random<impl Rng + Clone> {
80	crate::rng::Xoshiro256::from_seed(seed)
81}
82
83/// Creates a new cryptographically secure PRNG.
84///
85/// The generator is seeded securely from the system entropy source.
86///
87/// # Examples
88///
89/// ```
90/// let mut rand = urandom::csprng();
91/// let value: i32 = rand.next();
92/// ```
93#[must_use]
94#[inline]
95pub fn csprng() -> Random<impl rng::SecureRng + Clone> {
96	crate::rng::ChaCha12::new()
97}