| 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 = "simd_support", feature(stdsimd))] | 
|---|
| 53 | #![ cfg_attr(doc_cfg, 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 | #[ allow(unused)] | 
|---|
| 63 | macro_rules! trace { ($($x:tt)*) => ( | 
|---|
| 64 | #[cfg(feature = "log")] { | 
|---|
| 65 | log::trace!($($x)*) | 
|---|
| 66 | } | 
|---|
| 67 | ) } | 
|---|
| 68 | #[ allow(unused)] | 
|---|
| 69 | macro_rules! debug { ($($x:tt)*) => ( | 
|---|
| 70 | #[cfg(feature = "log")] { | 
|---|
| 71 | log::debug!($($x)*) | 
|---|
| 72 | } | 
|---|
| 73 | ) } | 
|---|
| 74 | #[ allow(unused)] | 
|---|
| 75 | macro_rules! info { ($($x:tt)*) => ( | 
|---|
| 76 | #[cfg(feature = "log")] { | 
|---|
| 77 | log::info!($($x)*) | 
|---|
| 78 | } | 
|---|
| 79 | ) } | 
|---|
| 80 | #[ allow(unused)] | 
|---|
| 81 | macro_rules! warn { ($($x:tt)*) => ( | 
|---|
| 82 | #[cfg(feature = "log")] { | 
|---|
| 83 | log::warn!($($x)*) | 
|---|
| 84 | } | 
|---|
| 85 | ) } | 
|---|
| 86 | #[ allow(unused)] | 
|---|
| 87 | macro_rules! error { ($($x:tt)*) => ( | 
|---|
| 88 | #[cfg(feature = "log")] { | 
|---|
| 89 | log::error!($($x)*) | 
|---|
| 90 | } | 
|---|
| 91 | ) } | 
|---|
| 92 |  | 
|---|
| 93 | // Re-exports from rand_core | 
|---|
| 94 | pub use rand_core::{CryptoRng, Error, RngCore, SeedableRng}; | 
|---|
| 95 |  | 
|---|
| 96 | // Public modules | 
|---|
| 97 | pub mod distributions; | 
|---|
| 98 | pub mod prelude; | 
|---|
| 99 | mod rng; | 
|---|
| 100 | pub mod rngs; | 
|---|
| 101 | pub mod seq; | 
|---|
| 102 |  | 
|---|
| 103 | // Public exports | 
|---|
| 104 | #[ cfg(all(feature = "std", feature = "std_rng"))] | 
|---|
| 105 | pub use crate::rngs::thread::thread_rng; | 
|---|
| 106 | pub use rng::{Fill, Rng}; | 
|---|
| 107 |  | 
|---|
| 108 | #[ cfg(all(feature = "std", feature = "std_rng"))] | 
|---|
| 109 | use crate::distributions::{Distribution, Standard}; | 
|---|
| 110 |  | 
|---|
| 111 | /// Generates a random value using the thread-local random number generator. | 
|---|
| 112 | /// | 
|---|
| 113 | /// This is simply a shortcut for `thread_rng().gen()`. See [`thread_rng`] for | 
|---|
| 114 | /// documentation of the entropy source and [`Standard`] for documentation of | 
|---|
| 115 | /// distributions and type-specific generation. | 
|---|
| 116 | /// | 
|---|
| 117 | /// # Provided implementations | 
|---|
| 118 | /// | 
|---|
| 119 | /// The following types have provided implementations that | 
|---|
| 120 | /// generate values with the following ranges and distributions: | 
|---|
| 121 | /// | 
|---|
| 122 | /// * Integers (`i32`, `u32`, `isize`, `usize`, etc.): Uniformly distributed | 
|---|
| 123 | ///   over all values of the type. | 
|---|
| 124 | /// * `char`: Uniformly distributed over all Unicode scalar values, i.e. all | 
|---|
| 125 | ///   code points in the range `0...0x10_FFFF`, except for the range | 
|---|
| 126 | ///   `0xD800...0xDFFF` (the surrogate code points). This includes | 
|---|
| 127 | ///   unassigned/reserved code points. | 
|---|
| 128 | /// * `bool`: Generates `false` or `true`, each with probability 0.5. | 
|---|
| 129 | /// * Floating point types (`f32` and `f64`): Uniformly distributed in the | 
|---|
| 130 | ///   half-open range `[0, 1)`. See notes below. | 
|---|
| 131 | /// * Wrapping integers (`Wrapping<T>`), besides the type identical to their | 
|---|
| 132 | ///   normal integer variants. | 
|---|
| 133 | /// | 
|---|
| 134 | /// Also supported is the generation of the following | 
|---|
| 135 | /// compound types where all component types are supported: | 
|---|
| 136 | /// | 
|---|
| 137 | /// *   Tuples (up to 12 elements): each element is generated sequentially. | 
|---|
| 138 | /// *   Arrays (up to 32 elements): each element is generated sequentially; | 
|---|
| 139 | ///     see also [`Rng::fill`] which supports arbitrary array length for integer | 
|---|
| 140 | ///     types and tends to be faster for `u32` and smaller types. | 
|---|
| 141 | /// *   `Option<T>` first generates a `bool`, and if true generates and returns | 
|---|
| 142 | ///     `Some(value)` where `value: T`, otherwise returning `None`. | 
|---|
| 143 | /// | 
|---|
| 144 | /// # Examples | 
|---|
| 145 | /// | 
|---|
| 146 | /// ``` | 
|---|
| 147 | /// let x = rand::random::<u8>(); | 
|---|
| 148 | /// println!( "{}", x); | 
|---|
| 149 | /// | 
|---|
| 150 | /// let y = rand::random::<f64>(); | 
|---|
| 151 | /// println!( "{}", y); | 
|---|
| 152 | /// | 
|---|
| 153 | /// if rand::random() { // generates a boolean | 
|---|
| 154 | ///     println!( "Better lucky than good!"); | 
|---|
| 155 | /// } | 
|---|
| 156 | /// ``` | 
|---|
| 157 | /// | 
|---|
| 158 | /// If you're calling `random()` in a loop, caching the generator as in the | 
|---|
| 159 | /// following example can increase performance. | 
|---|
| 160 | /// | 
|---|
| 161 | /// ``` | 
|---|
| 162 | /// use rand::Rng; | 
|---|
| 163 | /// | 
|---|
| 164 | /// let mut v = vec![1, 2, 3]; | 
|---|
| 165 | /// | 
|---|
| 166 | /// for x in v.iter_mut() { | 
|---|
| 167 | ///     *x = rand::random() | 
|---|
| 168 | /// } | 
|---|
| 169 | /// | 
|---|
| 170 | /// // can be made faster by caching thread_rng | 
|---|
| 171 | /// | 
|---|
| 172 | /// let mut rng = rand::thread_rng(); | 
|---|
| 173 | /// | 
|---|
| 174 | /// for x in v.iter_mut() { | 
|---|
| 175 | ///     *x = rng.gen(); | 
|---|
| 176 | /// } | 
|---|
| 177 | /// ``` | 
|---|
| 178 | /// | 
|---|
| 179 | /// [`Standard`]: distributions::Standard | 
|---|
| 180 | #[ cfg(all(feature = "std", feature = "std_rng"))] | 
|---|
| 181 | #[ cfg_attr(doc_cfg, doc(cfg(all(feature = "std", feature = "std_rng"))))] | 
|---|
| 182 | #[ inline] | 
|---|
| 183 | pub fn random<T>() -> T | 
|---|
| 184 | where Standard: Distribution<T> { | 
|---|
| 185 | thread_rng().gen() | 
|---|
| 186 | } | 
|---|
| 187 |  | 
|---|
| 188 | #[ cfg(test)] | 
|---|
| 189 | mod test { | 
|---|
| 190 | use super::*; | 
|---|
| 191 |  | 
|---|
| 192 | /// Construct a deterministic RNG with the given seed | 
|---|
| 193 | pub fn rng(seed: u64) -> impl RngCore { | 
|---|
| 194 | // For tests, we want a statistically good, fast, reproducible RNG. | 
|---|
| 195 | // PCG32 will do fine, and will be easy to embed if we ever need to. | 
|---|
| 196 | const INC: u64 = 11634580027462260723; | 
|---|
| 197 | rand_pcg::Pcg32::new(seed, INC) | 
|---|
| 198 | } | 
|---|
| 199 |  | 
|---|
| 200 | #[ test] | 
|---|
| 201 | #[ cfg(all(feature = "std", feature = "std_rng"))] | 
|---|
| 202 | fn test_random() { | 
|---|
| 203 | let _n: usize = random(); | 
|---|
| 204 | let _f: f32 = random(); | 
|---|
| 205 | let _o: Option<Option<i8>> = random(); | 
|---|
| 206 | #[ allow(clippy::type_complexity)] | 
|---|
| 207 | let _many: ( | 
|---|
| 208 | (), | 
|---|
| 209 | (usize, isize, Option<(u32, (bool,))>), | 
|---|
| 210 | (u8, i8, u16, i16, u32, i32, u64, i64), | 
|---|
| 211 | (f32, (f64, (f64,))), | 
|---|
| 212 | ) = random(); | 
|---|
| 213 | } | 
|---|
| 214 | } | 
|---|
| 215 |  | 
|---|