Skip to content

Commit 9796d61

Browse files
committedOct 27, 2022
tor-basic-utils: Provide an implementation of BinaryHeap::retain
This is currently nightly-only and is blocked on an unresolved API question: rust-lang/rust#71503
1 parent a59fef0 commit 9796d61

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed
 

‎crates/tor-basic-utils/semver.md

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
ADDED: Add extension trait providing BinaryHeap::retain on Stable (as retain_ext)

‎crates/tor-basic-utils/src/lib.rs

+22
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,9 @@
3636
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
3737
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
3838
39+
use std::collections::BinaryHeap;
3940
use std::fmt;
41+
use std::mem;
4042

4143
pub mod futures;
4244
pub mod iter;
@@ -101,6 +103,26 @@ impl IoErrorExt for std::io::Error {
101103

102104
// ----------------------------------------------------------------------
103105

106+
/// Implementation of `BinaryHeap::retain` that doesn't require Nightly
107+
pub trait BinaryHeapExt<T> {
108+
/// Remove all elements for which `f` returns `false`
109+
///
110+
/// Performance is not great right now - the algorithm is `O(n*log(n))`
111+
/// where `n` is the number of elements in the heap (not the number removed).
112+
///
113+
/// The name is `retain_ext` to avoid a name collision with the unstable function,
114+
/// which would require the use of UFCS and make this unergonomic.
115+
fn retain_ext<F: FnMut(&T) -> bool>(&mut self, f: F);
116+
}
117+
impl<T: Ord> BinaryHeapExt<T> for BinaryHeap<T> {
118+
fn retain_ext<F: FnMut(&T) -> bool>(&mut self, f: F) {
119+
let items = mem::take(self).into_iter();
120+
*self = items.filter(f).collect();
121+
}
122+
}
123+
124+
// ----------------------------------------------------------------------
125+
104126
/// Define an "accessor trait", which describes structs that have fields of certain types
105127
///
106128
/// This can be useful if a large struct, living high up in the dependency graph,

0 commit comments

Comments
 (0)
Please sign in to comment.