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/")]
32 #[cfg(test)] #[macro_use] extern crate std;
33 #[cfg(test)] #[macro_use] extern crate log;
37 pub use isaac::{IsaacRng, Isaac64Rng};
38 pub use chacha::ChaChaRng;
40 use distributions::{Range, IndependentSample};
41 use distributions::range::SampleRange;
44 static RAND_BENCH_N: u64 = 100;
46 pub mod distributions;
52 /// A type that can be randomly generated using an `Rng`.
53 pub trait Rand : Sized {
54 /// Generates a random instance of this type using the specified source of
56 fn rand<R: Rng>(rng: &mut R) -> Self;
59 /// A random number generator.
60 pub trait Rng : Sized {
61 /// Return the next random u32.
63 /// This rarely needs to be called directly, prefer `r.gen()` to
65 // FIXME #7771: Should be implemented in terms of next_u64
66 fn next_u32(&mut self) -> u32;
68 /// Return the next random u64.
70 /// By default this is implemented in terms of `next_u32`. An
71 /// implementation of this trait must provide at least one of
72 /// these two methods. Similarly to `next_u32`, this rarely needs
73 /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
74 fn next_u64(&mut self) -> u64 {
75 ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
78 /// Return the next random f32 selected from the half-open
79 /// interval `[0, 1)`.
81 /// By default this is implemented in terms of `next_u32`, but a
82 /// random number generator which can generate numbers satisfying
83 /// the requirements directly can overload this for performance.
84 /// It is required that the return value lies in `[0, 1)`.
86 /// See `Closed01` for the closed interval `[0,1]`, and
87 /// `Open01` for the open interval `(0,1)`.
88 fn next_f32(&mut self) -> f32 {
89 const MANTISSA_BITS: uint = 24;
90 const IGNORED_BITS: uint = 8;
91 const SCALE: f32 = (1u64 << MANTISSA_BITS) as f32;
93 // using any more than `MANTISSA_BITS` bits will
94 // cause (e.g.) 0xffff_ffff to correspond to 1
95 // exactly, so we need to drop some (8 for f32, 11
96 // for f64) to guarantee the open end.
97 (self.next_u32() >> IGNORED_BITS) as f32 / SCALE
100 /// Return the next random f64 selected from the half-open
101 /// interval `[0, 1)`.
103 /// By default this is implemented in terms of `next_u64`, but a
104 /// random number generator which can generate numbers satisfying
105 /// the requirements directly can overload this for performance.
106 /// It is required that the return value lies in `[0, 1)`.
108 /// See `Closed01` for the closed interval `[0,1]`, and
109 /// `Open01` for the open interval `(0,1)`.
110 fn next_f64(&mut self) -> f64 {
111 const MANTISSA_BITS: uint = 53;
112 const IGNORED_BITS: uint = 11;
113 const SCALE: f64 = (1u64 << MANTISSA_BITS) as f64;
115 (self.next_u64() >> IGNORED_BITS) as f64 / SCALE
118 /// Fill `dest` with random data.
120 /// This has a default implementation in terms of `next_u64` and
121 /// `next_u32`, but should be overridden by implementations that
122 /// offer a more efficient solution than just calling those
123 /// methods repeatedly.
125 /// This method does *not* have a requirement to bear any fixed
126 /// relationship to the other methods, for example, it does *not*
127 /// have to result in the same output as progressively filling
128 /// `dest` with `self.gen::<u8>()`, and any such behaviour should
129 /// not be relied upon.
131 /// This method should guarantee that `dest` is entirely filled
132 /// with new data, and may panic if this is impossible
133 /// (e.g. reading past the end of a file that is being used as the
134 /// source of randomness).
139 /// use std::rand::{thread_rng, Rng};
141 /// let mut v = [0u8; 13579];
142 /// thread_rng().fill_bytes(&mut v);
143 /// println!("{:?}", v.as_slice());
145 fn fill_bytes(&mut self, dest: &mut [u8]) {
146 // this could, in theory, be done by transmuting dest to a
147 // [u64], but this is (1) likely to be undefined behaviour for
148 // LLVM, (2) has to be very careful about alignment concerns,
149 // (3) adds more `unsafe` that needs to be checked, (4)
150 // probably doesn't give much performance gain if
151 // optimisations are on.
154 for byte in dest.iter_mut() {
156 // we could micro-optimise here by generating a u32 if
157 // we only need a few more bytes to fill the vector
159 num = self.next_u64();
163 *byte = (num & 0xff) as u8;
169 /// Return a random value of a `Rand` type.
174 /// use std::rand::{thread_rng, Rng};
176 /// let mut rng = thread_rng();
177 /// let x: uint = rng.gen();
178 /// println!("{}", x);
179 /// println!("{:?}", rng.gen::<(f64, bool)>());
182 fn gen<T: Rand>(&mut self) -> T {
186 /// Return an iterator that will yield an infinite number of randomly
192 /// use std::rand::{thread_rng, Rng};
194 /// let mut rng = thread_rng();
195 /// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
196 /// println!("{}", x);
197 /// println!("{:?}", rng.gen_iter::<(f64, bool)>().take(5)
198 /// .collect::<Vec<(f64, bool)>>());
200 fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
201 Generator { rng: self }
204 /// Generate a random value in the range [`low`, `high`).
206 /// This is a convenience wrapper around
207 /// `distributions::Range`. If this function will be called
208 /// repeatedly with the same arguments, one should use `Range`, as
209 /// that will amortize the computations that allow for perfect
210 /// uniformity, as they only happen on initialization.
214 /// Panics if `low >= high`.
219 /// use std::rand::{thread_rng, Rng};
221 /// let mut rng = thread_rng();
222 /// let n: uint = rng.gen_range(0u, 10);
223 /// println!("{}", n);
224 /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
225 /// println!("{}", m);
227 fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
228 assert!(low < high, "Rng.gen_range called with low >= high");
229 Range::new(low, high).ind_sample(self)
232 /// Return a bool with a 1 in n chance of true
237 /// use std::rand::{thread_rng, Rng};
239 /// let mut rng = thread_rng();
240 /// println!("{}", rng.gen_weighted_bool(3));
242 fn gen_weighted_bool(&mut self, n: uint) -> bool {
243 n <= 1 || self.gen_range(0, n) == 0
246 /// Return an iterator of random characters from the set A-Z,a-z,0-9.
251 /// use std::rand::{thread_rng, Rng};
253 /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
254 /// println!("{}", s);
256 fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
257 AsciiGenerator { rng: self }
260 /// Return a random element from `values`.
262 /// Return `None` if `values` is empty.
267 /// use std::rand::{thread_rng, Rng};
269 /// let choices = [1i, 2, 4, 8, 16, 32];
270 /// let mut rng = thread_rng();
271 /// println!("{:?}", rng.choose(&choices));
272 /// # // uncomment when slicing syntax is stable
273 /// //assert_eq!(rng.choose(choices.index(&(0..0))), None);
275 fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
276 if values.is_empty() {
279 Some(&values[self.gen_range(0u, values.len())])
283 /// Shuffle a mutable slice in place.
288 /// use std::rand::{thread_rng, Rng};
290 /// let mut rng = thread_rng();
291 /// let mut y = [1i, 2, 3];
292 /// rng.shuffle(&mut y);
293 /// println!("{}", y.as_slice());
294 /// rng.shuffle(&mut y);
295 /// println!("{}", y.as_slice());
297 fn shuffle<T>(&mut self, values: &mut [T]) {
298 let mut i = values.len();
300 // invariant: elements with index >= i have been locked in place.
302 // lock element i in place.
303 values.swap(i, self.gen_range(0u, i + 1u));
308 /// Iterator which will generate a stream of random items.
310 /// This iterator is created via the `gen_iter` method on `Rng`.
311 pub struct Generator<'a, T, R:'a> {
315 impl<'a, T: Rand, R: Rng> Iterator 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 for AsciiGenerator<'a, R> {
333 fn next(&mut self) -> Option<char> {
334 static GEN_ASCII_STR_CHARSET: &'static [u8] =
335 b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
336 abcdefghijklmnopqrstuvwxyz\
338 Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
342 /// A random number generator that can be explicitly seeded to produce
343 /// the same stream of randomness multiple times.
344 pub trait SeedableRng<Seed>: Rng {
345 /// Reseed an RNG with the given seed.
350 /// use std::rand::{Rng, SeedableRng, StdRng};
352 /// let seed: &[_] = &[1, 2, 3, 4];
353 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
354 /// println!("{}", rng.gen::<f64>());
355 /// rng.reseed(&[5, 6, 7, 8]);
356 /// println!("{}", rng.gen::<f64>());
358 fn reseed(&mut self, Seed);
360 /// Create a new RNG with the given seed.
365 /// use std::rand::{Rng, SeedableRng, StdRng};
367 /// let seed: &[_] = &[1, 2, 3, 4];
368 /// let mut rng: StdRng = SeedableRng::from_seed(seed);
369 /// println!("{}", rng.gen::<f64>());
371 fn from_seed(seed: Seed) -> Self;
374 /// An Xorshift[1] random number
377 /// The Xorshift algorithm is not suitable for cryptographic purposes
378 /// but is very fast. If you do not know for sure that it fits your
379 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
381 /// [1]: Marsaglia, George (July 2003). ["Xorshift
382 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
383 /// Statistical Software*. Vol. 8 (Issue 14).
384 #[allow(missing_copy_implementations)]
386 pub struct XorShiftRng {
394 /// Creates a new XorShiftRng instance which is not seeded.
396 /// The initial values of this RNG are constants, so all generators created
397 /// by this function will yield the same stream of random numbers. It is
398 /// highly recommended that this is created through `SeedableRng` instead of
400 pub fn new_unseeded() -> XorShiftRng {
410 impl Rng for XorShiftRng {
412 fn next_u32(&mut self) -> u32 {
414 let t = x ^ (x << 11);
419 self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
424 impl SeedableRng<[u32; 4]> for XorShiftRng {
425 /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
426 fn reseed(&mut self, seed: [u32; 4]) {
427 assert!(!seed.iter().all(|&x| x == 0),
428 "XorShiftRng.reseed called with an all zero seed.");
436 /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
437 fn from_seed(seed: [u32; 4]) -> XorShiftRng {
438 assert!(!seed.iter().all(|&x| x == 0),
439 "XorShiftRng::from_seed called with an all zero seed.");
450 impl Rand for XorShiftRng {
451 fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
452 let mut tuple: (u32, u32, u32, u32) = rng.gen();
453 while tuple == (0, 0, 0, 0) {
456 let (x, y, z, w) = tuple;
457 XorShiftRng { x: x, y: y, z: z, w: w }
461 /// A wrapper for generating floating point numbers uniformly in the
462 /// open interval `(0,1)` (not including either endpoint).
464 /// Use `Closed01` for the closed interval `[0,1]`, and the default
465 /// `Rand` implementation for `f32` and `f64` for the half-open
470 /// use std::rand::{random, Open01};
472 /// let Open01(val) = random::<Open01<f32>>();
473 /// println!("f32 from (0,1): {}", val);
475 pub struct Open01<F>(pub F);
477 /// A wrapper for generating floating point numbers uniformly in the
478 /// closed interval `[0,1]` (including both endpoints).
480 /// Use `Open01` for the closed interval `(0,1)`, and the default
481 /// `Rand` implementation of `f32` and `f64` for the half-open
487 /// use std::rand::{random, Closed01};
489 /// let Closed01(val) = random::<Closed01<f32>>();
490 /// println!("f32 from [0,1]: {}", val);
492 pub struct Closed01<F>(pub F);
496 pub use core::{option, fmt}; // panic!()
497 pub use core::clone; // derive Clone
498 pub use core::marker;
505 pub struct MyRng<R> { inner: R }
507 impl<R: rand::Rng> ::Rng for MyRng<R> {
508 fn next_u32(&mut self) -> u32 {
509 fn next<T: rand::Rng>(t: &mut T) -> u32 {
513 next(&mut self.inner)
517 pub fn rng() -> MyRng<rand::ThreadRng> {
518 MyRng { inner: rand::thread_rng() }
521 pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
522 MyRng { inner: rand::weak_rng() }