Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add retain function #59

Merged
merged 1 commit into from
Aug 21, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 57 additions & 0 deletions lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,24 @@ impl<A: Array> SmallVec<A> {
}
}
}

/// Retains only the elements specified by the predicate.
///
/// In other words, remove all elements `e` such that `f(&e)` returns `false`.
/// This method operates in place and preserves the order of the retained
/// elements.
pub fn retain<F: FnMut(&A::Item) -> bool>(&mut self, mut f: F) {
let mut del = 0;
let len = self.len;
for i in 0..len {
if !f(&self[i]) {
del += 1;
} else if del > 0 {
self.swap(i - del, i);
}
}
self.truncate(len - del);
}
}

impl<A: Array> SmallVec<A> where A::Item: Copy {
Expand Down Expand Up @@ -1059,6 +1077,10 @@ pub mod tests {
use std::borrow::ToOwned;
#[cfg(not(feature = "std"))]
use alloc::borrow::ToOwned;
#[cfg(feature = "std")]
use std::rc::Rc;
#[cfg(not(feature = "std"))]
use alloc::rc::Rc;
#[cfg(not(feature = "std"))]
use alloc::boxed::Box;
#[cfg(not(feature = "std"))]
Expand Down Expand Up @@ -1589,6 +1611,41 @@ pub mod tests {
drop(small_vec);
}

#[test]
fn test_retain() {
// Test inline data storate
let mut sv: SmallVec<[i32; 5]> = SmallVec::from_slice(&[1, 2, 3, 3, 4]);
sv.retain(|&i| i != 3);
assert_eq!(sv.pop(), Some(4));
assert_eq!(sv.pop(), Some(2));
assert_eq!(sv.pop(), Some(1));
assert_eq!(sv.pop(), None);

// Test spilled data storage
let mut sv: SmallVec<[i32; 3]> = SmallVec::from_slice(&[1, 2, 3, 3, 4]);
sv.retain(|&i| i != 3);
assert_eq!(sv.pop(), Some(4));
assert_eq!(sv.pop(), Some(2));
assert_eq!(sv.pop(), Some(1));
assert_eq!(sv.pop(), None);

// Test that drop implementations are called for inline.
let one = Rc::new(1);
let mut sv: SmallVec<[Rc<i32>; 3]> = SmallVec::new();
sv.push(Rc::clone(&one));
assert_eq!(Rc::strong_count(&one), 2);
sv.retain(|_| false);
assert_eq!(Rc::strong_count(&one), 1);

// Test that drop implementations are called for spilled data.
let mut sv: SmallVec<[Rc<i32>; 1]> = SmallVec::new();
sv.push(Rc::clone(&one));
sv.push(Rc::new(2));
assert_eq!(Rc::strong_count(&one), 2);
sv.retain(|_| false);
assert_eq!(Rc::strong_count(&one), 1);
}

#[cfg(feature = "std")]
#[test]
fn test_write() {
Expand Down