auto merge of #13177 : huonw/rust/devec-rand, r=alexcrichton

Remove ~[] from librand, rename Rng.shuffle_mut to .shuffle.

See commits.
This commit is contained in:
bors 2014-04-02 06:01:44 -07:00
commit 21273d52f5
10 changed files with 127 additions and 123 deletions

View File

@ -112,7 +112,7 @@ mod tests {
for _ in range(0, 20) {
let mut input = ~[];
for _ in range(0, 2000) {
input.push_all(r.choose(words.as_slice()));
input.push_all(r.choose(words.as_slice()).as_slice());
}
debug!("de/inflate of {} bytes of random word-sequences",
input.len());

View File

@ -91,9 +91,9 @@ pub struct Weighted<T> {
/// ```rust
/// use rand::distributions::{Weighted, WeightedChoice, IndependentSample};
///
/// let wc = WeightedChoice::new(~[Weighted { weight: 2, item: 'a' },
/// Weighted { weight: 4, item: 'b' },
/// Weighted { weight: 1, item: 'c' }]);
/// let wc = WeightedChoice::new(vec!(Weighted { weight: 2, item: 'a' },
/// Weighted { weight: 4, item: 'b' },
/// Weighted { weight: 1, item: 'c' }));
/// let mut rng = rand::task_rng();
/// for _ in range(0, 16) {
/// // on average prints 'a' 4 times, 'b' 8 and 'c' twice.
@ -101,8 +101,8 @@ pub struct Weighted<T> {
/// }
/// ```
pub struct WeightedChoice<T> {
pub items: ~[Weighted<T>],
pub weight_range: Range<uint>
items: Vec<Weighted<T>>,
weight_range: Range<uint>
}
impl<T: Clone> WeightedChoice<T> {
@ -112,7 +112,7 @@ impl<T: Clone> WeightedChoice<T> {
/// - `v` is empty
/// - the total weight is 0
/// - the total weight is larger than a `uint` can contain.
pub fn new(mut items: ~[Weighted<T>]) -> WeightedChoice<T> {
pub fn new(mut items: Vec<Weighted<T>>) -> WeightedChoice<T> {
// strictly speaking, this is subsumed by the total weight == 0 case
assert!(!items.is_empty(), "WeightedChoice::new called with no items");
@ -153,8 +153,8 @@ impl<T: Clone> IndependentSample<T> for WeightedChoice<T> {
let sample_weight = self.weight_range.ind_sample(rng);
// short circuit when it's the first item
if sample_weight < self.items[0].weight {
return self.items[0].item.clone();
if sample_weight < self.items.get(0).weight {
return self.items.get(0).item.clone();
}
let mut idx = 0;
@ -169,7 +169,7 @@ impl<T: Clone> IndependentSample<T> for WeightedChoice<T> {
// one is exactly the total weight.)
while modifier > 1 {
let i = idx + modifier / 2;
if self.items[i].weight <= sample_weight {
if self.items.get(i).weight <= sample_weight {
// we're small, so look to the right, but allow this
// exact element still.
idx = i;
@ -182,7 +182,7 @@ impl<T: Clone> IndependentSample<T> for WeightedChoice<T> {
}
modifier /= 2;
}
return self.items[idx + 1].item.clone();
return self.items.get(idx + 1).item.clone();
}
}
@ -297,54 +297,54 @@ mod tests {
}}
);
t!(~[Weighted { weight: 1, item: 10}], ~[10]);
t!(vec!(Weighted { weight: 1, item: 10}), [10]);
// skip some
t!(~[Weighted { weight: 0, item: 20},
Weighted { weight: 2, item: 21},
Weighted { weight: 0, item: 22},
Weighted { weight: 1, item: 23}],
~[21,21, 23]);
t!(vec!(Weighted { weight: 0, item: 20},
Weighted { weight: 2, item: 21},
Weighted { weight: 0, item: 22},
Weighted { weight: 1, item: 23}),
[21,21, 23]);
// different weights
t!(~[Weighted { weight: 4, item: 30},
Weighted { weight: 3, item: 31}],
~[30,30,30,30, 31,31,31]);
t!(vec!(Weighted { weight: 4, item: 30},
Weighted { weight: 3, item: 31}),
[30,30,30,30, 31,31,31]);
// check that we're binary searching
// correctly with some vectors of odd
// length.
t!(~[Weighted { weight: 1, item: 40},
Weighted { weight: 1, item: 41},
Weighted { weight: 1, item: 42},
Weighted { weight: 1, item: 43},
Weighted { weight: 1, item: 44}],
~[40, 41, 42, 43, 44]);
t!(~[Weighted { weight: 1, item: 50},
Weighted { weight: 1, item: 51},
Weighted { weight: 1, item: 52},
Weighted { weight: 1, item: 53},
Weighted { weight: 1, item: 54},
Weighted { weight: 1, item: 55},
Weighted { weight: 1, item: 56}],
~[50, 51, 52, 53, 54, 55, 56]);
t!(vec!(Weighted { weight: 1, item: 40},
Weighted { weight: 1, item: 41},
Weighted { weight: 1, item: 42},
Weighted { weight: 1, item: 43},
Weighted { weight: 1, item: 44}),
[40, 41, 42, 43, 44]);
t!(vec!(Weighted { weight: 1, item: 50},
Weighted { weight: 1, item: 51},
Weighted { weight: 1, item: 52},
Weighted { weight: 1, item: 53},
Weighted { weight: 1, item: 54},
Weighted { weight: 1, item: 55},
Weighted { weight: 1, item: 56}),
[50, 51, 52, 53, 54, 55, 56]);
}
#[test] #[should_fail]
fn test_weighted_choice_no_items() {
WeightedChoice::<int>::new(~[]);
WeightedChoice::<int>::new(vec!());
}
#[test] #[should_fail]
fn test_weighted_choice_zero_weight() {
WeightedChoice::new(~[Weighted { weight: 0, item: 0},
Weighted { weight: 0, item: 1}]);
WeightedChoice::new(vec!(Weighted { weight: 0, item: 0},
Weighted { weight: 0, item: 1}));
}
#[test] #[should_fail]
fn test_weighted_choice_weight_overflows() {
let x = (-1) as uint / 2; // x + x + 2 is the overflow
WeightedChoice::new(~[Weighted { weight: x, item: 0 },
Weighted { weight: 1, item: 1 },
Weighted { weight: x, item: 2 },
Weighted { weight: 1, item: 3 }]);
WeightedChoice::new(vec!(Weighted { weight: x, item: 0 },
Weighted { weight: 1, item: 1 },
Weighted { weight: x, item: 2 },
Weighted { weight: 1, item: 3 }));
}
}

View File

@ -441,7 +441,6 @@ impl<'a> SeedableRng<&'a [u64]> for Isaac64Rng {
mod test {
use super::{IsaacRng, Isaac64Rng};
use {Rng, SeedableRng, task_rng};
use std::slice;
#[test]
fn test_rng_32_rand_seeded() {
@ -479,7 +478,7 @@ mod test {
let mut r: IsaacRng = SeedableRng::from_seed(s.as_slice());
let string1 = r.gen_ascii_str(100);
r.reseed(s);
r.reseed(s.as_slice());
let string2 = r.gen_ascii_str(100);
assert_eq!(string1, string2);
@ -490,7 +489,7 @@ mod test {
let mut r: Isaac64Rng = SeedableRng::from_seed(s.as_slice());
let string1 = r.gen_ascii_str(100);
r.reseed(s);
r.reseed(s.as_slice());
let string2 = r.gen_ascii_str(100);
assert_eq!(string1, string2);
@ -501,43 +500,43 @@ mod test {
let seed = &[1, 23, 456, 7890, 12345];
let mut ra: IsaacRng = SeedableRng::from_seed(seed);
// Regression test that isaac is actually using the above vector
let v = slice::from_fn(10, |_| ra.next_u32());
let v = Vec::from_fn(10, |_| ra.next_u32());
assert_eq!(v,
~[2558573138, 873787463, 263499565, 2103644246, 3595684709,
4203127393, 264982119, 2765226902, 2737944514, 3900253796]);
vec!(2558573138, 873787463, 263499565, 2103644246, 3595684709,
4203127393, 264982119, 2765226902, 2737944514, 3900253796));
let seed = &[12345, 67890, 54321, 9876];
let mut rb: IsaacRng = SeedableRng::from_seed(seed);
// skip forward to the 10000th number
for _ in range(0, 10000) { rb.next_u32(); }
let v = slice::from_fn(10, |_| rb.next_u32());
let v = Vec::from_fn(10, |_| rb.next_u32());
assert_eq!(v,
~[3676831399, 3183332890, 2834741178, 3854698763, 2717568474,
1576568959, 3507990155, 179069555, 141456972, 2478885421]);
vec!(3676831399, 3183332890, 2834741178, 3854698763, 2717568474,
1576568959, 3507990155, 179069555, 141456972, 2478885421));
}
#[test]
fn test_rng_64_true_values() {
let seed = &[1, 23, 456, 7890, 12345];
let mut ra: Isaac64Rng = SeedableRng::from_seed(seed);
// Regression test that isaac is actually using the above vector
let v = slice::from_fn(10, |_| ra.next_u64());
let v = Vec::from_fn(10, |_| ra.next_u64());
assert_eq!(v,
~[547121783600835980, 14377643087320773276, 17351601304698403469,
1238879483818134882, 11952566807690396487, 13970131091560099343,
4469761996653280935, 15552757044682284409, 6860251611068737823,
13722198873481261842]);
vec!(547121783600835980, 14377643087320773276, 17351601304698403469,
1238879483818134882, 11952566807690396487, 13970131091560099343,
4469761996653280935, 15552757044682284409, 6860251611068737823,
13722198873481261842));
let seed = &[12345, 67890, 54321, 9876];
let mut rb: Isaac64Rng = SeedableRng::from_seed(seed);
// skip forward to the 10000th number
for _ in range(0, 10000) { rb.next_u64(); }
let v = slice::from_fn(10, |_| rb.next_u64());
let v = Vec::from_fn(10, |_| rb.next_u64());
assert_eq!(v,
~[18143823860592706164, 8491801882678285927, 2699425367717515619,
17196852593171130876, 2606123525235546165, 15790932315217671084,
596345674630742204, 9947027391921273664, 11788097613744130851,
10391409374914919106]);
vec!(18143823860592706164, 8491801882678285927, 2699425367717515619,
17196852593171130876, 2606123525235546165, 15790932315217671084,
596345674630742204, 9947027391921273664, 11788097613744130851,
10391409374914919106));
}
}

View File

@ -73,6 +73,7 @@ println!("{:?}", tuple_ptr)
#![feature(macro_rules, managed_boxes, phase)]
#![allow(visible_private_types)] // NOTE: remove after a stage0 snap
#![deny(deprecated_owned_vector)]
#[cfg(test)]
#[phase(syntax, link)] extern crate log;
@ -82,7 +83,6 @@ use std::io::IoResult;
use std::kinds::marker;
use std::local_data;
use std::str;
use std::slice;
pub use isaac::{IsaacRng, Isaac64Rng};
pub use os::OSRng;
@ -199,12 +199,12 @@ pub trait Rng {
/// use rand::{task_rng, Rng};
///
/// let mut rng = task_rng();
/// let x: ~[uint] = rng.gen_vec(10);
/// println!("{:?}", x);
/// println!("{:?}", rng.gen_vec::<(f64, bool)>(5));
/// let x: Vec<uint> = rng.gen_vec(10);
/// println!("{}", x);
/// println!("{}", rng.gen_vec::<(f64, bool)>(5));
/// ```
fn gen_vec<T: Rand>(&mut self, len: uint) -> ~[T] {
slice::from_fn(len, |_| self.gen())
fn gen_vec<T: Rand>(&mut self, len: uint) -> Vec<T> {
Vec::from_fn(len, |_| self.gen())
}
/// Generate a random value in the range [`low`, `high`). Fails if
@ -293,22 +293,7 @@ pub trait Rng {
}
}
/// Shuffle a vec
///
/// # Example
///
/// ```rust
/// use rand::{task_rng, Rng};
///
/// println!("{:?}", task_rng().shuffle(~[1,2,3]));
/// ```
fn shuffle<T>(&mut self, values: ~[T]) -> ~[T] {
let mut v = values;
self.shuffle_mut(v);
v
}
/// Shuffle a mutable vector in place.
/// Shuffle a mutable slice in place.
///
/// # Example
///
@ -317,12 +302,12 @@ pub trait Rng {
///
/// let mut rng = task_rng();
/// let mut y = [1,2,3];
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// rng.shuffle_mut(y);
/// println!("{:?}", y);
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// rng.shuffle(y);
/// println!("{}", y.as_slice());
/// ```
fn shuffle_mut<T>(&mut self, values: &mut [T]) {
fn shuffle<T>(&mut self, values: &mut [T]) {
let mut i = values.len();
while i >= 2u {
// invariant: elements with index >= i have been locked in place.
@ -332,6 +317,12 @@ pub trait Rng {
}
}
/// Shuffle a mutable slice in place.
#[deprecated="renamed to `.shuffle`"]
fn shuffle_mut<T>(&mut self, values: &mut [T]) {
self.shuffle(values)
}
/// Randomly sample up to `n` elements from an iterator.
///
/// # Example
@ -341,10 +332,10 @@ pub trait Rng {
///
/// let mut rng = task_rng();
/// let sample = rng.sample(range(1, 100), 5);
/// println!("{:?}", sample);
/// println!("{}", sample);
/// ```
fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> ~[A] {
let mut reservoir : ~[A] = slice::with_capacity(n);
fn sample<A, T: Iterator<A>>(&mut self, iter: T, n: uint) -> Vec<A> {
let mut reservoir = Vec::with_capacity(n);
for (i, elem) in iter.enumerate() {
if i < n {
reservoir.push(elem);
@ -353,7 +344,7 @@ pub trait Rng {
let k = self.gen_range(0, i + 1);
if k < reservoir.len() {
reservoir[k] = elem
*reservoir.get_mut(k) = elem
}
}
reservoir
@ -695,7 +686,6 @@ pub struct Closed01<F>(F);
#[cfg(test)]
mod test {
use std::slice;
use super::{Rng, task_rng, random, SeedableRng, StdRng};
struct ConstRng { i: u64 }
@ -714,8 +704,8 @@ mod test {
let lengths = [0, 1, 2, 3, 4, 5, 6, 7,
80, 81, 82, 83, 84, 85, 86, 87];
for &n in lengths.iter() {
let mut v = slice::from_elem(n, 0u8);
r.fill_bytes(v);
let mut v = Vec::from_elem(n, 0u8);
r.fill_bytes(v.as_mut_slice());
// use this to get nicer error messages.
for (i, &byte) in v.iter().enumerate() {
@ -813,16 +803,28 @@ mod test {
#[test]
fn test_shuffle() {
let mut r = task_rng();
let empty: ~[int] = ~[];
assert_eq!(r.shuffle(~[]), empty);
assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]);
let mut empty: &mut [int] = &mut [];
r.shuffle(empty);
let mut one = [1];
r.shuffle(one);
assert_eq!(one.as_slice(), &[1]);
let mut two = [1, 2];
r.shuffle(two);
assert!(two == [1, 2] || two == [2, 1]);
let mut x = [1, 1, 1];
r.shuffle(x);
assert_eq!(x.as_slice(), &[1, 1, 1]);
}
#[test]
fn test_task_rng() {
let mut r = task_rng();
r.gen::<int>();
assert_eq!(r.shuffle(~[1, 1, 1]), ~[1, 1, 1]);
let mut v = [1, 1, 1];
r.shuffle(v);
assert_eq!(v.as_slice(), &[1, 1, 1]);
assert_eq!(r.gen_range(0u, 1u), 0u);
}
@ -844,7 +846,7 @@ mod test {
let max_val = 100;
let mut r = task_rng();
let vals = range(min_val, max_val).collect::<~[int]>();
let vals = range(min_val, max_val).collect::<Vec<int>>();
let small_sample = r.sample(vals.iter(), 5);
let large_sample = r.sample(vals.iter(), vals.len() + 5);
@ -870,7 +872,7 @@ mod test {
let mut r: StdRng = SeedableRng::from_seed(s.as_slice());
let string1 = r.gen_ascii_str(100);
r.reseed(s);
r.reseed(s.as_slice());
let string2 = r.gen_ascii_str(100);
assert_eq!(string1, string2);
@ -936,7 +938,7 @@ mod bench {
let mut rng = XorShiftRng::new().unwrap();
let x : &mut[uint] = [1,..100];
bh.iter(|| {
rng.shuffle_mut(x);
rng.shuffle(x);
})
}
}

View File

@ -204,7 +204,7 @@ mod test {
#[test]
fn test_os_rng_tasks() {
let mut txs = ~[];
let mut txs = vec!();
for _ in range(0, 20) {
let (tx, rx) = channel();
txs.push(tx);

View File

@ -68,6 +68,7 @@ impl<R: Reader> Rng for ReaderRng<R> {
}
#[cfg(test)]
#[allow(deprecated_owned_vector)]
mod test {
use super::ReaderRng;
use std::io::MemReader;

View File

@ -205,8 +205,8 @@ mod test {
#[test]
fn test_rng_fill_bytes() {
use task_rng;
let mut v = ~[0u8, .. fill_bytes_v_len];
task_rng().fill_bytes(v);
let mut v = Vec::from_elem(fill_bytes_v_len, 0u8);
task_rng().fill_bytes(v.as_mut_slice());
// Sanity test: if we've gotten here, `fill_bytes` has not infinitely
// recursed.

View File

@ -3442,19 +3442,21 @@ mod tests {
#[test]
fn test_sort() {
use realstd::slice::Vector;
use realstd::clone::Clone;
for len in range(4u, 25) {
for _ in range(0, 100) {
let mut v = task_rng().gen_vec::<uint>(len);
let mut v1 = v.clone();
v.sort();
assert!(v.windows(2).all(|w| w[0] <= w[1]));
v.as_mut_slice().sort();
assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
v1.sort_by(|a, b| a.cmp(b));
assert!(v1.windows(2).all(|w| w[0] <= w[1]));
v1.as_mut_slice().sort_by(|a, b| a.cmp(b));
assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
v1.sort_by(|a, b| b.cmp(a));
assert!(v1.windows(2).all(|w| w[0] >= w[1]));
v1.as_mut_slice().sort_by(|a, b| b.cmp(a));
assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
}
}
@ -4487,8 +4489,8 @@ mod bench {
fn sort_random_small(bh: &mut BenchHarness) {
let mut rng = weak_rng();
bh.iter(|| {
let mut v: ~[u64] = rng.gen_vec(5);
v.sort();
let mut v = rng.gen_vec::<u64>(5);
v.as_mut_slice().sort();
});
bh.bytes = 5 * mem::size_of::<u64>() as u64;
}
@ -4497,8 +4499,8 @@ mod bench {
fn sort_random_medium(bh: &mut BenchHarness) {
let mut rng = weak_rng();
bh.iter(|| {
let mut v: ~[u64] = rng.gen_vec(100);
v.sort();
let mut v = rng.gen_vec::<u64>(100);
v.as_mut_slice().sort();
});
bh.bytes = 100 * mem::size_of::<u64>() as u64;
}
@ -4507,8 +4509,8 @@ mod bench {
fn sort_random_large(bh: &mut BenchHarness) {
let mut rng = weak_rng();
bh.iter(|| {
let mut v: ~[u64] = rng.gen_vec(10000);
v.sort();
let mut v = rng.gen_vec::<u64>(10000);
v.as_mut_slice().sort();
});
bh.bytes = 10000 * mem::size_of::<u64>() as u64;
}
@ -4528,7 +4530,7 @@ mod bench {
fn sort_big_random_small(bh: &mut BenchHarness) {
let mut rng = weak_rng();
bh.iter(|| {
let mut v: ~[BigSortable] = rng.gen_vec(5);
let mut v = rng.gen_vec::<BigSortable>(5);
v.sort();
});
bh.bytes = 5 * mem::size_of::<BigSortable>() as u64;
@ -4538,7 +4540,7 @@ mod bench {
fn sort_big_random_medium(bh: &mut BenchHarness) {
let mut rng = weak_rng();
bh.iter(|| {
let mut v: ~[BigSortable] = rng.gen_vec(100);
let mut v = rng.gen_vec::<BigSortable>(100);
v.sort();
});
bh.bytes = 100 * mem::size_of::<BigSortable>() as u64;
@ -4548,7 +4550,7 @@ mod bench {
fn sort_big_random_large(bh: &mut BenchHarness) {
let mut rng = weak_rng();
bh.iter(|| {
let mut v: ~[BigSortable] = rng.gen_vec(10000);
let mut v = rng.gen_vec::<BigSortable>(10000);
v.sort();
});
bh.bytes = 10000 * mem::size_of::<BigSortable>() as u64;

View File

@ -196,7 +196,7 @@ impl Uuid {
pub fn new_v4() -> Uuid {
let ub = rand::task_rng().gen_vec(16);
let mut uuid = Uuid{ bytes: [0, .. 16] };
slice::bytes::copy_memory(uuid.bytes, ub);
slice::bytes::copy_memory(uuid.bytes, ub.as_slice());
uuid.set_variant(VariantRFC4122);
uuid.set_version(Version4Random);
uuid
@ -510,7 +510,7 @@ impl rand::Rand for Uuid {
fn rand<R: rand::Rng>(rng: &mut R) -> Uuid {
let ub = rng.gen_vec(16);
let mut uuid = Uuid{ bytes: [0, .. 16] };
slice::bytes::copy_memory(uuid.bytes, ub);
slice::bytes::copy_memory(uuid.bytes, ub.as_slice());
uuid.set_variant(VariantRFC4122);
uuid.set_version(Version4Random);
uuid

View File

@ -52,7 +52,7 @@ pub fn main() {
// work out the total number of comparisons required to sort
// this array...
let mut count = 0;
main.clone().sort_by(|a, b| { count += 1; a.cmp(b) });
main.clone().as_mut_slice().sort_by(|a, b| { count += 1; a.cmp(b) });
// ... and then fail on each and every single one.
for fail_countdown in range(0, count) {
@ -67,7 +67,7 @@ pub fn main() {
task::try(proc() {
let mut v = v;
let mut fail_countdown = fail_countdown;
v.sort_by(|a, b| {
v.as_mut_slice().sort_by(|a, b| {
if fail_countdown == 0 {
fail!()
}