Skip to content

Commit 3613980

Browse files
committed
Specialize Vec::clone_from for Copy types
This should improve performance and reduce code size. This also improves `clone_from` for `String`, `OsString` and `PathBuf`.
1 parent ae90dcf commit 3613980

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

library/alloc/src/vec/mod.rs

+27-10
Original file line numberDiff line numberDiff line change
@@ -2378,6 +2378,32 @@ impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
23782378
}
23792379
}
23802380

2381+
trait SpecCloneFrom {
2382+
fn clone_from(this: &mut Self, other: &Self);
2383+
}
2384+
2385+
impl<T: Clone, A: Allocator> SpecCloneFrom for Vec<T, A> {
2386+
default fn clone_from(this: &mut Self, other: &Self) {
2387+
// drop anything that will not be overwritten
2388+
this.truncate(other.len());
2389+
2390+
// self.len <= other.len due to the truncate above, so the
2391+
// slices here are always in-bounds.
2392+
let (init, tail) = other.split_at(this.len());
2393+
2394+
// reuse the contained values' allocations/resources.
2395+
this.clone_from_slice(init);
2396+
this.extend_from_slice(tail);
2397+
}
2398+
}
2399+
2400+
impl<T: Copy, A: Allocator> SpecCloneFrom for Vec<T, A> {
2401+
fn clone_from(this: &mut Self, other: &Self) {
2402+
this.clear();
2403+
this.extend_from_slice(other);
2404+
}
2405+
}
2406+
23812407
#[cfg(not(no_global_oom_handling))]
23822408
#[stable(feature = "rust1", since = "1.0.0")]
23832409
impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
@@ -2398,16 +2424,7 @@ impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
23982424
}
23992425

24002426
fn clone_from(&mut self, other: &Self) {
2401-
// drop anything that will not be overwritten
2402-
self.truncate(other.len());
2403-
2404-
// self.len <= other.len due to the truncate above, so the
2405-
// slices here are always in-bounds.
2406-
let (init, tail) = other.split_at(self.len());
2407-
2408-
// reuse the contained values' allocations/resources.
2409-
self.clone_from_slice(init);
2410-
self.extend_from_slice(tail);
2427+
SpecCloneFrom::clone_from(self, other)
24112428
}
24122429
}
24132430

0 commit comments

Comments
 (0)