Skip to content

Commit c79c24a

Browse files
committed
Auto merge of #133662 - paolobarbolini:vec-extend-with-via-repeatn, r=<try>
Use `iter::repeat_n` to implement `Vec::extend_with` This replaces the `Vec::extend_with` manual implementation with `iter::repeat_n`, simplifying the code and also possibly fixing the issue identified in #120050.
2 parents d1d8e38 + 29565d7 commit c79c24a

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
@@ -3189,31 +3189,7 @@ impl<T: Clone, A: Allocator> Vec<T, A> {
31893189
#[track_caller]
31903190
/// Extend the vector by `n` clones of value.
31913191
fn extend_with(&mut self, n: usize, value: T) {
3192-
self.reserve(n);
3193-
3194-
unsafe {
3195-
let mut ptr = self.as_mut_ptr().add(self.len());
3196-
// Use SetLenOnDrop to work around bug where compiler
3197-
// might not realize the store through `ptr` through self.set_len()
3198-
// don't alias.
3199-
let mut local_len = SetLenOnDrop::new(&mut self.len);
3200-
3201-
// Write all elements except the last one
3202-
for _ in 1..n {
3203-
ptr::write(ptr, value.clone());
3204-
ptr = ptr.add(1);
3205-
// Increment the length in every step in case clone() panics
3206-
local_len.increment_len(1);
3207-
}
3208-
3209-
if n > 0 {
3210-
// We can write the last element directly without cloning needlessly
3211-
ptr::write(ptr, value);
3212-
local_len.increment_len(1);
3213-
}
3214-
3215-
// len set by scope guard
3216-
}
3192+
self.extend_trusted(iter::repeat_n(value, n));
32173193
}
32183194
}
32193195

0 commit comments

Comments
 (0)