alloc/collections/vec_deque/
extract_if.rs

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