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 contiguous growable array type with heap-allocated contents, written
12 //! `Vec<T>` but 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::boxed::Box;
63 use alloc::heap::EMPTY;
64 use alloc::raw_vec::RawVec;
66 use core::cmp::Ordering;
68 use core::hash::{self, Hash};
69 use core::intrinsics::{arith_offset, assume, needs_drop};
70 use core::iter::FromIterator;
72 use core::ops::{Index, IndexMut};
78 use borrow::{Cow, IntoCow};
80 use super::range::RangeArgument;
82 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector.'
87 /// let mut vec = Vec::new();
91 /// assert_eq!(vec.len(), 2);
92 /// assert_eq!(vec[0], 1);
94 /// assert_eq!(vec.pop(), Some(2));
95 /// assert_eq!(vec.len(), 1);
98 /// assert_eq!(vec[0], 7);
100 /// vec.extend([1, 2, 3].iter().cloned());
103 /// println!("{}", x);
105 /// assert_eq!(vec, [7, 1, 2, 3]);
108 /// The `vec!` macro is provided to make initialization more convenient:
111 /// let mut vec = vec![1, 2, 3];
113 /// assert_eq!(vec, [1, 2, 3, 4]);
116 /// It can also initialize each element of a `Vec<T>` with a given value:
119 /// let vec = vec![0; 5];
120 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
123 /// Use a `Vec<T>` as an efficient stack:
126 /// let mut stack = Vec::new();
132 /// while let Some(top) = stack.pop() {
133 /// // Prints 3, 2, 1
134 /// println!("{}", top);
138 /// # Capacity and reallocation
140 /// The capacity of a vector is the amount of space allocated for any future
141 /// elements that will be added onto the vector. This is not to be confused with
142 /// the *length* of a vector, which specifies the number of actual elements
143 /// within the vector. If a vector's length exceeds its capacity, its capacity
144 /// will automatically be increased, but its elements will have to be
147 /// For example, a vector with capacity 10 and length 0 would be an empty vector
148 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
149 /// vector will not change its capacity or cause reallocation to occur. However,
150 /// if the vector's length is increased to 11, it will have to reallocate, which
151 /// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
152 /// whenever possible to specify how big the vector is expected to get.
156 /// Due to its incredibly fundamental nature, Vec makes a lot of guarantees
157 /// about its design. This ensures that it's as low-overhead as possible in
158 /// the general case, and can be correctly manipulated in primitive ways
159 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
160 /// If additional type parameters are added (e.g. to support custom allocators),
161 /// overriding their defaults may change the behavior.
163 /// Most fundamentally, Vec is and always will be a (pointer, capacity, length)
164 /// triplet. No more, no less. The order of these fields is completely
165 /// unspecified, and you should use the appropriate methods to modify these.
166 /// The pointer will never be null, so this type is null-pointer-optimized.
168 /// However, the pointer may not actually point to allocated memory. In particular,
169 /// if you construct a Vec with capacity 0 via `Vec::new()`, `vec![]`,
170 /// `Vec::with_capacity(0)`, or by calling `shrink_to_fit()` on an empty Vec, it
171 /// will not allocate memory. Similarly, if you store zero-sized types inside
172 /// a Vec, it will not allocate space for them. *Note that in this case the
173 /// Vec may not report a `capacity()` of 0*. Vec will allocate if and only
174 /// if `mem::size_of::<T>() * capacity() > 0`. In general, Vec's allocation
175 /// details are subtle enough that it is strongly recommended that you only
176 /// free memory allocated by a Vec by creating a new Vec and dropping it.
178 /// If a Vec *has* allocated memory, then the memory it points to is on the heap
179 /// (as defined by the allocator Rust is configured to use by default), and its
180 /// pointer points to `len()` initialized elements in order (what you would see
181 /// if you coerced it to a slice), followed by `capacity() - len()` logically
182 /// uninitialized elements.
184 /// Vec will never perform a "small optimization" where elements are actually
185 /// stored on the stack for two reasons:
187 /// * It would make it more difficult for unsafe code to correctly manipulate
188 /// a Vec. The contents of a Vec wouldn't have a stable address if it were
189 /// only moved, and it would be more difficult to determine if a Vec had
190 /// actually allocated memory.
192 /// * It would penalize the general case, incurring an additional branch
195 /// Vec will never automatically shrink itself, even if completely empty. This
196 /// ensures no unnecessary allocations or deallocations occur. Emptying a Vec
197 /// and then filling it back up to the same `len()` should incur no calls to
198 /// the allocator. If you wish to free up unused memory, use `shrink_to_fit`.
200 /// `push` and `insert` will never (re)allocate if the reported capacity is
201 /// sufficient. `push` and `insert` *will* (re)allocate if `len() == capacity()`.
202 /// That is, the reported capacity is completely accurate, and can be relied on.
203 /// It can even be used to manually free the memory allocated by a Vec if
204 /// desired. Bulk insertion methods *may* reallocate, even when not necessary.
206 /// Vec does not guarantee any particular growth strategy when reallocating
207 /// when full, nor when `reserve` is called. The current strategy is basic
208 /// and it may prove desirable to use a non-constant growth factor. Whatever
209 /// strategy is used will of course guarantee `O(1)` amortized `push`.
211 /// `vec![x; n]`, `vec![a, b, c, d]`, and `Vec::with_capacity(n)`, will all
212 /// produce a Vec with exactly the requested capacity. If `len() == capacity()`,
213 /// (as is the case for the `vec!` macro), then a `Vec<T>` can be converted
214 /// to and from a `Box<[T]>` without reallocating or moving the elements.
216 /// Vec will not specifically overwrite any data that is removed from it,
217 /// but also won't specifically preserve it. Its uninitialized memory is
218 /// scratch space that it may use however it wants. It will generally just do
219 /// whatever is most efficient or otherwise easy to implement. Do not rely on
220 /// removed data to be erased for security purposes. Even if you drop a Vec, its
221 /// buffer may simply be reused by another Vec. Even if you zero a Vec's memory
222 /// first, that may not actually happen because the optimizer does not consider
223 /// this a side-effect that must be preserved.
225 /// Vec does not currently guarantee the order in which elements are dropped
226 /// (the order has changed in the past, and may change again).
228 #[unsafe_no_drop_flag]
229 #[stable(feature = "rust1", since = "1.0.0")]
235 ////////////////////////////////////////////////////////////////////////////////
237 ////////////////////////////////////////////////////////////////////////////////
240 /// Constructs a new, empty `Vec<T>`.
242 /// The vector will not allocate until elements are pushed onto it.
247 /// # #![allow(unused_mut)]
248 /// let mut vec: Vec<i32> = Vec::new();
251 #[stable(feature = "rust1", since = "1.0.0")]
252 pub fn new() -> Vec<T> {
259 /// Constructs a new, empty `Vec<T>` with the specified capacity.
261 /// The vector will be able to hold exactly `capacity` elements without
262 /// reallocating. If `capacity` is 0, the vector will not allocate.
264 /// It is important to note that this function does not specify the *length*
265 /// of the returned vector, but only the *capacity*. (For an explanation of
266 /// the difference between length and capacity, see the main `Vec<T>` docs
267 /// above, 'Capacity and reallocation'.)
272 /// let mut vec = Vec::with_capacity(10);
274 /// // The vector contains no items, even though it has capacity for more
275 /// assert_eq!(vec.len(), 0);
277 /// // These are all done without reallocating...
282 /// // ...but this may make the vector reallocate
286 #[stable(feature = "rust1", since = "1.0.0")]
287 pub fn with_capacity(capacity: usize) -> Vec<T> {
289 buf: RawVec::with_capacity(capacity),
294 /// Creates a `Vec<T>` directly from the raw components of another vector.
298 /// This is highly unsafe, due to the number of invariants that aren't
301 /// * `ptr` needs to have been previously allocated via `String`/`Vec<T>`
302 /// (at least, it's highly likely to be incorrect if it wasn't).
303 /// * `length` needs to be the length that less than or equal to `capacity`.
304 /// * `capacity` needs to be the capacity that the pointer was allocated with.
306 /// Violating these may cause problems like corrupting the allocator's
307 /// internal datastructures.
316 /// let mut v = vec![1, 2, 3];
318 /// // Pull out the various important pieces of information about `v`
319 /// let p = v.as_mut_ptr();
320 /// let len = v.len();
321 /// let cap = v.capacity();
324 /// // Cast `v` into the void: no destructor run, so we are in
325 /// // complete control of the allocation to which `p` points.
328 /// // Overwrite memory with 4, 5, 6
329 /// for i in 0..len as isize {
330 /// ptr::write(p.offset(i), 4 + i);
333 /// // Put everything back together into a Vec
334 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
335 /// assert_eq!(rebuilt, [4, 5, 6]);
339 #[stable(feature = "rust1", since = "1.0.0")]
340 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
342 buf: RawVec::from_raw_parts(ptr, capacity),
347 /// Returns the number of elements the vector can hold without
353 /// let vec: Vec<i32> = Vec::with_capacity(10);
354 /// assert_eq!(vec.capacity(), 10);
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn capacity(&self) -> usize {
362 /// Reserves capacity for at least `additional` more elements to be inserted
363 /// in the given `Vec<T>`. The collection may reserve more space to avoid
364 /// frequent reallocations.
368 /// Panics if the new capacity overflows `usize`.
373 /// let mut vec = vec![1];
375 /// assert!(vec.capacity() >= 11);
377 #[stable(feature = "rust1", since = "1.0.0")]
378 pub fn reserve(&mut self, additional: usize) {
379 self.buf.reserve(self.len, additional);
382 /// Reserves the minimum capacity for exactly `additional` more elements to
383 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
386 /// Note that the allocator may give the collection more space than it
387 /// requests. Therefore capacity can not be relied upon to be precisely
388 /// minimal. Prefer `reserve` if future insertions are expected.
392 /// Panics if the new capacity overflows `usize`.
397 /// let mut vec = vec![1];
398 /// vec.reserve_exact(10);
399 /// assert!(vec.capacity() >= 11);
401 #[stable(feature = "rust1", since = "1.0.0")]
402 pub fn reserve_exact(&mut self, additional: usize) {
403 self.buf.reserve_exact(self.len, additional);
406 /// Shrinks the capacity of the vector as much as possible.
408 /// It will drop down as close as possible to the length but the allocator
409 /// may still inform the vector that there is space for a few more elements.
414 /// let mut vec = Vec::with_capacity(10);
415 /// vec.extend([1, 2, 3].iter().cloned());
416 /// assert_eq!(vec.capacity(), 10);
417 /// vec.shrink_to_fit();
418 /// assert!(vec.capacity() >= 3);
420 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn shrink_to_fit(&mut self) {
422 self.buf.shrink_to_fit(self.len);
425 /// Converts the vector into Box<[T]>.
427 /// Note that this will drop any excess capacity. Calling this and
428 /// converting back to a vector with `into_vec()` is equivalent to calling
429 /// `shrink_to_fit()`.
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub fn into_boxed_slice(mut self) -> Box<[T]> {
433 self.shrink_to_fit();
434 let buf = ptr::read(&self.buf);
440 /// Shorten a vector to be `len` elements long, dropping excess elements.
442 /// If `len` is greater than the vector's current length, this has no
448 /// let mut vec = vec![1, 2, 3, 4, 5];
450 /// assert_eq!(vec, [1, 2]);
452 #[stable(feature = "rust1", since = "1.0.0")]
453 pub fn truncate(&mut self, len: usize) {
455 // drop any extra elements
456 while len < self.len {
457 // decrement len before the read(), so a panic on Drop doesn't
458 // re-drop the just-failed value.
460 ptr::read(self.get_unchecked(self.len));
465 /// Extracts a slice containing the entire vector.
467 /// Equivalent to `&s[..]`.
469 #[stable(feature = "vec_as_slice", since = "1.7.0")]
470 pub fn as_slice(&self) -> &[T] {
474 /// Extracts a mutable slice of the entire vector.
476 /// Equivalent to `&mut s[..]`.
478 #[stable(feature = "vec_as_slice", since = "1.7.0")]
479 pub fn as_mut_slice(&mut self) -> &mut [T] {
483 /// Sets the length of a vector.
485 /// This will explicitly set the size of the vector, without actually
486 /// modifying its buffers, so it is up to the caller to ensure that the
487 /// vector is actually the specified size.
492 /// let mut v = vec![1, 2, 3, 4];
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub unsafe fn set_len(&mut self, len: usize) {
503 /// Removes an element from anywhere in the vector and return it, replacing
504 /// it with the last element.
506 /// This does not preserve ordering, but is O(1).
510 /// Panics if `index` is out of bounds.
515 /// let mut v = vec!["foo", "bar", "baz", "qux"];
517 /// assert_eq!(v.swap_remove(1), "bar");
518 /// assert_eq!(v, ["foo", "qux", "baz"]);
520 /// assert_eq!(v.swap_remove(0), "foo");
521 /// assert_eq!(v, ["baz", "qux"]);
524 #[stable(feature = "rust1", since = "1.0.0")]
525 pub fn swap_remove(&mut self, index: usize) -> T {
526 let length = self.len();
527 self.swap(index, length - 1);
531 /// Inserts an element at position `index` within the vector, shifting all
532 /// elements after it to the right.
536 /// Panics if `index` is greater than the vector's length.
541 /// let mut vec = vec![1, 2, 3];
542 /// vec.insert(1, 4);
543 /// assert_eq!(vec, [1, 4, 2, 3]);
544 /// vec.insert(4, 5);
545 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
547 #[stable(feature = "rust1", since = "1.0.0")]
548 pub fn insert(&mut self, index: usize, element: T) {
549 let len = self.len();
550 assert!(index <= len);
552 // space for the new element
553 if len == self.buf.cap() {
559 // The spot to put the new value
561 let p = self.as_mut_ptr().offset(index as isize);
562 // Shift everything over to make space. (Duplicating the
563 // `index`th element into two consecutive places.)
564 ptr::copy(p, p.offset(1), len - index);
565 // Write it in, overwriting the first copy of the `index`th
567 ptr::write(p, element);
569 self.set_len(len + 1);
573 /// Removes and returns the element at position `index` within the vector,
574 /// shifting all elements after it to the left.
578 /// Panics if `index` is out of bounds.
583 /// let mut v = vec![1, 2, 3];
584 /// assert_eq!(v.remove(1), 2);
585 /// assert_eq!(v, [1, 3]);
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn remove(&mut self, index: usize) -> T {
589 let len = self.len();
590 assert!(index < len);
595 // the place we are taking from.
596 let ptr = self.as_mut_ptr().offset(index as isize);
597 // copy it out, unsafely having a copy of the value on
598 // the stack and in the vector at the same time.
599 ret = ptr::read(ptr);
601 // Shift everything down to fill in that spot.
602 ptr::copy(ptr.offset(1), ptr, len - index - 1);
604 self.set_len(len - 1);
609 /// Retains only the elements specified by the predicate.
611 /// In other words, remove all elements `e` such that `f(&e)` returns false.
612 /// This method operates in place and preserves the order of the retained
618 /// let mut vec = vec![1, 2, 3, 4];
619 /// vec.retain(|&x| x%2 == 0);
620 /// assert_eq!(vec, [2, 4]);
622 #[stable(feature = "rust1", since = "1.0.0")]
623 pub fn retain<F>(&mut self, mut f: F)
624 where F: FnMut(&T) -> bool
626 let len = self.len();
640 self.truncate(len - del);
644 /// Appends an element to the back of a collection.
648 /// Panics if the number of elements in the vector overflows a `usize`.
653 /// let mut vec = vec![1, 2];
655 /// assert_eq!(vec, [1, 2, 3]);
658 #[stable(feature = "rust1", since = "1.0.0")]
659 pub fn push(&mut self, value: T) {
660 // This will panic or abort if we would allocate > isize::MAX bytes
661 // or if the length increment would overflow for zero-sized types.
662 if self.len == self.buf.cap() {
666 let end = self.as_mut_ptr().offset(self.len as isize);
667 ptr::write(end, value);
672 /// Removes the last element from a vector and returns it, or `None` if it
678 /// let mut vec = vec![1, 2, 3];
679 /// assert_eq!(vec.pop(), Some(3));
680 /// assert_eq!(vec, [1, 2]);
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn pop(&mut self) -> Option<T> {
690 Some(ptr::read(self.get_unchecked(self.len())))
695 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
699 /// Panics if the number of elements in the vector overflows a `usize`.
704 /// let mut vec = vec![1, 2, 3];
705 /// let mut vec2 = vec![4, 5, 6];
706 /// vec.append(&mut vec2);
707 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
708 /// assert_eq!(vec2, []);
711 #[stable(feature = "append", since = "1.4.0")]
712 pub fn append(&mut self, other: &mut Self) {
713 self.reserve(other.len());
714 let len = self.len();
716 ptr::copy_nonoverlapping(other.as_ptr(), self.get_unchecked_mut(len), other.len());
719 self.len += other.len();
725 /// Create a draining iterator that removes the specified range in the vector
726 /// and yields the removed items.
728 /// Note 1: The element range is removed even if the iterator is not
729 /// consumed until the end.
731 /// Note 2: 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 /// let mut v = vec![1, 2, 3];
743 /// let u: Vec<_> = v.drain(1..).collect();
744 /// assert_eq!(v, &[1]);
745 /// assert_eq!(u, &[2, 3]);
747 /// // A full range clears the vector
749 /// assert_eq!(v, &[]);
751 #[stable(feature = "drain", since = "1.6.0")]
752 pub fn drain<R>(&mut self, range: R) -> Drain<T>
753 where R: RangeArgument<usize>
757 // When the Drain is first created, it shortens the length of
758 // the source vector to make sure no uninitalized or moved-from elements
759 // are accessible at all if the Drain's destructor never gets to run.
761 // Drain will ptr::read out the values to remove.
762 // When finished, remaining tail of the vec is copied back to cover
763 // the hole, and the vector length is restored to the new length.
765 let len = self.len();
766 let start = *range.start().unwrap_or(&0);
767 let end = *range.end().unwrap_or(&len);
768 assert!(start <= end);
772 // set self.vec length's to start, to be safe in case Drain is leaked
774 // Use the borrow in the IterMut to indicate borrowing behavior of the
775 // whole Drain iterator (like &mut T).
776 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
781 iter: range_slice.iter_mut(),
787 /// Clears the vector, removing all values.
792 /// let mut v = vec![1, 2, 3];
796 /// assert!(v.is_empty());
799 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn clear(&mut self) {
804 /// Returns the number of elements in the vector.
809 /// let a = vec![1, 2, 3];
810 /// assert_eq!(a.len(), 3);
813 #[stable(feature = "rust1", since = "1.0.0")]
814 pub fn len(&self) -> usize {
818 /// Returns `true` if the vector contains no elements.
823 /// let mut v = Vec::new();
824 /// assert!(v.is_empty());
827 /// assert!(!v.is_empty());
829 #[stable(feature = "rust1", since = "1.0.0")]
830 pub fn is_empty(&self) -> bool {
834 /// Splits the collection into two at the given index.
836 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
837 /// and the returned `Self` contains elements `[at, len)`.
839 /// Note that the capacity of `self` does not change.
843 /// Panics if `at > len`.
848 /// let mut vec = vec![1,2,3];
849 /// let vec2 = vec.split_off(1);
850 /// assert_eq!(vec, [1]);
851 /// assert_eq!(vec2, [2, 3]);
854 #[stable(feature = "split_off", since = "1.4.0")]
855 pub fn split_off(&mut self, at: usize) -> Self {
856 assert!(at <= self.len(), "`at` out of bounds");
858 let other_len = self.len - at;
859 let mut other = Vec::with_capacity(other_len);
861 // Unsafely `set_len` and copy items to `other`.
864 other.set_len(other_len);
866 ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
874 impl<T: Clone> Vec<T> {
875 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
877 /// If `new_len` is greater than `len()`, the `Vec` is extended by the
878 /// difference, with each additional slot filled with `value`.
879 /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
884 /// let mut vec = vec!["hello"];
885 /// vec.resize(3, "world");
886 /// assert_eq!(vec, ["hello", "world", "world"]);
888 /// let mut vec = vec![1, 2, 3, 4];
889 /// vec.resize(2, 0);
890 /// assert_eq!(vec, [1, 2]);
892 #[stable(feature = "vec_resize", since = "1.5.0")]
893 pub fn resize(&mut self, new_len: usize, value: T) {
894 let len = self.len();
897 self.extend_with_element(new_len - len, value);
899 self.truncate(new_len);
903 /// Extend the vector by `n` additional clones of `value`.
904 fn extend_with_element(&mut self, n: usize, value: T) {
908 let len = self.len();
909 let mut ptr = self.as_mut_ptr().offset(len as isize);
910 // Write all elements except the last one
912 ptr::write(ptr, value.clone());
914 // Increment the length in every step in case clone() panics
915 self.set_len(len + i);
919 // We can write the last element directly without cloning needlessly
920 ptr::write(ptr, value);
921 self.set_len(len + n);
926 #[allow(missing_docs)]
928 #[unstable(feature = "vec_push_all",
929 reason = "likely to be replaced by a more optimized extend",
931 #[rustc_deprecated(reason = "renamed to extend_from_slice",
933 pub fn push_all(&mut self, other: &[T]) {
934 self.extend_from_slice(other)
937 /// Appends all elements in a slice to the `Vec`.
939 /// Iterates over the slice `other`, clones each element, and then appends
940 /// it to this `Vec`. The `other` vector is traversed in-order.
942 /// Note that this function is same as `extend` except that it is
943 /// specialized to work with slices instead. If and when Rust gets
944 /// specialization this function will likely be deprecated (but still
950 /// let mut vec = vec![1];
951 /// vec.extend_from_slice(&[2, 3, 4]);
952 /// assert_eq!(vec, [1, 2, 3, 4]);
954 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
955 pub fn extend_from_slice(&mut self, other: &[T]) {
956 self.reserve(other.len());
958 for i in 0..other.len() {
959 let len = self.len();
961 // Unsafe code so this can be optimised to a memcpy (or something
962 // similarly fast) when T is Copy. LLVM is easily confused, so any
963 // extra operations during the loop can prevent this optimisation.
965 ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
966 self.set_len(len + 1);
972 impl<T: PartialEq> Vec<T> {
973 /// Removes consecutive repeated elements in the vector.
975 /// If the vector is sorted, this removes all duplicates.
980 /// let mut vec = vec![1, 2, 2, 3, 2];
984 /// assert_eq!(vec, [1, 2, 3, 2]);
986 #[stable(feature = "rust1", since = "1.0.0")]
987 pub fn dedup(&mut self) {
989 // Although we have a mutable reference to `self`, we cannot make
990 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
991 // must ensure that the vector is in a valid state at all time.
993 // The way that we handle this is by using swaps; we iterate
994 // over all the elements, swapping as we go so that at the end
995 // the elements we wish to keep are in the front, and those we
996 // wish to reject are at the back. We can then truncate the
997 // vector. This operation is still O(n).
999 // Example: We start in this state, where `r` represents "next
1000 // read" and `w` represents "next_write`.
1003 // +---+---+---+---+---+---+
1004 // | 0 | 1 | 1 | 2 | 3 | 3 |
1005 // +---+---+---+---+---+---+
1008 // Comparing self[r] against self[w-1], this is not a duplicate, so
1009 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1010 // r and w, leaving us with:
1013 // +---+---+---+---+---+---+
1014 // | 0 | 1 | 1 | 2 | 3 | 3 |
1015 // +---+---+---+---+---+---+
1018 // Comparing self[r] against self[w-1], this value is a duplicate,
1019 // so we increment `r` but leave everything else unchanged:
1022 // +---+---+---+---+---+---+
1023 // | 0 | 1 | 1 | 2 | 3 | 3 |
1024 // +---+---+---+---+---+---+
1027 // Comparing self[r] against self[w-1], this is not a duplicate,
1028 // so swap self[r] and self[w] and advance r and w:
1031 // +---+---+---+---+---+---+
1032 // | 0 | 1 | 2 | 1 | 3 | 3 |
1033 // +---+---+---+---+---+---+
1036 // Not a duplicate, repeat:
1039 // +---+---+---+---+---+---+
1040 // | 0 | 1 | 2 | 3 | 1 | 3 |
1041 // +---+---+---+---+---+---+
1044 // Duplicate, advance r. End of vec. Truncate to w.
1046 let ln = self.len();
1051 // Avoid bounds checks by using raw pointers.
1052 let p = self.as_mut_ptr();
1053 let mut r: usize = 1;
1054 let mut w: usize = 1;
1057 let p_r = p.offset(r as isize);
1058 let p_wm1 = p.offset((w - 1) as isize);
1061 let p_w = p_wm1.offset(1);
1062 mem::swap(&mut *p_r, &mut *p_w);
1074 ////////////////////////////////////////////////////////////////////////////////
1075 // Internal methods and functions
1076 ////////////////////////////////////////////////////////////////////////////////
1079 #[stable(feature = "rust1", since = "1.0.0")]
1080 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1081 let mut v = Vec::with_capacity(n);
1082 v.extend_with_element(n, elem);
1086 ////////////////////////////////////////////////////////////////////////////////
1087 // Common trait implementations for Vec
1088 ////////////////////////////////////////////////////////////////////////////////
1090 #[stable(feature = "rust1", since = "1.0.0")]
1091 impl<T: Clone> Clone for Vec<T> {
1093 fn clone(&self) -> Vec<T> {
1094 <[T]>::to_vec(&**self)
1097 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1098 // required for this method definition, is not available. Instead use the
1099 // `slice::to_vec` function which is only available with cfg(test)
1100 // NB see the slice::hack module in slice.rs for more information
1102 fn clone(&self) -> Vec<T> {
1103 ::slice::to_vec(&**self)
1106 fn clone_from(&mut self, other: &Vec<T>) {
1107 // drop anything in self that will not be overwritten
1108 self.truncate(other.len());
1109 let len = self.len();
1111 // reuse the contained values' allocations/resources.
1112 self.clone_from_slice(&other[..len]);
1114 // self.len <= other.len due to the truncate above, so the
1115 // slice here is always in-bounds.
1116 self.extend_from_slice(&other[len..]);
1120 #[stable(feature = "rust1", since = "1.0.0")]
1121 impl<T: Hash> Hash for Vec<T> {
1123 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1124 Hash::hash(&**self, state)
1128 #[stable(feature = "rust1", since = "1.0.0")]
1129 impl<T> Index<usize> for Vec<T> {
1133 fn index(&self, index: usize) -> &T {
1134 // NB built-in indexing via `&[T]`
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl<T> IndexMut<usize> for Vec<T> {
1142 fn index_mut(&mut self, index: usize) -> &mut T {
1143 // NB built-in indexing via `&mut [T]`
1144 &mut (**self)[index]
1149 #[stable(feature = "rust1", since = "1.0.0")]
1150 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1154 fn index(&self, index: ops::Range<usize>) -> &[T] {
1155 Index::index(&**self, index)
1158 #[stable(feature = "rust1", since = "1.0.0")]
1159 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1163 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1164 Index::index(&**self, index)
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1172 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1173 Index::index(&**self, index)
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1181 fn index(&self, _index: ops::RangeFull) -> &[T] {
1186 #[stable(feature = "rust1", since = "1.0.0")]
1187 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1189 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1190 IndexMut::index_mut(&mut **self, index)
1193 #[stable(feature = "rust1", since = "1.0.0")]
1194 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1196 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1197 IndexMut::index_mut(&mut **self, index)
1200 #[stable(feature = "rust1", since = "1.0.0")]
1201 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1203 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1204 IndexMut::index_mut(&mut **self, index)
1207 #[stable(feature = "rust1", since = "1.0.0")]
1208 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1210 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1215 #[stable(feature = "rust1", since = "1.0.0")]
1216 impl<T> ops::Deref for Vec<T> {
1219 fn deref(&self) -> &[T] {
1221 let p = self.buf.ptr();
1222 assume(!p.is_null());
1223 slice::from_raw_parts(p, self.len)
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 impl<T> ops::DerefMut for Vec<T> {
1230 fn deref_mut(&mut self) -> &mut [T] {
1232 let ptr = self.buf.ptr();
1233 assume(!ptr.is_null());
1234 slice::from_raw_parts_mut(ptr, self.len)
1239 #[stable(feature = "rust1", since = "1.0.0")]
1240 impl<T> FromIterator<T> for Vec<T> {
1242 fn from_iter<I: IntoIterator<Item = T>>(iterable: I) -> Vec<T> {
1243 // Unroll the first iteration, as the vector is going to be
1244 // expanded on this iteration in every case when the iterable is not
1245 // empty, but the loop in extend_desugared() is not going to see the
1246 // vector being full in the few subsequent loop iterations.
1247 // So we get better branch prediction.
1248 let mut iterator = iterable.into_iter();
1249 let mut vector = match iterator.next() {
1250 None => return Vec::new(),
1252 let (lower, _) = iterator.size_hint();
1253 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1255 ptr::write(vector.get_unchecked_mut(0), element);
1261 vector.extend_desugared(iterator);
1266 #[stable(feature = "rust1", since = "1.0.0")]
1267 impl<T> IntoIterator for Vec<T> {
1269 type IntoIter = IntoIter<T>;
1271 /// Creates a consuming iterator, that is, one that moves each value out of
1272 /// the vector (from start to end). The vector cannot be used after calling
1278 /// let v = vec!["a".to_string(), "b".to_string()];
1279 /// for s in v.into_iter() {
1280 /// // s has type String, not &String
1281 /// println!("{}", s);
1285 fn into_iter(mut self) -> IntoIter<T> {
1287 let ptr = self.as_mut_ptr();
1288 assume(!ptr.is_null());
1289 let begin = ptr as *const T;
1290 let end = if mem::size_of::<T>() == 0 {
1291 arith_offset(ptr as *const i8, self.len() as isize) as *const T
1293 ptr.offset(self.len() as isize) as *const T
1295 let buf = ptr::read(&self.buf);
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl<'a, T> IntoIterator for &'a Vec<T> {
1309 type IntoIter = slice::Iter<'a, T>;
1311 fn into_iter(self) -> slice::Iter<'a, T> {
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1318 type Item = &'a mut T;
1319 type IntoIter = slice::IterMut<'a, T>;
1321 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1326 #[stable(feature = "rust1", since = "1.0.0")]
1327 impl<T> Extend<T> for Vec<T> {
1329 fn extend<I: IntoIterator<Item = T>>(&mut self, iterable: I) {
1330 self.extend_desugared(iterable.into_iter())
1335 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1336 // This function should be the moral equivalent of:
1338 // for item in iterator {
1341 while let Some(element) = iterator.next() {
1342 let len = self.len();
1343 if len == self.capacity() {
1344 let (lower, _) = iterator.size_hint();
1345 self.reserve(lower.saturating_add(1));
1348 ptr::write(self.get_unchecked_mut(len), element);
1349 // NB can't overflow since we would have had to alloc the address space
1350 self.set_len(len + 1);
1356 #[stable(feature = "extend_ref", since = "1.2.0")]
1357 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1358 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1359 self.extend(iter.into_iter().cloned());
1363 macro_rules! __impl_slice_eq1 {
1364 ($Lhs: ty, $Rhs: ty) => {
1365 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1367 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1368 #[stable(feature = "rust1", since = "1.0.0")]
1369 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
1371 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
1373 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
1378 __impl_slice_eq1! { Vec<A>, Vec<B> }
1379 __impl_slice_eq1! { Vec<A>, &'b [B] }
1380 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1381 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1382 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1383 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1385 macro_rules! array_impls {
1388 // NOTE: some less important impls are omitted to reduce code bloat
1389 __impl_slice_eq1! { Vec<A>, [B; $N] }
1390 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1391 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1392 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1393 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1394 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1401 10 11 12 13 14 15 16 17 18 19
1402 20 21 22 23 24 25 26 27 28 29
1406 #[stable(feature = "rust1", since = "1.0.0")]
1407 impl<T: PartialOrd> PartialOrd for Vec<T> {
1409 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1410 PartialOrd::partial_cmp(&**self, &**other)
1414 #[stable(feature = "rust1", since = "1.0.0")]
1415 impl<T: Eq> Eq for Vec<T> {}
1417 #[stable(feature = "rust1", since = "1.0.0")]
1418 impl<T: Ord> Ord for Vec<T> {
1420 fn cmp(&self, other: &Vec<T>) -> Ordering {
1421 Ord::cmp(&**self, &**other)
1425 #[stable(feature = "rust1", since = "1.0.0")]
1426 impl<T> Drop for Vec<T> {
1427 #[unsafe_destructor_blind_to_params]
1428 fn drop(&mut self) {
1429 if self.buf.unsafe_no_drop_flag_needs_drop() {
1431 // The branch on needs_drop() is an -O1 performance optimization.
1432 // Without the branch, dropping Vec<u8> takes linear time.
1433 if needs_drop::<T>() {
1434 for x in self.iter_mut() {
1435 ptr::drop_in_place(x);
1440 // RawVec handles deallocation
1444 #[stable(feature = "rust1", since = "1.0.0")]
1445 impl<T> Default for Vec<T> {
1446 fn default() -> Vec<T> {
1451 #[stable(feature = "rust1", since = "1.0.0")]
1452 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1453 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1454 fmt::Debug::fmt(&**self, f)
1458 #[stable(feature = "rust1", since = "1.0.0")]
1459 impl<T> AsRef<Vec<T>> for Vec<T> {
1460 fn as_ref(&self) -> &Vec<T> {
1465 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1466 impl<T> AsMut<Vec<T>> for Vec<T> {
1467 fn as_mut(&mut self) -> &mut Vec<T> {
1472 #[stable(feature = "rust1", since = "1.0.0")]
1473 impl<T> AsRef<[T]> for Vec<T> {
1474 fn as_ref(&self) -> &[T] {
1479 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1480 impl<T> AsMut<[T]> for Vec<T> {
1481 fn as_mut(&mut self) -> &mut [T] {
1486 #[stable(feature = "rust1", since = "1.0.0")]
1487 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1489 fn from(s: &'a [T]) -> Vec<T> {
1493 fn from(s: &'a [T]) -> Vec<T> {
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<'a> From<&'a str> for Vec<u8> {
1500 fn from(s: &'a str) -> Vec<u8> {
1501 From::from(s.as_bytes())
1505 ////////////////////////////////////////////////////////////////////////////////
1507 ////////////////////////////////////////////////////////////////////////////////
1509 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1510 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
1511 fn from(s: &'a [T]) -> Cow<'a, [T]> {
1516 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1517 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
1518 fn from(v: Vec<T>) -> Cow<'a, [T]> {
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1525 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
1526 Cow::Owned(FromIterator::from_iter(it))
1530 #[stable(feature = "rust1", since = "1.0.0")]
1531 #[allow(deprecated)]
1532 impl<'a, T: 'a> IntoCow<'a, [T]> for Vec<T> where T: Clone {
1533 fn into_cow(self) -> Cow<'a, [T]> {
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 #[allow(deprecated)]
1540 impl<'a, T> IntoCow<'a, [T]> for &'a [T] where T: Clone {
1541 fn into_cow(self) -> Cow<'a, [T]> {
1546 ////////////////////////////////////////////////////////////////////////////////
1548 ////////////////////////////////////////////////////////////////////////////////
1550 /// An iterator that moves out of a vector.
1551 #[stable(feature = "rust1", since = "1.0.0")]
1552 pub struct IntoIter<T> {
1558 #[stable(feature = "rust1", since = "1.0.0")]
1559 unsafe impl<T: Send> Send for IntoIter<T> {}
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 unsafe impl<T: Sync> Sync for IntoIter<T> {}
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 impl<T> Iterator for IntoIter<T> {
1568 fn next(&mut self) -> Option<T> {
1570 if self.ptr == self.end {
1573 if mem::size_of::<T>() == 0 {
1574 // purposefully don't use 'ptr.offset' because for
1575 // vectors with 0-size elements this would return the
1577 self.ptr = arith_offset(self.ptr as *const i8, 1) as *const T;
1579 // Use a non-null pointer value
1580 Some(ptr::read(EMPTY as *mut T))
1583 self.ptr = self.ptr.offset(1);
1585 Some(ptr::read(old))
1592 fn size_hint(&self) -> (usize, Option<usize>) {
1593 let diff = (self.end as usize) - (self.ptr as usize);
1594 let size = mem::size_of::<T>();
1601 (exact, Some(exact))
1605 fn count(self) -> usize {
1610 #[stable(feature = "rust1", since = "1.0.0")]
1611 impl<T> DoubleEndedIterator for IntoIter<T> {
1613 fn next_back(&mut self) -> Option<T> {
1615 if self.end == self.ptr {
1618 if mem::size_of::<T>() == 0 {
1619 // See above for why 'ptr.offset' isn't used
1620 self.end = arith_offset(self.end as *const i8, -1) as *const T;
1622 // Use a non-null pointer value
1623 Some(ptr::read(EMPTY as *mut T))
1625 self.end = self.end.offset(-1);
1627 Some(ptr::read(self.end))
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 impl<T> ExactSizeIterator for IntoIter<T> {}
1637 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
1638 impl<T: Clone> Clone for IntoIter<T> {
1639 fn clone(&self) -> IntoIter<T> {
1641 slice::from_raw_parts(self.ptr, self.len()).to_owned().into_iter()
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl<T> Drop for IntoIter<T> {
1648 #[unsafe_destructor_blind_to_params]
1649 fn drop(&mut self) {
1650 // destroy the remaining elements
1653 // RawVec handles deallocation
1657 /// A draining iterator for `Vec<T>`.
1658 #[stable(feature = "drain", since = "1.6.0")]
1659 pub struct Drain<'a, T: 'a> {
1660 /// Index of tail to preserve
1664 /// Current remaining range to remove
1665 iter: slice::IterMut<'a, T>,
1669 #[stable(feature = "drain", since = "1.6.0")]
1670 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1671 #[stable(feature = "drain", since = "1.6.0")]
1672 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1674 #[stable(feature = "rust1", since = "1.0.0")]
1675 impl<'a, T> Iterator for Drain<'a, T> {
1679 fn next(&mut self) -> Option<T> {
1680 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
1683 fn size_hint(&self) -> (usize, Option<usize>) {
1684 self.iter.size_hint()
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1691 fn next_back(&mut self) -> Option<T> {
1692 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 impl<'a, T> Drop for Drain<'a, T> {
1698 fn drop(&mut self) {
1699 // exhaust self first
1700 while let Some(_) = self.next() {}
1702 if self.tail_len > 0 {
1704 let source_vec = &mut *self.vec;
1705 // memmove back untouched tail, update to new length
1706 let start = source_vec.len();
1707 let tail = self.tail_start;
1708 let src = source_vec.as_ptr().offset(tail as isize);
1709 let dst = source_vec.as_mut_ptr().offset(start as isize);
1710 ptr::copy(src, dst, self.tail_len);
1711 source_vec.set_len(start + self.tail_len);
1718 #[stable(feature = "rust1", since = "1.0.0")]
1719 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}