diff --git a/README.md b/README.md index 153476b4..c1dd9540 100644 --- a/README.md +++ b/README.md @@ -64,7 +64,7 @@ v.sort(); - `serde`: implements serde's serialization and deserialization - `specialization` (nightly): enables specialization, improving performance on some cases -- `std`: implements the `std::io::Write` type for `SmallVec` +- `std`: implements the `std::io::Write` type for `SmallVec` - `zeroize`: implements `zeroize::Zeroize`, erasing elements and storage > [!NOTE] diff --git a/src/borsh.rs b/src/borsh.rs index ee6ff3fa..dcce21ee 100644 --- a/src/borsh.rs +++ b/src/borsh.rs @@ -26,8 +26,8 @@ use { core::iter::repeat_with }; -impl BorshSerialize - for SmallVec +impl BorshSerialize + for SmallVec { fn serialize(&self, writer: &mut Writer) -> Serial<()> { (self.len() as u64).serialize(writer)?; @@ -39,12 +39,12 @@ impl BorshSerialize } } -impl BorshDeserialize - for SmallVec +impl BorshDeserialize + for SmallVec { fn deserialize_reader(reader: &mut R) -> Serial { let length = u64::deserialize_reader(reader)?; - repeat_with(|| Type::deserialize_reader(reader)) + repeat_with(|| Item::deserialize_reader(reader)) .take(length.try_into().map_err(|_| Error::new( ErrorKind::OutOfMemory, "Cannot deserialize a sequence with more than usize::MAX elements in this machine" @@ -53,11 +53,11 @@ impl BorshDeserialize } } -impl BorshSchema - for SmallVec +impl BorshSchema + for SmallVec { fn declaration() -> Declaration { - format!("Vec<{}>", Type::declaration()) + format!("Vec<{}>", Item::declaration()) } fn add_definitions_recursively(definitions: &mut Map) { @@ -65,13 +65,13 @@ impl BorshSchema if definitions.contains_key(&declaration) { return; } - Type::add_definitions_recursively(definitions); + Item::add_definitions_recursively(definitions); definitions.insert( declaration, Definition::Sequence { length_width: 8, length_range: 0..=u64::MAX, - elements: Type::declaration() + elements: Item::declaration() } ); } diff --git a/src/comparisons.rs b/src/comparisons.rs index ce70048d..79fc6090 100644 --- a/src/comparisons.rs +++ b/src/comparisons.rs @@ -12,9 +12,9 @@ use { macro_rules! __impl_slice_eq1 { ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?) => { - impl PartialEq<$rhs> for $lhs + impl PartialEq<$rhs> for $lhs where - T: PartialEq, + Item: PartialEq, $($ty: $bound)? { #[inline] @@ -23,25 +23,29 @@ macro_rules! __impl_slice_eq1 { }; } -__impl_slice_eq1! { [const M: usize, A2: Allocator] SmallVec, SmallVec } -__impl_slice_eq1! { [const M: usize] SmallVec, [U; N] } -__impl_slice_eq1! { [const M: usize] SmallVec, &[U; N] } -__impl_slice_eq1! { [] SmallVec, [U] } -__impl_slice_eq1! { [] SmallVec, &[U] } -__impl_slice_eq1! { [] SmallVec, &mut [U] } -__impl_slice_eq1! { [] [T], SmallVec } -__impl_slice_eq1! { [] &[T], SmallVec } -__impl_slice_eq1! { [] &mut [T], SmallVec } -__impl_slice_eq1! { [] Vec, SmallVec } -__impl_slice_eq1! { [] SmallVec, Vec } -__impl_slice_eq1! { [] Cow<'_, [T]>, SmallVec where T: Clone } -__impl_slice_eq1! { [] SmallVec, Cow<'_, [U]> where U: Clone } +__impl_slice_eq1! { [const M: usize, A2: Allocator] + SmallVec, + SmallVec +} +__impl_slice_eq1! { [const M: usize] SmallVec, [U; INLINE] } +__impl_slice_eq1! { [const M: usize] SmallVec, &[U; INLINE] } +__impl_slice_eq1! { [] SmallVec, [U] } +__impl_slice_eq1! { [] SmallVec, &[U] } +__impl_slice_eq1! { [] SmallVec, &mut [U] } +__impl_slice_eq1! { [] [Item], SmallVec } +__impl_slice_eq1! { [] &[Item], SmallVec } +__impl_slice_eq1! { [] &mut [Item], SmallVec } +__impl_slice_eq1! { [] Vec, SmallVec } +__impl_slice_eq1! { [] SmallVec, Vec } +__impl_slice_eq1! { [] Cow<'_, [Item]>, SmallVec where Item: Clone } +__impl_slice_eq1! { [] SmallVec, Cow<'_, [U]> where U: Clone } -impl PartialEq> for VecDeque -where T: PartialEq +impl PartialEq> + for VecDeque +where Item: PartialEq { #[inline] - fn eq(&self, other: &SmallVec) -> bool { + fn eq(&self, other: &SmallVec) -> bool { let other = other.as_slice(); if self.len() != other.len() { return false; @@ -52,22 +56,22 @@ where T: PartialEq } } -impl Eq for SmallVec where T: Eq {} +impl Eq for SmallVec {} -impl PartialOrd for SmallVec -where T: PartialOrd +impl PartialOrd for SmallVec +where Item: PartialOrd { #[inline] - fn partial_cmp(&self, other: &SmallVec) -> Option { + fn partial_cmp(&self, other: &SmallVec) -> Option { self.as_slice().partial_cmp(other.as_slice()) } } -impl Ord for SmallVec -where T: Ord +impl Ord for SmallVec +where Item: Ord { #[inline] - fn cmp(&self, other: &SmallVec) -> core::cmp::Ordering { + fn cmp(&self, other: &SmallVec) -> core::cmp::Ordering { self.as_slice().cmp(other.as_slice()) } } diff --git a/src/conversions.rs b/src/conversions.rs index 13cde585..d21da884 100644 --- a/src/conversions.rs +++ b/src/conversions.rs @@ -12,9 +12,9 @@ use { } }; -impl From<&[T]> for SmallVec { +impl From<&[Item]> for SmallVec { #[inline] - fn from(slice: &[T]) -> Self { + fn from(slice: &[Item]) -> Self { if slice.len() > Self::inline_size() { // Standard Rust vectors are already specialized. Self::from_vec(Vec::from(slice)) @@ -24,7 +24,7 @@ impl From<&[T]> for SmallVec { unsafe { #[cfg(feature = "specialization")] { - >::spec_from(slice) + >::spec_from(slice) } #[cfg(not(feature = "specialization"))] @@ -36,35 +36,39 @@ impl From<&[T]> for SmallVec { } } -impl From<&mut [T]> for SmallVec { +impl From<&mut [Item]> for SmallVec { #[inline] - fn from(slice: &mut [T]) -> Self { - Self::from(slice as &[T]) + fn from(slice: &mut [Item]) -> Self { + Self::from(slice as &[Item]) } } -impl From<&[T; M]> for SmallVec { +impl From<&[Item; M]> + for SmallVec +{ #[inline] - fn from(slice: &[T; M]) -> Self { - Self::from(slice as &[T]) + fn from(slice: &[Item; M]) -> Self { + Self::from(slice as &[Item]) } } -impl From<&mut [T; M]> for SmallVec { +impl From<&mut [Item; M]> + for SmallVec +{ #[inline] - fn from(slice: &mut [T; M]) -> Self { - Self::from(slice as &[T]) + fn from(slice: &mut [Item; M]) -> Self { + Self::from(slice as &[Item]) } } -impl From<[T; M]> for SmallVec { - fn from(array: [T; M]) -> Self { - if M > N { - // If M > N, we'd have to heap allocate anyway, +impl From<[Item; M]> for SmallVec { + fn from(array: [Item; M]) -> Self { + if M > INLINE { + // If M > INLINE, we'd have to heap allocate anyway, // so delegate for Vec for the allocation. Self::from(Vec::from(array)) } else { - // M <= N + // M <= INLINE let mut this = Self::new(); debug_assert!(M <= this.capacity()); let array = ManuallyDrop::new(array); @@ -78,11 +82,15 @@ impl From<[T; M]> for SmallVec } } -impl TryFrom> for [T; M] { - type Error = SmallVec; +impl + TryFrom> for [Item; M] +{ + type Error = SmallVec; #[inline] - fn try_from(mut this: SmallVec) -> Result<[T; M], SmallVec> { + fn try_from( + mut this: SmallVec + ) -> Result<[Item; M], SmallVec> { if this.len() != M { Err(this) } else { @@ -90,21 +98,21 @@ impl TryFrom> unsafe { this.set_len(0); } - let ptr = this.as_ptr() as *const [T; M]; + let ptr = this.as_ptr() as *const [Item; M]; // SAFETY: these elements are initialized since the length was `M` unsafe { Ok(ptr.read()) } } } } -impl From> for SmallVec { - fn from(array: Vec) -> Self { +impl From> for SmallVec { + fn from(array: Vec) -> Self { Self::from_vec(array) } } -impl From> for Vec { - fn from(this: SmallVec) -> Self { +impl From> for Vec { + fn from(this: SmallVec) -> Self { let (length, on_heap) = this.length.parts(); if !on_heap { let mut vec = Vec::with_capacity(length); @@ -122,10 +130,10 @@ impl From> for Vec { let this = ManuallyDrop::new(this); // SAFETY: // - `ptr` was created with the SmallVec's allocator - // - `ptr` was created with the appropriate alignment for `T` - // - the allocation pointed to by ptr is exactly cap * sizeof(T) + // - `ptr` was created with the appropriate alignment for `Item` + // - the allocation pointed to by ptr is exactly cap * sizeof(Item) // - `length` is less than or equal to `cap` - // - the first `length` entries are proper `T`-values + // - the first `length` entries are proper `Item`-values // - the allocation is not larger than `isize::MAX` unsafe { let (ptr, cap) = this.raw.heap; @@ -135,8 +143,10 @@ impl From> for Vec { } } -impl From> for Box<[T]> { - fn from(this: SmallVec) -> Self { +impl From> + for Box<[Item]> +{ + fn from(this: SmallVec) -> Self { Vec::from(this).into_boxed_slice() } } diff --git a/src/iterators/drain.rs b/src/iterators/drain.rs index 3297ac78..edf77343 100644 --- a/src/iterators/drain.rs +++ b/src/iterators/drain.rs @@ -11,7 +11,7 @@ use crate::{ /// Returned from [`SmallVec::drain`][1]. /// /// [1]: struct.SmallVec.html#method.drain -pub struct Drain<'a, T: 'a, const N: usize, A: Allocator = Global> { +pub struct Drain<'a, Item: 'a, const INLINE: usize, Heap: Allocator = Global> { // `vec` points to a valid object within its lifetime. // This is ensured by the fact that we're holding an iterator to its items. // @@ -21,15 +21,17 @@ pub struct Drain<'a, T: 'a, const N: usize, A: Allocator = Global> { // even though vec has length < tail_start pub(crate) tail_start: usize, pub(crate) tail_len: usize, - pub(crate) iter: core::slice::Iter<'a, T>, - pub(crate) vec: core::ptr::NonNull> + pub(crate) iter: core::slice::Iter<'a, Item>, + pub(crate) vec: core::ptr::NonNull> } -impl<'a, T: 'a, const N: usize, A: Allocator> Iterator for Drain<'a, T, N, A> { - type Item = T; +impl<'a, Item: 'a, const INLINE: usize, Heap: Allocator> Iterator + for Drain<'a, Item, INLINE, Heap> +{ + type Item = Item; #[inline] - fn next(&mut self) -> Option { + fn next(&mut self) -> Option { // SAFETY: we shrunk the length of the vector so it no longer owns these // items, and we can take ownership of them. self.iter @@ -43,9 +45,11 @@ impl<'a, T: 'a, const N: usize, A: Allocator> Iterator for Drain<'a, T, N, A> { } } -impl<'a, T: 'a, const N: usize, A: Allocator> DoubleEndedIterator for Drain<'a, T, N, A> { +impl<'a, Item: 'a, const INLINE: usize, Heap: Allocator> DoubleEndedIterator + for Drain<'a, Item, INLINE, Heap> +{ #[inline] - fn next_back(&mut self) -> Option { + fn next_back(&mut self) -> Option { // SAFETY: see above self.iter .next_back() @@ -53,21 +57,30 @@ impl<'a, T: 'a, const N: usize, A: Allocator> DoubleEndedIterator for Drain<'a, } } -impl ExactSizeIterator for Drain<'_, T, N, A> { +impl ExactSizeIterator + for Drain<'_, Item, INLINE, Heap> +{ #[inline] fn len(&self) -> usize { self.iter.len() } } -impl core::iter::FusedIterator for Drain<'_, T, N, A> {} +impl core::iter::FusedIterator + for Drain<'_, Item, INLINE, Heap> +{ +} -impl<'a, T: 'a, const N: usize, A: Allocator> Drop for Drain<'a, T, N, A> { +impl<'a, Item: 'a, const INLINE: usize, Heap: Allocator> Drop for Drain<'a, Item, INLINE, Heap> { fn drop(&mut self) { /// Moves back the un-`Drain`ed elements to restore the original `Vec`. - struct DropGuard<'r, 'a, T, const N: usize, A: Allocator>(&'r mut Drain<'a, T, N, A>); + struct DropGuard<'r, 'a, Item, const INLINE: usize, Heap: Allocator>( + &'r mut Drain<'a, Item, INLINE, Heap> + ); - impl<'r, 'a, T, const N: usize, A: Allocator> Drop for DropGuard<'r, 'a, T, N, A> { + impl<'r, 'a, Item, const INLINE: usize, Heap: Allocator> Drop + for DropGuard<'r, 'a, Item, INLINE, Heap> + { fn drop(&mut self) { if self.0.tail_len > 0 { unsafe { @@ -92,7 +105,7 @@ impl<'a, T: 'a, const N: usize, A: Allocator> Drop for Drain<'a, T, N, A> { let mut vec = self.vec; - if SmallVec::::IS_ZST { + if SmallVec::::IS_ZST { // ZSTs have no identity, so we don't need to move them around, we // only need to drop the correct amount. this can be // achieved by manipulating the Vec length instead of @@ -123,12 +136,13 @@ impl<'a, T: 'a, const N: usize, A: Allocator> Drop for Drain<'a, T, N, A> { let drop_ptr = iter.as_slice().as_ptr(); unsafe { - // drop_ptr comes from a slice::Iter which only gives us a &[T] but - // for drop_in_place a pointer with mutable provenance - // is necessary. Therefore we must reconstruct it from - // the original vec but also avoid creating a &mut to - // the front since that could invalidate raw pointers to - // it which some unsafe code might rely on. + // drop_ptr comes from a slice::Iter which only gives us a &[Item] + // but for drop_in_place a pointer with mutable + // provenance is necessary. Therefore we must + // reconstruct it from the original vec but also avoid + // creating a &mut to the front since that could + // invalidate raw pointers to it which some unsafe code + // might rely on. let vec_ptr = vec.as_mut().as_mut_ptr(); // May be replaced with the line below later, once this crate's MSRV // is >= 1.87. let drop_offset = @@ -140,9 +154,9 @@ impl<'a, T: 'a, const N: usize, A: Allocator> Drop for Drain<'a, T, N, A> { } } -impl Drain<'_, T, N, A> { +impl Drain<'_, Item, INLINE, Heap> { #[must_use] - pub fn as_slice(&self) -> &[T] { + pub fn as_slice(&self) -> &[Item] { self.iter.as_slice() } @@ -151,7 +165,7 @@ impl Drain<'_, T, N, A> { /// Fill that range as much as possible with new elements from the /// `replace_with` iterator. Returns `true` if we filled the entire /// range. (`replace_with.next()` didn’t return `None`.) - pub(crate) unsafe fn fill>(&mut self, replace_with: &mut I) -> bool { + pub(crate) unsafe fn fill>(&mut self, replace_with: &mut I) -> bool { let vec = unsafe { self.vec.as_mut() }; let range_end = self.tail_start; @@ -196,7 +210,9 @@ impl Drain<'_, T, N, A> { } } -impl core::fmt::Debug for Drain<'_, T, N, A> { +impl core::fmt::Debug + for Drain<'_, Item, INLINE, Heap> +{ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("Drain").field(&self.iter.as_slice()).finish() } diff --git a/src/iterators/extractif.rs b/src/iterators/extractif.rs index edd0c5b5..f53b8f65 100644 --- a/src/iterators/extractif.rs +++ b/src/iterators/extractif.rs @@ -10,10 +10,10 @@ use crate::{ /// Returned from [`SmallVec::extract_if`][1]. /// /// [1]: struct.SmallVec.html#method.extract_if -pub struct ExtractIf<'a, T, const N: usize, F, A: Allocator = Global> -where F: FnMut(&mut T) -> bool +pub struct ExtractIf<'a, Item, const INLINE: usize, F, Heap: Allocator = Global> +where F: FnMut(&mut Item) -> bool { - pub(crate) vec: &'a mut SmallVec, + pub(crate) vec: &'a mut SmallVec, /// The index of the item that will be inspected by the next call to `next`. pub(crate) idx: usize, /// Elements at and beyond this point will be retained. Must be equal or @@ -27,10 +27,11 @@ where F: FnMut(&mut T) -> bool pub(crate) pred: F } -impl core::fmt::Debug for ExtractIf<'_, T, N, F, A> +impl core::fmt::Debug + for ExtractIf<'_, Item, INLINE, F, Heap> where - F: FnMut(&mut T) -> bool, - T: core::fmt::Debug + F: FnMut(&mut Item) -> bool, + Item: core::fmt::Debug { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("ExtractIf") @@ -39,12 +40,13 @@ where } } -impl Iterator for ExtractIf<'_, T, N, F, A> -where F: FnMut(&mut T) -> bool +impl Iterator + for ExtractIf<'_, Item, INLINE, F, Heap> +where F: FnMut(&mut Item) -> bool { - type Item = T; + type Item = Item; - fn next(&mut self) -> Option { + fn next(&mut self) -> Option { unsafe { while self.idx < self.end { let i = self.idx; @@ -73,8 +75,8 @@ where F: FnMut(&mut T) -> bool } } -impl Drop for ExtractIf<'_, T, N, F, A> -where F: FnMut(&mut T) -> bool +impl Drop for ExtractIf<'_, Item, INLINE, F, Heap> +where F: FnMut(&mut Item) -> bool { fn drop(&mut self) { unsafe { diff --git a/src/iterators/intoiter.rs b/src/iterators/intoiter.rs index f8a7ad0e..1d305e37 100644 --- a/src/iterators/intoiter.rs +++ b/src/iterators/intoiter.rs @@ -23,27 +23,33 @@ use { /// Returned from [`SmallVec::into_iter`][1]. /// /// [1]: struct.SmallVec.html#method.into_iter -pub struct IntoIter { +pub struct IntoIter { // # Safety // // `end` decides whether the data lives on the heap or not // // The members from begin..end are initialized - raw: RawSmallVec, - allocator: A, + raw: RawSmallVec, + allocator: Heap, begin: usize, - end: LocatedLength + end: LocatedLength } // SAFETY: IntoIter has unique ownership of its contents. Sending (or sharing) -// an `IntoIter` is equivalent to sending (or sharing) a `SmallVec`. -unsafe impl Send for IntoIter {} -unsafe impl Sync for IntoIter {} +// an `IntoIter` is equivalent to sending (or sharing) a +// `SmallVec`. +unsafe impl Send + for IntoIter +{ +} +unsafe impl Sync + for IntoIter +{ +} -impl IntoIter { +impl IntoIter { #[inline] - pub const fn as_slice(&self) -> &[T] { + pub const fn as_slice(&self) -> &[Item] { let (end, on_heap) = self.end.parts(); // SAFETY: `end` tells which buffer is active, and the members in // `self.begin..end` are all initialized. So the pointer arithmetic is @@ -55,7 +61,7 @@ impl IntoIter { } #[inline] - pub const fn as_mut_slice(&mut self) -> &mut [T] { + pub const fn as_mut_slice(&mut self) -> &mut [Item] { let (end, on_heap) = self.end.parts(); // SAFETY: see above unsafe { @@ -70,8 +76,8 @@ impl IntoIter { } } -impl Iterator for IntoIter { - type Item = T; +impl Iterator for IntoIter { + type Item = Item; #[inline] fn next(&mut self) -> Option { @@ -96,7 +102,9 @@ impl Iterator for IntoIter { } } -impl DoubleEndedIterator for IntoIter { +impl DoubleEndedIterator + for IntoIter +{ #[inline] fn next_back(&mut self) -> Option { let (end, on_heap) = self.end.parts(); @@ -114,10 +122,16 @@ impl DoubleEndedIterator for IntoIter } } -impl ExactSizeIterator for IntoIter {} -impl core::iter::FusedIterator for IntoIter {} +impl ExactSizeIterator + for IntoIter +{ +} +impl core::iter::FusedIterator + for IntoIter +{ +} -impl Drop for IntoIter { +impl Drop for IntoIter { fn drop(&mut self) { // SAFETY: see above unsafe { @@ -128,8 +142,8 @@ impl Drop for IntoIter { let capacity = self.raw.heap.1; Some(DropDealloc { ptr: NonNull::new_unchecked(ptr as *mut u8), - size_bytes: capacity * size_of::(), - align: align_of::(), + size_bytes: capacity * size_of::(), + align: align_of::(), allocator: &self.allocator }) } else { @@ -140,9 +154,11 @@ impl Drop for IntoIter { } } -impl Clone for IntoIter { +impl Clone + for IntoIter +{ #[inline] - fn clone(&self) -> IntoIter { + fn clone(&self) -> IntoIter { let mut vec = SmallVec { length: LocatedLength::new(0, false), raw: RawSmallVec::new(), @@ -155,9 +171,9 @@ impl Clone for IntoIter } } -impl IntoIterator for SmallVec { - type IntoIter = IntoIter; - type Item = T; +impl IntoIterator for SmallVec { + type IntoIter = IntoIter; + type Item = Item; fn into_iter(self) -> Self::IntoIter { // SAFETY: we move out of this.raw by reading the value at its address, @@ -176,7 +192,7 @@ impl IntoIterator for SmallVec { } } -impl Debug for IntoIter { +impl Debug for IntoIter { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("IntoIter").field(&self.as_slice()).finish() } diff --git a/src/iterators/rayon.rs b/src/iterators/rayon.rs index 048f82e4..c567b292 100644 --- a/src/iterators/rayon.rs +++ b/src/iterators/rayon.rs @@ -24,41 +24,41 @@ use { } }; -struct SliceDrain<'a, T>(slice::IterMut<'a, T>); +struct SliceDrain<'a, Item>(slice::IterMut<'a, Item>); -impl Iterator for SliceDrain<'_, T> { - type Item = T; +impl Iterator for SliceDrain<'_, Item> { + type Item = Item; - fn next(&mut self) -> Option { + fn next(&mut self) -> Option { self.0.next().map(|val| unsafe { ptr::read(val) }) } } -impl DoubleEndedIterator for SliceDrain<'_, T> { - fn next_back(&mut self) -> Option { +impl DoubleEndedIterator for SliceDrain<'_, Item> { + fn next_back(&mut self) -> Option { self.0.next_back().map(|val| unsafe { ptr::read(val) }) } } -impl ExactSizeIterator for SliceDrain<'_, T> { +impl ExactSizeIterator for SliceDrain<'_, Item> { fn len(&self) -> usize { self.0.len() } } -impl Drop for SliceDrain<'_, T> { +impl Drop for SliceDrain<'_, Item> { fn drop(&mut self) { unsafe { drop_in_place(take(&mut self.0).into_slice()) }; } } -struct DrainProducer<'a, T>(&'a mut [T]); +struct DrainProducer<'a, Item>(&'a mut [Item]); -impl<'a, T: Send> Producer for DrainProducer<'a, T> { - type IntoIter = SliceDrain<'a, T>; - type Item = T; +impl<'a, Item: Send> Producer for DrainProducer<'a, Item> { + type IntoIter = SliceDrain<'a, Item>; + type Item = Item; - fn into_iter(mut self) -> SliceDrain<'a, T> { + fn into_iter(mut self) -> SliceDrain<'a, Item> { SliceDrain(take(&mut self.0).iter_mut()) } @@ -69,16 +69,18 @@ impl<'a, T: Send> Producer for DrainProducer<'a, T> { } } -impl Drop for DrainProducer<'_, T> { +impl Drop for DrainProducer<'_, Item> { fn drop(&mut self) { unsafe { drop_in_place(self.0) }; } } -impl ParallelIterator for SmallVec { - type Item = T; +impl ParallelIterator + for SmallVec +{ + type Item = Item; - fn drive_unindexed>(mut self, consumer: C) -> C::Result { + fn drive_unindexed>(mut self, consumer: C) -> C::Result { let length = self.len(); bridge_producer_consumer( diff --git a/src/iterators/splice.rs b/src/iterators/splice.rs index f827b6f0..bee64a74 100644 --- a/src/iterators/splice.rs +++ b/src/iterators/splice.rs @@ -8,13 +8,13 @@ use super::{ drain::Drain }; -pub struct Splice<'a, I: Iterator + 'a, const N: usize, A: Allocator = Global> { - drain: Drain<'a, I::Item, N, A>, +pub struct Splice<'a, I: Iterator + 'a, const INLINE: usize, Heap: Allocator = Global> { + drain: Drain<'a, I::Item, INLINE, Heap>, replace_with: I } -impl<'a, I: Iterator + 'a, const N: usize, A: Allocator> Splice<'a, I, N, A> { - pub(crate) fn new(drain: Drain<'a, I::Item, N, A>, replace_with: I) -> Self { +impl<'a, I: Iterator + 'a, const INLINE: usize, Heap: Allocator> Splice<'a, I, INLINE, Heap> { + pub(crate) fn new(drain: Drain<'a, I::Item, INLINE, Heap>, replace_with: I) -> Self { Self { drain, replace_with @@ -22,7 +22,7 @@ impl<'a, I: Iterator + 'a, const N: usize, A: Allocator> Splice<'a, I, N, A> { } } -impl<'a, I, const N: usize, A: Allocator> core::fmt::Debug for Splice<'a, I, N, A> +impl<'a, I, const INLINE: usize, Heap: Allocator> core::fmt::Debug for Splice<'a, I, INLINE, Heap> where I: core::fmt::Debug + Iterator + 'a, ::Item: core::fmt::Debug @@ -32,7 +32,7 @@ where } } -impl Iterator for Splice<'_, I, N, A> { +impl Iterator for Splice<'_, I, INLINE, Heap> { type Item = I::Item; fn next(&mut self) -> Option { @@ -44,15 +44,20 @@ impl Iterator for Splice<'_, I, N, A> } } -impl DoubleEndedIterator for Splice<'_, I, N, A> { +impl DoubleEndedIterator + for Splice<'_, I, INLINE, Heap> +{ fn next_back(&mut self) -> Option { self.drain.next_back() } } -impl ExactSizeIterator for Splice<'_, I, N, A> {} +impl ExactSizeIterator + for Splice<'_, I, INLINE, Heap> +{ +} -impl Drop for Splice<'_, I, N, A> { +impl Drop for Splice<'_, I, INLINE, Heap> { fn drop(&mut self) { self.drain.by_ref().for_each(drop); // At this point draining is done and the only remaining tasks are @@ -85,7 +90,7 @@ impl Drop for Splice<'_, I, N, A> { } let mut smallvec = - SmallVec::<_, N, _>::new_in(Proxy(&self.drain.vec.as_ref().allocator)); + SmallVec::<_, INLINE, _>::new_in(Proxy(&self.drain.vec.as_ref().allocator)); smallvec.extend(self.replace_with.by_ref()); let mut collected = smallvec.into_iter(); diff --git a/src/lib.rs b/src/lib.rs index f70aa017..dbd6390f 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -99,25 +99,31 @@ use { }; #[repr(C)] -pub struct SmallVec { - length: LocatedLength, - raw: RawSmallVec, - allocator: A +pub struct SmallVec { + length: LocatedLength, + raw: RawSmallVec, + allocator: Heap } -unsafe impl Send for SmallVec {} -unsafe impl Sync for SmallVec {} +unsafe impl Send + for SmallVec +{ +} +unsafe impl Sync + for SmallVec +{ +} -impl Default for SmallVec { +impl Default for SmallVec { #[inline] fn default() -> Self { Self::new() } } -impl SmallVec { +impl SmallVec { #[inline] - pub const fn new() -> SmallVec { + pub const fn new() -> SmallVec { Self::new_in(Global) } @@ -131,21 +137,21 @@ impl SmallVec { } #[inline] - pub const fn from_buf(elements: [T; S]) -> Self { + pub const fn from_buf(elements: [Item; S]) -> Self { const { - assert!(S <= N); + assert!(S <= INLINE); } - // Although we create a new buffer, since S and N are known at compile - // time, even with `-C opt-level=1`, it gets optimized as best - // as it could be. (Checked with ) - let mut buf: MaybeUninit<[T; N]> = MaybeUninit::uninit(); + // Although we create a new buffer, since S and INLINE are known at + // compile time, even with `-C opt-level=1`, it gets optimized + // as best as it could be. (Checked with ) + let mut buf: MaybeUninit<[Item; INLINE]> = MaybeUninit::uninit(); // SAFETY: buf and elements do not overlap, are aligned and have space - // for at least S elements since S <= N. + // for at least S elements since S <= INLINE. // We will drop the elements only once since we do forget(elements). unsafe { - copy_nonoverlapping(elements.as_ptr(), buf.as_mut_ptr() as *mut T, S); + copy_nonoverlapping(elements.as_ptr(), buf.as_mut_ptr() as *mut Item, S); } // `elements` have been moved into buf and will be dropped by SmallVec @@ -160,8 +166,8 @@ impl SmallVec { } #[inline] - pub fn from_buf_and_len(buf: [T; N], length: usize) -> Self { - assert!(length <= N); + pub fn from_buf_and_len(buf: [Item; INLINE], length: usize) -> Self { + assert!(length <= INLINE); // SAFETY: all the members in 0..length are initialized let mut vec = Self { length: LocatedLength::new(length, false), @@ -173,7 +179,7 @@ impl SmallVec { // SAFETY: both the input and output pointers are in range of the // stack allocation let remainder_ptr = vec.raw.as_mut_ptr_inline().add(length); - let remainder_len = N - length; + let remainder_len = INLINE - length; // SAFETY: the values are initialized, so dropping them here is // fine. @@ -188,7 +194,7 @@ impl SmallVec { /// Constructs a new `SmallVec` on the stack from a buffer without copying /// elements. Also sets the length. The user is responsible for ensuring - /// that `length <= N`. + /// that `length <= INLINE`. /// /// # Examples /// @@ -206,14 +212,14 @@ impl SmallVec { /// /// # Safety /// - /// `length <= N`, and all the elements in `buf[..length]` must be + /// `length <= INLINE`, and all the elements in `buf[..length]` must be /// initialized #[inline] pub const unsafe fn from_buf_and_len_unchecked( - buf: MaybeUninit<[T; N]>, + buf: MaybeUninit<[Item; INLINE]>, length: usize ) -> Self { - debug_assert!(length <= N); + debug_assert!(length <= INLINE); Self { length: LocatedLength::new(length, false), raw: RawSmallVec::new_inline(buf), @@ -222,7 +228,7 @@ impl SmallVec { } #[inline] - pub fn from_vec(vec: Vec) -> Self { + pub fn from_vec(vec: Vec) -> Self { if vec.capacity() == 0 { return Self::new(); } @@ -250,9 +256,9 @@ impl SmallVec { let length = vec.len(); // A heap-allocated `SmallVec` must always observe the invariant - // that `cap > N`. - if vec.capacity() <= N { - vec.reserve(N + 1 - length); + // that `cap > INLINE`. + if vec.capacity() <= INLINE { + vec.reserve(INLINE + 1 - length); } let cap = vec.capacity(); // SAFETY: vec.capacity is not `0` (checked above), so the pointer @@ -278,8 +284,8 @@ impl SmallVec { /// - `ptr` needs to have been previously allocated via `SmallVec` from its /// spilled storage (at least, it’s highly likely to be incorrect if it /// wasn’t). - /// - `ptr`’s `T` type needs to be the same size and alignment that it was - /// allocated with + /// - `ptr`’s `Item` type needs to be the same size and alignment that it + /// was allocated with /// - `length` needs to be less than or equal to `capacity`. /// - `capacity` needs to be the capacity that the pointer was allocated /// with. @@ -287,7 +293,7 @@ impl SmallVec { /// Violating these may cause problems like corrupting the allocator’s /// internal data structures. /// - /// Additionally, `capacity` must be greater than `N`; that is, the new + /// Additionally, `capacity` must be greater than `INLINE`; that is, the new /// `SmallVec` must need to spill over into heap allocated storage. This /// condition is asserted against. /// @@ -332,10 +338,10 @@ impl SmallVec { /// ``` #[inline] pub unsafe fn from_raw_parts( - ptr: *mut T, + ptr: *mut Item, length: usize, capacity: usize - ) -> SmallVec { + ) -> SmallVec { assert!(!Self::IS_ZST); // SAFETY: We require caller to provide same ptr as we alloc @@ -353,11 +359,11 @@ impl SmallVec { } } -impl SmallVec { +impl SmallVec { /// A function for creating [`SmallVec`] values out of slices /// for types with the [`Copy`] trait. - pub fn from_slice_copy(slice: &[T]) -> Self - where T: Copy { + pub fn from_slice_copy(slice: &[Item]) -> Self + where Item: Copy { let source = slice.as_ptr(); let length = slice.len(); let mut result = Self::with_capacity(length); @@ -374,8 +380,8 @@ impl SmallVec { } } -impl SmallVec { - const IS_ZST: bool = size_of::() == 0; +impl SmallVec { + const IS_ZST: bool = size_of::() == 0; /// Sets the length of a vector. /// @@ -395,7 +401,7 @@ impl SmallVec { #[inline] pub const fn inline_size() -> usize { - RawSmallVec::::INLINE_CAP + RawSmallVec::::INLINE_CAP } #[inline] @@ -420,7 +426,7 @@ impl SmallVec { self.length.on_heap() } - pub fn drain(&mut self, range: R) -> Drain<'_, T, N, A> + pub fn drain(&mut self, range: R) -> Drain<'_, Item, INLINE, Heap> where R: core::ops::RangeBounds { let length = self.len(); let core::ops::Range { @@ -531,9 +537,9 @@ impl SmallVec { /// ); /// assert_eq!(ones.len(), 3); /// ``` - pub fn extract_if(&mut self, range: R, filter: F) -> ExtractIf<'_, T, N, F, A> + pub fn extract_if(&mut self, range: R, filter: F) -> ExtractIf<'_, Item, INLINE, F, Heap> where - F: FnMut(&mut T) -> bool, + F: FnMut(&mut Item) -> bool, R: core::ops::RangeBounds { let old_len = self.len(); @@ -557,22 +563,26 @@ impl SmallVec { } } - pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, N, A> + pub fn splice( + &mut self, + range: R, + replace_with: I + ) -> Splice<'_, I::IntoIter, INLINE, Heap> where R: core::ops::RangeBounds, - I: IntoIterator + I: IntoIterator { Splice::new(self.drain(range), replace_with.into_iter()) } #[inline] - pub fn push(&mut self, value: T) { + pub fn push(&mut self, value: Item) { _ = self.push_mut(value); } #[inline] #[must_use] - pub fn push_mut(&mut self, value: T) -> &mut T { + pub fn push_mut(&mut self, value: Item) -> &mut Item { let length = self.len(); if length == self.capacity() { self.reserve(1); @@ -605,7 +615,7 @@ impl SmallVec { } #[inline] - pub fn pop(&mut self) -> Option { + pub fn pop(&mut self) -> Option { let length = self.len(); if length == 0 { return None; @@ -623,13 +633,13 @@ impl SmallVec { } #[inline] - pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option { + pub fn pop_if(&mut self, predicate: impl FnOnce(&mut Item) -> bool) -> Option { let last = self.last_mut()?; if predicate(last) { self.pop() } else { None } } #[inline] - pub fn append(&mut self, other: &mut SmallVec) { + pub fn append(&mut self, other: &mut SmallVec) { // can't overflow since both are smaller than isize::MAX and 2 * // isize::MAX < usize::MAX let length = self.len(); @@ -690,8 +700,8 @@ impl SmallVec { copy_nonoverlapping(ptr.as_ptr(), self.raw.as_mut_ptr_inline(), length); drop(DropDealloc { ptr: ptr.cast(), - size_bytes: old_cap * size_of::(), - align: align_of::(), + size_bytes: old_cap * size_of::(), + align: align_of::(), allocator: &self.allocator }); self.length.set_location::(); @@ -761,14 +771,17 @@ impl SmallVec { self.length.set_location::(); self.allocator.deallocate( ptr.cast(), - Layout::from_size_align_unchecked(capacity * size_of::(), align_of::()) + Layout::from_size_align_unchecked( + capacity * size_of::(), + align_of::() + ) ); } } else if length < self.capacity() { // SAFETY: length > Self::inline_size() >= 0 // so new capacity is non zero, it is equal to the length - // T can't be a ZST because SmallVec is never - // spilled. + // Item can't be a ZST because SmallVec is + // never spilled. unsafe { self.raw .try_grow_raw(self.length, length, &self.allocator) @@ -796,16 +809,16 @@ impl SmallVec { self.allocator.deallocate( ptr.cast(), Layout::from_size_align_unchecked( - capacity * size_of::(), - align_of::() + capacity * size_of::(), + align_of::() ) ); } } else if target < capacity { // SAFETY: length > Self::inline_size() >= 0 // so new capacity is non zero, it is equal to the length - // T can't be a ZST because SmallVec is never - // spilled. + // Item can't be a ZST because SmallVec is + // never spilled. unsafe { self.raw .try_grow_raw(self.length, target, &self.allocator) @@ -832,7 +845,7 @@ impl SmallVec { } #[inline] - pub fn swap_remove(&mut self, index: usize) -> T { + pub fn swap_remove(&mut self, index: usize) -> Item { #[cold] #[inline(never)] #[track_caller] @@ -873,7 +886,7 @@ impl SmallVec { } #[inline] - pub fn remove(&mut self, index: usize) -> T { + pub fn remove(&mut self, index: usize) -> Item { #[cold] #[inline(never)] #[track_caller] @@ -899,13 +912,13 @@ impl SmallVec { } #[inline] - pub fn insert(&mut self, index: usize, value: T) { + pub fn insert(&mut self, index: usize, value: Item) { _ = self.insert_mut(index, value); } #[inline] #[must_use] - pub fn insert_mut(&mut self, index: usize, value: T) -> &mut T { + pub fn insert_mut(&mut self, index: usize, value: Item) -> &mut Item { #[cold] #[inline(never)] #[track_caller] @@ -933,7 +946,7 @@ impl SmallVec { unsafe { copy(ptr, ptr.add(1), length - index) }; } - // SAFETY: the slot at `index` is free and properly aligned for `T`. + // SAFETY: the slot at `index` is free and properly aligned for `Item`. unsafe { ptr.write(value) }; // LEGAL: all elements in `0..length + 1` are initialized. @@ -955,50 +968,50 @@ impl SmallVec { } #[inline] - pub const fn as_slice(&self) -> &[T] { + pub const fn as_slice(&self) -> &[Item] { let (length, on_heap) = self.length.parts(); // SAFETY: all the elements in `..length` are initialized unsafe { core::slice::from_raw_parts(self.raw.as_ptr(on_heap), length) } } #[inline] - pub const fn as_mut_slice(&mut self) -> &mut [T] { + pub const fn as_mut_slice(&mut self) -> &mut [Item] { let (length, on_heap) = self.length.parts(); // SAFETY: see above unsafe { core::slice::from_raw_parts_mut(self.raw.as_mut_ptr(on_heap), length) } } #[inline] - pub const fn as_ptr(&self) -> *const T { + pub const fn as_ptr(&self) -> *const Item { // SAFETY: the tag tells which member is active unsafe { self.raw.as_ptr(self.length.on_heap()) } } #[inline] - pub const fn as_mut_ptr(&mut self) -> *mut T { + pub const fn as_mut_ptr(&mut self) -> *mut Item { // SAFETY: see above unsafe { self.raw.as_mut_ptr(self.length.on_heap()) } } #[inline] - #[deprecated(since = "2.0.0", note = "use `Into::>::into` instead")] - pub fn into_vec(self) -> Vec { + #[deprecated(since = "2.0.0", note = "use `Into::>::into` instead")] + pub fn into_vec(self) -> Vec { self.into() } #[inline] - #[deprecated(since = "2.0.0", note = "use `Into::>::into` instead")] - pub fn into_boxed_slice(self) -> Box<[T]> { + #[deprecated(since = "2.0.0", note = "use `Into::>::into` instead")] + pub fn into_boxed_slice(self) -> Box<[Item]> { self.into() } #[inline] #[deprecated( since = "2.0.0-alpha.13", - note = "use `TryInto::<[T; N]>::try_into` instead" + note = "use `TryInto::<[Item; INLINE]>::try_into` instead" )] - pub fn into_inner(self) -> Result<[T; N], Self> { - if self.len() != N { + pub fn into_inner(self) -> Result<[Item; INLINE], Self> { + if self.len() != INLINE { Err(self) } else { // when `this` is dropped, the memory is released if it's on the @@ -1008,19 +1021,20 @@ impl SmallVec { unsafe { this.set_len(0); } - let ptr = this.as_ptr() as *const [T; N]; - // SAFETY: these elements are initialized since the length was `N` + let ptr = this.as_ptr() as *const [Item; INLINE]; + // SAFETY: these elements are initialized since the length was + // `INLINE` unsafe { Ok(ptr.read()) } } } #[inline] - pub fn retain bool>(&mut self, mut f: F) { + pub fn retain bool>(&mut self, mut f: F) { self.retain_mut(|elem| f(elem)) } #[inline] - pub fn retain_mut bool>(&mut self, mut f: F) { + pub fn retain_mut bool>(&mut self, mut f: F) { let original_len = self.len(); if original_len == 0 { @@ -1040,14 +1054,14 @@ impl SmallVec { // panicked. It shifts unchecked elements to cover holes and // `set_len` to the correct length. In cases when predicate and // `drop` never panic, it will be optimized out. - struct PanicGuard<'a, T, const N: usize, A: Allocator> { - v: &'a mut SmallVec, + struct Guard<'a, Item, const INLINE: usize, Heap: Allocator> { + v: &'a mut SmallVec, read: usize, write: usize, original_len: usize } - impl Drop for PanicGuard<'_, T, N, A> { + impl Drop for Guard<'_, Item, INLINE, Heap> { #[cold] fn drop(&mut self) { let remaining = self.original_len - self.read; @@ -1082,7 +1096,7 @@ impl SmallVec { // Critical section starts here and at least one element is going to be // removed. Advance `g.read` early to avoid double drop if // `drop_in_place` panicked. - let mut g = PanicGuard { + let mut g = Guard { v: self, read: read + 1, write: read, @@ -1123,14 +1137,14 @@ impl SmallVec { #[inline] pub fn dedup(&mut self) - where T: PartialEq { + where Item: PartialEq { self.dedup_by(|a, b| a == b); } #[inline] pub fn dedup_by_key(&mut self, mut key: F) where - F: FnMut(&mut T) -> K, + F: FnMut(&mut Item) -> K, K: PartialEq { self.dedup_by(|a, b| key(a) == key(b)); @@ -1138,7 +1152,7 @@ impl SmallVec { #[inline] pub fn dedup_by(&mut self, mut same_bucket: F) - where F: FnMut(&mut T, &mut T) -> bool { + where F: FnMut(&mut Item, &mut Item) -> bool { // See the implementation of Vec::dedup_by in the // standard library for an explanation of this algorithm. let length = self.len(); @@ -1167,7 +1181,7 @@ impl SmallVec { } pub fn resize_with(&mut self, new_len: usize, f: F) - where F: FnMut() -> T { + where F: FnMut() -> Item { let old_len = self.len(); if old_len < new_len { self.extend(core::iter::repeat_with(f).take(new_len - old_len)); @@ -1176,7 +1190,7 @@ impl SmallVec { } } - pub fn leak<'a>(self) -> &'a mut [T] { + pub fn leak<'a>(self) -> &'a mut [Item] { let (length, on_heap) = self.length.parts(); if !on_heap { panic!( @@ -1188,24 +1202,24 @@ impl SmallVec { } /// Returns the remaining spare capacity of the vector as a slice of - /// `MaybeUninit`. + /// `MaybeUninit`. /// /// The returned slice can be used to fill the vector with data (e.g. by /// reading from a file) before marking the data as initialized using the /// [`set_len`](Self::set_len) method. #[inline] - pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { + pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit] { let (length, on_heap) = self.length.parts(); unsafe { let capacity = self.raw.capacity(on_heap); core::slice::from_raw_parts_mut( - self.raw.as_mut_ptr(on_heap).add(length) as *mut MaybeUninit, + self.raw.as_mut_ptr(on_heap).add(length) as *mut MaybeUninit, capacity - length ) } } - /// Decomposes a `SmallVec` into its raw components: + /// Decomposes a `SmallVec` into its raw components: /// `(pointer, length, capacity)`. /// /// Returns the raw pointer to the underlying data, the length of @@ -1217,9 +1231,9 @@ impl SmallVec { /// memory previously managed by the `SmallVec`. Most often, one does /// this by converting the raw pointer, length, and capacity back /// into a `SmallVec` with the [`from_raw_parts`] function; more generally, - /// if `T` is non-zero-sized and the capacity is nonzero, one may use + /// if `Item` is non-zero-sized and the capacity is nonzero, one may use /// any method that calls [`dealloc`] with a layout of - /// `Layout::array::(capacity)`; if `T` is zero-sized or the + /// `Layout::array::(capacity)`; if `Item` is zero-sized or the /// capacity is zero, nothing needs to be done. /// /// [`from_raw_parts`]: SmallVec::from_raw_parts @@ -1247,7 +1261,7 @@ impl SmallVec { /// assert_eq!(rebuilt, [4294967295, 0, 1]); /// ``` #[inline] - pub fn into_raw_parts(self) -> (*mut T, usize, usize) { + pub fn into_raw_parts(self) -> (*mut Item, usize, usize) { #[cold] #[inline(never)] #[track_caller] @@ -1266,8 +1280,8 @@ impl SmallVec { } #[inline] - pub fn extend_from_slice_copy(&mut self, other: &[T]) - where T: Copy { + pub fn extend_from_slice_copy(&mut self, other: &[Item]) + where Item: Copy { let length = other.len(); let source = other.as_ptr(); @@ -1286,7 +1300,7 @@ impl SmallVec { pub fn extend_from_within_copy(&mut self, source: R) where R: core::ops::RangeBounds, - T: Copy + Item: Copy { let source = core::ops::Range::new(source, self.len()); let core::ops::Range { @@ -1307,8 +1321,8 @@ impl SmallVec { } } - pub fn insert_from_slice_copy(&mut self, index: usize, other: &[T]) - where T: Copy { + pub fn insert_from_slice_copy(&mut self, index: usize, other: &[Item]) + where Item: Copy { let l = self.len(); let length = other.len(); assert!(index <= l); @@ -1328,7 +1342,7 @@ impl SmallVec { } } - pub const fn new_in(allocator: A) -> SmallVec { + pub const fn new_in(allocator: Heap) -> SmallVec { Self { length: LocatedLength::new(0, false), raw: RawSmallVec::new(), @@ -1336,7 +1350,7 @@ impl SmallVec { } } - pub fn try_with_capacity_in(capacity: usize, allocator: A) -> Result { + pub fn try_with_capacity_in(capacity: usize, allocator: Heap) -> Result { let mut this = Self::new_in(allocator); if capacity > Self::inline_size() && !Self::IS_ZST { // SAFETY: we checked all the preconditions @@ -1351,14 +1365,14 @@ impl SmallVec { Ok(this) } - pub fn with_capacity_in(capacity: usize, allocator: A) -> Self { + pub fn with_capacity_in(capacity: usize, allocator: Heap) -> Self { Self::try_with_capacity_in(capacity, allocator).unwrap_or_else(SmallVecError::handle) } } -impl SmallVec { +impl SmallVec { #[inline] - pub fn resize(&mut self, length: usize, value: T) { + pub fn resize(&mut self, length: usize, value: Item) { let old_len = self.len(); if length > old_len { self.extend(core::iter::repeat_n(value, length - old_len)); @@ -1368,7 +1382,7 @@ impl SmallVec { } #[inline] - pub fn extend_from_slice(&mut self, other: &[T]) { + pub fn extend_from_slice(&mut self, other: &[Item]) { self.extend(other.iter()) } @@ -1383,7 +1397,7 @@ impl SmallVec { unsafe { #[cfg(feature = "specialization")] { - >::spec_extend_from_within( + >::spec_extend_from_within( self, source ); } @@ -1396,7 +1410,7 @@ impl SmallVec { } } -impl SmallVec { +impl SmallVec { /// Splits the collection into two at the given index. /// /// Returns a newly allocated vector containing the elements in the range @@ -1443,11 +1457,11 @@ impl SmallVec { } } -struct DropGuard { - ptr: *mut T, +struct DropGuard { + ptr: *mut Item, length: usize } -impl Drop for DropGuard { +impl Drop for DropGuard { #[inline] fn drop(&mut self) { unsafe { @@ -1456,14 +1470,14 @@ impl Drop for DropGuard { } } -struct DropDealloc<'a, A: Allocator> { +struct DropDealloc<'a, Heap: Allocator> { ptr: NonNull, size_bytes: usize, align: usize, - allocator: &'a A + allocator: &'a Heap } -impl Drop for DropDealloc<'_, A> { +impl Drop for DropDealloc<'_, Heap> { #[inline] fn drop(&mut self) { unsafe { @@ -1477,7 +1491,7 @@ impl Drop for DropDealloc<'_, A> { } } -impl Drop for SmallVec { +impl Drop for SmallVec { fn drop(&mut self) { let (length, on_heap) = self.length.parts(); // SAFETY: the tag tells which member is active @@ -1488,8 +1502,8 @@ impl Drop for SmallVec { let capacity = self.raw.heap.1; Some(DropDealloc { ptr: NonNull::new_unchecked(ptr as *mut u8), - size_bytes: capacity * size_of::(), - align: align_of::(), + size_bytes: capacity * size_of::(), + align: align_of::(), allocator: &self.allocator }) } else { @@ -1504,8 +1518,11 @@ impl Drop for SmallVec { /// It is recommended to use the macro instead of using this function. #[doc(hidden)] #[track_caller] -pub fn from_elem(elem: T, n: usize) -> SmallVec { - if n > SmallVec::::inline_size() { +pub fn from_elem( + elem: Item, + n: usize +) -> SmallVec { + if n > SmallVec::::inline_size() { // Standard Rust vectors are already specialized. SmallVec::from_vec(vec![elem; n]) } else { @@ -1514,7 +1531,8 @@ pub fn from_elem(elem: T, n: usize) -> SmallVec as specialization::SpecFromElem>::spec_from_elem(elem, n) + + as specialization::SpecFromElem>::spec_from_elem(elem, n) } } @@ -1522,7 +1540,7 @@ pub fn from_elem(elem: T, n: usize) -> SmallVec::from_elem_fallback(elem, n) } + unsafe { SmallVec::::from_elem_fallback(elem, n) } } } } @@ -1530,15 +1548,15 @@ pub fn from_elem(elem: T, n: usize) -> SmallVec SmallVec { +impl SmallVec { /// Creates a `Smallvec` value where `elem` is repeated `n` times. /// This will use the inline storage, not the heap. /// /// # Safety /// /// The caller must ensure that `n <= Self::inline_size()`. - unsafe fn from_elem_fallback(elem: T, n: usize) -> Self - where T: Clone { + unsafe fn from_elem_fallback(elem: Item, n: usize) -> Self + where Item: Clone { let mut result = Self::new(); if n > 0 { @@ -1570,7 +1588,7 @@ impl SmallVec { } fn from_iter_fallback(iter: I) -> Self - where I: Iterator { + where I: Iterator { let (size, _) = iter.size_hint(); let mut v = Self::with_capacity(size); v.extend_fallback(iter); @@ -1583,8 +1601,8 @@ impl SmallVec { /// # Safety /// /// The caller must ensure that `slice.len() <= Self::inline_size()`. - unsafe fn from_slice_fallback(slice: &[T]) -> Self - where T: Clone { + unsafe fn from_slice_fallback(slice: &[Item]) -> Self + where Item: Clone { let mut v = Self::new(); let source = slice.as_ptr(); @@ -1615,9 +1633,9 @@ impl SmallVec { } } -impl SmallVec { +impl SmallVec { fn extend_fallback(&mut self, iter: I) - where I: IntoIterator { + where I: IntoIterator { let mut iterator = iter.into_iter(); while let Some(element) = iterator.next() { let length = self.len(); @@ -1646,7 +1664,7 @@ impl SmallVec { /// /// [`extend_from_within`]: SmallVec::extend_from_within unsafe fn extend_from_within_fallback(&mut self, source: core::ops::Range) - where T: Clone { + where Item: Clone { let old_len = self.len(); let start = source.start; @@ -1678,8 +1696,8 @@ impl SmallVec { } } - fn clone_from_fallback(&mut self, source: &[T]) - where T: Clone { + fn clone_from_fallback(&mut self, source: &[Item]) + where Item: Clone { // Inspired from `impl Clone for Vec`. // Drop anything that will not be overwritten. @@ -1695,9 +1713,11 @@ impl SmallVec { } } -impl Clone for SmallVec { +impl Clone + for SmallVec +{ #[inline] - fn clone(&self) -> SmallVec { + fn clone(&self) -> SmallVec { let mut vec = SmallVec { length: LocatedLength::new(0, false), raw: RawSmallVec::new(), @@ -1713,7 +1733,7 @@ impl Clone for SmallVec fn clone_from(&mut self, source: &Self) { #[cfg(feature = "specialization")] { - >::spec_clone_from(self, source); + >::spec_clone_from(self, source); } #[cfg(not(feature = "specialization"))] @@ -1723,12 +1743,12 @@ impl Clone for SmallVec } } -impl Extend for SmallVec { +impl Extend for SmallVec { #[inline] - fn extend>(&mut self, iter: I) { + fn extend>(&mut self, iter: I) { #[cfg(feature = "specialization")] { - specialization::SpecExtend::::spec_extend(self, iter.into_iter()); + specialization::SpecExtend::::spec_extend(self, iter.into_iter()); } #[cfg(not(feature = "specialization"))] @@ -1738,12 +1758,14 @@ impl Extend for SmallVec { } } -impl<'a, T: Clone + 'a, const N: usize, A: Allocator> Extend<&'a T> for SmallVec { +impl<'a, Item: Clone + 'a, const INLINE: usize, Heap: Allocator> Extend<&'a Item> + for SmallVec +{ #[inline] - fn extend>(&mut self, iter: I) { + fn extend>(&mut self, iter: I) { #[cfg(feature = "specialization")] { - specialization::SpecExtend::<&'a T, _>::spec_extend(self, iter.into_iter()); + specialization::SpecExtend::<&'a Item, _>::spec_extend(self, iter.into_iter()); } #[cfg(not(feature = "specialization"))] @@ -1753,12 +1775,12 @@ impl<'a, T: Clone + 'a, const N: usize, A: Allocator> Extend<&'a T> for SmallVec } } -impl core::iter::FromIterator for SmallVec { +impl core::iter::FromIterator for SmallVec { #[inline] - fn from_iter>(iter: I) -> Self { + fn from_iter>(iter: I) -> Self { #[cfg(feature = "specialization")] { - specialization::SpecFromIterator::::spec_from_iter(iter.into_iter()) + specialization::SpecFromIterator::::spec_from_iter(iter.into_iter()) } #[cfg(not(feature = "specialization"))] @@ -1768,38 +1790,42 @@ impl core::iter::FromIterator for SmallVec { } } -impl<'a, T, const N: usize, A: Allocator> IntoIterator for &'a SmallVec { - type IntoIter = core::slice::Iter<'a, T>; - type Item = &'a T; +impl<'a, Item, const INLINE: usize, Heap: Allocator> IntoIterator + for &'a SmallVec +{ + type IntoIter = core::slice::Iter<'a, Item>; + type Item = &'a Item; fn into_iter(self) -> Self::IntoIter { self.iter() } } -impl<'a, T, const N: usize, A: Allocator> IntoIterator for &'a mut SmallVec { - type IntoIter = core::slice::IterMut<'a, T>; - type Item = &'a mut T; +impl<'a, Item, const INLINE: usize, Heap: Allocator> IntoIterator + for &'a mut SmallVec +{ + type IntoIter = core::slice::IterMut<'a, Item>; + type Item = &'a mut Item; fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } -impl Hash for SmallVec { +impl Hash for SmallVec { fn hash(&self, state: &mut H) { self.as_slice().hash(state) } } -impl Debug for SmallVec { +impl Debug for SmallVec { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_list().entries(self.iter()).finish() } } #[cfg(feature = "zeroize")] -impl Zeroize for SmallVec { +impl Zeroize for SmallVec { fn zeroize(&mut self) { // Wipe the spare capacity before `clear` resets the length to zero, // otherwise it would cover the whole allocation and wipe the elements @@ -1816,8 +1842,8 @@ impl Zeroize for SmallVec { #[cfg(feature = "arbitrary")] #[cfg_attr(docsrs, doc(cfg(feature = "arbitrary")))] -impl<'a, T, const N: usize> arbitrary::Arbitrary<'a> for SmallVec -where T: arbitrary::Arbitrary<'a> +impl<'a, Item, const INLINE: usize> arbitrary::Arbitrary<'a> for SmallVec +where Item: arbitrary::Arbitrary<'a> { fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result { u.arbitrary_iter()?.collect() @@ -1834,7 +1860,7 @@ where T: arbitrary::Arbitrary<'a> #[cfg(feature = "std")] #[cfg_attr(docsrs, doc(cfg(feature = "std")))] -impl io::Write for SmallVec { +impl io::Write for SmallVec { #[inline] fn write(&mut self, buf: &[u8]) -> io::Result { self.extend_from_slice(buf); @@ -1854,7 +1880,7 @@ impl io::Write for SmallVec { } #[cfg(feature = "bytes")] -unsafe impl BufMut for SmallVec { +unsafe impl BufMut for SmallVec { #[inline] fn remaining_mut(&self) -> usize { // A vector can never have more than isize::MAX bytes @@ -1893,7 +1919,7 @@ unsafe impl BufMut for SmallVec { // Specialize these methods so they can skip checking `remaining_mut` // and `advance_mut`. #[inline] - fn put(&mut self, mut source: T) + fn put(&mut self, mut source: Item) where Self: Sized { // In case the source isn't contiguous, reserve upfront. self.reserve(source.remaining()); @@ -1920,11 +1946,16 @@ unsafe impl BufMut for SmallVec { } #[cfg(feature = "defmt")] -impl Format for SmallVec { +impl Format for SmallVec { fn format(&self, fmt: DeFormatter) { dewrite!(fmt, "{=[?]}", self.as_ref()); } } #[cfg(feature = "encase")] -encase::rts_array::impl_rts_array!(SmallVec; (T, const N: usize, A: Allocator); using len truncate); +// The encase macro requires the element type parameter to be named `T`. +encase::rts_array::impl_rts_array!( + SmallVec; + (T, const INLINE: usize, Heap: Allocator); + using len truncate +); diff --git a/src/locatedlength.rs b/src/locatedlength.rs index 8708efa9..fc833347 100644 --- a/src/locatedlength.rs +++ b/src/locatedlength.rs @@ -10,23 +10,23 @@ use core::marker::PhantomData; /// /// For a ZST, we never use the heap, so we just store the length directly. #[repr(transparent)] -pub struct LocatedLength(usize, PhantomData); +pub struct LocatedLength(usize, PhantomData); -// We don't use `#[derive(Clone, Copy)]` instead because `T` doesn't need to be -// `Copy` or `Clone`. -impl Clone for LocatedLength { +// We don't use `#[derive(Clone, Copy)]` instead because `Item` doesn't need to +// be `Copy` or `Clone`. +impl Clone for LocatedLength { #[inline] fn clone(&self) -> Self { *self } } -impl Copy for LocatedLength {} +impl Copy for LocatedLength {} #[allow(clippy::len_without_is_empty)] -impl LocatedLength { +impl LocatedLength { const MAX_LEN: usize = usize::MAX >> Self::SHIFT; - const SHIFT: u32 = (size_of::() != 0) as u32; + const SHIFT: u32 = (size_of::() != 0) as u32; const TAG: usize = Self::SHIFT as usize; #[inline(always)] diff --git a/src/mallocsizeof.rs b/src/mallocsizeof.rs index 0b30826a..151d09e2 100644 --- a/src/mallocsizeof.rs +++ b/src/mallocsizeof.rs @@ -10,7 +10,9 @@ use { } }; -impl MallocShallowSizeOf for SmallVec { +impl MallocShallowSizeOf + for SmallVec +{ fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize { self.spilled() .then(|| unsafe { ops.malloc_size_of(self.as_ptr()) }) @@ -18,7 +20,9 @@ impl MallocShallowSizeOf for SmallVec } } -impl MallocSizeOf for SmallVec { +impl MallocSizeOf + for SmallVec +{ fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize { self.shallow_size_of(ops) + self.iter().map(|item| item.size_of(ops)).sum::() } diff --git a/src/rawsmallvec.rs b/src/rawsmallvec.rs index 0330bc2e..b10b4845 100644 --- a/src/rawsmallvec.rs +++ b/src/rawsmallvec.rs @@ -18,14 +18,14 @@ use { }; #[repr(C)] -pub union RawSmallVec { - pub inline: ManuallyDrop>, - pub heap: (NonNull, usize) +pub union RawSmallVec { + pub inline: ManuallyDrop>, + pub heap: (NonNull, usize) } -impl RawSmallVec { - pub const INLINE_CAP: usize = if Self::IS_ZST { usize::MAX } else { N }; - const IS_ZST: bool = size_of::() == 0; +impl RawSmallVec { + pub const INLINE_CAP: usize = if Self::IS_ZST { usize::MAX } else { INLINE }; + const IS_ZST: bool = size_of::() == 0; #[inline] pub const fn new() -> Self { @@ -33,21 +33,21 @@ impl RawSmallVec { } #[inline] - pub const fn new_inline(inline: MaybeUninit<[T; N]>) -> Self { + pub const fn new_inline(inline: MaybeUninit<[Item; INLINE]>) -> Self { Self { inline: ManuallyDrop::new(inline) } } #[inline] - pub const fn new_heap(ptr: NonNull, capacity: usize) -> Self { + pub const fn new_heap(ptr: NonNull, capacity: usize) -> Self { Self { heap: (ptr, capacity) } } #[inline] - pub const fn as_ptr_inline(&self) -> *const T { + pub const fn as_ptr_inline(&self) -> *const Item { // SAFETY: it is safe because we aren't reading the value, just getting // a reference to it. reading it would be UB potentially, but // for that downstream unsafe is required @@ -56,7 +56,7 @@ impl RawSmallVec { } #[inline] - pub const fn as_mut_ptr_inline(&mut self) -> *mut T { + pub const fn as_mut_ptr_inline(&mut self) -> *mut Item { // SAFETY: same as above #[allow(unused_unsafe, reason = "Unsafe in MSRV")] (unsafe { &raw mut self.inline }).cast() @@ -66,7 +66,7 @@ impl RawSmallVec { /// /// `on_heap` must be true if and only if `self.heap` is the active member. #[inline(always)] - pub const unsafe fn as_ptr(&self, on_heap: bool) -> *const T { + pub const unsafe fn as_ptr(&self, on_heap: bool) -> *const Item { if on_heap { unsafe { self.heap.0.as_ptr() } } else { @@ -78,7 +78,7 @@ impl RawSmallVec { /// /// `on_heap` must be true if and only if `self.heap` is the active member. #[inline(always)] - pub const unsafe fn as_mut_ptr(&mut self, on_heap: bool) -> *mut T { + pub const unsafe fn as_mut_ptr(&mut self, on_heap: bool) -> *mut Item { if on_heap { unsafe { self.heap.0.as_ptr() } } else { @@ -101,14 +101,14 @@ impl RawSmallVec { /// # Safety /// /// `new_capacity` must be non zero, and greater or equal to the length. - /// T must not be a ZST. + /// Item must not be a ZST. /// /// the allocator must be the same one the data was allocated with - pub unsafe fn try_grow_raw( + pub unsafe fn try_grow_raw( &mut self, - length: LocatedLength, + length: LocatedLength, new_capacity: usize, - allocator: &A + allocator: &Heap ) -> Result<(), SmallVecError> { let (length, was_on_heap) = length.parts(); debug_assert!(!Self::IS_ZST); @@ -118,7 +118,7 @@ impl RawSmallVec { let ptr = unsafe { self.as_mut_ptr(was_on_heap) }; let new_layout = - Layout::array::(new_capacity).map_err(|_| SmallVecError::CapacityOverflow)?; + Layout::array::(new_capacity).map_err(|_| SmallVecError::CapacityOverflow)?; if new_layout.size() > isize::MAX as usize { return Err(SmallVecError::CapacityOverflow); } @@ -138,7 +138,10 @@ impl RawSmallVec { // this can't overflow since we already constructed an equivalent // layout during the previous allocation let old_layout = unsafe { - Layout::from_size_align_unchecked(self.heap.1 * size_of::(), align_of::()) + Layout::from_size_align_unchecked( + self.heap.1 * size_of::(), + align_of::() + ) }; // SAFETY: ptr was allocated with this allocator @@ -149,9 +152,9 @@ impl RawSmallVec { // with Layout::array unsafe { (if self.heap.1 < new_capacity { - A::grow + Heap::grow } else { - A::shrink + Heap::shrink })( allocator, NonNull::new(ptr as *mut u8).unwrap(), @@ -167,7 +170,7 @@ impl RawSmallVec { } } -impl Default for RawSmallVec { +impl Default for RawSmallVec { fn default() -> Self { Self::new() } diff --git a/src/references.rs b/src/references.rs index 0582ea12..462ca1f6 100644 --- a/src/references.rs +++ b/src/references.rs @@ -15,41 +15,43 @@ use { } }; -impl Borrow<[T]> for SmallVec { +impl Borrow<[Item]> for SmallVec { #[inline] - fn borrow(&self) -> &[T] { + fn borrow(&self) -> &[Item] { self.as_slice() } } -impl BorrowMut<[T]> for SmallVec { +impl BorrowMut<[Item]> + for SmallVec +{ #[inline] - fn borrow_mut(&mut self) -> &mut [T] { + fn borrow_mut(&mut self) -> &mut [Item] { self.as_mut_slice() } } -impl AsRef<[T]> for SmallVec { +impl AsRef<[Item]> for SmallVec { #[inline] - fn as_ref(&self) -> &[T] { + fn as_ref(&self) -> &[Item] { self.as_slice() } } -impl AsMut<[T]> for SmallVec { +impl AsMut<[Item]> for SmallVec { #[inline] - fn as_mut(&mut self) -> &mut [T] { + fn as_mut(&mut self) -> &mut [Item] { self.as_mut_slice() } } -impl Deref for SmallVec { - type Target = [T]; +impl Deref for SmallVec { + type Target = [Item]; #[inline] fn deref(&self) -> &Self::Target { self.as_slice() } } -impl DerefMut for SmallVec { +impl DerefMut for SmallVec { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { self.as_mut_slice() diff --git a/src/serde.rs b/src/serde.rs index 2135e200..ff3272a9 100644 --- a/src/serde.rs +++ b/src/serde.rs @@ -20,7 +20,9 @@ use { } }; -impl Serialize for SmallVec { +impl Serialize + for SmallVec +{ fn serialize(&self, serializer: S) -> Result { let mut state = serializer.serialize_seq(Some(self.len()))?; for item in self { @@ -30,7 +32,9 @@ impl Serialize for SmallVec } } -impl<'de, T: Deserialize<'de>, const N: usize> Deserialize<'de> for SmallVec { +impl<'de, Item: Deserialize<'de>, const INLINE: usize> Deserialize<'de> + for SmallVec +{ fn deserialize>(deserializer: D) -> Result { deserializer.deserialize_seq(SmallVecVisitor { phantom: PhantomData @@ -38,12 +42,14 @@ impl<'de, T: Deserialize<'de>, const N: usize> Deserialize<'de> for SmallVec { - phantom: PhantomData +struct SmallVecVisitor { + phantom: PhantomData } -impl<'de, T: Deserialize<'de>, const N: usize> Visitor<'de> for SmallVecVisitor { - type Value = SmallVec; +impl<'de, Item: Deserialize<'de>, const INLINE: usize> Visitor<'de> + for SmallVecVisitor +{ + type Value = SmallVec; fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { formatter.write_str("a sequence") diff --git a/src/specialization.rs b/src/specialization.rs index a62d02cd..24115347 100644 --- a/src/specialization.rs +++ b/src/specialization.rs @@ -12,26 +12,26 @@ use { /// A trait for specializing the implementation of [`from_elem`]. /// /// [`from_elem`]: crate::from_elem -pub trait SpecFromElem { +pub trait SpecFromElem { /// Creates a `Smallvec` value where `elem` is repeated `n` times. /// This will use the inline storage, not the heap. /// /// # Safety /// /// The caller must ensure that `n <= Self::inline_size()`. - unsafe fn spec_from_elem(elem: T, n: usize) -> Self; + unsafe fn spec_from_elem(elem: Item, n: usize) -> Self; } -impl SpecFromElem for SmallVec { +impl SpecFromElem for SmallVec { #[inline] - default unsafe fn spec_from_elem(elem: T, n: usize) -> Self { + default unsafe fn spec_from_elem(elem: Item, n: usize) -> Self { // SAFETY: Safety conditions are identical. unsafe { SmallVec::from_elem_fallback(elem, n) } } } -impl SpecFromElem for SmallVec { - unsafe fn spec_from_elem(elem: T, n: usize) -> Self { +impl SpecFromElem for SmallVec { + unsafe fn spec_from_elem(elem: Item, n: usize) -> Self { let mut result = Self::new(); if n > 0 { @@ -60,12 +60,13 @@ impl SpecFromElem for SmallVec { /// [`extend_from_slice`]. /// /// [`extend_from_slice`]: crate::SmallVec::extend_from_slice -pub trait SpecExtend { +pub trait SpecExtend { fn spec_extend(&mut self, iter: I); } -impl SpecExtend for SmallVec -where I: Iterator +impl SpecExtend + for SmallVec +where I: Iterator { #[inline] default fn spec_extend(&mut self, iter: I) { @@ -73,8 +74,9 @@ where I: Iterator } } -impl SpecExtend for SmallVec -where I: core::iter::TrustedLen +impl SpecExtend + for SmallVec +where I: core::iter::TrustedLen { fn spec_extend(&mut self, iter: I) { let (_, Some(additional)) = iter.size_hint() else { @@ -82,7 +84,7 @@ where I: core::iter::TrustedLen }; self.reserve(additional); - // SAFETY: A `TrustedLen` iterator provides accurate information + // SAFETY: Heap `TrustedLen` iterator provides accurate information // about its size, which was used to reserve additional memory. // This ensures that the access operations inside the loop always // operate on valid memory. @@ -106,10 +108,10 @@ where I: core::iter::TrustedLen } } -impl SpecExtend> - for SmallVec +impl + SpecExtend> for SmallVec { - fn spec_extend(&mut self, mut iter: IntoIter) { + fn spec_extend(&mut self, mut iter: IntoIter) { let slice = iter.as_slice(); let length = slice.len(); let old_len = self.len(); @@ -134,10 +136,11 @@ impl SpecExtend SpecExtend<&'a T, I> for SmallVec +impl<'a, Item: 'a, const INLINE: usize, I, Heap: Allocator> SpecExtend<&'a Item, I> + for SmallVec where - I: Iterator, - T: Clone + I: Iterator, + Item: Clone { #[inline] default fn spec_extend(&mut self, iterator: I) { @@ -145,11 +148,11 @@ where } } -impl<'a, T: 'a, const N: usize, A: Allocator> SpecExtend<&'a T, core::slice::Iter<'a, T>> - for SmallVec -where T: Copy +impl<'a, Item: 'a, const INLINE: usize, Heap: Allocator> + SpecExtend<&'a Item, core::slice::Iter<'a, Item>> for SmallVec +where Item: Copy { - fn spec_extend(&mut self, iter: core::slice::Iter<'a, T>) { + fn spec_extend(&mut self, iter: core::slice::Iter<'a, Item>) { let slice = iter.as_slice(); let length = slice.len(); let old_len = self.len(); @@ -174,7 +177,7 @@ where T: Copy /// A trait for specializing the implementation of [`extend_from_within`]. /// /// [`extend_from_within`]: crate::SmallVec::extend_from_within -pub trait SpecExtendFromWithin { +pub trait SpecExtendFromWithin { /// Main worker for [`extend_from_within`]. /// /// # Safety @@ -187,7 +190,9 @@ pub trait SpecExtendFromWithin { unsafe fn spec_extend_from_within(&mut self, source: core::ops::Range); } -impl SpecExtendFromWithin for SmallVec { +impl SpecExtendFromWithin + for SmallVec +{ default unsafe fn spec_extend_from_within(&mut self, source: core::ops::Range) { // SAFETY: Safety conditions are identical. unsafe { @@ -196,7 +201,9 @@ impl SpecExtendFromWithin for SmallVe } } -impl SpecExtendFromWithin for SmallVec { +impl SpecExtendFromWithin + for SmallVec +{ unsafe fn spec_extend_from_within(&mut self, source: core::ops::Range) { let old_len = self.len(); @@ -223,12 +230,12 @@ impl SpecExtendFromWithin for SmallVec /// A trait for specializing the implementation of [`FromIterator`]. /// /// [`clone_from`]: Clone::clone_from -pub trait SpecFromIterator { +pub trait SpecFromIterator { fn spec_from_iter(iter: I) -> Self; } -impl SpecFromIterator for SmallVec -where I: Iterator +impl SpecFromIterator for SmallVec +where I: Iterator { #[inline] default fn spec_from_iter(iter: I) -> Self { @@ -236,8 +243,8 @@ where I: Iterator } } -impl SpecFromIterator for SmallVec -where I: core::iter::TrustedLen +impl SpecFromIterator for SmallVec +where I: core::iter::TrustedLen { fn spec_from_iter(iter: I) -> Self { let mut v = match iter.size_hint() { @@ -257,19 +264,23 @@ where I: core::iter::TrustedLen /// A trait for specializing the implementation of [`clone_from`]. /// /// [`clone_from`]: Clone::clone_from -pub trait SpecCloneFrom { - fn spec_clone_from(&mut self, source: &[T]); +pub trait SpecCloneFrom { + fn spec_clone_from(&mut self, source: &[Item]); } -impl SpecCloneFrom for SmallVec { +impl SpecCloneFrom + for SmallVec +{ #[inline] - default fn spec_clone_from(&mut self, source: &[T]) { + default fn spec_clone_from(&mut self, source: &[Item]) { self.clone_from_fallback(source); } } -impl SpecCloneFrom for SmallVec { - fn spec_clone_from(&mut self, source: &[T]) { +impl SpecCloneFrom + for SmallVec +{ + fn spec_clone_from(&mut self, source: &[Item]) { self.clear(); self.extend_from_slice(source); } @@ -277,25 +288,25 @@ impl SpecCloneFrom for SmallVec { +pub trait SpecFromSlice { /// Creates a `SmallVec` value based on the contents of `slice`. /// This will use the inline storage, not the heap. /// /// # Safety /// /// The caller must ensure that `slice.len() <= Self::inline_size()`. - unsafe fn spec_from(slice: &[T]) -> Self; + unsafe fn spec_from(slice: &[Item]) -> Self; } -impl SpecFromSlice for SmallVec { - default unsafe fn spec_from(slice: &[T]) -> Self { +impl SpecFromSlice for SmallVec { + default unsafe fn spec_from(slice: &[Item]) -> Self { // SAFETY: Safety conditions are identical. unsafe { Self::from_slice_fallback(slice) } } } -impl SpecFromSlice for SmallVec { - unsafe fn spec_from(slice: &[T]) -> Self { +impl SpecFromSlice for SmallVec { + unsafe fn spec_from(slice: &[Item]) -> Self { let mut v = Self::new(); let source = slice.as_ptr();