Add shift and remove methods for Vec

This commit is contained in:
Kiet Tran 2014-03-11 00:53:23 -04:00
parent 18356675e5
commit ed2b3a2f0b

View File

@ -398,6 +398,11 @@ impl<T> Vec<T> {
self.insert(0, element)
}
#[inline]
pub fn shift(&mut self) -> Option<T> {
self.remove(0)
}
pub fn insert(&mut self, index: uint, element: T) {
let len = self.len();
assert!(index <= len);
@ -420,6 +425,30 @@ impl<T> Vec<T> {
}
}
fn remove(&mut self, index: uint) -> Option<T> {
let len = self.len();
if index < len {
unsafe { // infallible
let ret;
{
let slice = self.as_mut_slice();
// the place we are taking from.
let ptr = slice.as_mut_ptr().offset(index as int);
// copy it out, unsafely having a copy of the value on
// the stack and in the vector at the same time.
ret = Some(ptr::read(ptr as *T));
// Shift everything down to fill in that spot.
ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
}
self.set_len(len - 1);
ret
}
} else {
None
}
}
#[inline]
pub fn rev_iter<'a>(&'a self) -> RevItems<'a,T> {
self.as_slice().rev_iter()