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).
7 //! Vectors ensure they never allocate more than `isize::MAX` bytes.
11 //! You can explicitly create a [`Vec<T>`] with [`new`]:
14 //! let v: Vec<i32> = Vec::new();
17 //! ...or by using the [`vec!`] macro:
20 //! let v: Vec<i32> = vec![];
22 //! let v = vec![1, 2, 3, 4, 5];
24 //! let v = vec![0; 10]; // ten zeroes
27 //! You can [`push`] values onto the end of a vector (which will grow the vector
31 //! let mut v = vec![1, 2];
36 //! Popping values works in much the same way:
39 //! let mut v = vec![1, 2];
41 //! let two = v.pop();
44 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
47 //! let mut v = vec![1, 2, 3];
52 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
53 //! [`new`]: ../../std/vec/struct.Vec.html#method.new
54 //! [`push`]: ../../std/vec/struct.Vec.html#method.push
55 //! [`Index`]: ../../std/ops/trait.Index.html
56 //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
57 //! [`vec!`]: ../../std/macro.vec.html
59 #![stable(feature = "rust1", since = "1.0.0")]
61 use core::array::LengthAtMost32;
62 use core::cmp::{self, Ordering};
64 use core::hash::{self, Hash};
65 use core::intrinsics::{arith_offset, assume};
66 use core::iter::{FromIterator, FusedIterator, TrustedLen};
67 use core::marker::PhantomData;
69 use core::ops::Bound::{Excluded, Included, Unbounded};
70 use core::ops::{self, Index, IndexMut, RangeBounds};
71 use core::ptr::{self, NonNull};
72 use core::slice::{self, SliceIndex};
74 use crate::borrow::{Cow, ToOwned};
75 use crate::boxed::Box;
76 use crate::collections::TryReserveError;
77 use crate::raw_vec::RawVec;
79 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
84 /// let mut vec = Vec::new();
88 /// assert_eq!(vec.len(), 2);
89 /// assert_eq!(vec[0], 1);
91 /// assert_eq!(vec.pop(), Some(2));
92 /// assert_eq!(vec.len(), 1);
95 /// assert_eq!(vec[0], 7);
97 /// vec.extend([1, 2, 3].iter().copied());
100 /// println!("{}", x);
102 /// assert_eq!(vec, [7, 1, 2, 3]);
105 /// The [`vec!`] macro is provided to make initialization more convenient:
108 /// let mut vec = vec![1, 2, 3];
110 /// assert_eq!(vec, [1, 2, 3, 4]);
113 /// It can also initialize each element of a `Vec<T>` with a given value.
114 /// This may be more efficient than performing allocation and initialization
115 /// in separate steps, especially when initializing a vector of zeros:
118 /// let vec = vec![0; 5];
119 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
121 /// // The following is equivalent, but potentially slower:
122 /// let mut vec1 = Vec::with_capacity(5);
123 /// vec1.resize(5, 0);
126 /// Use a `Vec<T>` as an efficient stack:
129 /// let mut stack = Vec::new();
135 /// while let Some(top) = stack.pop() {
136 /// // Prints 3, 2, 1
137 /// println!("{}", top);
143 /// The `Vec` type allows to access values by index, because it implements the
144 /// [`Index`] trait. An example will be more explicit:
147 /// let v = vec![0, 2, 4, 6];
148 /// println!("{}", v[1]); // it will display '2'
151 /// However be careful: if you try to access an index which isn't in the `Vec`,
152 /// your software will panic! You cannot do this:
155 /// let v = vec![0, 2, 4, 6];
156 /// println!("{}", v[6]); // it will panic!
159 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
164 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
165 /// To get a slice, use `&`. Example:
168 /// fn read_slice(slice: &[usize]) {
172 /// let v = vec![0, 1];
175 /// // ... and that's all!
176 /// // you can also do it like this:
177 /// let x : &[usize] = &v;
180 /// In Rust, it's more common to pass slices as arguments rather than vectors
181 /// when you just want to provide read access. The same goes for [`String`] and
184 /// # Capacity and reallocation
186 /// The capacity of a vector is the amount of space allocated for any future
187 /// elements that will be added onto the vector. This is not to be confused with
188 /// the *length* of a vector, which specifies the number of actual elements
189 /// within the vector. If a vector's length exceeds its capacity, its capacity
190 /// will automatically be increased, but its elements will have to be
193 /// For example, a vector with capacity 10 and length 0 would be an empty vector
194 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
195 /// vector will not change its capacity or cause reallocation to occur. However,
196 /// if the vector's length is increased to 11, it will have to reallocate, which
197 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
198 /// whenever possible to specify how big the vector is expected to get.
202 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
203 /// about its design. This ensures that it's as low-overhead as possible in
204 /// the general case, and can be correctly manipulated in primitive ways
205 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
206 /// If additional type parameters are added (e.g., to support custom allocators),
207 /// overriding their defaults may change the behavior.
209 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
210 /// triplet. No more, no less. The order of these fields is completely
211 /// unspecified, and you should use the appropriate methods to modify these.
212 /// The pointer will never be null, so this type is null-pointer-optimized.
214 /// However, the pointer may not actually point to allocated memory. In particular,
215 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
216 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
217 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
218 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
219 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
220 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
221 /// details are very subtle — if you intend to allocate memory using a `Vec`
222 /// and use it for something else (either to pass to unsafe code, or to build your
223 /// own memory-backed collection), be sure to deallocate this memory by using
224 /// `from_raw_parts` to recover the `Vec` and then dropping it.
226 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
227 /// (as defined by the allocator Rust is configured to use by default), and its
228 /// pointer points to [`len`] initialized, contiguous elements in order (what
229 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
230 /// `[`len`] logically uninitialized, contiguous elements.
232 /// `Vec` will never perform a "small optimization" where elements are actually
233 /// stored on the stack for two reasons:
235 /// * It would make it more difficult for unsafe code to correctly manipulate
236 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
237 /// only moved, and it would be more difficult to determine if a `Vec` had
238 /// actually allocated memory.
240 /// * It would penalize the general case, incurring an additional branch
243 /// `Vec` will never automatically shrink itself, even if completely empty. This
244 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
245 /// and then filling it back up to the same [`len`] should incur no calls to
246 /// the allocator. If you wish to free up unused memory, use
247 /// [`shrink_to_fit`].
249 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
250 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
251 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
252 /// accurate, and can be relied on. It can even be used to manually free the memory
253 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
254 /// when not necessary.
256 /// `Vec` does not guarantee any particular growth strategy when reallocating
257 /// when full, nor when [`reserve`] is called. The current strategy is basic
258 /// and it may prove desirable to use a non-constant growth factor. Whatever
259 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
261 /// `vec![x; n]`, `vec![a, b, c, d]`, and
262 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
263 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
264 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
265 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
267 /// `Vec` will not specifically overwrite any data that is removed from it,
268 /// but also won't specifically preserve it. Its uninitialized memory is
269 /// scratch space that it may use however it wants. It will generally just do
270 /// whatever is most efficient or otherwise easy to implement. Do not rely on
271 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
272 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
273 /// first, that may not actually happen because the optimizer does not consider
274 /// this a side-effect that must be preserved. There is one case which we will
275 /// not break, however: using `unsafe` code to write to the excess capacity,
276 /// and then increasing the length to match, is always valid.
278 /// `Vec` does not currently guarantee the order in which elements are dropped.
279 /// The order has changed in the past and may change again.
281 /// [`vec!`]: ../../std/macro.vec.html
282 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
283 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
284 /// [`Index`]: ../../std/ops/trait.Index.html
285 /// [`String`]: ../../std/string/struct.String.html
286 /// [`&str`]: ../../std/primitive.str.html
287 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
288 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
289 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
290 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
291 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
292 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
293 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
294 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
295 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
296 /// [owned slice]: ../../std/boxed/struct.Box.html
297 #[stable(feature = "rust1", since = "1.0.0")]
298 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
304 ////////////////////////////////////////////////////////////////////////////////
306 ////////////////////////////////////////////////////////////////////////////////
309 /// Constructs a new, empty `Vec<T>`.
311 /// The vector will not allocate until elements are pushed onto it.
316 /// # #![allow(unused_mut)]
317 /// let mut vec: Vec<i32> = Vec::new();
320 #[rustc_const_stable(feature = "const_vec_new", since = "1.32.0")]
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub const fn new() -> Vec<T> {
323 Vec { buf: RawVec::NEW, len: 0 }
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> {
357 Vec { buf: RawVec::with_capacity(capacity), len: 0 }
360 /// Decomposes a `Vec<T>` into its raw components.
362 /// Returns the raw pointer to the underlying data, the length of
363 /// the vector (in elements), and the allocated capacity of the
364 /// data (in elements). These are the same arguments in the same
365 /// order as the arguments to [`from_raw_parts`].
367 /// After calling this function, the caller is responsible for the
368 /// memory previously managed by the `Vec`. The only way to do
369 /// this is to convert the raw pointer, length, and capacity back
370 /// into a `Vec` with the [`from_raw_parts`] function, allowing
371 /// the destructor to perform the cleanup.
373 /// [`from_raw_parts`]: #method.from_raw_parts
378 /// #![feature(vec_into_raw_parts)]
379 /// let v: Vec<i32> = vec![-1, 0, 1];
381 /// let (ptr, len, cap) = v.into_raw_parts();
383 /// let rebuilt = unsafe {
384 /// // We can now make changes to the components, such as
385 /// // transmuting the raw pointer to a compatible type.
386 /// let ptr = ptr as *mut u32;
388 /// Vec::from_raw_parts(ptr, len, cap)
390 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
392 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
393 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
394 let mut me = mem::ManuallyDrop::new(self);
395 (me.as_mut_ptr(), me.len(), me.capacity())
398 /// Creates a `Vec<T>` directly from the raw components of another vector.
402 /// This is highly unsafe, due to the number of invariants that aren't
405 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
406 /// (at least, it's highly likely to be incorrect if it wasn't).
407 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
408 /// (`T` having a less strict alignment is not sufficient, the alignment really
409 /// needs to be equal to satsify the [`dealloc`] requirement that memory must be
410 /// allocated and deallocated with the same layout.)
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
429 /// [`dealloc`]: ../../alloc/alloc/trait.GlobalAlloc.html#tymethod.dealloc
437 /// let v = vec![1, 2, 3];
439 // FIXME Update this when vec_into_raw_parts is stabilized
440 /// // Prevent running `v`'s destructor so we are in complete control
441 /// // of the allocation.
442 /// let mut v = mem::ManuallyDrop::new(v);
444 /// // Pull out the various important pieces of information about `v`
445 /// let p = v.as_mut_ptr();
446 /// let len = v.len();
447 /// let cap = v.capacity();
450 /// // Overwrite memory with 4, 5, 6
451 /// for i in 0..len as isize {
452 /// ptr::write(p.offset(i), 4 + i);
455 /// // Put everything back together into a Vec
456 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
457 /// assert_eq!(rebuilt, [4, 5, 6]);
460 #[stable(feature = "rust1", since = "1.0.0")]
461 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
462 Vec { buf: RawVec::from_raw_parts(ptr, capacity), len: length }
465 /// Returns the number of elements the vector can hold without
471 /// let vec: Vec<i32> = Vec::with_capacity(10);
472 /// assert_eq!(vec.capacity(), 10);
475 #[stable(feature = "rust1", since = "1.0.0")]
476 pub fn capacity(&self) -> usize {
480 /// Reserves capacity for at least `additional` more elements to be inserted
481 /// in the given `Vec<T>`. The collection may reserve more space to avoid
482 /// frequent reallocations. After calling `reserve`, capacity will be
483 /// greater than or equal to `self.len() + additional`. Does nothing if
484 /// capacity is already sufficient.
488 /// Panics if the new capacity overflows `usize`.
493 /// let mut vec = vec![1];
495 /// assert!(vec.capacity() >= 11);
497 #[stable(feature = "rust1", since = "1.0.0")]
498 pub fn reserve(&mut self, additional: usize) {
499 self.buf.reserve(self.len, additional);
502 /// Reserves the minimum capacity for exactly `additional` more elements to
503 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
504 /// capacity will be greater than or equal to `self.len() + additional`.
505 /// Does nothing if the capacity is already sufficient.
507 /// Note that the allocator may give the collection more space than it
508 /// requests. Therefore, capacity can not be relied upon to be precisely
509 /// minimal. Prefer `reserve` if future insertions are expected.
513 /// Panics if the new capacity overflows `usize`.
518 /// let mut vec = vec![1];
519 /// vec.reserve_exact(10);
520 /// assert!(vec.capacity() >= 11);
522 #[stable(feature = "rust1", since = "1.0.0")]
523 pub fn reserve_exact(&mut self, additional: usize) {
524 self.buf.reserve_exact(self.len, additional);
527 /// Tries to reserve capacity for at least `additional` more elements to be inserted
528 /// in the given `Vec<T>`. The collection may reserve more space to avoid
529 /// frequent reallocations. After calling `reserve`, capacity will be
530 /// greater than or equal to `self.len() + additional`. Does nothing if
531 /// capacity is already sufficient.
535 /// If the capacity overflows, or the allocator reports a failure, then an error
541 /// #![feature(try_reserve)]
542 /// use std::collections::TryReserveError;
544 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
545 /// let mut output = Vec::new();
547 /// // Pre-reserve the memory, exiting if we can't
548 /// output.try_reserve(data.len())?;
550 /// // Now we know this can't OOM in the middle of our complex work
551 /// output.extend(data.iter().map(|&val| {
552 /// val * 2 + 5 // very complicated
557 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
559 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
560 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
561 self.buf.try_reserve(self.len, additional)
564 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
565 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
566 /// capacity will be greater than or equal to `self.len() + additional`.
567 /// Does nothing if the capacity is already sufficient.
569 /// Note that the allocator may give the collection more space than it
570 /// requests. Therefore, capacity can not be relied upon to be precisely
571 /// minimal. Prefer `reserve` if future insertions are expected.
575 /// If the capacity overflows, or the allocator reports a failure, then an error
581 /// #![feature(try_reserve)]
582 /// use std::collections::TryReserveError;
584 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
585 /// let mut output = Vec::new();
587 /// // Pre-reserve the memory, exiting if we can't
588 /// output.try_reserve(data.len())?;
590 /// // Now we know this can't OOM in the middle of our complex work
591 /// output.extend(data.iter().map(|&val| {
592 /// val * 2 + 5 // very complicated
597 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
599 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
600 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
601 self.buf.try_reserve_exact(self.len, additional)
604 /// Shrinks the capacity of the vector as much as possible.
606 /// It will drop down as close as possible to the length but the allocator
607 /// may still inform the vector that there is space for a few more elements.
612 /// let mut vec = Vec::with_capacity(10);
613 /// vec.extend([1, 2, 3].iter().cloned());
614 /// assert_eq!(vec.capacity(), 10);
615 /// vec.shrink_to_fit();
616 /// assert!(vec.capacity() >= 3);
618 #[stable(feature = "rust1", since = "1.0.0")]
619 pub fn shrink_to_fit(&mut self) {
620 if self.capacity() != self.len {
621 self.buf.shrink_to_fit(self.len);
625 /// Shrinks the capacity of the vector with a lower bound.
627 /// The capacity will remain at least as large as both the length
628 /// 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();
813 assume(!ptr.is_null());
818 /// Returns an unsafe mutable pointer to the vector's buffer.
820 /// The caller must ensure that the vector outlives the pointer this
821 /// function returns, or else it will end up pointing to garbage.
822 /// Modifying the vector may cause its buffer to be reallocated,
823 /// which would also make any pointers to it invalid.
828 /// // Allocate vector big enough for 4 elements.
830 /// let mut x: Vec<i32> = Vec::with_capacity(size);
831 /// let x_ptr = x.as_mut_ptr();
833 /// // Initialize elements via raw pointer writes, then set length.
835 /// for i in 0..size {
836 /// *x_ptr.add(i) = i as i32;
840 /// assert_eq!(&*x, &[0,1,2,3]);
842 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
844 pub fn as_mut_ptr(&mut self) -> *mut T {
845 // We shadow the slice method of the same name to avoid going through
846 // `deref_mut`, which creates an intermediate reference.
847 let ptr = self.buf.ptr();
849 assume(!ptr.is_null());
854 /// Forces the length of the vector to `new_len`.
856 /// This is a low-level operation that maintains none of the normal
857 /// invariants of the type. Normally changing the length of a vector
858 /// is done using one of the safe operations instead, such as
859 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
861 /// [`truncate`]: #method.truncate
862 /// [`resize`]: #method.resize
863 /// [`extend`]: ../../std/iter/trait.Extend.html#tymethod.extend
864 /// [`clear`]: #method.clear
868 /// - `new_len` must be less than or equal to [`capacity()`].
869 /// - The elements at `old_len..new_len` must be initialized.
871 /// [`capacity()`]: #method.capacity
875 /// This method can be useful for situations in which the vector
876 /// is serving as a buffer for other code, particularly over FFI:
879 /// # #![allow(dead_code)]
880 /// # // This is just a minimal skeleton for the doc example;
881 /// # // don't use this as a starting point for a real library.
882 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
883 /// # const Z_OK: i32 = 0;
885 /// # fn deflateGetDictionary(
886 /// # strm: *mut std::ffi::c_void,
887 /// # dictionary: *mut u8,
888 /// # dictLength: *mut usize,
891 /// # impl StreamWrapper {
892 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
893 /// // Per the FFI method's docs, "32768 bytes is always enough".
894 /// let mut dict = Vec::with_capacity(32_768);
895 /// let mut dict_length = 0;
896 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
897 /// // 1. `dict_length` elements were initialized.
898 /// // 2. `dict_length` <= the capacity (32_768)
899 /// // which makes `set_len` safe to call.
901 /// // Make the FFI call...
902 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
904 /// // ...and update the length to what was initialized.
905 /// dict.set_len(dict_length);
915 /// While the following example is sound, there is a memory leak since
916 /// the inner vectors were not freed prior to the `set_len` call:
919 /// let mut vec = vec![vec![1, 0, 0],
923 /// // 1. `old_len..0` is empty so no elements need to be initialized.
924 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
930 /// Normally, here, one would use [`clear`] instead to correctly drop
931 /// the contents and thus not leak memory.
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub unsafe fn set_len(&mut self, new_len: usize) {
935 debug_assert!(new_len <= self.capacity());
940 /// Removes an element from the vector and returns it.
942 /// The removed element is replaced by the last element of the vector.
944 /// This does not preserve ordering, but is O(1).
948 /// Panics if `index` is out of bounds.
953 /// let mut v = vec!["foo", "bar", "baz", "qux"];
955 /// assert_eq!(v.swap_remove(1), "bar");
956 /// assert_eq!(v, ["foo", "qux", "baz"]);
958 /// assert_eq!(v.swap_remove(0), "foo");
959 /// assert_eq!(v, ["baz", "qux"]);
962 #[stable(feature = "rust1", since = "1.0.0")]
963 pub fn swap_remove(&mut self, index: usize) -> T {
965 // We replace self[index] with the last element. Note that if the
966 // bounds check on hole succeeds there must be a last element (which
967 // can be self[index] itself).
968 let hole: *mut T = &mut self[index];
969 let last = ptr::read(self.get_unchecked(self.len - 1));
971 ptr::replace(hole, last)
975 /// Inserts an element at position `index` within the vector, shifting all
976 /// elements after it to the right.
980 /// Panics if `index > len`.
985 /// let mut vec = vec![1, 2, 3];
986 /// vec.insert(1, 4);
987 /// assert_eq!(vec, [1, 4, 2, 3]);
988 /// vec.insert(4, 5);
989 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
991 #[stable(feature = "rust1", since = "1.0.0")]
992 pub fn insert(&mut self, index: usize, element: T) {
993 let len = self.len();
994 assert!(index <= len);
996 // space for the new element
997 if len == self.buf.capacity() {
1003 // The spot to put the new value
1005 let p = self.as_mut_ptr().add(index);
1006 // Shift everything over to make space. (Duplicating the
1007 // `index`th element into two consecutive places.)
1008 ptr::copy(p, p.offset(1), len - index);
1009 // Write it in, overwriting the first copy of the `index`th
1011 ptr::write(p, element);
1013 self.set_len(len + 1);
1017 /// Removes and returns the element at position `index` within the vector,
1018 /// shifting all elements after it to the left.
1022 /// Panics if `index` is out of bounds.
1027 /// let mut v = vec![1, 2, 3];
1028 /// assert_eq!(v.remove(1), 2);
1029 /// assert_eq!(v, [1, 3]);
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 pub fn remove(&mut self, index: usize) -> T {
1033 let len = self.len();
1034 assert!(index < len);
1039 // the place we are taking from.
1040 let ptr = self.as_mut_ptr().add(index);
1041 // copy it out, unsafely having a copy of the value on
1042 // the stack and in the vector at the same time.
1043 ret = ptr::read(ptr);
1045 // Shift everything down to fill in that spot.
1046 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1048 self.set_len(len - 1);
1053 /// Retains only the elements specified by the predicate.
1055 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1056 /// This method operates in place, visiting each element exactly once in the
1057 /// original order, and preserves the order of the retained elements.
1062 /// let mut vec = vec![1, 2, 3, 4];
1063 /// vec.retain(|&x| x % 2 == 0);
1064 /// assert_eq!(vec, [2, 4]);
1067 /// The exact order may be useful for tracking external state, like an index.
1070 /// let mut vec = vec![1, 2, 3, 4, 5];
1071 /// let keep = [false, true, true, false, true];
1073 /// vec.retain(|_| (keep[i], i += 1).0);
1074 /// assert_eq!(vec, [2, 3, 5]);
1076 #[stable(feature = "rust1", since = "1.0.0")]
1077 pub fn retain<F>(&mut self, mut f: F)
1079 F: FnMut(&T) -> bool,
1081 let len = self.len();
1084 let v = &mut **self;
1095 self.truncate(len - del);
1099 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1102 /// If the vector is sorted, this removes all duplicates.
1107 /// let mut vec = vec![10, 20, 21, 30, 20];
1109 /// vec.dedup_by_key(|i| *i / 10);
1111 /// assert_eq!(vec, [10, 20, 30, 20]);
1113 #[stable(feature = "dedup_by", since = "1.16.0")]
1115 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1117 F: FnMut(&mut T) -> K,
1120 self.dedup_by(|a, b| key(a) == key(b))
1123 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1126 /// The `same_bucket` function is passed references to two elements from the vector and
1127 /// must determine if the elements compare equal. The elements are passed in opposite order
1128 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1130 /// If the vector is sorted, this removes all duplicates.
1135 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1137 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1139 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1141 #[stable(feature = "dedup_by", since = "1.16.0")]
1142 pub fn dedup_by<F>(&mut self, same_bucket: F)
1144 F: FnMut(&mut T, &mut T) -> bool,
1147 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1153 /// Appends an element to the back of a collection.
1157 /// Panics if the number of elements in the vector overflows a `usize`.
1162 /// let mut vec = vec![1, 2];
1164 /// assert_eq!(vec, [1, 2, 3]);
1167 #[stable(feature = "rust1", since = "1.0.0")]
1168 pub fn push(&mut self, value: T) {
1169 // This will panic or abort if we would allocate > isize::MAX bytes
1170 // or if the length increment would overflow for zero-sized types.
1171 if self.len == self.buf.capacity() {
1175 let end = self.as_mut_ptr().add(self.len);
1176 ptr::write(end, value);
1181 /// Removes the last element from a vector and returns it, or [`None`] if it
1184 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1189 /// let mut vec = vec![1, 2, 3];
1190 /// assert_eq!(vec.pop(), Some(3));
1191 /// assert_eq!(vec, [1, 2]);
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 pub fn pop(&mut self) -> Option<T> {
1201 Some(ptr::read(self.get_unchecked(self.len())))
1206 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1210 /// Panics if the number of elements in the vector overflows a `usize`.
1215 /// let mut vec = vec![1, 2, 3];
1216 /// let mut vec2 = vec![4, 5, 6];
1217 /// vec.append(&mut vec2);
1218 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1219 /// assert_eq!(vec2, []);
1222 #[stable(feature = "append", since = "1.4.0")]
1223 pub fn append(&mut self, other: &mut Self) {
1225 self.append_elements(other.as_slice() as _);
1230 /// Appends elements to `Self` from other buffer.
1232 unsafe fn append_elements(&mut self, other: *const [T]) {
1233 let count = (*other).len();
1234 self.reserve(count);
1235 let len = self.len();
1236 ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count);
1240 /// Creates a draining iterator that removes the specified range in the vector
1241 /// and yields the removed items.
1243 /// Note 1: The element range is removed even if the iterator is only
1244 /// partially consumed or not consumed at all.
1246 /// Note 2: It is unspecified how many elements are removed from the vector
1247 /// if the `Drain` value is leaked.
1251 /// Panics if the starting point is greater than the end point or if
1252 /// the end point is greater than the length of the vector.
1257 /// let mut v = vec![1, 2, 3];
1258 /// let u: Vec<_> = v.drain(1..).collect();
1259 /// assert_eq!(v, &[1]);
1260 /// assert_eq!(u, &[2, 3]);
1262 /// // A full range clears the vector
1264 /// assert_eq!(v, &[]);
1266 #[stable(feature = "drain", since = "1.6.0")]
1267 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1269 R: RangeBounds<usize>,
1273 // When the Drain is first created, it shortens the length of
1274 // the source vector to make sure no uninitialized or moved-from elements
1275 // are accessible at all if the Drain's destructor never gets to run.
1277 // Drain will ptr::read out the values to remove.
1278 // When finished, remaining tail of the vec is copied back to cover
1279 // the hole, and the vector length is restored to the new length.
1281 let len = self.len();
1282 let start = match range.start_bound() {
1284 Excluded(&n) => n + 1,
1287 let end = match range.end_bound() {
1288 Included(&n) => n + 1,
1292 assert!(start <= end);
1293 assert!(end <= len);
1296 // set self.vec length's to start, to be safe in case Drain is leaked
1297 self.set_len(start);
1298 // Use the borrow in the IterMut to indicate borrowing behavior of the
1299 // whole Drain iterator (like &mut T).
1300 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1303 tail_len: len - end,
1304 iter: range_slice.iter(),
1305 vec: NonNull::from(self),
1310 /// Clears the vector, removing all values.
1312 /// Note that this method has no effect on the allocated capacity
1318 /// let mut v = vec![1, 2, 3];
1322 /// assert!(v.is_empty());
1325 #[stable(feature = "rust1", since = "1.0.0")]
1326 pub fn clear(&mut self) {
1330 /// Returns the number of elements in the vector, also referred to
1331 /// as its 'length'.
1336 /// let a = vec![1, 2, 3];
1337 /// assert_eq!(a.len(), 3);
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 pub fn len(&self) -> usize {
1345 /// Returns `true` if the vector contains no elements.
1350 /// let mut v = Vec::new();
1351 /// assert!(v.is_empty());
1354 /// assert!(!v.is_empty());
1356 #[stable(feature = "rust1", since = "1.0.0")]
1357 pub fn is_empty(&self) -> bool {
1361 /// Splits the collection into two at the given index.
1363 /// Returns a newly allocated vector containing the elements in the range
1364 /// `[at, len)`. After the call, the original vector will be left containing
1365 /// the elements `[0, at)` with its previous capacity unchanged.
1369 /// Panics if `at > len`.
1374 /// let mut vec = vec![1,2,3];
1375 /// let vec2 = vec.split_off(1);
1376 /// assert_eq!(vec, [1]);
1377 /// assert_eq!(vec2, [2, 3]);
1380 #[stable(feature = "split_off", since = "1.4.0")]
1381 pub fn split_off(&mut self, at: usize) -> Self {
1382 assert!(at <= self.len(), "`at` out of bounds");
1384 let other_len = self.len - at;
1385 let mut other = Vec::with_capacity(other_len);
1387 // Unsafely `set_len` and copy items to `other`.
1390 other.set_len(other_len);
1392 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1397 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1399 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1400 /// difference, with each additional slot filled with the result of
1401 /// calling the closure `f`. The return values from `f` will end up
1402 /// in the `Vec` in the order they have been generated.
1404 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1406 /// This method uses a closure to create new values on every push. If
1407 /// you'd rather [`Clone`] a given value, use [`resize`]. If you want
1408 /// to use the [`Default`] trait to generate values, you can pass
1409 /// [`Default::default()`] as the second argument.
1414 /// let mut vec = vec![1, 2, 3];
1415 /// vec.resize_with(5, Default::default);
1416 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1418 /// let mut vec = vec![];
1420 /// vec.resize_with(4, || { p *= 2; p });
1421 /// assert_eq!(vec, [2, 4, 8, 16]);
1424 /// [`resize`]: #method.resize
1425 /// [`Clone`]: ../../std/clone/trait.Clone.html
1426 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1427 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1431 let len = self.len();
1433 self.extend_with(new_len - len, ExtendFunc(f));
1435 self.truncate(new_len);
1439 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1440 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1441 /// `'a`. If the type has only static references, or none at all, then this
1442 /// may be chosen to be `'static`.
1444 /// This function is similar to the `leak` function on `Box`.
1446 /// This function is mainly useful for data that lives for the remainder of
1447 /// the program's life. Dropping the returned reference will cause a memory
1455 /// #![feature(vec_leak)]
1457 /// let x = vec![1, 2, 3];
1458 /// let static_ref: &'static mut [usize] = Vec::leak(x);
1459 /// static_ref[0] += 1;
1460 /// assert_eq!(static_ref, &[2, 2, 3]);
1462 #[unstable(feature = "vec_leak", issue = "62195")]
1464 pub fn leak<'a>(vec: Vec<T>) -> &'a mut [T]
1466 T: 'a, // Technically not needed, but kept to be explicit.
1468 Box::leak(vec.into_boxed_slice())
1472 impl<T: Clone> Vec<T> {
1473 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1475 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1476 /// difference, with each additional slot filled with `value`.
1477 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1479 /// This method requires [`Clone`] to be able clone the passed value. If
1480 /// you need more flexibility (or want to rely on [`Default`] instead of
1481 /// [`Clone`]), use [`resize_with`].
1486 /// let mut vec = vec!["hello"];
1487 /// vec.resize(3, "world");
1488 /// assert_eq!(vec, ["hello", "world", "world"]);
1490 /// let mut vec = vec![1, 2, 3, 4];
1491 /// vec.resize(2, 0);
1492 /// assert_eq!(vec, [1, 2]);
1495 /// [`Clone`]: ../../std/clone/trait.Clone.html
1496 /// [`Default`]: ../../std/default/trait.Default.html
1497 /// [`resize_with`]: #method.resize_with
1498 #[stable(feature = "vec_resize", since = "1.5.0")]
1499 pub fn resize(&mut self, new_len: usize, value: T) {
1500 let len = self.len();
1503 self.extend_with(new_len - len, ExtendElement(value))
1505 self.truncate(new_len);
1509 /// Clones and appends all elements in a slice to the `Vec`.
1511 /// Iterates over the slice `other`, clones each element, and then appends
1512 /// it to this `Vec`. The `other` vector is traversed in-order.
1514 /// Note that this function is same as [`extend`] except that it is
1515 /// specialized to work with slices instead. If and when Rust gets
1516 /// specialization this function will likely be deprecated (but still
1522 /// let mut vec = vec![1];
1523 /// vec.extend_from_slice(&[2, 3, 4]);
1524 /// assert_eq!(vec, [1, 2, 3, 4]);
1527 /// [`extend`]: #method.extend
1528 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1529 pub fn extend_from_slice(&mut self, other: &[T]) {
1530 self.spec_extend(other.iter())
1534 impl<T: Default> Vec<T> {
1535 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1537 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1538 /// difference, with each additional slot filled with [`Default::default()`].
1539 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1541 /// This method uses [`Default`] to create new values on every push. If
1542 /// you'd rather [`Clone`] a given value, use [`resize`].
1547 /// # #![allow(deprecated)]
1548 /// #![feature(vec_resize_default)]
1550 /// let mut vec = vec![1, 2, 3];
1551 /// vec.resize_default(5);
1552 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1554 /// let mut vec = vec![1, 2, 3, 4];
1555 /// vec.resize_default(2);
1556 /// assert_eq!(vec, [1, 2]);
1559 /// [`resize`]: #method.resize
1560 /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default
1561 /// [`Default`]: ../../std/default/trait.Default.html
1562 /// [`Clone`]: ../../std/clone/trait.Clone.html
1563 #[unstable(feature = "vec_resize_default", issue = "41758")]
1565 reason = "This is moving towards being removed in favor \
1566 of `.resize_with(Default::default)`. If you disagree, please comment \
1567 in the tracking issue.",
1570 pub fn resize_default(&mut self, new_len: usize) {
1571 let len = self.len();
1574 self.extend_with(new_len - len, ExtendDefault);
1576 self.truncate(new_len);
1581 // This code generalises `extend_with_{element,default}`.
1582 trait ExtendWith<T> {
1583 fn next(&mut self) -> T;
1587 struct ExtendElement<T>(T);
1588 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1589 fn next(&mut self) -> T {
1592 fn last(self) -> T {
1597 struct ExtendDefault;
1598 impl<T: Default> ExtendWith<T> for ExtendDefault {
1599 fn next(&mut self) -> T {
1602 fn last(self) -> T {
1607 struct ExtendFunc<F>(F);
1608 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1609 fn next(&mut self) -> T {
1612 fn last(mut self) -> T {
1618 /// Extend the vector by `n` values, using the given generator.
1619 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1623 let mut ptr = self.as_mut_ptr().add(self.len());
1624 // Use SetLenOnDrop to work around bug where compiler
1625 // may not realize the store through `ptr` through self.set_len()
1627 let mut local_len = SetLenOnDrop::new(&mut self.len);
1629 // Write all elements except the last one
1631 ptr::write(ptr, value.next());
1632 ptr = ptr.offset(1);
1633 // Increment the length in every step in case next() panics
1634 local_len.increment_len(1);
1638 // We can write the last element directly without cloning needlessly
1639 ptr::write(ptr, value.last());
1640 local_len.increment_len(1);
1643 // len set by scope guard
1648 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1650 // The idea is: The length field in SetLenOnDrop is a local variable
1651 // that the optimizer will see does not alias with any stores through the Vec's data
1652 // pointer. This is a workaround for alias analysis issue #32155
1653 struct SetLenOnDrop<'a> {
1658 impl<'a> SetLenOnDrop<'a> {
1660 fn new(len: &'a mut usize) -> Self {
1661 SetLenOnDrop { local_len: *len, len: len }
1665 fn increment_len(&mut self, increment: usize) {
1666 self.local_len += increment;
1670 impl Drop for SetLenOnDrop<'_> {
1672 fn drop(&mut self) {
1673 *self.len = self.local_len;
1677 impl<T: PartialEq> Vec<T> {
1678 /// Removes consecutive repeated elements in the vector according to the
1679 /// [`PartialEq`] trait implementation.
1681 /// If the vector is sorted, this removes all duplicates.
1686 /// let mut vec = vec![1, 2, 2, 3, 2];
1690 /// assert_eq!(vec, [1, 2, 3, 2]);
1692 #[stable(feature = "rust1", since = "1.0.0")]
1694 pub fn dedup(&mut self) {
1695 self.dedup_by(|a, b| a == b)
1700 /// Removes the first instance of `item` from the vector if the item exists.
1705 /// # #![feature(vec_remove_item)]
1706 /// let mut vec = vec![1, 2, 3, 1];
1708 /// vec.remove_item(&1);
1710 /// assert_eq!(vec, vec![2, 3, 1]);
1712 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1713 pub fn remove_item<V>(&mut self, item: &V) -> Option<T>
1717 let pos = self.iter().position(|x| *x == *item)?;
1718 Some(self.remove(pos))
1722 ////////////////////////////////////////////////////////////////////////////////
1723 // Internal methods and functions
1724 ////////////////////////////////////////////////////////////////////////////////
1727 #[stable(feature = "rust1", since = "1.0.0")]
1728 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1729 <T as SpecFromElem>::from_elem(elem, n)
1732 // Specialization trait used for Vec::from_elem
1733 trait SpecFromElem: Sized {
1734 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1737 impl<T: Clone> SpecFromElem for T {
1738 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1739 let mut v = Vec::with_capacity(n);
1740 v.extend_with(n, ExtendElement(elem));
1745 impl SpecFromElem for u8 {
1747 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1749 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1752 let mut v = Vec::with_capacity(n);
1753 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1760 impl<T: Clone + IsZero> SpecFromElem for T {
1762 fn from_elem(elem: T, n: usize) -> Vec<T> {
1764 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1766 let mut v = Vec::with_capacity(n);
1767 v.extend_with(n, ExtendElement(elem));
1772 unsafe trait IsZero {
1773 /// Whether this value is zero
1774 fn is_zero(&self) -> bool;
1777 macro_rules! impl_is_zero {
1778 ($t: ty, $is_zero: expr) => {
1779 unsafe impl IsZero for $t {
1781 fn is_zero(&self) -> bool {
1788 impl_is_zero!(i8, |x| x == 0);
1789 impl_is_zero!(i16, |x| x == 0);
1790 impl_is_zero!(i32, |x| x == 0);
1791 impl_is_zero!(i64, |x| x == 0);
1792 impl_is_zero!(i128, |x| x == 0);
1793 impl_is_zero!(isize, |x| x == 0);
1795 impl_is_zero!(u16, |x| x == 0);
1796 impl_is_zero!(u32, |x| x == 0);
1797 impl_is_zero!(u64, |x| x == 0);
1798 impl_is_zero!(u128, |x| x == 0);
1799 impl_is_zero!(usize, |x| x == 0);
1801 impl_is_zero!(bool, |x| x == false);
1802 impl_is_zero!(char, |x| x == '\0');
1804 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1805 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1807 unsafe impl<T> IsZero for *const T {
1809 fn is_zero(&self) -> bool {
1814 unsafe impl<T> IsZero for *mut T {
1816 fn is_zero(&self) -> bool {
1821 // `Option<&T>`, `Option<&mut T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
1822 // For fat pointers, the bytes that would be the pointer metadata in the `Some` variant
1823 // are padding in the `None` variant, so ignoring them and zero-initializing instead is ok.
1825 unsafe impl<T: ?Sized> IsZero for Option<&T> {
1827 fn is_zero(&self) -> bool {
1832 unsafe impl<T: ?Sized> IsZero for Option<&mut T> {
1834 fn is_zero(&self) -> bool {
1839 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
1841 fn is_zero(&self) -> bool {
1846 ////////////////////////////////////////////////////////////////////////////////
1847 // Common trait implementations for Vec
1848 ////////////////////////////////////////////////////////////////////////////////
1850 #[stable(feature = "rust1", since = "1.0.0")]
1851 impl<T: Clone> Clone for Vec<T> {
1853 fn clone(&self) -> Vec<T> {
1854 <[T]>::to_vec(&**self)
1857 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1858 // required for this method definition, is not available. Instead use the
1859 // `slice::to_vec` function which is only available with cfg(test)
1860 // NB see the slice::hack module in slice.rs for more information
1862 fn clone(&self) -> Vec<T> {
1863 crate::slice::to_vec(&**self)
1866 fn clone_from(&mut self, other: &Vec<T>) {
1867 other.as_slice().clone_into(self);
1871 #[stable(feature = "rust1", since = "1.0.0")]
1872 impl<T: Hash> Hash for Vec<T> {
1874 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1875 Hash::hash(&**self, state)
1879 #[stable(feature = "rust1", since = "1.0.0")]
1880 #[rustc_on_unimplemented(
1881 message = "vector indices are of type `usize` or ranges of `usize`",
1882 label = "vector indices are of type `usize` or ranges of `usize`"
1884 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
1885 type Output = I::Output;
1888 fn index(&self, index: I) -> &Self::Output {
1889 Index::index(&**self, index)
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 #[rustc_on_unimplemented(
1895 message = "vector indices are of type `usize` or ranges of `usize`",
1896 label = "vector indices are of type `usize` or ranges of `usize`"
1898 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
1900 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1901 IndexMut::index_mut(&mut **self, index)
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 impl<T> ops::Deref for Vec<T> {
1909 fn deref(&self) -> &[T] {
1910 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
1914 #[stable(feature = "rust1", since = "1.0.0")]
1915 impl<T> ops::DerefMut for Vec<T> {
1916 fn deref_mut(&mut self) -> &mut [T] {
1917 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl<T> FromIterator<T> for Vec<T> {
1924 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1925 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 impl<T> IntoIterator for Vec<T> {
1932 type IntoIter = IntoIter<T>;
1934 /// Creates a consuming iterator, that is, one that moves each value out of
1935 /// the vector (from start to end). The vector cannot be used after calling
1941 /// let v = vec!["a".to_string(), "b".to_string()];
1942 /// for s in v.into_iter() {
1943 /// // s has type String, not &String
1944 /// println!("{}", s);
1948 fn into_iter(mut self) -> IntoIter<T> {
1950 let begin = self.as_mut_ptr();
1951 let end = if mem::size_of::<T>() == 0 {
1952 arith_offset(begin as *const i8, self.len() as isize) as *const T
1954 begin.add(self.len()) as *const T
1956 let cap = self.buf.capacity();
1959 buf: NonNull::new_unchecked(begin),
1960 phantom: PhantomData,
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl<'a, T> IntoIterator for &'a Vec<T> {
1972 type IntoIter = slice::Iter<'a, T>;
1974 fn into_iter(self) -> slice::Iter<'a, T> {
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1981 type Item = &'a mut T;
1982 type IntoIter = slice::IterMut<'a, T>;
1984 fn into_iter(self) -> slice::IterMut<'a, T> {
1989 #[stable(feature = "rust1", since = "1.0.0")]
1990 impl<T> Extend<T> for Vec<T> {
1992 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1993 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1997 // Specialization trait used for Vec::from_iter and Vec::extend
1998 trait SpecExtend<T, I> {
1999 fn from_iter(iter: I) -> Self;
2000 fn spec_extend(&mut self, iter: I);
2003 impl<T, I> SpecExtend<T, I> for Vec<T>
2005 I: Iterator<Item = T>,
2007 default fn from_iter(mut iterator: I) -> Self {
2008 // Unroll the first iteration, as the vector is going to be
2009 // expanded on this iteration in every case when the iterable is not
2010 // empty, but the loop in extend_desugared() is not going to see the
2011 // vector being full in the few subsequent loop iterations.
2012 // So we get better branch prediction.
2013 let mut vector = match iterator.next() {
2014 None => return Vec::new(),
2016 let (lower, _) = iterator.size_hint();
2017 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2019 ptr::write(vector.get_unchecked_mut(0), element);
2025 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2029 default fn spec_extend(&mut self, iter: I) {
2030 self.extend_desugared(iter)
2034 impl<T, I> SpecExtend<T, I> for Vec<T>
2036 I: TrustedLen<Item = T>,
2038 default fn from_iter(iterator: I) -> Self {
2039 let mut vector = Vec::new();
2040 vector.spec_extend(iterator);
2044 default fn spec_extend(&mut self, iterator: I) {
2045 // This is the case for a TrustedLen iterator.
2046 let (low, high) = iterator.size_hint();
2047 if let Some(high_value) = high {
2051 "TrustedLen iterator's size hint is not exact: {:?}",
2055 if let Some(additional) = high {
2056 self.reserve(additional);
2058 let mut ptr = self.as_mut_ptr().add(self.len());
2059 let mut local_len = SetLenOnDrop::new(&mut self.len);
2060 iterator.for_each(move |element| {
2061 ptr::write(ptr, element);
2062 ptr = ptr.offset(1);
2063 // NB can't overflow since we would have had to alloc the address space
2064 local_len.increment_len(1);
2068 self.extend_desugared(iterator)
2073 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2074 fn from_iter(iterator: IntoIter<T>) -> Self {
2075 // A common case is passing a vector into a function which immediately
2076 // re-collects into a vector. We can short circuit this if the IntoIter
2077 // has not been advanced at all.
2078 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
2080 let vec = Vec::from_raw_parts(iterator.buf.as_ptr(), iterator.len(), iterator.cap);
2081 mem::forget(iterator);
2085 let mut vector = Vec::new();
2086 vector.spec_extend(iterator);
2091 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2093 self.append_elements(iterator.as_slice() as _);
2095 iterator.ptr = iterator.end;
2099 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2101 I: Iterator<Item = &'a T>,
2104 default fn from_iter(iterator: I) -> Self {
2105 SpecExtend::from_iter(iterator.cloned())
2108 default fn spec_extend(&mut self, iterator: I) {
2109 self.spec_extend(iterator.cloned())
2113 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2117 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2118 let slice = iterator.as_slice();
2119 self.reserve(slice.len());
2121 let len = self.len();
2122 self.set_len(len + slice.len());
2123 self.get_unchecked_mut(len..).copy_from_slice(slice);
2129 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2130 // This is the case for a general iterator.
2132 // This function should be the moral equivalent of:
2134 // for item in iterator {
2137 while let Some(element) = iterator.next() {
2138 let len = self.len();
2139 if len == self.capacity() {
2140 let (lower, _) = iterator.size_hint();
2141 self.reserve(lower.saturating_add(1));
2144 ptr::write(self.get_unchecked_mut(len), element);
2145 // NB can't overflow since we would have had to alloc the address space
2146 self.set_len(len + 1);
2151 /// Creates a splicing iterator that replaces the specified range in the vector
2152 /// with the given `replace_with` iterator and yields the removed items.
2153 /// `replace_with` does not need to be the same length as `range`.
2155 /// The element range is removed even if the iterator is not consumed until the end.
2157 /// It is unspecified how many elements are removed from the vector
2158 /// if the `Splice` value is leaked.
2160 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2162 /// This is optimal if:
2164 /// * The tail (elements in the vector after `range`) is empty,
2165 /// * or `replace_with` yields fewer elements than `range`’s length
2166 /// * or the lower bound of its `size_hint()` is exact.
2168 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2172 /// Panics if the starting point is greater than the end point or if
2173 /// the end point is greater than the length of the vector.
2178 /// let mut v = vec![1, 2, 3];
2179 /// let new = [7, 8];
2180 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2181 /// assert_eq!(v, &[7, 8, 3]);
2182 /// assert_eq!(u, &[1, 2]);
2185 #[stable(feature = "vec_splice", since = "1.21.0")]
2186 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2188 R: RangeBounds<usize>,
2189 I: IntoIterator<Item = T>,
2191 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2194 /// Creates an iterator which uses a closure to determine if an element should be removed.
2196 /// If the closure returns true, then the element is removed and yielded.
2197 /// If the closure returns false, the element will remain in the vector and will not be yielded
2198 /// by the iterator.
2200 /// Using this method is equivalent to the following code:
2203 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2204 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2206 /// while i != vec.len() {
2207 /// if some_predicate(&mut vec[i]) {
2208 /// let val = vec.remove(i);
2209 /// // your code here
2215 /// # assert_eq!(vec, vec![1, 4, 5]);
2218 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2219 /// because it can backshift the elements of the array in bulk.
2221 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2222 /// regardless of whether you choose to keep or remove it.
2227 /// Splitting an array into evens and odds, reusing the original allocation:
2230 /// #![feature(drain_filter)]
2231 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2233 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2234 /// let odds = numbers;
2236 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2237 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2239 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2240 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2242 F: FnMut(&mut T) -> bool,
2244 let old_len = self.len();
2246 // Guard against us getting leaked (leak amplification)
2251 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2255 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2257 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2258 /// append the entire slice at once.
2260 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2261 #[stable(feature = "extend_ref", since = "1.2.0")]
2262 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2263 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2264 self.spec_extend(iter.into_iter())
2268 macro_rules! __impl_slice_eq1 {
2269 ([$($vars:tt)*] $lhs:ty, $rhs:ty, $($constraints:tt)*) => {
2270 #[stable(feature = "rust1", since = "1.0.0")]
2271 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2277 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2279 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2284 __impl_slice_eq1! { [] Vec<A>, Vec<B>, }
2285 __impl_slice_eq1! { [] Vec<A>, &[B], }
2286 __impl_slice_eq1! { [] Vec<A>, &mut [B], }
2287 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B], A: Clone }
2288 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B], A: Clone }
2289 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B>, A: Clone }
2290 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N], [B; N]: LengthAtMost32 }
2291 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N], [B; N]: LengthAtMost32 }
2293 // NOTE: some less important impls are omitted to reduce code bloat
2294 // FIXME(Centril): Reconsider this?
2295 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], [B; N]: LengthAtMost32 }
2296 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], [B; N]: LengthAtMost32 }
2297 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], [B; N]: LengthAtMost32 }
2298 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], [B; N]: LengthAtMost32 }
2300 /// Implements comparison of vectors, lexicographically.
2301 #[stable(feature = "rust1", since = "1.0.0")]
2302 impl<T: PartialOrd> PartialOrd for Vec<T> {
2304 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2305 PartialOrd::partial_cmp(&**self, &**other)
2309 #[stable(feature = "rust1", since = "1.0.0")]
2310 impl<T: Eq> Eq for Vec<T> {}
2312 /// Implements ordering of vectors, lexicographically.
2313 #[stable(feature = "rust1", since = "1.0.0")]
2314 impl<T: Ord> Ord for Vec<T> {
2316 fn cmp(&self, other: &Vec<T>) -> Ordering {
2317 Ord::cmp(&**self, &**other)
2321 #[stable(feature = "rust1", since = "1.0.0")]
2322 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2323 fn drop(&mut self) {
2326 ptr::drop_in_place(&mut self[..]);
2328 // RawVec handles deallocation
2332 #[stable(feature = "rust1", since = "1.0.0")]
2333 impl<T> Default for Vec<T> {
2334 /// Creates an empty `Vec<T>`.
2335 fn default() -> Vec<T> {
2340 #[stable(feature = "rust1", since = "1.0.0")]
2341 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2342 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2343 fmt::Debug::fmt(&**self, f)
2347 #[stable(feature = "rust1", since = "1.0.0")]
2348 impl<T> AsRef<Vec<T>> for Vec<T> {
2349 fn as_ref(&self) -> &Vec<T> {
2354 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2355 impl<T> AsMut<Vec<T>> for Vec<T> {
2356 fn as_mut(&mut self) -> &mut Vec<T> {
2361 #[stable(feature = "rust1", since = "1.0.0")]
2362 impl<T> AsRef<[T]> for Vec<T> {
2363 fn as_ref(&self) -> &[T] {
2368 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2369 impl<T> AsMut<[T]> for Vec<T> {
2370 fn as_mut(&mut self) -> &mut [T] {
2375 #[stable(feature = "rust1", since = "1.0.0")]
2376 impl<T: Clone> From<&[T]> for Vec<T> {
2378 fn from(s: &[T]) -> Vec<T> {
2382 fn from(s: &[T]) -> Vec<T> {
2383 crate::slice::to_vec(s)
2387 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2388 impl<T: Clone> From<&mut [T]> for Vec<T> {
2390 fn from(s: &mut [T]) -> Vec<T> {
2394 fn from(s: &mut [T]) -> Vec<T> {
2395 crate::slice::to_vec(s)
2399 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2400 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2402 [T]: ToOwned<Owned = Vec<T>>,
2404 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2409 // note: test pulls in libstd, which causes errors here
2411 #[stable(feature = "vec_from_box", since = "1.18.0")]
2412 impl<T> From<Box<[T]>> for Vec<T> {
2413 fn from(s: Box<[T]>) -> Vec<T> {
2418 // note: test pulls in libstd, which causes errors here
2420 #[stable(feature = "box_from_vec", since = "1.20.0")]
2421 impl<T> From<Vec<T>> for Box<[T]> {
2422 fn from(v: Vec<T>) -> Box<[T]> {
2423 v.into_boxed_slice()
2427 #[stable(feature = "rust1", since = "1.0.0")]
2428 impl From<&str> for Vec<u8> {
2429 fn from(s: &str) -> Vec<u8> {
2430 From::from(s.as_bytes())
2434 ////////////////////////////////////////////////////////////////////////////////
2436 ////////////////////////////////////////////////////////////////////////////////
2438 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2439 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2440 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2445 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2446 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2447 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2452 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2453 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2454 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2455 Cow::Borrowed(v.as_slice())
2459 #[stable(feature = "rust1", since = "1.0.0")]
2460 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
2464 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2465 Cow::Owned(FromIterator::from_iter(it))
2469 ////////////////////////////////////////////////////////////////////////////////
2471 ////////////////////////////////////////////////////////////////////////////////
2473 /// An iterator that moves out of a vector.
2475 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
2476 /// by the [`IntoIterator`] trait).
2478 /// [`Vec`]: struct.Vec.html
2479 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2480 #[stable(feature = "rust1", since = "1.0.0")]
2481 pub struct IntoIter<T> {
2483 phantom: PhantomData<T>,
2489 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2490 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2491 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2492 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2496 impl<T> IntoIter<T> {
2497 /// Returns the remaining items of this iterator as a slice.
2502 /// let vec = vec!['a', 'b', 'c'];
2503 /// let mut into_iter = vec.into_iter();
2504 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2505 /// let _ = into_iter.next().unwrap();
2506 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2508 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2509 pub fn as_slice(&self) -> &[T] {
2510 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
2513 /// Returns the remaining items of this iterator as a mutable slice.
2518 /// let vec = vec!['a', 'b', 'c'];
2519 /// let mut into_iter = vec.into_iter();
2520 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2521 /// into_iter.as_mut_slice()[2] = 'z';
2522 /// assert_eq!(into_iter.next().unwrap(), 'a');
2523 /// assert_eq!(into_iter.next().unwrap(), 'b');
2524 /// assert_eq!(into_iter.next().unwrap(), 'z');
2526 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2527 pub fn as_mut_slice(&mut self) -> &mut [T] {
2528 unsafe { slice::from_raw_parts_mut(self.ptr as *mut T, self.len()) }
2532 #[stable(feature = "rust1", since = "1.0.0")]
2533 unsafe impl<T: Send> Send for IntoIter<T> {}
2534 #[stable(feature = "rust1", since = "1.0.0")]
2535 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2537 #[stable(feature = "rust1", since = "1.0.0")]
2538 impl<T> Iterator for IntoIter<T> {
2542 fn next(&mut self) -> Option<T> {
2544 if self.ptr as *const _ == self.end {
2547 if mem::size_of::<T>() == 0 {
2548 // purposefully don't use 'ptr.offset' because for
2549 // vectors with 0-size elements this would return the
2551 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2553 // Make up a value of this ZST.
2557 self.ptr = self.ptr.offset(1);
2559 Some(ptr::read(old))
2566 fn size_hint(&self) -> (usize, Option<usize>) {
2567 let exact = if mem::size_of::<T>() == 0 {
2568 (self.end as usize).wrapping_sub(self.ptr as usize)
2570 unsafe { self.end.offset_from(self.ptr) as usize }
2572 (exact, Some(exact))
2576 fn count(self) -> usize {
2581 #[stable(feature = "rust1", since = "1.0.0")]
2582 impl<T> DoubleEndedIterator for IntoIter<T> {
2584 fn next_back(&mut self) -> Option<T> {
2586 if self.end == self.ptr {
2589 if mem::size_of::<T>() == 0 {
2590 // See above for why 'ptr.offset' isn't used
2591 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2593 // Make up a value of this ZST.
2596 self.end = self.end.offset(-1);
2598 Some(ptr::read(self.end))
2605 #[stable(feature = "rust1", since = "1.0.0")]
2606 impl<T> ExactSizeIterator for IntoIter<T> {
2607 fn is_empty(&self) -> bool {
2608 self.ptr == self.end
2612 #[stable(feature = "fused", since = "1.26.0")]
2613 impl<T> FusedIterator for IntoIter<T> {}
2615 #[unstable(feature = "trusted_len", issue = "37572")]
2616 unsafe impl<T> TrustedLen for IntoIter<T> {}
2618 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2619 impl<T: Clone> Clone for IntoIter<T> {
2620 fn clone(&self) -> IntoIter<T> {
2621 self.as_slice().to_owned().into_iter()
2625 #[stable(feature = "rust1", since = "1.0.0")]
2626 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2627 fn drop(&mut self) {
2628 // destroy the remaining elements
2630 ptr::drop_in_place(self.as_mut_slice());
2633 // RawVec handles deallocation
2634 let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) };
2638 /// A draining iterator for `Vec<T>`.
2640 /// This `struct` is created by the [`drain`] method on [`Vec`].
2642 /// [`drain`]: struct.Vec.html#method.drain
2643 /// [`Vec`]: struct.Vec.html
2644 #[stable(feature = "drain", since = "1.6.0")]
2645 pub struct Drain<'a, T: 'a> {
2646 /// Index of tail to preserve
2650 /// Current remaining range to remove
2651 iter: slice::Iter<'a, T>,
2652 vec: NonNull<Vec<T>>,
2655 #[stable(feature = "collection_debug", since = "1.17.0")]
2656 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2657 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2658 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
2662 impl<'a, T> Drain<'a, T> {
2663 /// Returns the remaining items of this iterator as a slice.
2668 /// # #![feature(vec_drain_as_slice)]
2669 /// let mut vec = vec!['a', 'b', 'c'];
2670 /// let mut drain = vec.drain(..);
2671 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
2672 /// let _ = drain.next().unwrap();
2673 /// assert_eq!(drain.as_slice(), &['b', 'c']);
2675 #[unstable(feature = "vec_drain_as_slice", reason = "recently added", issue = "58957")]
2676 pub fn as_slice(&self) -> &[T] {
2677 self.iter.as_slice()
2681 #[stable(feature = "drain", since = "1.6.0")]
2682 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2683 #[stable(feature = "drain", since = "1.6.0")]
2684 unsafe impl<T: Send> Send for Drain<'_, T> {}
2686 #[stable(feature = "drain", since = "1.6.0")]
2687 impl<T> Iterator for Drain<'_, T> {
2691 fn next(&mut self) -> Option<T> {
2692 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2695 fn size_hint(&self) -> (usize, Option<usize>) {
2696 self.iter.size_hint()
2700 #[stable(feature = "drain", since = "1.6.0")]
2701 impl<T> DoubleEndedIterator for Drain<'_, T> {
2703 fn next_back(&mut self) -> Option<T> {
2704 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2708 #[stable(feature = "drain", since = "1.6.0")]
2709 impl<T> Drop for Drain<'_, T> {
2710 fn drop(&mut self) {
2711 /// Continues dropping the remaining elements in the `Drain`, then moves back the
2712 /// un-`Drain`ed elements to restore the original `Vec`.
2713 struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>);
2715 impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> {
2716 fn drop(&mut self) {
2717 // Continue the same loop we have below. If the loop already finished, this does
2719 self.0.for_each(drop);
2721 if self.0.tail_len > 0 {
2723 let source_vec = self.0.vec.as_mut();
2724 // memmove back untouched tail, update to new length
2725 let start = source_vec.len();
2726 let tail = self.0.tail_start;
2728 let src = source_vec.as_ptr().add(tail);
2729 let dst = source_vec.as_mut_ptr().add(start);
2730 ptr::copy(src, dst, self.0.tail_len);
2732 source_vec.set_len(start + self.0.tail_len);
2738 // exhaust self first
2739 while let Some(item) = self.next() {
2740 let guard = DropGuard(self);
2745 // Drop a `DropGuard` to move back the non-drained tail of `self`.
2750 #[stable(feature = "drain", since = "1.6.0")]
2751 impl<T> ExactSizeIterator for Drain<'_, T> {
2752 fn is_empty(&self) -> bool {
2753 self.iter.is_empty()
2757 #[unstable(feature = "trusted_len", issue = "37572")]
2758 unsafe impl<T> TrustedLen for Drain<'_, T> {}
2760 #[stable(feature = "fused", since = "1.26.0")]
2761 impl<T> FusedIterator for Drain<'_, T> {}
2763 /// A splicing iterator for `Vec`.
2765 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2766 /// documentation for more.
2768 /// [`splice()`]: struct.Vec.html#method.splice
2769 /// [`Vec`]: struct.Vec.html
2771 #[stable(feature = "vec_splice", since = "1.21.0")]
2772 pub struct Splice<'a, I: Iterator + 'a> {
2773 drain: Drain<'a, I::Item>,
2777 #[stable(feature = "vec_splice", since = "1.21.0")]
2778 impl<I: Iterator> Iterator for Splice<'_, I> {
2779 type Item = I::Item;
2781 fn next(&mut self) -> Option<Self::Item> {
2785 fn size_hint(&self) -> (usize, Option<usize>) {
2786 self.drain.size_hint()
2790 #[stable(feature = "vec_splice", since = "1.21.0")]
2791 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
2792 fn next_back(&mut self) -> Option<Self::Item> {
2793 self.drain.next_back()
2797 #[stable(feature = "vec_splice", since = "1.21.0")]
2798 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
2800 #[stable(feature = "vec_splice", since = "1.21.0")]
2801 impl<I: Iterator> Drop for Splice<'_, I> {
2802 fn drop(&mut self) {
2803 self.drain.by_ref().for_each(drop);
2806 if self.drain.tail_len == 0 {
2807 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2811 // First fill the range left by drain().
2812 if !self.drain.fill(&mut self.replace_with) {
2816 // There may be more elements. Use the lower bound as an estimate.
2817 // FIXME: Is the upper bound a better guess? Or something else?
2818 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2819 if lower_bound > 0 {
2820 self.drain.move_tail(lower_bound);
2821 if !self.drain.fill(&mut self.replace_with) {
2826 // Collect any remaining elements.
2827 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2828 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2829 // Now we have an exact count.
2830 if collected.len() > 0 {
2831 self.drain.move_tail(collected.len());
2832 let filled = self.drain.fill(&mut collected);
2833 debug_assert!(filled);
2834 debug_assert_eq!(collected.len(), 0);
2837 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2841 /// Private helper methods for `Splice::drop`
2842 impl<T> Drain<'_, T> {
2843 /// The range from `self.vec.len` to `self.tail_start` contains elements
2844 /// that have been moved out.
2845 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2846 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2847 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
2848 let vec = self.vec.as_mut();
2849 let range_start = vec.len;
2850 let range_end = self.tail_start;
2852 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start);
2854 for place in range_slice {
2855 if let Some(new_item) = replace_with.next() {
2856 ptr::write(place, new_item);
2865 /// Makes room for inserting more elements before the tail.
2866 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2867 let vec = self.vec.as_mut();
2868 let used_capacity = self.tail_start + self.tail_len;
2869 vec.buf.reserve(used_capacity, extra_capacity);
2871 let new_tail_start = self.tail_start + extra_capacity;
2872 let src = vec.as_ptr().add(self.tail_start);
2873 let dst = vec.as_mut_ptr().add(new_tail_start);
2874 ptr::copy(src, dst, self.tail_len);
2875 self.tail_start = new_tail_start;
2879 /// An iterator produced by calling `drain_filter` on Vec.
2880 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2882 pub struct DrainFilter<'a, T, F>
2884 F: FnMut(&mut T) -> bool,
2886 vec: &'a mut Vec<T>,
2887 /// The index of the item that will be inspected by the next call to `next`.
2889 /// The number of items that have been drained (removed) thus far.
2891 /// The original length of `vec` prior to draining.
2893 /// The filter test predicate.
2895 /// A flag that indicates a panic has occurred in the filter test prodicate.
2896 /// This is used as a hint in the drop implmentation to prevent consumption
2897 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
2898 /// backshifted in the `vec`, but no further items will be dropped or
2899 /// tested by the filter predicate.
2903 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2904 impl<T, F> Iterator for DrainFilter<'_, T, F>
2906 F: FnMut(&mut T) -> bool,
2910 fn next(&mut self) -> Option<T> {
2912 while self.idx < self.old_len {
2914 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
2915 self.panic_flag = true;
2916 let drained = (self.pred)(&mut v[i]);
2917 self.panic_flag = false;
2918 // Update the index *after* the predicate is called. If the index
2919 // is updated prior and the predicate panics, the element at this
2920 // index would be leaked.
2924 return Some(ptr::read(&v[i]));
2925 } else if self.del > 0 {
2927 let src: *const T = &v[i];
2928 let dst: *mut T = &mut v[i - del];
2929 ptr::copy_nonoverlapping(src, dst, 1);
2936 fn size_hint(&self) -> (usize, Option<usize>) {
2937 (0, Some(self.old_len - self.idx))
2941 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2942 impl<T, F> Drop for DrainFilter<'_, T, F>
2944 F: FnMut(&mut T) -> bool,
2946 fn drop(&mut self) {
2947 struct BackshiftOnDrop<'a, 'b, T, F>
2949 F: FnMut(&mut T) -> bool,
2951 drain: &'b mut DrainFilter<'a, T, F>,
2954 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
2956 F: FnMut(&mut T) -> bool,
2958 fn drop(&mut self) {
2960 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
2961 // This is a pretty messed up state, and there isn't really an
2962 // obviously right thing to do. We don't want to keep trying
2963 // to execute `pred`, so we just backshift all the unprocessed
2964 // elements and tell the vec that they still exist. The backshift
2965 // is required to prevent a double-drop of the last successfully
2966 // drained item prior to a panic in the predicate.
2967 let ptr = self.drain.vec.as_mut_ptr();
2968 let src = ptr.add(self.drain.idx);
2969 let dst = src.sub(self.drain.del);
2970 let tail_len = self.drain.old_len - self.drain.idx;
2971 src.copy_to(dst, tail_len);
2973 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
2978 let backshift = BackshiftOnDrop { drain: self };
2980 // Attempt to consume any remaining elements if the filter predicate
2981 // has not yet panicked. We'll backshift any remaining elements
2982 // whether we've already panicked or if the consumption here panics.
2983 if !backshift.drain.panic_flag {
2984 backshift.drain.for_each(drop);