1 // ignore-tidy-filelength
2 //! A contiguous growable array type with heap-allocated contents, written
5 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
6 //! `O(1)` pop (from the end).
8 //! Vectors ensure they never allocate more than `isize::MAX` bytes.
12 //! You can explicitly create a [`Vec`] with [`Vec::new`]:
15 //! let v: Vec<i32> = Vec::new();
18 //! ...or by using the [`vec!`] macro:
21 //! let v: Vec<i32> = vec![];
23 //! let v = vec![1, 2, 3, 4, 5];
25 //! let v = vec![0; 10]; // ten zeroes
28 //! You can [`push`] values onto the end of a vector (which will grow the vector
32 //! let mut v = vec![1, 2];
37 //! Popping values works in much the same way:
40 //! let mut v = vec![1, 2];
42 //! let two = v.pop();
45 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
48 //! let mut v = vec![1, 2, 3];
53 //! [`push`]: Vec::push
55 #![stable(feature = "rust1", since = "1.0.0")]
57 use core::cmp::{self, Ordering};
58 use core::convert::TryFrom;
60 use core::hash::{Hash, Hasher};
61 use core::intrinsics::{arith_offset, assume};
63 FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen, TrustedRandomAccess,
65 use core::marker::PhantomData;
66 use core::mem::{self, ManuallyDrop, MaybeUninit};
67 use core::ops::Bound::{Excluded, Included, Unbounded};
68 use core::ops::{self, Index, IndexMut, RangeBounds};
69 use core::ptr::{self, NonNull};
70 use core::slice::{self, SliceIndex};
72 use crate::borrow::{Cow, ToOwned};
73 use crate::boxed::Box;
74 use crate::collections::TryReserveError;
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().copied());
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 vec = Vec::with_capacity(5);
121 /// vec.resize(5, 0);
122 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
125 /// Use a `Vec<T>` as an efficient stack:
128 /// let mut stack = Vec::new();
134 /// while let Some(top) = stack.pop() {
135 /// // Prints 3, 2, 1
136 /// println!("{}", top);
142 /// The `Vec` type allows to access values by index, because it implements the
143 /// [`Index`] trait. An example will be more explicit:
146 /// let v = vec![0, 2, 4, 6];
147 /// println!("{}", v[1]); // it will display '2'
150 /// However be careful: if you try to access an index which isn't in the `Vec`,
151 /// your software will panic! You cannot do this:
154 /// let v = vec![0, 2, 4, 6];
155 /// println!("{}", v[6]); // it will panic!
158 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
163 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
164 /// To get a slice, use `&`. Example:
167 /// fn read_slice(slice: &[usize]) {
171 /// let v = vec![0, 1];
174 /// // ... and that's all!
175 /// // you can also do it like this:
176 /// let x : &[usize] = &v;
179 /// In Rust, it's more common to pass slices as arguments rather than vectors
180 /// when you just want to provide read access. The same goes for [`String`] and
183 /// # Capacity and reallocation
185 /// The capacity of a vector is the amount of space allocated for any future
186 /// elements that will be added onto the vector. This is not to be confused with
187 /// the *length* of a vector, which specifies the number of actual elements
188 /// within the vector. If a vector's length exceeds its capacity, its capacity
189 /// will automatically be increased, but its elements will have to be
192 /// For example, a vector with capacity 10 and length 0 would be an empty vector
193 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
194 /// vector will not change its capacity or cause reallocation to occur. However,
195 /// if the vector's length is increased to 11, it will have to reallocate, which
196 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
197 /// whenever possible to specify how big the vector is expected to get.
201 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
202 /// about its design. This ensures that it's as low-overhead as possible in
203 /// the general case, and can be correctly manipulated in primitive ways
204 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
205 /// If additional type parameters are added (e.g., to support custom allocators),
206 /// overriding their defaults may change the behavior.
208 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
209 /// triplet. No more, no less. The order of these fields is completely
210 /// unspecified, and you should use the appropriate methods to modify these.
211 /// The pointer will never be null, so this type is null-pointer-optimized.
213 /// However, the pointer may not actually point to allocated memory. In particular,
214 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
215 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
216 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
217 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
218 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
219 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
220 /// details are very subtle — if you intend to allocate memory using a `Vec`
221 /// and use it for something else (either to pass to unsafe code, or to build your
222 /// own memory-backed collection), be sure to deallocate this memory by using
223 /// `from_raw_parts` to recover the `Vec` and then dropping it.
225 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
226 /// (as defined by the allocator Rust is configured to use by default), and its
227 /// pointer points to [`len`] initialized, contiguous elements in order (what
228 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
229 /// `[`len`] logically uninitialized, contiguous elements.
231 /// `Vec` will never perform a "small optimization" where elements are actually
232 /// stored on the stack for two reasons:
234 /// * It would make it more difficult for unsafe code to correctly manipulate
235 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
236 /// only moved, and it would be more difficult to determine if a `Vec` had
237 /// actually allocated memory.
239 /// * It would penalize the general case, incurring an additional branch
242 /// `Vec` will never automatically shrink itself, even if completely empty. This
243 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
244 /// and then filling it back up to the same [`len`] should incur no calls to
245 /// the allocator. If you wish to free up unused memory, use
246 /// [`shrink_to_fit`].
248 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
249 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
250 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
251 /// accurate, and can be relied on. It can even be used to manually free the memory
252 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
253 /// when not necessary.
255 /// `Vec` does not guarantee any particular growth strategy when reallocating
256 /// when full, nor when [`reserve`] is called. The current strategy is basic
257 /// and it may prove desirable to use a non-constant growth factor. Whatever
258 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
260 /// `vec![x; n]`, `vec![a, b, c, d]`, and
261 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
262 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
263 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
264 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
266 /// `Vec` will not specifically overwrite any data that is removed from it,
267 /// but also won't specifically preserve it. Its uninitialized memory is
268 /// scratch space that it may use however it wants. It will generally just do
269 /// whatever is most efficient or otherwise easy to implement. Do not rely on
270 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
271 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
272 /// first, that may not actually happen because the optimizer does not consider
273 /// this a side-effect that must be preserved. There is one case which we will
274 /// not break, however: using `unsafe` code to write to the excess capacity,
275 /// and then increasing the length to match, is always valid.
277 /// `Vec` does not currently guarantee the order in which elements are dropped.
278 /// The order has changed in the past and may change again.
280 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
281 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
282 /// [`String`]: crate::string::String
283 /// [`&str`]: type@str
284 /// [`shrink_to_fit`]: Vec::shrink_to_fit
285 /// [`capacity`]: Vec::capacity
286 /// [`mem::size_of::<T>`]: core::mem::size_of
287 /// [`len`]: Vec::len
288 /// [`push`]: Vec::push
289 /// [`insert`]: Vec::insert
290 /// [`reserve`]: Vec::reserve
291 /// [owned slice]: Box
292 #[stable(feature = "rust1", since = "1.0.0")]
293 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
299 ////////////////////////////////////////////////////////////////////////////////
301 ////////////////////////////////////////////////////////////////////////////////
304 /// Constructs a new, empty `Vec<T>`.
306 /// The vector will not allocate until elements are pushed onto it.
311 /// # #![allow(unused_mut)]
312 /// let mut vec: Vec<i32> = Vec::new();
315 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
316 #[stable(feature = "rust1", since = "1.0.0")]
317 pub const fn new() -> Vec<T> {
318 Vec { buf: RawVec::NEW, len: 0 }
321 /// Constructs a new, empty `Vec<T>` with the specified capacity.
323 /// The vector will be able to hold exactly `capacity` elements without
324 /// reallocating. If `capacity` is 0, the vector will not allocate.
326 /// It is important to note that although the returned vector has the
327 /// *capacity* specified, the vector will have a zero *length*. For an
328 /// explanation of the difference between length and capacity, see
329 /// *[Capacity and reallocation]*.
331 /// [Capacity and reallocation]: #capacity-and-reallocation
336 /// let mut vec = Vec::with_capacity(10);
338 /// // The vector contains no items, even though it has capacity for more
339 /// assert_eq!(vec.len(), 0);
340 /// assert_eq!(vec.capacity(), 10);
342 /// // These are all done without reallocating...
346 /// assert_eq!(vec.len(), 10);
347 /// assert_eq!(vec.capacity(), 10);
349 /// // ...but this may make the vector reallocate
351 /// assert_eq!(vec.len(), 11);
352 /// assert!(vec.capacity() >= 11);
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`]: Vec::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 = 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`]: crate::string::String
429 /// [`dealloc`]: crate::alloc::GlobalAlloc::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 unsafe { 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 exceeds `isize::MAX` bytes.
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 `try_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 `try_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_exact(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 // The capacity is never less than the length, and there's nothing to do when
621 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
622 // by only calling it with a greater capacity.
623 if self.capacity() > self.len {
624 self.buf.shrink_to_fit(self.len);
628 /// Shrinks the capacity of the vector with a lower bound.
630 /// The capacity will remain at least as large as both the length
631 /// and the supplied value.
635 /// Panics if the current capacity is smaller than the supplied
636 /// minimum capacity.
641 /// #![feature(shrink_to)]
642 /// let mut vec = Vec::with_capacity(10);
643 /// vec.extend([1, 2, 3].iter().cloned());
644 /// assert_eq!(vec.capacity(), 10);
645 /// vec.shrink_to(4);
646 /// assert!(vec.capacity() >= 4);
647 /// vec.shrink_to(0);
648 /// assert!(vec.capacity() >= 3);
650 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
651 pub fn shrink_to(&mut self, min_capacity: usize) {
652 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
655 /// Converts the vector into [`Box<[T]>`][owned slice].
657 /// Note that this will drop any excess capacity.
659 /// [owned slice]: Box
664 /// let v = vec![1, 2, 3];
666 /// let slice = v.into_boxed_slice();
669 /// Any excess capacity is removed:
672 /// let mut vec = Vec::with_capacity(10);
673 /// vec.extend([1, 2, 3].iter().cloned());
675 /// assert_eq!(vec.capacity(), 10);
676 /// let slice = vec.into_boxed_slice();
677 /// assert_eq!(slice.into_vec().capacity(), 3);
679 #[stable(feature = "rust1", since = "1.0.0")]
680 pub fn into_boxed_slice(mut self) -> Box<[T]> {
682 self.shrink_to_fit();
683 let me = ManuallyDrop::new(self);
684 let buf = ptr::read(&me.buf);
686 buf.into_box(len).assume_init()
690 /// Shortens the vector, keeping the first `len` elements and dropping
693 /// If `len` is greater than the vector's current length, this has no
696 /// The [`drain`] method can emulate `truncate`, but causes the excess
697 /// elements to be returned instead of dropped.
699 /// Note that this method has no effect on the allocated capacity
704 /// Truncating a five element vector to two elements:
707 /// let mut vec = vec![1, 2, 3, 4, 5];
709 /// assert_eq!(vec, [1, 2]);
712 /// No truncation occurs when `len` is greater than the vector's current
716 /// let mut vec = vec![1, 2, 3];
718 /// assert_eq!(vec, [1, 2, 3]);
721 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
725 /// let mut vec = vec![1, 2, 3];
727 /// assert_eq!(vec, []);
730 /// [`clear`]: Vec::clear
731 /// [`drain`]: Vec::drain
732 #[stable(feature = "rust1", since = "1.0.0")]
733 pub fn truncate(&mut self, len: usize) {
734 // This is safe because:
736 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
737 // case avoids creating an invalid slice, and
738 // * the `len` of the vector is shrunk before calling `drop_in_place`,
739 // such that no value will be dropped twice in case `drop_in_place`
740 // were to panic once (if it panics twice, the program aborts).
745 let remaining_len = self.len - len;
746 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
748 ptr::drop_in_place(s);
752 /// Extracts a slice containing the entire vector.
754 /// Equivalent to `&s[..]`.
759 /// use std::io::{self, Write};
760 /// let buffer = vec![1, 2, 3, 5, 8];
761 /// io::sink().write(buffer.as_slice()).unwrap();
764 #[stable(feature = "vec_as_slice", since = "1.7.0")]
765 pub fn as_slice(&self) -> &[T] {
769 /// Extracts a mutable slice of the entire vector.
771 /// Equivalent to `&mut s[..]`.
776 /// use std::io::{self, Read};
777 /// let mut buffer = vec![0; 3];
778 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
781 #[stable(feature = "vec_as_slice", since = "1.7.0")]
782 pub fn as_mut_slice(&mut self) -> &mut [T] {
786 /// Returns a raw pointer to the vector's buffer.
788 /// The caller must ensure that the vector outlives the pointer this
789 /// function returns, or else it will end up pointing to garbage.
790 /// Modifying the vector may cause its buffer to be reallocated,
791 /// which would also make any pointers to it invalid.
793 /// The caller must also ensure that the memory the pointer (non-transitively) points to
794 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
795 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
800 /// let x = vec![1, 2, 4];
801 /// let x_ptr = x.as_ptr();
804 /// for i in 0..x.len() {
805 /// assert_eq!(*x_ptr.add(i), 1 << i);
810 /// [`as_mut_ptr`]: Vec::as_mut_ptr
811 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
813 pub fn as_ptr(&self) -> *const T {
814 // We shadow the slice method of the same name to avoid going through
815 // `deref`, which creates an intermediate reference.
816 let ptr = self.buf.ptr();
818 assume(!ptr.is_null());
823 /// Returns an unsafe mutable pointer to the vector's buffer.
825 /// The caller must ensure that the vector outlives the pointer this
826 /// function returns, or else it will end up pointing to garbage.
827 /// Modifying the vector may cause its buffer to be reallocated,
828 /// which would also make any pointers to it invalid.
833 /// // Allocate vector big enough for 4 elements.
835 /// let mut x: Vec<i32> = Vec::with_capacity(size);
836 /// let x_ptr = x.as_mut_ptr();
838 /// // Initialize elements via raw pointer writes, then set length.
840 /// for i in 0..size {
841 /// *x_ptr.add(i) = i as i32;
845 /// assert_eq!(&*x, &[0,1,2,3]);
847 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
849 pub fn as_mut_ptr(&mut self) -> *mut T {
850 // We shadow the slice method of the same name to avoid going through
851 // `deref_mut`, which creates an intermediate reference.
852 let ptr = self.buf.ptr();
854 assume(!ptr.is_null());
859 /// Forces the length of the vector to `new_len`.
861 /// This is a low-level operation that maintains none of the normal
862 /// invariants of the type. Normally changing the length of a vector
863 /// is done using one of the safe operations instead, such as
864 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
866 /// [`truncate`]: Vec::truncate
867 /// [`resize`]: Vec::resize
868 /// [`extend`]: Extend::extend
869 /// [`clear`]: Vec::clear
873 /// - `new_len` must be less than or equal to [`capacity()`].
874 /// - The elements at `old_len..new_len` must be initialized.
876 /// [`capacity()`]: Vec::capacity
880 /// This method can be useful for situations in which the vector
881 /// is serving as a buffer for other code, particularly over FFI:
884 /// # #![allow(dead_code)]
885 /// # // This is just a minimal skeleton for the doc example;
886 /// # // don't use this as a starting point for a real library.
887 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
888 /// # const Z_OK: i32 = 0;
890 /// # fn deflateGetDictionary(
891 /// # strm: *mut std::ffi::c_void,
892 /// # dictionary: *mut u8,
893 /// # dictLength: *mut usize,
896 /// # impl StreamWrapper {
897 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
898 /// // Per the FFI method's docs, "32768 bytes is always enough".
899 /// let mut dict = Vec::with_capacity(32_768);
900 /// let mut dict_length = 0;
901 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
902 /// // 1. `dict_length` elements were initialized.
903 /// // 2. `dict_length` <= the capacity (32_768)
904 /// // which makes `set_len` safe to call.
906 /// // Make the FFI call...
907 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
909 /// // ...and update the length to what was initialized.
910 /// dict.set_len(dict_length);
920 /// While the following example is sound, there is a memory leak since
921 /// the inner vectors were not freed prior to the `set_len` call:
924 /// let mut vec = vec![vec![1, 0, 0],
928 /// // 1. `old_len..0` is empty so no elements need to be initialized.
929 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
935 /// Normally, here, one would use [`clear`] instead to correctly drop
936 /// the contents and thus not leak memory.
938 #[stable(feature = "rust1", since = "1.0.0")]
939 pub unsafe fn set_len(&mut self, new_len: usize) {
940 debug_assert!(new_len <= self.capacity());
945 /// Removes an element from the vector and returns it.
947 /// The removed element is replaced by the last element of the vector.
949 /// This does not preserve ordering, but is O(1).
953 /// Panics if `index` is out of bounds.
958 /// let mut v = vec!["foo", "bar", "baz", "qux"];
960 /// assert_eq!(v.swap_remove(1), "bar");
961 /// assert_eq!(v, ["foo", "qux", "baz"]);
963 /// assert_eq!(v.swap_remove(0), "foo");
964 /// assert_eq!(v, ["baz", "qux"]);
967 #[stable(feature = "rust1", since = "1.0.0")]
968 pub fn swap_remove(&mut self, index: usize) -> T {
971 fn assert_failed(index: usize, len: usize) -> ! {
972 panic!("swap_remove index (is {}) should be < len (is {})", index, len);
975 let len = self.len();
977 assert_failed(index, len);
980 // We replace self[index] with the last element. Note that if the
981 // bounds check above succeeds there must be a last element (which
982 // can be self[index] itself).
983 let last = ptr::read(self.as_ptr().add(len - 1));
984 let hole = self.as_mut_ptr().add(index);
985 self.set_len(len - 1);
986 ptr::replace(hole, last)
990 /// Inserts an element at position `index` within the vector, shifting all
991 /// elements after it to the right.
995 /// Panics if `index > len`.
1000 /// let mut vec = vec![1, 2, 3];
1001 /// vec.insert(1, 4);
1002 /// assert_eq!(vec, [1, 4, 2, 3]);
1003 /// vec.insert(4, 5);
1004 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub fn insert(&mut self, index: usize, element: T) {
1010 fn assert_failed(index: usize, len: usize) -> ! {
1011 panic!("insertion index (is {}) should be <= len (is {})", index, len);
1014 let len = self.len();
1016 assert_failed(index, len);
1019 // space for the new element
1020 if len == self.buf.capacity() {
1026 // The spot to put the new value
1028 let p = self.as_mut_ptr().add(index);
1029 // Shift everything over to make space. (Duplicating the
1030 // `index`th element into two consecutive places.)
1031 ptr::copy(p, p.offset(1), len - index);
1032 // Write it in, overwriting the first copy of the `index`th
1034 ptr::write(p, element);
1036 self.set_len(len + 1);
1040 /// Removes and returns the element at position `index` within the vector,
1041 /// shifting all elements after it to the left.
1045 /// Panics if `index` is out of bounds.
1050 /// let mut v = vec![1, 2, 3];
1051 /// assert_eq!(v.remove(1), 2);
1052 /// assert_eq!(v, [1, 3]);
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 pub fn remove(&mut self, index: usize) -> T {
1058 fn assert_failed(index: usize, len: usize) -> ! {
1059 panic!("removal index (is {}) should be < len (is {})", index, len);
1062 let len = self.len();
1064 assert_failed(index, len);
1070 // the place we are taking from.
1071 let ptr = self.as_mut_ptr().add(index);
1072 // copy it out, unsafely having a copy of the value on
1073 // the stack and in the vector at the same time.
1074 ret = ptr::read(ptr);
1076 // Shift everything down to fill in that spot.
1077 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1079 self.set_len(len - 1);
1084 /// Retains only the elements specified by the predicate.
1086 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1087 /// This method operates in place, visiting each element exactly once in the
1088 /// original order, and preserves the order of the retained elements.
1093 /// let mut vec = vec![1, 2, 3, 4];
1094 /// vec.retain(|&x| x % 2 == 0);
1095 /// assert_eq!(vec, [2, 4]);
1098 /// The exact order may be useful for tracking external state, like an index.
1101 /// let mut vec = vec![1, 2, 3, 4, 5];
1102 /// let keep = [false, true, true, false, true];
1104 /// vec.retain(|_| (keep[i], i += 1).0);
1105 /// assert_eq!(vec, [2, 3, 5]);
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 pub fn retain<F>(&mut self, mut f: F)
1110 F: FnMut(&T) -> bool,
1112 let len = self.len();
1115 let v = &mut **self;
1126 self.truncate(len - del);
1130 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1133 /// If the vector is sorted, this removes all duplicates.
1138 /// let mut vec = vec![10, 20, 21, 30, 20];
1140 /// vec.dedup_by_key(|i| *i / 10);
1142 /// assert_eq!(vec, [10, 20, 30, 20]);
1144 #[stable(feature = "dedup_by", since = "1.16.0")]
1146 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1148 F: FnMut(&mut T) -> K,
1151 self.dedup_by(|a, b| key(a) == key(b))
1154 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1157 /// The `same_bucket` function is passed references to two elements from the vector and
1158 /// must determine if the elements compare equal. The elements are passed in opposite order
1159 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1161 /// If the vector is sorted, this removes all duplicates.
1166 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1168 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1170 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1172 #[stable(feature = "dedup_by", since = "1.16.0")]
1173 pub fn dedup_by<F>(&mut self, same_bucket: F)
1175 F: FnMut(&mut T, &mut T) -> bool,
1178 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1184 /// Appends an element to the back of a collection.
1188 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1193 /// let mut vec = vec![1, 2];
1195 /// assert_eq!(vec, [1, 2, 3]);
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 pub fn push(&mut self, value: T) {
1200 // This will panic or abort if we would allocate > isize::MAX bytes
1201 // or if the length increment would overflow for zero-sized types.
1202 if self.len == self.buf.capacity() {
1206 let end = self.as_mut_ptr().add(self.len);
1207 ptr::write(end, value);
1212 /// Removes the last element from a vector and returns it, or [`None`] if it
1218 /// let mut vec = vec![1, 2, 3];
1219 /// assert_eq!(vec.pop(), Some(3));
1220 /// assert_eq!(vec, [1, 2]);
1223 #[stable(feature = "rust1", since = "1.0.0")]
1224 pub fn pop(&mut self) -> Option<T> {
1230 Some(ptr::read(self.as_ptr().add(self.len())))
1235 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1239 /// Panics if the number of elements in the vector overflows a `usize`.
1244 /// let mut vec = vec![1, 2, 3];
1245 /// let mut vec2 = vec![4, 5, 6];
1246 /// vec.append(&mut vec2);
1247 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1248 /// assert_eq!(vec2, []);
1251 #[stable(feature = "append", since = "1.4.0")]
1252 pub fn append(&mut self, other: &mut Self) {
1254 self.append_elements(other.as_slice() as _);
1259 /// Appends elements to `Self` from other buffer.
1261 unsafe fn append_elements(&mut self, other: *const [T]) {
1262 let count = unsafe { (*other).len() };
1263 self.reserve(count);
1264 let len = self.len();
1265 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1269 /// Creates a draining iterator that removes the specified range in the vector
1270 /// and yields the removed items.
1272 /// When the iterator **is** dropped, all elements in the range are removed
1273 /// from the vector, even if the iterator was not fully consumed. If the
1274 /// iterator **is not** dropped (with [`mem::forget`] for example), it is
1275 /// unspecified how many elements are removed.
1279 /// Panics if the starting point is greater than the end point or if
1280 /// the end point is greater than the length of the vector.
1285 /// let mut v = vec![1, 2, 3];
1286 /// let u: Vec<_> = v.drain(1..).collect();
1287 /// assert_eq!(v, &[1]);
1288 /// assert_eq!(u, &[2, 3]);
1290 /// // A full range clears the vector
1292 /// assert_eq!(v, &[]);
1294 #[stable(feature = "drain", since = "1.6.0")]
1295 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1297 R: RangeBounds<usize>,
1301 // When the Drain is first created, it shortens the length of
1302 // the source vector to make sure no uninitialized or moved-from elements
1303 // are accessible at all if the Drain's destructor never gets to run.
1305 // Drain will ptr::read out the values to remove.
1306 // When finished, remaining tail of the vec is copied back to cover
1307 // the hole, and the vector length is restored to the new length.
1309 let len = self.len();
1310 let start = match range.start_bound() {
1312 Excluded(&n) => n + 1,
1315 let end = match range.end_bound() {
1316 Included(&n) => n + 1,
1323 fn start_assert_failed(start: usize, end: usize) -> ! {
1324 panic!("start drain index (is {}) should be <= end drain index (is {})", start, end);
1329 fn end_assert_failed(end: usize, len: usize) -> ! {
1330 panic!("end drain index (is {}) should be <= len (is {})", end, len);
1334 start_assert_failed(start, end);
1337 end_assert_failed(end, len);
1341 // set self.vec length's to start, to be safe in case Drain is leaked
1342 self.set_len(start);
1343 // Use the borrow in the IterMut to indicate borrowing behavior of the
1344 // whole Drain iterator (like &mut T).
1345 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1348 tail_len: len - end,
1349 iter: range_slice.iter(),
1350 vec: NonNull::from(self),
1355 /// Clears the vector, removing all values.
1357 /// Note that this method has no effect on the allocated capacity
1363 /// let mut v = vec![1, 2, 3];
1367 /// assert!(v.is_empty());
1370 #[stable(feature = "rust1", since = "1.0.0")]
1371 pub fn clear(&mut self) {
1375 /// Returns the number of elements in the vector, also referred to
1376 /// as its 'length'.
1381 /// let a = vec![1, 2, 3];
1382 /// assert_eq!(a.len(), 3);
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 pub fn len(&self) -> usize {
1390 /// Returns `true` if the vector contains no elements.
1395 /// let mut v = Vec::new();
1396 /// assert!(v.is_empty());
1399 /// assert!(!v.is_empty());
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 pub fn is_empty(&self) -> bool {
1406 /// Splits the collection into two at the given index.
1408 /// Returns a newly allocated vector containing the elements in the range
1409 /// `[at, len)`. After the call, the original vector will be left containing
1410 /// the elements `[0, at)` with its previous capacity unchanged.
1414 /// Panics if `at > len`.
1419 /// let mut vec = vec![1,2,3];
1420 /// let vec2 = vec.split_off(1);
1421 /// assert_eq!(vec, [1]);
1422 /// assert_eq!(vec2, [2, 3]);
1425 #[must_use = "use `.truncate()` if you don't need the other half"]
1426 #[stable(feature = "split_off", since = "1.4.0")]
1427 pub fn split_off(&mut self, at: usize) -> Self {
1430 fn assert_failed(at: usize, len: usize) -> ! {
1431 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1434 if at > self.len() {
1435 assert_failed(at, self.len());
1438 let other_len = self.len - at;
1439 let mut other = Vec::with_capacity(other_len);
1441 // Unsafely `set_len` and copy items to `other`.
1444 other.set_len(other_len);
1446 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1451 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1453 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1454 /// difference, with each additional slot filled with the result of
1455 /// calling the closure `f`. The return values from `f` will end up
1456 /// in the `Vec` in the order they have been generated.
1458 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1460 /// This method uses a closure to create new values on every push. If
1461 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
1462 /// want to use the [`Default`] trait to generate values, you can
1463 /// pass [`Default::default`] as the second argument.
1468 /// let mut vec = vec![1, 2, 3];
1469 /// vec.resize_with(5, Default::default);
1470 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1472 /// let mut vec = vec![];
1474 /// vec.resize_with(4, || { p *= 2; p });
1475 /// assert_eq!(vec, [2, 4, 8, 16]);
1477 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1478 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1482 let len = self.len();
1484 self.extend_with(new_len - len, ExtendFunc(f));
1486 self.truncate(new_len);
1490 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1491 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1492 /// `'a`. If the type has only static references, or none at all, then this
1493 /// may be chosen to be `'static`.
1495 /// This function is similar to the `leak` function on `Box`.
1497 /// This function is mainly useful for data that lives for the remainder of
1498 /// the program's life. Dropping the returned reference will cause a memory
1506 /// let x = vec![1, 2, 3];
1507 /// let static_ref: &'static mut [usize] = x.leak();
1508 /// static_ref[0] += 1;
1509 /// assert_eq!(static_ref, &[2, 2, 3]);
1511 #[stable(feature = "vec_leak", since = "1.47.0")]
1513 pub fn leak<'a>(self) -> &'a mut [T]
1515 T: 'a, // Technically not needed, but kept to be explicit.
1517 Box::leak(self.into_boxed_slice())
1520 /// Returns the remaining spare capacity of the vector as a slice of
1521 /// `MaybeUninit<T>`.
1523 /// The returned slice can be used to fill the vector with data (e.g. by
1524 /// reading from a file) before marking the data as initialized using the
1525 /// [`set_len`] method.
1527 /// [`set_len`]: Vec::set_len
1532 /// #![feature(vec_spare_capacity, maybe_uninit_extra)]
1534 /// // Allocate vector big enough for 10 elements.
1535 /// let mut v = Vec::with_capacity(10);
1537 /// // Fill in the first 3 elements.
1538 /// let uninit = v.spare_capacity_mut();
1539 /// uninit[0].write(0);
1540 /// uninit[1].write(1);
1541 /// uninit[2].write(2);
1543 /// // Mark the first 3 elements of the vector as being initialized.
1548 /// assert_eq!(&v, &[0, 1, 2]);
1550 #[unstable(feature = "vec_spare_capacity", issue = "75017")]
1552 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1554 slice::from_raw_parts_mut(
1555 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
1556 self.buf.capacity() - self.len,
1562 impl<T: Clone> Vec<T> {
1563 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1565 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1566 /// difference, with each additional slot filled with `value`.
1567 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1569 /// This method requires `T` to implement [`Clone`],
1570 /// in order to be able to clone the passed value.
1571 /// If you need more flexibility (or want to rely on [`Default`] instead of
1572 /// [`Clone`]), use [`Vec::resize_with`].
1577 /// let mut vec = vec!["hello"];
1578 /// vec.resize(3, "world");
1579 /// assert_eq!(vec, ["hello", "world", "world"]);
1581 /// let mut vec = vec![1, 2, 3, 4];
1582 /// vec.resize(2, 0);
1583 /// assert_eq!(vec, [1, 2]);
1585 #[stable(feature = "vec_resize", since = "1.5.0")]
1586 pub fn resize(&mut self, new_len: usize, value: T) {
1587 let len = self.len();
1590 self.extend_with(new_len - len, ExtendElement(value))
1592 self.truncate(new_len);
1596 /// Clones and appends all elements in a slice to the `Vec`.
1598 /// Iterates over the slice `other`, clones each element, and then appends
1599 /// it to this `Vec`. The `other` vector is traversed in-order.
1601 /// Note that this function is same as [`extend`] except that it is
1602 /// specialized to work with slices instead. If and when Rust gets
1603 /// specialization this function will likely be deprecated (but still
1609 /// let mut vec = vec![1];
1610 /// vec.extend_from_slice(&[2, 3, 4]);
1611 /// assert_eq!(vec, [1, 2, 3, 4]);
1614 /// [`extend`]: Vec::extend
1615 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1616 pub fn extend_from_slice(&mut self, other: &[T]) {
1617 self.spec_extend(other.iter())
1621 impl<T: Default> Vec<T> {
1622 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1624 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1625 /// difference, with each additional slot filled with [`Default::default()`].
1626 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1628 /// This method uses [`Default`] to create new values on every push. If
1629 /// you'd rather [`Clone`] a given value, use [`resize`].
1634 /// # #![allow(deprecated)]
1635 /// #![feature(vec_resize_default)]
1637 /// let mut vec = vec![1, 2, 3];
1638 /// vec.resize_default(5);
1639 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1641 /// let mut vec = vec![1, 2, 3, 4];
1642 /// vec.resize_default(2);
1643 /// assert_eq!(vec, [1, 2]);
1646 /// [`resize`]: Vec::resize
1647 #[unstable(feature = "vec_resize_default", issue = "41758")]
1649 reason = "This is moving towards being removed in favor \
1650 of `.resize_with(Default::default)`. If you disagree, please comment \
1651 in the tracking issue.",
1654 pub fn resize_default(&mut self, new_len: usize) {
1655 let len = self.len();
1658 self.extend_with(new_len - len, ExtendDefault);
1660 self.truncate(new_len);
1665 // This code generalizes `extend_with_{element,default}`.
1666 trait ExtendWith<T> {
1667 fn next(&mut self) -> T;
1671 struct ExtendElement<T>(T);
1672 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1673 fn next(&mut self) -> T {
1676 fn last(self) -> T {
1681 struct ExtendDefault;
1682 impl<T: Default> ExtendWith<T> for ExtendDefault {
1683 fn next(&mut self) -> T {
1686 fn last(self) -> T {
1691 struct ExtendFunc<F>(F);
1692 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1693 fn next(&mut self) -> T {
1696 fn last(mut self) -> T {
1702 /// Extend the vector by `n` values, using the given generator.
1703 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1707 let mut ptr = self.as_mut_ptr().add(self.len());
1708 // Use SetLenOnDrop to work around bug where compiler
1709 // may not realize the store through `ptr` through self.set_len()
1711 let mut local_len = SetLenOnDrop::new(&mut self.len);
1713 // Write all elements except the last one
1715 ptr::write(ptr, value.next());
1716 ptr = ptr.offset(1);
1717 // Increment the length in every step in case next() panics
1718 local_len.increment_len(1);
1722 // We can write the last element directly without cloning needlessly
1723 ptr::write(ptr, value.last());
1724 local_len.increment_len(1);
1727 // len set by scope guard
1732 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1734 // The idea is: The length field in SetLenOnDrop is a local variable
1735 // that the optimizer will see does not alias with any stores through the Vec's data
1736 // pointer. This is a workaround for alias analysis issue #32155
1737 struct SetLenOnDrop<'a> {
1742 impl<'a> SetLenOnDrop<'a> {
1744 fn new(len: &'a mut usize) -> Self {
1745 SetLenOnDrop { local_len: *len, len }
1749 fn increment_len(&mut self, increment: usize) {
1750 self.local_len += increment;
1754 impl Drop for SetLenOnDrop<'_> {
1756 fn drop(&mut self) {
1757 *self.len = self.local_len;
1761 impl<T: PartialEq> Vec<T> {
1762 /// Removes consecutive repeated elements in the vector according to the
1763 /// [`PartialEq`] trait implementation.
1765 /// If the vector is sorted, this removes all duplicates.
1770 /// let mut vec = vec![1, 2, 2, 3, 2];
1774 /// assert_eq!(vec, [1, 2, 3, 2]);
1776 #[stable(feature = "rust1", since = "1.0.0")]
1778 pub fn dedup(&mut self) {
1779 self.dedup_by(|a, b| a == b)
1784 /// Removes the first instance of `item` from the vector if the item exists.
1786 /// This method will be removed soon.
1787 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1789 reason = "Removing the first item equal to a needle is already easily possible \
1790 with iterators and the current Vec methods. Furthermore, having a method for \
1791 one particular case of removal (linear search, only the first item, no swap remove) \
1792 but not for others is inconsistent. This method will be removed soon.",
1795 pub fn remove_item<V>(&mut self, item: &V) -> Option<T>
1799 let pos = self.iter().position(|x| *x == *item)?;
1800 Some(self.remove(pos))
1804 ////////////////////////////////////////////////////////////////////////////////
1805 // Internal methods and functions
1806 ////////////////////////////////////////////////////////////////////////////////
1809 #[stable(feature = "rust1", since = "1.0.0")]
1810 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1811 <T as SpecFromElem>::from_elem(elem, n)
1814 // Specialization trait used for Vec::from_elem
1815 trait SpecFromElem: Sized {
1816 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1819 impl<T: Clone> SpecFromElem for T {
1820 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1821 let mut v = Vec::with_capacity(n);
1822 v.extend_with(n, ExtendElement(elem));
1827 impl SpecFromElem for i8 {
1829 fn from_elem(elem: i8, n: usize) -> Vec<i8> {
1831 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1834 let mut v = Vec::with_capacity(n);
1835 ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
1842 impl SpecFromElem for u8 {
1844 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1846 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1849 let mut v = Vec::with_capacity(n);
1850 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1857 impl<T: Clone + IsZero> SpecFromElem for T {
1859 fn from_elem(elem: T, n: usize) -> Vec<T> {
1861 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1863 let mut v = Vec::with_capacity(n);
1864 v.extend_with(n, ExtendElement(elem));
1869 #[rustc_specialization_trait]
1870 unsafe trait IsZero {
1871 /// Whether this value is zero
1872 fn is_zero(&self) -> bool;
1875 macro_rules! impl_is_zero {
1876 ($t:ty, $is_zero:expr) => {
1877 unsafe impl IsZero for $t {
1879 fn is_zero(&self) -> bool {
1886 impl_is_zero!(i16, |x| x == 0);
1887 impl_is_zero!(i32, |x| x == 0);
1888 impl_is_zero!(i64, |x| x == 0);
1889 impl_is_zero!(i128, |x| x == 0);
1890 impl_is_zero!(isize, |x| x == 0);
1892 impl_is_zero!(u16, |x| x == 0);
1893 impl_is_zero!(u32, |x| x == 0);
1894 impl_is_zero!(u64, |x| x == 0);
1895 impl_is_zero!(u128, |x| x == 0);
1896 impl_is_zero!(usize, |x| x == 0);
1898 impl_is_zero!(bool, |x| x == false);
1899 impl_is_zero!(char, |x| x == '\0');
1901 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1902 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1904 unsafe impl<T> IsZero for *const T {
1906 fn is_zero(&self) -> bool {
1911 unsafe impl<T> IsZero for *mut T {
1913 fn is_zero(&self) -> bool {
1918 // `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
1919 // For fat pointers, the bytes that would be the pointer metadata in the `Some`
1920 // variant are padding in the `None` variant, so ignoring them and
1921 // zero-initializing instead is ok.
1922 // `Option<&mut T>` never implements `Clone`, so there's no need for an impl of
1925 unsafe impl<T: ?Sized> IsZero for Option<&T> {
1927 fn is_zero(&self) -> bool {
1932 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
1934 fn is_zero(&self) -> bool {
1939 ////////////////////////////////////////////////////////////////////////////////
1940 // Common trait implementations for Vec
1941 ////////////////////////////////////////////////////////////////////////////////
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 impl<T> ops::Deref for Vec<T> {
1947 fn deref(&self) -> &[T] {
1948 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
1952 #[stable(feature = "rust1", since = "1.0.0")]
1953 impl<T> ops::DerefMut for Vec<T> {
1954 fn deref_mut(&mut self) -> &mut [T] {
1955 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1959 #[stable(feature = "rust1", since = "1.0.0")]
1960 impl<T: Clone> Clone for Vec<T> {
1962 fn clone(&self) -> Vec<T> {
1963 <[T]>::to_vec(&**self)
1966 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1967 // required for this method definition, is not available. Instead use the
1968 // `slice::to_vec` function which is only available with cfg(test)
1969 // NB see the slice::hack module in slice.rs for more information
1971 fn clone(&self) -> Vec<T> {
1972 crate::slice::to_vec(&**self)
1975 fn clone_from(&mut self, other: &Vec<T>) {
1976 other.as_slice().clone_into(self);
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 impl<T: Hash> Hash for Vec<T> {
1983 fn hash<H: Hasher>(&self, state: &mut H) {
1984 Hash::hash(&**self, state)
1988 #[stable(feature = "rust1", since = "1.0.0")]
1989 #[rustc_on_unimplemented(
1990 message = "vector indices are of type `usize` or ranges of `usize`",
1991 label = "vector indices are of type `usize` or ranges of `usize`"
1993 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
1994 type Output = I::Output;
1997 fn index(&self, index: I) -> &Self::Output {
1998 Index::index(&**self, index)
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 #[rustc_on_unimplemented(
2004 message = "vector indices are of type `usize` or ranges of `usize`",
2005 label = "vector indices are of type `usize` or ranges of `usize`"
2007 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
2009 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2010 IndexMut::index_mut(&mut **self, index)
2014 #[stable(feature = "rust1", since = "1.0.0")]
2015 impl<T> FromIterator<T> for Vec<T> {
2017 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2018 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
2022 #[stable(feature = "rust1", since = "1.0.0")]
2023 impl<T> IntoIterator for Vec<T> {
2025 type IntoIter = IntoIter<T>;
2027 /// Creates a consuming iterator, that is, one that moves each value out of
2028 /// the vector (from start to end). The vector cannot be used after calling
2034 /// let v = vec!["a".to_string(), "b".to_string()];
2035 /// for s in v.into_iter() {
2036 /// // s has type String, not &String
2037 /// println!("{}", s);
2041 fn into_iter(self) -> IntoIter<T> {
2043 let mut me = ManuallyDrop::new(self);
2044 let begin = me.as_mut_ptr();
2045 let end = if mem::size_of::<T>() == 0 {
2046 arith_offset(begin as *const i8, me.len() as isize) as *const T
2048 begin.add(me.len()) as *const T
2050 let cap = me.buf.capacity();
2052 buf: NonNull::new_unchecked(begin),
2053 phantom: PhantomData,
2062 #[stable(feature = "rust1", since = "1.0.0")]
2063 impl<'a, T> IntoIterator for &'a Vec<T> {
2065 type IntoIter = slice::Iter<'a, T>;
2067 fn into_iter(self) -> slice::Iter<'a, T> {
2072 #[stable(feature = "rust1", since = "1.0.0")]
2073 impl<'a, T> IntoIterator for &'a mut Vec<T> {
2074 type Item = &'a mut T;
2075 type IntoIter = slice::IterMut<'a, T>;
2077 fn into_iter(self) -> slice::IterMut<'a, T> {
2082 #[stable(feature = "rust1", since = "1.0.0")]
2083 impl<T> Extend<T> for Vec<T> {
2085 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2086 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2090 fn extend_one(&mut self, item: T) {
2095 fn extend_reserve(&mut self, additional: usize) {
2096 self.reserve(additional);
2100 /// Specialization trait used for Vec::from_iter
2102 /// ## The delegation graph:
2110 /// +-+-------------------------------+ +---------------------+
2111 /// |SpecFromIter +---->+SpecFromIterNested |
2112 /// |where I: | | |where I: |
2113 /// | Iterator (default)----------+ | | Iterator (default) |
2114 /// | vec::IntoIter | | | TrustedLen |
2115 /// | SourceIterMarker---fallback-+ | | |
2116 /// | slice::Iter | | |
2117 /// | Iterator<Item = &Clone> | +---------------------+
2118 /// +---------------------------------+
2121 trait SpecFromIter<T, I> {
2122 fn from_iter(iter: I) -> Self;
2125 /// Another specialization trait for Vec::from_iter
2126 /// necessary to manually prioritize overlapping specializations
2127 /// see [`SpecFromIter`] for details.
2128 trait SpecFromIterNested<T, I> {
2129 fn from_iter(iter: I) -> Self;
2132 impl<T, I> SpecFromIterNested<T, I> for Vec<T>
2134 I: Iterator<Item = T>,
2136 default fn from_iter(mut iterator: I) -> Self {
2137 // Unroll the first iteration, as the vector is going to be
2138 // expanded on this iteration in every case when the iterable is not
2139 // empty, but the loop in extend_desugared() is not going to see the
2140 // vector being full in the few subsequent loop iterations.
2141 // So we get better branch prediction.
2142 let mut vector = match iterator.next() {
2143 None => return Vec::new(),
2145 let (lower, _) = iterator.size_hint();
2146 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2148 ptr::write(vector.as_mut_ptr(), element);
2154 // must delegate to spec_extend() since extend() itself delegates
2155 // to spec_from for empty Vecs
2156 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2161 impl<T, I> SpecFromIterNested<T, I> for Vec<T>
2163 I: TrustedLen<Item = T>,
2165 fn from_iter(iterator: I) -> Self {
2166 let mut vector = Vec::new();
2167 // must delegate to spec_extend() since extend() itself delegates
2168 // to spec_from for empty Vecs
2169 vector.spec_extend(iterator);
2174 impl<T, I> SpecFromIter<T, I> for Vec<T>
2176 I: Iterator<Item = T>,
2178 default fn from_iter(iterator: I) -> Self {
2179 SpecFromIterNested::from_iter(iterator)
2183 // A helper struct for in-place iteration that drops the destination slice of iteration,
2184 // i.e. the head. The source slice (the tail) is dropped by IntoIter.
2185 struct InPlaceDrop<T> {
2190 impl<T> InPlaceDrop<T> {
2191 fn len(&self) -> usize {
2192 unsafe { self.dst.offset_from(self.inner) as usize }
2196 impl<T> Drop for InPlaceDrop<T> {
2198 fn drop(&mut self) {
2199 if mem::needs_drop::<T>() {
2201 ptr::drop_in_place(slice::from_raw_parts_mut(self.inner, self.len()));
2207 impl<T> SpecFromIter<T, IntoIter<T>> for Vec<T> {
2208 fn from_iter(iterator: IntoIter<T>) -> Self {
2209 // A common case is passing a vector into a function which immediately
2210 // re-collects into a vector. We can short circuit this if the IntoIter
2211 // has not been advanced at all.
2212 // When it has been advanced We can also reuse the memory and move the data to the front.
2213 // But we only do so when the resulting Vec wouldn't have more unused capacity
2214 // than creating it through the generic FromIterator implementation would. That limitation
2215 // is not strictly necessary as Vec's allocation behavior is intentionally unspecified.
2216 // But it is a conservative choice.
2217 let has_advanced = iterator.buf.as_ptr() as *const _ != iterator.ptr;
2218 if !has_advanced || iterator.len() >= iterator.cap / 2 {
2220 let it = ManuallyDrop::new(iterator);
2222 ptr::copy(it.ptr, it.buf.as_ptr(), it.len());
2224 return Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap);
2228 let mut vec = Vec::new();
2229 // must delegate to spec_extend() since extend() itself delegates
2230 // to spec_from for empty Vecs
2231 vec.spec_extend(iterator);
2236 fn write_in_place_with_drop<T>(
2238 ) -> impl FnMut(InPlaceDrop<T>, T) -> Result<InPlaceDrop<T>, !> {
2239 move |mut sink, item| {
2241 // the InPlaceIterable contract cannot be verified precisely here since
2242 // try_fold has an exclusive reference to the source pointer
2243 // all we can do is check if it's still in range
2244 debug_assert!(sink.dst as *const _ <= src_end, "InPlaceIterable contract violation");
2245 ptr::write(sink.dst, item);
2246 sink.dst = sink.dst.add(1);
2252 /// Specialization marker for collecting an iterator pipeline into a Vec while reusing the
2253 /// source allocation, i.e. executing the pipeline in place.
2255 /// The SourceIter parent trait is necessary for the specializing function to access the allocation
2256 /// which is to be reused. But it is not sufficient for the specialization to be valid. See
2257 /// additional bounds on the impl.
2258 #[rustc_unsafe_specialization_marker]
2259 trait SourceIterMarker: SourceIter<Source: AsIntoIter> {}
2261 // The std-internal SourceIter/InPlaceIterable traits are only implemented by chains of
2262 // Adapter<Adapter<Adapter<IntoIter>>> (all owned by core/std). Additional bounds
2263 // on the adapter implementations (beyond `impl<I: Trait> Trait for Adapter<I>`) only depend on other
2264 // traits already marked as specialization traits (Copy, TrustedRandomAccess, FusedIterator).
2265 // I.e. the marker does not depend on lifetimes of user-supplied types. Modulo the Copy hole, which
2266 // several other specializations already depend on.
2267 impl<T> SourceIterMarker for T where T: SourceIter<Source: AsIntoIter> + InPlaceIterable {}
2269 impl<T, I> SpecFromIter<T, I> for Vec<T>
2271 I: Iterator<Item = T> + SourceIterMarker,
2273 default fn from_iter(mut iterator: I) -> Self {
2274 // Additional requirements which cannot expressed via trait bounds. We rely on const eval
2276 // a) no ZSTs as there would be no allocation to reuse and pointer arithmetic would panic
2277 // b) size match as required by Alloc contract
2278 // c) alignments match as required by Alloc contract
2279 if mem::size_of::<T>() == 0
2280 || mem::size_of::<T>()
2281 != mem::size_of::<<<I as SourceIter>::Source as AsIntoIter>::Item>()
2282 || mem::align_of::<T>()
2283 != mem::align_of::<<<I as SourceIter>::Source as AsIntoIter>::Item>()
2285 // fallback to more generic implementations
2286 return SpecFromIterNested::from_iter(iterator);
2289 let (src_buf, src_ptr, dst_buf, dst_end, cap) = unsafe {
2290 let inner = iterator.as_inner().as_into_iter();
2294 inner.buf.as_ptr() as *mut T,
2295 inner.end as *const T,
2300 // use try-fold since
2301 // - it vectorizes better for some iterator adapters
2302 // - unlike most internal iteration methods methods it only takes a &mut self
2303 // - it lets us thread the write pointer through its innards and get it back in the end
2304 let sink = InPlaceDrop { inner: dst_buf, dst: dst_buf };
2306 .try_fold::<_, _, Result<_, !>>(sink, write_in_place_with_drop(dst_end))
2308 // iteration succeeded, don't drop head
2309 let dst = mem::ManuallyDrop::new(sink).dst;
2311 let src = unsafe { iterator.as_inner().as_into_iter() };
2312 // check if SourceIter contract was upheld
2313 // caveat: if they weren't we may not even make it to this point
2314 debug_assert_eq!(src_buf, src.buf.as_ptr());
2315 // check InPlaceIterable contract. This is only possible if the iterator advanced the
2316 // source pointer at all. If it uses unchecked access via TrustedRandomAccess
2317 // then the source pointer will stay in its initial position and we can't use it as reference
2318 if src.ptr != src_ptr {
2320 dst as *const _ <= src.ptr,
2321 "InPlaceIterable contract violation, write pointer advanced beyond read pointer"
2325 // drop any remaining values at the tail of the source
2326 src.drop_remaining();
2327 // but prevent drop of the allocation itself once IntoIter goes out of scope
2328 src.forget_allocation();
2331 let len = dst.offset_from(dst_buf) as usize;
2332 Vec::from_raw_parts(dst_buf, len, cap)
2339 impl<'a, T: 'a, I> SpecFromIter<&'a T, I> for Vec<T>
2341 I: Iterator<Item = &'a T>,
2344 default fn from_iter(iterator: I) -> Self {
2345 SpecFromIter::from_iter(iterator.cloned())
2349 impl<'a, T: 'a> SpecFromIter<&'a T, slice::Iter<'a, T>> for Vec<T>
2353 // reuses the extend specialization for T: Copy
2354 fn from_iter(iterator: slice::Iter<'a, T>) -> Self {
2355 let mut vec = Vec::new();
2356 // must delegate to spec_extend() since extend() itself delegates
2357 // to spec_from for empty Vecs
2358 vec.spec_extend(iterator);
2363 // Specialization trait used for Vec::extend
2364 trait SpecExtend<T, I> {
2365 fn spec_extend(&mut self, iter: I);
2368 impl<T, I> SpecExtend<T, I> for Vec<T>
2370 I: Iterator<Item = T>,
2372 default fn spec_extend(&mut self, iter: I) {
2373 self.extend_desugared(iter)
2377 impl<T, I> SpecExtend<T, I> for Vec<T>
2379 I: TrustedLen<Item = T>,
2381 default fn spec_extend(&mut self, iterator: I) {
2382 // This is the case for a TrustedLen iterator.
2383 let (low, high) = iterator.size_hint();
2384 if let Some(high_value) = high {
2388 "TrustedLen iterator's size hint is not exact: {:?}",
2392 if let Some(additional) = high {
2393 self.reserve(additional);
2395 let mut ptr = self.as_mut_ptr().add(self.len());
2396 let mut local_len = SetLenOnDrop::new(&mut self.len);
2397 iterator.for_each(move |element| {
2398 ptr::write(ptr, element);
2399 ptr = ptr.offset(1);
2400 // NB can't overflow since we would have had to alloc the address space
2401 local_len.increment_len(1);
2405 self.extend_desugared(iterator)
2410 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2411 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2413 self.append_elements(iterator.as_slice() as _);
2415 iterator.ptr = iterator.end;
2419 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2421 I: Iterator<Item = &'a T>,
2424 default fn spec_extend(&mut self, iterator: I) {
2425 self.spec_extend(iterator.cloned())
2429 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2433 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2434 let slice = iterator.as_slice();
2435 unsafe { self.append_elements(slice) };
2440 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2441 // they have no further optimizations to apply
2442 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2443 // This is the case for a general iterator.
2445 // This function should be the moral equivalent of:
2447 // for item in iterator {
2450 while let Some(element) = iterator.next() {
2451 let len = self.len();
2452 if len == self.capacity() {
2453 let (lower, _) = iterator.size_hint();
2454 self.reserve(lower.saturating_add(1));
2457 ptr::write(self.as_mut_ptr().add(len), element);
2458 // NB can't overflow since we would have had to alloc the address space
2459 self.set_len(len + 1);
2464 /// Creates a splicing iterator that replaces the specified range in the vector
2465 /// with the given `replace_with` iterator and yields the removed items.
2466 /// `replace_with` does not need to be the same length as `range`.
2468 /// `range` is removed even if the iterator is not consumed until the end.
2470 /// It is unspecified how many elements are removed from the vector
2471 /// if the `Splice` value is leaked.
2473 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2475 /// This is optimal if:
2477 /// * The tail (elements in the vector after `range`) is empty,
2478 /// * or `replace_with` yields fewer elements than `range`’s length
2479 /// * or the lower bound of its `size_hint()` is exact.
2481 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2485 /// Panics if the starting point is greater than the end point or if
2486 /// the end point is greater than the length of the vector.
2491 /// let mut v = vec![1, 2, 3];
2492 /// let new = [7, 8];
2493 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2494 /// assert_eq!(v, &[7, 8, 3]);
2495 /// assert_eq!(u, &[1, 2]);
2498 #[stable(feature = "vec_splice", since = "1.21.0")]
2499 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2501 R: RangeBounds<usize>,
2502 I: IntoIterator<Item = T>,
2504 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2507 /// Creates an iterator which uses a closure to determine if an element should be removed.
2509 /// If the closure returns true, then the element is removed and yielded.
2510 /// If the closure returns false, the element will remain in the vector and will not be yielded
2511 /// by the iterator.
2513 /// Using this method is equivalent to the following code:
2516 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2517 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2519 /// while i != vec.len() {
2520 /// if some_predicate(&mut vec[i]) {
2521 /// let val = vec.remove(i);
2522 /// // your code here
2528 /// # assert_eq!(vec, vec![1, 4, 5]);
2531 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2532 /// because it can backshift the elements of the array in bulk.
2534 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2535 /// regardless of whether you choose to keep or remove it.
2539 /// Splitting an array into evens and odds, reusing the original allocation:
2542 /// #![feature(drain_filter)]
2543 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2545 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2546 /// let odds = numbers;
2548 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2549 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2551 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2552 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2554 F: FnMut(&mut T) -> bool,
2556 let old_len = self.len();
2558 // Guard against us getting leaked (leak amplification)
2563 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2567 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2569 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2570 /// append the entire slice at once.
2572 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2573 #[stable(feature = "extend_ref", since = "1.2.0")]
2574 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2575 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2576 self.spec_extend(iter.into_iter())
2580 fn extend_one(&mut self, &item: &'a T) {
2585 fn extend_reserve(&mut self, additional: usize) {
2586 self.reserve(additional);
2590 macro_rules! __impl_slice_eq1 {
2591 ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => {
2593 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2599 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2601 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2606 __impl_slice_eq1! { [] Vec<A>, Vec<B>, #[stable(feature = "rust1", since = "1.0.0")] }
2607 __impl_slice_eq1! { [] Vec<A>, &[B], #[stable(feature = "rust1", since = "1.0.0")] }
2608 __impl_slice_eq1! { [] Vec<A>, &mut [B], #[stable(feature = "rust1", since = "1.0.0")] }
2609 __impl_slice_eq1! { [] &[A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2610 __impl_slice_eq1! { [] &mut [A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2611 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B> where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2612 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2613 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2614 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2615 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2617 // NOTE: some less important impls are omitted to reduce code bloat
2618 // FIXME(Centril): Reconsider this?
2619 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], }
2620 //__impl_slice_eq1! { [const N: usize] [A; N], Vec<B>, }
2621 //__impl_slice_eq1! { [const N: usize] &[A; N], Vec<B>, }
2622 //__impl_slice_eq1! { [const N: usize] &mut [A; N], Vec<B>, }
2623 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], }
2624 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], }
2625 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], }
2627 /// Implements comparison of vectors, lexicographically.
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 impl<T: PartialOrd> PartialOrd for Vec<T> {
2631 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2632 PartialOrd::partial_cmp(&**self, &**other)
2636 #[stable(feature = "rust1", since = "1.0.0")]
2637 impl<T: Eq> Eq for Vec<T> {}
2639 /// Implements ordering of vectors, lexicographically.
2640 #[stable(feature = "rust1", since = "1.0.0")]
2641 impl<T: Ord> Ord for Vec<T> {
2643 fn cmp(&self, other: &Vec<T>) -> Ordering {
2644 Ord::cmp(&**self, &**other)
2648 #[stable(feature = "rust1", since = "1.0.0")]
2649 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2650 fn drop(&mut self) {
2653 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2654 // could avoid questions of validity in certain cases
2655 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2657 // RawVec handles deallocation
2661 #[stable(feature = "rust1", since = "1.0.0")]
2662 impl<T> Default for Vec<T> {
2663 /// Creates an empty `Vec<T>`.
2664 fn default() -> Vec<T> {
2669 #[stable(feature = "rust1", since = "1.0.0")]
2670 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2671 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2672 fmt::Debug::fmt(&**self, f)
2676 #[stable(feature = "rust1", since = "1.0.0")]
2677 impl<T> AsRef<Vec<T>> for Vec<T> {
2678 fn as_ref(&self) -> &Vec<T> {
2683 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2684 impl<T> AsMut<Vec<T>> for Vec<T> {
2685 fn as_mut(&mut self) -> &mut Vec<T> {
2690 #[stable(feature = "rust1", since = "1.0.0")]
2691 impl<T> AsRef<[T]> for Vec<T> {
2692 fn as_ref(&self) -> &[T] {
2697 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2698 impl<T> AsMut<[T]> for Vec<T> {
2699 fn as_mut(&mut self) -> &mut [T] {
2704 #[stable(feature = "rust1", since = "1.0.0")]
2705 impl<T: Clone> From<&[T]> for Vec<T> {
2707 fn from(s: &[T]) -> Vec<T> {
2711 fn from(s: &[T]) -> Vec<T> {
2712 crate::slice::to_vec(s)
2716 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2717 impl<T: Clone> From<&mut [T]> for Vec<T> {
2719 fn from(s: &mut [T]) -> Vec<T> {
2723 fn from(s: &mut [T]) -> Vec<T> {
2724 crate::slice::to_vec(s)
2728 #[stable(feature = "vec_from_array", since = "1.44.0")]
2729 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2731 fn from(s: [T; N]) -> Vec<T> {
2732 <[T]>::into_vec(box s)
2735 fn from(s: [T; N]) -> Vec<T> {
2736 crate::slice::into_vec(box s)
2740 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2741 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2743 [T]: ToOwned<Owned = Vec<T>>,
2745 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2750 // note: test pulls in libstd, which causes errors here
2752 #[stable(feature = "vec_from_box", since = "1.18.0")]
2753 impl<T> From<Box<[T]>> for Vec<T> {
2754 fn from(s: Box<[T]>) -> Vec<T> {
2759 // note: test pulls in libstd, which causes errors here
2761 #[stable(feature = "box_from_vec", since = "1.20.0")]
2762 impl<T> From<Vec<T>> for Box<[T]> {
2763 fn from(v: Vec<T>) -> Box<[T]> {
2764 v.into_boxed_slice()
2768 #[stable(feature = "rust1", since = "1.0.0")]
2769 impl From<&str> for Vec<u8> {
2770 fn from(s: &str) -> Vec<u8> {
2771 From::from(s.as_bytes())
2775 #[stable(feature = "array_try_from_vec", since = "1.47.0")]
2776 impl<T, const N: usize> TryFrom<Vec<T>> for [T; N] {
2777 type Error = Vec<T>;
2779 /// Gets the entire contents of the `Vec<T>` as an array,
2780 /// if its size exactly matches that of the requested array.
2785 /// use std::convert::TryInto;
2786 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
2787 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
2790 /// If the length doesn't match, the input comes back in `Err`:
2792 /// use std::convert::TryInto;
2793 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
2794 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
2797 /// If you're fine with just getting a prefix of the `Vec<T>`,
2798 /// you can call [`.truncate(N)`](Vec::truncate) first.
2800 /// use std::convert::TryInto;
2801 /// let mut v = String::from("hello world").into_bytes();
2804 /// let [a, b]: [_; 2] = v.try_into().unwrap();
2805 /// assert_eq!(a, b' ');
2806 /// assert_eq!(b, b'd');
2808 fn try_from(mut vec: Vec<T>) -> Result<[T; N], Vec<T>> {
2813 // SAFETY: `.set_len(0)` is always sound.
2814 unsafe { vec.set_len(0) };
2816 // SAFETY: A `Vec`'s pointer is always aligned property, and
2817 // the alignment the array needs is the same as the items.
2818 // We checked earlier that we have sufficient items.
2819 // The items will not double-drop as the `set_len`
2820 // tells the `Vec` not to also drop them.
2821 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
2826 ////////////////////////////////////////////////////////////////////////////////
2828 ////////////////////////////////////////////////////////////////////////////////
2830 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2831 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2832 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2837 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2838 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2839 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2844 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2845 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2846 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2847 Cow::Borrowed(v.as_slice())
2851 #[stable(feature = "rust1", since = "1.0.0")]
2852 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
2856 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2857 Cow::Owned(FromIterator::from_iter(it))
2861 ////////////////////////////////////////////////////////////////////////////////
2863 ////////////////////////////////////////////////////////////////////////////////
2865 /// An iterator that moves out of a vector.
2867 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
2868 /// by the [`IntoIterator`] trait).
2869 #[stable(feature = "rust1", since = "1.0.0")]
2870 pub struct IntoIter<T> {
2872 phantom: PhantomData<T>,
2878 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2879 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2880 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2881 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2885 impl<T> IntoIter<T> {
2886 /// Returns the remaining items of this iterator as a slice.
2891 /// let vec = vec!['a', 'b', 'c'];
2892 /// let mut into_iter = vec.into_iter();
2893 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2894 /// let _ = into_iter.next().unwrap();
2895 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2897 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2898 pub fn as_slice(&self) -> &[T] {
2899 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
2902 /// Returns the remaining items of this iterator as a mutable slice.
2907 /// let vec = vec!['a', 'b', 'c'];
2908 /// let mut into_iter = vec.into_iter();
2909 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2910 /// into_iter.as_mut_slice()[2] = 'z';
2911 /// assert_eq!(into_iter.next().unwrap(), 'a');
2912 /// assert_eq!(into_iter.next().unwrap(), 'b');
2913 /// assert_eq!(into_iter.next().unwrap(), 'z');
2915 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2916 pub fn as_mut_slice(&mut self) -> &mut [T] {
2917 unsafe { &mut *self.as_raw_mut_slice() }
2920 fn as_raw_mut_slice(&mut self) -> *mut [T] {
2921 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
2924 fn drop_remaining(&mut self) {
2925 if mem::needs_drop::<T>() {
2927 ptr::drop_in_place(self.as_mut_slice());
2930 self.ptr = self.end;
2933 /// Relinquishes the backing allocation, equivalent to
2934 /// `ptr::write(&mut self, Vec::new().into_iter())`
2935 fn forget_allocation(&mut self) {
2937 self.buf = unsafe { NonNull::new_unchecked(RawVec::NEW.ptr()) };
2938 self.ptr = self.buf.as_ptr();
2939 self.end = self.buf.as_ptr();
2943 #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
2944 impl<T> AsRef<[T]> for IntoIter<T> {
2945 fn as_ref(&self) -> &[T] {
2950 #[stable(feature = "rust1", since = "1.0.0")]
2951 unsafe impl<T: Send> Send for IntoIter<T> {}
2952 #[stable(feature = "rust1", since = "1.0.0")]
2953 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2955 #[stable(feature = "rust1", since = "1.0.0")]
2956 impl<T> Iterator for IntoIter<T> {
2960 fn next(&mut self) -> Option<T> {
2962 if self.ptr as *const _ == self.end {
2965 if mem::size_of::<T>() == 0 {
2966 // purposefully don't use 'ptr.offset' because for
2967 // vectors with 0-size elements this would return the
2969 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2971 // Make up a value of this ZST.
2975 self.ptr = self.ptr.offset(1);
2977 Some(ptr::read(old))
2984 fn size_hint(&self) -> (usize, Option<usize>) {
2985 let exact = if mem::size_of::<T>() == 0 {
2986 (self.end as usize).wrapping_sub(self.ptr as usize)
2988 unsafe { self.end.offset_from(self.ptr) as usize }
2990 (exact, Some(exact))
2994 fn count(self) -> usize {
2998 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item
3000 Self: TrustedRandomAccess,
3002 // SAFETY: the caller must uphold the contract for
3003 // `Iterator::get_unchecked`.
3005 if mem::size_of::<T>() == 0 { mem::zeroed() } else { ptr::read(self.ptr.add(i)) }
3010 #[stable(feature = "rust1", since = "1.0.0")]
3011 impl<T> DoubleEndedIterator for IntoIter<T> {
3013 fn next_back(&mut self) -> Option<T> {
3015 if self.end == self.ptr {
3018 if mem::size_of::<T>() == 0 {
3019 // See above for why 'ptr.offset' isn't used
3020 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
3022 // Make up a value of this ZST.
3025 self.end = self.end.offset(-1);
3027 Some(ptr::read(self.end))
3034 #[stable(feature = "rust1", since = "1.0.0")]
3035 impl<T> ExactSizeIterator for IntoIter<T> {
3036 fn is_empty(&self) -> bool {
3037 self.ptr == self.end
3041 #[stable(feature = "fused", since = "1.26.0")]
3042 impl<T> FusedIterator for IntoIter<T> {}
3044 #[unstable(feature = "trusted_len", issue = "37572")]
3045 unsafe impl<T> TrustedLen for IntoIter<T> {}
3048 #[unstable(issue = "none", feature = "std_internals")]
3049 // T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr
3050 // and thus we can't implement drop-handling
3051 unsafe impl<T> TrustedRandomAccess for IntoIter<T>
3055 fn may_have_side_effect() -> bool {
3060 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
3061 impl<T: Clone> Clone for IntoIter<T> {
3062 fn clone(&self) -> IntoIter<T> {
3063 self.as_slice().to_owned().into_iter()
3067 #[stable(feature = "rust1", since = "1.0.0")]
3068 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
3069 fn drop(&mut self) {
3070 struct DropGuard<'a, T>(&'a mut IntoIter<T>);
3072 impl<T> Drop for DropGuard<'_, T> {
3073 fn drop(&mut self) {
3074 // RawVec handles deallocation
3075 let _ = unsafe { RawVec::from_raw_parts(self.0.buf.as_ptr(), self.0.cap) };
3079 let guard = DropGuard(self);
3080 // destroy the remaining elements
3082 ptr::drop_in_place(guard.0.as_raw_mut_slice());
3084 // now `guard` will be dropped and do the rest
3088 #[unstable(issue = "none", feature = "inplace_iteration")]
3089 unsafe impl<T> InPlaceIterable for IntoIter<T> {}
3091 #[unstable(issue = "none", feature = "inplace_iteration")]
3092 unsafe impl<T> SourceIter for IntoIter<T> {
3093 type Source = IntoIter<T>;
3096 unsafe fn as_inner(&mut self) -> &mut Self::Source {
3101 // internal helper trait for in-place iteration specialization.
3102 #[rustc_specialization_trait]
3103 pub(crate) trait AsIntoIter {
3105 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item>;
3108 impl<T> AsIntoIter for IntoIter<T> {
3111 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item> {
3116 /// A draining iterator for `Vec<T>`.
3118 /// This `struct` is created by [`Vec::drain`].
3119 #[stable(feature = "drain", since = "1.6.0")]
3120 pub struct Drain<'a, T: 'a> {
3121 /// Index of tail to preserve
3125 /// Current remaining range to remove
3126 iter: slice::Iter<'a, T>,
3127 vec: NonNull<Vec<T>>,
3130 #[stable(feature = "collection_debug", since = "1.17.0")]
3131 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
3132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3133 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
3137 impl<'a, T> Drain<'a, T> {
3138 /// Returns the remaining items of this iterator as a slice.
3143 /// let mut vec = vec!['a', 'b', 'c'];
3144 /// let mut drain = vec.drain(..);
3145 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
3146 /// let _ = drain.next().unwrap();
3147 /// assert_eq!(drain.as_slice(), &['b', 'c']);
3149 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3150 pub fn as_slice(&self) -> &[T] {
3151 self.iter.as_slice()
3155 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3156 impl<'a, T> AsRef<[T]> for Drain<'a, T> {
3157 fn as_ref(&self) -> &[T] {
3162 #[stable(feature = "drain", since = "1.6.0")]
3163 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
3164 #[stable(feature = "drain", since = "1.6.0")]
3165 unsafe impl<T: Send> Send for Drain<'_, T> {}
3167 #[stable(feature = "drain", since = "1.6.0")]
3168 impl<T> Iterator for Drain<'_, T> {
3172 fn next(&mut self) -> Option<T> {
3173 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
3176 fn size_hint(&self) -> (usize, Option<usize>) {
3177 self.iter.size_hint()
3181 #[stable(feature = "drain", since = "1.6.0")]
3182 impl<T> DoubleEndedIterator for Drain<'_, T> {
3184 fn next_back(&mut self) -> Option<T> {
3185 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
3189 #[stable(feature = "drain", since = "1.6.0")]
3190 impl<T> Drop for Drain<'_, T> {
3191 fn drop(&mut self) {
3192 /// Continues dropping the remaining elements in the `Drain`, then moves back the
3193 /// un-`Drain`ed elements to restore the original `Vec`.
3194 struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>);
3196 impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> {
3197 fn drop(&mut self) {
3198 // Continue the same loop we have below. If the loop already finished, this does
3200 self.0.for_each(drop);
3202 if self.0.tail_len > 0 {
3204 let source_vec = self.0.vec.as_mut();
3205 // memmove back untouched tail, update to new length
3206 let start = source_vec.len();
3207 let tail = self.0.tail_start;
3209 let src = source_vec.as_ptr().add(tail);
3210 let dst = source_vec.as_mut_ptr().add(start);
3211 ptr::copy(src, dst, self.0.tail_len);
3213 source_vec.set_len(start + self.0.tail_len);
3219 // exhaust self first
3220 while let Some(item) = self.next() {
3221 let guard = DropGuard(self);
3226 // Drop a `DropGuard` to move back the non-drained tail of `self`.
3231 #[stable(feature = "drain", since = "1.6.0")]
3232 impl<T> ExactSizeIterator for Drain<'_, T> {
3233 fn is_empty(&self) -> bool {
3234 self.iter.is_empty()
3238 #[unstable(feature = "trusted_len", issue = "37572")]
3239 unsafe impl<T> TrustedLen for Drain<'_, T> {}
3241 #[stable(feature = "fused", since = "1.26.0")]
3242 impl<T> FusedIterator for Drain<'_, T> {}
3244 /// A splicing iterator for `Vec`.
3246 /// This struct is created by [`Vec::splice()`].
3247 /// See its documentation for more.
3249 #[stable(feature = "vec_splice", since = "1.21.0")]
3250 pub struct Splice<'a, I: Iterator + 'a> {
3251 drain: Drain<'a, I::Item>,
3255 #[stable(feature = "vec_splice", since = "1.21.0")]
3256 impl<I: Iterator> Iterator for Splice<'_, I> {
3257 type Item = I::Item;
3259 fn next(&mut self) -> Option<Self::Item> {
3263 fn size_hint(&self) -> (usize, Option<usize>) {
3264 self.drain.size_hint()
3268 #[stable(feature = "vec_splice", since = "1.21.0")]
3269 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
3270 fn next_back(&mut self) -> Option<Self::Item> {
3271 self.drain.next_back()
3275 #[stable(feature = "vec_splice", since = "1.21.0")]
3276 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
3278 #[stable(feature = "vec_splice", since = "1.21.0")]
3279 impl<I: Iterator> Drop for Splice<'_, I> {
3280 fn drop(&mut self) {
3281 self.drain.by_ref().for_each(drop);
3284 if self.drain.tail_len == 0 {
3285 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
3289 // First fill the range left by drain().
3290 if !self.drain.fill(&mut self.replace_with) {
3294 // There may be more elements. Use the lower bound as an estimate.
3295 // FIXME: Is the upper bound a better guess? Or something else?
3296 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
3297 if lower_bound > 0 {
3298 self.drain.move_tail(lower_bound);
3299 if !self.drain.fill(&mut self.replace_with) {
3304 // Collect any remaining elements.
3305 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
3306 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
3307 // Now we have an exact count.
3308 if collected.len() > 0 {
3309 self.drain.move_tail(collected.len());
3310 let filled = self.drain.fill(&mut collected);
3311 debug_assert!(filled);
3312 debug_assert_eq!(collected.len(), 0);
3315 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
3319 /// Private helper methods for `Splice::drop`
3320 impl<T> Drain<'_, T> {
3321 /// The range from `self.vec.len` to `self.tail_start` contains elements
3322 /// that have been moved out.
3323 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
3324 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
3325 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
3326 let vec = unsafe { self.vec.as_mut() };
3327 let range_start = vec.len;
3328 let range_end = self.tail_start;
3329 let range_slice = unsafe {
3330 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
3333 for place in range_slice {
3334 if let Some(new_item) = replace_with.next() {
3335 unsafe { ptr::write(place, new_item) };
3344 /// Makes room for inserting more elements before the tail.
3345 unsafe fn move_tail(&mut self, additional: usize) {
3346 let vec = unsafe { self.vec.as_mut() };
3347 let len = self.tail_start + self.tail_len;
3348 vec.buf.reserve(len, additional);
3350 let new_tail_start = self.tail_start + additional;
3352 let src = vec.as_ptr().add(self.tail_start);
3353 let dst = vec.as_mut_ptr().add(new_tail_start);
3354 ptr::copy(src, dst, self.tail_len);
3356 self.tail_start = new_tail_start;
3360 /// An iterator which uses a closure to determine if an element should be removed.
3362 /// This struct is created by [`Vec::drain_filter`].
3363 /// See its documentation for more.
3364 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3366 pub struct DrainFilter<'a, T, F>
3368 F: FnMut(&mut T) -> bool,
3370 vec: &'a mut Vec<T>,
3371 /// The index of the item that will be inspected by the next call to `next`.
3373 /// The number of items that have been drained (removed) thus far.
3375 /// The original length of `vec` prior to draining.
3377 /// The filter test predicate.
3379 /// A flag that indicates a panic has occurred in the filter test predicate.
3380 /// This is used as a hint in the drop implementation to prevent consumption
3381 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3382 /// backshifted in the `vec`, but no further items will be dropped or
3383 /// tested by the filter predicate.
3387 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3388 impl<T, F> Iterator for DrainFilter<'_, T, F>
3390 F: FnMut(&mut T) -> bool,
3394 fn next(&mut self) -> Option<T> {
3396 while self.idx < self.old_len {
3398 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3399 self.panic_flag = true;
3400 let drained = (self.pred)(&mut v[i]);
3401 self.panic_flag = false;
3402 // Update the index *after* the predicate is called. If the index
3403 // is updated prior and the predicate panics, the element at this
3404 // index would be leaked.
3408 return Some(ptr::read(&v[i]));
3409 } else if self.del > 0 {
3411 let src: *const T = &v[i];
3412 let dst: *mut T = &mut v[i - del];
3413 ptr::copy_nonoverlapping(src, dst, 1);
3420 fn size_hint(&self) -> (usize, Option<usize>) {
3421 (0, Some(self.old_len - self.idx))
3425 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3426 impl<T, F> Drop for DrainFilter<'_, T, F>
3428 F: FnMut(&mut T) -> bool,
3430 fn drop(&mut self) {
3431 struct BackshiftOnDrop<'a, 'b, T, F>
3433 F: FnMut(&mut T) -> bool,
3435 drain: &'b mut DrainFilter<'a, T, F>,
3438 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
3440 F: FnMut(&mut T) -> bool,
3442 fn drop(&mut self) {
3444 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3445 // This is a pretty messed up state, and there isn't really an
3446 // obviously right thing to do. We don't want to keep trying
3447 // to execute `pred`, so we just backshift all the unprocessed
3448 // elements and tell the vec that they still exist. The backshift
3449 // is required to prevent a double-drop of the last successfully
3450 // drained item prior to a panic in the predicate.
3451 let ptr = self.drain.vec.as_mut_ptr();
3452 let src = ptr.add(self.drain.idx);
3453 let dst = src.sub(self.drain.del);
3454 let tail_len = self.drain.old_len - self.drain.idx;
3455 src.copy_to(dst, tail_len);
3457 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3462 let backshift = BackshiftOnDrop { drain: self };
3464 // Attempt to consume any remaining elements if the filter predicate
3465 // has not yet panicked. We'll backshift any remaining elements
3466 // whether we've already panicked or if the consumption here panics.
3467 if !backshift.drain.panic_flag {
3468 backshift.drain.for_each(drop);