FEAT: Add ArrayVec.extend_from_slice
This commit is contained in:
+33
@@ -536,6 +536,39 @@ impl<A: Array> ArrayVec<A> {
|
|||||||
self.len = Index::from(length);
|
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
|
/// 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
|
/// and yields the removed items from start to end. The element range is
|
||||||
|
|||||||
@@ -41,6 +41,17 @@ fn test_capacity_left() {
|
|||||||
assert_eq!(vec.capacity_left(), 0);
|
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]
|
#[test]
|
||||||
fn test_u16_index() {
|
fn test_u16_index() {
|
||||||
const N: usize = 4096;
|
const N: usize = 4096;
|
||||||
|
|||||||
Reference in New Issue
Block a user