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`.
70 pub trait Rand
: Sized
{
71 /// Generates a random instance of this type using the specified source of
73 fn rand
<R
: Rng
>(rng
: &mut R
) -> Self;
76 /// A random number generator.
77 pub trait Rng
: Sized
{
78 /// Return the next random u32.
80 /// This rarely needs to be called directly, prefer `r.gen()` to
82 // FIXME #7771: Should be implemented in terms of next_u64
83 fn next_u32(&mut self) -> u32;
85 /// Return the next random u64.
87 /// By default this is implemented in terms of `next_u32`. An
88 /// implementation of this trait must provide at least one of
89 /// these two methods. Similarly to `next_u32`, this rarely needs
90 /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
91 fn next_u64(&mut self) -> u64 {
92 ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
95 /// Return the next random f32 selected from the half-open
96 /// interval `[0, 1)`.
98 /// By default this is implemented in terms of `next_u32`, but a
99 /// random number generator which can generate numbers satisfying
100 /// the requirements directly can overload this for performance.
101 /// It is required that the return value lies in `[0, 1)`.
103 /// See `Closed01` for the closed interval `[0,1]`, and
104 /// `Open01` for the open interval `(0,1)`.
105 fn next_f32(&mut self) -> f32 {
106 const MANTISSA_BITS
: usize = 24;
107 const IGNORED_BITS
: usize = 8;
108 const SCALE
: f32 = (1u64 << MANTISSA_BITS
) as f32;
110 // using any more than `MANTISSA_BITS` bits will
111 // cause (e.g.) 0xffff_ffff to correspond to 1
112 // exactly, so we need to drop some (8 for f32, 11
113 // for f64) to guarantee the open end.
114 (self.next_u32() >> IGNORED_BITS
) as f32 / SCALE
117 /// Return the next random f64 selected from the half-open
118 /// interval `[0, 1)`.
120 /// By default this is implemented in terms of `next_u64`, but a
121 /// random number generator which can generate numbers satisfying
122 /// the requirements directly can overload this for performance.
123 /// It is required that the return value lies in `[0, 1)`.
125 /// See `Closed01` for the closed interval `[0,1]`, and
126 /// `Open01` for the open interval `(0,1)`.
127 fn next_f64(&mut self) -> f64 {
128 const MANTISSA_BITS
: usize = 53;
129 const IGNORED_BITS
: usize = 11;
130 const SCALE
: f64 = (1u64 << MANTISSA_BITS
) as f64;
132 (self.next_u64() >> IGNORED_BITS
) as f64 / SCALE
135 /// Fill `dest` with random data.
137 /// This has a default implementation in terms of `next_u64` and
138 /// `next_u32`, but should be overridden by implementations that
139 /// offer a more efficient solution than just calling those
140 /// methods repeatedly.
142 /// This method does *not* have a requirement to bear any fixed
143 /// relationship to the other methods, for example, it does *not*
144 /// have to result in the same output as progressively filling
145 /// `dest` with `self.gen::<u8>()`, and any such behaviour should
146 /// not be relied upon.
148 /// This method should guarantee that `dest` is entirely filled
149 /// with new data, and may panic if this is impossible
150 /// (e.g. reading past the end of a file that is being used as the
151 /// source of randomness).
152 fn fill_bytes(&mut self, dest
: &mut [u8]) {
153 // this could, in theory, be done by transmuting dest to a
154 // [u64], but this is (1) likely to be undefined behaviour for
155 // LLVM, (2) has to be very careful about alignment concerns,
156 // (3) adds more `unsafe` that needs to be checked, (4)
157 // probably doesn't give much performance gain if
158 // optimisations are on.
163 // we could micro-optimise here by generating a u32 if
164 // we only need a few more bytes to fill the vector
166 num
= self.next_u64();
170 *byte
= (num
& 0xff) as u8;
176 /// Return a random value of a `Rand` type.
178 fn gen
<T
: Rand
>(&mut self) -> T
{
182 /// Return an iterator that will yield an infinite number of randomly
184 fn gen_iter
<'a
, T
: Rand
>(&'a
mut self) -> Generator
<'a
, T
, Self> {
185 Generator { rng: self, _marker: PhantomData }
188 /// Generate a random value in the range [`low`, `high`).
190 /// This is a convenience wrapper around
191 /// `distributions::Range`. If this function will be called
192 /// repeatedly with the same arguments, one should use `Range`, as
193 /// that will amortize the computations that allow for perfect
194 /// uniformity, as they only happen on initialization.
198 /// Panics if `low >= high`.
199 fn gen_range
<T
: PartialOrd
+ SampleRange
>(&mut self, low
: T
, high
: T
) -> T
{
200 assert
!(low
< high
, "Rng.gen_range called with low >= high");
201 Range
::new(low
, high
).ind_sample(self)
204 /// Return a bool with a 1 in n chance of true
205 fn gen_weighted_bool(&mut self, n
: usize) -> bool
{
206 n
<= 1 || self.gen_range(0, n
) == 0
209 /// Return an iterator of random characters from the set A-Z,a-z,0-9.
210 fn gen_ascii_chars
<'a
>(&'a
mut self) -> AsciiGenerator
<'a
, Self> {
211 AsciiGenerator { rng: self }
214 /// Return a random element from `values`.
216 /// Return `None` if `values` is empty.
217 fn choose
<'a
, T
>(&mut self, values
: &'a
[T
]) -> Option
<&'a T
> {
218 if values
.is_empty() {
221 Some(&values
[self.gen_range(0, values
.len())])
225 /// Shuffle a mutable slice in place.
226 fn shuffle
<T
>(&mut self, values
: &mut [T
]) {
227 let mut i
= values
.len();
229 // invariant: elements with index >= i have been locked in place.
231 // lock element i in place.
232 values
.swap(i
, self.gen_range(0, i
+ 1));
237 /// Iterator which will generate a stream of random items.
239 /// This iterator is created via the `gen_iter` method on `Rng`.
240 pub struct Generator
<'a
, T
, R
:'a
> {
242 _marker
: PhantomData
<T
>
245 impl<'a
, T
: Rand
, R
: Rng
> Iterator
for Generator
<'a
, T
, R
> {
248 fn next(&mut self) -> Option
<T
> {
253 /// Iterator which will continuously generate random ascii characters.
255 /// This iterator is created via the `gen_ascii_chars` method on `Rng`.
256 pub struct AsciiGenerator
<'a
, R
:'a
> {
260 impl<'a
, R
: Rng
> Iterator
for AsciiGenerator
<'a
, R
> {
263 fn next(&mut self) -> Option
<char> {
264 const GEN_ASCII_STR_CHARSET
: &'
static [u8] =
265 b
"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
266 abcdefghijklmnopqrstuvwxyz\
268 Some(*self.rng
.choose(GEN_ASCII_STR_CHARSET
).unwrap() as char)
272 /// A random number generator that can be explicitly seeded to produce
273 /// the same stream of randomness multiple times.
274 pub trait SeedableRng
<Seed
>: Rng
{
275 /// Reseed an RNG with the given seed.
276 fn reseed(&mut self, Seed
);
278 /// Create a new RNG with the given seed.
279 fn from_seed(seed
: Seed
) -> Self;
282 /// An Xorshift[1] random number
285 /// The Xorshift algorithm is not suitable for cryptographic purposes
286 /// but is very fast. If you do not know for sure that it fits your
287 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
289 /// [1]: Marsaglia, George (July 2003). ["Xorshift
290 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
291 /// Statistical Software*. Vol. 8 (Issue 14).
293 pub struct XorShiftRng
{
301 /// Creates a new XorShiftRng instance which is not seeded.
303 /// The initial values of this RNG are constants, so all generators created
304 /// by this function will yield the same stream of random numbers. It is
305 /// highly recommended that this is created through `SeedableRng` instead of
307 pub fn new_unseeded() -> XorShiftRng
{
317 impl Rng
for XorShiftRng
{
319 fn next_u32(&mut self) -> u32 {
321 let t
= x ^
(x
<< 11);
326 self.w
= w ^
(w
>> 19) ^
(t ^
(t
>> 8));
331 impl SeedableRng
<[u32; 4]> for XorShiftRng
{
332 /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
333 fn reseed(&mut self, seed
: [u32; 4]) {
334 assert
!(!seed
.iter().all(|&x
| x
== 0),
335 "XorShiftRng.reseed called with an all zero seed.");
343 /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
344 fn from_seed(seed
: [u32; 4]) -> XorShiftRng
{
345 assert
!(!seed
.iter().all(|&x
| x
== 0),
346 "XorShiftRng::from_seed called with an all zero seed.");
357 impl Rand
for XorShiftRng
{
358 fn rand
<R
: Rng
>(rng
: &mut R
) -> XorShiftRng
{
359 let mut tuple
: (u32, u32, u32, u32) = rng
.gen();
360 while tuple
== (0, 0, 0, 0) {
363 let (x
, y
, z
, w
) = tuple
;
364 XorShiftRng { x: x, y: y, z: z, w: w }
368 /// A wrapper for generating floating point numbers uniformly in the
369 /// open interval `(0,1)` (not including either endpoint).
371 /// Use `Closed01` for the closed interval `[0,1]`, and the default
372 /// `Rand` implementation for `f32` and `f64` for the half-open
374 pub struct Open01
<F
>(pub F
);
376 /// A wrapper for generating floating point numbers uniformly in the
377 /// closed interval `[0,1]` (including both endpoints).
379 /// Use `Open01` for the closed interval `(0,1)`, and the default
380 /// `Rand` implementation of `f32` and `f64` for the half-open
382 pub struct Closed01
<F
>(pub F
);
386 use std
::__rand
as rand
;
388 pub struct MyRng
<R
> { inner: R }
390 impl<R
: rand
::Rng
> ::Rng
for MyRng
<R
> {
391 fn next_u32(&mut self) -> u32 {
392 rand
::Rng
::next_u32(&mut self.inner
)
396 pub fn rng() -> MyRng
<rand
::ThreadRng
> {
397 MyRng { inner: rand::thread_rng() }
400 pub fn weak_rng() -> MyRng
<rand
::ThreadRng
> {
401 MyRng { inner: rand::thread_rng() }