Skip to content

Commit c42f8eb

Browse files
authored
Rollup merge of #147780 - tisonkun:vec-deque-extract-if, r=joboet
Implement VecDeque::extract_if This refers to #147750.
2 parents 75fbbd3 + 06a2e72 commit c42f8eb

File tree

3 files changed

+514
-1
lines changed

3 files changed

+514
-1
lines changed
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
use core::ops::{Range, RangeBounds};
2+
use core::{fmt, ptr, slice};
3+
4+
use super::VecDeque;
5+
use 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"]
25+
pub 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+
44+
impl<'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")]
67+
impl<T, F, A: Allocator> Iterator for ExtractIf<'_, T, F, A>
68+
where
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")]
112+
impl<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")]
126+
impl<T, F, A> fmt::Debug for ExtractIf<'_, T, F, A>
127+
where
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+
}

library/alloc/src/collections/vec_deque/mod.rs

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@ pub use self::drain::Drain;
3232

3333
mod drain;
3434

35+
#[unstable(feature = "vec_deque_extract_if", issue = "147750")]
36+
pub use self::extract_if::ExtractIf;
37+
38+
mod extract_if;
39+
3540
#[stable(feature = "rust1", since = "1.0.0")]
3641
pub use self::iter_mut::IterMut;
3742

@@ -614,6 +619,95 @@ impl<T, A: Allocator> VecDeque<T, A> {
614619
}
615620
debug_assert!(self.head < self.capacity() || self.capacity() == 0);
616621
}
622+
623+
/// Creates an iterator which uses a closure to determine if an element in the range should be removed.
624+
///
625+
/// If the closure returns `true`, the element is removed from the deque and yielded. If the closure
626+
/// returns `false`, or panics, the element remains in the deque and will not be yielded.
627+
///
628+
/// Only elements that fall in the provided range are considered for extraction, but any elements
629+
/// after the range will still have to be moved if any element has been extracted.
630+
///
631+
/// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
632+
/// or the iteration short-circuits, then the remaining elements will be retained.
633+
/// Use [`retain_mut`] with a negated predicate if you do not need the returned iterator.
634+
///
635+
/// [`retain_mut`]: VecDeque::retain_mut
636+
///
637+
/// Using this method is equivalent to the following code:
638+
///
639+
/// ```
640+
/// #![feature(vec_deque_extract_if)]
641+
/// # use std::collections::VecDeque;
642+
/// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
643+
/// # let mut deq: VecDeque<_> = (0..10).collect();
644+
/// # let mut deq2 = deq.clone();
645+
/// # let range = 1..5;
646+
/// let mut i = range.start;
647+
/// let end_items = deq.len() - range.end;
648+
/// # let mut extracted = vec![];
649+
///
650+
/// while i < deq.len() - end_items {
651+
/// if some_predicate(&mut deq[i]) {
652+
/// let val = deq.remove(i).unwrap();
653+
/// // your code here
654+
/// # extracted.push(val);
655+
/// } else {
656+
/// i += 1;
657+
/// }
658+
/// }
659+
///
660+
/// # let extracted2: Vec<_> = deq2.extract_if(range, some_predicate).collect();
661+
/// # assert_eq!(deq, deq2);
662+
/// # assert_eq!(extracted, extracted2);
663+
/// ```
664+
///
665+
/// But `extract_if` is easier to use. `extract_if` is also more efficient,
666+
/// because it can backshift the elements of the array in bulk.
667+
///
668+
/// The iterator also lets you mutate the value of each element in the
669+
/// closure, regardless of whether you choose to keep or remove it.
670+
///
671+
/// # Panics
672+
///
673+
/// If `range` is out of bounds.
674+
///
675+
/// # Examples
676+
///
677+
/// Splitting a deque into even and odd values, reusing the original deque:
678+
///
679+
/// ```
680+
/// #![feature(vec_deque_extract_if)]
681+
/// use std::collections::VecDeque;
682+
///
683+
/// let mut numbers = VecDeque::from([1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
684+
///
685+
/// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<VecDeque<_>>();
686+
/// let odds = numbers;
687+
///
688+
/// assert_eq!(evens, VecDeque::from([2, 4, 6, 8, 14]));
689+
/// assert_eq!(odds, VecDeque::from([1, 3, 5, 9, 11, 13, 15]));
690+
/// ```
691+
///
692+
/// Using the range argument to only process a part of the deque:
693+
///
694+
/// ```
695+
/// #![feature(vec_deque_extract_if)]
696+
/// use std::collections::VecDeque;
697+
///
698+
/// let mut items = VecDeque::from([0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]);
699+
/// let ones = items.extract_if(7.., |x| *x == 1).collect::<VecDeque<_>>();
700+
/// assert_eq!(items, VecDeque::from([0, 0, 0, 0, 0, 0, 0, 2, 2, 2]));
701+
/// assert_eq!(ones.len(), 3);
702+
/// ```
703+
#[unstable(feature = "vec_deque_extract_if", issue = "147750")]
704+
pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A>
705+
where
706+
F: FnMut(&mut T) -> bool,
707+
R: RangeBounds<usize>,
708+
{
709+
ExtractIf::new(self, filter, range)
710+
}
617711
}
618712

619713
impl<T> VecDeque<T> {

0 commit comments

Comments
 (0)