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 // NOTE(stage0): remove impl after a snapshot
1195 #[experimental = "waiting on Index stability"]
1196 impl<T> Index<uint,T> for Vec<T> {
1198 fn index<'a>(&'a self, index: &uint) -> &'a T {
1199 &self.as_slice()[*index]
1203 #[cfg(not(stage0))] // NOTE(stage0): remove cfg after a snapshot
1204 #[experimental = "waiting on Index stability"]
1205 impl<T> Index<uint> for Vec<T> {
1209 fn index<'a>(&'a self, index: &uint) -> &'a T {
1210 &self.as_slice()[*index]
1214 // NOTE(stage0): remove impl after a snapshot
1216 impl<T> IndexMut<uint,T> for Vec<T> {
1218 fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
1219 &mut self.as_mut_slice()[*index]
1223 #[cfg(not(stage0))] // NOTE(stage0): remove cfg after a snapshot
1224 impl<T> IndexMut<uint> for Vec<T> {
1228 fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
1229 &mut self.as_mut_slice()[*index]
1233 impl<T> ops::Slice<uint, [T]> for Vec<T> {
1235 fn as_slice_<'a>(&'a self) -> &'a [T] {
1240 fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [T] {
1241 self.as_slice().slice_from_or_fail(start)
1245 fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [T] {
1246 self.as_slice().slice_to_or_fail(end)
1249 fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] {
1250 self.as_slice().slice_or_fail(start, end)
1254 impl<T> ops::SliceMut<uint, [T]> for Vec<T> {
1256 fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
1261 fn slice_from_or_fail_mut<'a>(&'a mut self, start: &uint) -> &'a mut [T] {
1262 self.as_mut_slice().slice_from_or_fail_mut(start)
1266 fn slice_to_or_fail_mut<'a>(&'a mut self, end: &uint) -> &'a mut [T] {
1267 self.as_mut_slice().slice_to_or_fail_mut(end)
1270 fn slice_or_fail_mut<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] {
1271 self.as_mut_slice().slice_or_fail_mut(start, end)
1275 #[experimental = "waiting on Deref stability"]
1276 impl<T> ops::Deref for Vec<T> {
1279 fn deref<'a>(&'a self) -> &'a [T] { self.as_slice() }
1282 #[experimental = "waiting on DerefMut stability"]
1283 impl<T> ops::DerefMut for Vec<T> {
1284 fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.as_mut_slice() }
1287 #[experimental = "waiting on FromIterator stability"]
1288 impl<T> FromIterator<T> for Vec<T> {
1290 fn from_iter<I:Iterator<Item=T>>(mut iterator: I) -> Vec<T> {
1291 let (lower, _) = iterator.size_hint();
1292 let mut vector = Vec::with_capacity(lower);
1293 for element in iterator {
1294 vector.push(element)
1300 #[experimental = "waiting on Extend stability"]
1301 impl<T> Extend<T> for Vec<T> {
1303 fn extend<I: Iterator<Item=T>>(&mut self, mut iterator: I) {
1304 let (lower, _) = iterator.size_hint();
1305 self.reserve(lower);
1306 for element in iterator {
1312 impl<A, B> PartialEq<Vec<B>> for Vec<A> where A: PartialEq<B> {
1314 fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1316 fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1319 macro_rules! impl_eq {
1320 ($lhs:ty, $rhs:ty) => {
1321 impl<'b, A, B> PartialEq<$rhs> for $lhs where A: PartialEq<B> {
1323 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1325 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1328 impl<'b, A, B> PartialEq<$lhs> for $rhs where B: PartialEq<A> {
1330 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
1332 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
1337 impl_eq! { Vec<A>, &'b [B] }
1338 impl_eq! { Vec<A>, &'b mut [B] }
1340 impl<'a, A, B> PartialEq<Vec<B>> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1342 fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1344 fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1347 impl<'a, A, B> PartialEq<CowVec<'a, A>> for Vec<B> where A: Clone, B: PartialEq<A> {
1349 fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1351 fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1354 macro_rules! impl_eq_for_cowvec {
1356 impl<'a, 'b, A, B> PartialEq<$rhs> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1358 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1360 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1363 impl<'a, 'b, A, B> PartialEq<CowVec<'a, A>> for $rhs where A: Clone, B: PartialEq<A> {
1365 fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1367 fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1372 impl_eq_for_cowvec! { &'b [B] }
1373 impl_eq_for_cowvec! { &'b mut [B] }
1375 #[unstable = "waiting on PartialOrd stability"]
1376 impl<T: PartialOrd> PartialOrd for Vec<T> {
1378 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1379 self.as_slice().partial_cmp(other.as_slice())
1383 #[unstable = "waiting on Eq stability"]
1384 impl<T: Eq> Eq for Vec<T> {}
1386 #[unstable = "waiting on Ord stability"]
1387 impl<T: Ord> Ord for Vec<T> {
1389 fn cmp(&self, other: &Vec<T>) -> Ordering {
1390 self.as_slice().cmp(other.as_slice())
1394 impl<T> AsSlice<T> for Vec<T> {
1395 /// Returns a slice into `self`.
1400 /// fn foo(slice: &[int]) {}
1402 /// let vec = vec![1i, 2];
1403 /// foo(vec.as_slice());
1407 fn as_slice<'a>(&'a self) -> &'a [T] {
1409 mem::transmute(RawSlice {
1410 data: *self.ptr as *const T,
1417 impl<'a, T: Clone> Add<&'a [T]> for Vec<T> {
1418 type Output = Vec<T>;
1421 fn add(mut self, rhs: &[T]) -> Vec<T> {
1427 #[unsafe_destructor]
1428 impl<T> Drop for Vec<T> {
1429 fn drop(&mut self) {
1430 // This is (and should always remain) a no-op if the fields are
1431 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1434 for x in self.iter() {
1437 dealloc(*self.ptr, self.cap)
1444 impl<T> Default for Vec<T> {
1446 fn default() -> Vec<T> {
1451 #[experimental = "waiting on Show stability"]
1452 impl<T:fmt::Show> fmt::Show for Vec<T> {
1453 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1454 self.as_slice().fmt(f)
1458 impl<'a> fmt::Writer for Vec<u8> {
1459 fn write_str(&mut self, s: &str) -> fmt::Result {
1460 self.push_all(s.as_bytes());
1465 ////////////////////////////////////////////////////////////////////////////////
1467 ////////////////////////////////////////////////////////////////////////////////
1469 #[experimental = "unclear how valuable this alias is"]
1470 /// A clone-on-write vector
1471 pub type CowVec<'a, T> = Cow<'a, Vec<T>, [T]>;
1473 impl<'a, T> FromIterator<T> for CowVec<'a, T> where T: Clone {
1474 fn from_iter<I: Iterator<Item=T>>(it: I) -> CowVec<'a, T> {
1475 Cow::Owned(FromIterator::from_iter(it))
1479 impl<'a, T: 'a> IntoCow<'a, Vec<T>, [T]> for Vec<T> where T: Clone {
1480 fn into_cow(self) -> CowVec<'a, T> {
1485 impl<'a, T> IntoCow<'a, Vec<T>, [T]> for &'a [T] where T: Clone {
1486 fn into_cow(self) -> CowVec<'a, T> {
1491 ////////////////////////////////////////////////////////////////////////////////
1493 ////////////////////////////////////////////////////////////////////////////////
1495 /// An iterator that moves out of a vector.
1497 pub struct IntoIter<T> {
1498 allocation: *mut T, // the block of memory allocated for the vector
1499 cap: uint, // the capacity of the vector
1504 impl<T> IntoIter<T> {
1506 /// Drops all items that have not yet been moved and returns the empty vector.
1508 pub fn into_inner(mut self) -> Vec<T> {
1511 let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
1513 Vec { ptr: NonZero::new(allocation), cap: cap, len: 0 }
1518 impl<T> Iterator for IntoIter<T> {
1522 fn next<'a>(&'a mut self) -> Option<T> {
1524 if self.ptr == self.end {
1527 if mem::size_of::<T>() == 0 {
1528 // purposefully don't use 'ptr.offset' because for
1529 // vectors with 0-size elements this would return the
1531 self.ptr = mem::transmute(self.ptr as uint + 1);
1533 // Use a non-null pointer value
1534 Some(ptr::read(mem::transmute(1u)))
1537 self.ptr = self.ptr.offset(1);
1539 Some(ptr::read(old))
1546 fn size_hint(&self) -> (uint, Option<uint>) {
1547 let diff = (self.end as uint) - (self.ptr as uint);
1548 let size = mem::size_of::<T>();
1549 let exact = diff / (if size == 0 {1} else {size});
1550 (exact, Some(exact))
1554 impl<T> DoubleEndedIterator for IntoIter<T> {
1556 fn next_back<'a>(&'a mut self) -> Option<T> {
1558 if self.end == self.ptr {
1561 if mem::size_of::<T>() == 0 {
1562 // See above for why 'ptr.offset' isn't used
1563 self.end = mem::transmute(self.end as uint - 1);
1565 // Use a non-null pointer value
1566 Some(ptr::read(mem::transmute(1u)))
1568 self.end = self.end.offset(-1);
1570 Some(ptr::read(mem::transmute(self.end)))
1577 impl<T> ExactSizeIterator for IntoIter<T> {}
1579 #[unsafe_destructor]
1580 impl<T> Drop for IntoIter<T> {
1581 fn drop(&mut self) {
1582 // destroy the remaining elements
1586 dealloc(self.allocation, self.cap);
1592 /// An iterator that drains a vector.
1593 #[unsafe_no_drop_flag]
1594 #[unstable = "recently added as part of collections reform 2"]
1595 pub struct Drain<'a, T> {
1598 marker: ContravariantLifetime<'a>,
1601 impl<'a, T> Iterator for Drain<'a, T> {
1605 fn next(&mut self) -> Option<T> {
1607 if self.ptr == self.end {
1610 if mem::size_of::<T>() == 0 {
1611 // purposefully don't use 'ptr.offset' because for
1612 // vectors with 0-size elements this would return the
1614 self.ptr = mem::transmute(self.ptr as uint + 1);
1616 // Use a non-null pointer value
1617 Some(ptr::read(mem::transmute(1u)))
1620 self.ptr = self.ptr.offset(1);
1622 Some(ptr::read(old))
1629 fn size_hint(&self) -> (uint, Option<uint>) {
1630 let diff = (self.end as uint) - (self.ptr as uint);
1631 let size = mem::size_of::<T>();
1632 let exact = diff / (if size == 0 {1} else {size});
1633 (exact, Some(exact))
1637 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1639 fn next_back(&mut self) -> Option<T> {
1641 if self.end == self.ptr {
1644 if mem::size_of::<T>() == 0 {
1645 // See above for why 'ptr.offset' isn't used
1646 self.end = mem::transmute(self.end as uint - 1);
1648 // Use a non-null pointer value
1649 Some(ptr::read(mem::transmute(1u)))
1651 self.end = self.end.offset(-1);
1653 Some(ptr::read(self.end))
1660 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1662 #[unsafe_destructor]
1663 impl<'a, T> Drop for Drain<'a, T> {
1664 fn drop(&mut self) {
1665 // self.ptr == self.end == null if drop has already been called,
1666 // so we can use #[unsafe_no_drop_flag].
1668 // destroy the remaining elements
1673 ////////////////////////////////////////////////////////////////////////////////
1674 // Conversion from &[T] to &Vec<T>
1675 ////////////////////////////////////////////////////////////////////////////////
1677 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1679 pub struct DerefVec<'a, T> {
1681 l: ContravariantLifetime<'a>
1685 impl<'a, T> Deref for DerefVec<'a, T> {
1686 type Target = Vec<T>;
1688 fn deref<'b>(&'b self) -> &'b Vec<T> {
1693 // Prevent the inner `Vec<T>` from attempting to deallocate memory.
1694 #[unsafe_destructor]
1696 impl<'a, T> Drop for DerefVec<'a, T> {
1697 fn drop(&mut self) {
1703 /// Convert a slice to a wrapper type providing a `&Vec<T>` reference.
1705 pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
1708 x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1709 l: ContravariantLifetime::<'a>
1714 ////////////////////////////////////////////////////////////////////////////////
1715 // Partial vec, used for map_in_place
1716 ////////////////////////////////////////////////////////////////////////////////
1718 /// An owned, partially type-converted vector of elements with non-zero size.
1720 /// `T` and `U` must have the same, non-zero size. They must also have the same
1723 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
1724 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
1725 /// destructed. Additionally the underlying storage of `vec` will be freed.
1726 struct PartialVecNonZeroSized<T,U> {
1735 /// An owned, partially type-converted vector of zero-sized elements.
1737 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1739 struct PartialVecZeroSized<T,U> {
1742 marker_t: InvariantType<T>,
1743 marker_u: InvariantType<U>,
1746 #[unsafe_destructor]
1747 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1748 fn drop(&mut self) {
1750 // `vec` hasn't been modified until now. As it has a length
1751 // currently, this would run destructors of `T`s which might not be
1752 // there. So at first, set `vec`s length to `0`. This must be done
1753 // at first to remain memory-safe as the destructors of `U` or `T`
1754 // might cause unwinding where `vec`s destructor would be executed.
1755 self.vec.set_len(0);
1757 // We have instances of `U`s and `T`s in `vec`. Destruct them.
1758 while self.start_u != self.end_u {
1759 let _ = ptr::read(self.start_u as *const U); // Run a `U` destructor.
1760 self.start_u = self.start_u.offset(1);
1762 while self.start_t != self.end_t {
1763 let _ = ptr::read(self.start_t as *const T); // Run a `T` destructor.
1764 self.start_t = self.start_t.offset(1);
1766 // After this destructor ran, the destructor of `vec` will run,
1767 // deallocating the underlying memory.
1772 #[unsafe_destructor]
1773 impl<T,U> Drop for PartialVecZeroSized<T,U> {
1774 fn drop(&mut self) {
1776 // Destruct the instances of `T` and `U` this struct owns.
1777 while self.num_t != 0 {
1778 let _: T = mem::uninitialized(); // Run a `T` destructor.
1781 while self.num_u != 0 {
1782 let _: U = mem::uninitialized(); // Run a `U` destructor.
1792 use core::mem::size_of;
1793 use core::iter::repeat;
1797 struct DropCounter<'a> {
1801 #[unsafe_destructor]
1802 impl<'a> Drop for DropCounter<'a> {
1803 fn drop(&mut self) {
1810 let xs = [1u8, 2u8, 3u8];
1811 assert_eq!(as_vec(&xs).as_slice(), xs);
1815 fn test_as_vec_dtor() {
1816 let (mut count_x, mut count_y) = (0, 0);
1818 let xs = &[DropCounter { count: &mut count_x }, DropCounter { count: &mut count_y }];
1819 assert_eq!(as_vec(xs).len(), 2);
1821 assert_eq!(count_x, 1);
1822 assert_eq!(count_y, 1);
1826 fn test_small_vec_struct() {
1827 assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1831 fn test_double_drop() {
1837 let (mut count_x, mut count_y) = (0, 0);
1839 let mut tv = TwoVec {
1843 tv.x.push(DropCounter {count: &mut count_x});
1844 tv.y.push(DropCounter {count: &mut count_y});
1846 // If Vec had a drop flag, here is where it would be zeroed.
1847 // Instead, it should rely on its internal state to prevent
1848 // doing anything significant when dropped multiple times.
1851 // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1854 assert_eq!(count_x, 1);
1855 assert_eq!(count_y, 1);
1860 let mut v = Vec::new();
1861 assert_eq!(v.capacity(), 0);
1864 assert!(v.capacity() >= 2);
1866 for i in range(0i, 16) {
1870 assert!(v.capacity() >= 16);
1872 assert!(v.capacity() >= 32);
1877 assert!(v.capacity() >= 33)
1882 let mut v = Vec::new();
1883 let mut w = Vec::new();
1885 v.extend(range(0i, 3));
1886 for i in range(0i, 3) { w.push(i) }
1890 v.extend(range(3i, 10));
1891 for i in range(3i, 10) { w.push(i) }
1897 fn test_slice_from_mut() {
1898 let mut values = vec![1u8,2,3,4,5];
1900 let slice = values.slice_from_mut(2);
1901 assert!(slice == [3, 4, 5]);
1902 for p in slice.iter_mut() {
1907 assert!(values == [1, 2, 5, 6, 7]);
1911 fn test_slice_to_mut() {
1912 let mut values = vec![1u8,2,3,4,5];
1914 let slice = values.slice_to_mut(2);
1915 assert!(slice == [1, 2]);
1916 for p in slice.iter_mut() {
1921 assert!(values == [2, 3, 3, 4, 5]);
1925 fn test_split_at_mut() {
1926 let mut values = vec![1u8,2,3,4,5];
1928 let (left, right) = values.split_at_mut(2);
1930 let left: &[_] = left;
1931 assert!(left[0..left.len()] == [1, 2][]);
1933 for p in left.iter_mut() {
1938 let right: &[_] = right;
1939 assert!(right[0..right.len()] == [3, 4, 5][]);
1941 for p in right.iter_mut() {
1946 assert!(values == vec![2u8, 3, 5, 6, 7]);
1951 let v: Vec<int> = vec!();
1952 let w = vec!(1i, 2, 3);
1954 assert_eq!(v, v.clone());
1958 // they should be disjoint in memory.
1959 assert!(w.as_ptr() != z.as_ptr())
1963 fn test_clone_from() {
1965 let three = vec!(box 1i, box 2, box 3);
1966 let two = vec!(box 4i, box 5);
1968 v.clone_from(&three);
1969 assert_eq!(v, three);
1972 v.clone_from(&three);
1973 assert_eq!(v, three);
1980 v.clone_from(&three);
1981 assert_eq!(v, three)
1986 let mut vec = vec![1u, 2, 3, 4];
1987 vec.retain(|&x| x % 2 == 0);
1988 assert!(vec == vec![2u, 4]);
1992 fn zero_sized_values() {
1993 let mut v = Vec::new();
1994 assert_eq!(v.len(), 0);
1996 assert_eq!(v.len(), 1);
1998 assert_eq!(v.len(), 2);
1999 assert_eq!(v.pop(), Some(()));
2000 assert_eq!(v.pop(), Some(()));
2001 assert_eq!(v.pop(), None);
2003 assert_eq!(v.iter().count(), 0);
2005 assert_eq!(v.iter().count(), 1);
2007 assert_eq!(v.iter().count(), 2);
2009 for &() in v.iter() {}
2011 assert_eq!(v.iter_mut().count(), 2);
2013 assert_eq!(v.iter_mut().count(), 3);
2015 assert_eq!(v.iter_mut().count(), 4);
2017 for &() in v.iter_mut() {}
2018 unsafe { v.set_len(0); }
2019 assert_eq!(v.iter_mut().count(), 0);
2023 fn test_partition() {
2024 assert_eq!(vec![].into_iter().partition(|x: &int| *x < 3), (vec![], vec![]));
2025 assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2026 assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2027 assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2031 fn test_zip_unzip() {
2032 let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
2034 let (left, right): (Vec<_>, Vec<_>) = z1.iter().map(|&x| x).unzip();
2036 assert_eq!((1, 4), (left[0], right[0]));
2037 assert_eq!((2, 5), (left[1], right[1]));
2038 assert_eq!((3, 6), (left[2], right[2]));
2042 fn test_unsafe_ptrs() {
2044 // Test on-stack copy-from-buf.
2046 let ptr = a.as_ptr();
2047 let b = Vec::from_raw_buf(ptr, 3u);
2048 assert_eq!(b, vec![1, 2, 3]);
2050 // Test on-heap copy-from-buf.
2051 let c = vec![1i, 2, 3, 4, 5];
2052 let ptr = c.as_ptr();
2053 let d = Vec::from_raw_buf(ptr, 5u);
2054 assert_eq!(d, vec![1, 2, 3, 4, 5]);
2059 fn test_vec_truncate_drop() {
2060 static mut drops: uint = 0;
2062 impl Drop for Elem {
2063 fn drop(&mut self) {
2064 unsafe { drops += 1; }
2068 let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
2069 assert_eq!(unsafe { drops }, 0);
2071 assert_eq!(unsafe { drops }, 2);
2073 assert_eq!(unsafe { drops }, 5);
2078 fn test_vec_truncate_fail() {
2079 struct BadElem(int);
2080 impl Drop for BadElem {
2081 fn drop(&mut self) {
2082 let BadElem(ref mut x) = *self;
2083 if *x == 0xbadbeef {
2084 panic!("BadElem panic: 0xbadbeef")
2089 let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
2095 let vec = vec!(1i, 2, 3);
2096 assert!(vec[1] == 2);
2101 fn test_index_out_of_bounds() {
2102 let vec = vec!(1i, 2, 3);
2108 fn test_slice_out_of_bounds_1() {
2109 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2115 fn test_slice_out_of_bounds_2() {
2116 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2122 fn test_slice_out_of_bounds_3() {
2123 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2129 fn test_slice_out_of_bounds_4() {
2130 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2136 fn test_slice_out_of_bounds_5() {
2137 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2143 fn test_swap_remove_empty() {
2144 let mut vec: Vec<uint> = vec!();
2149 fn test_move_iter_unwrap() {
2150 let mut vec: Vec<uint> = Vec::with_capacity(7);
2153 let ptr = vec.as_ptr();
2154 vec = vec.into_iter().into_inner();
2155 assert_eq!(vec.as_ptr(), ptr);
2156 assert_eq!(vec.capacity(), 7);
2157 assert_eq!(vec.len(), 0);
2162 fn test_map_in_place_incompatible_types_fail() {
2163 let v = vec![0u, 1, 2];
2164 v.map_in_place(|_| ());
2168 fn test_map_in_place() {
2169 let v = vec![0u, 1, 2];
2170 assert_eq!(v.map_in_place(|i: uint| i as int - 1), [-1i, 0, 1]);
2174 fn test_map_in_place_zero_sized() {
2175 let v = vec![(), ()];
2176 #[derive(PartialEq, Show)]
2178 assert_eq!(v.map_in_place(|_| ZeroSized), [ZeroSized, ZeroSized]);
2182 fn test_map_in_place_zero_drop_count() {
2183 use std::sync::atomic::{AtomicUint, Ordering, ATOMIC_UINT_INIT};
2185 #[derive(Clone, PartialEq, Show)]
2187 impl Drop for Nothing { fn drop(&mut self) { } }
2189 #[derive(Clone, PartialEq, Show)]
2191 impl Drop for ZeroSized {
2192 fn drop(&mut self) {
2193 DROP_COUNTER.fetch_add(1, Ordering::Relaxed);
2196 const NUM_ELEMENTS: uint = 2;
2197 static DROP_COUNTER: AtomicUint = ATOMIC_UINT_INIT;
2199 let v = repeat(Nothing).take(NUM_ELEMENTS).collect::<Vec<_>>();
2201 DROP_COUNTER.store(0, Ordering::Relaxed);
2203 let v = v.map_in_place(|_| ZeroSized);
2204 assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), 0);
2206 assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), NUM_ELEMENTS);
2210 fn test_move_items() {
2211 let vec = vec![1, 2, 3];
2212 let mut vec2 : Vec<i32> = vec![];
2213 for i in vec.into_iter() {
2216 assert!(vec2 == vec![1, 2, 3]);
2220 fn test_move_items_reverse() {
2221 let vec = vec![1, 2, 3];
2222 let mut vec2 : Vec<i32> = vec![];
2223 for i in vec.into_iter().rev() {
2226 assert!(vec2 == vec![3, 2, 1]);
2230 fn test_move_items_zero_sized() {
2231 let vec = vec![(), (), ()];
2232 let mut vec2 : Vec<()> = vec![];
2233 for i in vec.into_iter() {
2236 assert!(vec2 == vec![(), (), ()]);
2240 fn test_drain_items() {
2241 let mut vec = vec![1, 2, 3];
2242 let mut vec2: Vec<i32> = vec![];
2243 for i in vec.drain() {
2246 assert_eq!(vec, []);
2247 assert_eq!(vec2, [ 1, 2, 3 ]);
2251 fn test_drain_items_reverse() {
2252 let mut vec = vec![1, 2, 3];
2253 let mut vec2: Vec<i32> = vec![];
2254 for i in vec.drain().rev() {
2257 assert_eq!(vec, []);
2258 assert_eq!(vec2, [ 3, 2, 1 ]);
2262 fn test_drain_items_zero_sized() {
2263 let mut vec = vec![(), (), ()];
2264 let mut vec2: Vec<()> = vec![];
2265 for i in vec.drain() {
2268 assert_eq!(vec, []);
2269 assert_eq!(vec2, [(), (), ()]);
2273 fn test_into_boxed_slice() {
2274 let xs = vec![1u, 2, 3];
2275 let ys = xs.into_boxed_slice();
2276 assert_eq!(ys.as_slice(), [1u, 2, 3]);
2280 fn bench_new(b: &mut Bencher) {
2282 let v: Vec<uint> = Vec::new();
2283 assert_eq!(v.len(), 0);
2284 assert_eq!(v.capacity(), 0);
2288 fn do_bench_with_capacity(b: &mut Bencher, src_len: uint) {
2289 b.bytes = src_len as u64;
2292 let v: Vec<uint> = Vec::with_capacity(src_len);
2293 assert_eq!(v.len(), 0);
2294 assert_eq!(v.capacity(), src_len);
2299 fn bench_with_capacity_0000(b: &mut Bencher) {
2300 do_bench_with_capacity(b, 0)
2304 fn bench_with_capacity_0010(b: &mut Bencher) {
2305 do_bench_with_capacity(b, 10)
2309 fn bench_with_capacity_0100(b: &mut Bencher) {
2310 do_bench_with_capacity(b, 100)
2314 fn bench_with_capacity_1000(b: &mut Bencher) {
2315 do_bench_with_capacity(b, 1000)
2318 fn do_bench_from_fn(b: &mut Bencher, src_len: uint) {
2319 b.bytes = src_len as u64;
2322 let dst = range(0, src_len).collect::<Vec<_>>();
2323 assert_eq!(dst.len(), src_len);
2324 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2329 fn bench_from_fn_0000(b: &mut Bencher) {
2330 do_bench_from_fn(b, 0)
2334 fn bench_from_fn_0010(b: &mut Bencher) {
2335 do_bench_from_fn(b, 10)
2339 fn bench_from_fn_0100(b: &mut Bencher) {
2340 do_bench_from_fn(b, 100)
2344 fn bench_from_fn_1000(b: &mut Bencher) {
2345 do_bench_from_fn(b, 1000)
2348 fn do_bench_from_elem(b: &mut Bencher, src_len: uint) {
2349 b.bytes = src_len as u64;
2352 let dst: Vec<uint> = repeat(5).take(src_len).collect();
2353 assert_eq!(dst.len(), src_len);
2354 assert!(dst.iter().all(|x| *x == 5));
2359 fn bench_from_elem_0000(b: &mut Bencher) {
2360 do_bench_from_elem(b, 0)
2364 fn bench_from_elem_0010(b: &mut Bencher) {
2365 do_bench_from_elem(b, 10)
2369 fn bench_from_elem_0100(b: &mut Bencher) {
2370 do_bench_from_elem(b, 100)
2374 fn bench_from_elem_1000(b: &mut Bencher) {
2375 do_bench_from_elem(b, 1000)
2378 fn do_bench_from_slice(b: &mut Bencher, src_len: uint) {
2379 let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2381 b.bytes = src_len as u64;
2384 let dst = src.clone().as_slice().to_vec();
2385 assert_eq!(dst.len(), src_len);
2386 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2391 fn bench_from_slice_0000(b: &mut Bencher) {
2392 do_bench_from_slice(b, 0)
2396 fn bench_from_slice_0010(b: &mut Bencher) {
2397 do_bench_from_slice(b, 10)
2401 fn bench_from_slice_0100(b: &mut Bencher) {
2402 do_bench_from_slice(b, 100)
2406 fn bench_from_slice_1000(b: &mut Bencher) {
2407 do_bench_from_slice(b, 1000)
2410 fn do_bench_from_iter(b: &mut Bencher, src_len: uint) {
2411 let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2413 b.bytes = src_len as u64;
2416 let dst: Vec<uint> = FromIterator::from_iter(src.clone().into_iter());
2417 assert_eq!(dst.len(), src_len);
2418 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2423 fn bench_from_iter_0000(b: &mut Bencher) {
2424 do_bench_from_iter(b, 0)
2428 fn bench_from_iter_0010(b: &mut Bencher) {
2429 do_bench_from_iter(b, 10)
2433 fn bench_from_iter_0100(b: &mut Bencher) {
2434 do_bench_from_iter(b, 100)
2438 fn bench_from_iter_1000(b: &mut Bencher) {
2439 do_bench_from_iter(b, 1000)
2442 fn do_bench_extend(b: &mut Bencher, dst_len: uint, src_len: uint) {
2443 let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2444 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2446 b.bytes = src_len as u64;
2449 let mut dst = dst.clone();
2450 dst.extend(src.clone().into_iter());
2451 assert_eq!(dst.len(), dst_len + src_len);
2452 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2457 fn bench_extend_0000_0000(b: &mut Bencher) {
2458 do_bench_extend(b, 0, 0)
2462 fn bench_extend_0000_0010(b: &mut Bencher) {
2463 do_bench_extend(b, 0, 10)
2467 fn bench_extend_0000_0100(b: &mut Bencher) {
2468 do_bench_extend(b, 0, 100)
2472 fn bench_extend_0000_1000(b: &mut Bencher) {
2473 do_bench_extend(b, 0, 1000)
2477 fn bench_extend_0010_0010(b: &mut Bencher) {
2478 do_bench_extend(b, 10, 10)
2482 fn bench_extend_0100_0100(b: &mut Bencher) {
2483 do_bench_extend(b, 100, 100)
2487 fn bench_extend_1000_1000(b: &mut Bencher) {
2488 do_bench_extend(b, 1000, 1000)
2491 fn do_bench_push_all(b: &mut Bencher, dst_len: uint, src_len: uint) {
2492 let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2493 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2495 b.bytes = src_len as u64;
2498 let mut dst = dst.clone();
2499 dst.push_all(src.as_slice());
2500 assert_eq!(dst.len(), dst_len + src_len);
2501 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2506 fn bench_push_all_0000_0000(b: &mut Bencher) {
2507 do_bench_push_all(b, 0, 0)
2511 fn bench_push_all_0000_0010(b: &mut Bencher) {
2512 do_bench_push_all(b, 0, 10)
2516 fn bench_push_all_0000_0100(b: &mut Bencher) {
2517 do_bench_push_all(b, 0, 100)
2521 fn bench_push_all_0000_1000(b: &mut Bencher) {
2522 do_bench_push_all(b, 0, 1000)
2526 fn bench_push_all_0010_0010(b: &mut Bencher) {
2527 do_bench_push_all(b, 10, 10)
2531 fn bench_push_all_0100_0100(b: &mut Bencher) {
2532 do_bench_push_all(b, 100, 100)
2536 fn bench_push_all_1000_1000(b: &mut Bencher) {
2537 do_bench_push_all(b, 1000, 1000)
2540 fn do_bench_push_all_move(b: &mut Bencher, dst_len: uint, src_len: uint) {
2541 let dst: Vec<uint> = FromIterator::from_iter(range(0u, dst_len));
2542 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2544 b.bytes = src_len as u64;
2547 let mut dst = dst.clone();
2548 dst.extend(src.clone().into_iter());
2549 assert_eq!(dst.len(), dst_len + src_len);
2550 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2555 fn bench_push_all_move_0000_0000(b: &mut Bencher) {
2556 do_bench_push_all_move(b, 0, 0)
2560 fn bench_push_all_move_0000_0010(b: &mut Bencher) {
2561 do_bench_push_all_move(b, 0, 10)
2565 fn bench_push_all_move_0000_0100(b: &mut Bencher) {
2566 do_bench_push_all_move(b, 0, 100)
2570 fn bench_push_all_move_0000_1000(b: &mut Bencher) {
2571 do_bench_push_all_move(b, 0, 1000)
2575 fn bench_push_all_move_0010_0010(b: &mut Bencher) {
2576 do_bench_push_all_move(b, 10, 10)
2580 fn bench_push_all_move_0100_0100(b: &mut Bencher) {
2581 do_bench_push_all_move(b, 100, 100)
2585 fn bench_push_all_move_1000_1000(b: &mut Bencher) {
2586 do_bench_push_all_move(b, 1000, 1000)
2589 fn do_bench_clone(b: &mut Bencher, src_len: uint) {
2590 let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2592 b.bytes = src_len as u64;
2595 let dst = src.clone();
2596 assert_eq!(dst.len(), src_len);
2597 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2602 fn bench_clone_0000(b: &mut Bencher) {
2603 do_bench_clone(b, 0)
2607 fn bench_clone_0010(b: &mut Bencher) {
2608 do_bench_clone(b, 10)
2612 fn bench_clone_0100(b: &mut Bencher) {
2613 do_bench_clone(b, 100)
2617 fn bench_clone_1000(b: &mut Bencher) {
2618 do_bench_clone(b, 1000)
2621 fn do_bench_clone_from(b: &mut Bencher, times: uint, dst_len: uint, src_len: uint) {
2622 let dst: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2623 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2625 b.bytes = (times * src_len) as u64;
2628 let mut dst = dst.clone();
2630 for _ in range(0, times) {
2631 dst.clone_from(&src);
2633 assert_eq!(dst.len(), src_len);
2634 assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x));
2640 fn bench_clone_from_01_0000_0000(b: &mut Bencher) {
2641 do_bench_clone_from(b, 1, 0, 0)
2645 fn bench_clone_from_01_0000_0010(b: &mut Bencher) {
2646 do_bench_clone_from(b, 1, 0, 10)
2650 fn bench_clone_from_01_0000_0100(b: &mut Bencher) {
2651 do_bench_clone_from(b, 1, 0, 100)
2655 fn bench_clone_from_01_0000_1000(b: &mut Bencher) {
2656 do_bench_clone_from(b, 1, 0, 1000)
2660 fn bench_clone_from_01_0010_0010(b: &mut Bencher) {
2661 do_bench_clone_from(b, 1, 10, 10)
2665 fn bench_clone_from_01_0100_0100(b: &mut Bencher) {
2666 do_bench_clone_from(b, 1, 100, 100)
2670 fn bench_clone_from_01_1000_1000(b: &mut Bencher) {
2671 do_bench_clone_from(b, 1, 1000, 1000)
2675 fn bench_clone_from_01_0010_0100(b: &mut Bencher) {
2676 do_bench_clone_from(b, 1, 10, 100)
2680 fn bench_clone_from_01_0100_1000(b: &mut Bencher) {
2681 do_bench_clone_from(b, 1, 100, 1000)
2685 fn bench_clone_from_01_0010_0000(b: &mut Bencher) {
2686 do_bench_clone_from(b, 1, 10, 0)
2690 fn bench_clone_from_01_0100_0010(b: &mut Bencher) {
2691 do_bench_clone_from(b, 1, 100, 10)
2695 fn bench_clone_from_01_1000_0100(b: &mut Bencher) {
2696 do_bench_clone_from(b, 1, 1000, 100)
2700 fn bench_clone_from_10_0000_0000(b: &mut Bencher) {
2701 do_bench_clone_from(b, 10, 0, 0)
2705 fn bench_clone_from_10_0000_0010(b: &mut Bencher) {
2706 do_bench_clone_from(b, 10, 0, 10)
2710 fn bench_clone_from_10_0000_0100(b: &mut Bencher) {
2711 do_bench_clone_from(b, 10, 0, 100)
2715 fn bench_clone_from_10_0000_1000(b: &mut Bencher) {
2716 do_bench_clone_from(b, 10, 0, 1000)
2720 fn bench_clone_from_10_0010_0010(b: &mut Bencher) {
2721 do_bench_clone_from(b, 10, 10, 10)
2725 fn bench_clone_from_10_0100_0100(b: &mut Bencher) {
2726 do_bench_clone_from(b, 10, 100, 100)
2730 fn bench_clone_from_10_1000_1000(b: &mut Bencher) {
2731 do_bench_clone_from(b, 10, 1000, 1000)
2735 fn bench_clone_from_10_0010_0100(b: &mut Bencher) {
2736 do_bench_clone_from(b, 10, 10, 100)
2740 fn bench_clone_from_10_0100_1000(b: &mut Bencher) {
2741 do_bench_clone_from(b, 10, 100, 1000)
2745 fn bench_clone_from_10_0010_0000(b: &mut Bencher) {
2746 do_bench_clone_from(b, 10, 10, 0)
2750 fn bench_clone_from_10_0100_0010(b: &mut Bencher) {
2751 do_bench_clone_from(b, 10, 100, 10)
2755 fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
2756 do_bench_clone_from(b, 10, 1000, 100)