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.
10 //! An owned, growable vector.
12 use cast::{forget, transmute};
14 use cmp::{Ord, Eq, Ordering, TotalEq, TotalOrd};
15 use container::{Container, Mutable};
18 use iter::{DoubleEndedIterator, FromIterator, Extendable, Iterator};
19 use libc::{free, c_void};
20 use mem::{size_of, move_val_init};
23 use num::{CheckedMul, CheckedAdd};
25 use option::{None, Option, Some};
28 use rt::global_heap::{malloc_raw, realloc_raw};
30 use slice::{ImmutableEqVector, ImmutableVector, Items, MutItems, MutableVector};
31 use slice::{MutableTotalOrdVector, Vector};
33 /// An owned, growable vector.
38 /// # use std::vec::Vec;
39 /// let mut vec = Vec::new();
43 /// assert_eq!(vec.len(), 2);
44 /// assert_eq!(vec.get(0), &1);
46 /// assert_eq!(vec.pop(), Some(2));
47 /// assert_eq!(vec.len(), 1);
50 /// The `vec!` macro is provided to make initialization more convenient:
53 /// let mut vec = vec!(1, 2, 3);
55 /// assert_eq!(vec, vec!(1, 2, 3, 4));
57 #[unsafe_no_drop_flag]
65 /// Constructs a new, empty `Vec`.
67 /// The vector will not allocate until elements are pushed onto it.
72 /// # use std::vec::Vec;
73 /// let mut vec: Vec<int> = Vec::new();
76 pub fn new() -> Vec<T> {
77 Vec { len: 0, cap: 0, ptr: 0 as *mut T }
80 /// Constructs a new, empty `Vec` with the specified capacity.
82 /// The vector will be able to hold exactly `capacity` elements without
83 /// reallocating. If `capacity` is 0, the vector will not allocate.
88 /// # use std::vec::Vec;
89 /// let vec: Vec<int> = Vec::with_capacity(10);
91 pub fn with_capacity(capacity: uint) -> Vec<T> {
95 let size = capacity.checked_mul(&size_of::<T>()).expect("capacity overflow");
96 let ptr = unsafe { malloc_raw(size) };
97 Vec { len: 0, cap: capacity, ptr: ptr as *mut T }
101 /// Creates and initializes a `Vec`.
103 /// Creates a `Vec` of size `length` and initializes the elements to the
104 /// value returned by the closure `op`.
109 /// # use std::vec::Vec;
110 /// let vec = Vec::from_fn(3, |idx| idx * 2);
111 /// assert_eq!(vec, vec!(0, 2, 4));
113 pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
115 let mut xs = Vec::with_capacity(length);
116 while xs.len < length {
117 move_val_init(xs.as_mut_slice().unsafe_mut_ref(xs.len), op(xs.len));
124 /// Consumes the `Vec`, partitioning it based on a predcate.
126 /// Partitions the `Vec` into two `Vec`s `(A,B)`, where all elements of `A`
127 /// satisfy `f` and all elements of `B` do not. The order of elements is
133 /// let vec = vec!(1, 2, 3, 4);
134 /// let (even, odd) = vec.partition(|&n| n % 2 == 0);
135 /// assert_eq!(even, vec!(2, 4));
136 /// assert_eq!(odd, vec!(1, 3));
139 pub fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
140 let mut lefts = Vec::new();
141 let mut rights = Vec::new();
143 for elt in self.move_iter() {
155 impl<T: Clone> Vec<T> {
156 /// Constructs a `Vec` by cloning elements of a slice.
161 /// # use std::vec::Vec;
162 /// let slice = [1, 2, 3];
163 /// let vec = Vec::from_slice(slice);
165 pub fn from_slice(values: &[T]) -> Vec<T> {
166 values.iter().map(|x| x.clone()).collect()
169 /// Constructs a `Vec` with copies of a value.
171 /// Creates a `Vec` with `length` copies of `value`.
175 /// # use std::vec::Vec;
176 /// let vec = Vec::from_elem(3, "hi");
177 /// println!("{}", vec); // prints [hi, hi, hi]
179 pub fn from_elem(length: uint, value: T) -> Vec<T> {
181 let mut xs = Vec::with_capacity(length);
182 while xs.len < length {
183 move_val_init(xs.as_mut_slice().unsafe_mut_ref(xs.len), value.clone());
190 /// Appends all elements in a slice to the `Vec`.
192 /// Iterates over the slice `other`, clones each element, and then appends
193 /// it to this `Vec`. The `other` vector is traversed in-order.
198 /// let mut vec = vec!(1);
199 /// vec.push_all([2, 3, 4]);
200 /// assert_eq!(vec, vec!(1, 2, 3, 4));
203 pub fn push_all(&mut self, other: &[T]) {
204 for element in other.iter() {
205 self.push((*element).clone())
209 /// Grows the `Vec` in-place.
211 /// Adds `n` copies of `value` to the `Vec`.
216 /// let mut vec = vec!("hello");
217 /// vec.grow(2, & &"world");
218 /// assert_eq!(vec, vec!("hello", "world", "world"));
220 pub fn grow(&mut self, n: uint, value: &T) {
221 let new_len = self.len() + n;
222 self.reserve(new_len);
223 let mut i: uint = 0u;
226 self.push((*value).clone());
231 /// Sets the value of a vector element at a given index, growing the vector
234 /// Sets the element at position `index` to `value`. If `index` is past the
235 /// end of the vector, expands the vector by replicating `initval` to fill
236 /// the intervening space.
241 /// let mut vec = vec!("a", "b", "c");
242 /// vec.grow_set(1, & &"fill", "d");
243 /// vec.grow_set(4, & &"fill", "e");
244 /// assert_eq!(vec, vec!("a", "d", "c", "fill", "e"));
246 pub fn grow_set(&mut self, index: uint, initval: &T, value: T) {
249 self.grow(index - l + 1u, initval);
251 *self.get_mut(index) = value;
254 /// Partitions a vector based on a predcate.
256 /// Clones the elements of the vector, partitioning them into two `Vec`s
257 /// `(A,B)`, where all elements of `A` satisfy `f` and all elements of `B`
258 /// do not. The order of elements is preserved.
263 /// let vec = vec!(1, 2, 3, 4);
264 /// let (even, odd) = vec.partitioned(|&n| n % 2 == 0);
265 /// assert_eq!(even, vec!(2, 4));
266 /// assert_eq!(odd, vec!(1, 3));
268 pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
269 let mut lefts = Vec::new();
270 let mut rights = Vec::new();
272 for elt in self.iter() {
274 lefts.push(elt.clone());
276 rights.push(elt.clone());
284 impl<T:Clone> Clone for Vec<T> {
285 fn clone(&self) -> Vec<T> {
286 let mut vector = Vec::with_capacity(self.len());
287 for element in self.iter() {
288 vector.push((*element).clone())
294 impl<T> FromIterator<T> for Vec<T> {
295 fn from_iterator<I:Iterator<T>>(iterator: &mut I) -> Vec<T> {
296 let (lower, _) = iterator.size_hint();
297 let mut vector = Vec::with_capacity(lower);
298 for element in *iterator {
305 impl<T> Extendable<T> for Vec<T> {
306 fn extend<I: Iterator<T>>(&mut self, iterator: &mut I) {
307 let (lower, _) = iterator.size_hint();
308 self.reserve_additional(lower);
309 for element in *iterator {
315 impl<T: Eq> Eq for Vec<T> {
317 fn eq(&self, other: &Vec<T>) -> bool {
318 self.as_slice() == other.as_slice()
322 impl<T: Ord> Ord for Vec<T> {
324 fn lt(&self, other: &Vec<T>) -> bool {
325 self.as_slice() < other.as_slice()
329 impl<T: TotalEq> TotalEq for Vec<T> {
331 fn equals(&self, other: &Vec<T>) -> bool {
332 self.as_slice().equals(&other.as_slice())
336 impl<T: TotalOrd> TotalOrd for Vec<T> {
338 fn cmp(&self, other: &Vec<T>) -> Ordering {
339 self.as_slice().cmp(&other.as_slice())
343 impl<T> Container for Vec<T> {
345 fn len(&self) -> uint {
351 /// Returns the number of elements the vector can hold without
357 /// # use std::vec::Vec;
358 /// let vec: Vec<int> = Vec::with_capacity(10);
359 /// assert_eq!(vec.capacity(), 10);
362 pub fn capacity(&self) -> uint {
366 /// Reserves capacity for at least `n` additional elements in the given
371 /// Fails if the new capacity overflows `uint`.
376 /// # use std::vec::Vec;
377 /// let mut vec: Vec<int> = vec!(1);
378 /// vec.reserve_additional(10);
379 /// assert!(vec.capacity() >= 11);
381 pub fn reserve_additional(&mut self, extra: uint) {
382 if self.cap - self.len < extra {
383 match self.len.checked_add(&extra) {
384 None => fail!("Vec::reserve_additional: `uint` overflow"),
385 Some(new_cap) => self.reserve(new_cap)
390 /// Reserves capacity for at least `n` elements in the given vector.
392 /// This function will over-allocate in order to amortize the allocation
393 /// costs in scenarios where the caller may need to repeatedly reserve
394 /// additional space.
396 /// If the capacity for `self` is already equal to or greater than the
397 /// requested capacity, then no action is taken.
402 /// let mut vec = vec!(1, 2, 3);
404 /// assert!(vec.capacity() >= 10);
406 pub fn reserve(&mut self, capacity: uint) {
407 if capacity >= self.len {
408 self.reserve_exact(num::next_power_of_two(capacity))
412 /// Reserves capacity for exactly `capacity` elements in the given vector.
414 /// If the capacity for `self` is already equal to or greater than the
415 /// requested capacity, then no action is taken.
420 /// # use std::vec::Vec;
421 /// let mut vec: Vec<int> = Vec::with_capacity(10);
422 /// vec.reserve_exact(11);
423 /// assert_eq!(vec.capacity(), 11);
425 pub fn reserve_exact(&mut self, capacity: uint) {
426 if capacity >= self.len {
427 let size = capacity.checked_mul(&size_of::<T>()).expect("capacity overflow");
430 self.ptr = realloc_raw(self.ptr as *mut u8, size) as *mut T;
435 /// Shrink the capacity of the vector to match the length
440 /// let mut vec = vec!(1, 2, 3);
441 /// vec.shrink_to_fit();
442 /// assert_eq!(vec.capacity(), vec.len());
444 pub fn shrink_to_fit(&mut self) {
446 unsafe { free(self.ptr as *mut c_void) };
448 self.ptr = 0 as *mut T;
451 // Overflow check is unnecessary as the vector is already at least this large.
452 self.ptr = realloc_raw(self.ptr as *mut u8, self.len * size_of::<T>()) as *mut T;
458 /// Remove the last element from a vector and return it, or `None` if it is
464 /// let mut vec = vec!(1, 2, 3);
465 /// assert_eq!(vec.pop(), Some(3));
466 /// assert_eq!(vec, vec!(1, 2));
469 pub fn pop(&mut self) -> Option<T> {
475 Some(ptr::read(self.as_slice().unsafe_ref(self.len())))
480 /// Append an element to a vector.
484 /// Fails if the number of elements in the vector overflows a `uint`.
489 /// let mut vec = vec!(1, 2);
491 /// assert_eq!(vec, vec!(1, 2, 3));
494 pub fn push(&mut self, value: T) {
495 if self.len == self.cap {
496 if self.cap == 0 { self.cap += 2 }
497 let old_size = self.cap * size_of::<T>();
498 self.cap = self.cap * 2;
499 let size = old_size * 2;
500 if old_size > size { fail!("capacity overflow") }
502 self.ptr = realloc_raw(self.ptr as *mut u8, size) as *mut T;
507 let end = (self.ptr as *T).offset(self.len as int) as *mut T;
508 move_val_init(&mut *end, value);
513 /// Shorten a vector, dropping excess elements.
515 /// If `len` is greater than the vector's current length, this has no
521 /// let mut vec = vec!(1, 2, 3, 4);
523 /// assert_eq!(vec, vec!(1, 2));
525 pub fn truncate(&mut self, len: uint) {
528 // drop any extra elements
530 ptr::read(self.as_slice().unsafe_ref(i));
537 /// Work with `self` as a mutable slice.
542 /// fn foo(slice: &mut [int]) {}
544 /// let mut vec = vec!(1, 2);
545 /// foo(vec.as_mut_slice());
548 pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
549 let slice = Slice { data: self.ptr as *T, len: self.len };
550 unsafe { transmute(slice) }
553 /// Creates a consuming iterator, that is, one that moves each
554 /// value out of the vector (from start to end). The vector cannot
555 /// be used after calling this.
560 /// let v = vec!(~"a", ~"b");
561 /// for s in v.move_iter() {
562 /// // s has type ~str, not &~str
563 /// println!("{}", s);
567 pub fn move_iter(self) -> MoveItems<T> {
569 let iter = transmute(self.as_slice().iter());
570 let ptr = self.ptr as *mut c_void;
572 MoveItems { allocation: ptr, iter: iter }
577 /// Sets the length of a vector.
579 /// This will explicitly set the size of the vector, without actually
580 /// modifying its buffers, so it is up to the caller to ensure that the
581 /// vector is actually the specified size.
583 pub unsafe fn set_len(&mut self, len: uint) {
587 /// Returns a reference to the value at index `index`.
591 /// Fails if `index` is out of bounds
596 /// let vec = vec!(1, 2, 3);
597 /// assert!(vec.get(1) == &2);
600 pub fn get<'a>(&'a self, index: uint) -> &'a T {
601 &self.as_slice()[index]
604 /// Returns a mutable reference to the value at index `index`.
608 /// Fails if `index` is out of bounds
613 /// let mut vec = vec!(1, 2, 3);
614 /// *vec.get_mut(1) = 4;
615 /// assert_eq!(vec, vec!(1, 4, 3));
618 pub fn get_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
619 &mut self.as_mut_slice()[index]
622 /// Returns an iterator over references to the elements of the vector in
628 /// let vec = vec!(1, 2, 3);
629 /// for num in vec.iter() {
630 /// println!("{}", *num);
634 pub fn iter<'a>(&'a self) -> Items<'a,T> {
635 self.as_slice().iter()
639 /// Returns an iterator over mutable references to the elements of the
645 /// let mut vec = vec!(1, 2, 3);
646 /// for num in vec.mut_iter() {
651 pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a,T> {
652 self.as_mut_slice().mut_iter()
655 /// Sort the vector, in place, using `compare` to compare elements.
657 /// This sort is `O(n log n)` worst-case and stable, but allocates
658 /// approximately `2 * n`, where `n` is the length of `self`.
663 /// let mut v = vec!(5i, 4, 1, 3, 2);
664 /// v.sort_by(|a, b| a.cmp(b));
665 /// assert_eq!(v, vec!(1, 2, 3, 4, 5));
667 /// // reverse sorting
668 /// v.sort_by(|a, b| b.cmp(a));
669 /// assert_eq!(v, vec!(5, 4, 3, 2, 1));
672 pub fn sort_by(&mut self, compare: |&T, &T| -> Ordering) {
673 self.as_mut_slice().sort_by(compare)
676 /// Returns a slice of `self` between `start` and `end`.
680 /// Fails when `start` or `end` point outside the bounds of `self`, or when
686 /// let vec = vec!(1, 2, 3, 4);
687 /// assert!(vec.slice(0, 2) == [1, 2]);
690 pub fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] {
691 self.as_slice().slice(start, end)
694 /// Returns a slice containing all but the first element of the vector.
698 /// Fails when the vector is empty.
703 /// let vec = vec!(1, 2, 3);
704 /// assert!(vec.tail() == [2, 3]);
707 pub fn tail<'a>(&'a self) -> &'a [T] {
708 self.as_slice().tail()
711 /// Returns all but the first `n' elements of a vector.
715 /// Fails when there are fewer than `n` elements in the vector.
720 /// let vec = vec!(1, 2, 3, 4);
721 /// assert!(vec.tailn(2) == [3, 4]);
724 pub fn tailn<'a>(&'a self, n: uint) -> &'a [T] {
725 self.as_slice().tailn(n)
728 /// Returns a reference to the last element of a vector, or `None` if it is
734 /// let vec = vec!(1, 2, 3);
735 /// assert!(vec.last() == Some(&3));
738 pub fn last<'a>(&'a self) -> Option<&'a T> {
739 self.as_slice().last()
742 /// Returns a mutable reference to the last element of a vector, or `None`
748 /// let mut vec = vec!(1, 2, 3);
749 /// *vec.mut_last().unwrap() = 4;
750 /// assert_eq!(vec, vec!(1, 2, 4));
753 pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
754 self.as_mut_slice().mut_last()
757 /// Remove an element from anywhere in the vector and return it, replacing
758 /// it with the last element. This does not preserve ordering, but is O(1).
760 /// Returns `None` if `index` is out of bounds.
764 /// let mut v = vec!(~"foo", ~"bar", ~"baz", ~"qux");
766 /// assert_eq!(v.swap_remove(1), Some(~"bar"));
767 /// assert_eq!(v, vec!(~"foo", ~"qux", ~"baz"));
769 /// assert_eq!(v.swap_remove(0), Some(~"foo"));
770 /// assert_eq!(v, vec!(~"baz", ~"qux"));
772 /// assert_eq!(v.swap_remove(2), None);
775 pub fn swap_remove(&mut self, index: uint) -> Option<T> {
776 let length = self.len();
777 if index < length - 1 {
778 self.as_mut_slice().swap(index, length - 1);
779 } else if index >= length {
785 /// Prepend an element to the vector.
789 /// This is an O(n) operation as it requires copying every element in the
795 /// let mut vec = vec!(1, 2, 3);
797 /// assert_eq!(vec, vec!(4, 1, 2, 3));
800 pub fn unshift(&mut self, element: T) {
801 self.insert(0, element)
804 /// Removes the first element from a vector and returns it, or `None` if
805 /// the vector is empty.
809 /// This is an O(n) operation as it requires copying every element in the
815 /// let mut vec = vec!(1, 2, 3);
816 /// assert!(vec.shift() == Some(1));
817 /// assert_eq!(vec, vec!(2, 3));
820 pub fn shift(&mut self) -> Option<T> {
824 /// Insert an element at position `index` within the vector, shifting all
825 /// elements after position i one position to the right.
829 /// Fails if `index` is out of bounds of the vector.
834 /// let mut vec = vec!(1, 2, 3);
835 /// vec.insert(1, 4);
836 /// assert_eq!(vec, vec!(1, 4, 2, 3));
838 pub fn insert(&mut self, index: uint, element: T) {
839 let len = self.len();
840 assert!(index <= len);
841 // space for the new element
842 self.reserve(len + 1);
844 unsafe { // infallible
845 // The spot to put the new value
847 let p = self.as_mut_ptr().offset(index as int);
848 // Shift everything over to make space. (Duplicating the
849 // `index`th element into two consecutive places.)
850 ptr::copy_memory(p.offset(1), &*p, len - index);
851 // Write it in, overwriting the first copy of the `index`th
853 move_val_init(&mut *p, element);
855 self.set_len(len + 1);
859 /// Remove and return the element at position `index` within the vector,
860 /// shifting all elements after position `index` one position to the left.
861 /// Returns `None` if `i` is out of bounds.
866 /// let mut v = vec!(1, 2, 3);
867 /// assert_eq!(v.remove(1), Some(2));
868 /// assert_eq!(v, vec!(1, 3));
870 /// assert_eq!(v.remove(4), None);
871 /// // v is unchanged:
872 /// assert_eq!(v, vec!(1, 3));
874 pub fn remove(&mut self, index: uint) -> Option<T> {
875 let len = self.len();
877 unsafe { // infallible
880 // the place we are taking from.
881 let ptr = self.as_mut_ptr().offset(index as int);
882 // copy it out, unsafely having a copy of the value on
883 // the stack and in the vector at the same time.
884 ret = Some(ptr::read(ptr as *T));
886 // Shift everything down to fill in that spot.
887 ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
889 self.set_len(len - 1);
897 ///Apply a function to each element of a vector and return the results.
899 #[deprecated="Use `xs.iter().map(closure)` instead."]
900 pub fn map<U>(&self, f: |t: &T| -> U) -> Vec<U> {
901 self.iter().map(f).collect()
904 /// Takes ownership of the vector `other`, moving all elements into
905 /// the current vector. This does not copy any elements, and it is
906 /// illegal to use the `other` vector after calling this method
907 /// (because it is moved here).
912 /// let mut vec = vec!(~1);
913 /// vec.push_all_move(vec!(~2, ~3, ~4));
914 /// assert_eq!(vec, vec!(~1, ~2, ~3, ~4));
916 pub fn push_all_move(&mut self, other: Vec<T>) {
917 for element in other.move_iter() {
922 /// Returns a mutable slice of `self` between `start` and `end`.
926 /// Fails when `start` or `end` point outside the bounds of `self`, or when
932 /// let mut vec = vec!(1, 2, 3, 4);
933 /// assert!(vec.mut_slice(0, 2) == [1, 2]);
936 pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint)
938 self.as_mut_slice().mut_slice(start, end)
941 /// Reverse the order of elements in a vector, in place.
946 /// let mut v = vec!(1, 2, 3);
948 /// assert_eq!(v, vec!(3, 2, 1));
951 pub fn reverse(&mut self) {
952 self.as_mut_slice().reverse()
955 /// Returns a slice of `self` from `start` to the end of the vec.
959 /// Fails when `start` points outside the bounds of self.
964 /// let vec = vec!(1, 2, 3);
965 /// assert!(vec.slice_from(1) == [2, 3]);
968 pub fn slice_from<'a>(&'a self, start: uint) -> &'a [T] {
969 self.as_slice().slice_from(start)
972 /// Returns a slice of self from the start of the vec to `end`.
976 /// Fails when `end` points outside the bounds of self.
981 /// let vec = vec!(1, 2, 3);
982 /// assert!(vec.slice_to(2) == [1, 2]);
985 pub fn slice_to<'a>(&'a self, end: uint) -> &'a [T] {
986 self.as_slice().slice_to(end)
989 /// Returns a slice containing all but the last element of the vector.
993 /// Fails if the vector is empty
995 pub fn init<'a>(&'a self) -> &'a [T] {
996 self.slice(0, self.len() - 1)
1000 /// Returns an unsafe pointer to the vector's buffer.
1002 /// The caller must ensure that the vector outlives the pointer this
1003 /// function returns, or else it will end up pointing to garbage.
1005 /// Modifying the vector may cause its buffer to be reallocated, which
1006 /// would also make any pointers to it invalid.
1008 pub fn as_ptr(&self) -> *T {
1009 self.as_slice().as_ptr()
1012 /// Returns a mutable unsafe pointer to the vector's buffer.
1014 /// The caller must ensure that the vector outlives the pointer this
1015 /// function returns, or else it will end up pointing to garbage.
1017 /// Modifying the vector may cause its buffer to be reallocated, which
1018 /// would also make any pointers to it invalid.
1020 pub fn as_mut_ptr(&mut self) -> *mut T {
1021 self.as_mut_slice().as_mut_ptr()
1025 impl<T:TotalOrd> Vec<T> {
1026 /// Sorts the vector in place.
1028 /// This sort is `O(n log n)` worst-case and stable, but allocates
1029 /// approximately `2 * n`, where `n` is the length of `self`.
1034 /// let mut vec = vec!(3i, 1, 2);
1036 /// assert_eq!(vec, vec!(1, 2, 3));
1038 pub fn sort(&mut self) {
1039 self.as_mut_slice().sort()
1043 impl<T> Mutable for Vec<T> {
1045 fn clear(&mut self) {
1051 /// Return true if a vector contains an element with the given value
1056 /// let vec = vec!(1, 2, 3);
1057 /// assert!(vec.contains(&1));
1059 pub fn contains(&self, x: &T) -> bool {
1060 self.as_slice().contains(x)
1063 /// Remove consecutive repeated elements in the vector.
1065 /// If the vector is sorted, this removes all duplicates.
1070 /// let mut vec = vec!(1, 2, 2, 3, 2);
1072 /// assert_eq!(vec, vec!(1, 2, 3, 2));
1074 pub fn dedup(&mut self) {
1076 // Although we have a mutable reference to `self`, we cannot make
1077 // *arbitrary* changes. The `Eq` comparisons could fail, so we
1078 // must ensure that the vector is in a valid state at all time.
1080 // The way that we handle this is by using swaps; we iterate
1081 // over all the elements, swapping as we go so that at the end
1082 // the elements we wish to keep are in the front, and those we
1083 // wish to reject are at the back. We can then truncate the
1084 // vector. This operation is still O(n).
1086 // Example: We start in this state, where `r` represents "next
1087 // read" and `w` represents "next_write`.
1090 // +---+---+---+---+---+---+
1091 // | 0 | 1 | 1 | 2 | 3 | 3 |
1092 // +---+---+---+---+---+---+
1095 // Comparing self[r] against self[w-1], tis is not a duplicate, so
1096 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1097 // r and w, leaving us with:
1100 // +---+---+---+---+---+---+
1101 // | 0 | 1 | 1 | 2 | 3 | 3 |
1102 // +---+---+---+---+---+---+
1105 // Comparing self[r] against self[w-1], this value is a duplicate,
1106 // so we increment `r` but leave everything else unchanged:
1109 // +---+---+---+---+---+---+
1110 // | 0 | 1 | 1 | 2 | 3 | 3 |
1111 // +---+---+---+---+---+---+
1114 // Comparing self[r] against self[w-1], this is not a duplicate,
1115 // so swap self[r] and self[w] and advance r and w:
1118 // +---+---+---+---+---+---+
1119 // | 0 | 1 | 2 | 1 | 3 | 3 |
1120 // +---+---+---+---+---+---+
1123 // Not a duplicate, repeat:
1126 // +---+---+---+---+---+---+
1127 // | 0 | 1 | 2 | 3 | 1 | 3 |
1128 // +---+---+---+---+---+---+
1131 // Duplicate, advance r. End of vec. Truncate to w.
1133 let ln = self.len();
1134 if ln < 1 { return; }
1136 // Avoid bounds checks by using unsafe pointers.
1137 let p = self.as_mut_slice().as_mut_ptr();
1142 let p_r = p.offset(r as int);
1143 let p_wm1 = p.offset((w - 1) as int);
1146 let p_w = p_wm1.offset(1);
1147 mem::swap(&mut *p_r, &mut *p_w);
1159 impl<T> Vector<T> for Vec<T> {
1160 /// Work with `self` as a slice.
1165 /// fn foo(slice: &[int]) {}
1167 /// let vec = vec!(1, 2);
1168 /// foo(vec.as_slice());
1171 fn as_slice<'a>(&'a self) -> &'a [T] {
1172 let slice = Slice { data: self.ptr as *T, len: self.len };
1173 unsafe { transmute(slice) }
1177 /// Iterates over the `second` vector, copying each element and appending it to
1178 /// the `first`. Afterwards, the `first` is then returned for use again.
1183 /// let vec = vec!(1, 2);
1184 /// let vec = std::vec::append(vec, [3, 4]);
1185 /// assert_eq!(vec, vec!(1, 2, 3, 4));
1188 pub fn append<T:Clone>(mut first: Vec<T>, second: &[T]) -> Vec<T> {
1189 first.push_all(second);
1193 /// Appends one element to the vector provided. The vector itself is then
1194 /// returned for use again.
1199 /// let vec = vec!(1, 2);
1200 /// let vec = std::vec::append_one(vec, 3);
1201 /// assert_eq!(vec, vec!(1, 2, 3));
1204 pub fn append_one<T>(mut lhs: Vec<T>, x: T) -> Vec<T> {
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]).
1215 for x in self.as_mut_slice().iter() {
1218 free(self.ptr as *mut c_void)
1223 impl<T> Default for Vec<T> {
1224 fn default() -> Vec<T> {
1229 impl<T:fmt::Show> fmt::Show for Vec<T> {
1230 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1231 self.as_slice().fmt(f)
1235 /// An iterator that moves out of a vector.
1236 pub struct MoveItems<T> {
1237 priv allocation: *mut c_void, // the block of memory allocated for the vector
1238 priv iter: Items<'static, T>
1241 impl<T> Iterator<T> for MoveItems<T> {
1243 fn next(&mut self) -> Option<T> {
1245 self.iter.next().map(|x| ptr::read(x))
1250 fn size_hint(&self) -> (uint, Option<uint>) {
1251 self.iter.size_hint()
1255 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
1257 fn next_back(&mut self) -> Option<T> {
1259 self.iter.next_back().map(|x| ptr::read(x))
1264 #[unsafe_destructor]
1265 impl<T> Drop for MoveItems<T> {
1266 fn drop(&mut self) {
1267 // destroy the remaining elements
1270 free(self.allocation)
1278 use iter::{Iterator, range, Extendable};
1279 use mem::{drop, size_of};
1281 use option::{Some, None};
1285 fn test_small_vec_struct() {
1286 assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1290 fn test_double_drop() {
1296 struct DropCounter<'a> {
1300 #[unsafe_destructor]
1301 impl<'a> Drop for DropCounter<'a> {
1302 fn drop(&mut self) {
1307 let mut count_x @ mut count_y = 0;
1309 let mut tv = TwoVec {
1313 tv.x.push(DropCounter {count: &mut count_x});
1314 tv.y.push(DropCounter {count: &mut count_y});
1316 // If Vec had a drop flag, here is where it would be zeroed.
1317 // Instead, it should rely on its internal state to prevent
1318 // doing anything significant when dropped multiple times.
1321 // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1324 assert_eq!(count_x, 1);
1325 assert_eq!(count_y, 1);
1329 fn test_reserve_additional() {
1330 let mut v = Vec::new();
1331 assert_eq!(v.capacity(), 0);
1333 v.reserve_additional(2);
1334 assert!(v.capacity() >= 2);
1336 for i in range(0, 16) {
1340 assert!(v.capacity() >= 16);
1341 v.reserve_additional(16);
1342 assert!(v.capacity() >= 32);
1346 v.reserve_additional(16);
1347 assert!(v.capacity() >= 33)
1352 let mut v = Vec::new();
1353 let mut w = Vec::new();
1355 v.extend(&mut range(0, 3));
1356 for i in range(0, 3) { w.push(i) }
1360 v.extend(&mut range(3, 10));
1361 for i in range(3, 10) { w.push(i) }