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 //! Interface to random number generators in Rust.
13 //! This is an experimental library which lives underneath the standard library
14 //! in its dependency chain. This library is intended to define the interface
15 //! for random number generation and also provide utilities around doing so. It
16 //! is not recommended to use this library directly, but rather the official
17 //! interface through `std::rand`.
19 #![crate_name = "rand"]
20 #![crate_type = "rlib"]
21 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
22 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
23 html_root_url = "http://doc.rust-lang.org/nightly/",
24 html_playground_url = "http://play.rust-lang.org/")]
28 #![unstable(feature = "rand")]
29 #![feature(staged_api)]
32 #![deprecated(reason = "use the crates.io `rand` library instead",
33 since = "1.0.0-alpha")]
40 #[cfg(test)] #[macro_use] extern crate std;
41 #[cfg(test)] #[macro_use] extern crate log;
45 pub use isaac::{IsaacRng, Isaac64Rng};
46 pub use chacha::ChaChaRng;
48 use distributions::{Range, IndependentSample};
49 use distributions::range::SampleRange;
52 static RAND_BENCH_N: u64 = 100;
54 pub mod distributions;
60 /// A type that can be randomly generated using an `Rng`.
61 pub trait Rand : Sized {
62 /// Generates a random instance of this type using the specified source of
64 fn rand<R: Rng>(rng: &mut R) -> Self;
67 /// A random number generator.
68 pub trait Rng : Sized {
69 /// Return the next random u32.
71 /// This rarely needs to be called directly, prefer `r.gen()` to
73 // FIXME #7771: Should be implemented in terms of next_u64
74 fn next_u32(&mut self) -> u32;
76 /// Return the next random u64.
78 /// By default this is implemented in terms of `next_u32`. An
79 /// implementation of this trait must provide at least one of
80 /// these two methods. Similarly to `next_u32`, this rarely needs
81 /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
82 fn next_u64(&mut self) -> u64 {
83 ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
86 /// Return the next random f32 selected from the half-open
87 /// interval `[0, 1)`.
89 /// By default this is implemented in terms of `next_u32`, but a
90 /// random number generator which can generate numbers satisfying
91 /// the requirements directly can overload this for performance.
92 /// It is required that the return value lies in `[0, 1)`.
94 /// See `Closed01` for the closed interval `[0,1]`, and
95 /// `Open01` for the open interval `(0,1)`.
96 fn next_f32(&mut self) -> f32 {
97 const MANTISSA_BITS: uint = 24;
98 const IGNORED_BITS: uint = 8;
99 const SCALE: f32 = (1u64 << MANTISSA_BITS) as f32;
101 // using any more than `MANTISSA_BITS` bits will
102 // cause (e.g.) 0xffff_ffff to correspond to 1
103 // exactly, so we need to drop some (8 for f32, 11
104 // for f64) to guarantee the open end.
105 (self.next_u32() >> IGNORED_BITS) as f32 / SCALE
108 /// Return the next random f64 selected from the half-open
109 /// interval `[0, 1)`.
111 /// By default this is implemented in terms of `next_u64`, but a
112 /// random number generator which can generate numbers satisfying
113 /// the requirements directly can overload this for performance.
114 /// It is required that the return value lies in `[0, 1)`.
116 /// See `Closed01` for the closed interval `[0,1]`, and
117 /// `Open01` for the open interval `(0,1)`.
118 fn next_f64(&mut self) -> f64 {
119 const MANTISSA_BITS: uint = 53;
120 const IGNORED_BITS: uint = 11;
121 const SCALE: f64 = (1u64 << MANTISSA_BITS) as f64;
123 (self.next_u64() >> IGNORED_BITS) as f64 / SCALE
126 /// Fill `dest` with random data.
128 /// This has a default implementation in terms of `next_u64` and
129 /// `next_u32`, but should be overridden by implementations that
130 /// offer a more efficient solution than just calling those
131 /// methods repeatedly.
133 /// This method does *not* have a requirement to bear any fixed
134 /// relationship to the other methods, for example, it does *not*
135 /// have to result in the same output as progressively filling
136 /// `dest` with `self.gen::<u8>()`, and any such behaviour should
137 /// not be relied upon.
139 /// This method should guarantee that `dest` is entirely filled
140 /// with new data, and may panic if this is impossible
141 /// (e.g. reading past the end of a file that is being used as the
142 /// source of randomness).
147 /// use std::rand::{thread_rng, Rng};
149 /// let mut v = [0u8; 13579];
150 /// thread_rng().fill_bytes(&mut v);
151 /// println!("{:?}", v.as_slice());
153 fn fill_bytes(&mut self, dest: &mut [u8]) {
154 // this could, in theory, be done by transmuting dest to a
155 // [u64], but this is (1) likely to be undefined behaviour for
156 // LLVM, (2) has to be very careful about alignment concerns,
157 // (3) adds more `unsafe` that needs to be checked, (4)
158 // probably doesn't give much performance gain if
159 // optimisations are on.
164 // we could micro-optimise here by generating a u32 if
165 // we only need a few more bytes to fill the vector
167 num = self.next_u64();
171 *byte = (num & 0xff) as u8;
177 /// Return a random value of a `Rand` type.
182 /// use std::rand::{thread_rng, Rng};
184 /// let mut rng = thread_rng();
185 /// let x: uint = rng.gen();
186 /// println!("{}", x);
187 /// println!("{:?}", rng.gen::<(f64, bool)>());
190 fn gen<T: Rand>(&mut self) -> T {
194 /// Return an iterator that will yield an infinite number of randomly
200 /// use std::rand::{thread_rng, Rng};
202 /// let mut rng = thread_rng();
203 /// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
204 /// println!("{:?}", x);
205 /// println!("{:?}", rng.gen_iter::<(f64, bool)>().take(5)
206 /// .collect::<Vec<(f64, bool)>>());
208 fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
209 Generator { rng: self }
212 /// Generate a random value in the range [`low`, `high`).
214 /// This is a convenience wrapper around
215 /// `distributions::Range`. If this function will be called
216 /// repeatedly with the same arguments, one should use `Range`, as
217 /// that will amortize the computations that allow for perfect
218 /// uniformity, as they only happen on initialization.
222 /// Panics if `low >= high`.
227 /// use std::rand::{thread_rng, Rng};
229 /// let mut rng = thread_rng();
230 /// let n: uint = rng.gen_range(0, 10);
231 /// println!("{}", n);
232 /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
233 /// println!("{}", m);
235 fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
236 assert!(low < high, "Rng.gen_range called with low >= high");
237 Range::new(low, high).ind_sample(self)
240 /// Return a bool with a 1 in n chance of true
245 /// use std::rand::{thread_rng, Rng};
247 /// let mut rng = thread_rng();
248 /// println!("{}", rng.gen_weighted_bool(3));
250 fn gen_weighted_bool(&mut self, n: uint) -> bool {
251 n <= 1 || self.gen_range(0, n) == 0
254 /// Return an iterator of random characters from the set A-Z,a-z,0-9.
259 /// use std::rand::{thread_rng, Rng};
261 /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
262 /// println!("{}", s);
264 fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
265 AsciiGenerator { rng: self }
268 /// Return a random element from `values`.
270 /// Return `None` if `values` is empty.
275 /// use std::rand::{thread_rng, Rng};
277 /// let choices = [1, 2, 4, 8, 16, 32];
278 /// let mut rng = thread_rng();
279 /// println!("{:?}", rng.choose(&choices));
280 /// assert_eq!(rng.choose(&choices[..0]), None);
282 fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
283 if values.is_empty() {
286 Some(&values[self.gen_range(0, values.len())])
290 /// Shuffle a mutable slice in place.
295 /// use std::rand::{thread_rng, Rng};
297 /// let mut rng = thread_rng();
298 /// let mut y = [1, 2, 3];
299 /// rng.shuffle(&mut y);
300 /// println!("{:?}", y.as_slice());
301 /// rng.shuffle(&mut y);
302 /// println!("{:?}", y.as_slice());
304 fn shuffle<T>(&mut self, values: &mut [T]) {
305 let mut i = values.len();
307 // invariant: elements with index >= i have been locked in place.
309 // lock element i in place.
310 values.swap(i, self.gen_range(0, i + 1));
315 /// Iterator which will generate a stream of random items.
317 /// This iterator is created via the `gen_iter` method on `Rng`.
318 pub struct Generator<'a, T, R:'a> {
322 impl<'a, T: Rand, R: Rng> Iterator for Generator<'a, T, R> {
325 fn next(&mut self) -> Option<T> {
330 /// Iterator which will continuously generate random ascii characters.
332 /// This iterator is created via the `gen_ascii_chars` method on `Rng`.
333 pub struct AsciiGenerator<'a, R:'a> {
337 impl<'a, R: Rng> Iterator for AsciiGenerator<'a, R> {
340 fn next(&mut self) -> Option<char> {
341 static GEN_ASCII_STR_CHARSET: &'static [u8] =
342 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
343 abcdefghijklmnopqrstuvwxyz\
345 Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
349 /// A random number generator that can be explicitly seeded to produce
350 /// the same stream of randomness multiple times.
351 pub trait SeedableRng<Seed>: Rng {
352 /// Reseed an RNG with the given seed.
357 /// use std::rand::{Rng, SeedableRng, StdRng};
359 /// let seed: &[_] = &[1, 2, 3, 4];
360 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
361 /// println!("{}", rng.gen::<f64>());
362 /// rng.reseed(&[5, 6, 7, 8]);
363 /// println!("{}", rng.gen::<f64>());
365 fn reseed(&mut self, Seed);
367 /// Create a new RNG with the given seed.
372 /// use std::rand::{Rng, SeedableRng, StdRng};
374 /// let seed: &[_] = &[1, 2, 3, 4];
375 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
376 /// println!("{}", rng.gen::<f64>());
378 fn from_seed(seed: Seed) -> Self;
381 /// An Xorshift[1] random number
384 /// The Xorshift algorithm is not suitable for cryptographic purposes
385 /// but is very fast. If you do not know for sure that it fits your
386 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
388 /// [1]: Marsaglia, George (July 2003). ["Xorshift
389 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
390 /// Statistical Software*. Vol. 8 (Issue 14).
392 pub struct XorShiftRng {
400 /// Creates a new XorShiftRng instance which is not seeded.
402 /// The initial values of this RNG are constants, so all generators created
403 /// by this function will yield the same stream of random numbers. It is
404 /// highly recommended that this is created through `SeedableRng` instead of
406 pub fn new_unseeded() -> XorShiftRng {
416 impl Rng for XorShiftRng {
418 fn next_u32(&mut self) -> u32 {
420 let t = x ^ (x << 11);
425 self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
430 impl SeedableRng<[u32; 4]> for XorShiftRng {
431 /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
432 fn reseed(&mut self, seed: [u32; 4]) {
433 assert!(!seed.iter().all(|&x| x == 0),
434 "XorShiftRng.reseed called with an all zero seed.");
442 /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
443 fn from_seed(seed: [u32; 4]) -> XorShiftRng {
444 assert!(!seed.iter().all(|&x| x == 0),
445 "XorShiftRng::from_seed called with an all zero seed.");
456 impl Rand for XorShiftRng {
457 fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
458 let mut tuple: (u32, u32, u32, u32) = rng.gen();
459 while tuple == (0, 0, 0, 0) {
462 let (x, y, z, w) = tuple;
463 XorShiftRng { x: x, y: y, z: z, w: w }
467 /// A wrapper for generating floating point numbers uniformly in the
468 /// open interval `(0,1)` (not including either endpoint).
470 /// Use `Closed01` for the closed interval `[0,1]`, and the default
471 /// `Rand` implementation for `f32` and `f64` for the half-open
476 /// use std::rand::{random, Open01};
478 /// let Open01(val) = random::<Open01<f32>>();
479 /// println!("f32 from (0,1): {}", val);
481 pub struct Open01<F>(pub F);
483 /// A wrapper for generating floating point numbers uniformly in the
484 /// closed interval `[0,1]` (including both endpoints).
486 /// Use `Open01` for the closed interval `(0,1)`, and the default
487 /// `Rand` implementation of `f32` and `f64` for the half-open
493 /// use std::rand::{random, Closed01};
495 /// let Closed01(val) = random::<Closed01<f32>>();
496 /// println!("f32 from [0,1]: {}", val);
498 pub struct Closed01<F>(pub F);
504 pub struct MyRng<R> { inner: R }
506 impl<R: rand::Rng> ::Rng for MyRng<R> {
507 fn next_u32(&mut self) -> u32 {
508 fn next<T: rand::Rng>(t: &mut T) -> u32 {
512 next(&mut self.inner)
516 pub fn rng() -> MyRng<rand::ThreadRng> {
517 MyRng { inner: rand::thread_rng() }
520 pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
521 MyRng { inner: rand::weak_rng() }