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#[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 idx: usize,
32 end: usize,
34 del: usize,
36 old_len: usize,
38 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 unsafe {
49 vec.set_len(0);
50 }
51 ExtractIf { vec, idx: start, del: 0, end, old_len, pred }
52 }
53
54 #[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 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}