rust-lang/rust · #164252
Share retain implementation between Vec and VecDeque
library/alloc/src/collections/mod.rs1 + / 0 −
@@ -11,6 +11,7 @@ pub mod binary_heap; mod btree; #[cfg(not(no_global_oom_handling))] pub mod linked_list;+pub(crate) mod retain; #[cfg(not(no_global_oom_handling))] pub mod vec_deque; library/alloc/src/collections/retain.rsadded248 + / 0 −
@@ -0,0 +1,248 @@+use core::{cmp, hint, mem, ptr};++/// Returns a pointer to the slot at the given logical index.+///+/// # Safety+///+/// There are `front_len` slots in `front` and if `index >= front_len`,+/// there are `index - front_len + 1` slots in `back` at least.+#[inline]+unsafe fn slot<T>(front: *mut T, front_len: usize, back: *mut T, index: usize) -> *mut T {+ // SAFETY: Upheld by caller.+ unsafe { if index < front_len { front.add(index) } else { back.add(index - front_len) } }+}++/// Retains elements in two contiguous regions according to `f`.+///+/// The `*total_len` initialized elements are treated as one logical sequence:+/// the first `front_len` elements start at `front`, and the remaining elements+/// start at `back`.+///+/// Each element is passed to `f` in logical order. Elements for which `f`+/// returns `true` are compacted toward the beginning of the logical sequence,+/// preserving their relative order. Rejected elements are dropped.+///+/// On return, `*total_len` is updated to the number of retained elements.+///+/// On panic, retained and unchecked elements, including the element whose+/// predicate panicked, are compacted and `*total_len` is updated accordingly.+///+/// Uses the specialized `SINGLE_REGION` in `PanicGuard` to+/// eliminate unnecessary stack usage and move unchecked elements+/// with a single bulk copy for `Vec`.+///+/// # Safety+/// - `front_len` must equal `*total_len` if `SINGLE_REGION` is `true`.+/// - `front` must point to `front_len` initialized, valid instances of `T`.+/// - `back` must point to `*total_len - front_len` initialized, valid instances+/// of `T`.+/// - `front_len <= *total_len`.+/// - The two regions must not overlap.+/// - All elements in both regions must be exclusively accessible for the+/// duration of this call.+/// - `total_len` must not point into either region.+#[inline]+pub(crate) unsafe fn retain_raw<const SINGLE_REGION: bool, T, F>(+ front: *mut T,+ front_len: usize,+ back: *mut T,+ total_len: &mut usize,+ mut f: F,+) where+ F: FnMut(&mut T) -> bool,+{+ let original_len = *total_len;+ if original_len == 0 {+ return;+ }++ // Make the length equality explicit so LLVM can eliminate the back region+ // paths in the single region specialization.+ let front_len = if SINGLE_REGION { original_len } else { front_len };++ // Physical layout:+ //+ // front: [ ......... front_len elements ......... ]+ // back: [ .... original_len - front_len elements .... ]+ //+ // Logical layout:+ //+ // [Kept, Kept, Hole, Hole, Hole, Unchecked, Unchecked]+ // ^write ^read+ // |<--------------- original_len ------------------->|+ //+ // `front` contains logical indices `[0, front_len)`, and `back` contains+ // `[front_len, original_len)`. `read` and `write` are logical offsets and may+ // therefore refer to either physical region.+ //+ // Kept: Elements for which the predicate returned true.+ // Hole: Slots whose elements have been moved from or dropped.+ // Unchecked: Initialized elements that have not been visited yet.+ //+ // This drop guard will be invoked when predicate or `drop` of element panicked.+ // It shifts unchecked elements to cover holes and assigns the correct length to `*total_len`.+ // In cases when predicate and `drop` never panic, it will be optimized out.+ struct PanicGuard<'a, const SINGLE_REGION: bool, T> {+ front: *mut T,+ front_len: usize,+ back: *mut T,+ total_len: &'a mut usize,+ read: usize,+ write: usize,+ original_len: usize,+ }++ impl<const SINGLE_REGION: bool, T> Drop for PanicGuard<'_, SINGLE_REGION, T> {+ #[inline]+ #[cold]+ fn drop(&mut self) {+ let remaining = self.original_len - self.read;+ if SINGLE_REGION {+ // SAFETY: `front_len == original_len` means that there is only a region+ // at `front`. `read` and `write` are offsets within `front` and remaining+ // elements haven't been touched. Ranges of `src` and `dst` can overlap when+ // `remaining > read - write`, so `ptr::copy_nonoverlapping` is avoided.+ unsafe {+ ptr::copy(self.front.add(self.read), self.front.add(self.write), remaining)+ };+ } else {+ for i in 0..remaining {+ // SAFETY: `write < read`, so the slots don't overlap.+ // Trailing unchecked items must be valid since we never touch them.+ unsafe {+ ptr::copy_nonoverlapping(+ slot(self.front, self.front_len, self.back, self.read + i),+ slot(self.front, self.front_len, self.back, self.write + i),+ 1,+ )+ };+ }+ }++ *self.total_len = self.write + remaining;+ }+ }++ /// Returns the index of the first element rejected by `f`, or `None` if+ /// every element is retained.+ ///+ /// # Safety+ ///+ /// The `base` must have `n` initialized elements at least and+ /// the region must be exclusively accessible for the duration of this call.+ #[inline]+ unsafe fn first_rejected<T, F>(base: *mut T, n: usize, f: &mut F) -> Option<usize>+ where+ F: FnMut(&mut T) -> bool,+ {+ for i in 0..n {+ // SAFETY: `i < n`+ if hint::unlikely(!f(unsafe { &mut *base.add(i) })) {+ return Some(i);+ }+ }+ None+ }++ /// Processes elements from `g.read` up to `end`, advancing the guard's+ /// read and write indices.+ ///+ /// Each element is passed to `f` in order. Rejected elements are dropped;+ /// retained elements are moved into the next hole. On normal return,+ /// `g.read == end`.+ ///+ /// # Safety+ /// - `src` and `dst` must be the physical addresses of `g.read` and `g.write`.+ /// - `src` contains `end - g.read` elements at least and+ /// `dst` contains `end - g.read` slots at least.+ /// - `end <= g.original_len`+ /// - `g.write < g.read`+ #[inline]+ unsafe fn compact<const SINGLE_REGION: bool, T, F>(+ g: &mut PanicGuard<'_, SINGLE_REGION, T>,+ end: usize,+ src: *mut T,+ dst: *mut T,+ f: &mut F,+ ) where+ F: FnMut(&mut T) -> bool,+ {+ let src_start = g.read;+ let dst_start = g.write;+ while g.read < end {+ // SAFETY: `g.read < end` and `src` has `end - src_start` elements at least.+ let cur = unsafe { &mut *src.add(g.read - src_start) };+ if !f(cur) {+ // Advance `read` early to avoid double drop if `drop_in_place` panicked.+ g.read += 1;+ // SAFETY: We never touch this element again after dropped.+ unsafe { ptr::drop_in_place(cur) };+ } else {+ // SAFETY: `g.write < g.read < end`, so the slots don't overlap.+ // We use copy for move, and never touch the source element again.+ unsafe { ptr::copy_nonoverlapping(cur, dst.add(g.write - dst_start), 1) };++ g.write += 1;+ g.read += 1;+ }+ }+ }++ let back_len = original_len - front_len;++ // SAFETY: guaranteed by caller+ let (read, rejected) = unsafe {+ if let Some(n) = first_rejected(front, front_len, &mut f) {+ (n, front.add(n))+ } else if let Some(n) = first_rejected(back, back_len, &mut f) {+ (front_len + n, back.add(n))+ } else {+ // All elements are kept, return early.+ return;+ }+ };++ // Critical section starts here and at least one element is going to be removed.+ // Advance `g.read` early to avoid double drop if `drop_in_place` panicked.+ let mut g: PanicGuard<'_, SINGLE_REGION, T> =+ PanicGuard { front, back, front_len, total_len, read: read + 1, write: read, original_len };+ // SAFETY: `rejected` belongs to either `front` or `back` and is initialized.+ unsafe { ptr::drop_in_place(rejected) };++ // Retains the front.+ if g.read < front_len {+ let (read, write) = (g.read, g.write);+ // SAFETY: `front` has `front_len` elements; `write < read` and both is in the range of `front`.+ unsafe { compact(&mut g, front_len, front.add(read), front.add(write), &mut f) };+ }++ // Moves elements of back to front if there still are holes in front.+ while g.write < front_len && g.read < original_len {+ let end = g.read + cmp::min(original_len - g.read, front_len - g.write);+ let (read, write) = (g.read, g.write);+ // SAFETY: It accesses elements up to `end - g.read`,+ // which is the minimum of both accessible `front` and `back`.+ // The physical `read` has been at `back` now, so `read - front_len` isn't negative.+ unsafe { compact(&mut g, end, back.add(read - front_len), front.add(write), &mut f) };+ }++ // Retains the back.+ if g.read < original_len {+ let (read, write) = (g.read, g.write);+ // SAFETY: `back` remains `original_len - g.read` unread elements.+ unsafe {+ compact(+ &mut g,+ original_len,+ back.add(read - front_len),+ back.add(write - front_len),+ &mut f,+ )+ };+ }++ // We are leaving the critical section and no panic happened.+ // Commit the length change and forget the guard.+ *g.total_len = g.write;+ mem::forget(g);+}library/alloc/src/collections/vec_deque/mod.rs8 + / 29 −
@@ -22,6 +22,7 @@ use core::ops::{Index, IndexMut, Range, RangeBounds}; use core::{fmt, ptr, slice}; use crate::alloc::{Allocator, AllocatorNightly, Global};+use crate::collections::retain::retain_raw; use crate::collections::{TryReserveError, TryReserveErrorKind}; use crate::raw_vec::RawVec; use crate::vec::Vec;@@ -2870,38 +2871,16 @@ impl<T, A: Allocator> VecDeque<T, A> { /// assert_eq!(buf, [3, 5]); /// ``` #[stable(feature = "vec_retain_mut", since = "1.61.0")]- pub fn retain_mut<F>(&mut self, mut f: F)+ pub fn retain_mut<F>(&mut self, f: F) where F: FnMut(&mut T) -> bool, {- let len = self.len;- let mut idx = 0;- let mut cur = 0;-- // Stage 1: All values are retained.- while cur < len {- if !f(&mut self[cur]) {- cur += 1;- break;- }- cur += 1;- idx += 1;- }- // Stage 2: Swap retained value into current idx.- while cur < len {- if !f(&mut self[cur]) {- cur += 1;- continue;- }-- self.swap(idx, cur);- cur += 1;- idx += 1;- }- // Stage 3: Truncate all values after idx.- if cur != idx {- self.truncate(idx);- }+ let (buf, head, cap) = (self.ptr(), self.head.as_index(), self.capacity());+ let front_len = cmp::min(cap - head, self.len());+ // SAFETY: Initialized elements are splitted into two regions,+ // `head..head + front_len` and `0..self.len - front_len`.+ // Specify `SINGLE_REGION` false because `front_len` might not equal `self.len`.+ unsafe { retain_raw::<false, _, _>(buf.add(head), front_len, buf, &mut self.len, f) } } // Double the buffer size. This method is inline(never), so we expect it to onlylibrary/alloc/src/vec/mod.rs9 + / 89 −
@@ -117,6 +117,7 @@ use crate::alloc::{Allocator, AllocatorNightly, Global}; use crate::borrow::{Cow, ToOwned}; use crate::boxed::Box; use crate::collections::TryReserveError;+use crate::collections::retain::retain_raw; use crate::raw_vec::RawVec; mod extract_if;@@ -2428,19 +2429,13 @@ impl<T, A: Allocator> Vec<T, A> { /// assert_eq!(vec, [2, 3, 4]); /// ``` #[stable(feature = "vec_retain_mut", since = "1.61.0")]- pub fn retain_mut<F>(&mut self, mut f: F)+ pub fn retain_mut<F>(&mut self, f: F) where F: FnMut(&mut T) -> bool, {- let original_len = self.len();-- if original_len == 0 {- // Empty case: explicit return allows better optimization, vs letting compiler infer it- return;- }- #[cfg(all(target_arch = "aarch64", target_feature = "sve"))] {+ let original_len = self.len(); let long_enough = match mem::size_of::<T>() { 1 => original_len >= sve_retain::MIN_SVE_SIZE_1, 2 => original_len >= sve_retain::MIN_SVE_SIZE_2,@@ -2455,87 +2450,12 @@ impl<T, A: Allocator> Vec<T, A> { } } - // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]- // | ^- write ^- read |- // |<- original_len ->|- // Kept: Elements which predicate returns true on.- // Hole: Moved or dropped element slot.- // Unchecked: Unchecked valid elements.- //- // This drop guard will be invoked when predicate or `drop` of element panicked.- // It shifts unchecked elements to cover holes and `set_len` to the correct length.- // In cases when predicate and `drop` never panick, it will be optimized out.- struct PanicGuard<'a, T, A: Allocator> {- v: &'a mut Vec<T, A>,- read: usize,- write: usize,- original_len: usize,- }-- impl<T, A: Allocator> Drop for PanicGuard<'_, T, A> {- #[cold]- fn drop(&mut self) {- let remaining = self.original_len - self.read;- // SAFETY: Trailing unchecked items must be valid since we never touch them.- unsafe {- ptr::copy(- self.v.as_ptr().add(self.read),- self.v.as_mut_ptr().add(self.write),- remaining,- );- }- // SAFETY: After filling holes, all items are in contiguous memory.- unsafe {- self.v.set_len(self.write + remaining);- }- }- }-- let mut read = 0;- loop {- // SAFETY: read < original_len- let cur = unsafe { self.get_unchecked_mut(read) };- if hint::unlikely(!f(cur)) {- break;- }- read += 1;- if read == original_len {- // All elements are kept, return early.- return;- }- }-- // Critical section starts here and at least one element is going to be removed.- // Advance `g.read` early to avoid double drop if `drop_in_place` panicked.- let mut g = PanicGuard { v: self, read: read + 1, write: read, original_len };- // SAFETY: previous `read` is always less than original_len.- unsafe { ptr::drop_in_place(&mut *g.v.as_mut_ptr().add(read)) };-- while g.read < g.original_len {- // SAFETY: `read` is always less than original_len.- let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.read) };- if !f(cur) {- // Advance `read` early to avoid double drop if `drop_in_place` panicked.- g.read += 1;- // SAFETY: We never touch this element again after dropped.- unsafe { ptr::drop_in_place(cur) };- } else {- // SAFETY: `read` > `write`, so the slots don't overlap.- // We use copy for move, and never touch the source element again.- unsafe {- let hole = g.v.as_mut_ptr().add(g.write);- ptr::copy_nonoverlapping(cur, hole, 1);- }- g.write += 1;- g.read += 1;- }- }-- // We are leaving the critical section and no panic happened,- // Commit the length change and forget the guard.- // SAFETY: `write` is always less than or equal to original_len.- unsafe { g.v.set_len(g.write) };- mem::forget(g);+ let buf = self.as_mut_ptr();+ let front_len = self.len();+ // SAFETY: `buf[..len]` is initialized. `front_len == self.len`,+ // so `back` won't be accessed.+ // Specify `SINGLE_REGION` true because `front_len` always equals `self.len`.+ unsafe { retain_raw::<true, _, _>(buf, front_len, buf, &mut self.len, f) } } /// Retains only the elements specified by the predicate, passing a mutable reference to it.library/alloctests/benches/lib.rs1 + / 0 −
@@ -1,6 +1,7 @@ // This is marked as `test = true` and hence picked up by `./x miri`, but that would be too slow. #![cfg(not(miri))] #![allow(internal_features)]+#![feature(deque_extend_front)] #![feature(iter_next_chunk)] #![feature(macro_metavar_expr_concat)] #![feature(repr_simd)]library/alloctests/benches/vec_deque.rs77 + / 0 −
@@ -265,3 +265,80 @@ fn bench_extend_chained_bytes(b: &mut Bencher) { ring.extend(black_box(input1.iter().chain(input2.iter()))); }); }++fn retain_rand(i: usize) -> u32 {+ let mut x = (i as u32).wrapping_add(0x9e37_79b9);+ x ^= x >> 16;+ x = x.wrapping_mul(0x7feb_352d);+ x ^= x >> 15;+ x = x.wrapping_mul(0x846c_a68b);+ x ^= x >> 16;+ x+}++fn fill_retain_deque(v: &mut VecDeque<u32>, src: &[u32], wrapped: bool) {+ v.clear();+ if wrapped {+ let (front, back) = src.split_at(src.len() / 2);+ v.extend(back);+ v.prepend(front.iter().copied());+ } else {+ v.extend(src);+ }+ assert_eq!(v.as_slices().1.is_empty(), !wrapped);+}++macro_rules! retain_layout_bench {+ ($name:ident, $len:literal, $wrapped:literal, $src:expr) => {+ #[bench]+ fn $name(b: &mut Bencher) {+ let src: Vec<u32> = (0..$len).map($src).collect();+ let mut v = VecDeque::with_capacity($len);+ b.iter(|| {+ fill_retain_deque(&mut v, black_box(&src), $wrapped);+ v.retain(|x| *x == 0);+ });+ }+ };+}++macro_rules! retain_layout_benches {+ (@layout $len:literal, $suffix:literal, $layout:ident, $wrapped:literal) => {+ retain_layout_bench!(+ ${concat(bench_retain_whole_, $layout, _, $suffix)},+ $len, $wrapped, |_| 0+ );+ retain_layout_bench!(+ ${concat(bench_retain_odd_, $layout, _, $suffix)},+ $len, $wrapped, |i| (i & 1) as u32+ );+ retain_layout_bench!(+ ${concat(bench_retain_half_, $layout, _, $suffix)},+ $len, $wrapped, |i| (i < $len / 2) as u32+ );+ retain_layout_bench!(+ ${concat(bench_retain_rand50_, $layout, _, $suffix)},+ $len, $wrapped, |i| retain_rand(i) & 1+ );+ };+ ($($len:literal => $suffix:literal;)*) => {+ $(+ retain_layout_benches!(@layout $len, $suffix, contiguous, false);+ retain_layout_benches!(@layout $len, $suffix, wrapped, true);+ )*+ };+}++retain_layout_benches! {+ 4 => "000004";+ 8 => "000008";+ 16 => "000016";+ 32 => "000032";+ 64 => "000064";+ 128 => "000128";+ 256 => "000256";+ 512 => "000512";+ 1000 => "001000";+ 10000 => "010000";+ 100000 => "100000";+}library/alloctests/lib.rs1 + / 0 −
@@ -34,6 +34,7 @@ #![feature(inplace_iteration)] #![feature(iter_advance_by)] #![feature(iter_next_chunk)]+#![feature(likely_unlikely)] #![feature(maybe_uninit_uninit_array_transpose)] #![feature(ptr_alignment_type)] #![feature(rev_into_inner)]library/alloctests/tests/vec_deque.rs318 + / 0 −
@@ -7,6 +7,7 @@ use std::collections::vec_deque::Drain; use std::fmt::Debug; use std::ops::Bound::*; use std::panic::{AssertUnwindSafe, catch_unwind};+use std::rc::Rc; use std::sync::atomic::{AtomicUsize, Ordering}; use Taggy::*;@@ -1097,6 +1098,323 @@ fn test_retain() { assert_eq!(&v[..], &[2, 4]); } +fn wrapped_deque<T>(mut items: Vec<T>) -> VecDeque<T> {+ let mut v = VecDeque::with_capacity(items.len());+ let back = items.split_off(items.len() / 2);+ v.extend(back);+ for x in items.into_iter().rev() {+ v.push_front(x);+ }+ v+}++fn deque_with_head<T>(+ cap: usize,+ head: usize,+ items: Vec<T>,+ mut filler: impl FnMut() -> T,+) -> VecDeque<T> {+ let mut v = VecDeque::with_capacity(cap);+ let cap = v.capacity();+ assert!(head < cap);+ for _ in 0..head {+ v.push_back(filler());+ }+ for _ in 0..head {+ let _ = v.pop_front();+ }+ let len = items.len();+ v.extend(items);+ assert_eq!(v.capacity(), cap);+ assert_eq!(v.as_slices().1.len(), (head + len).saturating_sub(cap));+ v+}++#[test]+fn test_retain_empty() {+ let mut v = VecDeque::<u64>::new();+ v.retain(|_| unreachable!());+ assert!(v.is_empty());++ let mut v = VecDeque::<u64>::with_capacity(8);+ v.extend([1, 2, 3]);+ v.clear();+ v.retain(|_| unreachable!());+ assert!(v.is_empty());+}++const RETAIN_LENS: [usize; 9] = [0, 1, 2, 3, 5, 8, 17, 64, 100];++fn retain_keep(pattern: usize, len: usize, i: usize) -> bool {+ match pattern {+ 0 => true,+ 1 => false,+ 2 => i % 2 == 0,+ 3 => i % 3 != 1,+ _ => i >= len / 2,+ }+}++fn retain_expected(len: usize, pattern: usize) -> Vec<usize> {+ (0..len).filter(|&i| retain_keep(pattern, len, i)).collect()+}++fn check_retain_pattern(mut v: VecDeque<usize>, len: usize, pattern: usize) -> VecDeque<usize> {+ let mut calls = 0;+ v.retain(|&x| {+ assert_eq!(x, calls);+ calls += 1;+ retain_keep(pattern, len, x)+ });+ assert_eq!(calls, len);+ v+}++#[test]+fn test_retain_matches_filter() {+ for len in RETAIN_LENS {+ let items: Vec<usize> = (0..len).collect();+ for pattern in 0..5 {+ for wrapped in [false, true] {+ let v = if wrapped {+ wrapped_deque(items.clone())+ } else {+ VecDeque::from(items.clone())+ };+ let v = check_retain_pattern(v, len, pattern);+ assert_eq!(+ v,+ retain_expected(len, pattern),+ "len={len} pattern={pattern} wrapped={wrapped}"+ );+ }+ }+ }+}++#[test]+fn test_retain_head_positions() {+ let cap = VecDeque::<usize>::with_capacity(8).capacity();+ for head in 0..cap {+ for len in 0..=cap {+ let items: Vec<usize> = (0..len).collect();+ for pattern in 0..5 {+ let v = deque_with_head(cap, head, items.clone(), || usize::MAX);+ let v = check_retain_pattern(v, len, pattern);+ assert_eq!(+ v,+ retain_expected(len, pattern),+ "head={head} len={len} pattern={pattern}"+ );+ assert_eq!(v.capacity(), cap);+ }+ }+ }+}++thread_local! {+ static RETAIN_DROPS: Cell<usize> = const { Cell::new(0) };+ static RETAIN_DROP_PANIC_AT: Cell<usize> = const { Cell::new(usize::MAX) };+}++struct Counted(usize);++impl Drop for Counted {+ fn drop(&mut self) {+ let n = RETAIN_DROPS.with(|d| {+ d.set(d.get() + 1);+ d.get()+ });+ if n == RETAIN_DROP_PANIC_AT.with(Cell::get) {+ panic!();+ }+ }+}++fn counted_deque(len: usize, layout: usize) -> VecDeque<Counted> {+ let items: Vec<Counted> = (0..len).map(Counted).collect();+ let v = match layout {+ 0 => VecDeque::from(items),+ 1 => wrapped_deque(items),+ _ => deque_with_head(len, layout - 2, items, || Counted(usize::MAX)),+ };+ RETAIN_DROPS.with(|d| d.set(0));+ v+}++#[test]+#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]+fn test_retain_pred_panic_counted() {+ for len in [7, 20] {+ for panic_at in [0, 3, len / 2 + 1, len - 1] {+ for layout in 0..len + 2 {+ let mut v = counted_deque(len, layout);+ catch_unwind(AssertUnwindSafe(|| {+ v.retain(|c| {+ if c.0 == panic_at {+ panic!();+ }+ retain_keep(3, len, c.0)+ })+ }))+ .unwrap_err();+ let expected = (0..len).filter(|&i| i >= panic_at || retain_keep(3, len, i));+ let rejected = (0..panic_at).filter(|&i| !retain_keep(3, len, i)).count();+ let ctx = format!("len={len} panic_at={panic_at} layout={layout}");+ assert_eq!(RETAIN_DROPS.with(Cell::get), rejected, "{ctx}");+ assert!(v.iter().map(|c| c.0).eq(expected), "{ctx}");+ drop(v);+ assert_eq!(RETAIN_DROPS.with(Cell::get), len, "{ctx}");+ }+ }+ }+}++#[test]+#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]+fn test_retain_drop_panic_counted() {+ for len in [7, 20] {+ let rejected: Vec<usize> = (0..len).filter(|&i| !retain_keep(3, len, i)).collect();+ for nth in [1, 2, rejected.len() / 2, rejected.len()] {+ for layout in 0..len + 2 {+ let mut v = counted_deque(len, layout);+ RETAIN_DROP_PANIC_AT.with(|p| p.set(nth));+ catch_unwind(AssertUnwindSafe(|| v.retain(|c| retain_keep(3, len, c.0))))+ .unwrap_err();+ RETAIN_DROP_PANIC_AT.with(|p| p.set(usize::MAX));+ let panicked = rejected[nth - 1];+ let expected = (0..len).filter(|&i| i > panicked || retain_keep(3, len, i));+ let ctx = format!("len={len} nth={nth} layout={layout}");+ assert_eq!(RETAIN_DROPS.with(Cell::get), nth, "{ctx}");+ assert!(v.iter().map(|c| c.0).eq(expected), "{ctx}");+ drop(v);+ assert_eq!(RETAIN_DROPS.with(Cell::get), len, "{ctx}");+ }+ }+ }+}++#[test]+fn test_retain_zst_wrapping_head() {+ thread_local! {+ static ZST_DROPS: Cell<usize> = const { Cell::new(0) };+ }++ struct Zst;++ impl Drop for Zst {+ fn drop(&mut self) {+ ZST_DROPS.with(|d| d.set(d.get() + 1));+ }+ }++ for front in [1, 5, 64] {+ for back in [0, 1, 5, 64] {+ let mut v = VecDeque::new();+ for _ in 0..front {+ v.push_front(Zst);+ }+ for _ in 0..back {+ v.push_back(Zst);+ }+ let len = front + back;+ ZST_DROPS.with(|d| d.set(0));+ let mut calls = 0;+ v.retain(|_| {+ calls += 1;+ calls % 3 != 0+ });+ let rejected = len / 3;+ assert_eq!(calls, len);+ assert_eq!(v.len(), len - rejected);+ assert_eq!(ZST_DROPS.with(Cell::get), rejected);+ drop(v);+ assert_eq!(ZST_DROPS.with(Cell::get), len);+ }+ }+}++#[test]+fn test_retain_predicate_order() {+ for len in [5u64, 200] {+ for to_keep in [true, false] {+ let mut number_of_executions = 0;+ let mut v = wrapped_deque((0..len).collect());+ let mut next_expected = 0;+ v.retain(|&x| {+ assert_eq!(next_expected, x);+ next_expected += 1;+ number_of_executions += 1;+ to_keep+ });+ assert_eq!(number_of_executions, len);+ }+ }+}++#[test]+#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]+fn test_retain_pred_panic_with_hole() {+ for len in [5, 200] {+ let rcs = (0..len).map(Rc::new).collect::<Vec<_>>();+ catch_unwind(AssertUnwindSafe(|| {+ let mut v = wrapped_deque(rcs.clone());+ v.retain(|r| match **r {+ 1 => false,+ x if x == len - 2 => panic!(),+ x => x % 3 != 0,+ });+ }))+ .unwrap_err();+ assert!(rcs.iter().all(|r| Rc::strong_count(r) == 1));+ }+}++#[test]+#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]+fn test_retain_pred_panic_no_hole() {+ for len in [5, 200] {+ let rcs = (0..len).map(Rc::new).collect::<Vec<_>>();+ catch_unwind(AssertUnwindSafe(|| {+ let mut v = wrapped_deque(rcs.clone());+ v.retain(|r| match **r {+ x if x == len - 2 => panic!(),+ _ => true,+ });+ }))+ .unwrap_err();+ assert!(rcs.iter().all(|r| Rc::strong_count(r) == 1));+ }+}++#[test]+#[cfg_attr(not(panic = "unwind"), ignore = "test requires unwinding support")]+fn test_retain_drop_panic() {+ struct Wrap(Rc<i32>);++ impl Drop for Wrap {+ fn drop(&mut self) {+ if *self.0 == 3 {+ panic!();+ }+ }+ }++ for len in [5, 200] {+ let rcs = (0..len).map(Rc::new).collect::<Vec<_>>();+ catch_unwind(AssertUnwindSafe(|| {+ let mut v = wrapped_deque(rcs.iter().map(|r| Wrap(r.clone())).collect());+ v.retain(|w| match *w.0 {+ 1 => false,+ 3 => false,+ x => x % 3 != 0,+ });+ }))+ .unwrap_err();+ assert!(rcs.iter().all(|r| Rc::strong_count(r) == 1));+ }+}+ #[test] fn test_extend_ref() { let mut v = VecDeque::new();