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};
59 use core::hash::{Hash, Hasher};
60 use core::intrinsics::{arith_offset, assume};
62 FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen, TrustedRandomAccess,
64 use core::marker::PhantomData;
65 use core::mem::{self, ManuallyDrop, MaybeUninit};
66 use core::ops::Bound::{Excluded, Included, Unbounded};
67 use core::ops::{self, Index, IndexMut, RangeBounds};
68 use core::ptr::{self, NonNull};
69 use core::slice::{self, SliceIndex};
71 use crate::borrow::{Cow, ToOwned};
72 use crate::boxed::Box;
73 use crate::collections::TryReserveError;
74 use crate::raw_vec::RawVec;
76 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
81 /// let mut vec = Vec::new();
85 /// assert_eq!(vec.len(), 2);
86 /// assert_eq!(vec[0], 1);
88 /// assert_eq!(vec.pop(), Some(2));
89 /// assert_eq!(vec.len(), 1);
92 /// assert_eq!(vec[0], 7);
94 /// vec.extend([1, 2, 3].iter().copied());
97 /// println!("{}", x);
99 /// assert_eq!(vec, [7, 1, 2, 3]);
102 /// The [`vec!`] macro is provided to make initialization more convenient:
105 /// let mut vec = vec![1, 2, 3];
107 /// assert_eq!(vec, [1, 2, 3, 4]);
110 /// It can also initialize each element of a `Vec<T>` with a given value.
111 /// This may be more efficient than performing allocation and initialization
112 /// in separate steps, especially when initializing a vector of zeros:
115 /// let vec = vec![0; 5];
116 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
118 /// // The following is equivalent, but potentially slower:
119 /// let mut vec = Vec::with_capacity(5);
120 /// vec.resize(5, 0);
121 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
124 /// Use a `Vec<T>` as an efficient stack:
127 /// let mut stack = Vec::new();
133 /// while let Some(top) = stack.pop() {
134 /// // Prints 3, 2, 1
135 /// println!("{}", top);
141 /// The `Vec` type allows to access values by index, because it implements the
142 /// [`Index`] trait. An example will be more explicit:
145 /// let v = vec![0, 2, 4, 6];
146 /// println!("{}", v[1]); // it will display '2'
149 /// However be careful: if you try to access an index which isn't in the `Vec`,
150 /// your software will panic! You cannot do this:
153 /// let v = vec![0, 2, 4, 6];
154 /// println!("{}", v[6]); // it will panic!
157 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
162 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
163 /// To get a slice, use `&`. Example:
166 /// fn read_slice(slice: &[usize]) {
170 /// let v = vec![0, 1];
173 /// // ... and that's all!
174 /// // you can also do it like this:
175 /// let x : &[usize] = &v;
178 /// In Rust, it's more common to pass slices as arguments rather than vectors
179 /// when you just want to provide read access. The same goes for [`String`] and
182 /// # Capacity and reallocation
184 /// The capacity of a vector is the amount of space allocated for any future
185 /// elements that will be added onto the vector. This is not to be confused with
186 /// the *length* of a vector, which specifies the number of actual elements
187 /// within the vector. If a vector's length exceeds its capacity, its capacity
188 /// will automatically be increased, but its elements will have to be
191 /// For example, a vector with capacity 10 and length 0 would be an empty vector
192 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
193 /// vector will not change its capacity or cause reallocation to occur. However,
194 /// if the vector's length is increased to 11, it will have to reallocate, which
195 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
196 /// whenever possible to specify how big the vector is expected to get.
200 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
201 /// about its design. This ensures that it's as low-overhead as possible in
202 /// the general case, and can be correctly manipulated in primitive ways
203 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
204 /// If additional type parameters are added (e.g., to support custom allocators),
205 /// overriding their defaults may change the behavior.
207 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
208 /// triplet. No more, no less. The order of these fields is completely
209 /// unspecified, and you should use the appropriate methods to modify these.
210 /// The pointer will never be null, so this type is null-pointer-optimized.
212 /// However, the pointer may not actually point to allocated memory. In particular,
213 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
214 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
215 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
216 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
217 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
218 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
219 /// details are very subtle — if you intend to allocate memory using a `Vec`
220 /// and use it for something else (either to pass to unsafe code, or to build your
221 /// own memory-backed collection), be sure to deallocate this memory by using
222 /// `from_raw_parts` to recover the `Vec` and then dropping it.
224 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
225 /// (as defined by the allocator Rust is configured to use by default), and its
226 /// pointer points to [`len`] initialized, contiguous elements in order (what
227 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
228 /// `[`len`] logically uninitialized, contiguous elements.
230 /// `Vec` will never perform a "small optimization" where elements are actually
231 /// stored on the stack for two reasons:
233 /// * It would make it more difficult for unsafe code to correctly manipulate
234 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
235 /// only moved, and it would be more difficult to determine if a `Vec` had
236 /// actually allocated memory.
238 /// * It would penalize the general case, incurring an additional branch
241 /// `Vec` will never automatically shrink itself, even if completely empty. This
242 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
243 /// and then filling it back up to the same [`len`] should incur no calls to
244 /// the allocator. If you wish to free up unused memory, use
245 /// [`shrink_to_fit`].
247 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
248 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
249 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
250 /// accurate, and can be relied on. It can even be used to manually free the memory
251 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
252 /// when not necessary.
254 /// `Vec` does not guarantee any particular growth strategy when reallocating
255 /// when full, nor when [`reserve`] is called. The current strategy is basic
256 /// and it may prove desirable to use a non-constant growth factor. Whatever
257 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
259 /// `vec![x; n]`, `vec![a, b, c, d]`, and
260 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
261 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
262 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
263 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
265 /// `Vec` will not specifically overwrite any data that is removed from it,
266 /// but also won't specifically preserve it. Its uninitialized memory is
267 /// scratch space that it may use however it wants. It will generally just do
268 /// whatever is most efficient or otherwise easy to implement. Do not rely on
269 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
270 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
271 /// first, that may not actually happen because the optimizer does not consider
272 /// this a side-effect that must be preserved. There is one case which we will
273 /// not break, however: using `unsafe` code to write to the excess capacity,
274 /// and then increasing the length to match, is always valid.
276 /// `Vec` does not currently guarantee the order in which elements are dropped.
277 /// The order has changed in the past and may change again.
279 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
280 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
281 /// [`String`]: crate::string::String
282 /// [`&str`]: type@str
283 /// [`shrink_to_fit`]: Vec::shrink_to_fit
284 /// [`capacity`]: Vec::capacity
285 /// [`mem::size_of::<T>`]: core::mem::size_of
286 /// [`len`]: Vec::len
287 /// [`push`]: Vec::push
288 /// [`insert`]: Vec::insert
289 /// [`reserve`]: Vec::reserve
290 /// [owned slice]: Box
291 #[stable(feature = "rust1", since = "1.0.0")]
292 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
298 ////////////////////////////////////////////////////////////////////////////////
300 ////////////////////////////////////////////////////////////////////////////////
303 /// Constructs a new, empty `Vec<T>`.
305 /// The vector will not allocate until elements are pushed onto it.
310 /// # #![allow(unused_mut)]
311 /// let mut vec: Vec<i32> = Vec::new();
314 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
315 #[stable(feature = "rust1", since = "1.0.0")]
316 pub const fn new() -> Vec<T> {
317 Vec { buf: RawVec::NEW, len: 0 }
320 /// Constructs a new, empty `Vec<T>` with the specified capacity.
322 /// The vector will be able to hold exactly `capacity` elements without
323 /// reallocating. If `capacity` is 0, the vector will not allocate.
325 /// It is important to note that although the returned vector has the
326 /// *capacity* specified, the vector will have a zero *length*. For an
327 /// explanation of the difference between length and capacity, see
328 /// *[Capacity and reallocation]*.
330 /// [Capacity and reallocation]: #capacity-and-reallocation
335 /// let mut vec = Vec::with_capacity(10);
337 /// // The vector contains no items, even though it has capacity for more
338 /// assert_eq!(vec.len(), 0);
339 /// assert_eq!(vec.capacity(), 10);
341 /// // These are all done without reallocating...
345 /// assert_eq!(vec.len(), 10);
346 /// assert_eq!(vec.capacity(), 10);
348 /// // ...but this may make the vector reallocate
350 /// assert_eq!(vec.len(), 11);
351 /// assert!(vec.capacity() >= 11);
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn with_capacity(capacity: usize) -> Vec<T> {
356 Vec { buf: RawVec::with_capacity(capacity), len: 0 }
359 /// Decomposes a `Vec<T>` into its raw components.
361 /// Returns the raw pointer to the underlying data, the length of
362 /// the vector (in elements), and the allocated capacity of the
363 /// data (in elements). These are the same arguments in the same
364 /// order as the arguments to [`from_raw_parts`].
366 /// After calling this function, the caller is responsible for the
367 /// memory previously managed by the `Vec`. The only way to do
368 /// this is to convert the raw pointer, length, and capacity back
369 /// into a `Vec` with the [`from_raw_parts`] function, allowing
370 /// the destructor to perform the cleanup.
372 /// [`from_raw_parts`]: Vec::from_raw_parts
377 /// #![feature(vec_into_raw_parts)]
378 /// let v: Vec<i32> = vec![-1, 0, 1];
380 /// let (ptr, len, cap) = v.into_raw_parts();
382 /// let rebuilt = unsafe {
383 /// // We can now make changes to the components, such as
384 /// // transmuting the raw pointer to a compatible type.
385 /// let ptr = ptr as *mut u32;
387 /// Vec::from_raw_parts(ptr, len, cap)
389 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
391 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
392 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
393 let mut me = ManuallyDrop::new(self);
394 (me.as_mut_ptr(), me.len(), me.capacity())
397 /// Creates a `Vec<T>` directly from the raw components of another vector.
401 /// This is highly unsafe, due to the number of invariants that aren't
404 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
405 /// (at least, it's highly likely to be incorrect if it wasn't).
406 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
407 /// (`T` having a less strict alignment is not sufficient, the alignment really
408 /// needs to be equal to satsify the [`dealloc`] requirement that memory must be
409 /// allocated and deallocated with the same layout.)
410 /// * `length` needs to be less than or equal to `capacity`.
411 /// * `capacity` needs to be the capacity that the pointer was allocated with.
413 /// Violating these may cause problems like corrupting the allocator's
414 /// internal data structures. For example it is **not** safe
415 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
416 /// It's also not safe to build one from a `Vec<u16>` and its length, because
417 /// the allocator cares about the alignment, and these two types have different
418 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
419 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
421 /// The ownership of `ptr` is effectively transferred to the
422 /// `Vec<T>` which may then deallocate, reallocate or change the
423 /// contents of memory pointed to by the pointer at will. Ensure
424 /// that nothing else uses the pointer after calling this
427 /// [`String`]: crate::string::String
428 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
436 /// let v = vec![1, 2, 3];
438 // FIXME Update this when vec_into_raw_parts is stabilized
439 /// // Prevent running `v`'s destructor so we are in complete control
440 /// // of the allocation.
441 /// let mut v = mem::ManuallyDrop::new(v);
443 /// // Pull out the various important pieces of information about `v`
444 /// let p = v.as_mut_ptr();
445 /// let len = v.len();
446 /// let cap = v.capacity();
449 /// // Overwrite memory with 4, 5, 6
450 /// for i in 0..len as isize {
451 /// ptr::write(p.offset(i), 4 + i);
454 /// // Put everything back together into a Vec
455 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
456 /// assert_eq!(rebuilt, [4, 5, 6]);
459 #[stable(feature = "rust1", since = "1.0.0")]
460 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
461 unsafe { Vec { buf: RawVec::from_raw_parts(ptr, capacity), len: length } }
464 /// Returns the number of elements the vector can hold without
470 /// let vec: Vec<i32> = Vec::with_capacity(10);
471 /// assert_eq!(vec.capacity(), 10);
474 #[stable(feature = "rust1", since = "1.0.0")]
475 pub fn capacity(&self) -> usize {
479 /// Reserves capacity for at least `additional` more elements to be inserted
480 /// in the given `Vec<T>`. The collection may reserve more space to avoid
481 /// frequent reallocations. After calling `reserve`, capacity will be
482 /// greater than or equal to `self.len() + additional`. Does nothing if
483 /// capacity is already sufficient.
487 /// Panics if the new capacity exceeds `isize::MAX` bytes.
492 /// let mut vec = vec![1];
494 /// assert!(vec.capacity() >= 11);
496 #[stable(feature = "rust1", since = "1.0.0")]
497 pub fn reserve(&mut self, additional: usize) {
498 self.buf.reserve(self.len, additional);
501 /// Reserves the minimum capacity for exactly `additional` more elements to
502 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
503 /// capacity will be greater than or equal to `self.len() + additional`.
504 /// Does nothing if the capacity is already sufficient.
506 /// Note that the allocator may give the collection more space than it
507 /// requests. Therefore, capacity can not be relied upon to be precisely
508 /// minimal. Prefer `reserve` if future insertions are expected.
512 /// Panics if the new capacity overflows `usize`.
517 /// let mut vec = vec![1];
518 /// vec.reserve_exact(10);
519 /// assert!(vec.capacity() >= 11);
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn reserve_exact(&mut self, additional: usize) {
523 self.buf.reserve_exact(self.len, additional);
526 /// Tries to reserve capacity for at least `additional` more elements to be inserted
527 /// in the given `Vec<T>`. The collection may reserve more space to avoid
528 /// frequent reallocations. After calling `try_reserve`, capacity will be
529 /// greater than or equal to `self.len() + additional`. Does nothing if
530 /// capacity is already sufficient.
534 /// If the capacity overflows, or the allocator reports a failure, then an error
540 /// #![feature(try_reserve)]
541 /// use std::collections::TryReserveError;
543 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
544 /// let mut output = Vec::new();
546 /// // Pre-reserve the memory, exiting if we can't
547 /// output.try_reserve(data.len())?;
549 /// // Now we know this can't OOM in the middle of our complex work
550 /// output.extend(data.iter().map(|&val| {
551 /// val * 2 + 5 // very complicated
556 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
558 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
559 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
560 self.buf.try_reserve(self.len, additional)
563 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
564 /// be inserted in the given `Vec<T>`. After calling `try_reserve_exact`,
565 /// capacity will be greater than or equal to `self.len() + additional`.
566 /// Does nothing if the capacity is already sufficient.
568 /// Note that the allocator may give the collection more space than it
569 /// requests. Therefore, capacity can not be relied upon to be precisely
570 /// minimal. Prefer `reserve` if future insertions are expected.
574 /// If the capacity overflows, or the allocator reports a failure, then an error
580 /// #![feature(try_reserve)]
581 /// use std::collections::TryReserveError;
583 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
584 /// let mut output = Vec::new();
586 /// // Pre-reserve the memory, exiting if we can't
587 /// output.try_reserve_exact(data.len())?;
589 /// // Now we know this can't OOM in the middle of our complex work
590 /// output.extend(data.iter().map(|&val| {
591 /// val * 2 + 5 // very complicated
596 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
598 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
599 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
600 self.buf.try_reserve_exact(self.len, additional)
603 /// Shrinks the capacity of the vector as much as possible.
605 /// It will drop down as close as possible to the length but the allocator
606 /// may still inform the vector that there is space for a few more elements.
611 /// let mut vec = Vec::with_capacity(10);
612 /// vec.extend([1, 2, 3].iter().cloned());
613 /// assert_eq!(vec.capacity(), 10);
614 /// vec.shrink_to_fit();
615 /// assert!(vec.capacity() >= 3);
617 #[stable(feature = "rust1", since = "1.0.0")]
618 pub fn shrink_to_fit(&mut self) {
619 // The capacity is never less than the length, and there's nothing to do when
620 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
621 // by only calling it with a greater capacity.
622 if self.capacity() > self.len {
623 self.buf.shrink_to_fit(self.len);
627 /// Shrinks the capacity of the vector with a lower bound.
629 /// The capacity will remain at least as large as both the length
630 /// and the supplied value.
634 /// Panics if the current capacity is smaller than the supplied
635 /// minimum capacity.
640 /// #![feature(shrink_to)]
641 /// let mut vec = Vec::with_capacity(10);
642 /// vec.extend([1, 2, 3].iter().cloned());
643 /// assert_eq!(vec.capacity(), 10);
644 /// vec.shrink_to(4);
645 /// assert!(vec.capacity() >= 4);
646 /// vec.shrink_to(0);
647 /// assert!(vec.capacity() >= 3);
649 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
650 pub fn shrink_to(&mut self, min_capacity: usize) {
651 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
654 /// Converts the vector into [`Box<[T]>`][owned slice].
656 /// Note that this will drop any excess capacity.
658 /// [owned slice]: Box
663 /// let v = vec![1, 2, 3];
665 /// let slice = v.into_boxed_slice();
668 /// Any excess capacity is removed:
671 /// let mut vec = Vec::with_capacity(10);
672 /// vec.extend([1, 2, 3].iter().cloned());
674 /// assert_eq!(vec.capacity(), 10);
675 /// let slice = vec.into_boxed_slice();
676 /// assert_eq!(slice.into_vec().capacity(), 3);
678 #[stable(feature = "rust1", since = "1.0.0")]
679 pub fn into_boxed_slice(mut self) -> Box<[T]> {
681 self.shrink_to_fit();
682 let me = ManuallyDrop::new(self);
683 let buf = ptr::read(&me.buf);
685 buf.into_box(len).assume_init()
689 /// Shortens the vector, keeping the first `len` elements and dropping
692 /// If `len` is greater than the vector's current length, this has no
695 /// The [`drain`] method can emulate `truncate`, but causes the excess
696 /// elements to be returned instead of dropped.
698 /// Note that this method has no effect on the allocated capacity
703 /// Truncating a five element vector to two elements:
706 /// let mut vec = vec![1, 2, 3, 4, 5];
708 /// assert_eq!(vec, [1, 2]);
711 /// No truncation occurs when `len` is greater than the vector's current
715 /// let mut vec = vec![1, 2, 3];
717 /// assert_eq!(vec, [1, 2, 3]);
720 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
724 /// let mut vec = vec![1, 2, 3];
726 /// assert_eq!(vec, []);
729 /// [`clear`]: Vec::clear
730 /// [`drain`]: Vec::drain
731 #[stable(feature = "rust1", since = "1.0.0")]
732 pub fn truncate(&mut self, len: usize) {
733 // This is safe because:
735 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
736 // case avoids creating an invalid slice, and
737 // * the `len` of the vector is shrunk before calling `drop_in_place`,
738 // such that no value will be dropped twice in case `drop_in_place`
739 // were to panic once (if it panics twice, the program aborts).
744 let remaining_len = self.len - len;
745 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
747 ptr::drop_in_place(s);
751 /// Extracts a slice containing the entire vector.
753 /// Equivalent to `&s[..]`.
758 /// use std::io::{self, Write};
759 /// let buffer = vec![1, 2, 3, 5, 8];
760 /// io::sink().write(buffer.as_slice()).unwrap();
763 #[stable(feature = "vec_as_slice", since = "1.7.0")]
764 pub fn as_slice(&self) -> &[T] {
768 /// Extracts a mutable slice of the entire vector.
770 /// Equivalent to `&mut s[..]`.
775 /// use std::io::{self, Read};
776 /// let mut buffer = vec![0; 3];
777 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
780 #[stable(feature = "vec_as_slice", since = "1.7.0")]
781 pub fn as_mut_slice(&mut self) -> &mut [T] {
785 /// Returns a raw pointer to the vector's buffer.
787 /// The caller must ensure that the vector outlives the pointer this
788 /// function returns, or else it will end up pointing to garbage.
789 /// Modifying the vector may cause its buffer to be reallocated,
790 /// which would also make any pointers to it invalid.
792 /// The caller must also ensure that the memory the pointer (non-transitively) points to
793 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
794 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
799 /// let x = vec![1, 2, 4];
800 /// let x_ptr = x.as_ptr();
803 /// for i in 0..x.len() {
804 /// assert_eq!(*x_ptr.add(i), 1 << i);
809 /// [`as_mut_ptr`]: Vec::as_mut_ptr
810 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
812 pub fn as_ptr(&self) -> *const T {
813 // We shadow the slice method of the same name to avoid going through
814 // `deref`, which creates an intermediate reference.
815 let ptr = self.buf.ptr();
817 assume(!ptr.is_null());
822 /// Returns an unsafe mutable pointer to the vector's buffer.
824 /// The caller must ensure that the vector outlives the pointer this
825 /// function returns, or else it will end up pointing to garbage.
826 /// Modifying the vector may cause its buffer to be reallocated,
827 /// which would also make any pointers to it invalid.
832 /// // Allocate vector big enough for 4 elements.
834 /// let mut x: Vec<i32> = Vec::with_capacity(size);
835 /// let x_ptr = x.as_mut_ptr();
837 /// // Initialize elements via raw pointer writes, then set length.
839 /// for i in 0..size {
840 /// *x_ptr.add(i) = i as i32;
844 /// assert_eq!(&*x, &[0,1,2,3]);
846 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
848 pub fn as_mut_ptr(&mut self) -> *mut T {
849 // We shadow the slice method of the same name to avoid going through
850 // `deref_mut`, which creates an intermediate reference.
851 let ptr = self.buf.ptr();
853 assume(!ptr.is_null());
858 /// Forces the length of the vector to `new_len`.
860 /// This is a low-level operation that maintains none of the normal
861 /// invariants of the type. Normally changing the length of a vector
862 /// is done using one of the safe operations instead, such as
863 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
865 /// [`truncate`]: Vec::truncate
866 /// [`resize`]: Vec::resize
867 /// [`extend`]: Extend::extend
868 /// [`clear`]: Vec::clear
872 /// - `new_len` must be less than or equal to [`capacity()`].
873 /// - The elements at `old_len..new_len` must be initialized.
875 /// [`capacity()`]: Vec::capacity
879 /// This method can be useful for situations in which the vector
880 /// is serving as a buffer for other code, particularly over FFI:
883 /// # #![allow(dead_code)]
884 /// # // This is just a minimal skeleton for the doc example;
885 /// # // don't use this as a starting point for a real library.
886 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
887 /// # const Z_OK: i32 = 0;
889 /// # fn deflateGetDictionary(
890 /// # strm: *mut std::ffi::c_void,
891 /// # dictionary: *mut u8,
892 /// # dictLength: *mut usize,
895 /// # impl StreamWrapper {
896 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
897 /// // Per the FFI method's docs, "32768 bytes is always enough".
898 /// let mut dict = Vec::with_capacity(32_768);
899 /// let mut dict_length = 0;
900 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
901 /// // 1. `dict_length` elements were initialized.
902 /// // 2. `dict_length` <= the capacity (32_768)
903 /// // which makes `set_len` safe to call.
905 /// // Make the FFI call...
906 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
908 /// // ...and update the length to what was initialized.
909 /// dict.set_len(dict_length);
919 /// While the following example is sound, there is a memory leak since
920 /// the inner vectors were not freed prior to the `set_len` call:
923 /// let mut vec = vec![vec![1, 0, 0],
927 /// // 1. `old_len..0` is empty so no elements need to be initialized.
928 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
934 /// Normally, here, one would use [`clear`] instead to correctly drop
935 /// the contents and thus not leak memory.
937 #[stable(feature = "rust1", since = "1.0.0")]
938 pub unsafe fn set_len(&mut self, new_len: usize) {
939 debug_assert!(new_len <= self.capacity());
944 /// Removes an element from the vector and returns it.
946 /// The removed element is replaced by the last element of the vector.
948 /// This does not preserve ordering, but is O(1).
952 /// Panics if `index` is out of bounds.
957 /// let mut v = vec!["foo", "bar", "baz", "qux"];
959 /// assert_eq!(v.swap_remove(1), "bar");
960 /// assert_eq!(v, ["foo", "qux", "baz"]);
962 /// assert_eq!(v.swap_remove(0), "foo");
963 /// assert_eq!(v, ["baz", "qux"]);
966 #[stable(feature = "rust1", since = "1.0.0")]
967 pub fn swap_remove(&mut self, index: usize) -> T {
970 fn assert_failed(index: usize, len: usize) -> ! {
971 panic!("swap_remove index (is {}) should be < len (is {})", index, len);
974 let len = self.len();
976 assert_failed(index, len);
979 // We replace self[index] with the last element. Note that if the
980 // bounds check above succeeds there must be a last element (which
981 // can be self[index] itself).
982 let last = ptr::read(self.as_ptr().add(len - 1));
983 let hole = self.as_mut_ptr().add(index);
984 self.set_len(len - 1);
985 ptr::replace(hole, last)
989 /// Inserts an element at position `index` within the vector, shifting all
990 /// elements after it to the right.
994 /// Panics if `index > len`.
999 /// let mut vec = vec![1, 2, 3];
1000 /// vec.insert(1, 4);
1001 /// assert_eq!(vec, [1, 4, 2, 3]);
1002 /// vec.insert(4, 5);
1003 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1005 #[stable(feature = "rust1", since = "1.0.0")]
1006 pub fn insert(&mut self, index: usize, element: T) {
1009 fn assert_failed(index: usize, len: usize) -> ! {
1010 panic!("insertion index (is {}) should be <= len (is {})", index, len);
1013 let len = self.len();
1015 assert_failed(index, len);
1018 // space for the new element
1019 if len == self.buf.capacity() {
1025 // The spot to put the new value
1027 let p = self.as_mut_ptr().add(index);
1028 // Shift everything over to make space. (Duplicating the
1029 // `index`th element into two consecutive places.)
1030 ptr::copy(p, p.offset(1), len - index);
1031 // Write it in, overwriting the first copy of the `index`th
1033 ptr::write(p, element);
1035 self.set_len(len + 1);
1039 /// Removes and returns the element at position `index` within the vector,
1040 /// shifting all elements after it to the left.
1044 /// Panics if `index` is out of bounds.
1049 /// let mut v = vec![1, 2, 3];
1050 /// assert_eq!(v.remove(1), 2);
1051 /// assert_eq!(v, [1, 3]);
1053 #[stable(feature = "rust1", since = "1.0.0")]
1054 pub fn remove(&mut self, index: usize) -> T {
1057 fn assert_failed(index: usize, len: usize) -> ! {
1058 panic!("removal index (is {}) should be < len (is {})", index, len);
1061 let len = self.len();
1063 assert_failed(index, len);
1069 // the place we are taking from.
1070 let ptr = self.as_mut_ptr().add(index);
1071 // copy it out, unsafely having a copy of the value on
1072 // the stack and in the vector at the same time.
1073 ret = ptr::read(ptr);
1075 // Shift everything down to fill in that spot.
1076 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1078 self.set_len(len - 1);
1083 /// Retains only the elements specified by the predicate.
1085 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1086 /// This method operates in place, visiting each element exactly once in the
1087 /// original order, and preserves the order of the retained elements.
1092 /// let mut vec = vec![1, 2, 3, 4];
1093 /// vec.retain(|&x| x % 2 == 0);
1094 /// assert_eq!(vec, [2, 4]);
1097 /// The exact order may be useful for tracking external state, like an index.
1100 /// let mut vec = vec![1, 2, 3, 4, 5];
1101 /// let keep = [false, true, true, false, true];
1103 /// vec.retain(|_| (keep[i], i += 1).0);
1104 /// assert_eq!(vec, [2, 3, 5]);
1106 #[stable(feature = "rust1", since = "1.0.0")]
1107 pub fn retain<F>(&mut self, mut f: F)
1109 F: FnMut(&T) -> bool,
1111 let len = self.len();
1114 let v = &mut **self;
1125 self.truncate(len - del);
1129 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1132 /// If the vector is sorted, this removes all duplicates.
1137 /// let mut vec = vec![10, 20, 21, 30, 20];
1139 /// vec.dedup_by_key(|i| *i / 10);
1141 /// assert_eq!(vec, [10, 20, 30, 20]);
1143 #[stable(feature = "dedup_by", since = "1.16.0")]
1145 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1147 F: FnMut(&mut T) -> K,
1150 self.dedup_by(|a, b| key(a) == key(b))
1153 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1156 /// The `same_bucket` function is passed references to two elements from the vector and
1157 /// must determine if the elements compare equal. The elements are passed in opposite order
1158 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1160 /// If the vector is sorted, this removes all duplicates.
1165 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1167 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1169 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1171 #[stable(feature = "dedup_by", since = "1.16.0")]
1172 pub fn dedup_by<F>(&mut self, same_bucket: F)
1174 F: FnMut(&mut T, &mut T) -> bool,
1177 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1183 /// Appends an element to the back of a collection.
1187 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1192 /// let mut vec = vec![1, 2];
1194 /// assert_eq!(vec, [1, 2, 3]);
1197 #[stable(feature = "rust1", since = "1.0.0")]
1198 pub fn push(&mut self, value: T) {
1199 // This will panic or abort if we would allocate > isize::MAX bytes
1200 // or if the length increment would overflow for zero-sized types.
1201 if self.len == self.buf.capacity() {
1205 let end = self.as_mut_ptr().add(self.len);
1206 ptr::write(end, value);
1211 /// Removes the last element from a vector and returns it, or [`None`] if it
1217 /// let mut vec = vec![1, 2, 3];
1218 /// assert_eq!(vec.pop(), Some(3));
1219 /// assert_eq!(vec, [1, 2]);
1222 #[stable(feature = "rust1", since = "1.0.0")]
1223 pub fn pop(&mut self) -> Option<T> {
1229 Some(ptr::read(self.as_ptr().add(self.len())))
1234 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1238 /// Panics if the number of elements in the vector overflows a `usize`.
1243 /// let mut vec = vec![1, 2, 3];
1244 /// let mut vec2 = vec![4, 5, 6];
1245 /// vec.append(&mut vec2);
1246 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1247 /// assert_eq!(vec2, []);
1250 #[stable(feature = "append", since = "1.4.0")]
1251 pub fn append(&mut self, other: &mut Self) {
1253 self.append_elements(other.as_slice() as _);
1258 /// Appends elements to `Self` from other buffer.
1260 unsafe fn append_elements(&mut self, other: *const [T]) {
1261 let count = unsafe { (*other).len() };
1262 self.reserve(count);
1263 let len = self.len();
1264 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1268 /// Creates a draining iterator that removes the specified range in the vector
1269 /// and yields the removed items.
1271 /// When the iterator **is** dropped, all elements in the range are removed
1272 /// from the vector, even if the iterator was not fully consumed. If the
1273 /// iterator **is not** dropped (with [`mem::forget`] for example), it is
1274 /// unspecified how many elements are removed.
1278 /// Panics if the starting point is greater than the end point or if
1279 /// the end point is greater than the length of the vector.
1284 /// let mut v = vec![1, 2, 3];
1285 /// let u: Vec<_> = v.drain(1..).collect();
1286 /// assert_eq!(v, &[1]);
1287 /// assert_eq!(u, &[2, 3]);
1289 /// // A full range clears the vector
1291 /// assert_eq!(v, &[]);
1293 #[stable(feature = "drain", since = "1.6.0")]
1294 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1296 R: RangeBounds<usize>,
1300 // When the Drain is first created, it shortens the length of
1301 // the source vector to make sure no uninitialized or moved-from elements
1302 // are accessible at all if the Drain's destructor never gets to run.
1304 // Drain will ptr::read out the values to remove.
1305 // When finished, remaining tail of the vec is copied back to cover
1306 // the hole, and the vector length is restored to the new length.
1308 let len = self.len();
1309 let start = match range.start_bound() {
1311 Excluded(&n) => n + 1,
1314 let end = match range.end_bound() {
1315 Included(&n) => n + 1,
1322 fn start_assert_failed(start: usize, end: usize) -> ! {
1323 panic!("start drain index (is {}) should be <= end drain index (is {})", start, end);
1328 fn end_assert_failed(end: usize, len: usize) -> ! {
1329 panic!("end drain index (is {}) should be <= len (is {})", end, len);
1333 start_assert_failed(start, end);
1336 end_assert_failed(end, len);
1340 // set self.vec length's to start, to be safe in case Drain is leaked
1341 self.set_len(start);
1342 // Use the borrow in the IterMut to indicate borrowing behavior of the
1343 // whole Drain iterator (like &mut T).
1344 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1347 tail_len: len - end,
1348 iter: range_slice.iter(),
1349 vec: NonNull::from(self),
1354 /// Clears the vector, removing all values.
1356 /// Note that this method has no effect on the allocated capacity
1362 /// let mut v = vec![1, 2, 3];
1366 /// assert!(v.is_empty());
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 pub fn clear(&mut self) {
1374 /// Returns the number of elements in the vector, also referred to
1375 /// as its 'length'.
1380 /// let a = vec![1, 2, 3];
1381 /// assert_eq!(a.len(), 3);
1384 #[stable(feature = "rust1", since = "1.0.0")]
1385 pub fn len(&self) -> usize {
1389 /// Returns `true` if the vector contains no elements.
1394 /// let mut v = Vec::new();
1395 /// assert!(v.is_empty());
1398 /// assert!(!v.is_empty());
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 pub fn is_empty(&self) -> bool {
1405 /// Splits the collection into two at the given index.
1407 /// Returns a newly allocated vector containing the elements in the range
1408 /// `[at, len)`. After the call, the original vector will be left containing
1409 /// the elements `[0, at)` with its previous capacity unchanged.
1413 /// Panics if `at > len`.
1418 /// let mut vec = vec![1,2,3];
1419 /// let vec2 = vec.split_off(1);
1420 /// assert_eq!(vec, [1]);
1421 /// assert_eq!(vec2, [2, 3]);
1424 #[must_use = "use `.truncate()` if you don't need the other half"]
1425 #[stable(feature = "split_off", since = "1.4.0")]
1426 pub fn split_off(&mut self, at: usize) -> Self {
1429 fn assert_failed(at: usize, len: usize) -> ! {
1430 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1433 if at > self.len() {
1434 assert_failed(at, self.len());
1437 let other_len = self.len - at;
1438 let mut other = Vec::with_capacity(other_len);
1440 // Unsafely `set_len` and copy items to `other`.
1443 other.set_len(other_len);
1445 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1450 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1452 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1453 /// difference, with each additional slot filled with the result of
1454 /// calling the closure `f`. The return values from `f` will end up
1455 /// in the `Vec` in the order they have been generated.
1457 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1459 /// This method uses a closure to create new values on every push. If
1460 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
1461 /// want to use the [`Default`] trait to generate values, you can
1462 /// pass [`Default::default`] as the second argument.
1467 /// let mut vec = vec![1, 2, 3];
1468 /// vec.resize_with(5, Default::default);
1469 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1471 /// let mut vec = vec![];
1473 /// vec.resize_with(4, || { p *= 2; p });
1474 /// assert_eq!(vec, [2, 4, 8, 16]);
1476 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1477 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1481 let len = self.len();
1483 self.extend_with(new_len - len, ExtendFunc(f));
1485 self.truncate(new_len);
1489 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1490 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1491 /// `'a`. If the type has only static references, or none at all, then this
1492 /// may be chosen to be `'static`.
1494 /// This function is similar to the `leak` function on `Box`.
1496 /// This function is mainly useful for data that lives for the remainder of
1497 /// the program's life. Dropping the returned reference will cause a memory
1505 /// let x = vec![1, 2, 3];
1506 /// let static_ref: &'static mut [usize] = x.leak();
1507 /// static_ref[0] += 1;
1508 /// assert_eq!(static_ref, &[2, 2, 3]);
1510 #[stable(feature = "vec_leak", since = "1.47.0")]
1512 pub fn leak<'a>(self) -> &'a mut [T]
1514 T: 'a, // Technically not needed, but kept to be explicit.
1516 Box::leak(self.into_boxed_slice())
1519 /// Returns the remaining spare capacity of the vector as a slice of
1520 /// `MaybeUninit<T>`.
1522 /// The returned slice can be used to fill the vector with data (e.g. by
1523 /// reading from a file) before marking the data as initialized using the
1524 /// [`set_len`] method.
1526 /// [`set_len`]: Vec::set_len
1531 /// #![feature(vec_spare_capacity, maybe_uninit_extra)]
1533 /// // Allocate vector big enough for 10 elements.
1534 /// let mut v = Vec::with_capacity(10);
1536 /// // Fill in the first 3 elements.
1537 /// let uninit = v.spare_capacity_mut();
1538 /// uninit[0].write(0);
1539 /// uninit[1].write(1);
1540 /// uninit[2].write(2);
1542 /// // Mark the first 3 elements of the vector as being initialized.
1547 /// assert_eq!(&v, &[0, 1, 2]);
1549 #[unstable(feature = "vec_spare_capacity", issue = "75017")]
1551 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1553 slice::from_raw_parts_mut(
1554 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
1555 self.buf.capacity() - self.len,
1561 impl<T: Clone> Vec<T> {
1562 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1564 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1565 /// difference, with each additional slot filled with `value`.
1566 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1568 /// This method requires `T` to implement [`Clone`],
1569 /// in order to be able to clone the passed value.
1570 /// If you need more flexibility (or want to rely on [`Default`] instead of
1571 /// [`Clone`]), use [`Vec::resize_with`].
1576 /// let mut vec = vec!["hello"];
1577 /// vec.resize(3, "world");
1578 /// assert_eq!(vec, ["hello", "world", "world"]);
1580 /// let mut vec = vec![1, 2, 3, 4];
1581 /// vec.resize(2, 0);
1582 /// assert_eq!(vec, [1, 2]);
1584 #[stable(feature = "vec_resize", since = "1.5.0")]
1585 pub fn resize(&mut self, new_len: usize, value: T) {
1586 let len = self.len();
1589 self.extend_with(new_len - len, ExtendElement(value))
1591 self.truncate(new_len);
1595 /// Clones and appends all elements in a slice to the `Vec`.
1597 /// Iterates over the slice `other`, clones each element, and then appends
1598 /// it to this `Vec`. The `other` vector is traversed in-order.
1600 /// Note that this function is same as [`extend`] except that it is
1601 /// specialized to work with slices instead. If and when Rust gets
1602 /// specialization this function will likely be deprecated (but still
1608 /// let mut vec = vec![1];
1609 /// vec.extend_from_slice(&[2, 3, 4]);
1610 /// assert_eq!(vec, [1, 2, 3, 4]);
1613 /// [`extend`]: Vec::extend
1614 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1615 pub fn extend_from_slice(&mut self, other: &[T]) {
1616 self.spec_extend(other.iter())
1620 impl<T: Default> Vec<T> {
1621 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1623 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1624 /// difference, with each additional slot filled with [`Default::default()`].
1625 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1627 /// This method uses [`Default`] to create new values on every push. If
1628 /// you'd rather [`Clone`] a given value, use [`resize`].
1633 /// # #![allow(deprecated)]
1634 /// #![feature(vec_resize_default)]
1636 /// let mut vec = vec![1, 2, 3];
1637 /// vec.resize_default(5);
1638 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1640 /// let mut vec = vec![1, 2, 3, 4];
1641 /// vec.resize_default(2);
1642 /// assert_eq!(vec, [1, 2]);
1645 /// [`resize`]: Vec::resize
1646 #[unstable(feature = "vec_resize_default", issue = "41758")]
1648 reason = "This is moving towards being removed in favor \
1649 of `.resize_with(Default::default)`. If you disagree, please comment \
1650 in the tracking issue.",
1653 pub fn resize_default(&mut self, new_len: usize) {
1654 let len = self.len();
1657 self.extend_with(new_len - len, ExtendDefault);
1659 self.truncate(new_len);
1664 // This code generalizes `extend_with_{element,default}`.
1665 trait ExtendWith<T> {
1666 fn next(&mut self) -> T;
1670 struct ExtendElement<T>(T);
1671 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1672 fn next(&mut self) -> T {
1675 fn last(self) -> T {
1680 struct ExtendDefault;
1681 impl<T: Default> ExtendWith<T> for ExtendDefault {
1682 fn next(&mut self) -> T {
1685 fn last(self) -> T {
1690 struct ExtendFunc<F>(F);
1691 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1692 fn next(&mut self) -> T {
1695 fn last(mut self) -> T {
1701 /// Extend the vector by `n` values, using the given generator.
1702 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1706 let mut ptr = self.as_mut_ptr().add(self.len());
1707 // Use SetLenOnDrop to work around bug where compiler
1708 // may not realize the store through `ptr` through self.set_len()
1710 let mut local_len = SetLenOnDrop::new(&mut self.len);
1712 // Write all elements except the last one
1714 ptr::write(ptr, value.next());
1715 ptr = ptr.offset(1);
1716 // Increment the length in every step in case next() panics
1717 local_len.increment_len(1);
1721 // We can write the last element directly without cloning needlessly
1722 ptr::write(ptr, value.last());
1723 local_len.increment_len(1);
1726 // len set by scope guard
1731 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1733 // The idea is: The length field in SetLenOnDrop is a local variable
1734 // that the optimizer will see does not alias with any stores through the Vec's data
1735 // pointer. This is a workaround for alias analysis issue #32155
1736 struct SetLenOnDrop<'a> {
1741 impl<'a> SetLenOnDrop<'a> {
1743 fn new(len: &'a mut usize) -> Self {
1744 SetLenOnDrop { local_len: *len, len }
1748 fn increment_len(&mut self, increment: usize) {
1749 self.local_len += increment;
1753 impl Drop for SetLenOnDrop<'_> {
1755 fn drop(&mut self) {
1756 *self.len = self.local_len;
1760 impl<T: PartialEq> Vec<T> {
1761 /// Removes consecutive repeated elements in the vector according to the
1762 /// [`PartialEq`] trait implementation.
1764 /// If the vector is sorted, this removes all duplicates.
1769 /// let mut vec = vec![1, 2, 2, 3, 2];
1773 /// assert_eq!(vec, [1, 2, 3, 2]);
1775 #[stable(feature = "rust1", since = "1.0.0")]
1777 pub fn dedup(&mut self) {
1778 self.dedup_by(|a, b| a == b)
1783 /// Removes the first instance of `item` from the vector if the item exists.
1785 /// This method will be removed soon.
1786 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1788 reason = "Removing the first item equal to a needle is already easily possible \
1789 with iterators and the current Vec methods. Furthermore, having a method for \
1790 one particular case of removal (linear search, only the first item, no swap remove) \
1791 but not for others is inconsistent. This method will be removed soon.",
1794 pub fn remove_item<V>(&mut self, item: &V) -> Option<T>
1798 let pos = self.iter().position(|x| *x == *item)?;
1799 Some(self.remove(pos))
1803 ////////////////////////////////////////////////////////////////////////////////
1804 // Internal methods and functions
1805 ////////////////////////////////////////////////////////////////////////////////
1808 #[stable(feature = "rust1", since = "1.0.0")]
1809 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1810 <T as SpecFromElem>::from_elem(elem, n)
1813 // Specialization trait used for Vec::from_elem
1814 trait SpecFromElem: Sized {
1815 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1818 impl<T: Clone> SpecFromElem for T {
1819 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1820 let mut v = Vec::with_capacity(n);
1821 v.extend_with(n, ExtendElement(elem));
1826 impl SpecFromElem for i8 {
1828 fn from_elem(elem: i8, n: usize) -> Vec<i8> {
1830 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1833 let mut v = Vec::with_capacity(n);
1834 ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
1841 impl SpecFromElem for u8 {
1843 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1845 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1848 let mut v = Vec::with_capacity(n);
1849 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1856 impl<T: Clone + IsZero> SpecFromElem for T {
1858 fn from_elem(elem: T, n: usize) -> Vec<T> {
1860 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1862 let mut v = Vec::with_capacity(n);
1863 v.extend_with(n, ExtendElement(elem));
1868 #[rustc_specialization_trait]
1869 unsafe trait IsZero {
1870 /// Whether this value is zero
1871 fn is_zero(&self) -> bool;
1874 macro_rules! impl_is_zero {
1875 ($t:ty, $is_zero:expr) => {
1876 unsafe impl IsZero for $t {
1878 fn is_zero(&self) -> bool {
1885 impl_is_zero!(i16, |x| x == 0);
1886 impl_is_zero!(i32, |x| x == 0);
1887 impl_is_zero!(i64, |x| x == 0);
1888 impl_is_zero!(i128, |x| x == 0);
1889 impl_is_zero!(isize, |x| x == 0);
1891 impl_is_zero!(u16, |x| x == 0);
1892 impl_is_zero!(u32, |x| x == 0);
1893 impl_is_zero!(u64, |x| x == 0);
1894 impl_is_zero!(u128, |x| x == 0);
1895 impl_is_zero!(usize, |x| x == 0);
1897 impl_is_zero!(bool, |x| x == false);
1898 impl_is_zero!(char, |x| x == '\0');
1900 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1901 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1903 unsafe impl<T> IsZero for *const T {
1905 fn is_zero(&self) -> bool {
1910 unsafe impl<T> IsZero for *mut T {
1912 fn is_zero(&self) -> bool {
1917 // `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
1918 // For fat pointers, the bytes that would be the pointer metadata in the `Some`
1919 // variant are padding in the `None` variant, so ignoring them and
1920 // zero-initializing instead is ok.
1921 // `Option<&mut T>` never implements `Clone`, so there's no need for an impl of
1924 unsafe impl<T: ?Sized> IsZero for Option<&T> {
1926 fn is_zero(&self) -> bool {
1931 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
1933 fn is_zero(&self) -> bool {
1938 ////////////////////////////////////////////////////////////////////////////////
1939 // Common trait implementations for Vec
1940 ////////////////////////////////////////////////////////////////////////////////
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 impl<T> ops::Deref for Vec<T> {
1946 fn deref(&self) -> &[T] {
1947 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 impl<T> ops::DerefMut for Vec<T> {
1953 fn deref_mut(&mut self) -> &mut [T] {
1954 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 impl<T: Clone> Clone for Vec<T> {
1961 fn clone(&self) -> Vec<T> {
1962 <[T]>::to_vec(&**self)
1965 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1966 // required for this method definition, is not available. Instead use the
1967 // `slice::to_vec` function which is only available with cfg(test)
1968 // NB see the slice::hack module in slice.rs for more information
1970 fn clone(&self) -> Vec<T> {
1971 crate::slice::to_vec(&**self)
1974 fn clone_from(&mut self, other: &Vec<T>) {
1975 other.as_slice().clone_into(self);
1979 #[stable(feature = "rust1", since = "1.0.0")]
1980 impl<T: Hash> Hash for Vec<T> {
1982 fn hash<H: Hasher>(&self, state: &mut H) {
1983 Hash::hash(&**self, state)
1987 #[stable(feature = "rust1", since = "1.0.0")]
1988 #[rustc_on_unimplemented(
1989 message = "vector indices are of type `usize` or ranges of `usize`",
1990 label = "vector indices are of type `usize` or ranges of `usize`"
1992 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
1993 type Output = I::Output;
1996 fn index(&self, index: I) -> &Self::Output {
1997 Index::index(&**self, index)
2001 #[stable(feature = "rust1", since = "1.0.0")]
2002 #[rustc_on_unimplemented(
2003 message = "vector indices are of type `usize` or ranges of `usize`",
2004 label = "vector indices are of type `usize` or ranges of `usize`"
2006 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
2008 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2009 IndexMut::index_mut(&mut **self, index)
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl<T> FromIterator<T> for Vec<T> {
2016 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2017 <Self as SpecFrom<T, I::IntoIter>>::from_iter(iter.into_iter())
2021 #[stable(feature = "rust1", since = "1.0.0")]
2022 impl<T> IntoIterator for Vec<T> {
2024 type IntoIter = IntoIter<T>;
2026 /// Creates a consuming iterator, that is, one that moves each value out of
2027 /// the vector (from start to end). The vector cannot be used after calling
2033 /// let v = vec!["a".to_string(), "b".to_string()];
2034 /// for s in v.into_iter() {
2035 /// // s has type String, not &String
2036 /// println!("{}", s);
2040 fn into_iter(self) -> IntoIter<T> {
2042 let mut me = ManuallyDrop::new(self);
2043 let begin = me.as_mut_ptr();
2044 let end = if mem::size_of::<T>() == 0 {
2045 arith_offset(begin as *const i8, me.len() as isize) as *const T
2047 begin.add(me.len()) as *const T
2049 let cap = me.buf.capacity();
2051 buf: NonNull::new_unchecked(begin),
2052 phantom: PhantomData,
2061 #[stable(feature = "rust1", since = "1.0.0")]
2062 impl<'a, T> IntoIterator for &'a Vec<T> {
2064 type IntoIter = slice::Iter<'a, T>;
2066 fn into_iter(self) -> slice::Iter<'a, T> {
2071 #[stable(feature = "rust1", since = "1.0.0")]
2072 impl<'a, T> IntoIterator for &'a mut Vec<T> {
2073 type Item = &'a mut T;
2074 type IntoIter = slice::IterMut<'a, T>;
2076 fn into_iter(self) -> slice::IterMut<'a, T> {
2081 #[stable(feature = "rust1", since = "1.0.0")]
2082 impl<T> Extend<T> for Vec<T> {
2084 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2085 if self.capacity() > 0 {
2086 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2088 // if self has no allocation then use the more powerful from_iter specializations
2089 // and overwrite self
2090 *self = SpecFrom::from_iter(iter.into_iter());
2095 fn extend_one(&mut self, item: T) {
2100 fn extend_reserve(&mut self, additional: usize) {
2101 self.reserve(additional);
2105 // Specialization trait used for Vec::from_iter
2106 trait SpecFrom<T, I> {
2107 fn from_iter(iter: I) -> Self;
2110 // Another specialization trait for Vec::from_iter
2111 // necessary to manually prioritize overlapping specializations
2112 trait SpecFromNested<T, I> {
2113 fn from_iter(iter: I) -> Self;
2116 impl<T, I> SpecFromNested<T, I> for Vec<T>
2118 I: Iterator<Item = T>,
2120 default fn from_iter(mut iterator: I) -> Self {
2121 // Unroll the first iteration, as the vector is going to be
2122 // expanded on this iteration in every case when the iterable is not
2123 // empty, but the loop in extend_desugared() is not going to see the
2124 // vector being full in the few subsequent loop iterations.
2125 // So we get better branch prediction.
2126 let mut vector = match iterator.next() {
2127 None => return Vec::new(),
2129 let (lower, _) = iterator.size_hint();
2130 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2132 ptr::write(vector.as_mut_ptr(), element);
2138 // must delegate to spec_extend() since extend() itself delegates
2139 // to spec_from for empty Vecs
2140 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2145 impl<T, I> SpecFromNested<T, I> for Vec<T>
2147 I: TrustedLen<Item = T>,
2149 fn from_iter(iterator: I) -> Self {
2150 let mut vector = Vec::new();
2151 // must delegate to spec_extend() since extend() itself delegates
2152 // to spec_from for empty Vecs
2153 vector.spec_extend(iterator);
2158 impl<T, I> SpecFrom<T, I> for Vec<T>
2160 I: Iterator<Item = T>,
2162 default fn from_iter(iterator: I) -> Self {
2163 SpecFromNested::from_iter(iterator)
2167 // A helper struct for in-place iteration that drops the destination slice of iteration.
2168 // The source slice is dropped by IntoIter
2169 struct InPlaceDrop<T> {
2174 impl<T> InPlaceDrop<T> {
2175 unsafe fn len(&self) -> usize {
2176 self.dst.offset_from(self.inner) as usize
2180 impl<T> Drop for InPlaceDrop<T> {
2182 fn drop(&mut self) {
2184 ptr::drop_in_place(slice::from_raw_parts_mut(self.inner, self.len()) as *mut _);
2189 impl<T> SpecFrom<T, IntoIter<T>> for Vec<T> {
2190 fn from_iter(iterator: IntoIter<T>) -> Self {
2191 // A common case is passing a vector into a function which immediately
2192 // re-collects into a vector. We can short circuit this if the IntoIter
2193 // has not been advanced at all.
2194 // We can also reuse the memory and move the data to the front if
2195 // allocating a new vector and moving to it would result in the same capacity
2196 let non_zero_offset = iterator.buf.as_ptr() as *const _ != iterator.ptr;
2197 if !non_zero_offset || iterator.len() >= iterator.cap / 2 {
2199 let it = ManuallyDrop::new(iterator);
2200 if non_zero_offset {
2201 ptr::copy(it.ptr, it.buf.as_ptr(), it.len());
2203 return Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap);
2207 let mut vec = Vec::new();
2208 // must delegate to spec_extend() since extend() itself delegates
2209 // to spec_from for empty Vecs
2210 vec.spec_extend(iterator);
2215 // Further specialization potential once
2216 // https://github.com/rust-lang/rust/issues/62645 has been solved:
2217 // T can be split into IN and OUT which only need to have the same size and alignment
2218 impl<T, I> SpecFrom<T, I> for Vec<T>
2220 I: Iterator<Item = T> + InPlaceIterable + SourceIter<Source: AsIntoIter<T>>,
2222 default fn from_iter(mut iterator: I) -> Self {
2223 // This specialization only makes sense if we're juggling real allocations.
2224 // Additionally some of the pointer arithmetic would panic on ZSTs.
2225 if mem::size_of::<T>() == 0 {
2226 return SpecFromNested::from_iter(iterator);
2229 let (src_buf, src_end) = {
2230 let inner = unsafe { iterator.as_inner().as_into_iter() };
2231 (inner.buf.as_ptr(), inner.end)
2235 let dst = if mem::needs_drop::<T>() {
2236 // special-case drop handling since it prevents vectorization
2237 let mut sink = InPlaceDrop { inner: src_buf, dst };
2238 let _ = iterator.try_for_each::<_, Result<_, !>>(|item| {
2241 sink.dst as *const _ <= src_end,
2242 "InPlaceIterable contract violation"
2244 ptr::write(sink.dst, item);
2245 sink.dst = sink.dst.add(1);
2249 // iteration succeeded, don't drop head
2250 let sink = mem::ManuallyDrop::new(sink);
2254 // - it vectorizes better
2255 // - unlike most internal iteration methods methods it only takes a &mut self
2256 // - lets us thread the write pointer through its innards and get it back in the end
2258 .try_fold::<_, _, Result<_, !>>(dst, move |mut dst, item| {
2260 // the InPlaceIterable contract cannot be verified precisely here since
2261 // try_fold has an exclusive reference to the source pointer
2262 // all we can do is check if it's still in range
2264 dst as *const _ <= src_end,
2265 "InPlaceIterable contract violation"
2267 ptr::write(dst, item);
2275 let src = unsafe { iterator.as_inner().as_into_iter() };
2276 // check if SourceIter and InPlaceIterable contracts were upheld.
2277 // caveat: if they weren't we may not even make it to this point
2278 debug_assert_eq!(src_buf, src.buf.as_ptr());
2279 debug_assert!(dst as *const _ <= src.ptr, "InPlaceIterable contract violation");
2281 if mem::needs_drop::<T>() {
2282 // drop tail if iterator was only partially exhausted
2284 ptr::drop_in_place(src.as_mut_slice());
2289 let len = dst.offset_from(src_buf) as usize;
2290 Vec::from_raw_parts(src.buf.as_ptr(), len, src.cap)
2292 // prevent drop of the underlying storage by turning the IntoIter into
2293 // the equivalent of Vec::new().into_iter()
2295 src.buf = unsafe { NonNull::new_unchecked(RawVec::NEW.ptr()) };
2296 src.ptr = src.buf.as_ptr();
2297 src.end = src.buf.as_ptr();
2303 impl<'a, T: 'a, I> SpecFrom<&'a T, I> for Vec<T>
2305 I: Iterator<Item = &'a T>,
2308 default fn from_iter(iterator: I) -> Self {
2309 SpecFrom::from_iter(iterator.cloned())
2313 impl<'a, T: 'a> SpecFrom<&'a T, slice::Iter<'a, T>> for Vec<T>
2317 // reuses the extend specialization for T: Copy
2318 fn from_iter(iterator: slice::Iter<'a, T>) -> Self {
2319 let mut vec = Vec::new();
2320 // must delegate to spec_extend() since extend() itself delegates
2321 // to spec_from for empty Vecs
2322 vec.spec_extend(iterator);
2327 // Specialization trait used for Vec::extend
2328 trait SpecExtend<T, I> {
2329 fn spec_extend(&mut self, iter: I);
2332 impl<T, I> SpecExtend<T, I> for Vec<T>
2334 I: Iterator<Item = T>,
2336 default fn spec_extend(&mut self, iter: I) {
2337 self.extend_desugared(iter)
2341 impl<T, I> SpecExtend<T, I> for Vec<T>
2343 I: TrustedLen<Item = T>,
2345 default fn spec_extend(&mut self, iterator: I) {
2346 // This is the case for a TrustedLen iterator.
2347 let (low, high) = iterator.size_hint();
2348 if let Some(high_value) = high {
2352 "TrustedLen iterator's size hint is not exact: {:?}",
2356 if let Some(additional) = high {
2357 self.reserve(additional);
2359 let mut ptr = self.as_mut_ptr().add(self.len());
2360 let mut local_len = SetLenOnDrop::new(&mut self.len);
2361 iterator.for_each(move |element| {
2362 ptr::write(ptr, element);
2363 ptr = ptr.offset(1);
2364 // NB can't overflow since we would have had to alloc the address space
2365 local_len.increment_len(1);
2369 self.extend_desugared(iterator)
2374 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2375 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2377 self.append_elements(iterator.as_slice() as _);
2379 iterator.ptr = iterator.end;
2383 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2385 I: Iterator<Item = &'a T>,
2388 default fn spec_extend(&mut self, iterator: I) {
2389 self.spec_extend(iterator.cloned())
2393 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2397 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2398 let slice = iterator.as_slice();
2399 unsafe { self.append_elements(slice) };
2404 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2405 // they have no further optimizations to apply
2406 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2407 // This is the case for a general iterator.
2409 // This function should be the moral equivalent of:
2411 // for item in iterator {
2414 while let Some(element) = iterator.next() {
2415 let len = self.len();
2416 if len == self.capacity() {
2417 let (lower, _) = iterator.size_hint();
2418 self.reserve(lower.saturating_add(1));
2421 ptr::write(self.as_mut_ptr().add(len), element);
2422 // NB can't overflow since we would have had to alloc the address space
2423 self.set_len(len + 1);
2428 /// Creates a splicing iterator that replaces the specified range in the vector
2429 /// with the given `replace_with` iterator and yields the removed items.
2430 /// `replace_with` does not need to be the same length as `range`.
2432 /// `range` is removed even if the iterator is not consumed until the end.
2434 /// It is unspecified how many elements are removed from the vector
2435 /// if the `Splice` value is leaked.
2437 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2439 /// This is optimal if:
2441 /// * The tail (elements in the vector after `range`) is empty,
2442 /// * or `replace_with` yields fewer elements than `range`’s length
2443 /// * or the lower bound of its `size_hint()` is exact.
2445 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2449 /// Panics if the starting point is greater than the end point or if
2450 /// the end point is greater than the length of the vector.
2455 /// let mut v = vec![1, 2, 3];
2456 /// let new = [7, 8];
2457 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2458 /// assert_eq!(v, &[7, 8, 3]);
2459 /// assert_eq!(u, &[1, 2]);
2462 #[stable(feature = "vec_splice", since = "1.21.0")]
2463 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2465 R: RangeBounds<usize>,
2466 I: IntoIterator<Item = T>,
2468 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2471 /// Creates an iterator which uses a closure to determine if an element should be removed.
2473 /// If the closure returns true, then the element is removed and yielded.
2474 /// If the closure returns false, the element will remain in the vector and will not be yielded
2475 /// by the iterator.
2477 /// Using this method is equivalent to the following code:
2480 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2481 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2483 /// while i != vec.len() {
2484 /// if some_predicate(&mut vec[i]) {
2485 /// let val = vec.remove(i);
2486 /// // your code here
2492 /// # assert_eq!(vec, vec![1, 4, 5]);
2495 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2496 /// because it can backshift the elements of the array in bulk.
2498 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2499 /// regardless of whether you choose to keep or remove it.
2503 /// Splitting an array into evens and odds, reusing the original allocation:
2506 /// #![feature(drain_filter)]
2507 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2509 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2510 /// let odds = numbers;
2512 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2513 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2515 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2516 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2518 F: FnMut(&mut T) -> bool,
2520 let old_len = self.len();
2522 // Guard against us getting leaked (leak amplification)
2527 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2531 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2533 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2534 /// append the entire slice at once.
2536 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2537 #[stable(feature = "extend_ref", since = "1.2.0")]
2538 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2539 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2540 if self.capacity() > 0 {
2541 self.spec_extend(iter.into_iter())
2543 // if self has no allocation then use the more powerful from_iter specializations
2544 // and overwrite self
2545 *self = SpecFrom::from_iter(iter.into_iter());
2550 fn extend_one(&mut self, &item: &'a T) {
2555 fn extend_reserve(&mut self, additional: usize) {
2556 self.reserve(additional);
2560 macro_rules! __impl_slice_eq1 {
2561 ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => {
2563 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2569 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2571 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2576 __impl_slice_eq1! { [] Vec<A>, Vec<B>, #[stable(feature = "rust1", since = "1.0.0")] }
2577 __impl_slice_eq1! { [] Vec<A>, &[B], #[stable(feature = "rust1", since = "1.0.0")] }
2578 __impl_slice_eq1! { [] Vec<A>, &mut [B], #[stable(feature = "rust1", since = "1.0.0")] }
2579 __impl_slice_eq1! { [] &[A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2580 __impl_slice_eq1! { [] &mut [A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2581 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B> where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2582 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2583 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2584 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2585 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2587 // NOTE: some less important impls are omitted to reduce code bloat
2588 // FIXME(Centril): Reconsider this?
2589 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], }
2590 //__impl_slice_eq1! { [const N: usize] [A; N], Vec<B>, }
2591 //__impl_slice_eq1! { [const N: usize] &[A; N], Vec<B>, }
2592 //__impl_slice_eq1! { [const N: usize] &mut [A; N], Vec<B>, }
2593 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], }
2594 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], }
2595 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], }
2597 /// Implements comparison of vectors, lexicographically.
2598 #[stable(feature = "rust1", since = "1.0.0")]
2599 impl<T: PartialOrd> PartialOrd for Vec<T> {
2601 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2602 PartialOrd::partial_cmp(&**self, &**other)
2606 #[stable(feature = "rust1", since = "1.0.0")]
2607 impl<T: Eq> Eq for Vec<T> {}
2609 /// Implements ordering of vectors, lexicographically.
2610 #[stable(feature = "rust1", since = "1.0.0")]
2611 impl<T: Ord> Ord for Vec<T> {
2613 fn cmp(&self, other: &Vec<T>) -> Ordering {
2614 Ord::cmp(&**self, &**other)
2618 #[stable(feature = "rust1", since = "1.0.0")]
2619 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2620 fn drop(&mut self) {
2623 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2624 // could avoid questions of validity in certain cases
2625 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2627 // RawVec handles deallocation
2631 #[stable(feature = "rust1", since = "1.0.0")]
2632 impl<T> Default for Vec<T> {
2633 /// Creates an empty `Vec<T>`.
2634 fn default() -> Vec<T> {
2639 #[stable(feature = "rust1", since = "1.0.0")]
2640 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2641 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2642 fmt::Debug::fmt(&**self, f)
2646 #[stable(feature = "rust1", since = "1.0.0")]
2647 impl<T> AsRef<Vec<T>> for Vec<T> {
2648 fn as_ref(&self) -> &Vec<T> {
2653 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2654 impl<T> AsMut<Vec<T>> for Vec<T> {
2655 fn as_mut(&mut self) -> &mut Vec<T> {
2660 #[stable(feature = "rust1", since = "1.0.0")]
2661 impl<T> AsRef<[T]> for Vec<T> {
2662 fn as_ref(&self) -> &[T] {
2667 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2668 impl<T> AsMut<[T]> for Vec<T> {
2669 fn as_mut(&mut self) -> &mut [T] {
2674 #[stable(feature = "rust1", since = "1.0.0")]
2675 impl<T: Clone> From<&[T]> for Vec<T> {
2677 fn from(s: &[T]) -> Vec<T> {
2681 fn from(s: &[T]) -> Vec<T> {
2682 crate::slice::to_vec(s)
2686 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2687 impl<T: Clone> From<&mut [T]> for Vec<T> {
2689 fn from(s: &mut [T]) -> Vec<T> {
2693 fn from(s: &mut [T]) -> Vec<T> {
2694 crate::slice::to_vec(s)
2698 #[stable(feature = "vec_from_array", since = "1.44.0")]
2699 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2701 fn from(s: [T; N]) -> Vec<T> {
2702 <[T]>::into_vec(box s)
2705 fn from(s: [T; N]) -> Vec<T> {
2706 crate::slice::into_vec(box s)
2710 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2711 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2713 [T]: ToOwned<Owned = Vec<T>>,
2715 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2720 // note: test pulls in libstd, which causes errors here
2722 #[stable(feature = "vec_from_box", since = "1.18.0")]
2723 impl<T> From<Box<[T]>> for Vec<T> {
2724 fn from(s: Box<[T]>) -> Vec<T> {
2729 // note: test pulls in libstd, which causes errors here
2731 #[stable(feature = "box_from_vec", since = "1.20.0")]
2732 impl<T> From<Vec<T>> for Box<[T]> {
2733 fn from(v: Vec<T>) -> Box<[T]> {
2734 v.into_boxed_slice()
2738 #[stable(feature = "rust1", since = "1.0.0")]
2739 impl From<&str> for Vec<u8> {
2740 fn from(s: &str) -> Vec<u8> {
2741 From::from(s.as_bytes())
2745 ////////////////////////////////////////////////////////////////////////////////
2747 ////////////////////////////////////////////////////////////////////////////////
2749 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2750 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2751 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2756 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2757 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2758 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2763 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2764 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2765 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2766 Cow::Borrowed(v.as_slice())
2770 #[stable(feature = "rust1", since = "1.0.0")]
2771 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
2775 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2776 Cow::Owned(FromIterator::from_iter(it))
2780 ////////////////////////////////////////////////////////////////////////////////
2782 ////////////////////////////////////////////////////////////////////////////////
2784 /// An iterator that moves out of a vector.
2786 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
2787 /// by the [`IntoIterator`] trait).
2788 #[stable(feature = "rust1", since = "1.0.0")]
2789 pub struct IntoIter<T> {
2791 phantom: PhantomData<T>,
2797 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2798 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2799 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2800 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2804 impl<T> IntoIter<T> {
2805 /// Returns the remaining items of this iterator as a slice.
2810 /// let vec = vec!['a', 'b', 'c'];
2811 /// let mut into_iter = vec.into_iter();
2812 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2813 /// let _ = into_iter.next().unwrap();
2814 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2816 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2817 pub fn as_slice(&self) -> &[T] {
2818 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
2821 /// Returns the remaining items of this iterator as a mutable slice.
2826 /// let vec = vec!['a', 'b', 'c'];
2827 /// let mut into_iter = vec.into_iter();
2828 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2829 /// into_iter.as_mut_slice()[2] = 'z';
2830 /// assert_eq!(into_iter.next().unwrap(), 'a');
2831 /// assert_eq!(into_iter.next().unwrap(), 'b');
2832 /// assert_eq!(into_iter.next().unwrap(), 'z');
2834 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2835 pub fn as_mut_slice(&mut self) -> &mut [T] {
2836 unsafe { &mut *self.as_raw_mut_slice() }
2839 fn as_raw_mut_slice(&mut self) -> *mut [T] {
2840 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
2844 #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
2845 impl<T> AsRef<[T]> for IntoIter<T> {
2846 fn as_ref(&self) -> &[T] {
2851 #[stable(feature = "rust1", since = "1.0.0")]
2852 unsafe impl<T: Send> Send for IntoIter<T> {}
2853 #[stable(feature = "rust1", since = "1.0.0")]
2854 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2856 #[stable(feature = "rust1", since = "1.0.0")]
2857 impl<T> Iterator for IntoIter<T> {
2861 fn next(&mut self) -> Option<T> {
2863 if self.ptr as *const _ == self.end {
2866 if mem::size_of::<T>() == 0 {
2867 // purposefully don't use 'ptr.offset' because for
2868 // vectors with 0-size elements this would return the
2870 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2872 // Make up a value of this ZST.
2876 self.ptr = self.ptr.offset(1);
2878 Some(ptr::read(old))
2885 fn size_hint(&self) -> (usize, Option<usize>) {
2886 let exact = if mem::size_of::<T>() == 0 {
2887 (self.end as usize).wrapping_sub(self.ptr as usize)
2889 unsafe { self.end.offset_from(self.ptr) as usize }
2891 (exact, Some(exact))
2895 fn count(self) -> usize {
2900 #[stable(feature = "rust1", since = "1.0.0")]
2901 impl<T> DoubleEndedIterator for IntoIter<T> {
2903 fn next_back(&mut self) -> Option<T> {
2905 if self.end == self.ptr {
2908 if mem::size_of::<T>() == 0 {
2909 // See above for why 'ptr.offset' isn't used
2910 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2912 // Make up a value of this ZST.
2915 self.end = self.end.offset(-1);
2917 Some(ptr::read(self.end))
2924 #[stable(feature = "rust1", since = "1.0.0")]
2925 impl<T> ExactSizeIterator for IntoIter<T> {
2926 fn is_empty(&self) -> bool {
2927 self.ptr == self.end
2931 #[stable(feature = "fused", since = "1.26.0")]
2932 impl<T> FusedIterator for IntoIter<T> {}
2934 #[unstable(feature = "trusted_len", issue = "37572")]
2935 unsafe impl<T> TrustedLen for IntoIter<T> {}
2938 #[unstable(issue = "none", feature = "std_internals")]
2939 // T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr
2940 // and thus we can't implement drop-handling
2941 unsafe impl<T> TrustedRandomAccess for IntoIter<T>
2945 unsafe fn get_unchecked(&mut self, i: usize) -> Self::Item {
2947 if mem::size_of::<T>() == 0 { mem::zeroed() } else { ptr::read(self.ptr.add(i)) }
2951 fn may_have_side_effect() -> bool {
2956 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2957 impl<T: Clone> Clone for IntoIter<T> {
2958 fn clone(&self) -> IntoIter<T> {
2959 self.as_slice().to_owned().into_iter()
2963 #[stable(feature = "rust1", since = "1.0.0")]
2964 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2965 fn drop(&mut self) {
2966 struct DropGuard<'a, T>(&'a mut IntoIter<T>);
2968 impl<T> Drop for DropGuard<'_, T> {
2969 fn drop(&mut self) {
2970 // RawVec handles deallocation
2971 let _ = unsafe { RawVec::from_raw_parts(self.0.buf.as_ptr(), self.0.cap) };
2975 let guard = DropGuard(self);
2976 // destroy the remaining elements
2978 ptr::drop_in_place(guard.0.as_raw_mut_slice());
2980 // now `guard` will be dropped and do the rest
2984 #[unstable(issue = "none", feature = "inplace_iteration")]
2985 unsafe impl<T> InPlaceIterable for IntoIter<T> {}
2987 #[unstable(issue = "none", feature = "inplace_iteration")]
2988 unsafe impl<T> SourceIter for IntoIter<T> {
2989 type Source = IntoIter<T>;
2992 unsafe fn as_inner(&mut self) -> &mut Self::Source {
2997 // internal helper trait for in-place iteration specialization.
2998 pub(crate) trait AsIntoIter<T> {
2999 fn as_into_iter(&mut self) -> &mut IntoIter<T>;
3002 impl<T> AsIntoIter<T> for IntoIter<T> {
3003 fn as_into_iter(&mut self) -> &mut IntoIter<T> {
3008 /// A draining iterator for `Vec<T>`.
3010 /// This `struct` is created by [`Vec::drain`].
3011 #[stable(feature = "drain", since = "1.6.0")]
3012 pub struct Drain<'a, T: 'a> {
3013 /// Index of tail to preserve
3017 /// Current remaining range to remove
3018 iter: slice::Iter<'a, T>,
3019 vec: NonNull<Vec<T>>,
3022 #[stable(feature = "collection_debug", since = "1.17.0")]
3023 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
3024 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3025 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
3029 impl<'a, T> Drain<'a, T> {
3030 /// Returns the remaining items of this iterator as a slice.
3035 /// let mut vec = vec!['a', 'b', 'c'];
3036 /// let mut drain = vec.drain(..);
3037 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
3038 /// let _ = drain.next().unwrap();
3039 /// assert_eq!(drain.as_slice(), &['b', 'c']);
3041 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3042 pub fn as_slice(&self) -> &[T] {
3043 self.iter.as_slice()
3047 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3048 impl<'a, T> AsRef<[T]> for Drain<'a, T> {
3049 fn as_ref(&self) -> &[T] {
3054 #[stable(feature = "drain", since = "1.6.0")]
3055 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
3056 #[stable(feature = "drain", since = "1.6.0")]
3057 unsafe impl<T: Send> Send for Drain<'_, T> {}
3059 #[stable(feature = "drain", since = "1.6.0")]
3060 impl<T> Iterator for Drain<'_, T> {
3064 fn next(&mut self) -> Option<T> {
3065 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
3068 fn size_hint(&self) -> (usize, Option<usize>) {
3069 self.iter.size_hint()
3073 #[stable(feature = "drain", since = "1.6.0")]
3074 impl<T> DoubleEndedIterator for Drain<'_, T> {
3076 fn next_back(&mut self) -> Option<T> {
3077 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
3081 #[stable(feature = "drain", since = "1.6.0")]
3082 impl<T> Drop for Drain<'_, T> {
3083 fn drop(&mut self) {
3084 /// Continues dropping the remaining elements in the `Drain`, then moves back the
3085 /// un-`Drain`ed elements to restore the original `Vec`.
3086 struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>);
3088 impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> {
3089 fn drop(&mut self) {
3090 // Continue the same loop we have below. If the loop already finished, this does
3092 self.0.for_each(drop);
3094 if self.0.tail_len > 0 {
3096 let source_vec = self.0.vec.as_mut();
3097 // memmove back untouched tail, update to new length
3098 let start = source_vec.len();
3099 let tail = self.0.tail_start;
3101 let src = source_vec.as_ptr().add(tail);
3102 let dst = source_vec.as_mut_ptr().add(start);
3103 ptr::copy(src, dst, self.0.tail_len);
3105 source_vec.set_len(start + self.0.tail_len);
3111 // exhaust self first
3112 while let Some(item) = self.next() {
3113 let guard = DropGuard(self);
3118 // Drop a `DropGuard` to move back the non-drained tail of `self`.
3123 #[stable(feature = "drain", since = "1.6.0")]
3124 impl<T> ExactSizeIterator for Drain<'_, T> {
3125 fn is_empty(&self) -> bool {
3126 self.iter.is_empty()
3130 #[unstable(feature = "trusted_len", issue = "37572")]
3131 unsafe impl<T> TrustedLen for Drain<'_, T> {}
3133 #[stable(feature = "fused", since = "1.26.0")]
3134 impl<T> FusedIterator for Drain<'_, T> {}
3136 /// A splicing iterator for `Vec`.
3138 /// This struct is created by [`Vec::splice()`].
3139 /// See its documentation for more.
3141 #[stable(feature = "vec_splice", since = "1.21.0")]
3142 pub struct Splice<'a, I: Iterator + 'a> {
3143 drain: Drain<'a, I::Item>,
3147 #[stable(feature = "vec_splice", since = "1.21.0")]
3148 impl<I: Iterator> Iterator for Splice<'_, I> {
3149 type Item = I::Item;
3151 fn next(&mut self) -> Option<Self::Item> {
3155 fn size_hint(&self) -> (usize, Option<usize>) {
3156 self.drain.size_hint()
3160 #[stable(feature = "vec_splice", since = "1.21.0")]
3161 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
3162 fn next_back(&mut self) -> Option<Self::Item> {
3163 self.drain.next_back()
3167 #[stable(feature = "vec_splice", since = "1.21.0")]
3168 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
3170 #[stable(feature = "vec_splice", since = "1.21.0")]
3171 impl<I: Iterator> Drop for Splice<'_, I> {
3172 fn drop(&mut self) {
3173 self.drain.by_ref().for_each(drop);
3176 if self.drain.tail_len == 0 {
3177 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
3181 // First fill the range left by drain().
3182 if !self.drain.fill(&mut self.replace_with) {
3186 // There may be more elements. Use the lower bound as an estimate.
3187 // FIXME: Is the upper bound a better guess? Or something else?
3188 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
3189 if lower_bound > 0 {
3190 self.drain.move_tail(lower_bound);
3191 if !self.drain.fill(&mut self.replace_with) {
3196 // Collect any remaining elements.
3197 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
3198 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
3199 // Now we have an exact count.
3200 if collected.len() > 0 {
3201 self.drain.move_tail(collected.len());
3202 let filled = self.drain.fill(&mut collected);
3203 debug_assert!(filled);
3204 debug_assert_eq!(collected.len(), 0);
3207 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
3211 /// Private helper methods for `Splice::drop`
3212 impl<T> Drain<'_, T> {
3213 /// The range from `self.vec.len` to `self.tail_start` contains elements
3214 /// that have been moved out.
3215 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
3216 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
3217 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
3218 let vec = unsafe { self.vec.as_mut() };
3219 let range_start = vec.len;
3220 let range_end = self.tail_start;
3221 let range_slice = unsafe {
3222 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
3225 for place in range_slice {
3226 if let Some(new_item) = replace_with.next() {
3227 unsafe { ptr::write(place, new_item) };
3236 /// Makes room for inserting more elements before the tail.
3237 unsafe fn move_tail(&mut self, additional: usize) {
3238 let vec = unsafe { self.vec.as_mut() };
3239 let len = self.tail_start + self.tail_len;
3240 vec.buf.reserve(len, additional);
3242 let new_tail_start = self.tail_start + additional;
3244 let src = vec.as_ptr().add(self.tail_start);
3245 let dst = vec.as_mut_ptr().add(new_tail_start);
3246 ptr::copy(src, dst, self.tail_len);
3248 self.tail_start = new_tail_start;
3252 /// An iterator which uses a closure to determine if an element should be removed.
3254 /// This struct is created by [`Vec::drain_filter`].
3255 /// See its documentation for more.
3256 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3258 pub struct DrainFilter<'a, T, F>
3260 F: FnMut(&mut T) -> bool,
3262 vec: &'a mut Vec<T>,
3263 /// The index of the item that will be inspected by the next call to `next`.
3265 /// The number of items that have been drained (removed) thus far.
3267 /// The original length of `vec` prior to draining.
3269 /// The filter test predicate.
3271 /// A flag that indicates a panic has occurred in the filter test predicate.
3272 /// This is used as a hint in the drop implementation to prevent consumption
3273 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3274 /// backshifted in the `vec`, but no further items will be dropped or
3275 /// tested by the filter predicate.
3279 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3280 impl<T, F> Iterator for DrainFilter<'_, T, F>
3282 F: FnMut(&mut T) -> bool,
3286 fn next(&mut self) -> Option<T> {
3288 while self.idx < self.old_len {
3290 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3291 self.panic_flag = true;
3292 let drained = (self.pred)(&mut v[i]);
3293 self.panic_flag = false;
3294 // Update the index *after* the predicate is called. If the index
3295 // is updated prior and the predicate panics, the element at this
3296 // index would be leaked.
3300 return Some(ptr::read(&v[i]));
3301 } else if self.del > 0 {
3303 let src: *const T = &v[i];
3304 let dst: *mut T = &mut v[i - del];
3305 ptr::copy_nonoverlapping(src, dst, 1);
3312 fn size_hint(&self) -> (usize, Option<usize>) {
3313 (0, Some(self.old_len - self.idx))
3317 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3318 impl<T, F> Drop for DrainFilter<'_, T, F>
3320 F: FnMut(&mut T) -> bool,
3322 fn drop(&mut self) {
3323 struct BackshiftOnDrop<'a, 'b, T, F>
3325 F: FnMut(&mut T) -> bool,
3327 drain: &'b mut DrainFilter<'a, T, F>,
3330 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
3332 F: FnMut(&mut T) -> bool,
3334 fn drop(&mut self) {
3336 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3337 // This is a pretty messed up state, and there isn't really an
3338 // obviously right thing to do. We don't want to keep trying
3339 // to execute `pred`, so we just backshift all the unprocessed
3340 // elements and tell the vec that they still exist. The backshift
3341 // is required to prevent a double-drop of the last successfully
3342 // drained item prior to a panic in the predicate.
3343 let ptr = self.drain.vec.as_mut_ptr();
3344 let src = ptr.add(self.drain.idx);
3345 let dst = src.sub(self.drain.del);
3346 let tail_len = self.drain.old_len - self.drain.idx;
3347 src.copy_to(dst, tail_len);
3349 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3354 let backshift = BackshiftOnDrop { drain: self };
3356 // Attempt to consume any remaining elements if the filter predicate
3357 // has not yet panicked. We'll backshift any remaining elements
3358 // whether we've already panicked or if the consumption here panics.
3359 if !backshift.drain.panic_flag {
3360 backshift.drain.for_each(drop);