1#![no_std]
61#![cfg_attr(docsrs, feature(doc_cfg))]
62#![cfg_attr(feature = "specialization", allow(incomplete_features))]
63#![cfg_attr(feature = "specialization", feature(specialization, trusted_len))]
64#![cfg_attr(feature = "may_dangle", feature(dropck_eyepatch))]
65
66#[doc(hidden)]
67pub extern crate alloc;
68
69#[cfg(any(test, feature = "std"))]
70extern crate std;
71
72#[cfg(test)]
73mod tests;
74
75use alloc::boxed::Box;
76use alloc::vec;
77use alloc::vec::Vec;
78
79use alloc::alloc::Layout;
80use core::borrow::Borrow;
81use core::borrow::BorrowMut;
82use core::fmt::Debug;
83use core::hash::{Hash, Hasher};
84use core::marker::PhantomData;
85use core::mem::align_of;
86use core::mem::size_of;
87use core::mem::ManuallyDrop;
88use core::mem::MaybeUninit;
89use core::ptr::addr_of;
90use core::ptr::addr_of_mut;
91use core::ptr::copy;
92use core::ptr::copy_nonoverlapping;
93use core::ptr::NonNull;
94
95#[cfg(feature = "bytes")]
96use bytes::{buf::UninitSlice, BufMut};
97#[cfg(feature = "malloc_size_of")]
98use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
99#[cfg(feature = "serde")]
100use serde_core::{
101 de::{Deserialize, Deserializer, SeqAccess, Visitor},
102 ser::{Serialize, SerializeSeq, Serializer},
103};
104#[cfg(feature = "std")]
105use std::io;
106
107#[derive(Debug)]
109pub enum CollectionAllocErr {
110 CapacityOverflow,
112 AllocErr {
114 layout: Layout,
116 },
117}
118impl core::fmt::Display for CollectionAllocErr {
119 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
120 write!(f, "Allocation error: {:?}", self)
121 }
122}
123
124impl core::error::Error for CollectionAllocErr {}
125
126#[repr(C)]
133pub union RawSmallVec<T, const N: usize> {
134 inline: ManuallyDrop<MaybeUninit<[T; N]>>,
135 heap: (NonNull<T>, usize),
136}
137
138#[inline]
139fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
140 match result {
141 Ok(x) => x,
142 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
143 Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
144 }
145}
146
147#[inline]
148fn slice_range<R>(range: R, bounds: core::ops::RangeTo<usize>) -> core::ops::Range<usize>
151where
152 R: core::ops::RangeBounds<usize>,
153{
154 let len = bounds.end;
155
156 let start = match range.start_bound() {
157 core::ops::Bound::Included(&start) => start,
158 core::ops::Bound::Excluded(start) => start
159 .checked_add(1)
160 .unwrap_or_else(|| panic!("attempted to index slice from after maximum usize")),
161 core::ops::Bound::Unbounded => 0,
162 };
163
164 let end = match range.end_bound() {
165 core::ops::Bound::Included(end) => end
166 .checked_add(1)
167 .unwrap_or_else(|| panic!("attempted to index slice up to maximum usize")),
168 core::ops::Bound::Excluded(&end) => end,
169 core::ops::Bound::Unbounded => len,
170 };
171
172 if start > end {
173 panic!("slice index starts at {start} but ends at {end}");
174 }
175 if end > len {
176 panic!("range end index {end} out of range for slice of length {len}");
177 }
178
179 core::ops::Range { start, end }
180}
181
182impl<T, const N: usize> RawSmallVec<T, N> {
183 #[inline]
184 const fn is_zst() -> bool {
185 size_of::<T>() == 0
186 }
187
188 #[inline]
189 const fn new() -> Self {
190 Self::new_inline(MaybeUninit::uninit())
191 }
192 #[inline]
193 const fn new_inline(inline: MaybeUninit<[T; N]>) -> Self {
194 Self {
195 inline: ManuallyDrop::new(inline),
196 }
197 }
198 #[inline]
199 const fn new_heap(ptr: NonNull<T>, capacity: usize) -> Self {
200 Self {
201 heap: (ptr, capacity),
202 }
203 }
204
205 #[inline]
206 const fn as_ptr_inline(&self) -> *const T {
207 (unsafe { addr_of!(self.inline) }) as *const T
211 }
212
213 #[inline]
214 const fn as_mut_ptr_inline(&mut self) -> *mut T {
215 (unsafe { addr_of_mut!(self.inline) }) as *mut T
217 }
218
219 #[inline]
223 const unsafe fn as_ptr_heap(&self) -> *const T {
224 self.heap.0.as_ptr()
225 }
226
227 #[inline]
231 const unsafe fn as_mut_ptr_heap(&mut self) -> *mut T {
232 self.heap.0.as_ptr()
233 }
234
235 unsafe fn try_grow_raw(
240 &mut self,
241 len: TaggedLen,
242 new_capacity: usize,
243 ) -> Result<(), CollectionAllocErr> {
244 use alloc::alloc::{alloc, realloc};
245 debug_assert!(!Self::is_zst());
246 debug_assert!(new_capacity > 0);
247 debug_assert!(new_capacity >= len.value(Self::is_zst()));
248
249 let was_on_heap = len.on_heap(Self::is_zst());
250 let ptr = if was_on_heap {
251 self.as_mut_ptr_heap()
252 } else {
253 self.as_mut_ptr_inline()
254 };
255 let len = len.value(Self::is_zst());
256
257 let new_layout =
258 Layout::array::<T>(new_capacity).map_err(|_| CollectionAllocErr::CapacityOverflow)?;
259 if new_layout.size() > isize::MAX as usize {
260 return Err(CollectionAllocErr::CapacityOverflow);
261 }
262
263 let new_ptr = if len == 0 || !was_on_heap {
264 let new_ptr = alloc(new_layout) as *mut T; let new_ptr =
267 NonNull::new(new_ptr).ok_or(CollectionAllocErr::AllocErr { layout: new_layout })?;
268 copy_nonoverlapping(ptr, new_ptr.as_ptr(), len);
269 new_ptr
270 } else {
271 let old_layout =
276 Layout::from_size_align_unchecked(self.heap.1 * size_of::<T>(), align_of::<T>());
277
278 let new_ptr = realloc(ptr as *mut u8, old_layout, new_layout.size()) as *mut T;
284 NonNull::new(new_ptr).ok_or(CollectionAllocErr::AllocErr { layout: new_layout })?
285 };
286 *self = Self::new_heap(new_ptr, new_capacity);
287 Ok(())
288 }
289}
290
291#[repr(transparent)]
299#[derive(Clone, Copy)]
300struct TaggedLen(usize);
301
302impl TaggedLen {
303 #[inline]
304 pub const fn new(len: usize, on_heap: bool, is_zst: bool) -> Self {
305 if is_zst {
306 debug_assert!(!on_heap);
307 TaggedLen(len)
308 } else {
309 debug_assert!(len < isize::MAX as usize);
310 TaggedLen((len << 1) | on_heap as usize)
311 }
312 }
313
314 #[inline]
315 #[must_use]
316 pub const fn on_heap(self, is_zst: bool) -> bool {
317 if is_zst {
318 false
319 } else {
320 (self.0 & 1_usize) == 1
321 }
322 }
323
324 #[inline]
325 pub const fn value(self, is_zst: bool) -> usize {
326 if is_zst {
327 self.0
328 } else {
329 self.0 >> 1
330 }
331 }
332}
333
334#[repr(C)]
335pub struct SmallVec<T, const N: usize> {
336 len: TaggedLen,
337 raw: RawSmallVec<T, N>,
338 _marker: PhantomData<T>,
339}
340
341unsafe impl<T: Send, const N: usize> Send for SmallVec<T, N> {}
342unsafe impl<T: Sync, const N: usize> Sync for SmallVec<T, N> {}
343
344impl<T, const N: usize> Default for SmallVec<T, N> {
345 #[inline]
346 fn default() -> Self {
347 Self::new()
348 }
349}
350
351pub struct Drain<'a, T: 'a, const N: usize> {
357 tail_start: usize,
365 tail_len: usize,
366 iter: core::slice::Iter<'a, T>,
367 vec: core::ptr::NonNull<SmallVec<T, N>>,
368}
369
370impl<'a, T: 'a, const N: usize> Iterator for Drain<'a, T, N> {
371 type Item = T;
372
373 #[inline]
374 fn next(&mut self) -> Option<T> {
375 self.iter
378 .next()
379 .map(|reference| unsafe { core::ptr::read(reference) })
380 }
381
382 #[inline]
383 fn size_hint(&self) -> (usize, Option<usize>) {
384 self.iter.size_hint()
385 }
386}
387
388impl<'a, T: 'a, const N: usize> DoubleEndedIterator for Drain<'a, T, N> {
389 #[inline]
390 fn next_back(&mut self) -> Option<T> {
391 self.iter
393 .next_back()
394 .map(|reference| unsafe { core::ptr::read(reference) })
395 }
396}
397
398impl<T, const N: usize> ExactSizeIterator for Drain<'_, T, N> {
399 #[inline]
400 fn len(&self) -> usize {
401 self.iter.len()
402 }
403}
404
405impl<T, const N: usize> core::iter::FusedIterator for Drain<'_, T, N> {}
406
407impl<'a, T: 'a, const N: usize> Drop for Drain<'a, T, N> {
408 fn drop(&mut self) {
409 struct DropGuard<'r, 'a, T, const N: usize>(&'r mut Drain<'a, T, N>);
411
412 impl<'r, 'a, T, const N: usize> Drop for DropGuard<'r, 'a, T, N> {
413 fn drop(&mut self) {
414 if self.0.tail_len > 0 {
415 unsafe {
416 let source_vec = self.0.vec.as_mut();
417 let start = source_vec.len();
419 let tail = self.0.tail_start;
420 if tail != start {
421 let ptr = source_vec.as_mut_ptr();
422 let src = ptr.add(tail);
423 let dst = ptr.add(start);
424 core::ptr::copy(src, dst, self.0.tail_len);
425 }
426 source_vec.set_len(start + self.0.tail_len);
427 }
428 }
429 }
430 }
431
432 let iter = core::mem::take(&mut self.iter);
433 let drop_len = iter.len();
434
435 let mut vec = self.vec;
436
437 if SmallVec::<T, N>::is_zst() {
438 unsafe {
441 let vec = vec.as_mut();
442 let old_len = vec.len();
443 vec.set_len(old_len + drop_len + self.tail_len);
444 vec.truncate(old_len + self.tail_len);
445 }
446
447 return;
448 }
449
450 let _guard = DropGuard(self);
452
453 if drop_len == 0 {
454 return;
455 }
456
457 let drop_ptr = iter.as_slice().as_ptr();
462
463 unsafe {
464 let vec_ptr = vec.as_mut().as_mut_ptr();
469 let drop_offset = drop_ptr.offset_from(vec_ptr) as usize;
472 let to_drop = core::ptr::slice_from_raw_parts_mut(vec_ptr.add(drop_offset), drop_len);
473 core::ptr::drop_in_place(to_drop);
474 }
475 }
476}
477
478impl<T, const N: usize> Drain<'_, T, N> {
479 #[must_use]
480 pub fn as_slice(&self) -> &[T] {
481 self.iter.as_slice()
482 }
483
484 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
489 let vec = unsafe { self.vec.as_mut() };
490 let range_start = vec.len();
491 let range_end = self.tail_start;
492 let range_slice = unsafe {
493 core::slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
494 };
495
496 for place in range_slice {
497 if let Some(new_item) = replace_with.next() {
498 unsafe { core::ptr::write(place, new_item) };
499 vec.set_len(vec.len() + 1);
500 } else {
501 return false;
502 }
503 }
504 true
505 }
506
507 #[track_caller]
509 unsafe fn move_tail(&mut self, additional: usize) {
510 let vec = unsafe { self.vec.as_mut() };
511 let len = self.tail_start + self.tail_len;
512
513 let old_len = vec.len();
515 vec.set_len(len);
516 vec.reserve(additional);
517 vec.set_len(old_len);
518
519 let new_tail_start = self.tail_start + additional;
520 unsafe {
521 let src = vec.as_ptr().add(self.tail_start);
522 let dst = vec.as_mut_ptr().add(new_tail_start);
523 core::ptr::copy(src, dst, self.tail_len);
524 }
525 self.tail_start = new_tail_start;
526 }
527}
528
529#[cfg(feature = "extract_if")]
530pub struct ExtractIf<'a, T, const N: usize, F>
536where
537 F: FnMut(&mut T) -> bool,
538{
539 vec: &'a mut SmallVec<T, N>,
540 idx: usize,
542 end: usize,
544 del: usize,
546 old_len: usize,
548 pred: F,
550}
551
552#[cfg(feature = "extract_if")]
553impl<T, const N: usize, F> core::fmt::Debug for ExtractIf<'_, T, N, F>
554where
555 F: FnMut(&mut T) -> bool,
556 T: core::fmt::Debug,
557{
558 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
559 f.debug_tuple("ExtractIf")
560 .field(&self.vec.as_slice())
561 .finish()
562 }
563}
564
565#[cfg(feature = "extract_if")]
566impl<T, F, const N: usize> Iterator for ExtractIf<'_, T, N, F>
567where
568 F: FnMut(&mut T) -> bool,
569{
570 type Item = T;
571
572 fn next(&mut self) -> Option<T> {
573 unsafe {
574 while self.idx < self.end {
575 let i = self.idx;
576 let v = core::slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
577 let drained = (self.pred)(&mut v[i]);
578 self.idx += 1;
582 if drained {
583 self.del += 1;
584 return Some(core::ptr::read(&v[i]));
585 } else if self.del > 0 {
586 let del = self.del;
587 let src: *const T = &v[i];
588 let dst: *mut T = &mut v[i - del];
589 core::ptr::copy_nonoverlapping(src, dst, 1);
590 }
591 }
592 None
593 }
594 }
595
596 fn size_hint(&self) -> (usize, Option<usize>) {
597 (0, Some(self.end - self.idx))
598 }
599}
600
601#[cfg(feature = "extract_if")]
602impl<T, F, const N: usize> Drop for ExtractIf<'_, T, N, F>
603where
604 F: FnMut(&mut T) -> bool,
605{
606 fn drop(&mut self) {
607 unsafe {
608 if self.idx < self.old_len && self.del > 0 {
609 let ptr = self.vec.as_mut_ptr();
616 let src = ptr.add(self.idx);
617 let dst = src.sub(self.del);
618 let tail_len = self.old_len - self.idx;
619 src.copy_to(dst, tail_len);
620 }
621 self.vec.set_len(self.old_len - self.del);
622 }
623 }
624}
625
626pub struct Splice<'a, I: Iterator + 'a, const N: usize> {
627 drain: Drain<'a, I::Item, N>,
628 replace_with: I,
629}
630
631impl<'a, I, const N: usize> core::fmt::Debug for Splice<'a, I, N>
632where
633 I: Debug + Iterator + 'a,
634 <I as Iterator>::Item: Debug,
635{
636 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
637 f.debug_tuple("Splice").field(&self.drain).finish()
638 }
639}
640
641impl<I: Iterator, const N: usize> Iterator for Splice<'_, I, N> {
642 type Item = I::Item;
643
644 fn next(&mut self) -> Option<Self::Item> {
645 self.drain.next()
646 }
647
648 fn size_hint(&self) -> (usize, Option<usize>) {
649 self.drain.size_hint()
650 }
651}
652
653impl<I: Iterator, const N: usize> DoubleEndedIterator for Splice<'_, I, N> {
654 fn next_back(&mut self) -> Option<Self::Item> {
655 self.drain.next_back()
656 }
657}
658
659impl<I: Iterator, const N: usize> ExactSizeIterator for Splice<'_, I, N> {}
660
661impl<I: Iterator, const N: usize> Drop for Splice<'_, I, N> {
662 fn drop(&mut self) {
663 self.drain.by_ref().for_each(drop);
664 self.drain.iter = [].iter();
670
671 unsafe {
672 if self.drain.tail_len == 0 {
673 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
674 return;
675 }
676
677 if !self.drain.fill(&mut self.replace_with) {
679 return;
680 }
681
682 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
685 if lower_bound > 0 {
686 self.drain.move_tail(lower_bound);
687 if !self.drain.fill(&mut self.replace_with) {
688 return;
689 }
690 }
691
692 let mut collected = self.replace_with.by_ref().collect::<SmallVec<I::Item, N>>().into_iter();
694 if collected.len() > 0 {
696 self.drain.move_tail(collected.len());
697 let filled = self.drain.fill(&mut collected);
698 debug_assert!(filled);
699 debug_assert_eq!(collected.len(), 0);
700 }
701 }
702 }
704}
705
706pub struct IntoIter<T, const N: usize> {
712 raw: RawSmallVec<T, N>,
718 begin: usize,
719 end: TaggedLen,
720 _marker: PhantomData<T>,
721}
722
723unsafe impl<T, const N: usize> Send for IntoIter<T, N> where T: Send {}
726unsafe impl<T, const N: usize> Sync for IntoIter<T, N> where T: Sync {}
727
728impl<T, const N: usize> IntoIter<T, N> {
729 #[inline]
730 const fn is_zst() -> bool {
731 size_of::<T>() == 0
732 }
733
734 #[inline]
735 const fn as_ptr(&self) -> *const T {
736 let on_heap = self.end.on_heap(Self::is_zst());
737 if on_heap {
738 unsafe { self.raw.as_ptr_heap() }
740 } else {
741 self.raw.as_ptr_inline()
742 }
743 }
744
745 #[inline]
746 const fn as_mut_ptr(&mut self) -> *mut T {
747 let on_heap = self.end.on_heap(Self::is_zst());
748 if on_heap {
749 unsafe { self.raw.as_mut_ptr_heap() }
751 } else {
752 self.raw.as_mut_ptr_inline()
753 }
754 }
755
756 #[inline]
757 pub const fn as_slice(&self) -> &[T] {
758 unsafe {
761 let ptr = self.as_ptr();
762 core::slice::from_raw_parts(
763 ptr.add(self.begin),
764 self.end.value(Self::is_zst()) - self.begin,
765 )
766 }
767 }
768
769 #[inline]
770 pub const fn as_mut_slice(&mut self) -> &mut [T] {
771 unsafe {
773 let ptr = self.as_mut_ptr();
774 core::slice::from_raw_parts_mut(
775 ptr.add(self.begin),
776 self.end.value(Self::is_zst()) - self.begin,
777 )
778 }
779 }
780}
781
782impl<T, const N: usize> Iterator for IntoIter<T, N> {
783 type Item = T;
784
785 #[inline]
786 fn next(&mut self) -> Option<Self::Item> {
787 if self.begin == self.end.value(Self::is_zst()) {
788 None
789 } else {
790 unsafe {
792 let ptr = self.as_mut_ptr();
793 let value = ptr.add(self.begin).read();
794 self.begin += 1;
795 Some(value)
796 }
797 }
798 }
799
800 #[inline]
801 fn size_hint(&self) -> (usize, Option<usize>) {
802 let size = self.end.value(Self::is_zst()) - self.begin;
803 (size, Some(size))
804 }
805}
806
807impl<T, const N: usize> DoubleEndedIterator for IntoIter<T, N> {
808 #[inline]
809 fn next_back(&mut self) -> Option<Self::Item> {
810 let mut end = self.end.value(Self::is_zst());
811 if self.begin == end {
812 None
813 } else {
814 unsafe {
816 let ptr = self.as_mut_ptr();
817 let on_heap = self.end.on_heap(Self::is_zst());
818 end -= 1;
819 self.end = TaggedLen::new(end, on_heap, Self::is_zst());
820 let value = ptr.add(end).read();
821 Some(value)
822 }
823 }
824 }
825}
826impl<T, const N: usize> ExactSizeIterator for IntoIter<T, N> {}
827impl<T, const N: usize> core::iter::FusedIterator for IntoIter<T, N> {}
828
829impl<T, const N: usize> SmallVec<T, N> {
830 #[inline]
831 pub const fn new() -> SmallVec<T, N> {
832 Self {
833 len: TaggedLen::new(0, false, Self::is_zst()),
834 raw: RawSmallVec::new(),
835 _marker: PhantomData,
836 }
837 }
838
839 #[inline]
840 pub fn with_capacity(capacity: usize) -> Self {
841 let mut this = Self::new();
842 if capacity > Self::inline_size() {
843 this.grow(capacity);
844 }
845 this
846 }
847
848 #[inline]
849 pub const fn from_buf<const S: usize>(elements: [T; S]) -> Self {
850 const { assert!(S <= N); }
851
852 let mut buf: MaybeUninit<[T; N]> = MaybeUninit::uninit();
855
856 unsafe {
860 copy_nonoverlapping(elements.as_ptr(), buf.as_mut_ptr() as *mut T, S);
861 }
862
863 core::mem::forget(elements);
865
866 Self {
868 len: TaggedLen::new(S, false, Self::is_zst()),
869 raw: RawSmallVec::new_inline(buf),
870 _marker: PhantomData,
871 }
872 }
873
874 #[inline]
875 pub fn from_buf_and_len(buf: [T; N], len: usize) -> Self {
876 assert!(len <= N);
877 let mut vec = Self {
879 len: TaggedLen::new(len, false, Self::is_zst()),
880 raw: RawSmallVec::new_inline(MaybeUninit::new(buf)),
881 _marker: PhantomData,
882 };
883 unsafe {
885 let remainder_ptr = vec.raw.as_mut_ptr_inline().add(len);
887 let remainder_len = N - len;
888
889 core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
891 remainder_ptr,
892 remainder_len,
893 ));
894 }
895
896 vec
897 }
898
899 #[inline]
919 pub const unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<[T; N]>, len: usize) -> Self {
920 debug_assert!(len <= N);
921 Self {
922 len: TaggedLen::new(len, false, Self::is_zst()),
923 raw: RawSmallVec::new_inline(buf),
924 _marker: PhantomData,
925 }
926 }
927}
928
929impl<T, const N: usize> SmallVec<T, N> {
930 #[inline]
931 const fn is_zst() -> bool {
932 size_of::<T>() == 0
933 }
934
935 #[inline]
936 pub fn from_vec(vec: Vec<T>) -> Self {
937 if vec.capacity() == 0 {
938 return Self::new();
939 }
940
941 if Self::is_zst() {
942 let mut vec = vec;
947 let len = vec.len();
948
949 unsafe { vec.set_len(0) };
952 Self {
953 len: TaggedLen::new(len, false, Self::is_zst()),
954 raw: RawSmallVec::new(),
955 _marker: PhantomData,
956 }
957 } else {
958 let mut vec = ManuallyDrop::new(vec);
959 let len = vec.len();
960 let cap = vec.capacity();
961 let ptr = unsafe { NonNull::new_unchecked(vec.as_mut_ptr()) };
964
965 Self {
966 len: TaggedLen::new(len, true, Self::is_zst()),
967 raw: RawSmallVec::new_heap(ptr, cap),
968 _marker: PhantomData,
969 }
970 }
971 }
972
973 #[inline]
979 unsafe fn set_on_heap(&mut self) {
980 self.len = TaggedLen::new(self.len(), true, Self::is_zst());
981 }
982
983 #[inline]
989 unsafe fn set_inline(&mut self) {
990 self.len = TaggedLen::new(self.len(), false, Self::is_zst());
991 }
992
993 #[inline]
1003 pub unsafe fn set_len(&mut self, new_len: usize) {
1004 debug_assert!(new_len <= self.capacity());
1005 let on_heap = self.len.on_heap(Self::is_zst());
1006 self.len = TaggedLen::new(new_len, on_heap, Self::is_zst());
1007 }
1008
1009 #[inline]
1010 pub const fn inline_size() -> usize {
1011 if Self::is_zst() {
1012 usize::MAX
1013 } else {
1014 N
1015 }
1016 }
1017
1018 #[inline]
1019 pub const fn len(&self) -> usize {
1020 self.len.value(Self::is_zst())
1021 }
1022
1023 #[must_use]
1024 #[inline]
1025 pub const fn is_empty(&self) -> bool {
1026 self.len() == 0
1027 }
1028
1029 #[inline]
1030 pub const fn capacity(&self) -> usize {
1031 if self.len.on_heap(Self::is_zst()) {
1032 unsafe { self.raw.heap.1 }
1034 } else {
1035 Self::inline_size()
1036 }
1037 }
1038
1039 #[inline]
1040 pub const fn spilled(&self) -> bool {
1041 self.len.on_heap(Self::is_zst())
1042 }
1043
1044 #[inline]
1069 pub fn split_off(&mut self, at: usize) -> Self {
1070 let len = self.len();
1071 assert!(at <= len);
1072
1073 let other_len = len - at;
1074 let mut other = Self::with_capacity(other_len);
1075
1076 unsafe {
1078 self.set_len(at);
1079 other.set_len(other_len);
1080
1081 core::ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other_len);
1082 }
1083 other
1084 }
1085
1086 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, N>
1087 where
1088 R: core::ops::RangeBounds<usize>,
1089 {
1090 let len = self.len();
1091 let core::ops::Range { start, end } = slice_range(range, ..len);
1092
1093 unsafe {
1094 self.set_len(start);
1096
1097 let range_slice = core::slice::from_raw_parts(self.as_ptr().add(start), end - start);
1099
1100 Drain {
1102 tail_start: end,
1103 tail_len: len - end,
1104 iter: range_slice.iter(),
1105 vec: core::ptr::NonNull::new_unchecked(self as *mut _),
1107 }
1109 }
1110 }
1111
1112 #[cfg(feature = "extract_if")]
1113 pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, N, F>
1183 where
1184 F: FnMut(&mut T) -> bool,
1185 R: core::ops::RangeBounds<usize>,
1186 {
1187 let old_len = self.len();
1188 let core::ops::Range { start, end } = slice_range(range, ..old_len);
1189
1190 unsafe {
1192 self.set_len(0);
1193 }
1194
1195 ExtractIf {
1196 vec: self,
1197 idx: start,
1198 end,
1199 del: 0,
1200 old_len,
1201 pred: filter,
1202 }
1203 }
1204
1205 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, N>
1206 where
1207 R: core::ops::RangeBounds<usize>,
1208 I: IntoIterator<Item = T>,
1209 {
1210 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
1211 }
1212
1213 #[inline]
1214 pub fn push(&mut self, value: T) {
1215 let len = self.len();
1216 if len == self.capacity() {
1217 self.reserve(1);
1218 }
1219 let ptr = unsafe { self.as_mut_ptr().add(len) };
1221 unsafe { ptr.write(value) };
1224 unsafe { self.set_len(len + 1) }
1225 }
1226
1227 #[inline]
1228 pub fn pop(&mut self) -> Option<T> {
1229 if self.is_empty() {
1230 None
1231 } else {
1232 let len = self.len() - 1;
1233 unsafe { self.set_len(len) };
1235 let value = unsafe { self.as_mut_ptr().add(len).read() };
1238 Some(value)
1239 }
1240 }
1241
1242 #[inline]
1243 pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
1244 let last = self.last_mut()?;
1245 if predicate(last) { self.pop() } else { None }
1246 }
1247
1248 #[inline]
1249 pub fn append<const M: usize>(&mut self, other: &mut SmallVec<T, M>) {
1250 let len = self.len();
1252 let other_len = other.len();
1253 let total_len = len + other_len;
1254 if total_len > self.capacity() {
1255 self.reserve(other_len);
1256 }
1257
1258 let ptr = unsafe { self.as_mut_ptr().add(len) };
1260 unsafe { other.set_len(0) }
1261 unsafe { copy_nonoverlapping(other.as_ptr(), ptr, other_len) };
1264 unsafe { self.set_len(total_len) }
1265 }
1266
1267 #[inline]
1268 pub fn grow(&mut self, new_capacity: usize) {
1269 infallible(self.try_grow(new_capacity));
1270 }
1271
1272 #[cold]
1273 pub fn try_grow(&mut self, new_capacity: usize) -> Result<(), CollectionAllocErr> {
1274 if Self::is_zst() {
1275 return Ok(());
1276 }
1277
1278 let len = self.len();
1279 assert!(new_capacity >= len);
1280
1281 if new_capacity > Self::inline_size() {
1282 let result = unsafe { self.raw.try_grow_raw(self.len, new_capacity) };
1284
1285 if result.is_ok() {
1286 unsafe { self.set_on_heap() };
1288 }
1289 result
1290 } else {
1291 if self.spilled() {
1293 unsafe {
1294 let (ptr, old_cap) = self.raw.heap;
1296 copy_nonoverlapping(ptr.as_ptr(), self.raw.as_mut_ptr_inline(), len);
1301 drop(DropDealloc {
1302 ptr: ptr.cast(),
1303 size_bytes: old_cap * size_of::<T>(),
1304 align: align_of::<T>(),
1305 });
1306 self.set_inline();
1307 }
1308 }
1309 Ok(())
1310 }
1311 }
1312
1313 #[inline]
1314 pub fn reserve(&mut self, additional: usize) {
1315 if additional > self.capacity() - self.len() {
1317 let new_capacity = infallible(
1318 self.len()
1319 .checked_add(additional)
1320 .and_then(usize::checked_next_power_of_two)
1321 .ok_or(CollectionAllocErr::CapacityOverflow),
1322 );
1323 self.grow(new_capacity);
1324 }
1325 }
1326
1327 #[inline]
1328 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1329 if additional > self.capacity() - self.len() {
1330 let new_capacity = self
1331 .len()
1332 .checked_add(additional)
1333 .and_then(usize::checked_next_power_of_two)
1334 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1335 self.try_grow(new_capacity)
1336 } else {
1337 Ok(())
1338 }
1339 }
1340
1341 #[inline]
1342 pub fn reserve_exact(&mut self, additional: usize) {
1343 if additional > self.capacity() - self.len() {
1345 let new_capacity = infallible(
1346 self.len()
1347 .checked_add(additional)
1348 .ok_or(CollectionAllocErr::CapacityOverflow),
1349 );
1350 self.grow(new_capacity);
1351 }
1352 }
1353
1354 #[inline]
1355 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
1356 if additional > self.capacity() - self.len() {
1357 let new_capacity = self
1358 .len()
1359 .checked_add(additional)
1360 .ok_or(CollectionAllocErr::CapacityOverflow)?;
1361 self.try_grow(new_capacity)
1362 } else {
1363 Ok(())
1364 }
1365 }
1366
1367 #[inline]
1368 pub fn shrink_to_fit(&mut self) {
1369 if !self.spilled() {
1370 return;
1371 }
1372 let len = self.len();
1373 if len <= Self::inline_size() {
1374 unsafe {
1376 let (ptr, capacity) = self.raw.heap;
1377 self.raw = RawSmallVec::new_inline(MaybeUninit::uninit());
1378 copy_nonoverlapping(ptr.as_ptr(), self.raw.as_mut_ptr_inline(), len);
1379 self.set_inline();
1380 alloc::alloc::dealloc(
1381 ptr.cast().as_ptr(),
1382 Layout::from_size_align_unchecked(capacity * size_of::<T>(), align_of::<T>()),
1383 );
1384 }
1385 } else if len < self.capacity() {
1386 unsafe { infallible(self.raw.try_grow_raw(self.len, len)) };
1390 }
1391 }
1392
1393 #[inline]
1394 pub fn shrink_to(&mut self, min_capacity: usize) {
1395 if !self.spilled() {
1396 return;
1397 }
1398 if self.capacity() > min_capacity {
1399 let len = self.len();
1400 let target = core::cmp::max(len, min_capacity);
1401 if target <= Self::inline_size() {
1402 unsafe {
1404 let (ptr, capacity) = self.raw.heap;
1405 self.raw = RawSmallVec::new_inline(MaybeUninit::uninit());
1406 copy_nonoverlapping(ptr.as_ptr(), self.raw.as_mut_ptr_inline(), len);
1407 self.set_inline();
1408 alloc::alloc::dealloc(
1409 ptr.cast().as_ptr(),
1410 Layout::from_size_align_unchecked(capacity * size_of::<T>(), align_of::<T>()),
1411 );
1412 }
1413 } else if target < self.capacity() {
1414 unsafe { infallible(self.raw.try_grow_raw(self.len, target)) };
1418 }
1419 }
1420 }
1421
1422 #[inline]
1423 pub fn truncate(&mut self, len: usize) {
1424 let old_len = self.len();
1425 if len < old_len {
1426 unsafe {
1429 self.set_len(len);
1430 core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
1431 self.as_mut_ptr().add(len),
1432 old_len - len,
1433 ))
1434 }
1435 }
1436 }
1437
1438 #[inline]
1439 pub fn swap_remove(&mut self, index: usize) -> T {
1440 let len = self.len();
1441 assert!(index < len, "swap_remove index (is {index}) should be < len (is {len})");
1442 let new_len = len - 1;
1444 unsafe {
1445 let value = core::ptr::read(self.as_ptr().add(index));
1449 let base_ptr = self.as_mut_ptr();
1450 core::ptr::copy(base_ptr.add(new_len), base_ptr.add(index), 1);
1451 self.set_len(new_len);
1452 value
1453 }
1454 }
1455
1456 #[inline]
1457 pub fn clear(&mut self) {
1458 unsafe {
1461 let old_len = self.len();
1462 self.set_len(0);
1463 core::ptr::drop_in_place(core::ptr::slice_from_raw_parts_mut(
1464 self.as_mut_ptr(),
1465 old_len,
1466 ));
1467 }
1468 }
1469
1470 #[inline]
1471 pub fn remove(&mut self, index: usize) -> T {
1472 let len = self.len();
1473 assert!(index < len, "removal index (is {index}) should be < len (is {len})");
1474 let new_len = len - 1;
1475 unsafe {
1476 self.set_len(new_len);
1478 let ptr = self.as_mut_ptr();
1479 let ith = ptr.add(index);
1480 let ith_item = ith.read();
1482 copy(ith.add(1), ith, new_len - index);
1483 ith_item
1484 }
1485 }
1486
1487 #[inline]
1488 pub fn insert(&mut self, index: usize, value: T) {
1489 let len = self.len();
1490 assert!(index <= len, "insertion index (is {index}) should be <= len (is {len})");
1491 self.reserve(1);
1492 let ptr = self.as_mut_ptr();
1493 unsafe {
1494 if index < len {
1496 copy(ptr.add(index), ptr.add(index + 1), len - index);
1497 }
1498 ptr.add(index).write(value);
1500
1501 self.set_len(len + 1);
1503 }
1504 }
1505
1506 #[inline]
1507 pub const fn as_slice(&self) -> &[T] {
1508 let len = self.len();
1509 let ptr = self.as_ptr();
1510 unsafe { core::slice::from_raw_parts(ptr, len) }
1512 }
1513
1514 #[inline]
1515 pub const fn as_mut_slice(&mut self) -> &mut [T] {
1516 let len = self.len();
1517 let ptr = self.as_mut_ptr();
1518 unsafe { core::slice::from_raw_parts_mut(ptr, len) }
1520 }
1521
1522 #[inline]
1523 pub const fn as_ptr(&self) -> *const T {
1524 if self.len.on_heap(Self::is_zst()) {
1525 unsafe { self.raw.as_ptr_heap() }
1527 } else {
1528 self.raw.as_ptr_inline()
1529 }
1530 }
1531
1532 #[inline]
1533 pub const fn as_mut_ptr(&mut self) -> *mut T {
1534 if self.len.on_heap(Self::is_zst()) {
1535 unsafe { self.raw.as_mut_ptr_heap() }
1537 } else {
1538 self.raw.as_mut_ptr_inline()
1539 }
1540 }
1541
1542 #[inline]
1543 pub fn into_vec(self) -> Vec<T> {
1544 let len = self.len();
1545 if !self.spilled() {
1546 let mut vec = Vec::with_capacity(len);
1547 let this = ManuallyDrop::new(self);
1548 unsafe {
1552 copy_nonoverlapping(this.raw.as_ptr_inline(), vec.as_mut_ptr(), len);
1553 vec.set_len(len);
1554 }
1555 vec
1556 } else {
1557 let this = ManuallyDrop::new(self);
1558 unsafe {
1566 let (ptr, cap) = this.raw.heap;
1567 Vec::from_raw_parts(ptr.as_ptr(), len, cap)
1568 }
1569 }
1570 }
1571
1572 #[inline]
1573 pub fn into_boxed_slice(self) -> Box<[T]> {
1574 self.into_vec().into_boxed_slice()
1575 }
1576
1577 #[inline]
1578 pub fn into_inner(self) -> Result<[T; N], Self> {
1579 if self.len() != N {
1580 Err(self)
1581 } else {
1582 let mut this = self;
1584 unsafe {
1586 this.set_len(0);
1587 }
1588 let ptr = this.as_ptr() as *const [T; N];
1589 unsafe { Ok(ptr.read()) }
1591 }
1592 }
1593
1594 #[inline]
1595 pub fn retain<F: FnMut(&T) -> bool>(&mut self, mut f: F) {
1596 self.retain_mut(|elem| f(elem))
1597 }
1598
1599 #[inline]
1600 pub fn retain_mut<F: FnMut(&mut T) -> bool>(&mut self, mut f: F) {
1601 let mut del = 0;
1602 let len = self.len();
1603 let ptr = self.as_mut_ptr();
1604 for i in 0..len {
1605 unsafe {
1608 if !f(&mut *ptr.add(i)) {
1609 del += 1;
1610 } else if del > 0 {
1611 core::ptr::swap(ptr.add(i), ptr.add(i - del));
1612 }
1613 }
1614 }
1615 self.truncate(len - del);
1616 }
1617
1618 #[inline]
1619 pub fn dedup(&mut self)
1620 where
1621 T: PartialEq,
1622 {
1623 self.dedup_by(|a, b| a == b);
1624 }
1625
1626 #[inline]
1627 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1628 where
1629 F: FnMut(&mut T) -> K,
1630 K: PartialEq<K>,
1631 {
1632 self.dedup_by(|a, b| key(a) == key(b));
1633 }
1634
1635 #[inline]
1636 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1637 where
1638 F: FnMut(&mut T, &mut T) -> bool,
1639 {
1640 let len = self.len();
1643 if len <= 1 {
1644 return;
1645 }
1646
1647 let ptr = self.as_mut_ptr();
1648 let mut w: usize = 1;
1649
1650 unsafe {
1651 for r in 1..len {
1652 let p_r = ptr.add(r);
1653 let p_wm1 = ptr.add(w - 1);
1654 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1655 if r != w {
1656 let p_w = p_wm1.add(1);
1657 core::ptr::swap(p_r, p_w);
1658 }
1659 w += 1;
1660 }
1661 }
1662 }
1663
1664 self.truncate(w);
1665 }
1666
1667 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1668 where
1669 F: FnMut() -> T,
1670 {
1671 let old_len = self.len();
1672 if old_len < new_len {
1673 let mut f = f;
1674 let additional = new_len - old_len;
1675 self.reserve(additional);
1676 for _ in 0..additional {
1677 self.push(f());
1678 }
1679 } else if old_len > new_len {
1680 self.truncate(new_len);
1681 }
1682 }
1683
1684 pub fn leak<'a>(self) -> &'a mut [T] {
1685 if !self.spilled() {
1686 panic!("SmallVec::leak() called on inline (stack) SmallVec, which cannot be safely leaked");
1687 }
1688 let mut me = ManuallyDrop::new(self);
1689 unsafe { core::slice::from_raw_parts_mut(me.as_mut_ptr(), me.len()) }
1690 }
1691
1692 #[inline]
1699 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1700 unsafe {
1701 core::slice::from_raw_parts_mut(
1702 self.as_mut_ptr().add(self.len()) as *mut MaybeUninit<T>,
1703 self.capacity() - self.len(),
1704 )
1705 }
1706 }
1707
1708 #[inline]
1760 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> SmallVec<T, N> {
1761 assert!(!Self::is_zst());
1762
1763 let ptr = unsafe {
1766 debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1767 NonNull::new_unchecked(ptr)
1768 };
1769
1770 SmallVec {
1771 len: TaggedLen::new(length, true, Self::is_zst()),
1772 raw: RawSmallVec::new_heap(ptr, capacity),
1773 _marker: PhantomData,
1774 }
1775 }
1776}
1777
1778impl<T: Clone, const N: usize> SmallVec<T, N> {
1779 #[inline]
1780 pub fn resize(&mut self, len: usize, value: T) {
1781 let old_len = self.len();
1782 if len > old_len {
1783 self.extend(core::iter::repeat_n(value, len - old_len));
1784 } else {
1785 self.truncate(len);
1786 }
1787 }
1788
1789 #[inline]
1790 pub fn extend_from_slice(&mut self, other: &[T]) {
1791 self.extend(other.iter())
1792 }
1793
1794 pub fn extend_from_within<R>(&mut self, src: R)
1795 where
1796 R: core::ops::RangeBounds<usize>,
1797 {
1798 let src = slice_range(src, ..self.len());
1799 self.reserve(src.len());
1800
1801 unsafe {
1804 #[cfg(feature = "specialization")]
1805 {
1806 <Self as spec_traits::SpecExtendFromWithin<T>>::spec_extend_from_within(self, src);
1807 }
1808
1809 #[cfg(not(feature = "specialization"))]
1810 {
1811 self.extend_from_within_fallback(src);
1812 }
1813 }
1814 }
1815
1816 #[inline]
1817 pub fn extend_from_slice_copy(&mut self, other: &[T])
1818 where
1819 T: Copy
1820 {
1821
1822 let len = other.len();
1823 let src = other.as_ptr();
1824
1825 let l = self.len();
1826 self.reserve(len);
1827
1828 unsafe {
1831 let dst = self.as_mut_ptr().add(l);
1832 copy_nonoverlapping(src, dst, len);
1833 self.set_len(l + len);
1834 }
1835 }
1836
1837 pub fn extend_from_within_copy<R>(&mut self, src: R)
1838 where
1839 R: core::ops::RangeBounds<usize>,
1840 T: Copy
1841 {
1842 let src = slice_range(src, ..self.len());
1843 let core::ops::Range { start, end } = src;
1844 let len = end - start;
1845 self.reserve(len);
1846
1847 unsafe {
1850 let l = self.len();
1851 let ptr = self.as_mut_ptr();
1852 copy_nonoverlapping(ptr.add(start), ptr.add(l), len);
1853 self.set_len(l + len);
1854 }
1855 }
1856
1857 pub fn insert_from_slice_copy(&mut self, index: usize, other: &[T])
1858 where
1859 T: Copy
1860 {
1861 let l = self.len();
1862 let len = other.len();
1863 assert!(index <= l);
1864 self.reserve(len);
1865 unsafe {
1866 let base_ptr = self.as_mut_ptr();
1867 let ith_ptr = base_ptr.add(index);
1868 let shifted_ptr = base_ptr.add(index + len);
1869 copy(ith_ptr, shifted_ptr, l - index);
1871 copy_nonoverlapping(other.as_ptr(), ith_ptr, len);
1873
1874 self.set_len(l + len);
1876 }
1877 }
1878
1879 pub fn from_slice_copy(slice: &[T]) -> Self
1882 where
1883 T: Copy
1884 {
1885 let src = slice.as_ptr();
1886 let len = slice.len();
1887 let mut result = Self::with_capacity(len);
1888
1889 unsafe {
1891 let dst = result.as_mut_ptr();
1892 copy_nonoverlapping(src, dst, len);
1893 result.set_len(len);
1894 }
1895
1896 result
1897 }
1898}
1899
1900struct DropGuard<T> {
1901 ptr: *mut T,
1902 len: usize,
1903}
1904impl<T> Drop for DropGuard<T> {
1905 #[inline]
1906 fn drop(&mut self) {
1907 unsafe {
1908 core::ptr::slice_from_raw_parts_mut(self.ptr, self.len).drop_in_place();
1909 }
1910 }
1911}
1912
1913struct DropDealloc {
1914 ptr: NonNull<u8>,
1915 size_bytes: usize,
1916 align: usize,
1917}
1918
1919impl Drop for DropDealloc {
1920 #[inline]
1921 fn drop(&mut self) {
1922 unsafe {
1923 if self.size_bytes > 0 {
1924 alloc::alloc::dealloc(
1925 self.ptr.as_ptr(),
1926 Layout::from_size_align_unchecked(self.size_bytes, self.align),
1927 );
1928 }
1929 }
1930 }
1931}
1932
1933#[cfg(feature = "may_dangle")]
1934unsafe impl<#[may_dangle] T, const N: usize> Drop for SmallVec<T, N> {
1935 fn drop(&mut self) {
1936 let on_heap = self.spilled();
1937 let len = self.len();
1938 let ptr = self.as_mut_ptr();
1939 unsafe {
1942 let _drop_dealloc = if on_heap {
1943 let capacity = self.capacity();
1944 Some(DropDealloc {
1945 ptr: NonNull::new_unchecked(ptr as *mut u8),
1946 size_bytes: capacity * size_of::<T>(),
1947 align: align_of::<T>(),
1948 })
1949 } else {
1950 None
1951 };
1952 core::ptr::slice_from_raw_parts_mut(ptr, len).drop_in_place();
1953 }
1954 }
1955}
1956
1957#[cfg(not(feature = "may_dangle"))]
1958impl<T, const N: usize> Drop for SmallVec<T, N> {
1959 fn drop(&mut self) {
1960 let on_heap = self.spilled();
1961 let len = self.len();
1962 let ptr = self.as_mut_ptr();
1963 unsafe {
1965 let _drop_dealloc = if on_heap {
1966 let capacity = self.capacity();
1967 Some(DropDealloc {
1968 ptr: NonNull::new_unchecked(ptr as *mut u8),
1969 size_bytes: capacity * size_of::<T>(),
1970 align: align_of::<T>(),
1971 })
1972 } else {
1973 None
1974 };
1975 core::ptr::slice_from_raw_parts_mut(ptr, len).drop_in_place();
1976 }
1977 }
1978}
1979
1980impl<T, const N: usize> Drop for IntoIter<T, N> {
1981 fn drop(&mut self) {
1982 unsafe {
1984 let is_zst = size_of::<T>() == 0;
1985 let on_heap = self.end.on_heap(is_zst);
1986 let begin = self.begin;
1987 let end = self.end.value(is_zst);
1988 let ptr = self.as_mut_ptr();
1989 let _drop_dealloc = if on_heap {
1990 let capacity = self.raw.heap.1;
1991 Some(DropDealloc {
1992 ptr: NonNull::new_unchecked(ptr as *mut u8),
1993 size_bytes: capacity * size_of::<T>(),
1994 align: align_of::<T>(),
1995 })
1996 } else {
1997 None
1998 };
1999 core::ptr::slice_from_raw_parts_mut(ptr.add(begin), end - begin).drop_in_place();
2000 }
2001 }
2002}
2003
2004impl<T, const N: usize> core::ops::Deref for SmallVec<T, N> {
2005 type Target = [T];
2006
2007 #[inline]
2008 fn deref(&self) -> &Self::Target {
2009 self.as_slice()
2010 }
2011}
2012impl<T, const N: usize> core::ops::DerefMut for SmallVec<T, N> {
2013 #[inline]
2014 fn deref_mut(&mut self) -> &mut Self::Target {
2015 self.as_mut_slice()
2016 }
2017}
2018
2019#[doc(hidden)]
2022#[track_caller]
2023pub fn from_elem<T: Clone, const N: usize>(elem: T, n: usize) -> SmallVec<T, N> {
2024 if n > SmallVec::<T, N>::inline_size() {
2025 SmallVec::<T, N>::from_vec(vec![elem; n])
2027 } else {
2028 #[cfg(feature = "specialization")]
2029 {
2030 unsafe { <SmallVec<T, N> as spec_traits::SpecFromElem<T>>::spec_from_elem(elem, n) }
2032 }
2033
2034 #[cfg(not(feature = "specialization"))]
2035 {
2036 unsafe { SmallVec::<T, N>::from_elem_fallback(elem, n) }
2038 }
2039 }
2040}
2041
2042#[cfg(feature = "specialization")]
2043mod spec_traits {
2044 use super::*;
2045
2046 pub(crate) trait SpecFromElem<T> {
2050 unsafe fn spec_from_elem(elem: T, n: usize) -> Self;
2057 }
2058
2059 impl<T: Clone, const N: usize> SpecFromElem<T> for SmallVec<T, N> {
2060 #[inline]
2061 default unsafe fn spec_from_elem(elem: T, n: usize) -> Self {
2062 unsafe { SmallVec::from_elem_fallback(elem, n) }
2064 }
2065 }
2066
2067 impl<T: Copy, const N: usize> SpecFromElem<T> for SmallVec<T, N> {
2068 unsafe fn spec_from_elem(elem: T, n: usize) -> Self {
2069 let mut result = Self::new();
2070
2071 if n > 0 {
2072 let ptr = result.raw.as_mut_ptr_inline();
2073
2074 unsafe {
2077 for i in 0..n {
2078 ptr.add(i).write(elem);
2079 }
2080 }
2081 }
2082
2083 unsafe {
2086 result.set_len(n);
2087 }
2088
2089 result
2090 }
2091 }
2092
2093 pub(crate) trait SpecExtend<T, I> {
2097 fn spec_extend(&mut self, iter: I);
2098 }
2099
2100 impl<T, I, const N: usize> SpecExtend<T, I> for SmallVec<T, N>
2101 where
2102 I: Iterator<Item = T>,
2103 {
2104 #[inline]
2105 default fn spec_extend(&mut self, iter: I) {
2106 self.extend_fallback(iter);
2107 }
2108 }
2109
2110 impl<T, I, const N: usize> SpecExtend<T, I> for SmallVec<T, N>
2111 where
2112 I: core::iter::TrustedLen<Item = T>,
2113 {
2114 fn spec_extend(&mut self, iter: I) {
2115 let (_, Some(additional)) = iter.size_hint() else {
2116 panic!("capacity overflow")
2117 };
2118 self.reserve(additional);
2119
2120 unsafe {
2125 let len = self.len();
2126 let ptr = self.as_mut_ptr().add(len);
2127 let mut guard = DropGuard { ptr, len: 0 };
2128
2129 for x in iter {
2130 ptr.add(guard.len).write(x);
2131 guard.len += 1;
2132 }
2133
2134 self.set_len(len + guard.len);
2136 core::mem::forget(guard);
2137 }
2138 }
2139 }
2140
2141 impl<T, const N: usize, const M: usize> SpecExtend<T, IntoIter<T, M>> for SmallVec<T, N> {
2142 fn spec_extend(&mut self, mut iter: IntoIter<T, M>) {
2143 let slice = iter.as_slice();
2144 let len = slice.len();
2145 let old_len = self.len();
2146
2147 self.reserve(len);
2148
2149 unsafe {
2152 let dst = self.as_mut_ptr().add(old_len);
2153 let src = slice.as_ptr();
2154 copy_nonoverlapping(src, dst, len);
2155 }
2156
2157 unsafe {
2159 self.set_len(old_len + len);
2160 }
2161
2162 iter.begin = iter.end.value(Self::is_zst());
2164 }
2165 }
2166
2167 impl<'a, T: 'a, const N: usize, I> SpecExtend<&'a T, I> for SmallVec<T, N>
2168 where
2169 I: Iterator<Item = &'a T>,
2170 T: Clone,
2171 {
2172 #[inline]
2173 default fn spec_extend(&mut self, iterator: I) {
2174 self.spec_extend(iterator.cloned())
2175 }
2176 }
2177
2178 impl<'a, T: 'a, const N: usize> SpecExtend<&'a T, core::slice::Iter<'a, T>> for SmallVec<T, N>
2179 where
2180 T: Copy,
2181 {
2182 fn spec_extend(&mut self, iter: core::slice::Iter<'a, T>) {
2183 let slice = iter.as_slice();
2184 let len = slice.len();
2185 let old_len = self.len();
2186
2187 self.reserve(len);
2188
2189 unsafe {
2192 let dst = self.as_mut_ptr().add(old_len);
2193 let src = slice.as_ptr();
2194 copy_nonoverlapping(src, dst, len);
2195 }
2196
2197 unsafe {
2199 self.set_len(old_len + len);
2200 }
2201 }
2202 }
2203
2204 pub(crate) trait SpecExtendFromWithin<T> {
2208 unsafe fn spec_extend_from_within(&mut self, src: core::ops::Range<usize>);
2217 }
2218
2219 impl<T: Clone, const N: usize> SpecExtendFromWithin<T> for SmallVec<T, N> {
2220 default unsafe fn spec_extend_from_within(&mut self, src: core::ops::Range<usize>) {
2221 unsafe {
2223 self.extend_from_within_fallback(src);
2224 }
2225 }
2226 }
2227
2228 impl<T: Copy, const N: usize> SpecExtendFromWithin<T> for SmallVec<T, N> {
2229 unsafe fn spec_extend_from_within(&mut self, src: core::ops::Range<usize>) {
2230 let old_len = self.len();
2231
2232 let start = src.start;
2233 let len = src.len();
2234
2235 unsafe {
2239 let ptr = self.as_mut_ptr();
2240 let dst = ptr.add(old_len);
2241 let src = ptr.add(start);
2242 copy_nonoverlapping(src, dst, len);
2243 }
2244
2245 unsafe {
2247 self.set_len(old_len + len);
2248 }
2249 }
2250 }
2251
2252 pub(crate) trait SpecFromIterator<T, I> {
2256 fn spec_from_iter(iter: I) -> Self;
2257 }
2258
2259 impl<T, I, const N: usize> SpecFromIterator<T, I> for SmallVec<T, N>
2260 where
2261 I: Iterator<Item = T>,
2262 {
2263 #[inline]
2264 default fn spec_from_iter(iter: I) -> Self {
2265 Self::from_iter_fallback(iter)
2266 }
2267 }
2268
2269 impl<T, I, const N: usize> SpecFromIterator<T, I> for SmallVec<T, N>
2270 where
2271 I: core::iter::TrustedLen<Item = T>,
2272 {
2273 fn spec_from_iter(iter: I) -> Self {
2274 let mut v = match iter.size_hint() {
2275 (_, Some(upper)) => SmallVec::with_capacity(upper),
2276 _ => panic!("capacity overflow"),
2281 };
2282 v.spec_extend(iter);
2284 v
2285 }
2286 }
2287
2288 pub(crate) trait SpecCloneFrom<T> {
2292 fn spec_clone_from(&mut self, source: &[T]);
2293 }
2294
2295 impl<T: Clone, const N: usize> SpecCloneFrom<T> for SmallVec<T, N> {
2296 #[inline]
2297 default fn spec_clone_from(&mut self, source: &[T]) {
2298 self.clone_from_fallback(source);
2299 }
2300 }
2301
2302 impl<T: Copy, const N: usize> SpecCloneFrom<T> for SmallVec<T, N> {
2303 fn spec_clone_from(&mut self, source: &[T]) {
2304 self.clear();
2305 self.extend_from_slice(source);
2306 }
2307 }
2308
2309 pub(crate) trait SpecFromSlice<T> {
2312 unsafe fn spec_from(slice: &[T]) -> Self;
2319 }
2320
2321 impl<T: Clone, const N: usize> SpecFromSlice<T> for SmallVec<T, N> {
2322 default unsafe fn spec_from(slice: &[T]) -> Self {
2323 unsafe { Self::from_slice_fallback(slice) }
2325 }
2326 }
2327
2328 impl<T: Copy, const N: usize> SpecFromSlice<T> for SmallVec<T, N> {
2329 unsafe fn spec_from(slice: &[T]) -> Self {
2330 let mut v = Self::new();
2331
2332 let src = slice.as_ptr();
2333 let len = slice.len();
2334 let dst = v.as_mut_ptr();
2335
2336 unsafe {
2339 copy_nonoverlapping(src, dst, len);
2340 }
2341
2342 unsafe {
2344 v.set_len(len);
2345 }
2346
2347 v
2348 }
2349 }
2350}
2351
2352impl<T, const N: usize> SmallVec<T, N> {
2355 unsafe fn from_elem_fallback(elem: T, n: usize) -> Self
2362 where
2363 T: Clone,
2364 {
2365 let mut result = Self::new();
2366
2367 if n > 0 {
2368 let ptr = result.raw.as_mut_ptr_inline();
2369 let mut guard = DropGuard { ptr, len: 0 };
2370
2371 unsafe {
2374 for i in 0..(n - 1) {
2375 ptr.add(i).write(elem.clone());
2376 guard.len += 1;
2377 }
2378 core::mem::forget(guard);
2379 ptr.add(n - 1).write(elem);
2380 }
2381 }
2382
2383 unsafe {
2386 result.set_len(n);
2387 }
2388
2389 result
2390 }
2391
2392 fn extend_fallback<I>(&mut self, iter: I)
2393 where
2394 I: IntoIterator<Item = T>,
2395 {
2396 let iter = iter.into_iter();
2397 let (size, _) = iter.size_hint();
2398 self.reserve(size);
2399 for x in iter {
2400 self.push(x);
2401 }
2402 }
2403
2404 unsafe fn extend_from_within_fallback(&mut self, src: core::ops::Range<usize>)
2413 where
2414 T: Clone,
2415 {
2416 let old_len = self.len();
2417
2418 let start = src.start;
2419 let len = src.len();
2420
2421 unsafe {
2425 let ptr = self.as_mut_ptr();
2426 let dst = ptr.add(old_len);
2427 let src = ptr.add(start);
2428
2429 let mut guard = DropGuard { ptr: dst, len: 0 };
2430 for i in 0..len {
2431 let val = (*src.add(i)).clone();
2432 dst.add(i).write(val);
2433 guard.len += 1;
2434 }
2435 core::mem::forget(guard);
2436 }
2437
2438 unsafe {
2440 self.set_len(old_len + len);
2441 }
2442 }
2443
2444 fn from_iter_fallback<I>(iter: I) -> Self
2445 where
2446 I: Iterator<Item = T>,
2447 {
2448 let (size, _) = iter.size_hint();
2449 let mut v = Self::with_capacity(size);
2450 for x in iter {
2451 v.push(x);
2452 }
2453 v
2454 }
2455
2456 fn clone_from_fallback(&mut self, source: &[T])
2457 where
2458 T: Clone,
2459 {
2460 self.truncate(source.len());
2464
2465 let (init, tail) = unsafe { source.split_at_unchecked(self.len()) };
2468
2469 self.clone_from_slice(init);
2471 self.extend(tail.iter().cloned());
2472 }
2473
2474 unsafe fn from_slice_fallback(slice: &[T]) -> Self
2481 where
2482 T: Clone,
2483 {
2484 let mut v = Self::new();
2485
2486 let src = slice.as_ptr();
2487 let len = slice.len();
2488 let dst = v.as_mut_ptr();
2489
2490 unsafe {
2493 let mut guard = DropGuard { ptr: dst, len: 0 };
2494 for i in 0..len {
2495 let val = (*src.add(i)).clone();
2496 dst.add(i).write(val);
2497 guard.len += 1;
2498 }
2499 core::mem::forget(guard);
2500 }
2501
2502 unsafe {
2504 v.set_len(len);
2505 }
2506
2507 v
2508 }
2509}
2510
2511impl<T: Clone, const N: usize> From<&[T]> for SmallVec<T, N> {
2512 #[inline]
2513 fn from(slice: &[T]) -> Self {
2514 if slice.len() > Self::inline_size() {
2515 Self::from_vec(Vec::from(slice))
2517 } else {
2518 unsafe {
2520 #[cfg(feature = "specialization")]
2521 {
2522 <Self as spec_traits::SpecFromSlice<T>>::spec_from(slice)
2523 }
2524
2525 #[cfg(not(feature = "specialization"))]
2526 {
2527 Self::from_slice_fallback(slice)
2528 }
2529 }
2530 }
2531 }
2532}
2533
2534impl<T: Clone, const N: usize> From<&mut [T]> for SmallVec<T, N> {
2535 #[inline]
2536 fn from(slice: &mut [T]) -> Self {
2537 Self::from(slice as &[T])
2538 }
2539}
2540
2541impl<T: Clone, const M: usize, const N: usize> From<&[T; M]> for SmallVec<T, N> {
2542 #[inline]
2543 fn from(slice: &[T; M]) -> Self {
2544 Self::from(slice as &[T])
2545 }
2546}
2547
2548impl<T: Clone, const M: usize, const N: usize> From<&mut [T; M]> for SmallVec<T, N> {
2549 #[inline]
2550 fn from(slice: &mut [T; M]) -> Self {
2551 Self::from(slice as &[T])
2552 }
2553}
2554
2555impl<T, const N: usize, const M: usize> From<[T; M]> for SmallVec<T, N> {
2556 fn from(array: [T; M]) -> Self {
2557 if M > N {
2558 Self::from(Vec::from(array))
2561 } else {
2562 let mut this = Self::new();
2564 debug_assert!(M <= this.capacity());
2565 let array = ManuallyDrop::new(array);
2566 unsafe {
2568 copy_nonoverlapping(array.as_ptr(), this.as_mut_ptr(), M);
2569 this.set_len(M);
2570 }
2571 this
2572 }
2573 }
2574}
2575
2576impl<T, const N: usize> From<Vec<T>> for SmallVec<T, N> {
2577 fn from(array: Vec<T>) -> Self {
2578 Self::from_vec(array)
2579 }
2580}
2581
2582impl<T: Clone, const N: usize> Clone for SmallVec<T, N> {
2583 #[inline]
2584 fn clone(&self) -> SmallVec<T, N> {
2585 SmallVec::from(self.as_slice())
2586 }
2587
2588 #[inline]
2589 fn clone_from(&mut self, source: &Self) {
2590 #[cfg(feature = "specialization")]
2591 {
2592 <Self as spec_traits::SpecCloneFrom<T>>::spec_clone_from(self, source);
2593 }
2594
2595 #[cfg(not(feature = "specialization"))]
2596 {
2597 self.clone_from_fallback(&*source);
2598 }
2599 }
2600}
2601
2602impl<T: Clone, const N: usize> Clone for IntoIter<T, N> {
2603 #[inline]
2604 fn clone(&self) -> IntoIter<T, N> {
2605 SmallVec::from(self.as_slice()).into_iter()
2606 }
2607}
2608
2609impl<T, const N: usize> Extend<T> for SmallVec<T, N> {
2610 #[inline]
2611 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2612 #[cfg(feature = "specialization")]
2613 {
2614 spec_traits::SpecExtend::<T, _>::spec_extend(self, iter.into_iter());
2615 }
2616
2617 #[cfg(not(feature = "specialization"))]
2618 {
2619 self.extend_fallback(iter);
2620 }
2621 }
2622}
2623
2624impl<'a, T: Clone + 'a, const N: usize> Extend<&'a T> for SmallVec<T, N> {
2625 #[inline]
2626 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2627 #[cfg(feature = "specialization")]
2628 {
2629 spec_traits::SpecExtend::<&'a T, _>::spec_extend(self, iter.into_iter());
2630 }
2631
2632 #[cfg(not(feature = "specialization"))]
2633 {
2634 self.extend_fallback(iter.into_iter().cloned());
2635 }
2636 }
2637}
2638
2639impl<T, const N: usize> core::iter::FromIterator<T> for SmallVec<T, N> {
2640 #[inline]
2641 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
2642 #[cfg(feature = "specialization")]
2643 {
2644 spec_traits::SpecFromIterator::<T, _>::spec_from_iter(iter.into_iter())
2645 }
2646
2647 #[cfg(not(feature = "specialization"))]
2648 {
2649 Self::from_iter_fallback(iter.into_iter())
2650 }
2651 }
2652}
2653
2654#[macro_export]
2655macro_rules! smallvec {
2656 (@one $x:expr) => (1usize);
2658 () => (
2659 $crate::SmallVec::new()
2660 );
2661 ($elem:expr; $n:expr) => ({
2662 $crate::from_elem($elem, $n)
2663 });
2664 ($($x:expr),+$(,)?) => ({
2665 const COUNT: usize = 0usize $(+ $crate::smallvec!(@one $x))+;
2666 let mut vec = $crate::SmallVec::new();
2667 if COUNT <= vec.capacity() {
2668 $(vec.push($x);)*
2669 vec
2670 } else {
2671 $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
2672 }
2673 });
2674}
2675
2676#[macro_export]
2677macro_rules! smallvec_inline {
2678 (@one $x:expr) => (1usize);
2680 ($elem:expr; $n:expr) => ({
2681 $crate::SmallVec::<_, $n>::from_buf([$elem; $n])
2682 });
2683 ($($x:expr),+ $(,)?) => ({
2684 const N: usize = 0usize $(+ $crate::smallvec_inline!(@one $x))*;
2685 $crate::SmallVec::<_, N>::from_buf([$($x,)*])
2686 });
2687}
2688
2689impl<T, const N: usize> IntoIterator for SmallVec<T, N> {
2690 type IntoIter = IntoIter<T, N>;
2691 type Item = T;
2692 fn into_iter(self) -> Self::IntoIter {
2693 unsafe {
2696 let this = ManuallyDrop::new(self);
2698 IntoIter {
2699 raw: (&this.raw as *const RawSmallVec<T, N>).read(),
2700 begin: 0,
2701 end: this.len,
2702 _marker: PhantomData,
2703 }
2704 }
2705 }
2706}
2707
2708impl<'a, T, const N: usize> IntoIterator for &'a SmallVec<T, N> {
2709 type IntoIter = core::slice::Iter<'a, T>;
2710 type Item = &'a T;
2711 fn into_iter(self) -> Self::IntoIter {
2712 self.iter()
2713 }
2714}
2715
2716impl<'a, T, const N: usize> IntoIterator for &'a mut SmallVec<T, N> {
2717 type IntoIter = core::slice::IterMut<'a, T>;
2718 type Item = &'a mut T;
2719 fn into_iter(self) -> Self::IntoIter {
2720 self.iter_mut()
2721 }
2722}
2723
2724impl<T, U, const N: usize, const M: usize> PartialEq<SmallVec<U, M>> for SmallVec<T, N>
2725where
2726 T: PartialEq<U>,
2727{
2728 #[inline]
2729 fn eq(&self, other: &SmallVec<U, M>) -> bool {
2730 self.as_slice().eq(other.as_slice())
2731 }
2732}
2733impl<T, const N: usize> Eq for SmallVec<T, N> where T: Eq {}
2734
2735impl<T, U, const N: usize, const M: usize> PartialEq<[U; M]> for SmallVec<T, N>
2736where
2737 T: PartialEq<U>,
2738{
2739 #[inline]
2740 fn eq(&self, other: &[U; M]) -> bool {
2741 self[..] == other[..]
2742 }
2743}
2744
2745impl<T, U, const N: usize, const M: usize> PartialEq<&[U; M]> for SmallVec<T, N>
2746where
2747 T: PartialEq<U>,
2748{
2749 #[inline]
2750 fn eq(&self, other: &&[U; M]) -> bool {
2751 self[..] == other[..]
2752 }
2753}
2754
2755impl<T, U, const N: usize> PartialEq<[U]> for SmallVec<T, N>
2756where
2757 T: PartialEq<U>,
2758{
2759 #[inline]
2760 fn eq(&self, other: &[U]) -> bool {
2761 self[..] == other[..]
2762 }
2763}
2764
2765impl<T, U, const N: usize> PartialEq<&[U]> for SmallVec<T, N>
2766where
2767 T: PartialEq<U>,
2768{
2769 #[inline]
2770 fn eq(&self, other: &&[U]) -> bool {
2771 self[..] == other[..]
2772 }
2773}
2774
2775impl<T, U, const N: usize> PartialEq<&mut [U]> for SmallVec<T, N>
2776where
2777 T: PartialEq<U>,
2778{
2779 #[inline]
2780 fn eq(&self, other: &&mut [U]) -> bool {
2781 self[..] == other[..]
2782 }
2783}
2784
2785impl<T, const N: usize> PartialOrd for SmallVec<T, N>
2786where
2787 T: PartialOrd,
2788{
2789 #[inline]
2790 fn partial_cmp(&self, other: &SmallVec<T, N>) -> Option<core::cmp::Ordering> {
2791 self.as_slice().partial_cmp(other.as_slice())
2792 }
2793}
2794
2795impl<T, const N: usize> Ord for SmallVec<T, N>
2796where
2797 T: Ord,
2798{
2799 #[inline]
2800 fn cmp(&self, other: &SmallVec<T, N>) -> core::cmp::Ordering {
2801 self.as_slice().cmp(other.as_slice())
2802 }
2803}
2804
2805impl<T: Hash, const N: usize> Hash for SmallVec<T, N> {
2806 fn hash<H: Hasher>(&self, state: &mut H) {
2807 self.as_slice().hash(state)
2808 }
2809}
2810
2811impl<T, const N: usize> Borrow<[T]> for SmallVec<T, N> {
2812 #[inline]
2813 fn borrow(&self) -> &[T] {
2814 self.as_slice()
2815 }
2816}
2817
2818impl<T, const N: usize> BorrowMut<[T]> for SmallVec<T, N> {
2819 #[inline]
2820 fn borrow_mut(&mut self) -> &mut [T] {
2821 self.as_mut_slice()
2822 }
2823}
2824
2825impl<T, const N: usize> AsRef<[T]> for SmallVec<T, N> {
2826 #[inline]
2827 fn as_ref(&self) -> &[T] {
2828 self.as_slice()
2829 }
2830}
2831
2832impl<T, const N: usize> AsMut<[T]> for SmallVec<T, N> {
2833 #[inline]
2834 fn as_mut(&mut self) -> &mut [T] {
2835 self.as_mut_slice()
2836 }
2837}
2838
2839impl<T: Debug, const N: usize> Debug for SmallVec<T, N> {
2840 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2841 f.debug_list().entries(self.iter()).finish()
2842 }
2843}
2844
2845impl<T: Debug, const N: usize> Debug for IntoIter<T, N> {
2846 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2847 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2848 }
2849}
2850
2851impl<T: Debug, const N: usize> Debug for Drain<'_, T, N> {
2852 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2853 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
2854 }
2855}
2856
2857#[cfg(feature = "serde")]
2858#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2859impl<T, const N: usize> Serialize for SmallVec<T, N>
2860where
2861 T: Serialize,
2862{
2863 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
2864 let mut state = serializer.serialize_seq(Some(self.len()))?;
2865 for item in self {
2866 state.serialize_element(item)?;
2867 }
2868 state.end()
2869 }
2870}
2871
2872#[cfg(feature = "serde")]
2873#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
2874impl<'de, T, const N: usize> Deserialize<'de> for SmallVec<T, N>
2875where
2876 T: Deserialize<'de>,
2877{
2878 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
2879 deserializer.deserialize_seq(SmallVecVisitor {
2880 phantom: PhantomData,
2881 })
2882 }
2883}
2884
2885#[cfg(feature = "serde")]
2886struct SmallVecVisitor<T, const N: usize> {
2887 phantom: PhantomData<T>,
2888}
2889
2890#[cfg(feature = "serde")]
2891impl<'de, T, const N: usize> Visitor<'de> for SmallVecVisitor<T, N>
2892where
2893 T: Deserialize<'de>,
2894{
2895 type Value = SmallVec<T, N>;
2896
2897 fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2898 formatter.write_str("a sequence")
2899 }
2900
2901 fn visit_seq<B>(self, mut seq: B) -> Result<Self::Value, B::Error>
2902 where
2903 B: SeqAccess<'de>,
2904 {
2905 use serde_core::de::Error;
2906 let len = seq.size_hint().unwrap_or(0);
2907 let mut values = SmallVec::new();
2908 values.try_reserve(len).map_err(B::Error::custom)?;
2909
2910 while let Some(value) = seq.next_element()? {
2911 values.push(value);
2912 }
2913
2914 Ok(values)
2915 }
2916}
2917
2918#[cfg(feature = "malloc_size_of")]
2919impl<T, const N: usize> MallocShallowSizeOf for SmallVec<T, N> {
2920 fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2921 if self.spilled() {
2922 unsafe { ops.malloc_size_of(self.as_ptr()) }
2923 } else {
2924 0
2925 }
2926 }
2927}
2928
2929#[cfg(feature = "malloc_size_of")]
2930impl<T: MallocSizeOf, const N: usize> MallocSizeOf for SmallVec<T, N> {
2931 fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2932 let mut n = self.shallow_size_of(ops);
2933 for elem in self.iter() {
2934 n += elem.size_of(ops);
2935 }
2936 n
2937 }
2938}
2939
2940#[cfg(feature = "std")]
2941#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
2942impl<const N: usize> io::Write for SmallVec<u8, N> {
2943 #[inline]
2944 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
2945 self.extend_from_slice(buf);
2946 Ok(buf.len())
2947 }
2948
2949 #[inline]
2950 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
2951 self.extend_from_slice(buf);
2952 Ok(())
2953 }
2954
2955 #[inline]
2956 fn flush(&mut self) -> io::Result<()> {
2957 Ok(())
2958 }
2959}
2960
2961#[cfg(feature = "bytes")]
2962unsafe impl<const N: usize> BufMut for SmallVec<u8, N> {
2963 #[inline]
2964 fn remaining_mut(&self) -> usize {
2965 isize::MAX as usize - self.len()
2967 }
2968
2969 #[inline]
2970 unsafe fn advance_mut(&mut self, cnt: usize) {
2971 let len = self.len();
2972 let remaining = self.capacity() - len;
2973
2974 if remaining < cnt {
2975 panic!("advance out of bounds: the len is {remaining} but advancing by {cnt}");
2976 }
2977
2978 self.set_len(len + cnt);
2980 }
2981
2982 #[inline]
2983 fn chunk_mut(&mut self) -> &mut UninitSlice {
2984 if self.capacity() == self.len() {
2985 self.reserve(64); }
2987
2988 let cap = self.capacity();
2989 let len = self.len();
2990
2991 let ptr = self.as_mut_ptr();
2992 unsafe { UninitSlice::from_raw_parts_mut(ptr.add(len), cap - len) }
2996 }
2997
2998 #[inline]
3001 fn put<T: bytes::Buf>(&mut self, mut src: T)
3002 where
3003 Self: Sized,
3004 {
3005 self.reserve(src.remaining());
3007
3008 while src.has_remaining() {
3009 let s = src.chunk();
3010 let l = s.len();
3011 self.extend_from_slice(s);
3012 src.advance(l);
3013 }
3014 }
3015
3016 #[inline]
3017 fn put_slice(&mut self, src: &[u8]) {
3018 self.extend_from_slice(src);
3019 }
3020
3021 #[inline]
3022 fn put_bytes(&mut self, val: u8, cnt: usize) {
3023 let new_len = self.len().saturating_add(cnt);
3025 self.resize(new_len, val);
3026 }
3027}