]> git.lizzy.rs Git - rust.git/blob - src/librand/lib.rs
7ade4ef1c4628e4c65ccca7f747ba8c42f14487d
[rust.git] / src / librand / lib.rs
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.
4 //
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.
10
11 //! Interface to random number generators in Rust.
12 //!
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`.
18
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/")]
27 #![no_std]
28 #![staged_api]
29 #![unstable(feature = "rand",
30             reason = "use `rand` from crates.io")]
31 #![feature(core)]
32 #![feature(no_std)]
33 #![feature(staged_api)]
34 #![feature(step_by)]
35
36 #![cfg_attr(test, feature(test, rand, rustc_private))]
37
38 #![allow(deprecated)]
39
40 #[macro_use]
41 extern crate core;
42
43 #[cfg(test)] #[macro_use] extern crate std;
44 #[cfg(test)] #[macro_use] extern crate log;
45
46 use core::prelude::*;
47 use core::marker::PhantomData;
48
49 pub use isaac::{IsaacRng, Isaac64Rng};
50 pub use chacha::ChaChaRng;
51
52 use distributions::{Range, IndependentSample};
53 use distributions::range::SampleRange;
54
55 #[cfg(test)]
56 const RAND_BENCH_N: u64 = 100;
57
58 pub mod distributions;
59 pub mod isaac;
60 pub mod chacha;
61 pub mod reseeding;
62 mod rand_impls;
63
64 /// A type that can be randomly generated using an `Rng`.
65 pub trait Rand : Sized {
66     /// Generates a random instance of this type using the specified source of
67     /// randomness.
68     fn rand<R: Rng>(rng: &mut R) -> Self;
69 }
70
71 /// A random number generator.
72 pub trait Rng : Sized {
73     /// Return the next random u32.
74     ///
75     /// This rarely needs to be called directly, prefer `r.gen()` to
76     /// `r.next_u32()`.
77     // FIXME #7771: Should be implemented in terms of next_u64
78     fn next_u32(&mut self) -> u32;
79
80     /// Return the next random u64.
81     ///
82     /// By default this is implemented in terms of `next_u32`. An
83     /// implementation of this trait must provide at least one of
84     /// these two methods. Similarly to `next_u32`, this rarely needs
85     /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
86     fn next_u64(&mut self) -> u64 {
87         ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
88     }
89
90     /// Return the next random f32 selected from the half-open
91     /// interval `[0, 1)`.
92     ///
93     /// By default this is implemented in terms of `next_u32`, but a
94     /// random number generator which can generate numbers satisfying
95     /// the requirements directly can overload this for performance.
96     /// It is required that the return value lies in `[0, 1)`.
97     ///
98     /// See `Closed01` for the closed interval `[0,1]`, and
99     /// `Open01` for the open interval `(0,1)`.
100     fn next_f32(&mut self) -> f32 {
101         const MANTISSA_BITS: usize = 24;
102         const IGNORED_BITS: usize = 8;
103         const SCALE: f32 = (1u64 << MANTISSA_BITS) as f32;
104
105         // using any more than `MANTISSA_BITS` bits will
106         // cause (e.g.) 0xffff_ffff to correspond to 1
107         // exactly, so we need to drop some (8 for f32, 11
108         // for f64) to guarantee the open end.
109         (self.next_u32() >> IGNORED_BITS) as f32 / SCALE
110     }
111
112     /// Return the next random f64 selected from the half-open
113     /// interval `[0, 1)`.
114     ///
115     /// By default this is implemented in terms of `next_u64`, but a
116     /// random number generator which can generate numbers satisfying
117     /// the requirements directly can overload this for performance.
118     /// It is required that the return value lies in `[0, 1)`.
119     ///
120     /// See `Closed01` for the closed interval `[0,1]`, and
121     /// `Open01` for the open interval `(0,1)`.
122     fn next_f64(&mut self) -> f64 {
123         const MANTISSA_BITS: usize = 53;
124         const IGNORED_BITS: usize = 11;
125         const SCALE: f64 = (1u64 << MANTISSA_BITS) as f64;
126
127         (self.next_u64() >> IGNORED_BITS) as f64 / SCALE
128     }
129
130     /// Fill `dest` with random data.
131     ///
132     /// This has a default implementation in terms of `next_u64` and
133     /// `next_u32`, but should be overridden by implementations that
134     /// offer a more efficient solution than just calling those
135     /// methods repeatedly.
136     ///
137     /// This method does *not* have a requirement to bear any fixed
138     /// relationship to the other methods, for example, it does *not*
139     /// have to result in the same output as progressively filling
140     /// `dest` with `self.gen::<u8>()`, and any such behaviour should
141     /// not be relied upon.
142     ///
143     /// This method should guarantee that `dest` is entirely filled
144     /// with new data, and may panic if this is impossible
145     /// (e.g. reading past the end of a file that is being used as the
146     /// source of randomness).
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.
154         let mut count = 0;
155         let mut num = 0;
156         for byte in dest {
157             if count == 0 {
158                 // we could micro-optimise here by generating a u32 if
159                 // we only need a few more bytes to fill the vector
160                 // (i.e. at most 4).
161                 num = self.next_u64();
162                 count = 8;
163             }
164
165             *byte = (num & 0xff) as u8;
166             num >>= 8;
167             count -= 1;
168         }
169     }
170
171     /// Return a random value of a `Rand` type.
172     #[inline(always)]
173     fn gen<T: Rand>(&mut self) -> T {
174         Rand::rand(self)
175     }
176
177     /// Return an iterator that will yield an infinite number of randomly
178     /// generated items.
179     fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
180         Generator { rng: self, _marker: PhantomData }
181     }
182
183     /// Generate a random value in the range [`low`, `high`).
184     ///
185     /// This is a convenience wrapper around
186     /// `distributions::Range`. If this function will be called
187     /// repeatedly with the same arguments, one should use `Range`, as
188     /// that will amortize the computations that allow for perfect
189     /// uniformity, as they only happen on initialization.
190     ///
191     /// # Panics
192     ///
193     /// Panics if `low >= high`.
194     fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
195         assert!(low < high, "Rng.gen_range called with low >= high");
196         Range::new(low, high).ind_sample(self)
197     }
198
199     /// Return a bool with a 1 in n chance of true
200     fn gen_weighted_bool(&mut self, n: usize) -> bool {
201         n <= 1 || self.gen_range(0, n) == 0
202     }
203
204     /// Return an iterator of random characters from the set A-Z,a-z,0-9.
205     fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
206         AsciiGenerator { rng: self }
207     }
208
209     /// Return a random element from `values`.
210     ///
211     /// Return `None` if `values` is empty.
212     fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
213         if values.is_empty() {
214             None
215         } else {
216             Some(&values[self.gen_range(0, values.len())])
217         }
218     }
219
220     /// Shuffle a mutable slice in place.
221     fn shuffle<T>(&mut self, values: &mut [T]) {
222         let mut i = values.len();
223         while i >= 2 {
224             // invariant: elements with index >= i have been locked in place.
225             i -= 1;
226             // lock element i in place.
227             values.swap(i, self.gen_range(0, i + 1));
228         }
229     }
230 }
231
232 /// Iterator which will generate a stream of random items.
233 ///
234 /// This iterator is created via the `gen_iter` method on `Rng`.
235 pub struct Generator<'a, T, R:'a> {
236     rng: &'a mut R,
237     _marker: PhantomData<T>
238 }
239
240 impl<'a, T: Rand, R: Rng> Iterator for Generator<'a, T, R> {
241     type Item = T;
242
243     fn next(&mut self) -> Option<T> {
244         Some(self.rng.gen())
245     }
246 }
247
248 /// Iterator which will continuously generate random ascii characters.
249 ///
250 /// This iterator is created via the `gen_ascii_chars` method on `Rng`.
251 pub struct AsciiGenerator<'a, R:'a> {
252     rng: &'a mut R,
253 }
254
255 impl<'a, R: Rng> Iterator for AsciiGenerator<'a, R> {
256     type Item = char;
257
258     fn next(&mut self) -> Option<char> {
259         const GEN_ASCII_STR_CHARSET: &'static [u8] =
260             b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
261               abcdefghijklmnopqrstuvwxyz\
262               0123456789";
263         Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
264     }
265 }
266
267 /// A random number generator that can be explicitly seeded to produce
268 /// the same stream of randomness multiple times.
269 pub trait SeedableRng<Seed>: Rng {
270     /// Reseed an RNG with the given seed.
271     fn reseed(&mut self, Seed);
272
273     /// Create a new RNG with the given seed.
274     fn from_seed(seed: Seed) -> Self;
275 }
276
277 /// An Xorshift[1] random number
278 /// generator.
279 ///
280 /// The Xorshift algorithm is not suitable for cryptographic purposes
281 /// but is very fast. If you do not know for sure that it fits your
282 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
283 ///
284 /// [1]: Marsaglia, George (July 2003). ["Xorshift
285 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
286 /// Statistical Software*. Vol. 8 (Issue 14).
287 #[derive(Clone)]
288 pub struct XorShiftRng {
289     x: u32,
290     y: u32,
291     z: u32,
292     w: u32,
293 }
294
295 impl XorShiftRng {
296     /// Creates a new XorShiftRng instance which is not seeded.
297     ///
298     /// The initial values of this RNG are constants, so all generators created
299     /// by this function will yield the same stream of random numbers. It is
300     /// highly recommended that this is created through `SeedableRng` instead of
301     /// this function
302     pub fn new_unseeded() -> XorShiftRng {
303         XorShiftRng {
304             x: 0x193a6754,
305             y: 0xa8a7d469,
306             z: 0x97830e05,
307             w: 0x113ba7bb,
308         }
309     }
310 }
311
312 impl Rng for XorShiftRng {
313     #[inline]
314     fn next_u32(&mut self) -> u32 {
315         let x = self.x;
316         let t = x ^ (x << 11);
317         self.x = self.y;
318         self.y = self.z;
319         self.z = self.w;
320         let w = self.w;
321         self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
322         self.w
323     }
324 }
325
326 impl SeedableRng<[u32; 4]> for XorShiftRng {
327     /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
328     fn reseed(&mut self, seed: [u32; 4]) {
329         assert!(!seed.iter().all(|&x| x == 0),
330                 "XorShiftRng.reseed called with an all zero seed.");
331
332         self.x = seed[0];
333         self.y = seed[1];
334         self.z = seed[2];
335         self.w = seed[3];
336     }
337
338     /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
339     fn from_seed(seed: [u32; 4]) -> XorShiftRng {
340         assert!(!seed.iter().all(|&x| x == 0),
341                 "XorShiftRng::from_seed called with an all zero seed.");
342
343         XorShiftRng {
344             x: seed[0],
345             y: seed[1],
346             z: seed[2],
347             w: seed[3]
348         }
349     }
350 }
351
352 impl Rand for XorShiftRng {
353     fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
354         let mut tuple: (u32, u32, u32, u32) = rng.gen();
355         while tuple == (0, 0, 0, 0) {
356             tuple = rng.gen();
357         }
358         let (x, y, z, w) = tuple;
359         XorShiftRng { x: x, y: y, z: z, w: w }
360     }
361 }
362
363 /// A wrapper for generating floating point numbers uniformly in the
364 /// open interval `(0,1)` (not including either endpoint).
365 ///
366 /// Use `Closed01` for the closed interval `[0,1]`, and the default
367 /// `Rand` implementation for `f32` and `f64` for the half-open
368 /// `[0,1)`.
369 pub struct Open01<F>(pub F);
370
371 /// A wrapper for generating floating point numbers uniformly in the
372 /// closed interval `[0,1]` (including both endpoints).
373 ///
374 /// Use `Open01` for the closed interval `(0,1)`, and the default
375 /// `Rand` implementation of `f32` and `f64` for the half-open
376 /// `[0,1)`.
377 pub struct Closed01<F>(pub F);
378
379 #[cfg(test)]
380 mod test {
381     use std::__rand as rand;
382
383     pub struct MyRng<R> { inner: R }
384
385     impl<R: rand::Rng> ::Rng for MyRng<R> {
386         fn next_u32(&mut self) -> u32 {
387             rand::Rng::next_u32(&mut self.inner)
388         }
389     }
390
391     pub fn rng() -> MyRng<rand::ThreadRng> {
392         MyRng { inner: rand::thread_rng() }
393     }
394
395     pub fn weak_rng() -> MyRng<rand::ThreadRng> {
396         MyRng { inner: rand::thread_rng() }
397     }
398 }