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 push_many_from_slice method #237

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 29 additions & 0 deletions src/arrayvec.rs
Expand Up @@ -579,6 +579,35 @@ impl<T, const CAP: usize> ArrayVec<T, CAP> {
Ok(())
}

/// Copy as many elements as we can from the slice and append to the `ArrayVec`.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut vec: ArrayVec<usize, 2> = ArrayVec::new();
/// vec.push(1);
/// let rest = vec.push_many_from_slice(&[2, 3]);
/// assert_eq!(&vec[..], &[1, 2]);
/// assert_eq!(rest, &[3]);
/// ```
///
/// Can be thought of as a variation of [try_extend_from_slice] where
/// instead of failing, it does the "best it can" (extends the `ArrayVec`
/// with some but not all of the elements).
pub fn push_many_from_slice<'a, 'b>(&'a mut self, other: &'b [T]) -> &'b [T]
where T: Copy,
{
let self_len = self.len();
let take = usize::min(self.remaining_capacity(), other.len());

unsafe {
let dst = self.get_unchecked_ptr(self_len);
ptr::copy_nonoverlapping(other.as_ptr(), dst, take);
self.set_len(self_len + take);
}
&other[take..]
}

/// Create a draining iterator that removes the specified range in the vector
/// and yields the removed items from start to end. The element range is
/// removed even if the iterator is not consumed until the end.
Expand Down
17 changes: 16 additions & 1 deletion tests/tests.rs
Expand Up @@ -74,6 +74,21 @@ fn test_try_from_slice_error() {
assert_matches!(res, Err(_));
}

#[test]
fn test_push_many_from_slice() {
let mut vec: ArrayVec<usize, 4> = ArrayVec::new();

let ret = vec.push_many_from_slice(&[1, 2, 3]);
assert_eq!(ret, &[]);
assert_eq!(vec.len(), 3);
assert_eq!(&vec[..], &[1, 2, 3]);
assert_eq!(vec.pop(), Some(3));
assert_eq!(&vec[..], &[1, 2]);
let ret = vec.push_many_from_slice(&[3, 4, 5, 6]);
assert_eq!(&vec[..], &[1, 2, 3, 4]);
assert_eq!(ret, &[5, 6]);
}

#[test]
fn test_u16_index() {
const N: usize = 4096;
Expand Down Expand Up @@ -790,4 +805,4 @@ fn test_arraystring_zero_filled_has_some_sanity_checks() {
let string = ArrayString::<4>::zero_filled();
assert_eq!(string.as_str(), "\0\0\0\0");
assert_eq!(string.len(), 4);
}
}