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