Skip to content

Commit afdbc9e

Browse files
committed
Vec::dedup optimization - finishing polishes
1 parent 2abab1f commit afdbc9e

File tree

1 file changed

+7
-11
lines changed

1 file changed

+7
-11
lines changed

library/alloc/src/vec/mod.rs

Lines changed: 7 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1538,13 +1538,9 @@ impl<T, A: Allocator> Vec<T, A> {
15381538

15391539
impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
15401540
fn drop(&mut self) {
1541-
/* This code gets executed either at the end of `dedup_by` or
1542-
* when `same_bucket` panics */
1541+
/* This code gets executed when `same_bucket` panics */
15431542

1544-
/* SAFETY (if finishing successfully): self.read == len, so
1545-
* no data is copied and length is set correctly */
1546-
1547-
/* SAFETY (if panicing): invariant guarantees that `read - write`
1543+
/* SAFETY: invariant guarantees that `read - write`
15481544
* and `len - read` never overflow and that the copy is always
15491545
* in-bounds. */
15501546
unsafe {
@@ -1553,7 +1549,7 @@ impl<T, A: Allocator> Vec<T, A> {
15531549

15541550
/* How many items were left when `same_bucket` paniced.
15551551
* Basically vec[read..].len() */
1556-
let items_left = len - self.read;
1552+
let items_left = len.wrapping_sub(self.read);
15571553

15581554
/* Pointer to first item in vec[write..write+items_left] slice */
15591555
let dropped_ptr = ptr.add(self.write);
@@ -1566,15 +1562,14 @@ impl<T, A: Allocator> Vec<T, A> {
15661562

15671563
/* How many items have been already dropped
15681564
* Basically vec[read..write].len() */
1569-
let dropped = self.read - self.write;
1565+
let dropped = self.read.wrapping_sub(self.write);
15701566

15711567
self.vec.set_len(len - dropped);
15721568
}
15731569
}
15741570
}
15751571

15761572
let mut gap = FillGapOnDrop { read: 1, write: 1, vec: self };
1577-
15781573
let ptr = gap.vec.as_mut_ptr();
15791574

15801575
/* Drop items while going through Vec, it should be more efficient than
@@ -1593,8 +1588,9 @@ impl<T, A: Allocator> Vec<T, A> {
15931588
} else {
15941589
let write_ptr = ptr.add(gap.write);
15951590

1596-
/* Looks like doing just `copy` can be faster than
1597-
* conditional `copy_nonoverlapping` */
1591+
/* Because `read_ptr` can be equal to `write_ptr`, we either
1592+
* have to use `copy` or conditional `copy_nonoverlapping`.
1593+
* Looks like the first option is faster. */
15981594
ptr::copy(read_ptr, write_ptr, 1);
15991595

16001596
/* We have filled that place, so go further */

0 commit comments

Comments
 (0)