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 method drain for Vec #365

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Changes from all commits
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
29 changes: 29 additions & 0 deletions src/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -822,6 +822,35 @@ impl<T, const N: usize> Vec<T, N> {
// All item are processed. This can be optimized to `set_len` by LLVM.
drop(g);
}

/// Removes `len` elements in front of the vector
///
/// # Example
/// ```
/// use heapless::Vec;
///
/// let mut vec = Vec::<u8, 10>::from_slice(b"123").unwrap();
/// vec.drain(1).unwrap();
/// assert_eq!(vec.drain(3), Err(()));
/// assert_eq!(&vec, b"23");
/// ```
pub fn drain(&mut self, len: usize) -> Result<(), ()> {
if len > self.len() {
Err(())
} else if len == self.len() {
self.clear();
Ok(())
} else {
let new_len = self.len() - len;
unsafe {
let src = self.as_ptr().add(len);
let dst = self.as_mut_ptr();
core::ptr::copy(src, dst, new_len);
}
self.truncate(new_len);
Ok(())
}
}
}

// Trait implementations
Expand Down