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