smallvec/lib.rs
1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7//! Small vectors in various sizes. These store a certain number of elements
8//! inline, and fall back to the heap for larger allocations. This can be a
9//! useful optimization for improving cache locality and reducing allocator
10//! traffic for workloads that fit within the inline buffer.
11//!
12//! ## `no_std` support
13//!
14//! By default, `smallvec` does not depend on `std`. However, the optional
15//! `write` feature implements the `std::io::Write` trait for vectors of `u8`.
16//! When this feature is enabled, `smallvec` depends on `std`.
17//!
18//! ## Optional features
19//!
20//! ### `serde`
21//!
22//! When this optional dependency is enabled, `SmallVec` implements the
23//! `serde::Serialize` and `serde::Deserialize` traits.
24//!
25//! ### `write`
26//!
27//! When this feature is enabled, `SmallVec<[u8; _]>` implements the
28//! `std::io::Write` trait. This feature is not compatible with `#![no_std]`
29//! programs.
30//!
31//! ### `union`
32//!
33//! **This feature requires Rust 1.49.**
34//!
35//! When the `union` feature is enabled `smallvec` will track its state (inline
36//! or spilled) without the use of an enum tag, reducing the size of the
37//! `smallvec` by one machine word. This means that there is potentially no
38//! space overhead compared to `Vec`. Note that `smallvec` can still be larger
39//! than `Vec` if the inline buffer is larger than two machine words.
40//!
41//! To use this feature add `features = ["union"]` in the `smallvec` section of
42//! Cargo.toml. Note that this feature requires Rust 1.49.
43//!
44//! Tracking issue: [rust-lang/rust#55149](https://github.com/rust-lang/rust/issues/55149)
45//!
46//! ### `const_generics`
47//!
48//! **This feature requires Rust 1.51.**
49//!
50//! When this feature is enabled, `SmallVec` works with any arrays of any size,
51//! not just a fixed list of sizes.
52//!
53//! ### `const_new`
54//!
55//! **This feature requires Rust 1.51.**
56//!
57//! This feature exposes the functions [`SmallVec::new_const`],
58//! [`SmallVec::from_const`], and [`smallvec_inline`] which enables the
59//! `SmallVec` to be initialized from a const context. For details, see the
60//! [Rust Reference](https://doc.rust-lang.org/reference/const_eval.html#const-functions).
61//!
62//! ### `drain_filter`
63//!
64//! **This feature is unstable.** It may change to match the unstable
65//! `drain_filter` method in libstd.
66//!
67//! Enables the `drain_filter` method, which produces an iterator that calls a
68//! user-provided closure to determine which elements of the vector to remove
69//! and yield from the iterator.
70//!
71//! ### `drain_keep_rest`
72//!
73//! **This feature is unstable.** It may change to match the unstable
74//! `drain_keep_rest` method in libstd.
75//!
76//! Enables the `DrainFilter::keep_rest` method.
77//!
78//! ### `specialization`
79//!
80//! **This feature is unstable and requires a nightly build of the Rust
81//! toolchain.**
82//!
83//! When this feature is enabled, `SmallVec::from(slice)` has improved
84//! performance for slices of `Copy` types. (Without this feature, you can use
85//! `SmallVec::from_slice` to get optimal performance for `Copy` types.)
86//!
87//! Tracking issue: [rust-lang/rust#31844](https://github.com/rust-lang/rust/issues/31844)
88//!
89//! ### `may_dangle`
90//!
91//! **This feature is unstable and requires a nightly build of the Rust
92//! toolchain.**
93//!
94//! This feature makes the Rust compiler less strict about use of vectors that
95//! contain borrowed references. For details, see the
96//! [Rustonomicon](https://doc.rust-lang.org/1.42.0/nomicon/dropck.html#an-escape-hatch).
97//!
98//! Tracking issue: [rust-lang/rust#34761](https://github.com/rust-lang/rust/issues/34761)
99
100#![no_std]
101#![cfg_attr(docsrs, feature(doc_cfg))]
102#![cfg_attr(feature = "specialization", allow(incomplete_features))]
103#![cfg_attr(feature = "specialization", feature(specialization))]
104#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
105#![deny(missing_docs)]
106
107#[doc(hidden)]
108pub extern crate alloc;
109
110#[cfg(any(test, feature = "write"))]
111extern crate std;
112
113#[cfg(test)]
114mod tests;
115
116#[cfg(feature = "serde")]
117use core::marker::PhantomData;
118#[cfg(feature = "drain_keep_rest")]
119use core::mem::ManuallyDrop;
120#[cfg(feature = "malloc_size_of")]
121use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
122#[cfg(feature = "serde")]
123use serde::{
124 de::{Deserialize, Deserializer, SeqAccess, Visitor},
125 ser::{Serialize, SerializeSeq, Serializer},
126};
127#[cfg(feature = "write")]
128use std::io;
129#[allow(deprecated)]
130use {
131 alloc::{
132 alloc::{Layout, LayoutErr},
133 boxed::Box,
134 vec,
135 vec::Vec,
136 },
137 core::{
138 borrow::{Borrow, BorrowMut},
139 cmp, fmt,
140 hash::{Hash, Hasher},
141 hint::unreachable_unchecked,
142 iter::{repeat, FromIterator, FusedIterator, IntoIterator},
143 mem::{self, MaybeUninit},
144 ops::{self, Range, RangeBounds},
145 ptr::{self, NonNull},
146 slice::{self, SliceIndex},
147 },
148};
149
150/// Creates a [`SmallVec`] containing the arguments.
151///
152/// `smallvec!` allows `SmallVec`s to be defined with the same syntax as array
153/// expressions. There are two forms of this macro:
154///
155/// - Create a [`SmallVec`] containing a given list of elements:
156///
157/// ```
158/// # use smallvec::{smallvec, SmallVec};
159/// # fn main() {
160/// let v: SmallVec<[_; 128]> = smallvec![1, 2, 3];
161/// assert_eq!(v[0], 1);
162/// assert_eq!(v[1], 2);
163/// assert_eq!(v[2], 3);
164/// # }
165/// ```
166///
167/// - Create a [`SmallVec`] from a given element and size:
168///
169/// ```
170/// # use smallvec::{smallvec, SmallVec};
171/// # fn main() {
172/// let v: SmallVec<[_; 10]> = smallvec![1; 3];
173/// assert_eq!(v, SmallVec::from_buf([1, 1, 1]));
174/// # }
175/// ```
176///
177/// Note that unlike array expressions this syntax supports all elements
178/// which implement [`Clone`] and the number of elements doesn't have to be
179/// a constant.
180///
181/// This will use `clone` to duplicate an expression, so one should be careful
182/// using this with types having a nonstandard `Clone` implementation. For
183/// example, `smallvec![Rc::new(1); 5]` will create a vector of five references
184/// to the same boxed integer value, not five references pointing to
185/// independently boxed integers.
186#[macro_export]
187macro_rules! smallvec {
188 // count helper: transform any expression into 1
189 (@one $x:expr) => (1usize);
190 () => (
191 $crate::SmallVec::new()
192 );
193 ($elem:expr; $n:expr) => ({
194 $crate::SmallVec::from_elem($elem, $n)
195 });
196 ($($x:expr),+$(,)?) => ({
197 let count = 0usize $(+ $crate::smallvec!(@one $x))+;
198 let mut vec = $crate::SmallVec::new();
199 if count <= vec.inline_size() {
200 $(vec.push($x);)*
201 vec
202 } else {
203 $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
204 }
205 });
206}
207
208/// Creates an inline [`SmallVec`] containing the arguments. This macro is
209/// enabled by the feature `const_new`.
210///
211/// `smallvec_inline!` allows `SmallVec`s to be defined with the same syntax as
212/// array expressions in `const` contexts. The inline storage `A` will always be
213/// an array of the size specified by the arguments. There are two forms of this
214/// macro:
215///
216/// - Create a [`SmallVec`] containing a given list of elements:
217///
218/// ```
219/// # use smallvec::{smallvec_inline, SmallVec};
220/// # fn main() {
221/// const V: SmallVec<[i32; 3]> = smallvec_inline![1, 2, 3];
222/// assert_eq!(V[0], 1);
223/// assert_eq!(V[1], 2);
224/// assert_eq!(V[2], 3);
225/// # }
226/// ```
227///
228/// - Create a [`SmallVec`] from a given element and size:
229///
230/// ```
231/// # use smallvec::{smallvec_inline, SmallVec};
232/// # fn main() {
233/// const V: SmallVec<[i32; 3]> = smallvec_inline![1; 3];
234/// assert_eq!(V, SmallVec::from_buf([1, 1, 1]));
235/// # }
236/// ```
237///
238/// Note that the behavior mimics that of array expressions, in contrast to
239/// [`smallvec`].
240#[cfg(feature = "const_new")]
241#[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
242#[macro_export]
243macro_rules! smallvec_inline {
244 // count helper: transform any expression into 1
245 (@one $x:expr) => (1usize);
246 ($elem:expr; $n:expr) => ({
247 $crate::SmallVec::<[_; $n]>::from_const([$elem; $n])
248 });
249 ($($x:expr),+ $(,)?) => ({
250 const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
251 $crate::SmallVec::<[_; N]>::from_const([$($x,)*])
252 });
253}
254
255/// `panic!()` in debug builds, optimization hint in release.
256#[cfg(not(feature = "union"))]
257macro_rules! debug_unreachable {
258 () => {
259 debug_unreachable!("entered unreachable code")
260 };
261 ($e:expr) => {
262 if cfg!(debug_assertions) {
263 panic!($e);
264 } else {
265 unreachable_unchecked();
266 }
267 };
268}
269
270/// Trait to be implemented by a collection that can be extended from a slice
271///
272/// ## Example
273///
274/// ```rust
275/// use smallvec::{ExtendFromSlice, SmallVec};
276///
277/// fn initialize<V: ExtendFromSlice<u8>>(v: &mut V) {
278/// v.extend_from_slice(b"Test!");
279/// }
280///
281/// let mut vec = Vec::new();
282/// initialize(&mut vec);
283/// assert_eq!(&vec, b"Test!");
284///
285/// let mut small_vec = SmallVec::<[u8; 8]>::new();
286/// initialize(&mut small_vec);
287/// assert_eq!(&small_vec as &[_], b"Test!");
288/// ```
289#[doc(hidden)]
290#[deprecated]
291pub trait ExtendFromSlice<T> {
292 /// Extends a collection from a slice of its element type
293 fn extend_from_slice(&mut self, other: &[T]);
294}
295
296#[allow(deprecated)]
297impl<T: Clone> ExtendFromSlice<T> for Vec<T> {
298 fn extend_from_slice(&mut self, other: &[T]) {
299 Vec::extend_from_slice(self, other)
300 }
301}
302
303/// Error type for APIs with fallible heap allocation
304#[derive(Debug)]
305pub enum CollectionAllocErr {
306 /// Overflow `usize::MAX` or other error during size computation
307 CapacityOverflow,
308 /// The allocator return an error
309 AllocErr {
310 /// The layout that was passed to the allocator
311 layout: Layout,
312 },
313}
314
315impl fmt::Display for CollectionAllocErr {
316 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317 write!(f, "Allocation error: {:?}", self)
318 }
319}
320
321#[allow(deprecated)]
322impl From<LayoutErr> for CollectionAllocErr {
323 fn from(_: LayoutErr) -> Self {
324 CollectionAllocErr::CapacityOverflow
325 }
326}
327
328fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
329 match result {
330 Ok(x) => x,
331 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
332 Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
333 }
334}
335
336/// FIXME: use `Layout::array` when we require a Rust version where it’s stable
337/// <https://github.com/rust-lang/rust/issues/55724>
338fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
339 let size = mem::size_of::<T>()
340 .checked_mul(n)
341 .ok_or(CollectionAllocErr::CapacityOverflow)?;
342 let align = mem::align_of::<T>();
343 Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
344}
345
346unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
347 // This unwrap should succeed since the same did when allocating.
348 let layout = layout_array::<T>(capacity).unwrap();
349 alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout)
350}
351
352/// An iterator that removes the items from a `SmallVec` and yields them by
353/// value.
354///
355/// Returned from [`SmallVec::drain`][1].
356///
357/// [1]: struct.SmallVec.html#method.drain
358pub struct Drain<'a, T: 'a + Array> {
359 tail_start: usize,
360 tail_len: usize,
361 iter: slice::Iter<'a, T::Item>,
362 vec: NonNull<SmallVec<T>>,
363}
364
365impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
366where
367 T::Item: fmt::Debug,
368{
369 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
370 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
371 }
372}
373
374unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
375unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
376
377impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
378 type Item = T::Item;
379
380 #[inline]
381 fn next(&mut self) -> Option<T::Item> {
382 self.iter
383 .next()
384 .map(|reference| unsafe { ptr::read(reference) })
385 }
386
387 #[inline]
388 fn size_hint(&self) -> (usize, Option<usize>) {
389 self.iter.size_hint()
390 }
391}
392
393impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
394 #[inline]
395 fn next_back(&mut self) -> Option<T::Item> {
396 self.iter
397 .next_back()
398 .map(|reference| unsafe { ptr::read(reference) })
399 }
400}
401
402impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
403 #[inline]
404 fn len(&self) -> usize {
405 self.iter.len()
406 }
407}
408
409impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
410
411impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
412 fn drop(&mut self) {
413 self.for_each(drop);
414
415 if self.tail_len > 0 {
416 unsafe {
417 let source_vec = self.vec.as_mut();
418
419 // memmove back untouched tail, update to new length
420 let start = source_vec.len();
421 let tail = self.tail_start;
422 if tail != start {
423 // as_mut_ptr creates a &mut, invalidating other pointers.
424 // This pattern avoids calling it with a pointer already
425 // present.
426 let ptr = source_vec.as_mut_ptr();
427 let src = ptr.add(tail);
428 let dst = ptr.add(start);
429 ptr::copy(src, dst, self.tail_len);
430 }
431 source_vec.set_len(start + self.tail_len);
432 }
433 }
434 }
435}
436
437#[cfg(feature = "drain_filter")]
438/// An iterator which uses a closure to determine if an element should be
439/// removed.
440///
441/// Returned from [`SmallVec::drain_filter`][1].
442///
443/// [1]: struct.SmallVec.html#method.drain_filter
444pub struct DrainFilter<'a, T, F>
445where
446 F: FnMut(&mut T::Item) -> bool,
447 T: Array,
448{
449 vec: &'a mut SmallVec<T>,
450 /// The index of the item that will be inspected by the next call to `next`.
451 idx: usize,
452 /// The number of items that have been drained (removed) thus far.
453 del: usize,
454 /// The original length of `vec` prior to draining.
455 old_len: usize,
456 /// The filter test predicate.
457 pred: F,
458 /// A flag that indicates a panic has occurred in the filter test predicate.
459 /// This is used as a hint in the drop implementation to prevent consumption
460 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
461 /// backshifted in the `vec`, but no further items will be dropped or
462 /// tested by the filter predicate.
463 panic_flag: bool,
464}
465
466#[cfg(feature = "drain_filter")]
467impl<T, F> fmt::Debug for DrainFilter<'_, T, F>
468where
469 F: FnMut(&mut T::Item) -> bool,
470 T: Array,
471 T::Item: fmt::Debug,
472{
473 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
474 f.debug_tuple("DrainFilter")
475 .field(&self.vec.as_slice())
476 .finish()
477 }
478}
479
480#[cfg(feature = "drain_filter")]
481impl<T, F> Iterator for DrainFilter<'_, T, F>
482where
483 F: FnMut(&mut T::Item) -> bool,
484 T: Array,
485{
486 type Item = T::Item;
487
488 fn next(&mut self) -> Option<T::Item> {
489 unsafe {
490 while self.idx < self.old_len {
491 let i = self.idx;
492 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
493 self.panic_flag = true;
494 let drained = (self.pred)(&mut v[i]);
495 self.panic_flag = false;
496 // Update the index *after* the predicate is called. If the
497 // index is updated prior and the predicate
498 // panics, the element at this index would be
499 // leaked.
500 self.idx += 1;
501 if drained {
502 self.del += 1;
503 return Some(ptr::read(&v[i]));
504 } else if self.del > 0 {
505 let del = self.del;
506 let src: *const Self::Item = &v[i];
507 let dst: *mut Self::Item = &mut v[i - del];
508 ptr::copy_nonoverlapping(src, dst, 1);
509 }
510 }
511 None
512 }
513 }
514
515 fn size_hint(&self) -> (usize, Option<usize>) {
516 (0, Some(self.old_len - self.idx))
517 }
518}
519
520#[cfg(feature = "drain_filter")]
521impl<T, F> Drop for DrainFilter<'_, T, F>
522where
523 F: FnMut(&mut T::Item) -> bool,
524 T: Array,
525{
526 fn drop(&mut self) {
527 struct BackshiftOnDrop<'a, 'b, T, F>
528 where
529 F: FnMut(&mut T::Item) -> bool,
530 T: Array,
531 {
532 drain: &'b mut DrainFilter<'a, T, F>,
533 }
534
535 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
536 where
537 F: FnMut(&mut T::Item) -> bool,
538 T: Array,
539 {
540 fn drop(&mut self) {
541 unsafe {
542 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
543 // This is a pretty messed up state, and there isn't
544 // really an obviously right
545 // thing to do. We don't want to keep trying
546 // to execute `pred`, so we just backshift all the
547 // unprocessed elements and tell
548 // the vec that they still exist. The backshift
549 // is required to prevent a double-drop of the last
550 // successfully drained item
551 // prior to a panic in the predicate.
552 let ptr = self.drain.vec.as_mut_ptr();
553 let src = ptr.add(self.drain.idx);
554 let dst = src.sub(self.drain.del);
555 let tail_len = self.drain.old_len - self.drain.idx;
556 src.copy_to(dst, tail_len);
557 }
558 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
559 }
560 }
561 }
562
563 let backshift = BackshiftOnDrop { drain: self };
564
565 // Attempt to consume any remaining elements if the filter predicate
566 // has not yet panicked. We'll backshift any remaining elements
567 // whether we've already panicked or if the consumption here panics.
568 if !backshift.drain.panic_flag {
569 backshift.drain.for_each(drop);
570 }
571 }
572}
573
574#[cfg(feature = "drain_keep_rest")]
575impl<T, F> DrainFilter<'_, T, F>
576where
577 F: FnMut(&mut T::Item) -> bool,
578 T: Array,
579{
580 /// Keep unyielded elements in the source `Vec`.
581 ///
582 /// # Examples
583 ///
584 /// ```
585 /// # use smallvec::{smallvec, SmallVec};
586 ///
587 /// let mut vec: SmallVec<[char; 2]> = smallvec!['a', 'b', 'c'];
588 /// let mut drain = vec.drain_filter(|_| true);
589 ///
590 /// assert_eq!(drain.next().unwrap(), 'a');
591 ///
592 /// // This call keeps 'b' and 'c' in the vec.
593 /// drain.keep_rest();
594 ///
595 /// // If we wouldn't call `keep_rest()`,
596 /// // `vec` would be empty.
597 /// assert_eq!(vec, SmallVec::<[char; 2]>::from_slice(&['b', 'c']));
598 /// ```
599 pub fn keep_rest(self) {
600 // At this moment layout looks like this:
601 //
602 // _____________________/-- old_len
603 // / \
604 // [kept] [yielded] [tail]
605 // \_______/ ^-- idx
606 // \-- del
607 //
608 // Normally `Drop` impl would drop [tail] (via .for_each(drop), ie still
609 // calling `pred`)
610 //
611 // 1. Move [tail] after [kept]
612 // 2. Update length of the original vec to `old_len - del` a. In case of
613 // ZST, this is the only thing we want to do
614 // 3. Do *not* drop self, as everything is put in a consistent state
615 // already, there is nothing to do
616 let mut this = ManuallyDrop::new(self);
617
618 unsafe {
619 // ZSTs have no identity, so we don't need to move them around.
620 let needs_move = mem::size_of::<T::Item>() != 0;
621
622 if needs_move && this.idx < this.old_len && this.del > 0 {
623 let ptr = this.vec.as_mut_ptr();
624 let src = ptr.add(this.idx);
625 let dst = src.sub(this.del);
626 let tail_len = this.old_len - this.idx;
627 src.copy_to(dst, tail_len);
628 }
629
630 let new_len = this.old_len - this.del;
631 this.vec.set_len(new_len);
632 }
633 }
634}
635
636#[cfg(feature = "union")]
637union SmallVecData<A: Array> {
638 inline: core::mem::ManuallyDrop<MaybeUninit<A>>,
639 heap: (NonNull<A::Item>, usize),
640}
641
642#[cfg(all(feature = "union", feature = "const_new"))]
643impl<T, const N: usize> SmallVecData<[T; N]> {
644 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
645 #[inline]
646 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
647 SmallVecData {
648 inline: core::mem::ManuallyDrop::new(inline),
649 }
650 }
651}
652
653#[cfg(feature = "union")]
654impl<A: Array> SmallVecData<A> {
655 #[inline]
656 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
657 ConstNonNull::new(self.inline.as_ptr() as *const A::Item).unwrap()
658 }
659 #[inline]
660 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
661 NonNull::new(self.inline.as_mut_ptr() as *mut A::Item).unwrap()
662 }
663 #[inline]
664 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
665 SmallVecData {
666 inline: core::mem::ManuallyDrop::new(inline),
667 }
668 }
669 // Workaround for https://github.com/rust-lang/rust/issues/157743: when from_inline is
670 // called with MaybeUninit::uninit(), rustc 1.93+ GVN propagates const
671 // <uninit> into the ManuallyDrop::new() aggregate, causing LLVM to
672 // materialize a global constant that MemCpyOpt then collapses into a
673 // memset over the whole struct. Using assume_init() of a doubly-wrapped
674 // MaybeUninit produces Immediate::Uninit instead of const <uninit>,
675 // which codegen handles as undef without emitting any global. This
676 // function also avoids introducing an intermediate local that would
677 // inflate stack frames in debug builds.
678 #[inline]
679 fn empty() -> SmallVecData<A> {
680 // SAFETY: ManuallyDrop<MaybeUninit<A>> is valid for any bit pattern
681 // including uninitialized bytes, so assume_init() on a
682 // MaybeUninit of that type is sound.
683 SmallVecData {
684 inline: unsafe { MaybeUninit::uninit().assume_init() },
685 }
686 }
687 #[inline]
688 unsafe fn into_inline(self) -> MaybeUninit<A> {
689 core::mem::ManuallyDrop::into_inner(self.inline)
690 }
691 #[inline]
692 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
693 (ConstNonNull(self.heap.0), self.heap.1)
694 }
695 #[inline]
696 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
697 let h = &mut self.heap;
698 (h.0, &mut h.1)
699 }
700 #[inline]
701 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
702 SmallVecData { heap: (ptr, len) }
703 }
704}
705
706#[cfg(not(feature = "union"))]
707enum SmallVecData<A: Array> {
708 Inline(MaybeUninit<A>),
709 // Using NonNull and NonZero here allows to reduce size of `SmallVec`.
710 Heap {
711 // Since we never allocate on heap
712 // unless our capacity is bigger than inline capacity
713 // heap capacity cannot be less than 1.
714 // Therefore, pointer cannot be null too.
715 ptr: NonNull<A::Item>,
716 len: usize,
717 },
718}
719
720#[cfg(all(not(feature = "union"), feature = "const_new"))]
721impl<T, const N: usize> SmallVecData<[T; N]> {
722 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
723 #[inline]
724 const fn from_const(inline: MaybeUninit<[T; N]>) -> Self {
725 SmallVecData::Inline(inline)
726 }
727}
728
729#[cfg(not(feature = "union"))]
730impl<A: Array> SmallVecData<A> {
731 #[inline]
732 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
733 match self {
734 SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
735 _ => debug_unreachable!(),
736 }
737 }
738 #[inline]
739 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
740 match self {
741 SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
742 _ => debug_unreachable!(),
743 }
744 }
745 #[inline]
746 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
747 SmallVecData::Inline(inline)
748 }
749 // See the comment on the union variant's empty() for why this exists.
750 #[inline]
751 fn empty() -> SmallVecData<A> {
752 // SAFETY: MaybeUninit<A> is valid for any bit pattern including
753 // uninitialized bytes, so assume_init() on a MaybeUninit of
754 // that type is sound.
755 SmallVecData::Inline(unsafe { MaybeUninit::uninit().assume_init() })
756 }
757 #[inline]
758 unsafe fn into_inline(self) -> MaybeUninit<A> {
759 match self {
760 SmallVecData::Inline(a) => a,
761 _ => debug_unreachable!(),
762 }
763 }
764 #[inline]
765 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
766 match self {
767 SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
768 _ => debug_unreachable!(),
769 }
770 }
771 #[inline]
772 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
773 match self {
774 SmallVecData::Heap { ptr, len } => (*ptr, len),
775 _ => debug_unreachable!(),
776 }
777 }
778 #[inline]
779 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
780 SmallVecData::Heap { ptr, len }
781 }
782}
783
784unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
785unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
786
787/// A `Vec`-like container that can store a small number of elements inline.
788///
789/// `SmallVec` acts like a vector, but can store a limited amount of data inline
790/// within the `SmallVec` struct rather than in a separate allocation. If the
791/// data exceeds this limit, the `SmallVec` will "spill" its data onto the heap,
792/// allocating a new buffer to hold it.
793///
794/// The amount of data that a `SmallVec` can store inline depends on its backing
795/// store. The backing store can be any type that implements the `Array` trait;
796/// usually it is a small fixed-sized array. For example a `SmallVec<[u64; 8]>`
797/// can hold up to eight 64-bit integers inline.
798///
799/// ## Example
800///
801/// ```rust
802/// use smallvec::SmallVec;
803/// let mut v = SmallVec::<[u8; 4]>::new(); // initialize an empty vector
804///
805/// // The vector can hold up to 4 items without spilling onto the heap.
806/// v.extend(0..4);
807/// assert_eq!(v.len(), 4);
808/// assert!(!v.spilled());
809///
810/// // Pushing another element will force the buffer to spill:
811/// v.push(4);
812/// assert_eq!(v.len(), 5);
813/// assert!(v.spilled());
814/// ```
815pub struct SmallVec<A: Array> {
816 // The capacity field is used to determine which of the storage variants is active:
817 // If capacity <= Self::inline_capacity() then the inline variant is used and capacity holds
818 // the current length of the vector (number of elements actually in use). If capacity >
819 // Self::inline_capacity() then the heap variant is used and capacity holds the size of the
820 // memory allocation.
821 capacity: usize,
822 data: SmallVecData<A>,
823}
824
825impl<A: Array> SmallVec<A> {
826 /// Construct an empty vector
827 #[inline]
828 pub fn new() -> SmallVec<A> {
829 // Try to detect invalid custom implementations of `Array`. Hopefully,
830 // this check should be optimized away entirely for valid ones.
831 assert!(
832 mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
833 && mem::align_of::<A>() >= mem::align_of::<A::Item>()
834 );
835 SmallVec {
836 capacity: 0,
837 data: SmallVecData::empty(),
838 }
839 }
840
841 /// Construct an empty vector with enough capacity pre-allocated to store at
842 /// least `n` elements.
843 ///
844 /// Will create a heap allocation only if `n` is larger than the inline
845 /// capacity.
846 ///
847 /// ```
848 /// # use smallvec::SmallVec;
849 ///
850 /// let v: SmallVec<[u8; 3]> = SmallVec::with_capacity(100);
851 ///
852 /// assert!(v.is_empty());
853 /// assert!(v.capacity() >= 100);
854 /// ```
855 #[inline]
856 pub fn with_capacity(n: usize) -> Self {
857 let mut v = SmallVec::new();
858 v.reserve_exact(n);
859 v
860 }
861
862 /// Construct a new `SmallVec` from a `Vec<A::Item>`.
863 ///
864 /// Elements will be copied to the inline buffer if `vec.capacity() <=
865 /// Self::inline_capacity()`.
866 ///
867 /// ```rust
868 /// use smallvec::SmallVec;
869 ///
870 /// let vec = vec![1, 2, 3, 4, 5];
871 /// let small_vec: SmallVec<[_; 3]> = SmallVec::from_vec(vec);
872 ///
873 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
874 /// ```
875 #[inline]
876 pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
877 if vec.capacity() <= Self::inline_capacity() {
878 // Cannot use Vec with smaller capacity
879 // because we use value of `Self::capacity` field as indicator.
880 unsafe {
881 let mut data = SmallVecData::<A>::empty();
882 let len = vec.len();
883 vec.set_len(0);
884 ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
885
886 SmallVec {
887 capacity: len,
888 data,
889 }
890 }
891 } else {
892 let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
893 mem::forget(vec);
894 let ptr = NonNull::new(ptr)
895 // See docs: https://doc.rust-lang.org/std/vec/struct.Vec.html#method.as_mut_ptr
896 .expect("Cannot be null by `Vec` invariant");
897
898 SmallVec {
899 capacity: cap,
900 data: SmallVecData::from_heap(ptr, len),
901 }
902 }
903 }
904
905 /// Constructs a new `SmallVec` on the stack from an `A` without
906 /// copying elements.
907 ///
908 /// ```rust
909 /// use smallvec::SmallVec;
910 ///
911 /// let buf = [1, 2, 3, 4, 5];
912 /// let small_vec: SmallVec<_> = SmallVec::from_buf(buf);
913 ///
914 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
915 /// ```
916 #[inline]
917 pub fn from_buf(buf: A) -> SmallVec<A> {
918 SmallVec {
919 capacity: A::size(),
920 data: SmallVecData::from_inline(MaybeUninit::new(buf)),
921 }
922 }
923
924 /// Constructs a new `SmallVec` on the stack from an `A` without
925 /// copying elements. Also sets the length, which must be less or
926 /// equal to the size of `buf`.
927 ///
928 /// ```rust
929 /// use smallvec::SmallVec;
930 ///
931 /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
932 /// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5);
933 ///
934 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
935 /// ```
936 #[inline]
937 pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
938 assert!(len <= A::size());
939 unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
940 }
941
942 /// Constructs a new `SmallVec` on the stack from an `A` without
943 /// copying elements. Also sets the length. The user is responsible
944 /// for ensuring that `len <= A::size()`.
945 ///
946 /// ```rust
947 /// use {smallvec::SmallVec, std::mem::MaybeUninit};
948 ///
949 /// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
950 /// let small_vec: SmallVec<_> =
951 /// unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), 5) };
952 ///
953 /// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
954 /// ```
955 #[inline]
956 pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
957 SmallVec {
958 capacity: len,
959 data: SmallVecData::from_inline(buf),
960 }
961 }
962
963 /// Sets the length of a vector.
964 ///
965 /// This will explicitly set the size of the vector, without actually
966 /// modifying its buffers, so it is up to the caller to ensure that the
967 /// vector is actually the specified size.
968 pub unsafe fn set_len(&mut self, new_len: usize) {
969 let (_, len_ptr, _) = self.triple_mut();
970 *len_ptr = new_len;
971 }
972
973 /// The maximum number of elements this vector can hold inline
974 #[inline]
975 fn inline_capacity() -> usize {
976 if mem::size_of::<A::Item>() > 0 {
977 A::size()
978 } else {
979 // For zero-size items code like `ptr.add(offset)` always returns
980 // the same pointer. Therefore all items are at the same
981 // address, and any array size has capacity for
982 // infinitely many items. The capacity is limited by the
983 // bit width of the length field.
984 //
985 // `Vec` also does this:
986 // https://github.com/rust-lang/rust/blob/1.44.0/src/liballoc/raw_vec.rs#L186
987 //
988 // In our case, this also ensures that a smallvec of zero-size items
989 // never spills, and we never try to allocate zero bytes
990 // which `std::alloc::alloc` disallows.
991 #[allow(deprecated)]
992 core::usize::MAX
993 }
994 }
995
996 /// The maximum number of elements this vector can hold inline
997 #[inline]
998 pub fn inline_size(&self) -> usize {
999 Self::inline_capacity()
1000 }
1001
1002 /// The number of elements stored in the vector
1003 #[inline]
1004 pub fn len(&self) -> usize {
1005 self.triple().1
1006 }
1007
1008 /// Returns `true` if the vector is empty
1009 #[inline]
1010 pub fn is_empty(&self) -> bool {
1011 self.len() == 0
1012 }
1013
1014 /// The number of items the vector can hold without reallocating
1015 #[inline]
1016 pub fn capacity(&self) -> usize {
1017 self.triple().2
1018 }
1019
1020 /// Returns a tuple with (data ptr, len, capacity)
1021 /// Useful to get all `SmallVec` properties with a single check of the
1022 /// current storage variant.
1023 #[inline]
1024 fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
1025 unsafe {
1026 if self.spilled() {
1027 let (ptr, len) = self.data.heap();
1028 (ptr, len, self.capacity)
1029 } else {
1030 (self.data.inline(), self.capacity, Self::inline_capacity())
1031 }
1032 }
1033 }
1034
1035 /// Returns a tuple with (data ptr, len ptr, capacity)
1036 #[inline]
1037 fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
1038 unsafe {
1039 if self.spilled() {
1040 let (ptr, len_ptr) = self.data.heap_mut();
1041 (ptr, len_ptr, self.capacity)
1042 } else {
1043 (
1044 self.data.inline_mut(),
1045 &mut self.capacity,
1046 Self::inline_capacity(),
1047 )
1048 }
1049 }
1050 }
1051
1052 /// Returns `true` if the data has spilled into a separate heap-allocated
1053 /// buffer.
1054 #[inline]
1055 pub fn spilled(&self) -> bool {
1056 self.capacity > Self::inline_capacity()
1057 }
1058
1059 /// Creates a draining iterator that removes the specified range in the
1060 /// vector and yields the removed items.
1061 ///
1062 /// Note 1: The element range is removed even if the iterator is only
1063 /// partially consumed or not consumed at all.
1064 ///
1065 /// Note 2: It is unspecified how many elements are removed from the vector
1066 /// if the `Drain` value is leaked.
1067 ///
1068 /// # Panics
1069 ///
1070 /// Panics if the starting point is greater than the end point or if
1071 /// the end point is greater than the length of the vector.
1072 pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
1073 where
1074 R: RangeBounds<usize>,
1075 {
1076 use core::ops::Bound::*;
1077
1078 let len = self.len();
1079 let start = match range.start_bound() {
1080 Included(&n) => n,
1081 Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
1082 Unbounded => 0,
1083 };
1084 let end = match range.end_bound() {
1085 Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
1086 Excluded(&n) => n,
1087 Unbounded => len,
1088 };
1089
1090 assert!(start <= end);
1091 assert!(end <= len);
1092
1093 unsafe {
1094 self.set_len(start);
1095
1096 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1097
1098 Drain {
1099 tail_start: end,
1100 tail_len: len - end,
1101 iter: range_slice.iter(),
1102 // Since self is a &mut, passing it to a function would invalidate the slice
1103 // iterator.
1104 vec: NonNull::new_unchecked(self as *mut _),
1105 }
1106 }
1107 }
1108
1109 #[cfg(feature = "drain_filter")]
1110 /// Creates an iterator which uses a closure to determine if an element
1111 /// should be removed.
1112 ///
1113 /// If the closure returns true, the element is removed and yielded. If the
1114 /// closure returns false, the element will remain in the vector and
1115 /// will not be yielded by the iterator.
1116 ///
1117 /// Using this method is equivalent to the following code:
1118 /// ```
1119 /// # use smallvec::SmallVec;
1120 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
1121 /// # let mut vec: SmallVec<[i32; 8]> = SmallVec::from_slice(&[1i32, 2, 3, 4, 5, 6]);
1122 /// let mut i = 0;
1123 /// while i < vec.len() {
1124 /// if some_predicate(&mut vec[i]) {
1125 /// let val = vec.remove(i);
1126 /// // your code here
1127 /// } else {
1128 /// i += 1;
1129 /// }
1130 /// }
1131 ///
1132 /// # assert_eq!(vec, SmallVec::<[i32; 8]>::from_slice(&[1i32, 4, 5]));
1133 /// ```
1134 /// ///
1135 /// But `drain_filter` is easier to use. `drain_filter` is also more
1136 /// efficient, because it can backshift the elements of the array in
1137 /// bulk.
1138 ///
1139 /// Note that `drain_filter` also lets you mutate every element in the
1140 /// filter closure, regardless of whether you choose to keep or remove
1141 /// it.
1142 ///
1143 /// # Examples
1144 ///
1145 /// Splitting an array into evens and odds, reusing the original allocation:
1146 ///
1147 /// ```
1148 /// # use smallvec::SmallVec;
1149 /// let mut numbers: SmallVec<[i32; 16]> =
1150 /// SmallVec::from_slice(&[1i32, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15]);
1151 ///
1152 /// let evens = numbers
1153 /// .drain_filter(|x| *x % 2 == 0)
1154 /// .collect::<SmallVec<[i32; 16]>>();
1155 /// let odds = numbers;
1156 ///
1157 /// assert_eq!(
1158 /// evens,
1159 /// SmallVec::<[i32; 16]>::from_slice(&[2i32, 4, 6, 8, 14])
1160 /// );
1161 /// assert_eq!(
1162 /// odds,
1163 /// SmallVec::<[i32; 16]>::from_slice(&[1i32, 3, 5, 9, 11, 13, 15])
1164 /// );
1165 /// ```
1166 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, A, F>
1167 where
1168 F: FnMut(&mut A::Item) -> bool,
1169 {
1170 let old_len = self.len();
1171
1172 // Guard against us getting leaked (leak amplification)
1173 unsafe {
1174 self.set_len(0);
1175 }
1176
1177 DrainFilter {
1178 vec: self,
1179 idx: 0,
1180 del: 0,
1181 old_len,
1182 pred: filter,
1183 panic_flag: false,
1184 }
1185 }
1186
1187 /// Append an item to the vector.
1188 #[inline]
1189 pub fn push(&mut self, value: A::Item) {
1190 unsafe {
1191 if self.spilled() {
1192 let (mut ptr, mut len_ptr) = self.data.heap_mut();
1193 if *len_ptr == self.capacity {
1194 self.reserve_one_unchecked();
1195 let (heap_ptr, heap_len) = self.data.heap_mut();
1196 ptr = heap_ptr;
1197 len_ptr = heap_len;
1198 }
1199 ptr::write(ptr.as_ptr().add(*len_ptr), value);
1200 *len_ptr += 1;
1201 } else {
1202 let mut ptr = self.data.inline_mut();
1203 let mut len_ptr = &mut self.capacity;
1204 if *len_ptr == Self::inline_capacity() {
1205 self.reserve_one_unchecked();
1206 let (heap_ptr, heap_len) = self.data.heap_mut();
1207 ptr = heap_ptr;
1208 len_ptr = heap_len;
1209 }
1210 ptr::write(ptr.as_ptr().add(*len_ptr), value);
1211 *len_ptr += 1;
1212 };
1213 }
1214 }
1215
1216 /// Remove an item from the end of the vector and return it, or None if
1217 /// empty.
1218 #[inline]
1219 pub fn pop(&mut self) -> Option<A::Item> {
1220 unsafe {
1221 let (ptr, len_ptr, _) = self.triple_mut();
1222 let ptr: *const _ = ptr.as_ptr();
1223 if *len_ptr == 0 {
1224 return None;
1225 }
1226 let last_index = *len_ptr - 1;
1227 *len_ptr = last_index;
1228 Some(ptr::read(ptr.add(last_index)))
1229 }
1230 }
1231
1232 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1233 ///
1234 /// # Example
1235 ///
1236 /// ```
1237 /// # use smallvec::{SmallVec, smallvec};
1238 /// let mut v0: SmallVec<[u8; 16]> = smallvec![1, 2, 3];
1239 /// let mut v1: SmallVec<[u8; 32]> = smallvec![4, 5, 6];
1240 /// v0.append(&mut v1);
1241 /// assert_eq!(*v0, [1, 2, 3, 4, 5, 6]);
1242 /// assert_eq!(*v1, []);
1243 /// ```
1244 pub fn append<B>(&mut self, other: &mut SmallVec<B>)
1245 where
1246 B: Array<Item = A::Item>,
1247 {
1248 self.extend(other.drain(..))
1249 }
1250
1251 /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
1252 ///
1253 /// Panics if `new_cap` is less than the vector's length
1254 /// or if the capacity computation overflows `usize`.
1255 pub fn grow(&mut self, new_cap: usize) {
1256 infallible(self.try_grow(new_cap))
1257 }
1258
1259 /// Re-allocate to set the capacity to `max(new_cap, inline_size())`.
1260 ///
1261 /// Panics if `new_cap` is less than the vector's length
1262 pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
1263 unsafe {
1264 let unspilled = !self.spilled();
1265 let (ptr, &mut len, cap) = self.triple_mut();
1266 assert!(new_cap >= len);
1267 if new_cap <= Self::inline_capacity() {
1268 if unspilled {
1269 return Ok(());
1270 }
1271 self.data = SmallVecData::empty();
1272 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1273 self.capacity = len;
1274 deallocate(ptr, cap);
1275 } else if new_cap != cap {
1276 let layout = layout_array::<A::Item>(new_cap)?;
1277 debug_assert!(layout.size() > 0);
1278 let new_alloc;
1279 if unspilled {
1280 new_alloc = NonNull::new(alloc::alloc::alloc(layout))
1281 .ok_or(CollectionAllocErr::AllocErr { layout })?
1282 .cast();
1283 ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
1284 } else {
1285 // This should never fail since the same succeeded
1286 // when previously allocating `ptr`.
1287 let old_layout = layout_array::<A::Item>(cap)?;
1288
1289 let new_ptr =
1290 alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
1291 new_alloc = NonNull::new(new_ptr)
1292 .ok_or(CollectionAllocErr::AllocErr { layout })?
1293 .cast();
1294 }
1295 self.data = SmallVecData::from_heap(new_alloc, len);
1296 self.capacity = new_cap;
1297 }
1298 Ok(())
1299 }
1300 }
1301
1302 /// Reserve capacity for `additional` more elements to be inserted.
1303 ///
1304 /// May reserve more space to avoid frequent reallocations.
1305 ///
1306 /// Panics if the capacity computation overflows `usize`.
1307 #[inline]
1308 pub fn reserve(&mut self, additional: usize) {
1309 infallible(self.try_reserve(additional))
1310 }
1311
1312 /// Internal method used to grow in push() and insert(), where we know
1313 /// already we have to grow.
1314 #[cold]
1315 fn reserve_one_unchecked(&mut self) {
1316 debug_assert_eq!(self.len(), self.capacity());
1317 let new_cap = self
1318 .len()
1319 .checked_add(1)
1320 .and_then(usize::checked_next_power_of_two)
1321 .expect("capacity overflow");
1322 infallible(self.try_grow(new_cap))
1323 }
1324
1325 /// Reserve capacity for `additional` more elements to be inserted.
1326 ///
1327 /// May reserve more space to avoid frequent reallocations.
1328 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1329 // prefer triple_mut() even if triple() would work so that the optimizer
1330 // removes duplicated calls to it from callers.
1331 let (_, &mut len, cap) = self.triple_mut();
1332 if cap - len >= additional {
1333 return Ok(());
1334 }
1335 let new_cap = len
1336 .checked_add(additional)
1337 .and_then(usize::checked_next_power_of_two)
1338 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1339 self.try_grow(new_cap)
1340 }
1341
1342 /// Reserve the minimum capacity for `additional` more elements to be
1343 /// inserted.
1344 ///
1345 /// Panics if the new capacity overflows `usize`.
1346 pub fn reserve_exact(&mut self, additional: usize) {
1347 infallible(self.try_reserve_exact(additional))
1348 }
1349
1350 /// Reserve the minimum capacity for `additional` more elements to be
1351 /// inserted.
1352 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1353 let (_, &mut len, cap) = self.triple_mut();
1354 if cap - len >= additional {
1355 return Ok(());
1356 }
1357 let new_cap = len
1358 .checked_add(additional)
1359 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1360 self.try_grow(new_cap)
1361 }
1362
1363 /// Shrink the capacity of the vector as much as possible.
1364 ///
1365 /// When possible, this will move data from an external heap buffer to the
1366 /// vector's inline storage.
1367 pub fn shrink_to_fit(&mut self) {
1368 if !self.spilled() {
1369 return;
1370 }
1371 let len = self.len();
1372 if self.inline_size() >= len {
1373 unsafe {
1374 let (ptr, len) = self.data.heap();
1375 self.data = SmallVecData::empty();
1376 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
1377 deallocate(ptr.0, self.capacity);
1378 self.capacity = len;
1379 }
1380 } else if self.capacity() > len {
1381 self.grow(len);
1382 }
1383 }
1384
1385 /// Shorten the vector, keeping the first `len` elements and dropping the
1386 /// rest.
1387 ///
1388 /// If `len` is greater than or equal to the vector's current length, this
1389 /// has no effect.
1390 ///
1391 /// This does not re-allocate. If you want the vector's capacity to shrink,
1392 /// call `shrink_to_fit` after truncating.
1393 pub fn truncate(&mut self, len: usize) {
1394 unsafe {
1395 let (ptr, len_ptr, _) = self.triple_mut();
1396 let ptr = ptr.as_ptr();
1397 while len < *len_ptr {
1398 let last_index = *len_ptr - 1;
1399 *len_ptr = last_index;
1400 ptr::drop_in_place(ptr.add(last_index));
1401 }
1402 }
1403 }
1404
1405 /// Extracts a slice containing the entire vector.
1406 ///
1407 /// Equivalent to `&s[..]`.
1408 pub fn as_slice(&self) -> &[A::Item] {
1409 self
1410 }
1411
1412 /// Extracts a mutable slice of the entire vector.
1413 ///
1414 /// Equivalent to `&mut s[..]`.
1415 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1416 self
1417 }
1418
1419 /// Remove the element at position `index`, replacing it with the last
1420 /// element.
1421 ///
1422 /// This does not preserve ordering, but is O(1).
1423 ///
1424 /// Panics if `index` is out of bounds.
1425 #[inline]
1426 pub fn swap_remove(&mut self, index: usize) -> A::Item {
1427 let len = self.len();
1428 self.swap(len - 1, index);
1429 self.pop()
1430 .unwrap_or_else(|| unsafe { unreachable_unchecked() })
1431 }
1432
1433 /// Remove all elements from the vector.
1434 #[inline]
1435 pub fn clear(&mut self) {
1436 self.truncate(0);
1437 }
1438
1439 /// Remove and return the element at position `index`, shifting all elements
1440 /// after it to the left.
1441 ///
1442 /// Panics if `index` is out of bounds.
1443 pub fn remove(&mut self, index: usize) -> A::Item {
1444 unsafe {
1445 let (ptr, len_ptr, _) = self.triple_mut();
1446 let len = *len_ptr;
1447 assert!(index < len);
1448 *len_ptr = len - 1;
1449 let ptr = ptr.as_ptr().add(index);
1450 let item = ptr::read(ptr);
1451 ptr::copy(ptr.add(1), ptr, len - index - 1);
1452 item
1453 }
1454 }
1455
1456 /// Insert an element at position `index`, shifting all elements after it to
1457 /// the right.
1458 ///
1459 /// Panics if `index > len`.
1460 pub fn insert(&mut self, index: usize, element: A::Item) {
1461 unsafe {
1462 let (mut ptr, mut len_ptr, cap) = self.triple_mut();
1463 if *len_ptr == cap {
1464 self.reserve_one_unchecked();
1465 let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
1466 ptr = heap_ptr;
1467 len_ptr = heap_len_ptr;
1468 }
1469 let mut ptr = ptr.as_ptr();
1470 let len = *len_ptr;
1471 if index > len {
1472 panic!("index exceeds length");
1473 }
1474 // SAFETY: add is UB if index > len, but we panicked first
1475 ptr = ptr.add(index);
1476 if index < len {
1477 // Shift element to the right of `index`.
1478 ptr::copy(ptr, ptr.add(1), len - index);
1479 }
1480 *len_ptr = len + 1;
1481 ptr::write(ptr, element);
1482 }
1483 }
1484
1485 /// Insert multiple elements at position `index`, shifting all following
1486 /// elements toward the back.
1487 pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
1488 let mut iter = iterable.into_iter();
1489 if index == self.len() {
1490 return self.extend(iter);
1491 }
1492
1493 let (lower_size_bound, _) = iter.size_hint();
1494 #[allow(deprecated)]
1495 {
1496 assert!(lower_size_bound <= core::isize::MAX as usize)
1497 } // Ensure offset is indexable
1498 assert!(index + lower_size_bound >= index); // Protect against overflow
1499
1500 let mut num_added = 0;
1501 let old_len = self.len();
1502 assert!(index <= old_len);
1503
1504 unsafe {
1505 // Reserve space for `lower_size_bound` elements.
1506 self.reserve(lower_size_bound);
1507 let start = self.as_mut_ptr();
1508 let ptr = start.add(index);
1509
1510 // Move the trailing elements.
1511 ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
1512
1513 // In case the iterator panics, don't double-drop the items we just
1514 // copied above.
1515 self.set_len(0);
1516 let mut guard = DropOnPanic {
1517 start,
1518 skip: index..(index + lower_size_bound),
1519 len: old_len + lower_size_bound,
1520 };
1521
1522 // The set_len above invalidates the previous pointers, so we must
1523 // re-create them.
1524 let start = self.as_mut_ptr();
1525 let ptr = start.add(index);
1526
1527 while num_added < lower_size_bound {
1528 let element = match iter.next() {
1529 Some(x) => x,
1530 None => break,
1531 };
1532 let cur = ptr.add(num_added);
1533 ptr::write(cur, element);
1534 guard.skip.start += 1;
1535 num_added += 1;
1536 }
1537
1538 if num_added < lower_size_bound {
1539 // Iterator provided fewer elements than the hint. Move the tail
1540 // backward.
1541 ptr::copy(
1542 ptr.add(lower_size_bound),
1543 ptr.add(num_added),
1544 old_len - index,
1545 );
1546 }
1547 // There are no more duplicate or uninitialized slots, so the guard
1548 // is not needed.
1549 self.set_len(old_len + num_added);
1550 mem::forget(guard);
1551 }
1552
1553 // Insert any remaining elements one-by-one.
1554 for element in iter {
1555 self.insert(index + num_added, element);
1556 num_added += 1;
1557 }
1558
1559 struct DropOnPanic<T> {
1560 start: *mut T,
1561 skip: Range<usize>, // Space we copied-out-of, but haven't written-to yet.
1562 len: usize,
1563 }
1564
1565 impl<T> Drop for DropOnPanic<T> {
1566 fn drop(&mut self) {
1567 for i in 0..self.len {
1568 if !self.skip.contains(&i) {
1569 unsafe {
1570 ptr::drop_in_place(self.start.add(i));
1571 }
1572 }
1573 }
1574 }
1575 }
1576 }
1577
1578 /// Convert a `SmallVec` to a `Vec`, without reallocating if the `SmallVec`
1579 /// has already spilled onto the heap.
1580 pub fn into_vec(mut self) -> Vec<A::Item> {
1581 if self.spilled() {
1582 unsafe {
1583 let (ptr, &mut len) = self.data.heap_mut();
1584 let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
1585 mem::forget(self);
1586 v
1587 }
1588 } else {
1589 self.into_iter().collect()
1590 }
1591 }
1592
1593 /// Converts a `SmallVec` into a `Box<[T]>` without reallocating if the
1594 /// `SmallVec` has already spilled onto the heap.
1595 ///
1596 /// Note that this will drop any excess capacity.
1597 pub fn into_boxed_slice(self) -> Box<[A::Item]> {
1598 self.into_vec().into_boxed_slice()
1599 }
1600
1601 /// Convert the `SmallVec` into an `A` if possible. Otherwise return
1602 /// `Err(Self)`.
1603 ///
1604 /// This method returns `Err(Self)` if the `SmallVec` is too short (and the
1605 /// `A` contains uninitialized elements), or if the `SmallVec` is too
1606 /// long (and all the elements were spilled to the heap).
1607 pub fn into_inner(self) -> Result<A, Self> {
1608 if self.spilled() || self.len() != A::size() {
1609 // Note: A::size, not Self::inline_capacity
1610 Err(self)
1611 } else {
1612 unsafe {
1613 let data = ptr::read(&self.data);
1614 mem::forget(self);
1615 Ok(data.into_inline().assume_init())
1616 }
1617 }
1618 }
1619
1620 /// Retains only the elements specified by the predicate.
1621 ///
1622 /// In other words, remove all elements `e` such that `f(&e)` returns
1623 /// `false`. This method operates in place and preserves the order of
1624 /// the retained elements.
1625 pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1626 let mut del = 0;
1627 let len = self.len();
1628 for i in 0..len {
1629 if !f(&mut self[i]) {
1630 del += 1;
1631 } else if del > 0 {
1632 self.swap(i - del, i);
1633 }
1634 }
1635 self.truncate(len - del);
1636 }
1637
1638 /// Retains only the elements specified by the predicate.
1639 ///
1640 /// This method is identical in behaviour to [`SmallVec::retain`]; it is
1641 /// included only to maintain api-compatibility with `std::Vec`, where
1642 /// the methods are separate for historical reasons.
1643 pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1644 self.retain(f)
1645 }
1646
1647 /// Removes consecutive duplicate elements.
1648 pub fn dedup(&mut self)
1649 where
1650 A::Item: PartialEq<A::Item>,
1651 {
1652 self.dedup_by(|a, b| a == b);
1653 }
1654
1655 /// Removes consecutive duplicate elements using the given equality
1656 /// relation.
1657 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1658 where
1659 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1660 {
1661 // See the implementation of Vec::dedup_by in the
1662 // standard library for an explanation of this algorithm.
1663 let len = self.len();
1664 if len <= 1 {
1665 return;
1666 }
1667
1668 let ptr = self.as_mut_ptr();
1669 let mut w: usize = 1;
1670
1671 unsafe {
1672 for r in 1..len {
1673 let p_r = ptr.add(r);
1674 let p_wm1 = ptr.add(w - 1);
1675 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1676 if r != w {
1677 let p_w = p_wm1.add(1);
1678 mem::swap(&mut *p_r, &mut *p_w);
1679 }
1680 w += 1;
1681 }
1682 }
1683 }
1684
1685 self.truncate(w);
1686 }
1687
1688 /// Removes consecutive elements that map to the same key.
1689 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1690 where
1691 F: FnMut(&mut A::Item) -> K,
1692 K: PartialEq<K>,
1693 {
1694 self.dedup_by(|a, b| key(a) == key(b));
1695 }
1696
1697 /// Resizes the `SmallVec` in-place so that `len` is equal to `new_len`.
1698 ///
1699 /// If `new_len` is greater than `len`, the `SmallVec` is extended by the
1700 /// difference, with each additional slot filled with the result of
1701 /// calling the closure `f`. The return values from `f` will end up in
1702 /// the `SmallVec` in the order they have been generated.
1703 ///
1704 /// If `new_len` is less than `len`, the `SmallVec` is simply truncated.
1705 ///
1706 /// This method uses a closure to create new values on every push. If you'd
1707 /// rather `Clone` a given value, use `resize`. If you want to use the
1708 /// `Default` trait to generate values, you can pass
1709 /// `Default::default()` as the second argument.
1710 ///
1711 /// Added for `std::vec::Vec` compatibility (added in Rust 1.33.0)
1712 ///
1713 /// ```
1714 /// # use smallvec::{smallvec, SmallVec};
1715 /// let mut vec: SmallVec<[_; 4]> = smallvec![1, 2, 3];
1716 /// vec.resize_with(5, Default::default);
1717 /// assert_eq!(&*vec, &[1, 2, 3, 0, 0]);
1718 ///
1719 /// let mut vec: SmallVec<[_; 4]> = smallvec![];
1720 /// let mut p = 1;
1721 /// vec.resize_with(4, || {
1722 /// p *= 2;
1723 /// p
1724 /// });
1725 /// assert_eq!(&*vec, &[2, 4, 8, 16]);
1726 /// ```
1727 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1728 where
1729 F: FnMut() -> A::Item,
1730 {
1731 let old_len = self.len();
1732 if old_len < new_len {
1733 let mut f = f;
1734 let additional = new_len - old_len;
1735 self.reserve(additional);
1736 for _ in 0..additional {
1737 self.push(f());
1738 }
1739 } else if old_len > new_len {
1740 self.truncate(new_len);
1741 }
1742 }
1743
1744 /// Creates a `SmallVec` directly from the raw components of another
1745 /// `SmallVec`.
1746 ///
1747 /// # Safety
1748 ///
1749 /// This is highly unsafe, due to the number of invariants that aren't
1750 /// checked:
1751 ///
1752 /// * `ptr` needs to have been previously allocated via `SmallVec` for its
1753 /// spilled storage (at least, it's highly likely to be incorrect if it
1754 /// wasn't).
1755 /// * `ptr`'s `A::Item` type needs to be the same size and alignment that it
1756 /// was allocated with
1757 /// * `length` needs to be less than or equal to `capacity`.
1758 /// * `capacity` needs to be the capacity that the pointer was allocated
1759 /// with.
1760 ///
1761 /// Violating these may cause problems like corrupting the allocator's
1762 /// internal data structures.
1763 ///
1764 /// Additionally, `capacity` must be greater than the amount of inline
1765 /// storage `A` has; that is, the new `SmallVec` must need to spill over
1766 /// into heap allocated storage. This condition is asserted against.
1767 ///
1768 /// The ownership of `ptr` is effectively transferred to the
1769 /// `SmallVec` which may then deallocate, reallocate or change the
1770 /// contents of memory pointed to by the pointer at will. Ensure
1771 /// that nothing else uses the pointer after calling this
1772 /// function.
1773 ///
1774 /// # Examples
1775 ///
1776 /// ```
1777 /// # use smallvec::{smallvec, SmallVec};
1778 /// use std::mem;
1779 /// use std::ptr;
1780 ///
1781 /// fn main() {
1782 /// let mut v: SmallVec<[_; 1]> = smallvec![1, 2, 3];
1783 ///
1784 /// // Pull out the important parts of `v`.
1785 /// let p = v.as_mut_ptr();
1786 /// let len = v.len();
1787 /// let cap = v.capacity();
1788 /// let spilled = v.spilled();
1789 ///
1790 /// unsafe {
1791 /// // Forget all about `v`. The heap allocation that stored the
1792 /// // three values won't be deallocated.
1793 /// mem::forget(v);
1794 ///
1795 /// // Overwrite memory with [4, 5, 6].
1796 /// //
1797 /// // This is only safe if `spilled` is true! Otherwise, we are
1798 /// // writing into the old `SmallVec`'s inline storage on the
1799 /// // stack.
1800 /// assert!(spilled);
1801 /// for i in 0..len {
1802 /// ptr::write(p.add(i), 4 + i);
1803 /// }
1804 ///
1805 /// // Put everything back together into a SmallVec with a different
1806 /// // amount of inline storage, but which is still less than `cap`.
1807 /// let rebuilt = SmallVec::<[_; 2]>::from_raw_parts(p, len, cap);
1808 /// assert_eq!(&*rebuilt, &[4, 5, 6]);
1809 /// }
1810 /// }
1811 #[inline]
1812 pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1813 // SAFETY: We require caller to provide same ptr as we alloc
1814 // and we never alloc null pointer.
1815 let ptr = unsafe {
1816 debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1817 NonNull::new_unchecked(ptr)
1818 };
1819 assert!(capacity > Self::inline_capacity());
1820 SmallVec {
1821 capacity,
1822 data: SmallVecData::from_heap(ptr, length),
1823 }
1824 }
1825
1826 /// Returns a raw pointer to the vector's buffer.
1827 pub fn as_ptr(&self) -> *const A::Item {
1828 // We shadow the slice method of the same name to avoid going through
1829 // `deref`, which creates an intermediate reference that may place
1830 // additional safety constraints on the contents of the slice.
1831 self.triple().0.as_ptr()
1832 }
1833
1834 /// Returns a raw mutable pointer to the vector's buffer.
1835 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1836 // We shadow the slice method of the same name to avoid going through
1837 // `deref_mut`, which creates an intermediate reference that may place
1838 // additional safety constraints on the contents of the slice.
1839 self.triple_mut().0.as_ptr()
1840 }
1841}
1842
1843impl<A: Array> SmallVec<A>
1844where
1845 A::Item: Copy,
1846{
1847 /// Copy the elements from a slice into a new `SmallVec`.
1848 ///
1849 /// For slices of `Copy` types, this is more efficient than
1850 /// `SmallVec::from(slice)`.
1851 pub fn from_slice(slice: &[A::Item]) -> Self {
1852 let len = slice.len();
1853 if len <= Self::inline_capacity() {
1854 SmallVec {
1855 capacity: len,
1856 data: SmallVecData::from_inline(unsafe {
1857 let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1858 ptr::copy_nonoverlapping(
1859 slice.as_ptr(),
1860 data.as_mut_ptr() as *mut A::Item,
1861 len,
1862 );
1863 data
1864 }),
1865 }
1866 } else {
1867 let mut b = slice.to_vec();
1868 let cap = b.capacity();
1869 let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1870 mem::forget(b);
1871 SmallVec {
1872 capacity: cap,
1873 data: SmallVecData::from_heap(ptr, len),
1874 }
1875 }
1876 }
1877
1878 /// Copy elements from a slice into the vector at position `index`, shifting
1879 /// any following elements toward the back.
1880 ///
1881 /// For slices of `Copy` types, this is more efficient than `insert`.
1882 #[inline]
1883 pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1884 self.reserve(slice.len());
1885
1886 let len = self.len();
1887 assert!(index <= len);
1888
1889 unsafe {
1890 let slice_ptr = slice.as_ptr();
1891 let ptr = self.as_mut_ptr().add(index);
1892 ptr::copy(ptr, ptr.add(slice.len()), len - index);
1893 ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1894 self.set_len(len + slice.len());
1895 }
1896 }
1897
1898 /// Copy elements from a slice and append them to the vector.
1899 ///
1900 /// For slices of `Copy` types, this is more efficient than `extend`.
1901 #[inline]
1902 pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1903 let len = self.len();
1904 self.insert_from_slice(len, slice);
1905 }
1906}
1907
1908impl<A: Array> SmallVec<A>
1909where
1910 A::Item: Clone,
1911{
1912 /// Resizes the vector so that its length is equal to `len`.
1913 ///
1914 /// If `len` is less than the current length, the vector simply truncated.
1915 ///
1916 /// If `len` is greater than the current length, `value` is appended to the
1917 /// vector until its length equals `len`.
1918 pub fn resize(&mut self, len: usize, value: A::Item) {
1919 let old_len = self.len();
1920
1921 if len > old_len {
1922 self.extend(repeat(value).take(len - old_len));
1923 } else {
1924 self.truncate(len);
1925 }
1926 }
1927
1928 /// Creates a `SmallVec` with `n` copies of `elem`.
1929 /// ```
1930 /// use smallvec::SmallVec;
1931 ///
1932 /// let v = SmallVec::<[char; 128]>::from_elem('d', 2);
1933 /// assert_eq!(v, SmallVec::from_buf(['d', 'd']));
1934 /// ```
1935 pub fn from_elem(elem: A::Item, n: usize) -> Self {
1936 if n > Self::inline_capacity() {
1937 vec![elem; n].into()
1938 } else {
1939 let mut v = SmallVec::<A>::new();
1940 unsafe {
1941 let (ptr, len_ptr, _) = v.triple_mut();
1942 let ptr = ptr.as_ptr();
1943 let mut local_len = SetLenOnDrop::new(len_ptr);
1944
1945 for i in 0..n {
1946 ::core::ptr::write(ptr.add(i), elem.clone());
1947 local_len.increment_len(1);
1948 }
1949 }
1950 v
1951 }
1952 }
1953}
1954
1955impl<A: Array> ops::Deref for SmallVec<A> {
1956 type Target = [A::Item];
1957 #[inline]
1958 fn deref(&self) -> &[A::Item] {
1959 unsafe {
1960 let (ptr, len, _) = self.triple();
1961 slice::from_raw_parts(ptr.as_ptr(), len)
1962 }
1963 }
1964}
1965
1966impl<A: Array> ops::DerefMut for SmallVec<A> {
1967 #[inline]
1968 fn deref_mut(&mut self) -> &mut [A::Item] {
1969 unsafe {
1970 let (ptr, &mut len, _) = self.triple_mut();
1971 slice::from_raw_parts_mut(ptr.as_ptr(), len)
1972 }
1973 }
1974}
1975
1976impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1977 #[inline]
1978 fn as_ref(&self) -> &[A::Item] {
1979 self
1980 }
1981}
1982
1983impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1984 #[inline]
1985 fn as_mut(&mut self) -> &mut [A::Item] {
1986 self
1987 }
1988}
1989
1990impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1991 #[inline]
1992 fn borrow(&self) -> &[A::Item] {
1993 self
1994 }
1995}
1996
1997impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1998 #[inline]
1999 fn borrow_mut(&mut self) -> &mut [A::Item] {
2000 self
2001 }
2002}
2003
2004#[cfg(feature = "write")]
2005#[cfg_attr(docsrs, doc(cfg(feature = "write")))]
2006impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
2007 #[inline]
2008 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2009 self.extend_from_slice(buf);
2010 Ok(buf.len())
2011 }
2012
2013 #[inline]
2014 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
2015 self.extend_from_slice(buf);
2016 Ok(())
2017 }
2018
2019 #[inline]
2020 fn flush(&mut self) -> io::Result<()> {
2021 Ok(())
2022 }
2023}
2024
2025#[cfg(feature = "serde")]
2026#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2027impl<A: Array> Serialize for SmallVec<A>
2028where
2029 A::Item: Serialize,
2030{
2031 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2032 let mut state = serializer.serialize_seq(Some(self.len()))?;
2033 for item in self {
2034 state.serialize_element(&item)?;
2035 }
2036 state.end()
2037 }
2038}
2039
2040#[cfg(feature = "serde")]
2041#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2042impl<'de, A: Array> Deserialize<'de> for SmallVec<A>
2043where
2044 A::Item: Deserialize<'de>,
2045{
2046 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2047 deserializer.deserialize_seq(SmallVecVisitor {
2048 phantom: PhantomData,
2049 })
2050 }
2051}
2052
2053#[cfg(feature = "serde")]
2054struct SmallVecVisitor<A> {
2055 phantom: PhantomData<A>,
2056}
2057
2058#[cfg(feature = "serde")]
2059impl<'de, A: Array> Visitor<'de> for SmallVecVisitor<A>
2060where
2061 A::Item: Deserialize<'de>,
2062{
2063 type Value = SmallVec<A>;
2064
2065 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2066 formatter.write_str("a sequence")
2067 }
2068
2069 fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
2070 where
2071 B: SeqAccess<'de>,
2072 {
2073 use serde::de::Error;
2074 let len = seq.size_hint().unwrap_or(0);
2075 let mut values = SmallVec::new();
2076 values.try_reserve(len).map_err(B::Error::custom)?;
2077
2078 while let Some(value) = seq.next_element()? {
2079 values.push(value);
2080 }
2081
2082 Ok(values)
2083 }
2084}
2085
2086#[cfg(feature = "malloc_size_of")]
2087impl<A: Array> MallocShallowSizeOf for SmallVec<A> {
2088 fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2089 if self.spilled() {
2090 unsafe { ops.malloc_size_of(self.as_ptr()) }
2091 } else {
2092 0
2093 }
2094 }
2095}
2096
2097#[cfg(feature = "malloc_size_of")]
2098impl<A> MallocSizeOf for SmallVec<A>
2099where
2100 A: Array,
2101 A::Item: MallocSizeOf,
2102{
2103 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2104 let mut n = self.shallow_size_of(ops);
2105 for elem in self.iter() {
2106 n += elem.size_of(ops);
2107 }
2108 n
2109 }
2110}
2111
2112#[cfg(feature = "specialization")]
2113trait SpecFrom<A: Array, S> {
2114 fn spec_from(slice: S) -> SmallVec<A>;
2115}
2116
2117#[cfg(feature = "specialization")]
2118mod specialization;
2119
2120#[cfg(feature = "arbitrary")]
2121mod arbitrary;
2122
2123#[cfg(feature = "specialization")]
2124impl<'a, A: Array> SpecFrom<A, &'a [A::Item]> for SmallVec<A>
2125where
2126 A::Item: Copy,
2127{
2128 #[inline]
2129 fn spec_from(slice: &'a [A::Item]) -> SmallVec<A> {
2130 SmallVec::from_slice(slice)
2131 }
2132}
2133
2134impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
2135where
2136 A::Item: Clone,
2137{
2138 #[cfg(not(feature = "specialization"))]
2139 #[inline]
2140 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2141 slice.iter().cloned().collect()
2142 }
2143
2144 #[cfg(feature = "specialization")]
2145 #[inline]
2146 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
2147 SmallVec::spec_from(slice)
2148 }
2149}
2150
2151impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
2152 #[inline]
2153 fn from(vec: Vec<A::Item>) -> SmallVec<A> {
2154 SmallVec::from_vec(vec)
2155 }
2156}
2157
2158impl<A: Array> From<A> for SmallVec<A> {
2159 #[inline]
2160 fn from(array: A) -> SmallVec<A> {
2161 SmallVec::from_buf(array)
2162 }
2163}
2164
2165impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
2166 type Output = I::Output;
2167
2168 fn index(&self, index: I) -> &I::Output {
2169 &(**self)[index]
2170 }
2171}
2172
2173impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
2174 fn index_mut(&mut self, index: I) -> &mut I::Output {
2175 &mut (&mut **self)[index]
2176 }
2177}
2178
2179#[allow(deprecated)]
2180impl<A: Array> ExtendFromSlice<A::Item> for SmallVec<A>
2181where
2182 A::Item: Copy,
2183{
2184 fn extend_from_slice(&mut self, other: &[A::Item]) {
2185 SmallVec::extend_from_slice(self, other)
2186 }
2187}
2188
2189impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
2190 #[inline]
2191 fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
2192 let mut v = SmallVec::new();
2193 v.extend(iterable);
2194 v
2195 }
2196}
2197
2198impl<A: Array> Extend<A::Item> for SmallVec<A> {
2199 fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
2200 let mut iter = iterable.into_iter();
2201 let (lower_size_bound, _) = iter.size_hint();
2202 self.reserve(lower_size_bound);
2203
2204 unsafe {
2205 let (ptr, len_ptr, cap) = self.triple_mut();
2206 let ptr = ptr.as_ptr();
2207 let mut len = SetLenOnDrop::new(len_ptr);
2208 while len.get() < cap {
2209 if let Some(out) = iter.next() {
2210 ptr::write(ptr.add(len.get()), out);
2211 len.increment_len(1);
2212 } else {
2213 return;
2214 }
2215 }
2216 }
2217
2218 for elem in iter {
2219 self.push(elem);
2220 }
2221 }
2222}
2223
2224impl<A: Array> fmt::Debug for SmallVec<A>
2225where
2226 A::Item: fmt::Debug,
2227{
2228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2229 f.debug_list().entries(self.iter()).finish()
2230 }
2231}
2232
2233impl<A: Array> Default for SmallVec<A> {
2234 #[inline]
2235 fn default() -> SmallVec<A> {
2236 SmallVec::new()
2237 }
2238}
2239
2240#[cfg(feature = "may_dangle")]
2241unsafe impl<#[may_dangle] A: Array> Drop for SmallVec<A> {
2242 fn drop(&mut self) {
2243 unsafe {
2244 if self.spilled() {
2245 let (ptr, &mut len) = self.data.heap_mut();
2246 Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
2247 } else {
2248 ptr::drop_in_place(&mut self[..]);
2249 }
2250 }
2251 }
2252}
2253
2254#[cfg(not(feature = "may_dangle"))]
2255impl<A: Array> Drop for SmallVec<A> {
2256 fn drop(&mut self) {
2257 unsafe {
2258 if self.spilled() {
2259 let (ptr, &mut len) = self.data.heap_mut();
2260 drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
2261 } else {
2262 ptr::drop_in_place(&mut self[..]);
2263 }
2264 }
2265 }
2266}
2267
2268impl<A: Array> Clone for SmallVec<A>
2269where
2270 A::Item: Clone,
2271{
2272 #[inline]
2273 fn clone(&self) -> SmallVec<A> {
2274 SmallVec::from(self.as_slice())
2275 }
2276
2277 fn clone_from(&mut self, source: &Self) {
2278 // Inspired from `impl Clone for Vec`.
2279
2280 // drop anything that will not be overwritten
2281 self.truncate(source.len());
2282
2283 // self.len <= other.len due to the truncate above, so the
2284 // slices here are always in-bounds.
2285 let (init, tail) = source.split_at(self.len());
2286
2287 // reuse the contained values' allocations/resources.
2288 self.clone_from_slice(init);
2289 self.extend(tail.iter().cloned());
2290 }
2291}
2292
2293impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
2294where
2295 A::Item: PartialEq<B::Item>,
2296{
2297 #[inline]
2298 fn eq(&self, other: &SmallVec<B>) -> bool {
2299 self[..] == other[..]
2300 }
2301}
2302
2303impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
2304
2305impl<A: Array> PartialOrd for SmallVec<A>
2306where
2307 A::Item: PartialOrd,
2308{
2309 #[inline]
2310 fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
2311 PartialOrd::partial_cmp(&**self, &**other)
2312 }
2313}
2314
2315impl<A: Array> Ord for SmallVec<A>
2316where
2317 A::Item: Ord,
2318{
2319 #[inline]
2320 fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
2321 Ord::cmp(&**self, &**other)
2322 }
2323}
2324
2325impl<A: Array> Hash for SmallVec<A>
2326where
2327 A::Item: Hash,
2328{
2329 fn hash<H: Hasher>(&self, state: &mut H) {
2330 (**self).hash(state)
2331 }
2332}
2333
2334unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
2335
2336/// An iterator that consumes a `SmallVec` and yields its items by value.
2337///
2338/// Returned from [`SmallVec::into_iter`][1].
2339///
2340/// [1]: struct.SmallVec.html#method.into_iter
2341pub struct IntoIter<A: Array> {
2342 data: SmallVec<A>,
2343 current: usize,
2344 end: usize,
2345}
2346
2347impl<A: Array> fmt::Debug for IntoIter<A>
2348where
2349 A::Item: fmt::Debug,
2350{
2351 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2352 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2353 }
2354}
2355
2356impl<A: Array + Clone> Clone for IntoIter<A>
2357where
2358 A::Item: Clone,
2359{
2360 fn clone(&self) -> IntoIter<A> {
2361 SmallVec::from(self.as_slice()).into_iter()
2362 }
2363}
2364
2365impl<A: Array> Drop for IntoIter<A> {
2366 fn drop(&mut self) {
2367 for _ in self {}
2368 }
2369}
2370
2371impl<A: Array> Iterator for IntoIter<A> {
2372 type Item = A::Item;
2373
2374 #[inline]
2375 fn next(&mut self) -> Option<A::Item> {
2376 if self.current == self.end {
2377 None
2378 } else {
2379 unsafe {
2380 let current = self.current;
2381 self.current += 1;
2382 Some(ptr::read(self.data.as_ptr().add(current)))
2383 }
2384 }
2385 }
2386
2387 #[inline]
2388 fn size_hint(&self) -> (usize, Option<usize>) {
2389 let size = self.end - self.current;
2390 (size, Some(size))
2391 }
2392}
2393
2394impl<A: Array> DoubleEndedIterator for IntoIter<A> {
2395 #[inline]
2396 fn next_back(&mut self) -> Option<A::Item> {
2397 if self.current == self.end {
2398 None
2399 } else {
2400 unsafe {
2401 self.end -= 1;
2402 Some(ptr::read(self.data.as_ptr().add(self.end)))
2403 }
2404 }
2405 }
2406}
2407
2408impl<A: Array> ExactSizeIterator for IntoIter<A> {}
2409impl<A: Array> FusedIterator for IntoIter<A> {}
2410
2411impl<A: Array> IntoIter<A> {
2412 /// Returns the remaining items of this iterator as a slice.
2413 pub fn as_slice(&self) -> &[A::Item] {
2414 let len = self.end - self.current;
2415 unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
2416 }
2417
2418 /// Returns the remaining items of this iterator as a mutable slice.
2419 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
2420 let len = self.end - self.current;
2421 unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
2422 }
2423}
2424
2425impl<A: Array> IntoIterator for SmallVec<A> {
2426 type IntoIter = IntoIter<A>;
2427 type Item = A::Item;
2428 fn into_iter(mut self) -> Self::IntoIter {
2429 unsafe {
2430 // Set SmallVec len to zero as `IntoIter` drop handles dropping of
2431 // the elements
2432 let len = self.len();
2433 self.set_len(0);
2434 IntoIter {
2435 data: self,
2436 current: 0,
2437 end: len,
2438 }
2439 }
2440 }
2441}
2442
2443impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
2444 type IntoIter = slice::Iter<'a, A::Item>;
2445 type Item = &'a A::Item;
2446 fn into_iter(self) -> Self::IntoIter {
2447 self.iter()
2448 }
2449}
2450
2451impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
2452 type IntoIter = slice::IterMut<'a, A::Item>;
2453 type Item = &'a mut A::Item;
2454 fn into_iter(self) -> Self::IntoIter {
2455 self.iter_mut()
2456 }
2457}
2458
2459/// Types that can be used as the backing store for a [`SmallVec`].
2460pub unsafe trait Array {
2461 /// The type of the array's elements.
2462 type Item;
2463 /// Returns the number of items the array can hold.
2464 fn size() -> usize;
2465}
2466
2467/// Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
2468///
2469/// Copied from <https://github.com/rust-lang/rust/pull/36355>
2470struct SetLenOnDrop<'a> {
2471 len: &'a mut usize,
2472 local_len: usize,
2473}
2474
2475impl<'a> SetLenOnDrop<'a> {
2476 #[inline]
2477 fn new(len: &'a mut usize) -> Self {
2478 SetLenOnDrop {
2479 local_len: *len,
2480 len,
2481 }
2482 }
2483
2484 #[inline]
2485 fn get(&self) -> usize {
2486 self.local_len
2487 }
2488
2489 #[inline]
2490 fn increment_len(&mut self, increment: usize) {
2491 self.local_len += increment;
2492 }
2493}
2494
2495impl<'a> Drop for SetLenOnDrop<'a> {
2496 #[inline]
2497 fn drop(&mut self) {
2498 *self.len = self.local_len;
2499 }
2500}
2501
2502#[cfg(feature = "const_new")]
2503impl<T, const N: usize> SmallVec<[T; N]> {
2504 /// Construct an empty vector.
2505 ///
2506 /// This is a `const` version of [`SmallVec::new`] that is enabled by the
2507 /// feature `const_new`, with the limitation that it only works for arrays.
2508 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2509 #[inline]
2510 pub const fn new_const() -> Self {
2511 SmallVec {
2512 capacity: 0,
2513 data: SmallVecData::from_const(MaybeUninit::uninit()),
2514 }
2515 }
2516
2517 /// The array passed as an argument is moved to be an inline version of
2518 /// `SmallVec`.
2519 ///
2520 /// This is a `const` version of [`SmallVec::from_buf`] that is enabled by
2521 /// the feature `const_new`, with the limitation that it only works for
2522 /// arrays.
2523 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2524 #[inline]
2525 pub const fn from_const(items: [T; N]) -> Self {
2526 SmallVec {
2527 capacity: N,
2528 data: SmallVecData::from_const(MaybeUninit::new(items)),
2529 }
2530 }
2531
2532 /// Constructs a new `SmallVec` on the stack from an array without
2533 /// copying elements. Also sets the length. The user is responsible
2534 /// for ensuring that `len <= N`.
2535 ///
2536 /// This is a `const` version of [`SmallVec::from_buf_and_len_unchecked`]
2537 /// that is enabled by the feature `const_new`, with the limitation that it
2538 /// only works for arrays.
2539 #[cfg_attr(docsrs, doc(cfg(feature = "const_new")))]
2540 #[inline]
2541 pub const unsafe fn from_const_with_len_unchecked(items: [T; N], len: usize) -> Self {
2542 SmallVec {
2543 capacity: len,
2544 data: SmallVecData::from_const(MaybeUninit::new(items)),
2545 }
2546 }
2547}
2548
2549#[cfg(feature = "const_generics")]
2550#[cfg_attr(docsrs, doc(cfg(feature = "const_generics")))]
2551unsafe impl<T, const N: usize> Array for [T; N] {
2552 type Item = T;
2553 #[inline]
2554 fn size() -> usize {
2555 N
2556 }
2557}
2558
2559#[cfg(not(feature = "const_generics"))]
2560macro_rules! impl_array(
2561 ($($size:expr),+) => {
2562 $(
2563 unsafe impl<T> Array for [T; $size] {
2564 type Item = T;
2565 #[inline]
2566 fn size() -> usize { $size }
2567 }
2568 )+
2569 }
2570);
2571
2572#[cfg(not(feature = "const_generics"))]
2573impl_array!(
2574 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25,
2575 26, 27, 28, 29, 30, 31, 32, 36, 0x40, 0x60, 0x80, 0x100, 0x200, 0x400, 0x600, 0x800, 0x1000,
2576 0x2000, 0x4000, 0x6000, 0x8000, 0x10000, 0x20000, 0x40000, 0x60000, 0x80000, 0x10_0000
2577);
2578
2579/// Convenience trait for constructing a `SmallVec`
2580pub trait ToSmallVec<A: Array> {
2581 /// Construct a new `SmallVec` from a slice.
2582 fn to_smallvec(&self) -> SmallVec<A>;
2583}
2584
2585impl<A: Array> ToSmallVec<A> for [A::Item]
2586where
2587 A::Item: Copy,
2588{
2589 #[inline]
2590 fn to_smallvec(&self) -> SmallVec<A> {
2591 SmallVec::from_slice(self)
2592 }
2593}
2594
2595// Immutable counterpart for `NonNull<T>`.
2596#[repr(transparent)]
2597struct ConstNonNull<T>(NonNull<T>);
2598
2599impl<T> ConstNonNull<T> {
2600 #[inline]
2601 fn new(ptr: *const T) -> Option<Self> {
2602 NonNull::new(ptr as *mut T).map(Self)
2603 }
2604 #[inline]
2605 fn as_ptr(self) -> *const T {
2606 self.0.as_ptr()
2607 }
2608}
2609
2610impl<T> Clone for ConstNonNull<T> {
2611 #[inline]
2612 fn clone(&self) -> Self {
2613 *self
2614 }
2615}
2616
2617impl<T> Copy for ConstNonNull<T> {}
2618
2619#[cfg(feature = "impl_bincode")]
2620use bincode::{
2621 de::{read::Reader, BorrowDecoder, Decode, Decoder},
2622 enc::{write::Writer, Encode, Encoder},
2623 error::{DecodeError, EncodeError},
2624 BorrowDecode,
2625};
2626
2627#[cfg(feature = "impl_bincode")]
2628impl<A, Context> Decode<Context> for SmallVec<A>
2629where
2630 A: Array,
2631 A::Item: Decode<Context>,
2632{
2633 fn decode<D: Decoder<Context = Context>>(decoder: &mut D) -> Result<Self, DecodeError> {
2634 use core::convert::TryInto;
2635 let len = u64::decode(decoder)?;
2636 let len = len
2637 .try_into()
2638 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2639 decoder.claim_container_read::<A::Item>(len)?;
2640
2641 let mut vec = SmallVec::with_capacity(len);
2642 if unty::type_equal::<A::Item, u8>() {
2643 // Initialize the smallvec's buffer. Note that we need to do this
2644 // through the raw pointer as we cannot name the type
2645 // [u8; N] even though A::Item is u8.
2646 let ptr = vec.as_mut_ptr();
2647 // SAFETY: A::Item is u8 and the smallvec has been allocated with
2648 // enough capacity
2649 unsafe {
2650 core::ptr::write_bytes(ptr, 0, len);
2651 vec.set_len(len);
2652 }
2653 // Read the data into the smallvec's buffer.
2654 let slice = vec.as_mut_slice();
2655 // SAFETY: A::Item is u8
2656 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2657 decoder.reader().read(slice)?;
2658 } else {
2659 for _ in 0..len {
2660 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2661 vec.push(A::Item::decode(decoder)?);
2662 }
2663 }
2664 Ok(vec)
2665 }
2666}
2667
2668#[cfg(feature = "impl_bincode")]
2669impl<'de, A, Context> BorrowDecode<'de, Context> for SmallVec<A>
2670where
2671 A: Array,
2672 A::Item: BorrowDecode<'de, Context>,
2673{
2674 fn borrow_decode<D: BorrowDecoder<'de, Context = Context>>(
2675 decoder: &mut D,
2676 ) -> Result<Self, DecodeError> {
2677 use core::convert::TryInto;
2678 let len = u64::decode(decoder)?;
2679 let len = len
2680 .try_into()
2681 .map_err(|_| DecodeError::OutsideUsizeRange(len))?;
2682 decoder.claim_container_read::<A::Item>(len)?;
2683
2684 let mut vec = SmallVec::with_capacity(len);
2685 if unty::type_equal::<A::Item, u8>() {
2686 // Initialize the smallvec's buffer. Note that we need to do this
2687 // through the raw pointer as we cannot name the type
2688 // [u8; N] even though A::Item is u8.
2689 let ptr = vec.as_mut_ptr();
2690 // SAFETY: A::Item is u8 and the smallvec has been allocated with
2691 // enough capacity
2692 unsafe {
2693 core::ptr::write_bytes(ptr, 0, len);
2694 vec.set_len(len);
2695 }
2696 // Read the data into the smallvec's buffer.
2697 let slice = vec.as_mut_slice();
2698 // SAFETY: A::Item is u8
2699 let slice = unsafe { core::mem::transmute::<&mut [A::Item], &mut [u8]>(slice) };
2700 decoder.reader().read(slice)?;
2701 } else {
2702 for _ in 0..len {
2703 decoder.unclaim_bytes_read(core::mem::size_of::<A::Item>());
2704 vec.push(A::Item::borrow_decode(decoder)?);
2705 }
2706 }
2707 Ok(vec)
2708 }
2709}
2710
2711#[cfg(feature = "impl_bincode")]
2712impl<A> Encode for SmallVec<A>
2713where
2714 A: Array,
2715 A::Item: Encode,
2716{
2717 fn encode<E: Encoder>(&self, encoder: &mut E) -> Result<(), EncodeError> {
2718 (self.len() as u64).encode(encoder)?;
2719 if unty::type_equal::<A::Item, u8>() {
2720 // Safety: A::Item is u8
2721 let slice: &[u8] = unsafe { core::mem::transmute(self.as_slice()) };
2722 encoder.writer().write(slice)?;
2723 } else {
2724 for item in self.iter() {
2725 item.encode(encoder)?;
2726 }
2727 }
2728 Ok(())
2729 }
2730}