1use core::ops::{Range, RangeBounds};
2use core::{ptr, slice};
3
4use super::Vec;
5use crate::alloc::{Allocator, Global};
6
7#[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 idx: usize,
30 end: usize,
32 del: usize,
34 old_len: usize,
36 pred: F,
38}
39
40impl<'a, T, F, A: Allocator> ExtractIf<'a, T, F, A> {
41 pub(super) fn new<R: RangeBounds<usize>>(vec: &'a mut Vec<T, A>, pred: F, range: R) -> Self {
42 let old_len = vec.len();
43 let Range { start, end } = slice::range(range, ..old_len);
44
45 unsafe {
47 vec.set_len(0);
48 }
49 ExtractIf { vec, idx: start, del: 0, end, old_len, pred }
50 }
51
52 #[unstable(feature = "allocator_api", issue = "32838")]
54 #[inline]
55 pub fn allocator(&self) -> &A {
56 self.vec.allocator()
57 }
58}
59
60#[stable(feature = "extract_if", since = "CURRENT_RUSTC_VERSION")]
61impl<T, F, A: Allocator> Iterator for ExtractIf<'_, T, F, A>
62where
63 F: FnMut(&mut T) -> bool,
64{
65 type Item = T;
66
67 fn next(&mut self) -> Option<T> {
68 unsafe {
69 while self.idx < self.end {
70 let i = self.idx;
71 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
72 let drained = (self.pred)(&mut v[i]);
73 self.idx += 1;
77 if drained {
78 self.del += 1;
79 return Some(ptr::read(&v[i]));
80 } else if self.del > 0 {
81 let del = self.del;
82 let src: *const T = &v[i];
83 let dst: *mut T = &mut v[i - del];
84 ptr::copy_nonoverlapping(src, dst, 1);
85 }
86 }
87 None
88 }
89 }
90
91 fn size_hint(&self) -> (usize, Option<usize>) {
92 (0, Some(self.end - self.idx))
93 }
94}
95
96#[stable(feature = "extract_if", since = "CURRENT_RUSTC_VERSION")]
97impl<T, F, A: Allocator> Drop for ExtractIf<'_, T, F, A> {
98 fn drop(&mut self) {
99 unsafe {
100 if self.idx < self.old_len && self.del > 0 {
101 let ptr = self.vec.as_mut_ptr();
102 let src = ptr.add(self.idx);
103 let dst = src.sub(self.del);
104 let tail_len = self.old_len - self.idx;
105 src.copy_to(dst, tail_len);
106 }
107 self.vec.set_len(self.old_len - self.del);
108 }
109 }
110}