Skip to content

Commit 595a8d2

Browse files
Use iter::repeat_n to implement Vec::extend_with
This replaces the manual `Vec::extend_with` implementation with `iter::repeat_n` and `Vec::extend_trusted`. This simplifies the code and gets LLVM to remove the special case for the last element when `T` is trivial to clone.
1 parent 0dd07bd commit 595a8d2

File tree

1 file changed

+1
-25
lines changed

1 file changed

+1
-25
lines changed

library/alloc/src/vec/mod.rs

Lines changed: 1 addition & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3258,31 +3258,7 @@ impl<T: Clone, A: Allocator> Vec<T, A> {
32583258
#[track_caller]
32593259
/// Extend the vector by `n` clones of value.
32603260
fn extend_with(&mut self, n: usize, value: T) {
3261-
self.reserve(n);
3262-
3263-
unsafe {
3264-
let mut ptr = self.as_mut_ptr().add(self.len());
3265-
// Use SetLenOnDrop to work around bug where compiler
3266-
// might not realize the store through `ptr` through self.set_len()
3267-
// don't alias.
3268-
let mut local_len = SetLenOnDrop::new(&mut self.len);
3269-
3270-
// Write all elements except the last one
3271-
for _ in 1..n {
3272-
ptr::write(ptr, value.clone());
3273-
ptr = ptr.add(1);
3274-
// Increment the length in every step in case clone() panics
3275-
local_len.increment_len(1);
3276-
}
3277-
3278-
if n > 0 {
3279-
// We can write the last element directly without cloning needlessly
3280-
ptr::write(ptr, value);
3281-
local_len.increment_len(1);
3282-
}
3283-
3284-
// len set by scope guard
3285-
}
3261+
self.extend_trusted(iter::repeat_n(value, n));
32863262
}
32873263
}
32883264

0 commit comments

Comments
 (0)