1 // Copyright 2013 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 #![license = "MIT/ASL2"]
21 #![crate_type = "rlib"]
22 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
23 html_favicon_url = "http://www.rust-lang.org/favicon.ico",
24 html_root_url = "http://doc.rust-lang.org/nightly/",
25 html_playground_url = "http://play.rust-lang.org/")]
27 #![feature(macro_rules, phase, globs)]
31 #[phase(plugin, link)]
34 #[cfg(test)] #[phase(plugin, link)] extern crate std;
35 #[cfg(test)] #[phase(plugin, link)] extern crate log;
36 #[cfg(test)] extern crate native;
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`.
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.
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 /// Fill `dest` with random data.
83 /// This has a default implementation in terms of `next_u64` and
84 /// `next_u32`, but should be overridden by implementations that
85 /// offer a more efficient solution than just calling those
86 /// methods repeatedly.
88 /// This method does *not* have a requirement to bear any fixed
89 /// relationship to the other methods, for example, it does *not*
90 /// have to result in the same output as progressively filling
91 /// `dest` with `self.gen::<u8>()`, and any such behaviour should
92 /// not be relied upon.
94 /// This method should guarantee that `dest` is entirely filled
95 /// with new data, and may fail if this is impossible
96 /// (e.g. reading past the end of a file that is being used as the
97 /// source of randomness).
102 /// use std::rand::{task_rng, Rng};
104 /// let mut v = [0u8, .. 13579];
105 /// task_rng().fill_bytes(v);
106 /// println!("{}", v.as_slice());
108 fn fill_bytes(&mut self, dest: &mut [u8]) {
109 // this could, in theory, be done by transmuting dest to a
110 // [u64], but this is (1) likely to be undefined behaviour for
111 // LLVM, (2) has to be very careful about alignment concerns,
112 // (3) adds more `unsafe` that needs to be checked, (4)
113 // probably doesn't give much performance gain if
114 // optimisations are on.
117 for byte in dest.iter_mut() {
119 // we could micro-optimise here by generating a u32 if
120 // we only need a few more bytes to fill the vector
122 num = self.next_u64();
126 *byte = (num & 0xff) as u8;
132 /// Return a random value of a `Rand` type.
137 /// use std::rand::{task_rng, Rng};
139 /// let mut rng = task_rng();
140 /// let x: uint = rng.gen();
141 /// println!("{}", x);
142 /// println!("{}", rng.gen::<(f64, bool)>());
145 fn gen<T: Rand>(&mut self) -> T {
149 /// Return an iterator which will yield an infinite number of randomly
155 /// use std::rand::{task_rng, Rng};
157 /// let mut rng = task_rng();
158 /// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
159 /// println!("{}", x);
160 /// println!("{}", rng.gen_iter::<(f64, bool)>().take(5)
161 /// .collect::<Vec<(f64, bool)>>());
163 fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
164 Generator { rng: self }
167 /// Generate a random value in the range [`low`, `high`). Fails if
170 /// This is a convenience wrapper around
171 /// `distributions::Range`. If this function will be called
172 /// repeatedly with the same arguments, one should use `Range`, as
173 /// that will amortize the computations that allow for perfect
174 /// uniformity, as they only happen on initialization.
179 /// use std::rand::{task_rng, Rng};
181 /// let mut rng = task_rng();
182 /// let n: uint = rng.gen_range(0u, 10);
183 /// println!("{}", n);
184 /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
185 /// println!("{}", m);
187 fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
188 assert!(low < high, "Rng.gen_range called with low >= high");
189 Range::new(low, high).ind_sample(self)
192 /// Return a bool with a 1 in n chance of true
197 /// use std::rand::{task_rng, Rng};
199 /// let mut rng = task_rng();
200 /// println!("{:b}", rng.gen_weighted_bool(3));
202 fn gen_weighted_bool(&mut self, n: uint) -> bool {
203 n == 0 || self.gen_range(0, n) == 0
206 /// Return an iterator of random characters from the set A-Z,a-z,0-9.
211 /// use std::rand::{task_rng, Rng};
213 /// let s: String = task_rng().gen_ascii_chars().take(10).collect();
214 /// println!("{}", s);
216 fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
217 AsciiGenerator { rng: self }
220 /// Return a random element from `values`.
222 /// Return `None` if `values` is empty.
227 /// use std::rand::{task_rng, Rng};
229 /// let choices = [1i, 2, 4, 8, 16, 32];
230 /// let mut rng = task_rng();
231 /// println!("{}", rng.choose(choices));
232 /// assert_eq!(rng.choose(choices[..0]), None);
234 fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
235 if values.is_empty() {
238 Some(&values[self.gen_range(0u, values.len())])
242 /// Shuffle a mutable slice in place.
247 /// use std::rand::{task_rng, Rng};
249 /// let mut rng = task_rng();
250 /// let mut y = [1i, 2, 3];
252 /// println!("{}", y.as_slice());
254 /// println!("{}", y.as_slice());
256 fn shuffle<T>(&mut self, values: &mut [T]) {
257 let mut i = values.len();
259 // invariant: elements with index >= i have been locked in place.
261 // lock element i in place.
262 values.swap(i, self.gen_range(0u, i + 1u));
267 /// Iterator which will generate a stream of random items.
269 /// This iterator is created via the `gen_iter` method on `Rng`.
270 pub struct Generator<'a, T, R:'a> {
274 impl<'a, T: Rand, R: Rng> Iterator<T> for Generator<'a, T, R> {
275 fn next(&mut self) -> Option<T> {
280 /// Iterator which will continuously generate random ascii characters.
282 /// This iterator is created via the `gen_ascii_chars` method on `Rng`.
283 pub struct AsciiGenerator<'a, R:'a> {
287 impl<'a, R: Rng> Iterator<char> for AsciiGenerator<'a, R> {
288 fn next(&mut self) -> Option<char> {
289 static GEN_ASCII_STR_CHARSET: &'static [u8] =
290 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
291 abcdefghijklmnopqrstuvwxyz\
293 Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
297 /// A random number generator that can be explicitly seeded to produce
298 /// the same stream of randomness multiple times.
299 pub trait SeedableRng<Seed>: Rng {
300 /// Reseed an RNG with the given seed.
305 /// use std::rand::{Rng, SeedableRng, StdRng};
307 /// let seed: &[_] = &[1, 2, 3, 4];
308 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
309 /// println!("{}", rng.gen::<f64>());
310 /// rng.reseed([5, 6, 7, 8]);
311 /// println!("{}", rng.gen::<f64>());
313 fn reseed(&mut self, Seed);
315 /// Create a new RNG with the given seed.
320 /// use std::rand::{Rng, SeedableRng, StdRng};
322 /// let seed: &[_] = &[1, 2, 3, 4];
323 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
324 /// println!("{}", rng.gen::<f64>());
326 fn from_seed(seed: Seed) -> Self;
329 /// An Xorshift[1] random number
332 /// The Xorshift algorithm is not suitable for cryptographic purposes
333 /// but is very fast. If you do not know for sure that it fits your
334 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
336 /// [1]: Marsaglia, George (July 2003). ["Xorshift
337 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
338 /// Statistical Software*. Vol. 8 (Issue 14).
339 pub struct XorShiftRng {
347 /// Creates a new XorShiftRng instance which is not seeded.
349 /// The initial values of this RNG are constants, so all generators created
350 /// by this function will yield the same stream of random numbers. It is
351 /// highly recommended that this is created through `SeedableRng` instead of
353 pub fn new_unseeded() -> XorShiftRng {
363 impl Rng for XorShiftRng {
365 fn next_u32(&mut self) -> u32 {
367 let t = x ^ (x << 11);
372 self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
377 impl SeedableRng<[u32, .. 4]> for XorShiftRng {
378 /// Reseed an XorShiftRng. This will fail if `seed` is entirely 0.
379 fn reseed(&mut self, seed: [u32, .. 4]) {
380 assert!(!seed.iter().all(|&x| x == 0),
381 "XorShiftRng.reseed called with an all zero seed.");
389 /// Create a new XorShiftRng. This will fail if `seed` is entirely 0.
390 fn from_seed(seed: [u32, .. 4]) -> XorShiftRng {
391 assert!(!seed.iter().all(|&x| x == 0),
392 "XorShiftRng::from_seed called with an all zero seed.");
403 impl Rand for XorShiftRng {
404 fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
405 let mut tuple: (u32, u32, u32, u32) = rng.gen();
406 while tuple == (0, 0, 0, 0) {
409 let (x, y, z, w) = tuple;
410 XorShiftRng { x: x, y: y, z: z, w: w }
414 /// A wrapper for generating floating point numbers uniformly in the
415 /// open interval `(0,1)` (not including either endpoint).
417 /// Use `Closed01` for the closed interval `[0,1]`, and the default
418 /// `Rand` implementation for `f32` and `f64` for the half-open
423 /// use std::rand::{random, Open01};
425 /// let Open01(val) = random::<Open01<f32>>();
426 /// println!("f32 from (0,1): {}", val);
428 pub struct Open01<F>(pub F);
430 /// A wrapper for generating floating point numbers uniformly in the
431 /// closed interval `[0,1]` (including both endpoints).
433 /// Use `Open01` for the closed interval `(0,1)`, and the default
434 /// `Rand` implementation of `f32` and `f64` for the half-open
440 /// use std::rand::{random, Closed01};
442 /// let Closed01(val) = random::<Closed01<f32>>();
443 /// println!("f32 from [0,1]: {}", val);
445 pub struct Closed01<F>(pub F);
449 pub use core::{option, fmt}; // fail!()
456 pub struct MyRng<R> { inner: R }
458 impl<R: rand::Rng> ::Rng for MyRng<R> {
459 fn next_u32(&mut self) -> u32 {
460 fn next<T: rand::Rng>(t: &mut T) -> u32 {
464 next(&mut self.inner)
468 pub fn rng() -> MyRng<rand::TaskRng> {
469 MyRng { inner: rand::task_rng() }
472 pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
473 MyRng { inner: rand::weak_rng() }