]> git.lizzy.rs Git - rust.git/blob - src/libstd/rand/mod.rs
Auto merge of #22541 - Manishearth:rollup, r=Gankro
[rust.git] / src / libstd / rand / mod.rs
1 // Copyright 2013 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 //! Utilities for random number generation
12 //!
13 //! The key functions are `random()` and `Rng::gen()`. These are polymorphic
14 //! and so can be used to generate any type that implements `Rand`. Type inference
15 //! means that often a simple call to `rand::random()` or `rng.gen()` will
16 //! suffice, but sometimes an annotation is required, e.g. `rand::random::<f64>()`.
17 //!
18 //! See the `distributions` submodule for sampling random numbers from
19 //! distributions like normal and exponential.
20 //!
21 //! # Thread-local RNG
22 //!
23 //! There is built-in support for a RNG associated with each thread stored
24 //! in thread-local storage. This RNG can be accessed via `thread_rng`, or
25 //! used implicitly via `random`. This RNG is normally randomly seeded
26 //! from an operating-system source of randomness, e.g. `/dev/urandom` on
27 //! Unix systems, and will automatically reseed itself from this source
28 //! after generating 32 KiB of random data.
29 //!
30 //! # Cryptographic security
31 //!
32 //! An application that requires an entropy source for cryptographic purposes
33 //! must use `OsRng`, which reads randomness from the source that the operating
34 //! system provides (e.g. `/dev/urandom` on Unixes or `CryptGenRandom()` on Windows).
35 //! The other random number generators provided by this module are not suitable
36 //! for such purposes.
37 //!
38 //! *Note*: many Unix systems provide `/dev/random` as well as `/dev/urandom`.
39 //! This module uses `/dev/urandom` for the following reasons:
40 //!
41 //! -   On Linux, `/dev/random` may block if entropy pool is empty; `/dev/urandom` will not block.
42 //!     This does not mean that `/dev/random` provides better output than
43 //!     `/dev/urandom`; the kernel internally runs a cryptographically secure pseudorandom
44 //!     number generator (CSPRNG) based on entropy pool for random number generation,
45 //!     so the "quality" of `/dev/random` is not better than `/dev/urandom` in most cases.
46 //!     However, this means that `/dev/urandom` can yield somewhat predictable randomness
47 //!     if the entropy pool is very small, such as immediately after first booting.
48 //!     Linux 3.17 added the `getrandom(2)` system call which solves the issue: it blocks if entropy
49 //!     pool is not initialized yet, but it does not block once initialized.
50 //!     `OsRng` tries to use `getrandom(2)` if available, and use `/dev/urandom` fallback if not.
51 //!     If an application does not have `getrandom` and likely to be run soon after first booting,
52 //!     or on a system with very few entropy sources, one should consider using `/dev/random` via
53 //!     `ReaderRng`.
54 //! -   On some systems (e.g. FreeBSD, OpenBSD and Mac OS X) there is no difference
55 //!     between the two sources. (Also note that, on some systems e.g. FreeBSD, both `/dev/random`
56 //!     and `/dev/urandom` may block once if the CSPRNG has not seeded yet.)
57 //!
58 //! # Examples
59 //!
60 //! ```rust
61 //! use std::rand;
62 //! use std::rand::Rng;
63 //!
64 //! let mut rng = rand::thread_rng();
65 //! if rng.gen() { // random bool
66 //!     println!("int: {}, uint: {}", rng.gen::<int>(), rng.gen::<uint>())
67 //! }
68 //! ```
69 //!
70 //! ```rust
71 //! use std::rand;
72 //!
73 //! let tuple = rand::random::<(f64, char)>();
74 //! println!("{:?}", tuple)
75 //! ```
76 //!
77 //! ## Monte Carlo estimation of π
78 //!
79 //! For this example, imagine we have a square with sides of length 2 and a unit
80 //! circle, both centered at the origin. Since the area of a unit circle is π,
81 //! we have:
82 //!
83 //! ```text
84 //!     (area of unit circle) / (area of square) = π / 4
85 //! ```
86 //!
87 //! So if we sample many points randomly from the square, roughly π / 4 of them
88 //! should be inside the circle.
89 //!
90 //! We can use the above fact to estimate the value of π: pick many points in the
91 //! square at random, calculate the fraction that fall within the circle, and
92 //! multiply this fraction by 4.
93 //!
94 //! ```
95 //! use std::rand;
96 //! use std::rand::distributions::{IndependentSample, Range};
97 //!
98 //! fn main() {
99 //!    let between = Range::new(-1f64, 1.);
100 //!    let mut rng = rand::thread_rng();
101 //!
102 //!    let total = 1_000_000;
103 //!    let mut in_circle = 0;
104 //!
105 //!    for _ in 0..total {
106 //!        let a = between.ind_sample(&mut rng);
107 //!        let b = between.ind_sample(&mut rng);
108 //!        if a*a + b*b <= 1. {
109 //!            in_circle += 1;
110 //!        }
111 //!    }
112 //!
113 //!    // prints something close to 3.14159...
114 //!    println!("{}", 4. * (in_circle as f64) / (total as f64));
115 //! }
116 //! ```
117 //!
118 //! ## Monty Hall Problem
119 //!
120 //! This is a simulation of the [Monty Hall Problem][]:
121 //!
122 //! > Suppose you're on a game show, and you're given the choice of three doors:
123 //! > Behind one door is a car; behind the others, goats. You pick a door, say No. 1,
124 //! > and the host, who knows what's behind the doors, opens another door, say No. 3,
125 //! > which has a goat. He then says to you, "Do you want to pick door No. 2?"
126 //! > Is it to your advantage to switch your choice?
127 //!
128 //! The rather unintuitive answer is that you will have a 2/3 chance of winning if
129 //! you switch and a 1/3 chance of winning if you don't, so it's better to switch.
130 //!
131 //! This program will simulate the game show and with large enough simulation steps
132 //! it will indeed confirm that it is better to switch.
133 //!
134 //! [Monty Hall Problem]: http://en.wikipedia.org/wiki/Monty_Hall_problem
135 //!
136 //! ```
137 //! use std::rand;
138 //! use std::rand::Rng;
139 //! use std::rand::distributions::{IndependentSample, Range};
140 //!
141 //! struct SimulationResult {
142 //!     win: bool,
143 //!     switch: bool,
144 //! }
145 //!
146 //! // Run a single simulation of the Monty Hall problem.
147 //! fn simulate<R: Rng>(random_door: &Range<uint>, rng: &mut R) -> SimulationResult {
148 //!     let car = random_door.ind_sample(rng);
149 //!
150 //!     // This is our initial choice
151 //!     let mut choice = random_door.ind_sample(rng);
152 //!
153 //!     // The game host opens a door
154 //!     let open = game_host_open(car, choice, rng);
155 //!
156 //!     // Shall we switch?
157 //!     let switch = rng.gen();
158 //!     if switch {
159 //!         choice = switch_door(choice, open);
160 //!     }
161 //!
162 //!     SimulationResult { win: choice == car, switch: switch }
163 //! }
164 //!
165 //! // Returns the door the game host opens given our choice and knowledge of
166 //! // where the car is. The game host will never open the door with the car.
167 //! fn game_host_open<R: Rng>(car: uint, choice: uint, rng: &mut R) -> uint {
168 //!     let choices = free_doors(&[car, choice]);
169 //!     rand::sample(rng, choices.into_iter(), 1)[0]
170 //! }
171 //!
172 //! // Returns the door we switch to, given our current choice and
173 //! // the open door. There will only be one valid door.
174 //! fn switch_door(choice: uint, open: uint) -> uint {
175 //!     free_doors(&[choice, open])[0]
176 //! }
177 //!
178 //! fn free_doors(blocked: &[uint]) -> Vec<uint> {
179 //!     (0..3).filter(|x| !blocked.contains(x)).collect()
180 //! }
181 //!
182 //! fn main() {
183 //!     // The estimation will be more accurate with more simulations
184 //!     let num_simulations = 10000;
185 //!
186 //!     let mut rng = rand::thread_rng();
187 //!     let random_door = Range::new(0, 3);
188 //!
189 //!     let (mut switch_wins, mut switch_losses) = (0, 0);
190 //!     let (mut keep_wins, mut keep_losses) = (0, 0);
191 //!
192 //!     println!("Running {} simulations...", num_simulations);
193 //!     for _ in 0..num_simulations {
194 //!         let result = simulate(&random_door, &mut rng);
195 //!
196 //!         match (result.win, result.switch) {
197 //!             (true, true) => switch_wins += 1,
198 //!             (true, false) => keep_wins += 1,
199 //!             (false, true) => switch_losses += 1,
200 //!             (false, false) => keep_losses += 1,
201 //!         }
202 //!     }
203 //!
204 //!     let total_switches = switch_wins + switch_losses;
205 //!     let total_keeps = keep_wins + keep_losses;
206 //!
207 //!     println!("Switched door {} times with {} wins and {} losses",
208 //!              total_switches, switch_wins, switch_losses);
209 //!
210 //!     println!("Kept our choice {} times with {} wins and {} losses",
211 //!              total_keeps, keep_wins, keep_losses);
212 //!
213 //!     // With a large number of simulations, the values should converge to
214 //!     // 0.667 and 0.333 respectively.
215 //!     println!("Estimated chance to win if we switch: {}",
216 //!              switch_wins as f32 / total_switches as f32);
217 //!     println!("Estimated chance to win if we don't: {}",
218 //!              keep_wins as f32 / total_keeps as f32);
219 //! }
220 //! ```
221
222 #![unstable(feature = "rand")]
223 #![deprecated(reason = "use the crates.io `rand` library instead",
224               since = "1.0.0-alpha")]
225 #![allow(deprecated)]
226
227 use cell::RefCell;
228 use clone::Clone;
229 use old_io::IoResult;
230 use iter::{Iterator, IteratorExt};
231 use mem;
232 use rc::Rc;
233 use result::Result::{Ok, Err};
234 use vec::Vec;
235
236 #[cfg(target_pointer_width = "32")]
237 use core_rand::IsaacRng as IsaacWordRng;
238 #[cfg(target_pointer_width = "64")]
239 use core_rand::Isaac64Rng as IsaacWordRng;
240
241 pub use core_rand::{Rand, Rng, SeedableRng, Open01, Closed01};
242 pub use core_rand::{XorShiftRng, IsaacRng, Isaac64Rng, ChaChaRng};
243 pub use core_rand::{distributions, reseeding};
244 pub use rand::os::OsRng;
245
246 pub mod os;
247 pub mod reader;
248
249 /// The standard RNG. This is designed to be efficient on the current
250 /// platform.
251 #[derive(Copy, Clone)]
252 pub struct StdRng {
253     rng: IsaacWordRng,
254 }
255
256 impl StdRng {
257     /// Create a randomly seeded instance of `StdRng`.
258     ///
259     /// This is a very expensive operation as it has to read
260     /// randomness from the operating system and use this in an
261     /// expensive seeding operation. If one is only generating a small
262     /// number of random numbers, or doesn't need the utmost speed for
263     /// generating each number, `thread_rng` and/or `random` may be more
264     /// appropriate.
265     ///
266     /// Reading the randomness from the OS may fail, and any error is
267     /// propagated via the `IoResult` return value.
268     pub fn new() -> IoResult<StdRng> {
269         OsRng::new().map(|mut r| StdRng { rng: r.gen() })
270     }
271 }
272
273 impl Rng for StdRng {
274     #[inline]
275     fn next_u32(&mut self) -> u32 {
276         self.rng.next_u32()
277     }
278
279     #[inline]
280     fn next_u64(&mut self) -> u64 {
281         self.rng.next_u64()
282     }
283 }
284
285 impl<'a> SeedableRng<&'a [usize]> for StdRng {
286     fn reseed(&mut self, seed: &'a [usize]) {
287         // the internal RNG can just be seeded from the above
288         // randomness.
289         self.rng.reseed(unsafe {mem::transmute(seed)})
290     }
291
292     fn from_seed(seed: &'a [usize]) -> StdRng {
293         StdRng { rng: SeedableRng::from_seed(unsafe {mem::transmute(seed)}) }
294     }
295 }
296
297 /// Create a weak random number generator with a default algorithm and seed.
298 ///
299 /// It returns the fastest `Rng` algorithm currently available in Rust without
300 /// consideration for cryptography or security. If you require a specifically
301 /// seeded `Rng` for consistency over time you should pick one algorithm and
302 /// create the `Rng` yourself.
303 ///
304 /// This will read randomness from the operating system to seed the
305 /// generator.
306 pub fn weak_rng() -> XorShiftRng {
307     match OsRng::new() {
308         Ok(mut r) => r.gen(),
309         Err(e) => panic!("weak_rng: failed to create seeded RNG: {:?}", e)
310     }
311 }
312
313 /// Controls how the thread-local RNG is reseeded.
314 struct ThreadRngReseeder;
315
316 impl reseeding::Reseeder<StdRng> for ThreadRngReseeder {
317     fn reseed(&mut self, rng: &mut StdRng) {
318         *rng = match StdRng::new() {
319             Ok(r) => r,
320             Err(e) => panic!("could not reseed thread_rng: {}", e)
321         }
322     }
323 }
324 static THREAD_RNG_RESEED_THRESHOLD: usize = 32_768;
325 type ThreadRngInner = reseeding::ReseedingRng<StdRng, ThreadRngReseeder>;
326
327 /// The thread-local RNG.
328 #[derive(Clone)]
329 pub struct ThreadRng {
330     rng: Rc<RefCell<ThreadRngInner>>,
331 }
332
333 /// Retrieve the lazily-initialized thread-local random number
334 /// generator, seeded by the system. Intended to be used in method
335 /// chaining style, e.g. `thread_rng().gen::<int>()`.
336 ///
337 /// The RNG provided will reseed itself from the operating system
338 /// after generating a certain amount of randomness.
339 ///
340 /// The internal RNG used is platform and architecture dependent, even
341 /// if the operating system random number generator is rigged to give
342 /// the same sequence always. If absolute consistency is required,
343 /// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
344 pub fn thread_rng() -> ThreadRng {
345     // used to make space in TLS for a random number generator
346     thread_local!(static THREAD_RNG_KEY: Rc<RefCell<ThreadRngInner>> = {
347         let r = match StdRng::new() {
348             Ok(r) => r,
349             Err(e) => panic!("could not initialize thread_rng: {}", e)
350         };
351         let rng = reseeding::ReseedingRng::new(r,
352                                                THREAD_RNG_RESEED_THRESHOLD,
353                                                ThreadRngReseeder);
354         Rc::new(RefCell::new(rng))
355     });
356
357     ThreadRng { rng: THREAD_RNG_KEY.with(|t| t.clone()) }
358 }
359
360 impl Rng for ThreadRng {
361     fn next_u32(&mut self) -> u32 {
362         self.rng.borrow_mut().next_u32()
363     }
364
365     fn next_u64(&mut self) -> u64 {
366         self.rng.borrow_mut().next_u64()
367     }
368
369     #[inline]
370     fn fill_bytes(&mut self, bytes: &mut [u8]) {
371         self.rng.borrow_mut().fill_bytes(bytes)
372     }
373 }
374
375 /// Generates a random value using the thread-local random number generator.
376 ///
377 /// `random()` can generate various types of random things, and so may require
378 /// type hinting to generate the specific type you want.
379 ///
380 /// This function uses the thread local random number generator. This means
381 /// that if you're calling `random()` in a loop, caching the generator can
382 /// increase performance. An example is shown below.
383 ///
384 /// # Examples
385 ///
386 /// ```
387 /// use std::rand;
388 ///
389 /// let x = rand::random();
390 /// println!("{}", 2u8 * x);
391 ///
392 /// let y = rand::random::<f64>();
393 /// println!("{}", y);
394 ///
395 /// if rand::random() { // generates a boolean
396 ///     println!("Better lucky than good!");
397 /// }
398 /// ```
399 ///
400 /// Caching the thread local random number generator:
401 ///
402 /// ```
403 /// use std::rand;
404 /// use std::rand::Rng;
405 ///
406 /// let mut v = vec![1, 2, 3];
407 ///
408 /// for x in v.iter_mut() {
409 ///     *x = rand::random()
410 /// }
411 ///
412 /// // would be faster as
413 ///
414 /// let mut rng = rand::thread_rng();
415 ///
416 /// for x in v.iter_mut() {
417 ///     *x = rng.gen();
418 /// }
419 /// ```
420 #[inline]
421 pub fn random<T: Rand>() -> T {
422     thread_rng().gen()
423 }
424
425 /// Randomly sample up to `amount` elements from an iterator.
426 ///
427 /// # Example
428 ///
429 /// ```rust
430 /// use std::rand::{thread_rng, sample};
431 ///
432 /// let mut rng = thread_rng();
433 /// let sample = sample(&mut rng, 1..100, 5);
434 /// println!("{:?}", sample);
435 /// ```
436 pub fn sample<T, I: Iterator<Item=T>, R: Rng>(rng: &mut R,
437                                          mut iter: I,
438                                          amount: usize) -> Vec<T> {
439     let mut reservoir: Vec<T> = iter.by_ref().take(amount).collect();
440     for (i, elem) in iter.enumerate() {
441         let k = rng.gen_range(0, i + 1 + amount);
442         if k < amount {
443             reservoir[k] = elem;
444         }
445     }
446     return reservoir;
447 }
448
449 #[cfg(test)]
450 mod test {
451     use prelude::v1::*;
452     use super::{Rng, thread_rng, random, SeedableRng, StdRng, sample};
453     use iter::{order, repeat};
454
455     struct ConstRng { i: u64 }
456     impl Rng for ConstRng {
457         fn next_u32(&mut self) -> u32 { self.i as u32 }
458         fn next_u64(&mut self) -> u64 { self.i }
459
460         // no fill_bytes on purpose
461     }
462
463     #[test]
464     fn test_fill_bytes_default() {
465         let mut r = ConstRng { i: 0x11_22_33_44_55_66_77_88 };
466
467         // check every remainder mod 8, both in small and big vectors.
468         let lengths = [0, 1, 2, 3, 4, 5, 6, 7,
469                        80, 81, 82, 83, 84, 85, 86, 87];
470         for &n in &lengths {
471             let mut v = repeat(0u8).take(n).collect::<Vec<_>>();
472             r.fill_bytes(&mut v);
473
474             // use this to get nicer error messages.
475             for (i, &byte) in v.iter().enumerate() {
476                 if byte == 0 {
477                     panic!("byte {} of {} is zero", i, n)
478                 }
479             }
480         }
481     }
482
483     #[test]
484     fn test_gen_range() {
485         let mut r = thread_rng();
486         for _ in 0..1000 {
487             let a = r.gen_range(-3, 42);
488             assert!(a >= -3 && a < 42);
489             assert_eq!(r.gen_range(0, 1), 0);
490             assert_eq!(r.gen_range(-12, -11), -12);
491         }
492
493         for _ in 0..1000 {
494             let a = r.gen_range(10, 42);
495             assert!(a >= 10 && a < 42);
496             assert_eq!(r.gen_range(0, 1), 0);
497             assert_eq!(r.gen_range(3_000_000, 3_000_001), 3_000_000);
498         }
499
500     }
501
502     #[test]
503     #[should_fail]
504     fn test_gen_range_panic_int() {
505         let mut r = thread_rng();
506         r.gen_range(5, -2);
507     }
508
509     #[test]
510     #[should_fail]
511     fn test_gen_range_panic_uint() {
512         let mut r = thread_rng();
513         r.gen_range(5, 2);
514     }
515
516     #[test]
517     fn test_gen_f64() {
518         let mut r = thread_rng();
519         let a = r.gen::<f64>();
520         let b = r.gen::<f64>();
521         debug!("{:?}", (a, b));
522     }
523
524     #[test]
525     fn test_gen_weighted_bool() {
526         let mut r = thread_rng();
527         assert_eq!(r.gen_weighted_bool(0), true);
528         assert_eq!(r.gen_weighted_bool(1), true);
529     }
530
531     #[test]
532     fn test_gen_ascii_str() {
533         let mut r = thread_rng();
534         assert_eq!(r.gen_ascii_chars().take(0).count(), 0);
535         assert_eq!(r.gen_ascii_chars().take(10).count(), 10);
536         assert_eq!(r.gen_ascii_chars().take(16).count(), 16);
537     }
538
539     #[test]
540     fn test_gen_vec() {
541         let mut r = thread_rng();
542         assert_eq!(r.gen_iter::<u8>().take(0).count(), 0);
543         assert_eq!(r.gen_iter::<u8>().take(10).count(), 10);
544         assert_eq!(r.gen_iter::<f64>().take(16).count(), 16);
545     }
546
547     #[test]
548     fn test_choose() {
549         let mut r = thread_rng();
550         assert_eq!(r.choose(&[1, 1, 1]).cloned(), Some(1));
551
552         let v: &[int] = &[];
553         assert_eq!(r.choose(v), None);
554     }
555
556     #[test]
557     fn test_shuffle() {
558         let mut r = thread_rng();
559         let empty: &mut [int] = &mut [];
560         r.shuffle(empty);
561         let mut one = [1];
562         r.shuffle(&mut one);
563         let b: &[_] = &[1];
564         assert_eq!(one, b);
565
566         let mut two = [1, 2];
567         r.shuffle(&mut two);
568         assert!(two == [1, 2] || two == [2, 1]);
569
570         let mut x = [1, 1, 1];
571         r.shuffle(&mut x);
572         let b: &[_] = &[1, 1, 1];
573         assert_eq!(x, b);
574     }
575
576     #[test]
577     fn test_thread_rng() {
578         let mut r = thread_rng();
579         r.gen::<int>();
580         let mut v = [1, 1, 1];
581         r.shuffle(&mut v);
582         let b: &[_] = &[1, 1, 1];
583         assert_eq!(v, b);
584         assert_eq!(r.gen_range(0, 1), 0);
585     }
586
587     #[test]
588     fn test_random() {
589         // not sure how to test this aside from just getting some values
590         let _n : uint = random();
591         let _f : f32 = random();
592         let _o : Option<Option<i8>> = random();
593         let _many : ((),
594                      (uint,
595                       int,
596                       Option<(u32, (bool,))>),
597                      (u8, i8, u16, i16, u32, i32, u64, i64),
598                      (f32, (f64, (f64,)))) = random();
599     }
600
601     #[test]
602     fn test_sample() {
603         let min_val = 1;
604         let max_val = 100;
605
606         let mut r = thread_rng();
607         let vals = (min_val..max_val).collect::<Vec<int>>();
608         let small_sample = sample(&mut r, vals.iter(), 5);
609         let large_sample = sample(&mut r, vals.iter(), vals.len() + 5);
610
611         assert_eq!(small_sample.len(), 5);
612         assert_eq!(large_sample.len(), vals.len());
613
614         assert!(small_sample.iter().all(|e| {
615             **e >= min_val && **e <= max_val
616         }));
617     }
618
619     #[test]
620     fn test_std_rng_seeded() {
621         let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
622         let mut ra: StdRng = SeedableRng::from_seed(&*s);
623         let mut rb: StdRng = SeedableRng::from_seed(&*s);
624         assert!(order::equals(ra.gen_ascii_chars().take(100),
625                               rb.gen_ascii_chars().take(100)));
626     }
627
628     #[test]
629     fn test_std_rng_reseed() {
630         let s = thread_rng().gen_iter::<uint>().take(256).collect::<Vec<uint>>();
631         let mut r: StdRng = SeedableRng::from_seed(&*s);
632         let string1 = r.gen_ascii_chars().take(100).collect::<String>();
633
634         r.reseed(&s);
635
636         let string2 = r.gen_ascii_chars().take(100).collect::<String>();
637         assert_eq!(string1, string2);
638     }
639 }
640
641 #[cfg(test)]
642 static RAND_BENCH_N: u64 = 100;
643
644 #[cfg(test)]
645 mod bench {
646     extern crate test;
647     use prelude::v1::*;
648
649     use self::test::Bencher;
650     use super::{XorShiftRng, StdRng, IsaacRng, Isaac64Rng, Rng, RAND_BENCH_N};
651     use super::{OsRng, weak_rng};
652     use mem::size_of;
653
654     #[bench]
655     fn rand_xorshift(b: &mut Bencher) {
656         let mut rng: XorShiftRng = OsRng::new().unwrap().gen();
657         b.iter(|| {
658             for _ in 0..RAND_BENCH_N {
659                 rng.gen::<uint>();
660             }
661         });
662         b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
663     }
664
665     #[bench]
666     fn rand_isaac(b: &mut Bencher) {
667         let mut rng: IsaacRng = OsRng::new().unwrap().gen();
668         b.iter(|| {
669             for _ in 0..RAND_BENCH_N {
670                 rng.gen::<uint>();
671             }
672         });
673         b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
674     }
675
676     #[bench]
677     fn rand_isaac64(b: &mut Bencher) {
678         let mut rng: Isaac64Rng = OsRng::new().unwrap().gen();
679         b.iter(|| {
680             for _ in 0..RAND_BENCH_N {
681                 rng.gen::<uint>();
682             }
683         });
684         b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
685     }
686
687     #[bench]
688     fn rand_std(b: &mut Bencher) {
689         let mut rng = StdRng::new().unwrap();
690         b.iter(|| {
691             for _ in 0..RAND_BENCH_N {
692                 rng.gen::<uint>();
693             }
694         });
695         b.bytes = size_of::<uint>() as u64 * RAND_BENCH_N;
696     }
697
698     #[bench]
699     fn rand_shuffle_100(b: &mut Bencher) {
700         let mut rng = weak_rng();
701         let x : &mut[uint] = &mut [1; 100];
702         b.iter(|| {
703             rng.shuffle(x);
704         })
705     }
706 }