Skip to content

Commit 876c465

Browse files
committed
FEAT: Add ArrayVec.extend_from_slice
1 parent a3c9e32 commit 876c465

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

src/lib.rs

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -527,6 +527,39 @@ impl<A: Array> ArrayVec<A> {
527527
self.len = Index::from(length);
528528
}
529529

530+
/// Copy and appends all elements in a slice to the `ArrayVec`.
531+
///
532+
/// ```
533+
/// use arrayvec::ArrayVec;
534+
///
535+
/// let mut vec: ArrayVec<[usize; 10]> = ArrayVec::new();
536+
/// vec.push(1);
537+
/// vec.extend_from_slice(&[2, 3]);
538+
/// assert_eq!(&vec[..], &[1, 2, 3]);
539+
/// ```
540+
///
541+
/// # Panics
542+
///
543+
/// This method will panic if the capacity left (see [`capacity_left`]) is
544+
/// smaller then the length of the provided slice.
545+
///
546+
/// [`capacity_left`]: #method.capacity_left
547+
pub fn extend_from_slice(&mut self, other: &[A::Item])
548+
where A::Item: Copy,
549+
{
550+
if self.capacity_left() < other.len() {
551+
panic!("ArrayVec::extend_from_slice: slice is larger then capacity left");
552+
}
553+
554+
let self_len = self.len();
555+
let other_len = other.len();
556+
557+
unsafe {
558+
let dst = self.xs.as_mut_ptr().offset(self_len as isize);
559+
ptr::copy_nonoverlapping(other.as_ptr(), dst, other_len);
560+
self.set_len(self_len + other_len);
561+
}
562+
}
530563

531564
/// Create a draining iterator that removes the specified range in the vector
532565
/// and yields the removed items from start to end. The element range is

tests/tests.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,17 @@ fn test_capacity_left() {
4141
assert_eq!(vec.capacity_left(), 0);
4242
}
4343

44+
#[test]
45+
fn test_extend_from_slice() {
46+
let mut vec: ArrayVec<[usize; 10]> = ArrayVec::new();
47+
48+
vec.extend_from_slice(&[1, 2, 3]);
49+
assert_eq!(vec.len(), 3);
50+
assert_eq!(&vec[..], &[1, 2, 3]);
51+
assert_eq!(vec.pop(), Some(3));
52+
assert_eq!(&vec[..], &[1, 2]);
53+
}
54+
4455
#[test]
4556
fn test_u16_index() {
4657
const N: usize = 4096;

0 commit comments

Comments
 (0)