Add shift and remove methods for Vec
This commit is contained in:
parent
18356675e5
commit
ed2b3a2f0b
@ -398,6 +398,11 @@ impl<T> Vec<T> {
|
|||||||
self.insert(0, element)
|
self.insert(0, element)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn shift(&mut self) -> Option<T> {
|
||||||
|
self.remove(0)
|
||||||
|
}
|
||||||
|
|
||||||
pub fn insert(&mut self, index: uint, element: T) {
|
pub fn insert(&mut self, index: uint, element: T) {
|
||||||
let len = self.len();
|
let len = self.len();
|
||||||
assert!(index <= 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]
|
#[inline]
|
||||||
pub fn rev_iter<'a>(&'a self) -> RevItems<'a,T> {
|
pub fn rev_iter<'a>(&'a self) -> RevItems<'a,T> {
|
||||||
self.as_slice().rev_iter()
|
self.as_slice().rev_iter()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user