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::{self, Index, IndexMut, Range, 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 /// For more information, see
125 /// [Capacity and Reallocation](#capacity-and-reallocation).
127 /// Use a `Vec<T>` as an efficient stack:
130 /// let mut stack = Vec::new();
136 /// while let Some(top) = stack.pop() {
137 /// // Prints 3, 2, 1
138 /// println!("{}", top);
144 /// The `Vec` type allows to access values by index, because it implements the
145 /// [`Index`] trait. An example will be more explicit:
148 /// let v = vec![0, 2, 4, 6];
149 /// println!("{}", v[1]); // it will display '2'
152 /// However be careful: if you try to access an index which isn't in the `Vec`,
153 /// your software will panic! You cannot do this:
156 /// let v = vec![0, 2, 4, 6];
157 /// println!("{}", v[6]); // it will panic!
160 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
165 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
166 /// To get a [slice], use [`&`]. Example:
169 /// fn read_slice(slice: &[usize]) {
173 /// let v = vec![0, 1];
176 /// // ... and that's all!
177 /// // you can also do it like this:
178 /// let u: &[usize] = &v;
180 /// let u: &[_] = &v;
183 /// In Rust, it's more common to pass slices as arguments rather than vectors
184 /// when you just want to provide read access. The same goes for [`String`] and
187 /// # Capacity and reallocation
189 /// The capacity of a vector is the amount of space allocated for any future
190 /// elements that will be added onto the vector. This is not to be confused with
191 /// the *length* of a vector, which specifies the number of actual elements
192 /// within the vector. If a vector's length exceeds its capacity, its capacity
193 /// will automatically be increased, but its elements will have to be
196 /// For example, a vector with capacity 10 and length 0 would be an empty vector
197 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
198 /// vector will not change its capacity or cause reallocation to occur. However,
199 /// if the vector's length is increased to 11, it will have to reallocate, which
200 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
201 /// whenever possible to specify how big the vector is expected to get.
205 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
206 /// about its design. This ensures that it's as low-overhead as possible in
207 /// the general case, and can be correctly manipulated in primitive ways
208 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
209 /// If additional type parameters are added (e.g., to support custom allocators),
210 /// overriding their defaults may change the behavior.
212 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
213 /// triplet. No more, no less. The order of these fields is completely
214 /// unspecified, and you should use the appropriate methods to modify these.
215 /// The pointer will never be null, so this type is null-pointer-optimized.
217 /// However, the pointer may not actually point to allocated memory. In particular,
218 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
219 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
220 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
221 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
222 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
223 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
224 /// details are very subtle — if you intend to allocate memory using a `Vec`
225 /// and use it for something else (either to pass to unsafe code, or to build your
226 /// own memory-backed collection), be sure to deallocate this memory by using
227 /// `from_raw_parts` to recover the `Vec` and then dropping it.
229 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
230 /// (as defined by the allocator Rust is configured to use by default), and its
231 /// pointer points to [`len`] initialized, contiguous elements in order (what
232 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
233 /// `[`len`] logically uninitialized, contiguous elements.
235 /// `Vec` will never perform a "small optimization" where elements are actually
236 /// stored on the stack for two reasons:
238 /// * It would make it more difficult for unsafe code to correctly manipulate
239 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
240 /// only moved, and it would be more difficult to determine if a `Vec` had
241 /// actually allocated memory.
243 /// * It would penalize the general case, incurring an additional branch
246 /// `Vec` will never automatically shrink itself, even if completely empty. This
247 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
248 /// and then filling it back up to the same [`len`] should incur no calls to
249 /// the allocator. If you wish to free up unused memory, use
250 /// [`shrink_to_fit`].
252 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
253 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
254 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
255 /// accurate, and can be relied on. It can even be used to manually free the memory
256 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
257 /// when not necessary.
259 /// `Vec` does not guarantee any particular growth strategy when reallocating
260 /// when full, nor when [`reserve`] is called. The current strategy is basic
261 /// and it may prove desirable to use a non-constant growth factor. Whatever
262 /// strategy is used will of course guarantee *O*(1) amortized [`push`].
264 /// `vec![x; n]`, `vec![a, b, c, d]`, and
265 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
266 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
267 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
268 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
270 /// `Vec` will not specifically overwrite any data that is removed from it,
271 /// but also won't specifically preserve it. Its uninitialized memory is
272 /// scratch space that it may use however it wants. It will generally just do
273 /// whatever is most efficient or otherwise easy to implement. Do not rely on
274 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
275 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
276 /// first, that may not actually happen because the optimizer does not consider
277 /// this a side-effect that must be preserved. There is one case which we will
278 /// not break, however: using `unsafe` code to write to the excess capacity,
279 /// and then increasing the length to match, is always valid.
281 /// `Vec` does not currently guarantee the order in which elements are dropped.
282 /// The order has changed in the past and may change again.
284 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
285 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
286 /// [`String`]: crate::string::String
287 /// [`&str`]: type@str
288 /// [`shrink_to_fit`]: Vec::shrink_to_fit
289 /// [`capacity`]: Vec::capacity
290 /// [`mem::size_of::<T>`]: core::mem::size_of
291 /// [`len`]: Vec::len
292 /// [`push`]: Vec::push
293 /// [`insert`]: Vec::insert
294 /// [`reserve`]: Vec::reserve
295 /// [owned slice]: Box
296 /// [slice]: ../../std/primitive.slice.html
297 /// [`&`]: ../../std/primitive.reference.html
298 #[stable(feature = "rust1", since = "1.0.0")]
299 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
305 ////////////////////////////////////////////////////////////////////////////////
307 ////////////////////////////////////////////////////////////////////////////////
310 /// Constructs a new, empty `Vec<T>`.
312 /// The vector will not allocate until elements are pushed onto it.
317 /// # #![allow(unused_mut)]
318 /// let mut vec: Vec<i32> = Vec::new();
321 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub const fn new() -> Vec<T> {
324 Vec { buf: RawVec::NEW, len: 0 }
327 /// Constructs a new, empty `Vec<T>` with the specified capacity.
329 /// The vector will be able to hold exactly `capacity` elements without
330 /// reallocating. If `capacity` is 0, the vector will not allocate.
332 /// It is important to note that although the returned vector has the
333 /// *capacity* specified, the vector will have a zero *length*. For an
334 /// explanation of the difference between length and capacity, see
335 /// *[Capacity and reallocation]*.
337 /// [Capacity and reallocation]: #capacity-and-reallocation
342 /// let mut vec = Vec::with_capacity(10);
344 /// // The vector contains no items, even though it has capacity for more
345 /// assert_eq!(vec.len(), 0);
346 /// assert_eq!(vec.capacity(), 10);
348 /// // These are all done without reallocating...
352 /// assert_eq!(vec.len(), 10);
353 /// assert_eq!(vec.capacity(), 10);
355 /// // ...but this may make the vector reallocate
357 /// assert_eq!(vec.len(), 11);
358 /// assert!(vec.capacity() >= 11);
361 #[stable(feature = "rust1", since = "1.0.0")]
362 pub fn with_capacity(capacity: usize) -> Vec<T> {
363 Vec { buf: RawVec::with_capacity(capacity), len: 0 }
366 /// Decomposes a `Vec<T>` into its raw components.
368 /// Returns the raw pointer to the underlying data, the length of
369 /// the vector (in elements), and the allocated capacity of the
370 /// data (in elements). These are the same arguments in the same
371 /// order as the arguments to [`from_raw_parts`].
373 /// After calling this function, the caller is responsible for the
374 /// memory previously managed by the `Vec`. The only way to do
375 /// this is to convert the raw pointer, length, and capacity back
376 /// into a `Vec` with the [`from_raw_parts`] function, allowing
377 /// the destructor to perform the cleanup.
379 /// [`from_raw_parts`]: Vec::from_raw_parts
384 /// #![feature(vec_into_raw_parts)]
385 /// let v: Vec<i32> = vec![-1, 0, 1];
387 /// let (ptr, len, cap) = v.into_raw_parts();
389 /// let rebuilt = unsafe {
390 /// // We can now make changes to the components, such as
391 /// // transmuting the raw pointer to a compatible type.
392 /// let ptr = ptr as *mut u32;
394 /// Vec::from_raw_parts(ptr, len, cap)
396 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
398 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
399 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
400 let mut me = ManuallyDrop::new(self);
401 (me.as_mut_ptr(), me.len(), me.capacity())
404 /// Creates a `Vec<T>` directly from the raw components of another vector.
408 /// This is highly unsafe, due to the number of invariants that aren't
411 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
412 /// (at least, it's highly likely to be incorrect if it wasn't).
413 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
414 /// (`T` having a less strict alignment is not sufficient, the alignment really
415 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
416 /// allocated and deallocated with the same layout.)
417 /// * `length` needs to be less than or equal to `capacity`.
418 /// * `capacity` needs to be the capacity that the pointer was allocated with.
420 /// Violating these may cause problems like corrupting the allocator's
421 /// internal data structures. For example it is **not** safe
422 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
423 /// It's also not safe to build one from a `Vec<u16>` and its length, because
424 /// the allocator cares about the alignment, and these two types have different
425 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
426 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
428 /// The ownership of `ptr` is effectively transferred to the
429 /// `Vec<T>` which may then deallocate, reallocate or change the
430 /// contents of memory pointed to by the pointer at will. Ensure
431 /// that nothing else uses the pointer after calling this
434 /// [`String`]: crate::string::String
435 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
443 /// let v = vec![1, 2, 3];
445 // FIXME Update this when vec_into_raw_parts is stabilized
446 /// // Prevent running `v`'s destructor so we are in complete control
447 /// // of the allocation.
448 /// let mut v = mem::ManuallyDrop::new(v);
450 /// // Pull out the various important pieces of information about `v`
451 /// let p = v.as_mut_ptr();
452 /// let len = v.len();
453 /// let cap = v.capacity();
456 /// // Overwrite memory with 4, 5, 6
457 /// for i in 0..len as isize {
458 /// ptr::write(p.offset(i), 4 + i);
461 /// // Put everything back together into a Vec
462 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
463 /// assert_eq!(rebuilt, [4, 5, 6]);
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
468 unsafe { Vec { buf: RawVec::from_raw_parts(ptr, capacity), len: length } }
471 /// Returns the number of elements the vector can hold without
477 /// let vec: Vec<i32> = Vec::with_capacity(10);
478 /// assert_eq!(vec.capacity(), 10);
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn capacity(&self) -> usize {
486 /// Reserves capacity for at least `additional` more elements to be inserted
487 /// in the given `Vec<T>`. The collection may reserve more space to avoid
488 /// frequent reallocations. After calling `reserve`, capacity will be
489 /// greater than or equal to `self.len() + additional`. Does nothing if
490 /// capacity is already sufficient.
494 /// Panics if the new capacity exceeds `isize::MAX` bytes.
499 /// let mut vec = vec![1];
501 /// assert!(vec.capacity() >= 11);
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn reserve(&mut self, additional: usize) {
505 self.buf.reserve(self.len, additional);
508 /// Reserves the minimum capacity for exactly `additional` more elements to
509 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
510 /// capacity will be greater than or equal to `self.len() + additional`.
511 /// Does nothing if the capacity is already sufficient.
513 /// Note that the allocator may give the collection more space than it
514 /// requests. Therefore, capacity can not be relied upon to be precisely
515 /// minimal. Prefer `reserve` if future insertions are expected.
519 /// Panics if the new capacity overflows `usize`.
524 /// let mut vec = vec![1];
525 /// vec.reserve_exact(10);
526 /// assert!(vec.capacity() >= 11);
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn reserve_exact(&mut self, additional: usize) {
530 self.buf.reserve_exact(self.len, additional);
533 /// Tries to reserve capacity for at least `additional` more elements to be inserted
534 /// in the given `Vec<T>`. The collection may reserve more space to avoid
535 /// frequent reallocations. After calling `try_reserve`, capacity will be
536 /// greater than or equal to `self.len() + additional`. Does nothing if
537 /// capacity is already sufficient.
541 /// If the capacity overflows, or the allocator reports a failure, then an error
547 /// #![feature(try_reserve)]
548 /// use std::collections::TryReserveError;
550 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
551 /// let mut output = Vec::new();
553 /// // Pre-reserve the memory, exiting if we can't
554 /// output.try_reserve(data.len())?;
556 /// // Now we know this can't OOM in the middle of our complex work
557 /// output.extend(data.iter().map(|&val| {
558 /// val * 2 + 5 // very complicated
563 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
565 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
566 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
567 self.buf.try_reserve(self.len, additional)
570 /// Tries to reserve the minimum capacity for exactly `additional`
571 /// elements to be inserted in the given `Vec<T>`. After calling
572 /// `try_reserve_exact`, capacity will be greater than or equal to
573 /// `self.len() + additional` if it returns `Ok(())`.
574 /// Does nothing if the capacity is already sufficient.
576 /// Note that the allocator may give the collection more space than it
577 /// requests. Therefore, capacity can not be relied upon to be precisely
578 /// minimal. Prefer `reserve` if future insertions are expected.
582 /// If the capacity overflows, or the allocator reports a failure, then an error
588 /// #![feature(try_reserve)]
589 /// use std::collections::TryReserveError;
591 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
592 /// let mut output = Vec::new();
594 /// // Pre-reserve the memory, exiting if we can't
595 /// output.try_reserve_exact(data.len())?;
597 /// // Now we know this can't OOM in the middle of our complex work
598 /// output.extend(data.iter().map(|&val| {
599 /// val * 2 + 5 // very complicated
604 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
606 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
607 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
608 self.buf.try_reserve_exact(self.len, additional)
611 /// Shrinks the capacity of the vector as much as possible.
613 /// It will drop down as close as possible to the length but the allocator
614 /// may still inform the vector that there is space for a few more elements.
619 /// let mut vec = Vec::with_capacity(10);
620 /// vec.extend([1, 2, 3].iter().cloned());
621 /// assert_eq!(vec.capacity(), 10);
622 /// vec.shrink_to_fit();
623 /// assert!(vec.capacity() >= 3);
625 #[stable(feature = "rust1", since = "1.0.0")]
626 pub fn shrink_to_fit(&mut self) {
627 // The capacity is never less than the length, and there's nothing to do when
628 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
629 // by only calling it with a greater capacity.
630 if self.capacity() > self.len {
631 self.buf.shrink_to_fit(self.len);
635 /// Shrinks the capacity of the vector with a lower bound.
637 /// The capacity will remain at least as large as both the length
638 /// and the supplied value.
642 /// Panics if the current capacity is smaller than the supplied
643 /// minimum capacity.
648 /// #![feature(shrink_to)]
649 /// let mut vec = Vec::with_capacity(10);
650 /// vec.extend([1, 2, 3].iter().cloned());
651 /// assert_eq!(vec.capacity(), 10);
652 /// vec.shrink_to(4);
653 /// assert!(vec.capacity() >= 4);
654 /// vec.shrink_to(0);
655 /// assert!(vec.capacity() >= 3);
657 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
658 pub fn shrink_to(&mut self, min_capacity: usize) {
659 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
662 /// Converts the vector into [`Box<[T]>`][owned slice].
664 /// Note that this will drop any excess capacity.
666 /// [owned slice]: Box
671 /// let v = vec![1, 2, 3];
673 /// let slice = v.into_boxed_slice();
676 /// Any excess capacity is removed:
679 /// let mut vec = Vec::with_capacity(10);
680 /// vec.extend([1, 2, 3].iter().cloned());
682 /// assert_eq!(vec.capacity(), 10);
683 /// let slice = vec.into_boxed_slice();
684 /// assert_eq!(slice.into_vec().capacity(), 3);
686 #[stable(feature = "rust1", since = "1.0.0")]
687 pub fn into_boxed_slice(mut self) -> Box<[T]> {
689 self.shrink_to_fit();
690 let me = ManuallyDrop::new(self);
691 let buf = ptr::read(&me.buf);
693 buf.into_box(len).assume_init()
697 /// Shortens the vector, keeping the first `len` elements and dropping
700 /// If `len` is greater than the vector's current length, this has no
703 /// The [`drain`] method can emulate `truncate`, but causes the excess
704 /// elements to be returned instead of dropped.
706 /// Note that this method has no effect on the allocated capacity
711 /// Truncating a five element vector to two elements:
714 /// let mut vec = vec![1, 2, 3, 4, 5];
716 /// assert_eq!(vec, [1, 2]);
719 /// No truncation occurs when `len` is greater than the vector's current
723 /// let mut vec = vec![1, 2, 3];
725 /// assert_eq!(vec, [1, 2, 3]);
728 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
732 /// let mut vec = vec![1, 2, 3];
734 /// assert_eq!(vec, []);
737 /// [`clear`]: Vec::clear
738 /// [`drain`]: Vec::drain
739 #[stable(feature = "rust1", since = "1.0.0")]
740 pub fn truncate(&mut self, len: usize) {
741 // This is safe because:
743 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
744 // case avoids creating an invalid slice, and
745 // * the `len` of the vector is shrunk before calling `drop_in_place`,
746 // such that no value will be dropped twice in case `drop_in_place`
747 // were to panic once (if it panics twice, the program aborts).
752 let remaining_len = self.len - len;
753 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
755 ptr::drop_in_place(s);
759 /// Extracts a slice containing the entire vector.
761 /// Equivalent to `&s[..]`.
766 /// use std::io::{self, Write};
767 /// let buffer = vec![1, 2, 3, 5, 8];
768 /// io::sink().write(buffer.as_slice()).unwrap();
771 #[stable(feature = "vec_as_slice", since = "1.7.0")]
772 pub fn as_slice(&self) -> &[T] {
776 /// Extracts a mutable slice of the entire vector.
778 /// Equivalent to `&mut s[..]`.
783 /// use std::io::{self, Read};
784 /// let mut buffer = vec![0; 3];
785 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
788 #[stable(feature = "vec_as_slice", since = "1.7.0")]
789 pub fn as_mut_slice(&mut self) -> &mut [T] {
793 /// Returns a raw pointer to the vector's buffer.
795 /// The caller must ensure that the vector outlives the pointer this
796 /// function returns, or else it will end up pointing to garbage.
797 /// Modifying the vector may cause its buffer to be reallocated,
798 /// which would also make any pointers to it invalid.
800 /// The caller must also ensure that the memory the pointer (non-transitively) points to
801 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
802 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
807 /// let x = vec![1, 2, 4];
808 /// let x_ptr = x.as_ptr();
811 /// for i in 0..x.len() {
812 /// assert_eq!(*x_ptr.add(i), 1 << i);
817 /// [`as_mut_ptr`]: Vec::as_mut_ptr
818 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
820 pub fn as_ptr(&self) -> *const T {
821 // We shadow the slice method of the same name to avoid going through
822 // `deref`, which creates an intermediate reference.
823 let ptr = self.buf.ptr();
825 assume(!ptr.is_null());
830 /// Returns an unsafe mutable pointer to the vector's buffer.
832 /// The caller must ensure that the vector outlives the pointer this
833 /// function returns, or else it will end up pointing to garbage.
834 /// Modifying the vector may cause its buffer to be reallocated,
835 /// which would also make any pointers to it invalid.
840 /// // Allocate vector big enough for 4 elements.
842 /// let mut x: Vec<i32> = Vec::with_capacity(size);
843 /// let x_ptr = x.as_mut_ptr();
845 /// // Initialize elements via raw pointer writes, then set length.
847 /// for i in 0..size {
848 /// *x_ptr.add(i) = i as i32;
852 /// assert_eq!(&*x, &[0,1,2,3]);
854 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
856 pub fn as_mut_ptr(&mut self) -> *mut T {
857 // We shadow the slice method of the same name to avoid going through
858 // `deref_mut`, which creates an intermediate reference.
859 let ptr = self.buf.ptr();
861 assume(!ptr.is_null());
866 /// Forces the length of the vector to `new_len`.
868 /// This is a low-level operation that maintains none of the normal
869 /// invariants of the type. Normally changing the length of a vector
870 /// is done using one of the safe operations instead, such as
871 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
873 /// [`truncate`]: Vec::truncate
874 /// [`resize`]: Vec::resize
875 /// [`extend`]: Extend::extend
876 /// [`clear`]: Vec::clear
880 /// - `new_len` must be less than or equal to [`capacity()`].
881 /// - The elements at `old_len..new_len` must be initialized.
883 /// [`capacity()`]: Vec::capacity
887 /// This method can be useful for situations in which the vector
888 /// is serving as a buffer for other code, particularly over FFI:
891 /// # #![allow(dead_code)]
892 /// # // This is just a minimal skeleton for the doc example;
893 /// # // don't use this as a starting point for a real library.
894 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
895 /// # const Z_OK: i32 = 0;
897 /// # fn deflateGetDictionary(
898 /// # strm: *mut std::ffi::c_void,
899 /// # dictionary: *mut u8,
900 /// # dictLength: *mut usize,
903 /// # impl StreamWrapper {
904 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
905 /// // Per the FFI method's docs, "32768 bytes is always enough".
906 /// let mut dict = Vec::with_capacity(32_768);
907 /// let mut dict_length = 0;
908 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
909 /// // 1. `dict_length` elements were initialized.
910 /// // 2. `dict_length` <= the capacity (32_768)
911 /// // which makes `set_len` safe to call.
913 /// // Make the FFI call...
914 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
916 /// // ...and update the length to what was initialized.
917 /// dict.set_len(dict_length);
927 /// While the following example is sound, there is a memory leak since
928 /// the inner vectors were not freed prior to the `set_len` call:
931 /// let mut vec = vec![vec![1, 0, 0],
935 /// // 1. `old_len..0` is empty so no elements need to be initialized.
936 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
942 /// Normally, here, one would use [`clear`] instead to correctly drop
943 /// the contents and thus not leak memory.
945 #[stable(feature = "rust1", since = "1.0.0")]
946 pub unsafe fn set_len(&mut self, new_len: usize) {
947 debug_assert!(new_len <= self.capacity());
952 /// Removes an element from the vector and returns it.
954 /// The removed element is replaced by the last element of the vector.
956 /// This does not preserve ordering, but is O(1).
960 /// Panics if `index` is out of bounds.
965 /// let mut v = vec!["foo", "bar", "baz", "qux"];
967 /// assert_eq!(v.swap_remove(1), "bar");
968 /// assert_eq!(v, ["foo", "qux", "baz"]);
970 /// assert_eq!(v.swap_remove(0), "foo");
971 /// assert_eq!(v, ["baz", "qux"]);
974 #[stable(feature = "rust1", since = "1.0.0")]
975 pub fn swap_remove(&mut self, index: usize) -> T {
978 fn assert_failed(index: usize, len: usize) -> ! {
979 panic!("swap_remove index (is {}) should be < len (is {})", index, len);
982 let len = self.len();
984 assert_failed(index, len);
987 // We replace self[index] with the last element. Note that if the
988 // bounds check above succeeds there must be a last element (which
989 // can be self[index] itself).
990 let last = ptr::read(self.as_ptr().add(len - 1));
991 let hole = self.as_mut_ptr().add(index);
992 self.set_len(len - 1);
993 ptr::replace(hole, last)
997 /// Inserts an element at position `index` within the vector, shifting all
998 /// elements after it to the right.
1002 /// Panics if `index > len`.
1007 /// let mut vec = vec![1, 2, 3];
1008 /// vec.insert(1, 4);
1009 /// assert_eq!(vec, [1, 4, 2, 3]);
1010 /// vec.insert(4, 5);
1011 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1013 #[stable(feature = "rust1", since = "1.0.0")]
1014 pub fn insert(&mut self, index: usize, element: T) {
1017 fn assert_failed(index: usize, len: usize) -> ! {
1018 panic!("insertion index (is {}) should be <= len (is {})", index, len);
1021 let len = self.len();
1023 assert_failed(index, len);
1026 // space for the new element
1027 if len == self.buf.capacity() {
1033 // The spot to put the new value
1035 let p = self.as_mut_ptr().add(index);
1036 // Shift everything over to make space. (Duplicating the
1037 // `index`th element into two consecutive places.)
1038 ptr::copy(p, p.offset(1), len - index);
1039 // Write it in, overwriting the first copy of the `index`th
1041 ptr::write(p, element);
1043 self.set_len(len + 1);
1047 /// Removes and returns the element at position `index` within the vector,
1048 /// shifting all elements after it to the left.
1052 /// Panics if `index` is out of bounds.
1057 /// let mut v = vec![1, 2, 3];
1058 /// assert_eq!(v.remove(1), 2);
1059 /// assert_eq!(v, [1, 3]);
1061 #[stable(feature = "rust1", since = "1.0.0")]
1062 pub fn remove(&mut self, index: usize) -> T {
1065 fn assert_failed(index: usize, len: usize) -> ! {
1066 panic!("removal index (is {}) should be < len (is {})", index, len);
1069 let len = self.len();
1071 assert_failed(index, len);
1077 // the place we are taking from.
1078 let ptr = self.as_mut_ptr().add(index);
1079 // copy it out, unsafely having a copy of the value on
1080 // the stack and in the vector at the same time.
1081 ret = ptr::read(ptr);
1083 // Shift everything down to fill in that spot.
1084 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1086 self.set_len(len - 1);
1091 /// Retains only the elements specified by the predicate.
1093 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1094 /// This method operates in place, visiting each element exactly once in the
1095 /// original order, and preserves the order of the retained elements.
1100 /// let mut vec = vec![1, 2, 3, 4];
1101 /// vec.retain(|&x| x % 2 == 0);
1102 /// assert_eq!(vec, [2, 4]);
1105 /// The exact order may be useful for tracking external state, like an index.
1108 /// let mut vec = vec![1, 2, 3, 4, 5];
1109 /// let keep = [false, true, true, false, true];
1111 /// vec.retain(|_| (keep[i], i += 1).0);
1112 /// assert_eq!(vec, [2, 3, 5]);
1114 #[stable(feature = "rust1", since = "1.0.0")]
1115 pub fn retain<F>(&mut self, mut f: F)
1117 F: FnMut(&T) -> bool,
1119 let len = self.len();
1122 let v = &mut **self;
1133 self.truncate(len - del);
1137 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1140 /// If the vector is sorted, this removes all duplicates.
1145 /// let mut vec = vec![10, 20, 21, 30, 20];
1147 /// vec.dedup_by_key(|i| *i / 10);
1149 /// assert_eq!(vec, [10, 20, 30, 20]);
1151 #[stable(feature = "dedup_by", since = "1.16.0")]
1153 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1155 F: FnMut(&mut T) -> K,
1158 self.dedup_by(|a, b| key(a) == key(b))
1161 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1164 /// The `same_bucket` function is passed references to two elements from the vector and
1165 /// must determine if the elements compare equal. The elements are passed in opposite order
1166 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1168 /// If the vector is sorted, this removes all duplicates.
1173 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1175 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1177 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1179 #[stable(feature = "dedup_by", since = "1.16.0")]
1180 pub fn dedup_by<F>(&mut self, same_bucket: F)
1182 F: FnMut(&mut T, &mut T) -> bool,
1185 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1191 /// Appends an element to the back of a collection.
1195 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1200 /// let mut vec = vec![1, 2];
1202 /// assert_eq!(vec, [1, 2, 3]);
1205 #[stable(feature = "rust1", since = "1.0.0")]
1206 pub fn push(&mut self, value: T) {
1207 // This will panic or abort if we would allocate > isize::MAX bytes
1208 // or if the length increment would overflow for zero-sized types.
1209 if self.len == self.buf.capacity() {
1213 let end = self.as_mut_ptr().add(self.len);
1214 ptr::write(end, value);
1219 /// Removes the last element from a vector and returns it, or [`None`] if it
1225 /// let mut vec = vec![1, 2, 3];
1226 /// assert_eq!(vec.pop(), Some(3));
1227 /// assert_eq!(vec, [1, 2]);
1230 #[stable(feature = "rust1", since = "1.0.0")]
1231 pub fn pop(&mut self) -> Option<T> {
1237 Some(ptr::read(self.as_ptr().add(self.len())))
1242 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1246 /// Panics if the number of elements in the vector overflows a `usize`.
1251 /// let mut vec = vec![1, 2, 3];
1252 /// let mut vec2 = vec![4, 5, 6];
1253 /// vec.append(&mut vec2);
1254 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1255 /// assert_eq!(vec2, []);
1258 #[stable(feature = "append", since = "1.4.0")]
1259 pub fn append(&mut self, other: &mut Self) {
1261 self.append_elements(other.as_slice() as _);
1266 /// Appends elements to `Self` from other buffer.
1268 unsafe fn append_elements(&mut self, other: *const [T]) {
1269 let count = unsafe { (*other).len() };
1270 self.reserve(count);
1271 let len = self.len();
1272 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1276 /// Creates a draining iterator that removes the specified range in the vector
1277 /// and yields the removed items.
1279 /// When the iterator **is** dropped, all elements in the range are removed
1280 /// from the vector, even if the iterator was not fully consumed. If the
1281 /// iterator **is not** dropped (with [`mem::forget`] for example), it is
1282 /// unspecified how many elements are removed.
1286 /// Panics if the starting point is greater than the end point or if
1287 /// the end point is greater than the length of the vector.
1292 /// let mut v = vec![1, 2, 3];
1293 /// let u: Vec<_> = v.drain(1..).collect();
1294 /// assert_eq!(v, &[1]);
1295 /// assert_eq!(u, &[2, 3]);
1297 /// // A full range clears the vector
1299 /// assert_eq!(v, &[]);
1301 #[stable(feature = "drain", since = "1.6.0")]
1302 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1304 R: RangeBounds<usize>,
1308 // When the Drain is first created, it shortens the length of
1309 // the source vector to make sure no uninitialized or moved-from elements
1310 // are accessible at all if the Drain's destructor never gets to run.
1312 // Drain will ptr::read out the values to remove.
1313 // When finished, remaining tail of the vec is copied back to cover
1314 // the hole, and the vector length is restored to the new length.
1316 let len = self.len();
1317 let Range { start, end } = range.assert_len(len);
1320 // set self.vec length's to start, to be safe in case Drain is leaked
1321 self.set_len(start);
1322 // Use the borrow in the IterMut to indicate borrowing behavior of the
1323 // whole Drain iterator (like &mut T).
1324 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1327 tail_len: len - end,
1328 iter: range_slice.iter(),
1329 vec: NonNull::from(self),
1334 /// Clears the vector, removing all values.
1336 /// Note that this method has no effect on the allocated capacity
1342 /// let mut v = vec![1, 2, 3];
1346 /// assert!(v.is_empty());
1349 #[stable(feature = "rust1", since = "1.0.0")]
1350 pub fn clear(&mut self) {
1354 /// Returns the number of elements in the vector, also referred to
1355 /// as its 'length'.
1360 /// let a = vec![1, 2, 3];
1361 /// assert_eq!(a.len(), 3);
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 pub fn len(&self) -> usize {
1369 /// Returns `true` if the vector contains no elements.
1374 /// let mut v = Vec::new();
1375 /// assert!(v.is_empty());
1378 /// assert!(!v.is_empty());
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 pub fn is_empty(&self) -> bool {
1385 /// Splits the collection into two at the given index.
1387 /// Returns a newly allocated vector containing the elements in the range
1388 /// `[at, len)`. After the call, the original vector will be left containing
1389 /// the elements `[0, at)` with its previous capacity unchanged.
1393 /// Panics if `at > len`.
1398 /// let mut vec = vec![1,2,3];
1399 /// let vec2 = vec.split_off(1);
1400 /// assert_eq!(vec, [1]);
1401 /// assert_eq!(vec2, [2, 3]);
1404 #[must_use = "use `.truncate()` if you don't need the other half"]
1405 #[stable(feature = "split_off", since = "1.4.0")]
1406 pub fn split_off(&mut self, at: usize) -> Self {
1409 fn assert_failed(at: usize, len: usize) -> ! {
1410 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1413 if at > self.len() {
1414 assert_failed(at, self.len());
1418 // the new vector can take over the original buffer and avoid the copy
1419 return mem::replace(self, Vec::with_capacity(self.capacity()));
1422 let other_len = self.len - at;
1423 let mut other = Vec::with_capacity(other_len);
1425 // Unsafely `set_len` and copy items to `other`.
1428 other.set_len(other_len);
1430 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1435 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1437 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1438 /// difference, with each additional slot filled with the result of
1439 /// calling the closure `f`. The return values from `f` will end up
1440 /// in the `Vec` in the order they have been generated.
1442 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1444 /// This method uses a closure to create new values on every push. If
1445 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
1446 /// want to use the [`Default`] trait to generate values, you can
1447 /// pass [`Default::default`] as the second argument.
1452 /// let mut vec = vec![1, 2, 3];
1453 /// vec.resize_with(5, Default::default);
1454 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1456 /// let mut vec = vec![];
1458 /// vec.resize_with(4, || { p *= 2; p });
1459 /// assert_eq!(vec, [2, 4, 8, 16]);
1461 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1462 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1466 let len = self.len();
1468 self.extend_with(new_len - len, ExtendFunc(f));
1470 self.truncate(new_len);
1474 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1475 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1476 /// `'a`. If the type has only static references, or none at all, then this
1477 /// may be chosen to be `'static`.
1479 /// This function is similar to the [`leak`][Box::leak] function on [`Box`]
1480 /// except that there is no way to recover the leaked memory.
1482 /// This function is mainly useful for data that lives for the remainder of
1483 /// the program's life. Dropping the returned reference will cause a memory
1491 /// let x = vec![1, 2, 3];
1492 /// let static_ref: &'static mut [usize] = x.leak();
1493 /// static_ref[0] += 1;
1494 /// assert_eq!(static_ref, &[2, 2, 3]);
1496 #[stable(feature = "vec_leak", since = "1.47.0")]
1498 pub fn leak<'a>(self) -> &'a mut [T]
1500 T: 'a, // Technically not needed, but kept to be explicit.
1502 Box::leak(self.into_boxed_slice())
1505 /// Returns the remaining spare capacity of the vector as a slice of
1506 /// `MaybeUninit<T>`.
1508 /// The returned slice can be used to fill the vector with data (e.g. by
1509 /// reading from a file) before marking the data as initialized using the
1510 /// [`set_len`] method.
1512 /// [`set_len`]: Vec::set_len
1517 /// #![feature(vec_spare_capacity, maybe_uninit_extra)]
1519 /// // Allocate vector big enough for 10 elements.
1520 /// let mut v = Vec::with_capacity(10);
1522 /// // Fill in the first 3 elements.
1523 /// let uninit = v.spare_capacity_mut();
1524 /// uninit[0].write(0);
1525 /// uninit[1].write(1);
1526 /// uninit[2].write(2);
1528 /// // Mark the first 3 elements of the vector as being initialized.
1533 /// assert_eq!(&v, &[0, 1, 2]);
1535 #[unstable(feature = "vec_spare_capacity", issue = "75017")]
1537 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1539 slice::from_raw_parts_mut(
1540 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
1541 self.buf.capacity() - self.len,
1547 impl<T: Clone> Vec<T> {
1548 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1550 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1551 /// difference, with each additional slot filled with `value`.
1552 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1554 /// This method requires `T` to implement [`Clone`],
1555 /// in order to be able to clone the passed value.
1556 /// If you need more flexibility (or want to rely on [`Default`] instead of
1557 /// [`Clone`]), use [`Vec::resize_with`].
1562 /// let mut vec = vec!["hello"];
1563 /// vec.resize(3, "world");
1564 /// assert_eq!(vec, ["hello", "world", "world"]);
1566 /// let mut vec = vec![1, 2, 3, 4];
1567 /// vec.resize(2, 0);
1568 /// assert_eq!(vec, [1, 2]);
1570 #[stable(feature = "vec_resize", since = "1.5.0")]
1571 pub fn resize(&mut self, new_len: usize, value: T) {
1572 let len = self.len();
1575 self.extend_with(new_len - len, ExtendElement(value))
1577 self.truncate(new_len);
1581 /// Clones and appends all elements in a slice to the `Vec`.
1583 /// Iterates over the slice `other`, clones each element, and then appends
1584 /// it to this `Vec`. The `other` vector is traversed in-order.
1586 /// Note that this function is same as [`extend`] except that it is
1587 /// specialized to work with slices instead. If and when Rust gets
1588 /// specialization this function will likely be deprecated (but still
1594 /// let mut vec = vec![1];
1595 /// vec.extend_from_slice(&[2, 3, 4]);
1596 /// assert_eq!(vec, [1, 2, 3, 4]);
1599 /// [`extend`]: Vec::extend
1600 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1601 pub fn extend_from_slice(&mut self, other: &[T]) {
1602 self.spec_extend(other.iter())
1606 // This code generalizes `extend_with_{element,default}`.
1607 trait ExtendWith<T> {
1608 fn next(&mut self) -> T;
1612 struct ExtendElement<T>(T);
1613 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1614 fn next(&mut self) -> T {
1617 fn last(self) -> T {
1622 struct ExtendDefault;
1623 impl<T: Default> ExtendWith<T> for ExtendDefault {
1624 fn next(&mut self) -> T {
1627 fn last(self) -> T {
1632 struct ExtendFunc<F>(F);
1633 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1634 fn next(&mut self) -> T {
1637 fn last(mut self) -> T {
1643 /// Extend the vector by `n` values, using the given generator.
1644 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1648 let mut ptr = self.as_mut_ptr().add(self.len());
1649 // Use SetLenOnDrop to work around bug where compiler
1650 // may not realize the store through `ptr` through self.set_len()
1652 let mut local_len = SetLenOnDrop::new(&mut self.len);
1654 // Write all elements except the last one
1656 ptr::write(ptr, value.next());
1657 ptr = ptr.offset(1);
1658 // Increment the length in every step in case next() panics
1659 local_len.increment_len(1);
1663 // We can write the last element directly without cloning needlessly
1664 ptr::write(ptr, value.last());
1665 local_len.increment_len(1);
1668 // len set by scope guard
1673 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1675 // The idea is: The length field in SetLenOnDrop is a local variable
1676 // that the optimizer will see does not alias with any stores through the Vec's data
1677 // pointer. This is a workaround for alias analysis issue #32155
1678 struct SetLenOnDrop<'a> {
1683 impl<'a> SetLenOnDrop<'a> {
1685 fn new(len: &'a mut usize) -> Self {
1686 SetLenOnDrop { local_len: *len, len }
1690 fn increment_len(&mut self, increment: usize) {
1691 self.local_len += increment;
1695 impl Drop for SetLenOnDrop<'_> {
1697 fn drop(&mut self) {
1698 *self.len = self.local_len;
1702 impl<T: PartialEq> Vec<T> {
1703 /// Removes consecutive repeated elements in the vector according to the
1704 /// [`PartialEq`] trait implementation.
1706 /// If the vector is sorted, this removes all duplicates.
1711 /// let mut vec = vec![1, 2, 2, 3, 2];
1715 /// assert_eq!(vec, [1, 2, 3, 2]);
1717 #[stable(feature = "rust1", since = "1.0.0")]
1719 pub fn dedup(&mut self) {
1720 self.dedup_by(|a, b| a == b)
1725 /// Removes the first instance of `item` from the vector if the item exists.
1727 /// This method will be removed soon.
1728 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1730 reason = "Removing the first item equal to a needle is already easily possible \
1731 with iterators and the current Vec methods. Furthermore, having a method for \
1732 one particular case of removal (linear search, only the first item, no swap remove) \
1733 but not for others is inconsistent. This method will be removed soon.",
1736 pub fn remove_item<V>(&mut self, item: &V) -> Option<T>
1740 let pos = self.iter().position(|x| *x == *item)?;
1741 Some(self.remove(pos))
1745 ////////////////////////////////////////////////////////////////////////////////
1746 // Internal methods and functions
1747 ////////////////////////////////////////////////////////////////////////////////
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1752 <T as SpecFromElem>::from_elem(elem, n)
1755 // Specialization trait used for Vec::from_elem
1756 trait SpecFromElem: Sized {
1757 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1760 impl<T: Clone> SpecFromElem for T {
1761 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1762 let mut v = Vec::with_capacity(n);
1763 v.extend_with(n, ExtendElement(elem));
1768 impl SpecFromElem for i8 {
1770 fn from_elem(elem: i8, n: usize) -> Vec<i8> {
1772 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1775 let mut v = Vec::with_capacity(n);
1776 ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
1783 impl SpecFromElem for u8 {
1785 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1787 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1790 let mut v = Vec::with_capacity(n);
1791 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1798 impl<T: Clone + IsZero> SpecFromElem for T {
1800 fn from_elem(elem: T, n: usize) -> Vec<T> {
1802 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1804 let mut v = Vec::with_capacity(n);
1805 v.extend_with(n, ExtendElement(elem));
1810 #[rustc_specialization_trait]
1811 unsafe trait IsZero {
1812 /// Whether this value is zero
1813 fn is_zero(&self) -> bool;
1816 macro_rules! impl_is_zero {
1817 ($t:ty, $is_zero:expr) => {
1818 unsafe impl IsZero for $t {
1820 fn is_zero(&self) -> bool {
1827 impl_is_zero!(i16, |x| x == 0);
1828 impl_is_zero!(i32, |x| x == 0);
1829 impl_is_zero!(i64, |x| x == 0);
1830 impl_is_zero!(i128, |x| x == 0);
1831 impl_is_zero!(isize, |x| x == 0);
1833 impl_is_zero!(u16, |x| x == 0);
1834 impl_is_zero!(u32, |x| x == 0);
1835 impl_is_zero!(u64, |x| x == 0);
1836 impl_is_zero!(u128, |x| x == 0);
1837 impl_is_zero!(usize, |x| x == 0);
1839 impl_is_zero!(bool, |x| x == false);
1840 impl_is_zero!(char, |x| x == '\0');
1842 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1843 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1845 unsafe impl<T> IsZero for *const T {
1847 fn is_zero(&self) -> bool {
1852 unsafe impl<T> IsZero for *mut T {
1854 fn is_zero(&self) -> bool {
1859 // `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
1860 // For fat pointers, the bytes that would be the pointer metadata in the `Some`
1861 // variant are padding in the `None` variant, so ignoring them and
1862 // zero-initializing instead is ok.
1863 // `Option<&mut T>` never implements `Clone`, so there's no need for an impl of
1866 unsafe impl<T: ?Sized> IsZero for Option<&T> {
1868 fn is_zero(&self) -> bool {
1873 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
1875 fn is_zero(&self) -> bool {
1880 ////////////////////////////////////////////////////////////////////////////////
1881 // Common trait implementations for Vec
1882 ////////////////////////////////////////////////////////////////////////////////
1884 #[stable(feature = "rust1", since = "1.0.0")]
1885 impl<T> ops::Deref for Vec<T> {
1888 fn deref(&self) -> &[T] {
1889 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 impl<T> ops::DerefMut for Vec<T> {
1895 fn deref_mut(&mut self) -> &mut [T] {
1896 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 impl<T: Clone> Clone for Vec<T> {
1903 fn clone(&self) -> Vec<T> {
1904 <[T]>::to_vec(&**self)
1907 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1908 // required for this method definition, is not available. Instead use the
1909 // `slice::to_vec` function which is only available with cfg(test)
1910 // NB see the slice::hack module in slice.rs for more information
1912 fn clone(&self) -> Vec<T> {
1913 crate::slice::to_vec(&**self)
1916 fn clone_from(&mut self, other: &Vec<T>) {
1917 other.as_slice().clone_into(self);
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl<T: Hash> Hash for Vec<T> {
1924 fn hash<H: Hasher>(&self, state: &mut H) {
1925 Hash::hash(&**self, state)
1929 #[stable(feature = "rust1", since = "1.0.0")]
1930 #[rustc_on_unimplemented(
1931 message = "vector indices are of type `usize` or ranges of `usize`",
1932 label = "vector indices are of type `usize` or ranges of `usize`"
1934 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
1935 type Output = I::Output;
1938 fn index(&self, index: I) -> &Self::Output {
1939 Index::index(&**self, index)
1943 #[stable(feature = "rust1", since = "1.0.0")]
1944 #[rustc_on_unimplemented(
1945 message = "vector indices are of type `usize` or ranges of `usize`",
1946 label = "vector indices are of type `usize` or ranges of `usize`"
1948 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
1950 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1951 IndexMut::index_mut(&mut **self, index)
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 impl<T> FromIterator<T> for Vec<T> {
1958 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1959 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
1963 #[stable(feature = "rust1", since = "1.0.0")]
1964 impl<T> IntoIterator for Vec<T> {
1966 type IntoIter = IntoIter<T>;
1968 /// Creates a consuming iterator, that is, one that moves each value out of
1969 /// the vector (from start to end). The vector cannot be used after calling
1975 /// let v = vec!["a".to_string(), "b".to_string()];
1976 /// for s in v.into_iter() {
1977 /// // s has type String, not &String
1978 /// println!("{}", s);
1982 fn into_iter(self) -> IntoIter<T> {
1984 let mut me = ManuallyDrop::new(self);
1985 let begin = me.as_mut_ptr();
1986 let end = if mem::size_of::<T>() == 0 {
1987 arith_offset(begin as *const i8, me.len() as isize) as *const T
1989 begin.add(me.len()) as *const T
1991 let cap = me.buf.capacity();
1993 buf: NonNull::new_unchecked(begin),
1994 phantom: PhantomData,
2003 #[stable(feature = "rust1", since = "1.0.0")]
2004 impl<'a, T> IntoIterator for &'a Vec<T> {
2006 type IntoIter = slice::Iter<'a, T>;
2008 fn into_iter(self) -> slice::Iter<'a, T> {
2013 #[stable(feature = "rust1", since = "1.0.0")]
2014 impl<'a, T> IntoIterator for &'a mut Vec<T> {
2015 type Item = &'a mut T;
2016 type IntoIter = slice::IterMut<'a, T>;
2018 fn into_iter(self) -> slice::IterMut<'a, T> {
2023 #[stable(feature = "rust1", since = "1.0.0")]
2024 impl<T> Extend<T> for Vec<T> {
2026 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2027 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2031 fn extend_one(&mut self, item: T) {
2036 fn extend_reserve(&mut self, additional: usize) {
2037 self.reserve(additional);
2041 /// Specialization trait used for Vec::from_iter
2043 /// ## The delegation graph:
2051 /// +-+-------------------------------+ +---------------------+
2052 /// |SpecFromIter +---->+SpecFromIterNested |
2053 /// |where I: | | |where I: |
2054 /// | Iterator (default)----------+ | | Iterator (default) |
2055 /// | vec::IntoIter | | | TrustedLen |
2056 /// | SourceIterMarker---fallback-+ | | |
2057 /// | slice::Iter | | |
2058 /// | Iterator<Item = &Clone> | +---------------------+
2059 /// +---------------------------------+
2061 trait SpecFromIter<T, I> {
2062 fn from_iter(iter: I) -> Self;
2065 /// Another specialization trait for Vec::from_iter
2066 /// necessary to manually prioritize overlapping specializations
2067 /// see [`SpecFromIter`] for details.
2068 trait SpecFromIterNested<T, I> {
2069 fn from_iter(iter: I) -> Self;
2072 impl<T, I> SpecFromIterNested<T, I> for Vec<T>
2074 I: Iterator<Item = T>,
2076 default fn from_iter(mut iterator: I) -> Self {
2077 // Unroll the first iteration, as the vector is going to be
2078 // expanded on this iteration in every case when the iterable is not
2079 // empty, but the loop in extend_desugared() is not going to see the
2080 // vector being full in the few subsequent loop iterations.
2081 // So we get better branch prediction.
2082 let mut vector = match iterator.next() {
2083 None => return Vec::new(),
2085 let (lower, _) = iterator.size_hint();
2086 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2088 ptr::write(vector.as_mut_ptr(), element);
2094 // must delegate to spec_extend() since extend() itself delegates
2095 // to spec_from for empty Vecs
2096 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2101 impl<T, I> SpecFromIterNested<T, I> for Vec<T>
2103 I: TrustedLen<Item = T>,
2105 fn from_iter(iterator: I) -> Self {
2106 let mut vector = Vec::new();
2107 // must delegate to spec_extend() since extend() itself delegates
2108 // to spec_from for empty Vecs
2109 vector.spec_extend(iterator);
2114 impl<T, I> SpecFromIter<T, I> for Vec<T>
2116 I: Iterator<Item = T>,
2118 default fn from_iter(iterator: I) -> Self {
2119 SpecFromIterNested::from_iter(iterator)
2123 // A helper struct for in-place iteration that drops the destination slice of iteration,
2124 // i.e. the head. The source slice (the tail) is dropped by IntoIter.
2125 struct InPlaceDrop<T> {
2130 impl<T> InPlaceDrop<T> {
2131 fn len(&self) -> usize {
2132 unsafe { self.dst.offset_from(self.inner) as usize }
2136 impl<T> Drop for InPlaceDrop<T> {
2138 fn drop(&mut self) {
2139 if mem::needs_drop::<T>() {
2141 ptr::drop_in_place(slice::from_raw_parts_mut(self.inner, self.len()));
2147 impl<T> SpecFromIter<T, IntoIter<T>> for Vec<T> {
2148 fn from_iter(iterator: IntoIter<T>) -> Self {
2149 // A common case is passing a vector into a function which immediately
2150 // re-collects into a vector. We can short circuit this if the IntoIter
2151 // has not been advanced at all.
2152 // When it has been advanced We can also reuse the memory and move the data to the front.
2153 // But we only do so when the resulting Vec wouldn't have more unused capacity
2154 // than creating it through the generic FromIterator implementation would. That limitation
2155 // is not strictly necessary as Vec's allocation behavior is intentionally unspecified.
2156 // But it is a conservative choice.
2157 let has_advanced = iterator.buf.as_ptr() as *const _ != iterator.ptr;
2158 if !has_advanced || iterator.len() >= iterator.cap / 2 {
2160 let it = ManuallyDrop::new(iterator);
2162 ptr::copy(it.ptr, it.buf.as_ptr(), it.len());
2164 return Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap);
2168 let mut vec = Vec::new();
2169 // must delegate to spec_extend() since extend() itself delegates
2170 // to spec_from for empty Vecs
2171 vec.spec_extend(iterator);
2176 fn write_in_place_with_drop<T>(
2178 ) -> impl FnMut(InPlaceDrop<T>, T) -> Result<InPlaceDrop<T>, !> {
2179 move |mut sink, item| {
2181 // the InPlaceIterable contract cannot be verified precisely here since
2182 // try_fold has an exclusive reference to the source pointer
2183 // all we can do is check if it's still in range
2184 debug_assert!(sink.dst as *const _ <= src_end, "InPlaceIterable contract violation");
2185 ptr::write(sink.dst, item);
2186 sink.dst = sink.dst.add(1);
2192 /// Specialization marker for collecting an iterator pipeline into a Vec while reusing the
2193 /// source allocation, i.e. executing the pipeline in place.
2195 /// The SourceIter parent trait is necessary for the specializing function to access the allocation
2196 /// which is to be reused. But it is not sufficient for the specialization to be valid. See
2197 /// additional bounds on the impl.
2198 #[rustc_unsafe_specialization_marker]
2199 trait SourceIterMarker: SourceIter<Source: AsIntoIter> {}
2201 // The std-internal SourceIter/InPlaceIterable traits are only implemented by chains of
2202 // Adapter<Adapter<Adapter<IntoIter>>> (all owned by core/std). Additional bounds
2203 // on the adapter implementations (beyond `impl<I: Trait> Trait for Adapter<I>`) only depend on other
2204 // traits already marked as specialization traits (Copy, TrustedRandomAccess, FusedIterator).
2205 // I.e. the marker does not depend on lifetimes of user-supplied types. Modulo the Copy hole, which
2206 // several other specializations already depend on.
2207 impl<T> SourceIterMarker for T where T: SourceIter<Source: AsIntoIter> + InPlaceIterable {}
2209 impl<T, I> SpecFromIter<T, I> for Vec<T>
2211 I: Iterator<Item = T> + SourceIterMarker,
2213 default fn from_iter(mut iterator: I) -> Self {
2214 // Additional requirements which cannot expressed via trait bounds. We rely on const eval
2216 // a) no ZSTs as there would be no allocation to reuse and pointer arithmetic would panic
2217 // b) size match as required by Alloc contract
2218 // c) alignments match as required by Alloc contract
2219 if mem::size_of::<T>() == 0
2220 || mem::size_of::<T>()
2221 != mem::size_of::<<<I as SourceIter>::Source as AsIntoIter>::Item>()
2222 || mem::align_of::<T>()
2223 != mem::align_of::<<<I as SourceIter>::Source as AsIntoIter>::Item>()
2225 // fallback to more generic implementations
2226 return SpecFromIterNested::from_iter(iterator);
2229 let (src_buf, src_ptr, dst_buf, dst_end, cap) = unsafe {
2230 let inner = iterator.as_inner().as_into_iter();
2234 inner.buf.as_ptr() as *mut T,
2235 inner.end as *const T,
2240 // use try-fold since
2241 // - it vectorizes better for some iterator adapters
2242 // - unlike most internal iteration methods, it only takes a &mut self
2243 // - it lets us thread the write pointer through its innards and get it back in the end
2244 let sink = InPlaceDrop { inner: dst_buf, dst: dst_buf };
2246 .try_fold::<_, _, Result<_, !>>(sink, write_in_place_with_drop(dst_end))
2248 // iteration succeeded, don't drop head
2249 let dst = ManuallyDrop::new(sink).dst;
2251 let src = unsafe { iterator.as_inner().as_into_iter() };
2252 // check if SourceIter contract was upheld
2253 // caveat: if they weren't we may not even make it to this point
2254 debug_assert_eq!(src_buf, src.buf.as_ptr());
2255 // check InPlaceIterable contract. This is only possible if the iterator advanced the
2256 // source pointer at all. If it uses unchecked access via TrustedRandomAccess
2257 // then the source pointer will stay in its initial position and we can't use it as reference
2258 if src.ptr != src_ptr {
2260 dst as *const _ <= src.ptr,
2261 "InPlaceIterable contract violation, write pointer advanced beyond read pointer"
2265 // drop any remaining values at the tail of the source
2266 src.drop_remaining();
2267 // but prevent drop of the allocation itself once IntoIter goes out of scope
2268 src.forget_allocation();
2271 let len = dst.offset_from(dst_buf) as usize;
2272 Vec::from_raw_parts(dst_buf, len, cap)
2279 impl<'a, T: 'a, I> SpecFromIter<&'a T, I> for Vec<T>
2281 I: Iterator<Item = &'a T>,
2284 default fn from_iter(iterator: I) -> Self {
2285 SpecFromIter::from_iter(iterator.cloned())
2289 impl<'a, T: 'a> SpecFromIter<&'a T, slice::Iter<'a, T>> for Vec<T>
2293 // reuses the extend specialization for T: Copy
2294 fn from_iter(iterator: slice::Iter<'a, T>) -> Self {
2295 let mut vec = Vec::new();
2296 // must delegate to spec_extend() since extend() itself delegates
2297 // to spec_from for empty Vecs
2298 vec.spec_extend(iterator);
2303 // Specialization trait used for Vec::extend
2304 trait SpecExtend<T, I> {
2305 fn spec_extend(&mut self, iter: I);
2308 impl<T, I> SpecExtend<T, I> for Vec<T>
2310 I: Iterator<Item = T>,
2312 default fn spec_extend(&mut self, iter: I) {
2313 self.extend_desugared(iter)
2317 impl<T, I> SpecExtend<T, I> for Vec<T>
2319 I: TrustedLen<Item = T>,
2321 default fn spec_extend(&mut self, iterator: I) {
2322 // This is the case for a TrustedLen iterator.
2323 let (low, high) = iterator.size_hint();
2324 if let Some(high_value) = high {
2328 "TrustedLen iterator's size hint is not exact: {:?}",
2332 if let Some(additional) = high {
2333 self.reserve(additional);
2335 let mut ptr = self.as_mut_ptr().add(self.len());
2336 let mut local_len = SetLenOnDrop::new(&mut self.len);
2337 iterator.for_each(move |element| {
2338 ptr::write(ptr, element);
2339 ptr = ptr.offset(1);
2340 // NB can't overflow since we would have had to alloc the address space
2341 local_len.increment_len(1);
2345 self.extend_desugared(iterator)
2350 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2351 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2353 self.append_elements(iterator.as_slice() as _);
2355 iterator.ptr = iterator.end;
2359 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2361 I: Iterator<Item = &'a T>,
2364 default fn spec_extend(&mut self, iterator: I) {
2365 self.spec_extend(iterator.cloned())
2369 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2373 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2374 let slice = iterator.as_slice();
2375 unsafe { self.append_elements(slice) };
2380 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2381 // they have no further optimizations to apply
2382 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2383 // This is the case for a general iterator.
2385 // This function should be the moral equivalent of:
2387 // for item in iterator {
2390 while let Some(element) = iterator.next() {
2391 let len = self.len();
2392 if len == self.capacity() {
2393 let (lower, _) = iterator.size_hint();
2394 self.reserve(lower.saturating_add(1));
2397 ptr::write(self.as_mut_ptr().add(len), element);
2398 // NB can't overflow since we would have had to alloc the address space
2399 self.set_len(len + 1);
2404 /// Creates a splicing iterator that replaces the specified range in the vector
2405 /// with the given `replace_with` iterator and yields the removed items.
2406 /// `replace_with` does not need to be the same length as `range`.
2408 /// `range` is removed even if the iterator is not consumed until the end.
2410 /// It is unspecified how many elements are removed from the vector
2411 /// if the `Splice` value is leaked.
2413 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2415 /// This is optimal if:
2417 /// * The tail (elements in the vector after `range`) is empty,
2418 /// * or `replace_with` yields fewer elements than `range`’s length
2419 /// * or the lower bound of its `size_hint()` is exact.
2421 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2425 /// Panics if the starting point is greater than the end point or if
2426 /// the end point is greater than the length of the vector.
2431 /// let mut v = vec![1, 2, 3];
2432 /// let new = [7, 8];
2433 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2434 /// assert_eq!(v, &[7, 8, 3]);
2435 /// assert_eq!(u, &[1, 2]);
2438 #[stable(feature = "vec_splice", since = "1.21.0")]
2439 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2441 R: RangeBounds<usize>,
2442 I: IntoIterator<Item = T>,
2444 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2447 /// Creates an iterator which uses a closure to determine if an element should be removed.
2449 /// If the closure returns true, then the element is removed and yielded.
2450 /// If the closure returns false, the element will remain in the vector and will not be yielded
2451 /// by the iterator.
2453 /// Using this method is equivalent to the following code:
2456 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2457 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2459 /// while i != vec.len() {
2460 /// if some_predicate(&mut vec[i]) {
2461 /// let val = vec.remove(i);
2462 /// // your code here
2468 /// # assert_eq!(vec, vec![1, 4, 5]);
2471 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2472 /// because it can backshift the elements of the array in bulk.
2474 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2475 /// regardless of whether you choose to keep or remove it.
2479 /// Splitting an array into evens and odds, reusing the original allocation:
2482 /// #![feature(drain_filter)]
2483 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2485 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2486 /// let odds = numbers;
2488 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2489 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2491 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2492 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2494 F: FnMut(&mut T) -> bool,
2496 let old_len = self.len();
2498 // Guard against us getting leaked (leak amplification)
2503 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2507 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2509 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2510 /// append the entire slice at once.
2512 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2513 #[stable(feature = "extend_ref", since = "1.2.0")]
2514 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2515 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2516 self.spec_extend(iter.into_iter())
2520 fn extend_one(&mut self, &item: &'a T) {
2525 fn extend_reserve(&mut self, additional: usize) {
2526 self.reserve(additional);
2530 macro_rules! __impl_slice_eq1 {
2531 ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => {
2533 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2539 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2541 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2546 __impl_slice_eq1! { [] Vec<A>, Vec<B>, #[stable(feature = "rust1", since = "1.0.0")] }
2547 __impl_slice_eq1! { [] Vec<A>, &[B], #[stable(feature = "rust1", since = "1.0.0")] }
2548 __impl_slice_eq1! { [] Vec<A>, &mut [B], #[stable(feature = "rust1", since = "1.0.0")] }
2549 __impl_slice_eq1! { [] &[A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2550 __impl_slice_eq1! { [] &mut [A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2551 __impl_slice_eq1! { [] Vec<A>, [B], #[stable(feature = "partialeq_vec_for_slice", since = "1.48.0")] }
2552 __impl_slice_eq1! { [] [A], Vec<B>, #[stable(feature = "partialeq_vec_for_slice", since = "1.48.0")] }
2553 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B> where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2554 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2555 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2556 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2557 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2559 // NOTE: some less important impls are omitted to reduce code bloat
2560 // FIXME(Centril): Reconsider this?
2561 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], }
2562 //__impl_slice_eq1! { [const N: usize] [A; N], Vec<B>, }
2563 //__impl_slice_eq1! { [const N: usize] &[A; N], Vec<B>, }
2564 //__impl_slice_eq1! { [const N: usize] &mut [A; N], Vec<B>, }
2565 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], }
2566 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], }
2567 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], }
2569 /// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2570 #[stable(feature = "rust1", since = "1.0.0")]
2571 impl<T: PartialOrd> PartialOrd for Vec<T> {
2573 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2574 PartialOrd::partial_cmp(&**self, &**other)
2578 #[stable(feature = "rust1", since = "1.0.0")]
2579 impl<T: Eq> Eq for Vec<T> {}
2581 /// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2582 #[stable(feature = "rust1", since = "1.0.0")]
2583 impl<T: Ord> Ord for Vec<T> {
2585 fn cmp(&self, other: &Vec<T>) -> Ordering {
2586 Ord::cmp(&**self, &**other)
2590 #[stable(feature = "rust1", since = "1.0.0")]
2591 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2592 fn drop(&mut self) {
2595 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2596 // could avoid questions of validity in certain cases
2597 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2599 // RawVec handles deallocation
2603 #[stable(feature = "rust1", since = "1.0.0")]
2604 impl<T> Default for Vec<T> {
2605 /// Creates an empty `Vec<T>`.
2606 fn default() -> Vec<T> {
2611 #[stable(feature = "rust1", since = "1.0.0")]
2612 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2613 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2614 fmt::Debug::fmt(&**self, f)
2618 #[stable(feature = "rust1", since = "1.0.0")]
2619 impl<T> AsRef<Vec<T>> for Vec<T> {
2620 fn as_ref(&self) -> &Vec<T> {
2625 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2626 impl<T> AsMut<Vec<T>> for Vec<T> {
2627 fn as_mut(&mut self) -> &mut Vec<T> {
2632 #[stable(feature = "rust1", since = "1.0.0")]
2633 impl<T> AsRef<[T]> for Vec<T> {
2634 fn as_ref(&self) -> &[T] {
2639 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2640 impl<T> AsMut<[T]> for Vec<T> {
2641 fn as_mut(&mut self) -> &mut [T] {
2646 #[stable(feature = "rust1", since = "1.0.0")]
2647 impl<T: Clone> From<&[T]> for Vec<T> {
2649 fn from(s: &[T]) -> Vec<T> {
2653 fn from(s: &[T]) -> Vec<T> {
2654 crate::slice::to_vec(s)
2658 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2659 impl<T: Clone> From<&mut [T]> for Vec<T> {
2661 fn from(s: &mut [T]) -> Vec<T> {
2665 fn from(s: &mut [T]) -> Vec<T> {
2666 crate::slice::to_vec(s)
2670 #[stable(feature = "vec_from_array", since = "1.44.0")]
2671 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2673 fn from(s: [T; N]) -> Vec<T> {
2674 <[T]>::into_vec(box s)
2677 fn from(s: [T; N]) -> Vec<T> {
2678 crate::slice::into_vec(box s)
2682 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2683 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2685 [T]: ToOwned<Owned = Vec<T>>,
2687 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2692 // note: test pulls in libstd, which causes errors here
2694 #[stable(feature = "vec_from_box", since = "1.18.0")]
2695 impl<T> From<Box<[T]>> for Vec<T> {
2696 fn from(s: Box<[T]>) -> Vec<T> {
2701 // note: test pulls in libstd, which causes errors here
2703 #[stable(feature = "box_from_vec", since = "1.20.0")]
2704 impl<T> From<Vec<T>> for Box<[T]> {
2705 fn from(v: Vec<T>) -> Box<[T]> {
2706 v.into_boxed_slice()
2710 #[stable(feature = "rust1", since = "1.0.0")]
2711 impl From<&str> for Vec<u8> {
2712 fn from(s: &str) -> Vec<u8> {
2713 From::from(s.as_bytes())
2717 #[stable(feature = "array_try_from_vec", since = "1.48.0")]
2718 impl<T, const N: usize> TryFrom<Vec<T>> for [T; N] {
2719 type Error = Vec<T>;
2721 /// Gets the entire contents of the `Vec<T>` as an array,
2722 /// if its size exactly matches that of the requested array.
2727 /// use std::convert::TryInto;
2728 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
2729 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
2732 /// If the length doesn't match, the input comes back in `Err`:
2734 /// use std::convert::TryInto;
2735 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
2736 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
2739 /// If you're fine with just getting a prefix of the `Vec<T>`,
2740 /// you can call [`.truncate(N)`](Vec::truncate) first.
2742 /// use std::convert::TryInto;
2743 /// let mut v = String::from("hello world").into_bytes();
2746 /// let [a, b]: [_; 2] = v.try_into().unwrap();
2747 /// assert_eq!(a, b' ');
2748 /// assert_eq!(b, b'd');
2750 fn try_from(mut vec: Vec<T>) -> Result<[T; N], Vec<T>> {
2755 // SAFETY: `.set_len(0)` is always sound.
2756 unsafe { vec.set_len(0) };
2758 // SAFETY: A `Vec`'s pointer is always aligned properly, and
2759 // the alignment the array needs is the same as the items.
2760 // We checked earlier that we have sufficient items.
2761 // The items will not double-drop as the `set_len`
2762 // tells the `Vec` not to also drop them.
2763 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
2768 ////////////////////////////////////////////////////////////////////////////////
2770 ////////////////////////////////////////////////////////////////////////////////
2772 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2773 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2774 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2779 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2780 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2781 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2786 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2787 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2788 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2789 Cow::Borrowed(v.as_slice())
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
2798 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2799 Cow::Owned(FromIterator::from_iter(it))
2803 ////////////////////////////////////////////////////////////////////////////////
2805 ////////////////////////////////////////////////////////////////////////////////
2807 /// An iterator that moves out of a vector.
2809 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
2810 /// by the [`IntoIterator`] trait).
2815 /// let v = vec![0, 1, 2];
2816 /// let iter: std::vec::IntoIter<_> = v.into_iter();
2818 #[stable(feature = "rust1", since = "1.0.0")]
2819 pub struct IntoIter<T> {
2821 phantom: PhantomData<T>,
2827 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2828 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2829 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2830 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2834 impl<T> IntoIter<T> {
2835 /// Returns the remaining items of this iterator as a slice.
2840 /// let vec = vec!['a', 'b', 'c'];
2841 /// let mut into_iter = vec.into_iter();
2842 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2843 /// let _ = into_iter.next().unwrap();
2844 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2846 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2847 pub fn as_slice(&self) -> &[T] {
2848 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
2851 /// Returns the remaining items of this iterator as a mutable slice.
2856 /// let vec = vec!['a', 'b', 'c'];
2857 /// let mut into_iter = vec.into_iter();
2858 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2859 /// into_iter.as_mut_slice()[2] = 'z';
2860 /// assert_eq!(into_iter.next().unwrap(), 'a');
2861 /// assert_eq!(into_iter.next().unwrap(), 'b');
2862 /// assert_eq!(into_iter.next().unwrap(), 'z');
2864 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2865 pub fn as_mut_slice(&mut self) -> &mut [T] {
2866 unsafe { &mut *self.as_raw_mut_slice() }
2869 fn as_raw_mut_slice(&mut self) -> *mut [T] {
2870 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
2873 fn drop_remaining(&mut self) {
2874 if mem::needs_drop::<T>() {
2876 ptr::drop_in_place(self.as_mut_slice());
2879 self.ptr = self.end;
2882 /// Relinquishes the backing allocation, equivalent to
2883 /// `ptr::write(&mut self, Vec::new().into_iter())`
2884 fn forget_allocation(&mut self) {
2886 self.buf = unsafe { NonNull::new_unchecked(RawVec::NEW.ptr()) };
2887 self.ptr = self.buf.as_ptr();
2888 self.end = self.buf.as_ptr();
2892 #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
2893 impl<T> AsRef<[T]> for IntoIter<T> {
2894 fn as_ref(&self) -> &[T] {
2899 #[stable(feature = "rust1", since = "1.0.0")]
2900 unsafe impl<T: Send> Send for IntoIter<T> {}
2901 #[stable(feature = "rust1", since = "1.0.0")]
2902 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2904 #[stable(feature = "rust1", since = "1.0.0")]
2905 impl<T> Iterator for IntoIter<T> {
2909 fn next(&mut self) -> Option<T> {
2910 if self.ptr as *const _ == self.end {
2912 } else if mem::size_of::<T>() == 0 {
2913 // purposefully don't use 'ptr.offset' because for
2914 // vectors with 0-size elements this would return the
2916 self.ptr = unsafe { arith_offset(self.ptr as *const i8, 1) as *mut T };
2918 // Make up a value of this ZST.
2919 Some(unsafe { mem::zeroed() })
2922 self.ptr = unsafe { self.ptr.offset(1) };
2924 Some(unsafe { ptr::read(old) })
2929 fn size_hint(&self) -> (usize, Option<usize>) {
2930 let exact = if mem::size_of::<T>() == 0 {
2931 (self.end as usize).wrapping_sub(self.ptr as usize)
2933 unsafe { self.end.offset_from(self.ptr) as usize }
2935 (exact, Some(exact))
2939 fn count(self) -> usize {
2943 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item
2945 Self: TrustedRandomAccess,
2947 // SAFETY: the caller must guarantee that `i` is in bounds of the
2948 // `Vec<T>`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)`
2949 // is guaranteed to pointer to an element of the `Vec<T>` and
2950 // thus guaranteed to be valid to dereference.
2952 // Also note the implementation of `Self: TrustedRandomAccess` requires
2953 // that `T: Copy` so reading elements from the buffer doesn't invalidate
2956 if mem::size_of::<T>() == 0 { mem::zeroed() } else { ptr::read(self.ptr.add(i)) }
2961 #[stable(feature = "rust1", since = "1.0.0")]
2962 impl<T> DoubleEndedIterator for IntoIter<T> {
2964 fn next_back(&mut self) -> Option<T> {
2965 if self.end == self.ptr {
2967 } else if mem::size_of::<T>() == 0 {
2968 // See above for why 'ptr.offset' isn't used
2969 self.end = unsafe { arith_offset(self.end as *const i8, -1) as *mut T };
2971 // Make up a value of this ZST.
2972 Some(unsafe { mem::zeroed() })
2974 self.end = unsafe { self.end.offset(-1) };
2976 Some(unsafe { ptr::read(self.end) })
2981 #[stable(feature = "rust1", since = "1.0.0")]
2982 impl<T> ExactSizeIterator for IntoIter<T> {
2983 fn is_empty(&self) -> bool {
2984 self.ptr == self.end
2988 #[stable(feature = "fused", since = "1.26.0")]
2989 impl<T> FusedIterator for IntoIter<T> {}
2991 #[unstable(feature = "trusted_len", issue = "37572")]
2992 unsafe impl<T> TrustedLen for IntoIter<T> {}
2995 #[unstable(issue = "none", feature = "std_internals")]
2996 // T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr
2997 // and thus we can't implement drop-handling
2998 unsafe impl<T> TrustedRandomAccess for IntoIter<T>
3002 fn may_have_side_effect() -> bool {
3007 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
3008 impl<T: Clone> Clone for IntoIter<T> {
3009 fn clone(&self) -> IntoIter<T> {
3010 self.as_slice().to_owned().into_iter()
3014 #[stable(feature = "rust1", since = "1.0.0")]
3015 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
3016 fn drop(&mut self) {
3017 struct DropGuard<'a, T>(&'a mut IntoIter<T>);
3019 impl<T> Drop for DropGuard<'_, T> {
3020 fn drop(&mut self) {
3021 // RawVec handles deallocation
3022 let _ = unsafe { RawVec::from_raw_parts(self.0.buf.as_ptr(), self.0.cap) };
3026 let guard = DropGuard(self);
3027 // destroy the remaining elements
3029 ptr::drop_in_place(guard.0.as_raw_mut_slice());
3031 // now `guard` will be dropped and do the rest
3035 #[unstable(issue = "none", feature = "inplace_iteration")]
3036 unsafe impl<T> InPlaceIterable for IntoIter<T> {}
3038 #[unstable(issue = "none", feature = "inplace_iteration")]
3039 unsafe impl<T> SourceIter for IntoIter<T> {
3040 type Source = IntoIter<T>;
3043 unsafe fn as_inner(&mut self) -> &mut Self::Source {
3048 // internal helper trait for in-place iteration specialization.
3049 #[rustc_specialization_trait]
3050 pub(crate) trait AsIntoIter {
3052 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item>;
3055 impl<T> AsIntoIter for IntoIter<T> {
3058 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item> {
3063 /// A draining iterator for `Vec<T>`.
3065 /// This `struct` is created by [`Vec::drain`].
3066 /// See its documentation for more.
3071 /// let mut v = vec![0, 1, 2];
3072 /// let iter: std::vec::Drain<_> = v.drain(..);
3074 #[stable(feature = "drain", since = "1.6.0")]
3075 pub struct Drain<'a, T: 'a> {
3076 /// Index of tail to preserve
3080 /// Current remaining range to remove
3081 iter: slice::Iter<'a, T>,
3082 vec: NonNull<Vec<T>>,
3085 #[stable(feature = "collection_debug", since = "1.17.0")]
3086 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
3087 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3088 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
3092 impl<'a, T> Drain<'a, T> {
3093 /// Returns the remaining items of this iterator as a slice.
3098 /// let mut vec = vec!['a', 'b', 'c'];
3099 /// let mut drain = vec.drain(..);
3100 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
3101 /// let _ = drain.next().unwrap();
3102 /// assert_eq!(drain.as_slice(), &['b', 'c']);
3104 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3105 pub fn as_slice(&self) -> &[T] {
3106 self.iter.as_slice()
3110 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3111 impl<'a, T> AsRef<[T]> for Drain<'a, T> {
3112 fn as_ref(&self) -> &[T] {
3117 #[stable(feature = "drain", since = "1.6.0")]
3118 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
3119 #[stable(feature = "drain", since = "1.6.0")]
3120 unsafe impl<T: Send> Send for Drain<'_, T> {}
3122 #[stable(feature = "drain", since = "1.6.0")]
3123 impl<T> Iterator for Drain<'_, T> {
3127 fn next(&mut self) -> Option<T> {
3128 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
3131 fn size_hint(&self) -> (usize, Option<usize>) {
3132 self.iter.size_hint()
3136 #[stable(feature = "drain", since = "1.6.0")]
3137 impl<T> DoubleEndedIterator for Drain<'_, T> {
3139 fn next_back(&mut self) -> Option<T> {
3140 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
3144 #[stable(feature = "drain", since = "1.6.0")]
3145 impl<T> Drop for Drain<'_, T> {
3146 fn drop(&mut self) {
3147 /// Continues dropping the remaining elements in the `Drain`, then moves back the
3148 /// un-`Drain`ed elements to restore the original `Vec`.
3149 struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>);
3151 impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> {
3152 fn drop(&mut self) {
3153 // Continue the same loop we have below. If the loop already finished, this does
3155 self.0.for_each(drop);
3157 if self.0.tail_len > 0 {
3159 let source_vec = self.0.vec.as_mut();
3160 // memmove back untouched tail, update to new length
3161 let start = source_vec.len();
3162 let tail = self.0.tail_start;
3164 let src = source_vec.as_ptr().add(tail);
3165 let dst = source_vec.as_mut_ptr().add(start);
3166 ptr::copy(src, dst, self.0.tail_len);
3168 source_vec.set_len(start + self.0.tail_len);
3174 // exhaust self first
3175 while let Some(item) = self.next() {
3176 let guard = DropGuard(self);
3181 // Drop a `DropGuard` to move back the non-drained tail of `self`.
3186 #[stable(feature = "drain", since = "1.6.0")]
3187 impl<T> ExactSizeIterator for Drain<'_, T> {
3188 fn is_empty(&self) -> bool {
3189 self.iter.is_empty()
3193 #[unstable(feature = "trusted_len", issue = "37572")]
3194 unsafe impl<T> TrustedLen for Drain<'_, T> {}
3196 #[stable(feature = "fused", since = "1.26.0")]
3197 impl<T> FusedIterator for Drain<'_, T> {}
3199 /// A splicing iterator for `Vec`.
3201 /// This struct is created by [`Vec::splice()`].
3202 /// See its documentation for more.
3207 /// let mut v = vec![0, 1, 2];
3208 /// let new = [7, 8];
3209 /// let iter: std::vec::Splice<_> = v.splice(1.., new.iter().cloned());
3212 #[stable(feature = "vec_splice", since = "1.21.0")]
3213 pub struct Splice<'a, I: Iterator + 'a> {
3214 drain: Drain<'a, I::Item>,
3218 #[stable(feature = "vec_splice", since = "1.21.0")]
3219 impl<I: Iterator> Iterator for Splice<'_, I> {
3220 type Item = I::Item;
3222 fn next(&mut self) -> Option<Self::Item> {
3226 fn size_hint(&self) -> (usize, Option<usize>) {
3227 self.drain.size_hint()
3231 #[stable(feature = "vec_splice", since = "1.21.0")]
3232 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
3233 fn next_back(&mut self) -> Option<Self::Item> {
3234 self.drain.next_back()
3238 #[stable(feature = "vec_splice", since = "1.21.0")]
3239 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
3241 #[stable(feature = "vec_splice", since = "1.21.0")]
3242 impl<I: Iterator> Drop for Splice<'_, I> {
3243 fn drop(&mut self) {
3244 self.drain.by_ref().for_each(drop);
3247 if self.drain.tail_len == 0 {
3248 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
3252 // First fill the range left by drain().
3253 if !self.drain.fill(&mut self.replace_with) {
3257 // There may be more elements. Use the lower bound as an estimate.
3258 // FIXME: Is the upper bound a better guess? Or something else?
3259 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
3260 if lower_bound > 0 {
3261 self.drain.move_tail(lower_bound);
3262 if !self.drain.fill(&mut self.replace_with) {
3267 // Collect any remaining elements.
3268 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
3269 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
3270 // Now we have an exact count.
3271 if collected.len() > 0 {
3272 self.drain.move_tail(collected.len());
3273 let filled = self.drain.fill(&mut collected);
3274 debug_assert!(filled);
3275 debug_assert_eq!(collected.len(), 0);
3278 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
3282 /// Private helper methods for `Splice::drop`
3283 impl<T> Drain<'_, T> {
3284 /// The range from `self.vec.len` to `self.tail_start` contains elements
3285 /// that have been moved out.
3286 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
3287 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
3288 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
3289 let vec = unsafe { self.vec.as_mut() };
3290 let range_start = vec.len;
3291 let range_end = self.tail_start;
3292 let range_slice = unsafe {
3293 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
3296 for place in range_slice {
3297 if let Some(new_item) = replace_with.next() {
3298 unsafe { ptr::write(place, new_item) };
3307 /// Makes room for inserting more elements before the tail.
3308 unsafe fn move_tail(&mut self, additional: usize) {
3309 let vec = unsafe { self.vec.as_mut() };
3310 let len = self.tail_start + self.tail_len;
3311 vec.buf.reserve(len, additional);
3313 let new_tail_start = self.tail_start + additional;
3315 let src = vec.as_ptr().add(self.tail_start);
3316 let dst = vec.as_mut_ptr().add(new_tail_start);
3317 ptr::copy(src, dst, self.tail_len);
3319 self.tail_start = new_tail_start;
3323 /// An iterator which uses a closure to determine if an element should be removed.
3325 /// This struct is created by [`Vec::drain_filter`].
3326 /// See its documentation for more.
3331 /// #![feature(drain_filter)]
3333 /// let mut v = vec![0, 1, 2];
3334 /// let iter: std::vec::DrainFilter<_, _> = v.drain_filter(|x| *x % 2 == 0);
3336 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3338 pub struct DrainFilter<'a, T, F>
3340 F: FnMut(&mut T) -> bool,
3342 vec: &'a mut Vec<T>,
3343 /// The index of the item that will be inspected by the next call to `next`.
3345 /// The number of items that have been drained (removed) thus far.
3347 /// The original length of `vec` prior to draining.
3349 /// The filter test predicate.
3351 /// A flag that indicates a panic has occurred in the filter test predicate.
3352 /// This is used as a hint in the drop implementation to prevent consumption
3353 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3354 /// backshifted in the `vec`, but no further items will be dropped or
3355 /// tested by the filter predicate.
3359 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3360 impl<T, F> Iterator for DrainFilter<'_, T, F>
3362 F: FnMut(&mut T) -> bool,
3366 fn next(&mut self) -> Option<T> {
3368 while self.idx < self.old_len {
3370 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3371 self.panic_flag = true;
3372 let drained = (self.pred)(&mut v[i]);
3373 self.panic_flag = false;
3374 // Update the index *after* the predicate is called. If the index
3375 // is updated prior and the predicate panics, the element at this
3376 // index would be leaked.
3380 return Some(ptr::read(&v[i]));
3381 } else if self.del > 0 {
3383 let src: *const T = &v[i];
3384 let dst: *mut T = &mut v[i - del];
3385 ptr::copy_nonoverlapping(src, dst, 1);
3392 fn size_hint(&self) -> (usize, Option<usize>) {
3393 (0, Some(self.old_len - self.idx))
3397 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3398 impl<T, F> Drop for DrainFilter<'_, T, F>
3400 F: FnMut(&mut T) -> bool,
3402 fn drop(&mut self) {
3403 struct BackshiftOnDrop<'a, 'b, T, F>
3405 F: FnMut(&mut T) -> bool,
3407 drain: &'b mut DrainFilter<'a, T, F>,
3410 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
3412 F: FnMut(&mut T) -> bool,
3414 fn drop(&mut self) {
3416 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3417 // This is a pretty messed up state, and there isn't really an
3418 // obviously right thing to do. We don't want to keep trying
3419 // to execute `pred`, so we just backshift all the unprocessed
3420 // elements and tell the vec that they still exist. The backshift
3421 // is required to prevent a double-drop of the last successfully
3422 // drained item prior to a panic in the predicate.
3423 let ptr = self.drain.vec.as_mut_ptr();
3424 let src = ptr.add(self.drain.idx);
3425 let dst = src.sub(self.drain.del);
3426 let tail_len = self.drain.old_len - self.drain.idx;
3427 src.copy_to(dst, tail_len);
3429 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3434 let backshift = BackshiftOnDrop { drain: self };
3436 // Attempt to consume any remaining elements if the filter predicate
3437 // has not yet panicked. We'll backshift any remaining elements
3438 // whether we've already panicked or if the consumption here panics.
3439 if !backshift.drain.panic_flag {
3440 backshift.drain.for_each(drop);