diff --git a/src/lib.rs b/src/lib.rs index 1bbf379..cf5f6c7 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -164,10 +164,8 @@ impl ArrayVec { /// ``` pub fn push(&mut self, element: A::Item) -> Option { if self.len() < A::capacity() { - let len = self.len(); unsafe { - ptr::write(self.get_unchecked_mut(len), element); - self.set_len(len + 1); + self.push_unchecked(element); } None } else { @@ -175,6 +173,35 @@ impl ArrayVec { } } + /// Push `element` to the end of the vector without checking the capacity. + /// + /// It is up to the caller to ensure the capacity of the vector is + /// sufficiently large. + /// + /// # Examples + /// + /// ``` + /// use arrayvec::ArrayVec; + /// + /// let mut array = ArrayVec::<[_; 2]>::new(); + /// + /// if array.len() + 2 <= array.capacity() { + /// unsafe { + /// array.push_unchecked(1); + /// array.push_unchecked(2); + /// } + /// } + /// + /// assert_eq!(&array[..], &[1, 2]); + /// ``` + #[inline] + pub unsafe fn push_unchecked(&mut self, element: A::Item) { + let len = self.len(); + debug_assert!(len < A::capacity()); + ptr::write(self.get_unchecked_mut(len), element); + self.set_len(len + 1); + } + /// Insert `element` in position `index`. /// /// Shift up all elements after `index`. If any is pushed out, it is returned. @@ -669,7 +696,9 @@ impl Extend for ArrayVec { fn extend>(&mut self, iter: T) { let take = self.capacity() - self.len(); for elt in iter.into_iter().take(take) { - self.push(elt); + unsafe { + self.push_unchecked(elt); + } } } }