#![cfg(feature="std-vec")]
use slice::SliceFind;
pub fn vec<I>(iterable: I) -> Vec<I::Item>
where I: IntoIterator
{
iterable.into_iter().collect()
}
pub trait VecExt<T> {
fn retain_mut<F>(&mut self, f: F)
where F: FnMut(&mut T) -> bool;
}
impl<T> VecExt<T> for Vec<T> {
fn retain_mut<F>(&mut self, mut f: F)
where F: FnMut(&mut T) -> bool
{
let len = self.len();
let mut del = 0;
{
let v = &mut **self;
for i in 0..len {
if !f(&mut v[i]) {
del += 1;
} else if del > 0 {
v.swap(i - del, i);
}
}
}
if del > 0 {
self.truncate(len - del);
}
}
}
pub trait VecFindRemove {
type Item;
fn find_remove<U>(&mut self, elt: &U) -> Option<(usize, Self::Item)>
where Self::Item: PartialEq<U>;
fn rfind_remove<U>(&mut self, elt: &U) -> Option<(usize, Self::Item)>
where Self::Item: PartialEq<U>;
}
impl<T> VecFindRemove for Vec<T> {
type Item = T;
fn find_remove<U>(&mut self, elt: &U) -> Option<(usize, Self::Item)>
where Self::Item: PartialEq<U>
{
self.find(elt).map(|i| (i, self.remove(i)))
}
fn rfind_remove<U>(&mut self, elt: &U) -> Option<(usize, Self::Item)>
where Self::Item: PartialEq<U>
{
self.rfind(elt).map(|i| (i, self.remove(i)))
}
}
#[test]
fn test_find() {
let mut v = vec![0, 1, 2, 3, 1, 2, 1];
assert_eq!(v.rfind_remove(&1), Some((6, 1)));
assert_eq!(v.find_remove(&2), Some((2, 2)));
assert_eq!(v.find_remove(&7), None);
assert_eq!(&v, &[0, 1, 3, 1, 2]);
}