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;
67 use core::cmp::Ordering;
69 use core::hash::{self, Hash};
70 use core::intrinsics::{arith_offset, assume};
71 use core::iter::FromIterator;
73 use core::ops::{Index, IndexMut};
76 use core::ptr::Shared;
79 use super::SpecExtend;
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);
140 /// The Vec type allows to access values by index, because it implements the
141 /// `Index` trait. An example will be more explicit:
144 /// let v = vec!(0, 2, 4, 6);
145 /// println!("{}", v[1]); // it will display '2'
148 /// However be careful: if you try to access an index which isn't in the Vec,
149 /// your software will panic! You cannot do this:
152 /// let v = vec!(0, 2, 4, 6);
153 /// println!("{}", v[6]); // it will panic!
156 /// In conclusion: always check if the index you want to get really exists
161 /// A Vec can be mutable. Slices, on the other hand, are read-only objects.
162 /// To get a slice, use "&". Example:
165 /// fn read_slice(slice: &[usize]) {
169 /// let v = vec!(0, 1);
172 /// // ... and that's all!
173 /// // you can also do it like this:
174 /// let x : &[usize] = &v;
177 /// In Rust, it's more common to pass slices as arguments rather than vectors
178 /// when you just want to provide a read access. The same goes for String and
181 /// # Capacity and reallocation
183 /// The capacity of a vector is the amount of space allocated for any future
184 /// elements that will be added onto the vector. This is not to be confused with
185 /// the *length* of a vector, which specifies the number of actual elements
186 /// within the vector. If a vector's length exceeds its capacity, its capacity
187 /// will automatically be increased, but its elements will have to be
190 /// For example, a vector with capacity 10 and length 0 would be an empty vector
191 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
192 /// vector will not change its capacity or cause reallocation to occur. However,
193 /// if the vector's length is increased to 11, it will have to reallocate, which
194 /// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
195 /// whenever possible to specify how big the vector is expected to get.
199 /// Due to its incredibly fundamental nature, Vec makes a lot of guarantees
200 /// about its design. This ensures that it's as low-overhead as possible in
201 /// the general case, and can be correctly manipulated in primitive ways
202 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
203 /// If additional type parameters are added (e.g. to support custom allocators),
204 /// overriding their defaults may change the behavior.
206 /// Most fundamentally, Vec is and always will be a (pointer, capacity, length)
207 /// triplet. No more, no less. The order of these fields is completely
208 /// unspecified, and you should use the appropriate methods to modify these.
209 /// The pointer will never be null, so this type is null-pointer-optimized.
211 /// However, the pointer may not actually point to allocated memory. In particular,
212 /// if you construct a Vec with capacity 0 via `Vec::new()`, `vec![]`,
213 /// `Vec::with_capacity(0)`, or by calling `shrink_to_fit()` on an empty Vec, it
214 /// will not allocate memory. Similarly, if you store zero-sized types inside
215 /// a Vec, it will not allocate space for them. *Note that in this case the
216 /// Vec may not report a `capacity()` of 0*. Vec will allocate if and only
217 /// if `mem::size_of::<T>() * capacity() > 0`. In general, Vec's allocation
218 /// details are subtle enough that it is strongly recommended that you only
219 /// free memory allocated by a Vec by creating a new Vec and dropping it.
221 /// If a Vec *has* allocated memory, then the memory it points to is on the heap
222 /// (as defined by the allocator Rust is configured to use by default), and its
223 /// pointer points to `len()` initialized elements in order (what you would see
224 /// if you coerced it to a slice), followed by `capacity() - len()` logically
225 /// uninitialized elements.
227 /// Vec will never perform a "small optimization" where elements are actually
228 /// stored on the stack for two reasons:
230 /// * It would make it more difficult for unsafe code to correctly manipulate
231 /// a Vec. The contents of a Vec wouldn't have a stable address if it were
232 /// only moved, and it would be more difficult to determine if a Vec had
233 /// actually allocated memory.
235 /// * It would penalize the general case, incurring an additional branch
238 /// Vec will never automatically shrink itself, even if completely empty. This
239 /// ensures no unnecessary allocations or deallocations occur. Emptying a Vec
240 /// and then filling it back up to the same `len()` should incur no calls to
241 /// the allocator. If you wish to free up unused memory, use `shrink_to_fit`.
243 /// `push` and `insert` will never (re)allocate if the reported capacity is
244 /// sufficient. `push` and `insert` *will* (re)allocate if `len() == capacity()`.
245 /// That is, the reported capacity is completely accurate, and can be relied on.
246 /// It can even be used to manually free the memory allocated by a Vec if
247 /// desired. Bulk insertion methods *may* reallocate, even when not necessary.
249 /// Vec does not guarantee any particular growth strategy when reallocating
250 /// when full, nor when `reserve` is called. The current strategy is basic
251 /// and it may prove desirable to use a non-constant growth factor. Whatever
252 /// strategy is used will of course guarantee `O(1)` amortized `push`.
254 /// `vec![x; n]`, `vec![a, b, c, d]`, and `Vec::with_capacity(n)`, will all
255 /// produce a Vec with exactly the requested capacity. If `len() == capacity()`,
256 /// (as is the case for the `vec!` macro), then a `Vec<T>` can be converted
257 /// to and from a `Box<[T]>` without reallocating or moving the elements.
259 /// Vec will not specifically overwrite any data that is removed from it,
260 /// but also won't specifically preserve it. Its uninitialized memory is
261 /// scratch space that it may use however it wants. It will generally just do
262 /// whatever is most efficient or otherwise easy to implement. Do not rely on
263 /// removed data to be erased for security purposes. Even if you drop a Vec, its
264 /// buffer may simply be reused by another Vec. Even if you zero a Vec's memory
265 /// first, that may not actually happen because the optimizer does not consider
266 /// this a side-effect that must be preserved.
268 /// Vec does not currently guarantee the order in which elements are dropped
269 /// (the order has changed in the past, and may change again).
271 #[unsafe_no_drop_flag]
272 #[stable(feature = "rust1", since = "1.0.0")]
278 ////////////////////////////////////////////////////////////////////////////////
280 ////////////////////////////////////////////////////////////////////////////////
283 /// Constructs a new, empty `Vec<T>`.
285 /// The vector will not allocate until elements are pushed onto it.
290 /// # #![allow(unused_mut)]
291 /// let mut vec: Vec<i32> = Vec::new();
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn new() -> Vec<T> {
302 /// Constructs a new, empty `Vec<T>` with the specified capacity.
304 /// The vector will be able to hold exactly `capacity` elements without
305 /// reallocating. If `capacity` is 0, the vector will not allocate.
307 /// It is important to note that this function does not specify the *length*
308 /// of the returned vector, but only the *capacity*. (For an explanation of
309 /// the difference between length and capacity, see the main `Vec<T>` docs
310 /// above, 'Capacity and reallocation'.)
315 /// let mut vec = Vec::with_capacity(10);
317 /// // The vector contains no items, even though it has capacity for more
318 /// assert_eq!(vec.len(), 0);
320 /// // These are all done without reallocating...
325 /// // ...but this may make the vector reallocate
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn with_capacity(capacity: usize) -> Vec<T> {
332 buf: RawVec::with_capacity(capacity),
337 /// Creates a `Vec<T>` directly from the raw components of another vector.
341 /// This is highly unsafe, due to the number of invariants that aren't
344 /// * `ptr` needs to have been previously allocated via `String`/`Vec<T>`
345 /// (at least, it's highly likely to be incorrect if it wasn't).
346 /// * `length` needs to be less than or equal to `capacity`.
347 /// * `capacity` needs to be the capacity that the pointer was allocated with.
349 /// Violating these may cause problems like corrupting the allocator's
350 /// internal datastructures.
352 /// The ownership of `ptr` is effectively transferred to the
353 /// `Vec<T>` which may then deallocate, reallocate or change the
354 /// contents of memory pointed to by the pointer at will. Ensure
355 /// that nothing else uses the pointer after calling this
365 /// let mut v = vec![1, 2, 3];
367 /// // Pull out the various important pieces of information about `v`
368 /// let p = v.as_mut_ptr();
369 /// let len = v.len();
370 /// let cap = v.capacity();
373 /// // Cast `v` into the void: no destructor run, so we are in
374 /// // complete control of the allocation to which `p` points.
377 /// // Overwrite memory with 4, 5, 6
378 /// for i in 0..len as isize {
379 /// ptr::write(p.offset(i), 4 + i);
382 /// // Put everything back together into a Vec
383 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
384 /// assert_eq!(rebuilt, [4, 5, 6]);
388 #[stable(feature = "rust1", since = "1.0.0")]
389 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
391 buf: RawVec::from_raw_parts(ptr, capacity),
396 /// Returns the number of elements the vector can hold without
402 /// let vec: Vec<i32> = Vec::with_capacity(10);
403 /// assert_eq!(vec.capacity(), 10);
406 #[stable(feature = "rust1", since = "1.0.0")]
407 pub fn capacity(&self) -> usize {
411 /// Reserves capacity for at least `additional` more elements to be inserted
412 /// in the given `Vec<T>`. The collection may reserve more space to avoid
413 /// frequent reallocations.
417 /// Panics if the new capacity overflows `usize`.
422 /// let mut vec = vec![1];
424 /// assert!(vec.capacity() >= 11);
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn reserve(&mut self, additional: usize) {
428 self.buf.reserve(self.len, additional);
431 /// Reserves the minimum capacity for exactly `additional` more elements to
432 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
435 /// Note that the allocator may give the collection more space than it
436 /// requests. Therefore capacity can not be relied upon to be precisely
437 /// minimal. Prefer `reserve` if future insertions are expected.
441 /// Panics if the new capacity overflows `usize`.
446 /// let mut vec = vec![1];
447 /// vec.reserve_exact(10);
448 /// assert!(vec.capacity() >= 11);
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub fn reserve_exact(&mut self, additional: usize) {
452 self.buf.reserve_exact(self.len, additional);
455 /// Shrinks the capacity of the vector as much as possible.
457 /// It will drop down as close as possible to the length but the allocator
458 /// may still inform the vector that there is space for a few more elements.
463 /// let mut vec = Vec::with_capacity(10);
464 /// vec.extend([1, 2, 3].iter().cloned());
465 /// assert_eq!(vec.capacity(), 10);
466 /// vec.shrink_to_fit();
467 /// assert!(vec.capacity() >= 3);
469 #[stable(feature = "rust1", since = "1.0.0")]
470 pub fn shrink_to_fit(&mut self) {
471 self.buf.shrink_to_fit(self.len);
474 /// Converts the vector into Box<[T]>.
476 /// Note that this will drop any excess capacity. Calling this and
477 /// converting back to a vector with `into_vec()` is equivalent to calling
478 /// `shrink_to_fit()`.
483 /// let v = vec![1, 2, 3];
485 /// let slice = v.into_boxed_slice();
488 /// Any excess capacity is removed:
491 /// let mut vec = Vec::with_capacity(10);
492 /// vec.extend([1, 2, 3].iter().cloned());
494 /// assert_eq!(vec.capacity(), 10);
495 /// let slice = vec.into_boxed_slice();
496 /// assert_eq!(slice.into_vec().capacity(), 3);
498 #[stable(feature = "rust1", since = "1.0.0")]
499 pub fn into_boxed_slice(mut self) -> Box<[T]> {
501 self.shrink_to_fit();
502 let buf = ptr::read(&self.buf);
508 /// Shortens the vector, keeping the first `len` elements and dropping
511 /// If `len` is greater than the vector's current length, this has no
514 /// The [`drain`] method can emulate `truncate`, but causes the excess
515 /// elements to be returned instead of dropped.
519 /// Truncating a five element vector to two elements:
522 /// let mut vec = vec![1, 2, 3, 4, 5];
524 /// assert_eq!(vec, [1, 2]);
527 /// No truncation occurs when `len` is greater than the vector's current
531 /// let mut vec = vec![1, 2, 3];
533 /// assert_eq!(vec, [1, 2, 3]);
536 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
540 /// let mut vec = vec![1, 2, 3];
542 /// assert_eq!(vec, []);
545 /// [`clear`]: #method.clear
546 /// [`drain`]: #method.drain
547 #[stable(feature = "rust1", since = "1.0.0")]
548 pub fn truncate(&mut self, len: usize) {
550 // drop any extra elements
551 while len < self.len {
552 // decrement len before the drop_in_place(), so a panic on Drop
553 // doesn't re-drop the just-failed value.
556 ptr::drop_in_place(self.get_unchecked_mut(len));
561 /// Extracts a slice containing the entire vector.
563 /// Equivalent to `&s[..]`.
568 /// use std::io::{self, Write};
569 /// let buffer = vec![1, 2, 3, 5, 8];
570 /// io::sink().write(buffer.as_slice()).unwrap();
573 #[stable(feature = "vec_as_slice", since = "1.7.0")]
574 pub fn as_slice(&self) -> &[T] {
578 /// Extracts a mutable slice of the entire vector.
580 /// Equivalent to `&mut s[..]`.
585 /// use std::io::{self, Read};
586 /// let mut buffer = vec![0; 3];
587 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
590 #[stable(feature = "vec_as_slice", since = "1.7.0")]
591 pub fn as_mut_slice(&mut self) -> &mut [T] {
595 /// Sets the length of a vector.
597 /// This will explicitly set the size of the vector, without actually
598 /// modifying its buffers, so it is up to the caller to ensure that the
599 /// vector is actually the specified size.
606 /// let mut vec = vec!['r', 'u', 's', 't'];
609 /// ptr::drop_in_place(&mut vec[3]);
612 /// assert_eq!(vec, ['r', 'u', 's']);
615 /// In this example, there is a memory leak since the memory locations
616 /// owned by the inner vectors were not freed prior to the `set_len` call:
619 /// let mut vec = vec![vec![1, 0, 0],
627 /// In this example, the vector gets expanded from zero to four items
628 /// without any memory allocations occurring, resulting in vector
629 /// values of unallocated memory:
632 /// let mut vec: Vec<char> = Vec::new();
639 #[stable(feature = "rust1", since = "1.0.0")]
640 pub unsafe fn set_len(&mut self, len: usize) {
644 /// Removes an element from anywhere in the vector and return it, replacing
645 /// it with the last element.
647 /// This does not preserve ordering, but is O(1).
651 /// Panics if `index` is out of bounds.
656 /// let mut v = vec!["foo", "bar", "baz", "qux"];
658 /// assert_eq!(v.swap_remove(1), "bar");
659 /// assert_eq!(v, ["foo", "qux", "baz"]);
661 /// assert_eq!(v.swap_remove(0), "foo");
662 /// assert_eq!(v, ["baz", "qux"]);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn swap_remove(&mut self, index: usize) -> T {
667 let length = self.len();
668 self.swap(index, length - 1);
672 /// Inserts an element at position `index` within the vector, shifting all
673 /// elements after it to the right.
677 /// Panics if `index` is greater than the vector's length.
682 /// let mut vec = vec![1, 2, 3];
683 /// vec.insert(1, 4);
684 /// assert_eq!(vec, [1, 4, 2, 3]);
685 /// vec.insert(4, 5);
686 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
688 #[stable(feature = "rust1", since = "1.0.0")]
689 pub fn insert(&mut self, index: usize, element: T) {
690 let len = self.len();
691 assert!(index <= len);
693 // space for the new element
694 if len == self.buf.cap() {
700 // The spot to put the new value
702 let p = self.as_mut_ptr().offset(index as isize);
703 // Shift everything over to make space. (Duplicating the
704 // `index`th element into two consecutive places.)
705 ptr::copy(p, p.offset(1), len - index);
706 // Write it in, overwriting the first copy of the `index`th
708 ptr::write(p, element);
710 self.set_len(len + 1);
714 /// Removes and returns the element at position `index` within the vector,
715 /// shifting all elements after it to the left.
719 /// Panics if `index` is out of bounds.
724 /// let mut v = vec![1, 2, 3];
725 /// assert_eq!(v.remove(1), 2);
726 /// assert_eq!(v, [1, 3]);
728 #[stable(feature = "rust1", since = "1.0.0")]
729 pub fn remove(&mut self, index: usize) -> T {
730 let len = self.len();
731 assert!(index < len);
736 // the place we are taking from.
737 let ptr = self.as_mut_ptr().offset(index as isize);
738 // copy it out, unsafely having a copy of the value on
739 // the stack and in the vector at the same time.
740 ret = ptr::read(ptr);
742 // Shift everything down to fill in that spot.
743 ptr::copy(ptr.offset(1), ptr, len - index - 1);
745 self.set_len(len - 1);
750 /// Retains only the elements specified by the predicate.
752 /// In other words, remove all elements `e` such that `f(&e)` returns false.
753 /// This method operates in place and preserves the order of the retained
759 /// let mut vec = vec![1, 2, 3, 4];
760 /// vec.retain(|&x| x%2 == 0);
761 /// assert_eq!(vec, [2, 4]);
763 #[stable(feature = "rust1", since = "1.0.0")]
764 pub fn retain<F>(&mut self, mut f: F)
765 where F: FnMut(&T) -> bool
767 let len = self.len();
781 self.truncate(len - del);
785 /// Appends an element to the back of a collection.
789 /// Panics if the number of elements in the vector overflows a `usize`.
794 /// let mut vec = vec![1, 2];
796 /// assert_eq!(vec, [1, 2, 3]);
799 #[stable(feature = "rust1", since = "1.0.0")]
800 pub fn push(&mut self, value: T) {
801 // This will panic or abort if we would allocate > isize::MAX bytes
802 // or if the length increment would overflow for zero-sized types.
803 if self.len == self.buf.cap() {
807 let end = self.as_mut_ptr().offset(self.len as isize);
808 ptr::write(end, value);
813 /// Removes the last element from a vector and returns it, or `None` if it
819 /// let mut vec = vec![1, 2, 3];
820 /// assert_eq!(vec.pop(), Some(3));
821 /// assert_eq!(vec, [1, 2]);
824 #[stable(feature = "rust1", since = "1.0.0")]
825 pub fn pop(&mut self) -> Option<T> {
831 Some(ptr::read(self.get_unchecked(self.len())))
836 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
840 /// Panics if the number of elements in the vector overflows a `usize`.
845 /// let mut vec = vec![1, 2, 3];
846 /// let mut vec2 = vec![4, 5, 6];
847 /// vec.append(&mut vec2);
848 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
849 /// assert_eq!(vec2, []);
852 #[stable(feature = "append", since = "1.4.0")]
853 pub fn append(&mut self, other: &mut Self) {
854 self.reserve(other.len());
855 let len = self.len();
857 ptr::copy_nonoverlapping(other.as_ptr(), self.get_unchecked_mut(len), other.len());
860 self.len += other.len();
866 /// Create a draining iterator that removes the specified range in the vector
867 /// and yields the removed items.
869 /// Note 1: The element range is removed even if the iterator is not
870 /// consumed until the end.
872 /// Note 2: It is unspecified how many elements are removed from the vector,
873 /// if the `Drain` value is leaked.
877 /// Panics if the starting point is greater than the end point or if
878 /// the end point is greater than the length of the vector.
883 /// let mut v = vec![1, 2, 3];
884 /// let u: Vec<_> = v.drain(1..).collect();
885 /// assert_eq!(v, &[1]);
886 /// assert_eq!(u, &[2, 3]);
888 /// // A full range clears the vector
890 /// assert_eq!(v, &[]);
892 #[stable(feature = "drain", since = "1.6.0")]
893 pub fn drain<R>(&mut self, range: R) -> Drain<T>
894 where R: RangeArgument<usize>
898 // When the Drain is first created, it shortens the length of
899 // the source vector to make sure no uninitalized or moved-from elements
900 // are accessible at all if the Drain's destructor never gets to run.
902 // Drain will ptr::read out the values to remove.
903 // When finished, remaining tail of the vec is copied back to cover
904 // the hole, and the vector length is restored to the new length.
906 let len = self.len();
907 let start = *range.start().unwrap_or(&0);
908 let end = *range.end().unwrap_or(&len);
909 assert!(start <= end);
913 // set self.vec length's to start, to be safe in case Drain is leaked
915 // Use the borrow in the IterMut to indicate borrowing behavior of the
916 // whole Drain iterator (like &mut T).
917 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
922 iter: range_slice.iter(),
923 vec: Shared::new(self as *mut _),
928 /// Clears the vector, removing all values.
933 /// let mut v = vec![1, 2, 3];
937 /// assert!(v.is_empty());
940 #[stable(feature = "rust1", since = "1.0.0")]
941 pub fn clear(&mut self) {
945 /// Returns the number of elements in the vector.
950 /// let a = vec![1, 2, 3];
951 /// assert_eq!(a.len(), 3);
954 #[stable(feature = "rust1", since = "1.0.0")]
955 pub fn len(&self) -> usize {
959 /// Returns `true` if the vector contains no elements.
964 /// let mut v = Vec::new();
965 /// assert!(v.is_empty());
968 /// assert!(!v.is_empty());
970 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn is_empty(&self) -> bool {
975 /// Splits the collection into two at the given index.
977 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
978 /// and the returned `Self` contains elements `[at, len)`.
980 /// Note that the capacity of `self` does not change.
984 /// Panics if `at > len`.
989 /// let mut vec = vec![1,2,3];
990 /// let vec2 = vec.split_off(1);
991 /// assert_eq!(vec, [1]);
992 /// assert_eq!(vec2, [2, 3]);
995 #[stable(feature = "split_off", since = "1.4.0")]
996 pub fn split_off(&mut self, at: usize) -> Self {
997 assert!(at <= self.len(), "`at` out of bounds");
999 let other_len = self.len - at;
1000 let mut other = Vec::with_capacity(other_len);
1002 // Unsafely `set_len` and copy items to `other`.
1005 other.set_len(other_len);
1007 ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
1015 impl<T: Clone> Vec<T> {
1016 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1018 /// If `new_len` is greater than `len()`, the `Vec` is extended by the
1019 /// difference, with each additional slot filled with `value`.
1020 /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
1025 /// let mut vec = vec!["hello"];
1026 /// vec.resize(3, "world");
1027 /// assert_eq!(vec, ["hello", "world", "world"]);
1029 /// let mut vec = vec![1, 2, 3, 4];
1030 /// vec.resize(2, 0);
1031 /// assert_eq!(vec, [1, 2]);
1033 #[stable(feature = "vec_resize", since = "1.5.0")]
1034 pub fn resize(&mut self, new_len: usize, value: T) {
1035 let len = self.len();
1038 self.extend_with_element(new_len - len, value);
1040 self.truncate(new_len);
1044 /// Extend the vector by `n` additional clones of `value`.
1045 fn extend_with_element(&mut self, n: usize, value: T) {
1049 let len = self.len();
1050 let mut ptr = self.as_mut_ptr().offset(len as isize);
1051 // Write all elements except the last one
1053 ptr::write(ptr, value.clone());
1054 ptr = ptr.offset(1);
1055 // Increment the length in every step in case clone() panics
1056 self.set_len(len + i);
1060 // We can write the last element directly without cloning needlessly
1061 ptr::write(ptr, value);
1062 self.set_len(len + n);
1067 /// Clones and appends all elements in a slice to the `Vec`.
1069 /// Iterates over the slice `other`, clones each element, and then appends
1070 /// it to this `Vec`. The `other` vector is traversed in-order.
1072 /// Note that this function is same as `extend` except that it is
1073 /// specialized to work with slices instead. If and when Rust gets
1074 /// specialization this function will likely be deprecated (but still
1080 /// let mut vec = vec![1];
1081 /// vec.extend_from_slice(&[2, 3, 4]);
1082 /// assert_eq!(vec, [1, 2, 3, 4]);
1084 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1085 pub fn extend_from_slice(&mut self, other: &[T]) {
1086 self.reserve(other.len());
1088 for i in 0..other.len() {
1089 let len = self.len();
1091 // Unsafe code so this can be optimised to a memcpy (or something
1092 // similarly fast) when T is Copy. LLVM is easily confused, so any
1093 // extra operations during the loop can prevent this optimisation.
1095 ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
1096 self.set_len(len + 1);
1102 impl<T: PartialEq> Vec<T> {
1103 /// Removes consecutive repeated elements in the vector.
1105 /// If the vector is sorted, this removes all duplicates.
1110 /// let mut vec = vec![1, 2, 2, 3, 2];
1114 /// assert_eq!(vec, [1, 2, 3, 2]);
1116 #[stable(feature = "rust1", since = "1.0.0")]
1117 pub fn dedup(&mut self) {
1119 // Although we have a mutable reference to `self`, we cannot make
1120 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1121 // must ensure that the vector is in a valid state at all time.
1123 // The way that we handle this is by using swaps; we iterate
1124 // over all the elements, swapping as we go so that at the end
1125 // the elements we wish to keep are in the front, and those we
1126 // wish to reject are at the back. We can then truncate the
1127 // vector. This operation is still O(n).
1129 // Example: We start in this state, where `r` represents "next
1130 // read" and `w` represents "next_write`.
1133 // +---+---+---+---+---+---+
1134 // | 0 | 1 | 1 | 2 | 3 | 3 |
1135 // +---+---+---+---+---+---+
1138 // Comparing self[r] against self[w-1], this is not a duplicate, so
1139 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1140 // r and w, leaving us with:
1143 // +---+---+---+---+---+---+
1144 // | 0 | 1 | 1 | 2 | 3 | 3 |
1145 // +---+---+---+---+---+---+
1148 // Comparing self[r] against self[w-1], this value is a duplicate,
1149 // so we increment `r` but leave everything else unchanged:
1152 // +---+---+---+---+---+---+
1153 // | 0 | 1 | 1 | 2 | 3 | 3 |
1154 // +---+---+---+---+---+---+
1157 // Comparing self[r] against self[w-1], this is not a duplicate,
1158 // so swap self[r] and self[w] and advance r and w:
1161 // +---+---+---+---+---+---+
1162 // | 0 | 1 | 2 | 1 | 3 | 3 |
1163 // +---+---+---+---+---+---+
1166 // Not a duplicate, repeat:
1169 // +---+---+---+---+---+---+
1170 // | 0 | 1 | 2 | 3 | 1 | 3 |
1171 // +---+---+---+---+---+---+
1174 // Duplicate, advance r. End of vec. Truncate to w.
1176 let ln = self.len();
1181 // Avoid bounds checks by using raw pointers.
1182 let p = self.as_mut_ptr();
1183 let mut r: usize = 1;
1184 let mut w: usize = 1;
1187 let p_r = p.offset(r as isize);
1188 let p_wm1 = p.offset((w - 1) as isize);
1191 let p_w = p_wm1.offset(1);
1192 mem::swap(&mut *p_r, &mut *p_w);
1204 ////////////////////////////////////////////////////////////////////////////////
1205 // Internal methods and functions
1206 ////////////////////////////////////////////////////////////////////////////////
1209 #[stable(feature = "rust1", since = "1.0.0")]
1210 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1211 let mut v = Vec::with_capacity(n);
1212 v.extend_with_element(n, elem);
1216 ////////////////////////////////////////////////////////////////////////////////
1217 // Common trait implementations for Vec
1218 ////////////////////////////////////////////////////////////////////////////////
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 impl<T: Clone> Clone for Vec<T> {
1223 fn clone(&self) -> Vec<T> {
1224 <[T]>::to_vec(&**self)
1227 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1228 // required for this method definition, is not available. Instead use the
1229 // `slice::to_vec` function which is only available with cfg(test)
1230 // NB see the slice::hack module in slice.rs for more information
1232 fn clone(&self) -> Vec<T> {
1233 ::slice::to_vec(&**self)
1236 fn clone_from(&mut self, other: &Vec<T>) {
1237 // drop anything in self that will not be overwritten
1238 self.truncate(other.len());
1239 let len = self.len();
1241 // reuse the contained values' allocations/resources.
1242 self.clone_from_slice(&other[..len]);
1244 // self.len <= other.len due to the truncate above, so the
1245 // slice here is always in-bounds.
1246 self.extend_from_slice(&other[len..]);
1250 #[stable(feature = "rust1", since = "1.0.0")]
1251 impl<T: Hash> Hash for Vec<T> {
1253 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1254 Hash::hash(&**self, state)
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 impl<T> Index<usize> for Vec<T> {
1263 fn index(&self, index: usize) -> &T {
1264 // NB built-in indexing via `&[T]`
1269 #[stable(feature = "rust1", since = "1.0.0")]
1270 impl<T> IndexMut<usize> for Vec<T> {
1272 fn index_mut(&mut self, index: usize) -> &mut T {
1273 // NB built-in indexing via `&mut [T]`
1274 &mut (**self)[index]
1279 #[stable(feature = "rust1", since = "1.0.0")]
1280 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1284 fn index(&self, index: ops::Range<usize>) -> &[T] {
1285 Index::index(&**self, index)
1288 #[stable(feature = "rust1", since = "1.0.0")]
1289 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1293 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1294 Index::index(&**self, index)
1297 #[stable(feature = "rust1", since = "1.0.0")]
1298 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1302 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1303 Index::index(&**self, index)
1306 #[stable(feature = "rust1", since = "1.0.0")]
1307 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1311 fn index(&self, _index: ops::RangeFull) -> &[T] {
1315 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1316 impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> {
1320 fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
1321 Index::index(&**self, index)
1324 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1325 impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> {
1329 fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
1330 Index::index(&**self, index)
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1337 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1338 IndexMut::index_mut(&mut **self, index)
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1344 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1345 IndexMut::index_mut(&mut **self, index)
1348 #[stable(feature = "rust1", since = "1.0.0")]
1349 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1351 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1352 IndexMut::index_mut(&mut **self, index)
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1358 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1362 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1363 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> {
1365 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
1366 IndexMut::index_mut(&mut **self, index)
1369 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1370 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> {
1372 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
1373 IndexMut::index_mut(&mut **self, index)
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<T> ops::Deref for Vec<T> {
1381 fn deref(&self) -> &[T] {
1383 let p = self.buf.ptr();
1384 assume(!p.is_null());
1385 slice::from_raw_parts(p, self.len)
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl<T> ops::DerefMut for Vec<T> {
1392 fn deref_mut(&mut self) -> &mut [T] {
1394 let ptr = self.buf.ptr();
1395 assume(!ptr.is_null());
1396 slice::from_raw_parts_mut(ptr, self.len)
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<T> FromIterator<T> for Vec<T> {
1404 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1405 // Unroll the first iteration, as the vector is going to be
1406 // expanded on this iteration in every case when the iterable is not
1407 // empty, but the loop in extend_desugared() is not going to see the
1408 // vector being full in the few subsequent loop iterations.
1409 // So we get better branch prediction.
1410 let mut iterator = iter.into_iter();
1411 let mut vector = match iterator.next() {
1412 None => return Vec::new(),
1414 let (lower, _) = iterator.size_hint();
1415 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1417 ptr::write(vector.get_unchecked_mut(0), element);
1423 vector.extend_desugared(iterator);
1428 #[stable(feature = "rust1", since = "1.0.0")]
1429 impl<T> IntoIterator for Vec<T> {
1431 type IntoIter = IntoIter<T>;
1433 /// Creates a consuming iterator, that is, one that moves each value out of
1434 /// the vector (from start to end). The vector cannot be used after calling
1440 /// let v = vec!["a".to_string(), "b".to_string()];
1441 /// for s in v.into_iter() {
1442 /// // s has type String, not &String
1443 /// println!("{}", s);
1447 fn into_iter(mut self) -> IntoIter<T> {
1449 let begin = self.as_mut_ptr();
1450 assume(!begin.is_null());
1451 let end = if mem::size_of::<T>() == 0 {
1452 arith_offset(begin as *const i8, self.len() as isize) as *const T
1454 begin.offset(self.len() as isize) as *const T
1456 let cap = self.buf.cap();
1459 buf: Shared::new(begin),
1468 #[stable(feature = "rust1", since = "1.0.0")]
1469 impl<'a, T> IntoIterator for &'a Vec<T> {
1471 type IntoIter = slice::Iter<'a, T>;
1473 fn into_iter(self) -> slice::Iter<'a, T> {
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1480 type Item = &'a mut T;
1481 type IntoIter = slice::IterMut<'a, T>;
1483 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1488 #[stable(feature = "rust1", since = "1.0.0")]
1489 impl<T> Extend<T> for Vec<T> {
1491 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1492 <Self as SpecExtend<I>>::spec_extend(self, iter);
1496 impl<I: IntoIterator> SpecExtend<I> for Vec<I::Item> {
1497 default fn spec_extend(&mut self, iter: I) {
1498 self.extend_desugared(iter.into_iter())
1502 impl<T> SpecExtend<Vec<T>> for Vec<T> {
1503 fn spec_extend(&mut self, ref mut other: Vec<T>) {
1509 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1510 // This function should be the moral equivalent of:
1512 // for item in iterator {
1515 while let Some(element) = iterator.next() {
1516 let len = self.len();
1517 if len == self.capacity() {
1518 let (lower, _) = iterator.size_hint();
1519 self.reserve(lower.saturating_add(1));
1522 ptr::write(self.get_unchecked_mut(len), element);
1523 // NB can't overflow since we would have had to alloc the address space
1524 self.set_len(len + 1);
1530 #[stable(feature = "extend_ref", since = "1.2.0")]
1531 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1532 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1533 self.extend(iter.into_iter().cloned());
1537 macro_rules! __impl_slice_eq1 {
1538 ($Lhs: ty, $Rhs: ty) => {
1539 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1541 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1542 #[stable(feature = "rust1", since = "1.0.0")]
1543 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
1545 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
1547 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
1552 __impl_slice_eq1! { Vec<A>, Vec<B> }
1553 __impl_slice_eq1! { Vec<A>, &'b [B] }
1554 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1555 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1556 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1557 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1559 macro_rules! array_impls {
1562 // NOTE: some less important impls are omitted to reduce code bloat
1563 __impl_slice_eq1! { Vec<A>, [B; $N] }
1564 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1565 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1566 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1567 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1568 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1575 10 11 12 13 14 15 16 17 18 19
1576 20 21 22 23 24 25 26 27 28 29
1580 #[stable(feature = "rust1", since = "1.0.0")]
1581 impl<T: PartialOrd> PartialOrd for Vec<T> {
1583 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1584 PartialOrd::partial_cmp(&**self, &**other)
1588 #[stable(feature = "rust1", since = "1.0.0")]
1589 impl<T: Eq> Eq for Vec<T> {}
1591 #[stable(feature = "rust1", since = "1.0.0")]
1592 impl<T: Ord> Ord for Vec<T> {
1594 fn cmp(&self, other: &Vec<T>) -> Ordering {
1595 Ord::cmp(&**self, &**other)
1599 #[stable(feature = "rust1", since = "1.0.0")]
1600 impl<T> Drop for Vec<T> {
1601 #[unsafe_destructor_blind_to_params]
1602 fn drop(&mut self) {
1603 if self.buf.unsafe_no_drop_flag_needs_drop() {
1606 ptr::drop_in_place(&mut self[..]);
1609 // RawVec handles deallocation
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 impl<T> Default for Vec<T> {
1615 fn default() -> Vec<T> {
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1622 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1623 fmt::Debug::fmt(&**self, f)
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<T> AsRef<Vec<T>> for Vec<T> {
1629 fn as_ref(&self) -> &Vec<T> {
1634 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1635 impl<T> AsMut<Vec<T>> for Vec<T> {
1636 fn as_mut(&mut self) -> &mut Vec<T> {
1641 #[stable(feature = "rust1", since = "1.0.0")]
1642 impl<T> AsRef<[T]> for Vec<T> {
1643 fn as_ref(&self) -> &[T] {
1648 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1649 impl<T> AsMut<[T]> for Vec<T> {
1650 fn as_mut(&mut self) -> &mut [T] {
1655 #[stable(feature = "rust1", since = "1.0.0")]
1656 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1658 fn from(s: &'a [T]) -> Vec<T> {
1662 fn from(s: &'a [T]) -> Vec<T> {
1667 #[stable(feature = "rust1", since = "1.0.0")]
1668 impl<'a> From<&'a str> for Vec<u8> {
1669 fn from(s: &'a str) -> Vec<u8> {
1670 From::from(s.as_bytes())
1674 ////////////////////////////////////////////////////////////////////////////////
1676 ////////////////////////////////////////////////////////////////////////////////
1678 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1679 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
1680 fn from(s: &'a [T]) -> Cow<'a, [T]> {
1685 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1686 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
1687 fn from(v: Vec<T>) -> Cow<'a, [T]> {
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1694 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
1695 Cow::Owned(FromIterator::from_iter(it))
1699 ////////////////////////////////////////////////////////////////////////////////
1701 ////////////////////////////////////////////////////////////////////////////////
1703 /// An iterator that moves out of a vector.
1705 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
1706 /// by the [`IntoIterator`] trait).
1708 /// [`Vec`]: struct.Vec.html
1709 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 pub struct IntoIter<T> {
1718 #[stable(feature = "vec_intoiter_debug", since = "")]
1719 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
1720 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1721 f.debug_tuple("IntoIter")
1722 .field(&self.as_slice())
1727 impl<T> IntoIter<T> {
1728 /// Returns the remaining items of this iterator as a slice.
1733 /// # #![feature(vec_into_iter_as_slice)]
1734 /// let vec = vec!['a', 'b', 'c'];
1735 /// let mut into_iter = vec.into_iter();
1736 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
1737 /// let _ = into_iter.next().unwrap();
1738 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
1740 #[unstable(feature = "vec_into_iter_as_slice", issue = "35601")]
1741 pub fn as_slice(&self) -> &[T] {
1743 slice::from_raw_parts(self.ptr, self.len())
1747 /// Returns the remaining items of this iterator as a mutable slice.
1752 /// # #![feature(vec_into_iter_as_slice)]
1753 /// let vec = vec!['a', 'b', 'c'];
1754 /// let mut into_iter = vec.into_iter();
1755 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
1756 /// into_iter.as_mut_slice()[2] = 'z';
1757 /// assert_eq!(into_iter.next().unwrap(), 'a');
1758 /// assert_eq!(into_iter.next().unwrap(), 'b');
1759 /// assert_eq!(into_iter.next().unwrap(), 'z');
1761 #[unstable(feature = "vec_into_iter_as_slice", issue = "35601")]
1762 pub fn as_mut_slice(&self) -> &mut [T] {
1764 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
1769 #[stable(feature = "rust1", since = "1.0.0")]
1770 unsafe impl<T: Send> Send for IntoIter<T> {}
1771 #[stable(feature = "rust1", since = "1.0.0")]
1772 unsafe impl<T: Sync> Sync for IntoIter<T> {}
1774 #[stable(feature = "rust1", since = "1.0.0")]
1775 impl<T> Iterator for IntoIter<T> {
1779 fn next(&mut self) -> Option<T> {
1781 if self.ptr as *const _ == self.end {
1784 if mem::size_of::<T>() == 0 {
1785 // purposefully don't use 'ptr.offset' because for
1786 // vectors with 0-size elements this would return the
1788 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
1790 // Use a non-null pointer value
1791 Some(ptr::read(EMPTY as *mut T))
1794 self.ptr = self.ptr.offset(1);
1796 Some(ptr::read(old))
1803 fn size_hint(&self) -> (usize, Option<usize>) {
1804 let diff = (self.end as usize) - (self.ptr as usize);
1805 let size = mem::size_of::<T>();
1812 (exact, Some(exact))
1816 fn count(self) -> usize {
1821 #[stable(feature = "rust1", since = "1.0.0")]
1822 impl<T> DoubleEndedIterator for IntoIter<T> {
1824 fn next_back(&mut self) -> Option<T> {
1826 if self.end == self.ptr {
1829 if mem::size_of::<T>() == 0 {
1830 // See above for why 'ptr.offset' isn't used
1831 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
1833 // Use a non-null pointer value
1834 Some(ptr::read(EMPTY as *mut T))
1836 self.end = self.end.offset(-1);
1838 Some(ptr::read(self.end))
1845 #[stable(feature = "rust1", since = "1.0.0")]
1846 impl<T> ExactSizeIterator for IntoIter<T> {}
1848 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
1849 impl<T: Clone> Clone for IntoIter<T> {
1850 fn clone(&self) -> IntoIter<T> {
1851 self.as_slice().to_owned().into_iter()
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 impl<T> Drop for IntoIter<T> {
1857 #[unsafe_destructor_blind_to_params]
1858 fn drop(&mut self) {
1859 // destroy the remaining elements
1860 for _x in self.by_ref() {}
1862 // RawVec handles deallocation
1863 let _ = unsafe { RawVec::from_raw_parts(*self.buf, self.cap) };
1867 /// A draining iterator for `Vec<T>`.
1869 /// This `struct` is created by the [`drain`] method on [`Vec`].
1871 /// [`drain`]: struct.Vec.html#method.drain
1872 /// [`Vec`]: struct.Vec.html
1873 #[stable(feature = "drain", since = "1.6.0")]
1874 pub struct Drain<'a, T: 'a> {
1875 /// Index of tail to preserve
1879 /// Current remaining range to remove
1880 iter: slice::Iter<'a, T>,
1881 vec: Shared<Vec<T>>,
1884 #[stable(feature = "drain", since = "1.6.0")]
1885 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1886 #[stable(feature = "drain", since = "1.6.0")]
1887 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1889 #[stable(feature = "rust1", since = "1.0.0")]
1890 impl<'a, T> Iterator for Drain<'a, T> {
1894 fn next(&mut self) -> Option<T> {
1895 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
1898 fn size_hint(&self) -> (usize, Option<usize>) {
1899 self.iter.size_hint()
1903 #[stable(feature = "rust1", since = "1.0.0")]
1904 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1906 fn next_back(&mut self) -> Option<T> {
1907 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
1911 #[stable(feature = "rust1", since = "1.0.0")]
1912 impl<'a, T> Drop for Drain<'a, T> {
1913 fn drop(&mut self) {
1914 // exhaust self first
1915 while let Some(_) = self.next() {}
1917 if self.tail_len > 0 {
1919 let source_vec = &mut **self.vec;
1920 // memmove back untouched tail, update to new length
1921 let start = source_vec.len();
1922 let tail = self.tail_start;
1923 let src = source_vec.as_ptr().offset(tail as isize);
1924 let dst = source_vec.as_mut_ptr().offset(start as isize);
1925 ptr::copy(src, dst, self.tail_len);
1926 source_vec.set_len(start + self.tail_len);
1933 #[stable(feature = "rust1", since = "1.0.0")]
1934 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}