review comments on vec-insert-remove and vec-into-iter

pull/161/head
Lzu Tao 6 years ago
parent 89392c4a04
commit 518b61d026

@ -16,13 +16,14 @@ using the old len.
pub fn insert(&mut self, index: usize, elem: T) {
// Note: `<=` because it's valid to insert after everything
// which would be equivalent to push.
assert!(self.len >= index, "index is out of bounds");
assert!(index <= self.len, "index out of bounds");
if self.cap == self.len {
self.grow();
}
unsafe {
if index < self.len {
// ptr::copy(src, dest, len): "copy from source to dest len elems"
ptr::copy(
self.ptr.as_ptr().offset(index as isize),
self.ptr.as_ptr().offset(index as isize + 1),
@ -41,7 +42,7 @@ Remove behaves in the opposite manner. We need to shift all the elements from
```rust,ignore
pub fn remove(&mut self, index: usize) -> T {
// Note: `<` because it's *not* valid to remove after everything
assert!(self.len > index, "index is out of bounds");
assert!(index < self.len, "index out of bounds");
unsafe {
self.len -= 1;

@ -133,8 +133,16 @@ impl<T> Drop for IntoIter<T> {
if self.cap != 0 {
// drop any remaining elements
for _ in &mut *self {}
let align = mem::align_of::<T>();
let elem_size = mem::size_of::<T>();
let num_bytes = elem_size * self.cap;
unsafe {
alloc::dealloc(self.buf.as_ptr() as *mut _, alloc::Layout::new::<T>());
alloc::dealloc(
self.buf.as_ptr() as *mut _,
alloc::Layout::from_size_align_unchecked(num_bytes, align),
);
}
}
}

Loading…
Cancel
Save