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/")]
25 #![allow(unknown_features)] #![feature(int_uint)]
33 #[cfg(test)] #[macro_use] extern crate std;
34 #[cfg(test)] #[macro_use] extern crate log;
38 pub use isaac::{IsaacRng, Isaac64Rng};
39 pub use chacha::ChaChaRng;
41 use distributions::{Range, IndependentSample};
42 use distributions::range::SampleRange;
45 static RAND_BENCH_N: u64 = 100;
47 pub mod distributions;
53 /// A type that can be randomly generated using an `Rng`.
54 pub trait Rand : Sized {
55 /// Generates a random instance of this type using the specified source of
57 fn rand<R: Rng>(rng: &mut R) -> Self;
60 /// A random number generator.
61 pub trait Rng : Sized {
62 /// Return the next random u32.
64 /// This rarely needs to be called directly, prefer `r.gen()` to
66 // FIXME #7771: Should be implemented in terms of next_u64
67 fn next_u32(&mut self) -> u32;
69 /// Return the next random u64.
71 /// By default this is implemented in terms of `next_u32`. An
72 /// implementation of this trait must provide at least one of
73 /// these two methods. Similarly to `next_u32`, this rarely needs
74 /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
75 fn next_u64(&mut self) -> u64 {
76 ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
79 /// Return the next random f32 selected from the half-open
80 /// interval `[0, 1)`.
82 /// By default this is implemented in terms of `next_u32`, but a
83 /// random number generator which can generate numbers satisfying
84 /// the requirements directly can overload this for performance.
85 /// It is required that the return value lies in `[0, 1)`.
87 /// See `Closed01` for the closed interval `[0,1]`, and
88 /// `Open01` for the open interval `(0,1)`.
89 fn next_f32(&mut self) -> f32 {
90 const MANTISSA_BITS: uint = 24;
91 const IGNORED_BITS: uint = 8;
92 const SCALE: f32 = (1u64 << MANTISSA_BITS) as f32;
94 // using any more than `MANTISSA_BITS` bits will
95 // cause (e.g.) 0xffff_ffff to correspond to 1
96 // exactly, so we need to drop some (8 for f32, 11
97 // for f64) to guarantee the open end.
98 (self.next_u32() >> IGNORED_BITS) as f32 / SCALE
101 /// Return the next random f64 selected from the half-open
102 /// interval `[0, 1)`.
104 /// By default this is implemented in terms of `next_u64`, but a
105 /// random number generator which can generate numbers satisfying
106 /// the requirements directly can overload this for performance.
107 /// It is required that the return value lies in `[0, 1)`.
109 /// See `Closed01` for the closed interval `[0,1]`, and
110 /// `Open01` for the open interval `(0,1)`.
111 fn next_f64(&mut self) -> f64 {
112 const MANTISSA_BITS: uint = 53;
113 const IGNORED_BITS: uint = 11;
114 const SCALE: f64 = (1u64 << MANTISSA_BITS) as f64;
116 (self.next_u64() >> IGNORED_BITS) as f64 / SCALE
119 /// Fill `dest` with random data.
121 /// This has a default implementation in terms of `next_u64` and
122 /// `next_u32`, but should be overridden by implementations that
123 /// offer a more efficient solution than just calling those
124 /// methods repeatedly.
126 /// This method does *not* have a requirement to bear any fixed
127 /// relationship to the other methods, for example, it does *not*
128 /// have to result in the same output as progressively filling
129 /// `dest` with `self.gen::<u8>()`, and any such behaviour should
130 /// not be relied upon.
132 /// This method should guarantee that `dest` is entirely filled
133 /// with new data, and may panic if this is impossible
134 /// (e.g. reading past the end of a file that is being used as the
135 /// source of randomness).
140 /// use std::rand::{thread_rng, Rng};
142 /// let mut v = [0u8; 13579];
143 /// thread_rng().fill_bytes(&mut v);
144 /// println!("{:?}", v.as_slice());
146 fn fill_bytes(&mut self, dest: &mut [u8]) {
147 // this could, in theory, be done by transmuting dest to a
148 // [u64], but this is (1) likely to be undefined behaviour for
149 // LLVM, (2) has to be very careful about alignment concerns,
150 // (3) adds more `unsafe` that needs to be checked, (4)
151 // probably doesn't give much performance gain if
152 // optimisations are on.
155 for byte in dest.iter_mut() {
157 // we could micro-optimise here by generating a u32 if
158 // we only need a few more bytes to fill the vector
160 num = self.next_u64();
164 *byte = (num & 0xff) as u8;
170 /// Return a random value of a `Rand` type.
175 /// use std::rand::{thread_rng, Rng};
177 /// let mut rng = thread_rng();
178 /// let x: uint = rng.gen();
179 /// println!("{}", x);
180 /// println!("{:?}", rng.gen::<(f64, bool)>());
183 fn gen<T: Rand>(&mut self) -> T {
187 /// Return an iterator that will yield an infinite number of randomly
193 /// use std::rand::{thread_rng, Rng};
195 /// let mut rng = thread_rng();
196 /// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
197 /// println!("{:?}", x);
198 /// println!("{:?}", rng.gen_iter::<(f64, bool)>().take(5)
199 /// .collect::<Vec<(f64, bool)>>());
201 fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
202 Generator { rng: self }
205 /// Generate a random value in the range [`low`, `high`).
207 /// This is a convenience wrapper around
208 /// `distributions::Range`. If this function will be called
209 /// repeatedly with the same arguments, one should use `Range`, as
210 /// that will amortize the computations that allow for perfect
211 /// uniformity, as they only happen on initialization.
215 /// Panics if `low >= high`.
220 /// use std::rand::{thread_rng, Rng};
222 /// let mut rng = thread_rng();
223 /// let n: uint = rng.gen_range(0u, 10);
224 /// println!("{}", n);
225 /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
226 /// println!("{}", m);
228 fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
229 assert!(low < high, "Rng.gen_range called with low >= high");
230 Range::new(low, high).ind_sample(self)
233 /// Return a bool with a 1 in n chance of true
238 /// use std::rand::{thread_rng, Rng};
240 /// let mut rng = thread_rng();
241 /// println!("{}", rng.gen_weighted_bool(3));
243 fn gen_weighted_bool(&mut self, n: uint) -> bool {
244 n <= 1 || self.gen_range(0, n) == 0
247 /// Return an iterator of random characters from the set A-Z,a-z,0-9.
252 /// use std::rand::{thread_rng, Rng};
254 /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
255 /// println!("{}", s);
257 fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
258 AsciiGenerator { rng: self }
261 /// Return a random element from `values`.
263 /// Return `None` if `values` is empty.
268 /// use std::rand::{thread_rng, Rng};
270 /// let choices = [1i, 2, 4, 8, 16, 32];
271 /// let mut rng = thread_rng();
272 /// println!("{:?}", rng.choose(&choices));
273 /// # // uncomment when slicing syntax is stable
274 /// //assert_eq!(rng.choose(&choices[0..0]), None);
276 fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
277 if values.is_empty() {
280 Some(&values[self.gen_range(0u, values.len())])
284 /// Shuffle a mutable slice in place.
289 /// use std::rand::{thread_rng, Rng};
291 /// let mut rng = thread_rng();
292 /// let mut y = [1i, 2, 3];
293 /// rng.shuffle(&mut y);
294 /// println!("{:?}", y.as_slice());
295 /// rng.shuffle(&mut y);
296 /// println!("{:?}", y.as_slice());
298 fn shuffle<T>(&mut self, values: &mut [T]) {
299 let mut i = values.len();
301 // invariant: elements with index >= i have been locked in place.
303 // lock element i in place.
304 values.swap(i, self.gen_range(0u, i + 1u));
309 /// Iterator which will generate a stream of random items.
311 /// This iterator is created via the `gen_iter` method on `Rng`.
312 pub struct Generator<'a, T, R:'a> {
316 impl<'a, T: Rand, R: Rng> Iterator for Generator<'a, T, R> {
319 fn next(&mut self) -> Option<T> {
324 /// Iterator which will continuously generate random ascii characters.
326 /// This iterator is created via the `gen_ascii_chars` method on `Rng`.
327 pub struct AsciiGenerator<'a, R:'a> {
331 impl<'a, R: Rng> Iterator for AsciiGenerator<'a, R> {
334 fn next(&mut self) -> Option<char> {
335 static GEN_ASCII_STR_CHARSET: &'static [u8] =
336 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
337 abcdefghijklmnopqrstuvwxyz\
339 Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
343 /// A random number generator that can be explicitly seeded to produce
344 /// the same stream of randomness multiple times.
345 pub trait SeedableRng<Seed>: Rng {
346 /// Reseed an RNG with the given seed.
351 /// use std::rand::{Rng, SeedableRng, StdRng};
353 /// let seed: &[_] = &[1, 2, 3, 4];
354 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
355 /// println!("{}", rng.gen::<f64>());
356 /// rng.reseed(&[5, 6, 7, 8]);
357 /// println!("{}", rng.gen::<f64>());
359 fn reseed(&mut self, Seed);
361 /// Create a new RNG with the given seed.
366 /// use std::rand::{Rng, SeedableRng, StdRng};
368 /// let seed: &[_] = &[1, 2, 3, 4];
369 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
370 /// println!("{}", rng.gen::<f64>());
372 fn from_seed(seed: Seed) -> Self;
375 /// An Xorshift[1] random number
378 /// The Xorshift algorithm is not suitable for cryptographic purposes
379 /// but is very fast. If you do not know for sure that it fits your
380 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
382 /// [1]: Marsaglia, George (July 2003). ["Xorshift
383 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
384 /// Statistical Software*. Vol. 8 (Issue 14).
385 #[allow(missing_copy_implementations)]
387 pub struct XorShiftRng {
395 /// Creates a new XorShiftRng instance which is not seeded.
397 /// The initial values of this RNG are constants, so all generators created
398 /// by this function will yield the same stream of random numbers. It is
399 /// highly recommended that this is created through `SeedableRng` instead of
401 pub fn new_unseeded() -> XorShiftRng {
411 impl Rng for XorShiftRng {
413 fn next_u32(&mut self) -> u32 {
415 let t = x ^ (x << 11);
420 self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
425 impl SeedableRng<[u32; 4]> for XorShiftRng {
426 /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
427 fn reseed(&mut self, seed: [u32; 4]) {
428 assert!(!seed.iter().all(|&x| x == 0),
429 "XorShiftRng.reseed called with an all zero seed.");
437 /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
438 fn from_seed(seed: [u32; 4]) -> XorShiftRng {
439 assert!(!seed.iter().all(|&x| x == 0),
440 "XorShiftRng::from_seed called with an all zero seed.");
451 impl Rand for XorShiftRng {
452 fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
453 let mut tuple: (u32, u32, u32, u32) = rng.gen();
454 while tuple == (0, 0, 0, 0) {
457 let (x, y, z, w) = tuple;
458 XorShiftRng { x: x, y: y, z: z, w: w }
462 /// A wrapper for generating floating point numbers uniformly in the
463 /// open interval `(0,1)` (not including either endpoint).
465 /// Use `Closed01` for the closed interval `[0,1]`, and the default
466 /// `Rand` implementation for `f32` and `f64` for the half-open
471 /// use std::rand::{random, Open01};
473 /// let Open01(val) = random::<Open01<f32>>();
474 /// println!("f32 from (0,1): {}", val);
476 pub struct Open01<F>(pub F);
478 /// A wrapper for generating floating point numbers uniformly in the
479 /// closed interval `[0,1]` (including both endpoints).
481 /// Use `Open01` for the closed interval `(0,1)`, and the default
482 /// `Rand` implementation of `f32` and `f64` for the half-open
488 /// use std::rand::{random, Closed01};
490 /// let Closed01(val) = random::<Closed01<f32>>();
491 /// println!("f32 from [0,1]: {}", val);
493 pub struct Closed01<F>(pub F);
497 pub use core::{option, fmt}; // panic!()
498 pub use core::clone; // derive Clone
499 pub use core::marker;
506 pub struct MyRng<R> { inner: R }
508 impl<R: rand::Rng> ::Rng for MyRng<R> {
509 fn next_u32(&mut self) -> u32 {
510 fn next<T: rand::Rng>(t: &mut T) -> u32 {
514 next(&mut self.inner)
518 pub fn rng() -> MyRng<rand::ThreadRng> {
519 MyRng { inner: rand::thread_rng() }
522 pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
523 MyRng { inner: rand::weak_rng() }