1 use core::alloc::{Allocator, Layout};
2 use core::iter::IntoIterator;
3 use core::ptr::NonNull;
4 use std::alloc::System;
5 use std::assert_matches::assert_matches;
8 use std::collections::TryReserveErrorKind::*;
10 use std::iter::InPlaceIterable;
11 use std::mem::{size_of, swap};
12 use std::ops::Bound::*;
13 use std::panic::{catch_unwind, AssertUnwindSafe};
15 use std::sync::atomic::{AtomicU32, Ordering};
16 use std::vec::{Drain, IntoIter};
18 struct DropCounter<'a> {
22 impl Drop for DropCounter<'_> {
29 fn test_small_vec_struct() {
30 assert_eq!(size_of::<Vec<u8>>(), size_of::<usize>() * 3);
34 fn test_double_drop() {
40 let (mut count_x, mut count_y) = (0, 0);
42 let mut tv = TwoVec { x: Vec::new(), y: Vec::new() };
43 tv.x.push(DropCounter { count: &mut count_x });
44 tv.y.push(DropCounter { count: &mut count_y });
46 // If Vec had a drop flag, here is where it would be zeroed.
47 // Instead, it should rely on its internal state to prevent
48 // doing anything significant when dropped multiple times.
51 // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
54 assert_eq!(count_x, 1);
55 assert_eq!(count_y, 1);
60 let mut v = Vec::new();
61 assert_eq!(v.capacity(), 0);
64 assert!(v.capacity() >= 2);
70 assert!(v.capacity() >= 16);
72 assert!(v.capacity() >= 32);
77 assert!(v.capacity() >= 33)
81 fn test_zst_capacity() {
82 assert_eq!(Vec::<()>::new().capacity(), usize::MAX);
87 let v: Vec<isize> = vec![10, 20];
92 assert_eq!(v[x + 1], 20);
95 assert_eq!(v[x - 1], 10);
100 let vec1: Vec<isize> = vec![];
101 assert_eq!("[]", format!("{:?}", vec1));
103 let vec2 = vec![0, 1];
104 assert_eq!("[0, 1]", format!("{:?}", vec2));
106 let slice: &[isize] = &[4, 5];
107 assert_eq!("[4, 5]", format!("{slice:?}"));
116 assert_eq!(v, [1, 2]);
118 assert_eq!(v, [1, 2, 3]);
123 let mut v = Vec::new();
124 let mut w = Vec::new();
143 v.extend(w.clone()); // specializes to `append`
144 assert!(v.iter().eq(w.iter().chain(w.iter())));
147 #[derive(PartialEq, Debug)]
150 let mut a = Vec::new();
151 let b = vec![Foo, Foo];
154 assert_eq!(a, &[Foo, Foo]);
159 let mut x = Vec::new();
160 let y = vec![DropCounter { count: &mut count_x }];
163 assert_eq!(count_x, 1);
167 fn test_extend_from_slice() {
168 let a: Vec<isize> = vec![1, 2, 3, 4, 5];
169 let b: Vec<isize> = vec![6, 7, 8, 9, 0];
171 let mut v: Vec<isize> = a;
173 v.extend_from_slice(&b);
175 assert_eq!(v, [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]);
179 fn test_extend_ref() {
180 let mut v = vec![1, 2];
181 v.extend(&[3, 4, 5]);
183 assert_eq!(v.len(), 5);
184 assert_eq!(v, [1, 2, 3, 4, 5]);
189 assert_eq!(v.len(), 7);
190 assert_eq!(v, [1, 2, 3, 4, 5, 6, 7]);
194 fn test_slice_from_ref() {
195 let values = vec![1, 2, 3, 4, 5];
196 let slice = &values[1..3];
198 assert_eq!(slice, [2, 3]);
202 fn test_slice_from_mut() {
203 let mut values = vec![1, 2, 3, 4, 5];
205 let slice = &mut values[2..];
206 assert!(slice == [3, 4, 5]);
212 assert!(values == [1, 2, 5, 6, 7]);
216 fn test_slice_to_mut() {
217 let mut values = vec![1, 2, 3, 4, 5];
219 let slice = &mut values[..2];
220 assert!(slice == [1, 2]);
226 assert!(values == [2, 3, 3, 4, 5]);
230 fn test_split_at_mut() {
231 let mut values = vec![1, 2, 3, 4, 5];
233 let (left, right) = values.split_at_mut(2);
235 let left: &[_] = left;
236 assert!(&left[..left.len()] == &[1, 2]);
243 let right: &[_] = right;
244 assert!(&right[..right.len()] == &[3, 4, 5]);
251 assert_eq!(values, [2, 3, 5, 6, 7]);
256 let v: Vec<i32> = vec![];
257 let w = vec![1, 2, 3];
259 assert_eq!(v, v.clone());
263 // they should be disjoint in memory.
264 assert!(w.as_ptr() != z.as_ptr())
268 fn test_clone_from() {
270 let three: Vec<Box<_>> = vec![Box::new(1), Box::new(2), Box::new(3)];
271 let two: Vec<Box<_>> = vec![Box::new(4), Box::new(5)];
273 v.clone_from(&three);
274 assert_eq!(v, three);
277 v.clone_from(&three);
278 assert_eq!(v, three);
285 v.clone_from(&three);
291 let mut vec = vec![1, 2, 3, 4];
292 vec.retain(|&x| x % 2 == 0);
293 assert_eq!(vec, [2, 4]);
297 fn test_retain_predicate_order() {
298 for to_keep in [true, false] {
299 let mut number_of_executions = 0;
300 let mut vec = vec![1, 2, 3, 4];
301 let mut next_expected = 1;
303 assert_eq!(next_expected, x);
305 number_of_executions += 1;
308 assert_eq!(number_of_executions, 4);
313 fn test_retain_pred_panic_with_hole() {
314 let v = (0..5).map(Rc::new).collect::<Vec<_>>();
315 catch_unwind(AssertUnwindSafe(|| {
316 let mut v = v.clone();
317 v.retain(|r| match **r {
325 // Everything is dropped when predicate panicked.
326 assert!(v.iter().all(|r| Rc::strong_count(r) == 1));
330 fn test_retain_pred_panic_no_hole() {
331 let v = (0..5).map(Rc::new).collect::<Vec<_>>();
332 catch_unwind(AssertUnwindSafe(|| {
333 let mut v = v.clone();
334 v.retain(|r| match **r {
340 // Everything is dropped when predicate panicked.
341 assert!(v.iter().all(|r| Rc::strong_count(r) == 1));
345 fn test_retain_drop_panic() {
346 struct Wrap(Rc<i32>);
356 let v = (0..5).map(|x| Rc::new(x)).collect::<Vec<_>>();
357 catch_unwind(AssertUnwindSafe(|| {
358 let mut v = v.iter().map(|r| Wrap(r.clone())).collect::<Vec<_>>();
359 v.retain(|w| match *w.0 {
363 3 => false, // Drop panic.
368 // Other elements are dropped when `drop` of one element panicked.
369 // The panicked wrapper also has its Rc dropped.
370 assert!(v.iter().all(|r| Rc::strong_count(r) == 1));
374 fn test_retain_maybeuninits() {
375 // This test aimed to be run under miri.
376 use core::mem::MaybeUninit;
377 let mut vec: Vec<_> = [1i32, 2, 3, 4].map(|v| MaybeUninit::new(vec![v])).into();
379 // SAFETY: Retain must visit every element of Vec in original order and exactly once.
380 // Our values is initialized at creation of Vec.
381 let v = unsafe { x.assume_init_ref()[0] };
385 // SAFETY: Value is initialized.
386 // Value wouldn't be dropped by `Vec::retain`
387 // because `MaybeUninit` doesn't drop content.
388 drop(unsafe { x.assume_init_read() });
391 let vec: Vec<i32> = vec
394 // SAFETY: All values dropped in retain predicate must be removed by `Vec::retain`.
395 // Remaining values are initialized.
399 assert_eq!(vec, [2, 4]);
404 fn case(a: Vec<i32>, b: Vec<i32>) {
409 case(vec![], vec![]);
410 case(vec![1], vec![1]);
411 case(vec![1, 1], vec![1]);
412 case(vec![1, 2, 3], vec![1, 2, 3]);
413 case(vec![1, 1, 2, 3], vec![1, 2, 3]);
414 case(vec![1, 2, 2, 3], vec![1, 2, 3]);
415 case(vec![1, 2, 3, 3], vec![1, 2, 3]);
416 case(vec![1, 1, 2, 2, 2, 3, 3], vec![1, 2, 3]);
420 fn test_dedup_by_key() {
421 fn case(a: Vec<i32>, b: Vec<i32>) {
423 v.dedup_by_key(|i| *i / 10);
426 case(vec![], vec![]);
427 case(vec![10], vec![10]);
428 case(vec![10, 11], vec![10]);
429 case(vec![10, 20, 30], vec![10, 20, 30]);
430 case(vec![10, 11, 20, 30], vec![10, 20, 30]);
431 case(vec![10, 20, 21, 30], vec![10, 20, 30]);
432 case(vec![10, 20, 30, 31], vec![10, 20, 30]);
433 case(vec![10, 11, 20, 21, 22, 30, 31], vec![10, 20, 30]);
438 let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
439 vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
441 assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
443 let mut vec = vec![("foo", 1), ("foo", 2), ("bar", 3), ("bar", 4), ("bar", 5)];
444 vec.dedup_by(|a, b| {
451 assert_eq!(vec, [("foo", 3), ("bar", 12)]);
455 fn test_dedup_unique() {
456 let mut v0: Vec<Box<_>> = vec![Box::new(1), Box::new(1), Box::new(2), Box::new(3)];
458 let mut v1: Vec<Box<_>> = vec![Box::new(1), Box::new(2), Box::new(2), Box::new(3)];
460 let mut v2: Vec<Box<_>> = vec![Box::new(1), Box::new(2), Box::new(3), Box::new(3)];
462 // If the boxed pointers were leaked or otherwise misused, valgrind
463 // and/or rt should raise errors.
467 fn zero_sized_values() {
468 let mut v = Vec::new();
469 assert_eq!(v.len(), 0);
471 assert_eq!(v.len(), 1);
473 assert_eq!(v.len(), 2);
474 assert_eq!(v.pop(), Some(()));
475 assert_eq!(v.pop(), Some(()));
476 assert_eq!(v.pop(), None);
478 assert_eq!(v.iter().count(), 0);
480 assert_eq!(v.iter().count(), 1);
482 assert_eq!(v.iter().count(), 2);
486 assert_eq!(v.iter_mut().count(), 2);
488 assert_eq!(v.iter_mut().count(), 3);
490 assert_eq!(v.iter_mut().count(), 4);
492 for &mut () in &mut v {}
496 assert_eq!(v.iter_mut().count(), 0);
500 fn test_partition() {
501 assert_eq!([].into_iter().partition(|x: &i32| *x < 3), (vec![], vec![]));
502 assert_eq!([1, 2, 3].into_iter().partition(|x| *x < 4), (vec![1, 2, 3], vec![]));
503 assert_eq!([1, 2, 3].into_iter().partition(|x| *x < 2), (vec![1], vec![2, 3]));
504 assert_eq!([1, 2, 3].into_iter().partition(|x| *x < 0), (vec![], vec![1, 2, 3]));
508 fn test_zip_unzip() {
509 let z1 = vec![(1, 4), (2, 5), (3, 6)];
511 let (left, right): (Vec<_>, Vec<_>) = z1.iter().cloned().unzip();
513 assert_eq!((1, 4), (left[0], right[0]));
514 assert_eq!((2, 5), (left[1], right[1]));
515 assert_eq!((3, 6), (left[2], right[2]));
520 let x: &[isize] = &[1, 2, 3, 4, 5];
521 let cmp: &[isize] = &[1, 2, 3, 4, 5];
522 assert_eq!(&x[..], cmp);
523 let cmp: &[isize] = &[3, 4, 5];
524 assert_eq!(&x[2..], cmp);
525 let cmp: &[isize] = &[1, 2, 3];
526 assert_eq!(&x[..3], cmp);
527 let cmp: &[isize] = &[2, 3, 4];
528 assert_eq!(&x[1..4], cmp);
530 let x: Vec<isize> = vec![1, 2, 3, 4, 5];
531 let cmp: &[isize] = &[1, 2, 3, 4, 5];
532 assert_eq!(&x[..], cmp);
533 let cmp: &[isize] = &[3, 4, 5];
534 assert_eq!(&x[2..], cmp);
535 let cmp: &[isize] = &[1, 2, 3];
536 assert_eq!(&x[..3], cmp);
537 let cmp: &[isize] = &[2, 3, 4];
538 assert_eq!(&x[1..4], cmp);
542 fn test_vec_truncate_drop() {
543 static mut DROPS: u32 = 0;
553 let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
554 assert_eq!(unsafe { DROPS }, 0);
556 assert_eq!(unsafe { DROPS }, 2);
558 assert_eq!(unsafe { DROPS }, 5);
563 fn test_vec_truncate_fail() {
565 impl Drop for BadElem {
567 let BadElem(ref mut x) = *self;
569 panic!("BadElem panic: 0xbadbeef")
574 let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
580 let vec = vec![1, 2, 3];
581 assert!(vec[1] == 2);
586 fn test_index_out_of_bounds() {
587 let vec = vec![1, 2, 3];
593 fn test_slice_out_of_bounds_1() {
594 let x = vec![1, 2, 3, 4, 5];
600 fn test_slice_out_of_bounds_2() {
601 let x = vec![1, 2, 3, 4, 5];
607 fn test_slice_out_of_bounds_3() {
608 let x = vec![1, 2, 3, 4, 5];
614 fn test_slice_out_of_bounds_4() {
615 let x = vec![1, 2, 3, 4, 5];
621 fn test_slice_out_of_bounds_5() {
622 let x = vec![1, 2, 3, 4, 5];
628 fn test_swap_remove_empty() {
629 let mut vec = Vec::<i32>::new();
634 fn test_move_items() {
635 let vec = vec![1, 2, 3];
636 let mut vec2 = vec![];
640 assert_eq!(vec2, [1, 2, 3]);
644 fn test_move_items_reverse() {
645 let vec = vec![1, 2, 3];
646 let mut vec2 = vec![];
647 for i in vec.into_iter().rev() {
650 assert_eq!(vec2, [3, 2, 1]);
654 fn test_move_items_zero_sized() {
655 let vec = vec![(), (), ()];
656 let mut vec2 = vec![];
660 assert_eq!(vec2, [(), (), ()]);
664 fn test_drain_empty_vec() {
665 let mut vec: Vec<i32> = vec![];
666 let mut vec2: Vec<i32> = vec![];
667 for i in vec.drain(..) {
670 assert!(vec.is_empty());
671 assert!(vec2.is_empty());
675 fn test_drain_items() {
676 let mut vec = vec![1, 2, 3];
677 let mut vec2 = vec![];
678 for i in vec.drain(..) {
682 assert_eq!(vec2, [1, 2, 3]);
686 fn test_drain_items_reverse() {
687 let mut vec = vec![1, 2, 3];
688 let mut vec2 = vec![];
689 for i in vec.drain(..).rev() {
693 assert_eq!(vec2, [3, 2, 1]);
697 fn test_drain_items_zero_sized() {
698 let mut vec = vec![(), (), ()];
699 let mut vec2 = vec![];
700 for i in vec.drain(..) {
704 assert_eq!(vec2, [(), (), ()]);
709 fn test_drain_out_of_bounds() {
710 let mut v = vec![1, 2, 3, 4, 5];
715 fn test_drain_range() {
716 let mut v = vec![1, 2, 3, 4, 5];
717 for _ in v.drain(4..) {}
718 assert_eq!(v, &[1, 2, 3, 4]);
720 let mut v: Vec<_> = (1..6).map(|x| x.to_string()).collect();
721 for _ in v.drain(1..4) {}
722 assert_eq!(v, &[1.to_string(), 5.to_string()]);
724 let mut v: Vec<_> = (1..6).map(|x| x.to_string()).collect();
725 for _ in v.drain(1..4).rev() {}
726 assert_eq!(v, &[1.to_string(), 5.to_string()]);
728 let mut v: Vec<_> = vec![(); 5];
729 for _ in v.drain(1..4).rev() {}
730 assert_eq!(v, &[(), ()]);
734 fn test_drain_inclusive_range() {
735 let mut v = vec!['a', 'b', 'c', 'd', 'e'];
736 for _ in v.drain(1..=3) {}
737 assert_eq!(v, &['a', 'e']);
739 let mut v: Vec<_> = (0..=5).map(|x| x.to_string()).collect();
740 for _ in v.drain(1..=5) {}
741 assert_eq!(v, &["0".to_string()]);
743 let mut v: Vec<String> = (0..=5).map(|x| x.to_string()).collect();
744 for _ in v.drain(0..=5) {}
745 assert_eq!(v, Vec::<String>::new());
747 let mut v: Vec<_> = (0..=5).map(|x| x.to_string()).collect();
748 for _ in v.drain(0..=3) {}
749 assert_eq!(v, &["4".to_string(), "5".to_string()]);
751 let mut v: Vec<_> = (0..=1).map(|x| x.to_string()).collect();
752 for _ in v.drain(..=0) {}
753 assert_eq!(v, &["1".to_string()]);
757 fn test_drain_max_vec_size() {
758 let mut v = Vec::<()>::with_capacity(usize::MAX);
760 v.set_len(usize::MAX);
762 for _ in v.drain(usize::MAX - 1..) {}
763 assert_eq!(v.len(), usize::MAX - 1);
765 let mut v = Vec::<()>::with_capacity(usize::MAX);
767 v.set_len(usize::MAX);
769 for _ in v.drain(usize::MAX - 1..=usize::MAX - 1) {}
770 assert_eq!(v.len(), usize::MAX - 1);
775 fn test_drain_index_overflow() {
776 let mut v = Vec::<()>::with_capacity(usize::MAX);
778 v.set_len(usize::MAX);
780 v.drain(0..=usize::MAX);
785 fn test_drain_inclusive_out_of_bounds() {
786 let mut v = vec![1, 2, 3, 4, 5];
792 fn test_drain_start_overflow() {
793 let mut v = vec![1, 2, 3];
794 v.drain((Excluded(usize::MAX), Included(0)));
799 fn test_drain_end_overflow() {
800 let mut v = vec![1, 2, 3];
801 v.drain((Included(0), Included(usize::MAX)));
805 fn test_drain_leak() {
806 static mut DROPS: i32 = 0;
808 #[derive(Debug, PartialEq)]
818 panic!("panic in `drop`");
833 catch_unwind(AssertUnwindSafe(|| {
838 assert_eq!(unsafe { DROPS }, 4);
839 assert_eq!(v, vec![D(0, false), D(1, false), D(6, false),]);
844 let mut v = vec![1, 2, 3, 4, 5];
845 let a = [10, 11, 12];
847 assert_eq!(v, &[1, 2, 10, 11, 12, 5]);
848 v.splice(1..3, Some(20));
849 assert_eq!(v, &[1, 20, 11, 12, 5]);
853 fn test_splice_inclusive_range() {
854 let mut v = vec![1, 2, 3, 4, 5];
855 let a = [10, 11, 12];
856 let t1: Vec<_> = v.splice(2..=3, a).collect();
857 assert_eq!(v, &[1, 2, 10, 11, 12, 5]);
858 assert_eq!(t1, &[3, 4]);
859 let t2: Vec<_> = v.splice(1..=2, Some(20)).collect();
860 assert_eq!(v, &[1, 20, 11, 12, 5]);
861 assert_eq!(t2, &[2, 10]);
866 fn test_splice_out_of_bounds() {
867 let mut v = vec![1, 2, 3, 4, 5];
868 let a = [10, 11, 12];
874 fn test_splice_inclusive_out_of_bounds() {
875 let mut v = vec![1, 2, 3, 4, 5];
876 let a = [10, 11, 12];
881 fn test_splice_items_zero_sized() {
882 let mut vec = vec![(), (), ()];
884 let t: Vec<_> = vec.splice(1..2, vec2.iter().cloned()).collect();
885 assert_eq!(vec, &[(), ()]);
886 assert_eq!(t, &[()]);
890 fn test_splice_unbounded() {
891 let mut vec = vec![1, 2, 3, 4, 5];
892 let t: Vec<_> = vec.splice(.., None).collect();
893 assert_eq!(vec, &[]);
894 assert_eq!(t, &[1, 2, 3, 4, 5]);
898 fn test_splice_forget() {
899 let mut v = vec![1, 2, 3, 4, 5];
900 let a = [10, 11, 12];
901 std::mem::forget(v.splice(2..4, a));
902 assert_eq!(v, &[1, 2]);
906 fn test_into_boxed_slice() {
907 let xs = vec![1, 2, 3];
908 let ys = xs.into_boxed_slice();
909 assert_eq!(&*ys, [1, 2, 3]);
914 let mut vec = vec![1, 2, 3];
915 let mut vec2 = vec![4, 5, 6];
916 vec.append(&mut vec2);
917 assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
918 assert_eq!(vec2, []);
922 fn test_split_off() {
923 let mut vec = vec![1, 2, 3, 4, 5, 6];
924 let orig_capacity = vec.capacity();
925 let vec2 = vec.split_off(4);
926 assert_eq!(vec, [1, 2, 3, 4]);
927 assert_eq!(vec2, [5, 6]);
928 assert_eq!(vec.capacity(), orig_capacity);
932 fn test_split_off_take_all() {
933 let mut vec = vec![1, 2, 3, 4, 5, 6];
934 let orig_ptr = vec.as_ptr();
935 let orig_capacity = vec.capacity();
936 let vec2 = vec.split_off(0);
938 assert_eq!(vec2, [1, 2, 3, 4, 5, 6]);
939 assert_eq!(vec.capacity(), orig_capacity);
940 assert_eq!(vec2.as_ptr(), orig_ptr);
944 fn test_into_iter_as_slice() {
945 let vec = vec!['a', 'b', 'c'];
946 let mut into_iter = vec.into_iter();
947 assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
948 let _ = into_iter.next().unwrap();
949 assert_eq!(into_iter.as_slice(), &['b', 'c']);
950 let _ = into_iter.next().unwrap();
951 let _ = into_iter.next().unwrap();
952 assert_eq!(into_iter.as_slice(), &[]);
956 fn test_into_iter_as_mut_slice() {
957 let vec = vec!['a', 'b', 'c'];
958 let mut into_iter = vec.into_iter();
959 assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
960 into_iter.as_mut_slice()[0] = 'x';
961 into_iter.as_mut_slice()[1] = 'y';
962 assert_eq!(into_iter.next().unwrap(), 'x');
963 assert_eq!(into_iter.as_slice(), &['y', 'c']);
967 fn test_into_iter_debug() {
968 let vec = vec!['a', 'b', 'c'];
969 let into_iter = vec.into_iter();
970 let debug = format!("{into_iter:?}");
971 assert_eq!(debug, "IntoIter(['a', 'b', 'c'])");
975 fn test_into_iter_count() {
976 assert_eq!([1, 2, 3].into_iter().count(), 3);
980 fn test_into_iter_next_chunk() {
981 let mut iter = b"lorem".to_vec().into_iter();
983 assert_eq!(iter.next_chunk().unwrap(), [b'l', b'o']); // N is inferred as 2
984 assert_eq!(iter.next_chunk().unwrap(), [b'r', b'e', b'm']); // N is inferred as 3
985 assert_eq!(iter.next_chunk::<4>().unwrap_err().as_slice(), &[]); // N is explicitly 4
989 fn test_into_iter_clone() {
990 fn iter_equal<I: Iterator<Item = i32>>(it: I, slice: &[i32]) {
991 let v: Vec<i32> = it.collect();
992 assert_eq!(&v[..], slice);
994 let mut it = [1, 2, 3].into_iter();
995 iter_equal(it.clone(), &[1, 2, 3]);
996 assert_eq!(it.next(), Some(1));
997 let mut it = it.rev();
998 iter_equal(it.clone(), &[3, 2]);
999 assert_eq!(it.next(), Some(3));
1000 iter_equal(it.clone(), &[2]);
1001 assert_eq!(it.next(), Some(2));
1002 iter_equal(it.clone(), &[]);
1003 assert_eq!(it.next(), None);
1007 fn test_into_iter_leak() {
1008 static mut DROPS: i32 = 0;
1013 fn drop(&mut self) {
1019 panic!("panic in `drop`");
1024 let v = vec![D(false), D(true), D(false)];
1026 catch_unwind(move || drop(v.into_iter())).ok();
1028 assert_eq!(unsafe { DROPS }, 3);
1032 fn test_into_iter_advance_by() {
1033 let mut i = [1, 2, 3, 4, 5].into_iter();
1034 i.advance_by(0).unwrap();
1035 i.advance_back_by(0).unwrap();
1036 assert_eq!(i.as_slice(), [1, 2, 3, 4, 5]);
1038 i.advance_by(1).unwrap();
1039 i.advance_back_by(1).unwrap();
1040 assert_eq!(i.as_slice(), [2, 3, 4]);
1042 assert_eq!(i.advance_back_by(usize::MAX), Err(3));
1044 assert_eq!(i.advance_by(usize::MAX), Err(0));
1046 i.advance_by(0).unwrap();
1047 i.advance_back_by(0).unwrap();
1049 assert_eq!(i.len(), 0);
1053 fn test_into_iter_drop_allocator() {
1054 struct ReferenceCountedAllocator<'a>(DropCounter<'a>);
1056 unsafe impl Allocator for ReferenceCountedAllocator<'_> {
1057 fn allocate(&self, layout: Layout) -> Result<NonNull<[u8]>, core::alloc::AllocError> {
1058 System.allocate(layout)
1061 unsafe fn deallocate(&self, ptr: NonNull<u8>, layout: Layout) {
1062 System.deallocate(ptr, layout)
1066 let mut drop_count = 0;
1068 let allocator = ReferenceCountedAllocator(DropCounter { count: &mut drop_count });
1069 let _ = Vec::<u32, _>::new_in(allocator);
1070 assert_eq!(drop_count, 1);
1072 let allocator = ReferenceCountedAllocator(DropCounter { count: &mut drop_count });
1073 let _ = Vec::<u32, _>::new_in(allocator).into_iter();
1074 assert_eq!(drop_count, 2);
1078 fn test_from_iter_specialization() {
1079 let src: Vec<usize> = vec![0usize; 1];
1080 let srcptr = src.as_ptr();
1081 let sink = src.into_iter().collect::<Vec<_>>();
1082 let sinkptr = sink.as_ptr();
1083 assert_eq!(srcptr, sinkptr);
1087 fn test_from_iter_partially_drained_in_place_specialization() {
1088 let src: Vec<usize> = vec![0usize; 10];
1089 let srcptr = src.as_ptr();
1090 let mut iter = src.into_iter();
1093 let sink = iter.collect::<Vec<_>>();
1094 let sinkptr = sink.as_ptr();
1095 assert_eq!(srcptr, sinkptr);
1099 fn test_from_iter_specialization_with_iterator_adapters() {
1100 fn assert_in_place_trait<T: InPlaceIterable>(_: &T) {}
1101 let src: Vec<usize> = vec![0usize; 256];
1102 let srcptr = src.as_ptr();
1107 .zip(std::iter::repeat(1usize))
1108 .map(|(a, b)| a + b)
1109 .map_while(Option::Some)
1111 .map(|e| if e != usize::MAX { Ok(std::num::NonZeroUsize::new(e)) } else { Err(()) });
1112 assert_in_place_trait(&iter);
1113 let sink = iter.collect::<Result<Vec<_>, _>>().unwrap();
1114 let sinkptr = sink.as_ptr();
1115 assert_eq!(srcptr, sinkptr as *const usize);
1119 fn test_from_iter_specialization_head_tail_drop() {
1120 let drop_count: Vec<_> = (0..=2).map(|_| Rc::new(())).collect();
1121 let src: Vec<_> = drop_count.iter().cloned().collect();
1122 let srcptr = src.as_ptr();
1123 let iter = src.into_iter();
1124 let sink: Vec<_> = iter.skip(1).take(1).collect();
1125 let sinkptr = sink.as_ptr();
1126 assert_eq!(srcptr, sinkptr, "specialization was applied");
1127 assert_eq!(Rc::strong_count(&drop_count[0]), 1, "front was dropped");
1128 assert_eq!(Rc::strong_count(&drop_count[1]), 2, "one element was collected");
1129 assert_eq!(Rc::strong_count(&drop_count[2]), 1, "tail was dropped");
1130 assert_eq!(sink.len(), 1);
1134 fn test_from_iter_specialization_panic_during_iteration_drops() {
1135 let drop_count: Vec<_> = (0..=2).map(|_| Rc::new(())).collect();
1136 let src: Vec<_> = drop_count.iter().cloned().collect();
1137 let iter = src.into_iter();
1139 let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
1142 .filter_map(|(i, e)| {
1144 std::panic!("aborting iteration");
1148 .collect::<Vec<_>>();
1152 drop_count.iter().map(Rc::strong_count).all(|count| count == 1),
1153 "all items were dropped once"
1158 fn test_from_iter_specialization_panic_during_drop_leaks() {
1159 static mut DROP_COUNTER: usize = 0;
1163 DroppedTwice(Box<i32>),
1167 impl Drop for Droppable {
1168 fn drop(&mut self) {
1170 Droppable::DroppedTwice(_) => {
1174 println!("Dropping!")
1176 Droppable::PanicOnDrop => {
1177 if !std::thread::panicking() {
1185 let mut to_free: *mut Droppable = core::ptr::null_mut();
1188 let _ = std::panic::catch_unwind(AssertUnwindSafe(|| {
1189 let mut v = vec![Droppable::DroppedTwice(Box::new(123)), Droppable::PanicOnDrop];
1190 to_free = v.as_mut_ptr();
1192 let _ = v.into_iter().take(0).collect::<Vec<_>>();
1195 assert_eq!(unsafe { DROP_COUNTER }, 1);
1196 // clean up the leak to keep miri happy
1198 drop(Vec::from_raw_parts(to_free, 0, cap));
1202 // regression test for issue #85322. Peekable previously implemented InPlaceIterable,
1203 // but due to an interaction with IntoIter's current Clone implementation it failed to uphold
1206 fn test_collect_after_iterator_clone() {
1208 let mut i = v.into_iter().map(|i| i + 1).peekable();
1210 let v = i.clone().collect::<Vec<_>>();
1211 assert_eq!(v, [1, 1, 1, 1, 1]);
1212 assert!(v.len() <= v.capacity());
1215 fn test_cow_from() {
1216 let borrowed: &[_] = &["borrowed", "(slice)"];
1217 let owned = vec!["owned", "(vec)"];
1218 match (Cow::from(owned.clone()), Cow::from(borrowed)) {
1219 (Cow::Owned(o), Cow::Borrowed(b)) => assert!(o == owned && b == borrowed),
1220 _ => panic!("invalid `Cow::from`"),
1225 fn test_from_cow() {
1226 let borrowed: &[_] = &["borrowed", "(slice)"];
1227 let owned = vec!["owned", "(vec)"];
1228 assert_eq!(Vec::from(Cow::Borrowed(borrowed)), vec!["borrowed", "(slice)"]);
1229 assert_eq!(Vec::from(Cow::Owned(owned)), vec!["owned", "(vec)"]);
1233 fn assert_covariance() {
1234 fn drain<'new>(d: Drain<'static, &'static str>) -> Drain<'new, &'new str> {
1237 fn into_iter<'new>(i: IntoIter<&'static str>) -> IntoIter<&'new str> {
1243 fn from_into_inner() {
1244 let vec = vec![1, 2, 3];
1245 let ptr = vec.as_ptr();
1246 let vec = vec.into_iter().collect::<Vec<_>>();
1247 assert_eq!(vec, [1, 2, 3]);
1248 assert_eq!(vec.as_ptr(), ptr);
1250 let ptr = &vec[1] as *const _;
1251 let mut it = vec.into_iter();
1253 let vec = it.collect::<Vec<_>>();
1254 assert_eq!(vec, [2, 3]);
1255 assert!(ptr != vec.as_ptr());
1259 fn overaligned_allocations() {
1262 let mut v = vec![Foo(273)];
1263 for i in 0..0x1000 {
1265 assert!(v[0].0 == 273);
1266 assert!(v.as_ptr() as usize & 0xff == 0);
1268 assert!(v[0].0 == 273);
1269 assert!(v.as_ptr() as usize & 0xff == 0);
1274 fn drain_filter_empty() {
1275 let mut vec: Vec<i32> = vec![];
1278 let mut iter = vec.drain_filter(|_| true);
1279 assert_eq!(iter.size_hint(), (0, Some(0)));
1280 assert_eq!(iter.next(), None);
1281 assert_eq!(iter.size_hint(), (0, Some(0)));
1282 assert_eq!(iter.next(), None);
1283 assert_eq!(iter.size_hint(), (0, Some(0)));
1285 assert_eq!(vec.len(), 0);
1286 assert_eq!(vec, vec![]);
1290 fn drain_filter_zst() {
1291 let mut vec = vec![(), (), (), (), ()];
1292 let initial_len = vec.len();
1295 let mut iter = vec.drain_filter(|_| true);
1296 assert_eq!(iter.size_hint(), (0, Some(initial_len)));
1297 while let Some(_) = iter.next() {
1299 assert_eq!(iter.size_hint(), (0, Some(initial_len - count)));
1301 assert_eq!(iter.size_hint(), (0, Some(0)));
1302 assert_eq!(iter.next(), None);
1303 assert_eq!(iter.size_hint(), (0, Some(0)));
1306 assert_eq!(count, initial_len);
1307 assert_eq!(vec.len(), 0);
1308 assert_eq!(vec, vec![]);
1312 fn drain_filter_false() {
1313 let mut vec = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1315 let initial_len = vec.len();
1318 let mut iter = vec.drain_filter(|_| false);
1319 assert_eq!(iter.size_hint(), (0, Some(initial_len)));
1320 for _ in iter.by_ref() {
1323 assert_eq!(iter.size_hint(), (0, Some(0)));
1324 assert_eq!(iter.next(), None);
1325 assert_eq!(iter.size_hint(), (0, Some(0)));
1328 assert_eq!(count, 0);
1329 assert_eq!(vec.len(), initial_len);
1330 assert_eq!(vec, vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
1334 fn drain_filter_true() {
1335 let mut vec = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1337 let initial_len = vec.len();
1340 let mut iter = vec.drain_filter(|_| true);
1341 assert_eq!(iter.size_hint(), (0, Some(initial_len)));
1342 while let Some(_) = iter.next() {
1344 assert_eq!(iter.size_hint(), (0, Some(initial_len - count)));
1346 assert_eq!(iter.size_hint(), (0, Some(0)));
1347 assert_eq!(iter.next(), None);
1348 assert_eq!(iter.size_hint(), (0, Some(0)));
1351 assert_eq!(count, initial_len);
1352 assert_eq!(vec.len(), 0);
1353 assert_eq!(vec, vec![]);
1357 fn drain_filter_complex() {
1359 // [+xxx++++++xxxxx++++x+x++]
1361 1, 2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36, 37,
1365 let removed = vec.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
1366 assert_eq!(removed.len(), 10);
1367 assert_eq!(removed, vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]);
1369 assert_eq!(vec.len(), 14);
1370 assert_eq!(vec, vec![1, 7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39]);
1374 // [xxx++++++xxxxx++++x+x++]
1376 2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36, 37, 39,
1379 let removed = vec.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
1380 assert_eq!(removed.len(), 10);
1381 assert_eq!(removed, vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]);
1383 assert_eq!(vec.len(), 13);
1384 assert_eq!(vec, vec![7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35, 37, 39]);
1388 // [xxx++++++xxxxx++++x+x]
1390 vec![2, 4, 6, 7, 9, 11, 13, 15, 17, 18, 20, 22, 24, 26, 27, 29, 31, 33, 34, 35, 36];
1392 let removed = vec.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
1393 assert_eq!(removed.len(), 10);
1394 assert_eq!(removed, vec![2, 4, 6, 18, 20, 22, 24, 26, 34, 36]);
1396 assert_eq!(vec.len(), 11);
1397 assert_eq!(vec, vec![7, 9, 11, 13, 15, 17, 27, 29, 31, 33, 35]);
1401 // [xxxxxxxxxx+++++++++++]
1402 let mut vec = vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 1, 3, 5, 7, 9, 11, 13, 15, 17, 19];
1404 let removed = vec.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
1405 assert_eq!(removed.len(), 10);
1406 assert_eq!(removed, vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);
1408 assert_eq!(vec.len(), 10);
1409 assert_eq!(vec, vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19]);
1413 // [+++++++++++xxxxxxxxxx]
1414 let mut vec = vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20];
1416 let removed = vec.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
1417 assert_eq!(removed.len(), 10);
1418 assert_eq!(removed, vec![2, 4, 6, 8, 10, 12, 14, 16, 18, 20]);
1420 assert_eq!(vec.len(), 10);
1421 assert_eq!(vec, vec![1, 3, 5, 7, 9, 11, 13, 15, 17, 19]);
1425 // FIXME: re-enable emscripten once it can unwind again
1427 #[cfg(not(target_os = "emscripten"))]
1428 fn drain_filter_consumed_panic() {
1430 use std::sync::Mutex;
1434 drop_counts: Rc<Mutex<Vec<usize>>>,
1437 impl Drop for Check {
1438 fn drop(&mut self) {
1439 self.drop_counts.lock().unwrap()[self.index] += 1;
1440 println!("drop: {}", self.index);
1444 let check_count = 10;
1445 let drop_counts = Rc::new(Mutex::new(vec![0_usize; check_count]));
1446 let mut data: Vec<Check> = (0..check_count)
1447 .map(|index| Check { index, drop_counts: Rc::clone(&drop_counts) })
1450 let _ = std::panic::catch_unwind(move || {
1451 let filter = |c: &mut Check| {
1453 panic!("panic at index: {}", c.index);
1455 // Verify that if the filter could panic again on another element
1456 // that it would not cause a double panic and all elements of the
1457 // vec would still be dropped exactly once.
1459 panic!("panic at index: {}", c.index);
1463 let drain = data.drain_filter(filter);
1465 // NOTE: The DrainFilter is explicitly consumed
1466 drain.for_each(drop);
1469 let drop_counts = drop_counts.lock().unwrap();
1470 assert_eq!(check_count, drop_counts.len());
1472 for (index, count) in drop_counts.iter().cloned().enumerate() {
1473 assert_eq!(1, count, "unexpected drop count at index: {} (count: {})", index, count);
1477 // FIXME: Re-enable emscripten once it can catch panics
1479 #[cfg(not(target_os = "emscripten"))]
1480 fn drain_filter_unconsumed_panic() {
1482 use std::sync::Mutex;
1486 drop_counts: Rc<Mutex<Vec<usize>>>,
1489 impl Drop for Check {
1490 fn drop(&mut self) {
1491 self.drop_counts.lock().unwrap()[self.index] += 1;
1492 println!("drop: {}", self.index);
1496 let check_count = 10;
1497 let drop_counts = Rc::new(Mutex::new(vec![0_usize; check_count]));
1498 let mut data: Vec<Check> = (0..check_count)
1499 .map(|index| Check { index, drop_counts: Rc::clone(&drop_counts) })
1502 let _ = std::panic::catch_unwind(move || {
1503 let filter = |c: &mut Check| {
1505 panic!("panic at index: {}", c.index);
1507 // Verify that if the filter could panic again on another element
1508 // that it would not cause a double panic and all elements of the
1509 // vec would still be dropped exactly once.
1511 panic!("panic at index: {}", c.index);
1515 let _drain = data.drain_filter(filter);
1517 // NOTE: The DrainFilter is dropped without being consumed
1520 let drop_counts = drop_counts.lock().unwrap();
1521 assert_eq!(check_count, drop_counts.len());
1523 for (index, count) in drop_counts.iter().cloned().enumerate() {
1524 assert_eq!(1, count, "unexpected drop count at index: {} (count: {})", index, count);
1529 fn drain_filter_unconsumed() {
1530 let mut vec = vec![1, 2, 3, 4];
1531 let drain = vec.drain_filter(|&mut x| x % 2 != 0);
1533 assert_eq!(vec, [2, 4]);
1537 fn test_reserve_exact() {
1538 // This is all the same as test_reserve
1540 let mut v = Vec::new();
1541 assert_eq!(v.capacity(), 0);
1544 assert!(v.capacity() >= 2);
1550 assert!(v.capacity() >= 16);
1551 v.reserve_exact(16);
1552 assert!(v.capacity() >= 32);
1556 v.reserve_exact(16);
1557 assert!(v.capacity() >= 33)
1561 #[cfg_attr(miri, ignore)] // Miri does not support signalling OOM
1562 #[cfg_attr(target_os = "android", ignore)] // Android used in CI has a broken dlmalloc
1563 fn test_try_reserve() {
1564 // These are the interesting cases:
1565 // * exactly isize::MAX should never trigger a CapacityOverflow (can be OOM)
1566 // * > isize::MAX should always fail
1567 // * On 16/32-bit should CapacityOverflow
1568 // * On 64-bit should OOM
1569 // * overflow may trigger when adding `len` to `cap` (in number of elements)
1570 // * overflow may trigger when multiplying `new_cap` by size_of::<T> (to get bytes)
1572 const MAX_CAP: usize = isize::MAX as usize;
1573 const MAX_USIZE: usize = usize::MAX;
1576 // Note: basic stuff is checked by test_reserve
1577 let mut empty_bytes: Vec<u8> = Vec::new();
1579 // Check isize::MAX doesn't count as an overflow
1580 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_CAP).map_err(|e| e.kind()) {
1581 panic!("isize::MAX shouldn't trigger an overflow!");
1583 // Play it again, frank! (just to be sure)
1584 if let Err(CapacityOverflow) = empty_bytes.try_reserve(MAX_CAP).map_err(|e| e.kind()) {
1585 panic!("isize::MAX shouldn't trigger an overflow!");
1588 // Check isize::MAX + 1 does count as overflow
1590 empty_bytes.try_reserve(MAX_CAP + 1).map_err(|e| e.kind()),
1591 Err(CapacityOverflow),
1592 "isize::MAX + 1 should trigger an overflow!"
1595 // Check usize::MAX does count as overflow
1597 empty_bytes.try_reserve(MAX_USIZE).map_err(|e| e.kind()),
1598 Err(CapacityOverflow),
1599 "usize::MAX should trigger an overflow!"
1604 // Same basic idea, but with non-zero len
1605 let mut ten_bytes: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1607 if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 10).map_err(|e| e.kind()) {
1608 panic!("isize::MAX shouldn't trigger an overflow!");
1610 if let Err(CapacityOverflow) = ten_bytes.try_reserve(MAX_CAP - 10).map_err(|e| e.kind()) {
1611 panic!("isize::MAX shouldn't trigger an overflow!");
1615 ten_bytes.try_reserve(MAX_CAP - 9).map_err(|e| e.kind()),
1616 Err(CapacityOverflow),
1617 "isize::MAX + 1 should trigger an overflow!"
1620 // Should always overflow in the add-to-len
1622 ten_bytes.try_reserve(MAX_USIZE).map_err(|e| e.kind()),
1623 Err(CapacityOverflow),
1624 "usize::MAX should trigger an overflow!"
1629 // Same basic idea, but with interesting type size
1630 let mut ten_u32s: Vec<u32> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1632 if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP / 4 - 10).map_err(|e| e.kind())
1634 panic!("isize::MAX shouldn't trigger an overflow!");
1636 if let Err(CapacityOverflow) = ten_u32s.try_reserve(MAX_CAP / 4 - 10).map_err(|e| e.kind())
1638 panic!("isize::MAX shouldn't trigger an overflow!");
1642 ten_u32s.try_reserve(MAX_CAP / 4 - 9).map_err(|e| e.kind()),
1643 Err(CapacityOverflow),
1644 "isize::MAX + 1 should trigger an overflow!"
1647 // Should fail in the mul-by-size
1649 ten_u32s.try_reserve(MAX_USIZE - 20).map_err(|e| e.kind()),
1650 Err(CapacityOverflow),
1651 "usize::MAX should trigger an overflow!"
1657 #[cfg_attr(miri, ignore)] // Miri does not support signalling OOM
1658 #[cfg_attr(target_os = "android", ignore)] // Android used in CI has a broken dlmalloc
1659 fn test_try_reserve_exact() {
1660 // This is exactly the same as test_try_reserve with the method changed.
1661 // See that test for comments.
1663 const MAX_CAP: usize = isize::MAX as usize;
1664 const MAX_USIZE: usize = usize::MAX;
1667 let mut empty_bytes: Vec<u8> = Vec::new();
1669 if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_CAP).map_err(|e| e.kind())
1671 panic!("isize::MAX shouldn't trigger an overflow!");
1673 if let Err(CapacityOverflow) = empty_bytes.try_reserve_exact(MAX_CAP).map_err(|e| e.kind())
1675 panic!("isize::MAX shouldn't trigger an overflow!");
1679 empty_bytes.try_reserve_exact(MAX_CAP + 1).map_err(|e| e.kind()),
1680 Err(CapacityOverflow),
1681 "isize::MAX + 1 should trigger an overflow!"
1685 empty_bytes.try_reserve_exact(MAX_USIZE).map_err(|e| e.kind()),
1686 Err(CapacityOverflow),
1687 "usize::MAX should trigger an overflow!"
1692 let mut ten_bytes: Vec<u8> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1694 if let Err(CapacityOverflow) =
1695 ten_bytes.try_reserve_exact(MAX_CAP - 10).map_err(|e| e.kind())
1697 panic!("isize::MAX shouldn't trigger an overflow!");
1699 if let Err(CapacityOverflow) =
1700 ten_bytes.try_reserve_exact(MAX_CAP - 10).map_err(|e| e.kind())
1702 panic!("isize::MAX shouldn't trigger an overflow!");
1706 ten_bytes.try_reserve_exact(MAX_CAP - 9).map_err(|e| e.kind()),
1707 Err(CapacityOverflow),
1708 "isize::MAX + 1 should trigger an overflow!"
1712 ten_bytes.try_reserve_exact(MAX_USIZE).map_err(|e| e.kind()),
1713 Err(CapacityOverflow),
1714 "usize::MAX should trigger an overflow!"
1719 let mut ten_u32s: Vec<u32> = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1721 if let Err(CapacityOverflow) =
1722 ten_u32s.try_reserve_exact(MAX_CAP / 4 - 10).map_err(|e| e.kind())
1724 panic!("isize::MAX shouldn't trigger an overflow!");
1726 if let Err(CapacityOverflow) =
1727 ten_u32s.try_reserve_exact(MAX_CAP / 4 - 10).map_err(|e| e.kind())
1729 panic!("isize::MAX shouldn't trigger an overflow!");
1733 ten_u32s.try_reserve_exact(MAX_CAP / 4 - 9).map_err(|e| e.kind()),
1734 Err(CapacityOverflow),
1735 "isize::MAX + 1 should trigger an overflow!"
1739 ten_u32s.try_reserve_exact(MAX_USIZE - 20).map_err(|e| e.kind()),
1740 Err(CapacityOverflow),
1741 "usize::MAX should trigger an overflow!"
1747 fn test_stable_pointers() {
1748 /// Pull an element from the iterator, then drop it.
1749 /// Useful to cover both the `next` and `drop` paths of an iterator.
1750 fn next_then_drop<I: Iterator>(mut i: I) {
1755 // Test that, if we reserved enough space, adding and removing elements does not
1756 // invalidate references into the vector (such as `v0`). This test also
1757 // runs in Miri, which would detect such problems.
1758 // Note that this test does *not* constitute a stable guarantee that all these functions do not
1759 // reallocate! Only what is explicitly documented at
1760 // <https://doc.rust-lang.org/nightly/std/vec/struct.Vec.html#guarantees> is stably guaranteed.
1761 let mut v = Vec::with_capacity(128);
1764 // Laundering the lifetime -- we take care that `v` does not reallocate, so that's okay.
1766 let v0 = unsafe { &mut *(v0 as *mut _) };
1767 // Now do a bunch of things and occasionally use `v0` again to assert it is still valid.
1769 // Pushing/inserting and popping/removing
1773 assert_eq!(*v0, 13);
1776 assert_eq!(*v0, 13);
1779 assert_eq!(v.len(), 2);
1780 v.swap_remove(1); // swap_remove the last element
1781 assert_eq!(*v0, 13);
1784 v.append(&mut vec![27, 19]);
1785 assert_eq!(*v0, 13);
1788 v.extend_from_slice(&[1, 2]);
1789 v.extend(&[1, 2]); // `slice::Iter` (with `T: Copy`) specialization
1790 v.extend(vec![2, 3]); // `vec::IntoIter` specialization
1791 v.extend(std::iter::once(3)); // `TrustedLen` specialization
1792 v.extend(std::iter::empty::<i32>()); // `TrustedLen` specialization with empty iterator
1793 v.extend(std::iter::once(3).filter(|_| true)); // base case
1794 v.extend(std::iter::once(&3)); // `cloned` specialization
1795 assert_eq!(*v0, 13);
1799 assert_eq!(*v0, 13);
1802 v.resize_with(v.len() + 10, || 42);
1803 assert_eq!(*v0, 13);
1804 v.resize_with(2, || panic!());
1805 assert_eq!(*v0, 13);
1807 // No-op reservation
1809 v.reserve_exact(32);
1810 assert_eq!(*v0, 13);
1813 v.resize_with(10, || 42);
1814 next_then_drop(v.drain(5..));
1815 assert_eq!(*v0, 13);
1818 v.resize_with(10, || 42);
1819 next_then_drop(v.splice(5.., vec![1, 2, 3, 4, 5])); // empty tail after range
1820 assert_eq!(*v0, 13);
1821 next_then_drop(v.splice(5..8, vec![1])); // replacement is smaller than original range
1822 assert_eq!(*v0, 13);
1823 next_then_drop(v.splice(5..6, [1; 10].into_iter().filter(|_| true))); // lower bound not exact
1824 assert_eq!(*v0, 13);
1826 // spare_capacity_mut
1827 v.spare_capacity_mut();
1828 assert_eq!(*v0, 13);
1830 // Smoke test that would fire even outside Miri if an actual relocation happened.
1832 assert_eq!(v[0], 0);
1835 // https://github.com/rust-lang/rust/pull/49496 introduced specialization based on:
1838 // unsafe impl<T: ?Sized> IsZero for *mut T {
1839 // fn is_zero(&self) -> bool {
1840 // (*self).is_null()
1845 // … to call `RawVec::with_capacity_zeroed` for creating `Vec<*mut T>`,
1846 // which is incorrect for fat pointers since `<*mut T>::is_null` only looks at the data component.
1847 // That is, a fat pointer can be “null” without being made entirely of zero bits.
1849 fn vec_macro_repeating_null_raw_fat_pointer() {
1850 let raw_dyn = &mut (|| ()) as &mut dyn Fn() as *mut dyn Fn();
1851 let vtable = dbg!(ptr_metadata(raw_dyn));
1852 let null_raw_dyn = ptr_from_raw_parts(std::ptr::null_mut(), vtable);
1853 assert!(null_raw_dyn.is_null());
1855 let vec = vec![null_raw_dyn; 1];
1856 dbg!(ptr_metadata(vec[0]));
1857 assert!(vec[0] == null_raw_dyn);
1859 // Polyfill for https://github.com/rust-lang/rfcs/pull/2580
1861 fn ptr_metadata(ptr: *mut dyn Fn()) -> *mut () {
1862 unsafe { std::mem::transmute::<*mut dyn Fn(), DynRepr>(ptr).vtable }
1865 fn ptr_from_raw_parts(data: *mut (), vtable: *mut ()) -> *mut dyn Fn() {
1866 unsafe { std::mem::transmute::<DynRepr, *mut dyn Fn()>(DynRepr { data, vtable }) }
1876 // This test will likely fail if you change the capacities used in
1877 // `RawVec::grow_amortized`.
1879 fn test_push_growth_strategy() {
1880 // If the element size is 1, we jump from 0 to 8, then double.
1882 let mut v1: Vec<u8> = vec![];
1883 assert_eq!(v1.capacity(), 0);
1887 assert_eq!(v1.capacity(), 8);
1892 assert_eq!(v1.capacity(), 16);
1897 assert_eq!(v1.capacity(), 32);
1902 assert_eq!(v1.capacity(), 64);
1906 // If the element size is 2..=1024, we jump from 0 to 4, then double.
1908 let mut v2: Vec<u16> = vec![];
1909 let mut v1024: Vec<[u8; 1024]> = vec![];
1910 assert_eq!(v2.capacity(), 0);
1911 assert_eq!(v1024.capacity(), 0);
1915 v1024.push([0; 1024]);
1916 assert_eq!(v2.capacity(), 4);
1917 assert_eq!(v1024.capacity(), 4);
1922 v1024.push([0; 1024]);
1923 assert_eq!(v2.capacity(), 8);
1924 assert_eq!(v1024.capacity(), 8);
1929 v1024.push([0; 1024]);
1930 assert_eq!(v2.capacity(), 16);
1931 assert_eq!(v1024.capacity(), 16);
1936 v1024.push([0; 1024]);
1937 assert_eq!(v2.capacity(), 32);
1938 assert_eq!(v1024.capacity(), 32);
1943 v1024.push([0; 1024]);
1944 assert_eq!(v2.capacity(), 64);
1945 assert_eq!(v1024.capacity(), 64);
1949 // If the element size is > 1024, we jump from 0 to 1, then double.
1951 let mut v1025: Vec<[u8; 1025]> = vec![];
1952 assert_eq!(v1025.capacity(), 0);
1955 v1025.push([0; 1025]);
1956 assert_eq!(v1025.capacity(), 1);
1960 v1025.push([0; 1025]);
1961 assert_eq!(v1025.capacity(), 2);
1965 v1025.push([0; 1025]);
1966 assert_eq!(v1025.capacity(), 4);
1970 v1025.push([0; 1025]);
1971 assert_eq!(v1025.capacity(), 8);
1975 v1025.push([0; 1025]);
1976 assert_eq!(v1025.capacity(), 16);
1980 v1025.push([0; 1025]);
1981 assert_eq!(v1025.capacity(), 32);
1985 v1025.push([0; 1025]);
1986 assert_eq!(v1025.capacity(), 64);
1991 macro_rules! generate_assert_eq_vec_and_prim {
1992 ($name:ident<$B:ident>($type:ty)) => {
1993 fn $name<A: PartialEq<$B> + Debug, $B: Debug>(a: Vec<A>, b: $type) {
2000 generate_assert_eq_vec_and_prim! { assert_eq_vec_and_slice <B>(&[B]) }
2001 generate_assert_eq_vec_and_prim! { assert_eq_vec_and_array_3<B>([B; 3]) }
2004 fn partialeq_vec_and_prim() {
2005 assert_eq_vec_and_slice(vec![1, 2, 3], &[1, 2, 3]);
2006 assert_eq_vec_and_array_3(vec![1, 2, 3], [1, 2, 3]);
2009 macro_rules! assert_partial_eq_valid {
2010 ($a2:expr, $a3:expr; $b2:expr, $b3: expr) => {
2011 assert!($a2 == $b2);
2012 assert!($a2 != $b3);
2013 assert!($a3 != $b2);
2014 assert!($a3 == $b3);
2015 assert_eq!($a2, $b2);
2016 assert_ne!($a2, $b3);
2017 assert_ne!($a3, $b2);
2018 assert_eq!($a3, $b3);
2023 fn partialeq_vec_full() {
2024 let vec2: Vec<_> = vec![1, 2];
2025 let vec3: Vec<_> = vec![1, 2, 3];
2026 let slice2: &[_] = &[1, 2];
2027 let slice3: &[_] = &[1, 2, 3];
2028 let slicemut2: &[_] = &mut [1, 2];
2029 let slicemut3: &[_] = &mut [1, 2, 3];
2030 let array2: [_; 2] = [1, 2];
2031 let array3: [_; 3] = [1, 2, 3];
2032 let arrayref2: &[_; 2] = &[1, 2];
2033 let arrayref3: &[_; 3] = &[1, 2, 3];
2035 assert_partial_eq_valid!(vec2,vec3; vec2,vec3);
2036 assert_partial_eq_valid!(vec2,vec3; slice2,slice3);
2037 assert_partial_eq_valid!(vec2,vec3; slicemut2,slicemut3);
2038 assert_partial_eq_valid!(slice2,slice3; vec2,vec3);
2039 assert_partial_eq_valid!(slicemut2,slicemut3; vec2,vec3);
2040 assert_partial_eq_valid!(vec2,vec3; array2,array3);
2041 assert_partial_eq_valid!(vec2,vec3; arrayref2,arrayref3);
2042 assert_partial_eq_valid!(vec2,vec3; arrayref2[..],arrayref3[..]);
2046 fn test_vec_cycle() {
2049 v: Vec<Cell<Option<&'a C<'a>>>>,
2058 let mut c1 = C::new();
2059 let mut c2 = C::new();
2060 let mut c3 = C::new();
2063 c1.v.push(Cell::new(None));
2064 c1.v.push(Cell::new(None));
2066 c2.v.push(Cell::new(None));
2067 c2.v.push(Cell::new(None));
2069 c3.v.push(Cell::new(None));
2070 c3.v.push(Cell::new(None));
2073 c1.v[0].set(Some(&c2));
2074 c1.v[1].set(Some(&c3));
2076 c2.v[0].set(Some(&c2));
2077 c2.v[1].set(Some(&c3));
2079 c3.v[0].set(Some(&c1));
2080 c3.v[1].set(Some(&c2));
2084 fn test_vec_cycle_wrapped() {
2086 v: Vec<Cell<Option<&'a C<'a>>>>,
2094 fn new() -> Refs<'a> {
2095 Refs { v: Vec::new() }
2101 C { refs: Refs::new() }
2105 let mut c1 = C::new();
2106 let mut c2 = C::new();
2107 let mut c3 = C::new();
2109 c1.refs.v.push(Cell::new(None));
2110 c1.refs.v.push(Cell::new(None));
2111 c2.refs.v.push(Cell::new(None));
2112 c2.refs.v.push(Cell::new(None));
2113 c3.refs.v.push(Cell::new(None));
2114 c3.refs.v.push(Cell::new(None));
2116 c1.refs.v[0].set(Some(&c2));
2117 c1.refs.v[1].set(Some(&c3));
2118 c2.refs.v[0].set(Some(&c2));
2119 c2.refs.v[1].set(Some(&c3));
2120 c3.refs.v[0].set(Some(&c1));
2121 c3.refs.v[1].set(Some(&c2));
2125 fn test_zero_sized_capacity() {
2126 for len in [0, 1, 2, 4, 8, 16, 32, 64, 128, 256] {
2127 let v = Vec::<()>::with_capacity(len);
2128 assert_eq!(v.len(), 0);
2129 assert_eq!(v.capacity(), usize::MAX);
2134 fn test_zero_sized_vec_push() {
2138 let mut tester = Vec::with_capacity(len);
2139 assert_eq!(tester.len(), 0);
2140 assert!(tester.capacity() >= len);
2144 assert_eq!(tester.len(), len);
2145 assert_eq!(tester.iter().count(), len);
2151 fn test_vec_macro_repeat() {
2152 assert_eq!(vec![1; 3], vec![1, 1, 1]);
2153 assert_eq!(vec![1; 2], vec![1, 1]);
2154 assert_eq!(vec![1; 1], vec![1]);
2155 assert_eq!(vec![1; 0], vec![]);
2157 // from_elem syntax (see RFC 832)
2158 let el = Box::new(1);
2160 assert_eq!(vec![el; n], vec![Box::new(1), Box::new(1), Box::new(1)]);
2164 fn test_vec_swap() {
2165 let mut a: Vec<isize> = vec![0, 1, 2, 3, 4, 5, 6];
2167 assert_eq!(a[2], 4);
2168 assert_eq!(a[4], 2);
2170 swap(&mut n, &mut a[0]);
2171 assert_eq!(a[0], 42);
2176 fn test_extend_from_within_spec() {
2180 impl Clone for CopyOnly {
2181 fn clone(&self) -> Self {
2182 panic!("extend_from_within must use specialization on copy");
2186 vec![CopyOnly, CopyOnly].extend_from_within(..);
2190 fn test_extend_from_within_clone() {
2191 let mut v = vec![String::from("sssss"), String::from("12334567890"), String::from("c")];
2192 v.extend_from_within(1..);
2194 assert_eq!(v, ["sssss", "12334567890", "c", "12334567890", "c"]);
2198 fn test_extend_from_within_complete_rande() {
2199 let mut v = vec![0, 1, 2, 3];
2200 v.extend_from_within(..);
2202 assert_eq!(v, [0, 1, 2, 3, 0, 1, 2, 3]);
2206 fn test_extend_from_within_empty_rande() {
2207 let mut v = vec![0, 1, 2, 3];
2208 v.extend_from_within(1..1);
2210 assert_eq!(v, [0, 1, 2, 3]);
2215 fn test_extend_from_within_out_of_rande() {
2216 let mut v = vec![0, 1];
2217 v.extend_from_within(..3);
2221 fn test_extend_from_within_zst() {
2222 let mut v = vec![(); 8];
2223 v.extend_from_within(3..7);
2225 assert_eq!(v, [(); 12]);
2229 fn test_extend_from_within_empty_vec() {
2230 let mut v = Vec::<i32>::new();
2231 v.extend_from_within(..);
2237 fn test_extend_from_within() {
2238 let mut v = vec![String::from("a"), String::from("b"), String::from("c")];
2239 v.extend_from_within(1..=2);
2240 v.extend_from_within(..=1);
2242 assert_eq!(v, ["a", "b", "c", "b", "c", "a", "b"]);
2246 fn test_vec_dedup_by() {
2247 let mut vec: Vec<i32> = vec![1, -1, 2, 3, 1, -5, 5, -2, 2];
2249 vec.dedup_by(|a, b| a.abs() == b.abs());
2251 assert_eq!(vec, [1, 2, 3, 1, -5, -2]);
2255 fn test_vec_dedup_empty() {
2256 let mut vec: Vec<i32> = Vec::new();
2260 assert_eq!(vec, []);
2264 fn test_vec_dedup_one() {
2265 let mut vec = vec![12i32];
2269 assert_eq!(vec, [12]);
2273 fn test_vec_dedup_multiple_ident() {
2274 let mut vec = vec![12, 12, 12, 12, 12, 11, 11, 11, 11, 11, 11];
2278 assert_eq!(vec, [12, 11]);
2282 fn test_vec_dedup_partialeq() {
2284 struct Foo(i32, i32);
2286 impl PartialEq for Foo {
2287 fn eq(&self, other: &Foo) -> bool {
2292 let mut vec = vec![Foo(0, 1), Foo(0, 5), Foo(1, 7), Foo(1, 9)];
2295 assert_eq!(vec, [Foo(0, 1), Foo(1, 7)]);
2299 fn test_vec_dedup() {
2300 let mut vec: Vec<bool> = Vec::with_capacity(8);
2301 let mut template = vec.clone();
2303 for x in 0u8..255u8 {
2307 let iter = (0..8).map(move |bit| (x >> bit) & 1 == 1);
2309 template.extend_from_slice(&vec);
2311 let (dedup, _) = template.partition_dedup();
2314 assert_eq!(vec, dedup);
2319 fn test_vec_dedup_panicking() {
2322 drop_counter: &'a Cell<u32>,
2327 impl<'a> PartialEq for Panic<'a> {
2328 fn eq(&self, other: &Self) -> bool {
2329 self.value == other.value
2333 impl<'a> Drop for Panic<'a> {
2334 fn drop(&mut self) {
2335 self.drop_counter.set(self.drop_counter.get() + 1);
2336 if !std::thread::panicking() {
2337 assert!(self.index != 4);
2342 let drop_counter = &Cell::new(0);
2344 Panic { drop_counter, value: false, index: 0 },
2345 Panic { drop_counter, value: false, index: 5 },
2346 Panic { drop_counter, value: true, index: 6 },
2347 Panic { drop_counter, value: true, index: 7 },
2350 Panic { drop_counter, value: false, index: 0 },
2351 // these elements get deduplicated
2352 Panic { drop_counter, value: false, index: 1 },
2353 Panic { drop_counter, value: false, index: 2 },
2354 Panic { drop_counter, value: false, index: 3 },
2355 Panic { drop_counter, value: false, index: 4 },
2356 // here it panics while dropping the item with index==4
2357 Panic { drop_counter, value: false, index: 5 },
2358 Panic { drop_counter, value: true, index: 6 },
2359 Panic { drop_counter, value: true, index: 7 },
2362 let _ = catch_unwind(AssertUnwindSafe(|| vec.dedup())).unwrap_err();
2364 assert_eq!(drop_counter.get(), 4);
2366 let ok = vec.iter().zip(expected.iter()).all(|(x, y)| x.index == y.index);
2369 panic!("expected: {expected:?}\ngot: {vec:?}\n");
2373 // Regression test for issue #82533
2375 fn test_extend_from_within_panicing_clone() {
2377 drop_count: &'dc AtomicU32,
2381 impl Clone for Panic<'_> {
2382 fn clone(&self) -> Self {
2384 panic!("panic! at the clone");
2391 impl Drop for Panic<'_> {
2392 fn drop(&mut self) {
2393 self.drop_count.fetch_add(1, Ordering::SeqCst);
2397 let count = core::sync::atomic::AtomicU32::new(0);
2399 Panic { drop_count: &count, aaaaa: false },
2400 Panic { drop_count: &count, aaaaa: true },
2401 Panic { drop_count: &count, aaaaa: false },
2404 // This should clone&append one Panic{..} at the end, and then panic while
2405 // cloning second Panic{..}. This means that `Panic::drop` should be called
2406 // 4 times (3 for items already in vector, 1 for just appended).
2408 // Previously just appended item was leaked, making drop_count = 3, instead of 4.
2409 std::panic::catch_unwind(move || vec.extend_from_within(..)).unwrap_err();
2411 assert_eq!(count.load(Ordering::SeqCst), 4);
2415 #[should_panic = "vec len overflow"]
2416 fn test_into_flattened_size_overflow() {
2417 let v = vec![[(); usize::MAX]; 2];
2418 let _ = v.into_flattened();