1 //! A contiguous growable array type with heap-allocated contents, written
4 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
5 //! `O(1)` pop (from the end).
9 //! You can explicitly create a [`Vec<T>`] with [`new`]:
12 //! let v: Vec<i32> = Vec::new();
15 //! ...or by using the [`vec!`] macro:
18 //! let v: Vec<i32> = vec![];
20 //! let v = vec![1, 2, 3, 4, 5];
22 //! let v = vec![0; 10]; // ten zeroes
25 //! You can [`push`] values onto the end of a vector (which will grow the vector
29 //! let mut v = vec![1, 2];
34 //! Popping values works in much the same way:
37 //! let mut v = vec![1, 2];
39 //! let two = v.pop();
42 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
45 //! let mut v = vec![1, 2, 3];
50 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
51 //! [`new`]: ../../std/vec/struct.Vec.html#method.new
52 //! [`push`]: ../../std/vec/struct.Vec.html#method.push
53 //! [`Index`]: ../../std/ops/trait.Index.html
54 //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
55 //! [`vec!`]: ../../std/macro.vec.html
57 #![stable(feature = "rust1", since = "1.0.0")]
59 use core::array::LengthAtMost32;
60 use core::cmp::{self, Ordering};
62 use core::hash::{self, Hash};
63 use core::intrinsics::{arith_offset, assume};
64 use core::iter::{FromIterator, FusedIterator, TrustedLen};
65 use core::marker::PhantomData;
67 use core::ops::{self, Index, IndexMut, RangeBounds};
68 use core::ops::Bound::{Excluded, Included, Unbounded};
69 use core::ptr::{self, NonNull};
70 use core::slice::{self, SliceIndex};
72 use crate::borrow::{ToOwned, Cow};
73 use crate::collections::TryReserveError;
74 use crate::boxed::Box;
75 use crate::raw_vec::RawVec;
77 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
82 /// let mut vec = Vec::new();
86 /// assert_eq!(vec.len(), 2);
87 /// assert_eq!(vec[0], 1);
89 /// assert_eq!(vec.pop(), Some(2));
90 /// assert_eq!(vec.len(), 1);
93 /// assert_eq!(vec[0], 7);
95 /// vec.extend([1, 2, 3].iter().cloned());
98 /// println!("{}", x);
100 /// assert_eq!(vec, [7, 1, 2, 3]);
103 /// The [`vec!`] macro is provided to make initialization more convenient:
106 /// let mut vec = vec![1, 2, 3];
108 /// assert_eq!(vec, [1, 2, 3, 4]);
111 /// It can also initialize each element of a `Vec<T>` with a given value.
112 /// This may be more efficient than performing allocation and initialization
113 /// in separate steps, especially when initializing a vector of zeros:
116 /// let vec = vec![0; 5];
117 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
119 /// // The following is equivalent, but potentially slower:
120 /// let mut vec1 = Vec::with_capacity(5);
121 /// vec1.resize(5, 0);
124 /// Use a `Vec<T>` as an efficient stack:
127 /// let mut stack = Vec::new();
133 /// while let Some(top) = stack.pop() {
134 /// // Prints 3, 2, 1
135 /// println!("{}", top);
141 /// The `Vec` type allows to access values by index, because it implements the
142 /// [`Index`] trait. An example will be more explicit:
145 /// let v = vec![0, 2, 4, 6];
146 /// println!("{}", v[1]); // it will display '2'
149 /// However be careful: if you try to access an index which isn't in the `Vec`,
150 /// your software will panic! You cannot do this:
153 /// let v = vec![0, 2, 4, 6];
154 /// println!("{}", v[6]); // it will panic!
157 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
162 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
163 /// To get a slice, use `&`. Example:
166 /// fn read_slice(slice: &[usize]) {
170 /// let v = vec![0, 1];
173 /// // ... and that's all!
174 /// // you can also do it like this:
175 /// let x : &[usize] = &v;
178 /// In Rust, it's more common to pass slices as arguments rather than vectors
179 /// when you just want to provide a read access. The same goes for [`String`] and
182 /// # Capacity and reallocation
184 /// The capacity of a vector is the amount of space allocated for any future
185 /// elements that will be added onto the vector. This is not to be confused with
186 /// the *length* of a vector, which specifies the number of actual elements
187 /// within the vector. If a vector's length exceeds its capacity, its capacity
188 /// will automatically be increased, but its elements will have to be
191 /// For example, a vector with capacity 10 and length 0 would be an empty vector
192 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
193 /// vector will not change its capacity or cause reallocation to occur. However,
194 /// if the vector's length is increased to 11, it will have to reallocate, which
195 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
196 /// whenever possible to specify how big the vector is expected to get.
200 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
201 /// about its design. This ensures that it's as low-overhead as possible in
202 /// the general case, and can be correctly manipulated in primitive ways
203 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
204 /// If additional type parameters are added (e.g., to support custom allocators),
205 /// overriding their defaults may change the behavior.
207 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
208 /// triplet. No more, no less. The order of these fields is completely
209 /// unspecified, and you should use the appropriate methods to modify these.
210 /// The pointer will never be null, so this type is null-pointer-optimized.
212 /// However, the pointer may not actually point to allocated memory. In particular,
213 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
214 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
215 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
216 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
217 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
218 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
219 /// details are very subtle — if you intend to allocate memory using a `Vec`
220 /// and use it for something else (either to pass to unsafe code, or to build your
221 /// own memory-backed collection), be sure to deallocate this memory by using
222 /// `from_raw_parts` to recover the `Vec` and then dropping it.
224 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
225 /// (as defined by the allocator Rust is configured to use by default), and its
226 /// pointer points to [`len`] initialized, contiguous elements in order (what
227 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
228 /// `[`len`] logically uninitialized, contiguous elements.
230 /// `Vec` will never perform a "small optimization" where elements are actually
231 /// stored on the stack for two reasons:
233 /// * It would make it more difficult for unsafe code to correctly manipulate
234 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
235 /// only moved, and it would be more difficult to determine if a `Vec` had
236 /// actually allocated memory.
238 /// * It would penalize the general case, incurring an additional branch
241 /// `Vec` will never automatically shrink itself, even if completely empty. This
242 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
243 /// and then filling it back up to the same [`len`] should incur no calls to
244 /// the allocator. If you wish to free up unused memory, use
245 /// [`shrink_to_fit`][`shrink_to_fit`].
247 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
248 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
249 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
250 /// accurate, and can be relied on. It can even be used to manually free the memory
251 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
252 /// when not necessary.
254 /// `Vec` does not guarantee any particular growth strategy when reallocating
255 /// when full, nor when [`reserve`] is called. The current strategy is basic
256 /// and it may prove desirable to use a non-constant growth factor. Whatever
257 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
259 /// `vec![x; n]`, `vec![a, b, c, d]`, and
260 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
261 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
262 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
263 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
265 /// `Vec` will not specifically overwrite any data that is removed from it,
266 /// but also won't specifically preserve it. Its uninitialized memory is
267 /// scratch space that it may use however it wants. It will generally just do
268 /// whatever is most efficient or otherwise easy to implement. Do not rely on
269 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
270 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
271 /// first, that may not actually happen because the optimizer does not consider
272 /// this a side-effect that must be preserved. There is one case which we will
273 /// not break, however: using `unsafe` code to write to the excess capacity,
274 /// and then increasing the length to match, is always valid.
276 /// `Vec` does not currently guarantee the order in which elements are dropped.
277 /// The order has changed in the past and may change again.
279 /// [`vec!`]: ../../std/macro.vec.html
280 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
281 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
282 /// [`Index`]: ../../std/ops/trait.Index.html
283 /// [`String`]: ../../std/string/struct.String.html
284 /// [`&str`]: ../../std/primitive.str.html
285 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
286 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
287 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
288 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
289 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
290 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
291 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
292 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
293 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
294 /// [owned slice]: ../../std/boxed/struct.Box.html
295 #[stable(feature = "rust1", since = "1.0.0")]
296 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
302 ////////////////////////////////////////////////////////////////////////////////
304 ////////////////////////////////////////////////////////////////////////////////
307 /// Constructs a new, empty `Vec<T>`.
309 /// The vector will not allocate until elements are pushed onto it.
314 /// # #![allow(unused_mut)]
315 /// let mut vec: Vec<i32> = Vec::new();
318 #[stable(feature = "rust1", since = "1.0.0")]
319 pub const fn new() -> Vec<T> {
326 /// Constructs a new, empty `Vec<T>` with the specified capacity.
328 /// The vector will be able to hold exactly `capacity` elements without
329 /// reallocating. If `capacity` is 0, the vector will not allocate.
331 /// It is important to note that although the returned vector has the
332 /// *capacity* specified, the vector will have a zero *length*. For an
333 /// explanation of the difference between length and capacity, see
334 /// *[Capacity and reallocation]*.
336 /// [Capacity and reallocation]: #capacity-and-reallocation
341 /// let mut vec = Vec::with_capacity(10);
343 /// // The vector contains no items, even though it has capacity for more
344 /// assert_eq!(vec.len(), 0);
346 /// // These are all done without reallocating...
351 /// // ...but this may make the vector reallocate
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn with_capacity(capacity: usize) -> Vec<T> {
358 buf: RawVec::with_capacity(capacity),
363 /// Decomposes a `Vec<T>` into its raw components.
365 /// Returns the raw pointer to the underlying data, the length of
366 /// the vector (in elements), and the allocated capacity of the
367 /// data (in elements). These are the same arguments in the same
368 /// order as the arguments to [`from_raw_parts`].
370 /// After calling this function, the caller is responsible for the
371 /// memory previously managed by the `Vec`. The only way to do
372 /// this is to convert the raw pointer, length, and capacity back
373 /// into a `Vec` with the [`from_raw_parts`] function, allowing
374 /// the destructor to perform the cleanup.
376 /// [`from_raw_parts`]: #method.from_raw_parts
381 /// #![feature(vec_into_raw_parts)]
382 /// let v: Vec<i32> = vec![-1, 0, 1];
384 /// let (ptr, len, cap) = v.into_raw_parts();
386 /// let rebuilt = unsafe {
387 /// // We can now make changes to the components, such as
388 /// // transmuting the raw pointer to a compatible type.
389 /// let ptr = ptr as *mut u32;
391 /// Vec::from_raw_parts(ptr, len, cap)
393 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
395 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
396 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
397 let mut me = mem::ManuallyDrop::new(self);
398 (me.as_mut_ptr(), me.len(), me.capacity())
401 /// Creates a `Vec<T>` directly from the raw components of another vector.
405 /// This is highly unsafe, due to the number of invariants that aren't
408 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
409 /// (at least, it's highly likely to be incorrect if it wasn't).
410 /// * `ptr`'s `T` needs to have the same size and alignment as it was allocated with.
411 /// * `length` needs to be less than or equal to `capacity`.
412 /// * `capacity` needs to be the capacity that the pointer was allocated with.
414 /// Violating these may cause problems like corrupting the allocator's
415 /// internal data structures. For example it is **not** safe
416 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
417 /// It's also not safe to build one from a `Vec<u16>` and its length, because
418 /// the allocator cares about the alignment, and these two types have different
419 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
420 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
422 /// The ownership of `ptr` is effectively transferred to the
423 /// `Vec<T>` which may then deallocate, reallocate or change the
424 /// contents of memory pointed to by the pointer at will. Ensure
425 /// that nothing else uses the pointer after calling this
428 /// [`String`]: ../../std/string/struct.String.html
436 /// let v = vec![1, 2, 3];
438 // FIXME Update this when vec_into_raw_parts is stabilized
439 /// // Prevent running `v`'s destructor so we are in complete control
440 /// // of the allocation.
441 /// let mut v = mem::ManuallyDrop::new(v);
443 /// // Pull out the various important pieces of information about `v`
444 /// let p = v.as_mut_ptr();
445 /// let len = v.len();
446 /// let cap = v.capacity();
449 /// // Overwrite memory with 4, 5, 6
450 /// for i in 0..len as isize {
451 /// ptr::write(p.offset(i), 4 + i);
454 /// // Put everything back together into a Vec
455 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
456 /// assert_eq!(rebuilt, [4, 5, 6]);
459 #[stable(feature = "rust1", since = "1.0.0")]
460 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
462 buf: RawVec::from_raw_parts(ptr, capacity),
467 /// Returns the number of elements the vector can hold without
473 /// let vec: Vec<i32> = Vec::with_capacity(10);
474 /// assert_eq!(vec.capacity(), 10);
477 #[stable(feature = "rust1", since = "1.0.0")]
478 pub fn capacity(&self) -> usize {
482 /// Reserves capacity for at least `additional` more elements to be inserted
483 /// in the given `Vec<T>`. The collection may reserve more space to avoid
484 /// frequent reallocations. After calling `reserve`, capacity will be
485 /// greater than or equal to `self.len() + additional`. Does nothing if
486 /// capacity is already sufficient.
490 /// Panics if the new capacity overflows `usize`.
495 /// let mut vec = vec![1];
497 /// assert!(vec.capacity() >= 11);
499 #[stable(feature = "rust1", since = "1.0.0")]
500 pub fn reserve(&mut self, additional: usize) {
501 self.buf.reserve(self.len, additional);
504 /// Reserves the minimum capacity for exactly `additional` more elements to
505 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
506 /// capacity will be greater than or equal to `self.len() + additional`.
507 /// Does nothing if the capacity is already sufficient.
509 /// Note that the allocator may give the collection more space than it
510 /// requests. Therefore, capacity can not be relied upon to be precisely
511 /// minimal. Prefer `reserve` if future insertions are expected.
515 /// Panics if the new capacity overflows `usize`.
520 /// let mut vec = vec![1];
521 /// vec.reserve_exact(10);
522 /// assert!(vec.capacity() >= 11);
524 #[stable(feature = "rust1", since = "1.0.0")]
525 pub fn reserve_exact(&mut self, additional: usize) {
526 self.buf.reserve_exact(self.len, additional);
529 /// Tries to reserve capacity for at least `additional` more elements to be inserted
530 /// in the given `Vec<T>`. The collection may reserve more space to avoid
531 /// frequent reallocations. After calling `reserve`, capacity will be
532 /// greater than or equal to `self.len() + additional`. Does nothing if
533 /// capacity is already sufficient.
537 /// If the capacity overflows, or the allocator reports a failure, then an error
543 /// #![feature(try_reserve)]
544 /// use std::collections::TryReserveError;
546 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
547 /// let mut output = Vec::new();
549 /// // Pre-reserve the memory, exiting if we can't
550 /// output.try_reserve(data.len())?;
552 /// // Now we know this can't OOM in the middle of our complex work
553 /// output.extend(data.iter().map(|&val| {
554 /// val * 2 + 5 // very complicated
559 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
561 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
562 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
563 self.buf.try_reserve(self.len, additional)
566 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
567 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
568 /// capacity will be greater than or equal to `self.len() + additional`.
569 /// Does nothing if the capacity is already sufficient.
571 /// Note that the allocator may give the collection more space than it
572 /// requests. Therefore, capacity can not be relied upon to be precisely
573 /// minimal. Prefer `reserve` if future insertions are expected.
577 /// If the capacity overflows, or the allocator reports a failure, then an error
583 /// #![feature(try_reserve)]
584 /// use std::collections::TryReserveError;
586 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
587 /// let mut output = Vec::new();
589 /// // Pre-reserve the memory, exiting if we can't
590 /// output.try_reserve(data.len())?;
592 /// // Now we know this can't OOM in the middle of our complex work
593 /// output.extend(data.iter().map(|&val| {
594 /// val * 2 + 5 // very complicated
599 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
601 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
602 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
603 self.buf.try_reserve_exact(self.len, additional)
606 /// Shrinks the capacity of the vector as much as possible.
608 /// It will drop down as close as possible to the length but the allocator
609 /// may still inform the vector that there is space for a few more elements.
614 /// let mut vec = Vec::with_capacity(10);
615 /// vec.extend([1, 2, 3].iter().cloned());
616 /// assert_eq!(vec.capacity(), 10);
617 /// vec.shrink_to_fit();
618 /// assert!(vec.capacity() >= 3);
620 #[stable(feature = "rust1", since = "1.0.0")]
621 pub fn shrink_to_fit(&mut self) {
622 if self.capacity() != self.len {
623 self.buf.shrink_to_fit(self.len);
627 /// Shrinks the capacity of the vector with a lower bound.
629 /// The capacity will remain at least as large as both the length
630 /// and the supplied value.
632 /// Panics if the current capacity is smaller than the supplied
633 /// minimum capacity.
638 /// #![feature(shrink_to)]
639 /// let mut vec = Vec::with_capacity(10);
640 /// vec.extend([1, 2, 3].iter().cloned());
641 /// assert_eq!(vec.capacity(), 10);
642 /// vec.shrink_to(4);
643 /// assert!(vec.capacity() >= 4);
644 /// vec.shrink_to(0);
645 /// assert!(vec.capacity() >= 3);
647 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
648 pub fn shrink_to(&mut self, min_capacity: usize) {
649 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
652 /// Converts the vector into [`Box<[T]>`][owned slice].
654 /// Note that this will drop any excess capacity.
656 /// [owned slice]: ../../std/boxed/struct.Box.html
661 /// let v = vec![1, 2, 3];
663 /// let slice = v.into_boxed_slice();
666 /// Any excess capacity is removed:
669 /// let mut vec = Vec::with_capacity(10);
670 /// vec.extend([1, 2, 3].iter().cloned());
672 /// assert_eq!(vec.capacity(), 10);
673 /// let slice = vec.into_boxed_slice();
674 /// assert_eq!(slice.into_vec().capacity(), 3);
676 #[stable(feature = "rust1", since = "1.0.0")]
677 pub fn into_boxed_slice(mut self) -> Box<[T]> {
679 self.shrink_to_fit();
680 let buf = ptr::read(&self.buf);
686 /// Shortens the vector, keeping the first `len` elements and dropping
689 /// If `len` is greater than the vector's current length, this has no
692 /// The [`drain`] method can emulate `truncate`, but causes the excess
693 /// elements to be returned instead of dropped.
695 /// Note that this method has no effect on the allocated capacity
700 /// Truncating a five element vector to two elements:
703 /// let mut vec = vec![1, 2, 3, 4, 5];
705 /// assert_eq!(vec, [1, 2]);
708 /// No truncation occurs when `len` is greater than the vector's current
712 /// let mut vec = vec![1, 2, 3];
714 /// assert_eq!(vec, [1, 2, 3]);
717 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
721 /// let mut vec = vec![1, 2, 3];
723 /// assert_eq!(vec, []);
726 /// [`clear`]: #method.clear
727 /// [`drain`]: #method.drain
728 #[stable(feature = "rust1", since = "1.0.0")]
729 pub fn truncate(&mut self, len: usize) {
730 // This is safe because:
732 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
733 // case avoids creating an invalid slice, and
734 // * the `len` of the vector is shrunk before calling `drop_in_place`,
735 // such that no value will be dropped twice in case `drop_in_place`
736 // were to panic once (if it panics twice, the program aborts).
741 let s = self.get_unchecked_mut(len..) as *mut _;
743 ptr::drop_in_place(s);
747 /// Extracts a slice containing the entire vector.
749 /// Equivalent to `&s[..]`.
754 /// use std::io::{self, Write};
755 /// let buffer = vec![1, 2, 3, 5, 8];
756 /// io::sink().write(buffer.as_slice()).unwrap();
759 #[stable(feature = "vec_as_slice", since = "1.7.0")]
760 pub fn as_slice(&self) -> &[T] {
764 /// Extracts a mutable slice of the entire vector.
766 /// Equivalent to `&mut s[..]`.
771 /// use std::io::{self, Read};
772 /// let mut buffer = vec![0; 3];
773 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
776 #[stable(feature = "vec_as_slice", since = "1.7.0")]
777 pub fn as_mut_slice(&mut self) -> &mut [T] {
781 /// Returns a raw pointer to the vector's buffer.
783 /// The caller must ensure that the vector outlives the pointer this
784 /// function returns, or else it will end up pointing to garbage.
785 /// Modifying the vector may cause its buffer to be reallocated,
786 /// which would also make any pointers to it invalid.
788 /// The caller must also ensure that the memory the pointer (non-transitively) points to
789 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
790 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
795 /// let x = vec![1, 2, 4];
796 /// let x_ptr = x.as_ptr();
799 /// for i in 0..x.len() {
800 /// assert_eq!(*x_ptr.add(i), 1 << i);
805 /// [`as_mut_ptr`]: #method.as_mut_ptr
806 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
808 pub fn as_ptr(&self) -> *const T {
809 // We shadow the slice method of the same name to avoid going through
810 // `deref`, which creates an intermediate reference.
811 let ptr = self.buf.ptr();
812 unsafe { assume(!ptr.is_null()); }
816 /// Returns an unsafe mutable pointer to the vector's buffer.
818 /// The caller must ensure that the vector outlives the pointer this
819 /// function returns, or else it will end up pointing to garbage.
820 /// Modifying the vector may cause its buffer to be reallocated,
821 /// which would also make any pointers to it invalid.
826 /// // Allocate vector big enough for 4 elements.
828 /// let mut x: Vec<i32> = Vec::with_capacity(size);
829 /// let x_ptr = x.as_mut_ptr();
831 /// // Initialize elements via raw pointer writes, then set length.
833 /// for i in 0..size {
834 /// *x_ptr.add(i) = i as i32;
838 /// assert_eq!(&*x, &[0,1,2,3]);
840 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
842 pub fn as_mut_ptr(&mut self) -> *mut T {
843 // We shadow the slice method of the same name to avoid going through
844 // `deref_mut`, which creates an intermediate reference.
845 let ptr = self.buf.ptr();
846 unsafe { assume(!ptr.is_null()); }
850 /// Forces the length of the vector to `new_len`.
852 /// This is a low-level operation that maintains none of the normal
853 /// invariants of the type. Normally changing the length of a vector
854 /// is done using one of the safe operations instead, such as
855 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
857 /// [`truncate`]: #method.truncate
858 /// [`resize`]: #method.resize
859 /// [`extend`]: ../../std/iter/trait.Extend.html#tymethod.extend
860 /// [`clear`]: #method.clear
864 /// - `new_len` must be less than or equal to [`capacity()`].
865 /// - The elements at `old_len..new_len` must be initialized.
867 /// [`capacity()`]: #method.capacity
871 /// This method can be useful for situations in which the vector
872 /// is serving as a buffer for other code, particularly over FFI:
875 /// # #![allow(dead_code)]
876 /// # // This is just a minimal skeleton for the doc example;
877 /// # // don't use this as a starting point for a real library.
878 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
879 /// # const Z_OK: i32 = 0;
881 /// # fn deflateGetDictionary(
882 /// # strm: *mut std::ffi::c_void,
883 /// # dictionary: *mut u8,
884 /// # dictLength: *mut usize,
887 /// # impl StreamWrapper {
888 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
889 /// // Per the FFI method's docs, "32768 bytes is always enough".
890 /// let mut dict = Vec::with_capacity(32_768);
891 /// let mut dict_length = 0;
892 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
893 /// // 1. `dict_length` elements were initialized.
894 /// // 2. `dict_length` <= the capacity (32_768)
895 /// // which makes `set_len` safe to call.
897 /// // Make the FFI call...
898 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
900 /// // ...and update the length to what was initialized.
901 /// dict.set_len(dict_length);
911 /// While the following example is sound, there is a memory leak since
912 /// the inner vectors were not freed prior to the `set_len` call:
915 /// let mut vec = vec![vec![1, 0, 0],
919 /// // 1. `old_len..0` is empty so no elements need to be initialized.
920 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
926 /// Normally, here, one would use [`clear`] instead to correctly drop
927 /// the contents and thus not leak memory.
929 #[stable(feature = "rust1", since = "1.0.0")]
930 pub unsafe fn set_len(&mut self, new_len: usize) {
931 debug_assert!(new_len <= self.capacity());
936 /// Removes an element from the vector and returns it.
938 /// The removed element is replaced by the last element of the vector.
940 /// This does not preserve ordering, but is O(1).
944 /// Panics if `index` is out of bounds.
949 /// let mut v = vec!["foo", "bar", "baz", "qux"];
951 /// assert_eq!(v.swap_remove(1), "bar");
952 /// assert_eq!(v, ["foo", "qux", "baz"]);
954 /// assert_eq!(v.swap_remove(0), "foo");
955 /// assert_eq!(v, ["baz", "qux"]);
958 #[stable(feature = "rust1", since = "1.0.0")]
959 pub fn swap_remove(&mut self, index: usize) -> T {
961 // We replace self[index] with the last element. Note that if the
962 // bounds check on hole succeeds there must be a last element (which
963 // can be self[index] itself).
964 let hole: *mut T = &mut self[index];
965 let last = ptr::read(self.get_unchecked(self.len - 1));
967 ptr::replace(hole, last)
971 /// Inserts an element at position `index` within the vector, shifting all
972 /// elements after it to the right.
976 /// Panics if `index > len`.
981 /// let mut vec = vec![1, 2, 3];
982 /// vec.insert(1, 4);
983 /// assert_eq!(vec, [1, 4, 2, 3]);
984 /// vec.insert(4, 5);
985 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
987 #[stable(feature = "rust1", since = "1.0.0")]
988 pub fn insert(&mut self, index: usize, element: T) {
989 let len = self.len();
990 assert!(index <= len);
992 // space for the new element
993 if len == self.buf.capacity() {
999 // The spot to put the new value
1001 let p = self.as_mut_ptr().add(index);
1002 // Shift everything over to make space. (Duplicating the
1003 // `index`th element into two consecutive places.)
1004 ptr::copy(p, p.offset(1), len - index);
1005 // Write it in, overwriting the first copy of the `index`th
1007 ptr::write(p, element);
1009 self.set_len(len + 1);
1013 /// Removes and returns the element at position `index` within the vector,
1014 /// shifting all elements after it to the left.
1018 /// Panics if `index` is out of bounds.
1023 /// let mut v = vec![1, 2, 3];
1024 /// assert_eq!(v.remove(1), 2);
1025 /// assert_eq!(v, [1, 3]);
1027 #[stable(feature = "rust1", since = "1.0.0")]
1028 pub fn remove(&mut self, index: usize) -> T {
1029 let len = self.len();
1030 assert!(index < len);
1035 // the place we are taking from.
1036 let ptr = self.as_mut_ptr().add(index);
1037 // copy it out, unsafely having a copy of the value on
1038 // the stack and in the vector at the same time.
1039 ret = ptr::read(ptr);
1041 // Shift everything down to fill in that spot.
1042 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1044 self.set_len(len - 1);
1049 /// Retains only the elements specified by the predicate.
1051 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1052 /// This method operates in place, visiting each element exactly once in the
1053 /// original order, and preserves the order of the retained elements.
1058 /// let mut vec = vec![1, 2, 3, 4];
1059 /// vec.retain(|&x| x%2 == 0);
1060 /// assert_eq!(vec, [2, 4]);
1063 /// The exact order may be useful for tracking external state, like an index.
1066 /// let mut vec = vec![1, 2, 3, 4, 5];
1067 /// let keep = [false, true, true, false, true];
1069 /// vec.retain(|_| (keep[i], i += 1).0);
1070 /// assert_eq!(vec, [2, 3, 5]);
1072 #[stable(feature = "rust1", since = "1.0.0")]
1073 pub fn retain<F>(&mut self, mut f: F)
1074 where F: FnMut(&T) -> bool
1076 self.drain_filter(|x| !f(x));
1079 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1082 /// If the vector is sorted, this removes all duplicates.
1087 /// let mut vec = vec![10, 20, 21, 30, 20];
1089 /// vec.dedup_by_key(|i| *i / 10);
1091 /// assert_eq!(vec, [10, 20, 30, 20]);
1093 #[stable(feature = "dedup_by", since = "1.16.0")]
1095 pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
1096 self.dedup_by(|a, b| key(a) == key(b))
1099 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1102 /// The `same_bucket` function is passed references to two elements from the vector and
1103 /// must determine if the elements compare equal. The elements are passed in opposite order
1104 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1106 /// If the vector is sorted, this removes all duplicates.
1111 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1113 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1115 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1117 #[stable(feature = "dedup_by", since = "1.16.0")]
1118 pub fn dedup_by<F>(&mut self, same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
1120 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1126 /// Appends an element to the back of a collection.
1130 /// Panics if the number of elements in the vector overflows a `usize`.
1135 /// let mut vec = vec![1, 2];
1137 /// assert_eq!(vec, [1, 2, 3]);
1140 #[stable(feature = "rust1", since = "1.0.0")]
1141 pub fn push(&mut self, value: T) {
1142 // This will panic or abort if we would allocate > isize::MAX bytes
1143 // or if the length increment would overflow for zero-sized types.
1144 if self.len == self.buf.capacity() {
1148 let end = self.as_mut_ptr().add(self.len);
1149 ptr::write(end, value);
1154 /// Removes the last element from a vector and returns it, or [`None`] if it
1157 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1162 /// let mut vec = vec![1, 2, 3];
1163 /// assert_eq!(vec.pop(), Some(3));
1164 /// assert_eq!(vec, [1, 2]);
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 pub fn pop(&mut self) -> Option<T> {
1174 Some(ptr::read(self.get_unchecked(self.len())))
1179 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1183 /// Panics if the number of elements in the vector overflows a `usize`.
1188 /// let mut vec = vec![1, 2, 3];
1189 /// let mut vec2 = vec![4, 5, 6];
1190 /// vec.append(&mut vec2);
1191 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1192 /// assert_eq!(vec2, []);
1195 #[stable(feature = "append", since = "1.4.0")]
1196 pub fn append(&mut self, other: &mut Self) {
1198 self.append_elements(other.as_slice() as _);
1203 /// Appends elements to `Self` from other buffer.
1205 unsafe fn append_elements(&mut self, other: *const [T]) {
1206 let count = (*other).len();
1207 self.reserve(count);
1208 let len = self.len();
1209 ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count);
1213 /// Creates a draining iterator that removes the specified range in the vector
1214 /// and yields the removed items.
1216 /// Note 1: The element range is removed even if the iterator is only
1217 /// partially consumed or not consumed at all.
1219 /// Note 2: It is unspecified how many elements are removed from the vector
1220 /// if the `Drain` value is leaked.
1224 /// Panics if the starting point is greater than the end point or if
1225 /// the end point is greater than the length of the vector.
1230 /// let mut v = vec![1, 2, 3];
1231 /// let u: Vec<_> = v.drain(1..).collect();
1232 /// assert_eq!(v, &[1]);
1233 /// assert_eq!(u, &[2, 3]);
1235 /// // A full range clears the vector
1237 /// assert_eq!(v, &[]);
1239 #[stable(feature = "drain", since = "1.6.0")]
1240 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1241 where R: RangeBounds<usize>
1245 // When the Drain is first created, it shortens the length of
1246 // the source vector to make sure no uninitialized or moved-from elements
1247 // are accessible at all if the Drain's destructor never gets to run.
1249 // Drain will ptr::read out the values to remove.
1250 // When finished, remaining tail of the vec is copied back to cover
1251 // the hole, and the vector length is restored to the new length.
1253 let len = self.len();
1254 let start = match range.start_bound() {
1256 Excluded(&n) => n + 1,
1259 let end = match range.end_bound() {
1260 Included(&n) => n + 1,
1264 assert!(start <= end);
1265 assert!(end <= len);
1268 // set self.vec length's to start, to be safe in case Drain is leaked
1269 self.set_len(start);
1270 // Use the borrow in the IterMut to indicate borrowing behavior of the
1271 // whole Drain iterator (like &mut T).
1272 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start),
1276 tail_len: len - end,
1277 iter: range_slice.iter(),
1278 vec: NonNull::from(self),
1283 /// Clears the vector, removing all values.
1285 /// Note that this method has no effect on the allocated capacity
1291 /// let mut v = vec![1, 2, 3];
1295 /// assert!(v.is_empty());
1298 #[stable(feature = "rust1", since = "1.0.0")]
1299 pub fn clear(&mut self) {
1303 /// Returns the number of elements in the vector, also referred to
1304 /// as its 'length'.
1309 /// let a = vec![1, 2, 3];
1310 /// assert_eq!(a.len(), 3);
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 pub fn len(&self) -> usize {
1318 /// Returns `true` if the vector contains no elements.
1323 /// let mut v = Vec::new();
1324 /// assert!(v.is_empty());
1327 /// assert!(!v.is_empty());
1329 #[stable(feature = "rust1", since = "1.0.0")]
1330 pub fn is_empty(&self) -> bool {
1334 /// Splits the collection into two at the given index.
1336 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1337 /// and the returned `Self` contains elements `[at, len)`.
1339 /// Note that the capacity of `self` does not change.
1343 /// Panics if `at > len`.
1348 /// let mut vec = vec![1,2,3];
1349 /// let vec2 = vec.split_off(1);
1350 /// assert_eq!(vec, [1]);
1351 /// assert_eq!(vec2, [2, 3]);
1354 #[stable(feature = "split_off", since = "1.4.0")]
1355 pub fn split_off(&mut self, at: usize) -> Self {
1356 assert!(at <= self.len(), "`at` out of bounds");
1358 let other_len = self.len - at;
1359 let mut other = Vec::with_capacity(other_len);
1361 // Unsafely `set_len` and copy items to `other`.
1364 other.set_len(other_len);
1366 ptr::copy_nonoverlapping(self.as_ptr().add(at),
1373 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1375 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1376 /// difference, with each additional slot filled with the result of
1377 /// calling the closure `f`. The return values from `f` will end up
1378 /// in the `Vec` in the order they have been generated.
1380 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1382 /// This method uses a closure to create new values on every push. If
1383 /// you'd rather [`Clone`] a given value, use [`resize`]. If you want
1384 /// to use the [`Default`] trait to generate values, you can pass
1385 /// [`Default::default()`] as the second argument.
1390 /// let mut vec = vec![1, 2, 3];
1391 /// vec.resize_with(5, Default::default);
1392 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1394 /// let mut vec = vec![];
1396 /// vec.resize_with(4, || { p *= 2; p });
1397 /// assert_eq!(vec, [2, 4, 8, 16]);
1400 /// [`resize`]: #method.resize
1401 /// [`Clone`]: ../../std/clone/trait.Clone.html
1402 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1403 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1404 where F: FnMut() -> T
1406 let len = self.len();
1408 self.extend_with(new_len - len, ExtendFunc(f));
1410 self.truncate(new_len);
1414 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1415 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1416 /// `'a`. If the type has only static references, or none at all, then this
1417 /// may be chosen to be `'static`.
1419 /// This function is similar to the `leak` function on `Box`.
1421 /// This function is mainly useful for data that lives for the remainder of
1422 /// the program's life. Dropping the returned reference will cause a memory
1430 /// #![feature(vec_leak)]
1432 /// let x = vec![1, 2, 3];
1433 /// let static_ref: &'static mut [usize] = Vec::leak(x);
1434 /// static_ref[0] += 1;
1435 /// assert_eq!(static_ref, &[2, 2, 3]);
1437 #[unstable(feature = "vec_leak", issue = "62195")]
1439 pub fn leak<'a>(vec: Vec<T>) -> &'a mut [T]
1441 T: 'a // Technically not needed, but kept to be explicit.
1443 Box::leak(vec.into_boxed_slice())
1447 impl<T: Clone> Vec<T> {
1448 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1450 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1451 /// difference, with each additional slot filled with `value`.
1452 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1454 /// This method requires [`Clone`] to be able clone the passed value. If
1455 /// you need more flexibility (or want to rely on [`Default`] instead of
1456 /// [`Clone`]), use [`resize_with`].
1461 /// let mut vec = vec!["hello"];
1462 /// vec.resize(3, "world");
1463 /// assert_eq!(vec, ["hello", "world", "world"]);
1465 /// let mut vec = vec![1, 2, 3, 4];
1466 /// vec.resize(2, 0);
1467 /// assert_eq!(vec, [1, 2]);
1470 /// [`Clone`]: ../../std/clone/trait.Clone.html
1471 /// [`Default`]: ../../std/default/trait.Default.html
1472 /// [`resize_with`]: #method.resize_with
1473 #[stable(feature = "vec_resize", since = "1.5.0")]
1474 pub fn resize(&mut self, new_len: usize, value: T) {
1475 let len = self.len();
1478 self.extend_with(new_len - len, ExtendElement(value))
1480 self.truncate(new_len);
1484 /// Clones and appends all elements in a slice to the `Vec`.
1486 /// Iterates over the slice `other`, clones each element, and then appends
1487 /// it to this `Vec`. The `other` vector is traversed in-order.
1489 /// Note that this function is same as [`extend`] except that it is
1490 /// specialized to work with slices instead. If and when Rust gets
1491 /// specialization this function will likely be deprecated (but still
1497 /// let mut vec = vec![1];
1498 /// vec.extend_from_slice(&[2, 3, 4]);
1499 /// assert_eq!(vec, [1, 2, 3, 4]);
1502 /// [`extend`]: #method.extend
1503 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1504 pub fn extend_from_slice(&mut self, other: &[T]) {
1505 self.spec_extend(other.iter())
1509 impl<T: Default> Vec<T> {
1510 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1512 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1513 /// difference, with each additional slot filled with [`Default::default()`].
1514 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1516 /// This method uses [`Default`] to create new values on every push. If
1517 /// you'd rather [`Clone`] a given value, use [`resize`].
1522 /// # #![allow(deprecated)]
1523 /// #![feature(vec_resize_default)]
1525 /// let mut vec = vec![1, 2, 3];
1526 /// vec.resize_default(5);
1527 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1529 /// let mut vec = vec![1, 2, 3, 4];
1530 /// vec.resize_default(2);
1531 /// assert_eq!(vec, [1, 2]);
1534 /// [`resize`]: #method.resize
1535 /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default
1536 /// [`Default`]: ../../std/default/trait.Default.html
1537 /// [`Clone`]: ../../std/clone/trait.Clone.html
1538 #[unstable(feature = "vec_resize_default", issue = "41758")]
1539 #[rustc_deprecated(reason = "This is moving towards being removed in favor \
1540 of `.resize_with(Default::default)`. If you disagree, please comment \
1541 in the tracking issue.", since = "1.33.0")]
1542 pub fn resize_default(&mut self, new_len: usize) {
1543 let len = self.len();
1546 self.extend_with(new_len - len, ExtendDefault);
1548 self.truncate(new_len);
1553 // This code generalises `extend_with_{element,default}`.
1554 trait ExtendWith<T> {
1555 fn next(&mut self) -> T;
1559 struct ExtendElement<T>(T);
1560 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1561 fn next(&mut self) -> T { self.0.clone() }
1562 fn last(self) -> T { self.0 }
1565 struct ExtendDefault;
1566 impl<T: Default> ExtendWith<T> for ExtendDefault {
1567 fn next(&mut self) -> T { Default::default() }
1568 fn last(self) -> T { Default::default() }
1571 struct ExtendFunc<F>(F);
1572 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1573 fn next(&mut self) -> T { (self.0)() }
1574 fn last(mut self) -> T { (self.0)() }
1578 /// Extend the vector by `n` values, using the given generator.
1579 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1583 let mut ptr = self.as_mut_ptr().add(self.len());
1584 // Use SetLenOnDrop to work around bug where compiler
1585 // may not realize the store through `ptr` through self.set_len()
1587 let mut local_len = SetLenOnDrop::new(&mut self.len);
1589 // Write all elements except the last one
1591 ptr::write(ptr, value.next());
1592 ptr = ptr.offset(1);
1593 // Increment the length in every step in case next() panics
1594 local_len.increment_len(1);
1598 // We can write the last element directly without cloning needlessly
1599 ptr::write(ptr, value.last());
1600 local_len.increment_len(1);
1603 // len set by scope guard
1608 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1610 // The idea is: The length field in SetLenOnDrop is a local variable
1611 // that the optimizer will see does not alias with any stores through the Vec's data
1612 // pointer. This is a workaround for alias analysis issue #32155
1613 struct SetLenOnDrop<'a> {
1618 impl<'a> SetLenOnDrop<'a> {
1620 fn new(len: &'a mut usize) -> Self {
1621 SetLenOnDrop { local_len: *len, len: len }
1625 fn increment_len(&mut self, increment: usize) {
1626 self.local_len += increment;
1630 impl Drop for SetLenOnDrop<'_> {
1632 fn drop(&mut self) {
1633 *self.len = self.local_len;
1637 impl<T: PartialEq> Vec<T> {
1638 /// Removes consecutive repeated elements in the vector according to the
1639 /// [`PartialEq`] trait implementation.
1641 /// If the vector is sorted, this removes all duplicates.
1646 /// let mut vec = vec![1, 2, 2, 3, 2];
1650 /// assert_eq!(vec, [1, 2, 3, 2]);
1652 #[stable(feature = "rust1", since = "1.0.0")]
1654 pub fn dedup(&mut self) {
1655 self.dedup_by(|a, b| a == b)
1658 /// Removes the first instance of `item` from the vector if the item exists.
1663 /// # #![feature(vec_remove_item)]
1664 /// let mut vec = vec![1, 2, 3, 1];
1666 /// vec.remove_item(&1);
1668 /// assert_eq!(vec, vec![2, 3, 1]);
1670 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1671 pub fn remove_item(&mut self, item: &T) -> Option<T> {
1672 let pos = self.iter().position(|x| *x == *item)?;
1673 Some(self.remove(pos))
1677 ////////////////////////////////////////////////////////////////////////////////
1678 // Internal methods and functions
1679 ////////////////////////////////////////////////////////////////////////////////
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1684 <T as SpecFromElem>::from_elem(elem, n)
1687 // Specialization trait used for Vec::from_elem
1688 trait SpecFromElem: Sized {
1689 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1692 impl<T: Clone> SpecFromElem for T {
1693 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1694 let mut v = Vec::with_capacity(n);
1695 v.extend_with(n, ExtendElement(elem));
1700 impl SpecFromElem for u8 {
1702 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1705 buf: RawVec::with_capacity_zeroed(n),
1710 let mut v = Vec::with_capacity(n);
1711 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1718 impl<T: Clone + IsZero> SpecFromElem for T {
1720 fn from_elem(elem: T, n: usize) -> Vec<T> {
1723 buf: RawVec::with_capacity_zeroed(n),
1727 let mut v = Vec::with_capacity(n);
1728 v.extend_with(n, ExtendElement(elem));
1733 unsafe trait IsZero {
1734 /// Whether this value is zero
1735 fn is_zero(&self) -> bool;
1738 macro_rules! impl_is_zero {
1739 ($t: ty, $is_zero: expr) => {
1740 unsafe impl IsZero for $t {
1742 fn is_zero(&self) -> bool {
1749 impl_is_zero!(i8, |x| x == 0);
1750 impl_is_zero!(i16, |x| x == 0);
1751 impl_is_zero!(i32, |x| x == 0);
1752 impl_is_zero!(i64, |x| x == 0);
1753 impl_is_zero!(i128, |x| x == 0);
1754 impl_is_zero!(isize, |x| x == 0);
1756 impl_is_zero!(u16, |x| x == 0);
1757 impl_is_zero!(u32, |x| x == 0);
1758 impl_is_zero!(u64, |x| x == 0);
1759 impl_is_zero!(u128, |x| x == 0);
1760 impl_is_zero!(usize, |x| x == 0);
1762 impl_is_zero!(bool, |x| x == false);
1763 impl_is_zero!(char, |x| x == '\0');
1765 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1766 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1768 unsafe impl<T> IsZero for *const T {
1770 fn is_zero(&self) -> bool {
1775 unsafe impl<T> IsZero for *mut T {
1777 fn is_zero(&self) -> bool {
1782 // `Option<&T>`, `Option<&mut T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
1783 // For fat pointers, the bytes that would be the pointer metadata in the `Some` variant
1784 // are padding in the `None` variant, so ignoring them and zero-initializing instead is ok.
1786 unsafe impl<T: ?Sized> IsZero for Option<&T> {
1788 fn is_zero(&self) -> bool {
1793 unsafe impl<T: ?Sized> IsZero for Option<&mut T> {
1795 fn is_zero(&self) -> bool {
1800 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
1802 fn is_zero(&self) -> bool {
1808 ////////////////////////////////////////////////////////////////////////////////
1809 // Common trait implementations for Vec
1810 ////////////////////////////////////////////////////////////////////////////////
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 impl<T: Clone> Clone for Vec<T> {
1815 fn clone(&self) -> Vec<T> {
1816 <[T]>::to_vec(&**self)
1819 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1820 // required for this method definition, is not available. Instead use the
1821 // `slice::to_vec` function which is only available with cfg(test)
1822 // NB see the slice::hack module in slice.rs for more information
1824 fn clone(&self) -> Vec<T> {
1825 crate::slice::to_vec(&**self)
1828 fn clone_from(&mut self, other: &Vec<T>) {
1829 other.as_slice().clone_into(self);
1833 #[stable(feature = "rust1", since = "1.0.0")]
1834 impl<T: Hash> Hash for Vec<T> {
1836 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1837 Hash::hash(&**self, state)
1841 #[stable(feature = "rust1", since = "1.0.0")]
1842 #[rustc_on_unimplemented(
1843 message="vector indices are of type `usize` or ranges of `usize`",
1844 label="vector indices are of type `usize` or ranges of `usize`",
1846 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
1847 type Output = I::Output;
1850 fn index(&self, index: I) -> &Self::Output {
1851 Index::index(&**self, index)
1855 #[stable(feature = "rust1", since = "1.0.0")]
1856 #[rustc_on_unimplemented(
1857 message="vector indices are of type `usize` or ranges of `usize`",
1858 label="vector indices are of type `usize` or ranges of `usize`",
1860 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
1862 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1863 IndexMut::index_mut(&mut **self, index)
1867 #[stable(feature = "rust1", since = "1.0.0")]
1868 impl<T> ops::Deref for Vec<T> {
1871 fn deref(&self) -> &[T] {
1873 slice::from_raw_parts(self.as_ptr(), self.len)
1878 #[stable(feature = "rust1", since = "1.0.0")]
1879 impl<T> ops::DerefMut for Vec<T> {
1880 fn deref_mut(&mut self) -> &mut [T] {
1882 slice::from_raw_parts_mut(self.as_mut_ptr(), self.len)
1887 #[stable(feature = "rust1", since = "1.0.0")]
1888 impl<T> FromIterator<T> for Vec<T> {
1890 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1891 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1895 #[stable(feature = "rust1", since = "1.0.0")]
1896 impl<T> IntoIterator for Vec<T> {
1898 type IntoIter = IntoIter<T>;
1900 /// Creates a consuming iterator, that is, one that moves each value out of
1901 /// the vector (from start to end). The vector cannot be used after calling
1907 /// let v = vec!["a".to_string(), "b".to_string()];
1908 /// for s in v.into_iter() {
1909 /// // s has type String, not &String
1910 /// println!("{}", s);
1914 fn into_iter(mut self) -> IntoIter<T> {
1916 let begin = self.as_mut_ptr();
1917 let end = if mem::size_of::<T>() == 0 {
1918 arith_offset(begin as *const i8, self.len() as isize) as *const T
1920 begin.add(self.len()) as *const T
1922 let cap = self.buf.capacity();
1925 buf: NonNull::new_unchecked(begin),
1926 phantom: PhantomData,
1935 #[stable(feature = "rust1", since = "1.0.0")]
1936 impl<'a, T> IntoIterator for &'a Vec<T> {
1938 type IntoIter = slice::Iter<'a, T>;
1940 fn into_iter(self) -> slice::Iter<'a, T> {
1945 #[stable(feature = "rust1", since = "1.0.0")]
1946 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1947 type Item = &'a mut T;
1948 type IntoIter = slice::IterMut<'a, T>;
1950 fn into_iter(self) -> slice::IterMut<'a, T> {
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl<T> Extend<T> for Vec<T> {
1958 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1959 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1963 // Specialization trait used for Vec::from_iter and Vec::extend
1964 trait SpecExtend<T, I> {
1965 fn from_iter(iter: I) -> Self;
1966 fn spec_extend(&mut self, iter: I);
1969 impl<T, I> SpecExtend<T, I> for Vec<T>
1970 where I: Iterator<Item=T>,
1972 default fn from_iter(mut iterator: I) -> Self {
1973 // Unroll the first iteration, as the vector is going to be
1974 // expanded on this iteration in every case when the iterable is not
1975 // empty, but the loop in extend_desugared() is not going to see the
1976 // vector being full in the few subsequent loop iterations.
1977 // So we get better branch prediction.
1978 let mut vector = match iterator.next() {
1979 None => return Vec::new(),
1981 let (lower, _) = iterator.size_hint();
1982 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1984 ptr::write(vector.get_unchecked_mut(0), element);
1990 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1994 default fn spec_extend(&mut self, iter: I) {
1995 self.extend_desugared(iter)
1999 impl<T, I> SpecExtend<T, I> for Vec<T>
2000 where I: TrustedLen<Item=T>,
2002 default fn from_iter(iterator: I) -> Self {
2003 let mut vector = Vec::new();
2004 vector.spec_extend(iterator);
2008 default fn spec_extend(&mut self, iterator: I) {
2009 // This is the case for a TrustedLen iterator.
2010 let (low, high) = iterator.size_hint();
2011 if let Some(high_value) = high {
2012 debug_assert_eq!(low, high_value,
2013 "TrustedLen iterator's size hint is not exact: {:?}",
2016 if let Some(additional) = high {
2017 self.reserve(additional);
2019 let mut ptr = self.as_mut_ptr().add(self.len());
2020 let mut local_len = SetLenOnDrop::new(&mut self.len);
2021 iterator.for_each(move |element| {
2022 ptr::write(ptr, element);
2023 ptr = ptr.offset(1);
2024 // NB can't overflow since we would have had to alloc the address space
2025 local_len.increment_len(1);
2029 self.extend_desugared(iterator)
2034 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2035 fn from_iter(iterator: IntoIter<T>) -> Self {
2036 // A common case is passing a vector into a function which immediately
2037 // re-collects into a vector. We can short circuit this if the IntoIter
2038 // has not been advanced at all.
2039 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
2041 let vec = Vec::from_raw_parts(iterator.buf.as_ptr(),
2044 mem::forget(iterator);
2048 let mut vector = Vec::new();
2049 vector.spec_extend(iterator);
2054 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2056 self.append_elements(iterator.as_slice() as _);
2058 iterator.ptr = iterator.end;
2062 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2063 where I: Iterator<Item=&'a T>,
2066 default fn from_iter(iterator: I) -> Self {
2067 SpecExtend::from_iter(iterator.cloned())
2070 default fn spec_extend(&mut self, iterator: I) {
2071 self.spec_extend(iterator.cloned())
2075 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2078 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2079 let slice = iterator.as_slice();
2080 self.reserve(slice.len());
2082 let len = self.len();
2083 self.set_len(len + slice.len());
2084 self.get_unchecked_mut(len..).copy_from_slice(slice);
2090 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2091 // This is the case for a general iterator.
2093 // This function should be the moral equivalent of:
2095 // for item in iterator {
2098 while let Some(element) = iterator.next() {
2099 let len = self.len();
2100 if len == self.capacity() {
2101 let (lower, _) = iterator.size_hint();
2102 self.reserve(lower.saturating_add(1));
2105 ptr::write(self.get_unchecked_mut(len), element);
2106 // NB can't overflow since we would have had to alloc the address space
2107 self.set_len(len + 1);
2112 /// Creates a splicing iterator that replaces the specified range in the vector
2113 /// with the given `replace_with` iterator and yields the removed items.
2114 /// `replace_with` does not need to be the same length as `range`.
2116 /// The element range is removed even if the iterator is not consumed until the end.
2118 /// It is unspecified how many elements are removed from the vector
2119 /// if the `Splice` value is leaked.
2121 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2123 /// This is optimal if:
2125 /// * The tail (elements in the vector after `range`) is empty,
2126 /// * or `replace_with` yields fewer elements than `range`’s length
2127 /// * or the lower bound of its `size_hint()` is exact.
2129 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2133 /// Panics if the starting point is greater than the end point or if
2134 /// the end point is greater than the length of the vector.
2139 /// let mut v = vec![1, 2, 3];
2140 /// let new = [7, 8];
2141 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2142 /// assert_eq!(v, &[7, 8, 3]);
2143 /// assert_eq!(u, &[1, 2]);
2146 #[stable(feature = "vec_splice", since = "1.21.0")]
2147 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2148 where R: RangeBounds<usize>, I: IntoIterator<Item=T>
2151 drain: self.drain(range),
2152 replace_with: replace_with.into_iter(),
2156 /// Creates an iterator which uses a closure to determine if an element should be removed.
2158 /// If the closure returns true, then the element is removed and yielded.
2159 /// If the closure returns false, the element will remain in the vector and will not be yielded
2160 /// by the iterator.
2162 /// Using this method is equivalent to the following code:
2165 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2166 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2168 /// while i != vec.len() {
2169 /// if some_predicate(&mut vec[i]) {
2170 /// let val = vec.remove(i);
2171 /// // your code here
2177 /// # assert_eq!(vec, vec![1, 4, 5]);
2180 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2181 /// because it can backshift the elements of the array in bulk.
2183 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2184 /// regardless of whether you choose to keep or remove it.
2189 /// Splitting an array into evens and odds, reusing the original allocation:
2192 /// #![feature(drain_filter)]
2193 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2195 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2196 /// let odds = numbers;
2198 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2199 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2201 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2202 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2203 where F: FnMut(&mut T) -> bool,
2205 let old_len = self.len();
2207 // Guard against us getting leaked (leak amplification)
2208 unsafe { self.set_len(0); }
2221 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2223 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2224 /// append the entire slice at once.
2226 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2227 #[stable(feature = "extend_ref", since = "1.2.0")]
2228 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2229 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2230 self.spec_extend(iter.into_iter())
2234 macro_rules! __impl_slice_eq1 {
2235 ([$($vars:tt)*] $lhs:ty, $rhs:ty, $($constraints:tt)*) => {
2236 #[stable(feature = "rust1", since = "1.0.0")]
2237 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2243 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2245 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2250 __impl_slice_eq1! { [] Vec<A>, Vec<B>, }
2251 __impl_slice_eq1! { [] Vec<A>, &[B], }
2252 __impl_slice_eq1! { [] Vec<A>, &mut [B], }
2253 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B], A: Clone }
2254 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B], A: Clone }
2255 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B>, A: Clone }
2256 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N], [B; N]: LengthAtMost32 }
2257 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N], [B; N]: LengthAtMost32 }
2259 // NOTE: some less important impls are omitted to reduce code bloat
2260 // FIXME(Centril): Reconsider this?
2261 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], [B; N]: LengthAtMost32 }
2262 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], [B; N]: LengthAtMost32 }
2263 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], [B; N]: LengthAtMost32 }
2264 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], [B; N]: LengthAtMost32 }
2266 /// Implements comparison of vectors, lexicographically.
2267 #[stable(feature = "rust1", since = "1.0.0")]
2268 impl<T: PartialOrd> PartialOrd for Vec<T> {
2270 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2271 PartialOrd::partial_cmp(&**self, &**other)
2275 #[stable(feature = "rust1", since = "1.0.0")]
2276 impl<T: Eq> Eq for Vec<T> {}
2278 /// Implements ordering of vectors, lexicographically.
2279 #[stable(feature = "rust1", since = "1.0.0")]
2280 impl<T: Ord> Ord for Vec<T> {
2282 fn cmp(&self, other: &Vec<T>) -> Ordering {
2283 Ord::cmp(&**self, &**other)
2287 #[stable(feature = "rust1", since = "1.0.0")]
2288 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2289 fn drop(&mut self) {
2292 ptr::drop_in_place(&mut self[..]);
2294 // RawVec handles deallocation
2298 #[stable(feature = "rust1", since = "1.0.0")]
2299 impl<T> Default for Vec<T> {
2300 /// Creates an empty `Vec<T>`.
2301 fn default() -> Vec<T> {
2306 #[stable(feature = "rust1", since = "1.0.0")]
2307 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2308 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2309 fmt::Debug::fmt(&**self, f)
2313 #[stable(feature = "rust1", since = "1.0.0")]
2314 impl<T> AsRef<Vec<T>> for Vec<T> {
2315 fn as_ref(&self) -> &Vec<T> {
2320 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2321 impl<T> AsMut<Vec<T>> for Vec<T> {
2322 fn as_mut(&mut self) -> &mut Vec<T> {
2327 #[stable(feature = "rust1", since = "1.0.0")]
2328 impl<T> AsRef<[T]> for Vec<T> {
2329 fn as_ref(&self) -> &[T] {
2334 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2335 impl<T> AsMut<[T]> for Vec<T> {
2336 fn as_mut(&mut self) -> &mut [T] {
2341 #[stable(feature = "rust1", since = "1.0.0")]
2342 impl<T: Clone> From<&[T]> for Vec<T> {
2344 fn from(s: &[T]) -> Vec<T> {
2348 fn from(s: &[T]) -> Vec<T> {
2349 crate::slice::to_vec(s)
2353 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2354 impl<T: Clone> From<&mut [T]> for Vec<T> {
2356 fn from(s: &mut [T]) -> Vec<T> {
2360 fn from(s: &mut [T]) -> Vec<T> {
2361 crate::slice::to_vec(s)
2365 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2366 impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> {
2367 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2372 // note: test pulls in libstd, which causes errors here
2374 #[stable(feature = "vec_from_box", since = "1.18.0")]
2375 impl<T> From<Box<[T]>> for Vec<T> {
2376 fn from(s: Box<[T]>) -> Vec<T> {
2381 // note: test pulls in libstd, which causes errors here
2383 #[stable(feature = "box_from_vec", since = "1.20.0")]
2384 impl<T> From<Vec<T>> for Box<[T]> {
2385 fn from(v: Vec<T>) -> Box<[T]> {
2386 v.into_boxed_slice()
2390 #[stable(feature = "rust1", since = "1.0.0")]
2391 impl From<&str> for Vec<u8> {
2392 fn from(s: &str) -> Vec<u8> {
2393 From::from(s.as_bytes())
2397 ////////////////////////////////////////////////////////////////////////////////
2399 ////////////////////////////////////////////////////////////////////////////////
2401 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2402 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2403 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2408 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2409 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2410 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2415 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2416 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2417 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2418 Cow::Borrowed(v.as_slice())
2422 #[stable(feature = "rust1", since = "1.0.0")]
2423 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
2424 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2425 Cow::Owned(FromIterator::from_iter(it))
2429 ////////////////////////////////////////////////////////////////////////////////
2431 ////////////////////////////////////////////////////////////////////////////////
2433 /// An iterator that moves out of a vector.
2435 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2436 /// by the [`IntoIterator`] trait).
2438 /// [`Vec`]: struct.Vec.html
2439 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2440 #[stable(feature = "rust1", since = "1.0.0")]
2441 pub struct IntoIter<T> {
2443 phantom: PhantomData<T>,
2449 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2450 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2451 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2452 f.debug_tuple("IntoIter")
2453 .field(&self.as_slice())
2458 impl<T> IntoIter<T> {
2459 /// Returns the remaining items of this iterator as a slice.
2464 /// let vec = vec!['a', 'b', 'c'];
2465 /// let mut into_iter = vec.into_iter();
2466 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2467 /// let _ = into_iter.next().unwrap();
2468 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2470 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2471 pub fn as_slice(&self) -> &[T] {
2473 slice::from_raw_parts(self.ptr, self.len())
2477 /// Returns the remaining items of this iterator as a mutable slice.
2482 /// let vec = vec!['a', 'b', 'c'];
2483 /// let mut into_iter = vec.into_iter();
2484 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2485 /// into_iter.as_mut_slice()[2] = 'z';
2486 /// assert_eq!(into_iter.next().unwrap(), 'a');
2487 /// assert_eq!(into_iter.next().unwrap(), 'b');
2488 /// assert_eq!(into_iter.next().unwrap(), 'z');
2490 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2491 pub fn as_mut_slice(&mut self) -> &mut [T] {
2493 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
2498 #[stable(feature = "rust1", since = "1.0.0")]
2499 unsafe impl<T: Send> Send for IntoIter<T> {}
2500 #[stable(feature = "rust1", since = "1.0.0")]
2501 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2503 #[stable(feature = "rust1", since = "1.0.0")]
2504 impl<T> Iterator for IntoIter<T> {
2508 fn next(&mut self) -> Option<T> {
2510 if self.ptr as *const _ == self.end {
2513 if mem::size_of::<T>() == 0 {
2514 // purposefully don't use 'ptr.offset' because for
2515 // vectors with 0-size elements this would return the
2517 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2519 // Make up a value of this ZST.
2523 self.ptr = self.ptr.offset(1);
2525 Some(ptr::read(old))
2532 fn size_hint(&self) -> (usize, Option<usize>) {
2533 let exact = if mem::size_of::<T>() == 0 {
2534 (self.end as usize).wrapping_sub(self.ptr as usize)
2536 unsafe { self.end.offset_from(self.ptr) as usize }
2538 (exact, Some(exact))
2542 fn count(self) -> usize {
2547 #[stable(feature = "rust1", since = "1.0.0")]
2548 impl<T> DoubleEndedIterator for IntoIter<T> {
2550 fn next_back(&mut self) -> Option<T> {
2552 if self.end == self.ptr {
2555 if mem::size_of::<T>() == 0 {
2556 // See above for why 'ptr.offset' isn't used
2557 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2559 // Make up a value of this ZST.
2562 self.end = self.end.offset(-1);
2564 Some(ptr::read(self.end))
2571 #[stable(feature = "rust1", since = "1.0.0")]
2572 impl<T> ExactSizeIterator for IntoIter<T> {
2573 fn is_empty(&self) -> bool {
2574 self.ptr == self.end
2578 #[stable(feature = "fused", since = "1.26.0")]
2579 impl<T> FusedIterator for IntoIter<T> {}
2581 #[unstable(feature = "trusted_len", issue = "37572")]
2582 unsafe impl<T> TrustedLen for IntoIter<T> {}
2584 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2585 impl<T: Clone> Clone for IntoIter<T> {
2586 fn clone(&self) -> IntoIter<T> {
2587 self.as_slice().to_owned().into_iter()
2591 #[stable(feature = "rust1", since = "1.0.0")]
2592 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2593 fn drop(&mut self) {
2594 // destroy the remaining elements
2595 for _x in self.by_ref() {}
2597 // RawVec handles deallocation
2598 let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) };
2602 /// A draining iterator for `Vec<T>`.
2604 /// This `struct` is created by the [`drain`] method on [`Vec`].
2606 /// [`drain`]: struct.Vec.html#method.drain
2607 /// [`Vec`]: struct.Vec.html
2608 #[stable(feature = "drain", since = "1.6.0")]
2609 pub struct Drain<'a, T: 'a> {
2610 /// Index of tail to preserve
2614 /// Current remaining range to remove
2615 iter: slice::Iter<'a, T>,
2616 vec: NonNull<Vec<T>>,
2619 #[stable(feature = "collection_debug", since = "1.17.0")]
2620 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2621 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2622 f.debug_tuple("Drain")
2623 .field(&self.iter.as_slice())
2628 impl<'a, T> Drain<'a, T> {
2629 /// Returns the remaining items of this iterator as a slice.
2634 /// # #![feature(vec_drain_as_slice)]
2635 /// let mut vec = vec!['a', 'b', 'c'];
2636 /// let mut drain = vec.drain(..);
2637 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
2638 /// let _ = drain.next().unwrap();
2639 /// assert_eq!(drain.as_slice(), &['b', 'c']);
2641 #[unstable(feature = "vec_drain_as_slice", reason = "recently added", issue = "58957")]
2642 pub fn as_slice(&self) -> &[T] {
2643 self.iter.as_slice()
2647 #[stable(feature = "drain", since = "1.6.0")]
2648 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2649 #[stable(feature = "drain", since = "1.6.0")]
2650 unsafe impl<T: Send> Send for Drain<'_, T> {}
2652 #[stable(feature = "drain", since = "1.6.0")]
2653 impl<T> Iterator for Drain<'_, T> {
2657 fn next(&mut self) -> Option<T> {
2658 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2661 fn size_hint(&self) -> (usize, Option<usize>) {
2662 self.iter.size_hint()
2666 #[stable(feature = "drain", since = "1.6.0")]
2667 impl<T> DoubleEndedIterator for Drain<'_, T> {
2669 fn next_back(&mut self) -> Option<T> {
2670 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2674 #[stable(feature = "drain", since = "1.6.0")]
2675 impl<T> Drop for Drain<'_, T> {
2676 fn drop(&mut self) {
2677 // exhaust self first
2678 self.for_each(drop);
2680 if self.tail_len > 0 {
2682 let source_vec = self.vec.as_mut();
2683 // memmove back untouched tail, update to new length
2684 let start = source_vec.len();
2685 let tail = self.tail_start;
2687 let src = source_vec.as_ptr().add(tail);
2688 let dst = source_vec.as_mut_ptr().add(start);
2689 ptr::copy(src, dst, self.tail_len);
2691 source_vec.set_len(start + self.tail_len);
2698 #[stable(feature = "drain", since = "1.6.0")]
2699 impl<T> ExactSizeIterator for Drain<'_, T> {
2700 fn is_empty(&self) -> bool {
2701 self.iter.is_empty()
2705 #[stable(feature = "fused", since = "1.26.0")]
2706 impl<T> FusedIterator for Drain<'_, T> {}
2708 /// A splicing iterator for `Vec`.
2710 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2711 /// documentation for more.
2713 /// [`splice()`]: struct.Vec.html#method.splice
2714 /// [`Vec`]: struct.Vec.html
2716 #[stable(feature = "vec_splice", since = "1.21.0")]
2717 pub struct Splice<'a, I: Iterator + 'a> {
2718 drain: Drain<'a, I::Item>,
2722 #[stable(feature = "vec_splice", since = "1.21.0")]
2723 impl<I: Iterator> Iterator for Splice<'_, I> {
2724 type Item = I::Item;
2726 fn next(&mut self) -> Option<Self::Item> {
2730 fn size_hint(&self) -> (usize, Option<usize>) {
2731 self.drain.size_hint()
2735 #[stable(feature = "vec_splice", since = "1.21.0")]
2736 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
2737 fn next_back(&mut self) -> Option<Self::Item> {
2738 self.drain.next_back()
2742 #[stable(feature = "vec_splice", since = "1.21.0")]
2743 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
2746 #[stable(feature = "vec_splice", since = "1.21.0")]
2747 impl<I: Iterator> Drop for Splice<'_, I> {
2748 fn drop(&mut self) {
2749 self.drain.by_ref().for_each(drop);
2752 if self.drain.tail_len == 0 {
2753 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2757 // First fill the range left by drain().
2758 if !self.drain.fill(&mut self.replace_with) {
2762 // There may be more elements. Use the lower bound as an estimate.
2763 // FIXME: Is the upper bound a better guess? Or something else?
2764 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2765 if lower_bound > 0 {
2766 self.drain.move_tail(lower_bound);
2767 if !self.drain.fill(&mut self.replace_with) {
2772 // Collect any remaining elements.
2773 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2774 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2775 // Now we have an exact count.
2776 if collected.len() > 0 {
2777 self.drain.move_tail(collected.len());
2778 let filled = self.drain.fill(&mut collected);
2779 debug_assert!(filled);
2780 debug_assert_eq!(collected.len(), 0);
2783 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2787 /// Private helper methods for `Splice::drop`
2788 impl<T> Drain<'_, T> {
2789 /// The range from `self.vec.len` to `self.tail_start` contains elements
2790 /// that have been moved out.
2791 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2792 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2793 unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
2794 let vec = self.vec.as_mut();
2795 let range_start = vec.len;
2796 let range_end = self.tail_start;
2797 let range_slice = slice::from_raw_parts_mut(
2798 vec.as_mut_ptr().add(range_start),
2799 range_end - range_start);
2801 for place in range_slice {
2802 if let Some(new_item) = replace_with.next() {
2803 ptr::write(place, new_item);
2812 /// Makes room for inserting more elements before the tail.
2813 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2814 let vec = self.vec.as_mut();
2815 let used_capacity = self.tail_start + self.tail_len;
2816 vec.buf.reserve(used_capacity, extra_capacity);
2818 let new_tail_start = self.tail_start + extra_capacity;
2819 let src = vec.as_ptr().add(self.tail_start);
2820 let dst = vec.as_mut_ptr().add(new_tail_start);
2821 ptr::copy(src, dst, self.tail_len);
2822 self.tail_start = new_tail_start;
2826 /// An iterator produced by calling `drain_filter` on Vec.
2827 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2829 pub struct DrainFilter<'a, T, F>
2830 where F: FnMut(&mut T) -> bool,
2832 vec: &'a mut Vec<T>,
2833 /// The index of the item that will be inspected by the next call to `next`.
2835 /// The number of items that have been drained (removed) thus far.
2837 /// The original length of `vec` prior to draining.
2839 /// The filter test predicate.
2841 /// A flag that indicates a panic has occured in the filter test prodicate.
2842 /// This is used as a hint in the drop implmentation to prevent consumption
2843 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
2844 /// backshifted in the `vec`, but no further items will be dropped or
2845 /// tested by the filter predicate.
2849 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2850 impl<T, F> Iterator for DrainFilter<'_, T, F>
2851 where F: FnMut(&mut T) -> bool,
2855 fn next(&mut self) -> Option<T> {
2857 while self.idx < self.old_len {
2859 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
2860 self.panic_flag = true;
2861 let drained = (self.pred)(&mut v[i]);
2862 self.panic_flag = false;
2863 // Update the index *after* the predicate is called. If the index
2864 // is updated prior and the predicate panics, the element at this
2865 // index would be leaked.
2869 return Some(ptr::read(&v[i]));
2870 } else if self.del > 0 {
2872 let src: *const T = &v[i];
2873 let dst: *mut T = &mut v[i - del];
2874 ptr::copy_nonoverlapping(src, dst, 1);
2881 fn size_hint(&self) -> (usize, Option<usize>) {
2882 (0, Some(self.old_len - self.idx))
2886 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2887 impl<T, F> Drop for DrainFilter<'_, T, F>
2888 where F: FnMut(&mut T) -> bool,
2890 fn drop(&mut self) {
2891 struct BackshiftOnDrop<'a, 'b, T, F>
2893 F: FnMut(&mut T) -> bool,
2895 drain: &'b mut DrainFilter<'a, T, F>,
2898 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
2900 F: FnMut(&mut T) -> bool
2902 fn drop(&mut self) {
2904 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
2905 // This is a pretty messed up state, and there isn't really an
2906 // obviously right thing to do. We don't want to keep trying
2907 // to execute `pred`, so we just backshift all the unprocessed
2908 // elements and tell the vec that they still exist. The backshift
2909 // is required to prevent a double-drop of the last successfully
2910 // drained item prior to a panic in the predicate.
2911 let ptr = self.drain.vec.as_mut_ptr();
2912 let src = ptr.add(self.drain.idx);
2913 let dst = src.sub(self.drain.del);
2914 let tail_len = self.drain.old_len - self.drain.idx;
2915 src.copy_to(dst, tail_len);
2917 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
2922 let backshift = BackshiftOnDrop {
2926 // Attempt to consume any remaining elements if the filter predicate
2927 // has not yet panicked. We'll backshift any remaining elements
2928 // whether we've already panicked or if the consumption here panics.
2929 if !backshift.drain.panic_flag {
2930 backshift.drain.for_each(drop);