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