Skip to content

Commit 3f7606f

Browse files
committed
Implement insert_slice for SmallVec
1 parent 7e07fc0 commit 3f7606f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

lib.rs

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -314,6 +314,23 @@ impl<A: Array> SmallVec<A> {
314314
}
315315
}
316316

317+
impl<A: Array> SmallVec<A> where A::Item: Copy {
318+
pub fn insert_slice(&mut self, index: usize, slice: &[A::Item]) {
319+
self.reserve(slice.len());
320+
321+
let len = self.len;
322+
assert!(index <= len);
323+
324+
unsafe {
325+
let slice_ptr = slice.as_ptr();
326+
let ptr = self.as_mut_ptr().offset(index as isize);
327+
ptr::copy(ptr, ptr.offset(slice.len() as isize), len - index);
328+
ptr::copy(slice_ptr, ptr, slice.len());
329+
self.set_len(len + slice.len());
330+
}
331+
}
332+
}
333+
317334
impl<A: Array> ops::Deref for SmallVec<A> {
318335
type Target = [A::Item];
319336
#[inline]
@@ -859,6 +876,17 @@ pub mod tests {
859876
assert_eq!(&v.iter().map(|v| **v).collect::<Vec<_>>(), &[0, 3, 2]);
860877
}
861878

879+
#[test]
880+
fn test_insert_slice() {
881+
let mut v: SmallVec<[u8; 8]> = SmallVec::new();
882+
for x in 0..4 {
883+
v.push(x);
884+
}
885+
assert_eq!(v.len(), 4);
886+
v.insert_slice(1, &[5, 6]);
887+
assert_eq!(&v.iter().map(|v| *v).collect::<Vec<_>>(), &[0, 5, 6, 1, 2, 3]);
888+
}
889+
862890
#[test]
863891
#[should_panic]
864892
fn test_drop_panic_smallvec() {

0 commit comments

Comments
 (0)