1 // Copyright 2012 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.
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.
12 Random number generation.
14 The key functions are `random()` and `RngUtil::gen()`. These are polymorphic
15 and so can be used to generate any type that implements `Rand`. Type inference
16 means that often a simple call to `rand::random()` or `rng.gen()` will
17 suffice, but sometimes an annotation is required, e.g. `rand::random::<float>()`.
19 See the `distributions` submodule for sampling random numbers from
20 distributions like normal and exponential.
26 use std::rand::RngUtil;
29 let mut rng = rand::rng();
30 if rng.gen() { // bool
31 printfln!("int: %d, uint: %u", rng.gen(), rng.gen())
40 let tuple_ptr = rand::random::<~(f64, char)>();
49 use container::Container;
51 use iter::{Iterator, range, range_step};
63 #[path="rand/distributions.rs"]
64 pub mod distributions;
66 /// A type that can be randomly generated using an Rng
68 /// Generates a random instance of this type using the specified source of
70 fn rand<R: Rng>(rng: &mut R) -> Self;
75 fn rand<R: Rng>(rng: &mut R) -> int {
79 rng.gen::<i64>() as int
86 fn rand<R: Rng>(rng: &mut R) -> i8 {
93 fn rand<R: Rng>(rng: &mut R) -> i16 {
100 fn rand<R: Rng>(rng: &mut R) -> i32 {
107 fn rand<R: Rng>(rng: &mut R) -> i64 {
108 (rng.next() as i64 << 32) | rng.next() as i64
114 fn rand<R: Rng>(rng: &mut R) -> uint {
115 if uint::bits == 32 {
118 rng.gen::<u64>() as uint
125 fn rand<R: Rng>(rng: &mut R) -> u8 {
132 fn rand<R: Rng>(rng: &mut R) -> u16 {
139 fn rand<R: Rng>(rng: &mut R) -> u32 {
146 fn rand<R: Rng>(rng: &mut R) -> u64 {
147 (rng.next() as u64 << 32) | rng.next() as u64
151 impl Rand for float {
153 fn rand<R: Rng>(rng: &mut R) -> float {
154 rng.gen::<f64>() as float
160 fn rand<R: Rng>(rng: &mut R) -> f32 {
161 rng.gen::<f64>() as f32
165 static SCALE : f64 = (u32::max_value as f64) + 1.0f64;
168 fn rand<R: Rng>(rng: &mut R) -> f64 {
169 let u1 = rng.next() as f64;
170 let u2 = rng.next() as f64;
171 let u3 = rng.next() as f64;
173 ((u1 / SCALE + u2) / SCALE + u3) / SCALE
179 fn rand<R: Rng>(rng: &mut R) -> bool {
180 rng.next() & 1u32 == 1u32
184 macro_rules! tuple_impl {
185 // use variables to indicate the arity of the tuple
186 ($($tyvar:ident),* ) => {
187 // the trailing commas are for the 1 tuple
190 > Rand for ( $( $tyvar ),* , ) {
193 fn rand<R: Rng>(_rng: &mut R) -> ( $( $tyvar ),* , ) {
195 // use the $tyvar's to get the appropriate number of
196 // repeats (they're not actually needed)
209 fn rand<R: Rng>(_: &mut R) -> () { () }
214 tuple_impl!{A, B, C, D}
215 tuple_impl!{A, B, C, D, E}
216 tuple_impl!{A, B, C, D, E, F}
217 tuple_impl!{A, B, C, D, E, F, G}
218 tuple_impl!{A, B, C, D, E, F, G, H}
219 tuple_impl!{A, B, C, D, E, F, G, H, I}
220 tuple_impl!{A, B, C, D, E, F, G, H, I, J}
222 impl<T:Rand> Rand for Option<T> {
224 fn rand<R: Rng>(rng: &mut R) -> Option<T> {
233 impl<T: Rand> Rand for ~T {
235 fn rand<R: Rng>(rng: &mut R) -> ~T { ~rng.gen() }
238 impl<T: Rand + 'static> Rand for @T {
240 fn rand<R: Rng>(rng: &mut R) -> @T { @rng.gen() }
248 pub fn rand_seed_size() -> size_t;
249 pub fn rand_gen_seed(buf: *mut u8, sz: size_t);
253 /// A random number generator
255 /// Return the next random integer
256 fn next(&mut self) -> u32;
259 /// A value with a particular weight compared to other values
260 pub struct Weighted<T> {
261 /// The numerical weight of this item
263 /// The actual item which is being weighted
267 /// Helper functions attached to the Rng type
269 /// Return a random value of a Rand type
270 fn gen<T:Rand>(&mut self) -> T;
272 * Return a int randomly chosen from the range [start, end),
273 * failing if start >= end
275 fn gen_int_range(&mut self, start: int, end: int) -> int;
277 * Return a uint randomly chosen from the range [start, end),
278 * failing if start >= end
280 fn gen_uint_range(&mut self, start: uint, end: uint) -> uint;
282 * Return a char randomly chosen from chars, failing if chars is empty
284 fn gen_char_from(&mut self, chars: &str) -> char;
286 * Return a bool with a 1 in n chance of true
293 * use std::rand::RngUtil;
296 * let mut rng = rand::rng();
297 * printfln!("%b", rng.gen_weighted_bool(3));
301 fn gen_weighted_bool(&mut self, n: uint) -> bool;
303 * Return a random string of the specified length composed of A-Z,a-z,0-9
310 * use std::rand::RngUtil;
313 * let mut rng = rand::rng();
314 * println(rng.gen_str(8));
318 fn gen_str(&mut self, len: uint) -> ~str;
320 * Return a random byte string of the specified length
327 * use std::rand::RngUtil;
330 * let mut rng = rand::rng();
331 * printfln!(rng.gen_bytes(8));
335 fn gen_bytes(&mut self, len: uint) -> ~[u8];
337 * Choose an item randomly, failing if values is empty
344 * use std::rand::RngUtil;
347 * let mut rng = rand::rng();
348 * printfln!("%d", rng.choose([1,2,4,8,16,32]));
352 fn choose<T:Clone>(&mut self, values: &[T]) -> T;
353 /// Choose Some(item) randomly, returning None if values is empty
354 fn choose_option<T:Clone>(&mut self, values: &[T]) -> Option<T>;
356 * Choose an item respecting the relative weights, failing if the sum of
364 * use std::rand::RngUtil;
367 * let mut rng = rand::rng();
368 * let x = [rand::Weighted {weight: 4, item: 'a'},
369 * rand::Weighted {weight: 2, item: 'b'},
370 * rand::Weighted {weight: 2, item: 'c'}];
371 * printfln!("%c", rng.choose_weighted(x));
375 fn choose_weighted<T:Clone>(&mut self, v : &[Weighted<T>]) -> T;
377 * Choose Some(item) respecting the relative weights, returning none if
378 * the sum of the weights is 0
385 * use std::rand::RngUtil;
388 * let mut rng = rand::rng();
389 * let x = [rand::Weighted {weight: 4, item: 'a'},
390 * rand::Weighted {weight: 2, item: 'b'},
391 * rand::Weighted {weight: 2, item: 'c'}];
392 * printfln!(rng.choose_weighted_option(x));
396 fn choose_weighted_option<T:Clone>(&mut self, v: &[Weighted<T>])
399 * Return a vec containing copies of the items, in order, where
400 * the weight of the item determines how many copies there are
407 * use std::rand::RngUtil;
410 * let mut rng = rand::rng();
411 * let x = [rand::Weighted {weight: 4, item: 'a'},
412 * rand::Weighted {weight: 2, item: 'b'},
413 * rand::Weighted {weight: 2, item: 'c'}];
414 * printfln!(rng.weighted_vec(x));
418 fn weighted_vec<T:Clone>(&mut self, v: &[Weighted<T>]) -> ~[T];
427 * use std::rand::RngUtil;
430 * let mut rng = rand::rng();
431 * printfln!(rng.shuffle([1,2,3]));
435 fn shuffle<T:Clone>(&mut self, values: &[T]) -> ~[T];
437 * Shuffle a mutable vec in place
444 * use std::rand::RngUtil;
447 * let mut rng = rand::rng();
448 * let mut y = [1,2,3];
449 * rng.shuffle_mut(y);
451 * rng.shuffle_mut(y);
456 fn shuffle_mut<T>(&mut self, values: &mut [T]);
459 * Sample up to `n` values from an iterator.
466 * use std::rand::RngUtil;
469 * let mut rng = rand::rng();
470 * let vals = range(1, 100).to_owned_vec();
471 * let sample = rng.sample(vals.iter(), 5);
476 fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> ~[A];
479 /// Extension methods for random number generators
480 impl<R: Rng> RngUtil for R {
481 /// Return a random value for a Rand type
483 fn gen<T: Rand>(&mut self) -> T {
488 * Return an int randomly chosen from the range [start, end),
489 * failing if start >= end
491 fn gen_int_range(&mut self, start: int, end: int) -> int {
492 assert!(start < end);
493 start + num::abs(self.gen::<int>() % (end - start))
497 * Return a uint randomly chosen from the range [start, end),
498 * failing if start >= end
500 fn gen_uint_range(&mut self, start: uint, end: uint) -> uint {
501 assert!(start < end);
502 start + (self.gen::<uint>() % (end - start))
506 * Return a char randomly chosen from chars, failing if chars is empty
508 fn gen_char_from(&mut self, chars: &str) -> char {
509 assert!(!chars.is_empty());
511 for c in chars.iter() { cs.push(c) }
515 /// Return a bool with a 1-in-n chance of true
516 fn gen_weighted_bool(&mut self, n: uint) -> bool {
520 self.gen_uint_range(1u, n + 1u) == 1u
525 * Return a random string of the specified length composed of A-Z,a-z,0-9
527 fn gen_str(&mut self, len: uint) -> ~str {
528 let charset = ~"ABCDEFGHIJKLMNOPQRSTUVWXYZ\
529 abcdefghijklmnopqrstuvwxyz\
534 s = s + str::from_char(self.gen_char_from(charset));
540 /// Return a random byte string of the specified length
541 fn gen_bytes(&mut self, len: uint) -> ~[u8] {
542 do vec::from_fn(len) |_i| {
547 /// Choose an item randomly, failing if values is empty
548 fn choose<T:Clone>(&mut self, values: &[T]) -> T {
549 self.choose_option(values).unwrap()
552 /// Choose Some(item) randomly, returning None if values is empty
553 fn choose_option<T:Clone>(&mut self, values: &[T]) -> Option<T> {
554 if values.is_empty() {
557 Some(values[self.gen_uint_range(0u, values.len())].clone())
561 * Choose an item respecting the relative weights, failing if the sum of
564 fn choose_weighted<T:Clone>(&mut self, v: &[Weighted<T>]) -> T {
565 self.choose_weighted_option(v).unwrap()
569 * Choose Some(item) respecting the relative weights, returning none if
570 * the sum of the weights is 0
572 fn choose_weighted_option<T:Clone>(&mut self, v: &[Weighted<T>])
575 for item in v.iter() {
576 total += item.weight;
581 let chosen = self.gen_uint_range(0u, total);
583 for item in v.iter() {
584 so_far += item.weight;
586 return Some(item.item.clone());
593 * Return a vec containing copies of the items, in order, where
594 * the weight of the item determines how many copies there are
596 fn weighted_vec<T:Clone>(&mut self, v: &[Weighted<T>]) -> ~[T] {
598 for item in v.iter() {
599 for _ in range(0u, item.weight) {
600 r.push(item.item.clone());
607 fn shuffle<T:Clone>(&mut self, values: &[T]) -> ~[T] {
608 let mut m = values.to_owned();
613 /// Shuffle a mutable vec in place
614 fn shuffle_mut<T>(&mut self, values: &mut [T]) {
615 let mut i = values.len();
617 // invariant: elements with index >= i have been locked in place.
619 // lock element i in place.
620 values.swap(i, self.gen_uint_range(0u, i + 1u));
624 /// Randomly sample up to `n` elements from an iterator
625 fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> ~[A] {
626 let mut reservoir : ~[A] = vec::with_capacity(n);
627 for (i, elem) in iter.enumerate() {
629 reservoir.push(elem);
633 let k = self.gen_uint_range(0, i + 1);
634 if k < reservoir.len() {
642 /// Create a random number generator with a default algorithm and seed.
644 /// It returns the cryptographically-safest `Rng` algorithm currently
645 /// available in Rust. If you require a specifically seeded `Rng` for
646 /// consistency over time you should pick one algorithm and create the
648 pub fn rng() -> IsaacRng {
652 /// Create a weak random number generator with a default algorithm and seed.
654 /// It returns the fastest `Rng` algorithm currently available in Rust without
655 /// consideration for cryptography or security. If you require a specifically
656 /// seeded `Rng` for consistency over time you should pick one algorithm and
657 /// create the `Rng` yourself.
658 pub fn weak_rng() -> XorShiftRng {
662 static RAND_SIZE_LEN: u32 = 8;
663 static RAND_SIZE: u32 = 1 << RAND_SIZE_LEN;
665 /// A random number generator that uses the [ISAAC
666 /// algorithm](http://en.wikipedia.org/wiki/ISAAC_%28cipher%29).
668 /// The ISAAC algorithm is suitable for cryptographic purposes.
669 pub struct IsaacRng {
671 priv rsl: [u32, .. RAND_SIZE],
672 priv mem: [u32, .. RAND_SIZE],
679 /// Create an ISAAC random number generator with a random seed.
680 pub fn new() -> IsaacRng {
681 IsaacRng::new_seeded(seed())
684 /// Create an ISAAC random number generator with a seed. This can be any
685 /// length, although the maximum number of bytes used is 1024 and any more
686 /// will be silently ignored. A generator constructed with a given seed
687 /// will generate the same sequence of values as all other generators
688 /// constructed with the same seed.
689 pub fn new_seeded(seed: &[u8]) -> IsaacRng {
690 let mut rng = IsaacRng {
692 rsl: [0, .. RAND_SIZE],
693 mem: [0, .. RAND_SIZE],
697 let array_size = sys::size_of_val(&rng.rsl);
698 let copy_length = cmp::min(array_size, seed.len());
700 // manually create a &mut [u8] slice of randrsl to copy into.
701 let dest = unsafe { cast::transmute((&mut rng.rsl, array_size)) };
702 vec::bytes::copy_memory(dest, seed, copy_length);
707 /// Create an ISAAC random number generator using the default
709 pub fn new_unseeded() -> IsaacRng {
710 let mut rng = IsaacRng {
712 rsl: [0, .. RAND_SIZE],
713 mem: [0, .. RAND_SIZE],
720 /// Initialises `self`. If `use_rsl` is true, then use the current value
721 /// of `rsl` as a seed, otherwise construct one algorithmically (not
723 fn init(&mut self, use_rsl: bool) {
724 let mut a = 0x9e3779b9;
735 a^=b<<11; d+=a; b+=c;
738 d^=e>>16; g+=d; e+=f;
739 e^=f<<10; h+=e; f+=g;
746 do 4.times { mix!(); }
749 macro_rules! memloop (
751 for i in range_step(0u32, RAND_SIZE, 8) {
752 a+=$arr[i ]; b+=$arr[i+1];
753 c+=$arr[i+2]; d+=$arr[i+3];
754 e+=$arr[i+4]; f+=$arr[i+5];
755 g+=$arr[i+6]; h+=$arr[i+7];
757 self.mem[i ]=a; self.mem[i+1]=b;
758 self.mem[i+2]=c; self.mem[i+3]=d;
759 self.mem[i+4]=e; self.mem[i+5]=f;
760 self.mem[i+6]=g; self.mem[i+7]=h;
768 for i in range_step(0u32, RAND_SIZE, 8) {
770 self.mem[i ]=a; self.mem[i+1]=b;
771 self.mem[i+2]=c; self.mem[i+3]=d;
772 self.mem[i+4]=e; self.mem[i+5]=f;
773 self.mem[i+6]=g; self.mem[i+7]=h;
780 /// Refills the output buffer (`self.rsl`)
782 fn isaac(&mut self) {
786 let mut b = self.b + self.c;
788 static MIDPOINT: uint = RAND_SIZE as uint / 2;
790 macro_rules! ind (($x:expr) => {
791 self.mem[($x >> 2) & (RAND_SIZE - 1)]
793 macro_rules! rngstep(
794 ($j:expr, $shift:expr) => {{
796 let mix = if $shift < 0 {
802 let x = self.mem[base + mr_offset];
803 a = (a ^ mix) + self.mem[base + m2_offset];
804 let y = ind!(x) + a + b;
805 self.mem[base + mr_offset] = y;
807 b = ind!(y >> RAND_SIZE_LEN) + x;
808 self.rsl[base + mr_offset] = b;
812 let r = [(0, MIDPOINT), (MIDPOINT, 0)];
813 for &(mr_offset, m2_offset) in r.iter() {
814 for i in range_step(0u, MIDPOINT, 4) {
818 rngstep!(i + 3, -16);
824 self.cnt = RAND_SIZE;
828 impl Rng for IsaacRng {
830 fn next(&mut self) -> u32 {
832 // make some more numbers
840 /// An [Xorshift random number
841 /// generator](http://en.wikipedia.org/wiki/Xorshift).
843 /// The Xorshift algorithm is not suitable for cryptographic purposes
844 /// but is very fast. If you do not know for sure that it fits your
845 /// requirements, use a more secure one such as `IsaacRng`.
846 pub struct XorShiftRng {
853 impl Rng for XorShiftRng {
855 fn next(&mut self) -> u32 {
857 let t = x ^ (x << 11);
862 self.w = w ^ (w >> 19) ^ (t ^ (t >> 8));
868 /// Create an xor shift random number generator with a random seed.
869 pub fn new() -> XorShiftRng {
870 #[fixed_stack_segment]; #[inline(never)];
872 // generate seeds the same way as seed(), except we have a spceific size
873 let mut s = [0u8, ..16];
875 do s.as_mut_buf |p, sz| {
877 rustrt::rand_gen_seed(p, sz as size_t);
880 if !s.iter().all(|x| *x == 0) {
884 let s: &[u32, ..4] = unsafe { cast::transmute(&s) };
885 XorShiftRng::new_seeded(s[0], s[1], s[2], s[3])
889 * Create a random number generator using the specified seed. A generator
890 * constructed with a given seed will generate the same sequence of values
891 * as all other generators constructed with the same seed.
893 pub fn new_seeded(x: u32, y: u32, z: u32, w: u32) -> XorShiftRng {
903 /// Create a new random seed.
904 pub fn seed() -> ~[u8] {
905 #[fixed_stack_segment]; #[inline(never)];
908 let n = rustrt::rand_seed_size() as uint;
909 let mut s = vec::from_elem(n, 0_u8);
910 do s.as_mut_buf |p, sz| {
911 rustrt::rand_gen_seed(p, sz as size_t)
917 // used to make space in TLS for a random number generator
918 local_data_key!(tls_rng_state: @@mut IsaacRng)
921 * Gives back a lazily initialized task-local random number generator,
922 * seeded by the system. Intended to be used in method chaining style, ie
923 * `task_rng().gen::<int>()`.
926 pub fn task_rng() -> @mut IsaacRng {
927 let r = local_data::get(tls_rng_state, |k| k.map(|&k| *k));
930 let rng = @@mut IsaacRng::new_seeded(seed());
931 local_data::set(tls_rng_state, rng);
938 // Allow direct chaining with `task_rng`
939 impl<R: Rng> Rng for @mut R {
941 fn next(&mut self) -> u32 {
947 * Returns a random value of a Rand type, using the task's random number
951 pub fn random<T: Rand>() -> T {
957 use iter::{Iterator, range};
958 use option::{Option, Some};
962 fn test_rng_seeded() {
964 let mut ra = IsaacRng::new_seeded(seed);
965 let mut rb = IsaacRng::new_seeded(seed);
966 assert_eq!(ra.gen_str(100u), rb.gen_str(100u));
970 fn test_rng_seeded_custom_seed() {
971 // much shorter than generated seeds which are 1024 bytes
972 let seed = [2u8, 32u8, 4u8, 32u8, 51u8];
973 let mut ra = IsaacRng::new_seeded(seed);
974 let mut rb = IsaacRng::new_seeded(seed);
975 assert_eq!(ra.gen_str(100u), rb.gen_str(100u));
979 fn test_rng_seeded_custom_seed2() {
980 let seed = [2u8, 32u8, 4u8, 32u8, 51u8];
981 let mut ra = IsaacRng::new_seeded(seed);
982 // Regression test that isaac is actually using the above vector
985 assert!(r == 890007737u32 // on x86_64
986 || r == 2935188040u32); // on x86
990 fn test_gen_int_range() {
992 let a = r.gen_int_range(-3, 42);
993 assert!(a >= -3 && a < 42);
994 assert_eq!(r.gen_int_range(0, 1), 0);
995 assert_eq!(r.gen_int_range(-12, -11), -12);
1000 fn test_gen_int_from_fail() {
1002 r.gen_int_range(5, -2);
1006 fn test_gen_uint_range() {
1008 let a = r.gen_uint_range(3u, 42u);
1009 assert!(a >= 3u && a < 42u);
1010 assert_eq!(r.gen_uint_range(0u, 1u), 0u);
1011 assert_eq!(r.gen_uint_range(12u, 13u), 12u);
1016 fn test_gen_uint_range_fail() {
1018 r.gen_uint_range(5u, 2u);
1022 fn test_gen_float() {
1024 let a = r.gen::<float>();
1025 let b = r.gen::<float>();
1030 fn test_gen_weighted_bool() {
1032 assert_eq!(r.gen_weighted_bool(0u), true);
1033 assert_eq!(r.gen_weighted_bool(1u), true);
1039 debug!(r.gen_str(10u));
1040 debug!(r.gen_str(10u));
1041 debug!(r.gen_str(10u));
1042 assert_eq!(r.gen_str(0u).len(), 0u);
1043 assert_eq!(r.gen_str(10u).len(), 10u);
1044 assert_eq!(r.gen_str(16u).len(), 16u);
1048 fn test_gen_bytes() {
1050 assert_eq!(r.gen_bytes(0u).len(), 0u);
1051 assert_eq!(r.gen_bytes(10u).len(), 10u);
1052 assert_eq!(r.gen_bytes(16u).len(), 16u);
1058 assert_eq!(r.choose([1, 1, 1]), 1);
1062 fn test_choose_option() {
1064 let x: Option<int> = r.choose_option([]);
1065 assert!(x.is_none());
1066 assert_eq!(r.choose_option([1, 1, 1]), Some(1));
1070 fn test_choose_weighted() {
1072 assert!(r.choose_weighted([
1073 Weighted { weight: 1u, item: 42 },
1075 assert!(r.choose_weighted([
1076 Weighted { weight: 0u, item: 42 },
1077 Weighted { weight: 1u, item: 43 },
1082 fn test_choose_weighted_option() {
1084 assert!(r.choose_weighted_option([
1085 Weighted { weight: 1u, item: 42 },
1087 assert!(r.choose_weighted_option([
1088 Weighted { weight: 0u, item: 42 },
1089 Weighted { weight: 1u, item: 43 },
1091 let v: Option<int> = r.choose_weighted_option([]);
1092 assert!(v.is_none());
1096 fn test_weighted_vec() {
1098 let empty: ~[int] = ~[];
1099 assert_eq!(r.weighted_vec([]), empty);
1100 assert!(r.weighted_vec([
1101 Weighted { weight: 0u, item: 3u },
1102 Weighted { weight: 1u, item: 2u },
1103 Weighted { weight: 2u, item: 1u },
1104 ]) == ~[2u, 1u, 1u]);
1110 let empty: ~[int] = ~[];
1111 assert_eq!(r.shuffle([]), empty);
1112 assert_eq!(r.shuffle([1, 1, 1]), ~[1, 1, 1]);
1116 fn test_task_rng() {
1117 let mut r = task_rng();
1119 assert_eq!(r.shuffle([1, 1, 1]), ~[1, 1, 1]);
1120 assert_eq!(r.gen_uint_range(0u, 1u), 0u);
1125 // not sure how to test this aside from just getting some values
1126 let _n : uint = random();
1127 let _f : f32 = random();
1128 let _o : Option<Option<i8>> = random();
1130 (~uint, @int, ~Option<~(@u32, ~(@bool,))>),
1131 (u8, i8, u16, i16, u32, i32, u64, i64),
1132 (f32, (f64, (float,)))) = random();
1136 fn compare_isaac_implementation() {
1137 #[fixed_stack_segment]; #[inline(never)];
1139 // This is to verify that the implementation of the ISAAC rng is
1140 // correct (i.e. matches the output of the upstream implementation,
1141 // which is in the runtime)
1148 #[allow(non_camel_case_types)] // runtime type
1149 pub enum rust_rng {}
1152 pub fn rand_new_seeded(buf: *u8, sz: size_t) -> *rust_rng;
1153 pub fn rand_next(rng: *rust_rng) -> u32;
1154 pub fn rand_free(rng: *rust_rng);
1158 // run against several seeds
1161 let seed = super::seed();
1162 let rt_rng = do seed.as_imm_buf |p, sz| {
1163 rustrt::rand_new_seeded(p, sz as size_t)
1165 let mut rng = IsaacRng::new_seeded(seed);
1168 assert_eq!(rng.next(), rustrt::rand_next(rt_rng));
1170 rustrt::rand_free(rt_rng);
1181 let vals = range(MIN_VAL, MAX_VAL).to_owned_vec();
1182 let small_sample = r.sample(vals.iter(), 5);
1183 let large_sample = r.sample(vals.iter(), vals.len() + 5);
1185 assert_eq!(small_sample.len(), 5);
1186 assert_eq!(large_sample.len(), vals.len());
1188 assert!(small_sample.iter().all(|e| {
1189 **e >= MIN_VAL && **e <= MAX_VAL
1196 use extra::test::BenchHarness;
1201 fn rand_xorshift(bh: &mut BenchHarness) {
1202 let mut rng = XorShiftRng::new();
1206 bh.bytes = size_of::<uint>() as u64;
1210 fn rand_isaac(bh: &mut BenchHarness) {
1211 let mut rng = IsaacRng::new();
1215 bh.bytes = size_of::<uint>() as u64;
1219 fn rand_shuffle_100(bh: &mut BenchHarness) {
1220 let mut rng = XorShiftRng::new();
1221 let x : &mut[uint] = [1,..100];