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, Deref};
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 /// #![feature(drain)]
744 /// // Draining using `..` clears the whole vector.
745 /// let mut v = vec![1, 2, 3];
746 /// let u: Vec<_> = v.drain(..).collect();
747 /// assert_eq!(v, &[]);
748 /// assert_eq!(u, &[1, 2, 3]);
750 #[unstable(feature = "drain",
751 reason = "recently added, matches RFC",
753 pub fn drain<R>(&mut self, range: R) -> Drain<T>
754 where R: RangeArgument<usize>
758 // When the Drain is first created, it shortens the length of
759 // the source vector to make sure no uninitalized or moved-from elements
760 // are accessible at all if the Drain's destructor never gets to run.
762 // Drain will ptr::read out the values to remove.
763 // When finished, remaining tail of the vec is copied back to cover
764 // the hole, and the vector length is restored to the new length.
766 let len = self.len();
767 let start = *range.start().unwrap_or(&0);
768 let end = *range.end().unwrap_or(&len);
769 assert!(start <= end);
773 // set self.vec length's to start, to be safe in case Drain is leaked
775 // Use the borrow in the IterMut to indicate borrowing behavior of the
776 // whole Drain iterator (like &mut T).
777 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
782 iter: range_slice.iter_mut(),
788 /// Clears the vector, removing all values.
793 /// let mut v = vec![1, 2, 3];
797 /// assert!(v.is_empty());
800 #[stable(feature = "rust1", since = "1.0.0")]
801 pub fn clear(&mut self) {
805 /// Returns the number of elements in the vector.
810 /// let a = vec![1, 2, 3];
811 /// assert_eq!(a.len(), 3);
814 #[stable(feature = "rust1", since = "1.0.0")]
815 pub fn len(&self) -> usize {
819 /// Returns `true` if the vector contains no elements.
824 /// let mut v = Vec::new();
825 /// assert!(v.is_empty());
828 /// assert!(!v.is_empty());
830 #[stable(feature = "rust1", since = "1.0.0")]
831 pub fn is_empty(&self) -> bool {
835 /// Splits the collection into two at the given index.
837 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
838 /// and the returned `Self` contains elements `[at, len)`.
840 /// Note that the capacity of `self` does not change.
844 /// Panics if `at > len`.
849 /// let mut vec = vec![1,2,3];
850 /// let vec2 = vec.split_off(1);
851 /// assert_eq!(vec, [1]);
852 /// assert_eq!(vec2, [2, 3]);
855 #[stable(feature = "split_off", since = "1.4.0")]
856 pub fn split_off(&mut self, at: usize) -> Self {
857 assert!(at <= self.len(), "`at` out of bounds");
859 let other_len = self.len - at;
860 let mut other = Vec::with_capacity(other_len);
862 // Unsafely `set_len` and copy items to `other`.
865 other.set_len(other_len);
867 ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
875 impl<T: Clone> Vec<T> {
876 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
878 /// If `new_len` is greater than `len()`, the `Vec` is extended by the
879 /// difference, with each additional slot filled with `value`.
880 /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
885 /// let mut vec = vec!["hello"];
886 /// vec.resize(3, "world");
887 /// assert_eq!(vec, ["hello", "world", "world"]);
889 /// let mut vec = vec![1, 2, 3, 4];
890 /// vec.resize(2, 0);
891 /// assert_eq!(vec, [1, 2]);
893 #[stable(feature = "vec_resize", since = "1.5.0")]
894 pub fn resize(&mut self, new_len: usize, value: T) {
895 let len = self.len();
898 self.extend_with_element(new_len - len, value);
900 self.truncate(new_len);
904 /// Extend the vector by `n` additional clones of `value`.
905 fn extend_with_element(&mut self, n: usize, value: T) {
909 let len = self.len();
910 let mut ptr = self.as_mut_ptr().offset(len as isize);
911 // Write all elements except the last one
913 ptr::write(ptr, value.clone());
915 // Increment the length in every step in case clone() panics
916 self.set_len(len + i);
920 // We can write the last element directly without cloning needlessly
921 ptr::write(ptr, value);
922 self.set_len(len + n);
927 /// Appends all elements in a slice to the `Vec`.
929 /// Iterates over the slice `other`, clones each element, and then appends
930 /// it to this `Vec`. The `other` vector is traversed in-order.
935 /// #![feature(vec_push_all)]
937 /// let mut vec = vec![1];
938 /// vec.push_all(&[2, 3, 4]);
939 /// assert_eq!(vec, [1, 2, 3, 4]);
942 #[unstable(feature = "vec_push_all",
943 reason = "likely to be replaced by a more optimized extend",
945 pub fn push_all(&mut self, other: &[T]) {
946 self.reserve(other.len());
948 for i in 0..other.len() {
949 let len = self.len();
951 // Unsafe code so this can be optimised to a memcpy (or something
952 // similarly fast) when T is Copy. LLVM is easily confused, so any
953 // extra operations during the loop can prevent this optimisation.
955 ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
956 self.set_len(len + 1);
962 impl<T: PartialEq> Vec<T> {
963 /// Removes consecutive repeated elements in the vector.
965 /// If the vector is sorted, this removes all duplicates.
970 /// let mut vec = vec![1, 2, 2, 3, 2];
974 /// assert_eq!(vec, [1, 2, 3, 2]);
976 #[stable(feature = "rust1", since = "1.0.0")]
977 pub fn dedup(&mut self) {
979 // Although we have a mutable reference to `self`, we cannot make
980 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
981 // must ensure that the vector is in a valid state at all time.
983 // The way that we handle this is by using swaps; we iterate
984 // over all the elements, swapping as we go so that at the end
985 // the elements we wish to keep are in the front, and those we
986 // wish to reject are at the back. We can then truncate the
987 // vector. This operation is still O(n).
989 // Example: We start in this state, where `r` represents "next
990 // read" and `w` represents "next_write`.
993 // +---+---+---+---+---+---+
994 // | 0 | 1 | 1 | 2 | 3 | 3 |
995 // +---+---+---+---+---+---+
998 // Comparing self[r] against self[w-1], this is not a duplicate, so
999 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1000 // r and w, leaving us with:
1003 // +---+---+---+---+---+---+
1004 // | 0 | 1 | 1 | 2 | 3 | 3 |
1005 // +---+---+---+---+---+---+
1008 // Comparing self[r] against self[w-1], this value is a duplicate,
1009 // so we increment `r` but leave everything else unchanged:
1012 // +---+---+---+---+---+---+
1013 // | 0 | 1 | 1 | 2 | 3 | 3 |
1014 // +---+---+---+---+---+---+
1017 // Comparing self[r] against self[w-1], this is not a duplicate,
1018 // so swap self[r] and self[w] and advance r and w:
1021 // +---+---+---+---+---+---+
1022 // | 0 | 1 | 2 | 1 | 3 | 3 |
1023 // +---+---+---+---+---+---+
1026 // Not a duplicate, repeat:
1029 // +---+---+---+---+---+---+
1030 // | 0 | 1 | 2 | 3 | 1 | 3 |
1031 // +---+---+---+---+---+---+
1034 // Duplicate, advance r. End of vec. Truncate to w.
1036 let ln = self.len();
1041 // Avoid bounds checks by using raw pointers.
1042 let p = self.as_mut_ptr();
1043 let mut r: usize = 1;
1044 let mut w: usize = 1;
1047 let p_r = p.offset(r as isize);
1048 let p_wm1 = p.offset((w - 1) as isize);
1051 let p_w = p_wm1.offset(1);
1052 mem::swap(&mut *p_r, &mut *p_w);
1064 ////////////////////////////////////////////////////////////////////////////////
1065 // Internal methods and functions
1066 ////////////////////////////////////////////////////////////////////////////////
1069 #[stable(feature = "rust1", since = "1.0.0")]
1070 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1071 let mut v = Vec::with_capacity(n);
1072 v.extend_with_element(n, elem);
1076 ////////////////////////////////////////////////////////////////////////////////
1077 // Common trait implementations for Vec
1078 ////////////////////////////////////////////////////////////////////////////////
1080 #[stable(feature = "rust1", since = "1.0.0")]
1081 impl<T: Clone> Clone for Vec<T> {
1083 fn clone(&self) -> Vec<T> {
1084 <[T]>::to_vec(&**self)
1087 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1088 // required for this method definition, is not available. Instead use the
1089 // `slice::to_vec` function which is only available with cfg(test)
1090 // NB see the slice::hack module in slice.rs for more information
1092 fn clone(&self) -> Vec<T> {
1093 ::slice::to_vec(&**self)
1096 fn clone_from(&mut self, other: &Vec<T>) {
1097 // drop anything in self that will not be overwritten
1098 self.truncate(other.len());
1099 let len = self.len();
1101 // reuse the contained values' allocations/resources.
1102 self.clone_from_slice(&other[..len]);
1104 // self.len <= other.len due to the truncate above, so the
1105 // slice here is always in-bounds.
1106 self.push_all(&other[len..]);
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 impl<T: Hash> Hash for Vec<T> {
1113 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1114 Hash::hash(&**self, state)
1118 #[stable(feature = "rust1", since = "1.0.0")]
1119 impl<T> Index<usize> for Vec<T> {
1123 fn index(&self, index: usize) -> &T {
1124 // NB built-in indexing via `&[T]`
1129 #[stable(feature = "rust1", since = "1.0.0")]
1130 impl<T> IndexMut<usize> for Vec<T> {
1132 fn index_mut(&mut self, index: usize) -> &mut T {
1133 // NB built-in indexing via `&mut [T]`
1134 &mut (**self)[index]
1139 #[stable(feature = "rust1", since = "1.0.0")]
1140 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1144 fn index(&self, index: ops::Range<usize>) -> &[T] {
1145 Index::index(&**self, index)
1148 #[stable(feature = "rust1", since = "1.0.0")]
1149 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1153 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1154 Index::index(&**self, index)
1157 #[stable(feature = "rust1", since = "1.0.0")]
1158 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1162 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1163 Index::index(&**self, index)
1166 #[stable(feature = "rust1", since = "1.0.0")]
1167 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1171 fn index(&self, _index: ops::RangeFull) -> &[T] {
1176 #[stable(feature = "rust1", since = "1.0.0")]
1177 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1179 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1180 IndexMut::index_mut(&mut **self, index)
1183 #[stable(feature = "rust1", since = "1.0.0")]
1184 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1186 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1187 IndexMut::index_mut(&mut **self, index)
1190 #[stable(feature = "rust1", since = "1.0.0")]
1191 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1193 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1194 IndexMut::index_mut(&mut **self, index)
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1200 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 impl<T> ops::Deref for Vec<T> {
1209 fn deref(&self) -> &[T] {
1211 let p = self.buf.ptr();
1212 assume(!p.is_null());
1213 slice::from_raw_parts(p, self.len)
1218 #[stable(feature = "rust1", since = "1.0.0")]
1219 impl<T> ops::DerefMut for Vec<T> {
1220 fn deref_mut(&mut self) -> &mut [T] {
1222 let ptr = self.buf.ptr();
1223 assume(!ptr.is_null());
1224 slice::from_raw_parts_mut(ptr, self.len)
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 impl<T> FromIterator<T> for Vec<T> {
1232 fn from_iter<I: IntoIterator<Item = T>>(iterable: I) -> Vec<T> {
1233 // Unroll the first iteration, as the vector is going to be
1234 // expanded on this iteration in every case when the iterable is not
1235 // empty, but the loop in extend_desugared() is not going to see the
1236 // vector being full in the few subsequent loop iterations.
1237 // So we get better branch prediction.
1238 let mut iterator = iterable.into_iter();
1239 let mut vector = match iterator.next() {
1240 None => return Vec::new(),
1242 let (lower, _) = iterator.size_hint();
1243 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1245 ptr::write(vector.get_unchecked_mut(0), element);
1251 vector.extend_desugared(iterator);
1256 #[stable(feature = "rust1", since = "1.0.0")]
1257 impl<T> IntoIterator for Vec<T> {
1259 type IntoIter = IntoIter<T>;
1261 /// Creates a consuming iterator, that is, one that moves each value out of
1262 /// the vector (from start to end). The vector cannot be used after calling
1268 /// let v = vec!["a".to_string(), "b".to_string()];
1269 /// for s in v.into_iter() {
1270 /// // s has type String, not &String
1271 /// println!("{}", s);
1275 fn into_iter(mut self) -> IntoIter<T> {
1277 let ptr = self.as_mut_ptr();
1278 assume(!ptr.is_null());
1279 let begin = ptr as *const T;
1280 let end = if mem::size_of::<T>() == 0 {
1281 arith_offset(ptr as *const i8, self.len() as isize) as *const T
1283 ptr.offset(self.len() as isize) as *const T
1285 let buf = ptr::read(&self.buf);
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 impl<'a, T> IntoIterator for &'a Vec<T> {
1299 type IntoIter = slice::Iter<'a, T>;
1301 fn into_iter(self) -> slice::Iter<'a, T> {
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1308 type Item = &'a mut T;
1309 type IntoIter = slice::IterMut<'a, T>;
1311 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1316 #[stable(feature = "rust1", since = "1.0.0")]
1317 impl<T> Extend<T> for Vec<T> {
1319 fn extend<I: IntoIterator<Item = T>>(&mut self, iterable: I) {
1320 self.extend_desugared(iterable.into_iter())
1325 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1326 // This function should be the moral equivalent of:
1328 // for item in iterator {
1331 while let Some(element) = iterator.next() {
1332 let len = self.len();
1333 if len == self.capacity() {
1334 let (lower, _) = iterator.size_hint();
1335 self.reserve(lower.saturating_add(1));
1338 ptr::write(self.get_unchecked_mut(len), element);
1339 // NB can't overflow since we would have had to alloc the address space
1340 self.set_len(len + 1);
1346 #[stable(feature = "extend_ref", since = "1.2.0")]
1347 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1348 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1349 self.extend(iter.into_iter().cloned());
1353 __impl_slice_eq1! { Vec<A>, Vec<B> }
1354 __impl_slice_eq1! { Vec<A>, &'b [B] }
1355 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1356 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1357 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1358 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1360 macro_rules! array_impls {
1363 // NOTE: some less important impls are omitted to reduce code bloat
1364 __impl_slice_eq1! { Vec<A>, [B; $N] }
1365 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1366 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1367 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1368 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1369 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1376 10 11 12 13 14 15 16 17 18 19
1377 20 21 22 23 24 25 26 27 28 29
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 impl<T: PartialOrd> PartialOrd for Vec<T> {
1384 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1385 PartialOrd::partial_cmp(&**self, &**other)
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl<T: Eq> Eq for Vec<T> {}
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 impl<T: Ord> Ord for Vec<T> {
1395 fn cmp(&self, other: &Vec<T>) -> Ordering {
1396 Ord::cmp(&**self, &**other)
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<T> Drop for Vec<T> {
1402 #[unsafe_destructor_blind_to_params]
1403 fn drop(&mut self) {
1404 if self.buf.unsafe_no_drop_flag_needs_drop() {
1406 // The branch on needs_drop() is an -O1 performance optimization.
1407 // Without the branch, dropping Vec<u8> takes linear time.
1408 if needs_drop::<T>() {
1409 for x in self.iter_mut() {
1410 ptr::drop_in_place(x);
1415 // RawVec handles deallocation
1419 #[stable(feature = "rust1", since = "1.0.0")]
1420 impl<T> Default for Vec<T> {
1421 fn default() -> Vec<T> {
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1428 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1429 fmt::Debug::fmt(&**self, f)
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<T> AsRef<Vec<T>> for Vec<T> {
1435 fn as_ref(&self) -> &Vec<T> {
1440 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1441 impl<T> AsMut<Vec<T>> for Vec<T> {
1442 fn as_mut(&mut self) -> &mut Vec<T> {
1447 #[stable(feature = "rust1", since = "1.0.0")]
1448 impl<T> AsRef<[T]> for Vec<T> {
1449 fn as_ref(&self) -> &[T] {
1454 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1455 impl<T> AsMut<[T]> for Vec<T> {
1456 fn as_mut(&mut self) -> &mut [T] {
1461 #[stable(feature = "rust1", since = "1.0.0")]
1462 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1464 fn from(s: &'a [T]) -> Vec<T> {
1468 fn from(s: &'a [T]) -> Vec<T> {
1473 #[stable(feature = "rust1", since = "1.0.0")]
1474 impl<'a> From<&'a str> for Vec<u8> {
1475 fn from(s: &'a str) -> Vec<u8> {
1476 From::from(s.as_bytes())
1480 ////////////////////////////////////////////////////////////////////////////////
1482 ////////////////////////////////////////////////////////////////////////////////
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1486 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
1487 Cow::Owned(FromIterator::from_iter(it))
1491 #[stable(feature = "rust1", since = "1.0.0")]
1492 impl<'a, T: 'a> IntoCow<'a, [T]> for Vec<T> where T: Clone {
1493 fn into_cow(self) -> Cow<'a, [T]> {
1498 #[stable(feature = "rust1", since = "1.0.0")]
1499 impl<'a, T> IntoCow<'a, [T]> for &'a [T] where T: Clone {
1500 fn into_cow(self) -> Cow<'a, [T]> {
1505 ////////////////////////////////////////////////////////////////////////////////
1507 ////////////////////////////////////////////////////////////////////////////////
1509 /// An iterator that moves out of a vector.
1510 #[stable(feature = "rust1", since = "1.0.0")]
1511 pub struct IntoIter<T> {
1517 #[stable(feature = "rust1", since = "1.0.0")]
1518 unsafe impl<T: Send> Send for IntoIter<T> {}
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 unsafe impl<T: Sync> Sync for IntoIter<T> {}
1522 #[stable(feature = "rust1", since = "1.0.0")]
1523 impl<T> Iterator for IntoIter<T> {
1527 fn next(&mut self) -> Option<T> {
1529 if self.ptr == self.end {
1532 if mem::size_of::<T>() == 0 {
1533 // purposefully don't use 'ptr.offset' because for
1534 // vectors with 0-size elements this would return the
1536 self.ptr = arith_offset(self.ptr as *const i8, 1) as *const T;
1538 // Use a non-null pointer value
1539 Some(ptr::read(EMPTY as *mut T))
1542 self.ptr = self.ptr.offset(1);
1544 Some(ptr::read(old))
1551 fn size_hint(&self) -> (usize, Option<usize>) {
1552 let diff = (self.end as usize) - (self.ptr as usize);
1553 let size = mem::size_of::<T>();
1560 (exact, Some(exact))
1564 fn count(self) -> usize {
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl<T> DoubleEndedIterator for IntoIter<T> {
1572 fn next_back(&mut self) -> Option<T> {
1574 if self.end == self.ptr {
1577 if mem::size_of::<T>() == 0 {
1578 // See above for why 'ptr.offset' isn't used
1579 self.end = arith_offset(self.end as *const i8, -1) as *const T;
1581 // Use a non-null pointer value
1582 Some(ptr::read(EMPTY as *mut T))
1584 self.end = self.end.offset(-1);
1586 Some(ptr::read(self.end))
1593 #[stable(feature = "rust1", since = "1.0.0")]
1594 impl<T> ExactSizeIterator for IntoIter<T> {}
1596 #[stable(feature = "rust1", since = "1.0.0")]
1597 impl<T> Drop for IntoIter<T> {
1598 #[unsafe_destructor_blind_to_params]
1599 fn drop(&mut self) {
1600 // destroy the remaining elements
1603 // RawVec handles deallocation
1607 /// A draining iterator for `Vec<T>`.
1608 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1609 pub struct Drain<'a, T: 'a> {
1610 /// Index of tail to preserve
1614 /// Current remaining range to remove
1615 iter: slice::IterMut<'a, T>,
1619 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1620 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1621 #[unstable(feature = "drain", reason = "recently added", issue = "27711")]
1622 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1624 #[stable(feature = "rust1", since = "1.0.0")]
1625 impl<'a, T> Iterator for Drain<'a, T> {
1629 fn next(&mut self) -> Option<T> {
1630 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
1633 fn size_hint(&self) -> (usize, Option<usize>) {
1634 self.iter.size_hint()
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1641 fn next_back(&mut self) -> Option<T> {
1642 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl<'a, T> Drop for Drain<'a, T> {
1648 fn drop(&mut self) {
1649 // exhaust self first
1650 while let Some(_) = self.next() {}
1652 if self.tail_len > 0 {
1654 let source_vec = &mut *self.vec;
1655 // memmove back untouched tail, update to new length
1656 let start = source_vec.len();
1657 let tail = self.tail_start;
1658 let src = source_vec.as_ptr().offset(tail as isize);
1659 let dst = source_vec.as_mut_ptr().offset(start as isize);
1660 ptr::copy(src, dst, self.tail_len);
1661 source_vec.set_len(start + self.tail_len);
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}