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