| 1 |
// Copyright 2018 Developers of the Rand project. |
| 2 |
// Copyright 2013-2017 The Rust Project Developers. |
| 3 |
// |
| 4 |
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 5 |
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 6 |
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your |
| 7 |
// option. This file may not be copied, modified, or distributed |
| 8 |
// except according to those terms. |
| 9 |
|
| 10 |
//! Utilities for random number generation |
| 11 |
//! |
| 12 |
//! Rand provides utilities to generate random numbers, to convert them to |
| 13 |
//! useful types and distributions, and some randomness-related algorithms. |
| 14 |
//! |
| 15 |
//! # Quick Start |
| 16 |
//! |
| 17 |
//! To get you started quickly, the easiest and highest-level way to get |
| 18 |
//! a random value is to use [`random()`]; alternatively you can use |
| 19 |
//! [`thread_rng()`]. The [`Rng`] trait provides a useful API on all RNGs, while |
| 20 |
//! the [`distributions`] and [`seq`] modules provide further |
| 21 |
//! functionality on top of RNGs. |
| 22 |
//! |
| 23 |
//! ``` |
| 24 |
//! use rand::prelude::*; |
| 25 |
//! |
| 26 |
//! if rand::random() { // generates a boolean |
| 27 |
//! // Try printing a random unicode code point (probably a bad idea)! |
| 28 |
//! println!("char: {}", rand::random::<char>()); |
| 29 |
//! } |
| 30 |
//! |
| 31 |
//! let mut rng = rand::thread_rng(); |
| 32 |
//! let y: f64 = rng.gen(); // generates a float between 0 and 1 |
| 33 |
//! |
| 34 |
//! let mut nums: Vec<i32> = (1..100).collect(); |
| 35 |
//! nums.shuffle(&mut rng); |
| 36 |
//! ``` |
| 37 |
//! |
| 38 |
//! # The Book |
| 39 |
//! |
| 40 |
//! For the user guide and further documentation, please read |
| 41 |
//! [The Rust Rand Book](https://rust-random.github.io/book). |
| 42 |
|
| 43 |
#![doc( |
| 44 |
html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png", |
| 45 |
html_favicon_url = "https://www.rust-lang.org/favicon.ico", |
| 46 |
html_root_url = "https://rust-random.github.io/rand/" |
| 47 |
)] |
| 48 |
#![deny(missing_docs)] |
| 49 |
#![deny(missing_debug_implementations)] |
| 50 |
#![doc(test(attr(allow(unused_variables), deny(warnings))))] |
| 51 |
#![no_std] |
| 52 |
#![cfg_attr(feature = "nightly", feature(trusted_len))] |
| 53 |
#![cfg_attr(docsrs, feature(doc_cfg))] |
| 54 |
#![allow( |
| 55 |
clippy::float_cmp, |
| 56 |
clippy::neg_cmp_op_on_partial_ord, |
| 57 |
)] |
| 58 |
|
| 59 |
#[cfg(feature = "std")] extern crate std; |
| 60 |
#[cfg(feature = "alloc")] extern crate alloc; |
| 61 |
|
| 62 |
// Re-exports from rand_core |
| 63 |
pub use rand_core::{CryptoRng, Error, RngCore, SeedableRng}; |
| 64 |
|
| 65 |
// Public modules |
| 66 |
pub mod distributions; |
| 67 |
pub mod prelude; |
| 68 |
mod rng; |
| 69 |
pub mod rngs; |
| 70 |
pub mod seq; |
| 71 |
|
| 72 |
// Public exports |
| 73 |
#[cfg(all(feature = "std", feature = "std_rng"))] |
| 74 |
pub use crate::rngs::thread::thread_rng; |
| 75 |
pub use rng::{Fill, Rng}; |
| 76 |
|
| 77 |
#[cfg(all(feature = "std", feature = "std_rng"))] |
| 78 |
use crate::distributions::{Distribution, Standard}; |
| 79 |
|
| 80 |
/// Generates a random value using the thread-local random number generator. |
| 81 |
/// |
| 82 |
/// This is simply a shortcut for `thread_rng().gen()`. See [`thread_rng`] for |
| 83 |
/// documentation of the entropy source and [`Standard`] for documentation of |
| 84 |
/// distributions and type-specific generation. |
| 85 |
/// |
| 86 |
/// # Provided implementations |
| 87 |
/// |
| 88 |
/// The following types have provided implementations that |
| 89 |
/// generate values with the following ranges and distributions: |
| 90 |
/// |
| 91 |
/// * Integers (`i32`, `u32`, `isize`, `usize`, etc.): Uniformly distributed |
| 92 |
/// over all values of the type. |
| 93 |
/// * `char`: Uniformly distributed over all Unicode scalar values, i.e. all |
| 94 |
/// code points in the range `0...0x10_FFFF`, except for the range |
| 95 |
/// `0xD800...0xDFFF` (the surrogate code points). This includes |
| 96 |
/// unassigned/reserved code points. |
| 97 |
/// * `bool`: Generates `false` or `true`, each with probability 0.5. |
| 98 |
/// * Floating point types (`f32` and `f64`): Uniformly distributed in the |
| 99 |
/// half-open range `[0, 1)`. See notes below. |
| 100 |
/// * Wrapping integers (`Wrapping<T>`), besides the type identical to their |
| 101 |
/// normal integer variants. |
| 102 |
/// |
| 103 |
/// Also supported is the generation of the following |
| 104 |
/// compound types where all component types are supported: |
| 105 |
/// |
| 106 |
/// * Tuples (up to 12 elements): each element is generated sequentially. |
| 107 |
/// * Arrays (up to 32 elements): each element is generated sequentially; |
| 108 |
/// see also [`Rng::fill`] which supports arbitrary array length for integer |
| 109 |
/// types and tends to be faster for `u32` and smaller types. |
| 110 |
/// * `Option<T>` first generates a `bool`, and if true generates and returns |
| 111 |
/// `Some(value)` where `value: T`, otherwise returning `None`. |
| 112 |
/// |
| 113 |
/// # Examples |
| 114 |
/// |
| 115 |
/// ``` |
| 116 |
/// let x = rand::random::<u8>(); |
| 117 |
/// println!("{}", x); |
| 118 |
/// |
| 119 |
/// let y = rand::random::<f64>(); |
| 120 |
/// println!("{}", y); |
| 121 |
/// |
| 122 |
/// if rand::random() { // generates a boolean |
| 123 |
/// println!("Better lucky than good!"); |
| 124 |
/// } |
| 125 |
/// ``` |
| 126 |
/// |
| 127 |
/// If you're calling `random()` in a loop, caching the generator as in the |
| 128 |
/// following example can increase performance. |
| 129 |
/// |
| 130 |
/// ``` |
| 131 |
/// use rand::Rng; |
| 132 |
/// |
| 133 |
/// let mut v = vec![1, 2, 3]; |
| 134 |
/// |
| 135 |
/// for x in v.iter_mut() { |
| 136 |
/// *x = rand::random() |
| 137 |
/// } |
| 138 |
/// |
| 139 |
/// // can be made faster by caching thread_rng |
| 140 |
/// |
| 141 |
/// let mut rng = rand::thread_rng(); |
| 142 |
/// |
| 143 |
/// for x in v.iter_mut() { |
| 144 |
/// *x = rng.gen(); |
| 145 |
/// } |
| 146 |
/// ``` |
| 147 |
/// |
| 148 |
/// [`Standard`]: distributions::Standard |
| 149 |
#[cfg(all(feature = "std", feature = "std_rng"))] |
| 150 |
#[cfg_attr(docsrs, doc(cfg(all(feature = "std", feature = "std_rng"))))] |
| 151 |
#[inline] |
| 152 |
pub fn random<T>() -> T |
| 153 |
where Standard: Distribution<T> { |
| 154 |
thread_rng().gen() |
| 155 |
} |
| 156 |
|
| 157 |
#[cfg(test)] |
| 158 |
mod test { |
| 159 |
use super::*; |
| 160 |
|
| 161 |
/// Construct a deterministic RNG with the given seed |
| 162 |
pub fn rng(seed: u64) -> impl RngCore { |
| 163 |
// For tests, we want a statistically good, fast, reproducible RNG. |
| 164 |
// PCG32 will do fine, and will be easy to embed if we ever need to. |
| 165 |
const INC: u64 = 11634580027462260723; |
| 166 |
rand_pcg::Pcg32::new(seed, INC) |
| 167 |
} |
| 168 |
|
| 169 |
#[test] |
| 170 |
#[cfg(all(feature = "std", feature = "std_rng"))] |
| 171 |
fn test_random() { |
| 172 |
let _n: usize = random(); |
| 173 |
let _f: f32 = random(); |
| 174 |
let _o: Option<Option<i8>> = random(); |
| 175 |
#[allow(clippy::type_complexity)] |
| 176 |
let _many: ( |
| 177 |
(), |
| 178 |
(usize, isize, Option<(u32, (bool,))>), |
| 179 |
(u8, i8, u16, i16, u32, i32, u64, i64), |
| 180 |
(f32, (f64, (f64,))), |
| 181 |
) = random(); |
| 182 |
} |
| 183 |
} |