Skip to main content

alloc/vec/
mod.rs

1//! A contiguous growable array type with heap-allocated contents, written
2//! `Vec<T>`.
3//!
4//! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and
5//! *O*(1) pop (from the end).
6//!
7//! Vectors ensure they never allocate more than `isize::MAX` bytes.
8//!
9//! # Examples
10//!
11//! You can explicitly create a [`Vec`] with [`Vec::new`]:
12//!
13//! ```
14//! let v: Vec<i32> = Vec::new();
15//! ```
16//!
17//! ...or by using the [`vec!`] macro:
18//!
19//! ```
20//! let v: Vec<i32> = vec![];
21//!
22//! let v = vec![1, 2, 3, 4, 5];
23//!
24//! let v = vec![0; 10]; // ten zeroes
25//! ```
26//!
27//! You can [`push`] values onto the end of a vector (which will grow the vector
28//! as needed):
29//!
30//! ```
31//! let mut v = vec![1, 2];
32//!
33//! v.push(3);
34//! ```
35//!
36//! Popping values works in much the same way:
37//!
38//! ```
39//! let mut v = vec![1, 2];
40//!
41//! let two = v.pop();
42//! ```
43//!
44//! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
45//!
46//! ```
47//! let mut v = vec![1, 2, 3];
48//! let three = v[2];
49//! v[1] = v[1] + 5;
50//! ```
51//!
52//! # Memory layout
53//!
54//! When the type is non-zero-sized and the capacity is nonzero, [`Vec`] uses the [`Global`]
55//! allocator for its allocation. It is valid to convert both ways between such a [`Vec`] and a raw
56//! pointer allocated with the [`Global`] allocator, provided that the [`Layout`] used with the
57//! allocator is correct for a sequence of `capacity` elements of the type, and the first `len`
58//! values pointed to by the raw pointer are valid. More precisely, a `ptr: *mut T` that has been
59//! allocated with the [`Global`] allocator with [`Layout::array::<T>(capacity)`][Layout::array] may
60//! be converted into a vec using
61//! [`Vec::<T>::from_raw_parts(ptr, len, capacity)`](Vec::from_raw_parts). Conversely, the memory
62//! backing a `value: *mut T` obtained from [`Vec::<T>::as_mut_ptr`] may be deallocated using the
63//! [`Global`] allocator with the same layout.
64//!
65//! For zero-sized types (ZSTs), or when the capacity is zero, the `Vec` pointer must be non-null
66//! and sufficiently aligned. The recommended way to build a `Vec` of ZSTs if [`vec!`] cannot be
67//! used is to use [`ptr::NonNull::dangling`].
68//!
69//! [`push`]: Vec::push
70//! [`ptr::NonNull::dangling`]: NonNull::dangling
71//! [`Layout`]: crate::alloc::Layout
72//! [Layout::array]: crate::alloc::Layout::array
73
74#![stable(feature = "rust1", since = "1.0.0")]
75
76#[cfg(not(no_global_oom_handling))]
77use core::clone::TrivialClone;
78use core::cmp::Ordering;
79use core::hash::{Hash, Hasher};
80#[cfg(not(no_global_oom_handling))]
81use core::iter;
82use core::marker::{Destruct, Freeze, PhantomData};
83use core::mem::{self, Assume, ManuallyDrop, MaybeUninit, SizedTypeProperties, TransmuteFrom};
84use core::ops::{self, Index, IndexMut, Range, RangeBounds};
85use core::ptr::{self, NonNull};
86use core::slice::{self, SliceIndex};
87use core::{cmp, fmt, hint, intrinsics, ub_checks};
88
89#[stable(feature = "extract_if", since = "1.87.0")]
90pub use self::extract_if::ExtractIf;
91use crate::alloc::{Allocator, AllocatorNightly, Global};
92use crate::borrow::{Cow, ToOwned};
93use crate::boxed::Box;
94use crate::collections::TryReserveError;
95use crate::raw_vec::RawVec;
96
97mod extract_if;
98
99#[cfg(not(no_global_oom_handling))]
100#[stable(feature = "vec_splice", since = "1.21.0")]
101pub use self::splice::Splice;
102
103#[cfg(not(no_global_oom_handling))]
104mod splice;
105
106#[stable(feature = "drain", since = "1.6.0")]
107pub use self::drain::Drain;
108
109mod drain;
110
111#[cfg(not(no_global_oom_handling))]
112mod cow;
113
114#[cfg(not(no_global_oom_handling))]
115pub(crate) use self::in_place_collect::AsVecIntoIter;
116#[stable(feature = "rust1", since = "1.0.0")]
117pub use self::into_iter::IntoIter;
118
119mod into_iter;
120
121#[cfg(not(no_global_oom_handling))]
122use self::is_zero::IsZero;
123
124#[cfg(not(no_global_oom_handling))]
125mod is_zero;
126
127#[cfg(not(no_global_oom_handling))]
128mod in_place_collect;
129
130mod partial_eq;
131
132#[unstable(feature = "vec_peek_mut", issue = "122742")]
133pub use self::peek_mut::PeekMut;
134
135mod peek_mut;
136
137#[cfg(not(no_global_oom_handling))]
138use self::spec_from_elem::SpecFromElem;
139
140#[cfg(not(no_global_oom_handling))]
141mod spec_from_elem;
142
143#[cfg(not(no_global_oom_handling))]
144use self::set_len_on_drop::SetLenOnDrop;
145
146#[cfg(not(no_global_oom_handling))]
147mod set_len_on_drop;
148
149#[cfg(not(no_global_oom_handling))]
150use self::in_place_drop::{InPlaceDrop, InPlaceDstDataSrcBufDrop};
151
152#[cfg(not(no_global_oom_handling))]
153mod in_place_drop;
154
155#[cfg(not(no_global_oom_handling))]
156use self::spec_from_iter_nested::SpecFromIterNested;
157
158#[cfg(not(no_global_oom_handling))]
159mod spec_from_iter_nested;
160
161#[cfg(not(no_global_oom_handling))]
162use self::spec_from_iter::SpecFromIter;
163
164#[cfg(not(no_global_oom_handling))]
165mod spec_from_iter;
166
167#[cfg(not(no_global_oom_handling))]
168use self::spec_extend::SpecExtend;
169
170#[cfg(not(no_global_oom_handling))]
171mod spec_extend;
172
173#[cfg(all(target_arch = "aarch64", target_feature = "sve"))]
174mod sve_retain;
175
176/// A contiguous growable array type, written as `Vec<T>`, short for 'vector'.
177///
178/// # Examples
179///
180/// ```
181/// let mut vec = Vec::new();
182/// vec.push(1);
183/// vec.push(2);
184///
185/// assert_eq!(vec.len(), 2);
186/// assert_eq!(vec[0], 1);
187///
188/// assert_eq!(vec.pop(), Some(2));
189/// assert_eq!(vec.len(), 1);
190///
191/// vec[0] = 7;
192/// assert_eq!(vec[0], 7);
193///
194/// vec.extend([1, 2, 3]);
195///
196/// for x in &vec {
197///     println!("{x}");
198/// }
199/// assert_eq!(vec, [7, 1, 2, 3]);
200/// ```
201///
202/// The [`vec!`] macro is provided for convenient initialization:
203///
204/// ```
205/// let mut vec1 = vec![1, 2, 3];
206/// vec1.push(4);
207/// let vec2 = Vec::from([1, 2, 3, 4]);
208/// assert_eq!(vec1, vec2);
209/// ```
210///
211/// It can also initialize each element of a `Vec<T>` with a given value.
212/// This may be more efficient than performing allocation and initialization
213/// in separate steps, especially when initializing a vector of zeros:
214///
215/// ```
216/// let vec = vec![0; 5];
217/// assert_eq!(vec, [0, 0, 0, 0, 0]);
218///
219/// // The following is equivalent, but potentially slower:
220/// let mut vec = Vec::with_capacity(5);
221/// vec.resize(5, 0);
222/// assert_eq!(vec, [0, 0, 0, 0, 0]);
223/// ```
224///
225/// For more information, see
226/// [Capacity and Reallocation](#capacity-and-reallocation).
227///
228/// Use a `Vec<T>` as an efficient stack:
229///
230/// ```
231/// let mut stack = Vec::new();
232///
233/// stack.push(1);
234/// stack.push(2);
235/// stack.push(3);
236///
237/// while let Some(top) = stack.pop() {
238///     // Prints 3, 2, 1
239///     println!("{top}");
240/// }
241/// ```
242///
243/// # Indexing
244///
245/// The `Vec` type allows access to values by index, because it implements the
246/// [`Index`] trait. An example will be more explicit:
247///
248/// ```
249/// let v = vec![0, 2, 4, 6];
250/// println!("{}", v[1]); // it will display '2'
251/// ```
252///
253/// However be careful: if you try to access an index which isn't in the `Vec`,
254/// your software will panic! You cannot do this:
255///
256/// ```should_panic
257/// let v = vec![0, 2, 4, 6];
258/// println!("{}", v[6]); // it will panic!
259/// ```
260///
261/// Use [`get`] and [`get_mut`] if you want to check whether the index is in
262/// the `Vec`.
263///
264/// # Slicing
265///
266/// A `Vec` can be mutable. On the other hand, slices are read-only objects.
267/// To get a [slice][prim@slice], use [`&`]. Example:
268///
269/// ```
270/// fn read_slice(slice: &[usize]) {
271///     // ...
272/// }
273///
274/// let v = vec![0, 1];
275/// read_slice(&v);
276///
277/// // ... and that's all!
278/// // you can also do it like this:
279/// let u: &[usize] = &v;
280/// // or like this:
281/// let u: &[_] = &v;
282/// ```
283///
284/// In Rust, it's more common to pass slices as arguments rather than vectors
285/// when you just want to provide read access. The same goes for [`String`] and
286/// [`&str`].
287///
288/// # Capacity and reallocation
289///
290/// The capacity of a vector is the amount of space allocated for any future
291/// elements that will be added onto the vector. This is not to be confused with
292/// the *length* of a vector, which specifies the number of actual elements
293/// within the vector. If a vector's length exceeds its capacity, its capacity
294/// will automatically be increased, but its elements will have to be
295/// reallocated.
296///
297/// For example, a vector with capacity 10 and length 0 would be an empty vector
298/// with space for 10 more elements. Pushing 10 or fewer elements onto the
299/// vector will not change its capacity or cause reallocation to occur. However,
300/// if the vector's length is increased to 11, it will have to reallocate, which
301/// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
302/// whenever possible to specify how big the vector is expected to get.
303///
304/// # Guarantees
305///
306/// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
307/// about its design. This ensures that it's as low-overhead as possible in
308/// the general case, and can be correctly manipulated in primitive ways
309/// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
310/// If additional type parameters are added (e.g., to support custom allocators),
311/// overriding their defaults may change the behavior.
312///
313/// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
314/// triplet. No more, no less. The order of these fields is completely
315/// unspecified, and you should use the appropriate methods to modify these.
316/// The pointer will never be null, so this type is null-pointer-optimized.
317///
318/// However, the pointer might not actually point to allocated memory. In particular,
319/// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
320/// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
321/// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
322/// types inside a `Vec`, it will not allocate space for them. *Note that in this case
323/// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only
324/// if <code>[size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation
325/// details are very subtle --- if you intend to allocate memory using a `Vec`
326/// and use it for something else (either to pass to unsafe code, or to build your
327/// own memory-backed collection), be sure to deallocate this memory by using
328/// `from_raw_parts` to recover the `Vec` and then dropping it.
329///
330/// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
331/// (as defined by the allocator Rust is configured to use by default), and its
332/// pointer points to [`len`] initialized, contiguous elements in order (what
333/// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>
334/// logically uninitialized, contiguous elements.
335///
336/// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
337/// visualized as below. The top part is the `Vec` struct, it contains a
338/// pointer to the head of the allocation in the heap, length and capacity.
339/// The bottom part is the allocation on the heap, a contiguous memory block.
340///
341/// ```text
342///             ptr      len  capacity
343///        +--------+--------+--------+
344///        | 0x0123 |      2 |      4 |
345///        +--------+--------+--------+
346///             |
347///             v
348/// Heap   +--------+--------+--------+--------+
349///        |    'a' |    'b' | uninit | uninit |
350///        +--------+--------+--------+--------+
351/// ```
352///
353/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
354/// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
355///   layout (including the order of fields).
356///
357/// `Vec` will never perform a "small optimization" where elements are actually
358/// stored on the stack for two reasons:
359///
360/// * It would make it more difficult for unsafe code to correctly manipulate
361///   a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
362///   only moved, and it would be more difficult to determine if a `Vec` had
363///   actually allocated memory.
364///
365/// * It would penalize the general case, incurring an additional branch
366///   on every access.
367///
368/// `Vec` will never automatically shrink itself, even if completely empty. This
369/// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
370/// and then filling it back up to the same [`len`] should incur no calls to
371/// the allocator. If you wish to free up unused memory, use
372/// [`shrink_to_fit`] or [`shrink_to`].
373///
374/// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
375/// sufficient. [`push`] and [`insert`] *will* (re)allocate if
376/// <code>[len] == [capacity]</code>. That is, the reported capacity is completely
377/// accurate, and can be relied on. It can even be used to manually free the memory
378/// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
379/// when not necessary.
380///
381/// `Vec` does not guarantee any particular growth strategy when reallocating
382/// when full, nor when [`reserve`] is called. The current strategy is basic
383/// and it may prove desirable to use a non-constant growth factor. Whatever
384/// strategy is used will of course guarantee *O*(1) amortized [`push`].
385///
386/// It is guaranteed, in order to respect the intentions of the programmer, that
387/// all of `vec![e_1, e_2, ..., e_n]`, `vec![x; n]`, and [`Vec::with_capacity(n)`] produce a `Vec`
388/// that requests an allocation of the exact size needed for precisely `n` elements from the allocator,
389/// and no other size (such as, for example: a size rounded up to the nearest power of 2).
390/// The allocator will return an allocation that is at least as large as requested, but it may be larger.
391///
392/// It is guaranteed that the [`Vec::capacity`] method returns a value that is at least the requested capacity
393/// and not more than the allocated capacity.
394///
395/// The method [`Vec::shrink_to_fit`] will attempt to discard excess capacity an allocator has given to a `Vec`.
396/// If <code>[len] == [capacity]</code>, then a `Vec<T>` can be converted
397/// to and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
398/// `Vec` exploits this fact as much as reasonable when implementing common conversions
399/// such as [`into_boxed_slice`].
400///
401/// `Vec` will not specifically overwrite any data that is removed from it,
402/// but also won't specifically preserve it. Its uninitialized memory is
403/// scratch space that it may use however it wants. It will generally just do
404/// whatever is most efficient or otherwise easy to implement. Do not rely on
405/// removed data to be erased for security purposes. Even if you drop a `Vec`, its
406/// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory
407/// first, that might not actually happen because the optimizer does not consider
408/// this a side-effect that must be preserved. There is one case which we will
409/// not break, however: using `unsafe` code to write to the excess capacity,
410/// and then increasing the length to match, is always valid.
411///
412/// Currently, `Vec` does not guarantee the order in which elements are dropped.
413/// The order has changed in the past and may change again.
414///
415/// [`get`]: slice::get
416/// [`get_mut`]: slice::get_mut
417/// [`String`]: crate::string::String
418/// [`&str`]: type@str
419/// [`shrink_to_fit`]: Vec::shrink_to_fit
420/// [`shrink_to`]: Vec::shrink_to
421/// [capacity]: Vec::capacity
422/// [`capacity`]: Vec::capacity
423/// [`Vec::capacity`]: Vec::capacity
424/// [size_of::\<T>]: size_of
425/// [len]: Vec::len
426/// [`len`]: Vec::len
427/// [`push`]: Vec::push
428/// [`insert`]: Vec::insert
429/// [`reserve`]: Vec::reserve
430/// [`Vec::with_capacity(n)`]: Vec::with_capacity
431/// [`MaybeUninit`]: core::mem::MaybeUninit
432/// [owned slice]: Box
433/// [`into_boxed_slice`]: Vec::into_boxed_slice
434#[stable(feature = "rust1", since = "1.0.0")]
435#[rustc_diagnostic_item = "Vec"]
436#[rustc_insignificant_dtor]
437#[doc(alias = "list")]
438#[doc(alias = "vector")]
439pub struct Vec<
440    T,
441    #[stable(feature = "allocator_api", since = "CURRENT_RUSTC_VERSION")] A: Allocator = Global,
442> {
443    buf: RawVec<T, A>,
444    len: usize,
445}
446
447////////////////////////////////////////////////////////////////////////////////
448// Inherent methods
449////////////////////////////////////////////////////////////////////////////////
450
451impl<T> Vec<T> {
452    /// Constructs a new, empty `Vec<T>`.
453    ///
454    /// The vector will not allocate until elements are pushed onto it.
455    ///
456    /// # Examples
457    ///
458    /// ```
459    /// # #![allow(unused_mut)]
460    /// let mut vec: Vec<i32> = Vec::new();
461    /// ```
462    #[inline]
463    #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
464    #[rustc_diagnostic_item = "vec_new"]
465    #[stable(feature = "rust1", since = "1.0.0")]
466    #[must_use]
467    pub const fn new() -> Self {
468        Vec { buf: RawVec::new(), len: 0 }
469    }
470
471    /// Constructs a new, empty `Vec<T>` with at least the specified capacity.
472    ///
473    /// The vector will be able to hold at least `capacity` elements without
474    /// reallocating. This method is allowed to allocate for more elements than
475    /// `capacity`. If `capacity` is zero, the vector will not allocate.
476    ///
477    /// It is important to note that although the returned vector has the
478    /// minimum *capacity* specified, the vector will have a zero *length*. For
479    /// an explanation of the difference between length and capacity, see
480    /// *[Capacity and reallocation]*.
481    ///
482    /// If it is important to know the exact allocated capacity of a `Vec`,
483    /// always use the [`capacity`] method after construction.
484    ///
485    /// For `Vec<T>` where `T` is a zero-sized type, there will be no allocation
486    /// and the capacity will always be `usize::MAX`.
487    ///
488    /// [Capacity and reallocation]: #capacity-and-reallocation
489    /// [`capacity`]: Vec::capacity
490    ///
491    /// # Panics
492    ///
493    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
494    ///
495    /// # Examples
496    ///
497    /// ```
498    /// let mut vec = Vec::with_capacity(10);
499    ///
500    /// // The vector contains no items, even though it has capacity for more
501    /// assert_eq!(vec.len(), 0);
502    /// assert!(vec.capacity() >= 10);
503    ///
504    /// // These are all done without reallocating...
505    /// for i in 0..10 {
506    ///     vec.push(i);
507    /// }
508    /// assert_eq!(vec.len(), 10);
509    /// assert!(vec.capacity() >= 10);
510    ///
511    /// // ...but this may make the vector reallocate
512    /// vec.push(11);
513    /// assert_eq!(vec.len(), 11);
514    /// assert!(vec.capacity() >= 11);
515    ///
516    /// // A vector of a zero-sized type will always over-allocate, since no
517    /// // allocation is necessary
518    /// let vec_units = Vec::<()>::with_capacity(10);
519    /// assert_eq!(vec_units.capacity(), usize::MAX);
520    /// ```
521    #[cfg(not(no_global_oom_handling))]
522    #[inline]
523    #[stable(feature = "rust1", since = "1.0.0")]
524    #[must_use]
525    #[rustc_diagnostic_item = "vec_with_capacity"]
526    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
527    pub const fn with_capacity(capacity: usize) -> Self {
528        Self::with_capacity_in(capacity, Global)
529    }
530
531    /// Constructs a new, empty `Vec<T>` with at least the specified capacity.
532    ///
533    /// The vector will be able to hold at least `capacity` elements without
534    /// reallocating. This method is allowed to allocate for more elements than
535    /// `capacity`. If `capacity` is zero, the vector will not allocate.
536    ///
537    /// # Errors
538    ///
539    /// Returns an error if the capacity exceeds `isize::MAX` _bytes_,
540    /// or if the allocator reports allocation failure.
541    #[inline]
542    #[unstable(feature = "try_with_capacity", issue = "91913")]
543    pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> {
544        Self::try_with_capacity_in(capacity, Global)
545    }
546
547    /// Creates a `Vec<T>` directly from a pointer, a length, and a capacity.
548    ///
549    /// # Safety
550    ///
551    /// This is highly unsafe, due to the number of invariants that aren't
552    /// checked:
553    ///
554    /// * If `T` is not a zero-sized type and the capacity is nonzero, `ptr` must have
555    ///   been allocated using the global allocator, such as via the [`alloc::alloc`]
556    ///   function. If `T` is a zero-sized type or the capacity is zero, `ptr` need
557    ///   only be non-null and aligned.
558    /// * `T` needs to have the same alignment as what `ptr` was allocated with,
559    ///   if the pointer is required to be allocated.
560    ///   (`T` having a less strict alignment is not sufficient, the alignment really
561    ///   needs to be equal to satisfy the [`dealloc`] requirement that memory must be
562    ///   allocated and deallocated with the same layout.)
563    /// * The size of `T` times the `capacity` (i.e. the allocated size in bytes), if
564    ///   nonzero, needs to be the same size as the pointer was allocated with.
565    ///   (Because similar to alignment, [`dealloc`] must be called with the same
566    ///   layout `size`.)
567    /// * `length` needs to be less than or equal to `capacity`.
568    /// * The first `length` values must be properly initialized values of type `T`.
569    /// * `capacity` needs to be the capacity that the pointer was allocated with,
570    ///   if the pointer is required to be allocated.
571    /// * The allocated size in bytes must be no larger than `isize::MAX`.
572    ///   See the safety documentation of [`pointer::offset`].
573    ///
574    /// These requirements are always upheld by any `ptr` that has been allocated
575    /// via `Vec<T>`. Other allocation sources are allowed if the invariants are
576    /// upheld.
577    ///
578    /// Violating these may cause problems like corrupting the allocator's
579    /// internal data structures. For example it is normally **not** safe
580    /// to build a `Vec<u8>` from a pointer to a C `char` array with length
581    /// `size_t`, doing so is only safe if the array was initially allocated by
582    /// a `Vec` or `String`.
583    /// It's also not safe to build one from a `Vec<u16>` and its length, because
584    /// the allocator cares about the alignment, and these two types have different
585    /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
586    /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
587    /// these issues, it is often preferable to do casting/transmuting using
588    /// [`slice::from_raw_parts`] instead.
589    ///
590    /// The ownership of `ptr` is effectively transferred to the
591    /// `Vec<T>` which may then deallocate, reallocate or change the
592    /// contents of memory pointed to by the pointer at will. Ensure
593    /// that nothing else uses the pointer after calling this
594    /// function.
595    ///
596    /// [`String`]: crate::string::String
597    /// [`alloc::alloc`]: crate::alloc::alloc
598    /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
599    ///
600    /// # Examples
601    ///
602    /// ```
603    /// use std::ptr;
604    ///
605    /// let v = vec![1, 2, 3];
606    ///
607    /// // Deconstruct the vector into parts.
608    /// let (p, len, cap) = v.into_raw_parts();
609    ///
610    /// unsafe {
611    ///     // Overwrite memory with 4, 5, 6
612    ///     for i in 0..len {
613    ///         ptr::write(p.add(i), 4 + i);
614    ///     }
615    ///
616    ///     // Put everything back together into a Vec
617    ///     let rebuilt = Vec::from_raw_parts(p, len, cap);
618    ///     assert_eq!(rebuilt, [4, 5, 6]);
619    /// }
620    /// ```
621    ///
622    /// Using memory that was allocated elsewhere:
623    ///
624    /// ```rust
625    /// use std::alloc::{alloc, Layout};
626    ///
627    /// fn main() {
628    ///     let layout = Layout::array::<u32>(16).expect("16 u32s take 64 bytes, so it shouldn't overflow");
629    ///
630    ///     let vec = unsafe {
631    ///         let mem = alloc(layout).cast::<u32>();
632    ///         if mem.is_null() {
633    ///             return;
634    ///         }
635    ///
636    ///         mem.write(1_000_000);
637    ///
638    ///         Vec::from_raw_parts(mem, 1, 16)
639    ///     };
640    ///
641    ///     assert_eq!(vec, &[1_000_000]);
642    ///     assert_eq!(vec.capacity(), 16);
643    /// }
644    /// ```
645    #[inline]
646    #[stable(feature = "rust1", since = "1.0.0")]
647    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
648    pub const unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
649        // SAFETY: Upheld by caller.
650        unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
651    }
652
653    #[doc(alias = "from_non_null_parts")]
654    /// Creates a `Vec<T>` directly from a `NonNull` pointer, a length, and a capacity.
655    ///
656    /// # Safety
657    ///
658    /// This is highly unsafe, due to the number of invariants that aren't
659    /// checked:
660    ///
661    /// * `ptr` must have been allocated using the global allocator, such as via
662    ///   the [`alloc::alloc`] function.
663    /// * `T` needs to have the same alignment as what `ptr` was allocated with.
664    ///   (`T` having a less strict alignment is not sufficient, the alignment really
665    ///   needs to be equal to satisfy the [`dealloc`] requirement that memory must be
666    ///   allocated and deallocated with the same layout.)
667    /// * The size of `T` times the `capacity` (i.e. the allocated size in bytes) needs
668    ///   to be the same size as the pointer was allocated with. (Because similar to
669    ///   alignment, [`dealloc`] must be called with the same layout `size`.)
670    /// * `length` needs to be less than or equal to `capacity`.
671    /// * The first `length` values must be properly initialized values of type `T`.
672    /// * `capacity` needs to be the capacity that the pointer was allocated with.
673    /// * The allocated size in bytes must be no larger than `isize::MAX`.
674    ///   See the safety documentation of [`pointer::offset`].
675    ///
676    /// These requirements are always upheld by any `ptr` that has been allocated
677    /// via `Vec<T>`. Other allocation sources are allowed if the invariants are
678    /// upheld.
679    ///
680    /// Violating these may cause problems like corrupting the allocator's
681    /// internal data structures. For example it is normally **not** safe
682    /// to build a `Vec<u8>` from a pointer to a C `char` array with length
683    /// `size_t`, doing so is only safe if the array was initially allocated by
684    /// a `Vec` or `String`.
685    /// It's also not safe to build one from a `Vec<u16>` and its length, because
686    /// the allocator cares about the alignment, and these two types have different
687    /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
688    /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
689    /// these issues, it is often preferable to do casting/transmuting using
690    /// [`NonNull::slice_from_raw_parts`] instead.
691    ///
692    /// The ownership of `ptr` is effectively transferred to the
693    /// `Vec<T>` which may then deallocate, reallocate or change the
694    /// contents of memory pointed to by the pointer at will. Ensure
695    /// that nothing else uses the pointer after calling this
696    /// function.
697    ///
698    /// [`String`]: crate::string::String
699    /// [`alloc::alloc`]: crate::alloc::alloc
700    /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
701    ///
702    /// # Examples
703    ///
704    /// ```
705    /// let v = vec![1, 2, 3];
706    ///
707    /// // Deconstruct the vector into parts.
708    /// let (p, len, cap) = v.into_parts();
709    ///
710    /// unsafe {
711    ///     // Overwrite memory with 4, 5, 6
712    ///     for i in 0..len {
713    ///         p.add(i).write(4 + i);
714    ///     }
715    ///
716    ///     // Put everything back together into a Vec
717    ///     let rebuilt = Vec::from_parts(p, len, cap);
718    ///     assert_eq!(rebuilt, [4, 5, 6]);
719    /// }
720    /// ```
721    ///
722    /// Using memory that was allocated elsewhere:
723    ///
724    /// ```rust
725    /// use std::alloc::{alloc, Layout};
726    /// use std::ptr::NonNull;
727    ///
728    /// fn main() {
729    ///     let layout = Layout::array::<u32>(16).expect("16 u32s take 64 bytes, so it shouldn't overflow");
730    ///
731    ///     let vec = unsafe {
732    ///         let Some(mem) = NonNull::new(alloc(layout).cast::<u32>()) else {
733    ///             return;
734    ///         };
735    ///
736    ///         mem.write(1_000_000);
737    ///
738    ///         Vec::from_parts(mem, 1, 16)
739    ///     };
740    ///
741    ///     assert_eq!(vec, &[1_000_000]);
742    ///     assert_eq!(vec.capacity(), 16);
743    /// }
744    /// ```
745    #[inline]
746    #[stable(feature = "box_vec_non_null", since = "1.99.0")]
747    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
748    pub const unsafe fn from_parts(ptr: NonNull<T>, length: usize, capacity: usize) -> Self {
749        // SAFETY: Upheld by caller.
750        unsafe { Self::from_parts_in(ptr, length, capacity, Global) }
751    }
752
753    /// Creates a `Vec<T>` where each element is produced by calling `f` with
754    /// that element's index while walking forward through the `Vec<T>`.
755    ///
756    /// This is essentially the same as writing
757    ///
758    /// ```text
759    /// vec![f(0), f(1), f(2), …, f(length - 2), f(length - 1)]
760    /// ```
761    /// and is similar to `(0..i).map(f)`, just for `Vec<T>`s not iterators.
762    ///
763    /// If `length == 0`, this produces an empty `Vec<T>` without ever calling `f`.
764    ///
765    /// # Example
766    ///
767    /// ```rust
768    /// let vec = Vec::from_fn(5, |i| i);
769    ///
770    /// // indexes are:  0  1  2  3  4
771    /// assert_eq!(vec, [0, 1, 2, 3, 4]);
772    ///
773    /// let vec2 = Vec::from_fn(8, |i| i * 2);
774    ///
775    /// // indexes are:   0  1  2  3  4  5   6   7
776    /// assert_eq!(vec2, [0, 2, 4, 6, 8, 10, 12, 14]);
777    ///
778    /// let bool_vec = Vec::from_fn(5, |i| i % 2 == 0);
779    ///
780    /// // indexes are:       0     1      2     3      4
781    /// assert_eq!(bool_vec, [true, false, true, false, true]);
782    /// ```
783    ///
784    /// The `Vec<T>` is generated in ascending index order, starting from the front
785    /// and going towards the back, so you can use closures with mutable state:
786    /// ```
787    /// let mut state = 1;
788    /// let a = Vec::from_fn(6, |_| { let x = state; state *= 2; x });
789    ///
790    /// assert_eq!(a, [1, 2, 4, 8, 16, 32]);
791    /// ```
792    #[cfg(not(no_global_oom_handling))]
793    #[inline]
794    #[stable(feature = "vec_from_fn", since = "CURRENT_RUSTC_VERSION")]
795    pub fn from_fn<F>(length: usize, f: F) -> Self
796    where
797        F: FnMut(usize) -> T,
798    {
799        (0..length).map(f).collect()
800    }
801
802    /// Decomposes a `Vec<T>` into its raw components: `(pointer, length, capacity)`.
803    ///
804    /// Returns the raw pointer to the underlying data, the length of
805    /// the vector (in elements), and the allocated capacity of the
806    /// data (in elements). These are the same arguments in the same
807    /// order as the arguments to [`from_raw_parts`].
808    ///
809    /// After calling this function, the caller is responsible for the
810    /// memory previously managed by the `Vec`. Most often, one does
811    /// this by converting the raw pointer, length, and capacity back
812    /// into a `Vec` with the [`from_raw_parts`] function; more generally,
813    /// if `T` is non-zero-sized and the capacity is nonzero, one may use
814    /// any method that calls [`dealloc`] with a layout of
815    /// `Layout::array::<T>(capacity)`; if `T` is zero-sized or the
816    /// capacity is zero, nothing needs to be done.
817    ///
818    /// [`from_raw_parts`]: Vec::from_raw_parts
819    /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
820    ///
821    /// # Examples
822    ///
823    /// ```
824    /// let v: Vec<i32> = vec![-1, 0, 1];
825    ///
826    /// let (ptr, len, cap) = v.into_raw_parts();
827    ///
828    /// let rebuilt = unsafe {
829    ///     // We can now make changes to the components, such as
830    ///     // transmuting the raw pointer to a compatible type.
831    ///     let ptr = ptr as *mut u32;
832    ///
833    ///     Vec::from_raw_parts(ptr, len, cap)
834    /// };
835    /// assert_eq!(rebuilt, [4294967295, 0, 1]);
836    /// ```
837    #[must_use = "losing the pointer will leak memory"]
838    #[stable(feature = "vec_into_raw_parts", since = "1.93.0")]
839    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
840    pub const fn into_raw_parts(self) -> (*mut T, usize, usize) {
841        let mut me = ManuallyDrop::new(self);
842        (me.as_mut_ptr(), me.len(), me.capacity())
843    }
844
845    #[doc(alias = "into_non_null_parts")]
846    /// Decomposes a `Vec<T>` into its raw components: `(NonNull pointer, length, capacity)`.
847    ///
848    /// Returns the `NonNull` pointer to the underlying data, the length of
849    /// the vector (in elements), and the allocated capacity of the
850    /// data (in elements). These are the same arguments in the same
851    /// order as the arguments to [`from_parts`].
852    ///
853    /// After calling this function, the caller is responsible for the
854    /// memory previously managed by the `Vec`. The only way to do
855    /// this is to convert the `NonNull` pointer, length, and capacity back
856    /// into a `Vec` with the [`from_parts`] function, allowing
857    /// the destructor to perform the cleanup.
858    ///
859    /// [`from_parts`]: Vec::from_parts
860    ///
861    /// # Examples
862    ///
863    /// ```
864    /// let v: Vec<i32> = vec![-1, 0, 1];
865    ///
866    /// let (ptr, len, cap) = v.into_parts();
867    ///
868    /// let rebuilt = unsafe {
869    ///     // We can now make changes to the components, such as
870    ///     // transmuting the raw pointer to a compatible type.
871    ///     let ptr = ptr.cast::<u32>();
872    ///
873    ///     Vec::from_parts(ptr, len, cap)
874    /// };
875    /// assert_eq!(rebuilt, [4294967295, 0, 1]);
876    /// ```
877    #[must_use = "losing the pointer will leak memory"]
878    #[stable(feature = "box_vec_non_null", since = "1.99.0")]
879    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
880    pub const fn into_parts(self) -> (NonNull<T>, usize, usize) {
881        let (ptr, len, capacity) = self.into_raw_parts();
882        // SAFETY: A `Vec` always has a non-null pointer.
883        (unsafe { NonNull::new_unchecked(ptr) }, len, capacity)
884    }
885
886    /// Interns the `Vec<T>`, making the underlying memory read-only. This method should be
887    /// called during compile time. (This is a no-op if called during runtime)
888    ///
889    /// This method must be called if the memory used by `Vec` needs to appear in the final
890    /// values of constants.
891    #[unstable(feature = "const_heap", issue = "79597")]
892    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
893    pub const fn const_make_global(mut self) -> &'static [T]
894    where
895        T: Freeze,
896    {
897        // `const_make_global` requires the pointer to point to the beginning of a heap allocation,
898        // which is not the case when `self.capacity()` is 0, or if `T::IS_ZST`,
899        // which is why we instead return a new slice in this case.
900        if self.capacity() == 0 || T::IS_ZST {
901            let me = ManuallyDrop::new(self);
902            // ignore-tidy-undocumented-unsafe
903            unsafe { slice::from_raw_parts(NonNull::<T>::dangling().as_ptr(), me.len) }
904        } else {
905            // ignore-tidy-undocumented-unsafe
906            unsafe { core::intrinsics::const_make_global(self.as_mut_ptr().cast()) };
907            let me = ManuallyDrop::new(self);
908            // ignore-tidy-undocumented-unsafe
909            unsafe { slice::from_raw_parts(me.as_ptr(), me.len) }
910        }
911    }
912}
913
914#[cfg(not(no_global_oom_handling))]
915#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
916#[rustfmt::skip] // FIXME(fee1-dead): temporary measure before rustfmt is bumped
917const impl<T, A: [const] Allocator + [const] Destruct> Vec<T, A> {
918    /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity
919    /// with the provided allocator.
920    ///
921    /// The vector will be able to hold at least `capacity` elements without
922    /// reallocating. This method is allowed to allocate for more elements than
923    /// `capacity`. If `capacity` is zero, the vector will not allocate.
924    ///
925    /// It is important to note that although the returned vector has the
926    /// minimum *capacity* specified, the vector will have a zero *length*. For
927    /// an explanation of the difference between length and capacity, see
928    /// *[Capacity and reallocation]*.
929    ///
930    /// If it is important to know the exact allocated capacity of a `Vec`,
931    /// always use the [`capacity`] method after construction.
932    ///
933    /// For `Vec<T, A>` where `T` is a zero-sized type, there will be no allocation
934    /// and the capacity will always be `usize::MAX`.
935    ///
936    /// [Capacity and reallocation]: #capacity-and-reallocation
937    /// [`capacity`]: Vec::capacity
938    ///
939    /// # Panics
940    ///
941    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
942    ///
943    /// # Examples
944    ///
945    /// ```
946    /// use std::alloc::System;
947    ///
948    /// let mut vec = Vec::with_capacity_in(10, System);
949    ///
950    /// // The vector contains no items, even though it has capacity for more
951    /// assert_eq!(vec.len(), 0);
952    /// assert!(vec.capacity() >= 10);
953    ///
954    /// // These are all done without reallocating...
955    /// for i in 0..10 {
956    ///     vec.push(i);
957    /// }
958    /// assert_eq!(vec.len(), 10);
959    /// assert!(vec.capacity() >= 10);
960    ///
961    /// // ...but this may make the vector reallocate
962    /// vec.push(11);
963    /// assert_eq!(vec.len(), 11);
964    /// assert!(vec.capacity() >= 11);
965    ///
966    /// // A vector of a zero-sized type will always over-allocate, since no
967    /// // allocation is necessary
968    /// let vec_units = Vec::<(), System>::with_capacity_in(10, System);
969    /// assert_eq!(vec_units.capacity(), usize::MAX);
970    /// ```
971    #[inline]
972    #[stable(feature = "allocator_api", since = "CURRENT_RUSTC_VERSION")]
973    pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
974        Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
975    }
976
977    /// Appends an element to the back of a collection.
978    ///
979    /// # Panics
980    ///
981    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
982    ///
983    /// # Examples
984    ///
985    /// ```
986    /// let mut vec = vec![1, 2];
987    /// vec.push(3);
988    /// assert_eq!(vec, [1, 2, 3]);
989    /// ```
990    ///
991    /// # Time complexity
992    ///
993    /// Takes amortized *O*(1) time. If the vector's length would exceed its
994    /// capacity after the push, *O*(*capacity*) time is taken to copy the
995    /// vector's elements to a larger allocation. This expensive operation is
996    /// offset by the *capacity* *O*(1) insertions it allows.
997    #[inline]
998    #[stable(feature = "rust1", since = "1.0.0")]
999    #[rustc_confusables("push_back", "put", "append")]
1000    pub fn push(&mut self, value: T) {
1001        let _ = self.push_mut(value);
1002    }
1003
1004    /// Appends an element to the back of a collection, returning a reference to it.
1005    ///
1006    /// # Panics
1007    ///
1008    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1009    ///
1010    /// # Examples
1011    ///
1012    /// ```
1013    /// let mut vec = vec![1, 2];
1014    /// let last = vec.push_mut(3);
1015    /// assert_eq!(*last, 3);
1016    /// assert_eq!(vec, [1, 2, 3]);
1017    ///
1018    /// let last = vec.push_mut(3);
1019    /// *last += 1;
1020    /// assert_eq!(vec, [1, 2, 3, 4]);
1021    /// ```
1022    ///
1023    /// # Time complexity
1024    ///
1025    /// Takes amortized *O*(1) time. If the vector's length would exceed its
1026    /// capacity after the push, *O*(*capacity*) time is taken to copy the
1027    /// vector's elements to a larger allocation. This expensive operation is
1028    /// offset by the *capacity* *O*(1) insertions it allows.
1029    #[inline]
1030    #[stable(feature = "push_mut", since = "1.95.0")]
1031    #[must_use = "if you don't need a reference to the value, use `Vec::push` instead"]
1032    pub fn push_mut(&mut self, value: T) -> &mut T {
1033        // Inform codegen that the length does not change across grow_one().
1034        let len = self.len;
1035        // This will panic or abort if we would allocate > isize::MAX bytes
1036        // or if the length increment would overflow for zero-sized types.
1037        if len == self.buf.capacity() {
1038            self.buf.grow_one();
1039        }
1040        // ignore-tidy-undocumented-unsafe
1041        unsafe {
1042            let end = self.as_mut_ptr().add(len);
1043            ptr::write(end, value);
1044            self.len = len + 1;
1045            // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference.
1046            &mut *end
1047        }
1048    }
1049}
1050
1051impl<T, A: Allocator> Vec<T, A> {
1052    /// Constructs a new, empty `Vec<T, A>`.
1053    ///
1054    /// The vector will not allocate until elements are pushed onto it.
1055    ///
1056    /// # Examples
1057    ///
1058    /// ```
1059    /// use std::alloc::System;
1060    ///
1061    /// let vec: Vec<i32, System> = Vec::new_in(System);
1062    /// ```
1063    #[inline]
1064    #[stable(feature = "allocator_api", since = "CURRENT_RUSTC_VERSION")]
1065    #[rustc_const_unstable(feature = "allocator_ext", issue = "163177")]
1066    pub const fn new_in(alloc: A) -> Self {
1067        Vec { buf: RawVec::new_in(alloc), len: 0 }
1068    }
1069
1070    /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity
1071    /// with the provided allocator.
1072    ///
1073    /// The vector will be able to hold at least `capacity` elements without
1074    /// reallocating. This method is allowed to allocate for more elements than
1075    /// `capacity`. If `capacity` is zero, the vector will not allocate.
1076    ///
1077    /// # Errors
1078    ///
1079    /// Returns an error if the capacity exceeds `isize::MAX` _bytes_,
1080    /// or if the allocator reports allocation failure.
1081    #[inline]
1082    #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
1083    // #[unstable(feature = "try_with_capacity", issue = "91913")]
1084    pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
1085        Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 })
1086    }
1087
1088    /// Creates a `Vec<T, A>` directly from a pointer, a length, a capacity,
1089    /// and an allocator.
1090    ///
1091    /// # Safety
1092    ///
1093    /// This is highly unsafe, due to the number of invariants that aren't
1094    /// checked:
1095    ///
1096    /// * `ptr` must be [*currently allocated*] via the given allocator `alloc`.
1097    /// * `T` needs to have the same alignment as what `ptr` was allocated with.
1098    ///   (`T` having a less strict alignment is not sufficient, the alignment really
1099    ///   needs to be equal to satisfy the [`dealloc`] requirement that memory must be
1100    ///   allocated and deallocated with the same layout.)
1101    /// * The size of `T` times the `capacity` (i.e. the allocated size in bytes) needs
1102    ///   to be the same size as the pointer was allocated with. (Because similar to
1103    ///   alignment, [`dealloc`] must be called with the same layout `size`.)
1104    /// * `length` needs to be less than or equal to `capacity`.
1105    /// * The first `length` values must be properly initialized values of type `T`.
1106    /// * `capacity` needs to [*fit*] the layout size that the pointer was allocated with.
1107    /// * The allocated size in bytes must be no larger than `isize::MAX`.
1108    ///   See the safety documentation of [`pointer::offset`].
1109    ///
1110    /// These requirements are always upheld by any `ptr` that has been allocated
1111    /// via `Vec<T, A>`. Other allocation sources are allowed if the invariants are
1112    /// upheld.
1113    ///
1114    /// Violating these may cause problems like corrupting the allocator's
1115    /// internal data structures. For example it is **not** safe
1116    /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
1117    /// It's also not safe to build one from a `Vec<u16>` and its length, because
1118    /// the allocator cares about the alignment, and these two types have different
1119    /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
1120    /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
1121    ///
1122    /// The ownership of `ptr` is effectively transferred to the
1123    /// `Vec<T>` which may then deallocate, reallocate or change the
1124    /// contents of memory pointed to by the pointer at will. Ensure
1125    /// that nothing else uses the pointer after calling this
1126    /// function.
1127    ///
1128    /// [`String`]: crate::string::String
1129    /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
1130    /// [*currently allocated*]: crate::alloc::Allocator#currently-allocated-memory
1131    /// [*fit*]: crate::alloc::Allocator#memory-fitting
1132    ///
1133    /// # Examples
1134    ///
1135    /// ```
1136    /// use std::alloc::System;
1137    ///
1138    /// use std::ptr;
1139    ///
1140    /// let mut v = Vec::with_capacity_in(3, System);
1141    /// v.push(1);
1142    /// v.push(2);
1143    /// v.push(3);
1144    ///
1145    /// // Deconstruct the vector into parts.
1146    /// let (p, len, cap, alloc) = v.into_raw_parts_with_allocator();
1147    ///
1148    /// unsafe {
1149    ///     // Overwrite memory with 4, 5, 6
1150    ///     for i in 0..len {
1151    ///         ptr::write(p.add(i), 4 + i);
1152    ///     }
1153    ///
1154    ///     // Put everything back together into a Vec
1155    ///     let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
1156    ///     assert_eq!(rebuilt, [4, 5, 6]);
1157    /// }
1158    /// ```
1159    ///
1160    /// Using memory that was allocated elsewhere:
1161    ///
1162    /// ```rust
1163    /// use std::alloc::{AllocError, Allocator, Global, Layout};
1164    ///
1165    /// fn main() {
1166    ///     let layout = Layout::array::<u32>(16).expect("16 u32s take 64 bytes, so it shouldn't overflow");
1167    ///
1168    ///     let vec = unsafe {
1169    ///         let mem = match Global.allocate(layout) {
1170    ///             Ok(mem) => mem.cast::<u32>().as_ptr(),
1171    ///             Err(AllocError) => return,
1172    ///         };
1173    ///
1174    ///         mem.write(1_000_000);
1175    ///
1176    ///         Vec::from_raw_parts_in(mem, 1, 16, Global)
1177    ///     };
1178    ///
1179    ///     assert_eq!(vec, &[1_000_000]);
1180    ///     assert_eq!(vec.capacity(), 16);
1181    /// }
1182    /// ```
1183    #[inline]
1184    #[stable(feature = "allocator_api", since = "CURRENT_RUSTC_VERSION")]
1185    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
1186    pub const unsafe fn from_raw_parts_in(
1187        ptr: *mut T,
1188        length: usize,
1189        capacity: usize,
1190        alloc: A,
1191    ) -> Self {
1192        ub_checks::assert_unsafe_precondition!(
1193            check_library_ub,
1194            "Vec::from_raw_parts_in requires that length <= capacity",
1195            (length: usize = length, capacity: usize = capacity) => length <= capacity
1196        );
1197        // SAFETY: Upheld by caller.
1198        unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
1199    }
1200
1201    #[doc(alias = "from_non_null_parts_in")]
1202    /// Creates a `Vec<T, A>` directly from a `NonNull` pointer, a length, a capacity,
1203    /// and an allocator.
1204    ///
1205    /// # Safety
1206    ///
1207    /// This is highly unsafe, due to the number of invariants that aren't
1208    /// checked:
1209    ///
1210    /// * `ptr` must be [*currently allocated*] via the given allocator `alloc`.
1211    /// * `T` needs to have the same alignment as what `ptr` was allocated with.
1212    ///   (`T` having a less strict alignment is not sufficient, the alignment really
1213    ///   needs to be equal to satisfy the [`dealloc`] requirement that memory must be
1214    ///   allocated and deallocated with the same layout.)
1215    /// * The size of `T` times the `capacity` (i.e. the allocated size in bytes) needs
1216    ///   to be the same size as the pointer was allocated with. (Because similar to
1217    ///   alignment, [`dealloc`] must be called with the same layout `size`.)
1218    /// * `length` needs to be less than or equal to `capacity`.
1219    /// * The first `length` values must be properly initialized values of type `T`.
1220    /// * `capacity` needs to [*fit*] the layout size that the pointer was allocated with.
1221    /// * The allocated size in bytes must be no larger than `isize::MAX`.
1222    ///   See the safety documentation of [`pointer::offset`].
1223    ///
1224    /// These requirements are always upheld by any `ptr` that has been allocated
1225    /// via `Vec<T, A>`. Other allocation sources are allowed if the invariants are
1226    /// upheld.
1227    ///
1228    /// Violating these may cause problems like corrupting the allocator's
1229    /// internal data structures. For example it is **not** safe
1230    /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
1231    /// It's also not safe to build one from a `Vec<u16>` and its length, because
1232    /// the allocator cares about the alignment, and these two types have different
1233    /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
1234    /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
1235    ///
1236    /// The ownership of `ptr` is effectively transferred to the
1237    /// `Vec<T>` which may then deallocate, reallocate or change the
1238    /// contents of memory pointed to by the pointer at will. Ensure
1239    /// that nothing else uses the pointer after calling this
1240    /// function.
1241    ///
1242    /// [`String`]: crate::string::String
1243    /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
1244    /// [*currently allocated*]: crate::alloc::Allocator#currently-allocated-memory
1245    /// [*fit*]: crate::alloc::Allocator#memory-fitting
1246    ///
1247    /// # Examples
1248    ///
1249    /// ```
1250    /// use std::alloc::System;
1251    ///
1252    /// let mut v = Vec::with_capacity_in(3, System);
1253    /// v.push(1);
1254    /// v.push(2);
1255    /// v.push(3);
1256    ///
1257    /// // Deconstruct the vector into parts.
1258    /// let (p, len, cap, alloc) = v.into_parts_with_allocator();
1259    ///
1260    /// unsafe {
1261    ///     // Overwrite memory with 4, 5, 6
1262    ///     for i in 0..len {
1263    ///         p.add(i).write(4 + i);
1264    ///     }
1265    ///
1266    ///     // Put everything back together into a Vec
1267    ///     let rebuilt = Vec::from_parts_in(p, len, cap, alloc.clone());
1268    ///     assert_eq!(rebuilt, [4, 5, 6]);
1269    /// }
1270    /// ```
1271    ///
1272    /// Using memory that was allocated elsewhere:
1273    ///
1274    /// ```rust
1275    /// use std::alloc::{AllocError, Allocator, Global, Layout};
1276    ///
1277    /// fn main() {
1278    ///     let layout = Layout::array::<u32>(16).expect("16 u32s take 64 bytes, so it shouldn't overflow");
1279    ///
1280    ///     let vec = unsafe {
1281    ///         let mem = match Global.allocate(layout) {
1282    ///             Ok(mem) => mem.cast::<u32>(),
1283    ///             Err(AllocError) => return,
1284    ///         };
1285    ///
1286    ///         mem.write(1_000_000);
1287    ///
1288    ///         Vec::from_parts_in(mem, 1, 16, Global)
1289    ///     };
1290    ///
1291    ///     assert_eq!(vec, &[1_000_000]);
1292    ///     assert_eq!(vec.capacity(), 16);
1293    /// }
1294    /// ```
1295    #[inline]
1296    #[stable(feature = "allocator_api", since = "CURRENT_RUSTC_VERSION")]
1297    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
1298    pub const unsafe fn from_parts_in(
1299        ptr: NonNull<T>,
1300        length: usize,
1301        capacity: usize,
1302        alloc: A,
1303    ) -> Self {
1304        ub_checks::assert_unsafe_precondition!(
1305            check_library_ub,
1306            "Vec::from_parts_in requires that length <= capacity",
1307            (length: usize = length, capacity: usize = capacity) => length <= capacity
1308        );
1309        // SAFETY: Upheld by caller.
1310        unsafe { Vec { buf: RawVec::from_nonnull_in(ptr, capacity, alloc), len: length } }
1311    }
1312
1313    /// Decomposes a `Vec<T>` into its raw components: `(pointer, length, capacity, allocator)`.
1314    ///
1315    /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
1316    /// the allocated capacity of the data (in elements), and the allocator. These are the same
1317    /// arguments in the same order as the arguments to [`from_raw_parts_in`].
1318    ///
1319    /// After calling this function, the caller is responsible for the
1320    /// memory previously managed by the `Vec`. The only way to do
1321    /// this is to convert the raw pointer, length, and capacity back
1322    /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
1323    /// the destructor to perform the cleanup.
1324    ///
1325    /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
1326    ///
1327    /// # Examples
1328    ///
1329    /// ```
1330    /// use std::alloc::System;
1331    ///
1332    /// let mut v: Vec<i32, System> = Vec::new_in(System);
1333    /// v.push(-1);
1334    /// v.push(0);
1335    /// v.push(1);
1336    ///
1337    /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_allocator();
1338    ///
1339    /// let rebuilt = unsafe {
1340    ///     // We can now make changes to the components, such as
1341    ///     // transmuting the raw pointer to a compatible type.
1342    ///     let ptr = ptr as *mut u32;
1343    ///
1344    ///     Vec::from_raw_parts_in(ptr, len, cap, alloc)
1345    /// };
1346    /// assert_eq!(rebuilt, [4294967295, 0, 1]);
1347    /// ```
1348    #[must_use = "losing the pointer will leak memory"]
1349    #[stable(feature = "allocator_api", since = "CURRENT_RUSTC_VERSION")]
1350    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
1351    pub const fn into_raw_parts_with_allocator(self) -> (*mut T, usize, usize, A) {
1352        let mut me = ManuallyDrop::new(self);
1353        let len = me.len();
1354        let capacity = me.capacity();
1355        let ptr = me.as_mut_ptr();
1356        // ignore-tidy-undocumented-unsafe
1357        let alloc = unsafe { ptr::read(me.allocator()) };
1358        (ptr, len, capacity, alloc)
1359    }
1360
1361    #[doc(alias = "into_non_null_parts_with_alloc")]
1362    /// Decomposes a `Vec<T>` into its raw components: `(NonNull pointer, length, capacity, allocator)`.
1363    ///
1364    /// Returns the `NonNull` pointer to the underlying data, the length of the vector (in elements),
1365    /// the allocated capacity of the data (in elements), and the allocator. These are the same
1366    /// arguments in the same order as the arguments to [`from_parts_in`].
1367    ///
1368    /// After calling this function, the caller is responsible for the
1369    /// memory previously managed by the `Vec`. The only way to do
1370    /// this is to convert the `NonNull` pointer, length, and capacity back
1371    /// into a `Vec` with the [`from_parts_in`] function, allowing
1372    /// the destructor to perform the cleanup.
1373    ///
1374    /// [`from_parts_in`]: Vec::from_parts_in
1375    ///
1376    /// # Examples
1377    ///
1378    /// ```
1379    /// use std::alloc::System;
1380    ///
1381    /// let mut v: Vec<i32, System> = Vec::new_in(System);
1382    /// v.push(-1);
1383    /// v.push(0);
1384    /// v.push(1);
1385    ///
1386    /// let (ptr, len, cap, alloc) = v.into_parts_with_allocator();
1387    ///
1388    /// let rebuilt = unsafe {
1389    ///     // We can now make changes to the components, such as
1390    ///     // transmuting the raw pointer to a compatible type.
1391    ///     let ptr = ptr.cast::<u32>();
1392    ///
1393    ///     Vec::from_parts_in(ptr, len, cap, alloc)
1394    /// };
1395    /// assert_eq!(rebuilt, [4294967295, 0, 1]);
1396    /// ```
1397    #[must_use = "losing the pointer will leak memory"]
1398    #[stable(feature = "allocator_api", since = "CURRENT_RUSTC_VERSION")]
1399    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
1400    pub const fn into_parts_with_allocator(self) -> (NonNull<T>, usize, usize, A) {
1401        let (ptr, len, capacity, alloc) = self.into_raw_parts_with_allocator();
1402        // SAFETY: A `Vec` always has a non-null pointer.
1403        (unsafe { NonNull::new_unchecked(ptr) }, len, capacity, alloc)
1404    }
1405
1406    /// Returns the total number of elements the vector can hold without
1407    /// reallocating.
1408    ///
1409    /// # Examples
1410    ///
1411    /// ```
1412    /// let mut vec: Vec<i32> = Vec::with_capacity(10);
1413    /// vec.push(42);
1414    /// assert!(vec.capacity() >= 10);
1415    /// ```
1416    ///
1417    /// A vector with zero-sized elements will always have a capacity of usize::MAX:
1418    ///
1419    /// ```
1420    /// #[derive(Clone)]
1421    /// struct ZeroSized;
1422    ///
1423    /// fn main() {
1424    ///     assert_eq!(std::mem::size_of::<ZeroSized>(), 0);
1425    ///     let v = vec![ZeroSized; 0];
1426    ///     assert_eq!(v.capacity(), usize::MAX);
1427    /// }
1428    /// ```
1429    #[inline]
1430    #[stable(feature = "rust1", since = "1.0.0")]
1431    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1432    pub const fn capacity(&self) -> usize {
1433        self.buf.capacity()
1434    }
1435
1436    /// Reserves capacity for at least `additional` more elements to be inserted
1437    /// in the given `Vec<T>`. The collection may reserve more space to
1438    /// speculatively avoid frequent reallocations. After calling `reserve`,
1439    /// capacity will be greater than or equal to `self.len() + additional`.
1440    /// Does nothing if capacity is already sufficient.
1441    ///
1442    /// # Panics
1443    ///
1444    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1445    ///
1446    /// # Examples
1447    ///
1448    /// ```
1449    /// let mut vec = vec![1];
1450    /// vec.reserve(10);
1451    /// assert!(vec.capacity() >= 11);
1452    /// ```
1453    #[cfg(not(no_global_oom_handling))]
1454    #[stable(feature = "rust1", since = "1.0.0")]
1455    #[rustc_diagnostic_item = "vec_reserve"]
1456    pub fn reserve(&mut self, additional: usize) {
1457        self.buf.reserve(self.len, additional);
1458    }
1459
1460    /// Reserves the minimum capacity for at least `additional` more elements to
1461    /// be inserted in the given `Vec<T>`. Unlike [`reserve`], this will not
1462    /// deliberately over-allocate to speculatively avoid frequent allocations.
1463    /// After calling `reserve_exact`, capacity will be greater than or equal to
1464    /// `self.len() + additional`. Does nothing if the capacity is already
1465    /// sufficient.
1466    ///
1467    /// Note that the allocator may give the collection more space than it
1468    /// requests. Therefore, capacity can not be relied upon to be precisely
1469    /// minimal. Prefer [`reserve`] if future insertions are expected.
1470    ///
1471    /// [`reserve`]: Vec::reserve
1472    ///
1473    /// # Panics
1474    ///
1475    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1476    ///
1477    /// # Examples
1478    ///
1479    /// ```
1480    /// let mut vec = vec![1];
1481    /// vec.reserve_exact(10);
1482    /// assert!(vec.capacity() >= 11);
1483    /// ```
1484    #[cfg(not(no_global_oom_handling))]
1485    #[stable(feature = "rust1", since = "1.0.0")]
1486    pub fn reserve_exact(&mut self, additional: usize) {
1487        self.buf.reserve_exact(self.len, additional);
1488    }
1489
1490    /// Tries to reserve capacity for at least `additional` more elements to be inserted
1491    /// in the given `Vec<T>`. The collection may reserve more space to speculatively avoid
1492    /// frequent reallocations. After calling `try_reserve`, capacity will be
1493    /// greater than or equal to `self.len() + additional` if it returns
1494    /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1495    /// preserves the contents even if an error occurs.
1496    ///
1497    /// # Errors
1498    ///
1499    /// If the capacity overflows, or the allocator reports a failure, then an error
1500    /// is returned.
1501    ///
1502    /// # Examples
1503    ///
1504    /// ```
1505    /// use std::collections::TryReserveError;
1506    ///
1507    /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
1508    ///     let mut output = Vec::new();
1509    ///
1510    ///     // Pre-reserve the memory, exiting if we can't
1511    ///     output.try_reserve(data.len())?;
1512    ///
1513    ///     // Now we know this can't OOM in the middle of our complex work
1514    ///     output.extend(data.iter().map(|&val| {
1515    ///         val * 2 + 5 // very complicated
1516    ///     }));
1517    ///
1518    ///     Ok(output)
1519    /// }
1520    /// # process_data(&[1, 2, 3]).expect("this test needs 12 bytes, so it shouldn't fail");
1521    /// ```
1522    #[stable(feature = "try_reserve", since = "1.57.0")]
1523    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1524        self.buf.try_reserve(self.len, additional)
1525    }
1526
1527    /// Tries to reserve the minimum capacity for at least `additional`
1528    /// elements to be inserted in the given `Vec<T>`. Unlike [`try_reserve`],
1529    /// this will not deliberately over-allocate to speculatively avoid frequent
1530    /// allocations. After calling `try_reserve_exact`, capacity will be greater
1531    /// than or equal to `self.len() + additional` if it returns `Ok(())`.
1532    /// Does nothing if the capacity is already sufficient.
1533    ///
1534    /// Note that the allocator may give the collection more space than it
1535    /// requests. Therefore, capacity can not be relied upon to be precisely
1536    /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1537    ///
1538    /// [`try_reserve`]: Vec::try_reserve
1539    ///
1540    /// # Errors
1541    ///
1542    /// If the capacity overflows, or the allocator reports a failure, then an error
1543    /// is returned.
1544    ///
1545    /// # Examples
1546    ///
1547    /// ```
1548    /// use std::collections::TryReserveError;
1549    ///
1550    /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
1551    ///     let mut output = Vec::new();
1552    ///
1553    ///     // Pre-reserve the memory, exiting if we can't
1554    ///     output.try_reserve_exact(data.len())?;
1555    ///
1556    ///     // Now we know this can't OOM in the middle of our complex work
1557    ///     output.extend(data.iter().map(|&val| {
1558    ///         val * 2 + 5 // very complicated
1559    ///     }));
1560    ///
1561    ///     Ok(output)
1562    /// }
1563    /// # process_data(&[1, 2, 3]).expect("this test needs 12 bytes, so it shouldn't fail");
1564    /// ```
1565    #[stable(feature = "try_reserve", since = "1.57.0")]
1566    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1567        self.buf.try_reserve_exact(self.len, additional)
1568    }
1569
1570    /// Shrinks the capacity of the vector as much as possible.
1571    ///
1572    /// The behavior of this method depends on the allocator, which may either shrink the vector
1573    /// in-place or reallocate. The resulting vector might still have some excess capacity, just as
1574    /// is the case for [`with_capacity`]. See [`Allocator::shrink`] for more details.
1575    ///
1576    /// [`with_capacity`]: Vec::with_capacity
1577    ///
1578    /// # Examples
1579    ///
1580    /// ```
1581    /// let mut vec = Vec::with_capacity(10);
1582    /// vec.extend([1, 2, 3]);
1583    /// assert!(vec.capacity() >= 10);
1584    /// vec.shrink_to_fit();
1585    /// assert!(vec.capacity() >= 3);
1586    /// ```
1587    #[cfg(not(no_global_oom_handling))]
1588    #[stable(feature = "rust1", since = "1.0.0")]
1589    #[inline]
1590    pub fn shrink_to_fit(&mut self) {
1591        // The capacity is never less than the length, and there's nothing to do when
1592        // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
1593        // by only calling it with a greater capacity.
1594        if self.capacity() > self.len {
1595            self.buf.shrink_to_fit(self.len);
1596        }
1597    }
1598
1599    /// Shrinks the capacity of the vector with a lower bound.
1600    ///
1601    /// The capacity will remain at least as large as both the length
1602    /// and the supplied value.
1603    ///
1604    /// If the current capacity is less than the lower limit, this is a no-op.
1605    ///
1606    /// # Examples
1607    ///
1608    /// ```
1609    /// let mut vec = Vec::with_capacity(10);
1610    /// vec.extend([1, 2, 3]);
1611    /// assert!(vec.capacity() >= 10);
1612    /// vec.shrink_to(4);
1613    /// assert!(vec.capacity() >= 4);
1614    /// vec.shrink_to(0);
1615    /// assert!(vec.capacity() >= 3);
1616    /// ```
1617    #[cfg(not(no_global_oom_handling))]
1618    #[stable(feature = "shrink_to", since = "1.56.0")]
1619    pub fn shrink_to(&mut self, min_capacity: usize) {
1620        if self.capacity() > min_capacity {
1621            self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
1622        }
1623    }
1624
1625    /// Tries to shrink the capacity of the vector as much as possible
1626    ///
1627    /// The behavior of this method depends on the allocator, which may either shrink the vector
1628    /// in-place or reallocate. The resulting vector might still have some excess capacity, just as
1629    /// is the case for [`with_capacity`]. See [`Allocator::shrink`] for more details.
1630    ///
1631    /// [`with_capacity`]: Vec::with_capacity
1632    ///
1633    /// # Errors
1634    ///
1635    /// This function returns an error if the allocator fails to shrink the allocation,
1636    /// the vector thereafter is still safe to use, the capacity remains unchanged
1637    /// however. See [`Allocator::shrink`].
1638    ///
1639    /// # Examples
1640    ///
1641    /// ```
1642    /// #![feature(vec_fallible_shrink)]
1643    ///
1644    /// let mut vec = Vec::with_capacity(10);
1645    /// vec.extend([1, 2, 3]);
1646    /// assert!(vec.capacity() >= 10);
1647    /// vec.try_shrink_to_fit().expect("for this test, shrink shouldn't fail");
1648    /// assert!(vec.capacity() >= 3);
1649    /// ```
1650    #[unstable(feature = "vec_fallible_shrink", issue = "152350")]
1651    #[inline]
1652    pub fn try_shrink_to_fit(&mut self) -> Result<(), TryReserveError> {
1653        if self.capacity() > self.len { self.buf.try_shrink_to_fit(self.len) } else { Ok(()) }
1654    }
1655
1656    /// Shrinks the capacity of the vector with a lower bound.
1657    ///
1658    /// The capacity will remain at least as large as both the length
1659    /// and the supplied value.
1660    ///
1661    /// If the current capacity is less than the lower limit, this is a no-op.
1662    ///
1663    /// # Errors
1664    ///
1665    /// This function returns an error if the allocator fails to shrink the allocation,
1666    /// the vector thereafter is still safe to use, the capacity remains unchanged
1667    /// however. See [`Allocator::shrink`].
1668    ///
1669    /// # Examples
1670    ///
1671    /// ```
1672    /// #![feature(vec_fallible_shrink)]
1673    ///
1674    /// let mut vec = Vec::with_capacity(10);
1675    /// vec.extend([1, 2, 3]);
1676    /// assert!(vec.capacity() >= 10);
1677    /// vec.try_shrink_to(4).expect("for this test, shrink shouldn't fail");
1678    /// assert!(vec.capacity() >= 4);
1679    /// vec.try_shrink_to(0).expect("this is a no-op and thus the allocator isn't involved.");
1680    /// assert!(vec.capacity() >= 3);
1681    /// ```
1682    #[unstable(feature = "vec_fallible_shrink", issue = "152350")]
1683    #[inline]
1684    pub fn try_shrink_to(&mut self, min_capacity: usize) -> Result<(), TryReserveError> {
1685        if self.capacity() > min_capacity {
1686            self.buf.try_shrink_to_fit(cmp::max(self.len, min_capacity))
1687        } else {
1688            Ok(())
1689        }
1690    }
1691
1692    /// Converts the vector into [`Box<[T]>`][owned slice].
1693    ///
1694    /// Before doing the conversion, this method discards excess capacity like [`shrink_to_fit`].
1695    ///
1696    /// [owned slice]: Box
1697    /// [`shrink_to_fit`]: Vec::shrink_to_fit
1698    ///
1699    /// # Examples
1700    ///
1701    /// ```
1702    /// let v = vec![1, 2, 3];
1703    ///
1704    /// let slice = v.into_boxed_slice();
1705    /// ```
1706    ///
1707    /// Any excess capacity is removed:
1708    ///
1709    /// ```
1710    /// let mut vec = Vec::with_capacity(10);
1711    /// vec.extend([1, 2, 3]);
1712    ///
1713    /// assert!(vec.capacity() >= 10);
1714    /// let slice = vec.into_boxed_slice();
1715    /// assert_eq!(slice.into_vec().capacity(), 3);
1716    /// ```
1717    #[cfg(not(no_global_oom_handling))]
1718    #[stable(feature = "rust1", since = "1.0.0")]
1719    pub fn into_boxed_slice(mut self) -> Box<[T], A> {
1720        self.shrink_to_fit();
1721        let me = ManuallyDrop::new(self);
1722        // ignore-tidy-undocumented-unsafe
1723        unsafe {
1724            let buf = ptr::read(&me.buf);
1725            let len = me.len();
1726            buf.into_box(len).assume_init()
1727        }
1728    }
1729
1730    /// Converts the Vec into a boxed array. This conversion will discard any spare capacity,
1731    /// if there is any, see [`Vec::shrink_to_fit`].
1732    /// If you merely wish for a reference to an array, use [`as_array`](https://doc.rust-lang.org/stable/std/primitive.slice.html#method.as_array).
1733    ///
1734    /// # Errors
1735    ///
1736    /// Returns the original `Vec<T>` in the `Err` variant if [`Vec::len`] does not equal `N`.
1737    ///
1738    /// # Examples
1739    ///
1740    /// ```
1741    /// #![feature(alloc_slice_into_array)]
1742    /// let vec: Vec<i32> = vec![1, 2, 3];
1743    /// let box_array: Box<[i32; 3]> = vec.clone().into_array().unwrap();
1744    /// let not_enough_elements: Result<Box<[i32; 4]>, Vec<i32>> = vec.into_array::<4>();
1745    /// assert_eq!(not_enough_elements, Err(vec![1, 2, 3]));
1746    /// ```
1747    #[cfg(not(no_global_oom_handling))]
1748    #[unstable(feature = "alloc_slice_into_array", issue = "148082")]
1749    pub fn into_array<const N: usize>(self) -> Result<Box<[T; N], A>, Self> {
1750        if self.len() == N {
1751            // SAFETY: `Box::into_array` is guaranteed to return `Ok` if the
1752            // length of the slice is equal to `N`.
1753            // `self.into_boxed_slice().len()` is equal to `self.len()`,
1754            // which we just checked.
1755            Ok(unsafe { self.into_boxed_slice().into_array().unwrap_unchecked() })
1756        } else {
1757            Err(self)
1758        }
1759    }
1760
1761    /// Shortens the vector, keeping the first `len` elements and dropping
1762    /// the rest.
1763    ///
1764    /// If `len` is greater or equal to the vector's current length, this has
1765    /// no effect.
1766    ///
1767    /// The [`drain`] method can emulate `truncate`, but causes the excess
1768    /// elements to be returned instead of dropped.
1769    ///
1770    /// Note that this method has no effect on the allocated capacity
1771    /// of the vector.
1772    ///
1773    /// # Examples
1774    ///
1775    /// Truncating a five element vector to two elements:
1776    ///
1777    /// ```
1778    /// let mut vec = vec![1, 2, 3, 4, 5];
1779    /// vec.truncate(2);
1780    /// assert_eq!(vec, [1, 2]);
1781    /// ```
1782    ///
1783    /// No truncation occurs when `len` is greater than the vector's current
1784    /// length:
1785    ///
1786    /// ```
1787    /// let mut vec = vec![1, 2, 3];
1788    /// vec.truncate(8);
1789    /// assert_eq!(vec, [1, 2, 3]);
1790    /// ```
1791    ///
1792    /// Truncating when `len == 0` is equivalent to calling the [`clear`]
1793    /// method.
1794    ///
1795    /// ```
1796    /// let mut vec = vec![1, 2, 3];
1797    /// vec.truncate(0);
1798    /// assert_eq!(vec, []);
1799    /// ```
1800    ///
1801    /// [`clear`]: Vec::clear
1802    /// [`drain`]: Vec::drain
1803    #[stable(feature = "rust1", since = "1.0.0")]
1804    pub fn truncate(&mut self, len: usize) {
1805        // SAFETY: `BufWriter::flush_buf` assumes that this will not
1806        // de-initialize any elements of the spare capacity.
1807
1808        // This is safe because:
1809        //
1810        // * the slice passed to `drop_in_place` is valid; the `len > self.len`
1811        //   case avoids creating an invalid slice, and
1812        // * the `len` of the vector is shrunk before calling `drop_in_place`,
1813        //   such that no value will be dropped twice in case `drop_in_place`
1814        //   were to panic once (if it panics twice, the program aborts).
1815        unsafe {
1816            // Note: It's intentional that this is `>` and not `>=`.
1817            //       Changing it to `>=` has negative performance
1818            //       implications in some cases. See #78884 for more.
1819            if len > self.len {
1820                return;
1821            }
1822            let remaining_len = self.len - len;
1823            let s = self.as_mut_ptr().add(len).cast_slice(remaining_len);
1824            self.len = len;
1825            ptr::drop_in_place(s);
1826        }
1827    }
1828
1829    /// Extracts a slice containing the entire vector.
1830    ///
1831    /// Equivalent to `&s[..]`.
1832    ///
1833    /// # Examples
1834    ///
1835    /// ```
1836    /// use std::io::{self, Write};
1837    /// let buffer = vec![1, 2, 3, 5, 8];
1838    /// io::sink().write(buffer.as_slice()).unwrap();
1839    /// ```
1840    #[inline]
1841    #[stable(feature = "vec_as_slice", since = "1.7.0")]
1842    #[rustc_diagnostic_item = "vec_as_slice"]
1843    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1844    pub const fn as_slice(&self) -> &[T] {
1845        // SAFETY: `slice::from_raw_parts` requires pointee is a contiguous, aligned buffer of size
1846        // `len` containing properly-initialized `T`s. Data must not be mutated for the returned
1847        // lifetime. Further, `len * size_of::<T>` <= `isize::MAX`, and allocation does not
1848        // "wrap" through overflowing memory addresses.
1849        //
1850        // * Vec API guarantees that self.buf:
1851        //      * contains only properly-initialized items within 0..len
1852        //      * is aligned, contiguous, and valid for `len` reads
1853        //      * obeys size and address-wrapping constraints
1854        //
1855        // * We only construct `&mut` references to `self.buf` through `&mut self` methods; borrow-
1856        //   check ensures that it is not possible to mutably alias `self.buf` within the
1857        //   returned lifetime.
1858        unsafe {
1859            // normally this would use `slice::from_raw_parts`, but it's
1860            // instantiated often enough that avoiding the UB check is worth it
1861            &*core::intrinsics::aggregate_raw_ptr::<*const [T], _, _>(self.as_ptr(), self.len)
1862        }
1863    }
1864
1865    /// Extracts a mutable slice of the entire vector.
1866    ///
1867    /// Equivalent to `&mut s[..]`.
1868    ///
1869    /// # Examples
1870    ///
1871    /// ```
1872    /// use std::io::{self, Read};
1873    /// let mut buffer = vec![0; 3];
1874    /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1875    /// ```
1876    #[inline]
1877    #[stable(feature = "vec_as_slice", since = "1.7.0")]
1878    #[rustc_diagnostic_item = "vec_as_mut_slice"]
1879    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1880    pub const fn as_mut_slice(&mut self) -> &mut [T] {
1881        // SAFETY: `BufWriter::flush_buf` assumes that this will not
1882        // de-initialize any elements of the spare capacity.
1883
1884        // SAFETY: `slice::from_raw_parts_mut` requires pointee is a contiguous, aligned buffer of
1885        // size `len` containing properly-initialized `T`s. Data must not be accessed through any
1886        // other pointer for the returned lifetime. Further, `len * size_of::<T>` <=
1887        // `isize::MAX` and allocation does not "wrap" through overflowing memory addresses.
1888        //
1889        // * Vec API guarantees that self.buf:
1890        //      * contains only properly-initialized items within 0..len
1891        //      * is aligned, contiguous, and valid for `len` reads
1892        //      * obeys size and address-wrapping constraints
1893        //
1894        // * We only construct references to `self.buf` through `&self` and `&mut self` methods;
1895        //   borrow-check ensures that it is not possible to construct a reference to `self.buf`
1896        //   within the returned lifetime.
1897        unsafe {
1898            // normally this would use `slice::from_raw_parts_mut`, but it's
1899            // instantiated often enough that avoiding the UB check is worth it
1900            &mut *core::intrinsics::aggregate_raw_ptr::<*mut [T], _, _>(self.as_mut_ptr(), self.len)
1901        }
1902    }
1903
1904    /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
1905    /// valid for zero sized reads if the vector didn't allocate.
1906    ///
1907    /// The caller must ensure that the vector outlives the pointer this
1908    /// function returns, or else it will end up dangling.
1909    /// Modifying the vector may cause its buffer to be reallocated,
1910    /// which would also make any pointers to it invalid.
1911    ///
1912    /// The caller must also ensure that the memory the pointer (non-transitively) points to
1913    /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1914    /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1915    ///
1916    /// This method guarantees that for the purpose of the aliasing model, this method
1917    /// does not materialize a reference to the underlying slice, and thus the returned pointer
1918    /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1919    /// and [`as_non_null`].
1920    /// Note that calling other methods that materialize mutable references to the slice,
1921    /// or mutable references to specific elements you are planning on accessing through this pointer,
1922    /// as well as writing to those elements, may still invalidate this pointer.
1923    /// See the second example below for how this guarantee can be used.
1924    ///
1925    ///
1926    /// # Examples
1927    ///
1928    /// ```
1929    /// let x = vec![1, 2, 4];
1930    /// let x_ptr = x.as_ptr();
1931    ///
1932    /// unsafe {
1933    ///     for i in 0..x.len() {
1934    ///         assert_eq!(*x_ptr.add(i), 1 << i);
1935    ///     }
1936    /// }
1937    /// ```
1938    ///
1939    /// Due to the aliasing guarantee, the following code is legal:
1940    ///
1941    /// ```rust
1942    /// unsafe {
1943    ///     let mut v = vec![0, 1, 2];
1944    ///     let ptr1 = v.as_ptr();
1945    ///     let _ = ptr1.read();
1946    ///     let ptr2 = v.as_mut_ptr().offset(2);
1947    ///     ptr2.write(2);
1948    ///     // Notably, the write to `ptr2` did *not* invalidate `ptr1`
1949    ///     // because it mutated a different element:
1950    ///     let _ = ptr1.read();
1951    /// }
1952    /// ```
1953    ///
1954    /// [`as_mut_ptr`]: Vec::as_mut_ptr
1955    /// [`as_ptr`]: Vec::as_ptr
1956    /// [`as_non_null`]: Vec::as_non_null
1957    #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1958    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1959    #[rustc_never_returns_null_ptr]
1960    #[rustc_as_ptr]
1961    #[inline]
1962    pub const fn as_ptr(&self) -> *const T {
1963        // We shadow the slice method of the same name to avoid going through
1964        // `deref`, which creates an intermediate reference.
1965        self.buf.ptr()
1966    }
1967
1968    /// Returns a raw mutable pointer to the vector's buffer, or a dangling
1969    /// raw pointer valid for zero sized reads if the vector didn't allocate.
1970    ///
1971    /// The caller must ensure that the vector outlives the pointer this
1972    /// function returns, or else it will end up dangling.
1973    /// Modifying the vector may cause its buffer to be reallocated,
1974    /// which would also make any pointers to it invalid.
1975    ///
1976    /// This method guarantees that for the purpose of the aliasing model, this method
1977    /// does not materialize a reference to the underlying slice, and thus the returned pointer
1978    /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1979    /// and [`as_non_null`].
1980    /// Note that calling other methods that materialize references to the slice,
1981    /// or references to specific elements you are planning on accessing through this pointer,
1982    /// may still invalidate this pointer.
1983    /// See the second example below for how this guarantee can be used.
1984    ///
1985    /// The method also guarantees that, as long as `T` is not zero-sized and the capacity is
1986    /// nonzero, the pointer may be passed into [`dealloc`] with a layout of
1987    /// `Layout::array::<T>(capacity)` in order to deallocate the backing memory. If this is done,
1988    /// be careful not to run the destructor of the `Vec`, as dropping it will result in
1989    /// double-frees. Wrapping the `Vec` in a [`ManuallyDrop`] is the typical way to achieve this.
1990    ///
1991    /// # Examples
1992    ///
1993    /// ```
1994    /// // Allocate vector big enough for 4 elements.
1995    /// let size = 4;
1996    /// let mut x: Vec<i32> = Vec::with_capacity(size);
1997    /// let x_ptr = x.as_mut_ptr();
1998    ///
1999    /// // Initialize elements via raw pointer writes, then set length.
2000    /// unsafe {
2001    ///     for i in 0..size {
2002    ///         *x_ptr.add(i) = i as i32;
2003    ///     }
2004    ///     x.set_len(size);
2005    /// }
2006    /// assert_eq!(&*x, &[0, 1, 2, 3]);
2007    /// ```
2008    ///
2009    /// Due to the aliasing guarantee, the following code is legal:
2010    ///
2011    /// ```rust
2012    /// unsafe {
2013    ///     let mut v = vec![0];
2014    ///     let ptr1 = v.as_mut_ptr();
2015    ///     ptr1.write(1);
2016    ///     let ptr2 = v.as_mut_ptr();
2017    ///     ptr2.write(2);
2018    ///     // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
2019    ///     ptr1.write(3);
2020    /// }
2021    /// ```
2022    ///
2023    /// Deallocating a vector using [`Box`] (which uses [`dealloc`] internally):
2024    ///
2025    /// ```
2026    /// use std::mem::{ManuallyDrop, MaybeUninit};
2027    ///
2028    /// let mut v = ManuallyDrop::new(vec![0, 1, 2]);
2029    /// let ptr = v.as_mut_ptr();
2030    /// let capacity = v.capacity();
2031    /// let slice_ptr: *mut [MaybeUninit<i32>] =
2032    ///     std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity);
2033    /// drop(unsafe { Box::from_raw(slice_ptr) });
2034    /// ```
2035    ///
2036    /// [`as_mut_ptr`]: Vec::as_mut_ptr
2037    /// [`as_ptr`]: Vec::as_ptr
2038    /// [`as_non_null`]: Vec::as_non_null
2039    /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
2040    /// [`ManuallyDrop`]: core::mem::ManuallyDrop
2041    #[stable(feature = "vec_as_ptr", since = "1.37.0")]
2042    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
2043    #[rustc_never_returns_null_ptr]
2044    #[rustc_as_ptr]
2045    #[inline]
2046    pub const fn as_mut_ptr(&mut self) -> *mut T {
2047        // We shadow the slice method of the same name to avoid going through
2048        // `deref_mut`, which creates an intermediate reference.
2049        self.buf.ptr()
2050    }
2051
2052    /// Returns a `NonNull` pointer to the vector's buffer, or a dangling
2053    /// `NonNull` pointer valid for zero sized reads if the vector didn't allocate.
2054    ///
2055    /// The caller must ensure that the vector outlives the pointer this
2056    /// function returns, or else it will end up dangling.
2057    /// Modifying the vector may cause its buffer to be reallocated,
2058    /// which would also make any pointers to it invalid.
2059    ///
2060    /// This method guarantees that for the purpose of the aliasing model, this method
2061    /// does not materialize a reference to the underlying slice, and thus the returned pointer
2062    /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
2063    /// and [`as_non_null`].
2064    /// Note that calling other methods that materialize references to the slice,
2065    /// or references to specific elements you are planning on accessing through this pointer,
2066    /// may still invalidate this pointer.
2067    /// See the second example below for how this guarantee can be used.
2068    ///
2069    /// # Examples
2070    ///
2071    /// ```
2072    /// #![feature(vec_as_non_null)]
2073    ///
2074    /// // Allocate vector big enough for 4 elements.
2075    /// let size = 4;
2076    /// let mut x: Vec<i32> = Vec::with_capacity(size);
2077    /// let x_ptr = x.as_non_null();
2078    ///
2079    /// // Initialize elements via raw pointer writes, then set length.
2080    /// unsafe {
2081    ///     for i in 0..size {
2082    ///         x_ptr.add(i).write(i as i32);
2083    ///     }
2084    ///     x.set_len(size);
2085    /// }
2086    /// assert_eq!(&*x, &[0, 1, 2, 3]);
2087    /// ```
2088    ///
2089    /// Due to the aliasing guarantee, the following code is legal:
2090    ///
2091    /// ```rust
2092    /// #![feature(vec_as_non_null)]
2093    ///
2094    /// unsafe {
2095    ///     let mut v = vec![0];
2096    ///     let ptr1 = v.as_non_null();
2097    ///     ptr1.write(1);
2098    ///     let ptr2 = v.as_non_null();
2099    ///     ptr2.write(2);
2100    ///     // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
2101    ///     ptr1.write(3);
2102    /// }
2103    /// ```
2104    ///
2105    /// [`as_mut_ptr`]: Vec::as_mut_ptr
2106    /// [`as_ptr`]: Vec::as_ptr
2107    /// [`as_non_null`]: Vec::as_non_null
2108    #[unstable(feature = "vec_as_non_null", issue = "157843")]
2109    #[rustc_const_unstable(feature = "vec_as_non_null", issue = "157843")]
2110    #[rustc_as_ptr]
2111    #[inline]
2112    pub const fn as_non_null(&mut self) -> NonNull<T> {
2113        self.buf.non_null()
2114    }
2115
2116    /// Returns a reference to the underlying allocator.
2117    #[stable(feature = "allocator_api", since = "CURRENT_RUSTC_VERSION")]
2118    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2119    #[inline]
2120    pub const fn allocator(&self) -> &A {
2121        self.buf.allocator()
2122    }
2123
2124    /// Forces the length of the vector to `new_len`.
2125    ///
2126    /// This is a low-level operation that maintains none of the normal
2127    /// invariants of the type. Normally changing the length of a vector
2128    /// is done using one of the safe operations instead, such as
2129    /// [`truncate`], [`resize`], [`extend`], or [`clear`].
2130    ///
2131    /// [`truncate`]: Vec::truncate
2132    /// [`resize`]: Vec::resize
2133    /// [`extend`]: Extend::extend
2134    /// [`clear`]: Vec::clear
2135    ///
2136    /// # Safety
2137    ///
2138    /// - `new_len` must be less than or equal to [`capacity()`].
2139    /// - The elements at `old_len..new_len` must be initialized.
2140    ///
2141    /// [`capacity()`]: Vec::capacity
2142    ///
2143    /// # Examples
2144    ///
2145    /// See [`spare_capacity_mut()`] for an example with safe
2146    /// initialization of capacity elements and use of this method.
2147    ///
2148    /// `set_len()` can be useful for situations in which the vector
2149    /// is serving as a buffer for other code, particularly over FFI:
2150    ///
2151    /// ```no_run
2152    /// # #![allow(dead_code)]
2153    /// # // This is just a minimal skeleton for the doc example;
2154    /// # // don't use this as a starting point for a real library.
2155    /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
2156    /// # const Z_OK: i32 = 0;
2157    /// # unsafe extern "C" {
2158    /// #     fn deflateGetDictionary(
2159    /// #         strm: *mut std::ffi::c_void,
2160    /// #         dictionary: *mut u8,
2161    /// #         dictLength: *mut usize,
2162    /// #     ) -> i32;
2163    /// # }
2164    /// # impl StreamWrapper {
2165    /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
2166    ///     // Per the FFI method's docs, "32768 bytes is always enough".
2167    ///     let mut dict = Vec::with_capacity(32_768);
2168    ///     let mut dict_length = 0;
2169    ///     // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
2170    ///     // 1. `dict_length` elements were initialized.
2171    ///     // 2. `dict_length` <= the capacity (32_768)
2172    ///     // which makes `set_len` safe to call.
2173    ///     unsafe {
2174    ///         // Make the FFI call...
2175    ///         let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
2176    ///         if r == Z_OK {
2177    ///             // ...and update the length to what was initialized.
2178    ///             dict.set_len(dict_length);
2179    ///             Some(dict)
2180    ///         } else {
2181    ///             None
2182    ///         }
2183    ///     }
2184    /// }
2185    /// # }
2186    /// ```
2187    ///
2188    /// While the following example is sound, there is a memory leak since
2189    /// the inner vectors were not freed prior to the `set_len` call:
2190    ///
2191    /// ```
2192    /// let mut vec = vec![vec![1, 0, 0],
2193    ///                    vec![0, 1, 0],
2194    ///                    vec![0, 0, 1]];
2195    /// // SAFETY:
2196    /// // 1. `old_len..0` is empty so no elements need to be initialized.
2197    /// // 2. `0 <= capacity` always holds whatever `capacity` is.
2198    /// unsafe {
2199    ///     vec.set_len(0);
2200    /// #   // FIXME(https://github.com/rust-lang/miri/issues/3670):
2201    /// #   // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
2202    /// #   vec.set_len(3);
2203    /// }
2204    /// ```
2205    ///
2206    /// Normally, here, one would use [`clear`] instead to correctly drop
2207    /// the contents and thus not leak memory.
2208    ///
2209    /// [`spare_capacity_mut()`]: Vec::spare_capacity_mut
2210    #[inline]
2211    #[stable(feature = "rust1", since = "1.0.0")]
2212    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2213    pub const unsafe fn set_len(&mut self, new_len: usize) {
2214        ub_checks::assert_unsafe_precondition!(
2215            check_library_ub,
2216            "Vec::set_len requires that new_len <= capacity()",
2217            (new_len: usize = new_len, capacity: usize = self.capacity()) => new_len <= capacity
2218        );
2219
2220        self.len = new_len;
2221    }
2222
2223    /// Removes an element from the vector and returns it.
2224    ///
2225    /// The removed element is replaced by the last element of the vector.
2226    ///
2227    /// This does not preserve ordering of the remaining elements, but is *O*(1).
2228    /// If you need to preserve the element order, use [`remove`] instead.
2229    ///
2230    /// [`remove`]: Vec::remove
2231    ///
2232    /// # Panics
2233    ///
2234    /// Panics if `index` is out of bounds.
2235    ///
2236    /// # Examples
2237    ///
2238    /// ```
2239    /// let mut v = vec!["foo", "bar", "baz", "qux"];
2240    ///
2241    /// assert_eq!(v.swap_remove(1), "bar");
2242    /// assert_eq!(v, ["foo", "qux", "baz"]);
2243    ///
2244    /// assert_eq!(v.swap_remove(0), "foo");
2245    /// assert_eq!(v, ["baz", "qux"]);
2246    /// ```
2247    #[inline]
2248    #[stable(feature = "rust1", since = "1.0.0")]
2249    pub fn swap_remove(&mut self, index: usize) -> T {
2250        #[cold]
2251        #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2252        #[optimize(size)]
2253        fn assert_failed(index: usize, len: usize) -> ! {
2254            panic!("swap_remove index (is {index}) should be < len (is {len})");
2255        }
2256
2257        let len = self.len();
2258        if index >= len {
2259            assert_failed(index, len);
2260        }
2261        // ignore-tidy-undocumented-unsafe
2262        unsafe {
2263            // We replace self[index] with the last element. Note that if the
2264            // bounds check above succeeds there must be a last element (which
2265            // can be self[index] itself).
2266            let value = ptr::read(self.as_ptr().add(index));
2267            let base_ptr = self.as_mut_ptr();
2268            ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
2269            self.set_len(len - 1);
2270            value
2271        }
2272    }
2273
2274    /// Inserts an element at position `index` within the vector, shifting all
2275    /// elements after it to the right.
2276    ///
2277    /// # Panics
2278    ///
2279    /// Panics if `index > len`.
2280    ///
2281    /// # Examples
2282    ///
2283    /// ```
2284    /// let mut vec = vec!['a', 'b', 'c'];
2285    /// vec.insert(1, 'd');
2286    /// assert_eq!(vec, ['a', 'd', 'b', 'c']);
2287    /// vec.insert(4, 'e');
2288    /// assert_eq!(vec, ['a', 'd', 'b', 'c', 'e']);
2289    /// ```
2290    ///
2291    /// # Time complexity
2292    ///
2293    /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be
2294    /// shifted to the right. In the worst case, all elements are shifted when
2295    /// the insertion index is 0.
2296    #[cfg(not(no_global_oom_handling))]
2297    #[stable(feature = "rust1", since = "1.0.0")]
2298    #[track_caller]
2299    pub fn insert(&mut self, index: usize, element: T) {
2300        let _ = self.insert_mut(index, element);
2301    }
2302
2303    /// Inserts an element at position `index` within the vector, shifting all
2304    /// elements after it to the right, and returning a reference to the new
2305    /// element.
2306    ///
2307    /// # Panics
2308    ///
2309    /// Panics if `index > len`.
2310    ///
2311    /// # Examples
2312    ///
2313    /// ```
2314    /// let mut vec = vec![1, 3, 5, 9];
2315    /// let x = vec.insert_mut(3, 6);
2316    /// *x += 1;
2317    /// assert_eq!(vec, [1, 3, 5, 7, 9]);
2318    /// ```
2319    ///
2320    /// # Time complexity
2321    ///
2322    /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be
2323    /// shifted to the right. In the worst case, all elements are shifted when
2324    /// the insertion index is 0.
2325    #[cfg(not(no_global_oom_handling))]
2326    #[inline]
2327    #[stable(feature = "push_mut", since = "1.95.0")]
2328    #[track_caller]
2329    #[must_use = "if you don't need a reference to the value, use `Vec::insert` instead"]
2330    pub fn insert_mut(&mut self, index: usize, element: T) -> &mut T {
2331        #[cold]
2332        #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2333        #[track_caller]
2334        #[optimize(size)]
2335        fn assert_failed(index: usize, len: usize) -> ! {
2336            panic!("insertion index (is {index}) should be <= len (is {len})");
2337        }
2338
2339        let len = self.len();
2340        if index > len {
2341            assert_failed(index, len);
2342        }
2343
2344        // space for the new element
2345        if len == self.buf.capacity() {
2346            self.buf.grow_one();
2347        }
2348
2349        // ignore-tidy-undocumented-unsafe
2350        unsafe {
2351            // infallible
2352            // The spot to put the new value
2353            let p = self.as_mut_ptr().add(index);
2354            {
2355                if index < len {
2356                    // Shift everything over to make space. (Duplicating the
2357                    // `index`th element into two consecutive places.)
2358                    ptr::copy(p, p.add(1), len - index);
2359                }
2360                // Write it in, overwriting the first copy of the `index`th
2361                // element.
2362                ptr::write(p, element);
2363            }
2364            self.set_len(len + 1);
2365            &mut *p
2366        }
2367    }
2368
2369    /// Removes and returns the element at position `index` within the vector,
2370    /// shifting all elements after it to the left.
2371    ///
2372    /// Note: Because this shifts over the remaining elements, it has a
2373    /// worst-case performance of *O*(*n*). If you don't need the order of elements
2374    /// to be preserved, use [`swap_remove`] instead. If you'd like to remove
2375    /// elements from the beginning of the `Vec`, consider using
2376    /// [`VecDeque::pop_front`] instead.
2377    ///
2378    /// [`swap_remove`]: Vec::swap_remove
2379    /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2380    ///
2381    /// # Panics
2382    ///
2383    /// Panics if `index` is out of bounds.
2384    ///
2385    /// # Examples
2386    ///
2387    /// ```
2388    /// let mut v = vec!['a', 'b', 'c'];
2389    /// assert_eq!(v.remove(1), 'b');
2390    /// assert_eq!(v, ['a', 'c']);
2391    /// ```
2392    #[stable(feature = "rust1", since = "1.0.0")]
2393    #[track_caller]
2394    #[rustc_confusables("delete", "take")]
2395    pub fn remove(&mut self, index: usize) -> T {
2396        #[cold]
2397        #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2398        #[track_caller]
2399        #[optimize(size)]
2400        fn assert_failed(index: usize, len: usize) -> ! {
2401            panic!("removal index (is {index}) should be < len (is {len})");
2402        }
2403
2404        match self.try_remove(index) {
2405            Some(elem) => elem,
2406            None => assert_failed(index, self.len()),
2407        }
2408    }
2409
2410    /// Remove and return the element at position `index` within the vector,
2411    /// shifting all elements after it to the left, or [`None`] if it does not
2412    /// exist.
2413    ///
2414    /// Note: Because this shifts over the remaining elements, it has a
2415    /// worst-case performance of *O*(*n*). If you'd like to remove
2416    /// elements from the beginning of the `Vec`, consider using
2417    /// [`VecDeque::pop_front`] instead.
2418    ///
2419    /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2420    ///
2421    /// # Examples
2422    ///
2423    /// ```
2424    /// let mut v = vec![1, 2, 3];
2425    /// assert_eq!(v.try_remove(0), Some(1));
2426    /// assert_eq!(v.try_remove(2), None);
2427    /// ```
2428    #[stable(feature = "vec_try_remove", since = "CURRENT_RUSTC_VERSION")]
2429    #[rustc_confusables("delete", "take", "remove")]
2430    pub fn try_remove(&mut self, index: usize) -> Option<T> {
2431        let len = self.len();
2432        if index >= len {
2433            return None;
2434        }
2435        // infallible
2436        let ret;
2437        // ignore-tidy-undocumented-unsafe
2438        unsafe {
2439            {
2440                // the place we are taking from.
2441                let ptr = self.as_mut_ptr().add(index);
2442                // copy it out, unsafely having a copy of the value on
2443                // the stack and in the vector at the same time.
2444                ret = ptr::read(ptr);
2445
2446                // Shift everything down to fill in that spot.
2447                ptr::copy(ptr.add(1), ptr, len - index - 1);
2448            }
2449            self.set_len(len - 1);
2450        }
2451        Some(ret)
2452    }
2453
2454    /// Retains only the elements specified by the predicate.
2455    ///
2456    /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
2457    /// This method operates in place, visiting each element exactly once in the
2458    /// original order, and preserves the order of the retained elements.
2459    ///
2460    /// # Examples
2461    ///
2462    /// ```
2463    /// let mut vec = vec![1, 2, 3, 4];
2464    /// vec.retain(|&x| x % 2 == 0);
2465    /// assert_eq!(vec, [2, 4]);
2466    /// ```
2467    ///
2468    /// Because the elements are visited exactly once in the original order,
2469    /// external state may be used to decide which elements to keep.
2470    ///
2471    /// ```
2472    /// let mut vec = vec![1, 2, 3, 4, 5];
2473    /// let keep = [false, true, true, false, true];
2474    /// let mut iter = keep.iter();
2475    /// vec.retain(|_| *iter.next().unwrap());
2476    /// assert_eq!(vec, [2, 3, 5]);
2477    /// ```
2478    #[stable(feature = "rust1", since = "1.0.0")]
2479    pub fn retain<F>(&mut self, mut f: F)
2480    where
2481        F: FnMut(&T) -> bool,
2482    {
2483        self.retain_mut(|elem| f(elem));
2484    }
2485
2486    /// Retains only the elements specified by the predicate, passing a mutable reference to it.
2487    ///
2488    /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
2489    /// This method operates in place, visiting each element exactly once in the
2490    /// original order, and preserves the order of the retained elements.
2491    ///
2492    /// # Examples
2493    ///
2494    /// ```
2495    /// let mut vec = vec![1, 2, 3, 4];
2496    /// vec.retain_mut(|x| if *x <= 3 {
2497    ///     *x += 1;
2498    ///     true
2499    /// } else {
2500    ///     false
2501    /// });
2502    /// assert_eq!(vec, [2, 3, 4]);
2503    /// ```
2504    #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2505    pub fn retain_mut<F>(&mut self, mut f: F)
2506    where
2507        F: FnMut(&mut T) -> bool,
2508    {
2509        let original_len = self.len();
2510
2511        if original_len == 0 {
2512            // Empty case: explicit return allows better optimization, vs letting compiler infer it
2513            return;
2514        }
2515
2516        #[cfg(all(target_arch = "aarch64", target_feature = "sve"))]
2517        {
2518            let long_enough = match mem::size_of::<T>() {
2519                1 => original_len >= sve_retain::MIN_SVE_SIZE_1,
2520                2 => original_len >= sve_retain::MIN_SVE_SIZE_2,
2521                4 => original_len >= sve_retain::MIN_SVE_SIZE_4,
2522                8 => original_len >= sve_retain::MIN_SVE_SIZE_8,
2523                _ => false,
2524            };
2525            if long_enough {
2526                // SAFETY: size_of::<T>() is 1, 2, 4 or 8, matching
2527                // the kernel lane widths.
2528                return unsafe { sve_retain::chunked_retain(self, f) };
2529            }
2530        }
2531
2532        // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
2533        //      |            ^- write                ^- read             |
2534        //      |<-              original_len                          ->|
2535        // Kept: Elements which predicate returns true on.
2536        // Hole: Moved or dropped element slot.
2537        // Unchecked: Unchecked valid elements.
2538        //
2539        // This drop guard will be invoked when predicate or `drop` of element panicked.
2540        // It shifts unchecked elements to cover holes and `set_len` to the correct length.
2541        // In cases when predicate and `drop` never panick, it will be optimized out.
2542        struct PanicGuard<'a, T, A: Allocator> {
2543            v: &'a mut Vec<T, A>,
2544            read: usize,
2545            write: usize,
2546            original_len: usize,
2547        }
2548
2549        impl<T, A: Allocator> Drop for PanicGuard<'_, T, A> {
2550            #[cold]
2551            fn drop(&mut self) {
2552                let remaining = self.original_len - self.read;
2553                // SAFETY: Trailing unchecked items must be valid since we never touch them.
2554                unsafe {
2555                    ptr::copy(
2556                        self.v.as_ptr().add(self.read),
2557                        self.v.as_mut_ptr().add(self.write),
2558                        remaining,
2559                    );
2560                }
2561                // SAFETY: After filling holes, all items are in contiguous memory.
2562                unsafe {
2563                    self.v.set_len(self.write + remaining);
2564                }
2565            }
2566        }
2567
2568        let mut read = 0;
2569        loop {
2570            // SAFETY: read < original_len
2571            let cur = unsafe { self.get_unchecked_mut(read) };
2572            if hint::unlikely(!f(cur)) {
2573                break;
2574            }
2575            read += 1;
2576            if read == original_len {
2577                // All elements are kept, return early.
2578                return;
2579            }
2580        }
2581
2582        // Critical section starts here and at least one element is going to be removed.
2583        // Advance `g.read` early to avoid double drop if `drop_in_place` panicked.
2584        let mut g = PanicGuard { v: self, read: read + 1, write: read, original_len };
2585        // SAFETY: previous `read` is always less than original_len.
2586        unsafe { ptr::drop_in_place(&mut *g.v.as_mut_ptr().add(read)) };
2587
2588        while g.read < g.original_len {
2589            // SAFETY: `read` is always less than original_len.
2590            let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.read) };
2591            if !f(cur) {
2592                // Advance `read` early to avoid double drop if `drop_in_place` panicked.
2593                g.read += 1;
2594                // SAFETY: We never touch this element again after dropped.
2595                unsafe { ptr::drop_in_place(cur) };
2596            } else {
2597                // SAFETY: `read` > `write`, so the slots don't overlap.
2598                // We use copy for move, and never touch the source element again.
2599                unsafe {
2600                    let hole = g.v.as_mut_ptr().add(g.write);
2601                    ptr::copy_nonoverlapping(cur, hole, 1);
2602                }
2603                g.write += 1;
2604                g.read += 1;
2605            }
2606        }
2607
2608        // We are leaving the critical section and no panic happened,
2609        // Commit the length change and forget the guard.
2610        // SAFETY: `write` is always less than or equal to original_len.
2611        unsafe { g.v.set_len(g.write) };
2612        mem::forget(g);
2613    }
2614
2615    /// Removes all but the first of consecutive elements in the vector that resolve to the same
2616    /// key.
2617    ///
2618    /// If the vector is sorted, this removes all duplicates.
2619    ///
2620    /// # Examples
2621    ///
2622    /// ```
2623    /// let mut vec = vec![10, 20, 21, 30, 20];
2624    ///
2625    /// vec.dedup_by_key(|i| *i / 10);
2626    ///
2627    /// assert_eq!(vec, [10, 20, 30, 20]);
2628    /// ```
2629    #[stable(feature = "dedup_by", since = "1.16.0")]
2630    #[inline]
2631    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
2632    where
2633        F: FnMut(&mut T) -> K,
2634        K: PartialEq,
2635    {
2636        self.dedup_by(|a, b| key(a) == key(b))
2637    }
2638
2639    /// Removes all but the first of consecutive elements in the vector that are
2640    /// "equal" according to the given predicate function.
2641    ///
2642    /// The predicate `same_bucket(x, p)` is passed references to two elements.
2643    /// If it returns `true`, the element `x` is removed from the vector.
2644    ///
2645    /// The element `p` occurs *before* `x` in the vector (`[.., p, .., x, ..]`),
2646    /// so `same_bucket(x, p)` is receiving them in reversed order (unlike [`windows`]).
2647    ///
2648    /// If the vector is sorted, this removes all duplicates. For more complicated predicates
2649    /// however, the order (ascending vs. descending) can matter.
2650    ///
2651    /// [`windows`]: slice::windows
2652    ///
2653    /// # Examples
2654    ///
2655    /// ```
2656    /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
2657    /// vec.dedup_by(|x, p| x.eq_ignore_ascii_case(p));
2658    /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
2659    /// ```
2660    ///
2661    /// Both references passed to `same_bucket` are mutable.
2662    /// This allows merging elements by mutating `p` and returning `true`:
2663    ///
2664    /// ```
2665    /// let mut ranges = vec![1..2, 2..4, 2..5, 8..9];
2666    ///
2667    /// // Sort ranges by start, and if equal, by end (lexicographically)
2668    /// // Sorting in reverse instead (`x.start.cmp(&p.start)...`) would later fail
2669    /// ranges.sort_unstable_by(|p, x| p.start.cmp(&x.start).then(p.end.cmp(&x.end)));
2670    ///
2671    /// // Merge touching (`1..2` and `2..4`) and then overlapping (`1..4` and `2..5`) ranges
2672    /// ranges.dedup_by(|x, p| {
2673    ///     if p.end >= x.start {
2674    ///         p.end = p.end.max(x.end);
2675    ///         true
2676    ///     } else {
2677    ///         false
2678    ///     }
2679    /// });
2680    ///
2681    /// assert_eq!(ranges, [1..5, 8..9]);
2682    /// ```
2683    #[stable(feature = "dedup_by", since = "1.16.0")]
2684    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
2685    where
2686        F: FnMut(&mut T, &mut T) -> bool,
2687    {
2688        let len = self.len();
2689        if len <= 1 {
2690            return;
2691        }
2692
2693        // Check if we ever want to remove anything.
2694        // This allows to use copy_non_overlapping in next cycle.
2695        // And avoids any memory writes if we don't need to remove anything.
2696        let mut first_duplicate_idx: usize = 1;
2697        let start = self.as_mut_ptr();
2698        while first_duplicate_idx != len {
2699            let found_duplicate = {
2700                // SAFETY: first_duplicate always in range [1..len).
2701                // Note that we start iteration from 1 so we never overflow.
2702                let prev = unsafe { start.add(first_duplicate_idx.wrapping_sub(1)) };
2703                // ignore-tidy-undocumented-unsafe
2704                let current = unsafe { start.add(first_duplicate_idx) };
2705                // We explicitly say in docs that references are reversed.
2706                // ignore-tidy-undocumented-unsafe
2707                unsafe { same_bucket(&mut *current, &mut *prev) }
2708            };
2709            if found_duplicate {
2710                break;
2711            }
2712            first_duplicate_idx += 1;
2713        }
2714        // Don't need to remove anything.
2715        // We cannot get bigger than len.
2716        if first_duplicate_idx == len {
2717            return;
2718        }
2719
2720        /* INVARIANT: vec.len() > read > write > write-1 >= 0 */
2721        struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> {
2722            /* Offset of the element we want to check if it is duplicate */
2723            read: usize,
2724
2725            /* Offset of the place where we want to place the non-duplicate
2726             * when we find it. */
2727            write: usize,
2728
2729            /* The Vec that would need correction if `same_bucket` panicked */
2730            vec: &'a mut Vec<T, A>,
2731        }
2732
2733        impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
2734            fn drop(&mut self) {
2735                /* This code gets executed when `same_bucket` panics */
2736
2737                // SAFETY: invariant guarantees that `read - write`
2738                // and `len - read` never overflow and that the copy is always
2739                // in-bounds.
2740                unsafe {
2741                    let ptr = self.vec.as_mut_ptr();
2742                    let len = self.vec.len();
2743
2744                    /* How many items were left when `same_bucket` panicked.
2745                     * Basically vec[read..].len() */
2746                    let items_left = len.wrapping_sub(self.read);
2747
2748                    /* Pointer to first item in vec[write..write+items_left] slice */
2749                    let dropped_ptr = ptr.add(self.write);
2750                    /* Pointer to first item in vec[read..] slice */
2751                    let valid_ptr = ptr.add(self.read);
2752
2753                    /* Copy `vec[read..]` to `vec[write..write+items_left]`.
2754                     * The slices can overlap, so `copy_nonoverlapping` cannot be used */
2755                    ptr::copy(valid_ptr, dropped_ptr, items_left);
2756
2757                    /* How many items have been already dropped
2758                     * Basically vec[read..write].len() */
2759                    let dropped = self.read.wrapping_sub(self.write);
2760
2761                    self.vec.set_len(len - dropped);
2762                }
2763            }
2764        }
2765
2766        /* Drop items while going through Vec, it should be more efficient than
2767         * doing slice partition_dedup + truncate */
2768
2769        // Construct gap first and then drop item to avoid memory corruption if `T::drop` panics.
2770        let mut gap =
2771            FillGapOnDrop { read: first_duplicate_idx + 1, write: first_duplicate_idx, vec: self };
2772        // SAFETY: we checked that first_duplicate_idx in bounds before.
2773        // If drop panics, `gap` would remove this item without drop.
2774        unsafe {
2775            ptr::drop_in_place(start.add(first_duplicate_idx));
2776        }
2777
2778        // SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
2779        // are always in-bounds and read_ptr never aliases prev_ptr
2780        unsafe {
2781            while gap.read < len {
2782                let read_ptr = start.add(gap.read);
2783                let prev_ptr = start.add(gap.write.wrapping_sub(1));
2784
2785                // We explicitly say in docs that references are reversed.
2786                let found_duplicate = same_bucket(&mut *read_ptr, &mut *prev_ptr);
2787                if found_duplicate {
2788                    // Increase `gap.read` now since the drop may panic.
2789                    gap.read += 1;
2790                    /* We have found duplicate, drop it in-place */
2791                    ptr::drop_in_place(read_ptr);
2792                } else {
2793                    let write_ptr = start.add(gap.write);
2794
2795                    /* read_ptr cannot be equal to write_ptr because at this point
2796                     * we guaranteed to skip at least one element (before loop starts).
2797                     */
2798                    ptr::copy_nonoverlapping(read_ptr, write_ptr, 1);
2799
2800                    /* We have filled that place, so go further */
2801                    gap.write += 1;
2802                    gap.read += 1;
2803                }
2804            }
2805
2806            /* Technically we could let `gap` clean up with its Drop, but
2807             * when `same_bucket` is guaranteed to not panic, this bloats a little
2808             * the codegen, so we just do it manually */
2809            gap.vec.set_len(gap.write);
2810            mem::forget(gap);
2811        }
2812    }
2813
2814    /// Appends an element and returns a reference to it if there is sufficient spare capacity,
2815    /// otherwise an error is returned with the element.
2816    ///
2817    /// Unlike [`push`] this method will not reallocate when there's insufficient capacity.
2818    /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity.
2819    ///
2820    /// [`push`]: Vec::push
2821    /// [`reserve`]: Vec::reserve
2822    /// [`try_reserve`]: Vec::try_reserve
2823    ///
2824    /// # Examples
2825    ///
2826    /// A manual, panic-free alternative to [`FromIterator`]:
2827    ///
2828    /// ```
2829    /// #![feature(vec_push_within_capacity)]
2830    ///
2831    /// use std::collections::TryReserveError;
2832    /// fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
2833    ///     let mut vec = Vec::new();
2834    ///     for value in iter {
2835    ///         if let Err(value) = vec.push_within_capacity(value) {
2836    ///             vec.try_reserve(1)?;
2837    ///             // this cannot fail, the previous line either returned or added at least 1 free slot
2838    ///             let _ = vec.push_within_capacity(value);
2839    ///         }
2840    ///     }
2841    ///     Ok(vec)
2842    /// }
2843    /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
2844    /// ```
2845    ///
2846    /// # Time complexity
2847    ///
2848    /// Takes *O*(1) time.
2849    #[inline]
2850    #[unstable(feature = "vec_push_within_capacity", issue = "100486")]
2851    pub fn push_within_capacity(&mut self, value: T) -> Result<&mut T, T> {
2852        if self.len == self.buf.capacity() {
2853            return Err(value);
2854        }
2855
2856        // ignore-tidy-undocumented-unsafe
2857        let end = unsafe { self.as_mut_ptr().add(self.len) };
2858        // ignore-tidy-undocumented-unsafe
2859        unsafe { ptr::write(end, value) };
2860        self.len += 1;
2861
2862        // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference.
2863        Ok(unsafe { &mut *end })
2864    }
2865
2866    /// Removes the last element from a vector and returns it, or [`None`] if it
2867    /// is empty.
2868    ///
2869    /// If you'd like to pop the first element, consider using
2870    /// [`VecDeque::pop_front`] instead.
2871    ///
2872    /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2873    ///
2874    /// # Examples
2875    ///
2876    /// ```
2877    /// let mut vec = vec![1, 2, 3];
2878    /// assert_eq!(vec.pop(), Some(3));
2879    /// assert_eq!(vec, [1, 2]);
2880    /// ```
2881    ///
2882    /// # Time complexity
2883    ///
2884    /// Takes *O*(1) time.
2885    #[inline]
2886    #[stable(feature = "rust1", since = "1.0.0")]
2887    #[rustc_diagnostic_item = "vec_pop"]
2888    pub fn pop(&mut self) -> Option<T> {
2889        if self.len == 0 {
2890            None
2891        } else {
2892            self.len -= 1;
2893            // ignore-tidy-undocumented-unsafe
2894            unsafe {
2895                core::hint::assert_unchecked(self.len < self.capacity());
2896                Some(ptr::read(self.as_ptr().add(self.len())))
2897            }
2898        }
2899    }
2900
2901    /// Removes and returns the last element from a vector if the predicate
2902    /// returns `true`, or [`None`] if the predicate returns false or the vector
2903    /// is empty (the predicate will not be called in that case).
2904    ///
2905    /// # Examples
2906    ///
2907    /// ```
2908    /// let mut vec = vec![1, 2, 3, 4];
2909    /// let pred = |x: &mut i32| *x % 2 == 0;
2910    ///
2911    /// assert_eq!(vec.pop_if(pred), Some(4));
2912    /// assert_eq!(vec, [1, 2, 3]);
2913    /// assert_eq!(vec.pop_if(pred), None);
2914    /// ```
2915    #[stable(feature = "vec_pop_if", since = "1.86.0")]
2916    pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2917        let last = self.last_mut()?;
2918        if predicate(last) { self.pop() } else { None }
2919    }
2920
2921    /// Returns a mutable reference to the last item in the vector, or
2922    /// `None` if it is empty.
2923    ///
2924    /// # Examples
2925    ///
2926    /// Basic usage:
2927    ///
2928    /// ```
2929    /// #![feature(vec_peek_mut)]
2930    /// let mut vec = Vec::new();
2931    /// assert!(vec.peek_mut().is_none());
2932    ///
2933    /// vec.push(1);
2934    /// vec.push(5);
2935    /// vec.push(2);
2936    /// assert_eq!(vec.last(), Some(&2));
2937    /// if let Some(mut val) = vec.peek_mut() {
2938    ///     *val = 0;
2939    /// }
2940    /// assert_eq!(vec.last(), Some(&0));
2941    /// ```
2942    #[inline]
2943    #[unstable(feature = "vec_peek_mut", issue = "122742")]
2944    pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, A>>
2945    where
2946        A: AllocatorNightly,
2947    {
2948        PeekMut::new(self)
2949    }
2950
2951    /// Moves all the elements of `other` into `self`, leaving `other` empty.
2952    ///
2953    /// # Panics
2954    ///
2955    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
2956    ///
2957    /// # Examples
2958    ///
2959    /// ```
2960    /// let mut vec = vec![1, 2, 3];
2961    /// let mut vec2 = vec![4, 5, 6];
2962    /// vec.append(&mut vec2);
2963    /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
2964    /// assert_eq!(vec2, []);
2965    /// ```
2966    #[cfg(not(no_global_oom_handling))]
2967    #[inline]
2968    #[stable(feature = "append", since = "1.4.0")]
2969    pub fn append(&mut self, other: &mut Self) {
2970        // ignore-tidy-undocumented-unsafe
2971        unsafe {
2972            self.append_elements(other.as_slice() as _);
2973            other.set_len(0);
2974        }
2975    }
2976
2977    /// Appends elements to `self` from other buffer.
2978    #[cfg(not(no_global_oom_handling))]
2979    #[inline]
2980    unsafe fn append_elements(&mut self, other: *const [T]) {
2981        self.reserve(other.len());
2982        // ignore-tidy-undocumented-unsafe
2983        unsafe {
2984            self.append_elements_unreserved(other);
2985        }
2986    }
2987
2988    /// Appends elements to `self` from other buffer, returning [`TryReserveError`] on OOM.
2989    #[inline]
2990    unsafe fn try_append_elements(&mut self, other: *const [T]) -> Result<(), TryReserveError> {
2991        self.try_reserve(other.len())?;
2992        // ignore-tidy-undocumented-unsafe
2993        unsafe {
2994            self.append_elements_unreserved(other);
2995        }
2996        Ok(())
2997    }
2998
2999    /// Appends elements to `self` from other buffer without reserving additional capacity.
3000    #[inline]
3001    unsafe fn append_elements_unreserved(&mut self, other: *const [T]) {
3002        let count = other.len();
3003        let len = self.len();
3004        if count > 0 {
3005            // ignore-tidy-undocumented-unsafe
3006            unsafe {
3007                ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count)
3008            };
3009        }
3010        self.len += count;
3011    }
3012
3013    /// Removes the subslice indicated by the given range from the vector,
3014    /// returning a double-ended iterator over the removed subslice.
3015    ///
3016    /// If the iterator is dropped before being fully consumed,
3017    /// it drops the remaining removed elements.
3018    ///
3019    /// The returned iterator keeps a mutable borrow on the vector to optimize
3020    /// its implementation.
3021    ///
3022    /// # Panics
3023    ///
3024    /// Panics if the range has `start_bound > end_bound`, or, if the range is
3025    /// bounded on either end and past the length of the vector.
3026    ///
3027    /// # Leaking
3028    ///
3029    /// If the returned iterator goes out of scope without being dropped (due to
3030    /// [`mem::forget`], for example), the vector may have lost and leaked
3031    /// elements arbitrarily, including elements outside the range.
3032    ///
3033    /// # Examples
3034    ///
3035    /// ```
3036    /// let mut v = vec![1, 2, 3];
3037    /// let u: Vec<_> = v.drain(1..).collect();
3038    /// assert_eq!(v, &[1]);
3039    /// assert_eq!(u, &[2, 3]);
3040    ///
3041    /// // A full range clears the vector, like `clear()` does
3042    /// v.drain(..);
3043    /// assert_eq!(v, &[]);
3044    /// ```
3045    #[stable(feature = "drain", since = "1.6.0")]
3046    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
3047    where
3048        A: AllocatorNightly,
3049        R: RangeBounds<usize>,
3050    {
3051        // Memory safety
3052        //
3053        // When the Drain is first created, it shortens the length of
3054        // the source vector to make sure no uninitialized or moved-from elements
3055        // are accessible at all if the Drain's destructor never gets to run.
3056        //
3057        // Drain will ptr::read out the values to remove.
3058        // When finished, remaining tail of the vec is copied back to cover
3059        // the hole, and the vector length is restored to the new length.
3060        //
3061        let len = self.len();
3062        let Range { start, end } = slice::range(range, ..len);
3063
3064        // ignore-tidy-undocumented-unsafe
3065        unsafe {
3066            // set self.vec length's to start, to be safe in case Drain is leaked
3067            self.set_len(start);
3068            let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
3069            Drain {
3070                tail_start: end,
3071                tail_len: len - end,
3072                iter: range_slice.iter(),
3073                vec: NonNull::from(self),
3074            }
3075        }
3076    }
3077
3078    /// Clears the vector, removing all values.
3079    ///
3080    /// Note that this method has no effect on the allocated capacity
3081    /// of the vector.
3082    ///
3083    /// # Examples
3084    ///
3085    /// ```
3086    /// let mut v = vec![1, 2, 3];
3087    ///
3088    /// v.clear();
3089    ///
3090    /// assert!(v.is_empty());
3091    /// ```
3092    #[inline]
3093    #[stable(feature = "rust1", since = "1.0.0")]
3094    pub fn clear(&mut self) {
3095        // Though this is equivalent to `truncate(0)`, the manual version
3096        // optimizes better, justifying the additional complexity
3097        // (see #96002 and #154095 for context).
3098
3099        let elems: *mut [T] = self.as_mut_slice();
3100
3101        // SAFETY:
3102        // - `elems` comes directly from `as_mut_slice` and is therefore valid.
3103        // - Setting `self.len` before calling `drop_in_place` means that,
3104        //   if an element's `Drop` impl panics, the vector's `Drop` impl will
3105        //   do nothing (leaking the rest of the elements) instead of dropping
3106        //   some twice.
3107        unsafe {
3108            self.len = 0;
3109            ptr::drop_in_place(elems);
3110        }
3111    }
3112
3113    /// Returns the number of elements in the vector, also referred to
3114    /// as its 'length'.
3115    ///
3116    /// # Examples
3117    ///
3118    /// ```
3119    /// let a = vec![1, 2, 3];
3120    /// assert_eq!(a.len(), 3);
3121    /// ```
3122    #[inline]
3123    #[stable(feature = "rust1", since = "1.0.0")]
3124    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
3125    #[rustc_confusables("length", "size")]
3126    pub const fn len(&self) -> usize {
3127        let len = self.len;
3128
3129        // SAFETY: The maximum capacity of `Vec<T>` is `isize::MAX` bytes, so the maximum value can
3130        // be returned is `usize::checked_div(size_of::<T>()).unwrap_or(usize::MAX)`, which
3131        // matches the definition of `T::MAX_SLICE_LEN`.
3132        unsafe { intrinsics::assume(len <= T::MAX_SLICE_LEN) };
3133
3134        len
3135    }
3136
3137    /// Returns `true` if the vector contains no elements.
3138    ///
3139    /// # Examples
3140    ///
3141    /// ```
3142    /// let mut v = Vec::new();
3143    /// assert!(v.is_empty());
3144    ///
3145    /// v.push(1);
3146    /// assert!(!v.is_empty());
3147    /// ```
3148    #[stable(feature = "rust1", since = "1.0.0")]
3149    #[rustc_diagnostic_item = "vec_is_empty"]
3150    #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
3151    pub const fn is_empty(&self) -> bool {
3152        self.len() == 0
3153    }
3154
3155    /// Splits the collection into two at the given index.
3156    ///
3157    /// Returns a newly allocated vector containing the elements in the range
3158    /// `[at, len)`. After the call, the original vector will be left containing
3159    /// the elements `[0, at)` with its previous capacity unchanged.
3160    ///
3161    /// - If you want to take ownership of the entire contents and capacity of
3162    ///   the vector, see [`mem::take`] or [`mem::replace`].
3163    /// - If you don't need the returned vector at all, see [`Vec::truncate`].
3164    /// - If you want to take ownership of an arbitrary subslice, or you don't
3165    ///   necessarily want to store the removed items in a vector, see [`Vec::drain`].
3166    ///
3167    /// # Panics
3168    ///
3169    /// Panics if `at > len`.
3170    ///
3171    /// # Examples
3172    ///
3173    /// ```
3174    /// let mut vec = vec!['a', 'b', 'c'];
3175    /// let vec2 = vec.split_off(1);
3176    /// assert_eq!(vec, ['a']);
3177    /// assert_eq!(vec2, ['b', 'c']);
3178    /// ```
3179    #[cfg(not(no_global_oom_handling))]
3180    #[inline]
3181    #[must_use = "use `.truncate()` if you don't need the other half"]
3182    #[stable(feature = "split_off", since = "1.4.0")]
3183    #[track_caller]
3184    pub fn split_off(&mut self, at: usize) -> Self
3185    where
3186        A: Clone,
3187    {
3188        #[cold]
3189        #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
3190        #[track_caller]
3191        #[optimize(size)]
3192        fn assert_failed(at: usize, len: usize) -> ! {
3193            panic!("`at` split index (is {at}) should be <= len (is {len})");
3194        }
3195
3196        if at > self.len() {
3197            assert_failed(at, self.len());
3198        }
3199
3200        let other_len = self.len - at;
3201        let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
3202
3203        // Unsafely `set_len` and copy items to `other`.
3204        // ignore-tidy-undocumented-unsafe
3205        unsafe {
3206            self.set_len(at);
3207            other.set_len(other_len);
3208
3209            ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
3210        }
3211        other
3212    }
3213
3214    /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
3215    ///
3216    /// If `new_len` is greater than `len`, the `Vec` is extended by the
3217    /// difference, with each additional slot filled with the result of
3218    /// calling the closure `f`. The return values from `f` will end up
3219    /// in the `Vec` in the order they have been generated.
3220    ///
3221    /// If `new_len` is less than `len`, the `Vec` is simply truncated.
3222    ///
3223    /// This method uses a closure to create new values on every push. If
3224    /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
3225    /// want to use the [`Default`] trait to generate values, you can
3226    /// pass [`Default::default`] as the second argument.
3227    ///
3228    /// # Panics
3229    ///
3230    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3231    ///
3232    /// # Examples
3233    ///
3234    /// ```
3235    /// let mut vec = vec![1, 2, 3];
3236    /// vec.resize_with(5, Default::default);
3237    /// assert_eq!(vec, [1, 2, 3, 0, 0]);
3238    ///
3239    /// let mut vec = vec![];
3240    /// let mut p = 1;
3241    /// vec.resize_with(4, || { p *= 2; p });
3242    /// assert_eq!(vec, [2, 4, 8, 16]);
3243    /// ```
3244    #[cfg(not(no_global_oom_handling))]
3245    #[stable(feature = "vec_resize_with", since = "1.33.0")]
3246    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
3247    where
3248        F: FnMut() -> T,
3249    {
3250        let len = self.len();
3251        if new_len > len {
3252            self.extend_trusted(iter::repeat_with(f).take(new_len - len));
3253        } else {
3254            self.truncate(new_len);
3255        }
3256    }
3257
3258    /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
3259    /// `&'a mut [T]`.
3260    ///
3261    /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
3262    /// has only static references, or none at all, then this may be chosen to be
3263    /// `'static`.
3264    ///
3265    /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
3266    /// so the leaked allocation may include unused capacity that is not part
3267    /// of the returned slice.
3268    ///
3269    /// This function is mainly useful for data that lives for the remainder of
3270    /// the program's life. Dropping the returned reference will cause a memory
3271    /// leak.
3272    ///
3273    /// # Examples
3274    ///
3275    /// Simple usage:
3276    ///
3277    /// ```
3278    /// let x = vec![1, 2, 3];
3279    /// let static_ref: &'static mut [usize] = x.leak();
3280    /// static_ref[0] += 1;
3281    /// assert_eq!(static_ref, &[2, 2, 3]);
3282    /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
3283    /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
3284    /// # drop(unsafe { Box::from_raw(static_ref) });
3285    /// ```
3286    #[stable(feature = "vec_leak", since = "1.47.0")]
3287    #[inline]
3288    pub fn leak<'a>(self) -> &'a mut [T]
3289    where
3290        A: 'a,
3291    {
3292        let mut me = ManuallyDrop::new(self);
3293        // ignore-tidy-undocumented-unsafe
3294        unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
3295    }
3296
3297    /// Returns the remaining spare capacity of the vector as a slice of
3298    /// `MaybeUninit<T>`.
3299    ///
3300    /// The returned slice can be used to fill the vector with data (e.g. by
3301    /// reading from a file) before marking the data as initialized using the
3302    /// [`set_len`] method.
3303    ///
3304    /// [`set_len`]: Vec::set_len
3305    ///
3306    /// # Examples
3307    ///
3308    /// ```
3309    /// // Allocate vector big enough for 10 elements.
3310    /// let mut v = Vec::with_capacity(10);
3311    ///
3312    /// // Fill in the first 3 elements.
3313    /// let uninit = v.spare_capacity_mut();
3314    /// uninit[0].write(0);
3315    /// uninit[1].write(1);
3316    /// uninit[2].write(2);
3317    ///
3318    /// // Mark the first 3 elements of the vector as being initialized.
3319    /// unsafe {
3320    ///     v.set_len(3);
3321    /// }
3322    ///
3323    /// assert_eq!(&v, &[0, 1, 2]);
3324    /// ```
3325    #[stable(feature = "vec_spare_capacity", since = "1.60.0")]
3326    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
3327    #[inline]
3328    pub const fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
3329        // Note:
3330        // This method is not implemented in terms of `split_at_spare_mut`,
3331        // to prevent invalidation of pointers to the buffer.
3332        // ignore-tidy-undocumented-unsafe
3333        unsafe {
3334            slice::from_raw_parts_mut(
3335                self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
3336                self.buf.capacity() - self.len,
3337            )
3338        }
3339    }
3340
3341    /// Returns vector content as a slice of `T`, along with the remaining spare
3342    /// capacity of the vector as a slice of `MaybeUninit<T>`.
3343    ///
3344    /// The returned spare capacity slice can be used to fill the vector with data
3345    /// (e.g. by reading from a file) before marking the data as initialized using
3346    /// the [`set_len`] method.
3347    ///
3348    /// [`set_len`]: Vec::set_len
3349    ///
3350    /// Note that this is a low-level API, which should be used with care for
3351    /// optimization purposes. If you need to append data to a `Vec`
3352    /// you can use [`push`], [`extend`], [`extend_from_slice`],
3353    /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
3354    /// [`resize_with`], depending on your exact needs.
3355    ///
3356    /// [`push`]: Vec::push
3357    /// [`extend`]: Vec::extend
3358    /// [`extend_from_slice`]: Vec::extend_from_slice
3359    /// [`extend_from_within`]: Vec::extend_from_within
3360    /// [`insert`]: Vec::insert
3361    /// [`append`]: Vec::append
3362    /// [`resize`]: Vec::resize
3363    /// [`resize_with`]: Vec::resize_with
3364    ///
3365    /// # Examples
3366    ///
3367    /// ```
3368    /// #![feature(vec_split_at_spare)]
3369    ///
3370    /// let mut v = vec![1, 1, 2];
3371    ///
3372    /// // Reserve additional space big enough for 10 elements.
3373    /// v.reserve(10);
3374    ///
3375    /// let (init, uninit) = v.split_at_spare_mut();
3376    /// let sum = init.iter().copied().sum::<u32>();
3377    ///
3378    /// // Fill in the next 4 elements.
3379    /// uninit[0].write(sum);
3380    /// uninit[1].write(sum * 2);
3381    /// uninit[2].write(sum * 3);
3382    /// uninit[3].write(sum * 4);
3383    ///
3384    /// // Mark the 4 elements of the vector as being initialized.
3385    /// unsafe {
3386    ///     let len = v.len();
3387    ///     v.set_len(len + 4);
3388    /// }
3389    ///
3390    /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
3391    /// ```
3392    #[unstable(feature = "vec_split_at_spare", issue = "81944")]
3393    #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
3394    #[inline]
3395    pub const fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
3396        // SAFETY:
3397        // - len is ignored and so never changed
3398        let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
3399        (init, spare)
3400    }
3401
3402    /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
3403    ///
3404    /// This method provides unique access to all vec parts at once in `extend_from_within`.
3405    const unsafe fn split_at_spare_mut_with_len(
3406        &mut self,
3407    ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
3408        let ptr = self.as_mut_ptr();
3409        // SAFETY:
3410        // - `ptr` is guaranteed to be valid for `self.len` elements
3411        // - but the allocation extends out to `self.buf.capacity()` elements, possibly
3412        // uninitialized
3413        let spare_ptr = unsafe { ptr.add(self.len) };
3414        let spare_ptr = spare_ptr.cast_uninit();
3415        let spare_len = self.buf.capacity() - self.len;
3416
3417        // SAFETY:
3418        // - `ptr` is guaranteed to be valid for `self.len` elements
3419        // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
3420        unsafe {
3421            let initialized = slice::from_raw_parts_mut(ptr, self.len);
3422            let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
3423
3424            (initialized, spare, &mut self.len)
3425        }
3426    }
3427
3428    /// Groups every `N` elements in the `Vec<T>` into chunks to produce a `Vec<[T; N]>`, dropping
3429    /// elements in the remainder. `N` must be greater than zero.
3430    ///
3431    /// If the capacity is not a multiple of the chunk size, the buffer will shrink down to the
3432    /// nearest multiple with a reallocation or deallocation.
3433    ///
3434    /// This function can be used to reverse [`Vec::into_flattened`].
3435    ///
3436    /// # Examples
3437    ///
3438    /// ```
3439    /// #![feature(vec_into_chunks)]
3440    ///
3441    /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7];
3442    /// assert_eq!(vec.into_chunks::<3>(), [[0, 1, 2], [3, 4, 5]]);
3443    ///
3444    /// let vec = vec![0, 1, 2, 3];
3445    /// let chunks: Vec<[u8; 10]> = vec.into_chunks();
3446    /// assert!(chunks.is_empty());
3447    ///
3448    /// let flat = vec![0; 8 * 8 * 8];
3449    /// let reshaped: Vec<[[[u8; 8]; 8]; 8]> = flat.into_chunks().into_chunks().into_chunks();
3450    /// assert_eq!(reshaped.len(), 1);
3451    /// ```
3452    #[cfg(not(no_global_oom_handling))]
3453    #[unstable(feature = "vec_into_chunks", issue = "142137")]
3454    pub fn into_chunks<const N: usize>(mut self) -> Vec<[T; N], A> {
3455        const {
3456            assert!(N != 0, "chunk size must be greater than zero");
3457        }
3458
3459        let (len, cap) = (self.len(), self.capacity());
3460
3461        let len_remainder = len % N;
3462        if len_remainder != 0 {
3463            self.truncate(len - len_remainder);
3464        }
3465
3466        let cap_remainder = cap % N;
3467        if !T::IS_ZST && cap_remainder != 0 {
3468            self.buf.shrink_to_fit(cap - cap_remainder);
3469        }
3470
3471        let (ptr, _, _, alloc) = self.into_raw_parts_with_allocator();
3472
3473        // SAFETY:
3474        // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_allocator()`
3475        // - `[T; N]` has the same alignment as `T`
3476        // - `size_of::<[T; N]>() * cap / N == size_of::<T>() * cap`
3477        // - `len / N <= cap / N` because `len <= cap`
3478        // - the allocated memory consists of `len / N` valid values of type `[T; N]`
3479        // - `cap / N` fits the size of the allocated memory after shrinking
3480        unsafe { Vec::from_raw_parts_in(ptr.cast(), len / N, cap / N, alloc) }
3481    }
3482
3483    /// This clears out this `Vec` and recycles the allocation into a new `Vec`.
3484    /// The item type of the resulting `Vec` needs to have the same size and
3485    /// alignment as the item type of the original `Vec`.
3486    ///
3487    /// # Examples
3488    ///
3489    ///  ```
3490    /// #![feature(vec_recycle, transmutability)]
3491    /// let a: Vec<u8> = vec![0; 100];
3492    /// let capacity = a.capacity();
3493    /// let addr = a.as_ptr().addr();
3494    /// let b: Vec<i8> = a.recycle();
3495    /// assert_eq!(b.len(), 0);
3496    /// assert_eq!(b.capacity(), capacity);
3497    /// assert_eq!(b.as_ptr().addr(), addr);
3498    /// ```
3499    ///
3500    /// The `Recyclable` bound prevents this method from being called when `T` and `U` have different sizes; e.g.:
3501    ///
3502    ///  ```compile_fail,E0277
3503    /// #![feature(vec_recycle, transmutability)]
3504    /// let vec: Vec<[u8; 2]> = Vec::new();
3505    /// let _: Vec<[u8; 1]> = vec.recycle();
3506    /// ```
3507    /// ...or different alignments:
3508    ///
3509    ///  ```compile_fail,E0277
3510    /// #![feature(vec_recycle, transmutability)]
3511    /// let vec: Vec<[u16; 0]> = Vec::new();
3512    /// let _: Vec<[u8; 0]> = vec.recycle();
3513    /// ```
3514    ///
3515    /// However, due to temporary implementation limitations of `Recyclable`,
3516    /// this method is not yet callable when `T` or `U` are slices, trait objects,
3517    /// or other exotic types; e.g.:
3518    ///
3519    /// ```compile_fail,E0277
3520    /// #![feature(vec_recycle, transmutability)]
3521    /// # let inputs = ["a b c", "d e f"];
3522    /// # fn process(_: &[&str]) {}
3523    /// let mut storage: Vec<&[&str]> = Vec::new();
3524    ///
3525    /// for input in inputs {
3526    ///     let mut buffer: Vec<&str> = storage.recycle();
3527    ///     buffer.extend(input.split(" "));
3528    ///     process(&buffer);
3529    ///     storage = buffer.recycle();
3530    /// }
3531    /// ```
3532    #[unstable(feature = "vec_recycle", issue = "148227")]
3533    #[expect(private_bounds)]
3534    pub fn recycle<U>(mut self) -> Vec<U, A>
3535    where
3536        U: Recyclable<T>,
3537    {
3538        self.clear();
3539        const {
3540            // FIXME(const-hack, 146097): compare `Layout`s
3541            assert!(size_of::<T>() == size_of::<U>());
3542            assert!(align_of::<T>() == align_of::<U>());
3543        };
3544        let (ptr, length, capacity, alloc) = self.into_parts_with_allocator();
3545        debug_assert_eq!(length, 0);
3546        // SAFETY:
3547        // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_allocator()`
3548        // - `T` & `U` have the same layout, so `capacity` does not need to be changed and we can safely use `alloc.dealloc` later
3549        // - the original vector was cleared, so there is no problem with "transmuting" the stored values
3550        unsafe { Vec::from_parts_in(ptr.cast::<U>(), length, capacity, alloc) }
3551    }
3552}
3553
3554/// Denotes that an allocation of `From` can be recycled into an allocation of `Self`.
3555///
3556/// # Safety
3557///
3558/// `Self` is `Recyclable<From>` if `Layout::new::<Self>() == Layout::new::<From>()`.
3559unsafe trait Recyclable<From: Sized>: Sized {}
3560
3561#[unstable_feature_bound(transmutability)]
3562// SAFETY: enforced by `TransmuteFrom`
3563unsafe impl<From, To> Recyclable<From> for To
3564where
3565    for<'a> &'a MaybeUninit<To>: TransmuteFrom<&'a MaybeUninit<From>, { Assume::SAFETY }>,
3566    for<'a> &'a MaybeUninit<From>: TransmuteFrom<&'a MaybeUninit<To>, { Assume::SAFETY }>,
3567{
3568}
3569
3570impl<T: Clone, A: Allocator> Vec<T, A> {
3571    /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
3572    ///
3573    /// If `new_len` is greater than `len`, the `Vec` is extended by the
3574    /// difference, with each additional slot filled with `value`.
3575    /// If `new_len` is less than `len`, the `Vec` is simply truncated.
3576    ///
3577    /// This method requires `T` to implement [`Clone`],
3578    /// in order to be able to clone the passed value.
3579    /// If you need more flexibility (or want to rely on [`Default`] instead of
3580    /// [`Clone`]), use [`Vec::resize_with`].
3581    /// If you only need to resize to a smaller size, use [`Vec::truncate`].
3582    ///
3583    /// # Panics
3584    ///
3585    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3586    ///
3587    /// # Examples
3588    ///
3589    /// ```
3590    /// let mut vec = vec!["hello"];
3591    /// vec.resize(3, "world");
3592    /// assert_eq!(vec, ["hello", "world", "world"]);
3593    ///
3594    /// let mut vec = vec!['a', 'b', 'c', 'd'];
3595    /// vec.resize(2, '_');
3596    /// assert_eq!(vec, ['a', 'b']);
3597    /// ```
3598    #[cfg(not(no_global_oom_handling))]
3599    #[stable(feature = "vec_resize", since = "1.5.0")]
3600    pub fn resize(&mut self, new_len: usize, value: T) {
3601        let len = self.len();
3602
3603        if new_len > len {
3604            self.extend_with(new_len - len, value)
3605        } else {
3606            self.truncate(new_len);
3607        }
3608    }
3609
3610    /// Clones and appends all elements in a slice to the `Vec`.
3611    ///
3612    /// Iterates over the slice `other`, clones each element, and then appends
3613    /// it to this `Vec`. The `other` slice is traversed in-order.
3614    ///
3615    /// Note that this function is the same as [`extend`],
3616    /// except that it also works with slice elements that are Clone but not Copy.
3617    /// If Rust gets specialization this function may be deprecated.
3618    ///
3619    /// # Panics
3620    ///
3621    /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3622    ///
3623    /// # Examples
3624    ///
3625    /// ```
3626    /// let mut vec = vec![1];
3627    /// vec.extend_from_slice(&[2, 3, 4]);
3628    /// assert_eq!(vec, [1, 2, 3, 4]);
3629    /// ```
3630    ///
3631    /// [`extend`]: Vec::extend
3632    #[cfg(not(no_global_oom_handling))]
3633    #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
3634    pub fn extend_from_slice(&mut self, other: &[T]) {
3635        self.spec_extend(other.iter())
3636    }
3637
3638    /// Given a range `src`, clones a slice of elements in that range and appends it to the end.
3639    ///
3640    /// `src` must be a range that can form a valid subslice of the `Vec`.
3641    ///
3642    /// # Panics
3643    ///
3644    /// Panics if starting index is greater than the end index, if the index is
3645    /// greater than the length of the vector, or if the new capacity exceeds
3646    /// `isize::MAX` _bytes_.
3647    ///
3648    /// # Examples
3649    ///
3650    /// ```
3651    /// let mut characters = vec!['a', 'b', 'c', 'd', 'e'];
3652    /// characters.extend_from_within(2..);
3653    /// assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
3654    ///
3655    /// let mut numbers = vec![0, 1, 2, 3, 4];
3656    /// numbers.extend_from_within(..2);
3657    /// assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
3658    ///
3659    /// let mut strings = vec![String::from("hello"), String::from("world"), String::from("!")];
3660    /// strings.extend_from_within(1..=2);
3661    /// assert_eq!(strings, ["hello", "world", "!", "world", "!"]);
3662    /// ```
3663    #[cfg(not(no_global_oom_handling))]
3664    #[stable(feature = "vec_extend_from_within", since = "1.53.0")]
3665    pub fn extend_from_within<R>(&mut self, src: R)
3666    where
3667        R: RangeBounds<usize>,
3668    {
3669        let range = slice::range(src, ..self.len());
3670        self.reserve(range.len());
3671
3672        // SAFETY:
3673        // - `slice::range` guarantees that the given range is valid for indexing self
3674        unsafe {
3675            self.spec_extend_from_within(range);
3676        }
3677    }
3678}
3679
3680impl<A: Allocator> Vec<u8, A> {
3681    #[cfg_attr(
3682        not(no_global_oom_handling),
3683        expect(
3684            dead_code,
3685            reason = "currently only used in IO module when global OOM handling is disabled"
3686        )
3687    )]
3688    pub(crate) fn try_extend_from_slice_of_bytes(
3689        &mut self,
3690        other: &[u8],
3691    ) -> Result<(), TryReserveError> {
3692        // ignore-tidy-undocumented-unsafe
3693        unsafe { self.try_append_elements(other) }
3694    }
3695}
3696
3697impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
3698    /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
3699    ///
3700    /// # Panics
3701    ///
3702    /// Panics if the length of the resulting vector would overflow a `usize`.
3703    ///
3704    /// This is only possible when flattening a vector of arrays of zero-sized
3705    /// types, and thus tends to be irrelevant in practice. If
3706    /// `size_of::<T>() > 0`, this will never panic.
3707    ///
3708    /// # Examples
3709    ///
3710    /// ```
3711    /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
3712    /// assert_eq!(vec.pop(), Some([7, 8, 9]));
3713    ///
3714    /// let mut flattened = vec.into_flattened();
3715    /// assert_eq!(flattened.pop(), Some(6));
3716    /// ```
3717    #[stable(feature = "slice_flatten", since = "1.80.0")]
3718    pub fn into_flattened(self) -> Vec<T, A> {
3719        let (ptr, len, cap, alloc) = self.into_raw_parts_with_allocator();
3720        let (new_len, new_cap) = if T::IS_ZST {
3721            (
3722                len.checked_mul(N).expect("the product of vec len and N shouldn't overflow"),
3723                usize::MAX,
3724            )
3725        } else {
3726            // SAFETY:
3727            // - `cap * N` cannot overflow because the allocation is already in
3728            // the address space.
3729            // - Each `[T; N]` has `N` valid elements, so there are `len * N`
3730            // valid elements in the allocation.
3731            unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) }
3732        };
3733        // SAFETY:
3734        // - `ptr` was allocated by `self`
3735        // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
3736        // - `new_cap` refers to the same sized allocation as `cap` because
3737        // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
3738        // - `len` <= `cap`, so `len * N` <= `cap * N`.
3739        unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
3740    }
3741}
3742
3743impl<T: Clone, A: Allocator> Vec<T, A> {
3744    #[cfg(not(no_global_oom_handling))]
3745    /// Extend the vector by `n` clones of value.
3746    fn extend_with(&mut self, n: usize, value: T) {
3747        self.reserve(n);
3748
3749        // ignore-tidy-undocumented-unsafe
3750        unsafe {
3751            let mut ptr = self.as_mut_ptr().add(self.len());
3752            // Use SetLenOnDrop to work around bug where compiler
3753            // might not realize the store through `ptr` through self.set_len()
3754            // don't alias.
3755            let mut local_len = SetLenOnDrop::new(&mut self.len);
3756
3757            // Write all elements except the last one
3758            for _ in 1..n {
3759                ptr::write(ptr, value.clone());
3760                ptr = ptr.add(1);
3761                // Increment the length in every step in case clone() panics
3762                local_len.increment_len(1);
3763            }
3764
3765            if n > 0 {
3766                // We can write the last element directly without cloning needlessly
3767                ptr::write(ptr, value);
3768                local_len.increment_len(1);
3769            }
3770
3771            // len set by scope guard
3772        }
3773    }
3774}
3775
3776impl<T: PartialEq, A: Allocator> Vec<T, A> {
3777    /// Removes consecutive repeated elements in the vector according to the
3778    /// [`PartialEq`] trait implementation.
3779    ///
3780    /// If the vector is sorted, this removes all duplicates.
3781    ///
3782    /// # Examples
3783    ///
3784    /// ```
3785    /// let mut vec = vec![1, 2, 2, 3, 2];
3786    ///
3787    /// vec.dedup();
3788    ///
3789    /// assert_eq!(vec, [1, 2, 3, 2]);
3790    /// ```
3791    #[stable(feature = "rust1", since = "1.0.0")]
3792    #[inline]
3793    pub fn dedup(&mut self) {
3794        self.dedup_by(|a, b| a == b)
3795    }
3796}
3797
3798////////////////////////////////////////////////////////////////////////////////
3799// Internal methods and functions
3800////////////////////////////////////////////////////////////////////////////////
3801
3802#[doc(hidden)]
3803#[cfg(not(no_global_oom_handling))]
3804#[stable(feature = "rust1", since = "1.0.0")]
3805#[rustc_diagnostic_item = "vec_from_elem"]
3806pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
3807    <T as SpecFromElem>::from_elem(elem, n, Global)
3808}
3809
3810#[doc(hidden)]
3811#[cfg(not(no_global_oom_handling))]
3812#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
3813pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
3814    <T as SpecFromElem>::from_elem(elem, n, alloc)
3815}
3816
3817#[cfg(not(no_global_oom_handling))]
3818trait ExtendFromWithinSpec {
3819    /// # Safety
3820    ///
3821    /// - `src` needs to be valid index
3822    /// - `self.capacity() - self.len()` must be `>= src.len()`
3823    unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
3824}
3825
3826#[cfg(not(no_global_oom_handling))]
3827impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3828    default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3829        // SAFETY:
3830        // - len is increased only after initializing elements
3831        let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
3832
3833        // SAFETY:
3834        // - caller guarantees that src is a valid index
3835        let to_clone = unsafe { this.get_unchecked(src) };
3836
3837        iter::zip(to_clone, spare)
3838            .map(|(src, dst)| dst.write(src.clone()))
3839            // Note:
3840            // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
3841            // - len is increased after each element to prevent leaks (see issue #82533)
3842            .for_each(|_| *len += 1);
3843    }
3844}
3845
3846#[cfg(not(no_global_oom_handling))]
3847impl<T: TrivialClone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3848    unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3849        let count = src.len();
3850        {
3851            let (init, spare) = self.split_at_spare_mut();
3852
3853            // SAFETY:
3854            // - caller guarantees that `src` is a valid index
3855            let source = unsafe { init.get_unchecked(src) };
3856
3857            // SAFETY:
3858            // - Both pointers are created from unique slice references (`&mut [_]`)
3859            //   so they are valid and do not overlap.
3860            // - Elements implement `TrivialClone` so this is equivalent to calling
3861            //   `clone` on every one of them.
3862            // - `count` is equal to the len of `source`, so source is valid for
3863            //   `count` reads
3864            // - `.reserve(count)` guarantees that `spare.len() >= count` so spare
3865            //   is valid for `count` writes
3866            unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
3867        }
3868
3869        // SAFETY:
3870        // - The elements were just initialized by `copy_nonoverlapping`
3871        self.len += count;
3872    }
3873}
3874
3875////////////////////////////////////////////////////////////////////////////////
3876// Common trait implementations for Vec
3877////////////////////////////////////////////////////////////////////////////////
3878
3879#[stable(feature = "rust1", since = "1.0.0")]
3880#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3881const impl<T, A: Allocator> ops::Deref for Vec<T, A> {
3882    type Target = [T];
3883
3884    #[inline]
3885    fn deref(&self) -> &[T] {
3886        self.as_slice()
3887    }
3888}
3889
3890#[stable(feature = "rust1", since = "1.0.0")]
3891#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3892const impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
3893    #[inline]
3894    fn deref_mut(&mut self) -> &mut [T] {
3895        self.as_mut_slice()
3896    }
3897}
3898
3899#[unstable(feature = "deref_pure_trait", issue = "87121")]
3900unsafe impl<T, A: Allocator> ops::DerefPure for Vec<T, A> {}
3901
3902#[cfg(not(no_global_oom_handling))]
3903#[stable(feature = "rust1", since = "1.0.0")]
3904impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
3905    /// Creates a new `Vec` by deep-copying the contents of an existing `Vec`.
3906    ///
3907    /// This method will allocate a new `Vec` and `clone` all of `self`'s contents
3908    /// into it. The capacity of the duplicate `Vec` is not forced to match the
3909    /// capacity of the original.
3910    fn clone(&self) -> Self {
3911        let alloc = self.allocator().clone();
3912        <[T]>::to_vec_in(self, alloc)
3913    }
3914
3915    /// Overwrites the contents of `self` with a clone of the contents of `source`.
3916    ///
3917    /// This method is preferred over simply assigning `source.clone()` to `self`,
3918    /// as it avoids reallocation if possible. Additionally, if the element type
3919    /// `T` overrides `clone_from()`, this will reuse the resources of `self`'s
3920    /// elements as well.
3921    ///
3922    /// # Examples
3923    ///
3924    /// ```
3925    /// let x = vec![5, 6, 7];
3926    /// let mut y = vec![8, 9, 10];
3927    /// let yp: *const i32 = y.as_ptr();
3928    ///
3929    /// y.clone_from(&x);
3930    ///
3931    /// // The value is the same
3932    /// assert_eq!(x, y);
3933    ///
3934    /// // And no reallocation occurred
3935    /// assert_eq!(yp, y.as_ptr());
3936    /// ```
3937    fn clone_from(&mut self, source: &Self) {
3938        crate::slice::SpecCloneIntoVec::clone_into(source.as_slice(), self);
3939    }
3940}
3941
3942/// The hash of a vector is the same as that of the corresponding slice,
3943/// as required by the `core::borrow::Borrow` implementation.
3944///
3945/// ```
3946/// use std::hash::BuildHasher;
3947///
3948/// let b = std::hash::RandomState::new();
3949/// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
3950/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
3951/// assert_eq!(b.hash_one(v), b.hash_one(s));
3952/// ```
3953#[stable(feature = "rust1", since = "1.0.0")]
3954impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
3955    #[inline]
3956    fn hash<H: Hasher>(&self, state: &mut H) {
3957        Hash::hash(&**self, state)
3958    }
3959}
3960
3961#[stable(feature = "rust1", since = "1.0.0")]
3962#[rustc_const_unstable(feature = "const_index", issue = "143775")]
3963const impl<T, I: [const] SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
3964    type Output = I::Output;
3965
3966    #[inline]
3967    fn index(&self, index: I) -> &Self::Output {
3968        Index::index(&**self, index)
3969    }
3970}
3971
3972#[stable(feature = "rust1", since = "1.0.0")]
3973#[rustc_const_unstable(feature = "const_index", issue = "143775")]
3974const impl<T, I: [const] SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
3975    #[inline]
3976    fn index_mut(&mut self, index: I) -> &mut Self::Output {
3977        IndexMut::index_mut(&mut **self, index)
3978    }
3979}
3980
3981/// Collects an iterator into a Vec, commonly called via [`Iterator::collect()`]
3982///
3983/// # Allocation behavior
3984///
3985/// In general `Vec` does not guarantee any particular growth or allocation strategy.
3986/// That also applies to this trait impl.
3987///
3988/// **Note:** This section covers implementation details and is therefore exempt from
3989/// stability guarantees.
3990///
3991/// Vec may use any or none of the following strategies,
3992/// depending on the supplied iterator:
3993///
3994/// * preallocate based on [`Iterator::size_hint()`]
3995///   * and panic if the number of items is outside the provided lower/upper bounds
3996/// * use an amortized growth strategy similar to `pushing` one item at a time
3997/// * perform the iteration in-place on the original allocation backing the iterator
3998///
3999/// The last case warrants some attention. It is an optimization that in many cases reduces peak memory
4000/// consumption and improves cache locality. But when big, short-lived allocations are created,
4001/// only a small fraction of their items get collected, no further use is made of the spare capacity
4002/// and the resulting `Vec` is moved into a longer-lived structure, then this can lead to the large
4003/// allocations having their lifetimes unnecessarily extended which can result in increased memory
4004/// footprint.
4005///
4006/// In cases where this is an issue, the excess capacity can be discarded with [`Vec::shrink_to()`],
4007/// [`Vec::shrink_to_fit()`] or by collecting into [`Box<[T]>`][owned slice] instead, which additionally reduces
4008/// the size of the long-lived struct.
4009///
4010/// [owned slice]: Box
4011///
4012/// ```rust
4013/// # use std::sync::Mutex;
4014/// static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());
4015///
4016/// for i in 0..10 {
4017///     let big_temporary: Vec<u16> = (0..1024).collect();
4018///     // discard most items
4019///     let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect();
4020///     // without this a lot of unused capacity might be moved into the global
4021///     result.shrink_to_fit();
4022///     LONG_LIVED.lock().unwrap().push(result);
4023/// }
4024/// ```
4025#[cfg(not(no_global_oom_handling))]
4026#[stable(feature = "rust1", since = "1.0.0")]
4027impl<T> FromIterator<T> for Vec<T> {
4028    #[inline]
4029    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
4030        <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
4031    }
4032}
4033
4034#[stable(feature = "rust1", since = "1.0.0")]
4035impl<T, A: Allocator> IntoIterator for Vec<T, A> {
4036    type Item = T;
4037    type IntoIter = IntoIter<T, A>;
4038
4039    /// Creates a consuming iterator, that is, one that moves each value out of
4040    /// the vector (from start to end). The vector cannot be used after calling
4041    /// this.
4042    ///
4043    /// # Examples
4044    ///
4045    /// ```
4046    /// let v = vec!["a".to_string(), "b".to_string()];
4047    /// let mut v_iter = v.into_iter();
4048    ///
4049    /// let first_element: Option<String> = v_iter.next();
4050    ///
4051    /// assert_eq!(first_element, Some("a".to_string()));
4052    /// assert_eq!(v_iter.next(), Some("b".to_string()));
4053    /// assert_eq!(v_iter.next(), None);
4054    /// ```
4055    #[inline]
4056    fn into_iter(self) -> Self::IntoIter {
4057        let me = ManuallyDrop::new(self);
4058        // ignore-tidy-undocumented-unsafe
4059        unsafe {
4060            let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
4061            let buf = me.buf.non_null();
4062            let begin = buf.as_ptr();
4063            let end = if T::IS_ZST {
4064                begin.wrapping_byte_add(me.len())
4065            } else {
4066                begin.add(me.len()) as *const T
4067            };
4068            let cap = me.buf.capacity();
4069            IntoIter { buf, phantom: PhantomData, cap, alloc, ptr: buf, end }
4070        }
4071    }
4072}
4073
4074#[stable(feature = "rust1", since = "1.0.0")]
4075impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
4076    type Item = &'a T;
4077    type IntoIter = slice::Iter<'a, T>;
4078
4079    fn into_iter(self) -> Self::IntoIter {
4080        self.iter()
4081    }
4082}
4083
4084#[stable(feature = "rust1", since = "1.0.0")]
4085impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
4086    type Item = &'a mut T;
4087    type IntoIter = slice::IterMut<'a, T>;
4088
4089    fn into_iter(self) -> Self::IntoIter {
4090        self.iter_mut()
4091    }
4092}
4093
4094#[cfg(not(no_global_oom_handling))]
4095#[stable(feature = "rust1", since = "1.0.0")]
4096impl<T, A: Allocator> Extend<T> for Vec<T, A> {
4097    #[inline]
4098    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
4099        <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
4100    }
4101
4102    #[inline]
4103    fn extend_one(&mut self, item: T) {
4104        self.push(item);
4105    }
4106
4107    #[inline]
4108    fn extend_reserve(&mut self, additional: usize) {
4109        self.reserve(additional);
4110    }
4111
4112    #[inline]
4113    unsafe fn extend_one_unchecked(&mut self, item: T) {
4114        // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
4115        unsafe {
4116            let len = self.len();
4117            ptr::write(self.as_mut_ptr().add(len), item);
4118            self.set_len(len + 1);
4119        }
4120    }
4121}
4122
4123impl<T, A: Allocator> Vec<T, A> {
4124    // leaf method to which various SpecFrom/SpecExtend implementations delegate when
4125    // they have no further optimizations to apply
4126    #[cfg(not(no_global_oom_handling))]
4127    fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
4128        // This is the case for a general iterator.
4129        //
4130        // This function should be the moral equivalent of:
4131        //
4132        //      for item in iterator {
4133        //          self.push(item);
4134        //      }
4135        while let Some(element) = iterator.next() {
4136            let len = self.len();
4137            if len == self.capacity() {
4138                let (lower, _) = iterator.size_hint();
4139                self.reserve(lower.saturating_add(1));
4140            }
4141            // ignore-tidy-undocumented-unsafe
4142            unsafe {
4143                ptr::write(self.as_mut_ptr().add(len), element);
4144                // Since next() executes user code which can panic we have to bump the length
4145                // after each step.
4146                // NB can't overflow since we would have had to alloc the address space
4147                self.set_len(len + 1);
4148            }
4149        }
4150    }
4151
4152    // specific extend for `TrustedLen` iterators, called both by the specializations
4153    // and internal places where resolving specialization makes compilation slower
4154    #[cfg(not(no_global_oom_handling))]
4155    fn extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) {
4156        let (low, high) = iterator.size_hint();
4157        if let Some(additional) = high {
4158            debug_assert_eq!(
4159                low,
4160                additional,
4161                "TrustedLen iterator's size hint is not exact: {:?}",
4162                (low, high)
4163            );
4164            self.reserve(additional);
4165            let ptr = self.as_mut_ptr();
4166            let mut local_len = SetLenOnDrop::new(&mut self.len);
4167            // ignore-tidy-undocumented-unsafe
4168            unsafe {
4169                iterator.for_each(move |element| {
4170                    ptr::write(ptr.add(local_len.current_len()), element);
4171                    // Since the loop executes user code which can panic we have to update
4172                    // the length every step to correctly drop what we've written.
4173                    // NB can't overflow since we would have had to alloc the address space
4174                    local_len.increment_len(1);
4175                });
4176            }
4177        } else {
4178            // Per TrustedLen contract a `None` upper bound means that the iterator length
4179            // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
4180            // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
4181            // This avoids additional codegen for a fallback code path which would eventually
4182            // panic anyway.
4183            panic!("capacity overflow");
4184        }
4185    }
4186
4187    /// Creates a splicing iterator that replaces the specified range in the vector
4188    /// with the given `replace_with` iterator and yields the removed items.
4189    /// `replace_with` does not need to be the same length as `range`.
4190    ///
4191    /// `range` is removed even if the `Splice` iterator is not consumed before it is dropped.
4192    ///
4193    /// It is unspecified how many elements are removed from the vector
4194    /// if the `Splice` value is leaked.
4195    ///
4196    /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
4197    ///
4198    /// This is optimal if:
4199    ///
4200    /// * The tail (elements in the vector after `range`) is empty,
4201    /// * or `replace_with` yields fewer or equal elements than `range`'s length
4202    /// * or the lower bound of its `size_hint()` is exact.
4203    ///
4204    /// Otherwise, a temporary vector is allocated and the tail is moved twice.
4205    ///
4206    /// # Panics
4207    ///
4208    /// Panics if the range has `start_bound > end_bound`, or, if the range is
4209    /// bounded on either end and past the length of the vector.
4210    ///
4211    /// # Examples
4212    ///
4213    /// ```
4214    /// let mut v = vec![1, 2, 3, 4];
4215    /// let new = [7, 8, 9];
4216    /// let u: Vec<_> = v.splice(1..3, new).collect();
4217    /// assert_eq!(v, [1, 7, 8, 9, 4]);
4218    /// assert_eq!(u, [2, 3]);
4219    /// ```
4220    ///
4221    /// Using `splice` to insert new items into a vector efficiently at a specific position
4222    /// indicated by an empty range:
4223    ///
4224    /// ```
4225    /// let mut v = vec![1, 5];
4226    /// let new = [2, 3, 4];
4227    /// v.splice(1..1, new);
4228    /// assert_eq!(v, [1, 2, 3, 4, 5]);
4229    /// ```
4230    #[cfg(not(no_global_oom_handling))]
4231    #[inline]
4232    #[stable(feature = "vec_splice", since = "1.21.0")]
4233    pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
4234    where
4235        A: AllocatorNightly,
4236        R: RangeBounds<usize>,
4237        I: IntoIterator<Item = T>,
4238    {
4239        Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
4240    }
4241
4242    /// Creates an iterator which uses a closure to determine if an element in the range should be removed.
4243    ///
4244    /// If the closure returns `true`, the element is removed from the vector
4245    /// and yielded. If the closure returns `false`, or panics, the element
4246    /// remains in the vector and will not be yielded.
4247    ///
4248    /// Only elements that fall in the provided range are considered for extraction, but any elements
4249    /// after the range will still have to be moved if any element has been extracted.
4250    ///
4251    /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
4252    /// or the iteration short-circuits, then the remaining elements will be retained.
4253    /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
4254    /// or [`retain_mut`] with a negated predicate if you also do not need to restrict the range.
4255    ///
4256    /// [`retain_mut`]: Vec::retain_mut
4257    ///
4258    /// Using this method is equivalent to the following code:
4259    ///
4260    /// ```
4261    /// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
4262    /// # let mut vec = vec![0, 1, 2, 3, 4, 5, 6];
4263    /// # let mut vec2 = vec.clone();
4264    /// # let range = 1..5;
4265    /// let mut i = range.start;
4266    /// let end_items = vec.len() - range.end;
4267    /// # let mut extracted = vec![];
4268    ///
4269    /// while i < vec.len() - end_items {
4270    ///     if some_predicate(&mut vec[i]) {
4271    ///         let val = vec.remove(i);
4272    ///         // your code here
4273    /// #         extracted.push(val);
4274    ///     } else {
4275    ///         i += 1;
4276    ///     }
4277    /// }
4278    ///
4279    /// # let extracted2: Vec<_> = vec2.extract_if(range, some_predicate).collect();
4280    /// # assert_eq!(vec, vec2);
4281    /// # assert_eq!(extracted, extracted2);
4282    /// ```
4283    ///
4284    /// But `extract_if` is easier to use. `extract_if` is also more efficient,
4285    /// because it can backshift the elements of the array in bulk.
4286    ///
4287    /// The iterator also lets you mutate the value of each element in the
4288    /// closure, regardless of whether you choose to keep or remove it.
4289    ///
4290    /// # Panics
4291    ///
4292    /// If `range` is out of bounds.
4293    ///
4294    /// # Examples
4295    ///
4296    /// Splitting a vector into even and odd values, reusing the original vector:
4297    ///
4298    /// ```
4299    /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
4300    ///
4301    /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<Vec<_>>();
4302    /// let odds = numbers;
4303    ///
4304    /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
4305    /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
4306    /// ```
4307    ///
4308    /// Using the range argument to only process a part of the vector:
4309    ///
4310    /// ```
4311    /// let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2];
4312    /// let ones = items.extract_if(7.., |x| *x == 1).collect::<Vec<_>>();
4313    /// assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]);
4314    /// assert_eq!(ones.len(), 3);
4315    /// ```
4316    #[stable(feature = "extract_if", since = "1.87.0")]
4317    pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A>
4318    where
4319        A: AllocatorNightly,
4320        F: FnMut(&mut T) -> bool,
4321        R: RangeBounds<usize>,
4322    {
4323        ExtractIf::new(self, filter, range)
4324    }
4325}
4326
4327/// Extend implementation that copies elements out of references before pushing them onto the Vec.
4328///
4329/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
4330/// append the entire slice at once.
4331///
4332/// [`copy_from_slice`]: slice::copy_from_slice
4333#[cfg(not(no_global_oom_handling))]
4334#[stable(feature = "extend_ref", since = "1.2.0")]
4335impl<'a, T: Copy + 'a, A: Allocator> Extend<&'a T> for Vec<T, A> {
4336    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
4337        self.spec_extend(iter.into_iter())
4338    }
4339
4340    #[inline]
4341    fn extend_one(&mut self, &item: &'a T) {
4342        self.push(item);
4343    }
4344
4345    #[inline]
4346    fn extend_reserve(&mut self, additional: usize) {
4347        self.reserve(additional);
4348    }
4349
4350    #[inline]
4351    unsafe fn extend_one_unchecked(&mut self, &item: &'a T) {
4352        // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
4353        unsafe {
4354            let len = self.len();
4355            ptr::write(self.as_mut_ptr().add(len), item);
4356            self.set_len(len + 1);
4357        }
4358    }
4359}
4360
4361/// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison).
4362#[stable(feature = "rust1", since = "1.0.0")]
4363impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1>
4364where
4365    T: PartialOrd,
4366    A1: Allocator,
4367    A2: Allocator,
4368{
4369    #[inline]
4370    fn partial_cmp(&self, other: &Vec<T, A2>) -> Option<Ordering> {
4371        PartialOrd::partial_cmp(&**self, &**other)
4372    }
4373}
4374
4375#[stable(feature = "rust1", since = "1.0.0")]
4376impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
4377
4378/// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison).
4379#[stable(feature = "rust1", since = "1.0.0")]
4380impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
4381    #[inline]
4382    fn cmp(&self, other: &Self) -> Ordering {
4383        Ord::cmp(&**self, &**other)
4384    }
4385}
4386
4387#[stable(feature = "rust1", since = "1.0.0")]
4388#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
4389const unsafe impl<#[may_dangle] T: [const] Destruct, A: [const] Allocator + [const] Destruct> Drop
4390    for Vec<T, A>
4391{
4392    fn drop(&mut self) {
4393        // ignore-tidy-undocumented-unsafe
4394        unsafe {
4395            // use drop for [T]
4396            // use a raw slice to refer to the elements of the vector as weakest necessary type;
4397            // could avoid questions of validity in certain cases
4398            self.as_mut_ptr().cast_slice(self.len).drop_in_place()
4399        }
4400        // RawVec handles deallocation
4401    }
4402}
4403
4404#[stable(feature = "rust1", since = "1.0.0")]
4405#[rustc_const_unstable(feature = "const_default", issue = "143894")]
4406const impl<T> Default for Vec<T> {
4407    /// Creates an empty `Vec<T>`.
4408    ///
4409    /// The vector will not allocate until elements are pushed onto it.
4410    fn default() -> Vec<T> {
4411        Vec::new()
4412    }
4413}
4414
4415#[stable(feature = "rust1", since = "1.0.0")]
4416impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
4417    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4418        fmt::Debug::fmt(&**self, f)
4419    }
4420}
4421
4422#[stable(feature = "rust1", since = "1.0.0")]
4423impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
4424    fn as_ref(&self) -> &Vec<T, A> {
4425        self
4426    }
4427}
4428
4429#[stable(feature = "vec_as_mut", since = "1.5.0")]
4430impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
4431    fn as_mut(&mut self) -> &mut Vec<T, A> {
4432        self
4433    }
4434}
4435
4436#[stable(feature = "rust1", since = "1.0.0")]
4437impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
4438    fn as_ref(&self) -> &[T] {
4439        self
4440    }
4441}
4442
4443#[stable(feature = "vec_as_mut", since = "1.5.0")]
4444impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
4445    fn as_mut(&mut self) -> &mut [T] {
4446        self
4447    }
4448}
4449
4450#[cfg(not(no_global_oom_handling))]
4451#[stable(feature = "rust1", since = "1.0.0")]
4452impl<T: Clone> From<&[T]> for Vec<T> {
4453    /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4454    ///
4455    /// # Examples
4456    ///
4457    /// ```
4458    /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
4459    /// ```
4460    fn from(s: &[T]) -> Vec<T> {
4461        s.to_vec()
4462    }
4463}
4464
4465#[cfg(not(no_global_oom_handling))]
4466#[stable(feature = "vec_from_mut", since = "1.19.0")]
4467impl<T: Clone> From<&mut [T]> for Vec<T> {
4468    /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4469    ///
4470    /// # Examples
4471    ///
4472    /// ```
4473    /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
4474    /// ```
4475    fn from(s: &mut [T]) -> Vec<T> {
4476        s.to_vec()
4477    }
4478}
4479
4480#[cfg(not(no_global_oom_handling))]
4481#[stable(feature = "vec_from_array_ref", since = "1.74.0")]
4482impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T> {
4483    /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4484    ///
4485    /// # Examples
4486    ///
4487    /// ```
4488    /// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);
4489    /// ```
4490    fn from(s: &[T; N]) -> Vec<T> {
4491        Self::from(s.as_slice())
4492    }
4493}
4494
4495#[cfg(not(no_global_oom_handling))]
4496#[stable(feature = "vec_from_array_ref", since = "1.74.0")]
4497impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T> {
4498    /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4499    ///
4500    /// # Examples
4501    ///
4502    /// ```
4503    /// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
4504    /// ```
4505    fn from(s: &mut [T; N]) -> Vec<T> {
4506        Self::from(s.as_mut_slice())
4507    }
4508}
4509
4510#[cfg(not(no_global_oom_handling))]
4511#[stable(feature = "vec_from_array", since = "1.44.0")]
4512impl<T, const N: usize> From<[T; N]> for Vec<T> {
4513    /// Allocates a `Vec<T>` and moves `s`'s items into it.
4514    ///
4515    /// # Examples
4516    ///
4517    /// ```
4518    /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
4519    /// ```
4520    fn from(s: [T; N]) -> Vec<T> {
4521        <[T]>::into_vec(Box::new(s))
4522    }
4523}
4524
4525#[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
4526impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
4527where
4528    [T]: ToOwned<Owned = Vec<T>>,
4529{
4530    /// Converts a clone-on-write slice into a vector.
4531    ///
4532    /// If `s` already owns a `Vec<T>`, it will be returned directly.
4533    /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and
4534    /// filled by cloning `s`'s items into it.
4535    ///
4536    /// # Examples
4537    ///
4538    /// ```
4539    /// # use std::borrow::Cow;
4540    /// let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);
4541    /// let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);
4542    /// assert_eq!(Vec::from(o), Vec::from(b));
4543    /// ```
4544    fn from(s: Cow<'a, [T]>) -> Vec<T> {
4545        s.into_owned()
4546    }
4547}
4548
4549// note: test pulls in std, which causes errors here
4550#[stable(feature = "vec_from_box", since = "1.18.0")]
4551impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
4552    /// Converts a boxed slice into a vector by transferring ownership of
4553    /// the existing heap allocation.
4554    ///
4555    /// # Examples
4556    ///
4557    /// ```
4558    /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
4559    /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
4560    /// ```
4561    fn from(s: Box<[T], A>) -> Self {
4562        s.into_vec()
4563    }
4564}
4565
4566// note: test pulls in std, which causes errors here
4567#[cfg(not(no_global_oom_handling))]
4568#[stable(feature = "box_from_vec", since = "1.20.0")]
4569impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
4570    /// Converts a vector into a boxed slice.
4571    ///
4572    /// Before doing the conversion, this method discards excess capacity like [`Vec::shrink_to_fit`].
4573    ///
4574    /// [owned slice]: Box
4575    /// [`Vec::shrink_to_fit`]: Vec::shrink_to_fit
4576    ///
4577    /// # Examples
4578    ///
4579    /// ```
4580    /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
4581    /// ```
4582    ///
4583    /// Any excess capacity is removed:
4584    /// ```
4585    /// let mut vec = Vec::with_capacity(10);
4586    /// vec.extend([1, 2, 3]);
4587    ///
4588    /// assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice());
4589    /// ```
4590    fn from(v: Vec<T, A>) -> Self {
4591        v.into_boxed_slice()
4592    }
4593}
4594
4595#[cfg(not(no_global_oom_handling))]
4596#[stable(feature = "rust1", since = "1.0.0")]
4597impl From<&str> for Vec<u8> {
4598    /// Allocates a `Vec<u8>` and fills it with a UTF-8 string.
4599    ///
4600    /// # Examples
4601    ///
4602    /// ```
4603    /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
4604    /// ```
4605    fn from(s: &str) -> Vec<u8> {
4606        From::from(s.as_bytes())
4607    }
4608}
4609
4610#[stable(feature = "array_try_from_vec", since = "1.48.0")]
4611#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
4612const impl<T: [const] Destruct, A: [const] Allocator + [const] Destruct, const N: usize>
4613    TryFrom<Vec<T, A>> for [T; N]
4614{
4615    type Error = Vec<T, A>;
4616
4617    /// Gets the entire contents of the `Vec<T>` as an array,
4618    /// if its size exactly matches that of the requested array.
4619    ///
4620    /// # Examples
4621    ///
4622    /// ```
4623    /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
4624    /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
4625    /// ```
4626    ///
4627    /// If the length doesn't match, the input comes back in `Err`:
4628    /// ```
4629    /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
4630    /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
4631    /// ```
4632    ///
4633    /// If you're fine with just getting a prefix of the `Vec<T>`,
4634    /// you can call [`.truncate(N)`](Vec::truncate) first.
4635    /// ```
4636    /// let mut v = String::from("hello world").into_bytes();
4637    /// v.sort();
4638    /// v.truncate(2);
4639    /// let [a, b]: [_; 2] = v.try_into().unwrap();
4640    /// assert_eq!(a, b' ');
4641    /// assert_eq!(b, b'd');
4642    /// ```
4643    fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
4644        if vec.len() != N {
4645            return Err(vec);
4646        }
4647
4648        // SAFETY: `.set_len(0)` is always sound.
4649        unsafe { vec.set_len(0) };
4650
4651        // SAFETY: A `Vec`'s pointer is always aligned properly, and
4652        // the alignment the array needs is the same as the items.
4653        // We checked earlier that we have sufficient items.
4654        // The items will not double-drop as the `set_len`
4655        // tells the `Vec` not to also drop them.
4656        let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
4657        Ok(array)
4658    }
4659}