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