alloc/collections/retain.rs
1use core::{cmp, hint, mem, ptr};
2
3/// Returns a pointer to the slot at the given logical index.
4///
5/// # Safety
6///
7/// There are `front_len` slots in `front` and if `index >= front_len`,
8/// there are `index - front_len + 1` slots in `back` at least.
9#[inline]
10unsafe fn slot<T>(front: *mut T, front_len: usize, back: *mut T, index: usize) -> *mut T {
11 // SAFETY: Upheld by caller.
12 unsafe { if index < front_len { front.add(index) } else { back.add(index - front_len) } }
13}
14
15/// Retains elements in two contiguous regions according to `f`.
16///
17/// The `*total_len` initialized elements are treated as one logical sequence:
18/// the first `front_len` elements start at `front`, and the remaining elements
19/// start at `back`.
20///
21/// Each element is passed to `f` in logical order. Elements for which `f`
22/// returns `true` are compacted toward the beginning of the logical sequence,
23/// preserving their relative order. Rejected elements are dropped.
24///
25/// On return, `*total_len` is updated to the number of retained elements.
26///
27/// On panic, retained and unchecked elements, including the element whose
28/// predicate panicked, are compacted and `*total_len` is updated accordingly.
29///
30/// Uses the specialized `SINGLE_REGION` in `PanicGuard` to
31/// eliminate unnecessary stack usage and move unchecked elements
32/// with a single bulk copy for `Vec`.
33///
34/// # Safety
35/// - `front_len` must equal `*total_len` if `SINGLE_REGION` is `true`.
36/// - `front` must point to `front_len` initialized, valid instances of `T`.
37/// - `back` must point to `*total_len - front_len` initialized, valid instances
38/// of `T`.
39/// - `front_len <= *total_len`.
40/// - The two regions must not overlap.
41/// - All elements in both regions must be exclusively accessible for the
42/// duration of this call.
43/// - `total_len` must not point into either region.
44#[inline]
45pub(crate) unsafe fn retain_raw<const SINGLE_REGION: bool, T, F>(
46 front: *mut T,
47 front_len: usize,
48 back: *mut T,
49 total_len: &mut usize,
50 mut f: F,
51) where
52 F: FnMut(&mut T) -> bool,
53{
54 let original_len = *total_len;
55 if original_len == 0 {
56 return;
57 }
58
59 // Make the length equality explicit so LLVM can eliminate the back region
60 // paths in the single region specialization.
61 let front_len = if SINGLE_REGION { original_len } else { front_len };
62
63 // Physical layout:
64 //
65 // front: [ ......... front_len elements ......... ]
66 // back: [ .... original_len - front_len elements .... ]
67 //
68 // Logical layout:
69 //
70 // [Kept, Kept, Hole, Hole, Hole, Unchecked, Unchecked]
71 // ^write ^read
72 // |<--------------- original_len ------------------->|
73 //
74 // `front` contains logical indices `[0, front_len)`, and `back` contains
75 // `[front_len, original_len)`. `read` and `write` are logical offsets and may
76 // therefore refer to either physical region.
77 //
78 // Kept: Elements for which the predicate returned true.
79 // Hole: Slots whose elements have been moved from or dropped.
80 // Unchecked: Initialized elements that have not been visited yet.
81 //
82 // This drop guard will be invoked when predicate or `drop` of element panicked.
83 // It shifts unchecked elements to cover holes and assigns the correct length to `*total_len`.
84 // In cases when predicate and `drop` never panic, it will be optimized out.
85 struct PanicGuard<'a, const SINGLE_REGION: bool, T> {
86 front: *mut T,
87 front_len: usize,
88 back: *mut T,
89 total_len: &'a mut usize,
90 read: usize,
91 write: usize,
92 original_len: usize,
93 }
94
95 impl<const SINGLE_REGION: bool, T> Drop for PanicGuard<'_, SINGLE_REGION, T> {
96 #[inline]
97 #[cold]
98 fn drop(&mut self) {
99 let remaining = self.original_len - self.read;
100 if SINGLE_REGION {
101 // SAFETY: `front_len == original_len` means that there is only a region
102 // at `front`. `read` and `write` are offsets within `front` and remaining
103 // elements haven't been touched. Ranges of `src` and `dst` can overlap when
104 // `remaining > read - write`, so `ptr::copy_nonoverlapping` is avoided.
105 unsafe {
106 ptr::copy(self.front.add(self.read), self.front.add(self.write), remaining)
107 };
108 } else {
109 for i in 0..remaining {
110 // SAFETY: `write < read`, so the slots don't overlap.
111 // Trailing unchecked items must be valid since we never touch them.
112 unsafe {
113 ptr::copy_nonoverlapping(
114 slot(self.front, self.front_len, self.back, self.read + i),
115 slot(self.front, self.front_len, self.back, self.write + i),
116 1,
117 )
118 };
119 }
120 }
121
122 *self.total_len = self.write + remaining;
123 }
124 }
125
126 /// Returns the index of the first element rejected by `f`, or `None` if
127 /// every element is retained.
128 ///
129 /// # Safety
130 ///
131 /// The `base` must have `n` initialized elements at least and
132 /// the region must be exclusively accessible for the duration of this call.
133 #[inline]
134 unsafe fn first_rejected<T, F>(base: *mut T, n: usize, f: &mut F) -> Option<usize>
135 where
136 F: FnMut(&mut T) -> bool,
137 {
138 for i in 0..n {
139 // SAFETY: `i < n`
140 if hint::unlikely(!f(unsafe { &mut *base.add(i) })) {
141 return Some(i);
142 }
143 }
144 None
145 }
146
147 /// Processes elements from `g.read` up to `end`, advancing the guard's
148 /// read and write indices.
149 ///
150 /// Each element is passed to `f` in order. Rejected elements are dropped;
151 /// retained elements are moved into the next hole. On normal return,
152 /// `g.read == end`.
153 ///
154 /// # Safety
155 /// - `src` and `dst` must be the physical addresses of `g.read` and `g.write`.
156 /// - `src` contains `end - g.read` elements at least and
157 /// `dst` contains `end - g.read` slots at least.
158 /// - `end <= g.original_len`
159 /// - `g.write < g.read`
160 #[inline]
161 unsafe fn compact<const SINGLE_REGION: bool, T, F>(
162 g: &mut PanicGuard<'_, SINGLE_REGION, T>,
163 end: usize,
164 src: *mut T,
165 dst: *mut T,
166 f: &mut F,
167 ) where
168 F: FnMut(&mut T) -> bool,
169 {
170 let src_start = g.read;
171 let dst_start = g.write;
172 while g.read < end {
173 // SAFETY: `g.read < end` and `src` has `end - src_start` elements at least.
174 let cur = unsafe { &mut *src.add(g.read - src_start) };
175 if !f(cur) {
176 // Advance `read` early to avoid double drop if `drop_in_place` panicked.
177 g.read += 1;
178 // SAFETY: We never touch this element again after dropped.
179 unsafe { ptr::drop_in_place(cur) };
180 } else {
181 // SAFETY: `g.write < g.read < end`, so the slots don't overlap.
182 // We use copy for move, and never touch the source element again.
183 unsafe { ptr::copy_nonoverlapping(cur, dst.add(g.write - dst_start), 1) };
184
185 g.write += 1;
186 g.read += 1;
187 }
188 }
189 }
190
191 let back_len = original_len - front_len;
192
193 // SAFETY: guaranteed by caller
194 let (read, rejected) = unsafe {
195 if let Some(n) = first_rejected(front, front_len, &mut f) {
196 (n, front.add(n))
197 } else if let Some(n) = first_rejected(back, back_len, &mut f) {
198 (front_len + n, back.add(n))
199 } else {
200 // All elements are kept, return early.
201 return;
202 }
203 };
204
205 // Critical section starts here and at least one element is going to be removed.
206 // Advance `g.read` early to avoid double drop if `drop_in_place` panicked.
207 let mut g: PanicGuard<'_, SINGLE_REGION, T> =
208 PanicGuard { front, back, front_len, total_len, read: read + 1, write: read, original_len };
209 // SAFETY: `rejected` belongs to either `front` or `back` and is initialized.
210 unsafe { ptr::drop_in_place(rejected) };
211
212 // Retains the front.
213 if g.read < front_len {
214 let (read, write) = (g.read, g.write);
215 // SAFETY: `front` has `front_len` elements; `write < read` and both is in the range of `front`.
216 unsafe { compact(&mut g, front_len, front.add(read), front.add(write), &mut f) };
217 }
218
219 // Moves elements of back to front if there still are holes in front.
220 while g.write < front_len && g.read < original_len {
221 let end = g.read + cmp::min(original_len - g.read, front_len - g.write);
222 let (read, write) = (g.read, g.write);
223 // SAFETY: It accesses elements up to `end - g.read`,
224 // which is the minimum of both accessible `front` and `back`.
225 // The physical `read` has been at `back` now, so `read - front_len` isn't negative.
226 unsafe { compact(&mut g, end, back.add(read - front_len), front.add(write), &mut f) };
227 }
228
229 // Retains the back.
230 if g.read < original_len {
231 let (read, write) = (g.read, g.write);
232 // SAFETY: `back` remains `original_len - g.read` unread elements.
233 unsafe {
234 compact(
235 &mut g,
236 original_len,
237 back.add(read - front_len),
238 back.add(write - front_len),
239 &mut f,
240 )
241 };
242 }
243
244 // We are leaving the critical section and no panic happened.
245 // Commit the length change and forget the guard.
246 *g.total_len = g.write;
247 mem::forget(g);
248}