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