]> git.proxmox.com Git - rustc.git/blob - src/vendor/rand/src/lib.rs
New upstream version 1.20.0+dfsg1
[rustc.git] / src / vendor / rand / src / lib.rs
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.
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.3"
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::sample(rng, choices.into_iter(), 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://doc.rust-lang.org/rand/")]
243
244 #[cfg(test)] #[macro_use] extern crate log;
245
246 use std::cell::RefCell;
247 use std::marker;
248 use std::mem;
249 use std::io;
250 use std::rc::Rc;
251 use std::num::Wrapping as w;
252
253 pub use os::OsRng;
254
255 pub use isaac::{IsaacRng, Isaac64Rng};
256 pub use chacha::ChaChaRng;
257
258 #[cfg(target_pointer_width = "32")]
259 use IsaacRng as IsaacWordRng;
260 #[cfg(target_pointer_width = "64")]
261 use Isaac64Rng as IsaacWordRng;
262
263 use distributions::{Range, IndependentSample};
264 use distributions::range::SampleRange;
265
266 pub mod distributions;
267 pub mod isaac;
268 pub mod chacha;
269 pub mod reseeding;
270 mod rand_impls;
271 pub mod os;
272 pub mod read;
273
274 #[allow(bad_style)]
275 type w64 = w<u64>;
276 #[allow(bad_style)]
277 type w32 = w<u32>;
278
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
282 /// randomness.
283 fn rand<R: Rng>(rng: &mut R) -> Self;
284 }
285
286 /// A random number generator.
287 pub trait Rng {
288 /// Return the next random u32.
289 ///
290 /// This rarely needs to be called directly, prefer `r.gen()` to
291 /// `r.next_u32()`.
292 // FIXME #7771: Should be implemented in terms of next_u64
293 fn next_u32(&mut self) -> u32;
294
295 /// Return the next random u64.
296 ///
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)
303 }
304
305 /// Return the next random f32 selected from the half-open
306 /// interval `[0, 1)`.
307 ///
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.
316 ///
317 /// See:
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
322 ///
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)`.
327 ///
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) };
335 result - 1.0
336 }
337
338 /// Return the next random f64 selected from the half-open
339 /// interval `[0, 1)`.
340 ///
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)`.
345 ///
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) };
353 result - 1.0
354 }
355
356 /// Fill `dest` with random data.
357 ///
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.
362 ///
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.
368 ///
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).
373 ///
374 /// # Example
375 ///
376 /// ```rust
377 /// use rand::{thread_rng, Rng};
378 ///
379 /// let mut v = [0u8; 13579];
380 /// thread_rng().fill_bytes(&mut v);
381 /// println!("{:?}", &v[..]);
382 /// ```
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.
390 let mut count = 0;
391 let mut num = 0;
392 for byte in dest.iter_mut() {
393 if count == 0 {
394 // we could micro-optimise here by generating a u32 if
395 // we only need a few more bytes to fill the vector
396 // (i.e. at most 4).
397 num = self.next_u64();
398 count = 8;
399 }
400
401 *byte = (num & 0xff) as u8;
402 num >>= 8;
403 count -= 1;
404 }
405 }
406
407 /// Return a random value of a `Rand` type.
408 ///
409 /// # Example
410 ///
411 /// ```rust
412 /// use rand::{thread_rng, Rng};
413 ///
414 /// let mut rng = thread_rng();
415 /// let x: u32 = rng.gen();
416 /// println!("{}", x);
417 /// println!("{:?}", rng.gen::<(f64, bool)>());
418 /// ```
419 #[inline(always)]
420 fn gen<T: Rand>(&mut self) -> T where Self: Sized {
421 Rand::rand(self)
422 }
423
424 /// Return an iterator that will yield an infinite number of randomly
425 /// generated items.
426 ///
427 /// # Example
428 ///
429 /// ```
430 /// use rand::{thread_rng, Rng};
431 ///
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)>>());
437 /// ```
438 fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> where Self: Sized {
439 Generator { rng: self, _marker: marker::PhantomData }
440 }
441
442 /// Generate a random value in the range [`low`, `high`).
443 ///
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.
449 ///
450 /// # Panics
451 ///
452 /// Panics if `low >= high`.
453 ///
454 /// # Example
455 ///
456 /// ```rust
457 /// use rand::{thread_rng, Rng};
458 ///
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);
464 /// ```
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)
468 }
469
470 /// Return a bool with a 1 in n chance of true
471 ///
472 /// # Example
473 ///
474 /// ```rust
475 /// use rand::{thread_rng, Rng};
476 ///
477 /// let mut rng = thread_rng();
478 /// println!("{}", rng.gen_weighted_bool(3));
479 /// ```
480 fn gen_weighted_bool(&mut self, n: u32) -> bool where Self: Sized {
481 n <= 1 || self.gen_range(0, n) == 0
482 }
483
484 /// Return an iterator of random characters from the set A-Z,a-z,0-9.
485 ///
486 /// # Example
487 ///
488 /// ```rust
489 /// use rand::{thread_rng, Rng};
490 ///
491 /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
492 /// println!("{}", s);
493 /// ```
494 fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> where Self: Sized {
495 AsciiGenerator { rng: self }
496 }
497
498 /// Return a random element from `values`.
499 ///
500 /// Return `None` if `values` is empty.
501 ///
502 /// # Example
503 ///
504 /// ```
505 /// use rand::{thread_rng, Rng};
506 ///
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);
511 /// ```
512 fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> where Self: Sized {
513 if values.is_empty() {
514 None
515 } else {
516 Some(&values[self.gen_range(0, values.len())])
517 }
518 }
519
520 /// Return a mutable pointer to a random element from `values`.
521 ///
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() {
525 None
526 } else {
527 let len = values.len();
528 Some(&mut values[self.gen_range(0, len)])
529 }
530 }
531
532 /// Shuffle a mutable slice in place.
533 ///
534 /// # Example
535 ///
536 /// ```rust
537 /// use rand::{thread_rng, Rng};
538 ///
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);
545 /// ```
546 fn shuffle<T>(&mut self, values: &mut [T]) where Self: Sized {
547 let mut i = values.len();
548 while i >= 2 {
549 // invariant: elements with index >= i have been locked in place.
550 i -= 1;
551 // lock element i in place.
552 values.swap(i, self.gen_range(0, i + 1));
553 }
554 }
555 }
556
557 impl<'a, R: ?Sized> Rng for &'a mut R where R: Rng {
558 fn next_u32(&mut self) -> u32 {
559 (**self).next_u32()
560 }
561
562 fn next_u64(&mut self) -> u64 {
563 (**self).next_u64()
564 }
565
566 fn next_f32(&mut self) -> f32 {
567 (**self).next_f32()
568 }
569
570 fn next_f64(&mut self) -> f64 {
571 (**self).next_f64()
572 }
573
574 fn fill_bytes(&mut self, dest: &mut [u8]) {
575 (**self).fill_bytes(dest)
576 }
577 }
578
579 impl<R: ?Sized> Rng for Box<R> where R: Rng {
580 fn next_u32(&mut self) -> u32 {
581 (**self).next_u32()
582 }
583
584 fn next_u64(&mut self) -> u64 {
585 (**self).next_u64()
586 }
587
588 fn next_f32(&mut self) -> f32 {
589 (**self).next_f32()
590 }
591
592 fn next_f64(&mut self) -> f64 {
593 (**self).next_f64()
594 }
595
596 fn fill_bytes(&mut self, dest: &mut [u8]) {
597 (**self).fill_bytes(dest)
598 }
599 }
600
601 /// Iterator which will generate a stream of random items.
602 ///
603 /// This iterator is created via the [`gen_iter`] method on [`Rng`].
604 ///
605 /// [`gen_iter`]: trait.Rng.html#method.gen_iter
606 /// [`Rng`]: trait.Rng.html
607 pub struct Generator<'a, T, R:'a> {
608 rng: &'a mut R,
609 _marker: marker::PhantomData<fn() -> T>,
610 }
611
612 impl<'a, T: Rand, R: Rng> Iterator for Generator<'a, T, R> {
613 type Item = T;
614
615 fn next(&mut self) -> Option<T> {
616 Some(self.rng.gen())
617 }
618 }
619
620 /// Iterator which will continuously generate random ascii characters.
621 ///
622 /// This iterator is created via the [`gen_ascii_chars`] method on [`Rng`].
623 ///
624 /// [`gen_ascii_chars`]: trait.Rng.html#method.gen_ascii_chars
625 /// [`Rng`]: trait.Rng.html
626 pub struct AsciiGenerator<'a, R:'a> {
627 rng: &'a mut R,
628 }
629
630 impl<'a, R: Rng> Iterator for AsciiGenerator<'a, R> {
631 type Item = char;
632
633 fn next(&mut self) -> Option<char> {
634 const GEN_ASCII_STR_CHARSET: &'static [u8] =
635 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
636 abcdefghijklmnopqrstuvwxyz\
637 0123456789";
638 Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
639 }
640 }
641
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.
646 ///
647 /// # Example
648 ///
649 /// ```rust
650 /// use rand::{Rng, SeedableRng, StdRng};
651 ///
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>());
657 /// ```
658 fn reseed(&mut self, Seed);
659
660 /// Create a new RNG with the given seed.
661 ///
662 /// # Example
663 ///
664 /// ```rust
665 /// use rand::{Rng, SeedableRng, StdRng};
666 ///
667 /// let seed: &[_] = &[1, 2, 3, 4];
668 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
669 /// println!("{}", rng.gen::<f64>());
670 /// ```
671 fn from_seed(seed: Seed) -> Self;
672 }
673
674 /// An Xorshift[1] random number
675 /// generator.
676 ///
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`.
680 ///
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)]
685 #[derive(Clone)]
686 pub struct XorShiftRng {
687 x: w32,
688 y: w32,
689 z: w32,
690 w: w32,
691 }
692
693 impl XorShiftRng {
694 /// Creates a new XorShiftRng instance which is not seeded.
695 ///
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
699 /// this function
700 pub fn new_unseeded() -> XorShiftRng {
701 XorShiftRng {
702 x: w(0x193a6754),
703 y: w(0xa8a7d469),
704 z: w(0x97830e05),
705 w: w(0x113ba7bb),
706 }
707 }
708 }
709
710 impl Rng for XorShiftRng {
711 #[inline]
712 fn next_u32(&mut self) -> u32 {
713 let x = self.x;
714 let t = x ^ (x << 11);
715 self.x = self.y;
716 self.y = self.z;
717 self.z = self.w;
718 let w_ = self.w;
719 self.w = w_ ^ (w_ >> 19) ^ (t ^ (t >> 8));
720 self.w.0
721 }
722 }
723
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.");
729
730 self.x = w(seed[0]);
731 self.y = w(seed[1]);
732 self.z = w(seed[2]);
733 self.w = w(seed[3]);
734 }
735
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.");
740
741 XorShiftRng {
742 x: w(seed[0]),
743 y: w(seed[1]),
744 z: w(seed[2]),
745 w: w(seed[3]),
746 }
747 }
748 }
749
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) {
754 tuple = rng.gen();
755 }
756 let (x, y, z, w_) = tuple;
757 XorShiftRng { x: w(x), y: w(y), z: w(z), w: w(w_) }
758 }
759 }
760
761 /// A wrapper for generating floating point numbers uniformly in the
762 /// open interval `(0,1)` (not including either endpoint).
763 ///
764 /// Use `Closed01` for the closed interval `[0,1]`, and the default
765 /// `Rand` implementation for `f32` and `f64` for the half-open
766 /// `[0,1)`.
767 ///
768 /// # Example
769 /// ```rust
770 /// use rand::{random, Open01};
771 ///
772 /// let Open01(val) = random::<Open01<f32>>();
773 /// println!("f32 from (0,1): {}", val);
774 /// ```
775 pub struct Open01<F>(pub F);
776
777 /// A wrapper for generating floating point numbers uniformly in the
778 /// closed interval `[0,1]` (including both endpoints).
779 ///
780 /// Use `Open01` for the closed interval `(0,1)`, and the default
781 /// `Rand` implementation of `f32` and `f64` for the half-open
782 /// `[0,1)`.
783 ///
784 /// # Example
785 ///
786 /// ```rust
787 /// use rand::{random, Closed01};
788 ///
789 /// let Closed01(val) = random::<Closed01<f32>>();
790 /// println!("f32 from [0,1]: {}", val);
791 /// ```
792 pub struct Closed01<F>(pub F);
793
794 /// The standard RNG. This is designed to be efficient on the current
795 /// platform.
796 #[derive(Copy, Clone)]
797 pub struct StdRng {
798 rng: IsaacWordRng,
799 }
800
801 impl StdRng {
802 /// Create a randomly seeded instance of `StdRng`.
803 ///
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
809 /// appropriate.
810 ///
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() })
815 }
816 }
817
818 impl Rng for StdRng {
819 #[inline]
820 fn next_u32(&mut self) -> u32 {
821 self.rng.next_u32()
822 }
823
824 #[inline]
825 fn next_u64(&mut self) -> u64 {
826 self.rng.next_u64()
827 }
828 }
829
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
833 // randomness.
834 self.rng.reseed(unsafe {mem::transmute(seed)})
835 }
836
837 fn from_seed(seed: &'a [usize]) -> StdRng {
838 StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
839 }
840 }
841
842 /// Create a weak random number generator with a default algorithm and seed.
843 ///
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.
848 ///
849 /// This will read randomness from the operating system to seed the
850 /// generator.
851 pub fn weak_rng() -> XorShiftRng {
852 match OsRng::new() {
853 Ok(mut r) => r.gen(),
854 Err(e) => panic!("weak_rng: failed to create seeded RNG: {:?}", e)
855 }
856 }
857
858 /// Controls how the thread-local RNG is reseeded.
859 struct ThreadRngReseeder;
860
861 impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
862 fn reseed(&mut self, rng: &mut StdRng) {
863 *rng = match StdRng::new() {
864 Ok(r) => r,
865 Err(e) => panic!("could not reseed thread_rng: {}", e)
866 }
867 }
868 }
869 const THREAD_RNG_RESEED_THRESHOLD: u64 = 32_768;
870 type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
871
872 /// The thread-local RNG.
873 #[derive(Clone)]
874 pub struct ThreadRng {
875 rng: Rc<RefCell<ThreadRngInner>>,
876 }
877
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>()`.
881 ///
882 /// The RNG provided will reseed itself from the operating system
883 /// after generating a certain amount of randomness.
884 ///
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() {
893 Ok(r) => r,
894 Err(e) => panic!("could not initialize thread_rng: {}", e)
895 };
896 let rng = reseeding::ReseedingRng::new(r,
897 THREAD_RNG_RESEED_THRESHOLD,
898 ThreadRngReseeder);
899 Rc::new(RefCell::new(rng))
900 });
901
902 ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
903 }
904
905 impl Rng for ThreadRng {
906 fn next_u32(&mut self) -> u32 {
907 self.rng.borrow_mut().next_u32()
908 }
909
910 fn next_u64(&mut self) -> u64 {
911 self.rng.borrow_mut().next_u64()
912 }
913
914 #[inline]
915 fn fill_bytes(&mut self, bytes: &mut [u8]) {
916 self.rng.borrow_mut().fill_bytes(bytes)
917 }
918 }
919
920 /// Generates a random value using the thread-local random number generator.
921 ///
922 /// `random()` can generate various types of random things, and so may require
923 /// type hinting to generate the specific type you want.
924 ///
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.
928 ///
929 /// # Examples
930 ///
931 /// ```
932 /// let x = rand::random::<u8>();
933 /// println!("{}", x);
934 ///
935 /// let y = rand::random::<f64>();
936 /// println!("{}", y);
937 ///
938 /// if rand::random() { // generates a boolean
939 /// println!("Better lucky than good!");
940 /// }
941 /// ```
942 ///
943 /// Caching the thread local random number generator:
944 ///
945 /// ```
946 /// use rand::Rng;
947 ///
948 /// let mut v = vec![1, 2, 3];
949 ///
950 /// for x in v.iter_mut() {
951 /// *x = rand::random()
952 /// }
953 ///
954 /// // would be faster as
955 ///
956 /// let mut rng = rand::thread_rng();
957 ///
958 /// for x in v.iter_mut() {
959 /// *x = rng.gen();
960 /// }
961 /// ```
962 #[inline]
963 pub fn random<T: Rand>() -> T {
964 thread_rng().gen()
965 }
966
967 /// Randomly sample up to `amount` elements from an iterator.
968 ///
969 /// # Example
970 ///
971 /// ```rust
972 /// use rand::{thread_rng, sample};
973 ///
974 /// let mut rng = thread_rng();
975 /// let sample = sample(&mut rng, 1..100, 5);
976 /// println!("{:?}", sample);
977 /// ```
978 pub fn sample<T, I, R>(rng: &mut R, iterable: I, amount: usize) -> Vec<T>
979 where I: IntoIterator<Item=T>,
980 R: Rng,
981 {
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) {
989 *spot = elem;
990 }
991 }
992 }
993 reservoir
994 }
995
996 #[cfg(test)]
997 mod test {
998 use super::{Rng, thread_rng, random, SeedableRng, StdRng, sample};
999 use std::iter::repeat;
1000
1001 pub struct MyRng<R> { inner: R }
1002
1003 impl<R: Rng> Rng for MyRng<R> {
1004 fn next_u32(&mut self) -> u32 {
1005 fn next<T: Rng>(t: &mut T) -> u32 {
1006 t.next_u32()
1007 }
1008 next(&mut self.inner)
1009 }
1010 }
1011
1012 pub fn rng() -> MyRng<::ThreadRng> {
1013 MyRng { inner: ::thread_rng() }
1014 }
1015
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 }
1020
1021 // no fill_bytes on purpose
1022 }
1023
1024 pub fn iter_eq<I, J>(i: I, j: J) -> bool
1025 where I: IntoIterator,
1026 J: IntoIterator<Item=I::Item>,
1027 I::Item: Eq
1028 {
1029 // make sure the iterators have equal length
1030 let mut i = i.into_iter();
1031 let mut j = j.into_iter();
1032 loop {
1033 match (i.next(), j.next()) {
1034 (Some(ref ei), Some(ref ej)) if ei == ej => { }
1035 (None, None) => return true,
1036 _ => return false,
1037 }
1038 }
1039 }
1040
1041 #[test]
1042 fn test_fill_bytes_default() {
1043 let mut r = ConstRng { i: 0x11_22_33_44_55_66_77_88 };
1044
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);
1051
1052 // use this to get nicer error messages.
1053 for (i, &byte) in v.iter().enumerate() {
1054 if byte == 0 {
1055 panic!("byte {} of {} is zero", i, n)
1056 }
1057 }
1058 }
1059 }
1060
1061 #[test]
1062 fn test_gen_range() {
1063 let mut r = thread_rng();
1064 for _ in 0..1000 {
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);
1069 }
1070
1071 for _ in 0..1000 {
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);
1076 }
1077
1078 }
1079
1080 #[test]
1081 #[should_panic]
1082 fn test_gen_range_panic_int() {
1083 let mut r = thread_rng();
1084 r.gen_range(5, -2);
1085 }
1086
1087 #[test]
1088 #[should_panic]
1089 fn test_gen_range_panic_usize() {
1090 let mut r = thread_rng();
1091 r.gen_range(5, 2);
1092 }
1093
1094 #[test]
1095 fn test_gen_f64() {
1096 let mut r = thread_rng();
1097 let a = r.gen::<f64>();
1098 let b = r.gen::<f64>();
1099 debug!("{:?}", (a, b));
1100 }
1101
1102 #[test]
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);
1107 }
1108
1109 #[test]
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);
1115 }
1116
1117 #[test]
1118 fn test_gen_vec() {
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);
1123 }
1124
1125 #[test]
1126 fn test_choose() {
1127 let mut r = thread_rng();
1128 assert_eq!(r.choose(&[1, 1, 1]).map(|&x|x), Some(1));
1129
1130 let v: &[isize] = &[];
1131 assert_eq!(r.choose(v), None);
1132 }
1133
1134 #[test]
1135 fn test_shuffle() {
1136 let mut r = thread_rng();
1137 let empty: &mut [isize] = &mut [];
1138 r.shuffle(empty);
1139 let mut one = [1];
1140 r.shuffle(&mut one);
1141 let b: &[_] = &[1];
1142 assert_eq!(one, b);
1143
1144 let mut two = [1, 2];
1145 r.shuffle(&mut two);
1146 assert!(two == [1, 2] || two == [2, 1]);
1147
1148 let mut x = [1, 1, 1];
1149 r.shuffle(&mut x);
1150 let b: &[_] = &[1, 1, 1];
1151 assert_eq!(x, b);
1152 }
1153
1154 #[test]
1155 fn test_thread_rng() {
1156 let mut r = thread_rng();
1157 r.gen::<i32>();
1158 let mut v = [1, 1, 1];
1159 r.shuffle(&mut v);
1160 let b: &[_] = &[1, 1, 1];
1161 assert_eq!(v, b);
1162 assert_eq!(r.gen_range(0, 1), 0);
1163 }
1164
1165 #[test]
1166 fn test_rng_trait_object() {
1167 let mut rng = thread_rng();
1168 {
1169 let mut r = &mut rng as &mut Rng;
1170 r.next_u32();
1171 (&mut r).gen::<i32>();
1172 let mut v = [1, 1, 1];
1173 (&mut r).shuffle(&mut v);
1174 let b: &[_] = &[1, 1, 1];
1175 assert_eq!(v, b);
1176 assert_eq!((&mut r).gen_range(0, 1), 0);
1177 }
1178 {
1179 let mut r = Box::new(rng) as Box<Rng>;
1180 r.next_u32();
1181 r.gen::<i32>();
1182 let mut v = [1, 1, 1];
1183 r.shuffle(&mut v);
1184 let b: &[_] = &[1, 1, 1];
1185 assert_eq!(v, b);
1186 assert_eq!(r.gen_range(0, 1), 0);
1187 }
1188 }
1189
1190 #[test]
1191 fn test_random() {
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();
1196 let _many : ((),
1197 (usize,
1198 isize,
1199 Option<(u32, (bool,))>),
1200 (u8, i8, u16, i16, u32, i32, u64, i64),
1201 (f32, (f64, (f64,)))) = random();
1202 }
1203
1204 #[test]
1205 fn test_sample() {
1206 let min_val = 1;
1207 let max_val = 100;
1208
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);
1213
1214 assert_eq!(small_sample.len(), 5);
1215 assert_eq!(large_sample.len(), vals.len());
1216
1217 assert!(small_sample.iter().all(|e| {
1218 **e >= min_val && **e <= max_val
1219 }));
1220 }
1221
1222 #[test]
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)));
1229 }
1230
1231 #[test]
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>();
1236
1237 r.reseed(&s);
1238
1239 let string2 = r.gen_ascii_chars().take(100).collect::<String>();
1240 assert_eq!(string1, string2);
1241 }
1242 }