Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve the copying code for slices and Vec #13539

Merged
merged 2 commits into from
Apr 16, 2014
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions src/libstd/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -760,9 +760,25 @@ impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
/// Returns a copy of `v`.
#[inline]
fn to_owned(&self) -> ~[T] {
let mut result = with_capacity(self.len());
for e in self.iter() {
result.push((*e).clone());
let len = self.len();
let mut result = with_capacity(len);
// Unsafe code so this can be optimised to a memcpy (or something
// similarly fast) when T is Copy. LLVM is easily confused, so any
// extra operations during the loop can prevent this optimisation
unsafe {
let mut i = 0;
let p = result.as_mut_ptr();
// Use try_finally here otherwise the write to length
// inside the loop stops LLVM from optimising this.
try_finally(
&mut i, (),
|i, ()| while *i < len {
mem::move_val_init(
&mut(*p.offset(*i as int)),
self.unsafe_ref(*i).clone());
*i += 1;
},
|i| result.set_len(*i));
}
result
}
Expand Down Expand Up @@ -2584,7 +2600,8 @@ pub mod bytes {
impl<A: Clone> Clone for ~[A] {
#[inline]
fn clone(&self) -> ~[A] {
self.iter().map(|item| item.clone()).collect()
// Use the fast to_owned on &[A] for cloning
self.as_slice().to_owned()
}

fn clone_from(&mut self, source: &~[A]) {
Expand Down
18 changes: 17 additions & 1 deletion src/libstd/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,23 @@ impl<T: Clone> Vec<T> {

impl<T:Clone> Clone for Vec<T> {
fn clone(&self) -> Vec<T> {
self.iter().map(|x| x.clone()).collect()
let len = self.len;
let mut vector = Vec::with_capacity(len);
// Unsafe code so this can be optimised to a memcpy (or something
// similarly fast) when T is Copy. LLVM is easily confused, so any
// extra operations during the loop can prevent this optimisation
{
let this_slice = self.as_slice();
while vector.len < len {
unsafe {
mem::move_val_init(
vector.as_mut_slice().unsafe_mut_ref(vector.len),
this_slice.unsafe_ref(vector.len).clone());
}
vector.len += 1;
}
}
vector
}

fn clone_from(&mut self, other: &Vec<T>) {
Expand Down