Skip to content

Commit 8bc544a

Browse files
committed
Auto merge of #44355 - Xaeroxe:optimize_drain_filter, r=alexcrichton
Optimize drain_filter This PR cuts out two copies from each iteration of `drain_filter` by exchanging the swap operation for a copy_nonoverlapping function call instead. Since the data being swapped is not needed anymore we can just overwrite it instead.
2 parents 325ba23 + 10384ab commit 8bc544a

File tree

1 file changed

+7
-1
lines changed

1 file changed

+7
-1
lines changed

src/liballoc/vec.rs

+7-1
Original file line numberDiff line numberDiff line change
@@ -2694,7 +2694,13 @@ impl<'a, T, F> Iterator for DrainFilter<'a, T, F>
26942694
self.del += 1;
26952695
return Some(ptr::read(&v[i]));
26962696
} else if self.del > 0 {
2697-
v.swap(i - self.del, i);
2697+
let del = self.del;
2698+
let src: *const T = &v[i];
2699+
let dst: *mut T = &mut v[i - del];
2700+
// This is safe because self.vec has length 0
2701+
// thus its elements will not have Drop::drop
2702+
// called on them in the event of a panic.
2703+
ptr::copy_nonoverlapping(src, dst, 1);
26982704
}
26992705
}
27002706
None

0 commit comments

Comments
 (0)