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 /// Create a `Vec<T>` directly from the raw constituents.
126 /// This is highly unsafe:
128 /// - if `ptr` is null, then `length` and `capacity` should be 0
129 /// - `ptr` must point to an allocation of size `capacity`
130 /// - there must be `length` valid instances of type `T` at the
131 /// beginning of that allocation
132 /// - `ptr` must be allocated by the default `Vec` allocator
133 pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut T) -> Vec<T> {
134 Vec { len: length, cap: capacity, ptr: ptr }
137 /// Consumes the `Vec`, partitioning it based on a predcate.
139 /// Partitions the `Vec` into two `Vec`s `(A,B)`, where all elements of `A`
140 /// satisfy `f` and all elements of `B` do not. The order of elements is
146 /// let vec = vec!(1, 2, 3, 4);
147 /// let (even, odd) = vec.partition(|&n| n % 2 == 0);
148 /// assert_eq!(even, vec!(2, 4));
149 /// assert_eq!(odd, vec!(1, 3));
152 pub fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
153 let mut lefts = Vec::new();
154 let mut rights = Vec::new();
156 for elt in self.move_iter() {
168 impl<T: Clone> Vec<T> {
169 /// Constructs a `Vec` by cloning elements of a slice.
174 /// # use std::vec::Vec;
175 /// let slice = [1, 2, 3];
176 /// let vec = Vec::from_slice(slice);
178 pub fn from_slice(values: &[T]) -> Vec<T> {
179 values.iter().map(|x| x.clone()).collect()
182 /// Constructs a `Vec` with copies of a value.
184 /// Creates a `Vec` with `length` copies of `value`.
188 /// # use std::vec::Vec;
189 /// let vec = Vec::from_elem(3, "hi");
190 /// println!("{}", vec); // prints [hi, hi, hi]
192 pub fn from_elem(length: uint, value: T) -> Vec<T> {
194 let mut xs = Vec::with_capacity(length);
195 while xs.len < length {
196 move_val_init(xs.as_mut_slice().unsafe_mut_ref(xs.len), value.clone());
203 /// Appends all elements in a slice to the `Vec`.
205 /// Iterates over the slice `other`, clones each element, and then appends
206 /// it to this `Vec`. The `other` vector is traversed in-order.
211 /// let mut vec = vec!(1);
212 /// vec.push_all([2, 3, 4]);
213 /// assert_eq!(vec, vec!(1, 2, 3, 4));
216 pub fn push_all(&mut self, other: &[T]) {
217 for element in other.iter() {
218 self.push((*element).clone())
222 /// Grows the `Vec` in-place.
224 /// Adds `n` copies of `value` to the `Vec`.
229 /// let mut vec = vec!("hello");
230 /// vec.grow(2, & &"world");
231 /// assert_eq!(vec, vec!("hello", "world", "world"));
233 pub fn grow(&mut self, n: uint, value: &T) {
234 let new_len = self.len() + n;
235 self.reserve(new_len);
236 let mut i: uint = 0u;
239 self.push((*value).clone());
244 /// Sets the value of a vector element at a given index, growing the vector
247 /// Sets the element at position `index` to `value`. If `index` is past the
248 /// end of the vector, expands the vector by replicating `initval` to fill
249 /// the intervening space.
254 /// let mut vec = vec!("a", "b", "c");
255 /// vec.grow_set(1, & &"fill", "d");
256 /// vec.grow_set(4, & &"fill", "e");
257 /// assert_eq!(vec, vec!("a", "d", "c", "fill", "e"));
259 pub fn grow_set(&mut self, index: uint, initval: &T, value: T) {
262 self.grow(index - l + 1u, initval);
264 *self.get_mut(index) = value;
267 /// Partitions a vector based on a predcate.
269 /// Clones the elements of the vector, partitioning them into two `Vec`s
270 /// `(A,B)`, where all elements of `A` satisfy `f` and all elements of `B`
271 /// do not. The order of elements is preserved.
276 /// let vec = vec!(1, 2, 3, 4);
277 /// let (even, odd) = vec.partitioned(|&n| n % 2 == 0);
278 /// assert_eq!(even, vec!(2, 4));
279 /// assert_eq!(odd, vec!(1, 3));
281 pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
282 let mut lefts = Vec::new();
283 let mut rights = Vec::new();
285 for elt in self.iter() {
287 lefts.push(elt.clone());
289 rights.push(elt.clone());
297 impl<T:Clone> Clone for Vec<T> {
298 fn clone(&self) -> Vec<T> {
299 let mut vector = Vec::with_capacity(self.len());
300 for element in self.iter() {
301 vector.push((*element).clone())
307 impl<T> FromIterator<T> for Vec<T> {
308 fn from_iterator<I:Iterator<T>>(iterator: &mut I) -> Vec<T> {
309 let (lower, _) = iterator.size_hint();
310 let mut vector = Vec::with_capacity(lower);
311 for element in *iterator {
318 impl<T> Extendable<T> for Vec<T> {
319 fn extend<I: Iterator<T>>(&mut self, iterator: &mut I) {
320 let (lower, _) = iterator.size_hint();
321 self.reserve_additional(lower);
322 for element in *iterator {
328 impl<T: Eq> Eq for Vec<T> {
330 fn eq(&self, other: &Vec<T>) -> bool {
331 self.as_slice() == other.as_slice()
335 impl<T: Ord> Ord for Vec<T> {
337 fn lt(&self, other: &Vec<T>) -> bool {
338 self.as_slice() < other.as_slice()
342 impl<T: TotalEq> TotalEq for Vec<T> {}
344 impl<T: TotalOrd> TotalOrd for Vec<T> {
346 fn cmp(&self, other: &Vec<T>) -> Ordering {
347 self.as_slice().cmp(&other.as_slice())
351 impl<T> Container for Vec<T> {
353 fn len(&self) -> uint {
359 /// Returns the number of elements the vector can hold without
365 /// # use std::vec::Vec;
366 /// let vec: Vec<int> = Vec::with_capacity(10);
367 /// assert_eq!(vec.capacity(), 10);
370 pub fn capacity(&self) -> uint {
374 /// Reserves capacity for at least `n` additional elements in the given
379 /// Fails if the new capacity overflows `uint`.
384 /// # use std::vec::Vec;
385 /// let mut vec: Vec<int> = vec!(1);
386 /// vec.reserve_additional(10);
387 /// assert!(vec.capacity() >= 11);
389 pub fn reserve_additional(&mut self, extra: uint) {
390 if self.cap - self.len < extra {
391 match self.len.checked_add(&extra) {
392 None => fail!("Vec::reserve_additional: `uint` overflow"),
393 Some(new_cap) => self.reserve(new_cap)
398 /// Reserves capacity for at least `n` elements in the given vector.
400 /// This function will over-allocate in order to amortize the allocation
401 /// costs in scenarios where the caller may need to repeatedly reserve
402 /// additional space.
404 /// If the capacity for `self` is already equal to or greater than the
405 /// requested capacity, then no action is taken.
410 /// let mut vec = vec!(1, 2, 3);
412 /// assert!(vec.capacity() >= 10);
414 pub fn reserve(&mut self, capacity: uint) {
415 if capacity >= self.len {
416 self.reserve_exact(num::next_power_of_two(capacity))
420 /// Reserves capacity for exactly `capacity` elements in the given vector.
422 /// If the capacity for `self` is already equal to or greater than the
423 /// requested capacity, then no action is taken.
428 /// # use std::vec::Vec;
429 /// let mut vec: Vec<int> = Vec::with_capacity(10);
430 /// vec.reserve_exact(11);
431 /// assert_eq!(vec.capacity(), 11);
433 pub fn reserve_exact(&mut self, capacity: uint) {
434 if capacity >= self.len {
435 let size = capacity.checked_mul(&size_of::<T>()).expect("capacity overflow");
438 self.ptr = realloc_raw(self.ptr as *mut u8, size) as *mut T;
443 /// Shrink the capacity of the vector to match the length
448 /// let mut vec = vec!(1, 2, 3);
449 /// vec.shrink_to_fit();
450 /// assert_eq!(vec.capacity(), vec.len());
452 pub fn shrink_to_fit(&mut self) {
454 unsafe { free(self.ptr as *mut c_void) };
456 self.ptr = 0 as *mut T;
459 // Overflow check is unnecessary as the vector is already at least this large.
460 self.ptr = realloc_raw(self.ptr as *mut u8, self.len * size_of::<T>()) as *mut T;
466 /// Remove the last element from a vector and return it, or `None` if it is
472 /// let mut vec = vec!(1, 2, 3);
473 /// assert_eq!(vec.pop(), Some(3));
474 /// assert_eq!(vec, vec!(1, 2));
477 pub fn pop(&mut self) -> Option<T> {
483 Some(ptr::read(self.as_slice().unsafe_ref(self.len())))
488 /// Append an element to a vector.
492 /// Fails if the number of elements in the vector overflows a `uint`.
497 /// let mut vec = vec!(1, 2);
499 /// assert_eq!(vec, vec!(1, 2, 3));
502 pub fn push(&mut self, value: T) {
503 if self.len == self.cap {
504 if self.cap == 0 { self.cap += 2 }
505 let old_size = self.cap * size_of::<T>();
506 self.cap = self.cap * 2;
507 let size = old_size * 2;
508 if old_size > size { fail!("capacity overflow") }
510 self.ptr = realloc_raw(self.ptr as *mut u8, size) as *mut T;
515 let end = (self.ptr as *T).offset(self.len as int) as *mut T;
516 move_val_init(&mut *end, value);
521 /// Shorten a vector, dropping excess elements.
523 /// If `len` is greater than the vector's current length, this has no
529 /// let mut vec = vec!(1, 2, 3, 4);
531 /// assert_eq!(vec, vec!(1, 2));
533 pub fn truncate(&mut self, len: uint) {
536 // drop any extra elements
538 ptr::read(self.as_slice().unsafe_ref(i));
545 /// Work with `self` as a mutable slice.
550 /// fn foo(slice: &mut [int]) {}
552 /// let mut vec = vec!(1, 2);
553 /// foo(vec.as_mut_slice());
556 pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
557 let slice = Slice { data: self.ptr as *T, len: self.len };
558 unsafe { transmute(slice) }
561 /// Creates a consuming iterator, that is, one that moves each
562 /// value out of the vector (from start to end). The vector cannot
563 /// be used after calling this.
568 /// let v = vec!(~"a", ~"b");
569 /// for s in v.move_iter() {
570 /// // s has type ~str, not &~str
571 /// println!("{}", s);
575 pub fn move_iter(self) -> MoveItems<T> {
577 let iter = transmute(self.as_slice().iter());
578 let ptr = self.ptr as *mut c_void;
580 MoveItems { allocation: ptr, iter: iter }
585 /// Sets the length of a vector.
587 /// This will explicitly set the size of the vector, without actually
588 /// modifying its buffers, so it is up to the caller to ensure that the
589 /// vector is actually the specified size.
591 pub unsafe fn set_len(&mut self, len: uint) {
595 /// Returns a reference to the value at index `index`.
599 /// Fails if `index` is out of bounds
604 /// let vec = vec!(1, 2, 3);
605 /// assert!(vec.get(1) == &2);
608 pub fn get<'a>(&'a self, index: uint) -> &'a T {
609 &self.as_slice()[index]
612 /// Returns a mutable reference to the value at index `index`.
616 /// Fails if `index` is out of bounds
621 /// let mut vec = vec!(1, 2, 3);
622 /// *vec.get_mut(1) = 4;
623 /// assert_eq!(vec, vec!(1, 4, 3));
626 pub fn get_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
627 &mut self.as_mut_slice()[index]
630 /// Returns an iterator over references to the elements of the vector in
636 /// let vec = vec!(1, 2, 3);
637 /// for num in vec.iter() {
638 /// println!("{}", *num);
642 pub fn iter<'a>(&'a self) -> Items<'a,T> {
643 self.as_slice().iter()
647 /// Returns an iterator over mutable references to the elements of the
653 /// let mut vec = vec!(1, 2, 3);
654 /// for num in vec.mut_iter() {
659 pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a,T> {
660 self.as_mut_slice().mut_iter()
663 /// Sort the vector, in place, using `compare` to compare elements.
665 /// This sort is `O(n log n)` worst-case and stable, but allocates
666 /// approximately `2 * n`, where `n` is the length of `self`.
671 /// let mut v = vec!(5i, 4, 1, 3, 2);
672 /// v.sort_by(|a, b| a.cmp(b));
673 /// assert_eq!(v, vec!(1, 2, 3, 4, 5));
675 /// // reverse sorting
676 /// v.sort_by(|a, b| b.cmp(a));
677 /// assert_eq!(v, vec!(5, 4, 3, 2, 1));
680 pub fn sort_by(&mut self, compare: |&T, &T| -> Ordering) {
681 self.as_mut_slice().sort_by(compare)
684 /// Returns a slice of `self` between `start` and `end`.
688 /// Fails when `start` or `end` point outside the bounds of `self`, or when
694 /// let vec = vec!(1, 2, 3, 4);
695 /// assert!(vec.slice(0, 2) == [1, 2]);
698 pub fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] {
699 self.as_slice().slice(start, end)
702 /// Returns a slice containing all but the first element of the vector.
706 /// Fails when the vector is empty.
711 /// let vec = vec!(1, 2, 3);
712 /// assert!(vec.tail() == [2, 3]);
715 pub fn tail<'a>(&'a self) -> &'a [T] {
716 self.as_slice().tail()
719 /// Returns all but the first `n' elements of a vector.
723 /// Fails when there are fewer than `n` elements in the vector.
728 /// let vec = vec!(1, 2, 3, 4);
729 /// assert!(vec.tailn(2) == [3, 4]);
732 pub fn tailn<'a>(&'a self, n: uint) -> &'a [T] {
733 self.as_slice().tailn(n)
736 /// Returns a reference to the last element of a vector, or `None` if it is
742 /// let vec = vec!(1, 2, 3);
743 /// assert!(vec.last() == Some(&3));
746 pub fn last<'a>(&'a self) -> Option<&'a T> {
747 self.as_slice().last()
750 /// Returns a mutable reference to the last element of a vector, or `None`
756 /// let mut vec = vec!(1, 2, 3);
757 /// *vec.mut_last().unwrap() = 4;
758 /// assert_eq!(vec, vec!(1, 2, 4));
761 pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
762 self.as_mut_slice().mut_last()
765 /// Remove an element from anywhere in the vector and return it, replacing
766 /// it with the last element. This does not preserve ordering, but is O(1).
768 /// Returns `None` if `index` is out of bounds.
772 /// let mut v = vec!(~"foo", ~"bar", ~"baz", ~"qux");
774 /// assert_eq!(v.swap_remove(1), Some(~"bar"));
775 /// assert_eq!(v, vec!(~"foo", ~"qux", ~"baz"));
777 /// assert_eq!(v.swap_remove(0), Some(~"foo"));
778 /// assert_eq!(v, vec!(~"baz", ~"qux"));
780 /// assert_eq!(v.swap_remove(2), None);
783 pub fn swap_remove(&mut self, index: uint) -> Option<T> {
784 let length = self.len();
785 if index < length - 1 {
786 self.as_mut_slice().swap(index, length - 1);
787 } else if index >= length {
793 /// Prepend an element to the vector.
797 /// This is an O(n) operation as it requires copying every element in the
803 /// let mut vec = vec!(1, 2, 3);
805 /// assert_eq!(vec, vec!(4, 1, 2, 3));
808 pub fn unshift(&mut self, element: T) {
809 self.insert(0, element)
812 /// Removes the first element from a vector and returns it, or `None` if
813 /// the vector is empty.
817 /// This is an O(n) operation as it requires copying every element in the
823 /// let mut vec = vec!(1, 2, 3);
824 /// assert!(vec.shift() == Some(1));
825 /// assert_eq!(vec, vec!(2, 3));
828 pub fn shift(&mut self) -> Option<T> {
832 /// Insert an element at position `index` within the vector, shifting all
833 /// elements after position i one position to the right.
837 /// Fails if `index` is out of bounds of the vector.
842 /// let mut vec = vec!(1, 2, 3);
843 /// vec.insert(1, 4);
844 /// assert_eq!(vec, vec!(1, 4, 2, 3));
846 pub fn insert(&mut self, index: uint, element: T) {
847 let len = self.len();
848 assert!(index <= len);
849 // space for the new element
850 self.reserve(len + 1);
852 unsafe { // infallible
853 // The spot to put the new value
855 let p = self.as_mut_ptr().offset(index as int);
856 // Shift everything over to make space. (Duplicating the
857 // `index`th element into two consecutive places.)
858 ptr::copy_memory(p.offset(1), &*p, len - index);
859 // Write it in, overwriting the first copy of the `index`th
861 move_val_init(&mut *p, element);
863 self.set_len(len + 1);
867 /// Remove and return the element at position `index` within the vector,
868 /// shifting all elements after position `index` one position to the left.
869 /// Returns `None` if `i` is out of bounds.
874 /// let mut v = vec!(1, 2, 3);
875 /// assert_eq!(v.remove(1), Some(2));
876 /// assert_eq!(v, vec!(1, 3));
878 /// assert_eq!(v.remove(4), None);
879 /// // v is unchanged:
880 /// assert_eq!(v, vec!(1, 3));
882 pub fn remove(&mut self, index: uint) -> Option<T> {
883 let len = self.len();
885 unsafe { // infallible
888 // the place we are taking from.
889 let ptr = self.as_mut_ptr().offset(index as int);
890 // copy it out, unsafely having a copy of the value on
891 // the stack and in the vector at the same time.
892 ret = Some(ptr::read(ptr as *T));
894 // Shift everything down to fill in that spot.
895 ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
897 self.set_len(len - 1);
905 ///Apply a function to each element of a vector and return the results.
907 #[deprecated="Use `xs.iter().map(closure)` instead."]
908 pub fn map<U>(&self, f: |t: &T| -> U) -> Vec<U> {
909 self.iter().map(f).collect()
912 /// Takes ownership of the vector `other`, moving all elements into
913 /// the current vector. This does not copy any elements, and it is
914 /// illegal to use the `other` vector after calling this method
915 /// (because it is moved here).
920 /// let mut vec = vec!(~1);
921 /// vec.push_all_move(vec!(~2, ~3, ~4));
922 /// assert_eq!(vec, vec!(~1, ~2, ~3, ~4));
924 pub fn push_all_move(&mut self, other: Vec<T>) {
925 for element in other.move_iter() {
930 /// Returns a mutable slice of `self` between `start` and `end`.
934 /// Fails when `start` or `end` point outside the bounds of `self`, or when
940 /// let mut vec = vec!(1, 2, 3, 4);
941 /// assert!(vec.mut_slice(0, 2) == [1, 2]);
944 pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint)
946 self.as_mut_slice().mut_slice(start, end)
949 /// Returns a mutable slice of self from `start` to the end of the vec.
953 /// Fails when `start` points outside the bounds of self.
958 /// let mut vec = vec!(1, 2, 3, 4);
959 /// assert!(vec.mut_slice_from(2) == [3, 4]);
962 pub fn mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] {
963 self.as_mut_slice().mut_slice_from(start)
966 /// Returns a mutable slice of self from the start of the vec to `end`.
970 /// Fails when `end` points outside the bounds of self.
975 /// let mut vec = vec!(1, 2, 3, 4);
976 /// assert!(vec.mut_slice_to(2) == [1, 2]);
979 pub fn mut_slice_to<'a>(&'a mut self, end: uint) -> &'a mut [T] {
980 self.as_mut_slice().mut_slice_to(end)
983 /// Returns a pair of mutable slices that divides the vec at an index.
985 /// The first will contain all indices from `[0, mid)` (excluding
986 /// the index `mid` itself) and the second will contain all
987 /// indices from `[mid, len)` (excluding the index `len` itself).
991 /// Fails if `mid > len`.
996 /// let mut vec = vec!(1, 2, 3, 4, 5, 6);
998 /// // scoped to restrict the lifetime of the borrows
1000 /// let (left, right) = vec.mut_split_at(0);
1001 /// assert!(left == &mut []);
1002 /// assert!(right == &mut [1, 2, 3, 4, 5, 6]);
1006 /// let (left, right) = vec.mut_split_at(2);
1007 /// assert!(left == &mut [1, 2]);
1008 /// assert!(right == &mut [3, 4, 5, 6]);
1012 /// let (left, right) = vec.mut_split_at(6);
1013 /// assert!(left == &mut [1, 2, 3, 4, 5, 6]);
1014 /// assert!(right == &mut []);
1018 pub fn mut_split_at<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
1019 self.as_mut_slice().mut_split_at(mid)
1022 /// Reverse the order of elements in a vector, in place.
1027 /// let mut v = vec!(1, 2, 3);
1029 /// assert_eq!(v, vec!(3, 2, 1));
1032 pub fn reverse(&mut self) {
1033 self.as_mut_slice().reverse()
1036 /// Returns a slice of `self` from `start` to the end of the vec.
1040 /// Fails when `start` points outside the bounds of self.
1045 /// let vec = vec!(1, 2, 3);
1046 /// assert!(vec.slice_from(1) == [2, 3]);
1049 pub fn slice_from<'a>(&'a self, start: uint) -> &'a [T] {
1050 self.as_slice().slice_from(start)
1053 /// Returns a slice of self from the start of the vec to `end`.
1057 /// Fails when `end` points outside the bounds of self.
1062 /// let vec = vec!(1, 2, 3);
1063 /// assert!(vec.slice_to(2) == [1, 2]);
1066 pub fn slice_to<'a>(&'a self, end: uint) -> &'a [T] {
1067 self.as_slice().slice_to(end)
1070 /// Returns a slice containing all but the last element of the vector.
1074 /// Fails if the vector is empty
1076 pub fn init<'a>(&'a self) -> &'a [T] {
1077 self.slice(0, self.len() - 1)
1081 /// Returns an unsafe pointer to the vector's buffer.
1083 /// The caller must ensure that the vector outlives the pointer this
1084 /// function returns, or else it will end up pointing to garbage.
1086 /// Modifying the vector may cause its buffer to be reallocated, which
1087 /// would also make any pointers to it invalid.
1089 pub fn as_ptr(&self) -> *T {
1090 self.as_slice().as_ptr()
1093 /// Returns a mutable unsafe pointer to the vector's buffer.
1095 /// The caller must ensure that the vector outlives the pointer this
1096 /// function returns, or else it will end up pointing to garbage.
1098 /// Modifying the vector may cause its buffer to be reallocated, which
1099 /// would also make any pointers to it invalid.
1101 pub fn as_mut_ptr(&mut self) -> *mut T {
1102 self.as_mut_slice().as_mut_ptr()
1106 impl<T:TotalOrd> Vec<T> {
1107 /// Sorts the vector in place.
1109 /// This sort is `O(n log n)` worst-case and stable, but allocates
1110 /// approximately `2 * n`, where `n` is the length of `self`.
1115 /// let mut vec = vec!(3i, 1, 2);
1117 /// assert_eq!(vec, vec!(1, 2, 3));
1119 pub fn sort(&mut self) {
1120 self.as_mut_slice().sort()
1124 impl<T> Mutable for Vec<T> {
1126 fn clear(&mut self) {
1132 /// Return true if a vector contains an element with the given value
1137 /// let vec = vec!(1, 2, 3);
1138 /// assert!(vec.contains(&1));
1140 pub fn contains(&self, x: &T) -> bool {
1141 self.as_slice().contains(x)
1144 /// Remove consecutive repeated elements in the vector.
1146 /// If the vector is sorted, this removes all duplicates.
1151 /// let mut vec = vec!(1, 2, 2, 3, 2);
1153 /// assert_eq!(vec, vec!(1, 2, 3, 2));
1155 pub fn dedup(&mut self) {
1157 // Although we have a mutable reference to `self`, we cannot make
1158 // *arbitrary* changes. The `Eq` comparisons could fail, so we
1159 // must ensure that the vector is in a valid state at all time.
1161 // The way that we handle this is by using swaps; we iterate
1162 // over all the elements, swapping as we go so that at the end
1163 // the elements we wish to keep are in the front, and those we
1164 // wish to reject are at the back. We can then truncate the
1165 // vector. This operation is still O(n).
1167 // Example: We start in this state, where `r` represents "next
1168 // read" and `w` represents "next_write`.
1171 // +---+---+---+---+---+---+
1172 // | 0 | 1 | 1 | 2 | 3 | 3 |
1173 // +---+---+---+---+---+---+
1176 // Comparing self[r] against self[w-1], tis is not a duplicate, so
1177 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1178 // r and w, leaving us with:
1181 // +---+---+---+---+---+---+
1182 // | 0 | 1 | 1 | 2 | 3 | 3 |
1183 // +---+---+---+---+---+---+
1186 // Comparing self[r] against self[w-1], this value is a duplicate,
1187 // so we increment `r` but leave everything else unchanged:
1190 // +---+---+---+---+---+---+
1191 // | 0 | 1 | 1 | 2 | 3 | 3 |
1192 // +---+---+---+---+---+---+
1195 // Comparing self[r] against self[w-1], this is not a duplicate,
1196 // so swap self[r] and self[w] and advance r and w:
1199 // +---+---+---+---+---+---+
1200 // | 0 | 1 | 2 | 1 | 3 | 3 |
1201 // +---+---+---+---+---+---+
1204 // Not a duplicate, repeat:
1207 // +---+---+---+---+---+---+
1208 // | 0 | 1 | 2 | 3 | 1 | 3 |
1209 // +---+---+---+---+---+---+
1212 // Duplicate, advance r. End of vec. Truncate to w.
1214 let ln = self.len();
1215 if ln < 1 { return; }
1217 // Avoid bounds checks by using unsafe pointers.
1218 let p = self.as_mut_slice().as_mut_ptr();
1223 let p_r = p.offset(r as int);
1224 let p_wm1 = p.offset((w - 1) as int);
1227 let p_w = p_wm1.offset(1);
1228 mem::swap(&mut *p_r, &mut *p_w);
1240 impl<T> Vector<T> for Vec<T> {
1241 /// Work with `self` as a slice.
1246 /// fn foo(slice: &[int]) {}
1248 /// let vec = vec!(1, 2);
1249 /// foo(vec.as_slice());
1252 fn as_slice<'a>(&'a self) -> &'a [T] {
1253 let slice = Slice { data: self.ptr as *T, len: self.len };
1254 unsafe { transmute(slice) }
1258 /// Iterates over the `second` vector, copying each element and appending it to
1259 /// the `first`. Afterwards, the `first` is then returned for use again.
1264 /// let vec = vec!(1, 2);
1265 /// let vec = std::vec::append(vec, [3, 4]);
1266 /// assert_eq!(vec, vec!(1, 2, 3, 4));
1269 pub fn append<T:Clone>(mut first: Vec<T>, second: &[T]) -> Vec<T> {
1270 first.push_all(second);
1274 /// Appends one element to the vector provided. The vector itself is then
1275 /// returned for use again.
1280 /// let vec = vec!(1, 2);
1281 /// let vec = std::vec::append_one(vec, 3);
1282 /// assert_eq!(vec, vec!(1, 2, 3));
1285 pub fn append_one<T>(mut lhs: Vec<T>, x: T) -> Vec<T> {
1290 #[unsafe_destructor]
1291 impl<T> Drop for Vec<T> {
1292 fn drop(&mut self) {
1293 // This is (and should always remain) a no-op if the fields are
1294 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1296 for x in self.as_mut_slice().iter() {
1299 free(self.ptr as *mut c_void)
1304 impl<T> Default for Vec<T> {
1305 fn default() -> Vec<T> {
1310 impl<T:fmt::Show> fmt::Show for Vec<T> {
1311 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1312 self.as_slice().fmt(f)
1316 /// An iterator that moves out of a vector.
1317 pub struct MoveItems<T> {
1318 priv allocation: *mut c_void, // the block of memory allocated for the vector
1319 priv iter: Items<'static, T>
1322 impl<T> Iterator<T> for MoveItems<T> {
1324 fn next(&mut self) -> Option<T> {
1326 self.iter.next().map(|x| ptr::read(x))
1331 fn size_hint(&self) -> (uint, Option<uint>) {
1332 self.iter.size_hint()
1336 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
1338 fn next_back(&mut self) -> Option<T> {
1340 self.iter.next_back().map(|x| ptr::read(x))
1345 #[unsafe_destructor]
1346 impl<T> Drop for MoveItems<T> {
1347 fn drop(&mut self) {
1348 // destroy the remaining elements
1351 free(self.allocation)
1362 fn test_small_vec_struct() {
1363 assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1367 fn test_double_drop() {
1373 struct DropCounter<'a> {
1377 #[unsafe_destructor]
1378 impl<'a> Drop for DropCounter<'a> {
1379 fn drop(&mut self) {
1384 let mut count_x @ mut count_y = 0;
1386 let mut tv = TwoVec {
1390 tv.x.push(DropCounter {count: &mut count_x});
1391 tv.y.push(DropCounter {count: &mut count_y});
1393 // If Vec had a drop flag, here is where it would be zeroed.
1394 // Instead, it should rely on its internal state to prevent
1395 // doing anything significant when dropped multiple times.
1398 // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1401 assert_eq!(count_x, 1);
1402 assert_eq!(count_y, 1);
1406 fn test_reserve_additional() {
1407 let mut v = Vec::new();
1408 assert_eq!(v.capacity(), 0);
1410 v.reserve_additional(2);
1411 assert!(v.capacity() >= 2);
1413 for i in range(0, 16) {
1417 assert!(v.capacity() >= 16);
1418 v.reserve_additional(16);
1419 assert!(v.capacity() >= 32);
1423 v.reserve_additional(16);
1424 assert!(v.capacity() >= 33)
1429 let mut v = Vec::new();
1430 let mut w = Vec::new();
1432 v.extend(&mut range(0, 3));
1433 for i in range(0, 3) { w.push(i) }
1437 v.extend(&mut range(3, 10));
1438 for i in range(3, 10) { w.push(i) }
1444 fn test_mut_slice_from() {
1445 let mut values = Vec::from_slice([1u8,2,3,4,5]);
1447 let slice = values.mut_slice_from(2);
1448 assert!(slice == [3, 4, 5]);
1449 for p in slice.mut_iter() {
1454 assert!(values.as_slice() == [1, 2, 5, 6, 7]);
1458 fn test_mut_slice_to() {
1459 let mut values = Vec::from_slice([1u8,2,3,4,5]);
1461 let slice = values.mut_slice_to(2);
1462 assert!(slice == [1, 2]);
1463 for p in slice.mut_iter() {
1468 assert!(values.as_slice() == [2, 3, 3, 4, 5]);
1472 fn test_mut_split_at() {
1473 let mut values = Vec::from_slice([1u8,2,3,4,5]);
1475 let (left, right) = values.mut_split_at(2);
1476 assert!(left.slice(0, left.len()) == [1, 2]);
1477 for p in left.mut_iter() {
1481 assert!(right.slice(0, right.len()) == [3, 4, 5]);
1482 for p in right.mut_iter() {
1487 assert!(values == Vec::from_slice([2u8, 3, 5, 6, 7]));