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