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::{self, Ordering};
71 use core::hash::{self, Hash};
72 use core::intrinsics::{arith_offset, assume};
73 use core::iter::{FromIterator, FusedIterator, TrustedLen};
74 use core::marker::PhantomData;
76 use core::ops::Bound::{Excluded, Included, Unbounded};
77 use core::ops::{Index, IndexMut, RangeBounds};
80 use core::ptr::NonNull;
83 use alloc::CollectionAllocErr;
89 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
94 /// let mut vec = Vec::new();
98 /// assert_eq!(vec.len(), 2);
99 /// assert_eq!(vec[0], 1);
101 /// assert_eq!(vec.pop(), Some(2));
102 /// assert_eq!(vec.len(), 1);
105 /// assert_eq!(vec[0], 7);
107 /// vec.extend([1, 2, 3].iter().cloned());
110 /// println!("{}", x);
112 /// assert_eq!(vec, [7, 1, 2, 3]);
115 /// The [`vec!`] macro is provided to make initialization more convenient:
118 /// let mut vec = vec![1, 2, 3];
120 /// assert_eq!(vec, [1, 2, 3, 4]);
123 /// It can also initialize each element of a `Vec<T>` with a given value:
126 /// let vec = vec![0; 5];
127 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
130 /// Use a `Vec<T>` as an efficient stack:
133 /// let mut stack = Vec::new();
139 /// while let Some(top) = stack.pop() {
140 /// // Prints 3, 2, 1
141 /// println!("{}", top);
147 /// The `Vec` type allows to access values by index, because it implements the
148 /// [`Index`] trait. An example will be more explicit:
151 /// let v = vec![0, 2, 4, 6];
152 /// println!("{}", v[1]); // it will display '2'
155 /// However be careful: if you try to access an index which isn't in the `Vec`,
156 /// your software will panic! You cannot do this:
159 /// let v = vec![0, 2, 4, 6];
160 /// println!("{}", v[6]); // it will panic!
163 /// In conclusion: always check if the index you want to get really exists
168 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
169 /// To get a slice, use `&`. Example:
172 /// fn read_slice(slice: &[usize]) {
176 /// let v = vec![0, 1];
179 /// // ... and that's all!
180 /// // you can also do it like this:
181 /// let x : &[usize] = &v;
184 /// In Rust, it's more common to pass slices as arguments rather than vectors
185 /// when you just want to provide a read access. The same goes for [`String`] and
188 /// # Capacity and reallocation
190 /// The capacity of a vector is the amount of space allocated for any future
191 /// elements that will be added onto the vector. This is not to be confused with
192 /// the *length* of a vector, which specifies the number of actual elements
193 /// within the vector. If a vector's length exceeds its capacity, its capacity
194 /// will automatically be increased, but its elements will have to be
197 /// For example, a vector with capacity 10 and length 0 would be an empty vector
198 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
199 /// vector will not change its capacity or cause reallocation to occur. However,
200 /// if the vector's length is increased to 11, it will have to reallocate, which
201 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
202 /// whenever possible to specify how big the vector is expected to get.
206 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
207 /// about its design. This ensures that it's as low-overhead as possible in
208 /// the general case, and can be correctly manipulated in primitive ways
209 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
210 /// If additional type parameters are added (e.g. to support custom allocators),
211 /// overriding their defaults may change the behavior.
213 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
214 /// triplet. No more, no less. The order of these fields is completely
215 /// unspecified, and you should use the appropriate methods to modify these.
216 /// The pointer will never be null, so this type is null-pointer-optimized.
218 /// However, the pointer may not actually point to allocated memory. In particular,
219 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
220 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
221 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
222 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
223 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
224 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
225 /// details are very subtle — if you intend to allocate memory using a `Vec`
226 /// and use it for something else (either to pass to unsafe code, or to build your
227 /// own memory-backed collection), be sure to deallocate this memory by using
228 /// `from_raw_parts` to recover the `Vec` and then dropping it.
230 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
231 /// (as defined by the allocator Rust is configured to use by default), and its
232 /// pointer points to [`len`] initialized, contiguous elements in order (what
233 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
234 /// `[`len`] logically uninitialized, contiguous elements.
236 /// `Vec` will never perform a "small optimization" where elements are actually
237 /// stored on the stack for two reasons:
239 /// * It would make it more difficult for unsafe code to correctly manipulate
240 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
241 /// only moved, and it would be more difficult to determine if a `Vec` had
242 /// actually allocated memory.
244 /// * It would penalize the general case, incurring an additional branch
247 /// `Vec` will never automatically shrink itself, even if completely empty. This
248 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
249 /// and then filling it back up to the same [`len`] should incur no calls to
250 /// the allocator. If you wish to free up unused memory, use
251 /// [`shrink_to_fit`][`shrink_to_fit`].
253 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
254 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
255 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
256 /// accurate, and can be relied on. It can even be used to manually free the memory
257 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
258 /// when not necessary.
260 /// `Vec` does not guarantee any particular growth strategy when reallocating
261 /// when full, nor when [`reserve`] is called. The current strategy is basic
262 /// and it may prove desirable to use a non-constant growth factor. Whatever
263 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
265 /// `vec![x; n]`, `vec![a, b, c, d]`, and
266 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
267 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
268 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
269 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
271 /// `Vec` will not specifically overwrite any data that is removed from it,
272 /// but also won't specifically preserve it. Its uninitialized memory is
273 /// scratch space that it may use however it wants. It will generally just do
274 /// whatever is most efficient or otherwise easy to implement. Do not rely on
275 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
276 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
277 /// first, that may not actually happen because the optimizer does not consider
278 /// this a side-effect that must be preserved. There is one case which we will
279 /// not break, however: using `unsafe` code to write to the excess capacity,
280 /// and then increasing the length to match, is always valid.
282 /// `Vec` does not currently guarantee the order in which elements are dropped.
283 /// The order has changed in the past and may change again.
285 /// [`vec!`]: ../../std/macro.vec.html
286 /// [`Index`]: ../../std/ops/trait.Index.html
287 /// [`String`]: ../../std/string/struct.String.html
288 /// [`&str`]: ../../std/primitive.str.html
289 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
290 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
291 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
292 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
293 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
294 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
295 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
296 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
297 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
298 /// [owned slice]: ../../std/boxed/struct.Box.html
299 #[stable(feature = "rust1", since = "1.0.0")]
305 ////////////////////////////////////////////////////////////////////////////////
307 ////////////////////////////////////////////////////////////////////////////////
310 /// Constructs a new, empty `Vec<T>`.
312 /// The vector will not allocate until elements are pushed onto it.
317 /// # #![allow(unused_mut)]
318 /// let mut vec: Vec<i32> = Vec::new();
321 #[stable(feature = "rust1", since = "1.0.0")]
322 #[rustc_const_unstable(feature = "const_vec_new")]
323 pub const fn new() -> Vec<T> {
330 /// Constructs a new, empty `Vec<T>` with the specified capacity.
332 /// The vector will be able to hold exactly `capacity` elements without
333 /// reallocating. If `capacity` is 0, the vector will not allocate.
335 /// It is important to note that although the returned vector has the
336 /// *capacity* specified, the vector will have a zero *length*. For an
337 /// explanation of the difference between length and capacity, see
338 /// *[Capacity and reallocation]*.
340 /// [Capacity and reallocation]: #capacity-and-reallocation
345 /// let mut vec = Vec::with_capacity(10);
347 /// // The vector contains no items, even though it has capacity for more
348 /// assert_eq!(vec.len(), 0);
350 /// // These are all done without reallocating...
355 /// // ...but this may make the vector reallocate
359 #[stable(feature = "rust1", since = "1.0.0")]
360 pub fn with_capacity(capacity: usize) -> Vec<T> {
362 buf: RawVec::with_capacity(capacity),
367 /// Creates a `Vec<T>` directly from the raw components of another vector.
371 /// This is highly unsafe, due to the number of invariants that aren't
374 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
375 /// (at least, it's highly likely to be incorrect if it wasn't).
376 /// * `ptr`'s `T` needs to have the same size and alignment as it was allocated with.
377 /// * `length` needs to be less than or equal to `capacity`.
378 /// * `capacity` needs to be the capacity that the pointer was allocated with.
380 /// Violating these may cause problems like corrupting the allocator's
381 /// internal data structures. For example it is **not** safe
382 /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`.
384 /// The ownership of `ptr` is effectively transferred to the
385 /// `Vec<T>` which may then deallocate, reallocate or change the
386 /// contents of memory pointed to by the pointer at will. Ensure
387 /// that nothing else uses the pointer after calling this
390 /// [`String`]: ../../std/string/struct.String.html
399 /// let mut v = vec![1, 2, 3];
401 /// // Pull out the various important pieces of information about `v`
402 /// let p = v.as_mut_ptr();
403 /// let len = v.len();
404 /// let cap = v.capacity();
407 /// // Cast `v` into the void: no destructor run, so we are in
408 /// // complete control of the allocation to which `p` points.
411 /// // Overwrite memory with 4, 5, 6
412 /// for i in 0..len as isize {
413 /// ptr::write(p.offset(i), 4 + i);
416 /// // Put everything back together into a Vec
417 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
418 /// assert_eq!(rebuilt, [4, 5, 6]);
422 #[stable(feature = "rust1", since = "1.0.0")]
423 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
425 buf: RawVec::from_raw_parts(ptr, capacity),
430 /// Returns the number of elements the vector can hold without
436 /// let vec: Vec<i32> = Vec::with_capacity(10);
437 /// assert_eq!(vec.capacity(), 10);
440 #[stable(feature = "rust1", since = "1.0.0")]
441 pub fn capacity(&self) -> usize {
445 /// Reserves capacity for at least `additional` more elements to be inserted
446 /// in the given `Vec<T>`. The collection may reserve more space to avoid
447 /// frequent reallocations. After calling `reserve`, capacity will be
448 /// greater than or equal to `self.len() + additional`. Does nothing if
449 /// capacity is already sufficient.
453 /// Panics if the new capacity overflows `usize`.
458 /// let mut vec = vec![1];
460 /// assert!(vec.capacity() >= 11);
462 #[stable(feature = "rust1", since = "1.0.0")]
463 pub fn reserve(&mut self, additional: usize) {
464 self.buf.reserve(self.len, additional);
467 /// Reserves the minimum capacity for exactly `additional` more elements to
468 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
469 /// capacity will be greater than or equal to `self.len() + additional`.
470 /// Does nothing if the capacity is already sufficient.
472 /// Note that the allocator may give the collection more space than it
473 /// requests. Therefore capacity can not be relied upon to be precisely
474 /// minimal. Prefer `reserve` if future insertions are expected.
478 /// Panics if the new capacity overflows `usize`.
483 /// let mut vec = vec![1];
484 /// vec.reserve_exact(10);
485 /// assert!(vec.capacity() >= 11);
487 #[stable(feature = "rust1", since = "1.0.0")]
488 pub fn reserve_exact(&mut self, additional: usize) {
489 self.buf.reserve_exact(self.len, additional);
492 /// Tries to reserve capacity for at least `additional` more elements to be inserted
493 /// in the given `Vec<T>`. The collection may reserve more space to avoid
494 /// frequent reallocations. After calling `reserve`, capacity will be
495 /// greater than or equal to `self.len() + additional`. Does nothing if
496 /// capacity is already sufficient.
500 /// If the capacity overflows, or the allocator reports a failure, then an error
506 /// #![feature(try_reserve)]
507 /// use std::collections::CollectionAllocErr;
509 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> {
510 /// let mut output = Vec::new();
512 /// // Pre-reserve the memory, exiting if we can't
513 /// output.try_reserve(data.len())?;
515 /// // Now we know this can't OOM in the middle of our complex work
516 /// output.extend(data.iter().map(|&val| {
517 /// val * 2 + 5 // very complicated
522 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
524 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
525 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
526 self.buf.try_reserve(self.len, additional)
529 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
530 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
531 /// capacity will be greater than or equal to `self.len() + additional`.
532 /// Does nothing if the capacity is already sufficient.
534 /// Note that the allocator may give the collection more space than it
535 /// requests. Therefore capacity can not be relied upon to be precisely
536 /// minimal. Prefer `reserve` if future insertions are expected.
540 /// If the capacity overflows, or the allocator reports a failure, then an error
546 /// #![feature(try_reserve)]
547 /// use std::collections::CollectionAllocErr;
549 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> {
550 /// let mut output = Vec::new();
552 /// // Pre-reserve the memory, exiting if we can't
553 /// output.try_reserve(data.len())?;
555 /// // Now we know this can't OOM in the middle of our complex work
556 /// output.extend(data.iter().map(|&val| {
557 /// val * 2 + 5 // very complicated
562 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
564 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
565 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
566 self.buf.try_reserve_exact(self.len, additional)
569 /// Shrinks the capacity of the vector as much as possible.
571 /// It will drop down as close as possible to the length but the allocator
572 /// may still inform the vector that there is space for a few more elements.
577 /// let mut vec = Vec::with_capacity(10);
578 /// vec.extend([1, 2, 3].iter().cloned());
579 /// assert_eq!(vec.capacity(), 10);
580 /// vec.shrink_to_fit();
581 /// assert!(vec.capacity() >= 3);
583 #[stable(feature = "rust1", since = "1.0.0")]
584 pub fn shrink_to_fit(&mut self) {
585 if self.capacity() != self.len {
586 self.buf.shrink_to_fit(self.len);
590 /// Shrinks the capacity of the vector with a lower bound.
592 /// The capacity will remain at least as large as both the length
593 /// and the supplied value.
595 /// Panics if the current capacity is smaller than the supplied
596 /// minimum capacity.
601 /// #![feature(shrink_to)]
602 /// let mut vec = Vec::with_capacity(10);
603 /// vec.extend([1, 2, 3].iter().cloned());
604 /// assert_eq!(vec.capacity(), 10);
605 /// vec.shrink_to(4);
606 /// assert!(vec.capacity() >= 4);
607 /// vec.shrink_to(0);
608 /// assert!(vec.capacity() >= 3);
610 #[unstable(feature = "shrink_to", reason = "new API", issue="0")]
611 pub fn shrink_to(&mut self, min_capacity: usize) {
612 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
615 /// Converts the vector into [`Box<[T]>`][owned slice].
617 /// Note that this will drop any excess capacity.
619 /// [owned slice]: ../../std/boxed/struct.Box.html
624 /// let v = vec![1, 2, 3];
626 /// let slice = v.into_boxed_slice();
629 /// Any excess capacity is removed:
632 /// let mut vec = Vec::with_capacity(10);
633 /// vec.extend([1, 2, 3].iter().cloned());
635 /// assert_eq!(vec.capacity(), 10);
636 /// let slice = vec.into_boxed_slice();
637 /// assert_eq!(slice.into_vec().capacity(), 3);
639 #[stable(feature = "rust1", since = "1.0.0")]
640 pub fn into_boxed_slice(mut self) -> Box<[T]> {
642 self.shrink_to_fit();
643 let buf = ptr::read(&self.buf);
649 /// Shortens the vector, keeping the first `len` elements and dropping
652 /// If `len` is greater than the vector's current length, this has no
655 /// The [`drain`] method can emulate `truncate`, but causes the excess
656 /// elements to be returned instead of dropped.
658 /// Note that this method has no effect on the allocated capacity
663 /// Truncating a five element vector to two elements:
666 /// let mut vec = vec![1, 2, 3, 4, 5];
668 /// assert_eq!(vec, [1, 2]);
671 /// No truncation occurs when `len` is greater than the vector's current
675 /// let mut vec = vec![1, 2, 3];
677 /// assert_eq!(vec, [1, 2, 3]);
680 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
684 /// let mut vec = vec![1, 2, 3];
686 /// assert_eq!(vec, []);
689 /// [`clear`]: #method.clear
690 /// [`drain`]: #method.drain
691 #[stable(feature = "rust1", since = "1.0.0")]
692 pub fn truncate(&mut self, len: usize) {
694 // drop any extra elements
695 while len < self.len {
696 // decrement len before the drop_in_place(), so a panic on Drop
697 // doesn't re-drop the just-failed value.
700 ptr::drop_in_place(self.get_unchecked_mut(len));
705 /// Extracts a slice containing the entire vector.
707 /// Equivalent to `&s[..]`.
712 /// use std::io::{self, Write};
713 /// let buffer = vec![1, 2, 3, 5, 8];
714 /// io::sink().write(buffer.as_slice()).unwrap();
717 #[stable(feature = "vec_as_slice", since = "1.7.0")]
718 pub fn as_slice(&self) -> &[T] {
722 /// Extracts a mutable slice of the entire vector.
724 /// Equivalent to `&mut s[..]`.
729 /// use std::io::{self, Read};
730 /// let mut buffer = vec![0; 3];
731 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
734 #[stable(feature = "vec_as_slice", since = "1.7.0")]
735 pub fn as_mut_slice(&mut self) -> &mut [T] {
739 /// Sets the length of a vector.
741 /// This will explicitly set the size of the vector, without actually
742 /// modifying its buffers, so it is up to the caller to ensure that the
743 /// vector is actually the specified size.
750 /// let mut vec = vec!['r', 'u', 's', 't'];
753 /// ptr::drop_in_place(&mut vec[3]);
756 /// assert_eq!(vec, ['r', 'u', 's']);
759 /// In this example, there is a memory leak since the memory locations
760 /// owned by the inner vectors were not freed prior to the `set_len` call:
763 /// let mut vec = vec![vec![1, 0, 0],
771 /// In this example, the vector gets expanded from zero to four items
772 /// without any memory allocations occurring, resulting in vector
773 /// values of unallocated memory:
776 /// let mut vec: Vec<char> = Vec::new();
783 #[stable(feature = "rust1", since = "1.0.0")]
784 pub unsafe fn set_len(&mut self, len: usize) {
788 /// Removes an element from the vector and returns it.
790 /// The removed element is replaced by the last element of the vector.
792 /// This does not preserve ordering, but is O(1).
796 /// Panics if `index` is out of bounds.
801 /// let mut v = vec!["foo", "bar", "baz", "qux"];
803 /// assert_eq!(v.swap_remove(1), "bar");
804 /// assert_eq!(v, ["foo", "qux", "baz"]);
806 /// assert_eq!(v.swap_remove(0), "foo");
807 /// assert_eq!(v, ["baz", "qux"]);
810 #[stable(feature = "rust1", since = "1.0.0")]
811 pub fn swap_remove(&mut self, index: usize) -> T {
812 let length = self.len();
813 self.swap(index, length - 1);
817 /// Inserts an element at position `index` within the vector, shifting all
818 /// elements after it to the right.
822 /// Panics if `index > len`.
827 /// let mut vec = vec![1, 2, 3];
828 /// vec.insert(1, 4);
829 /// assert_eq!(vec, [1, 4, 2, 3]);
830 /// vec.insert(4, 5);
831 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub fn insert(&mut self, index: usize, element: T) {
835 let len = self.len();
836 assert!(index <= len);
838 // space for the new element
839 if len == self.buf.cap() {
845 // The spot to put the new value
847 let p = self.as_mut_ptr().offset(index as isize);
848 // Shift everything over to make space. (Duplicating the
849 // `index`th element into two consecutive places.)
850 ptr::copy(p, p.offset(1), len - index);
851 // Write it in, overwriting the first copy of the `index`th
853 ptr::write(p, element);
855 self.set_len(len + 1);
859 /// Removes and returns the element at position `index` within the vector,
860 /// shifting all elements after it to the left.
864 /// Panics if `index` is out of bounds.
869 /// let mut v = vec![1, 2, 3];
870 /// assert_eq!(v.remove(1), 2);
871 /// assert_eq!(v, [1, 3]);
873 #[stable(feature = "rust1", since = "1.0.0")]
874 pub fn remove(&mut self, index: usize) -> T {
875 let len = self.len();
876 assert!(index < len);
881 // the place we are taking from.
882 let ptr = self.as_mut_ptr().offset(index as isize);
883 // copy it out, unsafely having a copy of the value on
884 // the stack and in the vector at the same time.
885 ret = ptr::read(ptr);
887 // Shift everything down to fill in that spot.
888 ptr::copy(ptr.offset(1), ptr, len - index - 1);
890 self.set_len(len - 1);
895 /// Retains only the elements specified by the predicate.
897 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
898 /// This method operates in place and preserves the order of the retained
904 /// let mut vec = vec![1, 2, 3, 4];
905 /// vec.retain(|&x| x%2 == 0);
906 /// assert_eq!(vec, [2, 4]);
908 #[stable(feature = "rust1", since = "1.0.0")]
909 pub fn retain<F>(&mut self, mut f: F)
910 where F: FnMut(&T) -> bool
912 self.drain_filter(|x| !f(x));
915 /// Removes all but the first of consecutive elements in the vector that resolve to the same
918 /// If the vector is sorted, this removes all duplicates.
923 /// let mut vec = vec![10, 20, 21, 30, 20];
925 /// vec.dedup_by_key(|i| *i / 10);
927 /// assert_eq!(vec, [10, 20, 30, 20]);
929 #[stable(feature = "dedup_by", since = "1.16.0")]
931 pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
932 self.dedup_by(|a, b| key(a) == key(b))
935 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
938 /// The `same_bucket` function is passed references to two elements from the vector, and
939 /// returns `true` if the elements compare equal, or `false` if they do not. The elements are
940 /// passed in opposite order from their order in the vector, so if `same_bucket(a, b)` returns
941 /// `true`, `a` is removed.
943 /// If the vector is sorted, this removes all duplicates.
948 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
950 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
952 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
954 #[stable(feature = "dedup_by", since = "1.16.0")]
955 pub fn dedup_by<F>(&mut self, mut same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
957 // Although we have a mutable reference to `self`, we cannot make
958 // *arbitrary* changes. The `same_bucket` calls could panic, so we
959 // must ensure that the vector is in a valid state at all time.
961 // The way that we handle this is by using swaps; we iterate
962 // over all the elements, swapping as we go so that at the end
963 // the elements we wish to keep are in the front, and those we
964 // wish to reject are at the back. We can then truncate the
965 // vector. This operation is still O(n).
967 // Example: We start in this state, where `r` represents "next
968 // read" and `w` represents "next_write`.
971 // +---+---+---+---+---+---+
972 // | 0 | 1 | 1 | 2 | 3 | 3 |
973 // +---+---+---+---+---+---+
976 // Comparing self[r] against self[w-1], this is not a duplicate, so
977 // we swap self[r] and self[w] (no effect as r==w) and then increment both
978 // r and w, leaving us with:
981 // +---+---+---+---+---+---+
982 // | 0 | 1 | 1 | 2 | 3 | 3 |
983 // +---+---+---+---+---+---+
986 // Comparing self[r] against self[w-1], this value is a duplicate,
987 // so we increment `r` but leave everything else unchanged:
990 // +---+---+---+---+---+---+
991 // | 0 | 1 | 1 | 2 | 3 | 3 |
992 // +---+---+---+---+---+---+
995 // Comparing self[r] against self[w-1], this is not a duplicate,
996 // so swap self[r] and self[w] and advance r and w:
999 // +---+---+---+---+---+---+
1000 // | 0 | 1 | 2 | 1 | 3 | 3 |
1001 // +---+---+---+---+---+---+
1004 // Not a duplicate, repeat:
1007 // +---+---+---+---+---+---+
1008 // | 0 | 1 | 2 | 3 | 1 | 3 |
1009 // +---+---+---+---+---+---+
1012 // Duplicate, advance r. End of vec. Truncate to w.
1014 let ln = self.len();
1019 // Avoid bounds checks by using raw pointers.
1020 let p = self.as_mut_ptr();
1021 let mut r: usize = 1;
1022 let mut w: usize = 1;
1025 let p_r = p.offset(r as isize);
1026 let p_wm1 = p.offset((w - 1) as isize);
1027 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1029 let p_w = p_wm1.offset(1);
1030 mem::swap(&mut *p_r, &mut *p_w);
1041 /// Appends an element to the back of a collection.
1045 /// Panics if the number of elements in the vector overflows a `usize`.
1050 /// let mut vec = vec![1, 2];
1052 /// assert_eq!(vec, [1, 2, 3]);
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn push(&mut self, value: T) {
1057 // This will panic or abort if we would allocate > isize::MAX bytes
1058 // or if the length increment would overflow for zero-sized types.
1059 if self.len == self.buf.cap() {
1063 let end = self.as_mut_ptr().offset(self.len as isize);
1064 ptr::write(end, value);
1069 /// Removes the last element from a vector and returns it, or [`None`] if it
1072 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1077 /// let mut vec = vec![1, 2, 3];
1078 /// assert_eq!(vec.pop(), Some(3));
1079 /// assert_eq!(vec, [1, 2]);
1082 #[stable(feature = "rust1", since = "1.0.0")]
1083 pub fn pop(&mut self) -> Option<T> {
1089 Some(ptr::read(self.get_unchecked(self.len())))
1094 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1098 /// Panics if the number of elements in the vector overflows a `usize`.
1103 /// let mut vec = vec![1, 2, 3];
1104 /// let mut vec2 = vec![4, 5, 6];
1105 /// vec.append(&mut vec2);
1106 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1107 /// assert_eq!(vec2, []);
1110 #[stable(feature = "append", since = "1.4.0")]
1111 pub fn append(&mut self, other: &mut Self) {
1113 self.append_elements(other.as_slice() as _);
1118 /// Appends elements to `Self` from other buffer.
1120 unsafe fn append_elements(&mut self, other: *const [T]) {
1121 let count = (*other).len();
1122 self.reserve(count);
1123 let len = self.len();
1124 ptr::copy_nonoverlapping(other as *const T, self.get_unchecked_mut(len), count);
1128 /// Creates a draining iterator that removes the specified range in the vector
1129 /// and yields the removed items.
1131 /// Note 1: The element range is removed even if the iterator is only
1132 /// partially consumed or not consumed at all.
1134 /// Note 2: It is unspecified how many elements are removed from the vector
1135 /// if the `Drain` value is leaked.
1139 /// Panics if the starting point is greater than the end point or if
1140 /// the end point is greater than the length of the vector.
1145 /// let mut v = vec![1, 2, 3];
1146 /// let u: Vec<_> = v.drain(1..).collect();
1147 /// assert_eq!(v, &[1]);
1148 /// assert_eq!(u, &[2, 3]);
1150 /// // A full range clears the vector
1152 /// assert_eq!(v, &[]);
1154 #[stable(feature = "drain", since = "1.6.0")]
1155 pub fn drain<R>(&mut self, range: R) -> Drain<T>
1156 where R: RangeBounds<usize>
1160 // When the Drain is first created, it shortens the length of
1161 // the source vector to make sure no uninitialized or moved-from elements
1162 // are accessible at all if the Drain's destructor never gets to run.
1164 // Drain will ptr::read out the values to remove.
1165 // When finished, remaining tail of the vec is copied back to cover
1166 // the hole, and the vector length is restored to the new length.
1168 let len = self.len();
1169 let start = match range.start_bound() {
1171 Excluded(&n) => n + 1,
1174 let end = match range.end_bound() {
1175 Included(&n) => n + 1,
1179 assert!(start <= end);
1180 assert!(end <= len);
1183 // set self.vec length's to start, to be safe in case Drain is leaked
1184 self.set_len(start);
1185 // Use the borrow in the IterMut to indicate borrowing behavior of the
1186 // whole Drain iterator (like &mut T).
1187 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
1191 tail_len: len - end,
1192 iter: range_slice.iter(),
1193 vec: NonNull::from(self),
1198 /// Clears the vector, removing all values.
1200 /// Note that this method has no effect on the allocated capacity
1206 /// let mut v = vec![1, 2, 3];
1210 /// assert!(v.is_empty());
1213 #[stable(feature = "rust1", since = "1.0.0")]
1214 pub fn clear(&mut self) {
1218 /// Returns the number of elements in the vector, also referred to
1219 /// as its 'length'.
1224 /// let a = vec![1, 2, 3];
1225 /// assert_eq!(a.len(), 3);
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 pub fn len(&self) -> usize {
1233 /// Returns `true` if the vector contains no elements.
1238 /// let mut v = Vec::new();
1239 /// assert!(v.is_empty());
1242 /// assert!(!v.is_empty());
1244 #[stable(feature = "rust1", since = "1.0.0")]
1245 pub fn is_empty(&self) -> bool {
1249 /// Splits the collection into two at the given index.
1251 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1252 /// and the returned `Self` contains elements `[at, len)`.
1254 /// Note that the capacity of `self` does not change.
1258 /// Panics if `at > len`.
1263 /// let mut vec = vec![1,2,3];
1264 /// let vec2 = vec.split_off(1);
1265 /// assert_eq!(vec, [1]);
1266 /// assert_eq!(vec2, [2, 3]);
1269 #[stable(feature = "split_off", since = "1.4.0")]
1270 pub fn split_off(&mut self, at: usize) -> Self {
1271 assert!(at <= self.len(), "`at` out of bounds");
1273 let other_len = self.len - at;
1274 let mut other = Vec::with_capacity(other_len);
1276 // Unsafely `set_len` and copy items to `other`.
1279 other.set_len(other_len);
1281 ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
1288 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1290 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1291 /// difference, with each additional slot filled with the result of
1292 /// calling the closure `f`. The return values from `f` will end up
1293 /// in the `Vec` in the order they have been generated.
1295 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1297 /// This method uses a closure to create new values on every push. If
1298 /// you'd rather [`Clone`] a given value, use [`resize`]. If you want
1299 /// to use the [`Default`] trait to generate values, you can pass
1300 /// [`Default::default()`] as the second argument..
1305 /// #![feature(vec_resize_with)]
1307 /// let mut vec = vec![1, 2, 3];
1308 /// vec.resize_with(5, Default::default);
1309 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1311 /// let mut vec = vec![];
1313 /// vec.resize_with(4, || { p *= 2; p });
1314 /// assert_eq!(vec, [2, 4, 8, 16]);
1317 /// [`resize`]: #method.resize
1318 /// [`Clone`]: ../../std/clone/trait.Clone.html
1319 #[unstable(feature = "vec_resize_with", issue = "41758")]
1320 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1321 where F: FnMut() -> T
1323 let len = self.len();
1325 self.extend_with(new_len - len, ExtendFunc(f));
1327 self.truncate(new_len);
1332 impl<T: Clone> Vec<T> {
1333 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1335 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1336 /// difference, with each additional slot filled with `value`.
1337 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1339 /// This method requires [`Clone`] to be able clone the passed value. If
1340 /// you need more flexibility (or want to rely on [`Default`] instead of
1341 /// [`Clone`]), use [`resize_with`].
1346 /// let mut vec = vec!["hello"];
1347 /// vec.resize(3, "world");
1348 /// assert_eq!(vec, ["hello", "world", "world"]);
1350 /// let mut vec = vec![1, 2, 3, 4];
1351 /// vec.resize(2, 0);
1352 /// assert_eq!(vec, [1, 2]);
1355 /// [`Clone`]: ../../std/clone/trait.Clone.html
1356 /// [`Default`]: ../../std/default/trait.Default.html
1357 /// [`resize_with`]: #method.resize_with
1358 #[stable(feature = "vec_resize", since = "1.5.0")]
1359 pub fn resize(&mut self, new_len: usize, value: T) {
1360 let len = self.len();
1363 self.extend_with(new_len - len, ExtendElement(value))
1365 self.truncate(new_len);
1369 /// Clones and appends all elements in a slice to the `Vec`.
1371 /// Iterates over the slice `other`, clones each element, and then appends
1372 /// it to this `Vec`. The `other` vector is traversed in-order.
1374 /// Note that this function is same as [`extend`] except that it is
1375 /// specialized to work with slices instead. If and when Rust gets
1376 /// specialization this function will likely be deprecated (but still
1382 /// let mut vec = vec![1];
1383 /// vec.extend_from_slice(&[2, 3, 4]);
1384 /// assert_eq!(vec, [1, 2, 3, 4]);
1387 /// [`extend`]: #method.extend
1388 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1389 pub fn extend_from_slice(&mut self, other: &[T]) {
1390 self.spec_extend(other.iter())
1394 impl<T: Default> Vec<T> {
1395 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1397 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1398 /// difference, with each additional slot filled with [`Default::default()`].
1399 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1401 /// This method uses [`Default`] to create new values on every push. If
1402 /// you'd rather [`Clone`] a given value, use [`resize`].
1407 /// #![feature(vec_resize_default)]
1409 /// let mut vec = vec![1, 2, 3];
1410 /// vec.resize_default(5);
1411 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1413 /// let mut vec = vec![1, 2, 3, 4];
1414 /// vec.resize_default(2);
1415 /// assert_eq!(vec, [1, 2]);
1418 /// [`resize`]: #method.resize
1419 /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default
1420 /// [`Default`]: ../../std/default/trait.Default.html
1421 /// [`Clone`]: ../../std/clone/trait.Clone.html
1422 #[unstable(feature = "vec_resize_default", issue = "41758")]
1423 pub fn resize_default(&mut self, new_len: usize) {
1424 let len = self.len();
1427 self.extend_with(new_len - len, ExtendDefault);
1429 self.truncate(new_len);
1434 // This code generalises `extend_with_{element,default}`.
1435 trait ExtendWith<T> {
1436 fn next(&mut self) -> T;
1440 struct ExtendElement<T>(T);
1441 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1442 fn next(&mut self) -> T { self.0.clone() }
1443 fn last(self) -> T { self.0 }
1446 struct ExtendDefault;
1447 impl<T: Default> ExtendWith<T> for ExtendDefault {
1448 fn next(&mut self) -> T { Default::default() }
1449 fn last(self) -> T { Default::default() }
1452 struct ExtendFunc<F>(F);
1453 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1454 fn next(&mut self) -> T { (self.0)() }
1455 fn last(mut self) -> T { (self.0)() }
1459 /// Extend the vector by `n` values, using the given generator.
1460 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1464 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1465 // Use SetLenOnDrop to work around bug where compiler
1466 // may not realize the store through `ptr` through self.set_len()
1468 let mut local_len = SetLenOnDrop::new(&mut self.len);
1470 // Write all elements except the last one
1472 ptr::write(ptr, value.next());
1473 ptr = ptr.offset(1);
1474 // Increment the length in every step in case next() panics
1475 local_len.increment_len(1);
1479 // We can write the last element directly without cloning needlessly
1480 ptr::write(ptr, value.last());
1481 local_len.increment_len(1);
1484 // len set by scope guard
1489 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1491 // The idea is: The length field in SetLenOnDrop is a local variable
1492 // that the optimizer will see does not alias with any stores through the Vec's data
1493 // pointer. This is a workaround for alias analysis issue #32155
1494 struct SetLenOnDrop<'a> {
1499 impl<'a> SetLenOnDrop<'a> {
1501 fn new(len: &'a mut usize) -> Self {
1502 SetLenOnDrop { local_len: *len, len: len }
1506 fn increment_len(&mut self, increment: usize) {
1507 self.local_len += increment;
1511 impl<'a> Drop for SetLenOnDrop<'a> {
1513 fn drop(&mut self) {
1514 *self.len = self.local_len;
1518 impl<T: PartialEq> Vec<T> {
1519 /// Removes consecutive repeated elements in the vector.
1521 /// If the vector is sorted, this removes all duplicates.
1526 /// let mut vec = vec![1, 2, 2, 3, 2];
1530 /// assert_eq!(vec, [1, 2, 3, 2]);
1532 #[stable(feature = "rust1", since = "1.0.0")]
1534 pub fn dedup(&mut self) {
1535 self.dedup_by(|a, b| a == b)
1538 /// Removes the first instance of `item` from the vector if the item exists.
1543 /// # #![feature(vec_remove_item)]
1544 /// let mut vec = vec![1, 2, 3, 1];
1546 /// vec.remove_item(&1);
1548 /// assert_eq!(vec, vec![2, 3, 1]);
1550 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1551 pub fn remove_item(&mut self, item: &T) -> Option<T> {
1552 let pos = self.iter().position(|x| *x == *item)?;
1553 Some(self.remove(pos))
1557 ////////////////////////////////////////////////////////////////////////////////
1558 // Internal methods and functions
1559 ////////////////////////////////////////////////////////////////////////////////
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1564 <T as SpecFromElem>::from_elem(elem, n)
1567 // Specialization trait used for Vec::from_elem
1568 trait SpecFromElem: Sized {
1569 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1572 impl<T: Clone> SpecFromElem for T {
1573 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1574 let mut v = Vec::with_capacity(n);
1575 v.extend_with(n, ExtendElement(elem));
1580 impl SpecFromElem for u8 {
1582 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1585 buf: RawVec::with_capacity_zeroed(n),
1590 let mut v = Vec::with_capacity(n);
1591 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1598 impl<T: Clone + IsZero> SpecFromElem for T {
1600 fn from_elem(elem: T, n: usize) -> Vec<T> {
1603 buf: RawVec::with_capacity_zeroed(n),
1607 let mut v = Vec::with_capacity(n);
1608 v.extend_with(n, ExtendElement(elem));
1613 unsafe trait IsZero {
1614 /// Whether this value is zero
1615 fn is_zero(&self) -> bool;
1618 macro_rules! impl_is_zero {
1619 ($t: ty, $is_zero: expr) => {
1620 unsafe impl IsZero for $t {
1622 fn is_zero(&self) -> bool {
1629 impl_is_zero!(i8, |x| x == 0);
1630 impl_is_zero!(i16, |x| x == 0);
1631 impl_is_zero!(i32, |x| x == 0);
1632 impl_is_zero!(i64, |x| x == 0);
1633 impl_is_zero!(i128, |x| x == 0);
1634 impl_is_zero!(isize, |x| x == 0);
1636 impl_is_zero!(u16, |x| x == 0);
1637 impl_is_zero!(u32, |x| x == 0);
1638 impl_is_zero!(u64, |x| x == 0);
1639 impl_is_zero!(u128, |x| x == 0);
1640 impl_is_zero!(usize, |x| x == 0);
1642 impl_is_zero!(char, |x| x == '\0');
1644 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1645 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1647 unsafe impl<T: ?Sized> IsZero for *const T {
1649 fn is_zero(&self) -> bool {
1654 unsafe impl<T: ?Sized> IsZero for *mut T {
1656 fn is_zero(&self) -> bool {
1662 ////////////////////////////////////////////////////////////////////////////////
1663 // Common trait implementations for Vec
1664 ////////////////////////////////////////////////////////////////////////////////
1666 #[stable(feature = "rust1", since = "1.0.0")]
1667 impl<T: Clone> Clone for Vec<T> {
1669 fn clone(&self) -> Vec<T> {
1670 <[T]>::to_vec(&**self)
1673 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1674 // required for this method definition, is not available. Instead use the
1675 // `slice::to_vec` function which is only available with cfg(test)
1676 // NB see the slice::hack module in slice.rs for more information
1678 fn clone(&self) -> Vec<T> {
1679 ::slice::to_vec(&**self)
1682 fn clone_from(&mut self, other: &Vec<T>) {
1683 other.as_slice().clone_into(self);
1687 #[stable(feature = "rust1", since = "1.0.0")]
1688 impl<T: Hash> Hash for Vec<T> {
1690 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1691 Hash::hash(&**self, state)
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 #[rustc_on_unimplemented(
1697 message="vector indices are of type `usize` or ranges of `usize`",
1698 label="vector indices are of type `usize` or ranges of `usize`",
1700 impl<T, I> Index<I> for Vec<T>
1702 I: ::core::slice::SliceIndex<[T]>,
1704 type Output = I::Output;
1707 fn index(&self, index: I) -> &Self::Output {
1708 Index::index(&**self, index)
1712 #[stable(feature = "rust1", since = "1.0.0")]
1713 #[rustc_on_unimplemented(
1714 message="vector indices are of type `usize` or ranges of `usize`",
1715 label="vector indices are of type `usize` or ranges of `usize`",
1717 impl<T, I> IndexMut<I> for Vec<T>
1719 I: ::core::slice::SliceIndex<[T]>,
1722 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1723 IndexMut::index_mut(&mut **self, index)
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 impl<T> ops::Deref for Vec<T> {
1731 fn deref(&self) -> &[T] {
1733 let p = self.buf.ptr();
1734 assume(!p.is_null());
1735 slice::from_raw_parts(p, self.len)
1740 #[stable(feature = "rust1", since = "1.0.0")]
1741 impl<T> ops::DerefMut for Vec<T> {
1742 fn deref_mut(&mut self) -> &mut [T] {
1744 let ptr = self.buf.ptr();
1745 assume(!ptr.is_null());
1746 slice::from_raw_parts_mut(ptr, self.len)
1751 #[stable(feature = "rust1", since = "1.0.0")]
1752 impl<T> FromIterator<T> for Vec<T> {
1754 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1755 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<T> IntoIterator for Vec<T> {
1762 type IntoIter = IntoIter<T>;
1764 /// Creates a consuming iterator, that is, one that moves each value out of
1765 /// the vector (from start to end). The vector cannot be used after calling
1771 /// let v = vec!["a".to_string(), "b".to_string()];
1772 /// for s in v.into_iter() {
1773 /// // s has type String, not &String
1774 /// println!("{}", s);
1778 fn into_iter(mut self) -> IntoIter<T> {
1780 let begin = self.as_mut_ptr();
1781 assume(!begin.is_null());
1782 let end = if mem::size_of::<T>() == 0 {
1783 arith_offset(begin as *const i8, self.len() as isize) as *const T
1785 begin.offset(self.len() as isize) as *const T
1787 let cap = self.buf.cap();
1790 buf: NonNull::new_unchecked(begin),
1791 phantom: PhantomData,
1800 #[stable(feature = "rust1", since = "1.0.0")]
1801 impl<'a, T> IntoIterator for &'a Vec<T> {
1803 type IntoIter = slice::Iter<'a, T>;
1805 fn into_iter(self) -> slice::Iter<'a, T> {
1810 #[stable(feature = "rust1", since = "1.0.0")]
1811 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1812 type Item = &'a mut T;
1813 type IntoIter = slice::IterMut<'a, T>;
1815 fn into_iter(self) -> slice::IterMut<'a, T> {
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 impl<T> Extend<T> for Vec<T> {
1823 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1824 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1828 // Specialization trait used for Vec::from_iter and Vec::extend
1829 trait SpecExtend<T, I> {
1830 fn from_iter(iter: I) -> Self;
1831 fn spec_extend(&mut self, iter: I);
1834 impl<T, I> SpecExtend<T, I> for Vec<T>
1835 where I: Iterator<Item=T>,
1837 default fn from_iter(mut iterator: I) -> Self {
1838 // Unroll the first iteration, as the vector is going to be
1839 // expanded on this iteration in every case when the iterable is not
1840 // empty, but the loop in extend_desugared() is not going to see the
1841 // vector being full in the few subsequent loop iterations.
1842 // So we get better branch prediction.
1843 let mut vector = match iterator.next() {
1844 None => return Vec::new(),
1846 let (lower, _) = iterator.size_hint();
1847 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1849 ptr::write(vector.get_unchecked_mut(0), element);
1855 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1859 default fn spec_extend(&mut self, iter: I) {
1860 self.extend_desugared(iter)
1864 impl<T, I> SpecExtend<T, I> for Vec<T>
1865 where I: TrustedLen<Item=T>,
1867 default fn from_iter(iterator: I) -> Self {
1868 let mut vector = Vec::new();
1869 vector.spec_extend(iterator);
1873 default fn spec_extend(&mut self, iterator: I) {
1874 // This is the case for a TrustedLen iterator.
1875 let (low, high) = iterator.size_hint();
1876 if let Some(high_value) = high {
1877 debug_assert_eq!(low, high_value,
1878 "TrustedLen iterator's size hint is not exact: {:?}",
1881 if let Some(additional) = high {
1882 self.reserve(additional);
1884 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1885 let mut local_len = SetLenOnDrop::new(&mut self.len);
1886 for element in iterator {
1887 ptr::write(ptr, element);
1888 ptr = ptr.offset(1);
1889 // NB can't overflow since we would have had to alloc the address space
1890 local_len.increment_len(1);
1894 self.extend_desugared(iterator)
1899 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
1900 fn from_iter(iterator: IntoIter<T>) -> Self {
1901 // A common case is passing a vector into a function which immediately
1902 // re-collects into a vector. We can short circuit this if the IntoIter
1903 // has not been advanced at all.
1904 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
1906 let vec = Vec::from_raw_parts(iterator.buf.as_ptr(),
1909 mem::forget(iterator);
1913 let mut vector = Vec::new();
1914 vector.spec_extend(iterator);
1919 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
1921 self.append_elements(iterator.as_slice() as _);
1923 iterator.ptr = iterator.end;
1927 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
1928 where I: Iterator<Item=&'a T>,
1931 default fn from_iter(iterator: I) -> Self {
1932 SpecExtend::from_iter(iterator.cloned())
1935 default fn spec_extend(&mut self, iterator: I) {
1936 self.spec_extend(iterator.cloned())
1940 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
1943 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
1944 let slice = iterator.as_slice();
1945 self.reserve(slice.len());
1947 let len = self.len();
1948 self.set_len(len + slice.len());
1949 self.get_unchecked_mut(len..).copy_from_slice(slice);
1955 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1956 // This is the case for a general iterator.
1958 // This function should be the moral equivalent of:
1960 // for item in iterator {
1963 while let Some(element) = iterator.next() {
1964 let len = self.len();
1965 if len == self.capacity() {
1966 let (lower, _) = iterator.size_hint();
1967 self.reserve(lower.saturating_add(1));
1970 ptr::write(self.get_unchecked_mut(len), element);
1971 // NB can't overflow since we would have had to alloc the address space
1972 self.set_len(len + 1);
1977 /// Creates a splicing iterator that replaces the specified range in the vector
1978 /// with the given `replace_with` iterator and yields the removed items.
1979 /// `replace_with` does not need to be the same length as `range`.
1981 /// Note 1: The element range is removed even if the iterator is not
1982 /// consumed until the end.
1984 /// Note 2: It is unspecified how many elements are removed from the vector,
1985 /// if the `Splice` value is leaked.
1987 /// Note 3: The input iterator `replace_with` is only consumed
1988 /// when the `Splice` value is dropped.
1990 /// Note 4: This is optimal if:
1992 /// * The tail (elements in the vector after `range`) is empty,
1993 /// * or `replace_with` yields fewer elements than `range`’s length
1994 /// * or the lower bound of its `size_hint()` is exact.
1996 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2000 /// Panics if the starting point is greater than the end point or if
2001 /// the end point is greater than the length of the vector.
2006 /// let mut v = vec![1, 2, 3];
2007 /// let new = [7, 8];
2008 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2009 /// assert_eq!(v, &[7, 8, 3]);
2010 /// assert_eq!(u, &[1, 2]);
2013 #[stable(feature = "vec_splice", since = "1.21.0")]
2014 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<I::IntoIter>
2015 where R: RangeBounds<usize>, I: IntoIterator<Item=T>
2018 drain: self.drain(range),
2019 replace_with: replace_with.into_iter(),
2023 /// Creates an iterator which uses a closure to determine if an element should be removed.
2025 /// If the closure returns true, then the element is removed and yielded.
2026 /// If the closure returns false, the element will remain in the vector and will not be yielded
2027 /// by the iterator.
2029 /// Using this method is equivalent to the following code:
2032 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2033 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2035 /// while i != vec.len() {
2036 /// if some_predicate(&mut vec[i]) {
2037 /// let val = vec.remove(i);
2038 /// // your code here
2044 /// # assert_eq!(vec, vec![1, 4, 5]);
2047 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2048 /// because it can backshift the elements of the array in bulk.
2050 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2051 /// regardless of whether you choose to keep or remove it.
2056 /// Splitting an array into evens and odds, reusing the original allocation:
2059 /// #![feature(drain_filter)]
2060 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2062 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2063 /// let odds = numbers;
2065 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2066 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2068 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2069 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<T, F>
2070 where F: FnMut(&mut T) -> bool,
2072 let old_len = self.len();
2074 // Guard against us getting leaked (leak amplification)
2075 unsafe { self.set_len(0); }
2087 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2089 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2090 /// append the entire slice at once.
2092 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2093 #[stable(feature = "extend_ref", since = "1.2.0")]
2094 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2095 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2096 self.spec_extend(iter.into_iter())
2100 macro_rules! __impl_slice_eq1 {
2101 ($Lhs: ty, $Rhs: ty) => {
2102 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2104 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2105 #[stable(feature = "rust1", since = "1.0.0")]
2106 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2108 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
2110 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
2115 __impl_slice_eq1! { Vec<A>, Vec<B> }
2116 __impl_slice_eq1! { Vec<A>, &'b [B] }
2117 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
2118 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
2119 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
2120 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
2122 macro_rules! array_impls {
2125 // NOTE: some less important impls are omitted to reduce code bloat
2126 __impl_slice_eq1! { Vec<A>, [B; $N] }
2127 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
2128 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
2129 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
2130 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
2131 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
2138 10 11 12 13 14 15 16 17 18 19
2139 20 21 22 23 24 25 26 27 28 29
2143 /// Implements comparison of vectors, lexicographically.
2144 #[stable(feature = "rust1", since = "1.0.0")]
2145 impl<T: PartialOrd> PartialOrd for Vec<T> {
2147 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2148 PartialOrd::partial_cmp(&**self, &**other)
2152 #[stable(feature = "rust1", since = "1.0.0")]
2153 impl<T: Eq> Eq for Vec<T> {}
2155 /// Implements ordering of vectors, lexicographically.
2156 #[stable(feature = "rust1", since = "1.0.0")]
2157 impl<T: Ord> Ord for Vec<T> {
2159 fn cmp(&self, other: &Vec<T>) -> Ordering {
2160 Ord::cmp(&**self, &**other)
2164 #[stable(feature = "rust1", since = "1.0.0")]
2165 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2166 fn drop(&mut self) {
2169 ptr::drop_in_place(&mut self[..]);
2171 // RawVec handles deallocation
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 impl<T> Default for Vec<T> {
2177 /// Creates an empty `Vec<T>`.
2178 fn default() -> Vec<T> {
2183 #[stable(feature = "rust1", since = "1.0.0")]
2184 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2185 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2186 fmt::Debug::fmt(&**self, f)
2190 #[stable(feature = "rust1", since = "1.0.0")]
2191 impl<T> AsRef<Vec<T>> for Vec<T> {
2192 fn as_ref(&self) -> &Vec<T> {
2197 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2198 impl<T> AsMut<Vec<T>> for Vec<T> {
2199 fn as_mut(&mut self) -> &mut Vec<T> {
2204 #[stable(feature = "rust1", since = "1.0.0")]
2205 impl<T> AsRef<[T]> for Vec<T> {
2206 fn as_ref(&self) -> &[T] {
2211 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2212 impl<T> AsMut<[T]> for Vec<T> {
2213 fn as_mut(&mut self) -> &mut [T] {
2218 #[stable(feature = "rust1", since = "1.0.0")]
2219 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
2221 fn from(s: &'a [T]) -> Vec<T> {
2225 fn from(s: &'a [T]) -> Vec<T> {
2230 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2231 impl<'a, T: Clone> From<&'a mut [T]> for Vec<T> {
2233 fn from(s: &'a mut [T]) -> Vec<T> {
2237 fn from(s: &'a mut [T]) -> Vec<T> {
2242 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2243 impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> {
2244 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2249 // note: test pulls in libstd, which causes errors here
2251 #[stable(feature = "vec_from_box", since = "1.18.0")]
2252 impl<T> From<Box<[T]>> for Vec<T> {
2253 fn from(s: Box<[T]>) -> Vec<T> {
2258 // note: test pulls in libstd, which causes errors here
2260 #[stable(feature = "box_from_vec", since = "1.20.0")]
2261 impl<T> From<Vec<T>> for Box<[T]> {
2262 fn from(v: Vec<T>) -> Box<[T]> {
2263 v.into_boxed_slice()
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 impl<'a> From<&'a str> for Vec<u8> {
2269 fn from(s: &'a str) -> Vec<u8> {
2270 From::from(s.as_bytes())
2274 ////////////////////////////////////////////////////////////////////////////////
2276 ////////////////////////////////////////////////////////////////////////////////
2278 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2279 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2280 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2285 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2286 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2287 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2292 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2293 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2294 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2295 Cow::Borrowed(v.as_slice())
2299 #[stable(feature = "rust1", since = "1.0.0")]
2300 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
2301 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2302 Cow::Owned(FromIterator::from_iter(it))
2306 ////////////////////////////////////////////////////////////////////////////////
2308 ////////////////////////////////////////////////////////////////////////////////
2310 /// An iterator that moves out of a vector.
2312 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2313 /// by the [`IntoIterator`] trait).
2315 /// [`Vec`]: struct.Vec.html
2316 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2317 #[stable(feature = "rust1", since = "1.0.0")]
2318 pub struct IntoIter<T> {
2320 phantom: PhantomData<T>,
2326 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2327 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2328 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2329 f.debug_tuple("IntoIter")
2330 .field(&self.as_slice())
2335 impl<T> IntoIter<T> {
2336 /// Returns the remaining items of this iterator as a slice.
2341 /// let vec = vec!['a', 'b', 'c'];
2342 /// let mut into_iter = vec.into_iter();
2343 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2344 /// let _ = into_iter.next().unwrap();
2345 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2347 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2348 pub fn as_slice(&self) -> &[T] {
2350 slice::from_raw_parts(self.ptr, self.len())
2354 /// Returns the remaining items of this iterator as a mutable slice.
2359 /// let vec = vec!['a', 'b', 'c'];
2360 /// let mut into_iter = vec.into_iter();
2361 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2362 /// into_iter.as_mut_slice()[2] = 'z';
2363 /// assert_eq!(into_iter.next().unwrap(), 'a');
2364 /// assert_eq!(into_iter.next().unwrap(), 'b');
2365 /// assert_eq!(into_iter.next().unwrap(), 'z');
2367 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2368 pub fn as_mut_slice(&mut self) -> &mut [T] {
2370 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
2375 #[stable(feature = "rust1", since = "1.0.0")]
2376 unsafe impl<T: Send> Send for IntoIter<T> {}
2377 #[stable(feature = "rust1", since = "1.0.0")]
2378 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2380 #[stable(feature = "rust1", since = "1.0.0")]
2381 impl<T> Iterator for IntoIter<T> {
2385 fn next(&mut self) -> Option<T> {
2387 if self.ptr as *const _ == self.end {
2390 if mem::size_of::<T>() == 0 {
2391 // purposefully don't use 'ptr.offset' because for
2392 // vectors with 0-size elements this would return the
2394 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2396 // Use a non-null pointer value
2397 // (self.ptr might be null because of wrapping)
2398 Some(ptr::read(1 as *mut T))
2401 self.ptr = self.ptr.offset(1);
2403 Some(ptr::read(old))
2410 fn size_hint(&self) -> (usize, Option<usize>) {
2411 let exact = if mem::size_of::<T>() == 0 {
2412 (self.end as usize).wrapping_sub(self.ptr as usize)
2414 unsafe { self.end.offset_from(self.ptr) as usize }
2416 (exact, Some(exact))
2420 fn count(self) -> usize {
2425 #[stable(feature = "rust1", since = "1.0.0")]
2426 impl<T> DoubleEndedIterator for IntoIter<T> {
2428 fn next_back(&mut self) -> Option<T> {
2430 if self.end == self.ptr {
2433 if mem::size_of::<T>() == 0 {
2434 // See above for why 'ptr.offset' isn't used
2435 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2437 // Use a non-null pointer value
2438 // (self.end might be null because of wrapping)
2439 Some(ptr::read(1 as *mut T))
2441 self.end = self.end.offset(-1);
2443 Some(ptr::read(self.end))
2450 #[stable(feature = "rust1", since = "1.0.0")]
2451 impl<T> ExactSizeIterator for IntoIter<T> {
2452 fn is_empty(&self) -> bool {
2453 self.ptr == self.end
2457 #[stable(feature = "fused", since = "1.26.0")]
2458 impl<T> FusedIterator for IntoIter<T> {}
2460 #[unstable(feature = "trusted_len", issue = "37572")]
2461 unsafe impl<T> TrustedLen for IntoIter<T> {}
2463 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2464 impl<T: Clone> Clone for IntoIter<T> {
2465 fn clone(&self) -> IntoIter<T> {
2466 self.as_slice().to_owned().into_iter()
2470 #[stable(feature = "rust1", since = "1.0.0")]
2471 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2472 fn drop(&mut self) {
2473 // destroy the remaining elements
2474 for _x in self.by_ref() {}
2476 // RawVec handles deallocation
2477 let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) };
2481 /// A draining iterator for `Vec<T>`.
2483 /// This `struct` is created by the [`drain`] method on [`Vec`].
2485 /// [`drain`]: struct.Vec.html#method.drain
2486 /// [`Vec`]: struct.Vec.html
2487 #[stable(feature = "drain", since = "1.6.0")]
2488 pub struct Drain<'a, T: 'a> {
2489 /// Index of tail to preserve
2493 /// Current remaining range to remove
2494 iter: slice::Iter<'a, T>,
2495 vec: NonNull<Vec<T>>,
2498 #[stable(feature = "collection_debug", since = "1.17.0")]
2499 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2500 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2501 f.debug_tuple("Drain")
2502 .field(&self.iter.as_slice())
2507 #[stable(feature = "drain", since = "1.6.0")]
2508 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2509 #[stable(feature = "drain", since = "1.6.0")]
2510 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2512 #[stable(feature = "drain", since = "1.6.0")]
2513 impl<'a, T> Iterator for Drain<'a, T> {
2517 fn next(&mut self) -> Option<T> {
2518 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2521 fn size_hint(&self) -> (usize, Option<usize>) {
2522 self.iter.size_hint()
2526 #[stable(feature = "drain", since = "1.6.0")]
2527 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
2529 fn next_back(&mut self) -> Option<T> {
2530 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2534 #[stable(feature = "drain", since = "1.6.0")]
2535 impl<'a, T> Drop for Drain<'a, T> {
2536 fn drop(&mut self) {
2537 // exhaust self first
2538 self.for_each(drop);
2540 if self.tail_len > 0 {
2542 let source_vec = self.vec.as_mut();
2543 // memmove back untouched tail, update to new length
2544 let start = source_vec.len();
2545 let tail = self.tail_start;
2547 let src = source_vec.as_ptr().offset(tail as isize);
2548 let dst = source_vec.as_mut_ptr().offset(start as isize);
2549 ptr::copy(src, dst, self.tail_len);
2551 source_vec.set_len(start + self.tail_len);
2558 #[stable(feature = "drain", since = "1.6.0")]
2559 impl<'a, T> ExactSizeIterator for Drain<'a, T> {
2560 fn is_empty(&self) -> bool {
2561 self.iter.is_empty()
2565 #[stable(feature = "fused", since = "1.26.0")]
2566 impl<'a, T> FusedIterator for Drain<'a, T> {}
2568 /// A splicing iterator for `Vec`.
2570 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2571 /// documentation for more.
2573 /// [`splice()`]: struct.Vec.html#method.splice
2574 /// [`Vec`]: struct.Vec.html
2576 #[stable(feature = "vec_splice", since = "1.21.0")]
2577 pub struct Splice<'a, I: Iterator + 'a> {
2578 drain: Drain<'a, I::Item>,
2582 #[stable(feature = "vec_splice", since = "1.21.0")]
2583 impl<'a, I: Iterator> Iterator for Splice<'a, I> {
2584 type Item = I::Item;
2586 fn next(&mut self) -> Option<Self::Item> {
2590 fn size_hint(&self) -> (usize, Option<usize>) {
2591 self.drain.size_hint()
2595 #[stable(feature = "vec_splice", since = "1.21.0")]
2596 impl<'a, I: Iterator> DoubleEndedIterator for Splice<'a, I> {
2597 fn next_back(&mut self) -> Option<Self::Item> {
2598 self.drain.next_back()
2602 #[stable(feature = "vec_splice", since = "1.21.0")]
2603 impl<'a, I: Iterator> ExactSizeIterator for Splice<'a, I> {}
2606 #[stable(feature = "vec_splice", since = "1.21.0")]
2607 impl<'a, I: Iterator> Drop for Splice<'a, I> {
2608 fn drop(&mut self) {
2609 self.drain.by_ref().for_each(drop);
2612 if self.drain.tail_len == 0 {
2613 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2617 // First fill the range left by drain().
2618 if !self.drain.fill(&mut self.replace_with) {
2622 // There may be more elements. Use the lower bound as an estimate.
2623 // FIXME: Is the upper bound a better guess? Or something else?
2624 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2625 if lower_bound > 0 {
2626 self.drain.move_tail(lower_bound);
2627 if !self.drain.fill(&mut self.replace_with) {
2632 // Collect any remaining elements.
2633 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2634 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2635 // Now we have an exact count.
2636 if collected.len() > 0 {
2637 self.drain.move_tail(collected.len());
2638 let filled = self.drain.fill(&mut collected);
2639 debug_assert!(filled);
2640 debug_assert_eq!(collected.len(), 0);
2643 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2647 /// Private helper methods for `Splice::drop`
2648 impl<'a, T> Drain<'a, T> {
2649 /// The range from `self.vec.len` to `self.tail_start` contains elements
2650 /// that have been moved out.
2651 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2652 /// Return whether we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2653 unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
2654 let vec = self.vec.as_mut();
2655 let range_start = vec.len;
2656 let range_end = self.tail_start;
2657 let range_slice = slice::from_raw_parts_mut(
2658 vec.as_mut_ptr().offset(range_start as isize),
2659 range_end - range_start);
2661 for place in range_slice {
2662 if let Some(new_item) = replace_with.next() {
2663 ptr::write(place, new_item);
2672 /// Make room for inserting more elements before the tail.
2673 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2674 let vec = self.vec.as_mut();
2675 let used_capacity = self.tail_start + self.tail_len;
2676 vec.buf.reserve(used_capacity, extra_capacity);
2678 let new_tail_start = self.tail_start + extra_capacity;
2679 let src = vec.as_ptr().offset(self.tail_start as isize);
2680 let dst = vec.as_mut_ptr().offset(new_tail_start as isize);
2681 ptr::copy(src, dst, self.tail_len);
2682 self.tail_start = new_tail_start;
2686 /// An iterator produced by calling `drain_filter` on Vec.
2687 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2689 pub struct DrainFilter<'a, T: 'a, F>
2690 where F: FnMut(&mut T) -> bool,
2692 vec: &'a mut Vec<T>,
2699 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2700 impl<'a, T, F> Iterator for DrainFilter<'a, T, F>
2701 where F: FnMut(&mut T) -> bool,
2705 fn next(&mut self) -> Option<T> {
2707 while self.idx != self.old_len {
2710 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
2711 if (self.pred)(&mut v[i]) {
2713 return Some(ptr::read(&v[i]));
2714 } else if self.del > 0 {
2716 let src: *const T = &v[i];
2717 let dst: *mut T = &mut v[i - del];
2718 // This is safe because self.vec has length 0
2719 // thus its elements will not have Drop::drop
2720 // called on them in the event of a panic.
2721 ptr::copy_nonoverlapping(src, dst, 1);
2728 fn size_hint(&self) -> (usize, Option<usize>) {
2729 (0, Some(self.old_len - self.idx))
2733 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2734 impl<'a, T, F> Drop for DrainFilter<'a, T, F>
2735 where F: FnMut(&mut T) -> bool,
2737 fn drop(&mut self) {
2738 self.for_each(drop);
2740 self.vec.set_len(self.old_len - self.del);