1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A growable list type with heap-allocated contents, written `Vec<T>` but pronounced 'vector.'
13 //! Vectors have `O(1)` indexing, push (to the end) and pop (from the end).
17 //! Explicitly creating a `Vec<T>` with `new()`:
20 //! let xs: Vec<i32> = Vec::new();
23 //! Using the `vec!` macro:
26 //! let ys: Vec<i32> = vec![];
28 //! let zs = vec![1i32, 2, 3, 4, 5];
34 //! let mut xs = vec![1i32, 2];
42 //! let mut xs = vec![1i32, 2];
44 //! let two = xs.pop();
47 #![stable(feature = "rust1", since = "1.0.0")]
51 use alloc::boxed::Box;
52 use alloc::heap::{EMPTY, allocate, reallocate, deallocate};
53 use core::borrow::{Cow, IntoCow};
55 use core::cmp::{Ordering};
56 use core::default::Default;
58 use core::hash::{self, Hash};
59 use core::iter::{repeat, FromIterator, IntoIterator};
60 use core::marker::{ContravariantLifetime, InvariantType};
62 use core::nonzero::NonZero;
63 use core::num::{Int, UnsignedInt};
64 use core::ops::{Index, IndexMut, Deref, Add};
67 use core::raw::Slice as RawSlice;
71 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
76 /// let mut vec = Vec::new();
80 /// assert_eq!(vec.len(), 2);
81 /// assert_eq!(vec[0], 1);
83 /// assert_eq!(vec.pop(), Some(2));
84 /// assert_eq!(vec.len(), 1);
87 /// assert_eq!(vec[0], 7);
89 /// vec.push_all(&[1, 2, 3]);
91 /// for x in vec.iter() {
92 /// println!("{}", x);
94 /// assert_eq!(vec, vec![7, 1, 2, 3]);
97 /// The `vec!` macro is provided to make initialization more convenient:
100 /// let mut vec = vec![1, 2, 3];
102 /// assert_eq!(vec, vec![1, 2, 3, 4]);
105 /// Use a `Vec<T>` as an efficient stack:
108 /// let mut stack = Vec::new();
115 /// let top = match stack.pop() {
116 /// None => break, // empty
119 /// // Prints 3, 2, 1
120 /// println!("{}", top);
124 /// # Capacity and reallocation
126 /// The capacity of a vector is the amount of space allocated for any future elements that will be
127 /// added onto the vector. This is not to be confused with the *length* of a vector, which
128 /// specifies the number of actual elements within the vector. If a vector's length exceeds its
129 /// capacity, its capacity will automatically be increased, but its elements will have to be
132 /// For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10
133 /// more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or
134 /// cause reallocation to occur. However, if the vector's length is increased to 11, it will have
135 /// to reallocate, which can be slow. For this reason, it is recommended to use
136 /// `Vec::with_capacity` whenever possible to specify how big the vector is expected to get.
137 #[unsafe_no_drop_flag]
138 #[stable(feature = "rust1", since = "1.0.0")]
140 ptr: NonZero<*mut T>,
145 unsafe impl<T: Send> Send for Vec<T> { }
146 unsafe impl<T: Sync> Sync for Vec<T> { }
148 ////////////////////////////////////////////////////////////////////////////////
150 ////////////////////////////////////////////////////////////////////////////////
153 /// Constructs a new, empty `Vec<T>`.
155 /// The vector will not allocate until elements are pushed onto it.
160 /// let mut vec: Vec<int> = Vec::new();
163 #[stable(feature = "rust1", since = "1.0.0")]
164 pub fn new() -> Vec<T> {
165 // We want ptr to never be NULL so instead we set it to some arbitrary
166 // non-null value which is fine since we never call deallocate on the ptr
167 // if cap is 0. The reason for this is because the pointer of a slice
168 // being NULL would break the null pointer optimization for enums.
169 Vec { ptr: unsafe { NonZero::new(EMPTY as *mut T) }, len: 0, cap: 0 }
172 /// Constructs a new, empty `Vec<T>` with the specified capacity.
174 /// The vector will be able to hold exactly `capacity` elements without reallocating. If
175 /// `capacity` is 0, the vector will not allocate.
177 /// It is important to note that this function does not specify the *length* of the returned
178 /// vector, but only the *capacity*. (For an explanation of the difference between length and
179 /// capacity, see the main `Vec<T>` docs above, 'Capacity and reallocation'.)
184 /// let mut vec: Vec<_> = Vec::with_capacity(10);
186 /// // The vector contains no items, even though it has capacity for more
187 /// assert_eq!(vec.len(), 0);
189 /// // These are all done without reallocating...
194 /// // ...but this may make the vector reallocate
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub fn with_capacity(capacity: usize) -> Vec<T> {
200 if mem::size_of::<T>() == 0 {
201 Vec { ptr: unsafe { NonZero::new(EMPTY as *mut T) }, len: 0, cap: usize::MAX }
202 } else if capacity == 0 {
205 let size = capacity.checked_mul(mem::size_of::<T>())
206 .expect("capacity overflow");
207 let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
208 if ptr.is_null() { ::alloc::oom() }
209 Vec { ptr: unsafe { NonZero::new(ptr as *mut T) }, len: 0, cap: capacity }
213 /// Creates a `Vec<T>` directly from the raw components of another vector.
215 /// This is highly unsafe, due to the number of invariants that aren't checked.
224 /// let mut v = vec![1, 2, 3];
226 /// // Pull out the various important pieces of information about `v`
227 /// let p = v.as_mut_ptr();
228 /// let len = v.len();
229 /// let cap = v.capacity();
232 /// // Cast `v` into the void: no destructor run, so we are in
233 /// // complete control of the allocation to which `p` points.
236 /// // Overwrite memory with 4, 5, 6
237 /// for i in 0..len as isize {
238 /// ptr::write(p.offset(i), 4 + i);
241 /// // Put everything back together into a Vec
242 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
243 /// assert_eq!(rebuilt, vec![4, 5, 6]);
247 #[stable(feature = "rust1", since = "1.0.0")]
248 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize,
249 capacity: usize) -> Vec<T> {
250 Vec { ptr: NonZero::new(ptr), len: length, cap: capacity }
253 /// Creates a vector by copying the elements from a raw pointer.
255 /// This function will copy `elts` contiguous elements starting at `ptr` into a new allocation
256 /// owned by the returned `Vec<T>`. The elements of the buffer are copied into the vector
257 /// without cloning, as if `ptr::read()` were called on them.
259 #[unstable(feature = "collections",
260 reason = "may be better expressed via composition")]
261 pub unsafe fn from_raw_buf(ptr: *const T, elts: usize) -> Vec<T> {
262 let mut dst = Vec::with_capacity(elts);
264 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
268 /// Returns the number of elements the vector can hold without
274 /// let vec: Vec<int> = Vec::with_capacity(10);
275 /// assert_eq!(vec.capacity(), 10);
278 #[stable(feature = "rust1", since = "1.0.0")]
279 pub fn capacity(&self) -> usize {
283 /// Reserves capacity for at least `additional` more elements to be inserted in the given
284 /// `Vec<T>`. The collection may reserve more space to avoid frequent reallocations.
288 /// Panics if the new capacity overflows `usize`.
293 /// let mut vec: Vec<int> = vec![1];
295 /// assert!(vec.capacity() >= 11);
297 #[stable(feature = "rust1", since = "1.0.0")]
298 pub fn reserve(&mut self, additional: usize) {
299 if self.cap - self.len < additional {
300 let err_msg = "Vec::reserve: `usize` overflow";
301 let new_cap = self.len.checked_add(additional).expect(err_msg)
302 .checked_next_power_of_two().expect(err_msg);
303 self.grow_capacity(new_cap);
307 /// Reserves the minimum capacity for exactly `additional` more elements to
308 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
311 /// Note that the allocator may give the collection more space than it
312 /// requests. Therefore capacity can not be relied upon to be precisely
313 /// minimal. Prefer `reserve` if future insertions are expected.
317 /// Panics if the new capacity overflows `usize`.
322 /// let mut vec: Vec<int> = vec![1];
323 /// vec.reserve_exact(10);
324 /// assert!(vec.capacity() >= 11);
326 #[stable(feature = "rust1", since = "1.0.0")]
327 pub fn reserve_exact(&mut self, additional: usize) {
328 if self.cap - self.len < additional {
329 match self.len.checked_add(additional) {
330 None => panic!("Vec::reserve: `usize` overflow"),
331 Some(new_cap) => self.grow_capacity(new_cap)
336 /// Shrinks the capacity of the vector as much as possible.
338 /// It will drop down as close as possible to the length but the allocator
339 /// may still inform the vector that there is space for a few more elements.
344 /// let mut vec: Vec<int> = Vec::with_capacity(10);
345 /// vec.push_all(&[1, 2, 3]);
346 /// assert_eq!(vec.capacity(), 10);
347 /// vec.shrink_to_fit();
348 /// assert!(vec.capacity() >= 3);
350 #[stable(feature = "rust1", since = "1.0.0")]
351 pub fn shrink_to_fit(&mut self) {
352 if mem::size_of::<T>() == 0 { return }
357 dealloc(*self.ptr, self.cap)
361 } else if self.cap != self.len {
363 // Overflow check is unnecessary as the vector is already at
365 let ptr = reallocate(*self.ptr as *mut u8,
366 self.cap * mem::size_of::<T>(),
367 self.len * mem::size_of::<T>(),
368 mem::min_align_of::<T>()) as *mut T;
369 if ptr.is_null() { ::alloc::oom() }
370 self.ptr = NonZero::new(ptr);
376 /// Convert the vector into Box<[T]>.
378 /// Note that this will drop any excess capacity. Calling this and
379 /// converting back to a vector with `into_vec()` is equivalent to calling
380 /// `shrink_to_fit()`.
381 #[unstable(feature = "collections")]
382 pub fn into_boxed_slice(mut self) -> Box<[T]> {
383 self.shrink_to_fit();
385 let xs: Box<[T]> = mem::transmute(&mut *self);
391 /// Shorten a vector, dropping excess elements.
393 /// If `len` is greater than the vector's current length, this has no
399 /// let mut vec = vec![1, 2, 3, 4];
401 /// assert_eq!(vec, vec![1, 2]);
403 #[stable(feature = "rust1", since = "1.0.0")]
404 pub fn truncate(&mut self, len: usize) {
406 // drop any extra elements
407 while len < self.len {
408 // decrement len before the read(), so a panic on Drop doesn't
409 // re-drop the just-failed value.
411 ptr::read(self.get_unchecked(self.len));
416 /// Returns a mutable slice of the elements of `self`.
421 /// fn foo(slice: &mut [int]) {}
423 /// let mut vec = vec![1, 2];
424 /// foo(vec.as_mut_slice());
427 #[stable(feature = "rust1", since = "1.0.0")]
428 pub fn as_mut_slice(&mut self) -> &mut [T] {
430 mem::transmute(RawSlice {
437 /// Creates a consuming iterator, that is, one that moves each value out of
438 /// the vector (from start to end). The vector cannot be used after calling
444 /// let v = vec!["a".to_string(), "b".to_string()];
445 /// for s in v.into_iter() {
446 /// // s has type String, not &String
447 /// println!("{}", s);
451 #[stable(feature = "rust1", since = "1.0.0")]
452 pub fn into_iter(self) -> IntoIter<T> {
456 let begin = ptr as *const T;
457 let end = if mem::size_of::<T>() == 0 {
458 (ptr as usize + self.len()) as *const T
460 ptr.offset(self.len() as isize) as *const T
463 IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end }
467 /// Sets the length of a vector.
469 /// This will explicitly set the size of the vector, without actually
470 /// modifying its buffers, so it is up to the caller to ensure that the
471 /// vector is actually the specified size.
476 /// let mut v = vec![1, 2, 3, 4];
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub unsafe fn set_len(&mut self, len: usize) {
487 /// Removes an element from anywhere in the vector and return it, replacing
488 /// it with the last element.
490 /// This does not preserve ordering, but is O(1).
494 /// Panics if `index` is out of bounds.
499 /// let mut v = vec!["foo", "bar", "baz", "qux"];
501 /// assert_eq!(v.swap_remove(1), "bar");
502 /// assert_eq!(v, vec!["foo", "qux", "baz"]);
504 /// assert_eq!(v.swap_remove(0), "foo");
505 /// assert_eq!(v, vec!["baz", "qux"]);
508 #[stable(feature = "rust1", since = "1.0.0")]
509 pub fn swap_remove(&mut self, index: usize) -> T {
510 let length = self.len();
511 self.swap(index, length - 1);
515 /// Inserts an element at position `index` within the vector, shifting all
516 /// elements after position `i` one position to the right.
520 /// Panics if `index` is not between `0` and the vector's length (both
521 /// bounds inclusive).
526 /// let mut vec = vec![1, 2, 3];
527 /// vec.insert(1, 4);
528 /// assert_eq!(vec, vec![1, 4, 2, 3]);
529 /// vec.insert(4, 5);
530 /// assert_eq!(vec, vec![1, 4, 2, 3, 5]);
532 #[stable(feature = "rust1", since = "1.0.0")]
533 pub fn insert(&mut self, index: usize, element: T) {
534 let len = self.len();
535 assert!(index <= len);
536 // space for the new element
539 unsafe { // infallible
540 // The spot to put the new value
542 let p = self.as_mut_ptr().offset(index as isize);
543 // Shift everything over to make space. (Duplicating the
544 // `index`th element into two consecutive places.)
545 ptr::copy_memory(p.offset(1), &*p, len - index);
546 // Write it in, overwriting the first copy of the `index`th
548 ptr::write(&mut *p, element);
550 self.set_len(len + 1);
554 /// Removes and returns the element at position `index` within the vector,
555 /// shifting all elements after position `index` one position to the left.
559 /// Panics if `i` is out of bounds.
564 /// let mut v = vec![1, 2, 3];
565 /// assert_eq!(v.remove(1), 2);
566 /// assert_eq!(v, vec![1, 3]);
568 #[stable(feature = "rust1", since = "1.0.0")]
569 pub fn remove(&mut self, index: usize) -> T {
570 let len = self.len();
571 assert!(index < len);
572 unsafe { // infallible
575 // the place we are taking from.
576 let ptr = self.as_mut_ptr().offset(index as isize);
577 // copy it out, unsafely having a copy of the value on
578 // the stack and in the vector at the same time.
579 ret = ptr::read(ptr);
581 // Shift everything down to fill in that spot.
582 ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
584 self.set_len(len - 1);
589 /// Retains only the elements specified by the predicate.
591 /// In other words, remove all elements `e` such that `f(&e)` returns false.
592 /// This method operates in place and preserves the order of the retained
598 /// let mut vec = vec![1, 2, 3, 4];
599 /// vec.retain(|&x| x%2 == 0);
600 /// assert_eq!(vec, vec![2, 4]);
602 #[stable(feature = "rust1", since = "1.0.0")]
603 pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
604 let len = self.len();
618 self.truncate(len - del);
622 /// Appends an element to the back of a collection.
626 /// Panics if the number of elements in the vector overflows a `usize`.
631 /// let mut vec = vec!(1, 2);
633 /// assert_eq!(vec, vec!(1, 2, 3));
636 #[stable(feature = "rust1", since = "1.0.0")]
637 pub fn push(&mut self, value: T) {
638 if mem::size_of::<T>() == 0 {
639 // zero-size types consume no memory, so we can't rely on the
640 // address space running out
641 self.len = self.len.checked_add(1).expect("length overflow");
642 unsafe { mem::forget(value); }
645 if self.len == self.cap {
646 let old_size = self.cap * mem::size_of::<T>();
647 let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
648 if old_size > size { panic!("capacity overflow") }
650 let ptr = alloc_or_realloc(*self.ptr, old_size, size);
651 if ptr.is_null() { ::alloc::oom() }
652 self.ptr = NonZero::new(ptr);
654 self.cap = max(self.cap, 2) * 2;
658 let end = (*self.ptr).offset(self.len as isize);
659 ptr::write(&mut *end, value);
664 /// Removes the last element from a vector and returns it, or `None` if it is empty.
669 /// let mut vec = vec![1, 2, 3];
670 /// assert_eq!(vec.pop(), Some(3));
671 /// assert_eq!(vec, vec![1, 2]);
674 #[stable(feature = "rust1", since = "1.0.0")]
675 pub fn pop(&mut self) -> Option<T> {
681 Some(ptr::read(self.get_unchecked(self.len())))
686 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
690 /// Panics if the number of elements in the vector overflows a `usize`.
694 /// let mut vec = vec![1, 2, 3];
695 /// let mut vec2 = vec![4, 5, 6];
696 /// vec.append(&mut vec2);
697 /// assert_eq!(vec, vec![1, 2, 3, 4, 5, 6]);
698 /// assert_eq!(vec2, vec![]);
701 #[unstable(feature = "collections",
702 reason = "new API, waiting for dust to settle")]
703 pub fn append(&mut self, other: &mut Self) {
704 if mem::size_of::<T>() == 0 {
705 // zero-size types consume no memory, so we can't rely on the
706 // address space running out
707 self.len = self.len.checked_add(other.len()).expect("length overflow");
708 unsafe { other.set_len(0) }
711 self.reserve(other.len());
712 let len = self.len();
714 ptr::copy_nonoverlapping_memory(
715 self.get_unchecked_mut(len),
720 self.len += other.len();
721 unsafe { other.set_len(0); }
724 /// Creates a draining iterator that clears the `Vec` and iterates over
725 /// the removed items from start to end.
730 /// let mut v = vec!["a".to_string(), "b".to_string()];
731 /// for s in v.drain() {
732 /// // s has type String, not &String
733 /// println!("{}", s);
735 /// assert!(v.is_empty());
738 #[unstable(feature = "collections",
739 reason = "matches collection reform specification, waiting for dust to settle")]
740 pub fn drain(&mut self) -> Drain<T> {
742 let begin = *self.ptr as *const T;
743 let end = if mem::size_of::<T>() == 0 {
744 (*self.ptr as usize + self.len()) as *const T
746 (*self.ptr).offset(self.len() as isize) as *const T
752 marker: ContravariantLifetime,
757 /// Clears the vector, removing all values.
762 /// let mut v = vec![1, 2, 3];
766 /// assert!(v.is_empty());
769 #[stable(feature = "rust1", since = "1.0.0")]
770 pub fn clear(&mut self) {
774 /// Returns the number of elements in the vector.
779 /// let a = vec![1, 2, 3];
780 /// assert_eq!(a.len(), 3);
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub fn len(&self) -> usize { self.len }
786 /// Returns `true` if the vector contains no elements.
791 /// let mut v = Vec::new();
792 /// assert!(v.is_empty());
795 /// assert!(!v.is_empty());
797 #[stable(feature = "rust1", since = "1.0.0")]
798 pub fn is_empty(&self) -> bool { self.len() == 0 }
800 /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same
801 /// size and in case they are not zero-sized the same minimal alignment.
805 /// Panics if `T` and `U` have differing sizes or are not zero-sized and
806 /// have differing minimal alignments.
811 /// let v = vec![0, 1, 2];
812 /// let w = v.map_in_place(|i| i + 3);
813 /// assert_eq!(w.as_slice(), [3, 4, 5].as_slice());
815 /// #[derive(PartialEq, Debug)]
816 /// struct Newtype(u8);
817 /// let bytes = vec![0x11, 0x22];
818 /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x));
819 /// assert_eq!(newtyped_bytes.as_slice(), [Newtype(0x11), Newtype(0x22)].as_slice());
821 #[unstable(feature = "collections",
822 reason = "API may change to provide stronger guarantees")]
823 pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
824 // FIXME: Assert statically that the types `T` and `U` have the same
826 assert!(mem::size_of::<T>() == mem::size_of::<U>());
830 if mem::size_of::<T>() != 0 {
831 // FIXME: Assert statically that the types `T` and `U` have the
832 // same minimal alignment in case they are not zero-sized.
834 // These asserts are necessary because the `min_align_of` of the
835 // types are passed to the allocator by `Vec`.
836 assert!(mem::min_align_of::<T>() == mem::min_align_of::<U>());
838 // This `as isize` cast is safe, because the size of the elements of the
839 // vector is not 0, and:
841 // 1) If the size of the elements in the vector is 1, the `int` may
842 // overflow, but it has the correct bit pattern so that the
843 // `.offset()` function will work.
846 // Address space 0x0-0xF.
847 // `u8` array at: 0x1.
848 // Size of `u8` array: 0x8.
849 // Calculated `offset`: -0x8.
850 // After `array.offset(offset)`: 0x9.
851 // (0x1 + 0x8 = 0x1 - 0x8)
853 // 2) If the size of the elements in the vector is >1, the `usize` ->
854 // `int` conversion can't overflow.
855 let offset = vec.len() as isize;
856 let start = vec.as_mut_ptr();
858 let mut pv = PartialVecNonZeroSized {
862 // This points inside the vector, as the vector has length
864 end_t: unsafe { start.offset(offset) },
865 start_u: start as *mut U,
866 end_u: start as *mut U,
877 while pv.end_u as *mut T != pv.end_t {
881 // +-+-+-+-+-+-+-+-+-+
882 // |U|...|U|T|T|...|T|
883 // +-+-+-+-+-+-+-+-+-+
887 let t = ptr::read(pv.start_t);
890 // +-+-+-+-+-+-+-+-+-+
891 // |U|...|U|X|T|...|T|
892 // +-+-+-+-+-+-+-+-+-+
895 // We must not panic here, one cell is marked as `T`
896 // although it is not `T`.
898 pv.start_t = pv.start_t.offset(1);
901 // +-+-+-+-+-+-+-+-+-+
902 // |U|...|U|X|T|...|T|
903 // +-+-+-+-+-+-+-+-+-+
906 // We may panic again.
908 // The function given by the user might panic.
911 ptr::write(pv.end_u, u);
914 // +-+-+-+-+-+-+-+-+-+
915 // |U|...|U|U|T|...|T|
916 // +-+-+-+-+-+-+-+-+-+
919 // We should not panic here, because that would leak the `U`
920 // pointed to by `end_u`.
922 pv.end_u = pv.end_u.offset(1);
925 // +-+-+-+-+-+-+-+-+-+
926 // |U|...|U|U|T|...|T|
927 // +-+-+-+-+-+-+-+-+-+
930 // We may panic again.
942 // Extract `vec` and prevent the destructor of
943 // `PartialVecNonZeroSized` from running. Note that none of the
944 // function calls can panic, thus no resources can be leaked (as the
945 // `vec` member of `PartialVec` is the only one which holds
946 // allocations -- and it is returned from this function. None of
949 let vec_len = pv.vec.len();
950 let vec_cap = pv.vec.capacity();
951 let vec_ptr = pv.vec.as_mut_ptr() as *mut U;
953 Vec::from_raw_parts(vec_ptr, vec_len, vec_cap)
956 // Put the `Vec` into the `PartialVecZeroSized` structure and
957 // prevent the destructor of the `Vec` from running. Since the
958 // `Vec` contained zero-sized objects, it did not allocate, so we
959 // are not leaking memory here.
960 let mut pv = PartialVecZeroSized::<T,U> {
963 marker_t: InvariantType,
964 marker_u: InvariantType,
966 unsafe { mem::forget(vec); }
968 while pv.num_t != 0 {
970 // Create a `T` out of thin air and decrement `num_t`. This
971 // must not panic between these steps, as otherwise a
972 // destructor of `T` which doesn't exist runs.
973 let t = mem::uninitialized();
976 // The function given by the user might panic.
979 // Forget the `U` and increment `num_u`. This increment
980 // cannot overflow the `usize` as we only do this for a
981 // number of times that fits into a `usize` (and start with
982 // `0`). Again, we should not panic between these steps.
987 // Create a `Vec` from our `PartialVecZeroSized` and make sure the
988 // destructor of the latter will not run. None of this can panic.
989 let mut result = Vec::new();
991 result.set_len(pv.num_u);
998 /// Splits the collection into two at the given index.
1000 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1001 /// and the returned `Self` contains elements `[at, len)`.
1003 /// Note that the capacity of `self` does not change.
1007 /// let mut vec = vec![1,2,3];
1008 /// let vec2 = vec.split_off(1);
1009 /// assert_eq!(vec, vec![1]);
1010 /// assert_eq!(vec2, vec![2, 3]);
1013 #[unstable(feature = "collections",
1014 reason = "new API, waiting for dust to settle")]
1015 pub fn split_off(&mut self, at: usize) -> Self {
1016 assert!(at < self.len(), "`at` out of bounds");
1018 let other_len = self.len - at;
1019 let mut other = Vec::with_capacity(other_len);
1021 // Unsafely `set_len` and copy items to `other`.
1024 other.set_len(other_len);
1026 ptr::copy_nonoverlapping_memory(
1028 self.as_ptr().offset(at as isize),
1036 impl<T: Clone> Vec<T> {
1037 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1039 /// Calls either `extend()` or `truncate()` depending on whether `new_len`
1040 /// is larger than the current value of `len()` or not.
1045 /// let mut vec = vec!["hello"];
1046 /// vec.resize(3, "world");
1047 /// assert_eq!(vec, vec!["hello", "world", "world"]);
1049 /// let mut vec = vec![1, 2, 3, 4];
1050 /// vec.resize(2, 0);
1051 /// assert_eq!(vec, vec![1, 2]);
1053 #[unstable(feature = "collections",
1054 reason = "matches collection reform specification; waiting for dust to settle")]
1055 pub fn resize(&mut self, new_len: usize, value: T) {
1056 let len = self.len();
1059 self.extend(repeat(value).take(new_len - len));
1061 self.truncate(new_len);
1065 /// Appends all elements in a slice to the `Vec`.
1067 /// Iterates over the slice `other`, clones each element, and then appends
1068 /// it to this `Vec`. The `other` vector is traversed in-order.
1073 /// let mut vec = vec![1];
1074 /// vec.push_all(&[2, 3, 4]);
1075 /// assert_eq!(vec, vec![1, 2, 3, 4]);
1078 #[unstable(feature = "collections",
1079 reason = "likely to be replaced by a more optimized extend")]
1080 pub fn push_all(&mut self, other: &[T]) {
1081 self.reserve(other.len());
1083 for i in 0..other.len() {
1084 let len = self.len();
1086 // Unsafe code so this can be optimised to a memcpy (or something similarly
1087 // fast) when T is Copy. LLVM is easily confused, so any extra operations
1088 // during the loop can prevent this optimisation.
1091 self.get_unchecked_mut(len),
1092 other.get_unchecked(i).clone());
1093 self.set_len(len + 1);
1099 impl<T: PartialEq> Vec<T> {
1100 /// Removes consecutive repeated elements in the vector.
1102 /// If the vector is sorted, this removes all duplicates.
1107 /// let mut vec = vec![1, 2, 2, 3, 2];
1111 /// assert_eq!(vec, vec![1, 2, 3, 2]);
1113 #[stable(feature = "rust1", since = "1.0.0")]
1114 pub fn dedup(&mut self) {
1116 // Although we have a mutable reference to `self`, we cannot make
1117 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1118 // must ensure that the vector is in a valid state at all time.
1120 // The way that we handle this is by using swaps; we iterate
1121 // over all the elements, swapping as we go so that at the end
1122 // the elements we wish to keep are in the front, and those we
1123 // wish to reject are at the back. We can then truncate the
1124 // vector. This operation is still O(n).
1126 // Example: We start in this state, where `r` represents "next
1127 // read" and `w` represents "next_write`.
1130 // +---+---+---+---+---+---+
1131 // | 0 | 1 | 1 | 2 | 3 | 3 |
1132 // +---+---+---+---+---+---+
1135 // Comparing self[r] against self[w-1], this is not a duplicate, so
1136 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1137 // r and w, leaving us with:
1140 // +---+---+---+---+---+---+
1141 // | 0 | 1 | 1 | 2 | 3 | 3 |
1142 // +---+---+---+---+---+---+
1145 // Comparing self[r] against self[w-1], this value is a duplicate,
1146 // so we increment `r` but leave everything else unchanged:
1149 // +---+---+---+---+---+---+
1150 // | 0 | 1 | 1 | 2 | 3 | 3 |
1151 // +---+---+---+---+---+---+
1154 // Comparing self[r] against self[w-1], this is not a duplicate,
1155 // so swap self[r] and self[w] and advance r and w:
1158 // +---+---+---+---+---+---+
1159 // | 0 | 1 | 2 | 1 | 3 | 3 |
1160 // +---+---+---+---+---+---+
1163 // Not a duplicate, repeat:
1166 // +---+---+---+---+---+---+
1167 // | 0 | 1 | 2 | 3 | 1 | 3 |
1168 // +---+---+---+---+---+---+
1171 // Duplicate, advance r. End of vec. Truncate to w.
1173 let ln = self.len();
1174 if ln < 1 { return; }
1176 // Avoid bounds checks by using unsafe pointers.
1177 let p = self.as_mut_ptr();
1182 let p_r = p.offset(r as isize);
1183 let p_wm1 = p.offset((w - 1) as isize);
1186 let p_w = p_wm1.offset(1);
1187 mem::swap(&mut *p_r, &mut *p_w);
1199 ////////////////////////////////////////////////////////////////////////////////
1200 // Internal methods and functions
1201 ////////////////////////////////////////////////////////////////////////////////
1204 /// Reserves capacity for exactly `capacity` elements in the given vector.
1206 /// If the capacity for `self` is already equal to or greater than the
1207 /// requested capacity, then no action is taken.
1208 fn grow_capacity(&mut self, capacity: usize) {
1209 if mem::size_of::<T>() == 0 { return }
1211 if capacity > self.cap {
1212 let size = capacity.checked_mul(mem::size_of::<T>())
1213 .expect("capacity overflow");
1215 let ptr = alloc_or_realloc(*self.ptr, self.cap * mem::size_of::<T>(), size);
1216 if ptr.is_null() { ::alloc::oom() }
1217 self.ptr = NonZero::new(ptr);
1219 self.cap = capacity;
1224 // FIXME: #13996: need a way to mark the return value as `noalias`
1226 unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: usize, size: usize) -> *mut T {
1228 allocate(size, mem::min_align_of::<T>()) as *mut T
1230 reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T
1235 unsafe fn dealloc<T>(ptr: *mut T, len: usize) {
1236 if mem::size_of::<T>() != 0 {
1237 deallocate(ptr as *mut u8,
1238 len * mem::size_of::<T>(),
1239 mem::min_align_of::<T>())
1243 ////////////////////////////////////////////////////////////////////////////////
1244 // Common trait implementations for Vec
1245 ////////////////////////////////////////////////////////////////////////////////
1247 #[unstable(feature = "collections")]
1248 impl<T:Clone> Clone for Vec<T> {
1249 fn clone(&self) -> Vec<T> { ::slice::SliceExt::to_vec(&**self) }
1251 fn clone_from(&mut self, other: &Vec<T>) {
1252 // drop anything in self that will not be overwritten
1253 if self.len() > other.len() {
1254 self.truncate(other.len())
1257 // reuse the contained values' allocations/resources.
1258 for (place, thing) in self.iter_mut().zip(other.iter()) {
1259 place.clone_from(thing)
1262 // self.len <= other.len due to the truncate above, so the
1263 // slice here is always in-bounds.
1264 let slice = &other[self.len()..];
1265 self.push_all(slice);
1269 impl<S: hash::Writer + hash::Hasher, T: Hash<S>> Hash<S> for Vec<T> {
1271 fn hash(&self, state: &mut S) {
1272 Hash::hash(&**self, state)
1276 #[stable(feature = "rust1", since = "1.0.0")]
1277 impl<T> Index<usize> for Vec<T> {
1281 fn index(&self, index: &usize) -> &T {
1282 // NB built-in indexing via `&[T]`
1287 #[stable(feature = "rust1", since = "1.0.0")]
1288 impl<T> IndexMut<usize> for Vec<T> {
1292 fn index_mut(&mut self, index: &usize) -> &mut T {
1293 // NB built-in indexing via `&mut [T]`
1294 &mut (**self)[*index]
1299 #[stable(feature = "rust1", since = "1.0.0")]
1300 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1303 fn index(&self, index: &ops::Range<usize>) -> &[T] {
1304 Index::index(&**self, index)
1307 #[stable(feature = "rust1", since = "1.0.0")]
1308 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1311 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
1312 Index::index(&**self, index)
1315 #[stable(feature = "rust1", since = "1.0.0")]
1316 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1319 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
1320 Index::index(&**self, index)
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1327 fn index(&self, _index: &ops::RangeFull) -> &[T] {
1332 #[stable(feature = "rust1", since = "1.0.0")]
1333 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1336 fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
1337 IndexMut::index_mut(&mut **self, index)
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1344 fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
1345 IndexMut::index_mut(&mut **self, index)
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1352 fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
1353 IndexMut::index_mut(&mut **self, index)
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1360 fn index_mut(&mut self, _index: &ops::RangeFull) -> &mut [T] {
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl<T> ops::Deref for Vec<T> {
1369 fn deref(&self) -> &[T] { self.as_slice() }
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<T> ops::DerefMut for Vec<T> {
1374 fn deref_mut(&mut self) -> &mut [T] { self.as_mut_slice() }
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<T> FromIterator<T> for Vec<T> {
1380 fn from_iter<I:Iterator<Item=T>>(iterator: I) -> Vec<T> {
1381 let (lower, _) = iterator.size_hint();
1382 let mut vector = Vec::with_capacity(lower);
1383 for element in iterator {
1384 vector.push(element)
1390 impl<T> IntoIterator for Vec<T> {
1391 type Iter = IntoIter<T>;
1393 fn into_iter(self) -> IntoIter<T> {
1398 impl<'a, T> IntoIterator for &'a Vec<T> {
1399 type Iter = slice::Iter<'a, T>;
1401 fn into_iter(self) -> slice::Iter<'a, T> {
1406 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1407 type Iter = slice::IterMut<'a, T>;
1409 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1414 #[unstable(feature = "collections", reason = "waiting on Extend stability")]
1415 impl<T> Extend<T> for Vec<T> {
1417 fn extend<I: Iterator<Item=T>>(&mut self, iterator: I) {
1418 let (lower, _) = iterator.size_hint();
1419 self.reserve(lower);
1420 for element in iterator {
1426 impl<A, B> PartialEq<Vec<B>> for Vec<A> where A: PartialEq<B> {
1428 fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1430 fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1433 macro_rules! impl_eq {
1434 ($lhs:ty, $rhs:ty) => {
1435 impl<'b, A, B> PartialEq<$rhs> for $lhs where A: PartialEq<B> {
1437 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1439 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1442 impl<'b, A, B> PartialEq<$lhs> for $rhs where B: PartialEq<A> {
1444 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
1446 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
1451 impl_eq! { Vec<A>, &'b [B] }
1452 impl_eq! { Vec<A>, &'b mut [B] }
1454 impl<'a, A, B> PartialEq<Vec<B>> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1456 fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1458 fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1461 impl<'a, A, B> PartialEq<CowVec<'a, A>> for Vec<B> where A: Clone, B: PartialEq<A> {
1463 fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1465 fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1468 macro_rules! impl_eq_for_cowvec {
1470 impl<'a, 'b, A, B> PartialEq<$rhs> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1472 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1474 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1477 impl<'a, 'b, A, B> PartialEq<CowVec<'a, A>> for $rhs where A: Clone, B: PartialEq<A> {
1479 fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1481 fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1486 impl_eq_for_cowvec! { &'b [B] }
1487 impl_eq_for_cowvec! { &'b mut [B] }
1489 #[unstable(feature = "collections",
1490 reason = "waiting on PartialOrd stability")]
1491 impl<T: PartialOrd> PartialOrd for Vec<T> {
1493 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1494 PartialOrd::partial_cmp(&**self, &**other)
1498 #[unstable(feature = "collections", reason = "waiting on Eq stability")]
1499 impl<T: Eq> Eq for Vec<T> {}
1501 #[unstable(feature = "collections", reason = "waiting on Ord stability")]
1502 impl<T: Ord> Ord for Vec<T> {
1504 fn cmp(&self, other: &Vec<T>) -> Ordering {
1505 Ord::cmp(&**self, &**other)
1509 impl<T> AsSlice<T> for Vec<T> {
1510 /// Returns a slice into `self`.
1515 /// fn foo(slice: &[int]) {}
1517 /// let vec = vec![1, 2];
1518 /// foo(vec.as_slice());
1521 #[stable(feature = "rust1", since = "1.0.0")]
1522 fn as_slice(&self) -> &[T] {
1524 mem::transmute(RawSlice {
1532 #[unstable(feature = "collections",
1533 reason = "recent addition, needs more experience")]
1534 impl<'a, T: Clone> Add<&'a [T]> for Vec<T> {
1535 type Output = Vec<T>;
1538 fn add(mut self, rhs: &[T]) -> Vec<T> {
1544 #[unsafe_destructor]
1545 #[stable(feature = "rust1", since = "1.0.0")]
1546 impl<T> Drop for Vec<T> {
1547 fn drop(&mut self) {
1548 // This is (and should always remain) a no-op if the fields are
1549 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1555 dealloc(*self.ptr, self.cap)
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<T> Default for Vec<T> {
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 fn default() -> Vec<T> {
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1571 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1572 fmt::Debug::fmt(&**self, f)
1576 ////////////////////////////////////////////////////////////////////////////////
1578 ////////////////////////////////////////////////////////////////////////////////
1580 #[unstable(feature = "collections",
1581 reason = "unclear how valuable this alias is")]
1582 /// A clone-on-write vector
1583 pub type CowVec<'a, T> = Cow<'a, Vec<T>, [T]>;
1585 #[unstable(feature = "collections")]
1586 impl<'a, T> FromIterator<T> for CowVec<'a, T> where T: Clone {
1587 fn from_iter<I: Iterator<Item=T>>(it: I) -> CowVec<'a, T> {
1588 Cow::Owned(FromIterator::from_iter(it))
1592 impl<'a, T: 'a> IntoCow<'a, Vec<T>, [T]> for Vec<T> where T: Clone {
1593 fn into_cow(self) -> CowVec<'a, T> {
1598 impl<'a, T> IntoCow<'a, Vec<T>, [T]> for &'a [T] where T: Clone {
1599 fn into_cow(self) -> CowVec<'a, T> {
1604 ////////////////////////////////////////////////////////////////////////////////
1606 ////////////////////////////////////////////////////////////////////////////////
1608 /// An iterator that moves out of a vector.
1609 #[stable(feature = "rust1", since = "1.0.0")]
1610 pub struct IntoIter<T> {
1611 allocation: *mut T, // the block of memory allocated for the vector
1612 cap: usize, // the capacity of the vector
1617 unsafe impl<T: Send> Send for IntoIter<T> { }
1618 unsafe impl<T: Sync> Sync for IntoIter<T> { }
1620 impl<T> IntoIter<T> {
1622 /// Drops all items that have not yet been moved and returns the empty vector.
1623 #[unstable(feature = "collections")]
1624 pub fn into_inner(mut self) -> Vec<T> {
1626 for _x in self.by_ref() { }
1627 let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
1629 Vec { ptr: NonZero::new(allocation), cap: cap, len: 0 }
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 impl<T> Iterator for IntoIter<T> {
1639 fn next(&mut self) -> Option<T> {
1641 if self.ptr == self.end {
1644 if mem::size_of::<T>() == 0 {
1645 // purposefully don't use 'ptr.offset' because for
1646 // vectors with 0-size elements this would return the
1648 self.ptr = mem::transmute(self.ptr as usize + 1);
1650 // Use a non-null pointer value
1651 Some(ptr::read(EMPTY as *mut T))
1654 self.ptr = self.ptr.offset(1);
1656 Some(ptr::read(old))
1663 fn size_hint(&self) -> (usize, Option<usize>) {
1664 let diff = (self.end as usize) - (self.ptr as usize);
1665 let size = mem::size_of::<T>();
1666 let exact = diff / (if size == 0 {1} else {size});
1667 (exact, Some(exact))
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<T> DoubleEndedIterator for IntoIter<T> {
1674 fn next_back(&mut self) -> Option<T> {
1676 if self.end == self.ptr {
1679 if mem::size_of::<T>() == 0 {
1680 // See above for why 'ptr.offset' isn't used
1681 self.end = mem::transmute(self.end as usize - 1);
1683 // Use a non-null pointer value
1684 Some(ptr::read(EMPTY as *mut T))
1686 self.end = self.end.offset(-1);
1688 Some(ptr::read(mem::transmute(self.end)))
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<T> ExactSizeIterator for IntoIter<T> {}
1698 #[unsafe_destructor]
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl<T> Drop for IntoIter<T> {
1701 fn drop(&mut self) {
1702 // destroy the remaining elements
1704 for _x in self.by_ref() {}
1706 dealloc(self.allocation, self.cap);
1712 /// An iterator that drains a vector.
1713 #[unsafe_no_drop_flag]
1714 #[unstable(feature = "collections",
1715 reason = "recently added as part of collections reform 2")]
1716 pub struct Drain<'a, T> {
1719 marker: ContravariantLifetime<'a>,
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl<'a, T> Iterator for Drain<'a, T> {
1727 fn next(&mut self) -> Option<T> {
1729 if self.ptr == self.end {
1732 if mem::size_of::<T>() == 0 {
1733 // purposefully don't use 'ptr.offset' because for
1734 // vectors with 0-size elements this would return the
1736 self.ptr = mem::transmute(self.ptr as usize + 1);
1738 // Use a non-null pointer value
1739 Some(ptr::read(EMPTY as *mut T))
1742 self.ptr = self.ptr.offset(1);
1744 Some(ptr::read(old))
1751 fn size_hint(&self) -> (usize, Option<usize>) {
1752 let diff = (self.end as usize) - (self.ptr as usize);
1753 let size = mem::size_of::<T>();
1754 let exact = diff / (if size == 0 {1} else {size});
1755 (exact, Some(exact))
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1762 fn next_back(&mut self) -> Option<T> {
1764 if self.end == self.ptr {
1767 if mem::size_of::<T>() == 0 {
1768 // See above for why 'ptr.offset' isn't used
1769 self.end = mem::transmute(self.end as usize - 1);
1771 // Use a non-null pointer value
1772 Some(ptr::read(EMPTY as *mut T))
1774 self.end = self.end.offset(-1);
1776 Some(ptr::read(self.end))
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1786 #[unsafe_destructor]
1787 #[stable(feature = "rust1", since = "1.0.0")]
1788 impl<'a, T> Drop for Drain<'a, T> {
1789 fn drop(&mut self) {
1790 // self.ptr == self.end == null if drop has already been called,
1791 // so we can use #[unsafe_no_drop_flag].
1793 // destroy the remaining elements
1794 for _x in self.by_ref() {}
1798 ////////////////////////////////////////////////////////////////////////////////
1799 // Conversion from &[T] to &Vec<T>
1800 ////////////////////////////////////////////////////////////////////////////////
1802 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1803 #[unstable(feature = "collections")]
1804 pub struct DerefVec<'a, T> {
1806 l: ContravariantLifetime<'a>
1809 #[unstable(feature = "collections")]
1810 impl<'a, T> Deref for DerefVec<'a, T> {
1811 type Target = Vec<T>;
1813 fn deref<'b>(&'b self) -> &'b Vec<T> {
1818 // Prevent the inner `Vec<T>` from attempting to deallocate memory.
1819 #[unsafe_destructor]
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 impl<'a, T> Drop for DerefVec<'a, T> {
1822 fn drop(&mut self) {
1828 /// Convert a slice to a wrapper type providing a `&Vec<T>` reference.
1829 #[unstable(feature = "collections")]
1830 pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
1833 x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1834 l: ContravariantLifetime::<'a>
1839 ////////////////////////////////////////////////////////////////////////////////
1840 // Partial vec, used for map_in_place
1841 ////////////////////////////////////////////////////////////////////////////////
1843 /// An owned, partially type-converted vector of elements with non-zero size.
1845 /// `T` and `U` must have the same, non-zero size. They must also have the same
1848 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
1849 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
1850 /// destructed. Additionally the underlying storage of `vec` will be freed.
1851 struct PartialVecNonZeroSized<T,U> {
1860 /// An owned, partially type-converted vector of zero-sized elements.
1862 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1864 struct PartialVecZeroSized<T,U> {
1867 marker_t: InvariantType<T>,
1868 marker_u: InvariantType<U>,
1871 #[unsafe_destructor]
1872 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1873 fn drop(&mut self) {
1875 // `vec` hasn't been modified until now. As it has a length
1876 // currently, this would run destructors of `T`s which might not be
1877 // there. So at first, set `vec`s length to `0`. This must be done
1878 // at first to remain memory-safe as the destructors of `U` or `T`
1879 // might cause unwinding where `vec`s destructor would be executed.
1880 self.vec.set_len(0);
1882 // We have instances of `U`s and `T`s in `vec`. Destruct them.
1883 while self.start_u != self.end_u {
1884 let _ = ptr::read(self.start_u); // Run a `U` destructor.
1885 self.start_u = self.start_u.offset(1);
1887 while self.start_t != self.end_t {
1888 let _ = ptr::read(self.start_t); // Run a `T` destructor.
1889 self.start_t = self.start_t.offset(1);
1891 // After this destructor ran, the destructor of `vec` will run,
1892 // deallocating the underlying memory.
1897 #[unsafe_destructor]
1898 impl<T,U> Drop for PartialVecZeroSized<T,U> {
1899 fn drop(&mut self) {
1901 // Destruct the instances of `T` and `U` this struct owns.
1902 while self.num_t != 0 {
1903 let _: T = mem::uninitialized(); // Run a `T` destructor.
1906 while self.num_u != 0 {
1907 let _: U = mem::uninitialized(); // Run a `U` destructor.
1917 use core::mem::size_of;
1918 use core::iter::repeat;
1922 struct DropCounter<'a> {
1926 #[unsafe_destructor]
1927 impl<'a> Drop for DropCounter<'a> {
1928 fn drop(&mut self) {
1935 let xs = [1u8, 2u8, 3u8];
1936 assert_eq!(&**as_vec(&xs), xs);
1940 fn test_as_vec_dtor() {
1941 let (mut count_x, mut count_y) = (0, 0);
1943 let xs = &[DropCounter { count: &mut count_x }, DropCounter { count: &mut count_y }];
1944 assert_eq!(as_vec(xs).len(), 2);
1946 assert_eq!(count_x, 1);
1947 assert_eq!(count_y, 1);
1951 fn test_small_vec_struct() {
1952 assert!(size_of::<Vec<u8>>() == size_of::<usize>() * 3);
1956 fn test_double_drop() {
1962 let (mut count_x, mut count_y) = (0, 0);
1964 let mut tv = TwoVec {
1968 tv.x.push(DropCounter {count: &mut count_x});
1969 tv.y.push(DropCounter {count: &mut count_y});
1971 // If Vec had a drop flag, here is where it would be zeroed.
1972 // Instead, it should rely on its internal state to prevent
1973 // doing anything significant when dropped multiple times.
1976 // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1979 assert_eq!(count_x, 1);
1980 assert_eq!(count_y, 1);
1985 let mut v = Vec::new();
1986 assert_eq!(v.capacity(), 0);
1989 assert!(v.capacity() >= 2);
1995 assert!(v.capacity() >= 16);
1997 assert!(v.capacity() >= 32);
2002 assert!(v.capacity() >= 33)
2007 let mut v = Vec::new();
2008 let mut w = Vec::new();
2011 for i in 0..3 { w.push(i) }
2016 for i in 3..10 { w.push(i) }
2022 fn test_slice_from_mut() {
2023 let mut values = vec![1, 2, 3, 4, 5];
2025 let slice = &mut values[2 ..];
2026 assert!(slice == [3, 4, 5]);
2032 assert!(values == [1, 2, 5, 6, 7]);
2036 fn test_slice_to_mut() {
2037 let mut values = vec![1, 2, 3, 4, 5];
2039 let slice = &mut values[.. 2];
2040 assert!(slice == [1, 2]);
2046 assert!(values == [2, 3, 3, 4, 5]);
2050 fn test_split_at_mut() {
2051 let mut values = vec![1, 2, 3, 4, 5];
2053 let (left, right) = values.split_at_mut(2);
2055 let left: &[_] = left;
2056 assert!(&left[..left.len()] == &[1, 2][]);
2063 let right: &[_] = right;
2064 assert!(&right[..right.len()] == &[3, 4, 5][]);
2071 assert!(values == vec![2, 3, 5, 6, 7]);
2076 let v: Vec<i32> = vec![];
2077 let w = vec!(1, 2, 3);
2079 assert_eq!(v, v.clone());
2083 // they should be disjoint in memory.
2084 assert!(w.as_ptr() != z.as_ptr())
2088 fn test_clone_from() {
2090 let three = vec!(box 1, box 2, box 3);
2091 let two = vec!(box 4, box 5);
2093 v.clone_from(&three);
2094 assert_eq!(v, three);
2097 v.clone_from(&three);
2098 assert_eq!(v, three);
2105 v.clone_from(&three);
2106 assert_eq!(v, three)
2111 let mut vec = vec![1, 2, 3, 4];
2112 vec.retain(|&x| x % 2 == 0);
2113 assert!(vec == vec![2, 4]);
2117 fn zero_sized_values() {
2118 let mut v = Vec::new();
2119 assert_eq!(v.len(), 0);
2121 assert_eq!(v.len(), 1);
2123 assert_eq!(v.len(), 2);
2124 assert_eq!(v.pop(), Some(()));
2125 assert_eq!(v.pop(), Some(()));
2126 assert_eq!(v.pop(), None);
2128 assert_eq!(v.iter().count(), 0);
2130 assert_eq!(v.iter().count(), 1);
2132 assert_eq!(v.iter().count(), 2);
2136 assert_eq!(v.iter_mut().count(), 2);
2138 assert_eq!(v.iter_mut().count(), 3);
2140 assert_eq!(v.iter_mut().count(), 4);
2142 for &mut () in &mut v {}
2143 unsafe { v.set_len(0); }
2144 assert_eq!(v.iter_mut().count(), 0);
2148 fn test_partition() {
2149 assert_eq!(vec![].into_iter().partition(|x: &int| *x < 3), (vec![], vec![]));
2150 assert_eq!(vec![1, 2, 3].into_iter().partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2151 assert_eq!(vec![1, 2, 3].into_iter().partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2152 assert_eq!(vec![1, 2, 3].into_iter().partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2156 fn test_zip_unzip() {
2157 let z1 = vec![(1, 4), (2, 5), (3, 6)];
2159 let (left, right): (Vec<_>, Vec<_>) = z1.iter().map(|&x| x).unzip();
2161 assert_eq!((1, 4), (left[0], right[0]));
2162 assert_eq!((2, 5), (left[1], right[1]));
2163 assert_eq!((3, 6), (left[2], right[2]));
2167 fn test_unsafe_ptrs() {
2169 // Test on-stack copy-from-buf.
2171 let ptr = a.as_ptr();
2172 let b = Vec::from_raw_buf(ptr, 3);
2173 assert_eq!(b, vec![1, 2, 3]);
2175 // Test on-heap copy-from-buf.
2176 let c = vec![1, 2, 3, 4, 5];
2177 let ptr = c.as_ptr();
2178 let d = Vec::from_raw_buf(ptr, 5);
2179 assert_eq!(d, vec![1, 2, 3, 4, 5]);
2184 fn test_vec_truncate_drop() {
2185 static mut drops: u32 = 0;
2187 impl Drop for Elem {
2188 fn drop(&mut self) {
2189 unsafe { drops += 1; }
2193 let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
2194 assert_eq!(unsafe { drops }, 0);
2196 assert_eq!(unsafe { drops }, 2);
2198 assert_eq!(unsafe { drops }, 5);
2203 fn test_vec_truncate_fail() {
2204 struct BadElem(i32);
2205 impl Drop for BadElem {
2206 fn drop(&mut self) {
2207 let BadElem(ref mut x) = *self;
2208 if *x == 0xbadbeef {
2209 panic!("BadElem panic: 0xbadbeef")
2214 let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
2220 let vec = vec![1, 2, 3];
2221 assert!(vec[1] == 2);
2226 fn test_index_out_of_bounds() {
2227 let vec = vec![1, 2, 3];
2233 fn test_slice_out_of_bounds_1() {
2234 let x = vec![1, 2, 3, 4, 5];
2240 fn test_slice_out_of_bounds_2() {
2241 let x = vec![1, 2, 3, 4, 5];
2247 fn test_slice_out_of_bounds_3() {
2248 let x = vec![1, 2, 3, 4, 5];
2254 fn test_slice_out_of_bounds_4() {
2255 let x = vec![1, 2, 3, 4, 5];
2261 fn test_slice_out_of_bounds_5() {
2262 let x = vec![1, 2, 3, 4, 5];
2268 fn test_swap_remove_empty() {
2269 let mut vec= Vec::<i32>::new();
2274 fn test_move_iter_unwrap() {
2275 let mut vec = Vec::with_capacity(7);
2278 let ptr = vec.as_ptr();
2279 vec = vec.into_iter().into_inner();
2280 assert_eq!(vec.as_ptr(), ptr);
2281 assert_eq!(vec.capacity(), 7);
2282 assert_eq!(vec.len(), 0);
2287 fn test_map_in_place_incompatible_types_fail() {
2288 let v = vec![0, 1, 2];
2289 v.map_in_place(|_| ());
2293 fn test_map_in_place() {
2294 let v = vec![0, 1, 2];
2295 assert_eq!(v.map_in_place(|i: u32| i as i32 - 1), [-1, 0, 1]);
2299 fn test_map_in_place_zero_sized() {
2300 let v = vec![(), ()];
2301 #[derive(PartialEq, Debug)]
2303 assert_eq!(v.map_in_place(|_| ZeroSized), [ZeroSized, ZeroSized]);
2307 fn test_map_in_place_zero_drop_count() {
2308 use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
2310 #[derive(Clone, PartialEq, Debug)]
2312 impl Drop for Nothing { fn drop(&mut self) { } }
2314 #[derive(Clone, PartialEq, Debug)]
2316 impl Drop for ZeroSized {
2317 fn drop(&mut self) {
2318 DROP_COUNTER.fetch_add(1, Ordering::Relaxed);
2321 const NUM_ELEMENTS: usize = 2;
2322 static DROP_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
2324 let v = repeat(Nothing).take(NUM_ELEMENTS).collect::<Vec<_>>();
2326 DROP_COUNTER.store(0, Ordering::Relaxed);
2328 let v = v.map_in_place(|_| ZeroSized);
2329 assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), 0);
2331 assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), NUM_ELEMENTS);
2335 fn test_move_items() {
2336 let vec = vec![1, 2, 3];
2337 let mut vec2 = vec![];
2341 assert!(vec2 == vec![1, 2, 3]);
2345 fn test_move_items_reverse() {
2346 let vec = vec![1, 2, 3];
2347 let mut vec2 = vec![];
2348 for i in vec.into_iter().rev() {
2351 assert!(vec2 == vec![3, 2, 1]);
2355 fn test_move_items_zero_sized() {
2356 let vec = vec![(), (), ()];
2357 let mut vec2 = vec![];
2361 assert!(vec2 == vec![(), (), ()]);
2365 fn test_drain_items() {
2366 let mut vec = vec![1, 2, 3];
2367 let mut vec2 = vec![];
2368 for i in vec.drain() {
2371 assert_eq!(vec, []);
2372 assert_eq!(vec2, [ 1, 2, 3 ]);
2376 fn test_drain_items_reverse() {
2377 let mut vec = vec![1, 2, 3];
2378 let mut vec2 = vec![];
2379 for i in vec.drain().rev() {
2382 assert_eq!(vec, []);
2383 assert_eq!(vec2, [3, 2, 1]);
2387 fn test_drain_items_zero_sized() {
2388 let mut vec = vec![(), (), ()];
2389 let mut vec2 = vec![];
2390 for i in vec.drain() {
2393 assert_eq!(vec, []);
2394 assert_eq!(vec2, [(), (), ()]);
2398 fn test_into_boxed_slice() {
2399 let xs = vec![1, 2, 3];
2400 let ys = xs.into_boxed_slice();
2401 assert_eq!(ys, [1, 2, 3]);
2406 let mut vec = vec![1, 2, 3];
2407 let mut vec2 = vec![4, 5, 6];
2408 vec.append(&mut vec2);
2409 assert_eq!(vec, vec![1, 2, 3, 4, 5, 6]);
2410 assert_eq!(vec2, vec![]);
2414 fn test_split_off() {
2415 let mut vec = vec![1, 2, 3, 4, 5, 6];
2416 let vec2 = vec.split_off(4);
2417 assert_eq!(vec, vec![1, 2, 3, 4]);
2418 assert_eq!(vec2, vec![5, 6]);
2422 fn bench_new(b: &mut Bencher) {
2424 let v: Vec<u32> = Vec::new();
2425 assert_eq!(v.len(), 0);
2426 assert_eq!(v.capacity(), 0);
2430 fn do_bench_with_capacity(b: &mut Bencher, src_len: usize) {
2431 b.bytes = src_len as u64;
2434 let v: Vec<u32> = Vec::with_capacity(src_len);
2435 assert_eq!(v.len(), 0);
2436 assert_eq!(v.capacity(), src_len);
2441 fn bench_with_capacity_0000(b: &mut Bencher) {
2442 do_bench_with_capacity(b, 0)
2446 fn bench_with_capacity_0010(b: &mut Bencher) {
2447 do_bench_with_capacity(b, 10)
2451 fn bench_with_capacity_0100(b: &mut Bencher) {
2452 do_bench_with_capacity(b, 100)
2456 fn bench_with_capacity_1000(b: &mut Bencher) {
2457 do_bench_with_capacity(b, 1000)
2460 fn do_bench_from_fn(b: &mut Bencher, src_len: usize) {
2461 b.bytes = src_len as u64;
2464 let dst = (0..src_len).collect::<Vec<_>>();
2465 assert_eq!(dst.len(), src_len);
2466 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2471 fn bench_from_fn_0000(b: &mut Bencher) {
2472 do_bench_from_fn(b, 0)
2476 fn bench_from_fn_0010(b: &mut Bencher) {
2477 do_bench_from_fn(b, 10)
2481 fn bench_from_fn_0100(b: &mut Bencher) {
2482 do_bench_from_fn(b, 100)
2486 fn bench_from_fn_1000(b: &mut Bencher) {
2487 do_bench_from_fn(b, 1000)
2490 fn do_bench_from_elem(b: &mut Bencher, src_len: usize) {
2491 b.bytes = src_len as u64;
2494 let dst: Vec<usize> = repeat(5).take(src_len).collect();
2495 assert_eq!(dst.len(), src_len);
2496 assert!(dst.iter().all(|x| *x == 5));
2501 fn bench_from_elem_0000(b: &mut Bencher) {
2502 do_bench_from_elem(b, 0)
2506 fn bench_from_elem_0010(b: &mut Bencher) {
2507 do_bench_from_elem(b, 10)
2511 fn bench_from_elem_0100(b: &mut Bencher) {
2512 do_bench_from_elem(b, 100)
2516 fn bench_from_elem_1000(b: &mut Bencher) {
2517 do_bench_from_elem(b, 1000)
2520 fn do_bench_from_slice(b: &mut Bencher, src_len: usize) {
2521 let src: Vec<_> = FromIterator::from_iter(0..src_len);
2523 b.bytes = src_len as u64;
2526 let dst = src.clone()[].to_vec();
2527 assert_eq!(dst.len(), src_len);
2528 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2533 fn bench_from_slice_0000(b: &mut Bencher) {
2534 do_bench_from_slice(b, 0)
2538 fn bench_from_slice_0010(b: &mut Bencher) {
2539 do_bench_from_slice(b, 10)
2543 fn bench_from_slice_0100(b: &mut Bencher) {
2544 do_bench_from_slice(b, 100)
2548 fn bench_from_slice_1000(b: &mut Bencher) {
2549 do_bench_from_slice(b, 1000)
2552 fn do_bench_from_iter(b: &mut Bencher, src_len: usize) {
2553 let src: Vec<_> = FromIterator::from_iter(0..src_len);
2555 b.bytes = src_len as u64;
2558 let dst: Vec<_> = FromIterator::from_iter(src.clone().into_iter());
2559 assert_eq!(dst.len(), src_len);
2560 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2565 fn bench_from_iter_0000(b: &mut Bencher) {
2566 do_bench_from_iter(b, 0)
2570 fn bench_from_iter_0010(b: &mut Bencher) {
2571 do_bench_from_iter(b, 10)
2575 fn bench_from_iter_0100(b: &mut Bencher) {
2576 do_bench_from_iter(b, 100)
2580 fn bench_from_iter_1000(b: &mut Bencher) {
2581 do_bench_from_iter(b, 1000)
2584 fn do_bench_extend(b: &mut Bencher, dst_len: usize, src_len: usize) {
2585 let dst: Vec<_> = FromIterator::from_iter(0..dst_len);
2586 let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len);
2588 b.bytes = src_len as u64;
2591 let mut dst = dst.clone();
2592 dst.extend(src.clone().into_iter());
2593 assert_eq!(dst.len(), dst_len + src_len);
2594 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2599 fn bench_extend_0000_0000(b: &mut Bencher) {
2600 do_bench_extend(b, 0, 0)
2604 fn bench_extend_0000_0010(b: &mut Bencher) {
2605 do_bench_extend(b, 0, 10)
2609 fn bench_extend_0000_0100(b: &mut Bencher) {
2610 do_bench_extend(b, 0, 100)
2614 fn bench_extend_0000_1000(b: &mut Bencher) {
2615 do_bench_extend(b, 0, 1000)
2619 fn bench_extend_0010_0010(b: &mut Bencher) {
2620 do_bench_extend(b, 10, 10)
2624 fn bench_extend_0100_0100(b: &mut Bencher) {
2625 do_bench_extend(b, 100, 100)
2629 fn bench_extend_1000_1000(b: &mut Bencher) {
2630 do_bench_extend(b, 1000, 1000)
2633 fn do_bench_push_all(b: &mut Bencher, dst_len: usize, src_len: usize) {
2634 let dst: Vec<_> = FromIterator::from_iter(0..dst_len);
2635 let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len);
2637 b.bytes = src_len as u64;
2640 let mut dst = dst.clone();
2642 assert_eq!(dst.len(), dst_len + src_len);
2643 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2648 fn bench_push_all_0000_0000(b: &mut Bencher) {
2649 do_bench_push_all(b, 0, 0)
2653 fn bench_push_all_0000_0010(b: &mut Bencher) {
2654 do_bench_push_all(b, 0, 10)
2658 fn bench_push_all_0000_0100(b: &mut Bencher) {
2659 do_bench_push_all(b, 0, 100)
2663 fn bench_push_all_0000_1000(b: &mut Bencher) {
2664 do_bench_push_all(b, 0, 1000)
2668 fn bench_push_all_0010_0010(b: &mut Bencher) {
2669 do_bench_push_all(b, 10, 10)
2673 fn bench_push_all_0100_0100(b: &mut Bencher) {
2674 do_bench_push_all(b, 100, 100)
2678 fn bench_push_all_1000_1000(b: &mut Bencher) {
2679 do_bench_push_all(b, 1000, 1000)
2682 fn do_bench_push_all_move(b: &mut Bencher, dst_len: usize, src_len: usize) {
2683 let dst: Vec<_> = FromIterator::from_iter(0..dst_len);
2684 let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len);
2686 b.bytes = src_len as u64;
2689 let mut dst = dst.clone();
2690 dst.extend(src.clone().into_iter());
2691 assert_eq!(dst.len(), dst_len + src_len);
2692 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2697 fn bench_push_all_move_0000_0000(b: &mut Bencher) {
2698 do_bench_push_all_move(b, 0, 0)
2702 fn bench_push_all_move_0000_0010(b: &mut Bencher) {
2703 do_bench_push_all_move(b, 0, 10)
2707 fn bench_push_all_move_0000_0100(b: &mut Bencher) {
2708 do_bench_push_all_move(b, 0, 100)
2712 fn bench_push_all_move_0000_1000(b: &mut Bencher) {
2713 do_bench_push_all_move(b, 0, 1000)
2717 fn bench_push_all_move_0010_0010(b: &mut Bencher) {
2718 do_bench_push_all_move(b, 10, 10)
2722 fn bench_push_all_move_0100_0100(b: &mut Bencher) {
2723 do_bench_push_all_move(b, 100, 100)
2727 fn bench_push_all_move_1000_1000(b: &mut Bencher) {
2728 do_bench_push_all_move(b, 1000, 1000)
2731 fn do_bench_clone(b: &mut Bencher, src_len: usize) {
2732 let src: Vec<usize> = FromIterator::from_iter(0..src_len);
2734 b.bytes = src_len as u64;
2737 let dst = src.clone();
2738 assert_eq!(dst.len(), src_len);
2739 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2744 fn bench_clone_0000(b: &mut Bencher) {
2745 do_bench_clone(b, 0)
2749 fn bench_clone_0010(b: &mut Bencher) {
2750 do_bench_clone(b, 10)
2754 fn bench_clone_0100(b: &mut Bencher) {
2755 do_bench_clone(b, 100)
2759 fn bench_clone_1000(b: &mut Bencher) {
2760 do_bench_clone(b, 1000)
2763 fn do_bench_clone_from(b: &mut Bencher, times: usize, dst_len: usize, src_len: usize) {
2764 let dst: Vec<_> = FromIterator::from_iter(0..src_len);
2765 let src: Vec<_> = FromIterator::from_iter(dst_len..dst_len + src_len);
2767 b.bytes = (times * src_len) as u64;
2770 let mut dst = dst.clone();
2773 dst.clone_from(&src);
2775 assert_eq!(dst.len(), src_len);
2776 assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x));
2782 fn bench_clone_from_01_0000_0000(b: &mut Bencher) {
2783 do_bench_clone_from(b, 1, 0, 0)
2787 fn bench_clone_from_01_0000_0010(b: &mut Bencher) {
2788 do_bench_clone_from(b, 1, 0, 10)
2792 fn bench_clone_from_01_0000_0100(b: &mut Bencher) {
2793 do_bench_clone_from(b, 1, 0, 100)
2797 fn bench_clone_from_01_0000_1000(b: &mut Bencher) {
2798 do_bench_clone_from(b, 1, 0, 1000)
2802 fn bench_clone_from_01_0010_0010(b: &mut Bencher) {
2803 do_bench_clone_from(b, 1, 10, 10)
2807 fn bench_clone_from_01_0100_0100(b: &mut Bencher) {
2808 do_bench_clone_from(b, 1, 100, 100)
2812 fn bench_clone_from_01_1000_1000(b: &mut Bencher) {
2813 do_bench_clone_from(b, 1, 1000, 1000)
2817 fn bench_clone_from_01_0010_0100(b: &mut Bencher) {
2818 do_bench_clone_from(b, 1, 10, 100)
2822 fn bench_clone_from_01_0100_1000(b: &mut Bencher) {
2823 do_bench_clone_from(b, 1, 100, 1000)
2827 fn bench_clone_from_01_0010_0000(b: &mut Bencher) {
2828 do_bench_clone_from(b, 1, 10, 0)
2832 fn bench_clone_from_01_0100_0010(b: &mut Bencher) {
2833 do_bench_clone_from(b, 1, 100, 10)
2837 fn bench_clone_from_01_1000_0100(b: &mut Bencher) {
2838 do_bench_clone_from(b, 1, 1000, 100)
2842 fn bench_clone_from_10_0000_0000(b: &mut Bencher) {
2843 do_bench_clone_from(b, 10, 0, 0)
2847 fn bench_clone_from_10_0000_0010(b: &mut Bencher) {
2848 do_bench_clone_from(b, 10, 0, 10)
2852 fn bench_clone_from_10_0000_0100(b: &mut Bencher) {
2853 do_bench_clone_from(b, 10, 0, 100)
2857 fn bench_clone_from_10_0000_1000(b: &mut Bencher) {
2858 do_bench_clone_from(b, 10, 0, 1000)
2862 fn bench_clone_from_10_0010_0010(b: &mut Bencher) {
2863 do_bench_clone_from(b, 10, 10, 10)
2867 fn bench_clone_from_10_0100_0100(b: &mut Bencher) {
2868 do_bench_clone_from(b, 10, 100, 100)
2872 fn bench_clone_from_10_1000_1000(b: &mut Bencher) {
2873 do_bench_clone_from(b, 10, 1000, 1000)
2877 fn bench_clone_from_10_0010_0100(b: &mut Bencher) {
2878 do_bench_clone_from(b, 10, 10, 100)
2882 fn bench_clone_from_10_0100_1000(b: &mut Bencher) {
2883 do_bench_clone_from(b, 10, 100, 1000)
2887 fn bench_clone_from_10_0010_0000(b: &mut Bencher) {
2888 do_bench_clone_from(b, 10, 10, 0)
2892 fn bench_clone_from_10_0100_0010(b: &mut Bencher) {
2893 do_bench_clone_from(b, 10, 100, 10)
2897 fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
2898 do_bench_clone_from(b, 10, 1000, 100)