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