1#![allow(clippy::pedantic, clippy::all)]
2
3#![cfg_attr(docsrs, feature(doc_cfg))]
100#![deny(missing_docs)]
101
102#[doc(hidden)]
103pub extern crate alloc;
104
105#[cfg(any(test, feature = "write"))]
106extern crate std;
107
108#[allow(deprecated)]
109use alloc::alloc::{Layout, LayoutErr};
110use alloc::boxed::Box;
111use alloc::{vec, vec::Vec};
112use core::borrow::{Borrow, BorrowMut};
113use core::cmp;
114use core::fmt;
115use core::hash::{Hash, Hasher};
116use core::hint::unreachable_unchecked;
117use core::iter::{repeat, FromIterator, FusedIterator, IntoIterator};
118use core::mem;
119use core::mem::MaybeUninit;
120use core::ops::{self, Range, RangeBounds};
121use core::ptr::{self, NonNull};
122use core::slice::{self, SliceIndex};
123
124#[cfg(feature = "write")]
125use std::io;
126
127#[macro_export]
139macro_rules! smallvec {
140 (@one $x:expr) => (1usize);
142 () => (
143 $crate::SmallVec::new()
144 );
145 ($elem:expr; $n:expr) => ({
146 $crate::SmallVec::from_elem($elem, $n)
147 });
148 ($($x:expr),+$(,)?) => ({
149 let count = 0usize $(+ $crate::smallvec!(@one $x))+;
150 let mut vec = $crate::SmallVec::new();
151 if count <= vec.inline_size() {
152 $(vec.push($x);)*
153 vec
154 } else {
155 $crate::SmallVec::from_vec($crate::alloc::vec![$($x,)+])
156 }
157 });
158}
159
160#[derive(Debug)]
162pub enum CollectionAllocErr {
163 CapacityOverflow,
165 AllocErr {
167 layout: Layout,
169 },
170}
171
172impl fmt::Display for CollectionAllocErr {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 write!(f, "Allocation error: {:?}", self)
175 }
176}
177
178#[allow(deprecated)]
179impl From<LayoutErr> for CollectionAllocErr {
180 fn from(_: LayoutErr) -> Self {
181 CollectionAllocErr::CapacityOverflow
182 }
183}
184
185fn infallible<T>(result: Result<T, CollectionAllocErr>) -> T {
186 match result {
187 Ok(x) => x,
188 Err(CollectionAllocErr::CapacityOverflow) => panic!("capacity overflow"),
189 Err(CollectionAllocErr::AllocErr { layout }) => alloc::alloc::handle_alloc_error(layout),
190 }
191}
192
193fn layout_array<T>(n: usize) -> Result<Layout, CollectionAllocErr> {
196 let size = mem::size_of::<T>()
197 .checked_mul(n)
198 .ok_or(CollectionAllocErr::CapacityOverflow)?;
199 let align = mem::align_of::<T>();
200 Layout::from_size_align(size, align).map_err(|_| CollectionAllocErr::CapacityOverflow)
201}
202
203unsafe fn deallocate<T>(ptr: NonNull<T>, capacity: usize) {
204 let layout = layout_array::<T>(capacity).unwrap();
206 unsafe { alloc::alloc::dealloc(ptr.as_ptr() as *mut u8, layout) }
207}
208
209pub struct Drain<'a, T: 'a + Array> {
215 tail_start: usize,
216 tail_len: usize,
217 iter: slice::Iter<'a, T::Item>,
218 vec: NonNull<SmallVec<T>>,
219}
220
221impl<'a, T: 'a + Array> fmt::Debug for Drain<'a, T>
222where
223 T::Item: fmt::Debug,
224{
225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
226 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
227 }
228}
229
230unsafe impl<'a, T: Sync + Array> Sync for Drain<'a, T> {}
231unsafe impl<'a, T: Send + Array> Send for Drain<'a, T> {}
232
233impl<'a, T: 'a + Array> Iterator for Drain<'a, T> {
234 type Item = T::Item;
235
236 #[inline]
237 fn next(&mut self) -> Option<T::Item> {
238 self.iter
239 .next()
240 .map(|reference| unsafe { ptr::read(reference) })
241 }
242
243 #[inline]
244 fn size_hint(&self) -> (usize, Option<usize>) {
245 self.iter.size_hint()
246 }
247}
248
249impl<'a, T: 'a + Array> DoubleEndedIterator for Drain<'a, T> {
250 #[inline]
251 fn next_back(&mut self) -> Option<T::Item> {
252 self.iter
253 .next_back()
254 .map(|reference| unsafe { ptr::read(reference) })
255 }
256}
257
258impl<'a, T: Array> ExactSizeIterator for Drain<'a, T> {
259 #[inline]
260 fn len(&self) -> usize {
261 self.iter.len()
262 }
263}
264
265impl<'a, T: Array> FusedIterator for Drain<'a, T> {}
266
267impl<'a, T: 'a + Array> Drop for Drain<'a, T> {
268 fn drop(&mut self) {
269 self.for_each(drop);
270
271 if self.tail_len > 0 {
272 unsafe {
273 let source_vec = self.vec.as_mut();
274
275 let start = source_vec.len();
277 let tail = self.tail_start;
278 if tail != start {
279 let ptr = source_vec.as_mut_ptr();
282 let src = ptr.add(tail);
283 let dst = ptr.add(start);
284 ptr::copy(src, dst, self.tail_len);
285 }
286 source_vec.set_len(start + self.tail_len);
287 }
288 }
289 }
290}
291
292enum SmallVecData<A: Array> {
293 Inline(MaybeUninit<A>),
294 Heap {
296 ptr: NonNull<A::Item>,
301 len: usize,
302 },
303}
304
305impl<A: Array> SmallVecData<A> {
306 #[inline]
307 unsafe fn inline(&self) -> ConstNonNull<A::Item> {
308 match self {
309 SmallVecData::Inline(a) => ConstNonNull::new(a.as_ptr() as *const A::Item).unwrap(),
310 _ => unreachable!(),
311 }
312 }
313 #[inline]
314 unsafe fn inline_mut(&mut self) -> NonNull<A::Item> {
315 match self {
316 SmallVecData::Inline(a) => NonNull::new(a.as_mut_ptr() as *mut A::Item).unwrap(),
317 _ => unreachable!(),
318 }
319 }
320 #[inline]
321 fn from_inline(inline: MaybeUninit<A>) -> SmallVecData<A> {
322 SmallVecData::Inline(inline)
323 }
324 #[inline]
325 unsafe fn into_inline(self) -> MaybeUninit<A> {
326 match self {
327 SmallVecData::Inline(a) => a,
328 _ => unreachable!(),
329 }
330 }
331 #[inline]
332 unsafe fn heap(&self) -> (ConstNonNull<A::Item>, usize) {
333 match self {
334 SmallVecData::Heap { ptr, len } => (ConstNonNull(*ptr), *len),
335 _ => unreachable!(),
336 }
337 }
338 #[inline]
339 unsafe fn heap_mut(&mut self) -> (NonNull<A::Item>, &mut usize) {
340 match self {
341 SmallVecData::Heap { ptr, len } => (*ptr, len),
342 _ => unreachable!(),
343 }
344 }
345 #[inline]
346 fn from_heap(ptr: NonNull<A::Item>, len: usize) -> SmallVecData<A> {
347 SmallVecData::Heap { ptr, len }
348 }
349}
350
351unsafe impl<A: Array + Send> Send for SmallVecData<A> {}
352unsafe impl<A: Array + Sync> Sync for SmallVecData<A> {}
353
354pub struct SmallVec<A: Array> {
367 capacity: usize,
371 data: SmallVecData<A>,
372}
373
374impl<A: Array> SmallVec<A> {
375 #[inline]
377 pub fn new() -> SmallVec<A> {
378 assert!(
381 mem::size_of::<A>() == A::size() * mem::size_of::<A::Item>()
382 && mem::align_of::<A>() >= mem::align_of::<A::Item>()
383 );
384 SmallVec {
385 capacity: 0,
386 data: SmallVecData::from_inline(MaybeUninit::uninit()),
387 }
388 }
389
390 #[inline]
395 pub fn with_capacity(n: usize) -> Self {
396 let mut v = SmallVec::new();
397 v.reserve_exact(n);
398 v
399 }
400
401 #[inline]
405 pub fn from_vec(mut vec: Vec<A::Item>) -> SmallVec<A> {
406 if vec.capacity() <= Self::inline_capacity() {
407 unsafe {
410 let mut data = SmallVecData::<A>::from_inline(MaybeUninit::uninit());
411 let len = vec.len();
412 vec.set_len(0);
413 ptr::copy_nonoverlapping(vec.as_ptr(), data.inline_mut().as_ptr(), len);
414
415 SmallVec {
416 capacity: len,
417 data,
418 }
419 }
420 } else {
421 let (ptr, cap, len) = (vec.as_mut_ptr(), vec.capacity(), vec.len());
422 mem::forget(vec);
423 let ptr = NonNull::new(ptr)
424 .expect("Cannot be null by `Vec` invariant");
426
427 SmallVec {
428 capacity: cap,
429 data: SmallVecData::from_heap(ptr, len),
430 }
431 }
432 }
433
434 #[inline]
435 pub fn from_buf(buf: A) -> SmallVec<A> {
436 SmallVec {
437 capacity: A::size(),
438 data: SmallVecData::from_inline(MaybeUninit::new(buf)),
439 }
440 }
441
442 #[inline]
447 pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
448 assert!(len <= A::size());
449 unsafe { SmallVec::from_buf_and_len_unchecked(MaybeUninit::new(buf), len) }
450 }
451
452 #[inline]
456 pub unsafe fn from_buf_and_len_unchecked(buf: MaybeUninit<A>, len: usize) -> SmallVec<A> {
457 SmallVec {
458 capacity: len,
459 data: SmallVecData::from_inline(buf),
460 }
461 }
462
463 pub unsafe fn set_len(&mut self, new_len: usize) {
469 let (_, len_ptr, _) = self.triple_mut();
470 *len_ptr = new_len;
471 }
472
473 #[inline]
475 fn inline_capacity() -> usize {
476 if mem::size_of::<A::Item>() > 0 {
477 A::size()
478 } else {
479 core::usize::MAX
490 }
491 }
492
493 #[inline]
495 pub fn inline_size(&self) -> usize {
496 Self::inline_capacity()
497 }
498
499 #[inline]
501 pub fn len(&self) -> usize {
502 self.triple().1
503 }
504
505 #[inline]
507 pub fn is_empty(&self) -> bool {
508 self.len() == 0
509 }
510
511 #[inline]
513 pub fn capacity(&self) -> usize {
514 self.triple().2
515 }
516
517 #[inline]
520 fn triple(&self) -> (ConstNonNull<A::Item>, usize, usize) {
521 unsafe {
522 if self.spilled() {
523 let (ptr, len) = self.data.heap();
524 (ptr, len, self.capacity)
525 } else {
526 (self.data.inline(), self.capacity, Self::inline_capacity())
527 }
528 }
529 }
530
531 #[inline]
533 fn triple_mut(&mut self) -> (NonNull<A::Item>, &mut usize, usize) {
534 unsafe {
535 if self.spilled() {
536 let (ptr, len_ptr) = self.data.heap_mut();
537 (ptr, len_ptr, self.capacity)
538 } else {
539 (
540 self.data.inline_mut(),
541 &mut self.capacity,
542 Self::inline_capacity(),
543 )
544 }
545 }
546 }
547
548 #[inline]
550 pub fn spilled(&self) -> bool {
551 self.capacity > Self::inline_capacity()
552 }
553
554 pub fn drain<R>(&mut self, range: R) -> Drain<'_, A>
568 where
569 R: RangeBounds<usize>,
570 {
571 use core::ops::Bound::*;
572
573 let len = self.len();
574 let start = match range.start_bound() {
575 Included(&n) => n,
576 Excluded(&n) => n.checked_add(1).expect("Range start out of bounds"),
577 Unbounded => 0,
578 };
579 let end = match range.end_bound() {
580 Included(&n) => n.checked_add(1).expect("Range end out of bounds"),
581 Excluded(&n) => n,
582 Unbounded => len,
583 };
584
585 assert!(start <= end);
586 assert!(end <= len);
587
588 unsafe {
589 self.set_len(start);
590
591 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
592
593 Drain {
594 tail_start: end,
595 tail_len: len - end,
596 iter: range_slice.iter(),
597 vec: NonNull::new_unchecked(self as *mut _),
599 }
600 }
601 }
602
603 #[inline]
605 pub fn push(&mut self, value: A::Item) {
606 unsafe {
607 let (mut ptr, mut len, cap) = self.triple_mut();
608 if *len == cap {
609 self.reserve_one_unchecked();
610 let (heap_ptr, heap_len) = self.data.heap_mut();
611 ptr = heap_ptr;
612 len = heap_len;
613 }
614 ptr::write(ptr.as_ptr().add(*len), value);
615 *len += 1;
616 }
617 }
618
619 #[inline]
621 pub fn pop(&mut self) -> Option<A::Item> {
622 unsafe {
623 let (ptr, len_ptr, _) = self.triple_mut();
624 let ptr: *const _ = ptr.as_ptr();
625 if *len_ptr == 0 {
626 return None;
627 }
628 let last_index = *len_ptr - 1;
629 *len_ptr = last_index;
630 Some(ptr::read(ptr.add(last_index)))
631 }
632 }
633
634 pub fn append<B>(&mut self, other: &mut SmallVec<B>)
636 where
637 B: Array<Item = A::Item>,
638 {
639 self.extend(other.drain(..))
640 }
641
642 pub fn grow(&mut self, new_cap: usize) {
647 infallible(self.try_grow(new_cap))
648 }
649
650 pub fn try_grow(&mut self, new_cap: usize) -> Result<(), CollectionAllocErr> {
654 unsafe {
655 let unspilled = !self.spilled();
656 let (ptr, &mut len, cap) = self.triple_mut();
657 assert!(new_cap >= len);
658 if new_cap <= Self::inline_capacity() {
659 if unspilled {
660 return Ok(());
661 }
662 self.data = SmallVecData::from_inline(MaybeUninit::uninit());
663 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
664 self.capacity = len;
665 deallocate(ptr, cap);
666 } else if new_cap != cap {
667 let layout = layout_array::<A::Item>(new_cap)?;
668 debug_assert!(layout.size() > 0);
669 let new_alloc;
670 if unspilled {
671 new_alloc = NonNull::new(alloc::alloc::alloc(layout))
672 .ok_or(CollectionAllocErr::AllocErr { layout })?
673 .cast();
674 ptr::copy_nonoverlapping(ptr.as_ptr(), new_alloc.as_ptr(), len);
675 } else {
676 let old_layout = layout_array::<A::Item>(cap)?;
679
680 let new_ptr =
681 alloc::alloc::realloc(ptr.as_ptr() as *mut u8, old_layout, layout.size());
682 new_alloc = NonNull::new(new_ptr)
683 .ok_or(CollectionAllocErr::AllocErr { layout })?
684 .cast();
685 }
686 self.data = SmallVecData::from_heap(new_alloc, len);
687 self.capacity = new_cap;
688 }
689 Ok(())
690 }
691 }
692
693 #[inline]
699 pub fn reserve(&mut self, additional: usize) {
700 infallible(self.try_reserve(additional))
701 }
702
703 #[cold]
705 fn reserve_one_unchecked(&mut self) {
706 debug_assert_eq!(self.len(), self.capacity());
707 let new_cap = self.len()
708 .checked_add(1)
709 .and_then(usize::checked_next_power_of_two)
710 .expect("capacity overflow");
711 infallible(self.try_grow(new_cap))
712 }
713
714 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
718 let (_, &mut len, cap) = self.triple_mut();
721 if cap - len >= additional {
722 return Ok(());
723 }
724 let new_cap = len
725 .checked_add(additional)
726 .and_then(usize::checked_next_power_of_two)
727 .ok_or(CollectionAllocErr::CapacityOverflow)?;
728 self.try_grow(new_cap)
729 }
730
731 pub fn reserve_exact(&mut self, additional: usize) {
735 infallible(self.try_reserve_exact(additional))
736 }
737
738 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
740 let (_, &mut len, cap) = self.triple_mut();
741 if cap - len >= additional {
742 return Ok(());
743 }
744 let new_cap = len
745 .checked_add(additional)
746 .ok_or(CollectionAllocErr::CapacityOverflow)?;
747 self.try_grow(new_cap)
748 }
749
750 pub fn shrink_to_fit(&mut self) {
755 if !self.spilled() {
756 return;
757 }
758 let len = self.len();
759 if self.inline_size() >= len {
760 unsafe {
761 let (ptr, len) = self.data.heap();
762 self.data = SmallVecData::from_inline(MaybeUninit::uninit());
763 ptr::copy_nonoverlapping(ptr.as_ptr(), self.data.inline_mut().as_ptr(), len);
764 deallocate(ptr.0, self.capacity);
765 self.capacity = len;
766 }
767 } else if self.capacity() > len {
768 self.grow(len);
769 }
770 }
771
772 pub fn truncate(&mut self, len: usize) {
780 unsafe {
781 let (ptr, len_ptr, _) = self.triple_mut();
782 let ptr = ptr.as_ptr();
783 while len < *len_ptr {
784 let last_index = *len_ptr - 1;
785 *len_ptr = last_index;
786 ptr::drop_in_place(ptr.add(last_index));
787 }
788 }
789 }
790
791 pub fn as_slice(&self) -> &[A::Item] {
795 self
796 }
797
798 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
802 self
803 }
804
805 #[inline]
811 pub fn swap_remove(&mut self, index: usize) -> A::Item {
812 let len = self.len();
813 self.swap(len - 1, index);
814 self.pop()
815 .unwrap_or_else(|| unsafe { unreachable_unchecked() })
816 }
817
818 #[inline]
820 pub fn clear(&mut self) {
821 self.truncate(0);
822 }
823
824 pub fn remove(&mut self, index: usize) -> A::Item {
829 unsafe {
830 let (ptr, len_ptr, _) = self.triple_mut();
831 let len = *len_ptr;
832 assert!(index < len);
833 *len_ptr = len - 1;
834 let ptr = ptr.as_ptr().add(index);
835 let item = ptr::read(ptr);
836 ptr::copy(ptr.add(1), ptr, len - index - 1);
837 item
838 }
839 }
840
841 pub fn insert(&mut self, index: usize, element: A::Item) {
845 unsafe {
846 let (mut ptr, mut len_ptr, cap) = self.triple_mut();
847 if *len_ptr == cap {
848 self.reserve_one_unchecked();
849 let (heap_ptr, heap_len_ptr) = self.data.heap_mut();
850 ptr = heap_ptr;
851 len_ptr = heap_len_ptr;
852 }
853 let mut ptr = ptr.as_ptr();
854 let len = *len_ptr;
855 if index > len {
856 panic!("index exceeds length");
857 }
858 ptr = ptr.add(index);
860 if index < len {
861 ptr::copy(ptr, ptr.add(1), len - index);
863 }
864 *len_ptr = len + 1;
865 ptr::write(ptr, element);
866 }
867 }
868
869 pub fn insert_many<I: IntoIterator<Item = A::Item>>(&mut self, index: usize, iterable: I) {
872 let mut iter = iterable.into_iter();
873 if index == self.len() {
874 return self.extend(iter);
875 }
876
877 let (lower_size_bound, _) = iter.size_hint();
878 assert!(lower_size_bound <= core::isize::MAX as usize); assert!(index + lower_size_bound >= index); let mut num_added = 0;
882 let old_len = self.len();
883 assert!(index <= old_len);
884
885 unsafe {
886 self.reserve(lower_size_bound);
888 let start = self.as_mut_ptr();
889 let ptr = start.add(index);
890
891 ptr::copy(ptr, ptr.add(lower_size_bound), old_len - index);
893
894 self.set_len(0);
896 let mut guard = DropOnPanic {
897 start,
898 skip: index..(index + lower_size_bound),
899 len: old_len + lower_size_bound,
900 };
901
902 let start = self.as_mut_ptr();
904 let ptr = start.add(index);
905
906 while num_added < lower_size_bound {
907 let element = match iter.next() {
908 Some(x) => x,
909 None => break,
910 };
911 let cur = ptr.add(num_added);
912 ptr::write(cur, element);
913 guard.skip.start += 1;
914 num_added += 1;
915 }
916
917 if num_added < lower_size_bound {
918 ptr::copy(
920 ptr.add(lower_size_bound),
921 ptr.add(num_added),
922 old_len - index,
923 );
924 }
925 self.set_len(old_len + num_added);
927 mem::forget(guard);
928 }
929
930 for element in iter {
932 self.insert(index + num_added, element);
933 num_added += 1;
934 }
935
936 struct DropOnPanic<T> {
937 start: *mut T,
938 skip: Range<usize>, len: usize,
940 }
941
942 impl<T> Drop for DropOnPanic<T> {
943 fn drop(&mut self) {
944 for i in 0..self.len {
945 if !self.skip.contains(&i) {
946 unsafe {
947 ptr::drop_in_place(self.start.add(i));
948 }
949 }
950 }
951 }
952 }
953 }
954
955 pub fn into_vec(mut self) -> Vec<A::Item> {
958 if self.spilled() {
959 unsafe {
960 let (ptr, &mut len) = self.data.heap_mut();
961 let v = Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity);
962 mem::forget(self);
963 v
964 }
965 } else {
966 self.into_iter().collect()
967 }
968 }
969
970 pub fn into_boxed_slice(self) -> Box<[A::Item]> {
975 self.into_vec().into_boxed_slice()
976 }
977
978 pub fn into_inner(self) -> Result<A, Self> {
983 if self.spilled() || self.len() != A::size() {
984 Err(self)
986 } else {
987 unsafe {
988 let data = ptr::read(&self.data);
989 mem::forget(self);
990 Ok(data.into_inline().assume_init())
991 }
992 }
993 }
994
995 pub fn retain<F: FnMut(&mut A::Item) -> bool>(&mut self, mut f: F) {
1001 let mut del = 0;
1002 let len = self.len();
1003 for i in 0..len {
1004 if !f(&mut self[i]) {
1005 del += 1;
1006 } else if del > 0 {
1007 self.swap(i - del, i);
1008 }
1009 }
1010 self.truncate(len - del);
1011 }
1012
1013 pub fn retain_mut<F: FnMut(&mut A::Item) -> bool>(&mut self, f: F) {
1019 self.retain(f)
1020 }
1021
1022 pub fn dedup(&mut self)
1024 where
1025 A::Item: PartialEq<A::Item>,
1026 {
1027 self.dedup_by(|a, b| a == b);
1028 }
1029
1030 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1032 where
1033 F: FnMut(&mut A::Item, &mut A::Item) -> bool,
1034 {
1035 let len = self.len();
1038 if len <= 1 {
1039 return;
1040 }
1041
1042 let ptr = self.as_mut_ptr();
1043 let mut w: usize = 1;
1044
1045 unsafe {
1046 for r in 1..len {
1047 let p_r = ptr.add(r);
1048 let p_wm1 = ptr.add(w - 1);
1049 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1050 if r != w {
1051 let p_w = p_wm1.add(1);
1052 mem::swap(&mut *p_r, &mut *p_w);
1053 }
1054 w += 1;
1055 }
1056 }
1057 }
1058
1059 self.truncate(w);
1060 }
1061
1062 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1064 where
1065 F: FnMut(&mut A::Item) -> K,
1066 K: PartialEq<K>,
1067 {
1068 self.dedup_by(|a, b| key(a) == key(b));
1069 }
1070
1071 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1085 where
1086 F: FnMut() -> A::Item,
1087 {
1088 let old_len = self.len();
1089 if old_len < new_len {
1090 let mut f = f;
1091 let additional = new_len - old_len;
1092 self.reserve(additional);
1093 for _ in 0..additional {
1094 self.push(f());
1095 }
1096 } else if old_len > new_len {
1097 self.truncate(new_len);
1098 }
1099 }
1100
1101 #[inline]
1131 pub unsafe fn from_raw_parts(ptr: *mut A::Item, length: usize, capacity: usize) -> SmallVec<A> {
1132 let ptr = unsafe {
1135 debug_assert!(!ptr.is_null(), "Called `from_raw_parts` with null pointer.");
1136 NonNull::new_unchecked(ptr)
1137 };
1138 assert!(capacity > Self::inline_capacity());
1139 SmallVec {
1140 capacity,
1141 data: SmallVecData::from_heap(ptr, length),
1142 }
1143 }
1144
1145 pub fn as_ptr(&self) -> *const A::Item {
1147 self.triple().0.as_ptr()
1151 }
1152
1153 pub fn as_mut_ptr(&mut self) -> *mut A::Item {
1155 self.triple_mut().0.as_ptr()
1159 }
1160}
1161
1162impl<A: Array> SmallVec<A>
1163where
1164 A::Item: Copy,
1165{
1166 pub fn from_slice(slice: &[A::Item]) -> Self {
1170 let len = slice.len();
1171 if len <= Self::inline_capacity() {
1172 SmallVec {
1173 capacity: len,
1174 data: SmallVecData::from_inline(unsafe {
1175 let mut data: MaybeUninit<A> = MaybeUninit::uninit();
1176 ptr::copy_nonoverlapping(
1177 slice.as_ptr(),
1178 data.as_mut_ptr() as *mut A::Item,
1179 len,
1180 );
1181 data
1182 }),
1183 }
1184 } else {
1185 let mut b = slice.to_vec();
1186 let cap = b.capacity();
1187 let ptr = NonNull::new(b.as_mut_ptr()).expect("Vec always contain non null pointers.");
1188 mem::forget(b);
1189 SmallVec {
1190 capacity: cap,
1191 data: SmallVecData::from_heap(ptr, len),
1192 }
1193 }
1194 }
1195
1196 #[inline]
1201 pub fn insert_from_slice(&mut self, index: usize, slice: &[A::Item]) {
1202 self.reserve(slice.len());
1203
1204 let len = self.len();
1205 assert!(index <= len);
1206
1207 unsafe {
1208 let slice_ptr = slice.as_ptr();
1209 let ptr = self.as_mut_ptr().add(index);
1210 ptr::copy(ptr, ptr.add(slice.len()), len - index);
1211 ptr::copy_nonoverlapping(slice_ptr, ptr, slice.len());
1212 self.set_len(len + slice.len());
1213 }
1214 }
1215
1216 #[inline]
1220 pub fn extend_from_slice(&mut self, slice: &[A::Item]) {
1221 let len = self.len();
1222 self.insert_from_slice(len, slice);
1223 }
1224}
1225
1226impl<A: Array> SmallVec<A>
1227where
1228 A::Item: Clone,
1229{
1230 pub fn resize(&mut self, len: usize, value: A::Item) {
1237 let old_len = self.len();
1238
1239 if len > old_len {
1240 self.extend(repeat(value).take(len - old_len));
1241 } else {
1242 self.truncate(len);
1243 }
1244 }
1245
1246 pub fn from_elem(elem: A::Item, n: usize) -> Self {
1248 if n > Self::inline_capacity() {
1249 vec![elem; n].into()
1250 } else {
1251 let mut v = SmallVec::<A>::new();
1252 unsafe {
1253 let (ptr, len_ptr, _) = v.triple_mut();
1254 let ptr = ptr.as_ptr();
1255 let mut local_len = SetLenOnDrop::new(len_ptr);
1256
1257 for i in 0..n {
1258 ::core::ptr::write(ptr.add(i), elem.clone());
1259 local_len.increment_len(1);
1260 }
1261 }
1262 v
1263 }
1264 }
1265}
1266
1267impl<A: Array> ops::Deref for SmallVec<A> {
1268 type Target = [A::Item];
1269 #[inline]
1270 fn deref(&self) -> &[A::Item] {
1271 unsafe {
1272 let (ptr, len, _) = self.triple();
1273 slice::from_raw_parts(ptr.as_ptr(), len)
1274 }
1275 }
1276}
1277
1278impl<A: Array> ops::DerefMut for SmallVec<A> {
1279 #[inline]
1280 fn deref_mut(&mut self) -> &mut [A::Item] {
1281 unsafe {
1282 let (ptr, &mut len, _) = self.triple_mut();
1283 slice::from_raw_parts_mut(ptr.as_ptr(), len)
1284 }
1285 }
1286}
1287
1288impl<A: Array> AsRef<[A::Item]> for SmallVec<A> {
1289 #[inline]
1290 fn as_ref(&self) -> &[A::Item] {
1291 self
1292 }
1293}
1294
1295impl<A: Array> AsMut<[A::Item]> for SmallVec<A> {
1296 #[inline]
1297 fn as_mut(&mut self) -> &mut [A::Item] {
1298 self
1299 }
1300}
1301
1302impl<A: Array> Borrow<[A::Item]> for SmallVec<A> {
1303 #[inline]
1304 fn borrow(&self) -> &[A::Item] {
1305 self
1306 }
1307}
1308
1309impl<A: Array> BorrowMut<[A::Item]> for SmallVec<A> {
1310 #[inline]
1311 fn borrow_mut(&mut self) -> &mut [A::Item] {
1312 self
1313 }
1314}
1315
1316#[cfg(feature = "write")]
1317impl<A: Array<Item = u8>> io::Write for SmallVec<A> {
1318 #[inline]
1319 fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
1320 self.extend_from_slice(buf);
1321 Ok(buf.len())
1322 }
1323
1324 #[inline]
1325 fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
1326 self.extend_from_slice(buf);
1327 Ok(())
1328 }
1329
1330 #[inline]
1331 fn flush(&mut self) -> io::Result<()> {
1332 Ok(())
1333 }
1334}
1335
1336impl<'a, A: Array> From<&'a [A::Item]> for SmallVec<A>
1337where
1338 A::Item: Clone,
1339{
1340 #[inline]
1341 fn from(slice: &'a [A::Item]) -> SmallVec<A> {
1342 slice.iter().cloned().collect()
1343 }
1344}
1345
1346impl<A: Array> From<Vec<A::Item>> for SmallVec<A> {
1347 #[inline]
1348 fn from(vec: Vec<A::Item>) -> SmallVec<A> {
1349 SmallVec::from_vec(vec)
1350 }
1351}
1352
1353impl<A: Array> From<A> for SmallVec<A> {
1354 #[inline]
1355 fn from(array: A) -> SmallVec<A> {
1356 SmallVec::from_buf(array)
1357 }
1358}
1359
1360impl<A: Array, I: SliceIndex<[A::Item]>> ops::Index<I> for SmallVec<A> {
1361 type Output = I::Output;
1362
1363 fn index(&self, index: I) -> &I::Output {
1364 &(**self)[index]
1365 }
1366}
1367
1368impl<A: Array, I: SliceIndex<[A::Item]>> ops::IndexMut<I> for SmallVec<A> {
1369 fn index_mut(&mut self, index: I) -> &mut I::Output {
1370 &mut (&mut **self)[index]
1371 }
1372}
1373
1374impl<A: Array> FromIterator<A::Item> for SmallVec<A> {
1375 #[inline]
1376 fn from_iter<I: IntoIterator<Item = A::Item>>(iterable: I) -> SmallVec<A> {
1377 let mut v = SmallVec::new();
1378 v.extend(iterable);
1379 v
1380 }
1381}
1382
1383impl<A: Array> Extend<A::Item> for SmallVec<A> {
1384 fn extend<I: IntoIterator<Item = A::Item>>(&mut self, iterable: I) {
1385 let mut iter = iterable.into_iter();
1386 let (lower_size_bound, _) = iter.size_hint();
1387 self.reserve(lower_size_bound);
1388
1389 unsafe {
1390 let (ptr, len_ptr, cap) = self.triple_mut();
1391 let ptr = ptr.as_ptr();
1392 let mut len = SetLenOnDrop::new(len_ptr);
1393 while len.get() < cap {
1394 if let Some(out) = iter.next() {
1395 ptr::write(ptr.add(len.get()), out);
1396 len.increment_len(1);
1397 } else {
1398 return;
1399 }
1400 }
1401 }
1402
1403 for elem in iter {
1404 self.push(elem);
1405 }
1406 }
1407}
1408
1409impl<A: Array> fmt::Debug for SmallVec<A>
1410where
1411 A::Item: fmt::Debug,
1412{
1413 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1414 f.debug_list().entries(self.iter()).finish()
1415 }
1416}
1417
1418impl<A: Array> Default for SmallVec<A> {
1419 #[inline]
1420 fn default() -> SmallVec<A> {
1421 SmallVec::new()
1422 }
1423}
1424
1425impl<A: Array> Drop for SmallVec<A> {
1426 fn drop(&mut self) {
1427 unsafe {
1428 if self.spilled() {
1429 let (ptr, &mut len) = self.data.heap_mut();
1430 drop(Vec::from_raw_parts(ptr.as_ptr(), len, self.capacity));
1431 } else {
1432 ptr::drop_in_place(&mut self[..]);
1433 }
1434 }
1435 }
1436}
1437
1438impl<A: Array> Clone for SmallVec<A>
1439where
1440 A::Item: Clone,
1441{
1442 #[inline]
1443 fn clone(&self) -> SmallVec<A> {
1444 SmallVec::from(self.as_slice())
1445 }
1446
1447 fn clone_from(&mut self, source: &Self) {
1448 self.truncate(source.len());
1452
1453 let (init, tail) = source.split_at(self.len());
1456
1457 self.clone_from_slice(init);
1459 self.extend(tail.iter().cloned());
1460 }
1461}
1462
1463impl<A: Array, B: Array> PartialEq<SmallVec<B>> for SmallVec<A>
1464where
1465 A::Item: PartialEq<B::Item>,
1466{
1467 #[inline]
1468 fn eq(&self, other: &SmallVec<B>) -> bool {
1469 self[..] == other[..]
1470 }
1471}
1472
1473impl<A: Array> Eq for SmallVec<A> where A::Item: Eq {}
1474
1475impl<A: Array> PartialOrd for SmallVec<A>
1476where
1477 A::Item: PartialOrd,
1478{
1479 #[inline]
1480 fn partial_cmp(&self, other: &SmallVec<A>) -> Option<cmp::Ordering> {
1481 PartialOrd::partial_cmp(&**self, &**other)
1482 }
1483}
1484
1485impl<A: Array> Ord for SmallVec<A>
1486where
1487 A::Item: Ord,
1488{
1489 #[inline]
1490 fn cmp(&self, other: &SmallVec<A>) -> cmp::Ordering {
1491 Ord::cmp(&**self, &**other)
1492 }
1493}
1494
1495impl<A: Array> Hash for SmallVec<A>
1496where
1497 A::Item: Hash,
1498{
1499 fn hash<H: Hasher>(&self, state: &mut H) {
1500 (**self).hash(state)
1501 }
1502}
1503
1504unsafe impl<A: Array> Send for SmallVec<A> where A::Item: Send {}
1505
1506pub struct IntoIter<A: Array> {
1512 data: SmallVec<A>,
1513 current: usize,
1514 end: usize,
1515}
1516
1517impl<A: Array> fmt::Debug for IntoIter<A>
1518where
1519 A::Item: fmt::Debug,
1520{
1521 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1522 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
1523 }
1524}
1525
1526impl<A: Array + Clone> Clone for IntoIter<A>
1527where
1528 A::Item: Clone,
1529{
1530 fn clone(&self) -> IntoIter<A> {
1531 SmallVec::from(self.as_slice()).into_iter()
1532 }
1533}
1534
1535impl<A: Array> Drop for IntoIter<A> {
1536 fn drop(&mut self) {
1537 for _ in self {}
1538 }
1539}
1540
1541impl<A: Array> Iterator for IntoIter<A> {
1542 type Item = A::Item;
1543
1544 #[inline]
1545 fn next(&mut self) -> Option<A::Item> {
1546 if self.current == self.end {
1547 None
1548 } else {
1549 unsafe {
1550 let current = self.current;
1551 self.current += 1;
1552 Some(ptr::read(self.data.as_ptr().add(current)))
1553 }
1554 }
1555 }
1556
1557 #[inline]
1558 fn size_hint(&self) -> (usize, Option<usize>) {
1559 let size = self.end - self.current;
1560 (size, Some(size))
1561 }
1562}
1563
1564impl<A: Array> DoubleEndedIterator for IntoIter<A> {
1565 #[inline]
1566 fn next_back(&mut self) -> Option<A::Item> {
1567 if self.current == self.end {
1568 None
1569 } else {
1570 unsafe {
1571 self.end -= 1;
1572 Some(ptr::read(self.data.as_ptr().add(self.end)))
1573 }
1574 }
1575 }
1576}
1577
1578impl<A: Array> ExactSizeIterator for IntoIter<A> {}
1579impl<A: Array> FusedIterator for IntoIter<A> {}
1580
1581impl<A: Array> IntoIter<A> {
1582 pub fn as_slice(&self) -> &[A::Item] {
1584 let len = self.end - self.current;
1585 unsafe { core::slice::from_raw_parts(self.data.as_ptr().add(self.current), len) }
1586 }
1587
1588 pub fn as_mut_slice(&mut self) -> &mut [A::Item] {
1590 let len = self.end - self.current;
1591 unsafe { core::slice::from_raw_parts_mut(self.data.as_mut_ptr().add(self.current), len) }
1592 }
1593}
1594
1595impl<A: Array> IntoIterator for SmallVec<A> {
1596 type IntoIter = IntoIter<A>;
1597 type Item = A::Item;
1598 fn into_iter(mut self) -> Self::IntoIter {
1599 unsafe {
1600 let len = self.len();
1602 self.set_len(0);
1603 IntoIter {
1604 data: self,
1605 current: 0,
1606 end: len,
1607 }
1608 }
1609 }
1610}
1611
1612impl<'a, A: Array> IntoIterator for &'a SmallVec<A> {
1613 type IntoIter = slice::Iter<'a, A::Item>;
1614 type Item = &'a A::Item;
1615 fn into_iter(self) -> Self::IntoIter {
1616 self.iter()
1617 }
1618}
1619
1620impl<'a, A: Array> IntoIterator for &'a mut SmallVec<A> {
1621 type IntoIter = slice::IterMut<'a, A::Item>;
1622 type Item = &'a mut A::Item;
1623 fn into_iter(self) -> Self::IntoIter {
1624 self.iter_mut()
1625 }
1626}
1627
1628pub unsafe trait Array {
1630 type Item;
1632 fn size() -> usize;
1634}
1635
1636struct SetLenOnDrop<'a> {
1640 len: &'a mut usize,
1641 local_len: usize,
1642}
1643
1644impl<'a> SetLenOnDrop<'a> {
1645 #[inline]
1646 fn new(len: &'a mut usize) -> Self {
1647 SetLenOnDrop {
1648 local_len: *len,
1649 len,
1650 }
1651 }
1652
1653 #[inline]
1654 fn get(&self) -> usize {
1655 self.local_len
1656 }
1657
1658 #[inline]
1659 fn increment_len(&mut self, increment: usize) {
1660 self.local_len += increment;
1661 }
1662}
1663
1664impl<'a> Drop for SetLenOnDrop<'a> {
1665 #[inline]
1666 fn drop(&mut self) {
1667 *self.len = self.local_len;
1668 }
1669}
1670
1671unsafe impl<T, const N: usize> Array for [T; N] {
1672 type Item = T;
1673 #[inline]
1674 fn size() -> usize {
1675 N
1676 }
1677}
1678
1679#[repr(transparent)]
1681struct ConstNonNull<T>(NonNull<T>);
1682
1683impl<T> ConstNonNull<T> {
1684 #[inline]
1685 fn new(ptr: *const T) -> Option<Self> {
1686 NonNull::new(ptr as *mut T).map(Self)
1687 }
1688 #[inline]
1689 fn as_ptr(self) -> *const T {
1690 self.0.as_ptr()
1691 }
1692}
1693
1694impl<T> Clone for ConstNonNull<T> {
1695 #[inline]
1696 fn clone(&self) -> Self {
1697 *self
1698 }
1699}
1700
1701impl<T> Copy for ConstNonNull<T> {}