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 use alloc::boxed::Box;
18 use alloc::heap::{EMPTY, allocate, reallocate, deallocate};
20 use core::default::Default;
22 use core::kinds::marker::{ContravariantLifetime, InvariantType};
27 use core::raw::Slice as RawSlice;
30 use slice::{CloneSliceAllocPrelude};
32 /// An owned, growable vector.
37 /// let mut vec = Vec::new();
41 /// assert_eq!(vec.len(), 2);
42 /// assert_eq!(vec[0], 1);
44 /// assert_eq!(vec.pop(), Some(2));
45 /// assert_eq!(vec.len(), 1);
48 /// assert_eq!(vec[0], 7);
50 /// vec.push_all([1, 2, 3]);
52 /// for x in vec.iter() {
53 /// println!("{}", x);
55 /// assert_eq!(vec, vec![7i, 1, 2, 3]);
58 /// The `vec!` macro is provided to make initialization more convenient:
61 /// let mut vec = vec![1i, 2i, 3i];
63 /// assert_eq!(vec, vec![1, 2, 3, 4]);
66 /// Use a `Vec` as an efficient stack:
69 /// let mut stack = Vec::new();
76 /// let top = match stack.pop() {
77 /// None => break, // empty
81 /// println!("{}", top);
85 /// # Capacity and reallocation
87 /// The capacity of a vector is the amount of space allocated for any future
88 /// elements that will be added onto the vector. This is not to be confused
89 /// with the *length* of a vector, which specifies the number of actual
90 /// elements within the vector. If a vector's length exceeds its capacity,
91 /// its capacity will automatically be increased, but its elements will
92 /// have to be reallocated.
94 /// For example, a vector with capacity 10 and length 0 would be an empty
95 /// vector with space for 10 more elements. Pushing 10 or fewer elements onto
96 /// the vector will not change its capacity or cause reallocation to occur.
97 /// However, if the vector's length is increased to 11, it will have to
98 /// reallocate, which can be slow. For this reason, it is recommended
99 /// to use `Vec::with_capacity` whenever possible to specify how big the vector
100 /// is expected to get.
101 #[unsafe_no_drop_flag]
110 /// Constructs a new, empty `Vec`.
112 /// The vector will not allocate until elements are pushed onto it.
117 /// let mut vec: Vec<int> = Vec::new();
121 pub fn new() -> Vec<T> {
122 // We want ptr to never be NULL so instead we set it to some arbitrary
123 // non-null value which is fine since we never call deallocate on the ptr
124 // if cap is 0. The reason for this is because the pointer of a slice
125 // being NULL would break the null pointer optimization for enums.
126 Vec { ptr: EMPTY as *mut T, len: 0, cap: 0 }
129 /// Constructs a new, empty `Vec` with the specified capacity.
131 /// The vector will be able to hold exactly `capacity` elements without
132 /// reallocating. If `capacity` is 0, the vector will not allocate.
134 /// It is important to note that this function does not specify the
135 /// *length* of the returned vector, but only the *capacity*. (For an
136 /// explanation of the difference between length and capacity, see
137 /// the main `Vec` docs above, 'Capacity and reallocation'.) To create
138 /// a vector of a given length, use `Vec::from_elem` or `Vec::from_fn`.
143 /// let mut vec: Vec<int> = Vec::with_capacity(10);
145 /// // The vector contains no items, even though it has capacity for more
146 /// assert_eq!(vec.len(), 0);
148 /// // These are all done without reallocating...
149 /// for i in range(0i, 10) {
153 /// // ...but this may make the vector reallocate
158 pub fn with_capacity(capacity: uint) -> Vec<T> {
159 if mem::size_of::<T>() == 0 {
160 Vec { ptr: EMPTY as *mut T, len: 0, cap: uint::MAX }
161 } else if capacity == 0 {
164 let size = capacity.checked_mul(&mem::size_of::<T>())
165 .expect("capacity overflow");
166 let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
167 Vec { ptr: ptr as *mut T, len: 0, cap: capacity }
171 /// Creates and initializes a `Vec`.
173 /// Creates a `Vec` of size `length` and initializes the elements to the
174 /// value returned by the closure `op`.
179 /// let vec = Vec::from_fn(3, |idx| idx * 2);
180 /// assert_eq!(vec, vec![0, 2, 4]);
183 #[unstable = "the naming is uncertain as well as this migrating to unboxed \
184 closures in the future"]
185 pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
187 let mut xs = Vec::with_capacity(length);
188 while xs.len < length {
190 ptr::write(xs.as_mut_slice().unsafe_mut(len), op(len));
197 /// Creates a `Vec<T>` directly from the raw constituents.
199 /// This is highly unsafe:
201 /// - if `ptr` is null, then `length` and `capacity` should be 0
202 /// - `ptr` must point to an allocation of size `capacity`
203 /// - there must be `length` valid instances of type `T` at the
204 /// beginning of that allocation
205 /// - `ptr` must be allocated by the default `Vec` allocator
214 /// let mut v = vec![1i, 2, 3];
216 /// // Pull out the various important pieces of information about `v`
217 /// let p = v.as_mut_ptr();
218 /// let len = v.len();
219 /// let cap = v.capacity();
222 /// // Cast `v` into the void: no destructor run, so we are in
223 /// // complete control of the allocation to which `p` points.
226 /// // Overwrite memory with 4, 5, 6
227 /// for i in range(0, len as int) {
228 /// ptr::write(p.offset(i), 4 + i);
231 /// // Put everything back together into a Vec
232 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
233 /// assert_eq!(rebuilt, vec![4i, 5i, 6i]);
238 pub unsafe fn from_raw_parts(ptr: *mut T, length: uint,
239 capacity: uint) -> Vec<T> {
240 Vec { ptr: ptr, len: length, cap: capacity }
243 /// Consumes the `Vec`, partitioning it based on a predicate.
245 /// Partitions the `Vec` into two `Vec`s `(A,B)`, where all elements of `A`
246 /// satisfy `f` and all elements of `B` do not. The order of elements is
252 /// let vec = vec![1i, 2i, 3i, 4i];
253 /// let (even, odd) = vec.partition(|&n| n % 2 == 0);
254 /// assert_eq!(even, vec![2, 4]);
255 /// assert_eq!(odd, vec![1, 3]);
259 pub fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
260 let mut lefts = Vec::new();
261 let mut rights = Vec::new();
263 for elt in self.into_iter() {
275 impl<T: Clone> Vec<T> {
276 /// Constructs a `Vec` with copies of a value.
278 /// Creates a `Vec` with `length` copies of `value`.
282 /// let vec = Vec::from_elem(3, "hi");
283 /// println!("{}", vec); // prints [hi, hi, hi]
286 #[unstable = "this functionality may become more generic over all collections"]
287 pub fn from_elem(length: uint, value: T) -> Vec<T> {
289 let mut xs = Vec::with_capacity(length);
290 while xs.len < length {
292 ptr::write(xs.as_mut_slice().unsafe_mut(len),
300 /// Appends all elements in a slice to the `Vec`.
302 /// Iterates over the slice `other`, clones each element, and then appends
303 /// it to this `Vec`. The `other` vector is traversed in-order.
308 /// let mut vec = vec![1i];
309 /// vec.push_all([2i, 3, 4]);
310 /// assert_eq!(vec, vec![1, 2, 3, 4]);
314 pub fn push_all(&mut self, other: &[T]) {
315 self.reserve(other.len());
317 for i in range(0, other.len()) {
318 let len = self.len();
320 // Unsafe code so this can be optimised to a memcpy (or something similarly
321 // fast) when T is Copy. LLVM is easily confused, so any extra operations
322 // during the loop can prevent this optimisation.
325 self.as_mut_slice().unsafe_mut(len),
326 other.unsafe_get(i).clone());
327 self.set_len(len + 1);
332 /// Grows the `Vec` in-place.
334 /// Adds `n` copies of `value` to the `Vec`.
339 /// let mut vec = vec!["hello"];
340 /// vec.grow(2, "world");
341 /// assert_eq!(vec, vec!["hello", "world", "world"]);
344 pub fn grow(&mut self, n: uint, value: T) {
346 let mut i: uint = 0u;
349 self.push(value.clone());
354 /// Partitions a vector based on a predicate.
356 /// Clones the elements of the vector, partitioning them into two `Vec`s
357 /// `(a, b)`, where all elements of `a` satisfy `f` and all elements of `b`
358 /// do not. The order of elements is preserved.
363 /// let vec = vec![1i, 2, 3, 4];
364 /// let (even, odd) = vec.partitioned(|&n| n % 2 == 0);
365 /// assert_eq!(even, vec![2i, 4]);
366 /// assert_eq!(odd, vec![1i, 3]);
369 pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
370 let mut lefts = Vec::new();
371 let mut rights = Vec::new();
373 for elt in self.iter() {
375 lefts.push(elt.clone());
377 rights.push(elt.clone());
386 impl<T:Clone> Clone for Vec<T> {
387 fn clone(&self) -> Vec<T> { self.as_slice().to_vec() }
389 fn clone_from(&mut self, other: &Vec<T>) {
390 // drop anything in self that will not be overwritten
391 if self.len() > other.len() {
392 self.truncate(other.len())
395 // reuse the contained values' allocations/resources.
396 for (place, thing) in self.iter_mut().zip(other.iter()) {
397 place.clone_from(thing)
400 // self.len <= other.len due to the truncate above, so the
401 // slice here is always in-bounds.
402 let slice = other[self.len()..];
403 self.push_all(slice);
407 #[experimental = "waiting on Index stability"]
408 impl<T> Index<uint,T> for Vec<T> {
410 fn index<'a>(&'a self, index: &uint) -> &'a T {
411 &self.as_slice()[*index]
415 impl<T> IndexMut<uint,T> for Vec<T> {
417 fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
418 &mut self.as_mut_slice()[*index]
422 impl<T> ops::Slice<uint, [T]> for Vec<T> {
424 fn as_slice_<'a>(&'a self) -> &'a [T] {
429 fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [T] {
430 self.as_slice().slice_from_or_fail(start)
434 fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [T] {
435 self.as_slice().slice_to_or_fail(end)
438 fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] {
439 self.as_slice().slice_or_fail(start, end)
443 impl<T> ops::SliceMut<uint, [T]> for Vec<T> {
445 fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
450 fn slice_from_or_fail_mut<'a>(&'a mut self, start: &uint) -> &'a mut [T] {
451 self.as_mut_slice().slice_from_or_fail_mut(start)
455 fn slice_to_or_fail_mut<'a>(&'a mut self, end: &uint) -> &'a mut [T] {
456 self.as_mut_slice().slice_to_or_fail_mut(end)
459 fn slice_or_fail_mut<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] {
460 self.as_mut_slice().slice_or_fail_mut(start, end)
464 #[experimental = "waiting on Deref stability"]
465 impl<T> ops::Deref<[T]> for Vec<T> {
466 fn deref<'a>(&'a self) -> &'a [T] { self.as_slice() }
469 #[experimental = "waiting on DerefMut stability"]
470 impl<T> ops::DerefMut<[T]> for Vec<T> {
471 fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.as_mut_slice() }
474 #[experimental = "waiting on FromIterator stability"]
475 impl<T> FromIterator<T> for Vec<T> {
477 fn from_iter<I:Iterator<T>>(mut iterator: I) -> Vec<T> {
478 let (lower, _) = iterator.size_hint();
479 let mut vector = Vec::with_capacity(lower);
480 for element in iterator {
487 #[experimental = "waiting on Extend stability"]
488 impl<T> Extend<T> for Vec<T> {
490 fn extend<I: Iterator<T>>(&mut self, mut iterator: I) {
491 let (lower, _) = iterator.size_hint();
493 for element in iterator {
499 #[unstable = "waiting on PartialEq stability"]
500 impl<T: PartialEq> PartialEq for Vec<T> {
502 fn eq(&self, other: &Vec<T>) -> bool {
503 self.as_slice() == other.as_slice()
507 #[unstable = "waiting on PartialOrd stability"]
508 impl<T: PartialOrd> PartialOrd for Vec<T> {
509 // NOTE(stage0): remove method after a snapshot
512 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
513 self.as_slice().partial_cmp(&other.as_slice())
515 #[cfg(not(stage0))] // NOTE(stage0): remove cfg after a snapshot
517 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
518 self.as_slice().partial_cmp(other.as_slice())
522 #[unstable = "waiting on Eq stability"]
523 impl<T: Eq> Eq for Vec<T> {}
526 impl<T: PartialEq, V: AsSlice<T>> Equiv<V> for Vec<T> {
528 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
531 #[unstable = "waiting on Ord stability"]
532 impl<T: Ord> Ord for Vec<T> {
533 // NOTE(stage0): remove method after a snapshot
536 fn cmp(&self, other: &Vec<T>) -> Ordering {
537 self.as_slice().cmp(&other.as_slice())
539 #[cfg(not(stage0))] // NOTE(stage0): remove cfg after a snapshot
541 fn cmp(&self, other: &Vec<T>) -> Ordering {
542 self.as_slice().cmp(other.as_slice())
546 // FIXME: #13996: need a way to mark the return value as `noalias`
548 unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: uint, size: uint) -> *mut T {
550 allocate(size, mem::min_align_of::<T>()) as *mut T
552 reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T
557 unsafe fn dealloc<T>(ptr: *mut T, len: uint) {
558 if mem::size_of::<T>() != 0 {
559 deallocate(ptr as *mut u8,
560 len * mem::size_of::<T>(),
561 mem::min_align_of::<T>())
566 /// Returns the number of elements the vector can hold without
572 /// let vec: Vec<int> = Vec::with_capacity(10);
573 /// assert_eq!(vec.capacity(), 10);
577 pub fn capacity(&self) -> uint {
581 /// Deprecated: Renamed to `reserve`.
582 #[deprecated = "Renamed to `reserve`"]
583 pub fn reserve_additional(&mut self, extra: uint) {
587 /// Reserves capacity for at least `additional` more elements to be inserted in the given
588 /// `Vec`. The collection may reserve more space to avoid frequent reallocations.
592 /// Panics if the new capacity overflows `uint`.
597 /// let mut vec: Vec<int> = vec![1];
599 /// assert!(vec.capacity() >= 11);
601 #[unstable = "matches collection reform specification, waiting for dust to settle"]
602 pub fn reserve(&mut self, additional: uint) {
603 if self.cap - self.len < additional {
604 match self.len.checked_add(&additional) {
605 None => panic!("Vec::reserve: `uint` overflow"),
606 // if the checked_add
608 let amort_cap = num::next_power_of_two(new_cap);
609 // next_power_of_two will overflow to exactly 0 for really big capacities
611 self.grow_capacity(new_cap);
613 self.grow_capacity(amort_cap);
620 /// Reserves the minimum capacity for exactly `additional` more elements to be inserted in the
621 /// given `Vec`. Does nothing if the capacity is already sufficient.
623 /// Note that the allocator may give the collection more space than it requests. Therefore
624 /// capacity can not be relied upon to be precisely minimal. Prefer `reserve` if future
625 /// insertions are expected.
629 /// Panics if the new capacity overflows `uint`.
634 /// let mut vec: Vec<int> = vec![1];
635 /// vec.reserve_exact(10);
636 /// assert!(vec.capacity() >= 11);
638 #[unstable = "matches collection reform specification, waiting for dust to settle"]
639 pub fn reserve_exact(&mut self, additional: uint) {
640 if self.cap - self.len < additional {
641 match self.len.checked_add(&additional) {
642 None => panic!("Vec::reserve: `uint` overflow"),
643 Some(new_cap) => self.grow_capacity(new_cap)
648 /// Shrinks the capacity of the vector as much as possible. It will drop
649 /// down as close as possible to the length but the allocator may still
650 /// inform the vector that there is space for a few more elements.
655 /// let mut vec: Vec<int> = Vec::with_capacity(10);
656 /// vec.push_all([1, 2, 3]);
657 /// assert_eq!(vec.capacity(), 10);
658 /// vec.shrink_to_fit();
659 /// assert!(vec.capacity() >= 3);
662 #[unstable = "matches collection reform specification, waiting for dust to settle"]
663 pub fn shrink_to_fit(&mut self) {
664 if mem::size_of::<T>() == 0 { return }
669 dealloc(self.ptr, self.cap)
675 // Overflow check is unnecessary as the vector is already at
677 self.ptr = reallocate(self.ptr as *mut u8,
678 self.cap * mem::size_of::<T>(),
679 self.len * mem::size_of::<T>(),
680 mem::min_align_of::<T>()) as *mut T;
681 if self.ptr.is_null() { ::alloc::oom() }
687 /// Convert the vector into Box<[T]>.
689 /// Note that this will drop any excess capacity. Calling this and converting back to a vector
690 /// with `into_vec()` is equivalent to calling `shrink_to_fit()`.
692 pub fn into_boxed_slice(mut self) -> Box<[T]> {
693 self.shrink_to_fit();
695 let xs: Box<[T]> = mem::transmute(self.as_mut_slice());
701 /// Shorten a vector, dropping excess elements.
703 /// If `len` is greater than the vector's current length, this has no
709 /// let mut vec = vec![1i, 2, 3, 4];
711 /// assert_eq!(vec, vec![1, 2]);
713 #[unstable = "matches collection reform specification; waiting on panic semantics"]
714 pub fn truncate(&mut self, len: uint) {
716 // drop any extra elements
717 while len < self.len {
718 // decrement len before the read(), so a panic on Drop doesn't
719 // re-drop the just-failed value.
721 ptr::read(self.as_slice().unsafe_get(self.len));
726 /// Returns a mutable slice of the elements of `self`.
731 /// fn foo(slice: &mut [int]) {}
733 /// let mut vec = vec![1i, 2];
734 /// foo(vec.as_mut_slice());
738 pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
740 mem::transmute(RawSlice {
741 data: self.ptr as *const T,
747 /// Creates a consuming iterator, that is, one that moves each
748 /// value out of the vector (from start to end). The vector cannot
749 /// be used after calling this.
754 /// let v = vec!["a".to_string(), "b".to_string()];
755 /// for s in v.into_iter() {
756 /// // s has type String, not &String
757 /// println!("{}", s);
761 #[unstable = "matches collection reform specification, waiting for dust to settle"]
762 pub fn into_iter(self) -> MoveItems<T> {
766 let begin = self.ptr as *const T;
767 let end = if mem::size_of::<T>() == 0 {
768 (ptr as uint + self.len()) as *const T
770 ptr.offset(self.len() as int) as *const T
773 MoveItems { allocation: ptr, cap: cap, ptr: begin, end: end }
777 /// Sets the length of a vector.
779 /// This will explicitly set the size of the vector, without actually
780 /// modifying its buffers, so it is up to the caller to ensure that the
781 /// vector is actually the specified size.
786 /// let mut v = vec![1u, 2, 3, 4];
793 pub unsafe fn set_len(&mut self, len: uint) {
797 /// Removes an element from anywhere in the vector and return it, replacing
798 /// it with the last element. This does not preserve ordering, but is O(1).
800 /// Returns `None` if `index` is out of bounds.
804 /// let mut v = vec!["foo", "bar", "baz", "qux"];
806 /// assert_eq!(v.swap_remove(1), Some("bar"));
807 /// assert_eq!(v, vec!["foo", "qux", "baz"]);
809 /// assert_eq!(v.swap_remove(0), Some("foo"));
810 /// assert_eq!(v, vec!["baz", "qux"]);
812 /// assert_eq!(v.swap_remove(2), None);
815 #[unstable = "the naming of this function may be altered"]
816 pub fn swap_remove(&mut self, index: uint) -> Option<T> {
817 let length = self.len();
818 if length > 0 && index < length - 1 {
819 self.as_mut_slice().swap(index, length - 1);
820 } else if index >= length {
826 /// Inserts an element at position `index` within the vector, shifting all
827 /// elements after position `i` one position to the right.
831 /// Panics if `index` is not between `0` and the vector's length (both
832 /// bounds inclusive).
837 /// let mut vec = vec![1i, 2, 3];
838 /// vec.insert(1, 4);
839 /// assert_eq!(vec, vec![1, 4, 2, 3]);
840 /// vec.insert(4, 5);
841 /// assert_eq!(vec, vec![1, 4, 2, 3, 5]);
843 #[unstable = "panic semantics need settling"]
844 pub fn insert(&mut self, index: uint, element: T) {
845 let len = self.len();
846 assert!(index <= len);
847 // space for the new element
850 unsafe { // infallible
851 // The spot to put the new value
853 let p = self.as_mut_ptr().offset(index as int);
854 // Shift everything over to make space. (Duplicating the
855 // `index`th element into two consecutive places.)
856 ptr::copy_memory(p.offset(1), &*p, len - index);
857 // Write it in, overwriting the first copy of the `index`th
859 ptr::write(&mut *p, element);
861 self.set_len(len + 1);
865 /// Removes and returns the element at position `index` within the vector,
866 /// shifting all elements after position `index` one position to the left.
867 /// Returns `None` if `i` is out of bounds.
872 /// let mut v = vec![1i, 2, 3];
873 /// assert_eq!(v.remove(1), Some(2));
874 /// assert_eq!(v, vec![1, 3]);
876 /// assert_eq!(v.remove(4), None);
877 /// // v is unchanged:
878 /// assert_eq!(v, vec![1, 3]);
880 #[unstable = "panic semantics need settling"]
881 pub fn remove(&mut self, index: uint) -> Option<T> {
882 let len = self.len();
884 unsafe { // infallible
887 // the place we are taking from.
888 let ptr = self.as_mut_ptr().offset(index as int);
889 // copy it out, unsafely having a copy of the value on
890 // the stack and in the vector at the same time.
891 ret = Some(ptr::read(ptr as *const T));
893 // Shift everything down to fill in that spot.
894 ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
896 self.set_len(len - 1);
904 /// Retains only the elements specified by the predicate.
906 /// In other words, remove all elements `e` such that `f(&e)` returns false.
907 /// This method operates in place and preserves the order of the retained elements.
912 /// let mut vec = vec![1i, 2, 3, 4];
913 /// vec.retain(|&x| x%2 == 0);
914 /// assert_eq!(vec, vec![2, 4]);
916 #[unstable = "the closure argument may become an unboxed closure"]
917 pub fn retain(&mut self, f: |&T| -> bool) {
918 let len = self.len();
921 let v = self.as_mut_slice();
923 for i in range(0u, len) {
932 self.truncate(len - del);
936 /// Expands a vector in place, initializing the new elements to the result of a function.
938 /// The vector is grown by `n` elements. The i-th new element are initialized to the value
939 /// returned by `f(i)` where `i` is in the range [0, n).
944 /// let mut vec = vec![0u, 1];
945 /// vec.grow_fn(3, |i| i);
946 /// assert_eq!(vec, vec![0, 1, 0, 1, 2]);
948 #[unstable = "this function may be renamed or change to unboxed closures"]
949 pub fn grow_fn(&mut self, n: uint, f: |uint| -> T) {
951 for i in range(0u, n) {
956 /// Appends an element to the back of a collection.
960 /// Panics if the number of elements in the vector overflows a `uint`.
965 /// let mut vec = vec!(1i, 2);
967 /// assert_eq!(vec, vec!(1, 2, 3));
971 pub fn push(&mut self, value: T) {
972 if mem::size_of::<T>() == 0 {
973 // zero-size types consume no memory, so we can't rely on the address space running out
974 self.len = self.len.checked_add(&1).expect("length overflow");
975 unsafe { mem::forget(value); }
978 if self.len == self.cap {
979 let old_size = self.cap * mem::size_of::<T>();
980 let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
981 if old_size > size { panic!("capacity overflow") }
983 self.ptr = alloc_or_realloc(self.ptr, old_size, size);
984 if self.ptr.is_null() { ::alloc::oom() }
986 self.cap = max(self.cap, 2) * 2;
990 let end = (self.ptr as *const T).offset(self.len as int) as *mut T;
991 ptr::write(&mut *end, value);
996 /// Removes the last element from a vector and returns it, or `None` if
1002 /// let mut vec = vec![1i, 2, 3];
1003 /// assert_eq!(vec.pop(), Some(3));
1004 /// assert_eq!(vec, vec![1, 2]);
1008 pub fn pop(&mut self) -> Option<T> {
1014 Some(ptr::read(self.as_slice().unsafe_get(self.len())))
1019 /// Clears the vector, removing all values.
1024 /// let mut v = vec![1i, 2, 3];
1026 /// assert!(v.is_empty());
1030 pub fn clear(&mut self) {
1034 /// Return the number of elements in the vector
1039 /// let a = vec![1i, 2, 3];
1040 /// assert_eq!(a.len(), 3);
1044 pub fn len(&self) -> uint { self.len }
1046 /// Returns true if the vector contains no elements
1051 /// let mut v = Vec::new();
1052 /// assert!(v.is_empty());
1054 /// assert!(!v.is_empty());
1056 #[unstable = "matches collection reform specification, waiting for dust to settle"]
1057 pub fn is_empty(&self) -> bool { self.len() == 0 }
1059 /// Reserves capacity for exactly `capacity` elements in the given vector.
1061 /// If the capacity for `self` is already equal to or greater than the
1062 /// requested capacity, then no action is taken.
1063 fn grow_capacity(&mut self, capacity: uint) {
1064 if mem::size_of::<T>() == 0 { return }
1066 if capacity > self.cap {
1067 let size = capacity.checked_mul(&mem::size_of::<T>())
1068 .expect("capacity overflow");
1070 self.ptr = alloc_or_realloc(self.ptr, self.cap * mem::size_of::<T>(), size);
1071 if self.ptr.is_null() { ::alloc::oom() }
1073 self.cap = capacity;
1078 impl<T: PartialEq> Vec<T> {
1079 /// Removes consecutive repeated elements in the vector.
1081 /// If the vector is sorted, this removes all duplicates.
1086 /// let mut vec = vec![1i, 2, 2, 3, 2];
1088 /// assert_eq!(vec, vec![1i, 2, 3, 2]);
1090 #[unstable = "this function may be renamed"]
1091 pub fn dedup(&mut self) {
1093 // Although we have a mutable reference to `self`, we cannot make
1094 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1095 // must ensure that the vector is in a valid state at all time.
1097 // The way that we handle this is by using swaps; we iterate
1098 // over all the elements, swapping as we go so that at the end
1099 // the elements we wish to keep are in the front, and those we
1100 // wish to reject are at the back. We can then truncate the
1101 // vector. This operation is still O(n).
1103 // Example: We start in this state, where `r` represents "next
1104 // read" and `w` represents "next_write`.
1107 // +---+---+---+---+---+---+
1108 // | 0 | 1 | 1 | 2 | 3 | 3 |
1109 // +---+---+---+---+---+---+
1112 // Comparing self[r] against self[w-1], this is not a duplicate, so
1113 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1114 // r and w, leaving us with:
1117 // +---+---+---+---+---+---+
1118 // | 0 | 1 | 1 | 2 | 3 | 3 |
1119 // +---+---+---+---+---+---+
1122 // Comparing self[r] against self[w-1], this value is a duplicate,
1123 // so we increment `r` but leave everything else unchanged:
1126 // +---+---+---+---+---+---+
1127 // | 0 | 1 | 1 | 2 | 3 | 3 |
1128 // +---+---+---+---+---+---+
1131 // Comparing self[r] against self[w-1], this is not a duplicate,
1132 // so swap self[r] and self[w] and advance r and w:
1135 // +---+---+---+---+---+---+
1136 // | 0 | 1 | 2 | 1 | 3 | 3 |
1137 // +---+---+---+---+---+---+
1140 // Not a duplicate, repeat:
1143 // +---+---+---+---+---+---+
1144 // | 0 | 1 | 2 | 3 | 1 | 3 |
1145 // +---+---+---+---+---+---+
1148 // Duplicate, advance r. End of vec. Truncate to w.
1150 let ln = self.len();
1151 if ln < 1 { return; }
1153 // Avoid bounds checks by using unsafe pointers.
1154 let p = self.as_mut_slice().as_mut_ptr();
1159 let p_r = p.offset(r as int);
1160 let p_wm1 = p.offset((w - 1) as int);
1163 let p_w = p_wm1.offset(1);
1164 mem::swap(&mut *p_r, &mut *p_w);
1176 impl<T> AsSlice<T> for Vec<T> {
1177 /// Returns a slice into `self`.
1182 /// fn foo(slice: &[int]) {}
1184 /// let vec = vec![1i, 2];
1185 /// foo(vec.as_slice());
1189 fn as_slice<'a>(&'a self) -> &'a [T] {
1191 mem::transmute(RawSlice {
1192 data: self.ptr as *const T,
1199 impl<T: Clone, V: AsSlice<T>> Add<V, Vec<T>> for Vec<T> {
1201 fn add(&self, rhs: &V) -> Vec<T> {
1202 let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len());
1203 res.push_all(self.as_slice());
1204 res.push_all(rhs.as_slice());
1209 #[unsafe_destructor]
1210 impl<T> Drop for Vec<T> {
1211 fn drop(&mut self) {
1212 // This is (and should always remain) a no-op if the fields are
1213 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1216 for x in self.as_mut_slice().iter() {
1219 dealloc(self.ptr, self.cap)
1226 impl<T> Default for Vec<T> {
1227 fn default() -> Vec<T> {
1232 #[experimental = "waiting on Show stability"]
1233 impl<T:fmt::Show> fmt::Show for Vec<T> {
1234 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1235 self.as_slice().fmt(f)
1239 /// An iterator that moves out of a vector.
1240 pub struct MoveItems<T> {
1241 allocation: *mut T, // the block of memory allocated for the vector
1242 cap: uint, // the capacity of the vector
1247 impl<T> MoveItems<T> {
1249 /// Drops all items that have not yet been moved and returns the empty vector.
1250 pub fn unwrap(mut self) -> Vec<T> {
1253 let MoveItems { allocation, cap, ptr: _ptr, end: _end } = self;
1255 Vec { ptr: allocation, cap: cap, len: 0 }
1260 impl<T> Iterator<T> for MoveItems<T> {
1262 fn next<'a>(&'a mut self) -> Option<T> {
1264 if self.ptr == self.end {
1267 if mem::size_of::<T>() == 0 {
1268 // purposefully don't use 'ptr.offset' because for
1269 // vectors with 0-size elements this would return the
1271 self.ptr = mem::transmute(self.ptr as uint + 1);
1273 // Use a non-null pointer value
1274 Some(ptr::read(mem::transmute(1u)))
1277 self.ptr = self.ptr.offset(1);
1279 Some(ptr::read(old))
1286 fn size_hint(&self) -> (uint, Option<uint>) {
1287 let diff = (self.end as uint) - (self.ptr as uint);
1288 let size = mem::size_of::<T>();
1289 let exact = diff / (if size == 0 {1} else {size});
1290 (exact, Some(exact))
1294 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
1296 fn next_back<'a>(&'a mut self) -> Option<T> {
1298 if self.end == self.ptr {
1301 if mem::size_of::<T>() == 0 {
1302 // See above for why 'ptr.offset' isn't used
1303 self.end = mem::transmute(self.end as uint - 1);
1305 // Use a non-null pointer value
1306 Some(ptr::read(mem::transmute(1u)))
1308 self.end = self.end.offset(-1);
1310 Some(ptr::read(mem::transmute(self.end)))
1317 impl<T> ExactSize<T> for MoveItems<T> {}
1319 #[unsafe_destructor]
1320 impl<T> Drop for MoveItems<T> {
1321 fn drop(&mut self) {
1322 // destroy the remaining elements
1326 dealloc(self.allocation, self.cap);
1332 /// Converts an iterator of pairs into a pair of vectors.
1334 /// Returns a tuple containing two vectors where the i-th element of the first
1335 /// vector contains the first element of the i-th tuple of the input iterator,
1336 /// and the i-th element of the second vector contains the second element
1337 /// of the i-th tuple of the input iterator.
1338 #[unstable = "this functionality may become more generic over time"]
1339 pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (Vec<T>, Vec<U>) {
1340 let (lo, _) = iter.size_hint();
1341 let mut ts = Vec::with_capacity(lo);
1342 let mut us = Vec::with_capacity(lo);
1343 for (t, u) in iter {
1350 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1352 pub struct DerefVec<'a, T> {
1354 l: ContravariantLifetime<'a>
1357 impl<'a, T> Deref<Vec<T>> for DerefVec<'a, T> {
1358 fn deref<'b>(&'b self) -> &'b Vec<T> {
1363 // Prevent the inner `Vec<T>` from attempting to deallocate memory.
1364 #[unsafe_destructor]
1365 impl<'a, T> Drop for DerefVec<'a, T> {
1366 fn drop(&mut self) {
1372 /// Convert a slice to a wrapper type providing a `&Vec<T>` reference.
1374 pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
1377 x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1378 l: ContravariantLifetime::<'a>
1383 /// Unsafe vector operations.
1388 use core::slice::SlicePrelude;
1390 /// Constructs a vector from an unsafe pointer to a buffer.
1392 /// The elements of the buffer are copied into the vector without cloning,
1393 /// as if `ptr::read()` were called on them.
1396 pub unsafe fn from_buf<T>(ptr: *const T, elts: uint) -> Vec<T> {
1397 let mut dst = Vec::with_capacity(elts);
1399 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
1404 /// An owned, partially type-converted vector of elements with non-zero size.
1406 /// `T` and `U` must have the same, non-zero size. They must also have the same
1409 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
1410 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
1411 /// destructed. Additionally the underlying storage of `vec` will be freed.
1412 struct PartialVecNonZeroSized<T,U> {
1421 /// An owned, partially type-converted vector of zero-sized elements.
1423 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1425 struct PartialVecZeroSized<T,U> {
1428 marker_t: InvariantType<T>,
1429 marker_u: InvariantType<U>,
1432 #[unsafe_destructor]
1433 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1434 fn drop(&mut self) {
1436 // `vec` hasn't been modified until now. As it has a length
1437 // currently, this would run destructors of `T`s which might not be
1438 // there. So at first, set `vec`s length to `0`. This must be done
1439 // at first to remain memory-safe as the destructors of `U` or `T`
1440 // might cause unwinding where `vec`s destructor would be executed.
1441 self.vec.set_len(0);
1443 // We have instances of `U`s and `T`s in `vec`. Destruct them.
1444 while self.start_u != self.end_u {
1445 let _ = ptr::read(self.start_u as *const U); // Run a `U` destructor.
1446 self.start_u = self.start_u.offset(1);
1448 while self.start_t != self.end_t {
1449 let _ = ptr::read(self.start_t as *const T); // Run a `T` destructor.
1450 self.start_t = self.start_t.offset(1);
1452 // After this destructor ran, the destructor of `vec` will run,
1453 // deallocating the underlying memory.
1458 #[unsafe_destructor]
1459 impl<T,U> Drop for PartialVecZeroSized<T,U> {
1460 fn drop(&mut self) {
1462 // Destruct the instances of `T` and `U` this struct owns.
1463 while self.num_t != 0 {
1464 let _: T = mem::uninitialized(); // Run a `T` destructor.
1467 while self.num_u != 0 {
1468 let _: U = mem::uninitialized(); // Run a `U` destructor.
1476 /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same
1477 /// size and in case they are not zero-sized the same minimal alignment.
1481 /// Panics if `T` and `U` have differing sizes or are not zero-sized and
1482 /// have differing minimal alignments.
1487 /// let v = vec![0u, 1, 2];
1488 /// let w = v.map_in_place(|i| i + 3);
1489 /// assert_eq!(w.as_slice(), [3, 4, 5].as_slice());
1491 /// #[deriving(PartialEq, Show)]
1492 /// struct Newtype(u8);
1493 /// let bytes = vec![0x11, 0x22];
1494 /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x));
1495 /// assert_eq!(newtyped_bytes.as_slice(), [Newtype(0x11), Newtype(0x22)].as_slice());
1497 pub fn map_in_place<U>(self, f: |T| -> U) -> Vec<U> {
1498 // FIXME: Assert statically that the types `T` and `U` have the same
1500 assert!(mem::size_of::<T>() == mem::size_of::<U>());
1504 if mem::size_of::<T>() != 0 {
1505 // FIXME: Assert statically that the types `T` and `U` have the
1506 // same minimal alignment in case they are not zero-sized.
1508 // These asserts are necessary because the `min_align_of` of the
1509 // types are passed to the allocator by `Vec`.
1510 assert!(mem::min_align_of::<T>() == mem::min_align_of::<U>());
1512 // This `as int` cast is safe, because the size of the elements of the
1513 // vector is not 0, and:
1515 // 1) If the size of the elements in the vector is 1, the `int` may
1516 // overflow, but it has the correct bit pattern so that the
1517 // `.offset()` function will work.
1520 // Address space 0x0-0xF.
1521 // `u8` array at: 0x1.
1522 // Size of `u8` array: 0x8.
1523 // Calculated `offset`: -0x8.
1524 // After `array.offset(offset)`: 0x9.
1525 // (0x1 + 0x8 = 0x1 - 0x8)
1527 // 2) If the size of the elements in the vector is >1, the `uint` ->
1528 // `int` conversion can't overflow.
1529 let offset = vec.len() as int;
1530 let start = vec.as_mut_ptr();
1532 let mut pv = PartialVecNonZeroSized {
1536 // This points inside the vector, as the vector has length
1538 end_t: unsafe { start.offset(offset) },
1539 start_u: start as *mut U,
1540 end_u: start as *mut U,
1551 while pv.end_u as *mut T != pv.end_t {
1555 // +-+-+-+-+-+-+-+-+-+
1556 // |U|...|U|T|T|...|T|
1557 // +-+-+-+-+-+-+-+-+-+
1561 let t = ptr::read(pv.start_t as *const T);
1564 // +-+-+-+-+-+-+-+-+-+
1565 // |U|...|U|X|T|...|T|
1566 // +-+-+-+-+-+-+-+-+-+
1569 // We must not panic here, one cell is marked as `T`
1570 // although it is not `T`.
1572 pv.start_t = pv.start_t.offset(1);
1575 // +-+-+-+-+-+-+-+-+-+
1576 // |U|...|U|X|T|...|T|
1577 // +-+-+-+-+-+-+-+-+-+
1580 // We may panic again.
1582 // The function given by the user might panic.
1585 ptr::write(pv.end_u, u);
1588 // +-+-+-+-+-+-+-+-+-+
1589 // |U|...|U|U|T|...|T|
1590 // +-+-+-+-+-+-+-+-+-+
1593 // We should not panic here, because that would leak the `U`
1594 // pointed to by `end_u`.
1596 pv.end_u = pv.end_u.offset(1);
1599 // +-+-+-+-+-+-+-+-+-+
1600 // |U|...|U|U|T|...|T|
1601 // +-+-+-+-+-+-+-+-+-+
1604 // We may panic again.
1616 // Extract `vec` and prevent the destructor of
1617 // `PartialVecNonZeroSized` from running. Note that none of the
1618 // function calls can panic, thus no resources can be leaked (as the
1619 // `vec` member of `PartialVec` is the only one which holds
1620 // allocations -- and it is returned from this function. None of
1623 let vec_len = pv.vec.len();
1624 let vec_cap = pv.vec.capacity();
1625 let vec_ptr = pv.vec.as_mut_ptr() as *mut U;
1627 Vec::from_raw_parts(vec_ptr, vec_len, vec_cap)
1630 // Put the `Vec` into the `PartialVecZeroSized` structure and
1631 // prevent the destructor of the `Vec` from running. Since the
1632 // `Vec` contained zero-sized objects, it did not allocate, so we
1633 // are not leaking memory here.
1634 let mut pv = PartialVecZeroSized::<T,U> {
1637 marker_t: InvariantType,
1638 marker_u: InvariantType,
1640 unsafe { mem::forget(vec); }
1642 while pv.num_t != 0 {
1644 // Create a `T` out of thin air and decrement `num_t`. This
1645 // must not panic between these steps, as otherwise a
1646 // destructor of `T` which doesn't exist runs.
1647 let t = mem::uninitialized();
1650 // The function given by the user might panic.
1653 // Forget the `U` and increment `num_u`. This increment
1654 // cannot overflow the `uint` as we only do this for a
1655 // number of times that fits into a `uint` (and start with
1656 // `0`). Again, we should not panic between these steps.
1661 // Create a `Vec` from our `PartialVecZeroSized` and make sure the
1662 // destructor of the latter will not run. None of this can panic.
1663 let mut result = Vec::new();
1664 unsafe { result.set_len(pv.num_u); }
1674 use std::prelude::*;
1675 use std::mem::size_of;
1677 use super::{as_vec, unzip, raw, Vec};
1679 struct DropCounter<'a> {
1683 #[unsafe_destructor]
1684 impl<'a> Drop for DropCounter<'a> {
1685 fn drop(&mut self) {
1692 let xs = [1u8, 2u8, 3u8];
1693 assert_eq!(as_vec(xs).as_slice(), xs.as_slice());
1697 fn test_as_vec_dtor() {
1698 let (mut count_x, mut count_y) = (0, 0);
1700 let xs = &[DropCounter { count: &mut count_x }, DropCounter { count: &mut count_y }];
1701 assert_eq!(as_vec(xs).len(), 2);
1703 assert_eq!(count_x, 1);
1704 assert_eq!(count_y, 1);
1708 fn test_small_vec_struct() {
1709 assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1713 fn test_double_drop() {
1719 let (mut count_x, mut count_y) = (0, 0);
1721 let mut tv = TwoVec {
1725 tv.x.push(DropCounter {count: &mut count_x});
1726 tv.y.push(DropCounter {count: &mut count_y});
1728 // If Vec had a drop flag, here is where it would be zeroed.
1729 // Instead, it should rely on its internal state to prevent
1730 // doing anything significant when dropped multiple times.
1733 // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1736 assert_eq!(count_x, 1);
1737 assert_eq!(count_y, 1);
1742 let mut v = Vec::new();
1743 assert_eq!(v.capacity(), 0);
1746 assert!(v.capacity() >= 2);
1748 for i in range(0i, 16) {
1752 assert!(v.capacity() >= 16);
1754 assert!(v.capacity() >= 32);
1759 assert!(v.capacity() >= 33)
1764 let mut v = Vec::new();
1765 let mut w = Vec::new();
1767 v.extend(range(0i, 3));
1768 for i in range(0i, 3) { w.push(i) }
1772 v.extend(range(3i, 10));
1773 for i in range(3i, 10) { w.push(i) }
1779 fn test_slice_from_mut() {
1780 let mut values = vec![1u8,2,3,4,5];
1782 let slice = values.slice_from_mut(2);
1783 assert!(slice == [3, 4, 5]);
1784 for p in slice.iter_mut() {
1789 assert!(values.as_slice() == [1, 2, 5, 6, 7]);
1793 fn test_slice_to_mut() {
1794 let mut values = vec![1u8,2,3,4,5];
1796 let slice = values.slice_to_mut(2);
1797 assert!(slice == [1, 2]);
1798 for p in slice.iter_mut() {
1803 assert!(values.as_slice() == [2, 3, 3, 4, 5]);
1807 fn test_split_at_mut() {
1808 let mut values = vec![1u8,2,3,4,5];
1810 let (left, right) = values.split_at_mut(2);
1812 let left: &[_] = left;
1813 assert!(left[0..left.len()] == [1, 2][]);
1815 for p in left.iter_mut() {
1820 let right: &[_] = right;
1821 assert!(right[0..right.len()] == [3, 4, 5][]);
1823 for p in right.iter_mut() {
1828 assert!(values == vec![2u8, 3, 5, 6, 7]);
1833 let v: Vec<int> = vec!();
1834 let w = vec!(1i, 2, 3);
1836 assert_eq!(v, v.clone());
1840 // they should be disjoint in memory.
1841 assert!(w.as_ptr() != z.as_ptr())
1845 fn test_clone_from() {
1847 let three = vec!(box 1i, box 2, box 3);
1848 let two = vec!(box 4i, box 5);
1850 v.clone_from(&three);
1851 assert_eq!(v, three);
1854 v.clone_from(&three);
1855 assert_eq!(v, three);
1862 v.clone_from(&three);
1863 assert_eq!(v, three)
1868 let mut v = vec![0u, 1];
1869 v.grow_fn(3, |i| i);
1870 assert!(v == vec![0u, 1, 0, 1, 2]);
1875 let mut vec = vec![1u, 2, 3, 4];
1876 vec.retain(|&x| x % 2 == 0);
1877 assert!(vec == vec![2u, 4]);
1881 fn zero_sized_values() {
1882 let mut v = Vec::new();
1883 assert_eq!(v.len(), 0);
1885 assert_eq!(v.len(), 1);
1887 assert_eq!(v.len(), 2);
1888 assert_eq!(v.pop(), Some(()));
1889 assert_eq!(v.pop(), Some(()));
1890 assert_eq!(v.pop(), None);
1892 assert_eq!(v.iter().count(), 0);
1894 assert_eq!(v.iter().count(), 1);
1896 assert_eq!(v.iter().count(), 2);
1898 for &() in v.iter() {}
1900 assert_eq!(v.iter_mut().count(), 2);
1902 assert_eq!(v.iter_mut().count(), 3);
1904 assert_eq!(v.iter_mut().count(), 4);
1906 for &() in v.iter_mut() {}
1907 unsafe { v.set_len(0); }
1908 assert_eq!(v.iter_mut().count(), 0);
1912 fn test_partition() {
1913 assert_eq!(vec![].partition(|x: &int| *x < 3), (vec![], vec![]));
1914 assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1915 assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1916 assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1920 fn test_partitioned() {
1921 assert_eq!(vec![].partitioned(|x: &int| *x < 3), (vec![], vec![]))
1922 assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1923 assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1924 assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1928 fn test_zip_unzip() {
1929 let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
1931 let (left, right) = unzip(z1.iter().map(|&x| x));
1933 let (left, right) = (left.as_slice(), right.as_slice());
1934 assert_eq!((1, 4), (left[0], right[0]));
1935 assert_eq!((2, 5), (left[1], right[1]));
1936 assert_eq!((3, 6), (left[2], right[2]));
1940 fn test_unsafe_ptrs() {
1942 // Test on-stack copy-from-buf.
1944 let ptr = a.as_ptr();
1945 let b = raw::from_buf(ptr, 3u);
1946 assert_eq!(b, vec![1, 2, 3]);
1948 // Test on-heap copy-from-buf.
1949 let c = vec![1i, 2, 3, 4, 5];
1950 let ptr = c.as_ptr();
1951 let d = raw::from_buf(ptr, 5u);
1952 assert_eq!(d, vec![1, 2, 3, 4, 5]);
1957 fn test_vec_truncate_drop() {
1958 static mut drops: uint = 0;
1960 impl Drop for Elem {
1961 fn drop(&mut self) {
1962 unsafe { drops += 1; }
1966 let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
1967 assert_eq!(unsafe { drops }, 0);
1969 assert_eq!(unsafe { drops }, 2);
1971 assert_eq!(unsafe { drops }, 5);
1976 fn test_vec_truncate_fail() {
1977 struct BadElem(int);
1978 impl Drop for BadElem {
1979 fn drop(&mut self) {
1980 let BadElem(ref mut x) = *self;
1981 if *x == 0xbadbeef {
1982 panic!("BadElem panic: 0xbadbeef")
1987 let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
1993 let vec = vec!(1i, 2, 3);
1994 assert!(vec[1] == 2);
1999 fn test_index_out_of_bounds() {
2000 let vec = vec!(1i, 2, 3);
2006 fn test_slice_out_of_bounds_1() {
2007 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2013 fn test_slice_out_of_bounds_2() {
2014 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2020 fn test_slice_out_of_bounds_3() {
2021 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2027 fn test_slice_out_of_bounds_4() {
2028 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2034 fn test_slice_out_of_bounds_5() {
2035 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2040 fn test_swap_remove_empty() {
2041 let mut vec: Vec<uint> = vec!();
2042 assert_eq!(vec.swap_remove(0), None);
2046 fn test_move_iter_unwrap() {
2047 let mut vec: Vec<uint> = Vec::with_capacity(7);
2050 let ptr = vec.as_ptr();
2051 vec = vec.into_iter().unwrap();
2052 assert_eq!(vec.as_ptr(), ptr);
2053 assert_eq!(vec.capacity(), 7);
2054 assert_eq!(vec.len(), 0);
2059 fn test_map_in_place_incompatible_types_fail() {
2060 let v = vec![0u, 1, 2];
2061 v.map_in_place(|_| ());
2065 fn test_map_in_place() {
2066 let v = vec![0u, 1, 2];
2067 assert_eq!(v.map_in_place(|i: uint| i as int - 1).as_slice(), [-1i, 0, 1].as_slice());
2071 fn test_map_in_place_zero_sized() {
2072 let v = vec![(), ()];
2073 #[deriving(PartialEq, Show)]
2075 assert_eq!(v.map_in_place(|_| ZeroSized).as_slice(), [ZeroSized, ZeroSized].as_slice());
2079 fn test_move_items() {
2080 let vec = vec![1, 2, 3];
2081 let mut vec2 : Vec<i32> = vec![];
2082 for i in vec.into_iter() {
2085 assert!(vec2 == vec![1, 2, 3]);
2089 fn test_move_items_reverse() {
2090 let vec = vec![1, 2, 3];
2091 let mut vec2 : Vec<i32> = vec![];
2092 for i in vec.into_iter().rev() {
2095 assert!(vec2 == vec![3, 2, 1]);
2099 fn test_move_items_zero_sized() {
2100 let vec = vec![(), (), ()];
2101 let mut vec2 : Vec<()> = vec![];
2102 for i in vec.into_iter() {
2105 assert!(vec2 == vec![(), (), ()]);
2109 fn test_into_boxed_slice() {
2110 let xs = vec![1u, 2, 3];
2111 let ys = xs.into_boxed_slice();
2112 assert_eq!(ys.as_slice(), [1u, 2, 3].as_slice());
2116 fn bench_new(b: &mut Bencher) {
2118 let v: Vec<uint> = Vec::new();
2119 assert_eq!(v.len(), 0);
2120 assert_eq!(v.capacity(), 0);
2124 fn do_bench_with_capacity(b: &mut Bencher, src_len: uint) {
2125 b.bytes = src_len as u64;
2128 let v: Vec<uint> = Vec::with_capacity(src_len);
2129 assert_eq!(v.len(), 0);
2130 assert_eq!(v.capacity(), src_len);
2135 fn bench_with_capacity_0000(b: &mut Bencher) {
2136 do_bench_with_capacity(b, 0)
2140 fn bench_with_capacity_0010(b: &mut Bencher) {
2141 do_bench_with_capacity(b, 10)
2145 fn bench_with_capacity_0100(b: &mut Bencher) {
2146 do_bench_with_capacity(b, 100)
2150 fn bench_with_capacity_1000(b: &mut Bencher) {
2151 do_bench_with_capacity(b, 1000)
2154 fn do_bench_from_fn(b: &mut Bencher, src_len: uint) {
2155 b.bytes = src_len as u64;
2158 let dst = Vec::from_fn(src_len, |i| i);
2159 assert_eq!(dst.len(), src_len);
2160 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2165 fn bench_from_fn_0000(b: &mut Bencher) {
2166 do_bench_from_fn(b, 0)
2170 fn bench_from_fn_0010(b: &mut Bencher) {
2171 do_bench_from_fn(b, 10)
2175 fn bench_from_fn_0100(b: &mut Bencher) {
2176 do_bench_from_fn(b, 100)
2180 fn bench_from_fn_1000(b: &mut Bencher) {
2181 do_bench_from_fn(b, 1000)
2184 fn do_bench_from_elem(b: &mut Bencher, src_len: uint) {
2185 b.bytes = src_len as u64;
2188 let dst: Vec<uint> = Vec::from_elem(src_len, 5);
2189 assert_eq!(dst.len(), src_len);
2190 assert!(dst.iter().all(|x| *x == 5));
2195 fn bench_from_elem_0000(b: &mut Bencher) {
2196 do_bench_from_elem(b, 0)
2200 fn bench_from_elem_0010(b: &mut Bencher) {
2201 do_bench_from_elem(b, 10)
2205 fn bench_from_elem_0100(b: &mut Bencher) {
2206 do_bench_from_elem(b, 100)
2210 fn bench_from_elem_1000(b: &mut Bencher) {
2211 do_bench_from_elem(b, 1000)
2214 fn do_bench_from_slice(b: &mut Bencher, src_len: uint) {
2215 let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2217 b.bytes = src_len as u64;
2220 let dst = src.clone().as_slice().to_vec();
2221 assert_eq!(dst.len(), src_len);
2222 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2227 fn bench_from_slice_0000(b: &mut Bencher) {
2228 do_bench_from_slice(b, 0)
2232 fn bench_from_slice_0010(b: &mut Bencher) {
2233 do_bench_from_slice(b, 10)
2237 fn bench_from_slice_0100(b: &mut Bencher) {
2238 do_bench_from_slice(b, 100)
2242 fn bench_from_slice_1000(b: &mut Bencher) {
2243 do_bench_from_slice(b, 1000)
2246 fn do_bench_from_iter(b: &mut Bencher, src_len: uint) {
2247 let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2249 b.bytes = src_len as u64;
2252 let dst: Vec<uint> = FromIterator::from_iter(src.clone().into_iter());
2253 assert_eq!(dst.len(), src_len);
2254 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2259 fn bench_from_iter_0000(b: &mut Bencher) {
2260 do_bench_from_iter(b, 0)
2264 fn bench_from_iter_0010(b: &mut Bencher) {
2265 do_bench_from_iter(b, 10)
2269 fn bench_from_iter_0100(b: &mut Bencher) {
2270 do_bench_from_iter(b, 100)
2274 fn bench_from_iter_1000(b: &mut Bencher) {
2275 do_bench_from_iter(b, 1000)
2278 fn do_bench_extend(b: &mut Bencher, dst_len: uint, src_len: uint) {
2279 let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2280 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2282 b.bytes = src_len as u64;
2285 let mut dst = dst.clone();
2286 dst.extend(src.clone().into_iter());
2287 assert_eq!(dst.len(), dst_len + src_len);
2288 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2293 fn bench_extend_0000_0000(b: &mut Bencher) {
2294 do_bench_extend(b, 0, 0)
2298 fn bench_extend_0000_0010(b: &mut Bencher) {
2299 do_bench_extend(b, 0, 10)
2303 fn bench_extend_0000_0100(b: &mut Bencher) {
2304 do_bench_extend(b, 0, 100)
2308 fn bench_extend_0000_1000(b: &mut Bencher) {
2309 do_bench_extend(b, 0, 1000)
2313 fn bench_extend_0010_0010(b: &mut Bencher) {
2314 do_bench_extend(b, 10, 10)
2318 fn bench_extend_0100_0100(b: &mut Bencher) {
2319 do_bench_extend(b, 100, 100)
2323 fn bench_extend_1000_1000(b: &mut Bencher) {
2324 do_bench_extend(b, 1000, 1000)
2327 fn do_bench_push_all(b: &mut Bencher, dst_len: uint, src_len: uint) {
2328 let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2329 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2331 b.bytes = src_len as u64;
2334 let mut dst = dst.clone();
2335 dst.push_all(src.as_slice());
2336 assert_eq!(dst.len(), dst_len + src_len);
2337 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2342 fn bench_push_all_0000_0000(b: &mut Bencher) {
2343 do_bench_push_all(b, 0, 0)
2347 fn bench_push_all_0000_0010(b: &mut Bencher) {
2348 do_bench_push_all(b, 0, 10)
2352 fn bench_push_all_0000_0100(b: &mut Bencher) {
2353 do_bench_push_all(b, 0, 100)
2357 fn bench_push_all_0000_1000(b: &mut Bencher) {
2358 do_bench_push_all(b, 0, 1000)
2362 fn bench_push_all_0010_0010(b: &mut Bencher) {
2363 do_bench_push_all(b, 10, 10)
2367 fn bench_push_all_0100_0100(b: &mut Bencher) {
2368 do_bench_push_all(b, 100, 100)
2372 fn bench_push_all_1000_1000(b: &mut Bencher) {
2373 do_bench_push_all(b, 1000, 1000)
2376 fn do_bench_push_all_move(b: &mut Bencher, dst_len: uint, src_len: uint) {
2377 let dst: Vec<uint> = FromIterator::from_iter(range(0u, dst_len));
2378 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2380 b.bytes = src_len as u64;
2383 let mut dst = dst.clone();
2384 dst.extend(src.clone().into_iter());
2385 assert_eq!(dst.len(), dst_len + src_len);
2386 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2391 fn bench_push_all_move_0000_0000(b: &mut Bencher) {
2392 do_bench_push_all_move(b, 0, 0)
2396 fn bench_push_all_move_0000_0010(b: &mut Bencher) {
2397 do_bench_push_all_move(b, 0, 10)
2401 fn bench_push_all_move_0000_0100(b: &mut Bencher) {
2402 do_bench_push_all_move(b, 0, 100)
2406 fn bench_push_all_move_0000_1000(b: &mut Bencher) {
2407 do_bench_push_all_move(b, 0, 1000)
2411 fn bench_push_all_move_0010_0010(b: &mut Bencher) {
2412 do_bench_push_all_move(b, 10, 10)
2416 fn bench_push_all_move_0100_0100(b: &mut Bencher) {
2417 do_bench_push_all_move(b, 100, 100)
2421 fn bench_push_all_move_1000_1000(b: &mut Bencher) {
2422 do_bench_push_all_move(b, 1000, 1000)
2425 fn do_bench_clone(b: &mut Bencher, src_len: uint) {
2426 let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2428 b.bytes = src_len as u64;
2431 let dst = src.clone();
2432 assert_eq!(dst.len(), src_len);
2433 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2438 fn bench_clone_0000(b: &mut Bencher) {
2439 do_bench_clone(b, 0)
2443 fn bench_clone_0010(b: &mut Bencher) {
2444 do_bench_clone(b, 10)
2448 fn bench_clone_0100(b: &mut Bencher) {
2449 do_bench_clone(b, 100)
2453 fn bench_clone_1000(b: &mut Bencher) {
2454 do_bench_clone(b, 1000)
2457 fn do_bench_clone_from(b: &mut Bencher, times: uint, dst_len: uint, src_len: uint) {
2458 let dst: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2459 let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2461 b.bytes = (times * src_len) as u64;
2464 let mut dst = dst.clone();
2466 for _ in range(0, times) {
2467 dst.clone_from(&src);
2469 assert_eq!(dst.len(), src_len);
2470 assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x));
2476 fn bench_clone_from_01_0000_0000(b: &mut Bencher) {
2477 do_bench_clone_from(b, 1, 0, 0)
2481 fn bench_clone_from_01_0000_0010(b: &mut Bencher) {
2482 do_bench_clone_from(b, 1, 0, 10)
2486 fn bench_clone_from_01_0000_0100(b: &mut Bencher) {
2487 do_bench_clone_from(b, 1, 0, 100)
2491 fn bench_clone_from_01_0000_1000(b: &mut Bencher) {
2492 do_bench_clone_from(b, 1, 0, 1000)
2496 fn bench_clone_from_01_0010_0010(b: &mut Bencher) {
2497 do_bench_clone_from(b, 1, 10, 10)
2501 fn bench_clone_from_01_0100_0100(b: &mut Bencher) {
2502 do_bench_clone_from(b, 1, 100, 100)
2506 fn bench_clone_from_01_1000_1000(b: &mut Bencher) {
2507 do_bench_clone_from(b, 1, 1000, 1000)
2511 fn bench_clone_from_01_0010_0100(b: &mut Bencher) {
2512 do_bench_clone_from(b, 1, 10, 100)
2516 fn bench_clone_from_01_0100_1000(b: &mut Bencher) {
2517 do_bench_clone_from(b, 1, 100, 1000)
2521 fn bench_clone_from_01_0010_0000(b: &mut Bencher) {
2522 do_bench_clone_from(b, 1, 10, 0)
2526 fn bench_clone_from_01_0100_0010(b: &mut Bencher) {
2527 do_bench_clone_from(b, 1, 100, 10)
2531 fn bench_clone_from_01_1000_0100(b: &mut Bencher) {
2532 do_bench_clone_from(b, 1, 1000, 100)
2536 fn bench_clone_from_10_0000_0000(b: &mut Bencher) {
2537 do_bench_clone_from(b, 10, 0, 0)
2541 fn bench_clone_from_10_0000_0010(b: &mut Bencher) {
2542 do_bench_clone_from(b, 10, 0, 10)
2546 fn bench_clone_from_10_0000_0100(b: &mut Bencher) {
2547 do_bench_clone_from(b, 10, 0, 100)
2551 fn bench_clone_from_10_0000_1000(b: &mut Bencher) {
2552 do_bench_clone_from(b, 10, 0, 1000)
2556 fn bench_clone_from_10_0010_0010(b: &mut Bencher) {
2557 do_bench_clone_from(b, 10, 10, 10)
2561 fn bench_clone_from_10_0100_0100(b: &mut Bencher) {
2562 do_bench_clone_from(b, 10, 100, 100)
2566 fn bench_clone_from_10_1000_1000(b: &mut Bencher) {
2567 do_bench_clone_from(b, 10, 1000, 1000)
2571 fn bench_clone_from_10_0010_0100(b: &mut Bencher) {
2572 do_bench_clone_from(b, 10, 10, 100)
2576 fn bench_clone_from_10_0100_1000(b: &mut Bencher) {
2577 do_bench_clone_from(b, 10, 100, 1000)
2581 fn bench_clone_from_10_0010_0000(b: &mut Bencher) {
2582 do_bench_clone_from(b, 10, 10, 0)
2586 fn bench_clone_from_10_0100_0010(b: &mut Bencher) {
2587 do_bench_clone_from(b, 10, 100, 10)
2591 fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
2592 do_bench_clone_from(b, 10, 1000, 100)