blob: f5c60417bacb5c9344f64b745687f7d2ec060297 [file] [log] [blame]
Huon Wilson0b1a0d02013-10-01 17:16:221// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
Graydon Hoare00c856c2012-12-04 00:48:012// 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
Huon Wilson4a24f102013-04-24 12:29:1911/*!
12Random number generation.
13
Huon Wilsonfb923c72013-09-20 11:47:0514The key functions are `random()` and `Rng::gen()`. These are polymorphic
Huon Wilson4a24f102013-04-24 12:29:1915and so can be used to generate any type that implements `Rand`. Type inference
16means that often a simple call to `rand::random()` or `rng.gen()` will
Daniel Micayc9d4ad02013-09-26 06:26:0917suffice, but sometimes an annotation is required, e.g. `rand::random::<f64>()`.
Huon Wilson4a24f102013-04-24 12:29:1918
Huon Wilson1eb5efc2013-04-28 14:18:5319See the `distributions` submodule for sampling random numbers from
20distributions like normal and exponential.
21
Huon Wilson98869792013-10-01 17:17:5722# Task-local RNG
23
24There is built-in support for a RNG associated with each task stored
25in task-local storage. This RNG can be accessed via `task_rng`, or
26used implicitly via `random`. This RNG is normally randomly seeded
27from an operating-system source of randomness, e.g. `/dev/urandom` on
28Unix systems, and will automatically reseed itself from this source
29after generating 32 KiB of random data.
30
Huon Wilson4a24f102013-04-24 12:29:1931# Examples
Daniel Micay0d5fdce2013-05-27 13:49:5432
Alex Crichton3585c642013-09-24 00:20:3633```rust
korenchkin3cb3d752013-07-10 13:30:1434use std::rand;
Huon Wilsonfb923c72013-09-20 11:47:0535use std::rand::Rng;
Huon Wilson4a24f102013-04-24 12:29:1936
37fn main() {
John Clementsbe22fdd2013-05-17 18:23:5338 let mut rng = rand::rng();
Huon Wilson4a24f102013-04-24 12:29:1939 if rng.gen() { // bool
Alex Crichton409182d2013-09-25 05:16:4340 println!("int: {}, uint: {}", rng.gen::<int>(), rng.gen::<uint>())
Huon Wilson4a24f102013-04-24 12:29:1941 }
42}
Alex Crichton3585c642013-09-24 00:20:3643 ```
Huon Wilson4a24f102013-04-24 12:29:1944
Alex Crichton3585c642013-09-24 00:20:3645```rust
korenchkin3cb3d752013-07-10 13:30:1446use std::rand;
47
Huon Wilson4a24f102013-04-24 12:29:1948fn main () {
49 let tuple_ptr = rand::random::<~(f64, char)>();
Alex Crichton409182d2013-09-25 05:16:4350 println!(tuple_ptr)
Huon Wilson4a24f102013-04-24 12:29:1951}
Alex Crichton3585c642013-09-24 00:20:3652 ```
Huon Wilson4a24f102013-04-24 12:29:1953*/
54
Brian Anderson34d376f2013-10-17 01:34:0155use mem::size_of;
Daniel Micaye1a26ad2013-10-15 04:37:3256use unstable::raw::Slice;
Patrick Walton206ab892013-05-25 02:35:2957use cast;
Patrick Waltone015bee2013-06-18 16:39:1658use container::Container;
Huon Wilson39a69d32013-09-22 10:51:5759use iter::{Iterator, range};
Patrick Walton206ab892013-05-25 02:35:2960use local_data;
Patrick Walton2db3abd2013-01-09 03:37:2561use prelude::*;
Patrick Walton57c59992012-12-23 22:41:3762use str;
Huon Wilsonfb923c72013-09-20 11:47:0563use u64;
Patrick Walton57c59992012-12-23 22:41:3764use vec;
65
Huon Wilsona2b50962013-09-21 12:06:5066pub use self::isaac::{IsaacRng, Isaac64Rng};
Huon Wilson39a69d32013-09-22 10:51:5767pub use self::os::OSRng;
Huon Wilson72bf2012013-09-21 11:32:5768
Huon Wilson1eb5efc2013-04-28 14:18:5369pub mod distributions;
Huon Wilson72bf2012013-09-21 11:32:5770pub mod isaac;
Huon Wilson39a69d32013-09-22 10:51:5771pub mod os;
72pub mod reader;
Huon Wilson0223cf62013-09-29 06:49:1173pub mod reseeding;
Huon Wilson0b1a0d02013-10-01 17:16:2274mod rand_impls;
Huon Wilson1eb5efc2013-04-28 14:18:5375
Huon Wilson4a24f102013-04-24 12:29:1976/// A type that can be randomly generated using an Rng
Zack Corrabd29e52013-02-05 12:56:4077pub trait Rand {
Alex Crichton007651c2013-05-28 21:35:5278 /// Generates a random instance of this type using the specified source of
79 /// randomness
Patrick Waltonb2d1ac12013-05-03 06:09:5080 fn rand<R: Rng>(rng: &mut R) -> Self;
Zack Corrabd29e52013-02-05 12:56:4081}
82
Gareth Daniel Smithbe014162012-07-04 21:53:1283/// A value with a particular weight compared to other values
Erick Tryzelaare4d4a142013-01-22 16:12:5284pub struct Weighted<T> {
Alex Crichton007651c2013-05-28 21:35:5285 /// The numerical weight of this item
Erick Tryzelaare4d4a142013-01-22 16:12:5286 weight: uint,
Alex Crichton007651c2013-05-28 21:35:5287 /// The actual item which is being weighted
Erick Tryzelaare4d4a142013-01-22 16:12:5288 item: T,
89}
Huon Wilson4a24f102013-04-24 12:29:1990
Huon Wilsonfb923c72013-09-20 11:47:0591/// A random number generator
92pub trait Rng {
Huon Wilson39a69d32013-09-22 10:51:5793 /// Return the next random u32. This rarely needs to be called
94 /// directly, prefer `r.gen()` to `r.next_u32()`.
Huon Wilsona2b50962013-09-21 12:06:5095 ///
Huon Wilson62feded2013-10-08 22:56:5796 // FIXME #7771: Should be implemented in terms of next_u64
97 fn next_u32(&mut self) -> u32;
Huon Wilsona2b50962013-09-21 12:06:5098
Huon Wilson39a69d32013-09-22 10:51:5799 /// Return the next random u64. This rarely needs to be called
100 /// directly, prefer `r.gen()` to `r.next_u64()`.
Huon Wilsona2b50962013-09-21 12:06:50101 ///
102 /// By default this is implemented in terms of `next_u32`. An
103 /// implementation of this trait must provide at least one of
104 /// these two methods.
105 fn next_u64(&mut self) -> u64 {
106 (self.next_u32() as u64 << 32) | (self.next_u32() as u64)
107 }
Robert Knight11b3d762013-08-13 11:44:16108
Huon Wilson39a69d32013-09-22 10:51:57109 /// Fill `dest` with random data.
110 ///
111 /// This has a default implementation in terms of `next_u64` and
112 /// `next_u32`, but should be overriden by implementations that
113 /// offer a more efficient solution than just calling those
114 /// methods repeatedly.
115 ///
116 /// This method does *not* have a requirement to bear any fixed
117 /// relationship to the other methods, for example, it does *not*
118 /// have to result in the same output as progressively filling
119 /// `dest` with `self.gen::<u8>()`, and any such behaviour should
120 /// not be relied upon.
121 ///
122 /// This method should guarantee that `dest` is entirely filled
123 /// with new data, and may fail if this is impossible
124 /// (e.g. reading past the end of a file that is being used as the
125 /// source of randomness).
126 ///
127 /// # Example
128 ///
Huon Wilsonfb970632013-09-30 15:32:12129 /// ```rust
Huon Wilson39a69d32013-09-22 10:51:57130 /// use std::rand::{task_rng, Rng};
131 ///
132 /// fn main() {
133 /// let mut v = [0u8, .. 13579];
134 /// task_rng().fill_bytes(v);
Huon Wilson98869792013-10-01 17:17:57135 /// println!("{:?}", v);
Huon Wilson39a69d32013-09-22 10:51:57136 /// }
Huon Wilsonfb970632013-09-30 15:32:12137 /// ```
Daniel Micaye1a26ad2013-10-15 04:37:32138 fn fill_bytes(&mut self, dest: &mut [u8]) {
139 let mut slice: Slice<u64> = unsafe { cast::transmute_copy(&dest) };
140 slice.len /= size_of::<u64>();
141 let as_u64: &mut [u64] = unsafe { cast::transmute(slice) };
Huon Wilson39a69d32013-09-22 10:51:57142 for dest in as_u64.mut_iter() {
143 *dest = self.next_u64();
144 }
145
146 // the above will have filled up the vector as much as
147 // possible in multiples of 8 bytes.
148 let mut remaining = dest.len() % 8;
149
150 // space for a u32
151 if remaining >= 4 {
Daniel Micaye1a26ad2013-10-15 04:37:32152 let mut slice: Slice<u32> = unsafe { cast::transmute_copy(&dest) };
153 slice.len /= size_of::<u32>();
154 let as_u32: &mut [u32] = unsafe { cast::transmute(slice) };
Huon Wilson39a69d32013-09-22 10:51:57155 as_u32[as_u32.len() - 1] = self.next_u32();
156 remaining -= 4;
157 }
158 // exactly filled
159 if remaining == 0 { return }
160
161 // now we know we've either got 1, 2 or 3 spots to go,
162 // i.e. exactly one u32 is enough.
163 let rand = self.next_u32();
164 let remaining_index = dest.len() - remaining;
165 match dest.mut_slice_from(remaining_index) {
166 [ref mut a] => {
167 *a = rand as u8;
168 }
169 [ref mut a, ref mut b] => {
170 *a = rand as u8;
171 *b = (rand >> 8) as u8;
172 }
173 [ref mut a, ref mut b, ref mut c] => {
174 *a = rand as u8;
175 *b = (rand >> 8) as u8;
176 *c = (rand >> 16) as u8;
177 }
Alex Crichtondaf5f5a2013-10-21 20:08:31178 _ => fail!("Rng.fill_bytes: the impossible occurred: remaining != 1, 2 or 3")
Huon Wilson39a69d32013-09-22 10:51:57179 }
180 }
Patrick Waltonb1c69982013-03-12 20:00:50181
Huon Wilsonfb923c72013-09-20 11:47:05182 /// Return a random value of a Rand type.
183 ///
184 /// # Example
185 ///
Alex Crichton3585c642013-09-24 00:20:36186 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05187 /// use std::rand;
flo-lbf6b1982013-10-04 14:38:05188 /// use std::rand::Rng;
Huon Wilsonfb923c72013-09-20 11:47:05189 ///
190 /// fn main() {
flo-lbf6b1982013-10-04 14:38:05191 /// let mut rng = rand::task_rng();
Huon Wilsonfb923c72013-09-20 11:47:05192 /// let x: uint = rng.gen();
Alex Crichton409182d2013-09-25 05:16:43193 /// println!("{}", x);
Daniel Micayc9d4ad02013-09-26 06:26:09194 /// println!("{:?}", rng.gen::<(f64, bool)>());
Huon Wilsonfb923c72013-09-20 11:47:05195 /// }
Alex Crichton3585c642013-09-24 00:20:36196 /// ```
Huon Wilsonfb923c72013-09-20 11:47:05197 #[inline(always)]
Patrick Waltonb2d1ac12013-05-03 06:09:50198 fn gen<T: Rand>(&mut self) -> T {
Huon Wilson6c0a7c7b2013-04-23 14:00:43199 Rand::rand(self)
Zack Corrabd29e52013-02-05 12:56:40200 }
Gareth Daniel Smith11e81952012-05-17 18:52:49201
Huon Wilsonfb923c72013-09-20 11:47:05202 /// Return a random vector of the specified length.
203 ///
204 /// # Example
205 ///
Alex Crichton3585c642013-09-24 00:20:36206 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05207 /// use std::rand;
flo-lbf6b1982013-10-04 14:38:05208 /// use std::rand::Rng;
Huon Wilsonfb923c72013-09-20 11:47:05209 ///
210 /// fn main() {
flo-lbf6b1982013-10-04 14:38:05211 /// let mut rng = rand::task_rng();
Huon Wilsonfb923c72013-09-20 11:47:05212 /// let x: ~[uint] = rng.gen_vec(10);
Alex Crichton409182d2013-09-25 05:16:43213 /// println!("{:?}", x);
Daniel Micayc9d4ad02013-09-26 06:26:09214 /// println!("{:?}", rng.gen_vec::<(f64, bool)>(5));
Huon Wilsonfb923c72013-09-20 11:47:05215 /// }
Alex Crichton3585c642013-09-24 00:20:36216 /// ```
Huon Wilsonfb923c72013-09-20 11:47:05217 fn gen_vec<T: Rand>(&mut self, len: uint) -> ~[T] {
218 vec::from_fn(len, |_| self.gen())
Gareth Daniel Smith64130f12012-05-19 18:25:45219 }
220
Huon Wilsonfb923c72013-09-20 11:47:05221 /// Generate a random primitive integer in the range [`low`,
222 /// `high`). Fails if `low >= high`.
223 ///
224 /// This gives a uniform distribution (assuming this RNG is itself
225 /// uniform), even for edge cases like `gen_integer_range(0u8,
226 /// 170)`, which a naive modulo operation would return numbers
227 /// less than 85 with double the probability to those greater than
228 /// 85.
229 ///
230 /// # Example
231 ///
Alex Crichton3585c642013-09-24 00:20:36232 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05233 /// use std::rand;
flo-lbf6b1982013-10-04 14:38:05234 /// use std::rand::Rng;
Huon Wilsonfb923c72013-09-20 11:47:05235 ///
236 /// fn main() {
flo-lbf6b1982013-10-04 14:38:05237 /// let mut rng = rand::task_rng();
Huon Wilsonfb923c72013-09-20 11:47:05238 /// let n: uint = rng.gen_integer_range(0u, 10);
Alex Crichton409182d2013-09-25 05:16:43239 /// println!("{}", n);
flo-lbf6b1982013-10-04 14:38:05240 /// let m: int = rng.gen_integer_range(-40, 400);
Alex Crichton409182d2013-09-25 05:16:43241 /// println!("{}", m);
Huon Wilsonfb923c72013-09-20 11:47:05242 /// }
Alex Crichton3585c642013-09-24 00:20:36243 /// ```
Huon Wilsonfb923c72013-09-20 11:47:05244 fn gen_integer_range<T: Rand + Int>(&mut self, low: T, high: T) -> T {
245 assert!(low < high, "RNG.gen_integer_range called with low >= high");
Erick Tryzelaard9d1dfc2013-09-15 16:50:17246 let range = (high - low).to_u64().unwrap();
Huon Wilsonfb923c72013-09-20 11:47:05247 let accept_zone = u64::max_value - u64::max_value % range;
248 loop {
249 let rand = self.gen::<u64>();
250 if rand < accept_zone {
Erick Tryzelaard9d1dfc2013-09-15 16:50:17251 return low + NumCast::from(rand % range).unwrap();
Huon Wilsonfb923c72013-09-20 11:47:05252 }
Gareth Daniel Smith64130f12012-05-19 18:25:45253 }
254 }
255
Huon Wilsonfb923c72013-09-20 11:47:05256 /// Return a bool with a 1 in n chance of true
257 ///
258 /// # Example
259 ///
Alex Crichton3585c642013-09-24 00:20:36260 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05261 /// use std::rand;
262 /// use std::rand::Rng;
263 ///
264 /// fn main() {
265 /// let mut rng = rand::rng();
Alex Crichton409182d2013-09-25 05:16:43266 /// println!("{:b}", rng.gen_weighted_bool(3));
Huon Wilsonfb923c72013-09-20 11:47:05267 /// }
Alex Crichton3585c642013-09-24 00:20:36268 /// ```
Huon Wilsonfb923c72013-09-20 11:47:05269 fn gen_weighted_bool(&mut self, n: uint) -> bool {
270 n == 0 || self.gen_integer_range(0, n) == 0
271 }
272
273 /// Return a random string of the specified length composed of
274 /// A-Z,a-z,0-9.
275 ///
276 /// # Example
277 ///
Alex Crichton3585c642013-09-24 00:20:36278 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05279 /// use std::rand;
flo-lbf6b1982013-10-04 14:38:05280 /// use std::rand::Rng;
Huon Wilsonfb923c72013-09-20 11:47:05281 ///
282 /// fn main() {
283 /// println(rand::task_rng().gen_ascii_str(10));
284 /// }
Alex Crichton3585c642013-09-24 00:20:36285 /// ```
Huon Wilsonfb923c72013-09-20 11:47:05286 fn gen_ascii_str(&mut self, len: uint) -> ~str {
287 static GEN_ASCII_STR_CHARSET: &'static [u8] = bytes!("ABCDEFGHIJKLMNOPQRSTUVWXYZ\
288 abcdefghijklmnopqrstuvwxyz\
289 0123456789");
290 let mut s = str::with_capacity(len);
291 for _ in range(0, len) {
292 s.push_char(self.choose(GEN_ASCII_STR_CHARSET) as char)
Gareth Daniel Smith11e81952012-05-17 18:52:49293 }
Luqman Aden5912b142013-02-15 08:51:28294 s
Gareth Daniel Smith11e81952012-05-17 18:52:49295 }
296
Huon Wilsonfb923c72013-09-20 11:47:05297 /// Choose an item randomly, failing if `values` is empty.
298 fn choose<T: Clone>(&mut self, values: &[T]) -> T {
299 self.choose_option(values).expect("Rng.choose: `values` is empty").clone()
Gareth Daniel Smith11e81952012-05-17 18:52:49300 }
Gareth Daniel Smith64130f12012-05-19 18:25:45301
Huon Wilsonfb923c72013-09-20 11:47:05302 /// Choose `Some(&item)` randomly, returning `None` if values is
303 /// empty.
304 ///
305 /// # Example
306 ///
Alex Crichton3585c642013-09-24 00:20:36307 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05308 /// use std::rand;
flo-lbf6b1982013-10-04 14:38:05309 /// use std::rand::Rng;
Huon Wilsonfb923c72013-09-20 11:47:05310 ///
311 /// fn main() {
Alex Crichton409182d2013-09-25 05:16:43312 /// println!("{:?}", rand::task_rng().choose_option([1,2,4,8,16,32]));
313 /// println!("{:?}", rand::task_rng().choose_option([]));
Huon Wilsonfb923c72013-09-20 11:47:05314 /// }
Alex Crichton3585c642013-09-24 00:20:36315 /// ```
Huon Wilsonfb923c72013-09-20 11:47:05316 fn choose_option<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T> {
Gareth Daniel Smith64130f12012-05-19 18:25:45317 if values.is_empty() {
Brian Anderson8337fa12012-08-20 19:23:37318 None
Gareth Daniel Smith64130f12012-05-19 18:25:45319 } else {
Huon Wilsonfb923c72013-09-20 11:47:05320 Some(&values[self.gen_integer_range(0u, values.len())])
Gareth Daniel Smith64130f12012-05-19 18:25:45321 }
322 }
Huon Wilsonfb923c72013-09-20 11:47:05323
324 /// Choose an item respecting the relative weights, failing if the sum of
325 /// the weights is 0
326 ///
327 /// # Example
328 ///
Alex Crichton3585c642013-09-24 00:20:36329 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05330 /// use std::rand;
331 /// use std::rand::Rng;
332 ///
333 /// fn main() {
334 /// let mut rng = rand::rng();
335 /// let x = [rand::Weighted {weight: 4, item: 'a'},
336 /// rand::Weighted {weight: 2, item: 'b'},
337 /// rand::Weighted {weight: 2, item: 'c'}];
Alex Crichton409182d2013-09-25 05:16:43338 /// println!("{}", rng.choose_weighted(x));
Huon Wilsonfb923c72013-09-20 11:47:05339 /// }
Alex Crichton3585c642013-09-24 00:20:36340 /// ```
Patrick Waltone20549f2013-07-10 21:43:25341 fn choose_weighted<T:Clone>(&mut self, v: &[Weighted<T>]) -> T {
Huon Wilsonfb923c72013-09-20 11:47:05342 self.choose_weighted_option(v).expect("Rng.choose_weighted: total weight is 0")
Gareth Daniel Smith64130f12012-05-19 18:25:45343 }
344
Huon Wilsonfb923c72013-09-20 11:47:05345 /// Choose Some(item) respecting the relative weights, returning none if
346 /// the sum of the weights is 0
347 ///
348 /// # Example
349 ///
Alex Crichton3585c642013-09-24 00:20:36350 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05351 /// use std::rand;
352 /// use std::rand::Rng;
353 ///
354 /// fn main() {
355 /// let mut rng = rand::rng();
356 /// let x = [rand::Weighted {weight: 4, item: 'a'},
357 /// rand::Weighted {weight: 2, item: 'b'},
358 /// rand::Weighted {weight: 2, item: 'c'}];
Alex Crichton409182d2013-09-25 05:16:43359 /// println!("{:?}", rng.choose_weighted_option(x));
Huon Wilsonfb923c72013-09-20 11:47:05360 /// }
Alex Crichton3585c642013-09-24 00:20:36361 /// ```
Patrick Walton99b33f72013-07-02 19:47:32362 fn choose_weighted_option<T:Clone>(&mut self, v: &[Weighted<T>])
363 -> Option<T> {
Gareth Daniel Smith64130f12012-05-19 18:25:45364 let mut total = 0u;
Daniel Micay100894552013-08-03 16:45:23365 for item in v.iter() {
Gareth Daniel Smith64130f12012-05-19 18:25:45366 total += item.weight;
367 }
368 if total == 0u {
Brian Anderson8337fa12012-08-20 19:23:37369 return None;
Gareth Daniel Smith64130f12012-05-19 18:25:45370 }
Huon Wilsonfb923c72013-09-20 11:47:05371 let chosen = self.gen_integer_range(0u, total);
Gareth Daniel Smith64130f12012-05-19 18:25:45372 let mut so_far = 0u;
Daniel Micay100894552013-08-03 16:45:23373 for item in v.iter() {
Gareth Daniel Smith64130f12012-05-19 18:25:45374 so_far += item.weight;
375 if so_far > chosen {
Patrick Walton99b33f72013-07-02 19:47:32376 return Some(item.item.clone());
Gareth Daniel Smith64130f12012-05-19 18:25:45377 }
378 }
Chris Morgane2807a42013-09-19 05:04:03379 unreachable!();
Gareth Daniel Smith64130f12012-05-19 18:25:45380 }
381
Huon Wilsonfb923c72013-09-20 11:47:05382 /// Return a vec containing copies of the items, in order, where
383 /// the weight of the item determines how many copies there are
384 ///
385 /// # Example
386 ///
Alex Crichton3585c642013-09-24 00:20:36387 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05388 /// use std::rand;
389 /// use std::rand::Rng;
390 ///
391 /// fn main() {
392 /// let mut rng = rand::rng();
393 /// let x = [rand::Weighted {weight: 4, item: 'a'},
394 /// rand::Weighted {weight: 2, item: 'b'},
395 /// rand::Weighted {weight: 2, item: 'c'}];
Alex Crichton409182d2013-09-25 05:16:43396 /// println!("{}", rng.weighted_vec(x));
Huon Wilsonfb923c72013-09-20 11:47:05397 /// }
Alex Crichton3585c642013-09-24 00:20:36398 /// ```
Patrick Walton99b33f72013-07-02 19:47:32399 fn weighted_vec<T:Clone>(&mut self, v: &[Weighted<T>]) -> ~[T] {
Michael Sullivan98e161f2012-06-29 23:26:56400 let mut r = ~[];
Daniel Micay100894552013-08-03 16:45:23401 for item in v.iter() {
402 for _ in range(0u, item.weight) {
Patrick Walton99b33f72013-07-02 19:47:32403 r.push(item.item.clone());
Gareth Daniel Smith64130f12012-05-19 18:25:45404 }
405 }
Luqman Aden5912b142013-02-15 08:51:28406 r
Gareth Daniel Smith64130f12012-05-19 18:25:45407 }
408
Gareth Daniel Smithbe014162012-07-04 21:53:12409 /// Shuffle a vec
Huon Wilsonfb923c72013-09-20 11:47:05410 ///
411 /// # Example
412 ///
Alex Crichton3585c642013-09-24 00:20:36413 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05414 /// use std::rand;
flo-lbf6b1982013-10-04 14:38:05415 /// use std::rand::Rng;
Huon Wilsonfb923c72013-09-20 11:47:05416 ///
417 /// fn main() {
Alex Crichton409182d2013-09-25 05:16:43418 /// println!("{:?}", rand::task_rng().shuffle(~[1,2,3]));
Huon Wilsonfb923c72013-09-20 11:47:05419 /// }
Alex Crichton3585c642013-09-24 00:20:36420 /// ```
Huon Wilsonfb923c72013-09-20 11:47:05421 fn shuffle<T>(&mut self, values: ~[T]) -> ~[T] {
422 let mut v = values;
423 self.shuffle_mut(v);
424 v
Gareth Daniel Smith64130f12012-05-19 18:25:45425 }
426
Huon Wilsonfb923c72013-09-20 11:47:05427 /// Shuffle a mutable vector in place.
428 ///
429 /// # Example
430 ///
Alex Crichton3585c642013-09-24 00:20:36431 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05432 /// use std::rand;
flo-lbf6b1982013-10-04 14:38:05433 /// use std::rand::Rng;
Huon Wilsonfb923c72013-09-20 11:47:05434 ///
435 /// fn main() {
flo-lbf6b1982013-10-04 14:38:05436 /// let mut rng = rand::task_rng();
Huon Wilsonfb923c72013-09-20 11:47:05437 /// let mut y = [1,2,3];
438 /// rng.shuffle_mut(y);
Alex Crichton409182d2013-09-25 05:16:43439 /// println!("{:?}", y);
Huon Wilsonfb923c72013-09-20 11:47:05440 /// rng.shuffle_mut(y);
Alex Crichton409182d2013-09-25 05:16:43441 /// println!("{:?}", y);
Huon Wilsonfb923c72013-09-20 11:47:05442 /// }
Alex Crichton3585c642013-09-24 00:20:36443 /// ```
Patrick Waltonb2d1ac12013-05-03 06:09:50444 fn shuffle_mut<T>(&mut self, values: &mut [T]) {
Gareth Daniel Smith64130f12012-05-19 18:25:45445 let mut i = values.len();
446 while i >= 2u {
447 // invariant: elements with index >= i have been locked in place.
448 i -= 1u;
449 // lock element i in place.
Huon Wilsonfb923c72013-09-20 11:47:05450 values.swap(i, self.gen_integer_range(0u, i + 1u));
Gareth Daniel Smith64130f12012-05-19 18:25:45451 }
452 }
Robert Knight11b3d762013-08-13 11:44:16453
Huon Wilsonfb923c72013-09-20 11:47:05454 /// Randomly sample up to `n` elements from an iterator.
455 ///
456 /// # Example
457 ///
Alex Crichton3585c642013-09-24 00:20:36458 /// ```rust
Huon Wilsonfb923c72013-09-20 11:47:05459 /// use std::rand;
flo-lbf6b1982013-10-04 14:38:05460 /// use std::rand::Rng;
Huon Wilsonfb923c72013-09-20 11:47:05461 ///
462 /// fn main() {
flo-lbf6b1982013-10-04 14:38:05463 /// let mut rng = rand::task_rng();
Huon Wilsonfb923c72013-09-20 11:47:05464 /// let sample = rng.sample(range(1, 100), 5);
Alex Crichton409182d2013-09-25 05:16:43465 /// println!("{:?}", sample);
Huon Wilsonfb923c72013-09-20 11:47:05466 /// }
Alex Crichton3585c642013-09-24 00:20:36467 /// ```
Robert Knight11b3d762013-08-13 11:44:16468 fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> ~[A] {
469 let mut reservoir : ~[A] = vec::with_capacity(n);
470 for (i, elem) in iter.enumerate() {
471 if i < n {
472 reservoir.push(elem);
Alex Crichton4f67dcb2013-10-01 21:31:03473 continue
Robert Knight11b3d762013-08-13 11:44:16474 }
475
Huon Wilsonfb923c72013-09-20 11:47:05476 let k = self.gen_integer_range(0, i + 1);
Robert Knight11b3d762013-08-13 11:44:16477 if k < reservoir.len() {
478 reservoir[k] = elem
479 }
480 }
481 reservoir
482 }
Gareth Daniel Smith11e81952012-05-17 18:52:49483}
Roy Frostig5b6e7142010-07-26 04:45:09484
Huon Wilson92725ae2013-09-29 15:29:28485/// A random number generator that can be explicitly seeded to produce
486/// the same stream of randomness multiple times.
487pub trait SeedableRng<Seed>: Rng {
488 /// Reseed an RNG with the given seed.
489 ///
490 /// # Example
491 ///
492 /// ```rust
493 /// use std::rand;
494 /// use std::rand::Rng;
495 ///
496 /// fn main() {
Huon Wilson98869792013-10-01 17:17:57497 /// let mut rng: rand::StdRng = rand::SeedableRng::from_seed(&[1, 2, 3, 4]);
Huon Wilson92725ae2013-09-29 15:29:28498 /// println!("{}", rng.gen::<f64>());
499 /// rng.reseed([5, 6, 7, 8]);
500 /// println!("{}", rng.gen::<f64>());
501 /// }
502 /// ```
503 fn reseed(&mut self, Seed);
504
505 /// Create a new RNG with the given seed.
506 ///
507 /// # Example
508 ///
509 /// ```rust
510 /// use std::rand;
511 /// use std::rand::Rng;
512 ///
513 /// fn main() {
Huon Wilson98869792013-10-01 17:17:57514 /// let mut rng: rand::StdRng = rand::SeedableRng::from_seed(&[1, 2, 3, 4]);
Huon Wilson92725ae2013-09-29 15:29:28515 /// println!("{}", rng.gen::<f64>());
516 /// }
517 /// ```
518 fn from_seed(seed: Seed) -> Self;
519}
520
Huon Wilson6c0a7c7b2013-04-23 14:00:43521/// Create a random number generator with a default algorithm and seed.
Jordi Boggiano3db9dc12013-08-06 20:13:26522///
523/// It returns the cryptographically-safest `Rng` algorithm currently
524/// available in Rust. If you require a specifically seeded `Rng` for
525/// consistency over time you should pick one algorithm and create the
526/// `Rng` yourself.
Huon Wilsonf39a2152013-09-26 09:08:44527///
528/// This is a very expensive operation as it has to read randomness
529/// from the operating system and use this in an expensive seeding
Huon Wilsona836f132013-10-08 14:54:21530/// operation. If one does not require high performance generation of
531/// random numbers, `task_rng` and/or `random` may be more
532/// appropriate.
Huon Wilsonf39a2152013-09-26 09:08:44533pub fn rng() -> StdRng {
534 StdRng::new()
535}
536
537/// The standard RNG. This is designed to be efficient on the current
538/// platform.
539#[cfg(not(target_word_size="64"))]
540pub struct StdRng { priv rng: IsaacRng }
541
542/// The standard RNG. This is designed to be efficient on the current
543/// platform.
544#[cfg(target_word_size="64")]
545pub struct StdRng { priv rng: Isaac64Rng }
546
547impl StdRng {
Huon Wilsonfb970632013-09-30 15:32:12548 /// Create a randomly seeded instance of `StdRng`. This reads
549 /// randomness from the OS to seed the PRNG.
Huon Wilsonf39a2152013-09-26 09:08:44550 #[cfg(not(target_word_size="64"))]
Huon Wilsonfb970632013-09-30 15:32:12551 pub fn new() -> StdRng {
Huon Wilsonf39a2152013-09-26 09:08:44552 StdRng { rng: IsaacRng::new() }
553 }
Huon Wilsonfb970632013-09-30 15:32:12554 /// Create a randomly seeded instance of `StdRng`. This reads
555 /// randomness from the OS to seed the PRNG.
Huon Wilsonf39a2152013-09-26 09:08:44556 #[cfg(target_word_size="64")]
Huon Wilsonfb970632013-09-30 15:32:12557 pub fn new() -> StdRng {
Huon Wilsonf39a2152013-09-26 09:08:44558 StdRng { rng: Isaac64Rng::new() }
559 }
560}
561
562impl Rng for StdRng {
563 #[inline]
564 fn next_u32(&mut self) -> u32 {
565 self.rng.next_u32()
566 }
567
568 #[inline]
569 fn next_u64(&mut self) -> u64 {
570 self.rng.next_u64()
571 }
Ben Striegel43d43ad2013-02-28 00:13:53572}
573
Huon Wilson92725ae2013-09-29 15:29:28574impl<'self> SeedableRng<&'self [uint]> for StdRng {
575 fn reseed(&mut self, seed: &'self [uint]) {
576 // the internal RNG can just be seeded from the above
577 // randomness.
578 self.rng.reseed(unsafe {cast::transmute(seed)})
579 }
580
581 fn from_seed(seed: &'self [uint]) -> StdRng {
582 StdRng { rng: SeedableRng::from_seed(unsafe {cast::transmute(seed)}) }
583 }
584}
585
Jordi Boggiano403c52d2013-08-06 20:14:32586/// Create a weak random number generator with a default algorithm and seed.
587///
Huon Wilsonabe94f92013-08-16 05:41:28588/// It returns the fastest `Rng` algorithm currently available in Rust without
Jordi Boggiano403c52d2013-08-06 20:14:32589/// consideration for cryptography or security. If you require a specifically
590/// seeded `Rng` for consistency over time you should pick one algorithm and
591/// create the `Rng` yourself.
Huon Wilsona836f132013-10-08 14:54:21592///
593/// This will read randomness from the operating system to seed the
594/// generator.
Jordi Boggiano403c52d2013-08-06 20:14:32595pub fn weak_rng() -> XorShiftRng {
596 XorShiftRng::new()
597}
598
Huon Wilsond4b934b2013-04-26 13:53:29599/// An [Xorshift random number
Jordi Boggiano3db9dc12013-08-06 20:13:26600/// generator](http://en.wikipedia.org/wiki/Xorshift).
601///
602/// The Xorshift algorithm is not suitable for cryptographic purposes
603/// but is very fast. If you do not know for sure that it fits your
604/// requirements, use a more secure one such as `IsaacRng`.
Huon Wilson30266a72013-04-26 13:23:49605pub struct XorShiftRng {
Patrick Waltonb2d1ac12013-05-03 06:09:50606 priv x: u32,
607 priv y: u32,
608 priv z: u32,
609 priv w: u32,
Roy Frostig5b6e7142010-07-26 04:45:09610}
Brian Anderson6e27b272012-01-18 03:05:07611
Huon Wilson6c0a7c7b2013-04-23 14:00:43612impl Rng for XorShiftRng {
Huon Wilsond4b934b2013-04-26 13:53:29613 #[inline]
Huon Wilsona2b50962013-09-21 12:06:50614 fn next_u32(&mut self) -> u32 {
Eric Holkad292a82012-05-30 23:31:16615 let x = self.x;
Alex Crichton13537d22013-04-12 05:10:01616 let t = x ^ (x << 11);
Eric Holkad292a82012-05-30 23:31:16617 self.x = self.y;
618 self.y = self.z;
619 self.z = self.w;
620 let w = self.w;
621 self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
622 self.w
623 }
624}
625
Huon Wilson92725ae2013-09-29 15:29:28626impl SeedableRng<[u32, .. 4]> for XorShiftRng {
627 /// Reseed an XorShiftRng. This will fail if `seed` is entirely 0.
628 fn reseed(&mut self, seed: [u32, .. 4]) {
629 assert!(!seed.iter().all(|&x| x == 0),
630 "XorShiftRng.reseed called with an all zero seed.");
631
632 self.x = seed[0];
633 self.y = seed[1];
634 self.z = seed[2];
635 self.w = seed[3];
636 }
637
638 /// Create a new XorShiftRng. This will fail if `seed` is entirely 0.
639 fn from_seed(seed: [u32, .. 4]) -> XorShiftRng {
640 assert!(!seed.iter().all(|&x| x == 0),
641 "XorShiftRng::from_seed called with an all zero seed.");
642
643 XorShiftRng {
644 x: seed[0],
645 y: seed[1],
646 z: seed[2],
647 w: seed[3]
648 }
649 }
650}
651
Patrick Walton5fb25462013-05-31 22:17:22652impl XorShiftRng {
Kevin Ballarde7b85242013-08-16 19:11:34653 /// Create an xor shift random number generator with a random seed.
Patrick Walton5fb25462013-05-31 22:17:22654 pub fn new() -> XorShiftRng {
Kevin Ballarde7b85242013-08-16 19:11:34655 let mut s = [0u8, ..16];
656 loop {
Huon Wilson39a69d32013-09-22 10:51:57657 let mut r = OSRng::new();
658 r.fill_bytes(s);
659
Kevin Ballarde7b85242013-08-16 19:11:34660 if !s.iter().all(|x| *x == 0) {
661 break;
662 }
663 }
Huon Wilsona836f132013-10-08 14:54:21664 let s: [u32, ..4] = unsafe { cast::transmute(s) };
665 SeedableRng::from_seed(s)
Huon Wilson6c0a7c7b2013-04-23 14:00:43666 }
Huon Wilson30266a72013-04-26 13:23:49667}
Eric Holkad292a82012-05-30 23:31:16668
Huon Wilsonfb970632013-09-30 15:32:12669/// Controls how the task-local RNG is reseeded.
Huon Wilson5442a472013-10-09 06:36:31670struct TaskRngReseeder;
Huon Wilsonfb970632013-09-30 15:32:12671
672impl reseeding::Reseeder<StdRng> for TaskRngReseeder {
673 fn reseed(&mut self, rng: &mut StdRng) {
Huon Wilson5442a472013-10-09 06:36:31674 *rng = StdRng::new();
Huon Wilsonfb970632013-09-30 15:32:12675 }
676}
677static TASK_RNG_RESEED_THRESHOLD: uint = 32_768;
678/// The task-local RNG.
679pub type TaskRng = reseeding::ReseedingRng<StdRng, TaskRngReseeder>;
680
681// used to make space in TLS for a random number generator
682local_data_key!(TASK_RNG_KEY: @mut TaskRng)
683
684/// Retrieve the lazily-initialized task-local random number
685/// generator, seeded by the system. Intended to be used in method
686/// chaining style, e.g. `task_rng().gen::<int>()`.
687///
688/// The RNG provided will reseed itself from the operating system
Huon Wilson5442a472013-10-09 06:36:31689/// after generating a certain amount of randomness.
Huon Wilsonfb970632013-09-30 15:32:12690///
Huon Wilson5442a472013-10-09 06:36:31691/// The internal RNG used is platform and architecture dependent, even
692/// if the operating system random number generator is rigged to give
693/// the same sequence always. If absolute consistency is required,
694/// explicitly select an RNG, e.g. `IsaacRng` or `Isaac64Rng`.
Huon Wilsonfb970632013-09-30 15:32:12695pub fn task_rng() -> @mut TaskRng {
Daniel Micay6a90e802013-09-20 06:08:47696 let r = local_data::get(TASK_RNG_KEY, |k| k.map(|k| *k));
Daniel Pattersonc7354e62012-10-02 03:29:34697 match r {
698 None => {
Huon Wilson5442a472013-10-09 06:36:31699 let rng = @mut reseeding::ReseedingRng::new(StdRng::new(),
Huon Wilsonfb970632013-09-30 15:32:12700 TASK_RNG_RESEED_THRESHOLD,
Huon Wilson5442a472013-10-09 06:36:31701 TaskRngReseeder);
Huon Wilsonfb970632013-09-30 15:32:12702 local_data::set(TASK_RNG_KEY, rng);
Huon Wilsonf39a2152013-09-26 09:08:44703 rng
Daniel Pattersonc7354e62012-10-02 03:29:34704 }
Huon Wilsonf39a2152013-09-26 09:08:44705 Some(rng) => rng
Daniel Pattersonc7354e62012-10-02 03:29:34706 }
707}
708
Huon Wilson4a24f102013-04-24 12:29:19709// Allow direct chaining with `task_rng`
Kevin Ballardb8b2d1e2013-06-18 18:54:00710impl<R: Rng> Rng for @mut R {
Graydon Hoared904c722013-06-18 21:45:18711 #[inline]
Huon Wilsona2b50962013-09-21 12:06:50712 fn next_u32(&mut self) -> u32 {
713 (**self).next_u32()
714 }
715 #[inline]
716 fn next_u64(&mut self) -> u64 {
717 (**self).next_u64()
Patrick Waltonb2d1ac12013-05-03 06:09:50718 }
Huon Wilsone6784352013-10-09 06:39:37719
720 #[inline]
721 fn fill_bytes(&mut self, bytes: &mut [u8]) {
722 (**self).fill_bytes(bytes);
723 }
Huon Wilson4a24f102013-04-24 12:29:19724}
725
Huon Wilsonfb970632013-09-30 15:32:12726/// Generate a random value using the task-local random number
727/// generator.
728///
729/// # Example
730///
731/// ```rust
732/// use std::rand::random;
733///
734/// fn main() {
735/// if random() {
736/// let x = random();
Huon Wilson98869792013-10-01 17:17:57737/// println!("{}", 2u * x);
Huon Wilsonfb970632013-09-30 15:32:12738/// } else {
Volker Mische82f53d62013-10-10 19:54:29739/// println!("{}", random::<f64>());
Huon Wilsonfb970632013-09-30 15:32:12740/// }
741/// }
742/// ```
Huon Wilsond4b934b2013-04-26 13:53:29743#[inline]
Huon Wilsonaa763cd2013-04-21 12:09:33744pub fn random<T: Rand>() -> T {
Kevin Ballardb8b2d1e2013-06-18 18:54:00745 task_rng().gen()
Daniel Patterson0b9a47a2012-10-02 21:15:14746}
747
Brian Anderson6e27b272012-01-18 03:05:07748#[cfg(test)]
Graydon Hoared9776232013-07-22 18:43:12749mod test {
Daniel Micay6919cf52013-09-08 15:01:16750 use iter::{Iterator, range};
Alex Crichtonbe57d742013-03-26 20:38:07751 use option::{Option, Some};
Huon Wilson6c0a7c7b2013-04-23 14:00:43752 use super::*;
Patrick Waltone26ca352012-12-28 01:53:04753
Brian Anderson6e27b272012-01-18 03:05:07754 #[test]
Huon Wilson39a69d32013-09-22 10:51:57755 fn test_fill_bytes_default() {
756 let mut r = weak_rng();
757
758 let mut v = [0u8, .. 100];
759 r.fill_bytes(v);
760 }
761
762 #[test]
Huon Wilsonfb923c72013-09-20 11:47:05763 fn test_gen_integer_range() {
Patrick Walton16a01252013-05-08 00:57:58764 let mut r = rng();
Huon Wilsonfb923c72013-09-20 11:47:05765 for _ in range(0, 1000) {
766 let a = r.gen_integer_range(-3i, 42);
767 assert!(a >= -3 && a < 42);
768 assert_eq!(r.gen_integer_range(0, 1), 0);
769 assert_eq!(r.gen_integer_range(-12, -11), -12);
770 }
771
772 for _ in range(0, 1000) {
773 let a = r.gen_integer_range(10, 42);
774 assert!(a >= 10 && a < 42);
775 assert_eq!(r.gen_integer_range(0, 1), 0);
776 assert_eq!(r.gen_integer_range(3_000_000u, 3_000_001), 3_000_000);
777 }
778
Gareth Daniel Smith64130f12012-05-19 18:25:45779 }
780
781 #[test]
782 #[should_fail]
Huon Wilsonfb923c72013-09-20 11:47:05783 fn test_gen_integer_range_fail_int() {
Patrick Walton16a01252013-05-08 00:57:58784 let mut r = rng();
Huon Wilsonfb923c72013-09-20 11:47:05785 r.gen_integer_range(5i, -2);
Gareth Daniel Smith64130f12012-05-19 18:25:45786 }
787
788 #[test]
789 #[should_fail]
Huon Wilsonfb923c72013-09-20 11:47:05790 fn test_gen_integer_range_fail_uint() {
Patrick Walton16a01252013-05-08 00:57:58791 let mut r = rng();
Huon Wilsonfb923c72013-09-20 11:47:05792 r.gen_integer_range(5u, 2u);
Brian Anderson6e27b272012-01-18 03:05:07793 }
794
795 #[test]
Daniel Micayc9d4ad02013-09-26 06:26:09796 fn test_gen_f64() {
Patrick Walton16a01252013-05-08 00:57:58797 let mut r = rng();
Daniel Micayc9d4ad02013-09-26 06:26:09798 let a = r.gen::<f64>();
799 let b = r.gen::<f64>();
Alex Crichtondaf5f5a2013-10-21 20:08:31800 debug!("{:?}", (a, b));
Gareth Daniel Smith11e81952012-05-17 18:52:49801 }
802
803 #[test]
Huon Wilson6c0a7c7b2013-04-23 14:00:43804 fn test_gen_weighted_bool() {
Patrick Walton16a01252013-05-08 00:57:58805 let mut r = rng();
Corey Richardsoncc57ca02013-05-19 02:02:45806 assert_eq!(r.gen_weighted_bool(0u), true);
807 assert_eq!(r.gen_weighted_bool(1u), true);
Gareth Daniel Smith64130f12012-05-19 18:25:45808 }
809
810 #[test]
Huon Wilsonfb923c72013-09-20 11:47:05811 fn test_gen_ascii_str() {
Patrick Walton16a01252013-05-08 00:57:58812 let mut r = rng();
Alex Crichtondaf5f5a2013-10-21 20:08:31813 debug!("{}", r.gen_ascii_str(10u));
814 debug!("{}", r.gen_ascii_str(10u));
815 debug!("{}", r.gen_ascii_str(10u));
Huon Wilsonfb923c72013-09-20 11:47:05816 assert_eq!(r.gen_ascii_str(0u).len(), 0u);
817 assert_eq!(r.gen_ascii_str(10u).len(), 10u);
818 assert_eq!(r.gen_ascii_str(16u).len(), 16u);
Gareth Daniel Smith11e81952012-05-17 18:52:49819 }
820
821 #[test]
Huon Wilsonfb923c72013-09-20 11:47:05822 fn test_gen_vec() {
Patrick Walton16a01252013-05-08 00:57:58823 let mut r = rng();
Huon Wilsonfb923c72013-09-20 11:47:05824 assert_eq!(r.gen_vec::<u8>(0u).len(), 0u);
825 assert_eq!(r.gen_vec::<u8>(10u).len(), 10u);
826 assert_eq!(r.gen_vec::<f64>(16u).len(), 16u);
Brian Anderson6e27b272012-01-18 03:05:07827 }
Gareth Daniel Smith64130f12012-05-19 18:25:45828
829 #[test]
Huon Wilson6c0a7c7b2013-04-23 14:00:43830 fn test_choose() {
Patrick Walton16a01252013-05-08 00:57:58831 let mut r = rng();
Corey Richardsoncc57ca02013-05-19 02:02:45832 assert_eq!(r.choose([1, 1, 1]), 1);
Gareth Daniel Smith64130f12012-05-19 18:25:45833 }
834
835 #[test]
Huon Wilson6c0a7c7b2013-04-23 14:00:43836 fn test_choose_option() {
Patrick Walton16a01252013-05-08 00:57:58837 let mut r = rng();
Huon Wilsonfb923c72013-09-20 11:47:05838 let v: &[int] = &[];
839 assert!(r.choose_option(v).is_none());
840
841 let i = 1;
842 let v = [1,1,1];
843 assert_eq!(r.choose_option(v), Some(&i));
Gareth Daniel Smith64130f12012-05-19 18:25:45844 }
845
846 #[test]
Huon Wilson6c0a7c7b2013-04-23 14:00:43847 fn test_choose_weighted() {
Patrick Walton16a01252013-05-08 00:57:58848 let mut r = rng();
Erick Tryzelaardc970c12013-05-23 16:39:17849 assert!(r.choose_weighted([
Huon Wilson6c0a7c7b2013-04-23 14:00:43850 Weighted { weight: 1u, item: 42 },
Patrick Waltond7e74b52013-03-06 21:58:02851 ]) == 42);
Erick Tryzelaardc970c12013-05-23 16:39:17852 assert!(r.choose_weighted([
Huon Wilson6c0a7c7b2013-04-23 14:00:43853 Weighted { weight: 0u, item: 42 },
854 Weighted { weight: 1u, item: 43 },
Patrick Waltond7e74b52013-03-06 21:58:02855 ]) == 43);
Gareth Daniel Smith64130f12012-05-19 18:25:45856 }
857
858 #[test]
Huon Wilson6c0a7c7b2013-04-23 14:00:43859 fn test_choose_weighted_option() {
Patrick Walton16a01252013-05-08 00:57:58860 let mut r = rng();
Erick Tryzelaardc970c12013-05-23 16:39:17861 assert!(r.choose_weighted_option([
Huon Wilson6c0a7c7b2013-04-23 14:00:43862 Weighted { weight: 1u, item: 42 },
Patrick Waltond7e74b52013-03-06 21:58:02863 ]) == Some(42));
Erick Tryzelaardc970c12013-05-23 16:39:17864 assert!(r.choose_weighted_option([
Huon Wilson6c0a7c7b2013-04-23 14:00:43865 Weighted { weight: 0u, item: 42 },
866 Weighted { weight: 1u, item: 43 },
Patrick Waltond7e74b52013-03-06 21:58:02867 ]) == Some(43));
Patrick Walton96534362012-08-27 23:26:35868 let v: Option<int> = r.choose_weighted_option([]);
Patrick Walton1e915952013-03-29 01:39:09869 assert!(v.is_none());
Gareth Daniel Smith64130f12012-05-19 18:25:45870 }
871
872 #[test]
Huon Wilson6c0a7c7b2013-04-23 14:00:43873 fn test_weighted_vec() {
Patrick Walton16a01252013-05-08 00:57:58874 let mut r = rng();
Michael Sullivan98e161f2012-06-29 23:26:56875 let empty: ~[int] = ~[];
Erick Tryzelaardc970c12013-05-23 16:39:17876 assert_eq!(r.weighted_vec([]), empty);
877 assert!(r.weighted_vec([
Huon Wilson6c0a7c7b2013-04-23 14:00:43878 Weighted { weight: 0u, item: 3u },
879 Weighted { weight: 1u, item: 2u },
880 Weighted { weight: 2u, item: 1u },
Patrick Waltond7e74b52013-03-06 21:58:02881 ]) == ~[2u, 1u, 1u]);
Gareth Daniel Smith64130f12012-05-19 18:25:45882 }
883
884 #[test]
Huon Wilson6c0a7c7b2013-04-23 14:00:43885 fn test_shuffle() {
Patrick Walton16a01252013-05-08 00:57:58886 let mut r = rng();
Michael Sullivan98e161f2012-06-29 23:26:56887 let empty: ~[int] = ~[];
Huon Wilsonfb923c72013-09-20 11:47:05888 assert_eq!(r.shuffle(~[]), empty);
889 assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]);
Gareth Daniel Smith64130f12012-05-19 18:25:45890 }
Daniel Patterson6c7459d2012-10-02 03:48:33891
892 #[test]
Huon Wilson6c0a7c7b2013-04-23 14:00:43893 fn test_task_rng() {
Patrick Walton16a01252013-05-08 00:57:58894 let mut r = task_rng();
Huon Wilson4a24f102013-04-24 12:29:19895 r.gen::<int>();
Huon Wilsonfb923c72013-09-20 11:47:05896 assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]);
897 assert_eq!(r.gen_integer_range(0u, 1u), 0u);
Daniel Patterson6c7459d2012-10-02 03:48:33898 }
Daniel Patterson0b9a47a2012-10-02 21:15:14899
900 #[test]
Huon Wilson6c0a7c7b2013-04-23 14:00:43901 fn test_random() {
Huon Wilsonaa763cd2013-04-21 12:09:33902 // not sure how to test this aside from just getting some values
Huon Wilson6c0a7c7b2013-04-23 14:00:43903 let _n : uint = random();
904 let _f : f32 = random();
905 let _o : Option<Option<i8>> = random();
Huon Wilson56679022013-04-22 09:01:48906 let _many : ((),
Daniel Micay62a34342013-09-03 23:24:12907 (~uint, @int, ~Option<~(@u32, ~(@bool,))>),
Huon Wilson56679022013-04-22 09:01:48908 (u8, i8, u16, i16, u32, i32, u64, i64),
Daniel Micayc9d4ad02013-09-26 06:26:09909 (f32, (f64, (f64,)))) = random();
Daniel Patterson0b9a47a2012-10-02 21:15:14910 }
Huon Wilson30266a72013-04-26 13:23:49911
912 #[test]
Robert Knight11b3d762013-08-13 11:44:16913 fn test_sample() {
914 let MIN_VAL = 1;
915 let MAX_VAL = 100;
916
917 let mut r = rng();
918 let vals = range(MIN_VAL, MAX_VAL).to_owned_vec();
919 let small_sample = r.sample(vals.iter(), 5);
920 let large_sample = r.sample(vals.iter(), vals.len() + 5);
921
922 assert_eq!(small_sample.len(), 5);
923 assert_eq!(large_sample.len(), vals.len());
924
925 assert!(small_sample.iter().all(|e| {
926 **e >= MIN_VAL && **e <= MAX_VAL
927 }));
928 }
Huon Wilsonfb970632013-09-30 15:32:12929
930 #[test]
Huon Wilson6f4ec722013-10-01 16:23:22931 fn test_std_rng_seeded() {
Huon Wilson71addde2013-10-08 13:21:26932 let s = OSRng::new().gen_vec::<uint>(256);
Huon Wilson6f4ec722013-10-01 16:23:22933 let mut ra: StdRng = SeedableRng::from_seed(s.as_slice());
934 let mut rb: StdRng = SeedableRng::from_seed(s.as_slice());
935 assert_eq!(ra.gen_ascii_str(100u), rb.gen_ascii_str(100u));
936 }
937
938 #[test]
939 fn test_std_rng_reseed() {
Huon Wilson71addde2013-10-08 13:21:26940 let s = OSRng::new().gen_vec::<uint>(256);
Huon Wilson6f4ec722013-10-01 16:23:22941 let mut r: StdRng = SeedableRng::from_seed(s.as_slice());
942 let string1 = r.gen_ascii_str(100);
943
944 r.reseed(s);
945
946 let string2 = r.gen_ascii_str(100);
947 assert_eq!(string1, string2);
948 }
Brian Anderson6e27b272012-01-18 03:05:07949}
Graydon Hoared9776232013-07-22 18:43:12950
951#[cfg(test)]
952mod bench {
953 use extra::test::BenchHarness;
954 use rand::*;
Brian Anderson34d376f2013-10-17 01:34:01955 use mem::size_of;
Graydon Hoared9776232013-07-22 18:43:12956
957 #[bench]
958 fn rand_xorshift(bh: &mut BenchHarness) {
959 let mut rng = XorShiftRng::new();
960 do bh.iter {
961 rng.gen::<uint>();
962 }
963 bh.bytes = size_of::<uint>() as u64;
964 }
965
966 #[bench]
967 fn rand_isaac(bh: &mut BenchHarness) {
968 let mut rng = IsaacRng::new();
969 do bh.iter {
970 rng.gen::<uint>();
971 }
972 bh.bytes = size_of::<uint>() as u64;
973 }
974
975 #[bench]
Huon Wilsona2b50962013-09-21 12:06:50976 fn rand_isaac64(bh: &mut BenchHarness) {
977 let mut rng = Isaac64Rng::new();
978 do bh.iter {
979 rng.gen::<uint>();
980 }
981 bh.bytes = size_of::<uint>() as u64;
982 }
983
984 #[bench]
Huon Wilsonf39a2152013-09-26 09:08:44985 fn rand_std(bh: &mut BenchHarness) {
986 let mut rng = StdRng::new();
987 do bh.iter {
988 rng.gen::<uint>();
989 }
990 bh.bytes = size_of::<uint>() as u64;
991 }
992
993 #[bench]
Graydon Hoared9776232013-07-22 18:43:12994 fn rand_shuffle_100(bh: &mut BenchHarness) {
995 let mut rng = XorShiftRng::new();
996 let x : &mut[uint] = [1,..100];
997 do bh.iter {
998 rng.shuffle_mut(x);
999 }
1000 }
Daniel Micay1fc4db22013-08-01 07:16:421001}