FEAT: Add ArrayVec.extend_from_slice

This commit is contained in:
Thomas de Zeeuw
2018-07-17 15:07:48 +02:00
parent d11c853346
commit 2120e4bb75
2 changed files with 44 additions and 0 deletions
+33
View File
@@ -536,6 +536,39 @@ impl<A: Array> ArrayVec<A> {
self.len = Index::from(length);
}
/// Copy and appends all elements in a slice to the `ArrayVec`.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut vec: ArrayVec<[usize; 10]> = ArrayVec::new();
/// vec.push(1);
/// vec.extend_from_slice(&[2, 3]);
/// assert_eq!(&vec[..], &[1, 2, 3]);
/// ```
///
/// # Panics
///
/// This method will panic if the capacity left (see [`capacity_left`]) is
/// smaller then the length of the provided slice.
///
/// [`capacity_left`]: #method.capacity_left
pub fn extend_from_slice(&mut self, other: &[A::Item])
where A::Item: Copy,
{
if self.capacity_left() < other.len() {
panic!("ArrayVec::extend_from_slice: slice is larger then capacity left");
}
let self_len = self.len();
let other_len = other.len();
unsafe {
let dst = self.xs.as_mut_ptr().offset(self_len as isize);
ptr::copy_nonoverlapping(other.as_ptr(), dst, other_len);
self.set_len(self_len + other_len);
}
}
/// 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
+11
View File
@@ -41,6 +41,17 @@ fn test_capacity_left() {
assert_eq!(vec.capacity_left(), 0);
}
#[test]
fn test_extend_from_slice() {
let mut vec: ArrayVec<[usize; 10]> = ArrayVec::new();
vec.extend_from_slice(&[1, 2, 3]);
assert_eq!(vec.len(), 3);
assert_eq!(&vec[..], &[1, 2, 3]);
assert_eq!(vec.pop(), Some(3));
assert_eq!(&vec[..], &[1, 2]);
}
#[test]
fn test_u16_index() {
const N: usize = 4096;