FEAT: Add new const generics version of ArrayVec (first draft)

This commit is contained in:
bluss
2020-12-16 21:48:34 +01:00
parent 630b81b848
commit 02ab4dc796
2 changed files with 203 additions and 202 deletions
+187 -198
View File
@@ -14,13 +14,15 @@ use std::fmt;
#[cfg(feature="std")] #[cfg(feature="std")]
use std::io; use std::io;
use crate::maybe_uninit::MaybeUninit; use std::mem::ManuallyDrop;
use std::mem::MaybeUninit;
//use crate::maybe_uninit::MaybeUninit;
#[cfg(feature="serde")] #[cfg(feature="serde")]
use serde::{Serialize, Deserialize, Serializer, Deserializer}; use serde::{Serialize, Deserialize, Serializer, Deserializer};
use crate::array::Array;
use crate::errors::CapacityError; use crate::errors::CapacityError;
use crate::array::Index; use crate::array::Index;
use crate::arrayvec_impl::ArrayVecImpl; use crate::arrayvec_impl::ArrayVecImpl;
@@ -37,12 +39,13 @@ use crate::arrayvec_impl::ArrayVecImpl;
/// that the full slice API is available. /// that the full slice API is available.
/// ///
/// ArrayVec can be converted into a by value iterator. /// ArrayVec can be converted into a by value iterator.
pub struct ArrayVec<A: Array> { pub struct ArrayVec<T, const CAP: usize> {
xs: MaybeUninit<A>, // the `len` first elements of the array are initialized
len: A::Index, xs: [MaybeUninit<T>; CAP],
len: usize,
} }
impl<A: Array> Drop for ArrayVec<A> { impl<T, const CAP: usize> Drop for ArrayVec<T, CAP> {
fn drop(&mut self) { fn drop(&mut self) {
self.clear(); self.clear();
@@ -57,7 +60,10 @@ macro_rules! panic_oob {
} }
} }
impl<A: Array> ArrayVec<A> { impl<T, const CAP: usize> ArrayVec<T, CAP> {
/// Capacity
const CAPACITY: usize = CAP;
/// Create a new empty `ArrayVec`. /// Create a new empty `ArrayVec`.
/// ///
/// Capacity is inferred from the type parameter. /// Capacity is inferred from the type parameter.
@@ -72,16 +78,16 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(array.capacity(), 16); /// assert_eq!(array.capacity(), 16);
/// ``` /// ```
#[cfg(not(feature="unstable-const-fn"))] #[cfg(not(feature="unstable-const-fn"))]
pub fn new() -> ArrayVec<A> { pub fn new() -> ArrayVec<T, CAP> {
unsafe { unsafe {
ArrayVec { xs: MaybeUninit::uninitialized(), len: Index::ZERO } ArrayVec { xs: MaybeUninit::uninit().assume_init(), len: 0 }
} }
} }
#[cfg(feature="unstable-const-fn")] #[cfg(feature="unstable-const-fn")]
pub const fn new() -> ArrayVec<A> { pub const fn new() -> ArrayVec<T, CAP> {
unsafe { unsafe {
ArrayVec { xs: MaybeUninit::uninitialized(), len: Index::ZERO } ArrayVec { xs: MaybeUninit::uninit().assume_init(), len: 0 }
} }
} }
@@ -95,7 +101,7 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(array.len(), 2); /// assert_eq!(array.len(), 2);
/// ``` /// ```
#[inline] #[inline]
pub fn len(&self) -> usize { self.len.to_usize() } pub fn len(&self) -> usize { self.len as usize }
/// Returns whether the `ArrayVec` is empty. /// Returns whether the `ArrayVec` is empty.
/// ///
@@ -118,7 +124,7 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(array.capacity(), 3); /// assert_eq!(array.capacity(), 3);
/// ``` /// ```
#[inline(always)] #[inline(always)]
pub fn capacity(&self) -> usize { A::CAPACITY } pub fn capacity(&self) -> usize { CAP }
/// Return if the `ArrayVec` is completely filled. /// Return if the `ArrayVec` is completely filled.
/// ///
@@ -159,7 +165,7 @@ impl<A: Array> ArrayVec<A> {
/// ///
/// assert_eq!(&array[..], &[1, 2]); /// assert_eq!(&array[..], &[1, 2]);
/// ``` /// ```
pub fn push(&mut self, element: A::Item) { pub fn push(&mut self, element: T) {
ArrayVecImpl::push(self, element) ArrayVecImpl::push(self, element)
} }
@@ -185,11 +191,10 @@ impl<A: Array> ArrayVec<A> {
/// ///
/// assert!(overflow.is_err()); /// assert!(overflow.is_err());
/// ``` /// ```
pub fn try_push(&mut self, element: A::Item) -> Result<(), CapacityError<A::Item>> { pub fn try_push(&mut self, element: T) -> Result<(), CapacityError<T>> {
ArrayVecImpl::try_push(self, element) ArrayVecImpl::try_push(self, element)
} }
/// Push `element` to the end of the vector without checking the capacity. /// 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 /// It is up to the caller to ensure the capacity of the vector is
@@ -211,13 +216,38 @@ impl<A: Array> ArrayVec<A> {
/// ///
/// assert_eq!(&array[..], &[1, 2]); /// assert_eq!(&array[..], &[1, 2]);
/// ``` /// ```
pub unsafe fn push_unchecked(&mut self, element: A::Item) { pub unsafe fn push_unchecked(&mut self, element: T) {
ArrayVecImpl::push_unchecked(self, element) ArrayVecImpl::push_unchecked(self, element)
} }
/// Shortens the vector, keeping the first `len` elements and dropping
/// the rest.
///
/// If `len` is greater than the vectors current length this has no
/// effect.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut array = ArrayVec::from([1, 2, 3, 4, 5]);
/// array.truncate(3);
/// assert_eq!(&array[..], &[1, 2, 3]);
/// array.truncate(4);
/// assert_eq!(&array[..], &[1, 2, 3]);
/// ```
pub fn truncate(&mut self, new_len: usize) {
ArrayVecImpl::truncate(self, new_len)
}
/// Remove all elements in the vector.
pub fn clear(&mut self) {
ArrayVecImpl::clear(self)
}
/// Get pointer to where element at `index` would be /// Get pointer to where element at `index` would be
unsafe fn get_unchecked_ptr(&mut self, index: usize) -> *mut A::Item { unsafe fn get_unchecked_ptr(&mut self, index: usize) -> *mut T {
self.xs.ptr_mut().add(index) self.as_mut_ptr().add(index)
} }
/// Insert `element` at position `index`. /// Insert `element` at position `index`.
@@ -240,7 +270,7 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(&array[..], &["y", "x"]); /// assert_eq!(&array[..], &["y", "x"]);
/// ///
/// ``` /// ```
pub fn insert(&mut self, index: usize, element: A::Item) { pub fn insert(&mut self, index: usize, element: T) {
self.try_insert(index, element).unwrap() self.try_insert(index, element).unwrap()
} }
@@ -264,7 +294,7 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(&array[..], &["y", "x"]); /// assert_eq!(&array[..], &["y", "x"]);
/// ///
/// ``` /// ```
pub fn try_insert(&mut self, index: usize, element: A::Item) -> Result<(), CapacityError<A::Item>> { pub fn try_insert(&mut self, index: usize, element: T) -> Result<(), CapacityError<T>> {
if index > self.len() { if index > self.len() {
panic_oob!("try_insert", index, self.len()) panic_oob!("try_insert", index, self.len())
} }
@@ -304,7 +334,7 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(array.pop(), Some(1)); /// assert_eq!(array.pop(), Some(1));
/// assert_eq!(array.pop(), None); /// assert_eq!(array.pop(), None);
/// ``` /// ```
pub fn pop(&mut self) -> Option<A::Item> { pub fn pop(&mut self) -> Option<T> {
ArrayVecImpl::pop(self) ArrayVecImpl::pop(self)
} }
@@ -327,7 +357,7 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(array.swap_remove(1), 2); /// assert_eq!(array.swap_remove(1), 2);
/// assert_eq!(&array[..], &[3]); /// assert_eq!(&array[..], &[3]);
/// ``` /// ```
pub fn swap_remove(&mut self, index: usize) -> A::Item { pub fn swap_remove(&mut self, index: usize) -> T {
self.swap_pop(index) self.swap_pop(index)
.unwrap_or_else(|| { .unwrap_or_else(|| {
panic_oob!("swap_remove", index, self.len()) panic_oob!("swap_remove", index, self.len())
@@ -351,7 +381,7 @@ impl<A: Array> ArrayVec<A> {
/// ///
/// assert_eq!(array.swap_pop(10), None); /// assert_eq!(array.swap_pop(10), None);
/// ``` /// ```
pub fn swap_pop(&mut self, index: usize) -> Option<A::Item> { pub fn swap_pop(&mut self, index: usize) -> Option<T> {
let len = self.len(); let len = self.len();
if index >= len { if index >= len {
return None; return None;
@@ -375,7 +405,7 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(removed_elt, 1); /// assert_eq!(removed_elt, 1);
/// assert_eq!(&array[..], &[2, 3]); /// assert_eq!(&array[..], &[2, 3]);
/// ``` /// ```
pub fn remove(&mut self, index: usize) -> A::Item { pub fn remove(&mut self, index: usize) -> T {
self.pop_at(index) self.pop_at(index)
.unwrap_or_else(|| { .unwrap_or_else(|| {
panic_oob!("remove", index, self.len()) panic_oob!("remove", index, self.len())
@@ -398,7 +428,7 @@ impl<A: Array> ArrayVec<A> {
/// assert!(array.pop_at(2).is_none()); /// assert!(array.pop_at(2).is_none());
/// assert!(array.pop_at(10).is_none()); /// assert!(array.pop_at(10).is_none());
/// ``` /// ```
pub fn pop_at(&mut self, index: usize) -> Option<A::Item> { pub fn pop_at(&mut self, index: usize) -> Option<T> {
if index >= self.len() { if index >= self.len() {
None None
} else { } else {
@@ -406,30 +436,6 @@ impl<A: Array> ArrayVec<A> {
} }
} }
/// Shortens the vector, keeping the first `len` elements and dropping
/// the rest.
///
/// If `len` is greater than the vectors current length this has no
/// effect.
///
/// ```
/// use arrayvec::ArrayVec;
///
/// let mut array = ArrayVec::from([1, 2, 3, 4, 5]);
/// array.truncate(3);
/// assert_eq!(&array[..], &[1, 2, 3]);
/// array.truncate(4);
/// assert_eq!(&array[..], &[1, 2, 3]);
/// ```
pub fn truncate(&mut self, new_len: usize) {
ArrayVecImpl::truncate(self, new_len)
}
/// Remove all elements in the vector.
pub fn clear(&mut self) {
ArrayVecImpl::clear(self)
}
/// Retains only the elements specified by the predicate. /// Retains only the elements specified by the predicate.
/// ///
/// In other words, remove all elements `e` such that `f(&mut e)` returns false. /// In other words, remove all elements `e` such that `f(&mut e)` returns false.
@@ -444,7 +450,7 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(&array[..], &[1, 3]); /// assert_eq!(&array[..], &[1, 3]);
/// ``` /// ```
pub fn retain<F>(&mut self, mut f: F) pub fn retain<F>(&mut self, mut f: F)
where F: FnMut(&mut A::Item) -> bool where F: FnMut(&mut T) -> bool
{ {
let len = self.len(); let len = self.len();
let mut del = 0; let mut del = 0;
@@ -494,8 +500,8 @@ impl<A: Array> ArrayVec<A> {
/// slice. /// slice.
/// ///
/// [`remaining_capacity`]: #method.remaining_capacity /// [`remaining_capacity`]: #method.remaining_capacity
pub fn try_extend_from_slice(&mut self, other: &[A::Item]) -> Result<(), CapacityError> pub fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), CapacityError>
where A::Item: Copy, where T: Copy,
{ {
if self.remaining_capacity() < other.len() { if self.remaining_capacity() < other.len() {
return Err(CapacityError::new(())); return Err(CapacityError::new(()));
@@ -505,7 +511,7 @@ impl<A: Array> ArrayVec<A> {
let other_len = other.len(); let other_len = other.len();
unsafe { unsafe {
let dst = self.xs.ptr_mut().add(self_len); let dst = self.get_unchecked_ptr(self_len);
ptr::copy_nonoverlapping(other.as_ptr(), dst, other_len); ptr::copy_nonoverlapping(other.as_ptr(), dst, other_len);
self.set_len(self_len + other_len); self.set_len(self_len + other_len);
} }
@@ -530,7 +536,7 @@ impl<A: Array> ArrayVec<A> {
/// assert_eq!(&v[..], &[3]); /// assert_eq!(&v[..], &[3]);
/// assert_eq!(&u[..], &[1, 2]); /// assert_eq!(&u[..], &[1, 2]);
/// ``` /// ```
pub fn drain<R>(&mut self, range: R) -> Drain<A> pub fn drain<R>(&mut self, range: R) -> Drain<T, CAP>
where R: RangeBounds<usize> where R: RangeBounds<usize>
{ {
// Memory safety // Memory safety
@@ -557,7 +563,7 @@ impl<A: Array> ArrayVec<A> {
self.drain_range(start, end) self.drain_range(start, end)
} }
fn drain_range(&mut self, start: usize, end: usize) -> Drain<A> fn drain_range(&mut self, start: usize, end: usize) -> Drain<T, CAP>
{ {
let len = self.len(); let len = self.len();
@@ -582,12 +588,12 @@ impl<A: Array> ArrayVec<A> {
/// ///
/// Return an `Ok` value with the array if length equals capacity, /// Return an `Ok` value with the array if length equals capacity,
/// return an `Err` with self otherwise. /// return an `Err` with self otherwise.
pub fn into_inner(self) -> Result<A, Self> { pub fn into_inner(self) -> Result<[T; CAP], Self> {
if self.len() < self.capacity() { if self.len() < self.capacity() {
Err(self) Err(self)
} else { } else {
unsafe { unsafe {
let array = ptr::read(self.xs.ptr() as *const A); let array = ptr::read(self.as_ptr() as *const [T; CAP]);
mem::forget(self); mem::forget(self);
Ok(array) Ok(array)
} }
@@ -602,72 +608,58 @@ impl<A: Array> ArrayVec<A> {
} }
/// Return a slice containing all elements of the vector. /// Return a slice containing all elements of the vector.
pub fn as_slice(&self) -> &[A::Item] { pub fn as_slice(&self) -> &[T] {
self ArrayVecImpl::as_slice(self)
} }
/// Return a mutable slice containing all elements of the vector. /// Return a mutable slice containing all elements of the vector.
pub fn as_mut_slice(&mut self) -> &mut [A::Item] { pub fn as_mut_slice(&mut self) -> &mut [T] {
self ArrayVecImpl::as_mut_slice(self)
} }
/// Return a raw pointer to the vector's buffer. /// Return a raw pointer to the vector's buffer.
pub fn as_ptr(&self) -> *const A::Item { pub fn as_ptr(&self) -> *const T {
self.xs.ptr() ArrayVecImpl::as_ptr(self)
} }
/// Return a raw mutable pointer to the vector's buffer. /// Return a raw mutable pointer to the vector's buffer.
pub fn as_mut_ptr(&mut self) -> *mut A::Item { pub fn as_mut_ptr(&mut self) -> *mut T {
self.xs.ptr_mut() ArrayVecImpl::as_mut_ptr(self)
} }
} }
impl<A: Array> Deref for ArrayVec<A> { impl<T, const CAP: usize> ArrayVecImpl for ArrayVec<T, CAP> {
type Target = [A::Item]; type Item = T;
#[inline] const CAPACITY: usize = CAP;
fn deref(&self) -> &[A::Item] {
unsafe {
slice::from_raw_parts(self.xs.ptr(), self.len())
}
}
}
impl<A: Array> DerefMut for ArrayVec<A> {
#[inline]
fn deref_mut(&mut self) -> &mut [A::Item] {
let len = self.len();
unsafe {
slice::from_raw_parts_mut(self.xs.ptr_mut(), len)
}
}
}
impl<A: Array> ArrayVecImpl for ArrayVec<A> {
type Item = A::Item;
const CAPACITY: usize = A::CAPACITY;
fn len(&self) -> usize { self.len() } fn len(&self) -> usize { self.len() }
unsafe fn set_len(&mut self, length: usize) { self.set_len(length) }
/// Return a slice containing all elements of the vector. unsafe fn set_len(&mut self, length: usize) {
fn as_slice(&self) -> &[A::Item] { debug_assert!(length <= CAP);
self self.len = length;
} }
/// Return a mutable slice containing all elements of the vector. fn as_ptr(&self) -> *const Self::Item {
fn as_mut_slice(&mut self) -> &mut [A::Item] { self.xs.as_ptr() as _
self
} }
/// Return a raw pointer to the vector's buffer. fn as_mut_ptr(&mut self) -> *mut Self::Item {
fn as_ptr(&self) -> *const A::Item { self.xs.as_mut_ptr() as _
self.xs.ptr()
} }
}
/// Return a raw mutable pointer to the vector's buffer. impl<T, const CAP: usize> Deref for ArrayVec<T, CAP> {
fn as_mut_ptr(&mut self) -> *mut A::Item { type Target = [T];
self.xs.ptr_mut() #[inline]
fn deref(&self) -> &Self::Target {
self.as_slice()
}
}
impl<T, const CAP: usize> DerefMut for ArrayVec<T, CAP> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
self.as_mut_slice()
} }
} }
@@ -681,9 +673,16 @@ impl<A: Array> ArrayVecImpl for ArrayVec<A> {
/// assert_eq!(array.len(), 3); /// assert_eq!(array.len(), 3);
/// assert_eq!(array.capacity(), 3); /// assert_eq!(array.capacity(), 3);
/// ``` /// ```
impl<A: Array> From<A> for ArrayVec<A> { impl<T, const CAP: usize> From<[T; CAP]> for ArrayVec<T, CAP> {
fn from(array: A) -> Self { fn from(array: [T; CAP]) -> Self {
ArrayVec { xs: MaybeUninit::from(array), len: Index::from(A::CAPACITY) } let array = ManuallyDrop::new(array);
let mut vec = <ArrayVec<T, CAP>>::new();
unsafe {
(&*array as *const [T; CAP] as *const [MaybeUninit<T>; CAP])
.copy_to_nonoverlapping(&mut vec.xs as *mut [MaybeUninit<T>; CAP], 1);
}
vec
} }
} }
@@ -699,14 +698,13 @@ impl<A: Array> From<A> for ArrayVec<A> {
/// assert_eq!(array.len(), 3); /// assert_eq!(array.len(), 3);
/// assert_eq!(array.capacity(), 4); /// assert_eq!(array.capacity(), 4);
/// ``` /// ```
impl<A: Array> std::convert::TryFrom<&[A::Item]> for ArrayVec<A> impl<T, const CAP: usize> std::convert::TryFrom<&[T]> for ArrayVec<T, CAP>
where where T: Clone,
A::Item: Clone,
{ {
type Error = CapacityError; type Error = CapacityError;
fn try_from(slice: &[A::Item]) -> Result<Self, Self::Error> { fn try_from(slice: &[T]) -> Result<Self, Self::Error> {
if A::CAPACITY < slice.len() { if Self::CAPACITY < slice.len() {
Err(CapacityError::new(())) Err(CapacityError::new(()))
} else { } else {
let mut array = Self::new(); let mut array = Self::new();
@@ -728,9 +726,9 @@ impl<A: Array> std::convert::TryFrom<&[A::Item]> for ArrayVec<A>
/// // ... /// // ...
/// } /// }
/// ``` /// ```
impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> { impl<'a, T: 'a, const CAP: usize> IntoIterator for &'a ArrayVec<T, CAP> {
type Item = &'a A::Item; type Item = &'a T;
type IntoIter = slice::Iter<'a, A::Item>; type IntoIter = slice::Iter<'a, T>;
fn into_iter(self) -> Self::IntoIter { self.iter() } fn into_iter(self) -> Self::IntoIter { self.iter() }
} }
@@ -745,9 +743,9 @@ impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> {
/// // ... /// // ...
/// } /// }
/// ``` /// ```
impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> { impl<'a, T: 'a, const CAP: usize> IntoIterator for &'a mut ArrayVec<T, CAP> {
type Item = &'a mut A::Item; type Item = &'a mut T;
type IntoIter = slice::IterMut<'a, A::Item>; type IntoIter = slice::IterMut<'a, T>;
fn into_iter(self) -> Self::IntoIter { self.iter_mut() } fn into_iter(self) -> Self::IntoIter { self.iter_mut() }
} }
@@ -762,44 +760,44 @@ impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> {
/// // ... /// // ...
/// } /// }
/// ``` /// ```
impl<A: Array> IntoIterator for ArrayVec<A> { impl<T, const CAP: usize> IntoIterator for ArrayVec<T, CAP> {
type Item = A::Item; type Item = T;
type IntoIter = IntoIter<A>; type IntoIter = IntoIter<T, CAP>;
fn into_iter(self) -> IntoIter<A> { fn into_iter(self) -> IntoIter<T, CAP> {
IntoIter { index: Index::from(0), v: self, } IntoIter { index: Index::from(0), v: self, }
} }
} }
/// By-value iterator for `ArrayVec`. /// By-value iterator for `ArrayVec`.
pub struct IntoIter<A: Array> { pub struct IntoIter<T, const CAP: usize> {
index: A::Index, index: usize,
v: ArrayVec<A>, v: ArrayVec<T, CAP>,
} }
impl<A: Array> Iterator for IntoIter<A> { impl<T, const CAP: usize> Iterator for IntoIter<T, CAP> {
type Item = A::Item; type Item = T;
fn next(&mut self) -> Option<A::Item> { fn next(&mut self) -> Option<Self::Item> {
if self.index == self.v.len { if self.index == self.v.len {
None None
} else { } else {
unsafe { unsafe {
let index = self.index.to_usize(); let index = self.index;
self.index = Index::from(index + 1); self.index = index + 1;
Some(ptr::read(self.v.get_unchecked_ptr(index))) Some(ptr::read(self.v.get_unchecked_ptr(index)))
} }
} }
} }
fn size_hint(&self) -> (usize, Option<usize>) { fn size_hint(&self) -> (usize, Option<usize>) {
let len = self.v.len() - self.index.to_usize(); let len = self.v.len() - self.index;
(len, Some(len)) (len, Some(len))
} }
} }
impl<A: Array> DoubleEndedIterator for IntoIter<A> { impl<T, const CAP: usize> DoubleEndedIterator for IntoIter<T, CAP> {
fn next_back(&mut self) -> Option<A::Item> { fn next_back(&mut self) -> Option<Self::Item> {
if self.index == self.v.len { if self.index == self.v.len {
None None
} else { } else {
@@ -812,12 +810,12 @@ impl<A: Array> DoubleEndedIterator for IntoIter<A> {
} }
} }
impl<A: Array> ExactSizeIterator for IntoIter<A> { } impl<T, const CAP: usize> ExactSizeIterator for IntoIter<T, CAP> { }
impl<A: Array> Drop for IntoIter<A> { impl<T, const CAP: usize> Drop for IntoIter<T, CAP> {
fn drop(&mut self) { fn drop(&mut self) {
// panic safety: Set length to 0 before dropping elements. // panic safety: Set length to 0 before dropping elements.
let index = self.index.to_usize(); let index = self.index;
let len = self.v.len(); let len = self.v.len();
unsafe { unsafe {
self.v.set_len(0); self.v.set_len(0);
@@ -829,51 +827,45 @@ impl<A: Array> Drop for IntoIter<A> {
} }
} }
impl<A: Array> Clone for IntoIter<A> impl<T, const CAP: usize> Clone for IntoIter<T, CAP>
where where T: Clone,
A::Item: Clone,
{ {
fn clone(&self) -> IntoIter<A> { fn clone(&self) -> IntoIter<T, CAP> {
self.v[self.index.to_usize()..] self.v[self.index..]
.iter() .iter()
.cloned() .cloned()
.collect::<ArrayVec<A>>() .collect::<ArrayVec<T, CAP>>()
.into_iter() .into_iter()
} }
} }
impl<A: Array> fmt::Debug for IntoIter<A> impl<T, const CAP: usize> fmt::Debug for IntoIter<T, CAP>
where where
A::Item: fmt::Debug, T: fmt::Debug,
{ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.debug_list() f.debug_list()
.entries(&self.v[self.index.to_usize()..]) .entries(&self.v[self.index..])
.finish() .finish()
} }
} }
/// A draining iterator for `ArrayVec`. /// A draining iterator for `ArrayVec`.
pub struct Drain<'a, A> pub struct Drain<'a, T: 'a, const CAP: usize> {
where A: Array,
A::Item: 'a,
{
/// Index of tail to preserve /// Index of tail to preserve
tail_start: usize, tail_start: usize,
/// Length of tail /// Length of tail
tail_len: usize, tail_len: usize,
/// Current remaining range to remove /// Current remaining range to remove
iter: slice::Iter<'a, A::Item>, iter: slice::Iter<'a, T>,
vec: *mut ArrayVec<A>, vec: *mut ArrayVec<T, CAP>,
} }
unsafe impl<'a, A: Array + Sync> Sync for Drain<'a, A> {} unsafe impl<'a, T: Sync, const CAP: usize> Sync for Drain<'a, T, CAP> {}
unsafe impl<'a, A: Array + Send> Send for Drain<'a, A> {} unsafe impl<'a, T: Send, const CAP: usize> Send for Drain<'a, T, CAP> {}
impl<'a, A: Array> Iterator for Drain<'a, A> impl<'a, T: 'a, const CAP: usize> Iterator for Drain<'a, T, CAP> {
where A::Item: 'a, type Item = T;
{
type Item = A::Item;
fn next(&mut self) -> Option<Self::Item> { fn next(&mut self) -> Option<Self::Item> {
self.iter.next().map(|elt| self.iter.next().map(|elt|
@@ -888,8 +880,7 @@ impl<'a, A: Array> Iterator for Drain<'a, A>
} }
} }
impl<'a, A: Array> DoubleEndedIterator for Drain<'a, A> impl<'a, T: 'a, const CAP: usize> DoubleEndedIterator for Drain<'a, T, CAP>
where A::Item: 'a,
{ {
fn next_back(&mut self) -> Option<Self::Item> { fn next_back(&mut self) -> Option<Self::Item> {
self.iter.next_back().map(|elt| self.iter.next_back().map(|elt|
@@ -900,11 +891,9 @@ impl<'a, A: Array> DoubleEndedIterator for Drain<'a, A>
} }
} }
impl<'a, A: Array> ExactSizeIterator for Drain<'a, A> where A::Item: 'a {} impl<'a, T: 'a, const CAP: usize> ExactSizeIterator for Drain<'a, T, CAP> {}
impl<'a, A: Array> Drop for Drain<'a, A> impl<'a, T: 'a, const CAP: usize> Drop for Drain<'a, T, CAP> {
where A::Item: 'a
{
fn drop(&mut self) { fn drop(&mut self) {
// len is currently 0 so panicking while dropping will not cause a double drop. // len is currently 0 so panicking while dropping will not cause a double drop.
@@ -948,8 +937,8 @@ impl<T, Data, F> Drop for ScopeExitGuard<T, Data, F>
/// ///
/// Does not extract more items than there is space for. No error /// Does not extract more items than there is space for. No error
/// occurs if there are more iterator elements. /// occurs if there are more iterator elements.
impl<A: Array> Extend<A::Item> for ArrayVec<A> { impl<T, const CAP: usize> Extend<T> for ArrayVec<T, CAP> {
fn extend<T: IntoIterator<Item=A::Item>>(&mut self, iter: T) { fn extend<I: IntoIterator<Item=T>>(&mut self, iter: I) {
let take = self.capacity() - self.len(); let take = self.capacity() - self.len();
unsafe { unsafe {
let len = self.len(); let len = self.len();
@@ -1003,16 +992,16 @@ unsafe fn raw_ptr_write<T>(ptr: *mut T, value: T) {
/// ///
/// Does not extract more items than there is space for. No error /// Does not extract more items than there is space for. No error
/// occurs if there are more iterator elements. /// occurs if there are more iterator elements.
impl<A: Array> iter::FromIterator<A::Item> for ArrayVec<A> { impl<T, const CAP: usize> iter::FromIterator<T> for ArrayVec<T, CAP> {
fn from_iter<T: IntoIterator<Item=A::Item>>(iter: T) -> Self { fn from_iter<I: IntoIterator<Item=T>>(iter: I) -> Self {
let mut array = ArrayVec::new(); let mut array = ArrayVec::new();
array.extend(iter); array.extend(iter);
array array
} }
} }
impl<A: Array> Clone for ArrayVec<A> impl<T, const CAP: usize> Clone for ArrayVec<T, CAP>
where A::Item: Clone where T: Clone
{ {
fn clone(&self) -> Self { fn clone(&self) -> Self {
self.iter().cloned().collect() self.iter().cloned().collect()
@@ -1035,61 +1024,61 @@ impl<A: Array> Clone for ArrayVec<A>
} }
} }
impl<A: Array> Hash for ArrayVec<A> impl<T, const CAP: usize> Hash for ArrayVec<T, CAP>
where A::Item: Hash where T: Hash
{ {
fn hash<H: Hasher>(&self, state: &mut H) { fn hash<H: Hasher>(&self, state: &mut H) {
Hash::hash(&**self, state) Hash::hash(&**self, state)
} }
} }
impl<A: Array> PartialEq for ArrayVec<A> impl<T, const CAP: usize> PartialEq for ArrayVec<T, CAP>
where A::Item: PartialEq where T: PartialEq
{ {
fn eq(&self, other: &Self) -> bool { fn eq(&self, other: &Self) -> bool {
**self == **other **self == **other
} }
} }
impl<A: Array> PartialEq<[A::Item]> for ArrayVec<A> impl<T, const CAP: usize> PartialEq<[T]> for ArrayVec<T, CAP>
where A::Item: PartialEq where T: PartialEq
{ {
fn eq(&self, other: &[A::Item]) -> bool { fn eq(&self, other: &[T]) -> bool {
**self == *other **self == *other
} }
} }
impl<A: Array> Eq for ArrayVec<A> where A::Item: Eq { } impl<T, const CAP: usize> Eq for ArrayVec<T, CAP> where T: Eq { }
impl<A: Array> Borrow<[A::Item]> for ArrayVec<A> { impl<T, const CAP: usize> Borrow<[T]> for ArrayVec<T, CAP> {
fn borrow(&self) -> &[A::Item] { self } fn borrow(&self) -> &[T] { self }
} }
impl<A: Array> BorrowMut<[A::Item]> for ArrayVec<A> { impl<T, const CAP: usize> BorrowMut<[T]> for ArrayVec<T, CAP> {
fn borrow_mut(&mut self) -> &mut [A::Item] { self } fn borrow_mut(&mut self) -> &mut [T] { self }
} }
impl<A: Array> AsRef<[A::Item]> for ArrayVec<A> { impl<T, const CAP: usize> AsRef<[T]> for ArrayVec<T, CAP> {
fn as_ref(&self) -> &[A::Item] { self } fn as_ref(&self) -> &[T] { self }
} }
impl<A: Array> AsMut<[A::Item]> for ArrayVec<A> { impl<T, const CAP: usize> AsMut<[T]> for ArrayVec<T, CAP> {
fn as_mut(&mut self) -> &mut [A::Item] { self } fn as_mut(&mut self) -> &mut [T] { self }
} }
impl<A: Array> fmt::Debug for ArrayVec<A> where A::Item: fmt::Debug { impl<T, const CAP: usize> fmt::Debug for ArrayVec<T, CAP> where T: fmt::Debug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) }
} }
impl<A: Array> Default for ArrayVec<A> { impl<T, const CAP: usize> Default for ArrayVec<T, CAP> {
/// Return an empty array /// Return an empty array
fn default() -> ArrayVec<A> { fn default() -> ArrayVec<T, CAP> {
ArrayVec::new() ArrayVec::new()
} }
} }
impl<A: Array> PartialOrd for ArrayVec<A> where A::Item: PartialOrd { impl<T, const CAP: usize> PartialOrd for ArrayVec<T, CAP> where T: PartialOrd {
fn partial_cmp(&self, other: &ArrayVec<A>) -> Option<cmp::Ordering> { fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
(**self).partial_cmp(other) (**self).partial_cmp(other)
} }
@@ -1110,8 +1099,8 @@ impl<A: Array> PartialOrd for ArrayVec<A> where A::Item: PartialOrd {
} }
} }
impl<A: Array> Ord for ArrayVec<A> where A::Item: Ord { impl<T, const CAP: usize> Ord for ArrayVec<T, CAP> where T: Ord {
fn cmp(&self, other: &ArrayVec<A>) -> cmp::Ordering { fn cmp(&self, other: &Self) -> cmp::Ordering {
(**self).cmp(other) (**self).cmp(other)
} }
} }
@@ -1120,7 +1109,7 @@ impl<A: Array> Ord for ArrayVec<A> where A::Item: Ord {
/// `Write` appends written data to the end of the vector. /// `Write` appends written data to the end of the vector.
/// ///
/// Requires `features="std"`. /// Requires `features="std"`.
impl<A: Array<Item=u8>> io::Write for ArrayVec<A> { impl<const CAP: usize> io::Write for ArrayVec<u8, CAP> {
fn write(&mut self, data: &[u8]) -> io::Result<usize> { fn write(&mut self, data: &[u8]) -> io::Result<usize> {
let len = cmp::min(self.remaining_capacity(), data.len()); let len = cmp::min(self.remaining_capacity(), data.len());
let _result = self.try_extend_from_slice(&data[..len]); let _result = self.try_extend_from_slice(&data[..len]);
@@ -1132,7 +1121,7 @@ impl<A: Array<Item=u8>> io::Write for ArrayVec<A> {
#[cfg(feature="serde")] #[cfg(feature="serde")]
/// Requires crate feature `"serde"` /// Requires crate feature `"serde"`
impl<T: Serialize, A: Array<Item=T>> Serialize for ArrayVec<A> { impl<T: Serialize, const CAP: usize> Serialize for ArrayVec<T, CAP> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer where S: Serializer
{ {
@@ -1142,17 +1131,17 @@ impl<T: Serialize, A: Array<Item=T>> Serialize for ArrayVec<A> {
#[cfg(feature="serde")] #[cfg(feature="serde")]
/// Requires crate feature `"serde"` /// Requires crate feature `"serde"`
impl<'de, T: Deserialize<'de>, A: Array<Item=T>> Deserialize<'de> for ArrayVec<A> { impl<'de, T: Deserialize<'de>, const CAP: usize> Deserialize<'de> for ArrayVec<T, CAP> {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de> where D: Deserializer<'de>
{ {
use serde::de::{Visitor, SeqAccess, Error}; use serde::de::{Visitor, SeqAccess, Error};
use std::marker::PhantomData; use std::marker::PhantomData;
struct ArrayVecVisitor<'de, T: Deserialize<'de>, A: Array<Item=T>>(PhantomData<(&'de (), T, A)>); struct ArrayVecVisitor<'de, T: Deserialize<'de>, const CAP: usize>(PhantomData<(&'de (), [T; CAP])>);
impl<'de, T: Deserialize<'de>, A: Array<Item=T>> Visitor<'de> for ArrayVecVisitor<'de, T, A> { impl<'de, T: Deserialize<'de>, const CAP: usize> Visitor<'de> for ArrayVecVisitor<'de, T, CAP> {
type Value = ArrayVec<A>; type Value = ArrayVec<T, CAP>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(formatter, "an array with no more than {} items", A::CAPACITY) write!(formatter, "an array with no more than {} items", A::CAPACITY)
@@ -1173,6 +1162,6 @@ impl<'de, T: Deserialize<'de>, A: Array<Item=T>> Deserialize<'de> for ArrayVec<A
} }
} }
deserializer.deserialize_seq(ArrayVecVisitor::<T, A>(PhantomData)) deserializer.deserialize_seq(ArrayVecVisitor::<T, CAP>(PhantomData))
} }
} }
+16 -4
View File
@@ -1,4 +1,5 @@
use std::ptr; use std::ptr;
use std::slice;
use crate::CapacityError; use crate::CapacityError;
@@ -13,10 +14,20 @@ pub(crate) trait ArrayVecImpl {
unsafe fn set_len(&mut self, new_len: usize); unsafe fn set_len(&mut self, new_len: usize);
/// Return a slice containing all elements of the vector. /// Return a slice containing all elements of the vector.
fn as_slice(&self) -> &[Self::Item]; fn as_slice(&self) -> &[Self::Item] {
let len = self.len();
unsafe {
slice::from_raw_parts(self.as_ptr(), len)
}
}
/// Return a mutable slice containing all elements of the vector. /// Return a mutable slice containing all elements of the vector.
fn as_mut_slice(&mut self) -> &mut [Self::Item]; fn as_mut_slice(&mut self) -> &mut [Self::Item] {
let len = self.len();
unsafe {
std::slice::from_raw_parts_mut(self.as_mut_ptr(), len)
}
}
/// Return a raw pointer to the vector's buffer. /// Return a raw pointer to the vector's buffer.
fn as_ptr(&self) -> *const Self::Item; fn as_ptr(&self) -> *const Self::Item;
@@ -63,9 +74,10 @@ pub(crate) trait ArrayVecImpl {
fn truncate(&mut self, new_len: usize) { fn truncate(&mut self, new_len: usize) {
unsafe { unsafe {
if new_len < self.len() { let len = self.len();
let tail: *mut [_] = &mut self.as_mut_slice()[new_len..]; if new_len < len {
self.set_len(new_len); self.set_len(new_len);
let tail = slice::from_raw_parts_mut(self.as_mut_ptr().add(new_len), len - new_len);
ptr::drop_in_place(tail); ptr::drop_in_place(tail);
} }
} }