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