Skip to content

Commit 4269dff

Browse files
authored
Auto merge of #262 - Yamakaky:clone_from, r=mbrubeck
Add specialized `clone_from` implementation
2 parents 276e98c + a2b19ce commit 4269dff

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/lib.rs

+15
Original file line numberDiff line numberDiff line change
@@ -1725,6 +1725,21 @@ where
17251725
fn clone(&self) -> SmallVec<A> {
17261726
SmallVec::from(self.as_slice())
17271727
}
1728+
1729+
fn clone_from(&mut self, source: &Self) {
1730+
// Inspired from `impl Clone for Vec`.
1731+
1732+
// drop anything that will not be overwritten
1733+
self.truncate(source.len());
1734+
1735+
// self.len <= other.len due to the truncate above, so the
1736+
// slices here are always in-bounds.
1737+
let (init, tail) = source.split_at(self.len());
1738+
1739+
// reuse the contained values' allocations/resources.
1740+
self.clone_from_slice(init);
1741+
self.extend(tail.iter().cloned());
1742+
}
17281743
}
17291744

17301745
impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>

src/tests.rs

+22
Original file line numberDiff line numberDiff line change
@@ -925,3 +925,25 @@ fn test_insert_many_overflow() {
925925
v.insert_many(0, iter);
926926
assert_eq!(&*v, &[0, 2, 4, 123]);
927927
}
928+
929+
#[test]
930+
fn test_clone_from() {
931+
let mut a: SmallVec<[u8; 2]> = SmallVec::new();
932+
a.push(1);
933+
a.push(2);
934+
a.push(3);
935+
936+
let mut b: SmallVec<[u8; 2]> = SmallVec::new();
937+
b.push(10);
938+
939+
let mut c: SmallVec<[u8; 2]> = SmallVec::new();
940+
c.push(20);
941+
c.push(21);
942+
c.push(22);
943+
944+
a.clone_from(&b);
945+
assert_eq!(&*a, &[10]);
946+
947+
b.clone_from(&c);
948+
assert_eq!(&*b, &[20, 21, 22]);
949+
}

0 commit comments

Comments
 (0)