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