Skip to content

Commit ed2b3a2

Browse files
committed
Add shift and remove methods for Vec
1 parent 1835667 commit ed2b3a2

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

src/libstd/vec_ng.rs

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,11 @@ impl<T> Vec<T> {
398398
self.insert(0, element)
399399
}
400400

401+
#[inline]
402+
pub fn shift(&mut self) -> Option<T> {
403+
self.remove(0)
404+
}
405+
401406
pub fn insert(&mut self, index: uint, element: T) {
402407
let len = self.len();
403408
assert!(index <= len);
@@ -420,6 +425,30 @@ impl<T> Vec<T> {
420425
}
421426
}
422427

428+
fn remove(&mut self, index: uint) -> Option<T> {
429+
let len = self.len();
430+
if index < len {
431+
unsafe { // infallible
432+
let ret;
433+
{
434+
let slice = self.as_mut_slice();
435+
// the place we are taking from.
436+
let ptr = slice.as_mut_ptr().offset(index as int);
437+
// copy it out, unsafely having a copy of the value on
438+
// the stack and in the vector at the same time.
439+
ret = Some(ptr::read(ptr as *T));
440+
441+
// Shift everything down to fill in that spot.
442+
ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
443+
}
444+
self.set_len(len - 1);
445+
ret
446+
}
447+
} else {
448+
None
449+
}
450+
}
451+
423452
#[inline]
424453
pub fn rev_iter<'a>(&'a self) -> RevItems<'a,T> {
425454
self.as_slice().rev_iter()

0 commit comments

Comments
 (0)