Skip to content

Commit 13234ab

Browse files
authored
Merge pull request #2088 from dtolnay/retain
Add Punctuated::retain
2 parents f18a083 + b617dc9 commit 13234ab

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

‎src/punctuated.rs‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -293,6 +293,26 @@ impl<T, P> Punctuated<T, P> {
293293
self.last = None;
294294
}
295295

296+
/// Retains only the elements specified by the predicate.
297+
///
298+
/// In other words, remove all elements `t` such that `f(&mut t)` returns
299+
/// false.
300+
pub fn retain<F>(&mut self, mut f: F)
301+
where
302+
F: FnMut(&mut T) -> bool,
303+
{
304+
self.inner.retain_mut(|(t, _p)| f(t));
305+
if let Some(last) = &mut self.last {
306+
if !f(last) {
307+
if let Some((second_last, _p)) = self.inner.pop() {
308+
**last = second_last;
309+
} else {
310+
self.last = None;
311+
}
312+
}
313+
}
314+
}
315+
296316
/// Parses zero or more occurrences of `T` separated by punctuation of type
297317
/// `P`, with optional trailing punctuation.
298318
///

0 commit comments

Comments
 (0)