alloc/vec/
extract_if.rs

1use core::ops::{Range, RangeBounds};
2use core::{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/// #![feature(extract_if)]
16///
17/// let mut v = vec![0, 1, 2];
18/// let iter: std::vec::ExtractIf<'_, _, _> = v.extract_if(.., |x| *x % 2 == 0);
19/// ```
20#[unstable(feature = "extract_if", reason = "recently added", issue = "43244")]
21#[derive(Debug)]
22#[must_use = "iterators are lazy and do nothing unless consumed"]
23pub struct ExtractIf<
24    'a,
25    T,
26    F,
27    #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
28> {
29    vec: &'a mut Vec<T, A>,
30    /// The index of the item that will be inspected by the next call to `next`.
31    idx: usize,
32    /// Elements at and beyond this point will be retained. Must be equal or smaller than `old_len`.
33    end: usize,
34    /// The number of items that have been drained (removed) thus far.
35    del: usize,
36    /// The original length of `vec` prior to draining.
37    old_len: usize,
38    /// The filter test predicate.
39    pred: F,
40}
41
42impl<'a, T, F, A: Allocator> ExtractIf<'a, T, F, A> {
43    pub(super) fn new<R: RangeBounds<usize>>(vec: &'a mut Vec<T, A>, pred: F, range: R) -> Self {
44        let old_len = vec.len();
45        let Range { start, end } = slice::range(range, ..old_len);
46
47        // Guard against the vec getting leaked (leak amplification)
48        unsafe {
49            vec.set_len(0);
50        }
51        ExtractIf { vec, idx: start, del: 0, end, old_len, pred }
52    }
53
54    /// Returns a reference to the underlying allocator.
55    #[unstable(feature = "allocator_api", issue = "32838")]
56    #[inline]
57    pub fn allocator(&self) -> &A {
58        self.vec.allocator()
59    }
60}
61
62#[unstable(feature = "extract_if", reason = "recently added", issue = "43244")]
63impl<T, F, A: Allocator> Iterator for ExtractIf<'_, T, F, A>
64where
65    F: FnMut(&mut T) -> bool,
66{
67    type Item = T;
68
69    fn next(&mut self) -> Option<T> {
70        unsafe {
71            while self.idx < self.end {
72                let i = self.idx;
73                let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
74                let drained = (self.pred)(&mut v[i]);
75                // Update the index *after* the predicate is called. If the index
76                // is updated prior and the predicate panics, the element at this
77                // index would be leaked.
78                self.idx += 1;
79                if drained {
80                    self.del += 1;
81                    return Some(ptr::read(&v[i]));
82                } else if self.del > 0 {
83                    let del = self.del;
84                    let src: *const T = &v[i];
85                    let dst: *mut T = &mut v[i - del];
86                    ptr::copy_nonoverlapping(src, dst, 1);
87                }
88            }
89            None
90        }
91    }
92
93    fn size_hint(&self) -> (usize, Option<usize>) {
94        (0, Some(self.end - self.idx))
95    }
96}
97
98#[unstable(feature = "extract_if", reason = "recently added", issue = "43244")]
99impl<T, F, A: Allocator> Drop for ExtractIf<'_, T, F, A> {
100    fn drop(&mut self) {
101        unsafe {
102            if self.idx < self.old_len && self.del > 0 {
103                let ptr = self.vec.as_mut_ptr();
104                let src = ptr.add(self.idx);
105                let dst = src.sub(self.del);
106                let tail_len = self.old_len - self.idx;
107                src.copy_to(dst, tail_len);
108            }
109            self.vec.set_len(self.old_len - self.del);
110        }
111    }
112}