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