Skip to content

Commit 96ba386

Browse files
authored
Add pop_if() to Vec (#301)
* Added pop_if() to Vec, which has been stable in the stdlib since 1.86 * Fixed formatting
1 parent 8c2172a commit 96ba386

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/collections/vec.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1511,6 +1511,33 @@ impl<'bump, T: 'bump> Vec<'bump, T> {
15111511
}
15121512
}
15131513

1514+
/// Removes and returns the last element from a vector if the predicate
1515+
/// returns `true`, or [`None`] if the predicate returns false or the vector
1516+
/// is empty (the predicate will not be called in that case).
1517+
///
1518+
/// # Examples
1519+
///
1520+
/// ```
1521+
/// use bumpalo::{Bump, collections::Vec};
1522+
///
1523+
/// let b = Bump::new();
1524+
/// let mut vec = bumpalo::vec![in &b; 1, 2, 3, 4];
1525+
/// let pred = |x: &mut i32| *x % 2 == 0;
1526+
///
1527+
/// assert_eq!(vec.pop_if(pred), Some(4));
1528+
/// assert_eq!(vec, [1, 2, 3]);
1529+
/// assert_eq!(vec.pop_if(pred), None);
1530+
/// ```
1531+
#[inline]
1532+
pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
1533+
let last = self.last_mut()?;
1534+
if predicate(last) {
1535+
self.pop()
1536+
} else {
1537+
None
1538+
}
1539+
}
1540+
15141541
/// Moves all the elements of `other` into `Self`, leaving `other` empty.
15151542
///
15161543
/// # Panics

0 commit comments

Comments
 (0)