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