From 2120e4bb757a56f884d4a33d3efa0062819aa188 Mon Sep 17 00:00:00 2001 From: Thomas de Zeeuw Date: Tue, 17 Jul 2018 15:07:48 +0200 Subject: [PATCH] FEAT: Add ArrayVec.extend_from_slice --- src/lib.rs | 33 +++++++++++++++++++++++++++++++++ tests/tests.rs | 11 +++++++++++ 2 files changed, 44 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 5116f48..46ba3a8 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -536,6 +536,39 @@ impl ArrayVec { 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 diff --git a/tests/tests.rs b/tests/tests.rs index ed98241..a638de9 100644 --- a/tests/tests.rs +++ b/tests/tests.rs @@ -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;