diff --git a/benches/bench.rs b/benches/bench.rs index e881130..1bb0107 100644 --- a/benches/bench.rs +++ b/benches/bench.rs @@ -1,9 +1,21 @@ #![allow(deprecated)] -use criterion::{criterion_group, criterion_main, Bencher, Criterion}; -use smallvec::{smallvec, SmallVec}; -use std::hint::black_box; -use std::time::Duration; +use { + criterion::{ + Bencher, + Criterion, + criterion_group, + criterion_main + }, + smallvec::{ + SmallVec, + smallvec + }, + std::{ + hint::black_box, + time::Duration + } +}; const VEC_SIZE: usize = 16; const SPILLED_SIZE: usize = 100; @@ -18,39 +30,44 @@ trait Vector: for<'a> From<&'a [T]> + Extend { fn from_elems(val: &[T]) -> Self; fn extend_from_slice(&mut self, other: &[T]); fn retain_mut(&mut self, f: F) - where - F: FnMut(&mut T) -> bool; + where F: FnMut(&mut T) -> bool; } impl Vector for Vec { fn new() -> Self { Self::with_capacity(VEC_SIZE) } + fn push(&mut self, val: T) { self.push(val) } + fn pop(&mut self) -> Option { self.pop() } + fn remove(&mut self, p: usize) -> T { self.remove(p) } + fn insert(&mut self, n: usize, val: T) { self.insert(n, val) } + fn from_elem(val: T, n: usize) -> Self { vec![val; n] } + fn from_elems(val: &[T]) -> Self { val.to_owned() } + fn extend_from_slice(&mut self, other: &[T]) { Vec::extend_from_slice(self, other) } + fn retain_mut(&mut self, f: F) - where - F: FnMut(&mut T) -> bool, - { + where F: FnMut(&mut T) -> bool { self.retain_mut(f) } } @@ -59,31 +76,37 @@ impl Vector for SmallVec { fn new() -> Self { Self::new() } + fn push(&mut self, val: T) { self.push(val) } + fn pop(&mut self) -> Option { self.pop() } + fn remove(&mut self, p: usize) -> T { self.remove(p) } + fn insert(&mut self, n: usize, val: T) { self.insert(n, val) } + fn from_elem(val: T, n: usize) -> Self { smallvec![val; n] } + fn from_elems(val: &[T]) -> Self { SmallVec::from(val) } + fn extend_from_slice(&mut self, other: &[T]) { SmallVec::extend_from_slice(self, other) } + fn retain_mut(&mut self, f: F) - where - F: FnMut(&mut T) -> bool, - { + where F: FnMut(&mut T) -> bool { self.retain_mut(f) } } @@ -100,8 +123,8 @@ macro_rules! make_benches { } } -/* ---------- Bench generation (same list, just using the new macro) - * ---------- */ +// ---------- Bench generation (same list, just using the new macro) +// ---------- make_benches! { SmallVec { bench_push => gen_push(SPILLED_SIZE as _), @@ -216,7 +239,7 @@ fn gen_insert>(n: u64, b: &mut Bencher) { insert_noinline(&mut vec, 0, x); } vec - }, + } ); } @@ -233,7 +256,7 @@ fn gen_remove>(n: usize, b: &mut Bencher) { black_box(remove_noinline(&mut vec, 0)); } vec - }, + } ); } @@ -309,7 +332,7 @@ fn gen_retain_mut_half>(n: usize, b: &mut Bencher) { |mut vec| { vec.retain_mut(|x| black_box(*x) % 2 == 0); vec - }, + } ); } @@ -319,7 +342,7 @@ fn gen_retain_mut_all>(n: usize, b: &mut Bencher) { |mut vec| { vec.retain_mut(|_| true); vec - }, + } ); } @@ -329,7 +352,7 @@ fn gen_retain_mut_none>(n: usize, b: &mut Bencher) { |mut vec| { vec.retain_mut(|_| false); vec - }, + } ); } diff --git a/rustfmt.toml b/rustfmt.toml index 5171db1..1ce7cb7 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,4 +1,17 @@ wrap_comments = true -imports_granularity = "Preserve" +imports_granularity = "One" group_imports = "One" -format_code_in_doc_comments = true \ No newline at end of file +format_code_in_doc_comments = true +error_on_line_overflow = true +error_on_unformatted = true +blank_lines_lower_bound = 0 +blank_lines_upper_bound = 1 +float_literal_trailing_zero = "IfNoPostfix" +imports_layout = "Vertical" +normalize_comments = true +reorder_impl_items = true +struct_lit_single_line = false +style_edition = "2024" +trailing_comma = "Never" +use_try_shorthand = true +where_single_line = true \ No newline at end of file diff --git a/src/lib.rs b/src/lib.rs index ac9448d..9eaa7a2 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -67,37 +67,68 @@ extern crate std; mod rawsmallvec; -use alloc::alloc::Layout; -use alloc::boxed::Box; -use alloc::vec; -use alloc::vec::Vec; #[cfg(feature = "bytes")] -use bytes::{buf::UninitSlice, BufMut}; -use core::borrow::Borrow; -use core::borrow::BorrowMut; -use core::fmt::Debug; -use core::hash::{Hash, Hasher}; -use core::marker::PhantomData; -use core::mem::align_of; -use core::mem::size_of; -use core::mem::ManuallyDrop; -use core::mem::MaybeUninit; -use core::ptr::copy; -use core::ptr::copy_nonoverlapping; -use core::ptr::NonNull; +use bytes::{ + BufMut, + buf::UninitSlice +}; #[cfg(feature = "malloc_size_of")] -use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps}; +use malloc_size_of::{ + MallocShallowSizeOf, + MallocSizeOf, + MallocSizeOfOps +}; #[cfg(feature = "internals")] pub use rawsmallvec::RawSmallVec; #[cfg(not(feature = "internals"))] use rawsmallvec::RawSmallVec; #[cfg(feature = "serde")] use serde_core::{ - de::{Deserialize, Deserializer, SeqAccess, Visitor}, - ser::{Serialize, SerializeSeq, Serializer}, + de::{ + Deserialize, + Deserializer, + SeqAccess, + Visitor + }, + ser::{ + Serialize, + SerializeSeq, + Serializer + } }; #[cfg(feature = "std")] use std::io; +use { + alloc::{ + alloc::Layout, + boxed::Box, + vec::Vec + }, + core::{ + borrow::{ + Borrow, + BorrowMut + }, + fmt::Debug, + hash::{ + Hash, + Hasher + }, + iter::repeat_n, + marker::PhantomData, + mem::{ + ManuallyDrop, + MaybeUninit, + align_of, + size_of + }, + ptr::{ + NonNull, + copy, + copy_nonoverlapping + } + } +}; /// Error type for APIs with fallible heap allocation #[derive(Debug)] @@ -107,8 +138,8 @@ pub enum CollectionAllocErr { /// The allocator return an error AllocErr { /// The layout that was passed to the allocator - layout: Layout, - }, + layout: Layout + } } impl core::fmt::Display for CollectionAllocErr { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { @@ -123,7 +154,9 @@ fn infallible(result: Result) -> T { match result { Ok(x) => x, Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"), - Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout), + Err(CollectionAllocErr::AllocErr { + layout + }) => alloc::alloc::handle_alloc_error(layout) } } @@ -137,9 +170,7 @@ const fn is_zst() -> bool { /// A local copy of [`core::slice::range`]. The latter function is unstable /// and thus cannot be used yet. fn slice_range(range: R, bounds: core::ops::RangeTo) -> core::ops::Range -where - R: core::ops::RangeBounds, -{ +where R: core::ops::RangeBounds { let len = bounds.end; let start = match range.start_bound() { @@ -147,7 +178,7 @@ where core::ops::Bound::Excluded(start) => start .checked_add(1) .unwrap_or_else(|| panic!("attempted to index slice from after maximum usize")), - core::ops::Bound::Unbounded => 0, + core::ops::Bound::Unbounded => 0 }; let end = match range.end_bound() { @@ -155,7 +186,7 @@ where .checked_add(1) .unwrap_or_else(|| panic!("attempted to index slice up to maximum usize")), core::ops::Bound::Excluded(&end) => end, - core::ops::Bound::Unbounded => len, + core::ops::Bound::Unbounded => len }; if start > end { @@ -165,7 +196,10 @@ where panic!("range end index {end} out of range for slice of length {len}"); } - core::ops::Range { start, end } + core::ops::Range { + start, + end + } } impl RawSmallVec { @@ -175,24 +209,26 @@ impl RawSmallVec { const fn new() -> Self { Self::new_inline(MaybeUninit::uninit()) } + #[inline] const fn new_inline(inline: MaybeUninit<[T; N]>) -> Self { Self { - inline: ManuallyDrop::new(inline), + inline: ManuallyDrop::new(inline) } } + #[inline] const fn new_heap(ptr: NonNull, capacity: usize) -> Self { Self { - heap: (ptr, capacity), + heap: (ptr, capacity) } } #[inline] const fn as_ptr_inline(&self) -> *const T { - // 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 + // 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 (unsafe { &raw const self.inline }) as *mut T } @@ -225,9 +261,12 @@ impl RawSmallVec { unsafe fn try_grow_raw( &mut self, len: TaggedLen, - new_capacity: usize, + new_capacity: usize ) -> Result<(), CollectionAllocErr> { - use alloc::alloc::{alloc, realloc}; + use alloc::alloc::{ + alloc, + realloc + }; debug_assert!(!Self::IS_ZST); debug_assert!(new_capacity > 0); debug_assert!(new_capacity >= len.value()); @@ -249,25 +288,29 @@ impl RawSmallVec { let new_ptr = if !was_on_heap { // get a fresh allocation let new_ptr = alloc(new_layout) as *mut T; // `new_layout` has nonzero size. - let new_ptr = - NonNull::new(new_ptr).ok_or(CollectionAllocErr::AllocErr { layout: new_layout })?; + let new_ptr = NonNull::new(new_ptr).ok_or(CollectionAllocErr::AllocErr { + layout: new_layout + })?; copy_nonoverlapping(ptr, new_ptr.as_ptr(), len); new_ptr } else { // use realloc - // this can't overflow since we already constructed an equivalent layout during - // the previous allocation + // this can't overflow since we already constructed an equivalent + // layout during the previous allocation let old_layout = Layout::from_size_align_unchecked(self.heap.1 * size_of::(), align_of::()); // SAFETY: ptr was allocated with this allocator - // old_layout is the same as the layout used to allocate the previous memory - // block new_layout.size() is greater than zero - // does not overflow when rounded up to alignment. since it was constructed + // old_layout is the same as the layout used to allocate the + // previous memory block new_layout.size() is greater + // than zero does not overflow when rounded up to + // alignment. since it was constructed // with Layout::array let new_ptr = realloc(ptr as *mut u8, old_layout, new_layout.size()) as *mut T; - NonNull::new(new_ptr).ok_or(CollectionAllocErr::AllocErr { layout: new_layout })? + NonNull::new(new_ptr).ok_or(CollectionAllocErr::AllocErr { + layout: new_layout + })? }; *self = Self::new_heap(new_ptr, new_capacity); Ok(()) @@ -304,6 +347,7 @@ impl Copy for TaggedLen {} impl TaggedLen { const IS_ZST: bool = is_zst::(); + #[inline] pub const fn new(len: usize, on_heap: bool) -> Self { if Self::IS_ZST { @@ -327,11 +371,7 @@ impl TaggedLen { #[inline] pub const fn value(self) -> usize { - if Self::IS_ZST { - self.0 - } else { - self.0 >> 1 - } + if Self::IS_ZST { self.0 } else { self.0 >> 1 } } } @@ -339,7 +379,7 @@ impl TaggedLen { pub struct SmallVec { len: TaggedLen, raw: RawSmallVec, - _marker: PhantomData, + _marker: PhantomData } unsafe impl Send for SmallVec {} @@ -369,7 +409,7 @@ pub struct Drain<'a, T: 'a, const N: usize> { tail_start: usize, tail_len: usize, iter: core::slice::Iter<'a, T>, - vec: core::ptr::NonNull>, + vec: core::ptr::NonNull> } impl<'a, T: 'a, const N: usize> Iterator for Drain<'a, T, N> { @@ -377,8 +417,8 @@ impl<'a, T: 'a, const N: usize> Iterator for Drain<'a, T, N> { #[inline] 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. + // SAFETY: we shrunk the length of the vector so it no longer owns these + // items, and we can take ownership of them. self.iter .next() .map(|reference| unsafe { core::ptr::read(reference) }) @@ -440,9 +480,10 @@ impl<'a, T: 'a, const N: usize> Drop for Drain<'a, T, N> { let mut vec = self.vec; 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 moving values out from `iter`. + // 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 + // moving values out from `iter`. unsafe { let vec = vec.as_mut(); let old_len = vec.len(); @@ -453,8 +494,8 @@ impl<'a, T: 'a, const N: usize> Drop for Drain<'a, T, N> { return; } - // ensure elements are moved back into their appropriate places, even when - // drop_in_place panics + // ensure elements are moved back into their appropriate places, even + // when drop_in_place panics let _guard = DropGuard(self); if drop_len == 0 { @@ -462,20 +503,23 @@ impl<'a, T: 'a, const N: usize> Drop for Drain<'a, T, N> { } // as_slice() must only be called when iter.len() is > 0 because - // it also gets touched by vec::Splice which may turn it into a dangling pointer - // which would make it and the vec pointer point to different allocations which - // would lead to invalid pointer arithmetic below. + // it also gets touched by vec::Splice which may turn it into a dangling + // pointer which would make it and the vec pointer point to + // different allocations which would lead to invalid pointer + // arithmetic below. 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 &[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. 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 = drop_ptr.offset_from_unsigned(vec_ptr); + // May be replaced with the line below later, once this crate's MSRV + // is >= 1.87. let drop_offset = + // drop_ptr.offset_from_unsigned(vec_ptr); let drop_offset = drop_ptr.offset_from(vec_ptr) as usize; let to_drop = core::ptr::slice_from_raw_parts_mut(vec_ptr.add(drop_offset), drop_len); core::ptr::drop_in_place(to_drop); @@ -501,7 +545,7 @@ impl Drain<'_, T, N> { let range_slice = unsafe { core::slice::from_raw_parts_mut( vec.as_mut_ptr().add(range_start), - range_end - range_start, + range_end - range_start ) }; @@ -545,8 +589,7 @@ impl Drain<'_, T, N> { /// /// [1]: struct.SmallVec.html#method.extract_if pub struct ExtractIf<'a, T, const N: usize, F> -where - F: FnMut(&mut T) -> bool, +where F: FnMut(&mut T) -> bool { vec: &'a mut SmallVec, /// The index of the item that will be inspected by the next call to `next`. @@ -559,13 +602,13 @@ where /// The original length of `vec` prior to draining. old_len: usize, /// The filter test predicate. - pred: F, + pred: F } impl core::fmt::Debug for ExtractIf<'_, T, N, F> where F: FnMut(&mut T) -> bool, - T: core::fmt::Debug, + T: core::fmt::Debug { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("ExtractIf") @@ -575,8 +618,7 @@ where } impl Iterator for ExtractIf<'_, T, N, F> -where - F: FnMut(&mut T) -> bool, +where F: FnMut(&mut T) -> bool { type Item = T; @@ -586,9 +628,10 @@ where let i = self.idx; let v = core::slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len); let drained = (self.pred)(&mut v[i]); - // Update the index *after* the predicate is called. If the index - // is updated prior and the predicate panics, the element at this - // index would be leaked. + // Update the index *after* the predicate is called. If the + // index is updated prior and the predicate + // panics, the element at this index would be + // leaked. self.idx += 1; if drained { self.del += 1; @@ -610,8 +653,7 @@ where } impl Drop for ExtractIf<'_, T, N, F> -where - F: FnMut(&mut T) -> bool, +where F: FnMut(&mut T) -> bool { fn drop(&mut self) { unsafe { @@ -619,8 +661,9 @@ where // This is a pretty messed up state, and there isn't really an // obviously right thing to do. We don't want to keep trying // to execute `pred`, so we just backshift all the unprocessed - // elements and tell the vec that they still exist. The backshift - // is required to prevent a double-drop of the last successfully + // elements and tell the vec that they still exist. The + // backshift is required to prevent a + // double-drop of the last successfully // drained item prior to a panic in the predicate. let ptr = self.vec.as_mut_ptr(); let src = ptr.add(self.idx); @@ -635,13 +678,13 @@ where pub struct Splice<'a, I: Iterator + 'a, const N: usize> { drain: Drain<'a, I::Item, N>, - replace_with: I, + replace_with: I } impl<'a, I, const N: usize> core::fmt::Debug for Splice<'a, I, N> where I: Debug + Iterator + 'a, - ::Item: Debug, + ::Item: Debug { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_tuple("Splice").field(&self.drain).finish() @@ -671,11 +714,12 @@ impl ExactSizeIterator for Splice<'_, I, N> {} impl Drop for Splice<'_, I, N> { fn drop(&mut self) { self.drain.by_ref().for_each(drop); - // At this point draining is done and the only remaining tasks are splicing - // and moving things into the final place. - // Which means we can replace the slice::Iter with pointers that won't point to - // deallocated memory, so that Drain::drop is still allowed to call - // iter.len(), otherwise it would break the ptr.sub_ptr contract. + // At this point draining is done and the only remaining tasks are + // splicing and moving things into the final place. + // Which means we can replace the slice::Iter with pointers that won't + // point to deallocated memory, so that Drain::drop is still + // allowed to call iter.len(), otherwise it would break the + // ptr.sub_ptr contract. self.drain.iter = [].iter(); unsafe { @@ -732,7 +776,7 @@ pub struct IntoIter { raw: RawSmallVec, begin: usize, end: TaggedLen, - _marker: PhantomData, + _marker: PhantomData } // SAFETY: IntoIter has unique ownership of its contents. Sending (or sharing) @@ -765,8 +809,9 @@ impl IntoIter { #[inline] pub const fn as_slice(&self) -> &[T] { - // SAFETY: The members in self.begin..self.end.value() are all initialized - // So the pointer arithmetic is valid, and so is the construction of the slice + // SAFETY: The members in self.begin..self.end.value() are all + // initialized So the pointer arithmetic is valid, and so is the + // construction of the slice unsafe { let ptr = self.as_ptr(); core::slice::from_raw_parts(ptr.add(self.begin), self.end.value() - self.begin) @@ -836,7 +881,7 @@ impl SmallVec { Self { len: TaggedLen::new(0, false), raw: RawSmallVec::new(), - _marker: PhantomData, + _marker: PhantomData } } @@ -855,9 +900,9 @@ impl SmallVec { assert!(S <= N); } - // 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 ) + // 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(); // SAFETY: buf and elements do not overlap, are aligned and have space @@ -874,7 +919,7 @@ impl SmallVec { Self { len: TaggedLen::new(S, false), raw: RawSmallVec::new_inline(buf), - _marker: PhantomData, + _marker: PhantomData } } @@ -885,19 +930,20 @@ impl SmallVec { let mut vec = Self { len: TaggedLen::new(len, false), raw: RawSmallVec::new_inline(MaybeUninit::new(buf)), - _marker: PhantomData, + _marker: PhantomData }; // Deallocate the remaining elements so no memory is leaked. unsafe { - // SAFETY: both the input and output pointers are in range of the stack - // allocation + // SAFETY: both the input and output pointers are in range of the + // stack allocation let remainder_ptr = vec.raw.as_mut_ptr_inline().add(len); let remainder_len = N - len; - // SAFETY: the values are initialized, so dropping them here is fine. + // SAFETY: the values are initialized, so dropping them here is + // fine. core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut( remainder_ptr, - remainder_len, + remainder_len )); } @@ -911,8 +957,10 @@ impl SmallVec { /// # Examples /// /// ``` - /// use smallvec::SmallVec; - /// use std::mem::MaybeUninit; + /// use { + /// smallvec::SmallVec, + /// std::mem::MaybeUninit + /// }; /// /// let buf = [1, 2, 3, 4, 5, 0, 0, 0]; /// let small_vec = unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) }; @@ -929,7 +977,7 @@ impl SmallVec { Self { len: TaggedLen::new(len, false), raw: RawSmallVec::new_inline(buf), - _marker: PhantomData, + _marker: PhantomData } } } @@ -944,20 +992,22 @@ impl SmallVec { } if Self::IS_ZST { - // "Move" elements to stack buffer. They're ZST so we don't actually have to do - // anything. Just make sure they're not dropped. - // We don't wrap the vector in ManuallyDrop so that when it's dropped, the - // memory is deallocated, if it needs to be. + // "Move" elements to stack buffer. They're ZST so we don't actually + // have to do anything. Just make sure they're not + // dropped. We don't wrap the vector in ManuallyDrop so + // that when it's dropped, the memory is deallocated, if + // it needs to be. let mut vec = vec; let len = vec.len(); // SAFETY: `0` is less than the vector's capacity. - // old_len..new_len is an empty range. So there are no uninitialized elements + // old_len..new_len is an empty range. So there are no uninitialized + // elements unsafe { vec.set_len(0) }; Self { len: TaggedLen::new(len, false), raw: RawSmallVec::new(), - _marker: PhantomData, + _marker: PhantomData } } else { let mut vec = ManuallyDrop::new(vec); @@ -970,7 +1020,7 @@ impl SmallVec { Self { len: TaggedLen::new(len, true), raw: RawSmallVec::new_heap(ptr, cap), - _marker: PhantomData, + _marker: PhantomData } } } @@ -1014,11 +1064,7 @@ impl SmallVec { #[inline] pub const fn inline_size() -> usize { - if Self::IS_ZST { - usize::MAX - } else { - N - } + if Self::IS_ZST { usize::MAX } else { N } } #[inline] @@ -1092,11 +1138,12 @@ impl SmallVec { } pub fn drain(&mut self, range: R) -> Drain<'_, T, N> - where - R: core::ops::RangeBounds, - { + where R: core::ops::RangeBounds { let len = self.len(); - let core::ops::Range { start, end } = slice_range(range, ..len); + let core::ops::Range { + start, + end + } = slice_range(range, ..len); unsafe { // SAFETY: `start <= len` @@ -1112,8 +1159,7 @@ impl SmallVec { iter: range_slice.iter(), // Since self is a &mut, passing it to a function would invalidate the slice // iterator. - vec: core::ptr::NonNull::new_unchecked(self as *mut _), - //vec: core::ptr::NonNull::from(self), + vec: core::ptr::NonNull::new_unchecked(self as *mut _) } } } @@ -1205,10 +1251,13 @@ impl SmallVec { pub fn extract_if(&mut self, range: R, filter: F) -> ExtractIf<'_, T, N, F> where F: FnMut(&mut T) -> bool, - R: core::ops::RangeBounds, + R: core::ops::RangeBounds { let old_len = self.len(); - let core::ops::Range { start, end } = slice_range(range, ..old_len); + let core::ops::Range { + start, + end + } = slice_range(range, ..old_len); // Guard against us getting leaked (leak amplification) unsafe { @@ -1221,18 +1270,18 @@ impl SmallVec { end, del: 0, old_len, - pred: filter, + pred: filter } } pub fn splice(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, N> where R: core::ops::RangeBounds, - I: IntoIterator, + I: IntoIterator { Splice { drain: self.drain(range), - replace_with: replace_with.into_iter(), + replace_with: replace_with.into_iter() } } @@ -1252,15 +1301,15 @@ impl SmallVec { // SAFETY: `len < capacity` after the reserve, // so the offset stays in bounds of the allocation. let ptr = unsafe { self.as_mut_ptr().add(len) }; - // SAFETY: we allocated enough space in case it wasn't enough, so the address is - // valid for writes. + // SAFETY: we allocated enough space in case it wasn't enough, so the + // address is valid for writes. unsafe { ptr.write(value) }; // LEGAL: all elements in `0..len + 1` are initialized. { // This block is an exact copy of `self.set_len`. - // We have to do this so that Miri doesn't report a "Stacked Borrows" - // rule violation. See PR/406 + // We have to do this so that Miri doesn't report a "Stacked + // Borrows" rule violation. See PR/406 let new_len = len + 1; debug_assert!(new_len <= self.capacity()); @@ -1268,8 +1317,9 @@ impl SmallVec { self.len = TaggedLen::new(new_len, on_heap); } - // SAFETY: `ptr` is aligned, non-null and points to the element initialized - // above; the borrow is tied to `&mut self`, so it is exclusive. + // SAFETY: `ptr` is aligned, non-null and points to the element + // initialized above; the borrow is tied to `&mut self`, + // so it is exclusive. unsafe { &mut *ptr } } @@ -1282,8 +1332,8 @@ impl SmallVec { let new_len = len - 1; // SAFETY: new_len < len since len is non-zero unsafe { self.set_len(new_len) }; - // SAFETY: this element was initialized and we just gave up ownership of it, so - // we can give it away + // SAFETY: this element was initialized and we just gave up ownership of + // it, so we can give it away let value = unsafe { self.as_mut_ptr().add(new_len).read() }; Some(value) } @@ -1291,17 +1341,13 @@ impl SmallVec { #[inline] pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option { let last = self.last_mut()?; - if predicate(last) { - self.pop() - } else { - None - } + if predicate(last) { self.pop() } else { None } } #[inline] pub fn append(&mut self, other: &mut SmallVec) { - // can't overflow since both are smaller than isize::MAX and 2 * isize::MAX < - // usize::MAX + // can't overflow since both are smaller than isize::MAX and 2 * + // isize::MAX < usize::MAX let len = self.len(); let other_len = other.len(); let total_len = len + other_len; @@ -1312,8 +1358,8 @@ impl SmallVec { // SAFETY: see `Self::push` let ptr = unsafe { self.as_mut_ptr().add(len) }; unsafe { other.set_len(0) } - // SAFETY: we have a mutable reference to each vector and each uniquely owns its - // memory. so the ranges can't overlap + // SAFETY: we have a mutable reference to each vector and each uniquely + // owns its memory. so the ranges can't overlap unsafe { copy_nonoverlapping(other.as_ptr(), ptr, other_len) }; unsafe { self.set_len(total_len) } } @@ -1337,7 +1383,8 @@ impl SmallVec { let result = unsafe { self.raw.try_grow_raw(self.len, new_capacity) }; if result.is_ok() { - // SAFETY: the allocation succeeded, so self.raw.heap is now active + // SAFETY: the allocation succeeded, so self.raw.heap is now + // active unsafe { self.set_on_heap() }; } result @@ -1355,7 +1402,7 @@ impl SmallVec { drop(DropDealloc { ptr: ptr.cast(), size_bytes: old_cap * size_of::(), - align: align_of::(), + align: align_of::() }); self.set_inline(); } @@ -1372,7 +1419,7 @@ impl SmallVec { self.len() .checked_add(additional) .and_then(usize::checked_next_power_of_two) - .ok_or(CollectionAllocErr::CapacityOverflow), + .ok_or(CollectionAllocErr::CapacityOverflow) ); self.grow(new_capacity); } @@ -1399,7 +1446,7 @@ impl SmallVec { let new_capacity = infallible( self.len() .checked_add(additional) - .ok_or(CollectionAllocErr::CapacityOverflow), + .ok_or(CollectionAllocErr::CapacityOverflow) ); self.grow(new_capacity); } @@ -1433,7 +1480,7 @@ impl SmallVec { self.set_inline(); alloc::alloc::dealloc( ptr.cast().as_ptr(), - Layout::from_size_align_unchecked(capacity * size_of::(), align_of::()), + Layout::from_size_align_unchecked(capacity * size_of::(), align_of::()) ); } } else if len < self.capacity() { @@ -1463,8 +1510,8 @@ impl SmallVec { ptr.cast().as_ptr(), Layout::from_size_align_unchecked( capacity * size_of::(), - align_of::(), - ), + align_of::() + ) ); } } else if target < self.capacity() { @@ -1486,7 +1533,7 @@ impl SmallVec { self.set_len(len); core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut( self.as_mut_ptr().add(len), - old_len - len, + old_len - len )) } } @@ -1522,7 +1569,7 @@ impl SmallVec { self.set_len(0); core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut( self.as_mut_ptr(), - old_len, + old_len )); } } @@ -1568,9 +1615,9 @@ impl SmallVec { if index < len { // SAFETY: `reserve(1)` guarantees capacity for `len + 1` elements, - // so shifting `len - index` elements one slot up stays in bounds. - // Source and destination overlap, hence `copy` instead of - // `copy_nonoverlapping`. + // so shifting `len - index` elements one slot up stays in + // bounds. Source and destination overlap, hence + // `copy` instead of `copy_nonoverlapping`. unsafe { copy(ptr, ptr.add(1), len - index) }; } @@ -1580,8 +1627,8 @@ impl SmallVec { // LEGAL: all elements in `0..len + 1` are initialized. { // This block is an exact copy of `self.set_len`. - // We have to do this so that Miri doesn't report a "Stacked Borrows" - // rule violation. See PR/406 + // We have to do this so that Miri doesn't report a "Stacked + // Borrows" rule violation. See PR/406 let new_len = len + 1; debug_assert!(new_len <= self.capacity()); @@ -1589,8 +1636,9 @@ impl SmallVec { self.len = TaggedLen::new(new_len, on_heap); } - // SAFETY: `ptr` is aligned, non-null and points to the element initialized - // above; the borrow is tied to `&mut self`, so it is exclusive. + // SAFETY: `ptr` is aligned, non-null and points to the element + // initialized above; the borrow is tied to `&mut self`, + // so it is exclusive. unsafe { &mut *ptr } } @@ -1636,9 +1684,10 @@ impl SmallVec { if !self.spilled() { let mut vec = Vec::with_capacity(len); let this = ManuallyDrop::new(self); - // SAFETY: we create a new vector with sufficient capacity, copy our elements - // into it to transfer ownership and then set the length - // we don't drop the elements we previously held + // SAFETY: we create a new vector with sufficient capacity, copy our + // elements into it to transfer ownership and then set + // the length we don't drop the elements we previously + // held unsafe { copy_nonoverlapping(this.raw.as_ptr_inline(), vec.as_mut_ptr(), len); vec.set_len(len); @@ -1674,7 +1723,8 @@ impl SmallVec { if self.len() != N { Err(self) } else { - // when `this` is dropped, the memory is released if it's on the heap. + // when `this` is dropped, the memory is released if it's on the + // heap. let mut this = self; // SAFETY: we release ownership of the elements we hold unsafe { @@ -1719,9 +1769,7 @@ impl SmallVec { #[inline] pub fn dedup(&mut self) - where - T: PartialEq, - { + where T: PartialEq { self.dedup_by(|a, b| a == b); } @@ -1729,16 +1777,14 @@ impl SmallVec { pub fn dedup_by_key(&mut self, mut key: F) where F: FnMut(&mut T) -> K, - K: PartialEq, + K: PartialEq { self.dedup_by(|a, b| key(a) == key(b)); } #[inline] pub fn dedup_by(&mut self, mut same_bucket: F) - where - F: FnMut(&mut T, &mut T) -> bool, - { + where F: FnMut(&mut T, &mut T) -> bool { // See the implementation of Vec::dedup_by in the // standard library for an explanation of this algorithm. let len = self.len(); @@ -1767,9 +1813,7 @@ impl SmallVec { } pub fn resize_with(&mut self, new_len: usize, f: F) - where - F: FnMut() -> T, - { + where F: FnMut() -> T { let old_len = self.len(); if old_len < new_len { let mut f = f; @@ -1804,7 +1848,7 @@ impl SmallVec { unsafe { core::slice::from_raw_parts_mut( self.as_mut_ptr().add(self.len()) as *mut MaybeUninit, - self.capacity() - self.len(), + self.capacity() - self.len() ) } } @@ -1841,7 +1885,10 @@ impl SmallVec { /// # Examples /// /// ``` - /// use smallvec::{smallvec, SmallVec}; + /// use smallvec::{ + /// SmallVec, + /// smallvec + /// }; /// /// let mut v: SmallVec<_, 1> = smallvec![1, 2, 3]; /// @@ -1886,7 +1933,7 @@ impl SmallVec { SmallVec { len: TaggedLen::new(length, true), raw: RawSmallVec::new_heap(ptr, capacity), - _marker: PhantomData, + _marker: PhantomData } } } @@ -1908,14 +1955,13 @@ impl SmallVec { } pub fn extend_from_within(&mut self, src: R) - where - R: core::ops::RangeBounds, - { + where R: core::ops::RangeBounds { let src = slice_range(src, ..self.len()); self.reserve(src.len()); - // SAFETY: The call to `reserve` ensures that the capacity is large enough. - // The range is within bounds through the use of `core::slice::range`. + // SAFETY: The call to `reserve` ensures that the capacity is large + // enough. The range is within bounds through the use of + // `core::slice::range`. unsafe { #[cfg(feature = "specialization")] { @@ -1931,9 +1977,7 @@ impl SmallVec { #[inline] pub fn extend_from_slice_copy(&mut self, other: &[T]) - where - T: Copy, - { + where T: Copy { let len = other.len(); let src = other.as_ptr(); @@ -1952,15 +1996,19 @@ impl SmallVec { pub fn extend_from_within_copy(&mut self, src: R) where R: core::ops::RangeBounds, - T: Copy, + T: Copy { let src = slice_range(src, ..self.len()); - let core::ops::Range { start, end } = src; + let core::ops::Range { + start, + end + } = src; let len = end - start; self.reserve(len); - // SAFETY: The call to `reserve` ensures that the capacity is large enough. - // The range is within bounds through the use of `core::slice::range`. + // SAFETY: The call to `reserve` ensures that the capacity is large + // enough. The range is within bounds through the use of + // `core::slice::range`. unsafe { let l = self.len(); let ptr = self.as_mut_ptr(); @@ -1970,9 +2018,7 @@ impl SmallVec { } pub fn insert_from_slice_copy(&mut self, index: usize, other: &[T]) - where - T: Copy, - { + where T: Copy { let l = self.len(); let len = other.len(); assert!(index <= l); @@ -1981,7 +2027,8 @@ impl SmallVec { let base_ptr = self.as_mut_ptr(); let ith_ptr = base_ptr.add(index); let shifted_ptr = base_ptr.add(index + len); - // elements at `index + other_len..len + other_len` are now initialized + // elements at `index + other_len..len + other_len` are now + // initialized copy(ith_ptr, shifted_ptr, l - index); // elements at `index..index + other_len` are now initialized copy_nonoverlapping(other.as_ptr(), ith_ptr, len); @@ -1994,14 +2041,13 @@ 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, - { + where T: Copy { let src = slice.as_ptr(); let len = slice.len(); let mut result = Self::with_capacity(len); - // SAFETY: By using `with_capacity`, the pointer will point to valid memory. + // SAFETY: By using `with_capacity`, the pointer will point to valid + // memory. unsafe { let dst = result.as_mut_ptr(); copy_nonoverlapping(src, dst, len); @@ -2014,7 +2060,7 @@ impl SmallVec { struct DropGuard { ptr: *mut T, - len: usize, + len: usize } impl Drop for DropGuard { #[inline] @@ -2028,7 +2074,7 @@ impl Drop for DropGuard { struct DropDealloc { ptr: NonNull, size_bytes: usize, - align: usize, + align: usize } impl Drop for DropDealloc { @@ -2038,7 +2084,7 @@ impl Drop for DropDealloc { if self.size_bytes > 0 { alloc::alloc::dealloc( self.ptr.as_ptr(), - Layout::from_size_align_unchecked(self.size_bytes, self.align), + Layout::from_size_align_unchecked(self.size_bytes, self.align) ); } } @@ -2059,7 +2105,7 @@ unsafe impl<#[may_dangle] T, const N: usize> Drop for SmallVec { Some(DropDealloc { ptr: NonNull::new_unchecked(ptr as *mut u8), size_bytes: capacity * size_of::(), - align: align_of::(), + align: align_of::() }) } else { None @@ -2082,7 +2128,7 @@ impl Drop for SmallVec { Some(DropDealloc { ptr: NonNull::new_unchecked(ptr as *mut u8), size_bytes: capacity * size_of::(), - align: align_of::(), + align: align_of::() }) } else { None @@ -2105,7 +2151,7 @@ impl Drop for IntoIter { Some(DropDealloc { ptr: NonNull::new_unchecked(ptr as *mut u8), size_bytes: capacity * size_of::(), - align: align_of::(), + align: align_of::() }) } else { None @@ -2136,18 +2182,19 @@ impl core::ops::DerefMut for SmallVec { #[track_caller] pub fn from_elem(elem: T, n: usize) -> SmallVec { if n > SmallVec::::inline_size() { - // Standard Rust vectors are already specialized. - SmallVec::::from_vec(vec![elem; n]) + repeat_n(elem, n).collect() } else { #[cfg(feature = "specialization")] { - // SAFETY: The precondition is checked in the initial comparison above. + // SAFETY: The precondition is checked in the initial comparison + // above. unsafe { as spec_traits::SpecFromElem>::spec_from_elem(elem, n) } } #[cfg(not(feature = "specialization"))] { - // SAFETY: The precondition is checked in the initial comparison above. + // SAFETY: The precondition is checked in the initial comparison + // above. unsafe { SmallVec::::from_elem_fallback(elem, n) } } } @@ -2213,8 +2260,7 @@ mod spec_traits { } impl SpecExtend for SmallVec - where - I: Iterator, + where I: Iterator { #[inline] default fn spec_extend(&mut self, iter: I) { @@ -2223,8 +2269,7 @@ mod spec_traits { } impl SpecExtend for SmallVec - where - I: core::iter::TrustedLen, + where I: core::iter::TrustedLen { fn spec_extend(&mut self, iter: I) { let (_, Some(additional)) = iter.size_hint() else { @@ -2239,7 +2284,10 @@ mod spec_traits { unsafe { let len = self.len(); let ptr = self.as_mut_ptr().add(len); - let mut guard = DropGuard { ptr, len: 0 }; + let mut guard = DropGuard { + ptr, + len: 0 + }; for x in iter { ptr.add(guard.len).write(x); @@ -2282,7 +2330,7 @@ mod spec_traits { impl<'a, T: 'a, const N: usize, I> SpecExtend<&'a T, I> for SmallVec where I: Iterator, - T: Clone, + T: Clone { #[inline] default fn spec_extend(&mut self, iterator: I) { @@ -2291,8 +2339,7 @@ mod spec_traits { } impl<'a, T: 'a, const N: usize> SpecExtend<&'a T, core::slice::Iter<'a, T>> for SmallVec - where - T: Copy, + where T: Copy { fn spec_extend(&mut self, iter: core::slice::Iter<'a, T>) { let slice = iter.as_slice(); @@ -2349,8 +2396,8 @@ mod spec_traits { let len = src.len(); // SAFETY: The caller ensures that the vector has spare capacity - // for at least `src.len()` elements. This is also the amount of memory - // accessed when the data is copied. + // for at least `src.len()` elements. This is also the amount of + // memory accessed when the data is copied. unsafe { let ptr = self.as_mut_ptr(); let dst = ptr.add(old_len); @@ -2373,8 +2420,7 @@ mod spec_traits { } impl SpecFromIterator for SmallVec - where - I: Iterator, + where I: Iterator { #[inline] default fn spec_from_iter(iter: I) -> Self { @@ -2383,8 +2429,7 @@ mod spec_traits { } impl SpecFromIterator for SmallVec - where - I: core::iter::TrustedLen, + where I: core::iter::TrustedLen { fn spec_from_iter(iter: I) -> Self { let mut v = match iter.size_hint() { @@ -2393,7 +2438,7 @@ mod spec_traits { // are more than `usize::MAX` elements. // Since the previous branch would eagerly panic if the capacity is too large // (via `with_capacity`) we do the same here. - _ => panic!("capacity overflow"), + _ => panic!("capacity overflow") }; // Reuse the extend specialization for TrustedLen. v.spec_extend(iter); @@ -2476,14 +2521,15 @@ impl SmallVec { /// /// The caller must ensure that `n <= Self::inline_size()`. unsafe fn from_elem_fallback(elem: T, n: usize) -> Self - where - T: Clone, - { + where T: Clone { let mut result = Self::new(); if n > 0 { let ptr = result.raw.as_mut_ptr_inline(); - let mut guard = DropGuard { ptr, len: 0 }; + let mut guard = DropGuard { + ptr, + len: 0 + }; // SAFETY: The caller ensures that the first `n` // is smaller than the inline size. @@ -2507,9 +2553,7 @@ impl SmallVec { } fn extend_fallback(&mut self, iter: I) - where - I: IntoIterator, - { + where I: IntoIterator { let iter = iter.into_iter(); let (size, _) = iter.size_hint(); self.reserve(size); @@ -2528,9 +2572,7 @@ impl SmallVec { /// /// [`extend_from_within`]: SmallVec::extend_from_within unsafe fn extend_from_within_fallback(&mut self, src: core::ops::Range) - where - T: Clone, - { + where T: Clone { let old_len = self.len(); let start = src.start; @@ -2544,7 +2586,10 @@ impl SmallVec { let dst = ptr.add(old_len); let src = ptr.add(start); - let mut guard = DropGuard { ptr: dst, len: 0 }; + let mut guard = DropGuard { + ptr: dst, + len: 0 + }; for i in 0..len { let val = (*src.add(i)).clone(); dst.add(i).write(val); @@ -2560,9 +2605,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); for x in iter { @@ -2572,9 +2615,7 @@ impl SmallVec { } fn clone_from_fallback(&mut self, source: &[T]) - where - T: Clone, - { + where T: Clone { // Inspired from `impl Clone for Vec`. // Drop anything that will not be overwritten. @@ -2596,9 +2637,7 @@ impl SmallVec { /// /// The caller must ensure that `slice.len() <= Self::inline_size()`. unsafe fn from_slice_fallback(slice: &[T]) -> Self - where - T: Clone, - { + where T: Clone { let mut v = Self::new(); let src = slice.as_ptr(); @@ -2608,7 +2647,10 @@ impl SmallVec { // SAFETY: The caller ensures that the slice length is smaller // than or equal to the inline length. unsafe { - let mut guard = DropGuard { ptr: dst, len: 0 }; + let mut guard = DropGuard { + ptr: dst, + len: 0 + }; for i in 0..len { let val = (*src.add(i)).clone(); dst.add(i).write(val); @@ -2633,7 +2675,8 @@ impl From<&[T]> for SmallVec { // Standard Rust vectors are already specialized. Self::from_vec(Vec::from(slice)) } else { - // SAFETY: The precondition is checked in the initial comparison above. + // SAFETY: The precondition is checked in the initial comparison + // above. unsafe { #[cfg(feature = "specialization")] { @@ -2813,17 +2856,19 @@ macro_rules! smallvec_inline { impl IntoIterator for SmallVec { type IntoIter = IntoIter; type Item = T; + fn into_iter(self) -> Self::IntoIter { - // SAFETY: we move out of this.raw by reading the value at its address, which is - // fine since we don't drop it + // SAFETY: we move out of this.raw by reading the value at its address, + // which is fine since we don't drop it unsafe { - // Set SmallVec len to zero as `IntoIter` drop handles dropping of the elements + // Set SmallVec len to zero as `IntoIter` drop handles dropping of + // the elements let this = ManuallyDrop::new(self); IntoIter { raw: (&this.raw as *const RawSmallVec).read(), begin: 0, end: this.len, - _marker: PhantomData, + _marker: PhantomData } } } @@ -2832,6 +2877,7 @@ impl IntoIterator for SmallVec { impl<'a, T, const N: usize> IntoIterator for &'a SmallVec { type IntoIter = core::slice::Iter<'a, T>; type Item = &'a T; + fn into_iter(self) -> Self::IntoIter { self.iter() } @@ -2840,14 +2886,14 @@ impl<'a, T, const N: usize> IntoIterator for &'a SmallVec { impl<'a, T, const N: usize> IntoIterator for &'a mut SmallVec { type IntoIter = core::slice::IterMut<'a, T>; type Item = &'a mut T; + fn into_iter(self) -> Self::IntoIter { self.iter_mut() } } impl PartialEq> for SmallVec -where - T: PartialEq, +where T: PartialEq { #[inline] fn eq(&self, other: &SmallVec) -> bool { @@ -2857,8 +2903,7 @@ where impl Eq for SmallVec where T: Eq {} impl PartialEq<[U; M]> for SmallVec -where - T: PartialEq, +where T: PartialEq { #[inline] fn eq(&self, other: &[U; M]) -> bool { @@ -2867,8 +2912,7 @@ where } impl PartialEq<&[U; M]> for SmallVec -where - T: PartialEq, +where T: PartialEq { #[inline] fn eq(&self, other: &&[U; M]) -> bool { @@ -2877,8 +2921,7 @@ where } impl PartialEq<[U]> for SmallVec -where - T: PartialEq, +where T: PartialEq { #[inline] fn eq(&self, other: &[U]) -> bool { @@ -2887,8 +2930,7 @@ where } impl PartialEq<&[U]> for SmallVec -where - T: PartialEq, +where T: PartialEq { #[inline] fn eq(&self, other: &&[U]) -> bool { @@ -2897,8 +2939,7 @@ where } impl PartialEq<&mut [U]> for SmallVec -where - T: PartialEq, +where T: PartialEq { #[inline] fn eq(&self, other: &&mut [U]) -> bool { @@ -2907,8 +2948,7 @@ where } impl PartialOrd for SmallVec -where - T: PartialOrd, +where T: PartialOrd { #[inline] fn partial_cmp(&self, other: &SmallVec) -> Option { @@ -2917,8 +2957,7 @@ where } impl Ord for SmallVec -where - T: Ord, +where T: Ord { #[inline] fn cmp(&self, other: &SmallVec) -> core::cmp::Ordering { @@ -2981,8 +3020,7 @@ impl Debug for Drain<'_, T, N> { #[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>, +where T: arbitrary::Arbitrary<'a> { fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result { u.arbitrary_iter()?.collect() @@ -3000,8 +3038,7 @@ where #[cfg(feature = "serde")] #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] impl Serialize for SmallVec -where - T: Serialize, +where T: Serialize { fn serialize(&self, serializer: S) -> Result { let mut state = serializer.serialize_seq(Some(self.len()))?; @@ -3015,25 +3052,23 @@ where #[cfg(feature = "serde")] #[cfg_attr(docsrs, doc(cfg(feature = "serde")))] impl<'de, T, const N: usize> Deserialize<'de> for SmallVec -where - T: Deserialize<'de>, +where T: Deserialize<'de> { fn deserialize>(deserializer: D) -> Result { deserializer.deserialize_seq(SmallVecVisitor { - phantom: PhantomData, + phantom: PhantomData }) } } #[cfg(feature = "serde")] struct SmallVecVisitor { - phantom: PhantomData, + phantom: PhantomData } #[cfg(feature = "serde")] impl<'de, T, const N: usize> Visitor<'de> for SmallVecVisitor -where - T: Deserialize<'de>, +where T: Deserialize<'de> { type Value = SmallVec; @@ -3042,9 +3077,7 @@ where } fn visit_seq(self, mut seq: B) -> Result - where - B: SeqAccess<'de>, - { + where B: SeqAccess<'de> { use serde_core::de::Error; let len = seq.size_hint().unwrap_or(0); let mut values = SmallVec::new(); @@ -3142,9 +3175,7 @@ unsafe impl BufMut for SmallVec { // and `advance_mut`. #[inline] fn put(&mut self, mut src: T) - where - Self: Sized, - { + where Self: Sized { // In case the src isn't contiguous, reserve upfront. self.reserve(src.remaining()); diff --git a/src/rawsmallvec.rs b/src/rawsmallvec.rs index dadbf95..d0192ef 100644 --- a/src/rawsmallvec.rs +++ b/src/rawsmallvec.rs @@ -1,5 +1,10 @@ -use core::mem::{ManuallyDrop, MaybeUninit}; -use core::ptr::NonNull; +use core::{ + mem::{ + ManuallyDrop, + MaybeUninit + }, + ptr::NonNull +}; /// Either a stack array with `length <= N` or a heap array /// whose pointer and capacity are stored here. @@ -9,5 +14,5 @@ use core::ptr::NonNull; #[repr(C)] pub union RawSmallVec { pub inline: ManuallyDrop>, - pub heap: (NonNull, usize), + pub heap: (NonNull, usize) } diff --git a/tests/arbitrary.rs b/tests/arbitrary.rs index 8bc7bb4..453120d 100644 --- a/tests/arbitrary.rs +++ b/tests/arbitrary.rs @@ -1,9 +1,15 @@ -use arbitrary::{Arbitrary, Unstructured}; -use smallvec::SmallVec; +use { + arbitrary::{ + Arbitrary, + Unstructured + }, + smallvec::SmallVec +}; #[test] fn test_arbitrary() { - // Deterministic for fixed input bytes; assert it builds a consistent SmallVec. + // Deterministic for fixed input bytes; assert it builds a consistent + // SmallVec. let mut u = Unstructured::new(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]); let v = SmallVec::::arbitrary(&mut u).unwrap(); assert_eq!(v.len(), v.iter().count()); diff --git a/tests/main.rs b/tests/main.rs index a1a0508..f8617f7 100644 --- a/tests/main.rs +++ b/tests/main.rs @@ -1,6 +1,19 @@ -use smallvec::{smallvec, SmallVec}; -use std::hash::Hasher; -use std::rc::Rc; +use { + core::{ + hash::Hasher, + iter::FromIterator + }, + smallvec::{ + SmallVec, + smallvec + }, + std::{ + borrow::ToOwned, + boxed::Box, + rc::Rc, + vec::Vec + } +}; #[test] pub fn test_zero() { @@ -313,7 +326,7 @@ fn test_truncate() { #[test] fn test_truncate_references() { - let mut v = vec![0, 1, 2, 3, 4, 5, 6, 7]; + let mut v = Vec::from([0, 1, 2, 3, 4, 5, 6, 7]); let mut i = 8; let mut v: SmallVec<&mut u8, 8> = v.iter_mut().collect(); @@ -482,8 +495,10 @@ fn test_ord() { #[test] fn test_hash() { - use std::collections::hash_map::DefaultHasher; - use std::hash::Hash; + use std::{ + collections::hash_map::DefaultHasher, + hash::Hash + }; fn hash(value: impl Hash) -> u64 { let mut hasher = DefaultHasher::new(); @@ -563,17 +578,17 @@ fn test_from() { assert_eq!(&SmallVec::::from(&[1][..])[..], [1]); assert_eq!(&SmallVec::::from(&[1, 2, 3][..])[..], [1, 2, 3]); - let vec = vec![]; + let vec = Vec::new(); let small_vec: SmallVec = SmallVec::from(vec); assert_eq!(&*small_vec, &[0u8; 0]); drop(small_vec); - let vec = vec![1, 2, 3, 4, 5]; + let vec = Vec::from([1, 2, 3, 4, 5]); let small_vec: SmallVec = SmallVec::from(vec); assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); drop(small_vec); - let vec = vec![1, 2, 3, 4, 5]; + let vec = Vec::from([1, 2, 3, 4, 5]); let small_vec: SmallVec = SmallVec::from(vec); assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); drop(small_vec); @@ -585,7 +600,7 @@ fn test_from() { let array = [99; 128]; let small_vec: SmallVec = SmallVec::from(array); - assert_eq!(&*small_vec, vec![99u8; 128].as_slice()); + assert_eq!(&*small_vec, Vec::from([99u8; 128]).as_slice()); drop(small_vec); #[derive(PartialEq, Eq, Debug)] @@ -595,14 +610,14 @@ fn test_from() { assert_eq!(&*small_vec, &[NoClone(42)]); drop(small_vec); - let vec = vec![NoClone(42)]; + let vec = Vec::from([NoClone(42)]); let small_vec: SmallVec = SmallVec::from(vec); assert_eq!(&*small_vec, &[NoClone(42)]); drop(small_vec); let array = [1; 128]; let small_vec: SmallVec = SmallVec::from(array); - assert_eq!(&*small_vec, vec![1; 128].as_slice()); + assert_eq!(&*small_vec, Vec::from([1; 128]).as_slice()); drop(small_vec); let array = [99]; @@ -641,8 +656,8 @@ fn test_into_iter_as_slice() { #[test] fn test_into_iter_clone() { - // Test that the cloned iterator yields identical elements and that it owns its - // own copy (i.e. no use after move errors). + // Test that the cloned iterator yields identical elements and that it owns + // its own copy (i.e. no use after move errors). let mut iter = SmallVec::::from_iter(0..3).into_iter(); let mut clone_iter = iter.clone(); while let Some(x) = iter.next() { @@ -682,7 +697,7 @@ fn shrink_to_fit_unspill() { #[test] fn shrink_after_from_empty_vec() { - let mut v = SmallVec::::from_vec(vec![]); + let mut v = SmallVec::::from_vec(Vec::new()); v.shrink_to_fit(); assert!(!v.spilled()) } @@ -690,10 +705,10 @@ fn shrink_after_from_empty_vec() { #[test] fn test_into_vec() { let vec = SmallVec::::from_iter(0..2); - assert_eq!(vec.into_vec(), vec![0, 1]); + assert_eq!(vec.into_vec(), Vec::from([0, 1])); let vec = SmallVec::::from_iter(0..3); - assert_eq!(vec.into_vec(), vec![0, 1, 2]); + assert_eq!(vec.into_vec(), Vec::from([0, 1, 2])); } #[test] @@ -730,32 +745,32 @@ fn test_try_into_array() { #[test] fn test_from_vec() { - let vec = vec![]; + let vec = Vec::new(); let small_vec: SmallVec = SmallVec::from_vec(vec); assert_eq!(&*small_vec, &[0u8; 0]); drop(small_vec); - let vec = vec![]; + let vec = Vec::new(); let small_vec: SmallVec = SmallVec::from_vec(vec); assert_eq!(&*small_vec, &[0u8; 0]); drop(small_vec); - let vec = vec![1]; + let vec = Vec::from([1]); let small_vec: SmallVec = SmallVec::from_vec(vec); assert_eq!(&*small_vec, &[1]); drop(small_vec); - let vec = vec![1, 2, 3]; + let vec = Vec::from([1, 2, 3]); let small_vec: SmallVec = SmallVec::from_vec(vec); assert_eq!(&*small_vec, &[1, 2, 3]); drop(small_vec); - let vec = vec![1, 2, 3, 4, 5]; + let vec = Vec::from([1, 2, 3, 4, 5]); let small_vec: SmallVec = SmallVec::from_vec(vec); assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); drop(small_vec); - let vec = vec![1, 2, 3, 4, 5]; + let vec = Vec::from([1, 2, 3, 4, 5]); let small_vec: SmallVec = SmallVec::from_vec(vec); assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]); drop(small_vec); @@ -990,12 +1005,13 @@ fn collect_from_iter() { impl Iterator for IterNoHint { type Item = I::Item; + fn next(&mut self) -> Option { self.0.next() } - // no implementation of size_hint means it returns (0, None) - which forces - // from_iter to grow the allocated space iteratively. + // no implementation of size_hint means it returns (0, None) - which + // forces from_iter to grow the allocated space iteratively. } // A length of 3 is fine to trigger this bug under valgrind, but making the diff --git a/tests/serde.rs b/tests/serde.rs index 83e2da9..dbeec38 100644 --- a/tests/serde.rs +++ b/tests/serde.rs @@ -2,24 +2,43 @@ use smallvec::SmallVec; #[test] fn test_serde() { - use serde_test::{assert_tokens, Token}; + use serde_test::{ + Token, + assert_tokens + }; let mut small_vec: SmallVec = SmallVec::new(); - assert_tokens(&small_vec, &[Token::Seq { len: Some(0) }, Token::SeqEnd]); + assert_tokens( + &small_vec, + &[ + Token::Seq { + len: Some(0) + }, + Token::SeqEnd + ] + ); small_vec.push(1); assert_tokens( &small_vec, - &[Token::Seq { len: Some(1) }, Token::I32(1), Token::SeqEnd], + &[ + Token::Seq { + len: Some(1) + }, + Token::I32(1), + Token::SeqEnd + ] ); small_vec.extend([2, 3, 4]); assert_tokens( &small_vec, &[ - Token::Seq { len: Some(4) }, + Token::Seq { + len: Some(4) + }, Token::I32(1), Token::I32(2), Token::I32(3), Token::I32(4), - Token::SeqEnd, - ], + Token::SeqEnd + ] ); }