Skip to content

Commit

Permalink
Add shift and remove methods for Vec
Browse files Browse the repository at this point in the history
  • Loading branch information
ktt3ja committed Mar 12, 2014
1 parent 1835667 commit ed2b3a2
Showing 1 changed file with 29 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/libstd/vec_ng.rs
Expand Up @@ -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);
Expand All @@ -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()
Expand Down

0 comments on commit ed2b3a2

Please sign in to comment.