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, 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();
49 use alloc::boxed::Box;
50 use alloc::heap::{EMPTY, allocate, reallocate, deallocate};
51 use core::borrow::{Cow, IntoCow};
53 use core::cmp::{Ordering};
54 use core::default::Default;
56 use core::hash::{self, Hash};
57 use core::iter::{repeat, FromIterator};
58 use core::kinds::marker::{ContravariantLifetime, InvariantType};
60 use core::nonzero::NonZero;
61 use core::num::{Int, UnsignedInt};
62 use core::ops::{Index, IndexMut, Deref, Add};
65 use core::raw::Slice as RawSlice;
68 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
73 /// let mut vec = Vec::new();
77 /// assert_eq!(vec.len(), 2);
78 /// assert_eq!(vec[0], 1);
80 /// assert_eq!(vec.pop(), Some(2));
81 /// assert_eq!(vec.len(), 1);
84 /// assert_eq!(vec[0], 7);
86 /// vec.push_all(&[1, 2, 3]);
88 /// for x in vec.iter() {
89 /// println!("{}", x);
91 /// assert_eq!(vec, vec![7i, 1, 2, 3]);
94 /// The `vec!` macro is provided to make initialization more convenient:
97 /// let mut vec = vec![1i, 2i, 3i];
99 /// assert_eq!(vec, vec![1, 2, 3, 4]);
102 /// Use a `Vec<T>` as an efficient stack:
105 /// let mut stack = Vec::new();
112 /// let top = match stack.pop() {
113 /// None => break, // empty
116 /// // Prints 3, 2, 1
117 /// println!("{}", top);
121 /// # Capacity and reallocation
123 /// The capacity of a vector is the amount of space allocated for any future elements that will be
124 /// added onto the vector. This is not to be confused with the *length* of a vector, which
125 /// specifies the number of actual elements within the vector. If a vector's length exceeds its
126 /// capacity, its capacity will automatically be increased, but its elements will have to be
129 /// For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10
130 /// more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or
131 /// cause reallocation to occur. However, if the vector's length is increased to 11, it will have
132 /// to reallocate, which can be slow. For this reason, it is recommended to use
133 /// `Vec::with_capacity` whenever possible to specify how big the vector is expected to get.
134 #[unsafe_no_drop_flag]
137 ptr: NonZero<*mut T>,
142 unsafe impl<T: Send> Send for Vec<T> { }
143 unsafe impl<T: Sync> Sync for Vec<T> { }
145 ////////////////////////////////////////////////////////////////////////////////
147 ////////////////////////////////////////////////////////////////////////////////
150 /// Constructs a new, empty `Vec<T>`.
152 /// The vector will not allocate until elements are pushed onto it.
157 /// let mut vec: Vec<int> = Vec::new();
161 pub fn new() -> Vec<T> {
162 // We want ptr to never be NULL so instead we set it to some arbitrary
163 // non-null value which is fine since we never call deallocate on the ptr
164 // if cap is 0. The reason for this is because the pointer of a slice
165 // being NULL would break the null pointer optimization for enums.
166 Vec { ptr: unsafe { NonZero::new(EMPTY as *mut T) }, len: 0, cap: 0 }
169 /// Constructs a new, empty `Vec<T>` with the specified capacity.
171 /// The vector will be able to hold exactly `capacity` elements without reallocating. If
172 /// `capacity` is 0, the vector will not allocate.
174 /// It is important to note that this function does not specify the *length* of the returned
175 /// vector, but only the *capacity*. (For an explanation of the difference between length and
176 /// capacity, see the main `Vec<T>` docs above, 'Capacity and reallocation'.)
181 /// let mut vec: Vec<int> = Vec::with_capacity(10);
183 /// // The vector contains no items, even though it has capacity for more
184 /// assert_eq!(vec.len(), 0);
186 /// // These are all done without reallocating...
187 /// for i in range(0i, 10) {
191 /// // ...but this may make the vector reallocate
196 pub fn with_capacity(capacity: uint) -> Vec<T> {
197 if mem::size_of::<T>() == 0 {
198 Vec { ptr: unsafe { NonZero::new(EMPTY as *mut T) }, len: 0, cap: uint::MAX }
199 } else if capacity == 0 {
202 let size = capacity.checked_mul(mem::size_of::<T>())
203 .expect("capacity overflow");
204 let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
205 if ptr.is_null() { ::alloc::oom() }
206 Vec { ptr: unsafe { NonZero::new(ptr as *mut T) }, len: 0, cap: capacity }
210 /// Creates a `Vec<T>` directly from the raw components of another vector.
212 /// This is highly unsafe, due to the number of invariants that aren't checked.
221 /// let mut v = vec![1i, 2, 3];
223 /// // Pull out the various important pieces of information about `v`
224 /// let p = v.as_mut_ptr();
225 /// let len = v.len();
226 /// let cap = v.capacity();
229 /// // Cast `v` into the void: no destructor run, so we are in
230 /// // complete control of the allocation to which `p` points.
233 /// // Overwrite memory with 4, 5, 6
234 /// for i in range(0, len as int) {
235 /// ptr::write(p.offset(i), 4 + i);
238 /// // Put everything back together into a Vec
239 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
240 /// assert_eq!(rebuilt, vec![4i, 5i, 6i]);
245 pub unsafe fn from_raw_parts(ptr: *mut T, length: uint,
246 capacity: uint) -> Vec<T> {
247 Vec { ptr: NonZero::new(ptr), len: length, cap: capacity }
250 /// Creates a vector by copying the elements from a raw pointer.
252 /// This function will copy `elts` contiguous elements starting at `ptr` into a new allocation
253 /// owned by the returned `Vec<T>`. The elements of the buffer are copied into the vector
254 /// without cloning, as if `ptr::read()` were called on them.
256 #[unstable = "may be better expressed via composition"]
257 pub unsafe fn from_raw_buf(ptr: *const T, elts: uint) -> Vec<T> {
258 let mut dst = Vec::with_capacity(elts);
260 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
264 /// Returns the number of elements the vector can hold without
270 /// let vec: Vec<int> = Vec::with_capacity(10);
271 /// assert_eq!(vec.capacity(), 10);
275 pub fn capacity(&self) -> uint {
279 /// Reserves capacity for at least `additional` more elements to be inserted in the given
280 /// `Vec<T>`. The collection may reserve more space to avoid frequent reallocations.
284 /// Panics if the new capacity overflows `uint`.
289 /// let mut vec: Vec<int> = vec![1];
291 /// assert!(vec.capacity() >= 11);
294 pub fn reserve(&mut self, additional: uint) {
295 if self.cap - self.len < additional {
296 let err_msg = "Vec::reserve: `uint` overflow";
297 let new_cap = self.len.checked_add(additional).expect(err_msg)
298 .checked_next_power_of_two().expect(err_msg);
299 self.grow_capacity(new_cap);
303 /// Reserves the minimum capacity for exactly `additional` more elements to
304 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
307 /// Note that the allocator may give the collection more space than it
308 /// requests. Therefore capacity can not be relied upon to be precisely
309 /// minimal. Prefer `reserve` if future insertions are expected.
313 /// Panics if the new capacity overflows `uint`.
318 /// let mut vec: Vec<int> = vec![1];
319 /// vec.reserve_exact(10);
320 /// assert!(vec.capacity() >= 11);
323 pub fn reserve_exact(&mut self, additional: uint) {
324 if self.cap - self.len < additional {
325 match self.len.checked_add(additional) {
326 None => panic!("Vec::reserve: `uint` overflow"),
327 Some(new_cap) => self.grow_capacity(new_cap)
332 /// Shrinks the capacity of the vector as much as possible.
334 /// It will drop down as close as possible to the length but the allocator
335 /// may still inform the vector that there is space for a few more elements.
340 /// let mut vec: Vec<int> = Vec::with_capacity(10);
341 /// vec.push_all(&[1, 2, 3]);
342 /// assert_eq!(vec.capacity(), 10);
343 /// vec.shrink_to_fit();
344 /// assert!(vec.capacity() >= 3);
347 pub fn shrink_to_fit(&mut self) {
348 if mem::size_of::<T>() == 0 { return }
353 dealloc(*self.ptr, self.cap)
359 // Overflow check is unnecessary as the vector is already at
361 let ptr = reallocate(*self.ptr as *mut u8,
362 self.cap * mem::size_of::<T>(),
363 self.len * mem::size_of::<T>(),
364 mem::min_align_of::<T>()) as *mut T;
365 if ptr.is_null() { ::alloc::oom() }
366 self.ptr = NonZero::new(ptr);
372 /// Convert the vector into Box<[T]>.
374 /// Note that this will drop any excess capacity. Calling this and
375 /// converting back to a vector with `into_vec()` is equivalent to calling
376 /// `shrink_to_fit()`.
378 pub fn into_boxed_slice(mut self) -> Box<[T]> {
379 self.shrink_to_fit();
381 let xs: Box<[T]> = mem::transmute(self.as_mut_slice());
387 /// Shorten a vector, dropping excess elements.
389 /// If `len` is greater than the vector's current length, this has no
395 /// let mut vec = vec![1i, 2, 3, 4];
397 /// assert_eq!(vec, vec![1, 2]);
400 pub fn truncate(&mut self, len: uint) {
402 // drop any extra elements
403 while len < self.len {
404 // decrement len before the read(), so a panic on Drop doesn't
405 // re-drop the just-failed value.
407 ptr::read(self.get_unchecked(self.len));
412 /// Returns a mutable slice of the elements of `self`.
417 /// fn foo(slice: &mut [int]) {}
419 /// let mut vec = vec![1i, 2];
420 /// foo(vec.as_mut_slice());
424 pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
426 mem::transmute(RawSlice {
427 data: *self.ptr as *const T,
433 /// Creates a consuming iterator, that is, one that moves each value out of
434 /// the vector (from start to end). The vector cannot be used after calling
440 /// let v = vec!["a".to_string(), "b".to_string()];
441 /// for s in v.into_iter() {
442 /// // s has type String, not &String
443 /// println!("{}", s);
448 pub fn into_iter(self) -> IntoIter<T> {
452 let begin = ptr as *const T;
453 let end = if mem::size_of::<T>() == 0 {
454 (ptr as uint + self.len()) as *const T
456 ptr.offset(self.len() as int) as *const T
459 IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end }
463 /// Sets the length of a vector.
465 /// This will explicitly set the size of the vector, without actually
466 /// modifying its buffers, so it is up to the caller to ensure that the
467 /// vector is actually the specified size.
472 /// let mut v = vec![1u, 2, 3, 4];
479 pub unsafe fn set_len(&mut self, len: uint) {
483 /// Removes an element from anywhere in the vector and return it, replacing
484 /// it with the last element.
486 /// This does not preserve ordering, but is O(1).
490 /// Panics if `index` is out of bounds.
495 /// let mut v = vec!["foo", "bar", "baz", "qux"];
497 /// assert_eq!(v.swap_remove(1), "bar");
498 /// assert_eq!(v, vec!["foo", "qux", "baz"]);
500 /// assert_eq!(v.swap_remove(0), "foo");
501 /// assert_eq!(v, vec!["baz", "qux"]);
505 pub fn swap_remove(&mut self, index: uint) -> T {
506 let length = self.len();
507 self.swap(index, length - 1);
511 /// Inserts an element at position `index` within the vector, shifting all
512 /// elements after position `i` one position to the right.
516 /// Panics if `index` is not between `0` and the vector's length (both
517 /// bounds inclusive).
522 /// let mut vec = vec![1i, 2, 3];
523 /// vec.insert(1, 4);
524 /// assert_eq!(vec, vec![1, 4, 2, 3]);
525 /// vec.insert(4, 5);
526 /// assert_eq!(vec, vec![1, 4, 2, 3, 5]);
529 pub fn insert(&mut self, index: uint, element: T) {
530 let len = self.len();
531 assert!(index <= len);
532 // space for the new element
535 unsafe { // infallible
536 // The spot to put the new value
538 let p = self.as_mut_ptr().offset(index as int);
539 // Shift everything over to make space. (Duplicating the
540 // `index`th element into two consecutive places.)
541 ptr::copy_memory(p.offset(1), &*p, len - index);
542 // Write it in, overwriting the first copy of the `index`th
544 ptr::write(&mut *p, element);
546 self.set_len(len + 1);
550 /// Removes and returns the element at position `index` within the vector,
551 /// shifting all elements after position `index` one position to the left.
555 /// Panics if `i` is out of bounds.
560 /// let mut v = vec![1i, 2, 3];
561 /// assert_eq!(v.remove(1), 2);
562 /// assert_eq!(v, vec![1, 3]);
565 pub fn remove(&mut self, index: uint) -> T {
566 let len = self.len();
567 assert!(index < len);
568 unsafe { // infallible
571 // the place we are taking from.
572 let ptr = self.as_mut_ptr().offset(index as int);
573 // copy it out, unsafely having a copy of the value on
574 // the stack and in the vector at the same time.
575 ret = ptr::read(ptr as *const T);
577 // Shift everything down to fill in that spot.
578 ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
580 self.set_len(len - 1);
585 /// Retains only the elements specified by the predicate.
587 /// In other words, remove all elements `e` such that `f(&e)` returns false.
588 /// This method operates in place and preserves the order of the retained
594 /// let mut vec = vec![1i, 2, 3, 4];
595 /// vec.retain(|&x| x%2 == 0);
596 /// assert_eq!(vec, vec![2, 4]);
599 pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
600 let len = self.len();
603 let v = self.as_mut_slice();
605 for i in range(0u, len) {
614 self.truncate(len - del);
618 /// Appends an element to the back of a collection.
622 /// Panics if the number of elements in the vector overflows a `uint`.
627 /// let mut vec = vec!(1i, 2);
629 /// assert_eq!(vec, vec!(1, 2, 3));
633 pub fn push(&mut self, value: T) {
634 if mem::size_of::<T>() == 0 {
635 // zero-size types consume no memory, so we can't rely on the
636 // address space running out
637 self.len = self.len.checked_add(1).expect("length overflow");
638 unsafe { mem::forget(value); }
641 if self.len == self.cap {
642 let old_size = self.cap * mem::size_of::<T>();
643 let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
644 if old_size > size { panic!("capacity overflow") }
646 let ptr = alloc_or_realloc(*self.ptr, old_size, size);
647 if ptr.is_null() { ::alloc::oom() }
648 self.ptr = NonZero::new(ptr);
650 self.cap = max(self.cap, 2) * 2;
654 let end = (*self.ptr).offset(self.len as int);
655 ptr::write(&mut *end, value);
660 /// Removes the last element from a vector and returns it, or `None` if it is empty.
665 /// let mut vec = vec![1i, 2, 3];
666 /// assert_eq!(vec.pop(), Some(3));
667 /// assert_eq!(vec, vec![1, 2]);
671 pub fn pop(&mut self) -> Option<T> {
677 Some(ptr::read(self.get_unchecked(self.len())))
682 /// Creates a draining iterator that clears the `Vec` and iterates over
683 /// the removed items from start to end.
688 /// let mut v = vec!["a".to_string(), "b".to_string()];
689 /// for s in v.drain() {
690 /// // s has type String, not &String
691 /// println!("{}", s);
693 /// assert!(v.is_empty());
696 #[unstable = "matches collection reform specification, waiting for dust to settle"]
697 pub fn drain<'a>(&'a mut self) -> Drain<'a, T> {
699 let begin = *self.ptr as *const T;
700 let end = if mem::size_of::<T>() == 0 {
701 (*self.ptr as uint + self.len()) as *const T
703 (*self.ptr).offset(self.len() as int) as *const T
709 marker: ContravariantLifetime,
714 /// Clears the vector, removing all values.
719 /// let mut v = vec![1i, 2, 3];
723 /// assert!(v.is_empty());
727 pub fn clear(&mut self) {
731 /// Returns the number of elements in the vector.
736 /// let a = vec![1i, 2, 3];
737 /// assert_eq!(a.len(), 3);
741 pub fn len(&self) -> uint { self.len }
743 /// Returns `true` if the vector contains no elements.
748 /// let mut v = Vec::new();
749 /// assert!(v.is_empty());
752 /// assert!(!v.is_empty());
755 pub fn is_empty(&self) -> bool { self.len() == 0 }
757 /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same
758 /// size and in case they are not zero-sized the same minimal alignment.
762 /// Panics if `T` and `U` have differing sizes or are not zero-sized and
763 /// have differing minimal alignments.
768 /// let v = vec![0u, 1, 2];
769 /// let w = v.map_in_place(|i| i + 3);
770 /// assert_eq!(w.as_slice(), [3, 4, 5].as_slice());
772 /// #[derive(PartialEq, Show)]
773 /// struct Newtype(u8);
774 /// let bytes = vec![0x11, 0x22];
775 /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x));
776 /// assert_eq!(newtyped_bytes.as_slice(), [Newtype(0x11), Newtype(0x22)].as_slice());
778 #[experimental = "API may change to provide stronger guarantees"]
779 pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
780 // FIXME: Assert statically that the types `T` and `U` have the same
782 assert!(mem::size_of::<T>() == mem::size_of::<U>());
786 if mem::size_of::<T>() != 0 {
787 // FIXME: Assert statically that the types `T` and `U` have the
788 // same minimal alignment in case they are not zero-sized.
790 // These asserts are necessary because the `min_align_of` of the
791 // types are passed to the allocator by `Vec`.
792 assert!(mem::min_align_of::<T>() == mem::min_align_of::<U>());
794 // This `as int` cast is safe, because the size of the elements of the
795 // vector is not 0, and:
797 // 1) If the size of the elements in the vector is 1, the `int` may
798 // overflow, but it has the correct bit pattern so that the
799 // `.offset()` function will work.
802 // Address space 0x0-0xF.
803 // `u8` array at: 0x1.
804 // Size of `u8` array: 0x8.
805 // Calculated `offset`: -0x8.
806 // After `array.offset(offset)`: 0x9.
807 // (0x1 + 0x8 = 0x1 - 0x8)
809 // 2) If the size of the elements in the vector is >1, the `uint` ->
810 // `int` conversion can't overflow.
811 let offset = vec.len() as int;
812 let start = vec.as_mut_ptr();
814 let mut pv = PartialVecNonZeroSized {
818 // This points inside the vector, as the vector has length
820 end_t: unsafe { start.offset(offset) },
821 start_u: start as *mut U,
822 end_u: start as *mut U,
833 while pv.end_u as *mut T != pv.end_t {
837 // +-+-+-+-+-+-+-+-+-+
838 // |U|...|U|T|T|...|T|
839 // +-+-+-+-+-+-+-+-+-+
843 let t = ptr::read(pv.start_t as *const T);
846 // +-+-+-+-+-+-+-+-+-+
847 // |U|...|U|X|T|...|T|
848 // +-+-+-+-+-+-+-+-+-+
851 // We must not panic here, one cell is marked as `T`
852 // although it is not `T`.
854 pv.start_t = pv.start_t.offset(1);
857 // +-+-+-+-+-+-+-+-+-+
858 // |U|...|U|X|T|...|T|
859 // +-+-+-+-+-+-+-+-+-+
862 // We may panic again.
864 // The function given by the user might panic.
867 ptr::write(pv.end_u, u);
870 // +-+-+-+-+-+-+-+-+-+
871 // |U|...|U|U|T|...|T|
872 // +-+-+-+-+-+-+-+-+-+
875 // We should not panic here, because that would leak the `U`
876 // pointed to by `end_u`.
878 pv.end_u = pv.end_u.offset(1);
881 // +-+-+-+-+-+-+-+-+-+
882 // |U|...|U|U|T|...|T|
883 // +-+-+-+-+-+-+-+-+-+
886 // We may panic again.
898 // Extract `vec` and prevent the destructor of
899 // `PartialVecNonZeroSized` from running. Note that none of the
900 // function calls can panic, thus no resources can be leaked (as the
901 // `vec` member of `PartialVec` is the only one which holds
902 // allocations -- and it is returned from this function. None of
905 let vec_len = pv.vec.len();
906 let vec_cap = pv.vec.capacity();
907 let vec_ptr = pv.vec.as_mut_ptr() as *mut U;
909 Vec::from_raw_parts(vec_ptr, vec_len, vec_cap)
912 // Put the `Vec` into the `PartialVecZeroSized` structure and
913 // prevent the destructor of the `Vec` from running. Since the
914 // `Vec` contained zero-sized objects, it did not allocate, so we
915 // are not leaking memory here.
916 let mut pv = PartialVecZeroSized::<T,U> {
919 marker_t: InvariantType,
920 marker_u: InvariantType,
922 unsafe { mem::forget(vec); }
924 while pv.num_t != 0 {
926 // Create a `T` out of thin air and decrement `num_t`. This
927 // must not panic between these steps, as otherwise a
928 // destructor of `T` which doesn't exist runs.
929 let t = mem::uninitialized();
932 // The function given by the user might panic.
935 // Forget the `U` and increment `num_u`. This increment
936 // cannot overflow the `uint` as we only do this for a
937 // number of times that fits into a `uint` (and start with
938 // `0`). Again, we should not panic between these steps.
943 // Create a `Vec` from our `PartialVecZeroSized` and make sure the
944 // destructor of the latter will not run. None of this can panic.
945 let mut result = Vec::new();
947 result.set_len(pv.num_u);
955 impl<T: Clone> Vec<T> {
956 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
958 /// Calls either `extend()` or `truncate()` depending on whether `new_len`
959 /// is larger than the current value of `len()` or not.
964 /// let mut vec = vec!["hello"];
965 /// vec.resize(3, "world");
966 /// assert_eq!(vec, vec!["hello", "world", "world"]);
968 /// let mut vec = vec![1i, 2, 3, 4];
969 /// vec.resize(2, 0);
970 /// assert_eq!(vec, vec![1, 2]);
972 #[unstable = "matches collection reform specification; waiting for dust to settle"]
973 pub fn resize(&mut self, new_len: uint, value: T) {
974 let len = self.len();
977 self.extend(repeat(value).take(new_len - len));
979 self.truncate(new_len);
983 /// Appends all elements in a slice to the `Vec`.
985 /// Iterates over the slice `other`, clones each element, and then appends
986 /// it to this `Vec`. The `other` vector is traversed in-order.
991 /// let mut vec = vec![1i];
992 /// vec.push_all(&[2i, 3, 4]);
993 /// assert_eq!(vec, vec![1, 2, 3, 4]);
996 #[experimental = "likely to be replaced by a more optimized extend"]
997 pub fn push_all(&mut self, other: &[T]) {
998 self.reserve(other.len());
1000 for i in range(0, other.len()) {
1001 let len = self.len();
1003 // Unsafe code so this can be optimised to a memcpy (or something similarly
1004 // fast) when T is Copy. LLVM is easily confused, so any extra operations
1005 // during the loop can prevent this optimisation.
1008 self.get_unchecked_mut(len),
1009 other.get_unchecked(i).clone());
1010 self.set_len(len + 1);
1016 impl<T: PartialEq> Vec<T> {
1017 /// Removes consecutive repeated elements in the vector.
1019 /// If the vector is sorted, this removes all duplicates.
1024 /// let mut vec = vec![1i, 2, 2, 3, 2];
1028 /// assert_eq!(vec, vec![1i, 2, 3, 2]);
1031 pub fn dedup(&mut self) {
1033 // Although we have a mutable reference to `self`, we cannot make
1034 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1035 // must ensure that the vector is in a valid state at all time.
1037 // The way that we handle this is by using swaps; we iterate
1038 // over all the elements, swapping as we go so that at the end
1039 // the elements we wish to keep are in the front, and those we
1040 // wish to reject are at the back. We can then truncate the
1041 // vector. This operation is still O(n).
1043 // Example: We start in this state, where `r` represents "next
1044 // read" and `w` represents "next_write`.
1047 // +---+---+---+---+---+---+
1048 // | 0 | 1 | 1 | 2 | 3 | 3 |
1049 // +---+---+---+---+---+---+
1052 // Comparing self[r] against self[w-1], this is not a duplicate, so
1053 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1054 // r and w, leaving us with:
1057 // +---+---+---+---+---+---+
1058 // | 0 | 1 | 1 | 2 | 3 | 3 |
1059 // +---+---+---+---+---+---+
1062 // Comparing self[r] against self[w-1], this value is a duplicate,
1063 // so we increment `r` but leave everything else unchanged:
1066 // +---+---+---+---+---+---+
1067 // | 0 | 1 | 1 | 2 | 3 | 3 |
1068 // +---+---+---+---+---+---+
1071 // Comparing self[r] against self[w-1], this is not a duplicate,
1072 // so swap self[r] and self[w] and advance r and w:
1075 // +---+---+---+---+---+---+
1076 // | 0 | 1 | 2 | 1 | 3 | 3 |
1077 // +---+---+---+---+---+---+
1080 // Not a duplicate, repeat:
1083 // +---+---+---+---+---+---+
1084 // | 0 | 1 | 2 | 3 | 1 | 3 |
1085 // +---+---+---+---+---+---+
1088 // Duplicate, advance r. End of vec. Truncate to w.
1090 let ln = self.len();
1091 if ln < 1 { return; }
1093 // Avoid bounds checks by using unsafe pointers.
1094 let p = self.as_mut_ptr();
1099 let p_r = p.offset(r as int);
1100 let p_wm1 = p.offset((w - 1) as int);
1103 let p_w = p_wm1.offset(1);
1104 mem::swap(&mut *p_r, &mut *p_w);
1116 ////////////////////////////////////////////////////////////////////////////////
1117 // Internal methods and functions
1118 ////////////////////////////////////////////////////////////////////////////////
1121 /// Reserves capacity for exactly `capacity` elements in the given vector.
1123 /// If the capacity for `self` is already equal to or greater than the
1124 /// requested capacity, then no action is taken.
1125 fn grow_capacity(&mut self, capacity: uint) {
1126 if mem::size_of::<T>() == 0 { return }
1128 if capacity > self.cap {
1129 let size = capacity.checked_mul(mem::size_of::<T>())
1130 .expect("capacity overflow");
1132 let ptr = alloc_or_realloc(*self.ptr, self.cap * mem::size_of::<T>(), size);
1133 if ptr.is_null() { ::alloc::oom() }
1134 self.ptr = NonZero::new(ptr);
1136 self.cap = capacity;
1141 // FIXME: #13996: need a way to mark the return value as `noalias`
1143 unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: uint, size: uint) -> *mut T {
1145 allocate(size, mem::min_align_of::<T>()) as *mut T
1147 reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T
1152 unsafe fn dealloc<T>(ptr: *mut T, len: uint) {
1153 if mem::size_of::<T>() != 0 {
1154 deallocate(ptr as *mut u8,
1155 len * mem::size_of::<T>(),
1156 mem::min_align_of::<T>())
1160 ////////////////////////////////////////////////////////////////////////////////
1161 // Common trait implementations for Vec
1162 ////////////////////////////////////////////////////////////////////////////////
1165 impl<T:Clone> Clone for Vec<T> {
1166 fn clone(&self) -> Vec<T> { ::slice::SliceExt::to_vec(self.as_slice()) }
1168 fn clone_from(&mut self, other: &Vec<T>) {
1169 // drop anything in self that will not be overwritten
1170 if self.len() > other.len() {
1171 self.truncate(other.len())
1174 // reuse the contained values' allocations/resources.
1175 for (place, thing) in self.iter_mut().zip(other.iter()) {
1176 place.clone_from(thing)
1179 // self.len <= other.len due to the truncate above, so the
1180 // slice here is always in-bounds.
1181 let slice = other[self.len()..];
1182 self.push_all(slice);
1186 impl<S: hash::Writer, T: Hash<S>> Hash<S> for Vec<T> {
1188 fn hash(&self, state: &mut S) {
1189 self.as_slice().hash(state);
1193 #[experimental = "waiting on Index stability"]
1194 impl<T> Index<uint> for Vec<T> {
1198 fn index<'a>(&'a self, index: &uint) -> &'a T {
1199 &self.as_slice()[*index]
1203 impl<T> IndexMut<uint> for Vec<T> {
1207 fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
1208 &mut self.as_mut_slice()[*index]
1212 impl<T> ops::Slice<uint, [T]> for Vec<T> {
1214 fn as_slice_<'a>(&'a self) -> &'a [T] {
1219 fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [T] {
1220 self.as_slice().slice_from_or_fail(start)
1224 fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [T] {
1225 self.as_slice().slice_to_or_fail(end)
1228 fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] {
1229 self.as_slice().slice_or_fail(start, end)
1233 impl<T> ops::SliceMut<uint, [T]> for Vec<T> {
1235 fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
1240 fn slice_from_or_fail_mut<'a>(&'a mut self, start: &uint) -> &'a mut [T] {
1241 self.as_mut_slice().slice_from_or_fail_mut(start)
1245 fn slice_to_or_fail_mut<'a>(&'a mut self, end: &uint) -> &'a mut [T] {
1246 self.as_mut_slice().slice_to_or_fail_mut(end)
1249 fn slice_or_fail_mut<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] {
1250 self.as_mut_slice().slice_or_fail_mut(start, end)
1255 impl<T> ops::Deref for Vec<T> {
1258 fn deref<'a>(&'a self) -> &'a [T] { self.as_slice() }
1262 impl<T> ops::DerefMut for Vec<T> {
1263 fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.as_mut_slice() }
1267 impl<T> FromIterator<T> for Vec<T> {
1269 fn from_iter<I:Iterator<Item=T>>(mut iterator: I) -> Vec<T> {
1270 let (lower, _) = iterator.size_hint();
1271 let mut vector = Vec::with_capacity(lower);
1272 for element in iterator {
1273 vector.push(element)
1279 #[experimental = "waiting on Extend stability"]
1280 impl<T> Extend<T> for Vec<T> {
1282 fn extend<I: Iterator<Item=T>>(&mut self, mut iterator: I) {
1283 let (lower, _) = iterator.size_hint();
1284 self.reserve(lower);
1285 for element in iterator {
1291 impl<A, B> PartialEq<Vec<B>> for Vec<A> where A: PartialEq<B> {
1293 fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1295 fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1298 macro_rules! impl_eq {
1299 ($lhs:ty, $rhs:ty) => {
1300 impl<'b, A, B> PartialEq<$rhs> for $lhs where A: PartialEq<B> {
1302 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1304 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1307 impl<'b, A, B> PartialEq<$lhs> for $rhs where B: PartialEq<A> {
1309 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
1311 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
1316 impl_eq! { Vec<A>, &'b [B] }
1317 impl_eq! { Vec<A>, &'b mut [B] }
1319 impl<'a, A, B> PartialEq<Vec<B>> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1321 fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1323 fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1326 impl<'a, A, B> PartialEq<CowVec<'a, A>> for Vec<B> where A: Clone, B: PartialEq<A> {
1328 fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1330 fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1333 macro_rules! impl_eq_for_cowvec {
1335 impl<'a, 'b, A, B> PartialEq<$rhs> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1337 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1339 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1342 impl<'a, 'b, A, B> PartialEq<CowVec<'a, A>> for $rhs where A: Clone, B: PartialEq<A> {
1344 fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1346 fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1351 impl_eq_for_cowvec! { &'b [B] }
1352 impl_eq_for_cowvec! { &'b mut [B] }
1354 #[unstable = "waiting on PartialOrd stability"]
1355 impl<T: PartialOrd> PartialOrd for Vec<T> {
1357 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1358 self.as_slice().partial_cmp(other.as_slice())
1362 #[unstable = "waiting on Eq stability"]
1363 impl<T: Eq> Eq for Vec<T> {}
1365 #[unstable = "waiting on Ord stability"]
1366 impl<T: Ord> Ord for Vec<T> {
1368 fn cmp(&self, other: &Vec<T>) -> Ordering {
1369 self.as_slice().cmp(other.as_slice())
1373 impl<T> AsSlice<T> for Vec<T> {
1374 /// Returns a slice into `self`.
1379 /// fn foo(slice: &[int]) {}
1381 /// let vec = vec![1i, 2];
1382 /// foo(vec.as_slice());
1386 fn as_slice<'a>(&'a self) -> &'a [T] {
1388 mem::transmute(RawSlice {
1389 data: *self.ptr as *const T,
1396 #[unstable = "recent addition, needs more experience"]
1397 impl<'a, T: Clone> Add<&'a [T]> for Vec<T> {
1398 type Output = Vec<T>;
1401 fn add(mut self, rhs: &[T]) -> Vec<T> {
1407 #[unsafe_destructor]
1409 impl<T> Drop for Vec<T> {
1410 fn drop(&mut self) {
1411 // This is (and should always remain) a no-op if the fields are
1412 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1415 for x in self.iter() {
1418 dealloc(*self.ptr, self.cap)
1425 impl<T> Default for Vec<T> {
1427 fn default() -> Vec<T> {
1432 #[experimental = "waiting on Show stability"]
1433 impl<T:fmt::Show> fmt::Show for Vec<T> {
1434 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1435 self.as_slice().fmt(f)
1439 impl<'a> fmt::Writer for Vec<u8> {
1440 fn write_str(&mut self, s: &str) -> fmt::Result {
1441 self.push_all(s.as_bytes());
1446 ////////////////////////////////////////////////////////////////////////////////
1448 ////////////////////////////////////////////////////////////////////////////////
1450 #[experimental = "unclear how valuable this alias is"]
1451 /// A clone-on-write vector
1452 pub type CowVec<'a, T> = Cow<'a, Vec<T>, [T]>;
1455 impl<'a, T> FromIterator<T> for CowVec<'a, T> where T: Clone {
1456 fn from_iter<I: Iterator<Item=T>>(it: I) -> CowVec<'a, T> {
1457 Cow::Owned(FromIterator::from_iter(it))
1461 impl<'a, T: 'a> IntoCow<'a, Vec<T>, [T]> for Vec<T> where T: Clone {
1462 fn into_cow(self) -> CowVec<'a, T> {
1467 impl<'a, T> IntoCow<'a, Vec<T>, [T]> for &'a [T] where T: Clone {
1468 fn into_cow(self) -> CowVec<'a, T> {
1473 ////////////////////////////////////////////////////////////////////////////////
1475 ////////////////////////////////////////////////////////////////////////////////
1477 /// An iterator that moves out of a vector.
1479 pub struct IntoIter<T> {
1480 allocation: *mut T, // the block of memory allocated for the vector
1481 cap: uint, // the capacity of the vector
1486 impl<T> IntoIter<T> {
1488 /// Drops all items that have not yet been moved and returns the empty vector.
1490 pub fn into_inner(mut self) -> Vec<T> {
1493 let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
1495 Vec { ptr: NonZero::new(allocation), cap: cap, len: 0 }
1501 impl<T> Iterator for IntoIter<T> {
1505 fn next<'a>(&'a mut self) -> Option<T> {
1507 if self.ptr == self.end {
1510 if mem::size_of::<T>() == 0 {
1511 // purposefully don't use 'ptr.offset' because for
1512 // vectors with 0-size elements this would return the
1514 self.ptr = mem::transmute(self.ptr as uint + 1);
1516 // Use a non-null pointer value
1517 Some(ptr::read(mem::transmute(1u)))
1520 self.ptr = self.ptr.offset(1);
1522 Some(ptr::read(old))
1529 fn size_hint(&self) -> (uint, Option<uint>) {
1530 let diff = (self.end as uint) - (self.ptr as uint);
1531 let size = mem::size_of::<T>();
1532 let exact = diff / (if size == 0 {1} else {size});
1533 (exact, Some(exact))
1538 impl<T> DoubleEndedIterator for IntoIter<T> {
1540 fn next_back<'a>(&'a mut self) -> Option<T> {
1542 if self.end == self.ptr {
1545 if mem::size_of::<T>() == 0 {
1546 // See above for why 'ptr.offset' isn't used
1547 self.end = mem::transmute(self.end as uint - 1);
1549 // Use a non-null pointer value
1550 Some(ptr::read(mem::transmute(1u)))
1552 self.end = self.end.offset(-1);
1554 Some(ptr::read(mem::transmute(self.end)))
1562 impl<T> ExactSizeIterator for IntoIter<T> {}
1564 #[unsafe_destructor]
1566 impl<T> Drop for IntoIter<T> {
1567 fn drop(&mut self) {
1568 // destroy the remaining elements
1572 dealloc(self.allocation, self.cap);
1578 /// An iterator that drains a vector.
1579 #[unsafe_no_drop_flag]
1580 #[unstable = "recently added as part of collections reform 2"]
1581 pub struct Drain<'a, T> {
1584 marker: ContravariantLifetime<'a>,
1588 impl<'a, T> Iterator for Drain<'a, T> {
1592 fn next(&mut self) -> Option<T> {
1594 if self.ptr == self.end {
1597 if mem::size_of::<T>() == 0 {
1598 // purposefully don't use 'ptr.offset' because for
1599 // vectors with 0-size elements this would return the
1601 self.ptr = mem::transmute(self.ptr as uint + 1);
1603 // Use a non-null pointer value
1604 Some(ptr::read(mem::transmute(1u)))
1607 self.ptr = self.ptr.offset(1);
1609 Some(ptr::read(old))
1616 fn size_hint(&self) -> (uint, Option<uint>) {
1617 let diff = (self.end as uint) - (self.ptr as uint);
1618 let size = mem::size_of::<T>();
1619 let exact = diff / (if size == 0 {1} else {size});
1620 (exact, Some(exact))
1625 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1627 fn next_back(&mut self) -> Option<T> {
1629 if self.end == self.ptr {
1632 if mem::size_of::<T>() == 0 {
1633 // See above for why 'ptr.offset' isn't used
1634 self.end = mem::transmute(self.end as uint - 1);
1636 // Use a non-null pointer value
1637 Some(ptr::read(mem::transmute(1u)))
1639 self.end = self.end.offset(-1);
1641 Some(ptr::read(self.end))
1649 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1651 #[unsafe_destructor]
1653 impl<'a, T> Drop for Drain<'a, T> {
1654 fn drop(&mut self) {
1655 // self.ptr == self.end == null if drop has already been called,
1656 // so we can use #[unsafe_no_drop_flag].
1658 // destroy the remaining elements
1663 ////////////////////////////////////////////////////////////////////////////////
1664 // Conversion from &[T] to &Vec<T>
1665 ////////////////////////////////////////////////////////////////////////////////
1667 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1669 pub struct DerefVec<'a, T> {
1671 l: ContravariantLifetime<'a>
1675 impl<'a, T> Deref for DerefVec<'a, T> {
1676 type Target = Vec<T>;
1678 fn deref<'b>(&'b self) -> &'b Vec<T> {
1683 // Prevent the inner `Vec<T>` from attempting to deallocate memory.
1684 #[unsafe_destructor]
1686 impl<'a, T> Drop for DerefVec<'a, T> {
1687 fn drop(&mut self) {
1693 /// Convert a slice to a wrapper type providing a `&Vec<T>` reference.
1695 pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
1698 x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1699 l: ContravariantLifetime::<'a>
1704 ////////////////////////////////////////////////////////////////////////////////
1705 // Partial vec, used for map_in_place
1706 ////////////////////////////////////////////////////////////////////////////////
1708 /// An owned, partially type-converted vector of elements with non-zero size.
1710 /// `T` and `U` must have the same, non-zero size. They must also have the same
1713 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
1714 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
1715 /// destructed. Additionally the underlying storage of `vec` will be freed.
1716 struct PartialVecNonZeroSized<T,U> {
1725 /// An owned, partially type-converted vector of zero-sized elements.
1727 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1729 struct PartialVecZeroSized<T,U> {
1732 marker_t: InvariantType<T>,
1733 marker_u: InvariantType<U>,
1736 #[unsafe_destructor]
1737 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1738 fn drop(&mut self) {
1740 // `vec` hasn't been modified until now. As it has a length
1741 // currently, this would run destructors of `T`s which might not be
1742 // there. So at first, set `vec`s length to `0`. This must be done
1743 // at first to remain memory-safe as the destructors of `U` or `T`
1744 // might cause unwinding where `vec`s destructor would be executed.
1745 self.vec.set_len(0);
1747 // We have instances of `U`s and `T`s in `vec`. Destruct them.
1748 while self.start_u != self.end_u {
1749 let _ = ptr::read(self.start_u as *const U); // Run a `U` destructor.
1750 self.start_u = self.start_u.offset(1);
1752 while self.start_t != self.end_t {
1753 let _ = ptr::read(self.start_t as *const T); // Run a `T` destructor.
1754 self.start_t = self.start_t.offset(1);
1756 // After this destructor ran, the destructor of `vec` will run,
1757 // deallocating the underlying memory.
1762 #[unsafe_destructor]
1763 impl<T,U> Drop for PartialVecZeroSized<T,U> {
1764 fn drop(&mut self) {
1766 // Destruct the instances of `T` and `U` this struct owns.
1767 while self.num_t != 0 {
1768 let _: T = mem::uninitialized(); // Run a `T` destructor.
1771 while self.num_u != 0 {
1772 let _: U = mem::uninitialized(); // Run a `U` destructor.
1782 use core::mem::size_of;
1783 use core::iter::repeat;
1787 struct DropCounter<'a> {
1791 #[unsafe_destructor]
1792 impl<'a> Drop for DropCounter<'a> {
1793 fn drop(&mut self) {
1800 let xs = [1u8, 2u8, 3u8];
1801 assert_eq!(as_vec(&xs).as_slice(), xs);
1805 fn test_as_vec_dtor() {
1806 let (mut count_x, mut count_y) = (0, 0);
1808 let xs = &[DropCounter { count: &mut count_x }, DropCounter { count: &mut count_y }];
1809 assert_eq!(as_vec(xs).len(), 2);
1811 assert_eq!(count_x, 1);
1812 assert_eq!(count_y, 1);
1816 fn test_small_vec_struct() {
1817 assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1821 fn test_double_drop() {
1827 let (mut count_x, mut count_y) = (0, 0);
1829 let mut tv = TwoVec {
1833 tv.x.push(DropCounter {count: &mut count_x});
1834 tv.y.push(DropCounter {count: &mut count_y});
1836 // If Vec had a drop flag, here is where it would be zeroed.
1837 // Instead, it should rely on its internal state to prevent
1838 // doing anything significant when dropped multiple times.
1841 // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1844 assert_eq!(count_x, 1);
1845 assert_eq!(count_y, 1);
1850 let mut v = Vec::new();
1851 assert_eq!(v.capacity(), 0);
1854 assert!(v.capacity() >= 2);
1856 for i in range(0i, 16) {
1860 assert!(v.capacity() >= 16);
1862 assert!(v.capacity() >= 32);
1867 assert!(v.capacity() >= 33)
1872 let mut v = Vec::new();
1873 let mut w = Vec::new();
1875 v.extend(range(0i, 3));
1876 for i in range(0i, 3) { w.push(i) }
1880 v.extend(range(3i, 10));
1881 for i in range(3i, 10) { w.push(i) }
1887 fn test_slice_from_mut() {
1888 let mut values = vec![1u8,2,3,4,5];
1890 let slice = values.slice_from_mut(2);
1891 assert!(slice == [3, 4, 5]);
1892 for p in slice.iter_mut() {
1897 assert!(values == [1, 2, 5, 6, 7]);
1901 fn test_slice_to_mut() {
1902 let mut values = vec![1u8,2,3,4,5];
1904 let slice = values.slice_to_mut(2);
1905 assert!(slice == [1, 2]);
1906 for p in slice.iter_mut() {
1911 assert!(values == [2, 3, 3, 4, 5]);
1915 fn test_split_at_mut() {
1916 let mut values = vec![1u8,2,3,4,5];
1918 let (left, right) = values.split_at_mut(2);
1920 let left: &[_] = left;
1921 assert!(left[0..left.len()] == [1, 2][]);
1923 for p in left.iter_mut() {
1928 let right: &[_] = right;
1929 assert!(right[0..right.len()] == [3, 4, 5][]);
1931 for p in right.iter_mut() {
1936 assert!(values == vec![2u8, 3, 5, 6, 7]);
1941 let v: Vec<int> = vec!();
1942 let w = vec!(1i, 2, 3);
1944 assert_eq!(v, v.clone());
1948 // they should be disjoint in memory.
1949 assert!(w.as_ptr() != z.as_ptr())
1953 fn test_clone_from() {
1955 let three = vec!(box 1i, box 2, box 3);
1956 let two = vec!(box 4i, box 5);
1958 v.clone_from(&three);
1959 assert_eq!(v, three);
1962 v.clone_from(&three);
1963 assert_eq!(v, three);
1970 v.clone_from(&three);
1971 assert_eq!(v, three)
1976 let mut vec = vec![1u, 2, 3, 4];
1977 vec.retain(|&x| x % 2 == 0);
1978 assert!(vec == vec![2u, 4]);
1982 fn zero_sized_values() {
1983 let mut v = Vec::new();
1984 assert_eq!(v.len(), 0);
1986 assert_eq!(v.len(), 1);
1988 assert_eq!(v.len(), 2);
1989 assert_eq!(v.pop(), Some(()));
1990 assert_eq!(v.pop(), Some(()));
1991 assert_eq!(v.pop(), None);
1993 assert_eq!(v.iter().count(), 0);
1995 assert_eq!(v.iter().count(), 1);
1997 assert_eq!(v.iter().count(), 2);
1999 for &() in v.iter() {}
2001 assert_eq!(v.iter_mut().count(), 2);
2003 assert_eq!(v.iter_mut().count(), 3);
2005 assert_eq!(v.iter_mut().count(), 4);
2007 for &() in v.iter_mut() {}
2008 unsafe { v.set_len(0); }
2009 assert_eq!(v.iter_mut().count(), 0);
2013 fn test_partition() {
2014 assert_eq!(vec![].into_iter().partition(|x: &int| *x < 3), (vec![], vec![]));
2015 assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2016 assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2017 assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2021 fn test_zip_unzip() {
2022 let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
2024 let (left, right): (Vec<_>, Vec<_>) = z1.iter().map(|&x| x).unzip();
2026 assert_eq!((1, 4), (left[0], right[0]));
2027 assert_eq!((2, 5), (left[1], right[1]));
2028 assert_eq!((3, 6), (left[2], right[2]));
2032 fn test_unsafe_ptrs() {
2034 // Test on-stack copy-from-buf.
2036 let ptr = a.as_ptr();
2037 let b = Vec::from_raw_buf(ptr, 3u);
2038 assert_eq!(b, vec![1, 2, 3]);
2040 // Test on-heap copy-from-buf.
2041 let c = vec![1i, 2, 3, 4, 5];
2042 let ptr = c.as_ptr();
2043 let d = Vec::from_raw_buf(ptr, 5u);
2044 assert_eq!(d, vec![1, 2, 3, 4, 5]);
2049 fn test_vec_truncate_drop() {
2050 static mut drops: uint = 0;
2052 impl Drop for Elem {
2053 fn drop(&mut self) {
2054 unsafe { drops += 1; }
2058 let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
2059 assert_eq!(unsafe { drops }, 0);
2061 assert_eq!(unsafe { drops }, 2);
2063 assert_eq!(unsafe { drops }, 5);
2068 fn test_vec_truncate_fail() {
2069 struct BadElem(int);
2070 impl Drop for BadElem {
2071 fn drop(&mut self) {
2072 let BadElem(ref mut x) = *self;
2073 if *x == 0xbadbeef {
2074 panic!("BadElem panic: 0xbadbeef")
2079 let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
2085 let vec = vec!(1i, 2, 3);
2086 assert!(vec[1] == 2);
2091 fn test_index_out_of_bounds() {
2092 let vec = vec!(1i, 2, 3);
2098 fn test_slice_out_of_bounds_1() {
2099 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2105 fn test_slice_out_of_bounds_2() {
2106 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2112 fn test_slice_out_of_bounds_3() {
2113 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2119 fn test_slice_out_of_bounds_4() {
2120 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2126 fn test_slice_out_of_bounds_5() {
2127 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2133 fn test_swap_remove_empty() {
2134 let mut vec: Vec<uint> = vec!();
2139 fn test_move_iter_unwrap() {
2140 let mut vec: Vec<uint> = Vec::with_capacity(7);
2143 let ptr = vec.as_ptr();
2144 vec = vec.into_iter().into_inner();
2145 assert_eq!(vec.as_ptr(), ptr);
2146 assert_eq!(vec.capacity(), 7);
2147 assert_eq!(vec.len(), 0);
2152 fn test_map_in_place_incompatible_types_fail() {
2153 let v = vec![0u, 1, 2];
2154 v.map_in_place(|_| ());
2158 fn test_map_in_place() {
2159 let v = vec![0u, 1, 2];
2160 assert_eq!(v.map_in_place(|i: uint| i as int - 1), [-1i, 0, 1]);
2164 fn test_map_in_place_zero_sized() {
2165 let v = vec![(), ()];
2166 #[derive(PartialEq, Show)]
2168 assert_eq!(v.map_in_place(|_| ZeroSized), [ZeroSized, ZeroSized]);
2172 fn test_map_in_place_zero_drop_count() {
2173 use std::sync::atomic::{AtomicUint, Ordering, ATOMIC_UINT_INIT};
2175 #[derive(Clone, PartialEq, Show)]
2177 impl Drop for Nothing { fn drop(&mut self) { } }
2179 #[derive(Clone, PartialEq, Show)]
2181 impl Drop for ZeroSized {
2182 fn drop(&mut self) {
2183 DROP_COUNTER.fetch_add(1, Ordering::Relaxed);
2186 const NUM_ELEMENTS: uint = 2;
2187 static DROP_COUNTER: AtomicUint = ATOMIC_UINT_INIT;
2189 let v = repeat(Nothing).take(NUM_ELEMENTS).collect::<Vec<_>>();
2191 DROP_COUNTER.store(0, Ordering::Relaxed);
2193 let v = v.map_in_place(|_| ZeroSized);
2194 assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), 0);
2196 assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), NUM_ELEMENTS);
2200 fn test_move_items() {
2201 let vec = vec![1, 2, 3];
2202 let mut vec2 : Vec<i32> = vec![];
2203 for i in vec.into_iter() {
2206 assert!(vec2 == vec![1, 2, 3]);
2210 fn test_move_items_reverse() {
2211 let vec = vec![1, 2, 3];
2212 let mut vec2 : Vec<i32> = vec![];
2213 for i in vec.into_iter().rev() {
2216 assert!(vec2 == vec![3, 2, 1]);
2220 fn test_move_items_zero_sized() {
2221 let vec = vec![(), (), ()];
2222 let mut vec2 : Vec<()> = vec![];
2223 for i in vec.into_iter() {
2226 assert!(vec2 == vec![(), (), ()]);
2230 fn test_drain_items() {
2231 let mut vec = vec![1, 2, 3];
2232 let mut vec2: Vec<i32> = vec![];
2233 for i in vec.drain() {
2236 assert_eq!(vec, []);
2237 assert_eq!(vec2, [ 1, 2, 3 ]);
2241 fn test_drain_items_reverse() {
2242 let mut vec = vec![1, 2, 3];
2243 let mut vec2: Vec<i32> = vec![];
2244 for i in vec.drain().rev() {
2247 assert_eq!(vec, []);
2248 assert_eq!(vec2, [ 3, 2, 1 ]);
2252 fn test_drain_items_zero_sized() {
2253 let mut vec = vec![(), (), ()];
2254 let mut vec2: Vec<()> = vec![];
2255 for i in vec.drain() {
2258 assert_eq!(vec, []);
2259 assert_eq!(vec2, [(), (), ()]);
2263 fn test_into_boxed_slice() {
2264 let xs = vec![1u, 2, 3];
2265 let ys = xs.into_boxed_slice();
2266 assert_eq!(ys.as_slice(), [1u, 2, 3]);
2270 fn bench_new(b: &mut Bencher) {
2272 let v: Vec<uint> = Vec::new();
2273 assert_eq!(v.len(), 0);
2274 assert_eq!(v.capacity(), 0);
2278 fn do_bench_with_capacity(b: &mut Bencher, src_len: uint) {
2279 b.bytes = src_len as u64;
2282 let v: Vec<uint> = Vec::with_capacity(src_len);
2283 assert_eq!(v.len(), 0);
2284 assert_eq!(v.capacity(), src_len);
2289 fn bench_with_capacity_0000(b: &mut Bencher) {
2290 do_bench_with_capacity(b, 0)
2294 fn bench_with_capacity_0010(b: &mut Bencher) {
2295 do_bench_with_capacity(b, 10)
2299 fn bench_with_capacity_0100(b: &mut Bencher) {
2300 do_bench_with_capacity(b, 100)
2304 fn bench_with_capacity_1000(b: &mut Bencher) {
2305 do_bench_with_capacity(b, 1000)
2308 fn do_bench_from_fn(b: &mut Bencher, src_len: uint) {
2309 b.bytes = src_len as u64;
2312 let dst = range(0, src_len).collect::<Vec<_>>();
2313 assert_eq!(dst.len(), src_len);
2314 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2319 fn bench_from_fn_0000(b: &mut Bencher) {
2320 do_bench_from_fn(b, 0)
2324 fn bench_from_fn_0010(b: &mut Bencher) {
2325 do_bench_from_fn(b, 10)
2329 fn bench_from_fn_0100(b: &mut Bencher) {
2330 do_bench_from_fn(b, 100)
2334 fn bench_from_fn_1000(b: &mut Bencher) {
2335 do_bench_from_fn(b, 1000)
2338 fn do_bench_from_elem(b: &mut Bencher, src_len: uint) {
2339 b.bytes = src_len as u64;
2342 let dst: Vec<uint> = repeat(5).take(src_len).collect();
2343 assert_eq!(dst.len(), src_len);
2344 assert!(dst.iter().all(|x| *x == 5));
2349 fn bench_from_elem_0000(b: &mut Bencher) {
2350 do_bench_from_elem(b, 0)
2354 fn bench_from_elem_0010(b: &mut Bencher) {
2355 do_bench_from_elem(b, 10)
2359 fn bench_from_elem_0100(b: &mut Bencher) {
2360 do_bench_from_elem(b, 100)
2364 fn bench_from_elem_1000(b: &mut Bencher) {
2365 do_bench_from_elem(b, 1000)
2368 fn do_bench_from_slice(b: &mut Bencher, src_len: uint) {
2369 let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2371 b.bytes = src_len as u64;
2374 let dst = src.clone().as_slice().to_vec();
2375 assert_eq!(dst.len(), src_len);
2376 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2381 fn bench_from_slice_0000(b: &mut Bencher) {
2382 do_bench_from_slice(b, 0)
2386 fn bench_from_slice_0010(b: &mut Bencher) {
2387 do_bench_from_slice(b, 10)
2391 fn bench_from_slice_0100(b: &mut Bencher) {
2392 do_bench_from_slice(b, 100)
2396 fn bench_from_slice_1000(b: &mut Bencher) {
2397 do_bench_from_slice(b, 1000)
2400 fn do_bench_from_iter(b: &mut Bencher, src_len: uint) {
2401 let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2403 b.bytes = src_len as u64;
2406 let dst: Vec<uint> = FromIterator::from_iter(src.clone().into_iter());
2407 assert_eq!(dst.len(), src_len);
2408 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2413 fn bench_from_iter_0000(b: &mut Bencher) {
2414 do_bench_from_iter(b, 0)
2418 fn bench_from_iter_0010(b: &mut Bencher) {
2419 do_bench_from_iter(b, 10)
2423 fn bench_from_iter_0100(b: &mut Bencher) {
2424 do_bench_from_iter(b, 100)
2428 fn bench_from_iter_1000(b: &mut Bencher) {
2429 do_bench_from_iter(b, 1000)
2432 fn do_bench_extend(b: &mut Bencher, dst_len: uint, src_len: uint) {
2433 let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2434 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2436 b.bytes = src_len as u64;
2439 let mut dst = dst.clone();
2440 dst.extend(src.clone().into_iter());
2441 assert_eq!(dst.len(), dst_len + src_len);
2442 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2447 fn bench_extend_0000_0000(b: &mut Bencher) {
2448 do_bench_extend(b, 0, 0)
2452 fn bench_extend_0000_0010(b: &mut Bencher) {
2453 do_bench_extend(b, 0, 10)
2457 fn bench_extend_0000_0100(b: &mut Bencher) {
2458 do_bench_extend(b, 0, 100)
2462 fn bench_extend_0000_1000(b: &mut Bencher) {
2463 do_bench_extend(b, 0, 1000)
2467 fn bench_extend_0010_0010(b: &mut Bencher) {
2468 do_bench_extend(b, 10, 10)
2472 fn bench_extend_0100_0100(b: &mut Bencher) {
2473 do_bench_extend(b, 100, 100)
2477 fn bench_extend_1000_1000(b: &mut Bencher) {
2478 do_bench_extend(b, 1000, 1000)
2481 fn do_bench_push_all(b: &mut Bencher, dst_len: uint, src_len: uint) {
2482 let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2483 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2485 b.bytes = src_len as u64;
2488 let mut dst = dst.clone();
2489 dst.push_all(src.as_slice());
2490 assert_eq!(dst.len(), dst_len + src_len);
2491 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2496 fn bench_push_all_0000_0000(b: &mut Bencher) {
2497 do_bench_push_all(b, 0, 0)
2501 fn bench_push_all_0000_0010(b: &mut Bencher) {
2502 do_bench_push_all(b, 0, 10)
2506 fn bench_push_all_0000_0100(b: &mut Bencher) {
2507 do_bench_push_all(b, 0, 100)
2511 fn bench_push_all_0000_1000(b: &mut Bencher) {
2512 do_bench_push_all(b, 0, 1000)
2516 fn bench_push_all_0010_0010(b: &mut Bencher) {
2517 do_bench_push_all(b, 10, 10)
2521 fn bench_push_all_0100_0100(b: &mut Bencher) {
2522 do_bench_push_all(b, 100, 100)
2526 fn bench_push_all_1000_1000(b: &mut Bencher) {
2527 do_bench_push_all(b, 1000, 1000)
2530 fn do_bench_push_all_move(b: &mut Bencher, dst_len: uint, src_len: uint) {
2531 let dst: Vec<uint> = FromIterator::from_iter(range(0u, dst_len));
2532 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2534 b.bytes = src_len as u64;
2537 let mut dst = dst.clone();
2538 dst.extend(src.clone().into_iter());
2539 assert_eq!(dst.len(), dst_len + src_len);
2540 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2545 fn bench_push_all_move_0000_0000(b: &mut Bencher) {
2546 do_bench_push_all_move(b, 0, 0)
2550 fn bench_push_all_move_0000_0010(b: &mut Bencher) {
2551 do_bench_push_all_move(b, 0, 10)
2555 fn bench_push_all_move_0000_0100(b: &mut Bencher) {
2556 do_bench_push_all_move(b, 0, 100)
2560 fn bench_push_all_move_0000_1000(b: &mut Bencher) {
2561 do_bench_push_all_move(b, 0, 1000)
2565 fn bench_push_all_move_0010_0010(b: &mut Bencher) {
2566 do_bench_push_all_move(b, 10, 10)
2570 fn bench_push_all_move_0100_0100(b: &mut Bencher) {
2571 do_bench_push_all_move(b, 100, 100)
2575 fn bench_push_all_move_1000_1000(b: &mut Bencher) {
2576 do_bench_push_all_move(b, 1000, 1000)
2579 fn do_bench_clone(b: &mut Bencher, src_len: uint) {
2580 let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2582 b.bytes = src_len as u64;
2585 let dst = src.clone();
2586 assert_eq!(dst.len(), src_len);
2587 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2592 fn bench_clone_0000(b: &mut Bencher) {
2593 do_bench_clone(b, 0)
2597 fn bench_clone_0010(b: &mut Bencher) {
2598 do_bench_clone(b, 10)
2602 fn bench_clone_0100(b: &mut Bencher) {
2603 do_bench_clone(b, 100)
2607 fn bench_clone_1000(b: &mut Bencher) {
2608 do_bench_clone(b, 1000)
2611 fn do_bench_clone_from(b: &mut Bencher, times: uint, dst_len: uint, src_len: uint) {
2612 let dst: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2613 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2615 b.bytes = (times * src_len) as u64;
2618 let mut dst = dst.clone();
2620 for _ in range(0, times) {
2621 dst.clone_from(&src);
2623 assert_eq!(dst.len(), src_len);
2624 assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x));
2630 fn bench_clone_from_01_0000_0000(b: &mut Bencher) {
2631 do_bench_clone_from(b, 1, 0, 0)
2635 fn bench_clone_from_01_0000_0010(b: &mut Bencher) {
2636 do_bench_clone_from(b, 1, 0, 10)
2640 fn bench_clone_from_01_0000_0100(b: &mut Bencher) {
2641 do_bench_clone_from(b, 1, 0, 100)
2645 fn bench_clone_from_01_0000_1000(b: &mut Bencher) {
2646 do_bench_clone_from(b, 1, 0, 1000)
2650 fn bench_clone_from_01_0010_0010(b: &mut Bencher) {
2651 do_bench_clone_from(b, 1, 10, 10)
2655 fn bench_clone_from_01_0100_0100(b: &mut Bencher) {
2656 do_bench_clone_from(b, 1, 100, 100)
2660 fn bench_clone_from_01_1000_1000(b: &mut Bencher) {
2661 do_bench_clone_from(b, 1, 1000, 1000)
2665 fn bench_clone_from_01_0010_0100(b: &mut Bencher) {
2666 do_bench_clone_from(b, 1, 10, 100)
2670 fn bench_clone_from_01_0100_1000(b: &mut Bencher) {
2671 do_bench_clone_from(b, 1, 100, 1000)
2675 fn bench_clone_from_01_0010_0000(b: &mut Bencher) {
2676 do_bench_clone_from(b, 1, 10, 0)
2680 fn bench_clone_from_01_0100_0010(b: &mut Bencher) {
2681 do_bench_clone_from(b, 1, 100, 10)
2685 fn bench_clone_from_01_1000_0100(b: &mut Bencher) {
2686 do_bench_clone_from(b, 1, 1000, 100)
2690 fn bench_clone_from_10_0000_0000(b: &mut Bencher) {
2691 do_bench_clone_from(b, 10, 0, 0)
2695 fn bench_clone_from_10_0000_0010(b: &mut Bencher) {
2696 do_bench_clone_from(b, 10, 0, 10)
2700 fn bench_clone_from_10_0000_0100(b: &mut Bencher) {
2701 do_bench_clone_from(b, 10, 0, 100)
2705 fn bench_clone_from_10_0000_1000(b: &mut Bencher) {
2706 do_bench_clone_from(b, 10, 0, 1000)
2710 fn bench_clone_from_10_0010_0010(b: &mut Bencher) {
2711 do_bench_clone_from(b, 10, 10, 10)
2715 fn bench_clone_from_10_0100_0100(b: &mut Bencher) {
2716 do_bench_clone_from(b, 10, 100, 100)
2720 fn bench_clone_from_10_1000_1000(b: &mut Bencher) {
2721 do_bench_clone_from(b, 10, 1000, 1000)
2725 fn bench_clone_from_10_0010_0100(b: &mut Bencher) {
2726 do_bench_clone_from(b, 10, 10, 100)
2730 fn bench_clone_from_10_0100_1000(b: &mut Bencher) {
2731 do_bench_clone_from(b, 10, 100, 1000)
2735 fn bench_clone_from_10_0010_0000(b: &mut Bencher) {
2736 do_bench_clone_from(b, 10, 10, 0)
2740 fn bench_clone_from_10_0100_0010(b: &mut Bencher) {
2741 do_bench_clone_from(b, 10, 100, 10)
2745 fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
2746 do_bench_clone_from(b, 10, 1000, 100)