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/")]
26 #![feature(macro_rules, phase, globs)]
27 #![feature(unboxed_closures)]
28 #![feature(associated_types)]
32 #[phase(plugin, link)]
35 #[cfg(test)] #[phase(plugin, link)] extern crate std;
36 #[cfg(test)] #[phase(plugin, link)] extern crate log;
40 pub use isaac::{IsaacRng, Isaac64Rng};
41 pub use chacha::ChaChaRng;
43 use distributions::{Range, IndependentSample};
44 use distributions::range::SampleRange;
47 static RAND_BENCH_N: u64 = 100;
49 pub mod distributions;
55 /// A type that can be randomly generated using an `Rng`.
56 pub trait Rand : Sized {
57 /// Generates a random instance of this type using the specified source of
59 fn rand<R: Rng>(rng: &mut R) -> Self;
62 /// A random number generator.
63 pub trait Rng : Sized {
64 /// Return the next random u32.
66 /// This rarely needs to be called directly, prefer `r.gen()` to
68 // FIXME #7771: Should be implemented in terms of next_u64
69 fn next_u32(&mut self) -> u32;
71 /// Return the next random u64.
73 /// By default this is implemented in terms of `next_u32`. An
74 /// implementation of this trait must provide at least one of
75 /// these two methods. Similarly to `next_u32`, this rarely needs
76 /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
77 fn next_u64(&mut self) -> u64 {
78 ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
81 /// Return the next random f32 selected from the half-open
82 /// interval `[0, 1)`.
84 /// By default this is implemented in terms of `next_u32`, but a
85 /// random number generator which can generate numbers satisfying
86 /// the requirements directly can overload this for performance.
87 /// It is required that the return value lies in `[0, 1)`.
89 /// See `Closed01` for the closed interval `[0,1]`, and
90 /// `Open01` for the open interval `(0,1)`.
91 fn next_f32(&mut self) -> f32 {
92 const MANTISSA_BITS: uint = 24;
93 const IGNORED_BITS: uint = 8;
94 const SCALE: f32 = (1u64 << MANTISSA_BITS) as f32;
96 // using any more than `MANTISSA_BITS` bits will
97 // cause (e.g.) 0xffff_ffff to correspond to 1
98 // exactly, so we need to drop some (8 for f32, 11
99 // for f64) to guarantee the open end.
100 (self.next_u32() >> IGNORED_BITS) as f32 / SCALE
103 /// Return the next random f64 selected from the half-open
104 /// interval `[0, 1)`.
106 /// By default this is implemented in terms of `next_u64`, but a
107 /// random number generator which can generate numbers satisfying
108 /// the requirements directly can overload this for performance.
109 /// It is required that the return value lies in `[0, 1)`.
111 /// See `Closed01` for the closed interval `[0,1]`, and
112 /// `Open01` for the open interval `(0,1)`.
113 fn next_f64(&mut self) -> f64 {
114 const MANTISSA_BITS: uint = 53;
115 const IGNORED_BITS: uint = 11;
116 const SCALE: f64 = (1u64 << MANTISSA_BITS) as f64;
118 (self.next_u64() >> IGNORED_BITS) as f64 / SCALE
121 /// Fill `dest` with random data.
123 /// This has a default implementation in terms of `next_u64` and
124 /// `next_u32`, but should be overridden by implementations that
125 /// offer a more efficient solution than just calling those
126 /// methods repeatedly.
128 /// This method does *not* have a requirement to bear any fixed
129 /// relationship to the other methods, for example, it does *not*
130 /// have to result in the same output as progressively filling
131 /// `dest` with `self.gen::<u8>()`, and any such behaviour should
132 /// not be relied upon.
134 /// This method should guarantee that `dest` is entirely filled
135 /// with new data, and may panic if this is impossible
136 /// (e.g. reading past the end of a file that is being used as the
137 /// source of randomness).
142 /// use std::rand::{thread_rng, Rng};
144 /// let mut v = [0u8; 13579];
145 /// thread_rng().fill_bytes(&mut v);
146 /// println!("{}", v.as_slice());
148 fn fill_bytes(&mut self, dest: &mut [u8]) {
149 // this could, in theory, be done by transmuting dest to a
150 // [u64], but this is (1) likely to be undefined behaviour for
151 // LLVM, (2) has to be very careful about alignment concerns,
152 // (3) adds more `unsafe` that needs to be checked, (4)
153 // probably doesn't give much performance gain if
154 // optimisations are on.
157 for byte in dest.iter_mut() {
159 // we could micro-optimise here by generating a u32 if
160 // we only need a few more bytes to fill the vector
162 num = self.next_u64();
166 *byte = (num & 0xff) as u8;
172 /// Return a random value of a `Rand` type.
177 /// use std::rand::{thread_rng, Rng};
179 /// let mut rng = thread_rng();
180 /// let x: uint = rng.gen();
181 /// println!("{}", x);
182 /// println!("{}", rng.gen::<(f64, bool)>());
185 fn gen<T: Rand>(&mut self) -> T {
189 /// Return an iterator that will yield an infinite number of randomly
195 /// use std::rand::{thread_rng, Rng};
197 /// let mut rng = thread_rng();
198 /// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
199 /// println!("{}", x);
200 /// println!("{}", rng.gen_iter::<(f64, bool)>().take(5)
201 /// .collect::<Vec<(f64, bool)>>());
203 fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
204 Generator { rng: self }
207 /// Generate a random value in the range [`low`, `high`).
209 /// This is a convenience wrapper around
210 /// `distributions::Range`. If this function will be called
211 /// repeatedly with the same arguments, one should use `Range`, as
212 /// that will amortize the computations that allow for perfect
213 /// uniformity, as they only happen on initialization.
217 /// Panics if `low >= high`.
222 /// use std::rand::{thread_rng, Rng};
224 /// let mut rng = thread_rng();
225 /// let n: uint = rng.gen_range(0u, 10);
226 /// println!("{}", n);
227 /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
228 /// println!("{}", m);
230 fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
231 assert!(low < high, "Rng.gen_range called with low >= high");
232 Range::new(low, high).ind_sample(self)
235 /// Return a bool with a 1 in n chance of true
240 /// use std::rand::{thread_rng, Rng};
242 /// let mut rng = thread_rng();
243 /// println!("{}", rng.gen_weighted_bool(3));
245 fn gen_weighted_bool(&mut self, n: uint) -> bool {
246 n <= 1 || self.gen_range(0, n) == 0
249 /// Return an iterator of random characters from the set A-Z,a-z,0-9.
254 /// use std::rand::{thread_rng, Rng};
256 /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
257 /// println!("{}", s);
259 fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
260 AsciiGenerator { rng: self }
263 /// Return a random element from `values`.
265 /// Return `None` if `values` is empty.
270 /// use std::rand::{thread_rng, Rng};
272 /// let choices = [1, 2, 4, 8, 16, 32];
273 /// let mut rng = thread_rng();
274 /// println!("{}", rng.choose(&choices));
275 /// # // replace with slicing syntax when it's stable!
276 /// assert_eq!(rng.choose(choices.slice_to(0)), None);
278 fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
279 if values.is_empty() {
282 Some(&values[self.gen_range(0u, values.len())])
286 /// Shuffle a mutable slice in place.
291 /// use std::rand::{thread_rng, Rng};
293 /// let mut rng = thread_rng();
294 /// let mut y = [1, 2, 3];
295 /// rng.shuffle(&mut y);
296 /// println!("{}", y.as_slice());
297 /// rng.shuffle(&mut y);
298 /// println!("{}", y.as_slice());
300 fn shuffle<T>(&mut self, values: &mut [T]) {
301 let mut i = values.len();
303 // invariant: elements with index >= i have been locked in place.
305 // lock element i in place.
306 values.swap(i, self.gen_range(0u, i + 1u));
311 /// Iterator which will generate a stream of random items.
313 /// This iterator is created via the `gen_iter` method on `Rng`.
314 pub struct Generator<'a, T, R:'a> {
318 impl<'a, T: Rand, R: Rng> Iterator for Generator<'a, T, R> {
321 fn next(&mut self) -> Option<T> {
326 /// Iterator which will continuously generate random ascii characters.
328 /// This iterator is created via the `gen_ascii_chars` method on `Rng`.
329 pub struct AsciiGenerator<'a, R:'a> {
333 impl<'a, R: Rng> Iterator for AsciiGenerator<'a, R> {
336 fn next(&mut self) -> Option<char> {
337 static GEN_ASCII_STR_CHARSET: &'static [u8] =
338 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
339 abcdefghijklmnopqrstuvwxyz\
341 Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
345 /// A random number generator that can be explicitly seeded to produce
346 /// the same stream of randomness multiple times.
347 pub trait SeedableRng<Seed>: Rng {
348 /// Reseed an RNG with the given seed.
353 /// use std::rand::{Rng, SeedableRng, StdRng};
355 /// let seed: &[_] = &[1, 2, 3, 4];
356 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
357 /// println!("{}", rng.gen::<f64>());
358 /// rng.reseed(&[5, 6, 7, 8]);
359 /// println!("{}", rng.gen::<f64>());
361 fn reseed(&mut self, Seed);
363 /// Create a new RNG with the given seed.
368 /// use std::rand::{Rng, SeedableRng, StdRng};
370 /// let seed: &[_] = &[1, 2, 3, 4];
371 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
372 /// println!("{}", rng.gen::<f64>());
374 fn from_seed(seed: Seed) -> Self;
377 /// An Xorshift[1] random number
380 /// The Xorshift algorithm is not suitable for cryptographic purposes
381 /// but is very fast. If you do not know for sure that it fits your
382 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
384 /// [1]: Marsaglia, George (July 2003). ["Xorshift
385 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
386 /// Statistical Software*. Vol. 8 (Issue 14).
387 #[allow(missing_copy_implementations)]
389 pub struct XorShiftRng {
397 /// Creates a new XorShiftRng instance which is not seeded.
399 /// The initial values of this RNG are constants, so all generators created
400 /// by this function will yield the same stream of random numbers. It is
401 /// highly recommended that this is created through `SeedableRng` instead of
403 pub fn new_unseeded() -> XorShiftRng {
413 impl Rng for XorShiftRng {
415 fn next_u32(&mut self) -> u32 {
417 let t = x ^ (x << 11);
422 self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
427 impl SeedableRng<[u32; 4]> for XorShiftRng {
428 /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
429 fn reseed(&mut self, seed: [u32; 4]) {
430 assert!(!seed.iter().all(|&x| x == 0),
431 "XorShiftRng.reseed called with an all zero seed.");
439 /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
440 fn from_seed(seed: [u32; 4]) -> XorShiftRng {
441 assert!(!seed.iter().all(|&x| x == 0),
442 "XorShiftRng::from_seed called with an all zero seed.");
453 impl Rand for XorShiftRng {
454 fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
455 let mut tuple: (u32, u32, u32, u32) = rng.gen();
456 while tuple == (0, 0, 0, 0) {
459 let (x, y, z, w) = tuple;
460 XorShiftRng { x: x, y: y, z: z, w: w }
464 /// A wrapper for generating floating point numbers uniformly in the
465 /// open interval `(0,1)` (not including either endpoint).
467 /// Use `Closed01` for the closed interval `[0,1]`, and the default
468 /// `Rand` implementation for `f32` and `f64` for the half-open
473 /// use std::rand::{random, Open01};
475 /// let Open01(val) = random::<Open01<f32>>();
476 /// println!("f32 from (0,1): {}", val);
478 pub struct Open01<F>(pub F);
480 /// A wrapper for generating floating point numbers uniformly in the
481 /// closed interval `[0,1]` (including both endpoints).
483 /// Use `Open01` for the closed interval `(0,1)`, and the default
484 /// `Rand` implementation of `f32` and `f64` for the half-open
490 /// use std::rand::{random, Closed01};
492 /// let Closed01(val) = random::<Closed01<f32>>();
493 /// println!("f32 from [0,1]: {}", val);
495 pub struct Closed01<F>(pub F);
499 pub use core::{option, fmt}; // panic!()
500 pub use core::clone; // derive Clone
508 pub struct MyRng<R> { inner: R }
510 impl<R: rand::Rng> ::Rng for MyRng<R> {
511 fn next_u32(&mut self) -> u32 {
512 fn next<T: rand::Rng>(t: &mut T) -> u32 {
516 next(&mut self.inner)
520 pub fn rng() -> MyRng<rand::ThreadRng> {
521 MyRng { inner: rand::thread_rng() }
524 pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
525 MyRng { inner: rand::weak_rng() }