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