Skip to content

Commit

Permalink
Add specialized clone_from implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Mikaël Fourrier committed May 23, 2021
1 parent 276e98c commit a2b19ce
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1725,6 +1725,21 @@ where
fn clone(&self) -> SmallVec<A> {
SmallVec::from(self.as_slice())
}

fn clone_from(&mut self, source: &Self) {
// Inspired from `impl Clone for Vec`.

// drop anything that will not be overwritten
self.truncate(source.len());

// self.len <= other.len due to the truncate above, so the
// slices here are always in-bounds.
let (init, tail) = source.split_at(self.len());

// reuse the contained values' allocations/resources.
self.clone_from_slice(init);
self.extend(tail.iter().cloned());
}
}

impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
Expand Down
22 changes: 22 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -925,3 +925,25 @@ fn test_insert_many_overflow() {
v.insert_many(0, iter);
assert_eq!(&*v, &[0, 2, 4, 123]);
}

#[test]
fn test_clone_from() {
let mut a: SmallVec<[u8; 2]> = SmallVec::new();
a.push(1);
a.push(2);
a.push(3);

let mut b: SmallVec<[u8; 2]> = SmallVec::new();
b.push(10);

let mut c: SmallVec<[u8; 2]> = SmallVec::new();
c.push(20);
c.push(21);
c.push(22);

a.clone_from(&b);
assert_eq!(&*a, &[10]);

b.clone_from(&c);
assert_eq!(&*b, &[20, 21, 22]);
}

0 comments on commit a2b19ce

Please sign in to comment.