Skip to content

Commit 005a827

Browse files
committed
Try to implement insert_slice
1 parent 7e07fc0 commit 005a827

File tree

1 file changed

+16
-4
lines changed

1 file changed

+16
-4
lines changed

lib.rs

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -300,16 +300,27 @@ impl<A: Array> SmallVec<A> {
300300
}
301301

302302
pub fn insert(&mut self, index: usize, element: A::Item) {
303-
self.reserve(1);
303+
let elements = [element];
304+
self.insert_slice(index, &elements[..]);
305+
}
306+
307+
pub fn insert_slice(&mut self, index: usize, slice: &[A::Item]) {
308+
self.reserve(slice.len());
304309

305310
let len = self.len;
306311
assert!(index <= len);
307312

308313
unsafe {
314+
let slice_ptr = slice.as_ptr();
309315
let ptr = self.as_mut_ptr().offset(index as isize);
310-
ptr::copy(ptr, ptr.offset(1), len - index);
311-
ptr::write(ptr, element);
312-
self.set_len(len + 1);
316+
ptr::copy(ptr, ptr.offset(slice.len() as isize), len - index);
317+
318+
// This does not give self ownership/reference to the element in slice. Thus elements
319+
// of slice
320+
// How to do that...
321+
ptr::copy(slice_ptr, ptr, slice.len());
322+
323+
self.set_len(len + slice.len());
313324
}
314325
}
315326
}
@@ -855,6 +866,7 @@ pub mod tests {
855866
assert_eq!(*v.swap_remove(1), 1);
856867
assert_eq!(*v.remove(1), 3);
857868
v.insert(1, Box::new(3));
869+
// This test fails because the Box<3> ref drops to 0 during the iteration below
858870

859871
assert_eq!(&v.iter().map(|v| **v).collect::<Vec<_>>(), &[0, 3, 2]);
860872
}

0 commit comments

Comments
 (0)