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 // Do not remove on snapshot creation. Needed for bootstrap. (Issue #22364)
20 #![cfg_attr(stage0, feature(custom_attribute))]
21 #![crate_name = "rand"]
22 #![crate_type = "rlib"]
23 #![doc(html_logo_url = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
24 html_favicon_url
= "https://doc.rust-lang.org/favicon.ico",
25 html_root_url
= "http://doc.rust-lang.org/nightly/",
26 html_playground_url
= "http://play.rust-lang.org/")]
29 #![unstable(feature = "rand",
30 reason
= "use `rand` from crates.io")]
32 #![feature(core_float)]
33 #![feature(core_prelude)]
34 #![feature(core_slice_ext)]
36 #![feature(num_bits_bytes)]
37 #![feature(staged_api)]
40 #![cfg_attr(test, feature(test, rand, rustc_private, iter_order))]
47 #[cfg(test)] #[macro_use] extern crate std;
48 #[cfg(test)] #[macro_use] extern crate log;
51 use core
::marker
::PhantomData
;
53 pub use isaac
::{IsaacRng, Isaac64Rng}
;
54 pub use chacha
::ChaChaRng
;
56 use distributions
::{Range, IndependentSample}
;
57 use distributions
::range
::SampleRange
;
60 const RAND_BENCH_N
: u64 = 100;
62 pub mod distributions
;
68 /// A type that can be randomly generated using an `Rng`.
69 pub trait Rand
: Sized
{
70 /// Generates a random instance of this type using the specified source of
72 fn rand
<R
: Rng
>(rng
: &mut R
) -> Self;
75 /// A random number generator.
76 pub trait Rng
: Sized
{
77 /// Return the next random u32.
79 /// This rarely needs to be called directly, prefer `r.gen()` to
81 // FIXME #7771: Should be implemented in terms of next_u64
82 fn next_u32(&mut self) -> u32;
84 /// Return the next random u64.
86 /// By default this is implemented in terms of `next_u32`. An
87 /// implementation of this trait must provide at least one of
88 /// these two methods. Similarly to `next_u32`, this rarely needs
89 /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
90 fn next_u64(&mut self) -> u64 {
91 ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
94 /// Return the next random f32 selected from the half-open
95 /// interval `[0, 1)`.
97 /// By default this is implemented in terms of `next_u32`, but a
98 /// random number generator which can generate numbers satisfying
99 /// the requirements directly can overload this for performance.
100 /// It is required that the return value lies in `[0, 1)`.
102 /// See `Closed01` for the closed interval `[0,1]`, and
103 /// `Open01` for the open interval `(0,1)`.
104 fn next_f32(&mut self) -> f32 {
105 const MANTISSA_BITS
: usize = 24;
106 const IGNORED_BITS
: usize = 8;
107 const SCALE
: f32 = (1u64 << MANTISSA_BITS
) as f32;
109 // using any more than `MANTISSA_BITS` bits will
110 // cause (e.g.) 0xffff_ffff to correspond to 1
111 // exactly, so we need to drop some (8 for f32, 11
112 // for f64) to guarantee the open end.
113 (self.next_u32() >> IGNORED_BITS
) as f32 / SCALE
116 /// Return the next random f64 selected from the half-open
117 /// interval `[0, 1)`.
119 /// By default this is implemented in terms of `next_u64`, but a
120 /// random number generator which can generate numbers satisfying
121 /// the requirements directly can overload this for performance.
122 /// It is required that the return value lies in `[0, 1)`.
124 /// See `Closed01` for the closed interval `[0,1]`, and
125 /// `Open01` for the open interval `(0,1)`.
126 fn next_f64(&mut self) -> f64 {
127 const MANTISSA_BITS
: usize = 53;
128 const IGNORED_BITS
: usize = 11;
129 const SCALE
: f64 = (1u64 << MANTISSA_BITS
) as f64;
131 (self.next_u64() >> IGNORED_BITS
) as f64 / SCALE
134 /// Fill `dest` with random data.
136 /// This has a default implementation in terms of `next_u64` and
137 /// `next_u32`, but should be overridden by implementations that
138 /// offer a more efficient solution than just calling those
139 /// methods repeatedly.
141 /// This method does *not* have a requirement to bear any fixed
142 /// relationship to the other methods, for example, it does *not*
143 /// have to result in the same output as progressively filling
144 /// `dest` with `self.gen::<u8>()`, and any such behaviour should
145 /// not be relied upon.
147 /// This method should guarantee that `dest` is entirely filled
148 /// with new data, and may panic if this is impossible
149 /// (e.g. reading past the end of a file that is being used as the
150 /// source of randomness).
151 fn fill_bytes(&mut self, dest
: &mut [u8]) {
152 // this could, in theory, be done by transmuting dest to a
153 // [u64], but this is (1) likely to be undefined behaviour for
154 // LLVM, (2) has to be very careful about alignment concerns,
155 // (3) adds more `unsafe` that needs to be checked, (4)
156 // probably doesn't give much performance gain if
157 // optimisations are on.
162 // we could micro-optimise here by generating a u32 if
163 // we only need a few more bytes to fill the vector
165 num
= self.next_u64();
169 *byte
= (num
& 0xff) as u8;
175 /// Return a random value of a `Rand` type.
177 fn gen
<T
: Rand
>(&mut self) -> T
{
181 /// Return an iterator that will yield an infinite number of randomly
183 fn gen_iter
<'a
, T
: Rand
>(&'a
mut self) -> Generator
<'a
, T
, Self> {
184 Generator { rng: self, _marker: PhantomData }
187 /// Generate a random value in the range [`low`, `high`).
189 /// This is a convenience wrapper around
190 /// `distributions::Range`. If this function will be called
191 /// repeatedly with the same arguments, one should use `Range`, as
192 /// that will amortize the computations that allow for perfect
193 /// uniformity, as they only happen on initialization.
197 /// Panics if `low >= high`.
198 fn gen_range
<T
: PartialOrd
+ SampleRange
>(&mut self, low
: T
, high
: T
) -> T
{
199 assert
!(low
< high
, "Rng.gen_range called with low >= high");
200 Range
::new(low
, high
).ind_sample(self)
203 /// Return a bool with a 1 in n chance of true
204 fn gen_weighted_bool(&mut self, n
: usize) -> bool
{
205 n
<= 1 || self.gen_range(0, n
) == 0
208 /// Return an iterator of random characters from the set A-Z,a-z,0-9.
209 fn gen_ascii_chars
<'a
>(&'a
mut self) -> AsciiGenerator
<'a
, Self> {
210 AsciiGenerator { rng: self }
213 /// Return a random element from `values`.
215 /// Return `None` if `values` is empty.
216 fn choose
<'a
, T
>(&mut self, values
: &'a
[T
]) -> Option
<&'a T
> {
217 if values
.is_empty() {
220 Some(&values
[self.gen_range(0, values
.len())])
224 /// Shuffle a mutable slice in place.
225 fn shuffle
<T
>(&mut self, values
: &mut [T
]) {
226 let mut i
= values
.len();
228 // invariant: elements with index >= i have been locked in place.
230 // lock element i in place.
231 values
.swap(i
, self.gen_range(0, i
+ 1));
236 /// Iterator which will generate a stream of random items.
238 /// This iterator is created via the `gen_iter` method on `Rng`.
239 pub struct Generator
<'a
, T
, R
:'a
> {
241 _marker
: PhantomData
<T
>
244 impl<'a
, T
: Rand
, R
: Rng
> Iterator
for Generator
<'a
, T
, R
> {
247 fn next(&mut self) -> Option
<T
> {
252 /// Iterator which will continuously generate random ascii characters.
254 /// This iterator is created via the `gen_ascii_chars` method on `Rng`.
255 pub struct AsciiGenerator
<'a
, R
:'a
> {
259 impl<'a
, R
: Rng
> Iterator
for AsciiGenerator
<'a
, R
> {
262 fn next(&mut self) -> Option
<char> {
263 const GEN_ASCII_STR_CHARSET
: &'
static [u8] =
264 b
"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
265 abcdefghijklmnopqrstuvwxyz\
267 Some(*self.rng
.choose(GEN_ASCII_STR_CHARSET
).unwrap() as char)
271 /// A random number generator that can be explicitly seeded to produce
272 /// the same stream of randomness multiple times.
273 pub trait SeedableRng
<Seed
>: Rng
{
274 /// Reseed an RNG with the given seed.
275 fn reseed(&mut self, Seed
);
277 /// Create a new RNG with the given seed.
278 fn from_seed(seed
: Seed
) -> Self;
281 /// An Xorshift[1] random number
284 /// The Xorshift algorithm is not suitable for cryptographic purposes
285 /// but is very fast. If you do not know for sure that it fits your
286 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
288 /// [1]: Marsaglia, George (July 2003). ["Xorshift
289 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
290 /// Statistical Software*. Vol. 8 (Issue 14).
292 pub struct XorShiftRng
{
300 /// Creates a new XorShiftRng instance which is not seeded.
302 /// The initial values of this RNG are constants, so all generators created
303 /// by this function will yield the same stream of random numbers. It is
304 /// highly recommended that this is created through `SeedableRng` instead of
306 pub fn new_unseeded() -> XorShiftRng
{
316 impl Rng
for XorShiftRng
{
318 fn next_u32(&mut self) -> u32 {
320 let t
= x ^
(x
<< 11);
325 self.w
= w ^
(w
>> 19) ^
(t ^
(t
>> 8));
330 impl SeedableRng
<[u32; 4]> for XorShiftRng
{
331 /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
332 fn reseed(&mut self, seed
: [u32; 4]) {
333 assert
!(!seed
.iter().all(|&x
| x
== 0),
334 "XorShiftRng.reseed called with an all zero seed.");
342 /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
343 fn from_seed(seed
: [u32; 4]) -> XorShiftRng
{
344 assert
!(!seed
.iter().all(|&x
| x
== 0),
345 "XorShiftRng::from_seed called with an all zero seed.");
356 impl Rand
for XorShiftRng
{
357 fn rand
<R
: Rng
>(rng
: &mut R
) -> XorShiftRng
{
358 let mut tuple
: (u32, u32, u32, u32) = rng
.gen();
359 while tuple
== (0, 0, 0, 0) {
362 let (x
, y
, z
, w
) = tuple
;
363 XorShiftRng { x: x, y: y, z: z, w: w }
367 /// A wrapper for generating floating point numbers uniformly in the
368 /// open interval `(0,1)` (not including either endpoint).
370 /// Use `Closed01` for the closed interval `[0,1]`, and the default
371 /// `Rand` implementation for `f32` and `f64` for the half-open
373 pub struct Open01
<F
>(pub F
);
375 /// A wrapper for generating floating point numbers uniformly in the
376 /// closed interval `[0,1]` (including both endpoints).
378 /// Use `Open01` for the closed interval `(0,1)`, and the default
379 /// `Rand` implementation of `f32` and `f64` for the half-open
381 pub struct Closed01
<F
>(pub F
);
385 use std
::__rand
as rand
;
387 pub struct MyRng
<R
> { inner: R }
389 impl<R
: rand
::Rng
> ::Rng
for MyRng
<R
> {
390 fn next_u32(&mut self) -> u32 {
391 rand
::Rng
::next_u32(&mut self.inner
)
395 pub fn rng() -> MyRng
<rand
::ThreadRng
> {
396 MyRng { inner: rand::thread_rng() }
399 pub fn weak_rng() -> MyRng
<rand
::ThreadRng
> {
400 MyRng { inner: rand::thread_rng() }