Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add try_remove to Vec #77480

Closed
wants to merge 6 commits into from
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions library/alloc/src/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1088,6 +1088,39 @@ impl<T> Vec<T> {
}
}
ohsayan marked this conversation as resolved.
Show resolved Hide resolved

/// Tries to remove an element from the vector. If the element at `index` does not exist,
/// `None` is returned. Otherwise `Some(T)` is returned
///
/// # Examples
/// ```
/// let mut v = vec![1, 2, 3];
/// assert_eq!(v.remove(0), Some(1));
/// assert_eq!(v.remove(2), None);
/// ```
pub fn try_remove(&mut self, index: usize) -> Option<T> {
ohsayan marked this conversation as resolved.
Show resolved Hide resolved
let len = self.len();
if index >= len {
None
} else {
unsafe {
// infallible
let ret;
{
// the place we are taking from.
let ptr = self.as_mut_ptr().add(index);
// copy it out, unsafely having a copy of the value on
// the stack and in the vector at the same time.
ret = ptr::read(ptr);

// Shift everything down to fill in that spot.
ptr::copy(ptr.offset(1), ptr, len - index - 1);
}
self.set_len(len - 1);
Some(ret)
}
}
}

/// Retains only the elements specified by the predicate.
///
/// In other words, remove all elements `e` such that `f(&e)` returns `false`.
Expand Down