1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#![cfg_attr(test, feature(plugin))]
#![cfg_attr(test, plugin(clippy))]

#[cfg(test)]
#[macro_use]
extern crate quickcheck;

extern crate rand;
use rand::Rng;


/// Interface for randomly removing elements from a container.
pub trait RandPop: Sized {
    /// Type of the item that's removed from the container.
    type Item;

    /// Randomly removes an item from the container; does not necessarily preserve order.
    fn rand_pop<R: Rng>(&mut self, rng: &mut R) -> Option<Self::Item>;

    /// Randomly iterates through the items in this container, consuming the container.
    #[inline]
    fn rand_iter<R: Rng>(self, rng: &mut R) -> RandIter<Self, R> {
        RandIter {
            vals: self,
            rng: rng,
        }
    }
}

/// Iterator over a container that returns its items in random order.
pub struct RandIter<'a, C: RandPop, R: 'a + Rng> {
    vals: C,
    rng: &'a mut R,
}

impl<'a, C: RandPop, R: 'a + Rng> Iterator for RandIter<'a, C, R> {
    type Item = <C as RandPop>::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.vals.rand_pop(self.rng)
    }
}

impl<T> RandPop for Vec<T> {
    type Item = T;
    #[inline]
    fn rand_pop<R: Rng>(&mut self, rng: &mut R) -> Option<T> {
        match self.len() {
            0 => None,
            l => Some(self.swap_remove(rng.gen_range(0, l))),
        }
    }
}


#[cfg(test)]
mod tests {
    use rand;
    use super::*;

    quickcheck! {
        fn rand_pop(orig: Vec<usize>) -> bool {
            let mut from = orig.clone();
            let mut rng = rand::thread_rng();

            let mut to = Vec::new();
            while let Some(val) = from.rand_pop(&mut rng) {
                to.push(val);
            }
            to.sort();

            let mut orig = orig;
            orig.sort();

            return from.is_empty() && to == orig;
        }

        fn rand_iter(orig: Vec<usize>) -> bool {
            let from = orig.clone();
            let mut rng = rand::thread_rng();

            let mut to: Vec<usize> = from.rand_iter(&mut rng).collect();
            to.sort();

            let mut orig = orig;
            orig.sort();

            return to == orig;
        }
    }
}