alloc/vec/extract_if.rs
1use core::ops::{Range, RangeBounds};
2use core::{fmt, ptr, slice};
3
4use super::Vec;
5use crate::alloc::{Allocator, Global};
6
7/// An iterator which uses a closure to determine if an element should be removed.
8///
9/// This struct is created by [`Vec::extract_if`].
10/// See its documentation for more.
11///
12/// # Example
13///
14/// ```
15/// let mut v = vec![0, 1, 2];
16/// let iter: std::vec::ExtractIf<'_, _, _> = v.extract_if(.., |x| *x % 2 == 0);
17/// ```
18#[stable(feature = "extract_if", since = "1.87.0")]
19#[must_use = "iterators are lazy and do nothing unless consumed; \
20 use `retain_mut` or `extract_if().for_each(drop)` to remove and discard elements"]
21pub struct ExtractIf<
22 'a,
23 T,
24 F,
25 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
26> {
27 vec: &'a mut Vec<T, A>,
28 /// The index of the item that will be inspected by the next call to `next`.
29 idx: usize,
30 /// Elements at and beyond this point will be retained. Must be equal or smaller than `old_len`.
31 end: usize,
32 /// The number of items that have been drained (removed) thus far.
33 del: usize,
34 /// The original length of `vec` prior to draining.
35 old_len: usize,
36 /// The filter test predicate.
37 pred: F,
38}
39
40impl<'a, T, F, A: Allocator> ExtractIf<'a, T, F, A> {
41 pub(super) fn new<R: RangeBounds<usize>>(vec: &'a mut Vec<T, A>, pred: F, range: R) -> Self {
42 let old_len = vec.len();
43 let Range { start, end } = slice::range(range, ..old_len);
44
45 // Guard against the vec getting leaked (leak amplification)
46 // SAFETY: Setting length to 0 is always okay.
47 unsafe {
48 vec.set_len(0);
49 }
50 ExtractIf { vec, idx: start, del: 0, end, old_len, pred }
51 }
52
53 /// Returns a reference to the underlying allocator.
54 #[unstable(feature = "allocator_api", issue = "32838")]
55 #[inline]
56 pub fn allocator(&self) -> &A {
57 self.vec.allocator()
58 }
59}
60
61#[stable(feature = "extract_if", since = "1.87.0")]
62impl<T, F, A: Allocator> Iterator for ExtractIf<'_, T, F, A>
63where
64 F: FnMut(&mut T) -> bool,
65{
66 type Item = T;
67
68 fn next(&mut self) -> Option<T> {
69 while self.idx < self.end {
70 let i = self.idx;
71 // SAFETY:
72 // We know that `i < self.end` from the if guard and that `self.end <= self.old_len` from
73 // the validity of `Self`. Therefore `i` points to an element within `vec`.
74 //
75 // Additionally, the i-th element is valid because each element is visited at most once
76 // and it is the first time we access vec[i].
77 //
78 // Note: we can't use `vec.get_unchecked_mut(i)` here since the precondition for that
79 // function is that i < vec.len(), but we've set vec's length to zero.
80 let cur = unsafe { &mut *self.vec.as_mut_ptr().add(i) };
81 let drained = (self.pred)(cur);
82 // Update the index *after* the predicate is called. If the index
83 // is updated prior and the predicate panics, the element at this
84 // index would be leaked.
85 self.idx += 1;
86 if drained {
87 self.del += 1;
88 // SAFETY: We never touch this element again after returning it.
89 return Some(unsafe { ptr::read(cur) });
90 } else if self.del > 0 {
91 // SAFETY: `self.del` > 0, so the hole slot must not overlap with current element.
92 // We use copy for move, and never touch this element again.
93 unsafe {
94 let hole_slot = self.vec.as_mut_ptr().add(i - self.del);
95 ptr::copy_nonoverlapping(cur, hole_slot, 1);
96 }
97 }
98 }
99 None
100 }
101
102 fn size_hint(&self) -> (usize, Option<usize>) {
103 (0, Some(self.end - self.idx))
104 }
105}
106
107#[stable(feature = "extract_if", since = "1.87.0")]
108impl<T, F, A: Allocator> Drop for ExtractIf<'_, T, F, A> {
109 fn drop(&mut self) {
110 if self.del > 0 {
111 // SAFETY: Trailing unchecked items must be valid since we never touch them.
112 unsafe {
113 ptr::copy(
114 self.vec.as_ptr().add(self.idx),
115 self.vec.as_mut_ptr().add(self.idx - self.del),
116 self.old_len - self.idx,
117 );
118 }
119 }
120 // SAFETY: After filling holes, all items are in contiguous memory.
121 unsafe {
122 self.vec.set_len(self.old_len - self.del);
123 }
124 }
125}
126
127#[stable(feature = "extract_if", since = "1.87.0")]
128impl<T, F, A> fmt::Debug for ExtractIf<'_, T, F, A>
129where
130 T: fmt::Debug,
131 A: Allocator,
132{
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 // We have to use pointer arithmetics here,
135 // because the length of `self.vec` is temporarily set to 0.
136 let start = self.vec.as_ptr();
137
138 // SAFETY: we always keep first `self.idx - self.del` elements valid.
139 let retained = unsafe { slice::from_raw_parts(start, self.idx - self.del) };
140
141 let valid_tail =
142 // SAFETY: we have not yet touched elements starting at `self.idx`.
143 unsafe { slice::from_raw_parts(start.add(self.idx), self.old_len - self.idx) };
144
145 let (remainder, skipped_tail) =
146 // SAFETY: `end - idx <= old_len - idx`, because `end <= old_len`.
147 // Also `idx <= end` by invariant.
148 unsafe { valid_tail.split_at_unchecked(self.end - self.idx) };
149
150 f.debug_struct("ExtractIf")
151 .field("retained", &retained)
152 .field("remainder", &remainder)
153 .field("skipped_tail", &skipped_tail)
154 .finish_non_exhaustive()
155 }
156}