Thanks to visit codestin.com
Credit goes to doc.rust-lang.org

Skip to main content

alloc/vec/
mod.rs

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