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

feat: support retain operation over binary heap #345

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
61 changes: 61 additions & 0 deletions src/binary_heap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,41 @@ where
}
}

/// Removes all elements from the binary heap that do not satisfy the predicate `f`.
/// The elements are visited in arbitrary order.
///
/// ```
/// use heapless::binary_heap::{BinaryHeap, Max};
///
/// let mut heap: BinaryHeap<_, Max, 8> = BinaryHeap::new();
/// heap.push(1).unwrap();
/// heap.push(2).unwrap();
/// heap.push(3).unwrap();
/// heap.push(4).unwrap();
///
/// heap.retain(|&x| x % 2 == 0);
///
/// let mut iter = heap.iter();
/// assert_eq!(iter.next(), Some(&4));
/// assert_eq!(iter.next(), Some(&2));
/// assert_eq!(iter.next(), None);
/// ```
pub fn retain(&mut self, mut f: impl FnMut(&T) -> bool) {
let mut del = 0;
let len = self.len();
{
let v = self.data.as_mut_slice();
for i in 0..len {
if !f(&v[i]) {
del += 1;
} else if del > 0 {
v.swap(i - del, i);
}
}
}
self.data.truncate(len - del);
}

/// Removes the *top* (greatest if max-heap, smallest if min-heap) item from the binary heap and
/// returns it, without checking if the binary heap is empty.
pub unsafe fn pop_unchecked(&mut self) -> T {
Expand Down Expand Up @@ -738,4 +773,30 @@ mod tests {
assert_eq!(heap.pop(), Some(1));
assert_eq!(heap.pop(), None);
}

#[test]
fn retain() {
let mut heap = BinaryHeap::<_, Min, 16>::new();
heap.push(1).unwrap();
heap.push(2).unwrap();
heap.push(3).unwrap();
heap.push(17).unwrap();
heap.push(19).unwrap();
heap.push(36).unwrap();
heap.push(7).unwrap();
heap.push(25).unwrap();
heap.push(100).unwrap();

heap.retain(|&x| x % 2 == 0);

assert_eq!(
heap.iter().cloned().collect::<Vec<_>>(),
[2, 36, 100]
);

assert_eq!(heap.pop(), Some(2));
assert_eq!(heap.pop(), Some(36));
assert_eq!(heap.pop(), Some(100));
assert_eq!(heap.pop(), None);
}
}