Skip to main content

rstl_collection/
collection.rs

1use crate::dispose::Disposable;
2
3pub trait Collection: Disposable {
4    type Item;
5    type Iter<'a>: Iterator<Item = &'a Self::Item>
6    where
7        Self: 'a;
8
9    fn iter(&self) -> Self::Iter<'_>;
10    fn size(&self) -> usize;
11    fn clear(&mut self);
12    fn retain<F>(&mut self, f: F) -> usize
13    where
14        F: FnMut(&Self::Item) -> bool;
15
16    fn count<F>(&self, mut filter: F) -> usize
17    where
18        F: FnMut(&Self::Item) -> bool,
19    {
20        let mut count = 0usize;
21        for item in self.iter() {
22            if filter(item) {
23                count += 1;
24            }
25        }
26        count
27    }
28
29    fn collect_into<C>(&self, out: &mut C)
30    where
31        C: Extend<Self::Item>,
32        Self::Item: Clone,
33    {
34        out.extend(self.iter().cloned());
35    }
36
37    fn collect(&self) -> Vec<Self::Item>
38    where
39        Self::Item: Clone,
40    {
41        let mut out = Vec::with_capacity(self.size());
42        self.collect_into(&mut out);
43        out
44    }
45
46    fn is_empty(&self) -> bool {
47        self.size() == 0
48    }
49}