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
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 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
61 //! [`new`]: ../../std/vec/struct.Vec.html#method.new
62 //! [`push`]: ../../std/vec/struct.Vec.html#method.push
63 //! [`Index`]: ../../std/ops/trait.Index.html
64 //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
65 //! [`vec!`]: ../../std/macro.vec.html
67 #![stable(feature = "rust1", since = "1.0.0")]
69 use core::cmp::Ordering;
71 use core::hash::{self, Hash};
72 use core::intrinsics::{arith_offset, assume};
73 use core::iter::{FromIterator, FusedIterator, TrustedLen};
77 use core::ops::{InPlace, Index, IndexMut, Place, Placer};
80 use core::ptr::Shared;
87 use super::range::RangeArgument;
88 use Bound::{Excluded, Included, Unbounded};
90 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
95 /// let mut vec = Vec::new();
99 /// assert_eq!(vec.len(), 2);
100 /// assert_eq!(vec[0], 1);
102 /// assert_eq!(vec.pop(), Some(2));
103 /// assert_eq!(vec.len(), 1);
106 /// assert_eq!(vec[0], 7);
108 /// vec.extend([1, 2, 3].iter().cloned());
111 /// println!("{}", x);
113 /// assert_eq!(vec, [7, 1, 2, 3]);
116 /// The [`vec!`] macro is provided to make initialization more convenient:
119 /// let mut vec = vec![1, 2, 3];
121 /// assert_eq!(vec, [1, 2, 3, 4]);
124 /// It can also initialize each element of a `Vec<T>` with a given value:
127 /// let vec = vec![0; 5];
128 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
131 /// Use a `Vec<T>` as an efficient stack:
134 /// let mut stack = Vec::new();
140 /// while let Some(top) = stack.pop() {
141 /// // Prints 3, 2, 1
142 /// println!("{}", top);
148 /// The `Vec` type allows to access values by index, because it implements the
149 /// [`Index`] trait. An example will be more explicit:
152 /// let v = vec![0, 2, 4, 6];
153 /// println!("{}", v[1]); // it will display '2'
156 /// However be careful: if you try to access an index which isn't in the `Vec`,
157 /// your software will panic! You cannot do this:
160 /// let v = vec![0, 2, 4, 6];
161 /// println!("{}", v[6]); // it will panic!
164 /// In conclusion: always check if the index you want to get really exists
169 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
170 /// To get a slice, use `&`. Example:
173 /// fn read_slice(slice: &[usize]) {
177 /// let v = vec![0, 1];
180 /// // ... and that's all!
181 /// // you can also do it like this:
182 /// let x : &[usize] = &v;
185 /// In Rust, it's more common to pass slices as arguments rather than vectors
186 /// when you just want to provide a read access. The same goes for [`String`] and
189 /// # Capacity and reallocation
191 /// The capacity of a vector is the amount of space allocated for any future
192 /// elements that will be added onto the vector. This is not to be confused with
193 /// the *length* of a vector, which specifies the number of actual elements
194 /// within the vector. If a vector's length exceeds its capacity, its capacity
195 /// will automatically be increased, but its elements will have to be
198 /// For example, a vector with capacity 10 and length 0 would be an empty vector
199 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
200 /// vector will not change its capacity or cause reallocation to occur. However,
201 /// if the vector's length is increased to 11, it will have to reallocate, which
202 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
203 /// whenever possible to specify how big the vector is expected to get.
207 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
208 /// about its design. This ensures that it's as low-overhead as possible in
209 /// the general case, and can be correctly manipulated in primitive ways
210 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
211 /// If additional type parameters are added (e.g. to support custom allocators),
212 /// overriding their defaults may change the behavior.
214 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
215 /// triplet. No more, no less. The order of these fields is completely
216 /// unspecified, and you should use the appropriate methods to modify these.
217 /// The pointer will never be null, so this type is null-pointer-optimized.
219 /// However, the pointer may not actually point to allocated memory. In particular,
220 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
221 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
222 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
223 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
224 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
225 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
226 /// details are subtle enough that it is strongly recommended that you only
227 /// free memory allocated by a `Vec` by creating a new `Vec` and dropping it.
229 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
230 /// (as defined by the allocator Rust is configured to use by default), and its
231 /// pointer points to [`len`] initialized elements in order (what you would see
232 /// if you coerced it to a slice), followed by [`capacity`]` - `[`len`]
233 /// logically uninitialized elements.
235 /// `Vec` will never perform a "small optimization" where elements are actually
236 /// stored on the stack for two reasons:
238 /// * It would make it more difficult for unsafe code to correctly manipulate
239 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
240 /// only moved, and it would be more difficult to determine if a `Vec` had
241 /// actually allocated memory.
243 /// * It would penalize the general case, incurring an additional branch
246 /// `Vec` will never automatically shrink itself, even if completely empty. This
247 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
248 /// and then filling it back up to the same [`len`] should incur no calls to
249 /// the allocator. If you wish to free up unused memory, use
250 /// [`shrink_to_fit`][`shrink_to_fit`].
252 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
253 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
254 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
255 /// accurate, and can be relied on. It can even be used to manually free the memory
256 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
257 /// when not necessary.
259 /// `Vec` does not guarantee any particular growth strategy when reallocating
260 /// when full, nor when [`reserve`] is called. The current strategy is basic
261 /// and it may prove desirable to use a non-constant growth factor. Whatever
262 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
264 /// `vec![x; n]`, `vec![a, b, c, d]`, and
265 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
266 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
267 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
268 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
270 /// `Vec` will not specifically overwrite any data that is removed from it,
271 /// but also won't specifically preserve it. Its uninitialized memory is
272 /// scratch space that it may use however it wants. It will generally just do
273 /// whatever is most efficient or otherwise easy to implement. Do not rely on
274 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
275 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
276 /// first, that may not actually happen because the optimizer does not consider
277 /// this a side-effect that must be preserved. There is one case which we will
278 /// not break, however: using `unsafe` code to write to the excess capacity,
279 /// and then increasing the length to match, is always valid.
281 /// `Vec` does not currently guarantee the order in which elements are dropped
282 /// (the order has changed in the past, and may change again).
284 /// [`vec!`]: ../../std/macro.vec.html
285 /// [`Index`]: ../../std/ops/trait.Index.html
286 /// [`String`]: ../../std/string/struct.String.html
287 /// [`&str`]: ../../std/primitive.str.html
288 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
289 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
290 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
291 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
292 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
293 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
294 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
295 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
296 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
297 /// [owned slice]: ../../std/boxed/struct.Box.html
298 #[stable(feature = "rust1", since = "1.0.0")]
304 ////////////////////////////////////////////////////////////////////////////////
306 ////////////////////////////////////////////////////////////////////////////////
309 /// Constructs a new, empty `Vec<T>`.
311 /// The vector will not allocate until elements are pushed onto it.
316 /// # #![allow(unused_mut)]
317 /// let mut vec: Vec<i32> = Vec::new();
320 #[stable(feature = "rust1", since = "1.0.0")]
321 pub fn new() -> Vec<T> {
328 /// Constructs a new, empty `Vec<T>` with the specified capacity.
330 /// The vector will be able to hold exactly `capacity` elements without
331 /// reallocating. If `capacity` is 0, the vector will not allocate.
333 /// It is important to note that this function does not specify the *length*
334 /// of the returned vector, but only the *capacity*. For an explanation of
335 /// the difference between length and capacity, see *[Capacity and reallocation]*.
337 /// [Capacity and reallocation]: #capacity-and-reallocation
342 /// let mut vec = Vec::with_capacity(10);
344 /// // The vector contains no items, even though it has capacity for more
345 /// assert_eq!(vec.len(), 0);
347 /// // These are all done without reallocating...
352 /// // ...but this may make the vector reallocate
356 #[stable(feature = "rust1", since = "1.0.0")]
357 pub fn with_capacity(capacity: usize) -> Vec<T> {
359 buf: RawVec::with_capacity(capacity),
364 /// Creates a `Vec<T>` directly from the raw components of another vector.
368 /// This is highly unsafe, due to the number of invariants that aren't
371 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
372 /// (at least, it's highly likely to be incorrect if it wasn't).
373 /// * `ptr`'s `T` needs to have the same size and alignment as it was allocated with.
374 /// * `length` needs to be less than or equal to `capacity`.
375 /// * `capacity` needs to be the capacity that the pointer was allocated with.
377 /// Violating these may cause problems like corrupting the allocator's
378 /// internal data structures. For example it is **not** safe
379 /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`.
381 /// The ownership of `ptr` is effectively transferred to the
382 /// `Vec<T>` which may then deallocate, reallocate or change the
383 /// contents of memory pointed to by the pointer at will. Ensure
384 /// that nothing else uses the pointer after calling this
387 /// [`String`]: ../../std/string/struct.String.html
396 /// let mut v = vec![1, 2, 3];
398 /// // Pull out the various important pieces of information about `v`
399 /// let p = v.as_mut_ptr();
400 /// let len = v.len();
401 /// let cap = v.capacity();
404 /// // Cast `v` into the void: no destructor run, so we are in
405 /// // complete control of the allocation to which `p` points.
408 /// // Overwrite memory with 4, 5, 6
409 /// for i in 0..len as isize {
410 /// ptr::write(p.offset(i), 4 + i);
413 /// // Put everything back together into a Vec
414 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
415 /// assert_eq!(rebuilt, [4, 5, 6]);
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
422 buf: RawVec::from_raw_parts(ptr, capacity),
427 /// Returns the number of elements the vector can hold without
433 /// let vec: Vec<i32> = Vec::with_capacity(10);
434 /// assert_eq!(vec.capacity(), 10);
437 #[stable(feature = "rust1", since = "1.0.0")]
438 pub fn capacity(&self) -> usize {
442 /// Reserves capacity for at least `additional` more elements to be inserted
443 /// in the given `Vec<T>`. The collection may reserve more space to avoid
444 /// frequent reallocations. After calling `reserve`, capacity will be
445 /// greater than or equal to `self.len() + additional`. Does nothing if
446 /// capacity is already sufficient.
450 /// Panics if the new capacity overflows `usize`.
455 /// let mut vec = vec![1];
457 /// assert!(vec.capacity() >= 11);
459 #[stable(feature = "rust1", since = "1.0.0")]
460 pub fn reserve(&mut self, additional: usize) {
461 self.buf.reserve(self.len, additional);
464 /// Reserves the minimum capacity for exactly `additional` more elements to
465 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
466 /// capacity will be greater than or equal to `self.len() + additional`.
467 /// Does nothing if the capacity is already sufficient.
469 /// Note that the allocator may give the collection more space than it
470 /// requests. Therefore capacity can not be relied upon to be precisely
471 /// minimal. Prefer `reserve` if future insertions are expected.
475 /// Panics if the new capacity overflows `usize`.
480 /// let mut vec = vec![1];
481 /// vec.reserve_exact(10);
482 /// assert!(vec.capacity() >= 11);
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub fn reserve_exact(&mut self, additional: usize) {
486 self.buf.reserve_exact(self.len, additional);
489 /// Shrinks the capacity of the vector as much as possible.
491 /// It will drop down as close as possible to the length but the allocator
492 /// may still inform the vector that there is space for a few more elements.
497 /// let mut vec = Vec::with_capacity(10);
498 /// vec.extend([1, 2, 3].iter().cloned());
499 /// assert_eq!(vec.capacity(), 10);
500 /// vec.shrink_to_fit();
501 /// assert!(vec.capacity() >= 3);
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn shrink_to_fit(&mut self) {
505 self.buf.shrink_to_fit(self.len);
508 /// Converts the vector into [`Box<[T]>`][owned slice].
510 /// Note that this will drop any excess capacity. Calling this and
511 /// converting back to a vector with [`into_vec`] is equivalent to calling
512 /// [`shrink_to_fit`].
514 /// [owned slice]: ../../std/boxed/struct.Box.html
515 /// [`into_vec`]: ../../std/primitive.slice.html#method.into_vec
516 /// [`shrink_to_fit`]: #method.shrink_to_fit
521 /// let v = vec![1, 2, 3];
523 /// let slice = v.into_boxed_slice();
526 /// Any excess capacity is removed:
529 /// let mut vec = Vec::with_capacity(10);
530 /// vec.extend([1, 2, 3].iter().cloned());
532 /// assert_eq!(vec.capacity(), 10);
533 /// let slice = vec.into_boxed_slice();
534 /// assert_eq!(slice.into_vec().capacity(), 3);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn into_boxed_slice(mut self) -> Box<[T]> {
539 self.shrink_to_fit();
540 let buf = ptr::read(&self.buf);
546 /// Shortens the vector, keeping the first `len` elements and dropping
549 /// If `len` is greater than the vector's current length, this has no
552 /// The [`drain`] method can emulate `truncate`, but causes the excess
553 /// elements to be returned instead of dropped.
555 /// Note that this method has no effect on the allocated capacity
560 /// Truncating a five element vector to two elements:
563 /// let mut vec = vec![1, 2, 3, 4, 5];
565 /// assert_eq!(vec, [1, 2]);
568 /// No truncation occurs when `len` is greater than the vector's current
572 /// let mut vec = vec![1, 2, 3];
574 /// assert_eq!(vec, [1, 2, 3]);
577 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
581 /// let mut vec = vec![1, 2, 3];
583 /// assert_eq!(vec, []);
586 /// [`clear`]: #method.clear
587 /// [`drain`]: #method.drain
588 #[stable(feature = "rust1", since = "1.0.0")]
589 pub fn truncate(&mut self, len: usize) {
591 // drop any extra elements
592 while len < self.len {
593 // decrement len before the drop_in_place(), so a panic on Drop
594 // doesn't re-drop the just-failed value.
597 ptr::drop_in_place(self.get_unchecked_mut(len));
602 /// Extracts a slice containing the entire vector.
604 /// Equivalent to `&s[..]`.
609 /// use std::io::{self, Write};
610 /// let buffer = vec![1, 2, 3, 5, 8];
611 /// io::sink().write(buffer.as_slice()).unwrap();
614 #[stable(feature = "vec_as_slice", since = "1.7.0")]
615 pub fn as_slice(&self) -> &[T] {
619 /// Extracts a mutable slice of the entire vector.
621 /// Equivalent to `&mut s[..]`.
626 /// use std::io::{self, Read};
627 /// let mut buffer = vec![0; 3];
628 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
631 #[stable(feature = "vec_as_slice", since = "1.7.0")]
632 pub fn as_mut_slice(&mut self) -> &mut [T] {
636 /// Sets the length of a vector.
638 /// This will explicitly set the size of the vector, without actually
639 /// modifying its buffers, so it is up to the caller to ensure that the
640 /// vector is actually the specified size.
647 /// let mut vec = vec!['r', 'u', 's', 't'];
650 /// ptr::drop_in_place(&mut vec[3]);
653 /// assert_eq!(vec, ['r', 'u', 's']);
656 /// In this example, there is a memory leak since the memory locations
657 /// owned by the inner vectors were not freed prior to the `set_len` call:
660 /// let mut vec = vec![vec![1, 0, 0],
668 /// In this example, the vector gets expanded from zero to four items
669 /// without any memory allocations occurring, resulting in vector
670 /// values of unallocated memory:
673 /// let mut vec: Vec<char> = Vec::new();
680 #[stable(feature = "rust1", since = "1.0.0")]
681 pub unsafe fn set_len(&mut self, len: usize) {
685 /// Removes an element from the vector and returns it.
687 /// The removed element is replaced by the last element of the vector.
689 /// This does not preserve ordering, but is O(1).
693 /// Panics if `index` is out of bounds.
698 /// let mut v = vec!["foo", "bar", "baz", "qux"];
700 /// assert_eq!(v.swap_remove(1), "bar");
701 /// assert_eq!(v, ["foo", "qux", "baz"]);
703 /// assert_eq!(v.swap_remove(0), "foo");
704 /// assert_eq!(v, ["baz", "qux"]);
707 #[stable(feature = "rust1", since = "1.0.0")]
708 pub fn swap_remove(&mut self, index: usize) -> T {
709 let length = self.len();
710 self.swap(index, length - 1);
714 /// Inserts an element at position `index` within the vector, shifting all
715 /// elements after it to the right.
719 /// Panics if `index` is out of bounds.
724 /// let mut vec = vec![1, 2, 3];
725 /// vec.insert(1, 4);
726 /// assert_eq!(vec, [1, 4, 2, 3]);
727 /// vec.insert(4, 5);
728 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
730 #[stable(feature = "rust1", since = "1.0.0")]
731 pub fn insert(&mut self, index: usize, element: T) {
732 let len = self.len();
733 assert!(index <= len);
735 // space for the new element
736 if len == self.buf.cap() {
742 // The spot to put the new value
744 let p = self.as_mut_ptr().offset(index as isize);
745 // Shift everything over to make space. (Duplicating the
746 // `index`th element into two consecutive places.)
747 ptr::copy(p, p.offset(1), len - index);
748 // Write it in, overwriting the first copy of the `index`th
750 ptr::write(p, element);
752 self.set_len(len + 1);
756 /// Removes and returns the element at position `index` within the vector,
757 /// shifting all elements after it to the left.
761 /// Panics if `index` is out of bounds.
766 /// let mut v = vec![1, 2, 3];
767 /// assert_eq!(v.remove(1), 2);
768 /// assert_eq!(v, [1, 3]);
770 #[stable(feature = "rust1", since = "1.0.0")]
771 pub fn remove(&mut self, index: usize) -> T {
772 let len = self.len();
773 assert!(index < len);
778 // the place we are taking from.
779 let ptr = self.as_mut_ptr().offset(index as isize);
780 // copy it out, unsafely having a copy of the value on
781 // the stack and in the vector at the same time.
782 ret = ptr::read(ptr);
784 // Shift everything down to fill in that spot.
785 ptr::copy(ptr.offset(1), ptr, len - index - 1);
787 self.set_len(len - 1);
792 /// Retains only the elements specified by the predicate.
794 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
795 /// This method operates in place and preserves the order of the retained
801 /// let mut vec = vec![1, 2, 3, 4];
802 /// vec.retain(|&x| x%2 == 0);
803 /// assert_eq!(vec, [2, 4]);
805 #[stable(feature = "rust1", since = "1.0.0")]
806 pub fn retain<F>(&mut self, mut f: F)
807 where F: FnMut(&T) -> bool
809 let len = self.len();
823 self.truncate(len - del);
827 /// Removes all but the first of consecutive elements in the vector that resolve to the same
830 /// If the vector is sorted, this removes all duplicates.
835 /// let mut vec = vec![10, 20, 21, 30, 20];
837 /// vec.dedup_by_key(|i| *i / 10);
839 /// assert_eq!(vec, [10, 20, 30, 20]);
841 #[stable(feature = "dedup_by", since = "1.16.0")]
843 pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
844 self.dedup_by(|a, b| key(a) == key(b))
847 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
850 /// The `same_bucket` function is passed references to two elements from the vector, and
851 /// returns `true` if the elements compare equal, or `false` if they do not. The elements are
852 /// passed in opposite order from their order in the vector, so if `same_bucket(a, b)` returns
853 /// `true`, `a` is removed.
855 /// If the vector is sorted, this removes all duplicates.
860 /// use std::ascii::AsciiExt;
862 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
864 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
866 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
868 #[stable(feature = "dedup_by", since = "1.16.0")]
869 pub fn dedup_by<F>(&mut self, mut same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
871 // Although we have a mutable reference to `self`, we cannot make
872 // *arbitrary* changes. The `same_bucket` calls could panic, so we
873 // must ensure that the vector is in a valid state at all time.
875 // The way that we handle this is by using swaps; we iterate
876 // over all the elements, swapping as we go so that at the end
877 // the elements we wish to keep are in the front, and those we
878 // wish to reject are at the back. We can then truncate the
879 // vector. This operation is still O(n).
881 // Example: We start in this state, where `r` represents "next
882 // read" and `w` represents "next_write`.
885 // +---+---+---+---+---+---+
886 // | 0 | 1 | 1 | 2 | 3 | 3 |
887 // +---+---+---+---+---+---+
890 // Comparing self[r] against self[w-1], this is not a duplicate, so
891 // we swap self[r] and self[w] (no effect as r==w) and then increment both
892 // r and w, leaving us with:
895 // +---+---+---+---+---+---+
896 // | 0 | 1 | 1 | 2 | 3 | 3 |
897 // +---+---+---+---+---+---+
900 // Comparing self[r] against self[w-1], this value is a duplicate,
901 // so we increment `r` but leave everything else unchanged:
904 // +---+---+---+---+---+---+
905 // | 0 | 1 | 1 | 2 | 3 | 3 |
906 // +---+---+---+---+---+---+
909 // Comparing self[r] against self[w-1], this is not a duplicate,
910 // so swap self[r] and self[w] and advance r and w:
913 // +---+---+---+---+---+---+
914 // | 0 | 1 | 2 | 1 | 3 | 3 |
915 // +---+---+---+---+---+---+
918 // Not a duplicate, repeat:
921 // +---+---+---+---+---+---+
922 // | 0 | 1 | 2 | 3 | 1 | 3 |
923 // +---+---+---+---+---+---+
926 // Duplicate, advance r. End of vec. Truncate to w.
933 // Avoid bounds checks by using raw pointers.
934 let p = self.as_mut_ptr();
935 let mut r: usize = 1;
936 let mut w: usize = 1;
939 let p_r = p.offset(r as isize);
940 let p_wm1 = p.offset((w - 1) as isize);
941 if !same_bucket(&mut *p_r, &mut *p_wm1) {
943 let p_w = p_wm1.offset(1);
944 mem::swap(&mut *p_r, &mut *p_w);
955 /// Appends an element to the back of a collection.
959 /// Panics if the number of elements in the vector overflows a `usize`.
964 /// let mut vec = vec![1, 2];
966 /// assert_eq!(vec, [1, 2, 3]);
969 #[stable(feature = "rust1", since = "1.0.0")]
970 pub fn push(&mut self, value: T) {
971 // This will panic or abort if we would allocate > isize::MAX bytes
972 // or if the length increment would overflow for zero-sized types.
973 if self.len == self.buf.cap() {
977 let end = self.as_mut_ptr().offset(self.len as isize);
978 ptr::write(end, value);
983 /// Returns a place for insertion at the back of the `Vec`.
985 /// Using this method with placement syntax is equivalent to [`push`](#method.push),
986 /// but may be more efficient.
991 /// #![feature(collection_placement)]
992 /// #![feature(placement_in_syntax)]
994 /// let mut vec = vec![1, 2];
995 /// vec.place_back() <- 3;
996 /// vec.place_back() <- 4;
997 /// assert_eq!(&vec, &[1, 2, 3, 4]);
999 #[unstable(feature = "collection_placement",
1000 reason = "placement protocol is subject to change",
1002 pub fn place_back(&mut self) -> PlaceBack<T> {
1003 PlaceBack { vec: self }
1006 /// Removes the last element from a vector and returns it, or [`None`] if it
1009 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1014 /// let mut vec = vec![1, 2, 3];
1015 /// assert_eq!(vec.pop(), Some(3));
1016 /// assert_eq!(vec, [1, 2]);
1019 #[stable(feature = "rust1", since = "1.0.0")]
1020 pub fn pop(&mut self) -> Option<T> {
1026 Some(ptr::read(self.get_unchecked(self.len())))
1031 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1035 /// Panics if the number of elements in the vector overflows a `usize`.
1040 /// let mut vec = vec![1, 2, 3];
1041 /// let mut vec2 = vec![4, 5, 6];
1042 /// vec.append(&mut vec2);
1043 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1044 /// assert_eq!(vec2, []);
1047 #[stable(feature = "append", since = "1.4.0")]
1048 pub fn append(&mut self, other: &mut Self) {
1050 self.append_elements(other.as_slice() as _);
1055 /// Appends elements to `Self` from other buffer.
1057 unsafe fn append_elements(&mut self, other: *const [T]) {
1058 let count = (*other).len();
1059 self.reserve(count);
1060 let len = self.len();
1061 ptr::copy_nonoverlapping(other as *const T, self.get_unchecked_mut(len), count);
1065 /// Creates a draining iterator that removes the specified range in the vector
1066 /// and yields the removed items.
1068 /// Note 1: The element range is removed even if the iterator is only
1069 /// partially consumed or not consumed at all.
1071 /// Note 2: It is unspecified how many elements are removed from the vector
1072 /// if the `Drain` value is leaked.
1076 /// Panics if the starting point is greater than the end point or if
1077 /// the end point is greater than the length of the vector.
1082 /// let mut v = vec![1, 2, 3];
1083 /// let u: Vec<_> = v.drain(1..).collect();
1084 /// assert_eq!(v, &[1]);
1085 /// assert_eq!(u, &[2, 3]);
1087 /// // A full range clears the vector
1089 /// assert_eq!(v, &[]);
1091 #[stable(feature = "drain", since = "1.6.0")]
1092 pub fn drain<R>(&mut self, range: R) -> Drain<T>
1093 where R: RangeArgument<usize>
1097 // When the Drain is first created, it shortens the length of
1098 // the source vector to make sure no uninitalized or moved-from elements
1099 // are accessible at all if the Drain's destructor never gets to run.
1101 // Drain will ptr::read out the values to remove.
1102 // When finished, remaining tail of the vec is copied back to cover
1103 // the hole, and the vector length is restored to the new length.
1105 let len = self.len();
1106 let start = match range.start() {
1108 Excluded(&n) => n + 1,
1111 let end = match range.end() {
1112 Included(&n) => n + 1,
1116 assert!(start <= end);
1117 assert!(end <= len);
1120 // set self.vec length's to start, to be safe in case Drain is leaked
1121 self.set_len(start);
1122 // Use the borrow in the IterMut to indicate borrowing behavior of the
1123 // whole Drain iterator (like &mut T).
1124 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
1128 tail_len: len - end,
1129 iter: range_slice.iter(),
1130 vec: Shared::from(self),
1135 /// Clears the vector, removing all values.
1137 /// Note that this method has no effect on the allocated capacity
1143 /// let mut v = vec![1, 2, 3];
1147 /// assert!(v.is_empty());
1150 #[stable(feature = "rust1", since = "1.0.0")]
1151 pub fn clear(&mut self) {
1155 /// Returns the number of elements in the vector, also referred to
1156 /// as its 'length'.
1161 /// let a = vec![1, 2, 3];
1162 /// assert_eq!(a.len(), 3);
1165 #[stable(feature = "rust1", since = "1.0.0")]
1166 pub fn len(&self) -> usize {
1170 /// Returns `true` if the vector contains no elements.
1175 /// let mut v = Vec::new();
1176 /// assert!(v.is_empty());
1179 /// assert!(!v.is_empty());
1181 #[stable(feature = "rust1", since = "1.0.0")]
1182 pub fn is_empty(&self) -> bool {
1186 /// Splits the collection into two at the given index.
1188 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1189 /// and the returned `Self` contains elements `[at, len)`.
1191 /// Note that the capacity of `self` does not change.
1195 /// Panics if `at > len`.
1200 /// let mut vec = vec![1,2,3];
1201 /// let vec2 = vec.split_off(1);
1202 /// assert_eq!(vec, [1]);
1203 /// assert_eq!(vec2, [2, 3]);
1206 #[stable(feature = "split_off", since = "1.4.0")]
1207 pub fn split_off(&mut self, at: usize) -> Self {
1208 assert!(at <= self.len(), "`at` out of bounds");
1210 let other_len = self.len - at;
1211 let mut other = Vec::with_capacity(other_len);
1213 // Unsafely `set_len` and copy items to `other`.
1216 other.set_len(other_len);
1218 ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
1226 impl<T: Clone> Vec<T> {
1227 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1229 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1230 /// difference, with each additional slot filled with `value`.
1231 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1233 /// This method requires `Clone` to clone the passed value. If you'd
1234 /// rather create a value with `Default` instead, see [`resize_default`].
1239 /// let mut vec = vec!["hello"];
1240 /// vec.resize(3, "world");
1241 /// assert_eq!(vec, ["hello", "world", "world"]);
1243 /// let mut vec = vec![1, 2, 3, 4];
1244 /// vec.resize(2, 0);
1245 /// assert_eq!(vec, [1, 2]);
1248 /// [`resize_default`]: #method.resize_default
1249 #[stable(feature = "vec_resize", since = "1.5.0")]
1250 pub fn resize(&mut self, new_len: usize, value: T) {
1251 let len = self.len();
1254 self.extend_with(new_len - len, ExtendElement(value))
1256 self.truncate(new_len);
1260 /// Clones and appends all elements in a slice to the `Vec`.
1262 /// Iterates over the slice `other`, clones each element, and then appends
1263 /// it to this `Vec`. The `other` vector is traversed in-order.
1265 /// Note that this function is same as `extend` except that it is
1266 /// specialized to work with slices instead. If and when Rust gets
1267 /// specialization this function will likely be deprecated (but still
1273 /// let mut vec = vec![1];
1274 /// vec.extend_from_slice(&[2, 3, 4]);
1275 /// assert_eq!(vec, [1, 2, 3, 4]);
1277 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1278 pub fn extend_from_slice(&mut self, other: &[T]) {
1279 self.spec_extend(other.iter())
1283 impl<T: Default> Vec<T> {
1284 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1286 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1287 /// difference, with each additional slot filled with `Default::default()`.
1288 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1290 /// This method uses `Default` to create new values on every push. If
1291 /// you'd rather `Clone` a given value, use [`resize`].
1297 /// #![feature(vec_resize_default)]
1299 /// let mut vec = vec![1, 2, 3];
1300 /// vec.resize_default(5);
1301 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1303 /// let mut vec = vec![1, 2, 3, 4];
1304 /// vec.resize_default(2);
1305 /// assert_eq!(vec, [1, 2]);
1308 /// [`resize`]: #method.resize
1309 #[unstable(feature = "vec_resize_default", issue = "41758")]
1310 pub fn resize_default(&mut self, new_len: usize) {
1311 let len = self.len();
1314 self.extend_with(new_len - len, ExtendDefault);
1316 self.truncate(new_len);
1321 // This code generalises `extend_with_{element,default}`.
1322 trait ExtendWith<T> {
1323 fn next(&self) -> T;
1327 struct ExtendElement<T>(T);
1328 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1329 fn next(&self) -> T { self.0.clone() }
1330 fn last(self) -> T { self.0 }
1333 struct ExtendDefault;
1334 impl<T: Default> ExtendWith<T> for ExtendDefault {
1335 fn next(&self) -> T { Default::default() }
1336 fn last(self) -> T { Default::default() }
1339 /// Extend the vector by `n` values, using the given generator.
1340 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, value: E) {
1344 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1345 // Use SetLenOnDrop to work around bug where compiler
1346 // may not realize the store through `ptr` through self.set_len()
1348 let mut local_len = SetLenOnDrop::new(&mut self.len);
1350 // Write all elements except the last one
1352 ptr::write(ptr, value.next());
1353 ptr = ptr.offset(1);
1354 // Increment the length in every step in case next() panics
1355 local_len.increment_len(1);
1359 // We can write the last element directly without cloning needlessly
1360 ptr::write(ptr, value.last());
1361 local_len.increment_len(1);
1364 // len set by scope guard
1369 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1371 // The idea is: The length field in SetLenOnDrop is a local variable
1372 // that the optimizer will see does not alias with any stores through the Vec's data
1373 // pointer. This is a workaround for alias analysis issue #32155
1374 struct SetLenOnDrop<'a> {
1379 impl<'a> SetLenOnDrop<'a> {
1381 fn new(len: &'a mut usize) -> Self {
1382 SetLenOnDrop { local_len: *len, len: len }
1386 fn increment_len(&mut self, increment: usize) {
1387 self.local_len += increment;
1391 impl<'a> Drop for SetLenOnDrop<'a> {
1393 fn drop(&mut self) {
1394 *self.len = self.local_len;
1398 impl<T: PartialEq> Vec<T> {
1399 /// Removes consecutive repeated elements in the vector.
1401 /// If the vector is sorted, this removes all duplicates.
1406 /// let mut vec = vec![1, 2, 2, 3, 2];
1410 /// assert_eq!(vec, [1, 2, 3, 2]);
1412 #[stable(feature = "rust1", since = "1.0.0")]
1414 pub fn dedup(&mut self) {
1415 self.dedup_by(|a, b| a == b)
1418 /// Removes the first instance of `item` from the vector if the item exists.
1423 /// # #![feature(vec_remove_item)]
1424 /// let mut vec = vec![1, 2, 3, 1];
1426 /// vec.remove_item(&1);
1428 /// assert_eq!(vec, vec![2, 3, 1]);
1430 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1431 pub fn remove_item(&mut self, item: &T) -> Option<T> {
1432 let pos = match self.iter().position(|x| *x == *item) {
1434 None => return None,
1436 Some(self.remove(pos))
1440 ////////////////////////////////////////////////////////////////////////////////
1441 // Internal methods and functions
1442 ////////////////////////////////////////////////////////////////////////////////
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1447 <T as SpecFromElem>::from_elem(elem, n)
1450 // Specialization trait used for Vec::from_elem
1451 trait SpecFromElem: Sized {
1452 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1455 impl<T: Clone> SpecFromElem for T {
1456 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1457 let mut v = Vec::with_capacity(n);
1458 v.extend_with(n, ExtendElement(elem));
1463 impl SpecFromElem for u8 {
1465 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1468 buf: RawVec::with_capacity_zeroed(n),
1473 let mut v = Vec::with_capacity(n);
1474 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1481 macro_rules! impl_spec_from_elem {
1482 ($t: ty, $is_zero: expr) => {
1483 impl SpecFromElem for $t {
1485 fn from_elem(elem: $t, n: usize) -> Vec<$t> {
1488 buf: RawVec::with_capacity_zeroed(n),
1492 let mut v = Vec::with_capacity(n);
1493 v.extend_with(n, ExtendElement(elem));
1500 impl_spec_from_elem!(i8, |x| x == 0);
1501 impl_spec_from_elem!(i16, |x| x == 0);
1502 impl_spec_from_elem!(i32, |x| x == 0);
1503 impl_spec_from_elem!(i64, |x| x == 0);
1504 impl_spec_from_elem!(i128, |x| x == 0);
1505 impl_spec_from_elem!(isize, |x| x == 0);
1507 impl_spec_from_elem!(u16, |x| x == 0);
1508 impl_spec_from_elem!(u32, |x| x == 0);
1509 impl_spec_from_elem!(u64, |x| x == 0);
1510 impl_spec_from_elem!(u128, |x| x == 0);
1511 impl_spec_from_elem!(usize, |x| x == 0);
1513 impl_spec_from_elem!(f32, |x: f32| x == 0. && x.is_sign_positive());
1514 impl_spec_from_elem!(f64, |x: f64| x == 0. && x.is_sign_positive());
1516 ////////////////////////////////////////////////////////////////////////////////
1517 // Common trait implementations for Vec
1518 ////////////////////////////////////////////////////////////////////////////////
1520 #[stable(feature = "rust1", since = "1.0.0")]
1521 impl<T: Clone> Clone for Vec<T> {
1523 fn clone(&self) -> Vec<T> {
1524 <[T]>::to_vec(&**self)
1527 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1528 // required for this method definition, is not available. Instead use the
1529 // `slice::to_vec` function which is only available with cfg(test)
1530 // NB see the slice::hack module in slice.rs for more information
1532 fn clone(&self) -> Vec<T> {
1533 ::slice::to_vec(&**self)
1536 fn clone_from(&mut self, other: &Vec<T>) {
1537 other.as_slice().clone_into(self);
1541 #[stable(feature = "rust1", since = "1.0.0")]
1542 impl<T: Hash> Hash for Vec<T> {
1544 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1545 Hash::hash(&**self, state)
1549 #[stable(feature = "rust1", since = "1.0.0")]
1550 impl<T> Index<usize> for Vec<T> {
1554 fn index(&self, index: usize) -> &T {
1555 // NB built-in indexing via `&[T]`
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl<T> IndexMut<usize> for Vec<T> {
1563 fn index_mut(&mut self, index: usize) -> &mut T {
1564 // NB built-in indexing via `&mut [T]`
1565 &mut (**self)[index]
1570 #[stable(feature = "rust1", since = "1.0.0")]
1571 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1575 fn index(&self, index: ops::Range<usize>) -> &[T] {
1576 Index::index(&**self, index)
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1584 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1585 Index::index(&**self, index)
1588 #[stable(feature = "rust1", since = "1.0.0")]
1589 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1593 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1594 Index::index(&**self, index)
1597 #[stable(feature = "rust1", since = "1.0.0")]
1598 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1602 fn index(&self, _index: ops::RangeFull) -> &[T] {
1606 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1607 impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> {
1611 fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
1612 Index::index(&**self, index)
1615 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1616 impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> {
1620 fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
1621 Index::index(&**self, index)
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1628 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1629 IndexMut::index_mut(&mut **self, index)
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1635 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1636 IndexMut::index_mut(&mut **self, index)
1639 #[stable(feature = "rust1", since = "1.0.0")]
1640 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1642 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1643 IndexMut::index_mut(&mut **self, index)
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1649 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1653 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1654 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> {
1656 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
1657 IndexMut::index_mut(&mut **self, index)
1660 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1661 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> {
1663 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
1664 IndexMut::index_mut(&mut **self, index)
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<T> ops::Deref for Vec<T> {
1672 fn deref(&self) -> &[T] {
1674 let p = self.buf.ptr();
1675 assume(!p.is_null());
1676 slice::from_raw_parts(p, self.len)
1681 #[stable(feature = "rust1", since = "1.0.0")]
1682 impl<T> ops::DerefMut for Vec<T> {
1683 fn deref_mut(&mut self) -> &mut [T] {
1685 let ptr = self.buf.ptr();
1686 assume(!ptr.is_null());
1687 slice::from_raw_parts_mut(ptr, self.len)
1692 #[stable(feature = "rust1", since = "1.0.0")]
1693 impl<T> FromIterator<T> for Vec<T> {
1695 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1696 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1700 #[stable(feature = "rust1", since = "1.0.0")]
1701 impl<T> IntoIterator for Vec<T> {
1703 type IntoIter = IntoIter<T>;
1705 /// Creates a consuming iterator, that is, one that moves each value out of
1706 /// the vector (from start to end). The vector cannot be used after calling
1712 /// let v = vec!["a".to_string(), "b".to_string()];
1713 /// for s in v.into_iter() {
1714 /// // s has type String, not &String
1715 /// println!("{}", s);
1719 fn into_iter(mut self) -> IntoIter<T> {
1721 let begin = self.as_mut_ptr();
1722 assume(!begin.is_null());
1723 let end = if mem::size_of::<T>() == 0 {
1724 arith_offset(begin as *const i8, self.len() as isize) as *const T
1726 begin.offset(self.len() as isize) as *const T
1728 let cap = self.buf.cap();
1731 buf: Shared::new_unchecked(begin),
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 impl<'a, T> IntoIterator for &'a Vec<T> {
1743 type IntoIter = slice::Iter<'a, T>;
1745 fn into_iter(self) -> slice::Iter<'a, T> {
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1752 type Item = &'a mut T;
1753 type IntoIter = slice::IterMut<'a, T>;
1755 fn into_iter(self) -> slice::IterMut<'a, T> {
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 impl<T> Extend<T> for Vec<T> {
1763 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1764 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1768 // Specialization trait used for Vec::from_iter and Vec::extend
1769 trait SpecExtend<T, I> {
1770 fn from_iter(iter: I) -> Self;
1771 fn spec_extend(&mut self, iter: I);
1774 impl<T, I> SpecExtend<T, I> for Vec<T>
1775 where I: Iterator<Item=T>,
1777 default fn from_iter(mut iterator: I) -> Self {
1778 // Unroll the first iteration, as the vector is going to be
1779 // expanded on this iteration in every case when the iterable is not
1780 // empty, but the loop in extend_desugared() is not going to see the
1781 // vector being full in the few subsequent loop iterations.
1782 // So we get better branch prediction.
1783 let mut vector = match iterator.next() {
1784 None => return Vec::new(),
1786 let (lower, _) = iterator.size_hint();
1787 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1789 ptr::write(vector.get_unchecked_mut(0), element);
1795 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1799 default fn spec_extend(&mut self, iter: I) {
1800 self.extend_desugared(iter)
1804 impl<T, I> SpecExtend<T, I> for Vec<T>
1805 where I: TrustedLen<Item=T>,
1807 default fn from_iter(iterator: I) -> Self {
1808 let mut vector = Vec::new();
1809 vector.spec_extend(iterator);
1813 default fn spec_extend(&mut self, iterator: I) {
1814 // This is the case for a TrustedLen iterator.
1815 let (low, high) = iterator.size_hint();
1816 if let Some(high_value) = high {
1817 debug_assert_eq!(low, high_value,
1818 "TrustedLen iterator's size hint is not exact: {:?}",
1821 if let Some(additional) = high {
1822 self.reserve(additional);
1824 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1825 let mut local_len = SetLenOnDrop::new(&mut self.len);
1826 for element in iterator {
1827 ptr::write(ptr, element);
1828 ptr = ptr.offset(1);
1829 // NB can't overflow since we would have had to alloc the address space
1830 local_len.increment_len(1);
1834 self.extend_desugared(iterator)
1839 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
1840 fn from_iter(iterator: IntoIter<T>) -> Self {
1841 // A common case is passing a vector into a function which immediately
1842 // re-collects into a vector. We can short circuit this if the IntoIter
1843 // has not been advanced at all.
1844 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
1846 let vec = Vec::from_raw_parts(iterator.buf.as_ptr(),
1849 mem::forget(iterator);
1853 let mut vector = Vec::new();
1854 vector.spec_extend(iterator);
1859 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
1861 self.append_elements(iterator.as_slice() as _);
1863 iterator.ptr = iterator.end;
1867 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
1868 where I: Iterator<Item=&'a T>,
1871 default fn from_iter(iterator: I) -> Self {
1872 SpecExtend::from_iter(iterator.cloned())
1875 default fn spec_extend(&mut self, iterator: I) {
1876 self.spec_extend(iterator.cloned())
1880 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
1883 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
1884 let slice = iterator.as_slice();
1885 self.reserve(slice.len());
1887 let len = self.len();
1888 self.set_len(len + slice.len());
1889 self.get_unchecked_mut(len..).copy_from_slice(slice);
1895 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1896 // This is the case for a general iterator.
1898 // This function should be the moral equivalent of:
1900 // for item in iterator {
1903 while let Some(element) = iterator.next() {
1904 let len = self.len();
1905 if len == self.capacity() {
1906 let (lower, _) = iterator.size_hint();
1907 self.reserve(lower.saturating_add(1));
1910 ptr::write(self.get_unchecked_mut(len), element);
1911 // NB can't overflow since we would have had to alloc the address space
1912 self.set_len(len + 1);
1917 /// Creates a splicing iterator that replaces the specified range in the vector
1918 /// with the given `replace_with` iterator and yields the removed items.
1919 /// `replace_with` does not need to be the same length as `range`.
1921 /// Note 1: The element range is removed even if the iterator is not
1922 /// consumed until the end.
1924 /// Note 2: It is unspecified how many elements are removed from the vector,
1925 /// if the `Splice` value is leaked.
1927 /// Note 3: The input iterator `replace_with` is only consumed
1928 /// when the `Splice` value is dropped.
1930 /// Note 4: This is optimal if:
1932 /// * The tail (elements in the vector after `range`) is empty,
1933 /// * or `replace_with` yields fewer elements than `range`’s length
1934 /// * or the lower bound of its `size_hint()` is exact.
1936 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
1940 /// Panics if the starting point is greater than the end point or if
1941 /// the end point is greater than the length of the vector.
1946 /// #![feature(splice)]
1947 /// let mut v = vec![1, 2, 3];
1948 /// let new = [7, 8];
1949 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
1950 /// assert_eq!(v, &[7, 8, 3]);
1951 /// assert_eq!(u, &[1, 2]);
1954 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
1955 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<I::IntoIter>
1956 where R: RangeArgument<usize>, I: IntoIterator<Item=T>
1959 drain: self.drain(range),
1960 replace_with: replace_with.into_iter(),
1964 /// Creates an iterator which uses a closure to determine if an element should be removed.
1966 /// If the closure returns true, then the element is removed and yielded.
1967 /// If the closure returns false, it will try again, and call the closure
1968 /// on the next element, seeing if it passes the test.
1970 /// Using this method is equivalent to the following code:
1973 /// # let some_predicate = |x: &mut i32| { *x == 2 };
1974 /// # let mut vec = vec![1, 2, 3, 4, 5];
1976 /// while i != vec.len() {
1977 /// if some_predicate(&mut vec[i]) {
1978 /// let val = vec.remove(i);
1979 /// // your code here
1985 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
1986 /// because it can backshift the elements of the array in bulk.
1988 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
1989 /// regardless of whether you choose to keep or remove it.
1994 /// Splitting an array into evens and odds, reusing the original allocation:
1997 /// #![feature(drain_filter)]
1998 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2000 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2001 /// let odds = numbers;
2003 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2004 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2006 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2007 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<T, F>
2008 where F: FnMut(&mut T) -> bool,
2010 let old_len = self.len();
2012 // Guard against us getting leaked (leak amplification)
2013 unsafe { self.set_len(0); }
2025 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2027 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2028 /// append the entire slice at once.
2030 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2031 #[stable(feature = "extend_ref", since = "1.2.0")]
2032 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2033 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2034 self.spec_extend(iter.into_iter())
2038 macro_rules! __impl_slice_eq1 {
2039 ($Lhs: ty, $Rhs: ty) => {
2040 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2042 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2043 #[stable(feature = "rust1", since = "1.0.0")]
2044 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2046 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
2048 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
2053 __impl_slice_eq1! { Vec<A>, Vec<B> }
2054 __impl_slice_eq1! { Vec<A>, &'b [B] }
2055 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
2056 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
2057 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
2058 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
2060 macro_rules! array_impls {
2063 // NOTE: some less important impls are omitted to reduce code bloat
2064 __impl_slice_eq1! { Vec<A>, [B; $N] }
2065 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
2066 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
2067 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
2068 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
2069 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
2076 10 11 12 13 14 15 16 17 18 19
2077 20 21 22 23 24 25 26 27 28 29
2081 /// Implements comparison of vectors, lexicographically.
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 impl<T: PartialOrd> PartialOrd for Vec<T> {
2085 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2086 PartialOrd::partial_cmp(&**self, &**other)
2090 #[stable(feature = "rust1", since = "1.0.0")]
2091 impl<T: Eq> Eq for Vec<T> {}
2093 /// Implements ordering of vectors, lexicographically.
2094 #[stable(feature = "rust1", since = "1.0.0")]
2095 impl<T: Ord> Ord for Vec<T> {
2097 fn cmp(&self, other: &Vec<T>) -> Ordering {
2098 Ord::cmp(&**self, &**other)
2102 #[stable(feature = "rust1", since = "1.0.0")]
2103 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2104 fn drop(&mut self) {
2107 ptr::drop_in_place(&mut self[..]);
2109 // RawVec handles deallocation
2113 #[stable(feature = "rust1", since = "1.0.0")]
2114 impl<T> Default for Vec<T> {
2115 /// Creates an empty `Vec<T>`.
2116 fn default() -> Vec<T> {
2121 #[stable(feature = "rust1", since = "1.0.0")]
2122 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2123 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2124 fmt::Debug::fmt(&**self, f)
2128 #[stable(feature = "rust1", since = "1.0.0")]
2129 impl<T> AsRef<Vec<T>> for Vec<T> {
2130 fn as_ref(&self) -> &Vec<T> {
2135 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2136 impl<T> AsMut<Vec<T>> for Vec<T> {
2137 fn as_mut(&mut self) -> &mut Vec<T> {
2142 #[stable(feature = "rust1", since = "1.0.0")]
2143 impl<T> AsRef<[T]> for Vec<T> {
2144 fn as_ref(&self) -> &[T] {
2149 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2150 impl<T> AsMut<[T]> for Vec<T> {
2151 fn as_mut(&mut self) -> &mut [T] {
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
2159 fn from(s: &'a [T]) -> Vec<T> {
2163 fn from(s: &'a [T]) -> Vec<T> {
2168 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2169 impl<'a, T: Clone> From<&'a mut [T]> for Vec<T> {
2171 fn from(s: &'a mut [T]) -> Vec<T> {
2175 fn from(s: &'a mut [T]) -> Vec<T> {
2180 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2181 impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> {
2182 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2187 // note: test pulls in libstd, which causes errors here
2189 #[stable(feature = "vec_from_box", since = "1.18.0")]
2190 impl<T> From<Box<[T]>> for Vec<T> {
2191 fn from(s: Box<[T]>) -> Vec<T> {
2196 // note: test pulls in libstd, which causes errors here
2198 #[stable(feature = "box_from_vec", since = "1.20.0")]
2199 impl<T> From<Vec<T>> for Box<[T]> {
2200 fn from(v: Vec<T>) -> Box<[T]> {
2201 v.into_boxed_slice()
2205 #[stable(feature = "rust1", since = "1.0.0")]
2206 impl<'a> From<&'a str> for Vec<u8> {
2207 fn from(s: &'a str) -> Vec<u8> {
2208 From::from(s.as_bytes())
2212 ////////////////////////////////////////////////////////////////////////////////
2214 ////////////////////////////////////////////////////////////////////////////////
2216 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2217 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2218 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2223 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2224 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2225 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2230 #[stable(feature = "rust1", since = "1.0.0")]
2231 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
2232 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2233 Cow::Owned(FromIterator::from_iter(it))
2237 ////////////////////////////////////////////////////////////////////////////////
2239 ////////////////////////////////////////////////////////////////////////////////
2241 /// An iterator that moves out of a vector.
2243 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2244 /// by the [`IntoIterator`] trait).
2246 /// [`Vec`]: struct.Vec.html
2247 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2248 #[stable(feature = "rust1", since = "1.0.0")]
2249 pub struct IntoIter<T> {
2256 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2257 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2258 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2259 f.debug_tuple("IntoIter")
2260 .field(&self.as_slice())
2265 impl<T> IntoIter<T> {
2266 /// Returns the remaining items of this iterator as a slice.
2271 /// let vec = vec!['a', 'b', 'c'];
2272 /// let mut into_iter = vec.into_iter();
2273 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2274 /// let _ = into_iter.next().unwrap();
2275 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2277 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2278 pub fn as_slice(&self) -> &[T] {
2280 slice::from_raw_parts(self.ptr, self.len())
2284 /// Returns the remaining items of this iterator as a mutable slice.
2289 /// let vec = vec!['a', 'b', 'c'];
2290 /// let mut into_iter = vec.into_iter();
2291 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2292 /// into_iter.as_mut_slice()[2] = 'z';
2293 /// assert_eq!(into_iter.next().unwrap(), 'a');
2294 /// assert_eq!(into_iter.next().unwrap(), 'b');
2295 /// assert_eq!(into_iter.next().unwrap(), 'z');
2297 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2298 pub fn as_mut_slice(&mut self) -> &mut [T] {
2300 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
2305 #[stable(feature = "rust1", since = "1.0.0")]
2306 unsafe impl<T: Send> Send for IntoIter<T> {}
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2310 #[stable(feature = "rust1", since = "1.0.0")]
2311 impl<T> Iterator for IntoIter<T> {
2315 fn next(&mut self) -> Option<T> {
2317 if self.ptr as *const _ == self.end {
2320 if mem::size_of::<T>() == 0 {
2321 // purposefully don't use 'ptr.offset' because for
2322 // vectors with 0-size elements this would return the
2324 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2326 // Use a non-null pointer value
2327 // (self.ptr might be null because of wrapping)
2328 Some(ptr::read(1 as *mut T))
2331 self.ptr = self.ptr.offset(1);
2333 Some(ptr::read(old))
2340 fn size_hint(&self) -> (usize, Option<usize>) {
2341 let exact = match self.ptr.offset_to(self.end) {
2342 Some(x) => x as usize,
2343 None => (self.end as usize).wrapping_sub(self.ptr as usize),
2345 (exact, Some(exact))
2349 fn count(self) -> usize {
2354 #[stable(feature = "rust1", since = "1.0.0")]
2355 impl<T> DoubleEndedIterator for IntoIter<T> {
2357 fn next_back(&mut self) -> Option<T> {
2359 if self.end == self.ptr {
2362 if mem::size_of::<T>() == 0 {
2363 // See above for why 'ptr.offset' isn't used
2364 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2366 // Use a non-null pointer value
2367 // (self.end might be null because of wrapping)
2368 Some(ptr::read(1 as *mut T))
2370 self.end = self.end.offset(-1);
2372 Some(ptr::read(self.end))
2379 #[stable(feature = "rust1", since = "1.0.0")]
2380 impl<T> ExactSizeIterator for IntoIter<T> {
2381 fn is_empty(&self) -> bool {
2382 self.ptr == self.end
2386 #[unstable(feature = "fused", issue = "35602")]
2387 impl<T> FusedIterator for IntoIter<T> {}
2389 #[unstable(feature = "trusted_len", issue = "37572")]
2390 unsafe impl<T> TrustedLen for IntoIter<T> {}
2392 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2393 impl<T: Clone> Clone for IntoIter<T> {
2394 fn clone(&self) -> IntoIter<T> {
2395 self.as_slice().to_owned().into_iter()
2399 #[stable(feature = "rust1", since = "1.0.0")]
2400 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2401 fn drop(&mut self) {
2402 // destroy the remaining elements
2403 for _x in self.by_ref() {}
2405 // RawVec handles deallocation
2406 let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) };
2410 /// A draining iterator for `Vec<T>`.
2412 /// This `struct` is created by the [`drain`] method on [`Vec`].
2414 /// [`drain`]: struct.Vec.html#method.drain
2415 /// [`Vec`]: struct.Vec.html
2416 #[stable(feature = "drain", since = "1.6.0")]
2417 pub struct Drain<'a, T: 'a> {
2418 /// Index of tail to preserve
2422 /// Current remaining range to remove
2423 iter: slice::Iter<'a, T>,
2424 vec: Shared<Vec<T>>,
2427 #[stable(feature = "collection_debug", since = "1.17.0")]
2428 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2429 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2430 f.debug_tuple("Drain")
2431 .field(&self.iter.as_slice())
2436 #[stable(feature = "drain", since = "1.6.0")]
2437 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2438 #[stable(feature = "drain", since = "1.6.0")]
2439 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2441 #[stable(feature = "drain", since = "1.6.0")]
2442 impl<'a, T> Iterator for Drain<'a, T> {
2446 fn next(&mut self) -> Option<T> {
2447 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2450 fn size_hint(&self) -> (usize, Option<usize>) {
2451 self.iter.size_hint()
2455 #[stable(feature = "drain", since = "1.6.0")]
2456 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
2458 fn next_back(&mut self) -> Option<T> {
2459 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2463 #[stable(feature = "drain", since = "1.6.0")]
2464 impl<'a, T> Drop for Drain<'a, T> {
2465 fn drop(&mut self) {
2466 // exhaust self first
2467 while let Some(_) = self.next() {}
2469 if self.tail_len > 0 {
2471 let source_vec = self.vec.as_mut();
2472 // memmove back untouched tail, update to new length
2473 let start = source_vec.len();
2474 let tail = self.tail_start;
2475 let src = source_vec.as_ptr().offset(tail as isize);
2476 let dst = source_vec.as_mut_ptr().offset(start as isize);
2477 ptr::copy(src, dst, self.tail_len);
2478 source_vec.set_len(start + self.tail_len);
2485 #[stable(feature = "drain", since = "1.6.0")]
2486 impl<'a, T> ExactSizeIterator for Drain<'a, T> {
2487 fn is_empty(&self) -> bool {
2488 self.iter.is_empty()
2492 #[unstable(feature = "fused", issue = "35602")]
2493 impl<'a, T> FusedIterator for Drain<'a, T> {}
2495 /// A place for insertion at the back of a `Vec`.
2497 /// See [`Vec::place_back`](struct.Vec.html#method.place_back) for details.
2498 #[must_use = "places do nothing unless written to with `<-` syntax"]
2499 #[unstable(feature = "collection_placement",
2500 reason = "struct name and placement protocol are subject to change",
2503 pub struct PlaceBack<'a, T: 'a> {
2504 vec: &'a mut Vec<T>,
2507 #[unstable(feature = "collection_placement",
2508 reason = "placement protocol is subject to change",
2510 impl<'a, T> Placer<T> for PlaceBack<'a, T> {
2511 type Place = PlaceBack<'a, T>;
2513 fn make_place(self) -> Self {
2514 // This will panic or abort if we would allocate > isize::MAX bytes
2515 // or if the length increment would overflow for zero-sized types.
2516 if self.vec.len == self.vec.buf.cap() {
2517 self.vec.buf.double();
2523 #[unstable(feature = "collection_placement",
2524 reason = "placement protocol is subject to change",
2526 impl<'a, T> Place<T> for PlaceBack<'a, T> {
2527 fn pointer(&mut self) -> *mut T {
2528 unsafe { self.vec.as_mut_ptr().offset(self.vec.len as isize) }
2532 #[unstable(feature = "collection_placement",
2533 reason = "placement protocol is subject to change",
2535 impl<'a, T> InPlace<T> for PlaceBack<'a, T> {
2536 type Owner = &'a mut T;
2538 unsafe fn finalize(mut self) -> &'a mut T {
2539 let ptr = self.pointer();
2546 /// A splicing iterator for `Vec`.
2548 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2549 /// documentation for more.
2551 /// [`splice()`]: struct.Vec.html#method.splice
2552 /// [`Vec`]: struct.Vec.html
2554 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2555 pub struct Splice<'a, I: Iterator + 'a> {
2556 drain: Drain<'a, I::Item>,
2560 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2561 impl<'a, I: Iterator> Iterator for Splice<'a, I> {
2562 type Item = I::Item;
2564 fn next(&mut self) -> Option<Self::Item> {
2568 fn size_hint(&self) -> (usize, Option<usize>) {
2569 self.drain.size_hint()
2573 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2574 impl<'a, I: Iterator> DoubleEndedIterator for Splice<'a, I> {
2575 fn next_back(&mut self) -> Option<Self::Item> {
2576 self.drain.next_back()
2580 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2581 impl<'a, I: Iterator> ExactSizeIterator for Splice<'a, I> {}
2584 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2585 impl<'a, I: Iterator> Drop for Splice<'a, I> {
2586 fn drop(&mut self) {
2587 // exhaust drain first
2588 while let Some(_) = self.drain.next() {}
2592 if self.drain.tail_len == 0 {
2593 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2597 // First fill the range left by drain().
2598 if !self.drain.fill(&mut self.replace_with) {
2602 // There may be more elements. Use the lower bound as an estimate.
2603 // FIXME: Is the upper bound a better guess? Or something else?
2604 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2605 if lower_bound > 0 {
2606 self.drain.move_tail(lower_bound);
2607 if !self.drain.fill(&mut self.replace_with) {
2612 // Collect any remaining elements.
2613 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2614 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2615 // Now we have an exact count.
2616 if collected.len() > 0 {
2617 self.drain.move_tail(collected.len());
2618 let filled = self.drain.fill(&mut collected);
2619 debug_assert!(filled);
2620 debug_assert_eq!(collected.len(), 0);
2623 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2627 /// Private helper methods for `Splice::drop`
2628 impl<'a, T> Drain<'a, T> {
2629 /// The range from `self.vec.len` to `self.tail_start` contains elements
2630 /// that have been moved out.
2631 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2632 /// Return whether we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2633 unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
2634 let vec = self.vec.as_mut();
2635 let range_start = vec.len;
2636 let range_end = self.tail_start;
2637 let range_slice = slice::from_raw_parts_mut(
2638 vec.as_mut_ptr().offset(range_start as isize),
2639 range_end - range_start);
2641 for place in range_slice {
2642 if let Some(new_item) = replace_with.next() {
2643 ptr::write(place, new_item);
2652 /// Make room for inserting more elements before the tail.
2653 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2654 let vec = self.vec.as_mut();
2655 let used_capacity = self.tail_start + self.tail_len;
2656 vec.buf.reserve(used_capacity, extra_capacity);
2658 let new_tail_start = self.tail_start + extra_capacity;
2659 let src = vec.as_ptr().offset(self.tail_start as isize);
2660 let dst = vec.as_mut_ptr().offset(new_tail_start as isize);
2661 ptr::copy(src, dst, self.tail_len);
2662 self.tail_start = new_tail_start;
2666 /// An iterator produced by calling `drain_filter` on Vec.
2667 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2669 pub struct DrainFilter<'a, T: 'a, F>
2670 where F: FnMut(&mut T) -> bool,
2672 vec: &'a mut Vec<T>,
2679 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2680 impl<'a, T, F> Iterator for DrainFilter<'a, T, F>
2681 where F: FnMut(&mut T) -> bool,
2685 fn next(&mut self) -> Option<T> {
2687 while self.idx != self.old_len {
2690 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
2691 if (self.pred)(&mut v[i]) {
2693 return Some(ptr::read(&v[i]));
2694 } else if self.del > 0 {
2695 v.swap(i - self.del, i);
2702 fn size_hint(&self) -> (usize, Option<usize>) {
2703 (0, Some(self.old_len - self.idx))
2707 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2708 impl<'a, T, F> Drop for DrainFilter<'a, T, F>
2709 where F: FnMut(&mut T) -> bool,
2711 fn drop(&mut self) {
2712 for _ in self.by_ref() { }
2715 self.vec.set_len(self.old_len - self.del);