1 // Copyright 2013-2017 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 
11 //! Utilities for random number generation
12 //!
13 //! The key functions are `random()` and `Rng::gen()`. These are polymorphic and
14 //! so can be used to generate any type that implements `Rand`. Type inference
15 //! means that often a simple call to `rand::random()` or `rng.gen()` will
16 //! suffice, but sometimes an annotation is required, e.g.
17 //! `rand::random::<f64>()`.
18 //!
19 //! See the `distributions` submodule for sampling random numbers from
20 //! distributions like normal and exponential.
21 //!
22 //! # Usage
23 //!
24 //! This crate is [on crates.io](https://crates.io/crates/rand) and can be
25 //! used by adding `rand` to the dependencies in your project's `Cargo.toml`.
26 //!
27 //! ```toml
28 //! [dependencies]
29 //! rand = "0.4"
30 //! ```
31 //!
32 //! and this to your crate root:
33 //!
34 //! ```rust
35 //! extern crate rand;
36 //! ```
37 //!
38 //! # Thread-local RNG
39 //!
40 //! There is built-in support for a RNG associated with each thread stored
41 //! in thread-local storage. This RNG can be accessed via `thread_rng`, or
42 //! used implicitly via `random`. This RNG is normally randomly seeded
43 //! from an operating-system source of randomness, e.g. `/dev/urandom` on
44 //! Unix systems, and will automatically reseed itself from this source
45 //! after generating 32 KiB of random data.
46 //!
47 //! # Cryptographic security
48 //!
49 //! An application that requires an entropy source for cryptographic purposes
50 //! must use `OsRng`, which reads randomness from the source that the operating
51 //! system provides (e.g. `/dev/urandom` on Unixes or `CryptGenRandom()` on
52 //! Windows).
53 //! The other random number generators provided by this module are not suitable
54 //! for such purposes.
55 //!
56 //! *Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
57 //! This module uses `/dev/urandom` for the following reasons:
58 //!
59 //! -   On Linux, `/dev/random` may block if entropy pool is empty;
60 //!     `/dev/urandom` will not block.  This does not mean that `/dev/random`
61 //!     provides better output than `/dev/urandom`; the kernel internally runs a
62 //!     cryptographically secure pseudorandom number generator (CSPRNG) based on
63 //!     entropy pool for random number generation, so the "quality" of
64 //!     `/dev/random` is not better than `/dev/urandom` in most cases.  However,
65 //!     this means that `/dev/urandom` can yield somewhat predictable randomness
66 //!     if the entropy pool is very small, such as immediately after first
67 //!     booting.  Linux 3.17 added the `getrandom(2)` system call which solves
68 //!     the issue: it blocks if entropy pool is not initialized yet, but it does
69 //!     not block once initialized.  `OsRng` tries to use `getrandom(2)` if
70 //!     available, and use `/dev/urandom` fallback if not.  If an application
71 //!     does not have `getrandom` and likely to be run soon after first booting,
72 //!     or on a system with very few entropy sources, one should consider using
73 //!     `/dev/random` via `ReadRng`.
74 //! -   On some systems (e.g. FreeBSD, OpenBSD and Mac OS X) there is no
75 //!     difference between the two sources. (Also note that, on some systems
76 //!     e.g.  FreeBSD, both `/dev/random` and `/dev/urandom` may block once if
77 //!     the CSPRNG has not seeded yet.)
78 //!
79 //! # Examples
80 //!
81 //! ```rust
82 //! use rand::Rng;
83 //!
84 //! let mut rng = rand::thread_rng();
85 //! if rng.gen() { // random bool
86 //!     println!("i32: {}, u32: {}", rng.gen::<i32>(), rng.gen::<u32>())
87 //! }
88 //! ```
89 //!
90 //! ```rust
91 //! let tuple = rand::random::<(f64, char)>();
92 //! println!("{:?}", tuple)
93 //! ```
94 //!
95 //! ## Monte Carlo estimation of π
96 //!
97 //! For this example, imagine we have a square with sides of length 2 and a unit
98 //! circle, both centered at the origin. Since the area of a unit circle is π,
99 //! we have:
100 //!
101 //! ```text
102 //!     (area of unit circle) / (area of square) = π / 4
103 //! ```
104 //!
105 //! So if we sample many points randomly from the square, roughly π / 4 of them
106 //! should be inside the circle.
107 //!
108 //! We can use the above fact to estimate the value of π: pick many points in
109 //! the square at random, calculate the fraction that fall within the circle,
110 //! and multiply this fraction by 4.
111 //!
112 //! ```
113 //! use rand::distributions::{IndependentSample, Range};
114 //!
115 //! fn main() {
116 //!    let between = Range::new(-1f64, 1.);
117 //!    let mut rng = rand::thread_rng();
118 //!
119 //!    let total = 1_000_000;
120 //!    let mut in_circle = 0;
121 //!
122 //!    for _ in 0..total {
123 //!        let a = between.ind_sample(&mut rng);
124 //!        let b = between.ind_sample(&mut rng);
125 //!        if a*a + b*b <= 1. {
126 //!            in_circle += 1;
127 //!        }
128 //!    }
129 //!
130 //!    // prints something close to 3.14159...
131 //!    println!("{}", 4. * (in_circle as f64) / (total as f64));
132 //! }
133 //! ```
134 //!
135 //! ## Monty Hall Problem
136 //!
137 //! This is a simulation of the [Monty Hall Problem][]:
138 //!
139 //! > Suppose you're on a game show, and you're given the choice of three doors:
140 //! > Behind one door is a car; behind the others, goats. You pick a door, say
141 //! > No. 1, and the host, who knows what's behind the doors, opens another
142 //! > door, say No. 3, which has a goat. He then says to you, "Do you want to
143 //! > pick door No. 2?" Is it to your advantage to switch your choice?
144 //!
145 //! The rather unintuitive answer is that you will have a 2/3 chance of winning
146 //! if you switch and a 1/3 chance of winning if you don't, so it's better to
147 //! switch.
148 //!
149 //! This program will simulate the game show and with large enough simulation
150 //! steps it will indeed confirm that it is better to switch.
151 //!
152 //! [Monty Hall Problem]: http://en.wikipedia.org/wiki/Monty_Hall_problem
153 //!
154 //! ```
155 //! use rand::Rng;
156 //! use rand::distributions::{IndependentSample, Range};
157 //!
158 //! struct SimulationResult {
159 //!     win: bool,
160 //!     switch: bool,
161 //! }
162 //!
163 //! // Run a single simulation of the Monty Hall problem.
164 //! fn simulate<R: Rng>(random_door: &Range<u32>, rng: &mut R)
165 //!                     -> SimulationResult {
166 //!     let car = random_door.ind_sample(rng);
167 //!
168 //!     // This is our initial choice
169 //!     let mut choice = random_door.ind_sample(rng);
170 //!
171 //!     // The game host opens a door
172 //!     let open = game_host_open(car, choice, rng);
173 //!
174 //!     // Shall we switch?
175 //!     let switch = rng.gen();
176 //!     if switch {
177 //!         choice = switch_door(choice, open);
178 //!     }
179 //!
180 //!     SimulationResult { win: choice == car, switch: switch }
181 //! }
182 //!
183 //! // Returns the door the game host opens given our choice and knowledge of
184 //! // where the car is. The game host will never open the door with the car.
185 //! fn game_host_open<R: Rng>(car: u32, choice: u32, rng: &mut R) -> u32 {
186 //!     let choices = free_doors(&[car, choice]);
187 //!     rand::seq::sample_slice(rng, &choices, 1)[0]
188 //! }
189 //!
190 //! // Returns the door we switch to, given our current choice and
191 //! // the open door. There will only be one valid door.
192 //! fn switch_door(choice: u32, open: u32) -> u32 {
193 //!     free_doors(&[choice, open])[0]
194 //! }
195 //!
196 //! fn free_doors(blocked: &[u32]) -> Vec<u32> {
197 //!     (0..3).filter(|x| !blocked.contains(x)).collect()
198 //! }
199 //!
200 //! fn main() {
201 //!     // The estimation will be more accurate with more simulations
202 //!     let num_simulations = 10000;
203 //!
204 //!     let mut rng = rand::thread_rng();
205 //!     let random_door = Range::new(0, 3);
206 //!
207 //!     let (mut switch_wins, mut switch_losses) = (0, 0);
208 //!     let (mut keep_wins, mut keep_losses) = (0, 0);
209 //!
210 //!     println!("Running {} simulations...", num_simulations);
211 //!     for _ in 0..num_simulations {
212 //!         let result = simulate(&random_door, &mut rng);
213 //!
214 //!         match (result.win, result.switch) {
215 //!             (true, true) => switch_wins += 1,
216 //!             (true, false) => keep_wins += 1,
217 //!             (false, true) => switch_losses += 1,
218 //!             (false, false) => keep_losses += 1,
219 //!         }
220 //!     }
221 //!
222 //!     let total_switches = switch_wins + switch_losses;
223 //!     let total_keeps = keep_wins + keep_losses;
224 //!
225 //!     println!("Switched door {} times with {} wins and {} losses",
226 //!              total_switches, switch_wins, switch_losses);
227 //!
228 //!     println!("Kept our choice {} times with {} wins and {} losses",
229 //!              total_keeps, keep_wins, keep_losses);
230 //!
231 //!     // With a large number of simulations, the values should converge to
232 //!     // 0.667 and 0.333 respectively.
233 //!     println!("Estimated chance to win if we switch: {}",
234 //!              switch_wins as f32 / total_switches as f32);
235 //!     println!("Estimated chance to win if we don't: {}",
236 //!              keep_wins as f32 / total_keeps as f32);
237 //! }
238 //! ```
239 
240 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
241        html_favicon_url = "https://www.rust-lang.org/favicon.ico",
242        html_root_url = "https://docs.rs/rand/0.3")]
243 
244 #![deny(missing_debug_implementations)]
245 
246 #![cfg_attr(not(feature="std"), no_std)]
247 #![cfg_attr(all(feature="alloc", not(feature="std")), feature(alloc))]
248 #![cfg_attr(feature = "i128_support", feature(i128_type, i128))]
249 
250 #[cfg(feature="std")] extern crate std as core;
251 #[cfg(all(feature = "alloc", not(feature="std")))] extern crate alloc;
252 
253 use core::marker;
254 use core::mem;
255 #[cfg(feature="std")] use std::cell::RefCell;
256 #[cfg(feature="std")] use std::io;
257 #[cfg(feature="std")] use std::rc::Rc;
258 
259 // external rngs
260 pub use jitter::JitterRng;
261 #[cfg(feature="std")] pub use os::OsRng;
262 
263 // pseudo rngs
264 pub use isaac::{IsaacRng, Isaac64Rng};
265 pub use chacha::ChaChaRng;
266 pub use prng::XorShiftRng;
267 
268 // local use declarations
269 #[cfg(target_pointer_width = "32")]
270 use prng::IsaacRng as IsaacWordRng;
271 #[cfg(target_pointer_width = "64")]
272 use prng::Isaac64Rng as IsaacWordRng;
273 
274 use distributions::{Range, IndependentSample};
275 use distributions::range::SampleRange;
276 
277 // public modules
278 pub mod distributions;
279 pub mod jitter;
280 #[cfg(feature="std")] pub mod os;
281 #[cfg(feature="std")] pub mod read;
282 pub mod reseeding;
283 #[cfg(any(feature="std", feature = "alloc"))] pub mod seq;
284 
285 // These tiny modules are here to avoid API breakage, probably only temporarily
286 pub mod chacha {
287     //! The ChaCha random number generator.
288     pub use prng::ChaChaRng;
289 }
290 pub mod isaac {
291     //! The ISAAC random number generator.
292     pub use prng::{IsaacRng, Isaac64Rng};
293 }
294 
295 // private modules
296 mod rand_impls;
297 mod prng;
298 
299 
300 /// A type that can be randomly generated using an `Rng`.
301 ///
302 /// ## Built-in Implementations
303 ///
304 /// This crate implements `Rand` for various primitive types.  Assuming the
305 /// provided `Rng` is well-behaved, these implementations generate values with
306 /// the following ranges and distributions:
307 ///
308 /// * Integers (`i32`, `u32`, `isize`, `usize`, etc.): Uniformly distributed
309 ///   over all values of the type.
310 /// * `char`: Uniformly distributed over all Unicode scalar values, i.e. all
311 ///   code points in the range `0...0x10_FFFF`, except for the range
312 ///   `0xD800...0xDFFF` (the surrogate code points).  This includes
313 ///   unassigned/reserved code points.
314 /// * `bool`: Generates `false` or `true`, each with probability 0.5.
315 /// * Floating point types (`f32` and `f64`): Uniformly distributed in the
316 ///   half-open range `[0, 1)`.  (The [`Open01`], [`Closed01`], [`Exp1`], and
317 ///   [`StandardNormal`] wrapper types produce floating point numbers with
318 ///   alternative ranges or distributions.)
319 ///
320 /// [`Open01`]: struct.Open01.html
321 /// [`Closed01`]: struct.Closed01.html
322 /// [`Exp1`]: distributions/exponential/struct.Exp1.html
323 /// [`StandardNormal`]: distributions/normal/struct.StandardNormal.html
324 ///
325 /// The following aggregate types also implement `Rand` as long as their
326 /// component types implement it:
327 ///
328 /// * Tuples and arrays: Each element of the tuple or array is generated
329 ///   independently, using its own `Rand` implementation.
330 /// * `Option<T>`: Returns `None` with probability 0.5; otherwise generates a
331 ///   random `T` and returns `Some(T)`.
332 pub trait Rand : Sized {
333     /// Generates a random instance of this type using the specified source of
334     /// randomness.
rand<R: Rng>(rng: &mut R) -> Self335     fn rand<R: Rng>(rng: &mut R) -> Self;
336 }
337 
338 /// A random number generator.
339 pub trait Rng {
340     /// Return the next random u32.
341     ///
342     /// This rarely needs to be called directly, prefer `r.gen()` to
343     /// `r.next_u32()`.
344     // FIXME #rust-lang/rfcs#628: Should be implemented in terms of next_u64
next_u32(&mut self) -> u32345     fn next_u32(&mut self) -> u32;
346 
347     /// Return the next random u64.
348     ///
349     /// By default this is implemented in terms of `next_u32`. An
350     /// implementation of this trait must provide at least one of
351     /// these two methods. Similarly to `next_u32`, this rarely needs
352     /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
next_u64(&mut self) -> u64353     fn next_u64(&mut self) -> u64 {
354         ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
355     }
356 
357     /// Return the next random f32 selected from the half-open
358     /// interval `[0, 1)`.
359     ///
360     /// This uses a technique described by Saito and Matsumoto at
361     /// MCQMC'08. Given that the IEEE floating point numbers are
362     /// uniformly distributed over [1,2), we generate a number in
363     /// this range and then offset it onto the range [0,1). Our
364     /// choice of bits (masking v. shifting) is arbitrary and
365     /// should be immaterial for high quality generators. For low
366     /// quality generators (ex. LCG), prefer bitshifting due to
367     /// correlation between sequential low order bits.
368     ///
369     /// See:
370     /// A PRNG specialized in double precision floating point numbers using
371     /// an affine transition
372     ///
373     /// * <http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/ARTICLES/dSFMT.pdf>
374     /// * <http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/dSFMT-slide-e.pdf>
375     ///
376     /// By default this is implemented in terms of `next_u32`, but a
377     /// random number generator which can generate numbers satisfying
378     /// the requirements directly can overload this for performance.
379     /// It is required that the return value lies in `[0, 1)`.
380     ///
381     /// See `Closed01` for the closed interval `[0,1]`, and
382     /// `Open01` for the open interval `(0,1)`.
next_f32(&mut self) -> f32383     fn next_f32(&mut self) -> f32 {
384         const UPPER_MASK: u32 = 0x3F800000;
385         const LOWER_MASK: u32 = 0x7FFFFF;
386         let tmp = UPPER_MASK | (self.next_u32() & LOWER_MASK);
387         let result: f32 = unsafe { mem::transmute(tmp) };
388         result - 1.0
389     }
390 
391     /// Return the next random f64 selected from the half-open
392     /// interval `[0, 1)`.
393     ///
394     /// By default this is implemented in terms of `next_u64`, but a
395     /// random number generator which can generate numbers satisfying
396     /// the requirements directly can overload this for performance.
397     /// It is required that the return value lies in `[0, 1)`.
398     ///
399     /// See `Closed01` for the closed interval `[0,1]`, and
400     /// `Open01` for the open interval `(0,1)`.
next_f64(&mut self) -> f64401     fn next_f64(&mut self) -> f64 {
402         const UPPER_MASK: u64 = 0x3FF0000000000000;
403         const LOWER_MASK: u64 = 0xFFFFFFFFFFFFF;
404         let tmp = UPPER_MASK | (self.next_u64() & LOWER_MASK);
405         let result: f64 = unsafe { mem::transmute(tmp) };
406         result - 1.0
407     }
408 
409     /// Fill `dest` with random data.
410     ///
411     /// This has a default implementation in terms of `next_u64` and
412     /// `next_u32`, but should be overridden by implementations that
413     /// offer a more efficient solution than just calling those
414     /// methods repeatedly.
415     ///
416     /// This method does *not* have a requirement to bear any fixed
417     /// relationship to the other methods, for example, it does *not*
418     /// have to result in the same output as progressively filling
419     /// `dest` with `self.gen::<u8>()`, and any such behaviour should
420     /// not be relied upon.
421     ///
422     /// This method should guarantee that `dest` is entirely filled
423     /// with new data, and may panic if this is impossible
424     /// (e.g. reading past the end of a file that is being used as the
425     /// source of randomness).
426     ///
427     /// # Example
428     ///
429     /// ```rust
430     /// use rand::{thread_rng, Rng};
431     ///
432     /// let mut v = [0u8; 13579];
433     /// thread_rng().fill_bytes(&mut v);
434     /// println!("{:?}", &v[..]);
435     /// ```
fill_bytes(&mut self, dest: &mut [u8])436     fn fill_bytes(&mut self, dest: &mut [u8]) {
437         // this could, in theory, be done by transmuting dest to a
438         // [u64], but this is (1) likely to be undefined behaviour for
439         // LLVM, (2) has to be very careful about alignment concerns,
440         // (3) adds more `unsafe` that needs to be checked, (4)
441         // probably doesn't give much performance gain if
442         // optimisations are on.
443         let mut count = 0;
444         let mut num = 0;
445         for byte in dest.iter_mut() {
446             if count == 0 {
447                 // we could micro-optimise here by generating a u32 if
448                 // we only need a few more bytes to fill the vector
449                 // (i.e. at most 4).
450                 num = self.next_u64();
451                 count = 8;
452             }
453 
454             *byte = (num & 0xff) as u8;
455             num >>= 8;
456             count -= 1;
457         }
458     }
459 
460     /// Return a random value of a `Rand` type.
461     ///
462     /// # Example
463     ///
464     /// ```rust
465     /// use rand::{thread_rng, Rng};
466     ///
467     /// let mut rng = thread_rng();
468     /// let x: u32 = rng.gen();
469     /// println!("{}", x);
470     /// println!("{:?}", rng.gen::<(f64, bool)>());
471     /// ```
472     #[inline(always)]
gen<T: Rand>(&mut self) -> T where Self: Sized473     fn gen<T: Rand>(&mut self) -> T where Self: Sized {
474         Rand::rand(self)
475     }
476 
477     /// Return an iterator that will yield an infinite number of randomly
478     /// generated items.
479     ///
480     /// # Example
481     ///
482     /// ```
483     /// use rand::{thread_rng, Rng};
484     ///
485     /// let mut rng = thread_rng();
486     /// let x = rng.gen_iter::<u32>().take(10).collect::<Vec<u32>>();
487     /// println!("{:?}", x);
488     /// println!("{:?}", rng.gen_iter::<(f64, bool)>().take(5)
489     ///                     .collect::<Vec<(f64, bool)>>());
490     /// ```
gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> where Self: Sized491     fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> where Self: Sized {
492         Generator { rng: self, _marker: marker::PhantomData }
493     }
494 
495     /// Generate a random value in the range [`low`, `high`).
496     ///
497     /// This is a convenience wrapper around
498     /// `distributions::Range`. If this function will be called
499     /// repeatedly with the same arguments, one should use `Range`, as
500     /// that will amortize the computations that allow for perfect
501     /// uniformity, as they only happen on initialization.
502     ///
503     /// # Panics
504     ///
505     /// Panics if `low >= high`.
506     ///
507     /// # Example
508     ///
509     /// ```rust
510     /// use rand::{thread_rng, Rng};
511     ///
512     /// let mut rng = thread_rng();
513     /// let n: u32 = rng.gen_range(0, 10);
514     /// println!("{}", n);
515     /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
516     /// println!("{}", m);
517     /// ```
gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T where Self: Sized518     fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T where Self: Sized {
519         assert!(low < high, "Rng.gen_range called with low >= high");
520         Range::new(low, high).ind_sample(self)
521     }
522 
523     /// Return a bool with a 1 in n chance of true
524     ///
525     /// # Example
526     ///
527     /// ```rust
528     /// use rand::{thread_rng, Rng};
529     ///
530     /// let mut rng = thread_rng();
531     /// println!("{}", rng.gen_weighted_bool(3));
532     /// ```
gen_weighted_bool(&mut self, n: u32) -> bool where Self: Sized533     fn gen_weighted_bool(&mut self, n: u32) -> bool where Self: Sized {
534         n <= 1 || self.gen_range(0, n) == 0
535     }
536 
537     /// Return an iterator of random characters from the set A-Z,a-z,0-9.
538     ///
539     /// # Example
540     ///
541     /// ```rust
542     /// use rand::{thread_rng, Rng};
543     ///
544     /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
545     /// println!("{}", s);
546     /// ```
gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> where Self: Sized547     fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> where Self: Sized {
548         AsciiGenerator { rng: self }
549     }
550 
551     /// Return a random element from `values`.
552     ///
553     /// Return `None` if `values` is empty.
554     ///
555     /// # Example
556     ///
557     /// ```
558     /// use rand::{thread_rng, Rng};
559     ///
560     /// let choices = [1, 2, 4, 8, 16, 32];
561     /// let mut rng = thread_rng();
562     /// println!("{:?}", rng.choose(&choices));
563     /// assert_eq!(rng.choose(&choices[..0]), None);
564     /// ```
choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> where Self: Sized565     fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> where Self: Sized {
566         if values.is_empty() {
567             None
568         } else {
569             Some(&values[self.gen_range(0, values.len())])
570         }
571     }
572 
573     /// Return a mutable pointer to a random element from `values`.
574     ///
575     /// Return `None` if `values` is empty.
choose_mut<'a, T>(&mut self, values: &'a mut [T]) -> Option<&'a mut T> where Self: Sized576     fn choose_mut<'a, T>(&mut self, values: &'a mut [T]) -> Option<&'a mut T> where Self: Sized {
577         if values.is_empty() {
578             None
579         } else {
580             let len = values.len();
581             Some(&mut values[self.gen_range(0, len)])
582         }
583     }
584 
585     /// Shuffle a mutable slice in place.
586     ///
587     /// This applies Durstenfeld's algorithm for the [Fisher–Yates shuffle](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm)
588     /// which produces an unbiased permutation.
589     ///
590     /// # Example
591     ///
592     /// ```rust
593     /// use rand::{thread_rng, Rng};
594     ///
595     /// let mut rng = thread_rng();
596     /// let mut y = [1, 2, 3];
597     /// rng.shuffle(&mut y);
598     /// println!("{:?}", y);
599     /// rng.shuffle(&mut y);
600     /// println!("{:?}", y);
601     /// ```
shuffle<T>(&mut self, values: &mut [T]) where Self: Sized602     fn shuffle<T>(&mut self, values: &mut [T]) where Self: Sized {
603         let mut i = values.len();
604         while i >= 2 {
605             // invariant: elements with index >= i have been locked in place.
606             i -= 1;
607             // lock element i in place.
608             values.swap(i, self.gen_range(0, i + 1));
609         }
610     }
611 }
612 
613 impl<'a, R: ?Sized> Rng for &'a mut R where R: Rng {
next_u32(&mut self) -> u32614     fn next_u32(&mut self) -> u32 {
615         (**self).next_u32()
616     }
617 
next_u64(&mut self) -> u64618     fn next_u64(&mut self) -> u64 {
619         (**self).next_u64()
620     }
621 
next_f32(&mut self) -> f32622     fn next_f32(&mut self) -> f32 {
623         (**self).next_f32()
624     }
625 
next_f64(&mut self) -> f64626     fn next_f64(&mut self) -> f64 {
627         (**self).next_f64()
628     }
629 
fill_bytes(&mut self, dest: &mut [u8])630     fn fill_bytes(&mut self, dest: &mut [u8]) {
631         (**self).fill_bytes(dest)
632     }
633 }
634 
635 #[cfg(feature="std")]
636 impl<R: ?Sized> Rng for Box<R> where R: Rng {
next_u32(&mut self) -> u32637     fn next_u32(&mut self) -> u32 {
638         (**self).next_u32()
639     }
640 
next_u64(&mut self) -> u64641     fn next_u64(&mut self) -> u64 {
642         (**self).next_u64()
643     }
644 
next_f32(&mut self) -> f32645     fn next_f32(&mut self) -> f32 {
646         (**self).next_f32()
647     }
648 
next_f64(&mut self) -> f64649     fn next_f64(&mut self) -> f64 {
650         (**self).next_f64()
651     }
652 
fill_bytes(&mut self, dest: &mut [u8])653     fn fill_bytes(&mut self, dest: &mut [u8]) {
654         (**self).fill_bytes(dest)
655     }
656 }
657 
658 /// Iterator which will generate a stream of random items.
659 ///
660 /// This iterator is created via the [`gen_iter`] method on [`Rng`].
661 ///
662 /// [`gen_iter`]: trait.Rng.html#method.gen_iter
663 /// [`Rng`]: trait.Rng.html
664 #[derive(Debug)]
665 pub struct Generator<'a, T, R:'a> {
666     rng: &'a mut R,
667     _marker: marker::PhantomData<fn() -> T>,
668 }
669 
670 impl<'a, T: Rand, R: Rng> Iterator for Generator<'a, T, R> {
671     type Item = T;
672 
next(&mut self) -> Option<T>673     fn next(&mut self) -> Option<T> {
674         Some(self.rng.gen())
675     }
676 }
677 
678 /// Iterator which will continuously generate random ascii characters.
679 ///
680 /// This iterator is created via the [`gen_ascii_chars`] method on [`Rng`].
681 ///
682 /// [`gen_ascii_chars`]: trait.Rng.html#method.gen_ascii_chars
683 /// [`Rng`]: trait.Rng.html
684 #[derive(Debug)]
685 pub struct AsciiGenerator<'a, R:'a> {
686     rng: &'a mut R,
687 }
688 
689 impl<'a, R: Rng> Iterator for AsciiGenerator<'a, R> {
690     type Item = char;
691 
next(&mut self) -> Option<char>692     fn next(&mut self) -> Option<char> {
693         const GEN_ASCII_STR_CHARSET: &'static [u8] =
694             b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
695               abcdefghijklmnopqrstuvwxyz\
696               0123456789";
697         Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
698     }
699 }
700 
701 /// A random number generator that can be explicitly seeded to produce
702 /// the same stream of randomness multiple times.
703 pub trait SeedableRng<Seed>: Rng {
704     /// Reseed an RNG with the given seed.
705     ///
706     /// # Example
707     ///
708     /// ```rust
709     /// use rand::{Rng, SeedableRng, StdRng};
710     ///
711     /// let seed: &[_] = &[1, 2, 3, 4];
712     /// let mut rng: StdRng = SeedableRng::from_seed(seed);
713     /// println!("{}", rng.gen::<f64>());
714     /// rng.reseed(&[5, 6, 7, 8]);
715     /// println!("{}", rng.gen::<f64>());
716     /// ```
reseed(&mut self, Seed)717     fn reseed(&mut self, Seed);
718 
719     /// Create a new RNG with the given seed.
720     ///
721     /// # Example
722     ///
723     /// ```rust
724     /// use rand::{Rng, SeedableRng, StdRng};
725     ///
726     /// let seed: &[_] = &[1, 2, 3, 4];
727     /// let mut rng: StdRng = SeedableRng::from_seed(seed);
728     /// println!("{}", rng.gen::<f64>());
729     /// ```
from_seed(seed: Seed) -> Self730     fn from_seed(seed: Seed) -> Self;
731 }
732 
733 /// A wrapper for generating floating point numbers uniformly in the
734 /// open interval `(0,1)` (not including either endpoint).
735 ///
736 /// Use `Closed01` for the closed interval `[0,1]`, and the default
737 /// `Rand` implementation for `f32` and `f64` for the half-open
738 /// `[0,1)`.
739 ///
740 /// # Example
741 /// ```rust
742 /// use rand::{random, Open01};
743 ///
744 /// let Open01(val) = random::<Open01<f32>>();
745 /// println!("f32 from (0,1): {}", val);
746 /// ```
747 #[derive(Debug)]
748 pub struct Open01<F>(pub F);
749 
750 /// A wrapper for generating floating point numbers uniformly in the
751 /// closed interval `[0,1]` (including both endpoints).
752 ///
753 /// Use `Open01` for the closed interval `(0,1)`, and the default
754 /// `Rand` implementation of `f32` and `f64` for the half-open
755 /// `[0,1)`.
756 ///
757 /// # Example
758 ///
759 /// ```rust
760 /// use rand::{random, Closed01};
761 ///
762 /// let Closed01(val) = random::<Closed01<f32>>();
763 /// println!("f32 from [0,1]: {}", val);
764 /// ```
765 #[derive(Debug)]
766 pub struct Closed01<F>(pub F);
767 
768 /// The standard RNG. This is designed to be efficient on the current
769 /// platform.
770 #[derive(Copy, Clone, Debug)]
771 pub struct StdRng {
772     rng: IsaacWordRng,
773 }
774 
775 impl StdRng {
776     /// Create a randomly seeded instance of `StdRng`.
777     ///
778     /// This is a very expensive operation as it has to read
779     /// randomness from the operating system and use this in an
780     /// expensive seeding operation. If one is only generating a small
781     /// number of random numbers, or doesn't need the utmost speed for
782     /// generating each number, `thread_rng` and/or `random` may be more
783     /// appropriate.
784     ///
785     /// Reading the randomness from the OS may fail, and any error is
786     /// propagated via the `io::Result` return value.
787     #[cfg(feature="std")]
new() -> io::Result<StdRng>788     pub fn new() -> io::Result<StdRng> {
789         match OsRng::new() {
790             Ok(mut r) => Ok(StdRng { rng: r.gen() }),
791             Err(e1) => {
792                 match JitterRng::new() {
793                     Ok(mut r) => Ok(StdRng { rng: r.gen() }),
794                     Err(_) => {
795                         Err(e1)
796                     }
797                 }
798             }
799         }
800     }
801 }
802 
803 impl Rng for StdRng {
804     #[inline]
next_u32(&mut self) -> u32805     fn next_u32(&mut self) -> u32 {
806         self.rng.next_u32()
807     }
808 
809     #[inline]
next_u64(&mut self) -> u64810     fn next_u64(&mut self) -> u64 {
811         self.rng.next_u64()
812     }
813 }
814 
815 impl<'a> SeedableRng<&'a [usize]> for StdRng {
reseed(&mut self, seed: &'a [usize])816     fn reseed(&mut self, seed: &'a [usize]) {
817         // the internal RNG can just be seeded from the above
818         // randomness.
819         self.rng.reseed(unsafe {mem::transmute(seed)})
820     }
821 
from_seed(seed: &'a [usize]) -> StdRng822     fn from_seed(seed: &'a [usize]) -> StdRng {
823         StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
824     }
825 }
826 
827 /// Create a weak random number generator with a default algorithm and seed.
828 ///
829 /// It returns the fastest `Rng` algorithm currently available in Rust without
830 /// consideration for cryptography or security. If you require a specifically
831 /// seeded `Rng` for consistency over time you should pick one algorithm and
832 /// create the `Rng` yourself.
833 ///
834 /// This will seed the generator with randomness from thread_rng.
835 #[cfg(feature="std")]
weak_rng() -> XorShiftRng836 pub fn weak_rng() -> XorShiftRng {
837     thread_rng().gen()
838 }
839 
840 /// Controls how the thread-local RNG is reseeded.
841 #[cfg(feature="std")]
842 #[derive(Debug)]
843 struct ThreadRngReseeder;
844 
845 #[cfg(feature="std")]
846 impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
reseed(&mut self, rng: &mut StdRng)847     fn reseed(&mut self, rng: &mut StdRng) {
848         match StdRng::new() {
849             Ok(r) => *rng = r,
850             Err(e) => panic!("No entropy available: {}", e),
851         }
852     }
853 }
854 #[cfg(feature="std")]
855 const THREAD_RNG_RESEED_THRESHOLD: u64 = 32_768;
856 #[cfg(feature="std")]
857 type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
858 
859 /// The thread-local RNG.
860 #[cfg(feature="std")]
861 #[derive(Clone, Debug)]
862 pub struct ThreadRng {
863     rng: Rc<RefCell<ThreadRngInner>>,
864 }
865 
866 /// Retrieve the lazily-initialized thread-local random number
867 /// generator, seeded by the system. Intended to be used in method
868 /// chaining style, e.g. `thread_rng().gen::<i32>()`.
869 ///
870 /// After generating a certain amount of randomness, the RNG will reseed itself
871 /// from the operating system or, if the operating system RNG returns an error,
872 /// a seed based on the current system time.
873 ///
874 /// The internal RNG used is platform and architecture dependent, even
875 /// if the operating system random number generator is rigged to give
876 /// the same sequence always. If absolute consistency is required,
877 /// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
878 #[cfg(feature="std")]
thread_rng() -> ThreadRng879 pub fn thread_rng() -> ThreadRng {
880     // used to make space in TLS for a random number generator
881     thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = {
882         let r = match StdRng::new() {
883             Ok(r) => r,
884             Err(e) => panic!("No entropy available: {}", e),
885         };
886         let rng = reseeding::ReseedingRng::new(r,
887                                                THREAD_RNG_RESEED_THRESHOLD,
888                                                ThreadRngReseeder);
889         Rc::new(RefCell::new(rng))
890     });
891 
892     ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
893 }
894 
895 #[cfg(feature="std")]
896 impl Rng for ThreadRng {
next_u32(&mut self) -> u32897     fn next_u32(&mut self) -> u32 {
898         self.rng.borrow_mut().next_u32()
899     }
900 
next_u64(&mut self) -> u64901     fn next_u64(&mut self) -> u64 {
902         self.rng.borrow_mut().next_u64()
903     }
904 
905     #[inline]
fill_bytes(&mut self, bytes: &mut [u8])906     fn fill_bytes(&mut self, bytes: &mut [u8]) {
907         self.rng.borrow_mut().fill_bytes(bytes)
908     }
909 }
910 
911 /// Generates a random value using the thread-local random number generator.
912 ///
913 /// `random()` can generate various types of random things, and so may require
914 /// type hinting to generate the specific type you want.
915 ///
916 /// This function uses the thread local random number generator. This means
917 /// that if you're calling `random()` in a loop, caching the generator can
918 /// increase performance. An example is shown below.
919 ///
920 /// # Examples
921 ///
922 /// ```
923 /// let x = rand::random::<u8>();
924 /// println!("{}", x);
925 ///
926 /// let y = rand::random::<f64>();
927 /// println!("{}", y);
928 ///
929 /// if rand::random() { // generates a boolean
930 ///     println!("Better lucky than good!");
931 /// }
932 /// ```
933 ///
934 /// Caching the thread local random number generator:
935 ///
936 /// ```
937 /// use rand::Rng;
938 ///
939 /// let mut v = vec![1, 2, 3];
940 ///
941 /// for x in v.iter_mut() {
942 ///     *x = rand::random()
943 /// }
944 ///
945 /// // can be made faster by caching thread_rng
946 ///
947 /// let mut rng = rand::thread_rng();
948 ///
949 /// for x in v.iter_mut() {
950 ///     *x = rng.gen();
951 /// }
952 /// ```
953 #[cfg(feature="std")]
954 #[inline]
random<T: Rand>() -> T955 pub fn random<T: Rand>() -> T {
956     thread_rng().gen()
957 }
958 
959 /// DEPRECATED: use `seq::sample_iter` instead.
960 ///
961 /// Randomly sample up to `amount` elements from a finite iterator.
962 /// The order of elements in the sample is not random.
963 ///
964 /// # Example
965 ///
966 /// ```rust
967 /// use rand::{thread_rng, sample};
968 ///
969 /// let mut rng = thread_rng();
970 /// let sample = sample(&mut rng, 1..100, 5);
971 /// println!("{:?}", sample);
972 /// ```
973 #[cfg(feature="std")]
974 #[inline(always)]
975 #[deprecated(since="0.4.0", note="renamed to seq::sample_iter")]
sample<T, I, R>(rng: &mut R, iterable: I, amount: usize) -> Vec<T> where I: IntoIterator<Item=T>, R: Rng,976 pub fn sample<T, I, R>(rng: &mut R, iterable: I, amount: usize) -> Vec<T>
977     where I: IntoIterator<Item=T>,
978           R: Rng,
979 {
980     // the legacy sample didn't care whether amount was met
981     seq::sample_iter(rng, iterable, amount)
982         .unwrap_or_else(|e| e)
983 }
984 
985 #[cfg(test)]
986 mod test {
987     use super::{Rng, thread_rng, random, SeedableRng, StdRng, weak_rng};
988     use std::iter::repeat;
989 
990     pub struct MyRng<R> { inner: R }
991 
992     impl<R: Rng> Rng for MyRng<R> {
next_u32(&mut self) -> u32993         fn next_u32(&mut self) -> u32 {
994             fn next<T: Rng>(t: &mut T) -> u32 {
995                 t.next_u32()
996             }
997             next(&mut self.inner)
998         }
999     }
1000 
rng() -> MyRng<::ThreadRng>1001     pub fn rng() -> MyRng<::ThreadRng> {
1002         MyRng { inner: ::thread_rng() }
1003     }
1004 
1005     struct ConstRng { i: u64 }
1006     impl Rng for ConstRng {
next_u32(&mut self) -> u321007         fn next_u32(&mut self) -> u32 { self.i as u32 }
next_u64(&mut self) -> u641008         fn next_u64(&mut self) -> u64 { self.i }
1009 
1010         // no fill_bytes on purpose
1011     }
1012 
iter_eq<I, J>(i: I, j: J) -> bool where I: IntoIterator, J: IntoIterator<Item=I::Item>, I::Item: Eq1013     pub fn iter_eq<I, J>(i: I, j: J) -> bool
1014         where I: IntoIterator,
1015               J: IntoIterator<Item=I::Item>,
1016               I::Item: Eq
1017     {
1018         // make sure the iterators have equal length
1019         let mut i = i.into_iter();
1020         let mut j = j.into_iter();
1021         loop {
1022             match (i.next(), j.next()) {
1023                 (Some(ref ei), Some(ref ej)) if ei == ej => { }
1024                 (None, None) => return true,
1025                 _ => return false,
1026             }
1027         }
1028     }
1029 
1030     #[test]
test_fill_bytes_default()1031     fn test_fill_bytes_default() {
1032         let mut r = ConstRng { i: 0x11_22_33_44_55_66_77_88 };
1033 
1034         // check every remainder mod 8, both in small and big vectors.
1035         let lengths = [0, 1, 2, 3, 4, 5, 6, 7,
1036                        80, 81, 82, 83, 84, 85, 86, 87];
1037         for &n in lengths.iter() {
1038             let mut v = repeat(0u8).take(n).collect::<Vec<_>>();
1039             r.fill_bytes(&mut v);
1040 
1041             // use this to get nicer error messages.
1042             for (i, &byte) in v.iter().enumerate() {
1043                 if byte == 0 {
1044                     panic!("byte {} of {} is zero", i, n)
1045                 }
1046             }
1047         }
1048     }
1049 
1050     #[test]
test_gen_range()1051     fn test_gen_range() {
1052         let mut r = thread_rng();
1053         for _ in 0..1000 {
1054             let a = r.gen_range(-3, 42);
1055             assert!(a >= -3 && a < 42);
1056             assert_eq!(r.gen_range(0, 1), 0);
1057             assert_eq!(r.gen_range(-12, -11), -12);
1058         }
1059 
1060         for _ in 0..1000 {
1061             let a = r.gen_range(10, 42);
1062             assert!(a >= 10 && a < 42);
1063             assert_eq!(r.gen_range(0, 1), 0);
1064             assert_eq!(r.gen_range(3_000_000, 3_000_001), 3_000_000);
1065         }
1066 
1067     }
1068 
1069     #[test]
1070     #[should_panic]
test_gen_range_panic_int()1071     fn test_gen_range_panic_int() {
1072         let mut r = thread_rng();
1073         r.gen_range(5, -2);
1074     }
1075 
1076     #[test]
1077     #[should_panic]
test_gen_range_panic_usize()1078     fn test_gen_range_panic_usize() {
1079         let mut r = thread_rng();
1080         r.gen_range(5, 2);
1081     }
1082 
1083     #[test]
test_gen_weighted_bool()1084     fn test_gen_weighted_bool() {
1085         let mut r = thread_rng();
1086         assert_eq!(r.gen_weighted_bool(0), true);
1087         assert_eq!(r.gen_weighted_bool(1), true);
1088     }
1089 
1090     #[test]
test_gen_ascii_str()1091     fn test_gen_ascii_str() {
1092         let mut r = thread_rng();
1093         assert_eq!(r.gen_ascii_chars().take(0).count(), 0);
1094         assert_eq!(r.gen_ascii_chars().take(10).count(), 10);
1095         assert_eq!(r.gen_ascii_chars().take(16).count(), 16);
1096     }
1097 
1098     #[test]
test_gen_vec()1099     fn test_gen_vec() {
1100         let mut r = thread_rng();
1101         assert_eq!(r.gen_iter::<u8>().take(0).count(), 0);
1102         assert_eq!(r.gen_iter::<u8>().take(10).count(), 10);
1103         assert_eq!(r.gen_iter::<f64>().take(16).count(), 16);
1104     }
1105 
1106     #[test]
test_choose()1107     fn test_choose() {
1108         let mut r = thread_rng();
1109         assert_eq!(r.choose(&[1, 1, 1]).map(|&x|x), Some(1));
1110 
1111         let v: &[isize] = &[];
1112         assert_eq!(r.choose(v), None);
1113     }
1114 
1115     #[test]
test_shuffle()1116     fn test_shuffle() {
1117         let mut r = thread_rng();
1118         let empty: &mut [isize] = &mut [];
1119         r.shuffle(empty);
1120         let mut one = [1];
1121         r.shuffle(&mut one);
1122         let b: &[_] = &[1];
1123         assert_eq!(one, b);
1124 
1125         let mut two = [1, 2];
1126         r.shuffle(&mut two);
1127         assert!(two == [1, 2] || two == [2, 1]);
1128 
1129         let mut x = [1, 1, 1];
1130         r.shuffle(&mut x);
1131         let b: &[_] = &[1, 1, 1];
1132         assert_eq!(x, b);
1133     }
1134 
1135     #[test]
test_thread_rng()1136     fn test_thread_rng() {
1137         let mut r = thread_rng();
1138         r.gen::<i32>();
1139         let mut v = [1, 1, 1];
1140         r.shuffle(&mut v);
1141         let b: &[_] = &[1, 1, 1];
1142         assert_eq!(v, b);
1143         assert_eq!(r.gen_range(0, 1), 0);
1144     }
1145 
1146     #[test]
test_rng_trait_object()1147     fn test_rng_trait_object() {
1148         let mut rng = thread_rng();
1149         {
1150             let mut r = &mut rng as &mut Rng;
1151             r.next_u32();
1152             (&mut r).gen::<i32>();
1153             let mut v = [1, 1, 1];
1154             (&mut r).shuffle(&mut v);
1155             let b: &[_] = &[1, 1, 1];
1156             assert_eq!(v, b);
1157             assert_eq!((&mut r).gen_range(0, 1), 0);
1158         }
1159         {
1160             let mut r = Box::new(rng) as Box<Rng>;
1161             r.next_u32();
1162             r.gen::<i32>();
1163             let mut v = [1, 1, 1];
1164             r.shuffle(&mut v);
1165             let b: &[_] = &[1, 1, 1];
1166             assert_eq!(v, b);
1167             assert_eq!(r.gen_range(0, 1), 0);
1168         }
1169     }
1170 
1171     #[test]
test_random()1172     fn test_random() {
1173         // not sure how to test this aside from just getting some values
1174         let _n : usize = random();
1175         let _f : f32 = random();
1176         let _o : Option<Option<i8>> = random();
1177         let _many : ((),
1178                      (usize,
1179                       isize,
1180                       Option<(u32, (bool,))>),
1181                      (u8, i8, u16, i16, u32, i32, u64, i64),
1182                      (f32, (f64, (f64,)))) = random();
1183     }
1184 
1185     #[test]
test_std_rng_seeded()1186     fn test_std_rng_seeded() {
1187         let s = thread_rng().gen_iter::<usize>().take(256).collect::<Vec<usize>>();
1188         let mut ra: StdRng = SeedableRng::from_seed(&s[..]);
1189         let mut rb: StdRng = SeedableRng::from_seed(&s[..]);
1190         assert!(iter_eq(ra.gen_ascii_chars().take(100),
1191                         rb.gen_ascii_chars().take(100)));
1192     }
1193 
1194     #[test]
test_std_rng_reseed()1195     fn test_std_rng_reseed() {
1196         let s = thread_rng().gen_iter::<usize>().take(256).collect::<Vec<usize>>();
1197         let mut r: StdRng = SeedableRng::from_seed(&s[..]);
1198         let string1 = r.gen_ascii_chars().take(100).collect::<String>();
1199 
1200         r.reseed(&s);
1201 
1202         let string2 = r.gen_ascii_chars().take(100).collect::<String>();
1203         assert_eq!(string1, string2);
1204     }
1205 
1206     #[test]
test_weak_rng()1207     fn test_weak_rng() {
1208         let s = weak_rng().gen_iter::<usize>().take(256).collect::<Vec<usize>>();
1209         let mut ra: StdRng = SeedableRng::from_seed(&s[..]);
1210         let mut rb: StdRng = SeedableRng::from_seed(&s[..]);
1211         assert!(iter_eq(ra.gen_ascii_chars().take(100),
1212                         rb.gen_ascii_chars().take(100)));
1213     }
1214 }
1215