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