Skip to main content

alloc/vec/
mod.rs

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