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 //! An owned, growable vector.
15 use alloc::heap::{allocate, reallocate, deallocate};
18 use core::default::Default;
21 use core::num::{CheckedMul, CheckedAdd};
26 use {Collection, Mutable};
27 use slice::{MutableOrdVector, MutableVectorAllocating, CloneableVector};
28 use slice::{Items, MutItems};
30 /// An owned, growable vector.
35 /// # use std::vec::Vec;
36 /// let mut vec = Vec::new();
40 /// assert_eq!(vec.len(), 2);
41 /// assert_eq!(vec.get(0), &1);
43 /// assert_eq!(vec.pop(), Some(2));
44 /// assert_eq!(vec.len(), 1);
47 /// The `vec!` macro is provided to make initialization more convenient:
50 /// let mut vec = vec!(1, 2, 3);
52 /// assert_eq!(vec, vec!(1, 2, 3, 4));
54 #[unsafe_no_drop_flag]
62 /// Constructs a new, empty `Vec`.
64 /// The vector will not allocate until elements are pushed onto it.
69 /// # use std::vec::Vec;
70 /// let mut vec: Vec<int> = Vec::new();
73 pub fn new() -> Vec<T> {
74 Vec { len: 0, cap: 0, ptr: 0 as *mut T }
77 /// Constructs a new, empty `Vec` with the specified capacity.
79 /// The vector will be able to hold exactly `capacity` elements without
80 /// reallocating. If `capacity` is 0, the vector will not allocate.
85 /// # use std::vec::Vec;
86 /// let vec: Vec<int> = Vec::with_capacity(10);
89 pub fn with_capacity(capacity: uint) -> Vec<T> {
90 if mem::size_of::<T>() == 0 {
91 Vec { len: 0, cap: uint::MAX, ptr: 0 as *mut T }
92 } else if capacity == 0 {
95 let size = capacity.checked_mul(&mem::size_of::<T>())
96 .expect("capacity overflow");
97 let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
98 Vec { len: 0, cap: capacity, ptr: ptr as *mut T }
102 /// Creates and initializes a `Vec`.
104 /// Creates a `Vec` of size `length` and initializes the elements to the
105 /// value returned by the closure `op`.
110 /// # use std::vec::Vec;
111 /// let vec = Vec::from_fn(3, |idx| idx * 2);
112 /// assert_eq!(vec, vec!(0, 2, 4));
115 pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
117 let mut xs = Vec::with_capacity(length);
118 while xs.len < length {
120 ptr::write(xs.as_mut_slice().unsafe_mut_ref(len), op(len));
127 /// Create a `Vec<T>` directly from the raw constituents.
129 /// This is highly unsafe:
131 /// - if `ptr` is null, then `length` and `capacity` should be 0
132 /// - `ptr` must point to an allocation of size `capacity`
133 /// - there must be `length` valid instances of type `T` at the
134 /// beginning of that allocation
135 /// - `ptr` must be allocated by the default `Vec` allocator
136 pub unsafe fn from_raw_parts(length: uint, capacity: uint,
137 ptr: *mut T) -> Vec<T> {
138 Vec { len: length, cap: capacity, ptr: ptr }
141 /// Consumes the `Vec`, partitioning it based on a predicate.
143 /// Partitions the `Vec` into two `Vec`s `(A,B)`, where all elements of `A`
144 /// satisfy `f` and all elements of `B` do not. The order of elements is
150 /// let vec = vec!(1, 2, 3, 4);
151 /// let (even, odd) = vec.partition(|&n| n % 2 == 0);
152 /// assert_eq!(even, vec!(2, 4));
153 /// assert_eq!(odd, vec!(1, 3));
156 pub fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
157 let mut lefts = Vec::new();
158 let mut rights = Vec::new();
160 for elt in self.move_iter() {
172 impl<T: Clone> Vec<T> {
173 /// Iterates over the `second` vector, copying each element and appending it to
174 /// the `first`. Afterwards, the `first` is then returned for use again.
179 /// let vec = vec!(1, 2);
180 /// let vec = vec.append([3, 4]);
181 /// assert_eq!(vec, vec!(1, 2, 3, 4));
184 pub fn append(mut self, second: &[T]) -> Vec<T> {
185 self.push_all(second);
189 /// Constructs a `Vec` by cloning elements of a slice.
194 /// # use std::vec::Vec;
195 /// let slice = [1, 2, 3];
196 /// let vec = Vec::from_slice(slice);
199 pub fn from_slice(values: &[T]) -> Vec<T> {
200 values.iter().map(|x| x.clone()).collect()
203 /// Constructs a `Vec` with copies of a value.
205 /// Creates a `Vec` with `length` copies of `value`.
209 /// # use std::vec::Vec;
210 /// let vec = Vec::from_elem(3, "hi");
211 /// println!("{}", vec); // prints [hi, hi, hi]
214 pub fn from_elem(length: uint, value: T) -> Vec<T> {
216 let mut xs = Vec::with_capacity(length);
217 while xs.len < length {
219 ptr::write(xs.as_mut_slice().unsafe_mut_ref(len),
227 /// Appends all elements in a slice to the `Vec`.
229 /// Iterates over the slice `other`, clones each element, and then appends
230 /// it to this `Vec`. The `other` vector is traversed in-order.
235 /// let mut vec = vec!(1);
236 /// vec.push_all([2, 3, 4]);
237 /// assert_eq!(vec, vec!(1, 2, 3, 4));
240 pub fn push_all(&mut self, other: &[T]) {
241 self.extend(other.iter().map(|e| e.clone()));
244 /// Grows the `Vec` in-place.
246 /// Adds `n` copies of `value` to the `Vec`.
251 /// let mut vec = vec!("hello");
252 /// vec.grow(2, &("world"));
253 /// assert_eq!(vec, vec!("hello", "world", "world"));
255 pub fn grow(&mut self, n: uint, value: &T) {
256 let new_len = self.len() + n;
257 self.reserve(new_len);
258 let mut i: uint = 0u;
261 self.push((*value).clone());
266 /// Sets the value of a vector element at a given index, growing the vector
269 /// Sets the element at position `index` to `value`. If `index` is past the
270 /// end of the vector, expands the vector by replicating `initval` to fill
271 /// the intervening space.
276 /// let mut vec = vec!("a", "b", "c");
277 /// vec.grow_set(1, &("fill"), "d");
278 /// vec.grow_set(4, &("fill"), "e");
279 /// assert_eq!(vec, vec!("a", "d", "c", "fill", "e"));
281 pub fn grow_set(&mut self, index: uint, initval: &T, value: T) {
284 self.grow(index - l + 1u, initval);
286 *self.get_mut(index) = value;
289 /// Partitions a vector based on a predicate.
291 /// Clones the elements of the vector, partitioning them into two `Vec`s
292 /// `(A,B)`, where all elements of `A` satisfy `f` and all elements of `B`
293 /// do not. The order of elements is preserved.
298 /// let vec = vec!(1, 2, 3, 4);
299 /// let (even, odd) = vec.partitioned(|&n| n % 2 == 0);
300 /// assert_eq!(even, vec!(2, 4));
301 /// assert_eq!(odd, vec!(1, 3));
303 pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
304 let mut lefts = Vec::new();
305 let mut rights = Vec::new();
307 for elt in self.iter() {
309 lefts.push(elt.clone());
311 rights.push(elt.clone());
319 impl<T:Clone> Clone for Vec<T> {
320 fn clone(&self) -> Vec<T> {
322 let mut vector = Vec::with_capacity(len);
323 // Unsafe code so this can be optimised to a memcpy (or something
324 // similarly fast) when T is Copy. LLVM is easily confused, so any
325 // extra operations during the loop can prevent this optimisation
327 let this_slice = self.as_slice();
328 while vector.len < len {
330 let len = vector.len;
332 vector.as_mut_slice().unsafe_mut_ref(len),
333 this_slice.unsafe_ref(len).clone());
341 fn clone_from(&mut self, other: &Vec<T>) {
342 // drop anything in self that will not be overwritten
343 if self.len() > other.len() {
344 self.truncate(other.len())
347 // reuse the contained values' allocations/resources.
348 for (place, thing) in self.mut_iter().zip(other.iter()) {
349 place.clone_from(thing)
352 // self.len <= other.len due to the truncate above, so the
353 // slice here is always in-bounds.
354 let len = self.len();
355 self.extend(other.slice_from(len).iter().map(|x| x.clone()));
359 impl<T> FromIterator<T> for Vec<T> {
361 fn from_iter<I:Iterator<T>>(mut iterator: I) -> Vec<T> {
362 let (lower, _) = iterator.size_hint();
363 let mut vector = Vec::with_capacity(lower);
364 for element in iterator {
371 impl<T> Extendable<T> for Vec<T> {
373 fn extend<I: Iterator<T>>(&mut self, mut iterator: I) {
374 let (lower, _) = iterator.size_hint();
375 self.reserve_additional(lower);
376 for element in iterator {
382 impl<T: PartialEq> PartialEq for Vec<T> {
384 fn eq(&self, other: &Vec<T>) -> bool {
385 self.as_slice() == other.as_slice()
389 impl<T: PartialOrd> PartialOrd for Vec<T> {
391 fn lt(&self, other: &Vec<T>) -> bool {
392 self.as_slice() < other.as_slice()
396 impl<T: Eq> Eq for Vec<T> {}
398 impl<T: PartialEq, V: Vector<T>> Equiv<V> for Vec<T> {
400 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
403 impl<T: Ord> Ord for Vec<T> {
405 fn cmp(&self, other: &Vec<T>) -> Ordering {
406 self.as_slice().cmp(&other.as_slice())
410 impl<T> Collection for Vec<T> {
412 fn len(&self) -> uint {
417 impl<T: Clone> CloneableVector<T> for Vec<T> {
418 fn to_owned(&self) -> Vec<T> { self.clone() }
419 fn into_owned(self) -> Vec<T> { self }
422 // FIXME: #13996: need a way to mark the return value as `noalias`
424 unsafe fn alloc_or_realloc<T>(ptr: *mut T, size: uint, old_size: uint) -> *mut T {
426 allocate(size, mem::min_align_of::<T>()) as *mut T
428 reallocate(ptr as *mut u8, size,
429 mem::min_align_of::<T>(), old_size) as *mut T
434 unsafe fn dealloc<T>(ptr: *mut T, len: uint) {
435 if mem::size_of::<T>() != 0 {
436 deallocate(ptr as *mut u8,
437 len * mem::size_of::<T>(),
438 mem::min_align_of::<T>())
443 /// Returns the number of elements the vector can hold without
449 /// # use std::vec::Vec;
450 /// let vec: Vec<int> = Vec::with_capacity(10);
451 /// assert_eq!(vec.capacity(), 10);
454 pub fn capacity(&self) -> uint {
458 /// Reserves capacity for at least `n` additional elements in the given
463 /// Fails if the new capacity overflows `uint`.
468 /// # use std::vec::Vec;
469 /// let mut vec: Vec<int> = vec!(1);
470 /// vec.reserve_additional(10);
471 /// assert!(vec.capacity() >= 11);
473 pub fn reserve_additional(&mut self, extra: uint) {
474 if self.cap - self.len < extra {
475 match self.len.checked_add(&extra) {
476 None => fail!("Vec::reserve_additional: `uint` overflow"),
477 Some(new_cap) => self.reserve(new_cap)
482 /// Reserves capacity for at least `n` elements in the given vector.
484 /// This function will over-allocate in order to amortize the allocation
485 /// costs in scenarios where the caller may need to repeatedly reserve
486 /// additional space.
488 /// If the capacity for `self` is already equal to or greater than the
489 /// requested capacity, then no action is taken.
494 /// let mut vec = vec!(1, 2, 3);
496 /// assert!(vec.capacity() >= 10);
498 pub fn reserve(&mut self, capacity: uint) {
499 if capacity >= self.len {
500 self.reserve_exact(num::next_power_of_two(capacity))
504 /// Reserves capacity for exactly `capacity` elements in the given vector.
506 /// If the capacity for `self` is already equal to or greater than the
507 /// requested capacity, then no action is taken.
512 /// # use std::vec::Vec;
513 /// let mut vec: Vec<int> = Vec::with_capacity(10);
514 /// vec.reserve_exact(11);
515 /// assert_eq!(vec.capacity(), 11);
517 pub fn reserve_exact(&mut self, capacity: uint) {
518 if mem::size_of::<T>() == 0 { return }
520 if capacity > self.cap {
521 let size = capacity.checked_mul(&mem::size_of::<T>())
522 .expect("capacity overflow");
524 self.ptr = alloc_or_realloc(self.ptr, size,
525 self.cap * mem::size_of::<T>());
531 /// Shrink the capacity of the vector as much as possible
536 /// let mut vec = vec!(1, 2, 3);
537 /// vec.shrink_to_fit();
539 pub fn shrink_to_fit(&mut self) {
540 if mem::size_of::<T>() == 0 { return }
545 dealloc(self.ptr, self.cap)
551 // Overflow check is unnecessary as the vector is already at
553 self.ptr = reallocate(self.ptr as *mut u8,
554 self.len * mem::size_of::<T>(),
555 mem::min_align_of::<T>(),
556 self.cap * mem::size_of::<T>()) as *mut T;
562 /// Remove the last element from a vector and return it, or `None` if it is
568 /// let mut vec = vec!(1, 2, 3);
569 /// assert_eq!(vec.pop(), Some(3));
570 /// assert_eq!(vec, vec!(1, 2));
573 pub fn pop(&mut self) -> Option<T> {
579 Some(ptr::read(self.as_slice().unsafe_ref(self.len())))
584 /// Append an element to a vector.
588 /// Fails if the number of elements in the vector overflows a `uint`.
593 /// let mut vec = vec!(1, 2);
595 /// assert_eq!(vec, vec!(1, 2, 3));
598 pub fn push(&mut self, value: T) {
599 if mem::size_of::<T>() == 0 {
600 // zero-size types consume no memory, so we can't rely on the address space running out
601 self.len = self.len.checked_add(&1).expect("length overflow");
602 unsafe { mem::forget(value); }
605 if self.len == self.cap {
606 let old_size = self.cap * mem::size_of::<T>();
607 let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
608 if old_size > size { fail!("capacity overflow") }
610 self.ptr = alloc_or_realloc(self.ptr, size,
611 self.cap * mem::size_of::<T>());
613 self.cap = max(self.cap, 2) * 2;
617 let end = (self.ptr as *T).offset(self.len as int) as *mut T;
618 ptr::write(&mut *end, value);
623 /// Appends one element to the vector provided. The vector itself is then
624 /// returned for use again.
629 /// let vec = vec!(1, 2);
630 /// let vec = vec.append_one(3);
631 /// assert_eq!(vec, vec!(1, 2, 3));
634 pub fn append_one(mut self, x: T) -> Vec<T> {
639 /// Shorten a vector, dropping excess elements.
641 /// If `len` is greater than the vector's current length, this has no
647 /// let mut vec = vec!(1, 2, 3, 4);
649 /// assert_eq!(vec, vec!(1, 2));
651 pub fn truncate(&mut self, len: uint) {
653 // drop any extra elements
654 while len < self.len {
655 // decrement len before the read(), so a failure on Drop doesn't
656 // re-drop the just-failed value.
658 ptr::read(self.as_slice().unsafe_ref(self.len));
663 /// Work with `self` as a mutable slice.
668 /// fn foo(slice: &mut [int]) {}
670 /// let mut vec = vec!(1, 2);
671 /// foo(vec.as_mut_slice());
674 pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
676 mem::transmute(Slice { data: self.as_mut_ptr() as *T, len: self.len })
680 /// Creates a consuming iterator, that is, one that moves each
681 /// value out of the vector (from start to end). The vector cannot
682 /// be used after calling this.
687 /// let v = vec!("a".to_string(), "b".to_string());
688 /// for s in v.move_iter() {
689 /// // s has type String, not &String
690 /// println!("{}", s);
694 pub fn move_iter(self) -> MoveItems<T> {
696 let iter = mem::transmute(self.as_slice().iter());
700 MoveItems { allocation: ptr, cap: cap, iter: iter }
705 /// Sets the length of a vector.
707 /// This will explicitly set the size of the vector, without actually
708 /// modifying its buffers, so it is up to the caller to ensure that the
709 /// vector is actually the specified size.
711 pub unsafe fn set_len(&mut self, len: uint) {
715 /// Returns a reference to the value at index `index`.
719 /// Fails if `index` is out of bounds
724 /// let vec = vec!(1, 2, 3);
725 /// assert!(vec.get(1) == &2);
728 pub fn get<'a>(&'a self, index: uint) -> &'a T {
729 &self.as_slice()[index]
732 /// Returns a mutable reference to the value at index `index`.
736 /// Fails if `index` is out of bounds
741 /// let mut vec = vec!(1, 2, 3);
742 /// *vec.get_mut(1) = 4;
743 /// assert_eq!(vec, vec!(1, 4, 3));
746 pub fn get_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
747 &mut self.as_mut_slice()[index]
750 /// Returns an iterator over references to the elements of the vector in
756 /// let vec = vec!(1, 2, 3);
757 /// for num in vec.iter() {
758 /// println!("{}", *num);
762 pub fn iter<'a>(&'a self) -> Items<'a,T> {
763 self.as_slice().iter()
767 /// Returns an iterator over mutable references to the elements of the
773 /// let mut vec = vec!(1, 2, 3);
774 /// for num in vec.mut_iter() {
779 pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a,T> {
780 self.as_mut_slice().mut_iter()
783 /// Sort the vector, in place, using `compare` to compare elements.
785 /// This sort is `O(n log n)` worst-case and stable, but allocates
786 /// approximately `2 * n`, where `n` is the length of `self`.
791 /// let mut v = vec!(5i, 4, 1, 3, 2);
792 /// v.sort_by(|a, b| a.cmp(b));
793 /// assert_eq!(v, vec!(1, 2, 3, 4, 5));
795 /// // reverse sorting
796 /// v.sort_by(|a, b| b.cmp(a));
797 /// assert_eq!(v, vec!(5, 4, 3, 2, 1));
800 pub fn sort_by(&mut self, compare: |&T, &T| -> Ordering) {
801 self.as_mut_slice().sort_by(compare)
804 /// Returns a slice of self spanning the interval [`start`, `end`).
808 /// Fails when the slice (or part of it) is outside the bounds of self, or when
814 /// let vec = vec!(1, 2, 3, 4);
815 /// assert!(vec.slice(0, 2) == [1, 2]);
818 pub fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] {
819 self.as_slice().slice(start, end)
822 /// Returns a slice containing all but the first element of the vector.
826 /// Fails when the vector is empty.
831 /// let vec = vec!(1, 2, 3);
832 /// assert!(vec.tail() == [2, 3]);
835 pub fn tail<'a>(&'a self) -> &'a [T] {
836 self.as_slice().tail()
839 /// Returns all but the first `n' elements of a vector.
843 /// Fails when there are fewer than `n` elements in the vector.
848 /// let vec = vec!(1, 2, 3, 4);
849 /// assert!(vec.tailn(2) == [3, 4]);
852 pub fn tailn<'a>(&'a self, n: uint) -> &'a [T] {
853 self.as_slice().tailn(n)
856 /// Returns a reference to the last element of a vector, or `None` if it is
862 /// let vec = vec!(1, 2, 3);
863 /// assert!(vec.last() == Some(&3));
866 pub fn last<'a>(&'a self) -> Option<&'a T> {
867 self.as_slice().last()
870 /// Returns a mutable reference to the last element of a vector, or `None`
876 /// let mut vec = vec!(1, 2, 3);
877 /// *vec.mut_last().unwrap() = 4;
878 /// assert_eq!(vec, vec!(1, 2, 4));
881 pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
882 self.as_mut_slice().mut_last()
885 /// Remove an element from anywhere in the vector and return it, replacing
886 /// it with the last element. This does not preserve ordering, but is O(1).
888 /// Returns `None` if `index` is out of bounds.
892 /// let mut v = vec!("foo".to_string(), "bar".to_string(),
893 /// "baz".to_string(), "qux".to_string());
895 /// assert_eq!(v.swap_remove(1), Some("bar".to_string()));
896 /// assert_eq!(v, vec!("foo".to_string(), "qux".to_string(), "baz".to_string()));
898 /// assert_eq!(v.swap_remove(0), Some("foo".to_string()));
899 /// assert_eq!(v, vec!("baz".to_string(), "qux".to_string()));
901 /// assert_eq!(v.swap_remove(2), None);
904 pub fn swap_remove(&mut self, index: uint) -> Option<T> {
905 let length = self.len();
906 if index < length - 1 {
907 self.as_mut_slice().swap(index, length - 1);
908 } else if index >= length {
914 /// Prepend an element to the vector.
918 /// This is an O(n) operation as it requires copying every element in the
924 /// let mut vec = vec!(1, 2, 3);
926 /// assert_eq!(vec, vec!(4, 1, 2, 3));
929 pub fn unshift(&mut self, element: T) {
930 self.insert(0, element)
933 /// Removes the first element from a vector and returns it, or `None` if
934 /// the vector is empty.
938 /// This is an O(n) operation as it requires copying every element in the
944 /// let mut vec = vec!(1, 2, 3);
945 /// assert!(vec.shift() == Some(1));
946 /// assert_eq!(vec, vec!(2, 3));
949 pub fn shift(&mut self) -> Option<T> {
953 /// Insert an element at position `index` within the vector, shifting all
954 /// elements after position i one position to the right.
958 /// Fails if `index` is out of bounds of the vector.
963 /// let mut vec = vec!(1, 2, 3);
964 /// vec.insert(1, 4);
965 /// assert_eq!(vec, vec!(1, 4, 2, 3));
967 pub fn insert(&mut self, index: uint, element: T) {
968 let len = self.len();
969 assert!(index <= len);
970 // space for the new element
971 self.reserve(len + 1);
973 unsafe { // infallible
974 // The spot to put the new value
976 let p = self.as_mut_ptr().offset(index as int);
977 // Shift everything over to make space. (Duplicating the
978 // `index`th element into two consecutive places.)
979 ptr::copy_memory(p.offset(1), &*p, len - index);
980 // Write it in, overwriting the first copy of the `index`th
982 ptr::write(&mut *p, element);
984 self.set_len(len + 1);
988 /// Remove and return the element at position `index` within the vector,
989 /// shifting all elements after position `index` one position to the left.
990 /// Returns `None` if `i` is out of bounds.
995 /// let mut v = vec!(1, 2, 3);
996 /// assert_eq!(v.remove(1), Some(2));
997 /// assert_eq!(v, vec!(1, 3));
999 /// assert_eq!(v.remove(4), None);
1000 /// // v is unchanged:
1001 /// assert_eq!(v, vec!(1, 3));
1003 pub fn remove(&mut self, index: uint) -> Option<T> {
1004 let len = self.len();
1006 unsafe { // infallible
1009 // the place we are taking from.
1010 let ptr = self.as_mut_ptr().offset(index as int);
1011 // copy it out, unsafely having a copy of the value on
1012 // the stack and in the vector at the same time.
1013 ret = Some(ptr::read(ptr as *T));
1015 // Shift everything down to fill in that spot.
1016 ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
1018 self.set_len(len - 1);
1026 /// Takes ownership of the vector `other`, moving all elements into
1027 /// the current vector. This does not copy any elements, and it is
1028 /// illegal to use the `other` vector after calling this method
1029 /// (because it is moved here).
1034 /// let mut vec = vec!(box 1);
1035 /// vec.push_all_move(vec!(box 2, box 3, box 4));
1036 /// assert_eq!(vec, vec!(box 1, box 2, box 3, box 4));
1039 pub fn push_all_move(&mut self, other: Vec<T>) {
1040 self.extend(other.move_iter());
1043 /// Returns a mutable slice of `self` between `start` and `end`.
1047 /// Fails when `start` or `end` point outside the bounds of `self`, or when
1048 /// `start` > `end`.
1053 /// let mut vec = vec!(1, 2, 3, 4);
1054 /// assert!(vec.mut_slice(0, 2) == [1, 2]);
1057 pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint)
1059 self.as_mut_slice().mut_slice(start, end)
1062 /// Returns a mutable slice of self from `start` to the end of the vec.
1066 /// Fails when `start` points outside the bounds of self.
1071 /// let mut vec = vec!(1, 2, 3, 4);
1072 /// assert!(vec.mut_slice_from(2) == [3, 4]);
1075 pub fn mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] {
1076 self.as_mut_slice().mut_slice_from(start)
1079 /// Returns a mutable slice of self from the start of the vec to `end`.
1083 /// Fails when `end` points outside the bounds of self.
1088 /// let mut vec = vec!(1, 2, 3, 4);
1089 /// assert!(vec.mut_slice_to(2) == [1, 2]);
1092 pub fn mut_slice_to<'a>(&'a mut self, end: uint) -> &'a mut [T] {
1093 self.as_mut_slice().mut_slice_to(end)
1096 /// Returns a pair of mutable slices that divides the vec at an index.
1098 /// The first will contain all indices from `[0, mid)` (excluding
1099 /// the index `mid` itself) and the second will contain all
1100 /// indices from `[mid, len)` (excluding the index `len` itself).
1104 /// Fails if `mid > len`.
1109 /// let mut vec = vec!(1, 2, 3, 4, 5, 6);
1111 /// // scoped to restrict the lifetime of the borrows
1113 /// let (left, right) = vec.mut_split_at(0);
1114 /// assert!(left == &mut []);
1115 /// assert!(right == &mut [1, 2, 3, 4, 5, 6]);
1119 /// let (left, right) = vec.mut_split_at(2);
1120 /// assert!(left == &mut [1, 2]);
1121 /// assert!(right == &mut [3, 4, 5, 6]);
1125 /// let (left, right) = vec.mut_split_at(6);
1126 /// assert!(left == &mut [1, 2, 3, 4, 5, 6]);
1127 /// assert!(right == &mut []);
1131 pub fn mut_split_at<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
1132 self.as_mut_slice().mut_split_at(mid)
1135 /// Reverse the order of elements in a vector, in place.
1140 /// let mut v = vec!(1, 2, 3);
1142 /// assert_eq!(v, vec!(3, 2, 1));
1145 pub fn reverse(&mut self) {
1146 self.as_mut_slice().reverse()
1149 /// Returns a slice of `self` from `start` to the end of the vec.
1153 /// Fails when `start` points outside the bounds of self.
1158 /// let vec = vec!(1, 2, 3);
1159 /// assert!(vec.slice_from(1) == [2, 3]);
1162 pub fn slice_from<'a>(&'a self, start: uint) -> &'a [T] {
1163 self.as_slice().slice_from(start)
1166 /// Returns a slice of self from the start of the vec to `end`.
1170 /// Fails when `end` points outside the bounds of self.
1175 /// let vec = vec!(1, 2, 3);
1176 /// assert!(vec.slice_to(2) == [1, 2]);
1179 pub fn slice_to<'a>(&'a self, end: uint) -> &'a [T] {
1180 self.as_slice().slice_to(end)
1183 /// Returns a slice containing all but the last element of the vector.
1187 /// Fails if the vector is empty
1189 pub fn init<'a>(&'a self) -> &'a [T] {
1190 self.slice(0, self.len() - 1)
1194 /// Returns an unsafe pointer to the vector's buffer.
1196 /// The caller must ensure that the vector outlives the pointer this
1197 /// function returns, or else it will end up pointing to garbage.
1199 /// Modifying the vector may cause its buffer to be reallocated, which
1200 /// would also make any pointers to it invalid.
1202 pub fn as_ptr(&self) -> *T {
1203 // If we have a 0-sized vector, then the base pointer should not be NULL
1204 // because an iterator over the slice will attempt to yield the base
1205 // pointer as the first element in the vector, but this will end up
1206 // being Some(NULL) which is optimized to None.
1207 if mem::size_of::<T>() == 0 {
1214 /// Returns a mutable unsafe pointer to the vector's buffer.
1216 /// The caller must ensure that the vector outlives the pointer this
1217 /// function returns, or else it will end up pointing to garbage.
1219 /// Modifying the vector may cause its buffer to be reallocated, which
1220 /// would also make any pointers to it invalid.
1222 pub fn as_mut_ptr(&mut self) -> *mut T {
1223 // see above for the 0-size check
1224 if mem::size_of::<T>() == 0 {
1231 /// Retains only the elements specified by the predicate.
1233 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1234 /// This method operates in place and preserves the order the retained elements.
1239 /// let mut vec = vec!(1i, 2, 3, 4);
1240 /// vec.retain(|x| x%2 == 0);
1241 /// assert_eq!(vec, vec!(2, 4));
1243 pub fn retain(&mut self, f: |&T| -> bool) {
1244 let len = self.len();
1247 let v = self.as_mut_slice();
1249 for i in range(0u, len) {
1258 self.truncate(len - del);
1262 /// Expands a vector in place, initializing the new elements to the result of a function.
1264 /// The vector is grown by `n` elements. The i-th new element are initialized to the value
1265 /// returned by `f(i)` where `i` is in the range [0, n).
1270 /// let mut vec = vec!(0u, 1);
1271 /// vec.grow_fn(3, |i| i);
1272 /// assert_eq!(vec, vec!(0, 1, 0, 1, 2));
1274 pub fn grow_fn(&mut self, n: uint, f: |uint| -> T) {
1275 self.reserve_additional(n);
1276 for i in range(0u, n) {
1282 impl<T:Ord> Vec<T> {
1283 /// Sorts the vector in place.
1285 /// This sort is `O(n log n)` worst-case and stable, but allocates
1286 /// approximately `2 * n`, where `n` is the length of `self`.
1291 /// let mut vec = vec!(3i, 1, 2);
1293 /// assert_eq!(vec, vec!(1, 2, 3));
1295 pub fn sort(&mut self) {
1296 self.as_mut_slice().sort()
1300 impl<T> Mutable for Vec<T> {
1302 fn clear(&mut self) {
1307 impl<T:PartialEq> Vec<T> {
1308 /// Return true if a vector contains an element with the given value
1313 /// let vec = vec!(1, 2, 3);
1314 /// assert!(vec.contains(&1));
1317 pub fn contains(&self, x: &T) -> bool {
1318 self.as_slice().contains(x)
1321 /// Remove consecutive repeated elements in the vector.
1323 /// If the vector is sorted, this removes all duplicates.
1328 /// let mut vec = vec!(1, 2, 2, 3, 2);
1330 /// assert_eq!(vec, vec!(1, 2, 3, 2));
1332 pub fn dedup(&mut self) {
1334 // Although we have a mutable reference to `self`, we cannot make
1335 // *arbitrary* changes. The `PartialEq` comparisons could fail, so we
1336 // must ensure that the vector is in a valid state at all time.
1338 // The way that we handle this is by using swaps; we iterate
1339 // over all the elements, swapping as we go so that at the end
1340 // the elements we wish to keep are in the front, and those we
1341 // wish to reject are at the back. We can then truncate the
1342 // vector. This operation is still O(n).
1344 // Example: We start in this state, where `r` represents "next
1345 // read" and `w` represents "next_write`.
1348 // +---+---+---+---+---+---+
1349 // | 0 | 1 | 1 | 2 | 3 | 3 |
1350 // +---+---+---+---+---+---+
1353 // Comparing self[r] against self[w-1], this is not a duplicate, so
1354 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1355 // r and w, leaving us with:
1358 // +---+---+---+---+---+---+
1359 // | 0 | 1 | 1 | 2 | 3 | 3 |
1360 // +---+---+---+---+---+---+
1363 // Comparing self[r] against self[w-1], this value is a duplicate,
1364 // so we increment `r` but leave everything else unchanged:
1367 // +---+---+---+---+---+---+
1368 // | 0 | 1 | 1 | 2 | 3 | 3 |
1369 // +---+---+---+---+---+---+
1372 // Comparing self[r] against self[w-1], this is not a duplicate,
1373 // so swap self[r] and self[w] and advance r and w:
1376 // +---+---+---+---+---+---+
1377 // | 0 | 1 | 2 | 1 | 3 | 3 |
1378 // +---+---+---+---+---+---+
1381 // Not a duplicate, repeat:
1384 // +---+---+---+---+---+---+
1385 // | 0 | 1 | 2 | 3 | 1 | 3 |
1386 // +---+---+---+---+---+---+
1389 // Duplicate, advance r. End of vec. Truncate to w.
1391 let ln = self.len();
1392 if ln < 1 { return; }
1394 // Avoid bounds checks by using unsafe pointers.
1395 let p = self.as_mut_slice().as_mut_ptr();
1400 let p_r = p.offset(r as int);
1401 let p_wm1 = p.offset((w - 1) as int);
1404 let p_w = p_wm1.offset(1);
1405 mem::swap(&mut *p_r, &mut *p_w);
1417 impl<T> Vector<T> for Vec<T> {
1418 /// Work with `self` as a slice.
1423 /// fn foo(slice: &[int]) {}
1425 /// let vec = vec!(1, 2);
1426 /// foo(vec.as_slice());
1429 fn as_slice<'a>(&'a self) -> &'a [T] {
1430 unsafe { mem::transmute(Slice { data: self.as_ptr(), len: self.len }) }
1434 impl<T: Clone, V: Vector<T>> Add<V, Vec<T>> for Vec<T> {
1436 fn add(&self, rhs: &V) -> Vec<T> {
1437 let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len());
1438 res.push_all(self.as_slice());
1439 res.push_all(rhs.as_slice());
1444 #[unsafe_destructor]
1445 impl<T> Drop for Vec<T> {
1446 fn drop(&mut self) {
1447 // This is (and should always remain) a no-op if the fields are
1448 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1451 for x in self.as_mut_slice().iter() {
1454 dealloc(self.ptr, self.cap)
1460 impl<T> Default for Vec<T> {
1461 fn default() -> Vec<T> {
1466 impl<T:fmt::Show> fmt::Show for Vec<T> {
1467 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1468 self.as_slice().fmt(f)
1472 /// An iterator that moves out of a vector.
1473 pub struct MoveItems<T> {
1474 allocation: *mut T, // the block of memory allocated for the vector
1475 cap: uint, // the capacity of the vector
1476 iter: Items<'static, T>
1479 impl<T> Iterator<T> for MoveItems<T> {
1481 fn next(&mut self) -> Option<T> {
1483 self.iter.next().map(|x| ptr::read(x))
1488 fn size_hint(&self) -> (uint, Option<uint>) {
1489 self.iter.size_hint()
1493 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
1495 fn next_back(&mut self) -> Option<T> {
1497 self.iter.next_back().map(|x| ptr::read(x))
1502 #[unsafe_destructor]
1503 impl<T> Drop for MoveItems<T> {
1504 fn drop(&mut self) {
1505 // destroy the remaining elements
1509 dealloc(self.allocation, self.cap);
1516 * Convert an iterator of pairs into a pair of vectors.
1518 * Returns a tuple containing two vectors where the i-th element of the first
1519 * vector contains the first element of the i-th tuple of the input iterator,
1520 * and the i-th element of the second vector contains the second element
1521 * of the i-th tuple of the input iterator.
1523 pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (Vec<T>, Vec<U>) {
1524 let (lo, _) = iter.size_hint();
1525 let mut ts = Vec::with_capacity(lo);
1526 let mut us = Vec::with_capacity(lo);
1527 for (t, u) in iter {
1534 /// Unsafe operations
1539 /// Constructs a vector from an unsafe pointer to a buffer.
1541 /// The elements of the buffer are copied into the vector without cloning,
1542 /// as if `ptr::read()` were called on them.
1544 pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> Vec<T> {
1545 let mut dst = Vec::with_capacity(elts);
1547 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
1557 use std::prelude::*;
1558 use std::mem::size_of;
1560 use super::{unzip, raw, Vec};
1563 fn test_small_vec_struct() {
1564 assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1568 fn test_double_drop() {
1574 struct DropCounter<'a> {
1578 #[unsafe_destructor]
1579 impl<'a> Drop for DropCounter<'a> {
1580 fn drop(&mut self) {
1585 let mut count_x @ mut count_y = 0;
1587 let mut tv = TwoVec {
1591 tv.x.push(DropCounter {count: &mut count_x});
1592 tv.y.push(DropCounter {count: &mut count_y});
1594 // If Vec had a drop flag, here is where it would be zeroed.
1595 // Instead, it should rely on its internal state to prevent
1596 // doing anything significant when dropped multiple times.
1599 // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1602 assert_eq!(count_x, 1);
1603 assert_eq!(count_y, 1);
1607 fn test_reserve_additional() {
1608 let mut v = Vec::new();
1609 assert_eq!(v.capacity(), 0);
1611 v.reserve_additional(2);
1612 assert!(v.capacity() >= 2);
1614 for i in range(0, 16) {
1618 assert!(v.capacity() >= 16);
1619 v.reserve_additional(16);
1620 assert!(v.capacity() >= 32);
1624 v.reserve_additional(16);
1625 assert!(v.capacity() >= 33)
1630 let mut v = Vec::new();
1631 let mut w = Vec::new();
1633 v.extend(range(0, 3));
1634 for i in range(0, 3) { w.push(i) }
1638 v.extend(range(3, 10));
1639 for i in range(3, 10) { w.push(i) }
1645 fn test_mut_slice_from() {
1646 let mut values = Vec::from_slice([1u8,2,3,4,5]);
1648 let slice = values.mut_slice_from(2);
1649 assert!(slice == [3, 4, 5]);
1650 for p in slice.mut_iter() {
1655 assert!(values.as_slice() == [1, 2, 5, 6, 7]);
1659 fn test_mut_slice_to() {
1660 let mut values = Vec::from_slice([1u8,2,3,4,5]);
1662 let slice = values.mut_slice_to(2);
1663 assert!(slice == [1, 2]);
1664 for p in slice.mut_iter() {
1669 assert!(values.as_slice() == [2, 3, 3, 4, 5]);
1673 fn test_mut_split_at() {
1674 let mut values = Vec::from_slice([1u8,2,3,4,5]);
1676 let (left, right) = values.mut_split_at(2);
1677 assert!(left.slice(0, left.len()) == [1, 2]);
1678 for p in left.mut_iter() {
1682 assert!(right.slice(0, right.len()) == [3, 4, 5]);
1683 for p in right.mut_iter() {
1688 assert!(values == Vec::from_slice([2u8, 3, 5, 6, 7]));
1693 let v: Vec<int> = vec!();
1694 let w = vec!(1, 2, 3);
1696 assert_eq!(v, v.clone());
1700 // they should be disjoint in memory.
1701 assert!(w.as_ptr() != z.as_ptr())
1705 fn test_clone_from() {
1707 let three = vec!(box 1, box 2, box 3);
1708 let two = vec!(box 4, box 5);
1710 v.clone_from(&three);
1711 assert_eq!(v, three);
1714 v.clone_from(&three);
1715 assert_eq!(v, three);
1722 v.clone_from(&three);
1723 assert_eq!(v, three)
1728 let mut v = Vec::from_slice([0u, 1]);
1729 v.grow_fn(3, |i| i);
1730 assert!(v == Vec::from_slice([0u, 1, 0, 1, 2]));
1735 let mut vec = Vec::from_slice([1u, 2, 3, 4]);
1736 vec.retain(|x| x%2 == 0);
1737 assert!(vec == Vec::from_slice([2u, 4]));
1741 fn zero_sized_values() {
1742 let mut v = Vec::new();
1743 assert_eq!(v.len(), 0);
1745 assert_eq!(v.len(), 1);
1747 assert_eq!(v.len(), 2);
1748 assert_eq!(v.pop(), Some(()));
1749 assert_eq!(v.pop(), Some(()));
1750 assert_eq!(v.pop(), None);
1752 assert_eq!(v.iter().count(), 0);
1754 assert_eq!(v.iter().count(), 1);
1756 assert_eq!(v.iter().count(), 2);
1758 for &() in v.iter() {}
1760 assert_eq!(v.mut_iter().count(), 2);
1762 assert_eq!(v.mut_iter().count(), 3);
1764 assert_eq!(v.mut_iter().count(), 4);
1766 for &() in v.mut_iter() {}
1767 unsafe { v.set_len(0); }
1768 assert_eq!(v.mut_iter().count(), 0);
1772 fn test_partition() {
1773 assert_eq!(vec![].partition(|x: &int| *x < 3), (vec![], vec![]));
1774 assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1775 assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1776 assert_eq!(vec![1, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1780 fn test_partitioned() {
1781 assert_eq!(vec![].partitioned(|x: &int| *x < 3), (vec![], vec![]))
1782 assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1783 assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1784 assert_eq!(vec![1, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1788 fn test_zip_unzip() {
1789 let z1 = vec![(1, 4), (2, 5), (3, 6)];
1791 let (left, right) = unzip(z1.iter().map(|&x| x));
1793 let (left, right) = (left.as_slice(), right.as_slice());
1794 assert_eq!((1, 4), (left[0], right[0]));
1795 assert_eq!((2, 5), (left[1], right[1]));
1796 assert_eq!((3, 6), (left[2], right[2]));
1800 fn test_unsafe_ptrs() {
1802 // Test on-stack copy-from-buf.
1804 let ptr = a.as_ptr();
1805 let b = raw::from_buf(ptr, 3u);
1806 assert_eq!(b, vec![1, 2, 3]);
1808 // Test on-heap copy-from-buf.
1809 let c = vec![1, 2, 3, 4, 5];
1810 let ptr = c.as_ptr();
1811 let d = raw::from_buf(ptr, 5u);
1812 assert_eq!(d, vec![1, 2, 3, 4, 5]);
1817 fn test_vec_truncate_drop() {
1818 static mut drops: uint = 0;
1820 impl Drop for Elem {
1821 fn drop(&mut self) {
1822 unsafe { drops += 1; }
1826 let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
1827 assert_eq!(unsafe { drops }, 0);
1829 assert_eq!(unsafe { drops }, 2);
1831 assert_eq!(unsafe { drops }, 5);
1836 fn test_vec_truncate_fail() {
1837 struct BadElem(int);
1838 impl Drop for BadElem {
1839 fn drop(&mut self) {
1840 let BadElem(ref mut x) = *self;
1841 if *x == 0xbadbeef {
1842 fail!("BadElem failure: 0xbadbeef")
1847 let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
1852 fn bench_new(b: &mut Bencher) {
1854 let v: Vec<int> = Vec::new();
1855 assert_eq!(v.capacity(), 0);
1856 assert!(v.as_slice() == []);
1861 fn bench_with_capacity_0(b: &mut Bencher) {
1863 let v: Vec<int> = Vec::with_capacity(0);
1864 assert_eq!(v.capacity(), 0);
1865 assert!(v.as_slice() == []);
1871 fn bench_with_capacity_5(b: &mut Bencher) {
1873 let v: Vec<int> = Vec::with_capacity(5);
1874 assert_eq!(v.capacity(), 5);
1875 assert!(v.as_slice() == []);
1880 fn bench_with_capacity_100(b: &mut Bencher) {
1882 let v: Vec<int> = Vec::with_capacity(100);
1883 assert_eq!(v.capacity(), 100);
1884 assert!(v.as_slice() == []);
1889 fn bench_from_fn_0(b: &mut Bencher) {
1891 let v: Vec<int> = Vec::from_fn(0, |_| 5);
1892 assert!(v.as_slice() == []);
1897 fn bench_from_fn_5(b: &mut Bencher) {
1899 let v: Vec<int> = Vec::from_fn(5, |_| 5);
1900 assert!(v.as_slice() == [5, 5, 5, 5, 5]);
1905 fn bench_from_slice_0(b: &mut Bencher) {
1907 let v: Vec<int> = Vec::from_slice([]);
1908 assert!(v.as_slice() == []);
1913 fn bench_from_slice_5(b: &mut Bencher) {
1915 let v: Vec<int> = Vec::from_slice([1, 2, 3, 4, 5]);
1916 assert!(v.as_slice() == [1, 2, 3, 4, 5]);
1921 fn bench_from_iter_0(b: &mut Bencher) {
1923 let v0: Vec<int> = vec!();
1924 let v1: Vec<int> = FromIterator::from_iter(v0.move_iter());
1925 assert!(v1.as_slice() == []);
1930 fn bench_from_iter_5(b: &mut Bencher) {
1932 let v0: Vec<int> = vec!(1, 2, 3, 4, 5);
1933 let v1: Vec<int> = FromIterator::from_iter(v0.move_iter());
1934 assert!(v1.as_slice() == [1, 2, 3, 4, 5]);
1939 fn bench_extend_0(b: &mut Bencher) {
1941 let v0: Vec<int> = vec!();
1942 let mut v1: Vec<int> = vec!(1, 2, 3, 4, 5);
1943 v1.extend(v0.move_iter());
1944 assert!(v1.as_slice() == [1, 2, 3, 4, 5]);
1949 fn bench_extend_5(b: &mut Bencher) {
1951 let v0: Vec<int> = vec!(1, 2, 3, 4, 5);
1952 let mut v1: Vec<int> = vec!(1, 2, 3, 4, 5);
1953 v1.extend(v0.move_iter());
1954 assert!(v1.as_slice() == [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]);