1 // Copyright 2013-2014 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.
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.
11 //! Utilities for random number generation
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>()`.
19 //! See the `distributions` submodule for sampling random numbers from
20 //! distributions like normal and exponential.
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`.
32 //! and this to your crate root:
35 //! extern crate rand;
38 //! # Thread-local RNG
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.
47 //! # Cryptographic security
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
53 //! The other random number generators provided by this module are not suitable
54 //! for such purposes.
56 //! *Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
57 //! This module uses `/dev/urandom` for the following reasons:
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.)
84 //! let mut rng = rand::thread_rng();
85 //! if rng.gen() { // random bool
86 //! println!("i32: {}, u32: {}", rng.gen::<i32>(), rng.gen::<u32>())
91 //! let tuple = rand::random::<(f64, char)>();
92 //! println!("{:?}", tuple)
95 //! ## Monte Carlo estimation of π
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 π,
102 //! (area of unit circle) / (area of square) = π / 4
105 //! So if we sample many points randomly from the square, roughly π / 4 of them
106 //! should be inside the circle.
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.
113 //! use rand::distributions::{IndependentSample, Range};
116 //! let between = Range::new(-1f64, 1.);
117 //! let mut rng = rand::thread_rng();
119 //! let total = 1_000_000;
120 //! let mut in_circle = 0;
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. {
130 //! // prints something close to 3.14159...
131 //! println!("{}", 4. * (in_circle as f64) / (total as f64));
135 //! ## Monty Hall Problem
137 //! This is a simulation of the [Monty Hall Problem][]:
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?
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
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.
152 //! [Monty Hall Problem]: http://en.wikipedia.org/wiki/Monty_Hall_problem
156 //! use rand::distributions::{IndependentSample, Range};
158 //! struct SimulationResult {
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);
168 //! // This is our initial choice
169 //! let mut choice = random_door.ind_sample(rng);
171 //! // The game host opens a door
172 //! let open = game_host_open(car, choice, rng);
174 //! // Shall we switch?
175 //! let switch = rng.gen();
177 //! choice = switch_door(choice, open);
180 //! SimulationResult { win: choice == car, switch: switch }
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::sample(rng, choices.into_iter(), 1)[0]
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]
196 //! fn free_doors(blocked: &[u32]) -> Vec<u32> {
197 //! (0..3).filter(|x| !blocked.contains(x)).collect()
201 //! // The estimation will be more accurate with more simulations
202 //! let num_simulations = 10000;
204 //! let mut rng = rand::thread_rng();
205 //! let random_door = Range::new(0, 3);
207 //! let (mut switch_wins, mut switch_losses) = (0, 0);
208 //! let (mut keep_wins, mut keep_losses) = (0, 0);
210 //! println!("Running {} simulations...", num_simulations);
211 //! for _ in 0..num_simulations {
212 //! let result = simulate(&random_door, &mut rng);
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,
222 //! let total_switches = switch_wins + switch_losses;
223 //! let total_keeps = keep_wins + keep_losses;
225 //! println!("Switched door {} times with {} wins and {} losses",
226 //! total_switches, switch_wins, switch_losses);
228 //! println!("Kept our choice {} times with {} wins and {} losses",
229 //! total_keeps, keep_wins, keep_losses);
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);
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://doc.rust-lang.org/rand/")]
244 #[cfg(test)] #[macro_use] extern crate log;
246 use std
::cell
::RefCell
;
251 use std
::num
::Wrapping
as w
;
255 pub use isaac
::{IsaacRng, Isaac64Rng}
;
256 pub use chacha
::ChaChaRng
;
258 #[cfg(target_pointer_width = "32")]
259 use IsaacRng
as IsaacWordRng
;
260 #[cfg(target_pointer_width = "64")]
261 use Isaac64Rng
as IsaacWordRng
;
263 use distributions
::{Range, IndependentSample}
;
264 use distributions
::range
::SampleRange
;
266 pub mod distributions
;
279 /// A type that can be randomly generated using an `Rng`.
280 pub trait Rand
: Sized
{
281 /// Generates a random instance of this type using the specified source of
283 fn rand
<R
: Rng
>(rng
: &mut R
) -> Self;
286 /// A random number generator.
288 /// Return the next random u32.
290 /// This rarely needs to be called directly, prefer `r.gen()` to
292 // FIXME #7771: Should be implemented in terms of next_u64
293 fn next_u32(&mut self) -> u32;
295 /// Return the next random u64.
297 /// By default this is implemented in terms of `next_u32`. An
298 /// implementation of this trait must provide at least one of
299 /// these two methods. Similarly to `next_u32`, this rarely needs
300 /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
301 fn next_u64(&mut self) -> u64 {
302 ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
305 /// Return the next random f32 selected from the half-open
306 /// interval `[0, 1)`.
308 /// This uses a technique described by Saito and Matsumoto at
309 /// MCQMC'08. Given that the IEEE floating point numbers are
310 /// uniformly distributed over [1,2), we generate a number in
311 /// this range and then offset it onto the range [0,1). Our
312 /// choice of bits (masking v. shifting) is arbitrary and
313 /// should be immaterial for high quality generators. For low
314 /// quality generators (ex. LCG), prefer bitshifting due to
315 /// correlation between sequential low order bits.
318 /// A PRNG specialized in double precision floating point numbers using
319 /// an affine transition
320 /// http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/ARTICLES/dSFMT.pdf
321 /// http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/SFMT/dSFMT-slide-e.pdf
323 /// By default this is implemented in terms of `next_u32`, but a
324 /// random number generator which can generate numbers satisfying
325 /// the requirements directly can overload this for performance.
326 /// It is required that the return value lies in `[0, 1)`.
328 /// See `Closed01` for the closed interval `[0,1]`, and
329 /// `Open01` for the open interval `(0,1)`.
330 fn next_f32(&mut self) -> f32 {
331 const UPPER_MASK
: u32 = 0x3F800000;
332 const LOWER_MASK
: u32 = 0x7FFFFF;
333 let tmp
= UPPER_MASK
| (self.next_u32() & LOWER_MASK
);
334 let result
: f32 = unsafe { mem::transmute(tmp) }
;
338 /// Return the next random f64 selected from the half-open
339 /// interval `[0, 1)`.
341 /// By default this is implemented in terms of `next_u64`, but a
342 /// random number generator which can generate numbers satisfying
343 /// the requirements directly can overload this for performance.
344 /// It is required that the return value lies in `[0, 1)`.
346 /// See `Closed01` for the closed interval `[0,1]`, and
347 /// `Open01` for the open interval `(0,1)`.
348 fn next_f64(&mut self) -> f64 {
349 const UPPER_MASK
: u64 = 0x3FF0000000000000;
350 const LOWER_MASK
: u64 = 0xFFFFFFFFFFFFF;
351 let tmp
= UPPER_MASK
| (self.next_u64() & LOWER_MASK
);
352 let result
: f64 = unsafe { mem::transmute(tmp) }
;
356 /// Fill `dest` with random data.
358 /// This has a default implementation in terms of `next_u64` and
359 /// `next_u32`, but should be overridden by implementations that
360 /// offer a more efficient solution than just calling those
361 /// methods repeatedly.
363 /// This method does *not* have a requirement to bear any fixed
364 /// relationship to the other methods, for example, it does *not*
365 /// have to result in the same output as progressively filling
366 /// `dest` with `self.gen::<u8>()`, and any such behaviour should
367 /// not be relied upon.
369 /// This method should guarantee that `dest` is entirely filled
370 /// with new data, and may panic if this is impossible
371 /// (e.g. reading past the end of a file that is being used as the
372 /// source of randomness).
377 /// use rand::{thread_rng, Rng};
379 /// let mut v = [0u8; 13579];
380 /// thread_rng().fill_bytes(&mut v);
381 /// println!("{:?}", &v[..]);
383 fn fill_bytes(&mut self, dest
: &mut [u8]) {
384 // this could, in theory, be done by transmuting dest to a
385 // [u64], but this is (1) likely to be undefined behaviour for
386 // LLVM, (2) has to be very careful about alignment concerns,
387 // (3) adds more `unsafe` that needs to be checked, (4)
388 // probably doesn't give much performance gain if
389 // optimisations are on.
392 for byte
in dest
.iter_mut() {
394 // we could micro-optimise here by generating a u32 if
395 // we only need a few more bytes to fill the vector
397 num
= self.next_u64();
401 *byte
= (num
& 0xff) as u8;
407 /// Return a random value of a `Rand` type.
412 /// use rand::{thread_rng, Rng};
414 /// let mut rng = thread_rng();
415 /// let x: u32 = rng.gen();
416 /// println!("{}", x);
417 /// println!("{:?}", rng.gen::<(f64, bool)>());
420 fn gen
<T
: Rand
>(&mut self) -> T
where Self: Sized
{
424 /// Return an iterator that will yield an infinite number of randomly
430 /// use rand::{thread_rng, Rng};
432 /// let mut rng = thread_rng();
433 /// let x = rng.gen_iter::<u32>().take(10).collect::<Vec<u32>>();
434 /// println!("{:?}", x);
435 /// println!("{:?}", rng.gen_iter::<(f64, bool)>().take(5)
436 /// .collect::<Vec<(f64, bool)>>());
438 fn gen_iter
<'a
, T
: Rand
>(&'a
mut self) -> Generator
<'a
, T
, Self> where Self: Sized
{
439 Generator { rng: self, _marker: marker::PhantomData }
442 /// Generate a random value in the range [`low`, `high`).
444 /// This is a convenience wrapper around
445 /// `distributions::Range`. If this function will be called
446 /// repeatedly with the same arguments, one should use `Range`, as
447 /// that will amortize the computations that allow for perfect
448 /// uniformity, as they only happen on initialization.
452 /// Panics if `low >= high`.
457 /// use rand::{thread_rng, Rng};
459 /// let mut rng = thread_rng();
460 /// let n: u32 = rng.gen_range(0, 10);
461 /// println!("{}", n);
462 /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
463 /// println!("{}", m);
465 fn gen_range
<T
: PartialOrd
+ SampleRange
>(&mut self, low
: T
, high
: T
) -> T
where Self: Sized
{
466 assert
!(low
< high
, "Rng.gen_range called with low >= high");
467 Range
::new(low
, high
).ind_sample(self)
470 /// Return a bool with a 1 in n chance of true
475 /// use rand::{thread_rng, Rng};
477 /// let mut rng = thread_rng();
478 /// println!("{}", rng.gen_weighted_bool(3));
480 fn gen_weighted_bool(&mut self, n
: u32) -> bool
where Self: Sized
{
481 n
<= 1 || self.gen_range(0, n
) == 0
484 /// Return an iterator of random characters from the set A-Z,a-z,0-9.
489 /// use rand::{thread_rng, Rng};
491 /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
492 /// println!("{}", s);
494 fn gen_ascii_chars
<'a
>(&'a
mut self) -> AsciiGenerator
<'a
, Self> where Self: Sized
{
495 AsciiGenerator { rng: self }
498 /// Return a random element from `values`.
500 /// Return `None` if `values` is empty.
505 /// use rand::{thread_rng, Rng};
507 /// let choices = [1, 2, 4, 8, 16, 32];
508 /// let mut rng = thread_rng();
509 /// println!("{:?}", rng.choose(&choices));
510 /// assert_eq!(rng.choose(&choices[..0]), None);
512 fn choose
<'a
, T
>(&mut self, values
: &'a
[T
]) -> Option
<&'a T
> where Self: Sized
{
513 if values
.is_empty() {
516 Some(&values
[self.gen_range(0, values
.len())])
520 /// Return a mutable pointer to a random element from `values`.
522 /// Return `None` if `values` is empty.
523 fn choose_mut
<'a
, T
>(&mut self, values
: &'a
mut [T
]) -> Option
<&'a
mut T
> where Self: Sized
{
524 if values
.is_empty() {
527 let len
= values
.len();
528 Some(&mut values
[self.gen_range(0, len
)])
532 /// Shuffle a mutable slice in place.
537 /// use rand::{thread_rng, Rng};
539 /// let mut rng = thread_rng();
540 /// let mut y = [1, 2, 3];
541 /// rng.shuffle(&mut y);
542 /// println!("{:?}", y);
543 /// rng.shuffle(&mut y);
544 /// println!("{:?}", y);
546 fn shuffle
<T
>(&mut self, values
: &mut [T
]) where Self: Sized
{
547 let mut i
= values
.len();
549 // invariant: elements with index >= i have been locked in place.
551 // lock element i in place.
552 values
.swap(i
, self.gen_range(0, i
+ 1));
557 impl<'a
, R
: ?Sized
> Rng
for &'a
mut R
where R
: Rng
{
558 fn next_u32(&mut self) -> u32 {
562 fn next_u64(&mut self) -> u64 {
566 fn next_f32(&mut self) -> f32 {
570 fn next_f64(&mut self) -> f64 {
574 fn fill_bytes(&mut self, dest
: &mut [u8]) {
575 (**self).fill_bytes(dest
)
579 impl<R
: ?Sized
> Rng
for Box
<R
> where R
: Rng
{
580 fn next_u32(&mut self) -> u32 {
584 fn next_u64(&mut self) -> u64 {
588 fn next_f32(&mut self) -> f32 {
592 fn next_f64(&mut self) -> f64 {
596 fn fill_bytes(&mut self, dest
: &mut [u8]) {
597 (**self).fill_bytes(dest
)
601 /// Iterator which will generate a stream of random items.
603 /// This iterator is created via the [`gen_iter`] method on [`Rng`].
605 /// [`gen_iter`]: trait.Rng.html#method.gen_iter
606 /// [`Rng`]: trait.Rng.html
607 pub struct Generator
<'a
, T
, R
:'a
> {
609 _marker
: marker
::PhantomData
<fn() -> T
>,
612 impl<'a
, T
: Rand
, R
: Rng
> Iterator
for Generator
<'a
, T
, R
> {
615 fn next(&mut self) -> Option
<T
> {
620 /// Iterator which will continuously generate random ascii characters.
622 /// This iterator is created via the [`gen_ascii_chars`] method on [`Rng`].
624 /// [`gen_ascii_chars`]: trait.Rng.html#method.gen_ascii_chars
625 /// [`Rng`]: trait.Rng.html
626 pub struct AsciiGenerator
<'a
, R
:'a
> {
630 impl<'a
, R
: Rng
> Iterator
for AsciiGenerator
<'a
, R
> {
633 fn next(&mut self) -> Option
<char> {
634 const GEN_ASCII_STR_CHARSET
: &'
static [u8] =
635 b
"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
636 abcdefghijklmnopqrstuvwxyz\
638 Some(*self.rng
.choose(GEN_ASCII_STR_CHARSET
).unwrap() as char)
642 /// A random number generator that can be explicitly seeded to produce
643 /// the same stream of randomness multiple times.
644 pub trait SeedableRng
<Seed
>: Rng
{
645 /// Reseed an RNG with the given seed.
650 /// use rand::{Rng, SeedableRng, StdRng};
652 /// let seed: &[_] = &[1, 2, 3, 4];
653 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
654 /// println!("{}", rng.gen::<f64>());
655 /// rng.reseed(&[5, 6, 7, 8]);
656 /// println!("{}", rng.gen::<f64>());
658 fn reseed(&mut self, Seed
);
660 /// Create a new RNG with the given seed.
665 /// use rand::{Rng, SeedableRng, StdRng};
667 /// let seed: &[_] = &[1, 2, 3, 4];
668 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
669 /// println!("{}", rng.gen::<f64>());
671 fn from_seed(seed
: Seed
) -> Self;
674 /// An Xorshift[1] random number
677 /// The Xorshift algorithm is not suitable for cryptographic purposes
678 /// but is very fast. If you do not know for sure that it fits your
679 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
681 /// [1]: Marsaglia, George (July 2003). ["Xorshift
682 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
683 /// Statistical Software*. Vol. 8 (Issue 14).
684 #[allow(missing_copy_implementations)]
686 pub struct XorShiftRng
{
694 /// Creates a new XorShiftRng instance which is not seeded.
696 /// The initial values of this RNG are constants, so all generators created
697 /// by this function will yield the same stream of random numbers. It is
698 /// highly recommended that this is created through `SeedableRng` instead of
700 pub fn new_unseeded() -> XorShiftRng
{
710 impl Rng
for XorShiftRng
{
712 fn next_u32(&mut self) -> u32 {
714 let t
= x ^
(x
<< 11);
719 self.w
= w_ ^
(w_
>> 19) ^
(t ^
(t
>> 8));
724 impl SeedableRng
<[u32; 4]> for XorShiftRng
{
725 /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
726 fn reseed(&mut self, seed
: [u32; 4]) {
727 assert
!(!seed
.iter().all(|&x
| x
== 0),
728 "XorShiftRng.reseed called with an all zero seed.");
736 /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
737 fn from_seed(seed
: [u32; 4]) -> XorShiftRng
{
738 assert
!(!seed
.iter().all(|&x
| x
== 0),
739 "XorShiftRng::from_seed called with an all zero seed.");
750 impl Rand
for XorShiftRng
{
751 fn rand
<R
: Rng
>(rng
: &mut R
) -> XorShiftRng
{
752 let mut tuple
: (u32, u32, u32, u32) = rng
.gen();
753 while tuple
== (0, 0, 0, 0) {
756 let (x
, y
, z
, w_
) = tuple
;
757 XorShiftRng { x: w(x), y: w(y), z: w(z), w: w(w_) }
761 /// A wrapper for generating floating point numbers uniformly in the
762 /// open interval `(0,1)` (not including either endpoint).
764 /// Use `Closed01` for the closed interval `[0,1]`, and the default
765 /// `Rand` implementation for `f32` and `f64` for the half-open
770 /// use rand::{random, Open01};
772 /// let Open01(val) = random::<Open01<f32>>();
773 /// println!("f32 from (0,1): {}", val);
775 pub struct Open01
<F
>(pub F
);
777 /// A wrapper for generating floating point numbers uniformly in the
778 /// closed interval `[0,1]` (including both endpoints).
780 /// Use `Open01` for the closed interval `(0,1)`, and the default
781 /// `Rand` implementation of `f32` and `f64` for the half-open
787 /// use rand::{random, Closed01};
789 /// let Closed01(val) = random::<Closed01<f32>>();
790 /// println!("f32 from [0,1]: {}", val);
792 pub struct Closed01
<F
>(pub F
);
794 /// The standard RNG. This is designed to be efficient on the current
796 #[derive(Copy, Clone)]
802 /// Create a randomly seeded instance of `StdRng`.
804 /// This is a very expensive operation as it has to read
805 /// randomness from the operating system and use this in an
806 /// expensive seeding operation. If one is only generating a small
807 /// number of random numbers, or doesn't need the utmost speed for
808 /// generating each number, `thread_rng` and/or `random` may be more
811 /// Reading the randomness from the OS may fail, and any error is
812 /// propagated via the `io::Result` return value.
813 pub fn new() -> io
::Result
<StdRng
> {
814 OsRng
::new().map(|mut r
| StdRng { rng: r.gen() }
)
818 impl Rng
for StdRng
{
820 fn next_u32(&mut self) -> u32 {
825 fn next_u64(&mut self) -> u64 {
830 impl<'a
> SeedableRng
<&'a
[usize]> for StdRng
{
831 fn reseed(&mut self, seed
: &'a
[usize]) {
832 // the internal RNG can just be seeded from the above
834 self.rng
.reseed(unsafe {mem::transmute(seed)}
)
837 fn from_seed(seed
: &'a
[usize]) -> StdRng
{
838 StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}
) }
842 /// Create a weak random number generator with a default algorithm and seed.
844 /// It returns the fastest `Rng` algorithm currently available in Rust without
845 /// consideration for cryptography or security. If you require a specifically
846 /// seeded `Rng` for consistency over time you should pick one algorithm and
847 /// create the `Rng` yourself.
849 /// This will read randomness from the operating system to seed the
851 pub fn weak_rng() -> XorShiftRng
{
853 Ok(mut r
) => r
.gen(),
854 Err(e
) => panic
!("weak_rng: failed to create seeded RNG: {:?}", e
)
858 /// Controls how the thread-local RNG is reseeded.
859 struct ThreadRngReseeder
;
861 impl reseeding
::Reseeder
<StdRng
> for ThreadRngReseeder
{
862 fn reseed(&mut self, rng
: &mut StdRng
) {
863 *rng
= match StdRng
::new() {
865 Err(e
) => panic
!("could not reseed thread_rng: {}", e
)
869 const THREAD_RNG_RESEED_THRESHOLD
: u64 = 32_768;
870 type ThreadRngInner
= reseeding
::ReseedingRng
<StdRng
, ThreadRngReseeder
>;
872 /// The thread-local RNG.
874 pub struct ThreadRng
{
875 rng
: Rc
<RefCell
<ThreadRngInner
>>,
878 /// Retrieve the lazily-initialized thread-local random number
879 /// generator, seeded by the system. Intended to be used in method
880 /// chaining style, e.g. `thread_rng().gen::<i32>()`.
882 /// The RNG provided will reseed itself from the operating system
883 /// after generating a certain amount of randomness.
885 /// The internal RNG used is platform and architecture dependent, even
886 /// if the operating system random number generator is rigged to give
887 /// the same sequence always. If absolute consistency is required,
888 /// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
889 pub fn thread_rng() -> ThreadRng
{
890 // used to make space in TLS for a random number generator
891 thread_local
!(static THREAD_RNG_KEY
: Rc
<RefCell
<ThreadRngInner
>> = {
892 let r
= match StdRng
::new() {
894 Err(e
) => panic
!("could not initialize thread_rng: {}", e
)
896 let rng
= reseeding
::ReseedingRng
::new(r
,
897 THREAD_RNG_RESEED_THRESHOLD
,
899 Rc
::new(RefCell
::new(rng
))
902 ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
905 impl Rng
for ThreadRng
{
906 fn next_u32(&mut self) -> u32 {
907 self.rng
.borrow_mut().next_u32()
910 fn next_u64(&mut self) -> u64 {
911 self.rng
.borrow_mut().next_u64()
915 fn fill_bytes(&mut self, bytes
: &mut [u8]) {
916 self.rng
.borrow_mut().fill_bytes(bytes
)
920 /// Generates a random value using the thread-local random number generator.
922 /// `random()` can generate various types of random things, and so may require
923 /// type hinting to generate the specific type you want.
925 /// This function uses the thread local random number generator. This means
926 /// that if you're calling `random()` in a loop, caching the generator can
927 /// increase performance. An example is shown below.
932 /// let x = rand::random::<u8>();
933 /// println!("{}", x);
935 /// let y = rand::random::<f64>();
936 /// println!("{}", y);
938 /// if rand::random() { // generates a boolean
939 /// println!("Better lucky than good!");
943 /// Caching the thread local random number generator:
948 /// let mut v = vec![1, 2, 3];
950 /// for x in v.iter_mut() {
951 /// *x = rand::random()
954 /// // would be faster as
956 /// let mut rng = rand::thread_rng();
958 /// for x in v.iter_mut() {
963 pub fn random
<T
: Rand
>() -> T
{
967 /// Randomly sample up to `amount` elements from an iterator.
972 /// use rand::{thread_rng, sample};
974 /// let mut rng = thread_rng();
975 /// let sample = sample(&mut rng, 1..100, 5);
976 /// println!("{:?}", sample);
978 pub fn sample
<T
, I
, R
>(rng
: &mut R
, iterable
: I
, amount
: usize) -> Vec
<T
>
979 where I
: IntoIterator
<Item
=T
>,
982 let mut iter
= iterable
.into_iter();
983 let mut reservoir
: Vec
<T
> = iter
.by_ref().take(amount
).collect();
984 // continue unless the iterator was exhausted
985 if reservoir
.len() == amount
{
986 for (i
, elem
) in iter
.enumerate() {
987 let k
= rng
.gen_range(0, i
+ 1 + amount
);
988 if let Some(spot
) = reservoir
.get_mut(k
) {
998 use super::{Rng, thread_rng, random, SeedableRng, StdRng, sample}
;
999 use std
::iter
::repeat
;
1001 pub struct MyRng
<R
> { inner: R }
1003 impl<R
: Rng
> Rng
for MyRng
<R
> {
1004 fn next_u32(&mut self) -> u32 {
1005 fn next
<T
: Rng
>(t
: &mut T
) -> u32 {
1008 next(&mut self.inner
)
1012 pub fn rng() -> MyRng
<::ThreadRng
> {
1013 MyRng { inner: ::thread_rng() }
1016 struct ConstRng { i: u64 }
1017 impl Rng
for ConstRng
{
1018 fn next_u32(&mut self) -> u32 { self.i as u32 }
1019 fn next_u64(&mut self) -> u64 { self.i }
1021 // no fill_bytes on purpose
1024 pub fn iter_eq
<I
, J
>(i
: I
, j
: J
) -> bool
1025 where I
: IntoIterator
,
1026 J
: IntoIterator
<Item
=I
::Item
>,
1029 // make sure the iterators have equal length
1030 let mut i
= i
.into_iter();
1031 let mut j
= j
.into_iter();
1033 match (i
.next(), j
.next()) {
1034 (Some(ref ei
), Some(ref ej
)) if ei
== ej
=> { }
1035 (None
, None
) => return true,
1042 fn test_fill_bytes_default() {
1043 let mut r
= ConstRng { i: 0x11_22_33_44_55_66_77_88 }
;
1045 // check every remainder mod 8, both in small and big vectors.
1046 let lengths
= [0, 1, 2, 3, 4, 5, 6, 7,
1047 80, 81, 82, 83, 84, 85, 86, 87];
1048 for &n
in lengths
.iter() {
1049 let mut v
= repeat(0u8).take(n
).collect
::<Vec
<_
>>();
1050 r
.fill_bytes(&mut v
);
1052 // use this to get nicer error messages.
1053 for (i
, &byte
) in v
.iter().enumerate() {
1055 panic
!("byte {} of {} is zero", i
, n
)
1062 fn test_gen_range() {
1063 let mut r
= thread_rng();
1065 let a
= r
.gen_range(-3, 42);
1066 assert
!(a
>= -3 && a
< 42);
1067 assert_eq
!(r
.gen_range(0, 1), 0);
1068 assert_eq
!(r
.gen_range(-12, -11), -12);
1072 let a
= r
.gen_range(10, 42);
1073 assert
!(a
>= 10 && a
< 42);
1074 assert_eq
!(r
.gen_range(0, 1), 0);
1075 assert_eq
!(r
.gen_range(3_000_000, 3_000_001), 3_000_000);
1082 fn test_gen_range_panic_int() {
1083 let mut r
= thread_rng();
1089 fn test_gen_range_panic_usize() {
1090 let mut r
= thread_rng();
1096 let mut r
= thread_rng();
1097 let a
= r
.gen
::<f64>();
1098 let b
= r
.gen
::<f64>();
1099 debug
!("{:?}", (a
, b
));
1103 fn test_gen_weighted_bool() {
1104 let mut r
= thread_rng();
1105 assert_eq
!(r
.gen_weighted_bool(0), true);
1106 assert_eq
!(r
.gen_weighted_bool(1), true);
1110 fn test_gen_ascii_str() {
1111 let mut r
= thread_rng();
1112 assert_eq
!(r
.gen_ascii_chars().take(0).count(), 0);
1113 assert_eq
!(r
.gen_ascii_chars().take(10).count(), 10);
1114 assert_eq
!(r
.gen_ascii_chars().take(16).count(), 16);
1119 let mut r
= thread_rng();
1120 assert_eq
!(r
.gen_iter
::<u8>().take(0).count(), 0);
1121 assert_eq
!(r
.gen_iter
::<u8>().take(10).count(), 10);
1122 assert_eq
!(r
.gen_iter
::<f64>().take(16).count(), 16);
1127 let mut r
= thread_rng();
1128 assert_eq
!(r
.choose(&[1, 1, 1]).map(|&x
|x
), Some(1));
1130 let v
: &[isize] = &[];
1131 assert_eq
!(r
.choose(v
), None
);
1136 let mut r
= thread_rng();
1137 let empty
: &mut [isize] = &mut [];
1140 r
.shuffle(&mut one
);
1144 let mut two
= [1, 2];
1145 r
.shuffle(&mut two
);
1146 assert
!(two
== [1, 2] || two
== [2, 1]);
1148 let mut x
= [1, 1, 1];
1150 let b
: &[_
] = &[1, 1, 1];
1155 fn test_thread_rng() {
1156 let mut r
= thread_rng();
1158 let mut v
= [1, 1, 1];
1160 let b
: &[_
] = &[1, 1, 1];
1162 assert_eq
!(r
.gen_range(0, 1), 0);
1166 fn test_rng_trait_object() {
1167 let mut rng
= thread_rng();
1169 let mut r
= &mut rng
as &mut Rng
;
1171 (&mut r
).gen
::<i32>();
1172 let mut v
= [1, 1, 1];
1173 (&mut r
).shuffle(&mut v
);
1174 let b
: &[_
] = &[1, 1, 1];
1176 assert_eq
!((&mut r
).gen_range(0, 1), 0);
1179 let mut r
= Box
::new(rng
) as Box
<Rng
>;
1182 let mut v
= [1, 1, 1];
1184 let b
: &[_
] = &[1, 1, 1];
1186 assert_eq
!(r
.gen_range(0, 1), 0);
1192 // not sure how to test this aside from just getting some values
1193 let _n
: usize = random();
1194 let _f
: f32 = random();
1195 let _o
: Option
<Option
<i8>> = random();
1199 Option
<(u32, (bool
,))>),
1200 (u8, i8, u16, i16, u32, i32, u64, i64),
1201 (f32, (f64, (f64,)))) = random();
1209 let mut r
= thread_rng();
1210 let vals
= (min_val
..max_val
).collect
::<Vec
<i32>>();
1211 let small_sample
= sample(&mut r
, vals
.iter(), 5);
1212 let large_sample
= sample(&mut r
, vals
.iter(), vals
.len() + 5);
1214 assert_eq
!(small_sample
.len(), 5);
1215 assert_eq
!(large_sample
.len(), vals
.len());
1217 assert
!(small_sample
.iter().all(|e
| {
1218 **e
>= min_val
&& **e
<= max_val
1223 fn test_std_rng_seeded() {
1224 let s
= thread_rng().gen_iter
::<usize>().take(256).collect
::<Vec
<usize>>();
1225 let mut ra
: StdRng
= SeedableRng
::from_seed(&s
[..]);
1226 let mut rb
: StdRng
= SeedableRng
::from_seed(&s
[..]);
1227 assert
!(iter_eq(ra
.gen_ascii_chars().take(100),
1228 rb
.gen_ascii_chars().take(100)));
1232 fn test_std_rng_reseed() {
1233 let s
= thread_rng().gen_iter
::<usize>().take(256).collect
::<Vec
<usize>>();
1234 let mut r
: StdRng
= SeedableRng
::from_seed(&s
[..]);
1235 let string1
= r
.gen_ascii_chars().take(100).collect
::<String
>();
1239 let string2
= r
.gen_ascii_chars().take(100).collect
::<String
>();
1240 assert_eq
!(string1
, string2
);