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;
78 use core::ops::Bound::{Excluded, Included, Unbounded};
79 use core::ops::{Index, IndexMut, RangeBounds};
82 use core::ptr::NonNull;
85 use alloc::CollectionAllocErr;
91 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
96 /// let mut vec = Vec::new();
100 /// assert_eq!(vec.len(), 2);
101 /// assert_eq!(vec[0], 1);
103 /// assert_eq!(vec.pop(), Some(2));
104 /// assert_eq!(vec.len(), 1);
107 /// assert_eq!(vec[0], 7);
109 /// vec.extend([1, 2, 3].iter().cloned());
112 /// println!("{}", x);
114 /// assert_eq!(vec, [7, 1, 2, 3]);
117 /// The [`vec!`] macro is provided to make initialization more convenient:
120 /// let mut vec = vec![1, 2, 3];
122 /// assert_eq!(vec, [1, 2, 3, 4]);
125 /// It can also initialize each element of a `Vec<T>` with a given value:
128 /// let vec = vec![0; 5];
129 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
132 /// Use a `Vec<T>` as an efficient stack:
135 /// let mut stack = Vec::new();
141 /// while let Some(top) = stack.pop() {
142 /// // Prints 3, 2, 1
143 /// println!("{}", top);
149 /// The `Vec` type allows to access values by index, because it implements the
150 /// [`Index`] trait. An example will be more explicit:
153 /// let v = vec![0, 2, 4, 6];
154 /// println!("{}", v[1]); // it will display '2'
157 /// However be careful: if you try to access an index which isn't in the `Vec`,
158 /// your software will panic! You cannot do this:
161 /// let v = vec![0, 2, 4, 6];
162 /// println!("{}", v[6]); // it will panic!
165 /// In conclusion: always check if the index you want to get really exists
170 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
171 /// To get a slice, use `&`. Example:
174 /// fn read_slice(slice: &[usize]) {
178 /// let v = vec![0, 1];
181 /// // ... and that's all!
182 /// // you can also do it like this:
183 /// let x : &[usize] = &v;
186 /// In Rust, it's more common to pass slices as arguments rather than vectors
187 /// when you just want to provide a read access. The same goes for [`String`] and
190 /// # Capacity and reallocation
192 /// The capacity of a vector is the amount of space allocated for any future
193 /// elements that will be added onto the vector. This is not to be confused with
194 /// the *length* of a vector, which specifies the number of actual elements
195 /// within the vector. If a vector's length exceeds its capacity, its capacity
196 /// will automatically be increased, but its elements will have to be
199 /// For example, a vector with capacity 10 and length 0 would be an empty vector
200 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
201 /// vector will not change its capacity or cause reallocation to occur. However,
202 /// if the vector's length is increased to 11, it will have to reallocate, which
203 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
204 /// whenever possible to specify how big the vector is expected to get.
208 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
209 /// about its design. This ensures that it's as low-overhead as possible in
210 /// the general case, and can be correctly manipulated in primitive ways
211 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
212 /// If additional type parameters are added (e.g. to support custom allocators),
213 /// overriding their defaults may change the behavior.
215 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
216 /// triplet. No more, no less. The order of these fields is completely
217 /// unspecified, and you should use the appropriate methods to modify these.
218 /// The pointer will never be null, so this type is null-pointer-optimized.
220 /// However, the pointer may not actually point to allocated memory. In particular,
221 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
222 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
223 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
224 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
225 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
226 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
227 /// details are very subtle — if you intend to allocate memory using a `Vec`
228 /// and use it for something else (either to pass to unsafe code, or to build your
229 /// own memory-backed collection), be sure to deallocate this memory by using
230 /// `from_raw_parts` to recover the `Vec` and then dropping it.
232 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
233 /// (as defined by the allocator Rust is configured to use by default), and its
234 /// pointer points to [`len`] initialized, contiguous elements in order (what
235 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
236 /// `[`len`] logically uninitialized, contiguous elements.
238 /// `Vec` will never perform a "small optimization" where elements are actually
239 /// stored on the stack for two reasons:
241 /// * It would make it more difficult for unsafe code to correctly manipulate
242 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
243 /// only moved, and it would be more difficult to determine if a `Vec` had
244 /// actually allocated memory.
246 /// * It would penalize the general case, incurring an additional branch
249 /// `Vec` will never automatically shrink itself, even if completely empty. This
250 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
251 /// and then filling it back up to the same [`len`] should incur no calls to
252 /// the allocator. If you wish to free up unused memory, use
253 /// [`shrink_to_fit`][`shrink_to_fit`].
255 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
256 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
257 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
258 /// accurate, and can be relied on. It can even be used to manually free the memory
259 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
260 /// when not necessary.
262 /// `Vec` does not guarantee any particular growth strategy when reallocating
263 /// when full, nor when [`reserve`] is called. The current strategy is basic
264 /// and it may prove desirable to use a non-constant growth factor. Whatever
265 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
267 /// `vec![x; n]`, `vec![a, b, c, d]`, and
268 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
269 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
270 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
271 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
273 /// `Vec` will not specifically overwrite any data that is removed from it,
274 /// but also won't specifically preserve it. Its uninitialized memory is
275 /// scratch space that it may use however it wants. It will generally just do
276 /// whatever is most efficient or otherwise easy to implement. Do not rely on
277 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
278 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
279 /// first, that may not actually happen because the optimizer does not consider
280 /// this a side-effect that must be preserved. There is one case which we will
281 /// not break, however: using `unsafe` code to write to the excess capacity,
282 /// and then increasing the length to match, is always valid.
284 /// `Vec` does not currently guarantee the order in which elements are dropped.
285 /// The order has changed in the past and may change again.
287 /// [`vec!`]: ../../std/macro.vec.html
288 /// [`Index`]: ../../std/ops/trait.Index.html
289 /// [`String`]: ../../std/string/struct.String.html
290 /// [`&str`]: ../../std/primitive.str.html
291 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
292 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
293 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
294 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
295 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
296 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
297 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
298 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
299 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
300 /// [owned slice]: ../../std/boxed/struct.Box.html
301 #[stable(feature = "rust1", since = "1.0.0")]
307 ////////////////////////////////////////////////////////////////////////////////
309 ////////////////////////////////////////////////////////////////////////////////
312 /// Constructs a new, empty `Vec<T>`.
314 /// The vector will not allocate until elements are pushed onto it.
319 /// # #![allow(unused_mut)]
320 /// let mut vec: Vec<i32> = Vec::new();
323 #[stable(feature = "rust1", since = "1.0.0")]
324 pub fn new() -> Vec<T> {
331 /// Constructs a new, empty `Vec<T>` with the specified capacity.
333 /// The vector will be able to hold exactly `capacity` elements without
334 /// reallocating. If `capacity` is 0, the vector will not allocate.
336 /// It is important to note that although the returned vector has the
337 /// *capacity* specified, the vector will have a zero *length*. For an
338 /// explanation of the difference between length and capacity, see
339 /// *[Capacity and reallocation]*.
341 /// [Capacity and reallocation]: #capacity-and-reallocation
346 /// let mut vec = Vec::with_capacity(10);
348 /// // The vector contains no items, even though it has capacity for more
349 /// assert_eq!(vec.len(), 0);
351 /// // These are all done without reallocating...
356 /// // ...but this may make the vector reallocate
360 #[stable(feature = "rust1", since = "1.0.0")]
361 pub fn with_capacity(capacity: usize) -> Vec<T> {
363 buf: RawVec::with_capacity(capacity),
368 /// Creates a `Vec<T>` directly from the raw components of another vector.
372 /// This is highly unsafe, due to the number of invariants that aren't
375 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
376 /// (at least, it's highly likely to be incorrect if it wasn't).
377 /// * `ptr`'s `T` needs to have the same size and alignment as it was allocated with.
378 /// * `length` needs to be less than or equal to `capacity`.
379 /// * `capacity` needs to be the capacity that the pointer was allocated with.
381 /// Violating these may cause problems like corrupting the allocator's
382 /// internal data structures. For example it is **not** safe
383 /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`.
385 /// The ownership of `ptr` is effectively transferred to the
386 /// `Vec<T>` which may then deallocate, reallocate or change the
387 /// contents of memory pointed to by the pointer at will. Ensure
388 /// that nothing else uses the pointer after calling this
391 /// [`String`]: ../../std/string/struct.String.html
400 /// let mut v = vec![1, 2, 3];
402 /// // Pull out the various important pieces of information about `v`
403 /// let p = v.as_mut_ptr();
404 /// let len = v.len();
405 /// let cap = v.capacity();
408 /// // Cast `v` into the void: no destructor run, so we are in
409 /// // complete control of the allocation to which `p` points.
412 /// // Overwrite memory with 4, 5, 6
413 /// for i in 0..len as isize {
414 /// ptr::write(p.offset(i), 4 + i);
417 /// // Put everything back together into a Vec
418 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
419 /// assert_eq!(rebuilt, [4, 5, 6]);
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
426 buf: RawVec::from_raw_parts(ptr, capacity),
431 /// Returns the number of elements the vector can hold without
437 /// let vec: Vec<i32> = Vec::with_capacity(10);
438 /// assert_eq!(vec.capacity(), 10);
441 #[stable(feature = "rust1", since = "1.0.0")]
442 pub fn capacity(&self) -> usize {
446 /// Reserves capacity for at least `additional` more elements to be inserted
447 /// in the given `Vec<T>`. The collection may reserve more space to avoid
448 /// frequent reallocations. After calling `reserve`, capacity will be
449 /// greater than or equal to `self.len() + additional`. Does nothing if
450 /// capacity is already sufficient.
454 /// Panics if the new capacity overflows `usize`.
459 /// let mut vec = vec![1];
461 /// assert!(vec.capacity() >= 11);
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub fn reserve(&mut self, additional: usize) {
465 self.buf.reserve(self.len, additional);
468 /// Reserves the minimum capacity for exactly `additional` more elements to
469 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
470 /// capacity will be greater than or equal to `self.len() + additional`.
471 /// Does nothing if the capacity is already sufficient.
473 /// Note that the allocator may give the collection more space than it
474 /// requests. Therefore capacity can not be relied upon to be precisely
475 /// minimal. Prefer `reserve` if future insertions are expected.
479 /// Panics if the new capacity overflows `usize`.
484 /// let mut vec = vec![1];
485 /// vec.reserve_exact(10);
486 /// assert!(vec.capacity() >= 11);
488 #[stable(feature = "rust1", since = "1.0.0")]
489 pub fn reserve_exact(&mut self, additional: usize) {
490 self.buf.reserve_exact(self.len, additional);
493 /// Tries to reserve capacity for at least `additional` more elements to be inserted
494 /// in the given `Vec<T>`. The collection may reserve more space to avoid
495 /// frequent reallocations. After calling `reserve`, capacity will be
496 /// greater than or equal to `self.len() + additional`. Does nothing if
497 /// capacity is already sufficient.
501 /// If the capacity overflows, or the allocator reports a failure, then an error
507 /// #![feature(try_reserve)]
508 /// use std::collections::CollectionAllocErr;
510 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> {
511 /// let mut output = Vec::new();
513 /// // Pre-reserve the memory, exiting if we can't
514 /// output.try_reserve(data.len())?;
516 /// // Now we know this can't OOM in the middle of our complex work
517 /// output.extend(data.iter().map(|&val| {
518 /// val * 2 + 5 // very complicated
523 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
525 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
526 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
527 self.buf.try_reserve(self.len, additional)
530 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
531 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
532 /// capacity will be greater than or equal to `self.len() + additional`.
533 /// Does nothing if the capacity is already sufficient.
535 /// Note that the allocator may give the collection more space than it
536 /// requests. Therefore capacity can not be relied upon to be precisely
537 /// minimal. Prefer `reserve` if future insertions are expected.
541 /// If the capacity overflows, or the allocator reports a failure, then an error
547 /// #![feature(try_reserve)]
548 /// use std::collections::CollectionAllocErr;
550 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> {
551 /// let mut output = Vec::new();
553 /// // Pre-reserve the memory, exiting if we can't
554 /// output.try_reserve(data.len())?;
556 /// // Now we know this can't OOM in the middle of our complex work
557 /// output.extend(data.iter().map(|&val| {
558 /// val * 2 + 5 // very complicated
563 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
565 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
566 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
567 self.buf.try_reserve_exact(self.len, additional)
570 /// Shrinks the capacity of the vector as much as possible.
572 /// It will drop down as close as possible to the length but the allocator
573 /// may still inform the vector that there is space for a few more elements.
578 /// let mut vec = Vec::with_capacity(10);
579 /// vec.extend([1, 2, 3].iter().cloned());
580 /// assert_eq!(vec.capacity(), 10);
581 /// vec.shrink_to_fit();
582 /// assert!(vec.capacity() >= 3);
584 #[stable(feature = "rust1", since = "1.0.0")]
585 pub fn shrink_to_fit(&mut self) {
586 if self.capacity() != self.len {
587 self.buf.shrink_to_fit(self.len);
591 /// Shrinks the capacity of the vector with a lower bound.
593 /// The capacity will remain at least as large as both the length
594 /// and the supplied value.
596 /// Panics if the current capacity is smaller than the supplied
597 /// minimum capacity.
602 /// #![feature(shrink_to)]
603 /// let mut vec = Vec::with_capacity(10);
604 /// vec.extend([1, 2, 3].iter().cloned());
605 /// assert_eq!(vec.capacity(), 10);
606 /// vec.shrink_to(4);
607 /// assert!(vec.capacity() >= 4);
608 /// vec.shrink_to(0);
609 /// assert!(vec.capacity() >= 3);
611 #[unstable(feature = "shrink_to", reason = "new API", issue="0")]
612 pub fn shrink_to(&mut self, min_capacity: usize) {
613 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
616 /// Converts the vector into [`Box<[T]>`][owned slice].
618 /// Note that this will drop any excess capacity.
620 /// [owned slice]: ../../std/boxed/struct.Box.html
625 /// let v = vec![1, 2, 3];
627 /// let slice = v.into_boxed_slice();
630 /// Any excess capacity is removed:
633 /// let mut vec = Vec::with_capacity(10);
634 /// vec.extend([1, 2, 3].iter().cloned());
636 /// assert_eq!(vec.capacity(), 10);
637 /// let slice = vec.into_boxed_slice();
638 /// assert_eq!(slice.into_vec().capacity(), 3);
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn into_boxed_slice(mut self) -> Box<[T]> {
643 self.shrink_to_fit();
644 let buf = ptr::read(&self.buf);
650 /// Shortens the vector, keeping the first `len` elements and dropping
653 /// If `len` is greater than the vector's current length, this has no
656 /// The [`drain`] method can emulate `truncate`, but causes the excess
657 /// elements to be returned instead of dropped.
659 /// Note that this method has no effect on the allocated capacity
664 /// Truncating a five element vector to two elements:
667 /// let mut vec = vec![1, 2, 3, 4, 5];
669 /// assert_eq!(vec, [1, 2]);
672 /// No truncation occurs when `len` is greater than the vector's current
676 /// let mut vec = vec![1, 2, 3];
678 /// assert_eq!(vec, [1, 2, 3]);
681 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
685 /// let mut vec = vec![1, 2, 3];
687 /// assert_eq!(vec, []);
690 /// [`clear`]: #method.clear
691 /// [`drain`]: #method.drain
692 #[stable(feature = "rust1", since = "1.0.0")]
693 pub fn truncate(&mut self, len: usize) {
695 // drop any extra elements
696 while len < self.len {
697 // decrement len before the drop_in_place(), so a panic on Drop
698 // doesn't re-drop the just-failed value.
701 ptr::drop_in_place(self.get_unchecked_mut(len));
706 /// Extracts a slice containing the entire vector.
708 /// Equivalent to `&s[..]`.
713 /// use std::io::{self, Write};
714 /// let buffer = vec![1, 2, 3, 5, 8];
715 /// io::sink().write(buffer.as_slice()).unwrap();
718 #[stable(feature = "vec_as_slice", since = "1.7.0")]
719 pub fn as_slice(&self) -> &[T] {
723 /// Extracts a mutable slice of the entire vector.
725 /// Equivalent to `&mut s[..]`.
730 /// use std::io::{self, Read};
731 /// let mut buffer = vec![0; 3];
732 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
735 #[stable(feature = "vec_as_slice", since = "1.7.0")]
736 pub fn as_mut_slice(&mut self) -> &mut [T] {
740 /// Sets the length of a vector.
742 /// This will explicitly set the size of the vector, without actually
743 /// modifying its buffers, so it is up to the caller to ensure that the
744 /// vector is actually the specified size.
751 /// let mut vec = vec!['r', 'u', 's', 't'];
754 /// ptr::drop_in_place(&mut vec[3]);
757 /// assert_eq!(vec, ['r', 'u', 's']);
760 /// In this example, there is a memory leak since the memory locations
761 /// owned by the inner vectors were not freed prior to the `set_len` call:
764 /// let mut vec = vec![vec![1, 0, 0],
772 /// In this example, the vector gets expanded from zero to four items
773 /// without any memory allocations occurring, resulting in vector
774 /// values of unallocated memory:
777 /// let mut vec: Vec<char> = Vec::new();
784 #[stable(feature = "rust1", since = "1.0.0")]
785 pub unsafe fn set_len(&mut self, len: usize) {
789 /// Removes an element from the vector and returns it.
791 /// The removed element is replaced by the last element of the vector.
793 /// This does not preserve ordering, but is O(1).
797 /// Panics if `index` is out of bounds.
802 /// let mut v = vec!["foo", "bar", "baz", "qux"];
804 /// assert_eq!(v.swap_remove(1), "bar");
805 /// assert_eq!(v, ["foo", "qux", "baz"]);
807 /// assert_eq!(v.swap_remove(0), "foo");
808 /// assert_eq!(v, ["baz", "qux"]);
811 #[stable(feature = "rust1", since = "1.0.0")]
812 pub fn swap_remove(&mut self, index: usize) -> T {
813 let length = self.len();
814 self.swap(index, length - 1);
818 /// Inserts an element at position `index` within the vector, shifting all
819 /// elements after it to the right.
823 /// Panics if `index > len`.
828 /// let mut vec = vec![1, 2, 3];
829 /// vec.insert(1, 4);
830 /// assert_eq!(vec, [1, 4, 2, 3]);
831 /// vec.insert(4, 5);
832 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
834 #[stable(feature = "rust1", since = "1.0.0")]
835 pub fn insert(&mut self, index: usize, element: T) {
836 let len = self.len();
837 assert!(index <= len);
839 // space for the new element
840 if len == self.buf.cap() {
846 // The spot to put the new value
848 let p = self.as_mut_ptr().offset(index as isize);
849 // Shift everything over to make space. (Duplicating the
850 // `index`th element into two consecutive places.)
851 ptr::copy(p, p.offset(1), len - index);
852 // Write it in, overwriting the first copy of the `index`th
854 ptr::write(p, element);
856 self.set_len(len + 1);
860 /// Removes and returns the element at position `index` within the vector,
861 /// shifting all elements after it to the left.
865 /// Panics if `index` is out of bounds.
870 /// let mut v = vec![1, 2, 3];
871 /// assert_eq!(v.remove(1), 2);
872 /// assert_eq!(v, [1, 3]);
874 #[stable(feature = "rust1", since = "1.0.0")]
875 pub fn remove(&mut self, index: usize) -> T {
876 let len = self.len();
877 assert!(index < len);
882 // the place we are taking from.
883 let ptr = self.as_mut_ptr().offset(index as isize);
884 // copy it out, unsafely having a copy of the value on
885 // the stack and in the vector at the same time.
886 ret = ptr::read(ptr);
888 // Shift everything down to fill in that spot.
889 ptr::copy(ptr.offset(1), ptr, len - index - 1);
891 self.set_len(len - 1);
896 /// Retains only the elements specified by the predicate.
898 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
899 /// This method operates in place and preserves the order of the retained
905 /// let mut vec = vec![1, 2, 3, 4];
906 /// vec.retain(|&x| x%2 == 0);
907 /// assert_eq!(vec, [2, 4]);
909 #[stable(feature = "rust1", since = "1.0.0")]
910 pub fn retain<F>(&mut self, mut f: F)
911 where F: FnMut(&T) -> bool
913 self.drain_filter(|x| !f(x));
916 /// Removes all but the first of consecutive elements in the vector that resolve to the same
919 /// If the vector is sorted, this removes all duplicates.
924 /// let mut vec = vec![10, 20, 21, 30, 20];
926 /// vec.dedup_by_key(|i| *i / 10);
928 /// assert_eq!(vec, [10, 20, 30, 20]);
930 #[stable(feature = "dedup_by", since = "1.16.0")]
932 pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
933 self.dedup_by(|a, b| key(a) == key(b))
936 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
939 /// The `same_bucket` function is passed references to two elements from the vector, and
940 /// returns `true` if the elements compare equal, or `false` if they do not. The elements are
941 /// passed in opposite order from their order in the vector, so if `same_bucket(a, b)` returns
942 /// `true`, `a` is removed.
944 /// If the vector is sorted, this removes all duplicates.
949 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
951 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
953 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
955 #[stable(feature = "dedup_by", since = "1.16.0")]
956 pub fn dedup_by<F>(&mut self, mut same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
958 // Although we have a mutable reference to `self`, we cannot make
959 // *arbitrary* changes. The `same_bucket` calls could panic, so we
960 // must ensure that the vector is in a valid state at all time.
962 // The way that we handle this is by using swaps; we iterate
963 // over all the elements, swapping as we go so that at the end
964 // the elements we wish to keep are in the front, and those we
965 // wish to reject are at the back. We can then truncate the
966 // vector. This operation is still O(n).
968 // Example: We start in this state, where `r` represents "next
969 // read" and `w` represents "next_write`.
972 // +---+---+---+---+---+---+
973 // | 0 | 1 | 1 | 2 | 3 | 3 |
974 // +---+---+---+---+---+---+
977 // Comparing self[r] against self[w-1], this is not a duplicate, so
978 // we swap self[r] and self[w] (no effect as r==w) and then increment both
979 // r and w, leaving us with:
982 // +---+---+---+---+---+---+
983 // | 0 | 1 | 1 | 2 | 3 | 3 |
984 // +---+---+---+---+---+---+
987 // Comparing self[r] against self[w-1], this value is a duplicate,
988 // so we increment `r` but leave everything else unchanged:
991 // +---+---+---+---+---+---+
992 // | 0 | 1 | 1 | 2 | 3 | 3 |
993 // +---+---+---+---+---+---+
996 // Comparing self[r] against self[w-1], this is not a duplicate,
997 // so swap self[r] and self[w] and advance r and w:
1000 // +---+---+---+---+---+---+
1001 // | 0 | 1 | 2 | 1 | 3 | 3 |
1002 // +---+---+---+---+---+---+
1005 // Not a duplicate, repeat:
1008 // +---+---+---+---+---+---+
1009 // | 0 | 1 | 2 | 3 | 1 | 3 |
1010 // +---+---+---+---+---+---+
1013 // Duplicate, advance r. End of vec. Truncate to w.
1015 let ln = self.len();
1020 // Avoid bounds checks by using raw pointers.
1021 let p = self.as_mut_ptr();
1022 let mut r: usize = 1;
1023 let mut w: usize = 1;
1026 let p_r = p.offset(r as isize);
1027 let p_wm1 = p.offset((w - 1) as isize);
1028 if !same_bucket(&mut *p_r, &mut *p_wm1) {
1030 let p_w = p_wm1.offset(1);
1031 mem::swap(&mut *p_r, &mut *p_w);
1042 /// Appends an element to the back of a collection.
1046 /// Panics if the number of elements in the vector overflows a `usize`.
1051 /// let mut vec = vec![1, 2];
1053 /// assert_eq!(vec, [1, 2, 3]);
1056 #[stable(feature = "rust1", since = "1.0.0")]
1057 pub fn push(&mut self, value: T) {
1058 // This will panic or abort if we would allocate > isize::MAX bytes
1059 // or if the length increment would overflow for zero-sized types.
1060 if self.len == self.buf.cap() {
1064 let end = self.as_mut_ptr().offset(self.len as isize);
1065 ptr::write(end, value);
1070 /// Removes the last element from a vector and returns it, or [`None`] if it
1073 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1078 /// let mut vec = vec![1, 2, 3];
1079 /// assert_eq!(vec.pop(), Some(3));
1080 /// assert_eq!(vec, [1, 2]);
1083 #[stable(feature = "rust1", since = "1.0.0")]
1084 pub fn pop(&mut self) -> Option<T> {
1090 Some(ptr::read(self.get_unchecked(self.len())))
1095 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1099 /// Panics if the number of elements in the vector overflows a `usize`.
1104 /// let mut vec = vec![1, 2, 3];
1105 /// let mut vec2 = vec![4, 5, 6];
1106 /// vec.append(&mut vec2);
1107 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1108 /// assert_eq!(vec2, []);
1111 #[stable(feature = "append", since = "1.4.0")]
1112 pub fn append(&mut self, other: &mut Self) {
1114 self.append_elements(other.as_slice() as _);
1119 /// Appends elements to `Self` from other buffer.
1121 unsafe fn append_elements(&mut self, other: *const [T]) {
1122 let count = (*other).len();
1123 self.reserve(count);
1124 let len = self.len();
1125 ptr::copy_nonoverlapping(other as *const T, self.get_unchecked_mut(len), count);
1129 /// Creates a draining iterator that removes the specified range in the vector
1130 /// and yields the removed items.
1132 /// Note 1: The element range is removed even if the iterator is only
1133 /// partially consumed or not consumed at all.
1135 /// Note 2: It is unspecified how many elements are removed from the vector
1136 /// if the `Drain` value is leaked.
1140 /// Panics if the starting point is greater than the end point or if
1141 /// the end point is greater than the length of the vector.
1146 /// let mut v = vec![1, 2, 3];
1147 /// let u: Vec<_> = v.drain(1..).collect();
1148 /// assert_eq!(v, &[1]);
1149 /// assert_eq!(u, &[2, 3]);
1151 /// // A full range clears the vector
1153 /// assert_eq!(v, &[]);
1155 #[stable(feature = "drain", since = "1.6.0")]
1156 pub fn drain<R>(&mut self, range: R) -> Drain<T>
1157 where R: RangeBounds<usize>
1161 // When the Drain is first created, it shortens the length of
1162 // the source vector to make sure no uninitialized or moved-from elements
1163 // are accessible at all if the Drain's destructor never gets to run.
1165 // Drain will ptr::read out the values to remove.
1166 // When finished, remaining tail of the vec is copied back to cover
1167 // the hole, and the vector length is restored to the new length.
1169 let len = self.len();
1170 let start = match range.start() {
1172 Excluded(&n) => n + 1,
1175 let end = match range.end() {
1176 Included(&n) => n + 1,
1180 assert!(start <= end);
1181 assert!(end <= len);
1184 // set self.vec length's to start, to be safe in case Drain is leaked
1185 self.set_len(start);
1186 // Use the borrow in the IterMut to indicate borrowing behavior of the
1187 // whole Drain iterator (like &mut T).
1188 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
1192 tail_len: len - end,
1193 iter: range_slice.iter(),
1194 vec: NonNull::from(self),
1199 /// Clears the vector, removing all values.
1201 /// Note that this method has no effect on the allocated capacity
1207 /// let mut v = vec![1, 2, 3];
1211 /// assert!(v.is_empty());
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 pub fn clear(&mut self) {
1219 /// Returns the number of elements in the vector, also referred to
1220 /// as its 'length'.
1225 /// let a = vec![1, 2, 3];
1226 /// assert_eq!(a.len(), 3);
1229 #[stable(feature = "rust1", since = "1.0.0")]
1230 pub fn len(&self) -> usize {
1234 /// Returns `true` if the vector contains no elements.
1239 /// let mut v = Vec::new();
1240 /// assert!(v.is_empty());
1243 /// assert!(!v.is_empty());
1245 #[stable(feature = "rust1", since = "1.0.0")]
1246 pub fn is_empty(&self) -> bool {
1250 /// Splits the collection into two at the given index.
1252 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1253 /// and the returned `Self` contains elements `[at, len)`.
1255 /// Note that the capacity of `self` does not change.
1259 /// Panics if `at > len`.
1264 /// let mut vec = vec![1,2,3];
1265 /// let vec2 = vec.split_off(1);
1266 /// assert_eq!(vec, [1]);
1267 /// assert_eq!(vec2, [2, 3]);
1270 #[stable(feature = "split_off", since = "1.4.0")]
1271 pub fn split_off(&mut self, at: usize) -> Self {
1272 assert!(at <= self.len(), "`at` out of bounds");
1274 let other_len = self.len - at;
1275 let mut other = Vec::with_capacity(other_len);
1277 // Unsafely `set_len` and copy items to `other`.
1280 other.set_len(other_len);
1282 ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
1289 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1291 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1292 /// difference, with each additional slot filled with the result of
1293 /// calling the closure `f`. The return values from `f` will end up
1294 /// in the `Vec` in the order they have been generated.
1296 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1298 /// This method uses a closure to create new values on every push. If
1299 /// you'd rather [`Clone`] a given value, use [`resize`]. If you want
1300 /// to use the [`Default`] trait to generate values, you can pass
1301 /// [`Default::default()`] as the second argument..
1306 /// #![feature(vec_resize_with)]
1308 /// let mut vec = vec![1, 2, 3];
1309 /// vec.resize_with(5, Default::default);
1310 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1312 /// let mut vec = vec![];
1314 /// vec.resize_with(4, || { p *= 2; p });
1315 /// assert_eq!(vec, [2, 4, 8, 16]);
1318 /// [`resize`]: #method.resize
1319 /// [`Clone`]: ../../std/clone/trait.Clone.html
1320 #[unstable(feature = "vec_resize_with", issue = "41758")]
1321 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1322 where F: FnMut() -> T
1324 let len = self.len();
1326 self.extend_with(new_len - len, ExtendFunc(f));
1328 self.truncate(new_len);
1333 impl<T: Clone> Vec<T> {
1334 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1336 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1337 /// difference, with each additional slot filled with `value`.
1338 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1340 /// This method requires [`Clone`] to be able clone the passed value. If
1341 /// you need more flexibility (or want to rely on [`Default`] instead of
1342 /// [`Clone`]), use [`resize_with`].
1347 /// let mut vec = vec!["hello"];
1348 /// vec.resize(3, "world");
1349 /// assert_eq!(vec, ["hello", "world", "world"]);
1351 /// let mut vec = vec![1, 2, 3, 4];
1352 /// vec.resize(2, 0);
1353 /// assert_eq!(vec, [1, 2]);
1356 /// [`Clone`]: ../../std/clone/trait.Clone.html
1357 /// [`Default`]: ../../std/default/trait.Default.html
1358 /// [`resize_with`]: #method.resize_with
1359 #[stable(feature = "vec_resize", since = "1.5.0")]
1360 pub fn resize(&mut self, new_len: usize, value: T) {
1361 let len = self.len();
1364 self.extend_with(new_len - len, ExtendElement(value))
1366 self.truncate(new_len);
1370 /// Clones and appends all elements in a slice to the `Vec`.
1372 /// Iterates over the slice `other`, clones each element, and then appends
1373 /// it to this `Vec`. The `other` vector is traversed in-order.
1375 /// Note that this function is same as [`extend`] except that it is
1376 /// specialized to work with slices instead. If and when Rust gets
1377 /// specialization this function will likely be deprecated (but still
1383 /// let mut vec = vec![1];
1384 /// vec.extend_from_slice(&[2, 3, 4]);
1385 /// assert_eq!(vec, [1, 2, 3, 4]);
1388 /// [`extend`]: #method.extend
1389 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1390 pub fn extend_from_slice(&mut self, other: &[T]) {
1391 self.spec_extend(other.iter())
1395 impl<T: Default> Vec<T> {
1396 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1398 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1399 /// difference, with each additional slot filled with [`Default::default()`].
1400 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1402 /// This method uses [`Default`] to create new values on every push. If
1403 /// you'd rather [`Clone`] a given value, use [`resize`].
1408 /// #![feature(vec_resize_default)]
1410 /// let mut vec = vec![1, 2, 3];
1411 /// vec.resize_default(5);
1412 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1414 /// let mut vec = vec![1, 2, 3, 4];
1415 /// vec.resize_default(2);
1416 /// assert_eq!(vec, [1, 2]);
1419 /// [`resize`]: #method.resize
1420 /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default
1421 /// [`Default`]: ../../std/default/trait.Default.html
1422 /// [`Clone`]: ../../std/clone/trait.Clone.html
1423 #[unstable(feature = "vec_resize_default", issue = "41758")]
1424 pub fn resize_default(&mut self, new_len: usize) {
1425 let len = self.len();
1428 self.extend_with(new_len - len, ExtendDefault);
1430 self.truncate(new_len);
1435 // This code generalises `extend_with_{element,default}`.
1436 trait ExtendWith<T> {
1437 fn next(&mut self) -> T;
1441 struct ExtendElement<T>(T);
1442 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1443 fn next(&mut self) -> T { self.0.clone() }
1444 fn last(self) -> T { self.0 }
1447 struct ExtendDefault;
1448 impl<T: Default> ExtendWith<T> for ExtendDefault {
1449 fn next(&mut self) -> T { Default::default() }
1450 fn last(self) -> T { Default::default() }
1453 struct ExtendFunc<F>(F);
1454 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1455 fn next(&mut self) -> T { (self.0)() }
1456 fn last(mut self) -> T { (self.0)() }
1460 /// Extend the vector by `n` values, using the given generator.
1461 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1465 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1466 // Use SetLenOnDrop to work around bug where compiler
1467 // may not realize the store through `ptr` through self.set_len()
1469 let mut local_len = SetLenOnDrop::new(&mut self.len);
1471 // Write all elements except the last one
1473 ptr::write(ptr, value.next());
1474 ptr = ptr.offset(1);
1475 // Increment the length in every step in case next() panics
1476 local_len.increment_len(1);
1480 // We can write the last element directly without cloning needlessly
1481 ptr::write(ptr, value.last());
1482 local_len.increment_len(1);
1485 // len set by scope guard
1490 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1492 // The idea is: The length field in SetLenOnDrop is a local variable
1493 // that the optimizer will see does not alias with any stores through the Vec's data
1494 // pointer. This is a workaround for alias analysis issue #32155
1495 struct SetLenOnDrop<'a> {
1500 impl<'a> SetLenOnDrop<'a> {
1502 fn new(len: &'a mut usize) -> Self {
1503 SetLenOnDrop { local_len: *len, len: len }
1507 fn increment_len(&mut self, increment: usize) {
1508 self.local_len += increment;
1512 impl<'a> Drop for SetLenOnDrop<'a> {
1514 fn drop(&mut self) {
1515 *self.len = self.local_len;
1519 impl<T: PartialEq> Vec<T> {
1520 /// Removes consecutive repeated elements in the vector.
1522 /// If the vector is sorted, this removes all duplicates.
1527 /// let mut vec = vec![1, 2, 2, 3, 2];
1531 /// assert_eq!(vec, [1, 2, 3, 2]);
1533 #[stable(feature = "rust1", since = "1.0.0")]
1535 pub fn dedup(&mut self) {
1536 self.dedup_by(|a, b| a == b)
1539 /// Removes the first instance of `item` from the vector if the item exists.
1544 /// # #![feature(vec_remove_item)]
1545 /// let mut vec = vec![1, 2, 3, 1];
1547 /// vec.remove_item(&1);
1549 /// assert_eq!(vec, vec![2, 3, 1]);
1551 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1552 pub fn remove_item(&mut self, item: &T) -> Option<T> {
1553 let pos = self.iter().position(|x| *x == *item)?;
1554 Some(self.remove(pos))
1558 ////////////////////////////////////////////////////////////////////////////////
1559 // Internal methods and functions
1560 ////////////////////////////////////////////////////////////////////////////////
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1565 <T as SpecFromElem>::from_elem(elem, n)
1568 // Specialization trait used for Vec::from_elem
1569 trait SpecFromElem: Sized {
1570 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1573 impl<T: Clone> SpecFromElem for T {
1574 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1575 let mut v = Vec::with_capacity(n);
1576 v.extend_with(n, ExtendElement(elem));
1581 impl SpecFromElem for u8 {
1583 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1586 buf: RawVec::with_capacity_zeroed(n),
1591 let mut v = Vec::with_capacity(n);
1592 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1599 impl<T: Clone + IsZero> SpecFromElem for T {
1601 fn from_elem(elem: T, n: usize) -> Vec<T> {
1604 buf: RawVec::with_capacity_zeroed(n),
1608 let mut v = Vec::with_capacity(n);
1609 v.extend_with(n, ExtendElement(elem));
1614 unsafe trait IsZero {
1615 /// Whether this value is zero
1616 fn is_zero(&self) -> bool;
1619 macro_rules! impl_is_zero {
1620 ($t: ty, $is_zero: expr) => {
1621 unsafe impl IsZero for $t {
1623 fn is_zero(&self) -> bool {
1630 impl_is_zero!(i8, |x| x == 0);
1631 impl_is_zero!(i16, |x| x == 0);
1632 impl_is_zero!(i32, |x| x == 0);
1633 impl_is_zero!(i64, |x| x == 0);
1634 impl_is_zero!(i128, |x| x == 0);
1635 impl_is_zero!(isize, |x| x == 0);
1637 impl_is_zero!(u16, |x| x == 0);
1638 impl_is_zero!(u32, |x| x == 0);
1639 impl_is_zero!(u64, |x| x == 0);
1640 impl_is_zero!(u128, |x| x == 0);
1641 impl_is_zero!(usize, |x| x == 0);
1643 impl_is_zero!(char, |x| x == '\0');
1645 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1646 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1648 unsafe impl<T: ?Sized> IsZero for *const T {
1650 fn is_zero(&self) -> bool {
1655 unsafe impl<T: ?Sized> IsZero for *mut T {
1657 fn is_zero(&self) -> bool {
1663 ////////////////////////////////////////////////////////////////////////////////
1664 // Common trait implementations for Vec
1665 ////////////////////////////////////////////////////////////////////////////////
1667 #[stable(feature = "rust1", since = "1.0.0")]
1668 impl<T: Clone> Clone for Vec<T> {
1670 fn clone(&self) -> Vec<T> {
1671 <[T]>::to_vec(&**self)
1674 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1675 // required for this method definition, is not available. Instead use the
1676 // `slice::to_vec` function which is only available with cfg(test)
1677 // NB see the slice::hack module in slice.rs for more information
1679 fn clone(&self) -> Vec<T> {
1680 ::slice::to_vec(&**self)
1683 fn clone_from(&mut self, other: &Vec<T>) {
1684 other.as_slice().clone_into(self);
1688 #[stable(feature = "rust1", since = "1.0.0")]
1689 impl<T: Hash> Hash for Vec<T> {
1691 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1692 Hash::hash(&**self, state)
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 #[rustc_on_unimplemented = "vector indices are of type `usize` or ranges of `usize`"]
1698 impl<T, I> Index<I> for Vec<T>
1700 I: ::core::slice::SliceIndex<[T]>,
1702 type Output = I::Output;
1705 fn index(&self, index: I) -> &Self::Output {
1706 Index::index(&**self, index)
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 #[rustc_on_unimplemented = "vector indices are of type `usize` or ranges of `usize`"]
1712 impl<T, I> IndexMut<I> for Vec<T>
1714 I: ::core::slice::SliceIndex<[T]>,
1717 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1718 IndexMut::index_mut(&mut **self, index)
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl<T> ops::Deref for Vec<T> {
1726 fn deref(&self) -> &[T] {
1728 let p = self.buf.ptr();
1729 assume(!p.is_null());
1730 slice::from_raw_parts(p, self.len)
1735 #[stable(feature = "rust1", since = "1.0.0")]
1736 impl<T> ops::DerefMut for Vec<T> {
1737 fn deref_mut(&mut self) -> &mut [T] {
1739 let ptr = self.buf.ptr();
1740 assume(!ptr.is_null());
1741 slice::from_raw_parts_mut(ptr, self.len)
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 impl<T> FromIterator<T> for Vec<T> {
1749 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1750 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1754 #[stable(feature = "rust1", since = "1.0.0")]
1755 impl<T> IntoIterator for Vec<T> {
1757 type IntoIter = IntoIter<T>;
1759 /// Creates a consuming iterator, that is, one that moves each value out of
1760 /// the vector (from start to end). The vector cannot be used after calling
1766 /// let v = vec!["a".to_string(), "b".to_string()];
1767 /// for s in v.into_iter() {
1768 /// // s has type String, not &String
1769 /// println!("{}", s);
1773 fn into_iter(mut self) -> IntoIter<T> {
1775 let begin = self.as_mut_ptr();
1776 assume(!begin.is_null());
1777 let end = if mem::size_of::<T>() == 0 {
1778 arith_offset(begin as *const i8, self.len() as isize) as *const T
1780 begin.offset(self.len() as isize) as *const T
1782 let cap = self.buf.cap();
1785 buf: NonNull::new_unchecked(begin),
1786 phantom: PhantomData,
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl<'a, T> IntoIterator for &'a Vec<T> {
1798 type IntoIter = slice::Iter<'a, T>;
1800 fn into_iter(self) -> slice::Iter<'a, T> {
1805 #[stable(feature = "rust1", since = "1.0.0")]
1806 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1807 type Item = &'a mut T;
1808 type IntoIter = slice::IterMut<'a, T>;
1810 fn into_iter(self) -> slice::IterMut<'a, T> {
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 impl<T> Extend<T> for Vec<T> {
1818 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1819 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1823 // Specialization trait used for Vec::from_iter and Vec::extend
1824 trait SpecExtend<T, I> {
1825 fn from_iter(iter: I) -> Self;
1826 fn spec_extend(&mut self, iter: I);
1829 impl<T, I> SpecExtend<T, I> for Vec<T>
1830 where I: Iterator<Item=T>,
1832 default fn from_iter(mut iterator: I) -> Self {
1833 // Unroll the first iteration, as the vector is going to be
1834 // expanded on this iteration in every case when the iterable is not
1835 // empty, but the loop in extend_desugared() is not going to see the
1836 // vector being full in the few subsequent loop iterations.
1837 // So we get better branch prediction.
1838 let mut vector = match iterator.next() {
1839 None => return Vec::new(),
1841 let (lower, _) = iterator.size_hint();
1842 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1844 ptr::write(vector.get_unchecked_mut(0), element);
1850 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1854 default fn spec_extend(&mut self, iter: I) {
1855 self.extend_desugared(iter)
1859 impl<T, I> SpecExtend<T, I> for Vec<T>
1860 where I: TrustedLen<Item=T>,
1862 default fn from_iter(iterator: I) -> Self {
1863 let mut vector = Vec::new();
1864 vector.spec_extend(iterator);
1868 default fn spec_extend(&mut self, iterator: I) {
1869 // This is the case for a TrustedLen iterator.
1870 let (low, high) = iterator.size_hint();
1871 if let Some(high_value) = high {
1872 debug_assert_eq!(low, high_value,
1873 "TrustedLen iterator's size hint is not exact: {:?}",
1876 if let Some(additional) = high {
1877 self.reserve(additional);
1879 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1880 let mut local_len = SetLenOnDrop::new(&mut self.len);
1881 for element in iterator {
1882 ptr::write(ptr, element);
1883 ptr = ptr.offset(1);
1884 // NB can't overflow since we would have had to alloc the address space
1885 local_len.increment_len(1);
1889 self.extend_desugared(iterator)
1894 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
1895 fn from_iter(iterator: IntoIter<T>) -> Self {
1896 // A common case is passing a vector into a function which immediately
1897 // re-collects into a vector. We can short circuit this if the IntoIter
1898 // has not been advanced at all.
1899 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
1901 let vec = Vec::from_raw_parts(iterator.buf.as_ptr(),
1904 mem::forget(iterator);
1908 let mut vector = Vec::new();
1909 vector.spec_extend(iterator);
1914 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
1916 self.append_elements(iterator.as_slice() as _);
1918 iterator.ptr = iterator.end;
1922 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
1923 where I: Iterator<Item=&'a T>,
1926 default fn from_iter(iterator: I) -> Self {
1927 SpecExtend::from_iter(iterator.cloned())
1930 default fn spec_extend(&mut self, iterator: I) {
1931 self.spec_extend(iterator.cloned())
1935 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
1938 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
1939 let slice = iterator.as_slice();
1940 self.reserve(slice.len());
1942 let len = self.len();
1943 self.set_len(len + slice.len());
1944 self.get_unchecked_mut(len..).copy_from_slice(slice);
1950 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1951 // This is the case for a general iterator.
1953 // This function should be the moral equivalent of:
1955 // for item in iterator {
1958 while let Some(element) = iterator.next() {
1959 let len = self.len();
1960 if len == self.capacity() {
1961 let (lower, _) = iterator.size_hint();
1962 self.reserve(lower.saturating_add(1));
1965 ptr::write(self.get_unchecked_mut(len), element);
1966 // NB can't overflow since we would have had to alloc the address space
1967 self.set_len(len + 1);
1972 /// Creates a splicing iterator that replaces the specified range in the vector
1973 /// with the given `replace_with` iterator and yields the removed items.
1974 /// `replace_with` does not need to be the same length as `range`.
1976 /// Note 1: The element range is removed even if the iterator is not
1977 /// consumed until the end.
1979 /// Note 2: It is unspecified how many elements are removed from the vector,
1980 /// if the `Splice` value is leaked.
1982 /// Note 3: The input iterator `replace_with` is only consumed
1983 /// when the `Splice` value is dropped.
1985 /// Note 4: This is optimal if:
1987 /// * The tail (elements in the vector after `range`) is empty,
1988 /// * or `replace_with` yields fewer elements than `range`’s length
1989 /// * or the lower bound of its `size_hint()` is exact.
1991 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
1995 /// Panics if the starting point is greater than the end point or if
1996 /// the end point is greater than the length of the vector.
2001 /// let mut v = vec![1, 2, 3];
2002 /// let new = [7, 8];
2003 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2004 /// assert_eq!(v, &[7, 8, 3]);
2005 /// assert_eq!(u, &[1, 2]);
2008 #[stable(feature = "vec_splice", since = "1.21.0")]
2009 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<I::IntoIter>
2010 where R: RangeBounds<usize>, I: IntoIterator<Item=T>
2013 drain: self.drain(range),
2014 replace_with: replace_with.into_iter(),
2018 /// Creates an iterator which uses a closure to determine if an element should be removed.
2020 /// If the closure returns true, then the element is removed and yielded.
2021 /// If the closure returns false, the element will remain in the vector and will not be yielded
2022 /// by the iterator.
2024 /// Using this method is equivalent to the following code:
2027 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2028 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2030 /// while i != vec.len() {
2031 /// if some_predicate(&mut vec[i]) {
2032 /// let val = vec.remove(i);
2033 /// // your code here
2039 /// # assert_eq!(vec, vec![1, 4, 5]);
2042 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2043 /// because it can backshift the elements of the array in bulk.
2045 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2046 /// regardless of whether you choose to keep or remove it.
2051 /// Splitting an array into evens and odds, reusing the original allocation:
2054 /// #![feature(drain_filter)]
2055 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2057 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2058 /// let odds = numbers;
2060 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2061 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2063 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2064 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<T, F>
2065 where F: FnMut(&mut T) -> bool,
2067 let old_len = self.len();
2069 // Guard against us getting leaked (leak amplification)
2070 unsafe { self.set_len(0); }
2082 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2084 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2085 /// append the entire slice at once.
2087 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2088 #[stable(feature = "extend_ref", since = "1.2.0")]
2089 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2090 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2091 self.spec_extend(iter.into_iter())
2095 macro_rules! __impl_slice_eq1 {
2096 ($Lhs: ty, $Rhs: ty) => {
2097 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2099 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2100 #[stable(feature = "rust1", since = "1.0.0")]
2101 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2103 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
2105 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
2110 __impl_slice_eq1! { Vec<A>, Vec<B> }
2111 __impl_slice_eq1! { Vec<A>, &'b [B] }
2112 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
2113 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
2114 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
2115 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
2117 macro_rules! array_impls {
2120 // NOTE: some less important impls are omitted to reduce code bloat
2121 __impl_slice_eq1! { Vec<A>, [B; $N] }
2122 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
2123 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
2124 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
2125 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
2126 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
2133 10 11 12 13 14 15 16 17 18 19
2134 20 21 22 23 24 25 26 27 28 29
2138 /// Implements comparison of vectors, lexicographically.
2139 #[stable(feature = "rust1", since = "1.0.0")]
2140 impl<T: PartialOrd> PartialOrd for Vec<T> {
2142 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2143 PartialOrd::partial_cmp(&**self, &**other)
2147 #[stable(feature = "rust1", since = "1.0.0")]
2148 impl<T: Eq> Eq for Vec<T> {}
2150 /// Implements ordering of vectors, lexicographically.
2151 #[stable(feature = "rust1", since = "1.0.0")]
2152 impl<T: Ord> Ord for Vec<T> {
2154 fn cmp(&self, other: &Vec<T>) -> Ordering {
2155 Ord::cmp(&**self, &**other)
2159 #[stable(feature = "rust1", since = "1.0.0")]
2160 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2161 fn drop(&mut self) {
2164 ptr::drop_in_place(&mut self[..]);
2166 // RawVec handles deallocation
2170 #[stable(feature = "rust1", since = "1.0.0")]
2171 impl<T> Default for Vec<T> {
2172 /// Creates an empty `Vec<T>`.
2173 fn default() -> Vec<T> {
2178 #[stable(feature = "rust1", since = "1.0.0")]
2179 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2180 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2181 fmt::Debug::fmt(&**self, f)
2185 #[stable(feature = "rust1", since = "1.0.0")]
2186 impl<T> AsRef<Vec<T>> for Vec<T> {
2187 fn as_ref(&self) -> &Vec<T> {
2192 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2193 impl<T> AsMut<Vec<T>> for Vec<T> {
2194 fn as_mut(&mut self) -> &mut Vec<T> {
2199 #[stable(feature = "rust1", since = "1.0.0")]
2200 impl<T> AsRef<[T]> for Vec<T> {
2201 fn as_ref(&self) -> &[T] {
2206 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2207 impl<T> AsMut<[T]> for Vec<T> {
2208 fn as_mut(&mut self) -> &mut [T] {
2213 #[stable(feature = "rust1", since = "1.0.0")]
2214 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
2216 fn from(s: &'a [T]) -> Vec<T> {
2220 fn from(s: &'a [T]) -> Vec<T> {
2225 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2226 impl<'a, T: Clone> From<&'a mut [T]> for Vec<T> {
2228 fn from(s: &'a mut [T]) -> Vec<T> {
2232 fn from(s: &'a mut [T]) -> Vec<T> {
2237 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2238 impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> {
2239 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2244 // note: test pulls in libstd, which causes errors here
2246 #[stable(feature = "vec_from_box", since = "1.18.0")]
2247 impl<T> From<Box<[T]>> for Vec<T> {
2248 fn from(s: Box<[T]>) -> Vec<T> {
2253 // note: test pulls in libstd, which causes errors here
2255 #[stable(feature = "box_from_vec", since = "1.20.0")]
2256 impl<T> From<Vec<T>> for Box<[T]> {
2257 fn from(v: Vec<T>) -> Box<[T]> {
2258 v.into_boxed_slice()
2262 #[stable(feature = "rust1", since = "1.0.0")]
2263 impl<'a> From<&'a str> for Vec<u8> {
2264 fn from(s: &'a str) -> Vec<u8> {
2265 From::from(s.as_bytes())
2269 ////////////////////////////////////////////////////////////////////////////////
2271 ////////////////////////////////////////////////////////////////////////////////
2273 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2274 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2275 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2280 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2281 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2282 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2287 #[stable(feature = "rust1", since = "1.0.0")]
2288 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
2289 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2290 Cow::Owned(FromIterator::from_iter(it))
2294 ////////////////////////////////////////////////////////////////////////////////
2296 ////////////////////////////////////////////////////////////////////////////////
2298 /// An iterator that moves out of a vector.
2300 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2301 /// by the [`IntoIterator`] trait).
2303 /// [`Vec`]: struct.Vec.html
2304 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2305 #[stable(feature = "rust1", since = "1.0.0")]
2306 pub struct IntoIter<T> {
2308 phantom: PhantomData<T>,
2314 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2315 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2316 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2317 f.debug_tuple("IntoIter")
2318 .field(&self.as_slice())
2323 impl<T> IntoIter<T> {
2324 /// Returns the remaining items of this iterator as a slice.
2329 /// let vec = vec!['a', 'b', 'c'];
2330 /// let mut into_iter = vec.into_iter();
2331 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2332 /// let _ = into_iter.next().unwrap();
2333 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2335 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2336 pub fn as_slice(&self) -> &[T] {
2338 slice::from_raw_parts(self.ptr, self.len())
2342 /// Returns the remaining items of this iterator as a mutable slice.
2347 /// let vec = vec!['a', 'b', 'c'];
2348 /// let mut into_iter = vec.into_iter();
2349 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2350 /// into_iter.as_mut_slice()[2] = 'z';
2351 /// assert_eq!(into_iter.next().unwrap(), 'a');
2352 /// assert_eq!(into_iter.next().unwrap(), 'b');
2353 /// assert_eq!(into_iter.next().unwrap(), 'z');
2355 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2356 pub fn as_mut_slice(&mut self) -> &mut [T] {
2358 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
2363 #[stable(feature = "rust1", since = "1.0.0")]
2364 unsafe impl<T: Send> Send for IntoIter<T> {}
2365 #[stable(feature = "rust1", since = "1.0.0")]
2366 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2368 #[stable(feature = "rust1", since = "1.0.0")]
2369 impl<T> Iterator for IntoIter<T> {
2373 fn next(&mut self) -> Option<T> {
2375 if self.ptr as *const _ == self.end {
2378 if mem::size_of::<T>() == 0 {
2379 // purposefully don't use 'ptr.offset' because for
2380 // vectors with 0-size elements this would return the
2382 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2384 // Use a non-null pointer value
2385 // (self.ptr might be null because of wrapping)
2386 Some(ptr::read(1 as *mut T))
2389 self.ptr = self.ptr.offset(1);
2391 Some(ptr::read(old))
2398 fn size_hint(&self) -> (usize, Option<usize>) {
2399 let exact = if mem::size_of::<T>() == 0 {
2400 (self.end as usize).wrapping_sub(self.ptr as usize)
2402 unsafe { self.end.offset_from(self.ptr) as usize }
2404 (exact, Some(exact))
2408 fn count(self) -> usize {
2413 #[stable(feature = "rust1", since = "1.0.0")]
2414 impl<T> DoubleEndedIterator for IntoIter<T> {
2416 fn next_back(&mut self) -> Option<T> {
2418 if self.end == self.ptr {
2421 if mem::size_of::<T>() == 0 {
2422 // See above for why 'ptr.offset' isn't used
2423 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2425 // Use a non-null pointer value
2426 // (self.end might be null because of wrapping)
2427 Some(ptr::read(1 as *mut T))
2429 self.end = self.end.offset(-1);
2431 Some(ptr::read(self.end))
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 impl<T> ExactSizeIterator for IntoIter<T> {
2440 fn is_empty(&self) -> bool {
2441 self.ptr == self.end
2445 #[stable(feature = "fused", since = "1.26.0")]
2446 impl<T> FusedIterator for IntoIter<T> {}
2448 #[unstable(feature = "trusted_len", issue = "37572")]
2449 unsafe impl<T> TrustedLen for IntoIter<T> {}
2451 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2452 impl<T: Clone> Clone for IntoIter<T> {
2453 fn clone(&self) -> IntoIter<T> {
2454 self.as_slice().to_owned().into_iter()
2458 #[stable(feature = "rust1", since = "1.0.0")]
2459 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2460 fn drop(&mut self) {
2461 // destroy the remaining elements
2462 for _x in self.by_ref() {}
2464 // RawVec handles deallocation
2465 let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) };
2469 /// A draining iterator for `Vec<T>`.
2471 /// This `struct` is created by the [`drain`] method on [`Vec`].
2473 /// [`drain`]: struct.Vec.html#method.drain
2474 /// [`Vec`]: struct.Vec.html
2475 #[stable(feature = "drain", since = "1.6.0")]
2476 pub struct Drain<'a, T: 'a> {
2477 /// Index of tail to preserve
2481 /// Current remaining range to remove
2482 iter: slice::Iter<'a, T>,
2483 vec: NonNull<Vec<T>>,
2486 #[stable(feature = "collection_debug", since = "1.17.0")]
2487 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2488 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2489 f.debug_tuple("Drain")
2490 .field(&self.iter.as_slice())
2495 #[stable(feature = "drain", since = "1.6.0")]
2496 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2497 #[stable(feature = "drain", since = "1.6.0")]
2498 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2500 #[stable(feature = "drain", since = "1.6.0")]
2501 impl<'a, T> Iterator for Drain<'a, T> {
2505 fn next(&mut self) -> Option<T> {
2506 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2509 fn size_hint(&self) -> (usize, Option<usize>) {
2510 self.iter.size_hint()
2514 #[stable(feature = "drain", since = "1.6.0")]
2515 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
2517 fn next_back(&mut self) -> Option<T> {
2518 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2522 #[stable(feature = "drain", since = "1.6.0")]
2523 impl<'a, T> Drop for Drain<'a, T> {
2524 fn drop(&mut self) {
2525 // exhaust self first
2526 self.for_each(drop);
2528 if self.tail_len > 0 {
2530 let source_vec = self.vec.as_mut();
2531 // memmove back untouched tail, update to new length
2532 let start = source_vec.len();
2533 let tail = self.tail_start;
2534 let src = source_vec.as_ptr().offset(tail as isize);
2535 let dst = source_vec.as_mut_ptr().offset(start as isize);
2536 ptr::copy(src, dst, self.tail_len);
2537 source_vec.set_len(start + self.tail_len);
2544 #[stable(feature = "drain", since = "1.6.0")]
2545 impl<'a, T> ExactSizeIterator for Drain<'a, T> {
2546 fn is_empty(&self) -> bool {
2547 self.iter.is_empty()
2551 #[stable(feature = "fused", since = "1.26.0")]
2552 impl<'a, T> FusedIterator for Drain<'a, T> {}
2554 /// A splicing iterator for `Vec`.
2556 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2557 /// documentation for more.
2559 /// [`splice()`]: struct.Vec.html#method.splice
2560 /// [`Vec`]: struct.Vec.html
2562 #[stable(feature = "vec_splice", since = "1.21.0")]
2563 pub struct Splice<'a, I: Iterator + 'a> {
2564 drain: Drain<'a, I::Item>,
2568 #[stable(feature = "vec_splice", since = "1.21.0")]
2569 impl<'a, I: Iterator> Iterator for Splice<'a, I> {
2570 type Item = I::Item;
2572 fn next(&mut self) -> Option<Self::Item> {
2576 fn size_hint(&self) -> (usize, Option<usize>) {
2577 self.drain.size_hint()
2581 #[stable(feature = "vec_splice", since = "1.21.0")]
2582 impl<'a, I: Iterator> DoubleEndedIterator for Splice<'a, I> {
2583 fn next_back(&mut self) -> Option<Self::Item> {
2584 self.drain.next_back()
2588 #[stable(feature = "vec_splice", since = "1.21.0")]
2589 impl<'a, I: Iterator> ExactSizeIterator for Splice<'a, I> {}
2592 #[stable(feature = "vec_splice", since = "1.21.0")]
2593 impl<'a, I: Iterator> Drop for Splice<'a, I> {
2594 fn drop(&mut self) {
2595 self.drain.by_ref().for_each(drop);
2598 if self.drain.tail_len == 0 {
2599 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2603 // First fill the range left by drain().
2604 if !self.drain.fill(&mut self.replace_with) {
2608 // There may be more elements. Use the lower bound as an estimate.
2609 // FIXME: Is the upper bound a better guess? Or something else?
2610 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2611 if lower_bound > 0 {
2612 self.drain.move_tail(lower_bound);
2613 if !self.drain.fill(&mut self.replace_with) {
2618 // Collect any remaining elements.
2619 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2620 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2621 // Now we have an exact count.
2622 if collected.len() > 0 {
2623 self.drain.move_tail(collected.len());
2624 let filled = self.drain.fill(&mut collected);
2625 debug_assert!(filled);
2626 debug_assert_eq!(collected.len(), 0);
2629 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2633 /// Private helper methods for `Splice::drop`
2634 impl<'a, T> Drain<'a, T> {
2635 /// The range from `self.vec.len` to `self.tail_start` contains elements
2636 /// that have been moved out.
2637 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2638 /// Return whether we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2639 unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
2640 let vec = self.vec.as_mut();
2641 let range_start = vec.len;
2642 let range_end = self.tail_start;
2643 let range_slice = slice::from_raw_parts_mut(
2644 vec.as_mut_ptr().offset(range_start as isize),
2645 range_end - range_start);
2647 for place in range_slice {
2648 if let Some(new_item) = replace_with.next() {
2649 ptr::write(place, new_item);
2658 /// Make room for inserting more elements before the tail.
2659 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2660 let vec = self.vec.as_mut();
2661 let used_capacity = self.tail_start + self.tail_len;
2662 vec.buf.reserve(used_capacity, extra_capacity);
2664 let new_tail_start = self.tail_start + extra_capacity;
2665 let src = vec.as_ptr().offset(self.tail_start as isize);
2666 let dst = vec.as_mut_ptr().offset(new_tail_start as isize);
2667 ptr::copy(src, dst, self.tail_len);
2668 self.tail_start = new_tail_start;
2672 /// An iterator produced by calling `drain_filter` on Vec.
2673 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2675 pub struct DrainFilter<'a, T: 'a, F>
2676 where F: FnMut(&mut T) -> bool,
2678 vec: &'a mut Vec<T>,
2685 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2686 impl<'a, T, F> Iterator for DrainFilter<'a, T, F>
2687 where F: FnMut(&mut T) -> bool,
2691 fn next(&mut self) -> Option<T> {
2693 while self.idx != self.old_len {
2696 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
2697 if (self.pred)(&mut v[i]) {
2699 return Some(ptr::read(&v[i]));
2700 } else if self.del > 0 {
2702 let src: *const T = &v[i];
2703 let dst: *mut T = &mut v[i - del];
2704 // This is safe because self.vec has length 0
2705 // thus its elements will not have Drop::drop
2706 // called on them in the event of a panic.
2707 ptr::copy_nonoverlapping(src, dst, 1);
2714 fn size_hint(&self) -> (usize, Option<usize>) {
2715 (0, Some(self.old_len - self.idx))
2719 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2720 impl<'a, T, F> Drop for DrainFilter<'a, T, F>
2721 where F: FnMut(&mut T) -> bool,
2723 fn drop(&mut self) {
2724 self.for_each(drop);
2726 self.vec.set_len(self.old_len - self.del);