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.
13 use cast::{forget, transmute};
15 use cmp::{Ord, Eq, Ordering, TotalEq, TotalOrd};
16 use container::{Container, Mutable};
19 use iter::{DoubleEndedIterator, FromIterator, Extendable, Iterator, range};
20 use libc::{free, c_void};
21 use mem::{size_of, move_val_init};
24 use num::{CheckedMul, CheckedAdd};
26 use option::{None, Option, Some};
29 use rt::global_heap::{malloc_raw, realloc_raw};
31 use slice::{ImmutableEqVector, ImmutableVector, Items, MutItems, MutableVector};
32 use slice::{MutableTotalOrdVector, OwnedVector, Vector};
33 use slice::{MutableVectorAllocating};
35 /// An owned, growable vector.
40 /// # use std::vec::Vec;
41 /// let mut vec = Vec::new();
45 /// assert_eq!(vec.len(), 2);
46 /// assert_eq!(vec.get(0), &1);
48 /// assert_eq!(vec.pop(), Some(2));
49 /// assert_eq!(vec.len(), 1);
52 /// The `vec!` macro is provided to make initialization more convenient:
55 /// let mut vec = vec!(1, 2, 3);
57 /// assert_eq!(vec, vec!(1, 2, 3, 4));
59 #[unsafe_no_drop_flag]
67 /// Constructs a new, empty `Vec`.
69 /// The vector will not allocate until elements are pushed onto it.
74 /// # use std::vec::Vec;
75 /// let mut vec: Vec<int> = Vec::new();
78 pub fn new() -> Vec<T> {
79 Vec { len: 0, cap: 0, ptr: 0 as *mut T }
82 /// Constructs a new, empty `Vec` with the specified capacity.
84 /// The vector will be able to hold exactly `capacity` elements without
85 /// reallocating. If `capacity` is 0, the vector will not allocate.
90 /// # use std::vec::Vec;
91 /// let vec: Vec<int> = Vec::with_capacity(10);
93 pub fn with_capacity(capacity: uint) -> Vec<T> {
97 let size = capacity.checked_mul(&size_of::<T>()).expect("capacity overflow");
98 let ptr = unsafe { malloc_raw(size) };
99 Vec { len: 0, cap: capacity, ptr: ptr as *mut T }
103 /// Creates and initializes a `Vec`.
105 /// Creates a `Vec` of size `length` and initializes the elements to the
106 /// value returned by the closure `op`.
111 /// # use std::vec::Vec;
112 /// let vec = Vec::from_fn(3, |idx| idx * 2);
113 /// 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 {
119 move_val_init(xs.as_mut_slice().unsafe_mut_ref(xs.len), op(xs.len));
126 /// Create a `Vec<T>` directly from the raw constituents.
128 /// This is highly unsafe:
130 /// - if `ptr` is null, then `length` and `capacity` should be 0
131 /// - `ptr` must point to an allocation of size `capacity`
132 /// - there must be `length` valid instances of type `T` at the
133 /// beginning of that allocation
134 /// - `ptr` must be allocated by the default `Vec` allocator
135 pub unsafe fn from_raw_parts(length: uint, capacity: uint, ptr: *mut T) -> Vec<T> {
136 Vec { len: length, cap: capacity, ptr: ptr }
139 /// Consumes the `Vec`, partitioning it based on a predicate.
141 /// Partitions the `Vec` into two `Vec`s `(A,B)`, where all elements of `A`
142 /// satisfy `f` and all elements of `B` do not. The order of elements is
148 /// let vec = vec!(1, 2, 3, 4);
149 /// let (even, odd) = vec.partition(|&n| n % 2 == 0);
150 /// assert_eq!(even, vec!(2, 4));
151 /// assert_eq!(odd, vec!(1, 3));
154 pub fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
155 let mut lefts = Vec::new();
156 let mut rights = Vec::new();
158 for elt in self.move_iter() {
170 impl<T: Clone> Vec<T> {
171 /// Iterates over the `second` vector, copying each element and appending it to
172 /// the `first`. Afterwards, the `first` is then returned for use again.
177 /// let vec = vec!(1, 2);
178 /// let vec = vec.append([3, 4]);
179 /// assert_eq!(vec, vec!(1, 2, 3, 4));
182 pub fn append(mut self, second: &[T]) -> Vec<T> {
183 self.push_all(second);
187 /// Constructs a `Vec` by cloning elements of a slice.
192 /// # use std::vec::Vec;
193 /// let slice = [1, 2, 3];
194 /// let vec = Vec::from_slice(slice);
196 pub fn from_slice(values: &[T]) -> Vec<T> {
197 values.iter().map(|x| x.clone()).collect()
200 /// Constructs a `Vec` with copies of a value.
202 /// Creates a `Vec` with `length` copies of `value`.
206 /// # use std::vec::Vec;
207 /// let vec = Vec::from_elem(3, "hi");
208 /// println!("{}", vec); // prints [hi, hi, hi]
210 pub fn from_elem(length: uint, value: T) -> Vec<T> {
212 let mut xs = Vec::with_capacity(length);
213 while xs.len < length {
214 move_val_init(xs.as_mut_slice().unsafe_mut_ref(xs.len), value.clone());
221 /// Appends all elements in a slice to the `Vec`.
223 /// Iterates over the slice `other`, clones each element, and then appends
224 /// it to this `Vec`. The `other` vector is traversed in-order.
229 /// let mut vec = vec!(1);
230 /// vec.push_all([2, 3, 4]);
231 /// assert_eq!(vec, vec!(1, 2, 3, 4));
234 pub fn push_all(&mut self, other: &[T]) {
235 self.extend(other.iter().map(|e| e.clone()));
238 /// Grows the `Vec` in-place.
240 /// Adds `n` copies of `value` to the `Vec`.
245 /// let mut vec = vec!("hello");
246 /// vec.grow(2, &("world"));
247 /// assert_eq!(vec, vec!("hello", "world", "world"));
249 pub fn grow(&mut self, n: uint, value: &T) {
250 let new_len = self.len() + n;
251 self.reserve(new_len);
252 let mut i: uint = 0u;
255 self.push((*value).clone());
260 /// Sets the value of a vector element at a given index, growing the vector
263 /// Sets the element at position `index` to `value`. If `index` is past the
264 /// end of the vector, expands the vector by replicating `initval` to fill
265 /// the intervening space.
270 /// let mut vec = vec!("a", "b", "c");
271 /// vec.grow_set(1, &("fill"), "d");
272 /// vec.grow_set(4, &("fill"), "e");
273 /// assert_eq!(vec, vec!("a", "d", "c", "fill", "e"));
275 pub fn grow_set(&mut self, index: uint, initval: &T, value: T) {
278 self.grow(index - l + 1u, initval);
280 *self.get_mut(index) = value;
283 /// Partitions a vector based on a predicate.
285 /// Clones the elements of the vector, partitioning them into two `Vec`s
286 /// `(A,B)`, where all elements of `A` satisfy `f` and all elements of `B`
287 /// do not. The order of elements is preserved.
292 /// let vec = vec!(1, 2, 3, 4);
293 /// let (even, odd) = vec.partitioned(|&n| n % 2 == 0);
294 /// assert_eq!(even, vec!(2, 4));
295 /// assert_eq!(odd, vec!(1, 3));
297 pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
298 let mut lefts = Vec::new();
299 let mut rights = Vec::new();
301 for elt in self.iter() {
303 lefts.push(elt.clone());
305 rights.push(elt.clone());
313 impl<T:Clone> Clone for Vec<T> {
314 fn clone(&self) -> Vec<T> {
316 let mut vector = Vec::with_capacity(len);
317 // Unsafe code so this can be optimised to a memcpy (or something
318 // similarly fast) when T is Copy. LLVM is easily confused, so any
319 // extra operations during the loop can prevent this optimisation
321 let this_slice = self.as_slice();
322 while vector.len < len {
325 vector.as_mut_slice().unsafe_mut_ref(vector.len),
326 this_slice.unsafe_ref(vector.len).clone());
334 fn clone_from(&mut self, other: &Vec<T>) {
335 // drop anything in self that will not be overwritten
336 if self.len() > other.len() {
337 self.truncate(other.len())
340 // reuse the contained values' allocations/resources.
341 for (place, thing) in self.mut_iter().zip(other.iter()) {
342 place.clone_from(thing)
345 // self.len <= other.len due to the truncate above, so the
346 // slice here is always in-bounds.
347 let len = self.len();
348 self.extend(other.slice_from(len).iter().map(|x| x.clone()));
352 impl<T> FromIterator<T> for Vec<T> {
353 fn from_iter<I:Iterator<T>>(mut iterator: I) -> Vec<T> {
354 let (lower, _) = iterator.size_hint();
355 let mut vector = Vec::with_capacity(lower);
356 for element in iterator {
363 impl<T> Extendable<T> for Vec<T> {
364 fn extend<I: Iterator<T>>(&mut self, mut iterator: I) {
365 let (lower, _) = iterator.size_hint();
366 self.reserve_additional(lower);
367 for element in iterator {
373 impl<T: Eq> Eq for Vec<T> {
375 fn eq(&self, other: &Vec<T>) -> bool {
376 self.as_slice() == other.as_slice()
380 impl<T: Ord> Ord for Vec<T> {
382 fn lt(&self, other: &Vec<T>) -> bool {
383 self.as_slice() < other.as_slice()
387 impl<T: TotalEq> TotalEq for Vec<T> {}
389 impl<T: TotalOrd> TotalOrd for Vec<T> {
391 fn cmp(&self, other: &Vec<T>) -> Ordering {
392 self.as_slice().cmp(&other.as_slice())
396 impl<T> Container for Vec<T> {
398 fn len(&self) -> uint {
404 /// Returns the number of elements the vector can hold without
410 /// # use std::vec::Vec;
411 /// let vec: Vec<int> = Vec::with_capacity(10);
412 /// assert_eq!(vec.capacity(), 10);
415 pub fn capacity(&self) -> uint {
419 /// Reserves capacity for at least `n` additional elements in the given
424 /// Fails if the new capacity overflows `uint`.
429 /// # use std::vec::Vec;
430 /// let mut vec: Vec<int> = vec!(1);
431 /// vec.reserve_additional(10);
432 /// assert!(vec.capacity() >= 11);
434 pub fn reserve_additional(&mut self, extra: uint) {
435 if self.cap - self.len < extra {
436 match self.len.checked_add(&extra) {
437 None => fail!("Vec::reserve_additional: `uint` overflow"),
438 Some(new_cap) => self.reserve(new_cap)
443 /// Reserves capacity for at least `n` elements in the given vector.
445 /// This function will over-allocate in order to amortize the allocation
446 /// costs in scenarios where the caller may need to repeatedly reserve
447 /// additional space.
449 /// If the capacity for `self` is already equal to or greater than the
450 /// requested capacity, then no action is taken.
455 /// let mut vec = vec!(1, 2, 3);
457 /// assert!(vec.capacity() >= 10);
459 pub fn reserve(&mut self, capacity: uint) {
460 if capacity >= self.len {
461 self.reserve_exact(num::next_power_of_two(capacity))
465 /// Reserves capacity for exactly `capacity` elements in the given vector.
467 /// If the capacity for `self` is already equal to or greater than the
468 /// requested capacity, then no action is taken.
473 /// # use std::vec::Vec;
474 /// let mut vec: Vec<int> = Vec::with_capacity(10);
475 /// vec.reserve_exact(11);
476 /// assert_eq!(vec.capacity(), 11);
478 pub fn reserve_exact(&mut self, capacity: uint) {
479 if capacity > self.cap {
480 let size = capacity.checked_mul(&size_of::<T>()).expect("capacity overflow");
483 self.ptr = realloc_raw(self.ptr as *mut u8, size) as *mut T;
488 /// Shrink the capacity of the vector to match the length
493 /// let mut vec = vec!(1, 2, 3);
494 /// vec.shrink_to_fit();
495 /// assert_eq!(vec.capacity(), vec.len());
497 pub fn shrink_to_fit(&mut self) {
499 unsafe { free(self.ptr as *mut c_void) };
501 self.ptr = 0 as *mut T;
504 // Overflow check is unnecessary as the vector is already at least this large.
505 self.ptr = realloc_raw(self.ptr as *mut u8, self.len * size_of::<T>()) as *mut T;
511 /// Remove the last element from a vector and return it, or `None` if it is
517 /// let mut vec = vec!(1, 2, 3);
518 /// assert_eq!(vec.pop(), Some(3));
519 /// assert_eq!(vec, vec!(1, 2));
522 pub fn pop(&mut self) -> Option<T> {
528 Some(ptr::read(self.as_slice().unsafe_ref(self.len())))
533 /// Append an element to a vector.
537 /// Fails if the number of elements in the vector overflows a `uint`.
542 /// let mut vec = vec!(1, 2);
544 /// assert_eq!(vec, vec!(1, 2, 3));
547 pub fn push(&mut self, value: T) {
548 if self.len == self.cap {
549 if self.cap == 0 { self.cap += 2 }
550 let old_size = self.cap * size_of::<T>();
551 self.cap = self.cap * 2;
552 let size = old_size * 2;
553 if old_size > size { fail!("capacity overflow") }
555 self.ptr = realloc_raw(self.ptr as *mut u8, size) as *mut T;
560 let end = (self.ptr as *T).offset(self.len as int) as *mut T;
561 move_val_init(&mut *end, value);
566 /// Appends one element to the vector provided. The vector itself is then
567 /// returned for use again.
572 /// let vec = vec!(1, 2);
573 /// let vec = vec.append_one(3);
574 /// assert_eq!(vec, vec!(1, 2, 3));
577 pub fn append_one(mut self, x: T) -> Vec<T> {
582 /// Shorten a vector, dropping excess elements.
584 /// If `len` is greater than the vector's current length, this has no
590 /// let mut vec = vec!(1, 2, 3, 4);
592 /// assert_eq!(vec, vec!(1, 2));
594 pub fn truncate(&mut self, len: uint) {
597 // drop any extra elements
599 ptr::read(self.as_slice().unsafe_ref(i));
606 /// Work with `self` as a mutable slice.
611 /// fn foo(slice: &mut [int]) {}
613 /// let mut vec = vec!(1, 2);
614 /// foo(vec.as_mut_slice());
617 pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
619 transmute(Slice { data: self.as_mut_ptr() as *T, len: self.len })
623 /// Creates a consuming iterator, that is, one that moves each
624 /// value out of the vector (from start to end). The vector cannot
625 /// be used after calling this.
630 /// let v = vec!("a".to_owned(), "b".to_owned());
631 /// for s in v.move_iter() {
632 /// // s has type ~str, not &~str
633 /// println!("{}", s);
637 pub fn move_iter(self) -> MoveItems<T> {
639 let iter = transmute(self.as_slice().iter());
640 let ptr = self.ptr as *mut c_void;
642 MoveItems { allocation: ptr, iter: iter }
647 /// Sets the length of a vector.
649 /// This will explicitly set the size of the vector, without actually
650 /// modifying its buffers, so it is up to the caller to ensure that the
651 /// vector is actually the specified size.
653 pub unsafe fn set_len(&mut self, len: uint) {
657 /// Returns a reference to the value at index `index`.
661 /// Fails if `index` is out of bounds
666 /// let vec = vec!(1, 2, 3);
667 /// assert!(vec.get(1) == &2);
670 pub fn get<'a>(&'a self, index: uint) -> &'a T {
671 &self.as_slice()[index]
674 /// Returns a mutable reference to the value at index `index`.
678 /// Fails if `index` is out of bounds
683 /// let mut vec = vec!(1, 2, 3);
684 /// *vec.get_mut(1) = 4;
685 /// assert_eq!(vec, vec!(1, 4, 3));
688 pub fn get_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
689 &mut self.as_mut_slice()[index]
692 /// Returns an iterator over references to the elements of the vector in
698 /// let vec = vec!(1, 2, 3);
699 /// for num in vec.iter() {
700 /// println!("{}", *num);
704 pub fn iter<'a>(&'a self) -> Items<'a,T> {
705 self.as_slice().iter()
709 /// Returns an iterator over mutable references to the elements of the
715 /// let mut vec = vec!(1, 2, 3);
716 /// for num in vec.mut_iter() {
721 pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a,T> {
722 self.as_mut_slice().mut_iter()
725 /// Sort the vector, in place, using `compare` to compare elements.
727 /// This sort is `O(n log n)` worst-case and stable, but allocates
728 /// approximately `2 * n`, where `n` is the length of `self`.
733 /// let mut v = vec!(5i, 4, 1, 3, 2);
734 /// v.sort_by(|a, b| a.cmp(b));
735 /// assert_eq!(v, vec!(1, 2, 3, 4, 5));
737 /// // reverse sorting
738 /// v.sort_by(|a, b| b.cmp(a));
739 /// assert_eq!(v, vec!(5, 4, 3, 2, 1));
742 pub fn sort_by(&mut self, compare: |&T, &T| -> Ordering) {
743 self.as_mut_slice().sort_by(compare)
746 /// Returns a slice of `self` between `start` and `end`.
750 /// Fails when `start` or `end` point outside the bounds of `self`, or when
756 /// let vec = vec!(1, 2, 3, 4);
757 /// assert!(vec.slice(0, 2) == [1, 2]);
760 pub fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] {
761 self.as_slice().slice(start, end)
764 /// Returns a slice containing all but the first element of the vector.
768 /// Fails when the vector is empty.
773 /// let vec = vec!(1, 2, 3);
774 /// assert!(vec.tail() == [2, 3]);
777 pub fn tail<'a>(&'a self) -> &'a [T] {
778 self.as_slice().tail()
781 /// Returns all but the first `n' elements of a vector.
785 /// Fails when there are fewer than `n` elements in the vector.
790 /// let vec = vec!(1, 2, 3, 4);
791 /// assert!(vec.tailn(2) == [3, 4]);
794 pub fn tailn<'a>(&'a self, n: uint) -> &'a [T] {
795 self.as_slice().tailn(n)
798 /// Returns a reference to the last element of a vector, or `None` if it is
804 /// let vec = vec!(1, 2, 3);
805 /// assert!(vec.last() == Some(&3));
808 pub fn last<'a>(&'a self) -> Option<&'a T> {
809 self.as_slice().last()
812 /// Returns a mutable reference to the last element of a vector, or `None`
818 /// let mut vec = vec!(1, 2, 3);
819 /// *vec.mut_last().unwrap() = 4;
820 /// assert_eq!(vec, vec!(1, 2, 4));
823 pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
824 self.as_mut_slice().mut_last()
827 /// Remove an element from anywhere in the vector and return it, replacing
828 /// it with the last element. This does not preserve ordering, but is O(1).
830 /// Returns `None` if `index` is out of bounds.
834 /// let mut v = vec!("foo".to_owned(), "bar".to_owned(), "baz".to_owned(), "qux".to_owned());
836 /// assert_eq!(v.swap_remove(1), Some("bar".to_owned()));
837 /// assert_eq!(v, vec!("foo".to_owned(), "qux".to_owned(), "baz".to_owned()));
839 /// assert_eq!(v.swap_remove(0), Some("foo".to_owned()));
840 /// assert_eq!(v, vec!("baz".to_owned(), "qux".to_owned()));
842 /// assert_eq!(v.swap_remove(2), None);
845 pub fn swap_remove(&mut self, index: uint) -> Option<T> {
846 let length = self.len();
847 if index < length - 1 {
848 self.as_mut_slice().swap(index, length - 1);
849 } else if index >= length {
855 /// Prepend an element to the vector.
859 /// This is an O(n) operation as it requires copying every element in the
865 /// let mut vec = vec!(1, 2, 3);
867 /// assert_eq!(vec, vec!(4, 1, 2, 3));
870 pub fn unshift(&mut self, element: T) {
871 self.insert(0, element)
874 /// Removes the first element from a vector and returns it, or `None` if
875 /// the vector is empty.
879 /// This is an O(n) operation as it requires copying every element in the
885 /// let mut vec = vec!(1, 2, 3);
886 /// assert!(vec.shift() == Some(1));
887 /// assert_eq!(vec, vec!(2, 3));
890 pub fn shift(&mut self) -> Option<T> {
894 /// Insert an element at position `index` within the vector, shifting all
895 /// elements after position i one position to the right.
899 /// Fails if `index` is out of bounds of the vector.
904 /// let mut vec = vec!(1, 2, 3);
905 /// vec.insert(1, 4);
906 /// assert_eq!(vec, vec!(1, 4, 2, 3));
908 pub fn insert(&mut self, index: uint, element: T) {
909 let len = self.len();
910 assert!(index <= len);
911 // space for the new element
912 self.reserve(len + 1);
914 unsafe { // infallible
915 // The spot to put the new value
917 let p = self.as_mut_ptr().offset(index as int);
918 // Shift everything over to make space. (Duplicating the
919 // `index`th element into two consecutive places.)
920 ptr::copy_memory(p.offset(1), &*p, len - index);
921 // Write it in, overwriting the first copy of the `index`th
923 move_val_init(&mut *p, element);
925 self.set_len(len + 1);
929 /// Remove and return the element at position `index` within the vector,
930 /// shifting all elements after position `index` one position to the left.
931 /// Returns `None` if `i` is out of bounds.
936 /// let mut v = vec!(1, 2, 3);
937 /// assert_eq!(v.remove(1), Some(2));
938 /// assert_eq!(v, vec!(1, 3));
940 /// assert_eq!(v.remove(4), None);
941 /// // v is unchanged:
942 /// assert_eq!(v, vec!(1, 3));
944 pub fn remove(&mut self, index: uint) -> Option<T> {
945 let len = self.len();
947 unsafe { // infallible
950 // the place we are taking from.
951 let ptr = self.as_mut_ptr().offset(index as int);
952 // copy it out, unsafely having a copy of the value on
953 // the stack and in the vector at the same time.
954 ret = Some(ptr::read(ptr as *T));
956 // Shift everything down to fill in that spot.
957 ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
959 self.set_len(len - 1);
967 /// Takes ownership of the vector `other`, moving all elements into
968 /// the current vector. This does not copy any elements, and it is
969 /// illegal to use the `other` vector after calling this method
970 /// (because it is moved here).
975 /// let mut vec = vec!(box 1);
976 /// vec.push_all_move(vec!(box 2, box 3, box 4));
977 /// assert_eq!(vec, vec!(box 1, box 2, box 3, box 4));
979 pub fn push_all_move(&mut self, other: Vec<T>) {
980 self.extend(other.move_iter());
983 /// Returns a mutable slice of `self` between `start` and `end`.
987 /// Fails when `start` or `end` point outside the bounds of `self`, or when
993 /// let mut vec = vec!(1, 2, 3, 4);
994 /// assert!(vec.mut_slice(0, 2) == [1, 2]);
997 pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint)
999 self.as_mut_slice().mut_slice(start, end)
1002 /// Returns a mutable slice of self from `start` to the end of the vec.
1006 /// Fails when `start` points outside the bounds of self.
1011 /// let mut vec = vec!(1, 2, 3, 4);
1012 /// assert!(vec.mut_slice_from(2) == [3, 4]);
1015 pub fn mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] {
1016 self.as_mut_slice().mut_slice_from(start)
1019 /// Returns a mutable slice of self from the start of the vec to `end`.
1023 /// Fails when `end` points outside the bounds of self.
1028 /// let mut vec = vec!(1, 2, 3, 4);
1029 /// assert!(vec.mut_slice_to(2) == [1, 2]);
1032 pub fn mut_slice_to<'a>(&'a mut self, end: uint) -> &'a mut [T] {
1033 self.as_mut_slice().mut_slice_to(end)
1036 /// Returns a pair of mutable slices that divides the vec at an index.
1038 /// The first will contain all indices from `[0, mid)` (excluding
1039 /// the index `mid` itself) and the second will contain all
1040 /// indices from `[mid, len)` (excluding the index `len` itself).
1044 /// Fails if `mid > len`.
1049 /// let mut vec = vec!(1, 2, 3, 4, 5, 6);
1051 /// // scoped to restrict the lifetime of the borrows
1053 /// let (left, right) = vec.mut_split_at(0);
1054 /// assert!(left == &mut []);
1055 /// assert!(right == &mut [1, 2, 3, 4, 5, 6]);
1059 /// let (left, right) = vec.mut_split_at(2);
1060 /// assert!(left == &mut [1, 2]);
1061 /// assert!(right == &mut [3, 4, 5, 6]);
1065 /// let (left, right) = vec.mut_split_at(6);
1066 /// assert!(left == &mut [1, 2, 3, 4, 5, 6]);
1067 /// assert!(right == &mut []);
1071 pub fn mut_split_at<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
1072 self.as_mut_slice().mut_split_at(mid)
1075 /// Reverse the order of elements in a vector, in place.
1080 /// let mut v = vec!(1, 2, 3);
1082 /// assert_eq!(v, vec!(3, 2, 1));
1085 pub fn reverse(&mut self) {
1086 self.as_mut_slice().reverse()
1089 /// Returns a slice of `self` from `start` to the end of the vec.
1093 /// Fails when `start` points outside the bounds of self.
1098 /// let vec = vec!(1, 2, 3);
1099 /// assert!(vec.slice_from(1) == [2, 3]);
1102 pub fn slice_from<'a>(&'a self, start: uint) -> &'a [T] {
1103 self.as_slice().slice_from(start)
1106 /// Returns a slice of self from the start of the vec to `end`.
1110 /// Fails when `end` points outside the bounds of self.
1115 /// let vec = vec!(1, 2, 3);
1116 /// assert!(vec.slice_to(2) == [1, 2]);
1119 pub fn slice_to<'a>(&'a self, end: uint) -> &'a [T] {
1120 self.as_slice().slice_to(end)
1123 /// Returns a slice containing all but the last element of the vector.
1127 /// Fails if the vector is empty
1129 pub fn init<'a>(&'a self) -> &'a [T] {
1130 self.slice(0, self.len() - 1)
1134 /// Returns an unsafe pointer to the vector's buffer.
1136 /// The caller must ensure that the vector outlives the pointer this
1137 /// function returns, or else it will end up pointing to garbage.
1139 /// Modifying the vector may cause its buffer to be reallocated, which
1140 /// would also make any pointers to it invalid.
1142 pub fn as_ptr(&self) -> *T {
1143 // If we have a 0-sized vector, then the base pointer should not be NULL
1144 // because an iterator over the slice will attempt to yield the base
1145 // pointer as the first element in the vector, but this will end up
1146 // being Some(NULL) which is optimized to None.
1147 if mem::size_of::<T>() == 0 {
1154 /// Returns a mutable unsafe pointer to the vector's buffer.
1156 /// The caller must ensure that the vector outlives the pointer this
1157 /// function returns, or else it will end up pointing to garbage.
1159 /// Modifying the vector may cause its buffer to be reallocated, which
1160 /// would also make any pointers to it invalid.
1162 pub fn as_mut_ptr(&mut self) -> *mut T {
1163 // see above for the 0-size check
1164 if mem::size_of::<T>() == 0 {
1171 /// Retains only the elements specified by the predicate.
1173 /// In other words, remove all elements `e` such that `f(&e)` returns false.
1174 /// This method operates in place and preserves the order the retained elements.
1179 /// let mut vec = vec!(1i, 2, 3, 4);
1180 /// vec.retain(|x| x%2 == 0);
1181 /// assert_eq!(vec, vec!(2, 4));
1183 pub fn retain(&mut self, f: |&T| -> bool) {
1184 let len = self.len();
1187 let v = self.as_mut_slice();
1189 for i in range(0u, len) {
1198 self.truncate(len - del);
1202 /// Expands a vector in place, initializing the new elements to the result of a function.
1204 /// The vector is grown by `n` elements. The i-th new element are initialized to the value
1205 /// returned by `f(i)` where `i` is in the range [0, n).
1210 /// let mut vec = vec!(0u, 1);
1211 /// vec.grow_fn(3, |i| i);
1212 /// assert_eq!(vec, vec!(0, 1, 0, 1, 2));
1214 pub fn grow_fn(&mut self, n: uint, f: |uint| -> T) {
1215 self.reserve_additional(n);
1216 for i in range(0u, n) {
1222 impl<T:TotalOrd> Vec<T> {
1223 /// Sorts the vector in place.
1225 /// This sort is `O(n log n)` worst-case and stable, but allocates
1226 /// approximately `2 * n`, where `n` is the length of `self`.
1231 /// let mut vec = vec!(3i, 1, 2);
1233 /// assert_eq!(vec, vec!(1, 2, 3));
1235 pub fn sort(&mut self) {
1236 self.as_mut_slice().sort()
1240 impl<T> Mutable for Vec<T> {
1242 fn clear(&mut self) {
1248 /// Return true if a vector contains an element with the given value
1253 /// let vec = vec!(1, 2, 3);
1254 /// assert!(vec.contains(&1));
1256 pub fn contains(&self, x: &T) -> bool {
1257 self.as_slice().contains(x)
1260 /// Remove consecutive repeated elements in the vector.
1262 /// If the vector is sorted, this removes all duplicates.
1267 /// let mut vec = vec!(1, 2, 2, 3, 2);
1269 /// assert_eq!(vec, vec!(1, 2, 3, 2));
1271 pub fn dedup(&mut self) {
1273 // Although we have a mutable reference to `self`, we cannot make
1274 // *arbitrary* changes. The `Eq` comparisons could fail, so we
1275 // must ensure that the vector is in a valid state at all time.
1277 // The way that we handle this is by using swaps; we iterate
1278 // over all the elements, swapping as we go so that at the end
1279 // the elements we wish to keep are in the front, and those we
1280 // wish to reject are at the back. We can then truncate the
1281 // vector. This operation is still O(n).
1283 // Example: We start in this state, where `r` represents "next
1284 // read" and `w` represents "next_write`.
1287 // +---+---+---+---+---+---+
1288 // | 0 | 1 | 1 | 2 | 3 | 3 |
1289 // +---+---+---+---+---+---+
1292 // Comparing self[r] against self[w-1], this is not a duplicate, so
1293 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1294 // r and w, leaving us with:
1297 // +---+---+---+---+---+---+
1298 // | 0 | 1 | 1 | 2 | 3 | 3 |
1299 // +---+---+---+---+---+---+
1302 // Comparing self[r] against self[w-1], this value is a duplicate,
1303 // so we increment `r` but leave everything else unchanged:
1306 // +---+---+---+---+---+---+
1307 // | 0 | 1 | 1 | 2 | 3 | 3 |
1308 // +---+---+---+---+---+---+
1311 // Comparing self[r] against self[w-1], this is not a duplicate,
1312 // so swap self[r] and self[w] and advance r and w:
1315 // +---+---+---+---+---+---+
1316 // | 0 | 1 | 2 | 1 | 3 | 3 |
1317 // +---+---+---+---+---+---+
1320 // Not a duplicate, repeat:
1323 // +---+---+---+---+---+---+
1324 // | 0 | 1 | 2 | 3 | 1 | 3 |
1325 // +---+---+---+---+---+---+
1328 // Duplicate, advance r. End of vec. Truncate to w.
1330 let ln = self.len();
1331 if ln < 1 { return; }
1333 // Avoid bounds checks by using unsafe pointers.
1334 let p = self.as_mut_slice().as_mut_ptr();
1339 let p_r = p.offset(r as int);
1340 let p_wm1 = p.offset((w - 1) as int);
1343 let p_w = p_wm1.offset(1);
1344 mem::swap(&mut *p_r, &mut *p_w);
1356 impl<T> Vector<T> for Vec<T> {
1357 /// Work with `self` as a slice.
1362 /// fn foo(slice: &[int]) {}
1364 /// let vec = vec!(1, 2);
1365 /// foo(vec.as_slice());
1368 fn as_slice<'a>(&'a self) -> &'a [T] {
1369 unsafe { transmute(Slice { data: self.as_ptr(), len: self.len }) }
1373 #[unsafe_destructor]
1374 impl<T> Drop for Vec<T> {
1375 fn drop(&mut self) {
1376 // This is (and should always remain) a no-op if the fields are
1377 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1379 for x in self.as_mut_slice().iter() {
1382 free(self.ptr as *mut c_void)
1387 impl<T> Default for Vec<T> {
1388 fn default() -> Vec<T> {
1393 impl<T:fmt::Show> fmt::Show for Vec<T> {
1394 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1395 self.as_slice().fmt(f)
1399 /// An iterator that moves out of a vector.
1400 pub struct MoveItems<T> {
1401 allocation: *mut c_void, // the block of memory allocated for the vector
1402 iter: Items<'static, T>
1405 impl<T> Iterator<T> for MoveItems<T> {
1407 fn next(&mut self) -> Option<T> {
1409 self.iter.next().map(|x| ptr::read(x))
1414 fn size_hint(&self) -> (uint, Option<uint>) {
1415 self.iter.size_hint()
1419 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
1421 fn next_back(&mut self) -> Option<T> {
1423 self.iter.next_back().map(|x| ptr::read(x))
1428 #[unsafe_destructor]
1429 impl<T> Drop for MoveItems<T> {
1430 fn drop(&mut self) {
1431 // destroy the remaining elements
1434 free(self.allocation)
1445 fn test_small_vec_struct() {
1446 assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1450 fn test_double_drop() {
1456 struct DropCounter<'a> {
1460 #[unsafe_destructor]
1461 impl<'a> Drop for DropCounter<'a> {
1462 fn drop(&mut self) {
1467 let mut count_x @ mut count_y = 0;
1469 let mut tv = TwoVec {
1473 tv.x.push(DropCounter {count: &mut count_x});
1474 tv.y.push(DropCounter {count: &mut count_y});
1476 // If Vec had a drop flag, here is where it would be zeroed.
1477 // Instead, it should rely on its internal state to prevent
1478 // doing anything significant when dropped multiple times.
1481 // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1484 assert_eq!(count_x, 1);
1485 assert_eq!(count_y, 1);
1489 fn test_reserve_additional() {
1490 let mut v = Vec::new();
1491 assert_eq!(v.capacity(), 0);
1493 v.reserve_additional(2);
1494 assert!(v.capacity() >= 2);
1496 for i in range(0, 16) {
1500 assert!(v.capacity() >= 16);
1501 v.reserve_additional(16);
1502 assert!(v.capacity() >= 32);
1506 v.reserve_additional(16);
1507 assert!(v.capacity() >= 33)
1512 let mut v = Vec::new();
1513 let mut w = Vec::new();
1515 v.extend(range(0, 3));
1516 for i in range(0, 3) { w.push(i) }
1520 v.extend(range(3, 10));
1521 for i in range(3, 10) { w.push(i) }
1527 fn test_mut_slice_from() {
1528 let mut values = Vec::from_slice([1u8,2,3,4,5]);
1530 let slice = values.mut_slice_from(2);
1531 assert!(slice == [3, 4, 5]);
1532 for p in slice.mut_iter() {
1537 assert!(values.as_slice() == [1, 2, 5, 6, 7]);
1541 fn test_mut_slice_to() {
1542 let mut values = Vec::from_slice([1u8,2,3,4,5]);
1544 let slice = values.mut_slice_to(2);
1545 assert!(slice == [1, 2]);
1546 for p in slice.mut_iter() {
1551 assert!(values.as_slice() == [2, 3, 3, 4, 5]);
1555 fn test_mut_split_at() {
1556 let mut values = Vec::from_slice([1u8,2,3,4,5]);
1558 let (left, right) = values.mut_split_at(2);
1559 assert!(left.slice(0, left.len()) == [1, 2]);
1560 for p in left.mut_iter() {
1564 assert!(right.slice(0, right.len()) == [3, 4, 5]);
1565 for p in right.mut_iter() {
1570 assert!(values == Vec::from_slice([2u8, 3, 5, 6, 7]));
1575 let v: Vec<int> = vec!();
1576 let w = vec!(1, 2, 3);
1578 assert_eq!(v, v.clone());
1582 // they should be disjoint in memory.
1583 assert!(w.as_ptr() != z.as_ptr())
1587 fn test_clone_from() {
1589 let three = vec!(box 1, box 2, box 3);
1590 let two = vec!(box 4, box 5);
1592 v.clone_from(&three);
1593 assert_eq!(v, three);
1596 v.clone_from(&three);
1597 assert_eq!(v, three);
1604 v.clone_from(&three);
1605 assert_eq!(v, three)
1610 let mut v = Vec::from_slice([0u, 1]);
1611 v.grow_fn(3, |i| i);
1612 assert!(v == Vec::from_slice([0u, 1, 0, 1, 2]));
1617 let mut vec = Vec::from_slice([1u, 2, 3, 4]);
1618 vec.retain(|x| x%2 == 0);
1619 assert!(vec == Vec::from_slice([2u, 4]));
1623 fn zero_sized_values() {
1624 let mut v = Vec::new();
1625 assert_eq!(v.len(), 0);
1627 assert_eq!(v.len(), 1);
1629 assert_eq!(v.len(), 2);
1630 assert_eq!(v.pop(), Some(()));
1631 assert_eq!(v.pop(), Some(()));
1632 assert_eq!(v.pop(), None);
1634 assert_eq!(v.iter().len(), 0);
1636 assert_eq!(v.iter().len(), 1);
1638 assert_eq!(v.iter().len(), 2);
1640 for &() in v.iter() {}
1642 assert_eq!(v.mut_iter().len(), 2);
1644 assert_eq!(v.mut_iter().len(), 3);
1646 assert_eq!(v.mut_iter().len(), 4);
1648 for &() in v.mut_iter() {}
1649 unsafe { v.set_len(0); }
1650 assert_eq!(v.mut_iter().len(), 0);