Skip to content

Commit 6a4f2bf

Browse files
authored
Unrolled build for #147780
Rollup merge of #147780 - tisonkun:vec-deque-extract-if, r=joboet Implement VecDeque::extract_if This refers to #147750.
2 parents 17e7324 + 06a2e72 commit 6a4f2bf

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

@@ -542,6 +547,95 @@ impl<T, A: Allocator> VecDeque<T, A> {
542547
}
543548
debug_assert!(self.head < self.capacity() || self.capacity() == 0);
544549
}
550+
551+
/// Creates an iterator which uses a closure to determine if an element in the range should be removed.
552+
///
553+
/// If the closure returns `true`, the element is removed from the deque and yielded. If the closure
554+
/// returns `false`, or panics, the element remains in the deque and will not be yielded.
555+
///
556+
/// Only elements that fall in the provided range are considered for extraction, but any elements
557+
/// after the range will still have to be moved if any element has been extracted.
558+
///
559+
/// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
560+
/// or the iteration short-circuits, then the remaining elements will be retained.
561+
/// Use [`retain_mut`] with a negated predicate if you do not need the returned iterator.
562+
///
563+
/// [`retain_mut`]: VecDeque::retain_mut
564+
///
565+
/// Using this method is equivalent to the following code:
566+
///
567+
/// ```
568+
/// #![feature(vec_deque_extract_if)]
569+
/// # use std::collections::VecDeque;
570+
/// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
571+
/// # let mut deq: VecDeque<_> = (0..10).collect();
572+
/// # let mut deq2 = deq.clone();
573+
/// # let range = 1..5;
574+
/// let mut i = range.start;
575+
/// let end_items = deq.len() - range.end;
576+
/// # let mut extracted = vec![];
577+
///
578+
/// while i < deq.len() - end_items {
579+
/// if some_predicate(&mut deq[i]) {
580+
/// let val = deq.remove(i).unwrap();
581+
/// // your code here
582+
/// # extracted.push(val);
583+
/// } else {
584+
/// i += 1;
585+
/// }
586+
/// }
587+
///
588+
/// # let extracted2: Vec<_> = deq2.extract_if(range, some_predicate).collect();
589+
/// # assert_eq!(deq, deq2);
590+
/// # assert_eq!(extracted, extracted2);
591+
/// ```
592+
///
593+
/// But `extract_if` is easier to use. `extract_if` is also more efficient,
594+
/// because it can backshift the elements of the array in bulk.
595+
///
596+
/// The iterator also lets you mutate the value of each element in the
597+
/// closure, regardless of whether you choose to keep or remove it.
598+
///
599+
/// # Panics
600+
///
601+
/// If `range` is out of bounds.
602+
///
603+
/// # Examples
604+
///
605+
/// Splitting a deque into even and odd values, reusing the original deque:
606+
///
607+
/// ```
608+
/// #![feature(vec_deque_extract_if)]
609+
/// use std::collections::VecDeque;
610+
///
611+
/// let mut numbers = VecDeque::from([1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
612+
///
613+
/// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<VecDeque<_>>();
614+
/// let odds = numbers;
615+
///
616+
/// assert_eq!(evens, VecDeque::from([2, 4, 6, 8, 14]));
617+
/// assert_eq!(odds, VecDeque::from([1, 3, 5, 9, 11, 13, 15]));
618+
/// ```
619+
///
620+
/// Using the range argument to only process a part of the deque:
621+
///
622+
/// ```
623+
/// #![feature(vec_deque_extract_if)]
624+
/// use std::collections::VecDeque;
625+
///
626+
/// let mut items = VecDeque::from([0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2]);
627+
/// let ones = items.extract_if(7.., |x| *x == 1).collect::<VecDeque<_>>();
628+
/// assert_eq!(items, VecDeque::from([0, 0, 0, 0, 0, 0, 0, 2, 2, 2]));
629+
/// assert_eq!(ones.len(), 3);
630+
/// ```
631+
#[unstable(feature = "vec_deque_extract_if", issue = "147750")]
632+
pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A>
633+
where
634+
F: FnMut(&mut T) -> bool,
635+
R: RangeBounds<usize>,
636+
{
637+
ExtractIf::new(self, filter, range)
638+
}
545639
}
546640

547641
impl<T> VecDeque<T> {

0 commit comments

Comments
 (0)