1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A growable list type with heap-allocated contents, written `Vec<T>` but
12 //! pronounced 'vector.'
14 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
15 //! `O(1)` pop (from the end).
19 //! You can explicitly create a `Vec<T>` with `new()`:
22 //! let v: Vec<i32> = Vec::new();
25 //! ...or by using the `vec!` macro:
28 //! let v: Vec<i32> = vec![];
30 //! let v = vec![1, 2, 3, 4, 5];
32 //! let v = vec![0; 10]; // ten zeroes
35 //! You can `push` values onto the end of a vector (which will grow the vector
39 //! let mut v = vec![1, 2];
44 //! Popping values works in much the same way:
47 //! let mut v = vec![1, 2];
49 //! let two = v.pop();
52 //! Vectors also support indexing (through the `Index` and `IndexMut` traits):
55 //! let mut v = vec![1, 2, 3];
60 #![stable(feature = "rust1", since = "1.0.0")]
62 use alloc::raw_vec::RawVec;
63 use alloc::boxed::Box;
64 use alloc::heap::EMPTY;
65 use core::cmp::Ordering;
67 use core::hash::{self, Hash};
68 use core::intrinsics::{arith_offset, assume, needs_drop};
69 use core::iter::FromIterator;
71 use core::ops::{Index, IndexMut};
76 use borrow::{Cow, IntoCow};
78 use super::range::RangeArgument;
80 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
85 /// let mut vec = Vec::new();
89 /// assert_eq!(vec.len(), 2);
90 /// assert_eq!(vec[0], 1);
92 /// assert_eq!(vec.pop(), Some(2));
93 /// assert_eq!(vec.len(), 1);
96 /// assert_eq!(vec[0], 7);
98 /// vec.extend([1, 2, 3].iter().cloned());
101 /// println!("{}", x);
103 /// assert_eq!(vec, [7, 1, 2, 3]);
106 /// The `vec!` macro is provided to make initialization more convenient:
109 /// let mut vec = vec![1, 2, 3];
111 /// assert_eq!(vec, [1, 2, 3, 4]);
114 /// It can also initialize each element of a `Vec<T>` with a given value:
117 /// let vec = vec![0; 5];
118 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
121 /// Use a `Vec<T>` as an efficient stack:
124 /// let mut stack = Vec::new();
130 /// while let Some(top) = stack.pop() {
131 /// // Prints 3, 2, 1
132 /// println!("{}", top);
136 /// # Capacity and reallocation
138 /// The capacity of a vector is the amount of space allocated for any future
139 /// elements that will be added onto the vector. This is not to be confused with
140 /// the *length* of a vector, which specifies the number of actual elements
141 /// within the vector. If a vector's length exceeds its capacity, its capacity
142 /// will automatically be increased, but its elements will have to be
145 /// For example, a vector with capacity 10 and length 0 would be an empty vector
146 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
147 /// vector will not change its capacity or cause reallocation to occur. However,
148 /// if the vector's length is increased to 11, it will have to reallocate, which
149 /// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
150 /// whenever possible to specify how big the vector is expected to get.
154 /// Due to its incredibly fundamental nature, Vec makes a lot of guarantees
155 /// about its design. This ensures that it's as low-overhead as possible in
156 /// the general case, and can be correctly manipulated in primitive ways
157 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
158 /// If additional type parameters are added (e.g. to support custom allocators),
159 /// overriding their defaults may change the behavior.
161 /// Most fundamentally, Vec is and always will be a (pointer, capacity, length)
162 /// triplet. No more, no less. The order of these fields is completely
163 /// unspecified, and you should use the appropriate methods to modify these.
164 /// The pointer will never be null, so this type is null-pointer-optimized.
166 /// However, the pointer may not actually point to allocated memory. In particular,
167 /// if you construct a Vec with capacity 0 via `Vec::new()`, `vec![]`,
168 /// `Vec::with_capacity(0)`, or by calling `shrink_to_fit()` on an empty Vec, it
169 /// will not allocate memory. Similarly, if you store zero-sized types inside
170 /// a Vec, it will not allocate space for them. *Note that in this case the
171 /// Vec may not report a `capacity()` of 0*. Vec will allocate if and only
172 /// if `mem::size_of::<T>() * capacity() > 0`. In general, Vec's allocation
173 /// details are subtle enough that it is strongly recommended that you only
174 /// free memory allocated by a Vec by creating a new Vec and dropping it.
176 /// If a Vec *has* allocated memory, then the memory it points to is on the heap
177 /// (as defined by the allocator Rust is configured to use by default), and its
178 /// pointer points to `len()` initialized elements in order (what you would see
179 /// if you coerced it to a slice), followed by `capacity() - len()` logically
180 /// uninitialized elements.
182 /// Vec will never perform a "small optimization" where elements are actually
183 /// stored on the stack for two reasons:
185 /// * It would make it more difficult for unsafe code to correctly manipulate
186 /// a Vec. The contents of a Vec wouldn't have a stable address if it were
187 /// only moved, and it would be more difficult to determine if a Vec had
188 /// actually allocated memory.
190 /// * It would penalize the general case, incurring an additional branch
193 /// Vec will never automatically shrink itself, even if completely empty. This
194 /// ensures no unnecessary allocations or deallocations occur. Emptying a Vec
195 /// and then filling it back up to the same `len()` should incur no calls to
196 /// the allocator. If you wish to free up unused memory, use `shrink_to_fit`.
198 /// `push` and `insert` will never (re)allocate if the reported capacity is
199 /// sufficient. `push` and `insert` *will* (re)allocate if `len() == capacity()`.
200 /// That is, the reported capacity is completely accurate, and can be relied on.
201 /// It can even be used to manually free the memory allocated by a Vec if
202 /// desired. Bulk insertion methods *may* reallocate, even when not necessary.
204 /// Vec does not guarantee any particular growth strategy when reallocating
205 /// when full, nor when `reserve` is called. The current strategy is basic
206 /// and it may prove desirable to use a non-constant growth factor. Whatever
207 /// strategy is used will of course guarantee `O(1)` amortized `push`.
209 /// `vec![x; n]`, `vec![a, b, c, d]`, and `Vec::with_capacity(n)`, will all
210 /// produce a Vec with exactly the requested capacity. If `len() == capacity()`,
211 /// (as is the case for the `vec!` macro), then a `Vec<T>` can be converted
212 /// to and from a `Box<[T]>` without reallocating or moving the elements.
214 /// Vec will not specifically overwrite any data that is removed from it,
215 /// but also won't specifically preserve it. Its uninitialized memory is
216 /// scratch space that it may use however it wants. It will generally just do
217 /// whatever is most efficient or otherwise easy to implement. Do not rely on
218 /// removed data to be erased for security purposes. Even if you drop a Vec, its
219 /// buffer may simply be reused by another Vec. Even if you zero a Vec's memory
220 /// first, that may not actually happen because the optimizer does not consider
221 /// this a side-effect that must be preserved.
223 /// Vec does not currently guarantee the order in which elements are dropped
224 /// (the order has changed in the past, and may change again).
226 #[unsafe_no_drop_flag]
227 #[stable(feature = "rust1", since = "1.0.0")]
233 ////////////////////////////////////////////////////////////////////////////////
235 ////////////////////////////////////////////////////////////////////////////////
238 /// Constructs a new, empty `Vec<T>`.
240 /// The vector will not allocate until elements are pushed onto it.
245 /// # #![allow(unused_mut)]
246 /// let mut vec: Vec<i32> = Vec::new();
249 #[stable(feature = "rust1", since = "1.0.0")]
250 pub fn new() -> Vec<T> {
257 /// Constructs a new, empty `Vec<T>` with the specified capacity.
259 /// The vector will be able to hold exactly `capacity` elements without
260 /// reallocating. If `capacity` is 0, the vector will not allocate.
262 /// It is important to note that this function does not specify the *length*
263 /// of the returned vector, but only the *capacity*. (For an explanation of
264 /// the difference between length and capacity, see the main `Vec<T>` docs
265 /// above, 'Capacity and reallocation'.)
270 /// let mut vec = Vec::with_capacity(10);
272 /// // The vector contains no items, even though it has capacity for more
273 /// assert_eq!(vec.len(), 0);
275 /// // These are all done without reallocating...
280 /// // ...but this may make the vector reallocate
284 #[stable(feature = "rust1", since = "1.0.0")]
285 pub fn with_capacity(capacity: usize) -> Vec<T> {
287 buf: RawVec::with_capacity(capacity),
292 /// Creates a `Vec<T>` directly from the raw components of another vector.
296 /// This is highly unsafe, due to the number of invariants that aren't
299 /// * `ptr` needs to have been previously allocated via `String`/`Vec<T>`
300 /// (at least, it's highly likely to be incorrect if it wasn't).
301 /// * `length` needs to be the length that less than or equal to `capacity`.
302 /// * `capacity` needs to be the capacity that the pointer was allocated with.
304 /// Violating these may cause problems like corrupting the allocator's
305 /// internal datastructures.
314 /// let mut v = vec![1, 2, 3];
316 /// // Pull out the various important pieces of information about `v`
317 /// let p = v.as_mut_ptr();
318 /// let len = v.len();
319 /// let cap = v.capacity();
322 /// // Cast `v` into the void: no destructor run, so we are in
323 /// // complete control of the allocation to which `p` points.
326 /// // Overwrite memory with 4, 5, 6
327 /// for i in 0..len as isize {
328 /// ptr::write(p.offset(i), 4 + i);
331 /// // Put everything back together into a Vec
332 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
333 /// assert_eq!(rebuilt, [4, 5, 6]);
337 #[stable(feature = "rust1", since = "1.0.0")]
338 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
340 buf: RawVec::from_raw_parts(ptr, capacity),
345 /// Returns the number of elements the vector can hold without
351 /// let vec: Vec<i32> = Vec::with_capacity(10);
352 /// assert_eq!(vec.capacity(), 10);
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn capacity(&self) -> usize {
360 /// Reserves capacity for at least `additional` more elements to be inserted
361 /// in the given `Vec<T>`. The collection may reserve more space to avoid
362 /// frequent reallocations.
366 /// Panics if the new capacity overflows `usize`.
371 /// let mut vec = vec![1];
373 /// assert!(vec.capacity() >= 11);
375 #[stable(feature = "rust1", since = "1.0.0")]
376 pub fn reserve(&mut self, additional: usize) {
377 self.buf.reserve(self.len, additional);
380 /// Reserves the minimum capacity for exactly `additional` more elements to
381 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
384 /// Note that the allocator may give the collection more space than it
385 /// requests. Therefore capacity can not be relied upon to be precisely
386 /// minimal. Prefer `reserve` if future insertions are expected.
390 /// Panics if the new capacity overflows `usize`.
395 /// let mut vec = vec![1];
396 /// vec.reserve_exact(10);
397 /// assert!(vec.capacity() >= 11);
399 #[stable(feature = "rust1", since = "1.0.0")]
400 pub fn reserve_exact(&mut self, additional: usize) {
401 self.buf.reserve_exact(self.len, additional);
404 /// Shrinks the capacity of the vector as much as possible.
406 /// It will drop down as close as possible to the length but the allocator
407 /// may still inform the vector that there is space for a few more elements.
412 /// let mut vec = Vec::with_capacity(10);
413 /// vec.extend([1, 2, 3].iter().cloned());
414 /// assert_eq!(vec.capacity(), 10);
415 /// vec.shrink_to_fit();
416 /// assert!(vec.capacity() >= 3);
418 #[stable(feature = "rust1", since = "1.0.0")]
419 pub fn shrink_to_fit(&mut self) {
420 self.buf.shrink_to_fit(self.len);
423 /// Converts the vector into Box<[T]>.
425 /// Note that this will drop any excess capacity. Calling this and
426 /// converting back to a vector with `into_vec()` is equivalent to calling
427 /// `shrink_to_fit()`.
428 #[stable(feature = "rust1", since = "1.0.0")]
429 pub fn into_boxed_slice(mut self) -> Box<[T]> {
431 self.shrink_to_fit();
432 let buf = ptr::read(&self.buf);
438 /// Shorten a vector to be `len` elements long, dropping excess elements.
440 /// If `len` is greater than the vector's current length, this has no
446 /// let mut vec = vec![1, 2, 3, 4, 5];
448 /// assert_eq!(vec, [1, 2]);
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub fn truncate(&mut self, len: usize) {
453 // drop any extra elements
454 while len < self.len {
455 // decrement len before the read(), so a panic on Drop doesn't
456 // re-drop the just-failed value.
458 ptr::read(self.get_unchecked(self.len));
463 /// Extracts a slice containing the entire vector.
465 /// Equivalent to `&s[..]`.
467 #[unstable(feature = "convert",
468 reason = "waiting on RFC revision",
470 pub fn as_slice(&self) -> &[T] {
474 /// Extracts a mutable slice of the entire vector.
476 /// Equivalent to `&mut s[..]`.
478 #[unstable(feature = "convert",
479 reason = "waiting on RFC revision",
481 pub fn as_mut_slice(&mut self) -> &mut [T] {
485 /// Sets the length of a vector.
487 /// This will explicitly set the size of the vector, without actually
488 /// modifying its buffers, so it is up to the caller to ensure that the
489 /// vector is actually the specified size.
494 /// let mut v = vec![1, 2, 3, 4];
500 #[stable(feature = "rust1", since = "1.0.0")]
501 pub unsafe fn set_len(&mut self, len: usize) {
505 /// Removes an element from anywhere in the vector and return it, replacing
506 /// it with the last element.
508 /// This does not preserve ordering, but is O(1).
512 /// Panics if `index` is out of bounds.
517 /// let mut v = vec!["foo", "bar", "baz", "qux"];
519 /// assert_eq!(v.swap_remove(1), "bar");
520 /// assert_eq!(v, ["foo", "qux", "baz"]);
522 /// assert_eq!(v.swap_remove(0), "foo");
523 /// assert_eq!(v, ["baz", "qux"]);
526 #[stable(feature = "rust1", since = "1.0.0")]
527 pub fn swap_remove(&mut self, index: usize) -> T {
528 let length = self.len();
529 self.swap(index, length - 1);
533 /// Inserts an element at position `index` within the vector, shifting all
534 /// elements after position `i` one position to the right.
538 /// Panics if `index` is greater than the vector's length.
543 /// let mut vec = vec![1, 2, 3];
544 /// vec.insert(1, 4);
545 /// assert_eq!(vec, [1, 4, 2, 3]);
546 /// vec.insert(4, 5);
547 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
549 #[stable(feature = "rust1", since = "1.0.0")]
550 pub fn insert(&mut self, index: usize, element: T) {
551 let len = self.len();
552 assert!(index <= len);
554 // space for the new element
555 if len == self.buf.cap() {
561 // The spot to put the new value
563 let p = self.as_mut_ptr().offset(index as isize);
564 // Shift everything over to make space. (Duplicating the
565 // `index`th element into two consecutive places.)
566 ptr::copy(p, p.offset(1), len - index);
567 // Write it in, overwriting the first copy of the `index`th
569 ptr::write(p, element);
571 self.set_len(len + 1);
575 /// Removes and returns the element at position `index` within the vector,
576 /// shifting all elements after position `index` one position to the left.
580 /// Panics if `index` is out of bounds.
585 /// let mut v = vec![1, 2, 3];
586 /// assert_eq!(v.remove(1), 2);
587 /// assert_eq!(v, [1, 3]);
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn remove(&mut self, index: usize) -> T {
591 let len = self.len();
592 assert!(index < len);
597 // the place we are taking from.
598 let ptr = self.as_mut_ptr().offset(index as isize);
599 // copy it out, unsafely having a copy of the value on
600 // the stack and in the vector at the same time.
601 ret = ptr::read(ptr);
603 // Shift everything down to fill in that spot.
604 ptr::copy(ptr.offset(1), ptr, len - index - 1);
606 self.set_len(len - 1);
611 /// Retains only the elements specified by the predicate.
613 /// In other words, remove all elements `e` such that `f(&e)` returns false.
614 /// This method operates in place and preserves the order of the retained
620 /// let mut vec = vec![1, 2, 3, 4];
621 /// vec.retain(|&x| x%2 == 0);
622 /// assert_eq!(vec, [2, 4]);
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub fn retain<F>(&mut self, mut f: F)
626 where F: FnMut(&T) -> bool
628 let len = self.len();
642 self.truncate(len - del);
646 /// Appends an element to the back of a collection.
650 /// Panics if the number of elements in the vector overflows a `usize`.
655 /// let mut vec = vec![1, 2];
657 /// assert_eq!(vec, [1, 2, 3]);
660 #[stable(feature = "rust1", since = "1.0.0")]
661 pub fn push(&mut self, value: T) {
662 // This will panic or abort if we would allocate > isize::MAX bytes
663 // or if the length increment would overflow for zero-sized types.
664 if self.len == self.buf.cap() {
668 let end = self.as_mut_ptr().offset(self.len as isize);
669 ptr::write(end, value);
674 /// Removes the last element from a vector and returns it, or `None` if it
680 /// let mut vec = vec![1, 2, 3];
681 /// assert_eq!(vec.pop(), Some(3));
682 /// assert_eq!(vec, [1, 2]);
685 #[stable(feature = "rust1", since = "1.0.0")]
686 pub fn pop(&mut self) -> Option<T> {
692 Some(ptr::read(self.get_unchecked(self.len())))
697 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
701 /// Panics if the number of elements in the vector overflows a `usize`.
706 /// let mut vec = vec![1, 2, 3];
707 /// let mut vec2 = vec![4, 5, 6];
708 /// vec.append(&mut vec2);
709 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
710 /// assert_eq!(vec2, []);
713 #[stable(feature = "append", since = "1.4.0")]
714 pub fn append(&mut self, other: &mut Self) {
715 self.reserve(other.len());
716 let len = self.len();
718 ptr::copy_nonoverlapping(other.as_ptr(), self.get_unchecked_mut(len), other.len());
721 self.len += other.len();
727 /// Create a draining iterator that removes the specified range in the vector
728 /// and yields the removed items from start to end. The element range is
729 /// removed even if the iterator is not consumed until the end.
731 /// Note: It is unspecified how many elements are removed from the vector,
732 /// if the `Drain` value is leaked.
736 /// Panics if the starting point is greater than the end point or if
737 /// the end point is greater than the length of the vector.
742 /// // Draining using `..` clears the whole vector.
743 /// let mut v = vec![1, 2, 3];
744 /// let u: Vec<_> = v.drain(..).collect();
745 /// assert_eq!(v, &[]);
746 /// assert_eq!(u, &[1, 2, 3]);
748 #[stable(feature = "drain", since = "1.6.0")]
749 pub fn drain<R>(&mut self, range: R) -> Drain<T>
750 where R: RangeArgument<usize>
754 // When the Drain is first created, it shortens the length of
755 // the source vector to make sure no uninitalized or moved-from elements
756 // are accessible at all if the Drain's destructor never gets to run.
758 // Drain will ptr::read out the values to remove.
759 // When finished, remaining tail of the vec is copied back to cover
760 // the hole, and the vector length is restored to the new length.
762 let len = self.len();
763 let start = *range.start().unwrap_or(&0);
764 let end = *range.end().unwrap_or(&len);
765 assert!(start <= end);
769 // set self.vec length's to start, to be safe in case Drain is leaked
771 // Use the borrow in the IterMut to indicate borrowing behavior of the
772 // whole Drain iterator (like &mut T).
773 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
778 iter: range_slice.iter_mut(),
784 /// Clears the vector, removing all values.
789 /// let mut v = vec![1, 2, 3];
793 /// assert!(v.is_empty());
796 #[stable(feature = "rust1", since = "1.0.0")]
797 pub fn clear(&mut self) {
801 /// Returns the number of elements in the vector.
806 /// let a = vec![1, 2, 3];
807 /// assert_eq!(a.len(), 3);
810 #[stable(feature = "rust1", since = "1.0.0")]
811 pub fn len(&self) -> usize {
815 /// Returns `true` if the vector contains no elements.
820 /// let mut v = Vec::new();
821 /// assert!(v.is_empty());
824 /// assert!(!v.is_empty());
826 #[stable(feature = "rust1", since = "1.0.0")]
827 pub fn is_empty(&self) -> bool {
831 /// Splits the collection into two at the given index.
833 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
834 /// and the returned `Self` contains elements `[at, len)`.
836 /// Note that the capacity of `self` does not change.
840 /// Panics if `at > len`.
845 /// let mut vec = vec![1,2,3];
846 /// let vec2 = vec.split_off(1);
847 /// assert_eq!(vec, [1]);
848 /// assert_eq!(vec2, [2, 3]);
851 #[stable(feature = "split_off", since = "1.4.0")]
852 pub fn split_off(&mut self, at: usize) -> Self {
853 assert!(at <= self.len(), "`at` out of bounds");
855 let other_len = self.len - at;
856 let mut other = Vec::with_capacity(other_len);
858 // Unsafely `set_len` and copy items to `other`.
861 other.set_len(other_len);
863 ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
871 impl<T: Clone> Vec<T> {
872 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
874 /// If `new_len` is greater than `len()`, the `Vec` is extended by the
875 /// difference, with each additional slot filled with `value`.
876 /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
881 /// let mut vec = vec!["hello"];
882 /// vec.resize(3, "world");
883 /// assert_eq!(vec, ["hello", "world", "world"]);
885 /// let mut vec = vec![1, 2, 3, 4];
886 /// vec.resize(2, 0);
887 /// assert_eq!(vec, [1, 2]);
889 #[stable(feature = "vec_resize", since = "1.5.0")]
890 pub fn resize(&mut self, new_len: usize, value: T) {
891 let len = self.len();
894 self.extend_with_element(new_len - len, value);
896 self.truncate(new_len);
900 /// Extend the vector by `n` additional clones of `value`.
901 fn extend_with_element(&mut self, n: usize, value: T) {
905 let len = self.len();
906 let mut ptr = self.as_mut_ptr().offset(len as isize);
907 // Write all elements except the last one
909 ptr::write(ptr, value.clone());
911 // Increment the length in every step in case clone() panics
912 self.set_len(len + i);
916 // We can write the last element directly without cloning needlessly
917 ptr::write(ptr, value);
918 self.set_len(len + n);
923 #[allow(missing_docs)]
925 #[unstable(feature = "vec_push_all",
926 reason = "likely to be replaced by a more optimized extend",
928 #[rustc_deprecated(reason = "renamed to extend_from_slice",
930 pub fn push_all(&mut self, other: &[T]) {
931 self.extend_from_slice(other)
934 /// Appends all elements in a slice to the `Vec`.
936 /// Iterates over the slice `other`, clones each element, and then appends
937 /// it to this `Vec`. The `other` vector is traversed in-order.
939 /// Note that this function is same as `extend` except that it is
940 /// specialized to work with slices instead. If and when Rust gets
941 /// specialization this function will likely be deprecated (but still
947 /// let mut vec = vec![1];
948 /// vec.extend_from_slice(&[2, 3, 4]);
949 /// assert_eq!(vec, [1, 2, 3, 4]);
951 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
952 pub fn extend_from_slice(&mut self, other: &[T]) {
953 self.reserve(other.len());
955 for i in 0..other.len() {
956 let len = self.len();
958 // Unsafe code so this can be optimised to a memcpy (or something
959 // similarly fast) when T is Copy. LLVM is easily confused, so any
960 // extra operations during the loop can prevent this optimisation.
962 ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
963 self.set_len(len + 1);
969 impl<T: PartialEq> Vec<T> {
970 /// Removes consecutive repeated elements in the vector.
972 /// If the vector is sorted, this removes all duplicates.
977 /// let mut vec = vec![1, 2, 2, 3, 2];
981 /// assert_eq!(vec, [1, 2, 3, 2]);
983 #[stable(feature = "rust1", since = "1.0.0")]
984 pub fn dedup(&mut self) {
986 // Although we have a mutable reference to `self`, we cannot make
987 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
988 // must ensure that the vector is in a valid state at all time.
990 // The way that we handle this is by using swaps; we iterate
991 // over all the elements, swapping as we go so that at the end
992 // the elements we wish to keep are in the front, and those we
993 // wish to reject are at the back. We can then truncate the
994 // vector. This operation is still O(n).
996 // Example: We start in this state, where `r` represents "next
997 // read" and `w` represents "next_write`.
1000 // +---+---+---+---+---+---+
1001 // | 0 | 1 | 1 | 2 | 3 | 3 |
1002 // +---+---+---+---+---+---+
1005 // Comparing self[r] against self[w-1], this is not a duplicate, so
1006 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1007 // r and w, leaving us with:
1010 // +---+---+---+---+---+---+
1011 // | 0 | 1 | 1 | 2 | 3 | 3 |
1012 // +---+---+---+---+---+---+
1015 // Comparing self[r] against self[w-1], this value is a duplicate,
1016 // so we increment `r` but leave everything else unchanged:
1019 // +---+---+---+---+---+---+
1020 // | 0 | 1 | 1 | 2 | 3 | 3 |
1021 // +---+---+---+---+---+---+
1024 // Comparing self[r] against self[w-1], this is not a duplicate,
1025 // so swap self[r] and self[w] and advance r and w:
1028 // +---+---+---+---+---+---+
1029 // | 0 | 1 | 2 | 1 | 3 | 3 |
1030 // +---+---+---+---+---+---+
1033 // Not a duplicate, repeat:
1036 // +---+---+---+---+---+---+
1037 // | 0 | 1 | 2 | 3 | 1 | 3 |
1038 // +---+---+---+---+---+---+
1041 // Duplicate, advance r. End of vec. Truncate to w.
1043 let ln = self.len();
1048 // Avoid bounds checks by using raw pointers.
1049 let p = self.as_mut_ptr();
1050 let mut r: usize = 1;
1051 let mut w: usize = 1;
1054 let p_r = p.offset(r as isize);
1055 let p_wm1 = p.offset((w - 1) as isize);
1058 let p_w = p_wm1.offset(1);
1059 mem::swap(&mut *p_r, &mut *p_w);
1071 ////////////////////////////////////////////////////////////////////////////////
1072 // Internal methods and functions
1073 ////////////////////////////////////////////////////////////////////////////////
1076 #[stable(feature = "rust1", since = "1.0.0")]
1077 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1078 let mut v = Vec::with_capacity(n);
1079 v.extend_with_element(n, elem);
1083 ////////////////////////////////////////////////////////////////////////////////
1084 // Common trait implementations for Vec
1085 ////////////////////////////////////////////////////////////////////////////////
1087 #[stable(feature = "rust1", since = "1.0.0")]
1088 impl<T: Clone> Clone for Vec<T> {
1090 fn clone(&self) -> Vec<T> {
1091 <[T]>::to_vec(&**self)
1094 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1095 // required for this method definition, is not available. Instead use the
1096 // `slice::to_vec` function which is only available with cfg(test)
1097 // NB see the slice::hack module in slice.rs for more information
1099 fn clone(&self) -> Vec<T> {
1100 ::slice::to_vec(&**self)
1103 fn clone_from(&mut self, other: &Vec<T>) {
1104 // drop anything in self that will not be overwritten
1105 self.truncate(other.len());
1106 let len = self.len();
1108 // reuse the contained values' allocations/resources.
1109 self.clone_from_slice(&other[..len]);
1111 // self.len <= other.len due to the truncate above, so the
1112 // slice here is always in-bounds.
1113 self.extend_from_slice(&other[len..]);
1117 #[stable(feature = "rust1", since = "1.0.0")]
1118 impl<T: Hash> Hash for Vec<T> {
1120 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1121 Hash::hash(&**self, state)
1125 #[stable(feature = "rust1", since = "1.0.0")]
1126 impl<T> Index<usize> for Vec<T> {
1130 fn index(&self, index: usize) -> &T {
1131 // NB built-in indexing via `&[T]`
1136 #[stable(feature = "rust1", since = "1.0.0")]
1137 impl<T> IndexMut<usize> for Vec<T> {
1139 fn index_mut(&mut self, index: usize) -> &mut T {
1140 // NB built-in indexing via `&mut [T]`
1141 &mut (**self)[index]
1146 #[stable(feature = "rust1", since = "1.0.0")]
1147 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1151 fn index(&self, index: ops::Range<usize>) -> &[T] {
1152 Index::index(&**self, index)
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1160 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1161 Index::index(&**self, index)
1164 #[stable(feature = "rust1", since = "1.0.0")]
1165 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1169 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1170 Index::index(&**self, index)
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1178 fn index(&self, _index: ops::RangeFull) -> &[T] {
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1186 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1187 IndexMut::index_mut(&mut **self, index)
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1193 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1194 IndexMut::index_mut(&mut **self, index)
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1200 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1201 IndexMut::index_mut(&mut **self, index)
1204 #[stable(feature = "rust1", since = "1.0.0")]
1205 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1207 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 impl<T> ops::Deref for Vec<T> {
1216 fn deref(&self) -> &[T] {
1218 let p = self.buf.ptr();
1219 assume(!p.is_null());
1220 slice::from_raw_parts(p, self.len)
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 impl<T> ops::DerefMut for Vec<T> {
1227 fn deref_mut(&mut self) -> &mut [T] {
1229 let ptr = self.buf.ptr();
1230 assume(!ptr.is_null());
1231 slice::from_raw_parts_mut(ptr, self.len)
1236 #[stable(feature = "rust1", since = "1.0.0")]
1237 impl<T> FromIterator<T> for Vec<T> {
1239 fn from_iter<I: IntoIterator<Item = T>>(iterable: I) -> Vec<T> {
1240 // Unroll the first iteration, as the vector is going to be
1241 // expanded on this iteration in every case when the iterable is not
1242 // empty, but the loop in extend_desugared() is not going to see the
1243 // vector being full in the few subsequent loop iterations.
1244 // So we get better branch prediction.
1245 let mut iterator = iterable.into_iter();
1246 let mut vector = match iterator.next() {
1247 None => return Vec::new(),
1249 let (lower, _) = iterator.size_hint();
1250 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1252 ptr::write(vector.get_unchecked_mut(0), element);
1258 vector.extend_desugared(iterator);
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 impl<T> IntoIterator for Vec<T> {
1266 type IntoIter = IntoIter<T>;
1268 /// Creates a consuming iterator, that is, one that moves each value out of
1269 /// the vector (from start to end). The vector cannot be used after calling
1275 /// let v = vec!["a".to_string(), "b".to_string()];
1276 /// for s in v.into_iter() {
1277 /// // s has type String, not &String
1278 /// println!("{}", s);
1282 fn into_iter(mut self) -> IntoIter<T> {
1284 let ptr = self.as_mut_ptr();
1285 assume(!ptr.is_null());
1286 let begin = ptr as *const T;
1287 let end = if mem::size_of::<T>() == 0 {
1288 arith_offset(ptr as *const i8, self.len() as isize) as *const T
1290 ptr.offset(self.len() as isize) as *const T
1292 let buf = ptr::read(&self.buf);
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl<'a, T> IntoIterator for &'a Vec<T> {
1306 type IntoIter = slice::Iter<'a, T>;
1308 fn into_iter(self) -> slice::Iter<'a, T> {
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1315 type Item = &'a mut T;
1316 type IntoIter = slice::IterMut<'a, T>;
1318 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1323 #[stable(feature = "rust1", since = "1.0.0")]
1324 impl<T> Extend<T> for Vec<T> {
1326 fn extend<I: IntoIterator<Item = T>>(&mut self, iterable: I) {
1327 self.extend_desugared(iterable.into_iter())
1332 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1333 // This function should be the moral equivalent of:
1335 // for item in iterator {
1338 while let Some(element) = iterator.next() {
1339 let len = self.len();
1340 if len == self.capacity() {
1341 let (lower, _) = iterator.size_hint();
1342 self.reserve(lower.saturating_add(1));
1345 ptr::write(self.get_unchecked_mut(len), element);
1346 // NB can't overflow since we would have had to alloc the address space
1347 self.set_len(len + 1);
1353 #[stable(feature = "extend_ref", since = "1.2.0")]
1354 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1355 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1356 self.extend(iter.into_iter().cloned());
1360 macro_rules! __impl_slice_eq1 {
1361 ($Lhs: ty, $Rhs: ty) => {
1362 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1364 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
1368 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
1370 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
1375 __impl_slice_eq1! { Vec<A>, Vec<B> }
1376 __impl_slice_eq1! { Vec<A>, &'b [B] }
1377 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1378 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1379 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1380 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1382 macro_rules! array_impls {
1385 // NOTE: some less important impls are omitted to reduce code bloat
1386 __impl_slice_eq1! { Vec<A>, [B; $N] }
1387 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1388 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1389 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1390 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1391 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1398 10 11 12 13 14 15 16 17 18 19
1399 20 21 22 23 24 25 26 27 28 29
1403 #[stable(feature = "rust1", since = "1.0.0")]
1404 impl<T: PartialOrd> PartialOrd for Vec<T> {
1406 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1407 PartialOrd::partial_cmp(&**self, &**other)
1411 #[stable(feature = "rust1", since = "1.0.0")]
1412 impl<T: Eq> Eq for Vec<T> {}
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 impl<T: Ord> Ord for Vec<T> {
1417 fn cmp(&self, other: &Vec<T>) -> Ordering {
1418 Ord::cmp(&**self, &**other)
1422 #[stable(feature = "rust1", since = "1.0.0")]
1423 impl<T> Drop for Vec<T> {
1424 #[unsafe_destructor_blind_to_params]
1425 fn drop(&mut self) {
1426 if self.buf.unsafe_no_drop_flag_needs_drop() {
1428 // The branch on needs_drop() is an -O1 performance optimization.
1429 // Without the branch, dropping Vec<u8> takes linear time.
1430 if needs_drop::<T>() {
1431 for x in self.iter_mut() {
1432 ptr::drop_in_place(x);
1437 // RawVec handles deallocation
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 impl<T> Default for Vec<T> {
1443 fn default() -> Vec<T> {
1448 #[stable(feature = "rust1", since = "1.0.0")]
1449 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1450 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1451 fmt::Debug::fmt(&**self, f)
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl<T> AsRef<Vec<T>> for Vec<T> {
1457 fn as_ref(&self) -> &Vec<T> {
1462 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1463 impl<T> AsMut<Vec<T>> for Vec<T> {
1464 fn as_mut(&mut self) -> &mut Vec<T> {
1469 #[stable(feature = "rust1", since = "1.0.0")]
1470 impl<T> AsRef<[T]> for Vec<T> {
1471 fn as_ref(&self) -> &[T] {
1476 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1477 impl<T> AsMut<[T]> for Vec<T> {
1478 fn as_mut(&mut self) -> &mut [T] {
1483 #[stable(feature = "rust1", since = "1.0.0")]
1484 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1486 fn from(s: &'a [T]) -> Vec<T> {
1490 fn from(s: &'a [T]) -> Vec<T> {
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl<'a> From<&'a str> for Vec<u8> {
1497 fn from(s: &'a str) -> Vec<u8> {
1498 From::from(s.as_bytes())
1502 ////////////////////////////////////////////////////////////////////////////////
1504 ////////////////////////////////////////////////////////////////////////////////
1506 #[stable(feature = "rust1", since = "1.0.0")]
1507 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1508 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
1509 Cow::Owned(FromIterator::from_iter(it))
1513 #[stable(feature = "rust1", since = "1.0.0")]
1514 impl<'a, T: 'a> IntoCow<'a, [T]> for Vec<T> where T: Clone {
1515 fn into_cow(self) -> Cow<'a, [T]> {
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<'a, T> IntoCow<'a, [T]> for &'a [T] where T: Clone {
1522 fn into_cow(self) -> Cow<'a, [T]> {
1527 ////////////////////////////////////////////////////////////////////////////////
1529 ////////////////////////////////////////////////////////////////////////////////
1531 /// An iterator that moves out of a vector.
1532 #[stable(feature = "rust1", since = "1.0.0")]
1533 pub struct IntoIter<T> {
1539 #[stable(feature = "rust1", since = "1.0.0")]
1540 unsafe impl<T: Send> Send for IntoIter<T> {}
1541 #[stable(feature = "rust1", since = "1.0.0")]
1542 unsafe impl<T: Sync> Sync for IntoIter<T> {}
1544 #[stable(feature = "rust1", since = "1.0.0")]
1545 impl<T> Iterator for IntoIter<T> {
1549 fn next(&mut self) -> Option<T> {
1551 if self.ptr == self.end {
1554 if mem::size_of::<T>() == 0 {
1555 // purposefully don't use 'ptr.offset' because for
1556 // vectors with 0-size elements this would return the
1558 self.ptr = arith_offset(self.ptr as *const i8, 1) as *const T;
1560 // Use a non-null pointer value
1561 Some(ptr::read(EMPTY as *mut T))
1564 self.ptr = self.ptr.offset(1);
1566 Some(ptr::read(old))
1573 fn size_hint(&self) -> (usize, Option<usize>) {
1574 let diff = (self.end as usize) - (self.ptr as usize);
1575 let size = mem::size_of::<T>();
1582 (exact, Some(exact))
1586 fn count(self) -> usize {
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl<T> DoubleEndedIterator for IntoIter<T> {
1594 fn next_back(&mut self) -> Option<T> {
1596 if self.end == self.ptr {
1599 if mem::size_of::<T>() == 0 {
1600 // See above for why 'ptr.offset' isn't used
1601 self.end = arith_offset(self.end as *const i8, -1) as *const T;
1603 // Use a non-null pointer value
1604 Some(ptr::read(EMPTY as *mut T))
1606 self.end = self.end.offset(-1);
1608 Some(ptr::read(self.end))
1615 #[stable(feature = "rust1", since = "1.0.0")]
1616 impl<T> ExactSizeIterator for IntoIter<T> {}
1618 #[stable(feature = "rust1", since = "1.0.0")]
1619 impl<T> Drop for IntoIter<T> {
1620 #[unsafe_destructor_blind_to_params]
1621 fn drop(&mut self) {
1622 // destroy the remaining elements
1625 // RawVec handles deallocation
1629 /// A draining iterator for `Vec<T>`.
1630 #[stable(feature = "drain", since = "1.6.0")]
1631 pub struct Drain<'a, T: 'a> {
1632 /// Index of tail to preserve
1636 /// Current remaining range to remove
1637 iter: slice::IterMut<'a, T>,
1641 #[stable(feature = "drain", since = "1.6.0")]
1642 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1643 #[stable(feature = "drain", since = "1.6.0")]
1644 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl<'a, T> Iterator for Drain<'a, T> {
1651 fn next(&mut self) -> Option<T> {
1652 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
1655 fn size_hint(&self) -> (usize, Option<usize>) {
1656 self.iter.size_hint()
1660 #[stable(feature = "rust1", since = "1.0.0")]
1661 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1663 fn next_back(&mut self) -> Option<T> {
1664 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<'a, T> Drop for Drain<'a, T> {
1670 fn drop(&mut self) {
1671 // exhaust self first
1672 while let Some(_) = self.next() {}
1674 if self.tail_len > 0 {
1676 let source_vec = &mut *self.vec;
1677 // memmove back untouched tail, update to new length
1678 let start = source_vec.len();
1679 let tail = self.tail_start;
1680 let src = source_vec.as_ptr().offset(tail as isize);
1681 let dst = source_vec.as_mut_ptr().offset(start as isize);
1682 ptr::copy(src, dst, self.tail_len);
1683 source_vec.set_len(start + self.tail_len);
1690 #[stable(feature = "rust1", since = "1.0.0")]
1691 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}