|
| 1 | +use std::ptr; |
| 2 | + |
| 3 | +use crate::CapacityError; |
| 4 | + |
| 5 | +/// Implements basic arrayvec methods - based on a few required methods |
| 6 | +/// for length and element access. |
| 7 | +pub(crate) trait ArrayVecImpl { |
| 8 | + type Item; |
| 9 | + const CAPACITY: usize; |
| 10 | + |
| 11 | + fn len(&self) -> usize; |
| 12 | + |
| 13 | + unsafe fn set_len(&mut self, new_len: usize); |
| 14 | + |
| 15 | + /// Return a slice containing all elements of the vector. |
| 16 | + fn as_slice(&self) -> &[Self::Item]; |
| 17 | + |
| 18 | + /// Return a mutable slice containing all elements of the vector. |
| 19 | + fn as_mut_slice(&mut self) -> &mut [Self::Item]; |
| 20 | + |
| 21 | + /// Return a raw pointer to the vector's buffer. |
| 22 | + fn as_ptr(&self) -> *const Self::Item; |
| 23 | + |
| 24 | + /// Return a raw mutable pointer to the vector's buffer. |
| 25 | + fn as_mut_ptr(&mut self) -> *mut Self::Item; |
| 26 | + |
| 27 | + fn push(&mut self, element: Self::Item) { |
| 28 | + self.try_push(element).unwrap() |
| 29 | + } |
| 30 | + |
| 31 | + fn try_push(&mut self, element: Self::Item) -> Result<(), CapacityError<Self::Item>> { |
| 32 | + if self.len() < Self::CAPACITY { |
| 33 | + unsafe { |
| 34 | + self.push_unchecked(element); |
| 35 | + } |
| 36 | + Ok(()) |
| 37 | + } else { |
| 38 | + Err(CapacityError::new(element)) |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + unsafe fn push_unchecked(&mut self, element: Self::Item) { |
| 43 | + let len = self.len(); |
| 44 | + debug_assert!(len < Self::CAPACITY); |
| 45 | + ptr::write(self.as_mut_ptr().add(len), element); |
| 46 | + self.set_len(len + 1); |
| 47 | + } |
| 48 | + |
| 49 | + fn pop(&mut self) -> Option<Self::Item> { |
| 50 | + if self.len() == 0 { |
| 51 | + return None; |
| 52 | + } |
| 53 | + unsafe { |
| 54 | + let new_len = self.len() - 1; |
| 55 | + self.set_len(new_len); |
| 56 | + Some(ptr::read(self.as_ptr().add(new_len))) |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + fn clear(&mut self) { |
| 61 | + self.truncate(0) |
| 62 | + } |
| 63 | + |
| 64 | + fn truncate(&mut self, new_len: usize) { |
| 65 | + unsafe { |
| 66 | + if new_len < self.len() { |
| 67 | + let tail: *mut [_] = &mut self.as_mut_slice()[new_len..]; |
| 68 | + self.set_len(new_len); |
| 69 | + ptr::drop_in_place(tail); |
| 70 | + } |
| 71 | + } |
| 72 | + } |
| 73 | +} |
| 74 | + |
0 commit comments