utils/vec.rs
1//!
2//! vec.rs
3//!
4//! Created by Mitchell Nordine at 01:25AM on November 18, 2014.
5//!
6//!
7
8
9/// Take only the elements that return `true` from the given condition.
10pub trait TakeOnly<T> {
11 /// Take only the elements that return `true` from the given condition.
12 fn take_only<F>(&mut self, F) -> Vec<T> where F: Fn(&T) -> bool;
13}
14
15impl<T> TakeOnly<T> for Vec<T> {
16 fn take_only<F>(&mut self, cond: F) -> Vec<T> where F: Fn(&T) -> bool {
17 let mut vec = Vec::with_capacity(self.len());
18 let mut i = 0;
19 while i < self.len() {
20 let cond_result = cond(&self[i]);
21 if cond_result {
22 vec.push(self.remove(i));
23 } else {
24 i += 1;
25 }
26 }
27 vec
28 }
29}
30