diff options
| author | Alex van de Sandt <alex@avandesa.dev> | 2024-03-26 15:54:22 -0400 |
|---|---|---|
| committer | Alex van de Sandt <alex@avandesa.dev> | 2024-03-26 18:25:24 -0400 |
| commit | 07d3806eb1a9dcfc6acdc54476c9cc2b7bbbad7b (patch) | |
| tree | ade7cf6792f56654c5085db64e3344579bea6e2e /library/alloc/src | |
| parent | 47ecded3525392b77843534bed69b4302f9af8d2 (diff) | |
Implement `Vec::pop_if`
Diffstat (limited to 'library/alloc/src')
| -rw-r--r-- | library/alloc/src/lib.rs | 1 | ||||
| -rw-r--r-- | library/alloc/src/vec/mod.rs | 25 |
2 files changed, 26 insertions, 0 deletions
diff --git a/library/alloc/src/lib.rs b/library/alloc/src/lib.rs index 02d155aaf12..97ad0dbd5ad 100644 --- a/library/alloc/src/lib.rs +++ b/library/alloc/src/lib.rs @@ -169,6 +169,7 @@ #![feature(unicode_internals)] #![feature(unsize)] #![feature(utf8_chunks)] +#![feature(vec_pop_if)] // tidy-alphabetical-end // // Language features: diff --git a/library/alloc/src/vec/mod.rs b/library/alloc/src/vec/mod.rs index 94bed825bb2..35789f526db 100644 --- a/library/alloc/src/vec/mod.rs +++ b/library/alloc/src/vec/mod.rs @@ -2058,6 +2058,31 @@ impl<T, A: Allocator> Vec<T, A> { } } + /// Removes and returns the last element in a vector if the predicate + /// returns `true`, or [`None`] if the predicate returns false or the vector + /// is empty. + /// + /// # Examples + /// + /// ``` + /// #![feature(vec_pop_if)] + /// + /// let mut vec = vec![1, 2, 3, 4]; + /// let pred = |x: &mut i32| *x % 2 == 0; + /// + /// assert_eq!(vec.pop_if(pred), Some(4)); + /// assert_eq!(vec, [1, 2, 3]); + /// assert_eq!(vec.pop_if(pred), None); + /// ``` + #[unstable(feature = "vec_pop_if", issue = "122741")] + pub fn pop_if<F>(&mut self, f: F) -> Option<T> + where + F: FnOnce(&mut T) -> bool, + { + let last = self.last_mut()?; + if f(last) { self.pop() } else { None } + } + /// Moves all the elements of `other` into `self`, leaving `other` empty. /// /// # Panics |
