]> git.lizzy.rs Git - rust.git/blob - src/librand/lib.rs
Rewrite Condvar::wait_timeout and make it public
[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 = "http://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
22        html_favicon_url = "http://www.rust-lang.org/favicon.ico",
23        html_root_url = "http://doc.rust-lang.org/nightly/",
24        html_playground_url = "http://play.rust-lang.org/")]
25 #![allow(unknown_features)] #![feature(int_uint)]
26 #![no_std]
27 #![unstable]
28 #![staged_api]
29
30 #[macro_use]
31 extern crate core;
32
33 #[cfg(test)] #[macro_use] extern crate std;
34 #[cfg(test)] #[macro_use] extern crate log;
35
36 use core::prelude::*;
37
38 pub use isaac::{IsaacRng, Isaac64Rng};
39 pub use chacha::ChaChaRng;
40
41 use distributions::{Range, IndependentSample};
42 use distributions::range::SampleRange;
43
44 #[cfg(test)]
45 static RAND_BENCH_N: u64 = 100;
46
47 pub mod distributions;
48 pub mod isaac;
49 pub mod chacha;
50 pub mod reseeding;
51 mod rand_impls;
52
53 /// A type that can be randomly generated using an `Rng`.
54 pub trait Rand : Sized {
55     /// Generates a random instance of this type using the specified source of
56     /// randomness.
57     fn rand<R: Rng>(rng: &mut R) -> Self;
58 }
59
60 /// A random number generator.
61 pub trait Rng : Sized {
62     /// Return the next random u32.
63     ///
64     /// This rarely needs to be called directly, prefer `r.gen()` to
65     /// `r.next_u32()`.
66     // FIXME #7771: Should be implemented in terms of next_u64
67     fn next_u32(&mut self) -> u32;
68
69     /// Return the next random u64.
70     ///
71     /// By default this is implemented in terms of `next_u32`. An
72     /// implementation of this trait must provide at least one of
73     /// these two methods. Similarly to `next_u32`, this rarely needs
74     /// to be called directly, prefer `r.gen()` to `r.next_u64()`.
75     fn next_u64(&mut self) -> u64 {
76         ((self.next_u32() as u64) << 32) | (self.next_u32() as u64)
77     }
78
79     /// Return the next random f32 selected from the half-open
80     /// interval `[0, 1)`.
81     ///
82     /// By default this is implemented in terms of `next_u32`, but a
83     /// random number generator which can generate numbers satisfying
84     /// the requirements directly can overload this for performance.
85     /// It is required that the return value lies in `[0, 1)`.
86     ///
87     /// See `Closed01` for the closed interval `[0,1]`, and
88     /// `Open01` for the open interval `(0,1)`.
89     fn next_f32(&mut self) -> f32 {
90         const MANTISSA_BITS: uint = 24;
91         const IGNORED_BITS: uint = 8;
92         const SCALE: f32 = (1u64 << MANTISSA_BITS) as f32;
93
94         // using any more than `MANTISSA_BITS` bits will
95         // cause (e.g.) 0xffff_ffff to correspond to 1
96         // exactly, so we need to drop some (8 for f32, 11
97         // for f64) to guarantee the open end.
98         (self.next_u32() >> IGNORED_BITS) as f32 / SCALE
99     }
100
101     /// Return the next random f64 selected from the half-open
102     /// interval `[0, 1)`.
103     ///
104     /// By default this is implemented in terms of `next_u64`, but a
105     /// random number generator which can generate numbers satisfying
106     /// the requirements directly can overload this for performance.
107     /// It is required that the return value lies in `[0, 1)`.
108     ///
109     /// See `Closed01` for the closed interval `[0,1]`, and
110     /// `Open01` for the open interval `(0,1)`.
111     fn next_f64(&mut self) -> f64 {
112         const MANTISSA_BITS: uint = 53;
113         const IGNORED_BITS: uint = 11;
114         const SCALE: f64 = (1u64 << MANTISSA_BITS) as f64;
115
116         (self.next_u64() >> IGNORED_BITS) as f64 / SCALE
117     }
118
119     /// Fill `dest` with random data.
120     ///
121     /// This has a default implementation in terms of `next_u64` and
122     /// `next_u32`, but should be overridden by implementations that
123     /// offer a more efficient solution than just calling those
124     /// methods repeatedly.
125     ///
126     /// This method does *not* have a requirement to bear any fixed
127     /// relationship to the other methods, for example, it does *not*
128     /// have to result in the same output as progressively filling
129     /// `dest` with `self.gen::<u8>()`, and any such behaviour should
130     /// not be relied upon.
131     ///
132     /// This method should guarantee that `dest` is entirely filled
133     /// with new data, and may panic if this is impossible
134     /// (e.g. reading past the end of a file that is being used as the
135     /// source of randomness).
136     ///
137     /// # Example
138     ///
139     /// ```rust
140     /// use std::rand::{thread_rng, Rng};
141     ///
142     /// let mut v = [0u8; 13579];
143     /// thread_rng().fill_bytes(&mut v);
144     /// println!("{:?}", v.as_slice());
145     /// ```
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 = 0i;
154         let mut num = 0;
155         for byte in dest.iter_mut() {
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     ///
172     /// # Example
173     ///
174     /// ```rust
175     /// use std::rand::{thread_rng, Rng};
176     ///
177     /// let mut rng = thread_rng();
178     /// let x: uint = rng.gen();
179     /// println!("{}", x);
180     /// println!("{:?}", rng.gen::<(f64, bool)>());
181     /// ```
182     #[inline(always)]
183     fn gen<T: Rand>(&mut self) -> T {
184         Rand::rand(self)
185     }
186
187     /// Return an iterator that will yield an infinite number of randomly
188     /// generated items.
189     ///
190     /// # Example
191     ///
192     /// ```
193     /// use std::rand::{thread_rng, Rng};
194     ///
195     /// let mut rng = thread_rng();
196     /// let x = rng.gen_iter::<uint>().take(10).collect::<Vec<uint>>();
197     /// println!("{:?}", x);
198     /// println!("{:?}", rng.gen_iter::<(f64, bool)>().take(5)
199     ///                     .collect::<Vec<(f64, bool)>>());
200     /// ```
201     fn gen_iter<'a, T: Rand>(&'a mut self) -> Generator<'a, T, Self> {
202         Generator { rng: self }
203     }
204
205     /// Generate a random value in the range [`low`, `high`).
206     ///
207     /// This is a convenience wrapper around
208     /// `distributions::Range`. If this function will be called
209     /// repeatedly with the same arguments, one should use `Range`, as
210     /// that will amortize the computations that allow for perfect
211     /// uniformity, as they only happen on initialization.
212     ///
213     /// # Panics
214     ///
215     /// Panics if `low >= high`.
216     ///
217     /// # Example
218     ///
219     /// ```rust
220     /// use std::rand::{thread_rng, Rng};
221     ///
222     /// let mut rng = thread_rng();
223     /// let n: uint = rng.gen_range(0u, 10);
224     /// println!("{}", n);
225     /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
226     /// println!("{}", m);
227     /// ```
228     fn gen_range<T: PartialOrd + SampleRange>(&mut self, low: T, high: T) -> T {
229         assert!(low < high, "Rng.gen_range called with low >= high");
230         Range::new(low, high).ind_sample(self)
231     }
232
233     /// Return a bool with a 1 in n chance of true
234     ///
235     /// # Example
236     ///
237     /// ```rust
238     /// use std::rand::{thread_rng, Rng};
239     ///
240     /// let mut rng = thread_rng();
241     /// println!("{}", rng.gen_weighted_bool(3));
242     /// ```
243     fn gen_weighted_bool(&mut self, n: uint) -> bool {
244         n <= 1 || self.gen_range(0, n) == 0
245     }
246
247     /// Return an iterator of random characters from the set A-Z,a-z,0-9.
248     ///
249     /// # Example
250     ///
251     /// ```rust
252     /// use std::rand::{thread_rng, Rng};
253     ///
254     /// let s: String = thread_rng().gen_ascii_chars().take(10).collect();
255     /// println!("{}", s);
256     /// ```
257     fn gen_ascii_chars<'a>(&'a mut self) -> AsciiGenerator<'a, Self> {
258         AsciiGenerator { rng: self }
259     }
260
261     /// Return a random element from `values`.
262     ///
263     /// Return `None` if `values` is empty.
264     ///
265     /// # Example
266     ///
267     /// ```
268     /// use std::rand::{thread_rng, Rng};
269     ///
270     /// let choices = [1i, 2, 4, 8, 16, 32];
271     /// let mut rng = thread_rng();
272     /// println!("{:?}", rng.choose(&choices));
273     /// # // uncomment when slicing syntax is stable
274     /// //assert_eq!(rng.choose(&choices[0..0]), None);
275     /// ```
276     fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
277         if values.is_empty() {
278             None
279         } else {
280             Some(&values[self.gen_range(0u, values.len())])
281         }
282     }
283
284     /// Shuffle a mutable slice in place.
285     ///
286     /// # Example
287     ///
288     /// ```rust
289     /// use std::rand::{thread_rng, Rng};
290     ///
291     /// let mut rng = thread_rng();
292     /// let mut y = [1i, 2, 3];
293     /// rng.shuffle(&mut y);
294     /// println!("{:?}", y.as_slice());
295     /// rng.shuffle(&mut y);
296     /// println!("{:?}", y.as_slice());
297     /// ```
298     fn shuffle<T>(&mut self, values: &mut [T]) {
299         let mut i = values.len();
300         while i >= 2u {
301             // invariant: elements with index >= i have been locked in place.
302             i -= 1u;
303             // lock element i in place.
304             values.swap(i, self.gen_range(0u, i + 1u));
305         }
306     }
307 }
308
309 /// Iterator which will generate a stream of random items.
310 ///
311 /// This iterator is created via the `gen_iter` method on `Rng`.
312 pub struct Generator<'a, T, R:'a> {
313     rng: &'a mut R,
314 }
315
316 impl<'a, T: Rand, R: Rng> Iterator for Generator<'a, T, R> {
317     type Item = T;
318
319     fn next(&mut self) -> Option<T> {
320         Some(self.rng.gen())
321     }
322 }
323
324 /// Iterator which will continuously generate random ascii characters.
325 ///
326 /// This iterator is created via the `gen_ascii_chars` method on `Rng`.
327 pub struct AsciiGenerator<'a, R:'a> {
328     rng: &'a mut R,
329 }
330
331 impl<'a, R: Rng> Iterator for AsciiGenerator<'a, R> {
332     type Item = char;
333
334     fn next(&mut self) -> Option<char> {
335         static GEN_ASCII_STR_CHARSET: &'static [u8] =
336             b"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
337               abcdefghijklmnopqrstuvwxyz\
338               0123456789";
339         Some(*self.rng.choose(GEN_ASCII_STR_CHARSET).unwrap() as char)
340     }
341 }
342
343 /// A random number generator that can be explicitly seeded to produce
344 /// the same stream of randomness multiple times.
345 pub trait SeedableRng<Seed>: Rng {
346     /// Reseed an RNG with the given seed.
347     ///
348     /// # Example
349     ///
350     /// ```rust
351     /// use std::rand::{Rng, SeedableRng, StdRng};
352     ///
353     /// let seed: &[_] = &[1, 2, 3, 4];
354     /// let mut rng: StdRng = SeedableRng::from_seed(seed);
355     /// println!("{}", rng.gen::<f64>());
356     /// rng.reseed(&[5, 6, 7, 8]);
357     /// println!("{}", rng.gen::<f64>());
358     /// ```
359     fn reseed(&mut self, Seed);
360
361     /// Create a new RNG with the given seed.
362     ///
363     /// # Example
364     ///
365     /// ```rust
366     /// use std::rand::{Rng, SeedableRng, StdRng};
367     ///
368     /// let seed: &[_] = &[1, 2, 3, 4];
369     /// let mut rng: StdRng = SeedableRng::from_seed(seed);
370     /// println!("{}", rng.gen::<f64>());
371     /// ```
372     fn from_seed(seed: Seed) -> Self;
373 }
374
375 /// An Xorshift[1] random number
376 /// generator.
377 ///
378 /// The Xorshift algorithm is not suitable for cryptographic purposes
379 /// but is very fast. If you do not know for sure that it fits your
380 /// requirements, use a more secure one such as `IsaacRng` or `OsRng`.
381 ///
382 /// [1]: Marsaglia, George (July 2003). ["Xorshift
383 /// RNGs"](http://www.jstatsoft.org/v08/i14/paper). *Journal of
384 /// Statistical Software*. Vol. 8 (Issue 14).
385 #[allow(missing_copy_implementations)]
386 #[derive(Clone)]
387 pub struct XorShiftRng {
388     x: u32,
389     y: u32,
390     z: u32,
391     w: u32,
392 }
393
394 impl XorShiftRng {
395     /// Creates a new XorShiftRng instance which is not seeded.
396     ///
397     /// The initial values of this RNG are constants, so all generators created
398     /// by this function will yield the same stream of random numbers. It is
399     /// highly recommended that this is created through `SeedableRng` instead of
400     /// this function
401     pub fn new_unseeded() -> XorShiftRng {
402         XorShiftRng {
403             x: 0x193a6754,
404             y: 0xa8a7d469,
405             z: 0x97830e05,
406             w: 0x113ba7bb,
407         }
408     }
409 }
410
411 impl Rng for XorShiftRng {
412     #[inline]
413     fn next_u32(&mut self) -> u32 {
414         let x = self.x;
415         let t = x ^ (x << 11);
416         self.x = self.y;
417         self.y = self.z;
418         self.z = self.w;
419         let w = self.w;
420         self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
421         self.w
422     }
423 }
424
425 impl SeedableRng<[u32; 4]> for XorShiftRng {
426     /// Reseed an XorShiftRng. This will panic if `seed` is entirely 0.
427     fn reseed(&mut self, seed: [u32; 4]) {
428         assert!(!seed.iter().all(|&x| x == 0),
429                 "XorShiftRng.reseed called with an all zero seed.");
430
431         self.x = seed[0];
432         self.y = seed[1];
433         self.z = seed[2];
434         self.w = seed[3];
435     }
436
437     /// Create a new XorShiftRng. This will panic if `seed` is entirely 0.
438     fn from_seed(seed: [u32; 4]) -> XorShiftRng {
439         assert!(!seed.iter().all(|&x| x == 0),
440                 "XorShiftRng::from_seed called with an all zero seed.");
441
442         XorShiftRng {
443             x: seed[0],
444             y: seed[1],
445             z: seed[2],
446             w: seed[3]
447         }
448     }
449 }
450
451 impl Rand for XorShiftRng {
452     fn rand<R: Rng>(rng: &mut R) -> XorShiftRng {
453         let mut tuple: (u32, u32, u32, u32) = rng.gen();
454         while tuple == (0, 0, 0, 0) {
455             tuple = rng.gen();
456         }
457         let (x, y, z, w) = tuple;
458         XorShiftRng { x: x, y: y, z: z, w: w }
459     }
460 }
461
462 /// A wrapper for generating floating point numbers uniformly in the
463 /// open interval `(0,1)` (not including either endpoint).
464 ///
465 /// Use `Closed01` for the closed interval `[0,1]`, and the default
466 /// `Rand` implementation for `f32` and `f64` for the half-open
467 /// `[0,1)`.
468 ///
469 /// # Example
470 /// ```rust
471 /// use std::rand::{random, Open01};
472 ///
473 /// let Open01(val) = random::<Open01<f32>>();
474 /// println!("f32 from (0,1): {}", val);
475 /// ```
476 pub struct Open01<F>(pub F);
477
478 /// A wrapper for generating floating point numbers uniformly in the
479 /// closed interval `[0,1]` (including both endpoints).
480 ///
481 /// Use `Open01` for the closed interval `(0,1)`, and the default
482 /// `Rand` implementation of `f32` and `f64` for the half-open
483 /// `[0,1)`.
484 ///
485 /// # Example
486 ///
487 /// ```rust
488 /// use std::rand::{random, Closed01};
489 ///
490 /// let Closed01(val) = random::<Closed01<f32>>();
491 /// println!("f32 from [0,1]: {}", val);
492 /// ```
493 pub struct Closed01<F>(pub F);
494
495 #[cfg(not(test))]
496 mod std {
497     pub use core::{option, fmt}; // panic!()
498     pub use core::clone; // derive Clone
499     pub use core::marker;
500 }
501
502 #[cfg(test)]
503 mod test {
504     use std::rand;
505
506     pub struct MyRng<R> { inner: R }
507
508     impl<R: rand::Rng> ::Rng for MyRng<R> {
509         fn next_u32(&mut self) -> u32 {
510             fn next<T: rand::Rng>(t: &mut T) -> u32 {
511                 use std::rand::Rng;
512                 t.next_u32()
513             }
514             next(&mut self.inner)
515         }
516     }
517
518     pub fn rng() -> MyRng<rand::ThreadRng> {
519         MyRng { inner: rand::thread_rng() }
520     }
521
522     pub fn weak_rng() -> MyRng<rand::XorShiftRng> {
523         MyRng { inner: rand::weak_rng() }
524     }
525 }