1 // SPDX-License-Identifier: Apache-2.0 OR MIT
3 use crate::alloc::{Allocator, Global};
9 /// An iterator which uses a closure to determine if an element should be removed.
11 /// This struct is created by [`Vec::extract_if`].
12 /// See its documentation for more.
17 /// #![feature(extract_if)]
19 /// let mut v = vec![0, 1, 2];
20 /// let iter: std::vec::ExtractIf<'_, _, _> = v.extract_if(|x| *x % 2 == 0);
22 #[unstable(feature = "extract_if", reason = "recently added", issue = "43244")]
24 #[must_use = "iterators are lazy and do nothing unless consumed"]
29 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
31 F: FnMut(&mut T) -> bool,
33 pub(super) vec: &'a mut Vec<T, A>,
34 /// The index of the item that will be inspected by the next call to `next`.
35 pub(super) idx: usize,
36 /// The number of items that have been drained (removed) thus far.
37 pub(super) del: usize,
38 /// The original length of `vec` prior to draining.
39 pub(super) old_len: usize,
40 /// The filter test predicate.
44 impl<T, F, A: Allocator> ExtractIf<'_, T, F, A>
46 F: FnMut(&mut T) -> bool,
48 /// Returns a reference to the underlying allocator.
49 #[unstable(feature = "allocator_api", issue = "32838")]
51 pub fn allocator(&self) -> &A {
56 #[unstable(feature = "extract_if", reason = "recently added", issue = "43244")]
57 impl<T, F, A: Allocator> Iterator for ExtractIf<'_, T, F, A>
59 F: FnMut(&mut T) -> bool,
63 fn next(&mut self) -> Option<T> {
65 while self.idx < self.old_len {
67 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
68 let drained = (self.pred)(&mut v[i]);
69 // Update the index *after* the predicate is called. If the index
70 // is updated prior and the predicate panics, the element at this
71 // index would be leaked.
75 return Some(ptr::read(&v[i]));
76 } else if self.del > 0 {
78 let src: *const T = &v[i];
79 let dst: *mut T = &mut v[i - del];
80 ptr::copy_nonoverlapping(src, dst, 1);
87 fn size_hint(&self) -> (usize, Option<usize>) {
88 (0, Some(self.old_len - self.idx))
92 #[unstable(feature = "extract_if", reason = "recently added", issue = "43244")]
93 impl<T, F, A: Allocator> Drop for ExtractIf<'_, T, F, A>
95 F: FnMut(&mut T) -> bool,
99 if self.idx < self.old_len && self.del > 0 {
100 // This is a pretty messed up state, and there isn't really an
101 // obviously right thing to do. We don't want to keep trying
102 // to execute `pred`, so we just backshift all the unprocessed
103 // elements and tell the vec that they still exist. The backshift
104 // is required to prevent a double-drop of the last successfully
105 // drained item prior to a panic in the predicate.
106 let ptr = self.vec.as_mut_ptr();
107 let src = ptr.add(self.idx);
108 let dst = src.sub(self.del);
109 let tail_len = self.old_len - self.idx;
110 src.copy_to(dst, tail_len);
112 self.vec.set_len(self.old_len - self.del);