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)]
31 #[phase(plugin, link)]
34 #[cfg(test)] #[phase(plugin, link)] extern crate std;
35 #[cfg(test)] #[phase(plugin, link)] extern crate log;
39 pub use isaac::{IsaacRng, Isaac64Rng};
40 pub use chacha::ChaChaRng;
42 use distributions::{Range, IndependentSample};
43 use distributions::range::SampleRange;
46 static RAND_BENCH_N: u64 = 100;
48 pub mod distributions;
54 /// A type that can be randomly generated using an `Rng`.
56 /// Generates a random instance of this type using the specified source of
58 fn rand<R: Rng>(rng: &mut R) -> Self;
61 /// A random number generator.
63 /// Return the next random u32.
65 /// This rarely needs to be called directly, prefer `r.gen()` to
67 // FIXME #7771: Should be implemented in terms of next_u64
68 fn next_u32(&mut self) -> u32;
70 /// Return the next random u64.
72 /// By default this is implemented in terms of `next_u32`. An
73 /// implementation of this trait must provide at least one of
74 /// these two methods. Similarly to `next_u32`, this rarely needs
75 /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
76 fn next_u64(&mut self) -> u64 {
77 (self.next_u32() as u64 << 32) | (self.next_u32() as u64)
80 /// Return the next random f32 selected from the half-open
81 /// interval `[0, 1)`.
83 /// By default this is implemented in terms of `next_u32`, but a
84 /// random number generator which can generate numbers satisfying
85 /// the requirements directly can overload this for performance.
86 /// It is required that the return value lies in `[0, 1)`.
88 /// See `Closed01` for the closed interval `[0,1]`, and
89 /// `Open01` for the open interval `(0,1)`.
90 fn next_f32(&mut self) -> f32 {
91 const MANTISSA_BITS: uint = 24;
92 const IGNORED_BITS: uint = 8;
93 const SCALE: f32 = (1u64 << MANTISSA_BITS) as f32;
95 // using any more than `MANTISSA_BITS` bits will
96 // cause (e.g.) 0xffff_ffff to correspond to 1
97 // exactly, so we need to drop some (8 for f32, 11
98 // for f64) to guarantee the open end.
99 (self.next_u32() >> IGNORED_BITS) as f32 / SCALE
102 /// Return the next random f64 selected from the half-open
103 /// interval `[0, 1)`.
105 /// By default this is implemented in terms of `next_u64`, but a
106 /// random number generator which can generate numbers satisfying
107 /// the requirements directly can overload this for performance.
108 /// It is required that the return value lies in `[0, 1)`.
110 /// See `Closed01` for the closed interval `[0,1]`, and
111 /// `Open01` for the open interval `(0,1)`.
112 fn next_f64(&mut self) -> f64 {
113 const MANTISSA_BITS: uint = 53;
114 const IGNORED_BITS: uint = 11;
115 const SCALE: f64 = (1u64 << MANTISSA_BITS) as f64;
117 (self.next_u64() >> IGNORED_BITS) as f64 / SCALE
120 /// Fill `dest` with random data.
122 /// This has a default implementation in terms of `next_u64` and
123 /// `next_u32`, but should be overridden by implementations that
124 /// offer a more efficient solution than just calling those
125 /// methods repeatedly.
127 /// This method does *not* have a requirement to bear any fixed
128 /// relationship to the other methods, for example, it does *not*
129 /// have to result in the same output as progressively filling
130 /// `dest` with `self.gen::<u8>()`, and any such behaviour should
131 /// not be relied upon.
133 /// This method should guarantee that `dest` is entirely filled
134 /// with new data, and may panic if this is impossible
135 /// (e.g. reading past the end of a file that is being used as the
136 /// source of randomness).
141 /// use std::rand::{thread_rng, Rng};
143 /// let mut v = [0u8; 13579];
144 /// thread_rng().fill_bytes(&mut v);
145 /// println!("{}", v.as_slice());
147 fn fill_bytes(&mut self, dest: &mut [u8]) {
148 // this could, in theory, be done by transmuting dest to a
149 // [u64], but this is (1) likely to be undefined behaviour for
150 // LLVM, (2) has to be very careful about alignment concerns,
151 // (3) adds more `unsafe` that needs to be checked, (4)
152 // probably doesn't give much performance gain if
153 // optimisations are on.
156 for byte in dest.iter_mut() {
158 // we could micro-optimise here by generating a u32 if
159 // we only need a few more bytes to fill the vector
161 num = self.next_u64();
165 *byte = (num & 0xff) as u8;
171 /// Return a random value of a `Rand` type.
176 /// use std::rand::{thread_rng, Rng};
178 /// let mut rng = thread_rng();
179 /// let x: uint = rng.gen();
180 /// println!("{}", x);
181 /// println!("{}", rng.gen::<(f64, bool)>());
184 fn gen<T: Rand>(&mut self) -> T {
188 /// Return an iterator that will yield an infinite number of randomly
194 /// use std::rand::{thread_rng, Rng};
196 /// let mut rng = thread_rng();
197 /// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
198 /// println!("{}", x);
199 /// println!("{}", rng.gen_iter::<(f64, bool)>().take(5)
200 /// .collect::<Vec<(f64, bool)>>());
202 fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
203 Generator { rng: self }
206 /// Generate a random value in the range [`low`, `high`).
208 /// This is a convenience wrapper around
209 /// `distributions::Range`. If this function will be called
210 /// repeatedly with the same arguments, one should use `Range`, as
211 /// that will amortize the computations that allow for perfect
212 /// uniformity, as they only happen on initialization.
216 /// Panics if `low >= high`.
221 /// use std::rand::{thread_rng, Rng};
223 /// let mut rng = thread_rng();
224 /// let n: uint = rng.gen_range(0u, 10);
225 /// println!("{}", n);
226 /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
227 /// println!("{}", m);
229 fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
230 assert!(low < high, "Rng.gen_range called with low >= high");
231 Range::new(low, high).ind_sample(self)
234 /// Return a bool with a 1 in n chance of true
239 /// use std::rand::{thread_rng, Rng};
241 /// let mut rng = thread_rng();
242 /// println!("{}", rng.gen_weighted_bool(3));
244 fn gen_weighted_bool(&mut self, n: uint) -> bool {
245 n == 0 || self.gen_range(0, n) == 0
248 /// Return an iterator of random characters from the set A-Z,a-z,0-9.
253 /// use std::rand::{thread_rng, Rng};
255 /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
256 /// println!("{}", s);
258 fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
259 AsciiGenerator { rng: self }
262 /// Return a random element from `values`.
264 /// Return `None` if `values` is empty.
269 /// use std::rand::{thread_rng, Rng};
271 /// let choices = [1i, 2, 4, 8, 16, 32];
272 /// let mut rng = thread_rng();
273 /// println!("{}", rng.choose(&choices));
274 /// # // replace with slicing syntax when it's stable!
275 /// assert_eq!(rng.choose(choices.slice_to(0)), None);
277 fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
278 if values.is_empty() {
281 Some(&values[self.gen_range(0u, values.len())])
285 /// Shuffle a mutable slice in place.
290 /// use std::rand::{thread_rng, Rng};
292 /// let mut rng = thread_rng();
293 /// let mut y = [1i, 2, 3];
294 /// rng.shuffle(&mut y);
295 /// println!("{}", y.as_slice());
296 /// rng.shuffle(&mut y);
297 /// println!("{}", y.as_slice());
299 fn shuffle<T>(&mut self, values: &mut [T]) {
300 let mut i = values.len();
302 // invariant: elements with index >= i have been locked in place.
304 // lock element i in place.
305 values.swap(i, self.gen_range(0u, i + 1u));
310 /// Iterator which will generate a stream of random items.
312 /// This iterator is created via the `gen_iter` method on `Rng`.
313 pub struct Generator<'a, T, R:'a> {
317 impl<'a, T: Rand, R: Rng> Iterator<T> for Generator<'a, T, R> {
318 fn next(&mut self) -> Option<T> {
323 /// Iterator which will continuously generate random ascii characters.
325 /// This iterator is created via the `gen_ascii_chars` method on `Rng`.
326 pub struct AsciiGenerator<'a, R:'a> {
330 impl<'a, R: Rng> Iterator<char> for AsciiGenerator<'a, R> {
331 fn next(&mut self) -> Option<char> {
332 static GEN_ASCII_STR_CHARSET: &'static [u8] =
333 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
334 abcdefghijklmnopqrstuvwxyz\
336 Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
340 /// A random number generator that can be explicitly seeded to produce
341 /// the same stream of randomness multiple times.
342 pub trait SeedableRng<Seed>: Rng {
343 /// Reseed an RNG with the given seed.
348 /// use std::rand::{Rng, SeedableRng, StdRng};
350 /// let seed: &[_] = &[1, 2, 3, 4];
351 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
352 /// println!("{}", rng.gen::<f64>());
353 /// rng.reseed(&[5, 6, 7, 8]);
354 /// println!("{}", rng.gen::<f64>());
356 fn reseed(&mut self, Seed);
358 /// Create a new RNG with the given seed.
363 /// use std::rand::{Rng, SeedableRng, StdRng};
365 /// let seed: &[_] = &[1, 2, 3, 4];
366 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
367 /// println!("{}", rng.gen::<f64>());
369 fn from_seed(seed: Seed) -> Self;
372 /// An Xorshift[1] random number
375 /// The Xorshift algorithm is not suitable for cryptographic purposes
376 /// but is very fast. If you do not know for sure that it fits your
377 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
379 /// [1]: Marsaglia, George (July 2003). ["Xorshift
380 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
381 /// Statistical Software*. Vol. 8 (Issue 14).
382 #[allow(missing_copy_implementations)]
383 pub struct XorShiftRng {
390 impl Clone for XorShiftRng {
391 fn clone(&self) -> XorShiftRng {
402 /// Creates a new XorShiftRng instance which is not seeded.
404 /// The initial values of this RNG are constants, so all generators created
405 /// by this function will yield the same stream of random numbers. It is
406 /// highly recommended that this is created through `SeedableRng` instead of
408 pub fn new_unseeded() -> XorShiftRng {
418 impl Rng for XorShiftRng {
420 fn next_u32(&mut self) -> u32 {
422 let t = x ^ (x << 11);
427 self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
432 impl SeedableRng<[u32; 4]> for XorShiftRng {
433 /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
434 fn reseed(&mut self, seed: [u32; 4]) {
435 assert!(!seed.iter().all(|&x| x == 0),
436 "XorShiftRng.reseed called with an all zero seed.");
444 /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
445 fn from_seed(seed: [u32; 4]) -> XorShiftRng {
446 assert!(!seed.iter().all(|&x| x == 0),
447 "XorShiftRng::from_seed called with an all zero seed.");
458 impl Rand for XorShiftRng {
459 fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
460 let mut tuple: (u32, u32, u32, u32) = rng.gen();
461 while tuple == (0, 0, 0, 0) {
464 let (x, y, z, w) = tuple;
465 XorShiftRng { x: x, y: y, z: z, w: w }
469 /// A wrapper for generating floating point numbers uniformly in the
470 /// open interval `(0,1)` (not including either endpoint).
472 /// Use `Closed01` for the closed interval `[0,1]`, and the default
473 /// `Rand` implementation for `f32` and `f64` for the half-open
478 /// use std::rand::{random, Open01};
480 /// let Open01(val) = random::<Open01<f32>>();
481 /// println!("f32 from (0,1): {}", val);
483 pub struct Open01<F>(pub F);
485 /// A wrapper for generating floating point numbers uniformly in the
486 /// closed interval `[0,1]` (including both endpoints).
488 /// Use `Open01` for the closed interval `(0,1)`, and the default
489 /// `Rand` implementation of `f32` and `f64` for the half-open
495 /// use std::rand::{random, Closed01};
497 /// let Closed01(val) = random::<Closed01<f32>>();
498 /// println!("f32 from [0,1]: {}", val);
500 pub struct Closed01<F>(pub F);
504 pub use core::{option, fmt}; // panic!()
512 pub struct MyRng<R> { inner: R }
514 impl<R: rand::Rng> ::Rng for MyRng<R> {
515 fn next_u32(&mut self) -> u32 {
516 fn next<T: rand::Rng>(t: &mut T) -> u32 {
520 next(&mut self.inner)
524 pub fn rng() -> MyRng<rand::ThreadRng> {
525 MyRng { inner: rand::thread_rng() }
528 pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
529 MyRng { inner: rand::weak_rng() }