allocator_api2/stable/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#[cfg(not(no_global_oom_handling))]
55use core::cmp;
56use core::cmp::Ordering;
57use core::convert::TryFrom;
58use core::fmt;
59use core::hash::{Hash, Hasher};
60#[cfg(not(no_global_oom_handling))]
61use core::iter;
62#[cfg(not(no_global_oom_handling))]
63use core::iter::FromIterator;
64use core::marker::PhantomData;
65use core::mem::{self, size_of, ManuallyDrop, MaybeUninit};
66use core::ops::{self, Bound, Index, IndexMut, RangeBounds};
67use core::ptr::{self, NonNull};
68use core::slice::{self, SliceIndex};
69
70#[cfg(feature = "std")]
71use std::io;
72
73use super::{
74    alloc::{Allocator, Global},
75    assume,
76    boxed::Box,
77    raw_vec::{RawVec, TryReserveError},
78};
79
80#[cfg(not(no_global_oom_handling))]
81pub use self::splice::Splice;
82
83#[cfg(not(no_global_oom_handling))]
84mod splice;
85
86pub use self::drain::Drain;
87
88mod drain;
89
90pub use self::into_iter::IntoIter;
91
92mod into_iter;
93
94mod partial_eq;
95
96#[cfg(not(no_global_oom_handling))]
97mod set_len_on_drop;
98
99#[cfg(not(no_global_oom_handling))]
100use self::set_len_on_drop::SetLenOnDrop;
101
102/// A contiguous growable array type, written as `Vec<T>`, short for 'vector'.
103///
104/// # Examples
105///
106/// ```
107/// let mut vec = Vec::new();
108/// vec.push(1);
109/// vec.push(2);
110///
111/// assert_eq!(vec.len(), 2);
112/// assert_eq!(vec[0], 1);
113///
114/// assert_eq!(vec.pop(), Some(2));
115/// assert_eq!(vec.len(), 1);
116///
117/// vec[0] = 7;
118/// assert_eq!(vec[0], 7);
119///
120/// vec.extend([1, 2, 3].iter().copied());
121///
122/// for x in &vec {
123///     println!("{x}");
124/// }
125/// assert_eq!(vec, [7, 1, 2, 3]);
126/// ```
127///
128/// The [`vec!`] macro is provided for convenient initialization:
129///
130/// ```
131/// let mut vec1 = vec![1, 2, 3];
132/// vec1.push(4);
133/// let vec2 = Vec::from([1, 2, 3, 4]);
134/// assert_eq!(vec1, vec2);
135/// ```
136///
137/// It can also initialize each element of a `Vec<T>` with a given value.
138/// This may be more efficient than performing allocation and initialization
139/// in separate steps, especially when initializing a vector of zeros:
140///
141/// ```
142/// let vec = vec![0; 5];
143/// assert_eq!(vec, [0, 0, 0, 0, 0]);
144///
145/// // The following is equivalent, but potentially slower:
146/// let mut vec = Vec::with_capacity(5);
147/// vec.resize(5, 0);
148/// assert_eq!(vec, [0, 0, 0, 0, 0]);
149/// ```
150///
151/// For more information, see
152/// [Capacity and Reallocation](#capacity-and-reallocation).
153///
154/// Use a `Vec<T>` as an efficient stack:
155///
156/// ```
157/// let mut stack = Vec::new();
158///
159/// stack.push(1);
160/// stack.push(2);
161/// stack.push(3);
162///
163/// while let Some(top) = stack.pop() {
164///     // Prints 3, 2, 1
165///     println!("{top}");
166/// }
167/// ```
168///
169/// # Indexing
170///
171/// The `Vec` type allows to access values by index, because it implements the
172/// [`Index`] trait. An example will be more explicit:
173///
174/// ```
175/// let v = vec![0, 2, 4, 6];
176/// println!("{}", v[1]); // it will display '2'
177/// ```
178///
179/// However be careful: if you try to access an index which isn't in the `Vec`,
180/// your software will panic! You cannot do this:
181///
182/// ```should_panic
183/// let v = vec![0, 2, 4, 6];
184/// println!("{}", v[6]); // it will panic!
185/// ```
186///
187/// Use [`get`] and [`get_mut`] if you want to check whether the index is in
188/// the `Vec`.
189///
190/// # Slicing
191///
192/// A `Vec` can be mutable. On the other hand, slices are read-only objects.
193/// To get a [slice][prim@slice], use [`&`]. Example:
194///
195/// ```
196/// fn read_slice(slice: &[usize]) {
197///     // ...
198/// }
199///
200/// let v = vec![0, 1];
201/// read_slice(&v);
202///
203/// // ... and that's all!
204/// // you can also do it like this:
205/// let u: &[usize] = &v;
206/// // or like this:
207/// let u: &[_] = &v;
208/// ```
209///
210/// In Rust, it's more common to pass slices as arguments rather than vectors
211/// when you just want to provide read access. The same goes for [`String`] and
212/// [`&str`].
213///
214/// # Capacity and reallocation
215///
216/// The capacity of a vector is the amount of space allocated for any future
217/// elements that will be added onto the vector. This is not to be confused with
218/// the *length* of a vector, which specifies the number of actual elements
219/// within the vector. If a vector's length exceeds its capacity, its capacity
220/// will automatically be increased, but its elements will have to be
221/// reallocated.
222///
223/// For example, a vector with capacity 10 and length 0 would be an empty vector
224/// with space for 10 more elements. Pushing 10 or fewer elements onto the
225/// vector will not change its capacity or cause reallocation to occur. However,
226/// if the vector's length is increased to 11, it will have to reallocate, which
227/// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
228/// whenever possible to specify how big the vector is expected to get.
229///
230/// # Guarantees
231///
232/// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
233/// about its design. This ensures that it's as low-overhead as possible in
234/// the general case, and can be correctly manipulated in primitive ways
235/// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
236/// If additional type parameters are added (e.g., to support custom allocators),
237/// overriding their defaults may change the behavior.
238///
239/// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
240/// triplet. No more, no less. The order of these fields is completely
241/// unspecified, and you should use the appropriate methods to modify these.
242/// The pointer will never be null, so this type is null-pointer-optimized.
243///
244/// However, the pointer might not actually point to allocated memory. In particular,
245/// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
246/// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
247/// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
248/// types inside a `Vec`, it will not allocate space for them. *Note that in this case
249/// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only
250/// if <code>[mem::size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation
251/// details are very subtle --- if you intend to allocate memory using a `Vec`
252/// and use it for something else (either to pass to unsafe code, or to build your
253/// own memory-backed collection), be sure to deallocate this memory by using
254/// `from_raw_parts` to recover the `Vec` and then dropping it.
255///
256/// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
257/// (as defined by the allocator Rust is configured to use by default), and its
258/// pointer points to [`len`] initialized, contiguous elements in order (what
259/// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>
260/// logically uninitialized, contiguous elements.
261///
262/// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
263/// visualized as below. The top part is the `Vec` struct, it contains a
264/// pointer to the head of the allocation in the heap, length and capacity.
265/// The bottom part is the allocation on the heap, a contiguous memory block.
266///
267/// ```text
268///             ptr      len  capacity
269///        +--------+--------+--------+
270///        | 0x0123 |      2 |      4 |
271///        +--------+--------+--------+
272///             |
273///             v
274/// Heap   +--------+--------+--------+--------+
275///        |    'a' |    'b' | uninit | uninit |
276///        +--------+--------+--------+--------+
277/// ```
278///
279/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
280/// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
281///   layout (including the order of fields).
282///
283/// `Vec` will never perform a "small optimization" where elements are actually
284/// stored on the stack for two reasons:
285///
286/// * It would make it more difficult for unsafe code to correctly manipulate
287///   a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
288///   only moved, and it would be more difficult to determine if a `Vec` had
289///   actually allocated memory.
290///
291/// * It would penalize the general case, incurring an additional branch
292///   on every access.
293///
294/// `Vec` will never automatically shrink itself, even if completely empty. This
295/// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
296/// and then filling it back up to the same [`len`] should incur no calls to
297/// the allocator. If you wish to free up unused memory, use
298/// [`shrink_to_fit`] or [`shrink_to`].
299///
300/// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
301/// sufficient. [`push`] and [`insert`] *will* (re)allocate if
302/// <code>[len] == [capacity]</code>. That is, the reported capacity is completely
303/// accurate, and can be relied on. It can even be used to manually free the memory
304/// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
305/// when not necessary.
306///
307/// `Vec` does not guarantee any particular growth strategy when reallocating
308/// when full, nor when [`reserve`] is called. The current strategy is basic
309/// and it may prove desirable to use a non-constant growth factor. Whatever
310/// strategy is used will of course guarantee *O*(1) amortized [`push`].
311///
312/// `vec![x; n]`, `vec![a, b, c, d]`, and
313/// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
314/// with exactly the requested capacity. If <code>[len] == [capacity]</code>,
315/// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
316/// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
317///
318/// `Vec` will not specifically overwrite any data that is removed from it,
319/// but also won't specifically preserve it. Its uninitialized memory is
320/// scratch space that it may use however it wants. It will generally just do
321/// whatever is most efficient or otherwise easy to implement. Do not rely on
322/// removed data to be erased for security purposes. Even if you drop a `Vec`, its
323/// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory
324/// first, that might not actually happen because the optimizer does not consider
325/// this a side-effect that must be preserved. There is one case which we will
326/// not break, however: using `unsafe` code to write to the excess capacity,
327/// and then increasing the length to match, is always valid.
328///
329/// Currently, `Vec` does not guarantee the order in which elements are dropped.
330/// The order has changed in the past and may change again.
331///
332/// [`get`]: ../../std/vec/struct.Vec.html#method.get
333/// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
334/// [`String`]: alloc_crate::string::String
335/// [`&str`]: type@str
336/// [`shrink_to_fit`]: Vec::shrink_to_fit
337/// [`shrink_to`]: Vec::shrink_to
338/// [capacity]: Vec::capacity
339/// [`capacity`]: Vec::capacity
340/// [mem::size_of::\<T>]: core::mem::size_of
341/// [len]: Vec::len
342/// [`len`]: Vec::len
343/// [`push`]: Vec::push
344/// [`insert`]: Vec::insert
345/// [`reserve`]: Vec::reserve
346/// [`MaybeUninit`]: core::mem::MaybeUninit
347/// [owned slice]: Box
348pub struct Vec<T, A: Allocator = Global> {
349    buf: RawVec<T, A>,
350    len: usize,
351}
352
353////////////////////////////////////////////////////////////////////////////////
354// Inherent methods
355////////////////////////////////////////////////////////////////////////////////
356
357impl<T> Vec<T> {
358    /// Constructs a new, empty `Vec<T>`.
359    ///
360    /// The vector will not allocate until elements are pushed onto it.
361    ///
362    /// # Examples
363    ///
364    /// ```
365    /// # #![allow(unused_mut)]
366    /// let mut vec: Vec<i32> = Vec::new();
367    /// ```
368    #[inline(always)]
369    #[must_use]
370    pub const fn new() -> Self {
371        Vec {
372            buf: RawVec::new(),
373            len: 0,
374        }
375    }
376
377    /// Constructs a new, empty `Vec<T>` with at least the specified capacity.
378    ///
379    /// The vector will be able to hold at least `capacity` elements without
380    /// reallocating. This method is allowed to allocate for more elements than
381    /// `capacity`. If `capacity` is 0, the vector will not allocate.
382    ///
383    /// It is important to note that although the returned vector has the
384    /// minimum *capacity* specified, the vector will have a zero *length*. For
385    /// an explanation of the difference between length and capacity, see
386    /// *[Capacity and reallocation]*.
387    ///
388    /// If it is important to know the exact allocated capacity of a `Vec`,
389    /// always use the [`capacity`] method after construction.
390    ///
391    /// For `Vec<T>` where `T` is a zero-sized type, there will be no allocation
392    /// and the capacity will always be `usize::MAX`.
393    ///
394    /// [Capacity and reallocation]: #capacity-and-reallocation
395    /// [`capacity`]: Vec::capacity
396    ///
397    /// # Panics
398    ///
399    /// Panics if the new capacity exceeds `isize::MAX` bytes.
400    ///
401    /// # Examples
402    ///
403    /// ```
404    /// let mut vec = Vec::with_capacity(10);
405    ///
406    /// // The vector contains no items, even though it has capacity for more
407    /// assert_eq!(vec.len(), 0);
408    /// assert!(vec.capacity() >= 10);
409    ///
410    /// // These are all done without reallocating...
411    /// for i in 0..10 {
412    ///     vec.push(i);
413    /// }
414    /// assert_eq!(vec.len(), 10);
415    /// assert!(vec.capacity() >= 10);
416    ///
417    /// // ...but this may make the vector reallocate
418    /// vec.push(11);
419    /// assert_eq!(vec.len(), 11);
420    /// assert!(vec.capacity() >= 11);
421    ///
422    /// // A vector of a zero-sized type will always over-allocate, since no
423    /// // allocation is necessary
424    /// let vec_units = Vec::<()>::with_capacity(10);
425    /// assert_eq!(vec_units.capacity(), usize::MAX);
426    /// ```
427    #[cfg(not(no_global_oom_handling))]
428    #[inline(always)]
429    #[must_use]
430    pub fn with_capacity(capacity: usize) -> Self {
431        Self::with_capacity_in(capacity, Global)
432    }
433
434    /// Creates a `Vec<T>` directly from a pointer, a capacity, and a length.
435    ///
436    /// # Safety
437    ///
438    /// This is highly unsafe, due to the number of invariants that aren't
439    /// checked:
440    ///
441    /// * `T` needs to have the same alignment as what `ptr` was allocated with.
442    ///   (`T` having a less strict alignment is not sufficient, the alignment really
443    ///   needs to be equal to satisfy the [`dealloc`] requirement that memory must be
444    ///   allocated and deallocated with the same layout.)
445    /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
446    ///   to be the same size as the pointer was allocated with. (Because similar to
447    ///   alignment, [`dealloc`] must be called with the same layout `size`.)
448    /// * `length` needs to be less than or equal to `capacity`.
449    /// * The first `length` values must be properly initialized values of type `T`.
450    /// * `capacity` needs to be the capacity that the pointer was allocated with.
451    /// * The allocated size in bytes must be no larger than `isize::MAX`.
452    ///   See the safety documentation of [`pointer::offset`](https://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.offset).
453    ///
454    /// These requirements are always upheld by any `ptr` that has been allocated
455    /// via `Vec<T>`. Other allocation sources are allowed if the invariants are
456    /// upheld.
457    ///
458    /// Violating these may cause problems like corrupting the allocator's
459    /// internal data structures. For example it is normally **not** safe
460    /// to build a `Vec<u8>` from a pointer to a C `char` array with length
461    /// `size_t`, doing so is only safe if the array was initially allocated by
462    /// a `Vec` or `String`.
463    /// It's also not safe to build one from a `Vec<u16>` and its length, because
464    /// the allocator cares about the alignment, and these two types have different
465    /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
466    /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
467    /// these issues, it is often preferable to do casting/transmuting using
468    /// [`slice::from_raw_parts`] instead.
469    ///
470    /// The ownership of `ptr` is effectively transferred to the
471    /// `Vec<T>` which may then deallocate, reallocate or change the
472    /// contents of memory pointed to by the pointer at will. Ensure
473    /// that nothing else uses the pointer after calling this
474    /// function.
475    ///
476    /// [`String`]: alloc_crate::string::String
477    /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
478    ///
479    /// # Examples
480    ///
481    /// ```
482    /// use std::ptr;
483    /// use std::mem;
484    ///
485    /// let v = vec![1, 2, 3];
486    ///
487    // FIXME Update this when vec_into_raw_parts is stabilized
488    /// // Prevent running `v`'s destructor so we are in complete control
489    /// // of the allocation.
490    /// let mut v = mem::ManuallyDrop::new(v);
491    ///
492    /// // Pull out the various important pieces of information about `v`
493    /// let p = v.as_mut_ptr();
494    /// let len = v.len();
495    /// let cap = v.capacity();
496    ///
497    /// unsafe {
498    ///     // Overwrite memory with 4, 5, 6
499    ///     for i in 0..len {
500    ///         ptr::write(p.add(i), 4 + i);
501    ///     }
502    ///
503    ///     // Put everything back together into a Vec
504    ///     let rebuilt = Vec::from_raw_parts(p, len, cap);
505    ///     assert_eq!(rebuilt, [4, 5, 6]);
506    /// }
507    /// ```
508    ///
509    /// Using memory that was allocated elsewhere:
510    ///
511    /// ```rust
512    /// #![feature(allocator_api)]
513    ///
514    /// use std::alloc::{AllocError, Allocator, Global, Layout};
515    ///
516    /// fn main() {
517    ///     let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
518    ///
519    ///     let vec = unsafe {
520    ///         let mem = match Global.allocate(layout) {
521    ///             Ok(mem) => mem.cast::<u32>().as_ptr(),
522    ///             Err(AllocError) => return,
523    ///         };
524    ///
525    ///         mem.write(1_000_000);
526    ///
527    ///         Vec::from_raw_parts_in(mem, 1, 16, Global)
528    ///     };
529    ///
530    ///     assert_eq!(vec, &[1_000_000]);
531    ///     assert_eq!(vec.capacity(), 16);
532    /// }
533    /// ```
534    #[inline(always)]
535    pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
536        unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
537    }
538}
539
540impl<T, A: Allocator> Vec<T, A> {
541    /// Constructs a new, empty `Vec<T, A>`.
542    ///
543    /// The vector will not allocate until elements are pushed onto it.
544    ///
545    /// # Examples
546    ///
547    /// ```
548    /// use std::alloc::System;
549    ///
550    /// # #[allow(unused_mut)]
551    /// let mut vec: Vec<i32, _> = Vec::new_in(System);
552    /// ```
553    #[inline(always)]
554    pub const fn new_in(alloc: A) -> Self {
555        Vec {
556            buf: RawVec::new_in(alloc),
557            len: 0,
558        }
559    }
560
561    /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity
562    /// with the provided allocator.
563    ///
564    /// The vector will be able to hold at least `capacity` elements without
565    /// reallocating. This method is allowed to allocate for more elements than
566    /// `capacity`. If `capacity` is 0, the vector will not allocate.
567    ///
568    /// It is important to note that although the returned vector has the
569    /// minimum *capacity* specified, the vector will have a zero *length*. For
570    /// an explanation of the difference between length and capacity, see
571    /// *[Capacity and reallocation]*.
572    ///
573    /// If it is important to know the exact allocated capacity of a `Vec`,
574    /// always use the [`capacity`] method after construction.
575    ///
576    /// For `Vec<T, A>` where `T` is a zero-sized type, there will be no allocation
577    /// and the capacity will always be `usize::MAX`.
578    ///
579    /// [Capacity and reallocation]: #capacity-and-reallocation
580    /// [`capacity`]: Vec::capacity
581    ///
582    /// # Panics
583    ///
584    /// Panics if the new capacity exceeds `isize::MAX` bytes.
585    ///
586    /// # Examples
587    ///
588    /// ```
589    /// use std::alloc::System;
590    ///
591    /// let mut vec = Vec::with_capacity_in(10, System);
592    ///
593    /// // The vector contains no items, even though it has capacity for more
594    /// assert_eq!(vec.len(), 0);
595    /// assert_eq!(vec.capacity(), 10);
596    ///
597    /// // These are all done without reallocating...
598    /// for i in 0..10 {
599    ///     vec.push(i);
600    /// }
601    /// assert_eq!(vec.len(), 10);
602    /// assert_eq!(vec.capacity(), 10);
603    ///
604    /// // ...but this may make the vector reallocate
605    /// vec.push(11);
606    /// assert_eq!(vec.len(), 11);
607    /// assert!(vec.capacity() >= 11);
608    ///
609    /// // A vector of a zero-sized type will always over-allocate, since no
610    /// // allocation is necessary
611    /// let vec_units = Vec::<(), System>::with_capacity_in(10, System);
612    /// assert_eq!(vec_units.capacity(), usize::MAX);
613    /// ```
614    #[cfg(not(no_global_oom_handling))]
615    #[inline(always)]
616    pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
617        Vec {
618            buf: RawVec::with_capacity_in(capacity, alloc),
619            len: 0,
620        }
621    }
622
623    /// Creates a `Vec<T, A>` directly from a pointer, a capacity, a length,
624    /// and an allocator.
625    ///
626    /// # Safety
627    ///
628    /// This is highly unsafe, due to the number of invariants that aren't
629    /// checked:
630    ///
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 [*fit*] the layout size 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`](https://doc.rust-lang.org/nightly/std/primitive.pointer.html#method.offset).
643    ///
644    /// These requirements are always upheld by any `ptr` that has been allocated
645    /// via `Vec<T, A>`. 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 **not** safe
650    /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
651    /// It's also not safe to build one from a `Vec<u16>` and its length, because
652    /// the allocator cares about the alignment, and these two types have different
653    /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
654    /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
655    ///
656    /// The ownership of `ptr` is effectively transferred to the
657    /// `Vec<T>` which may then deallocate, reallocate or change the
658    /// contents of memory pointed to by the pointer at will. Ensure
659    /// that nothing else uses the pointer after calling this
660    /// function.
661    ///
662    /// [`String`]: alloc_crate::string::String
663    /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
664    /// [*fit*]: crate::alloc::Allocator#memory-fitting
665    ///
666    /// # Examples
667    ///
668    /// ```
669    /// use std::alloc::System;
670    ///
671    /// use std::ptr;
672    /// use std::mem;
673    ///
674    ///
675    /// # use allocator_api2::vec::Vec;
676    /// let mut v = Vec::with_capacity_in(3, System);
677    /// v.push(1);
678    /// v.push(2);
679    /// v.push(3);
680    ///
681    // FIXME Update this when vec_into_raw_parts is stabilized
682    /// // Prevent running `v`'s destructor so we are in complete control
683    /// // of the allocation.
684    /// let mut v = mem::ManuallyDrop::new(v);
685    ///
686    /// // Pull out the various important pieces of information about `v`
687    /// let p = v.as_mut_ptr();
688    /// let len = v.len();
689    /// let cap = v.capacity();
690    /// let alloc = v.allocator();
691    ///
692    /// unsafe {
693    ///     // Overwrite memory with 4, 5, 6
694    ///     for i in 0..len {
695    ///         ptr::write(p.add(i), 4 + i);
696    ///     }
697    ///
698    ///     // Put everything back together into a Vec
699    ///     let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
700    ///     assert_eq!(rebuilt, [4, 5, 6]);
701    /// }
702    /// ```
703    ///
704    /// Using memory that was allocated elsewhere:
705    ///
706    /// ```rust
707    /// use std::alloc::{alloc, Layout};
708    ///
709    /// fn main() {
710    ///     let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
711    ///     let vec = unsafe {
712    ///         let mem = alloc(layout).cast::<u32>();
713    ///         if mem.is_null() {
714    ///             return;
715    ///         }
716    ///
717    ///         mem.write(1_000_000);
718    ///
719    ///         Vec::from_raw_parts(mem, 1, 16)
720    ///     };
721    ///
722    ///     assert_eq!(vec, &[1_000_000]);
723    ///     assert_eq!(vec.capacity(), 16);
724    /// }
725    /// ```
726    #[inline(always)]
727    pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
728        unsafe {
729            Vec {
730                buf: RawVec::from_raw_parts_in(ptr, capacity, alloc),
731                len: length,
732            }
733        }
734    }
735
736    /// Decomposes a `Vec<T>` into its raw components.
737    ///
738    /// Returns the raw pointer to the underlying data, the length of
739    /// the vector (in elements), and the allocated capacity of the
740    /// data (in elements). These are the same arguments in the same
741    /// order as the arguments to [`from_raw_parts`].
742    ///
743    /// After calling this function, the caller is responsible for the
744    /// memory previously managed by the `Vec`. The only way to do
745    /// this is to convert the raw pointer, length, and capacity back
746    /// into a `Vec` with the [`from_raw_parts`] function, allowing
747    /// the destructor to perform the cleanup.
748    ///
749    /// [`from_raw_parts`]: Vec::from_raw_parts
750    ///
751    /// # Examples
752    ///
753    /// ```
754    /// #![feature(vec_into_raw_parts)]
755    /// let v: Vec<i32> = vec![-1, 0, 1];
756    ///
757    /// let (ptr, len, cap) = v.into_raw_parts();
758    ///
759    /// let rebuilt = unsafe {
760    ///     // We can now make changes to the components, such as
761    ///     // transmuting the raw pointer to a compatible type.
762    ///     let ptr = ptr as *mut u32;
763    ///
764    ///     Vec::from_raw_parts(ptr, len, cap)
765    /// };
766    /// assert_eq!(rebuilt, [4294967295, 0, 1]);
767    /// ```
768    pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
769        let mut me = ManuallyDrop::new(self);
770        (me.as_mut_ptr(), me.len(), me.capacity())
771    }
772
773    /// Decomposes a `Vec<T>` into its raw components.
774    ///
775    /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
776    /// the allocated capacity of the data (in elements), and the allocator. These are the same
777    /// arguments in the same order as the arguments to [`from_raw_parts_in`].
778    ///
779    /// After calling this function, the caller is responsible for the
780    /// memory previously managed by the `Vec`. The only way to do
781    /// this is to convert the raw pointer, length, and capacity back
782    /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
783    /// the destructor to perform the cleanup.
784    ///
785    /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
786    ///
787    /// # Examples
788    ///
789    /// ```
790    /// #![feature(allocator_api, vec_into_raw_parts)]
791    ///
792    /// use std::alloc::System;
793    ///
794    /// let mut v: Vec<i32, System> = Vec::new_in(System);
795    /// v.push(-1);
796    /// v.push(0);
797    /// v.push(1);
798    ///
799    /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
800    ///
801    /// let rebuilt = unsafe {
802    ///     // We can now make changes to the components, such as
803    ///     // transmuting the raw pointer to a compatible type.
804    ///     let ptr = ptr as *mut u32;
805    ///
806    ///     Vec::from_raw_parts_in(ptr, len, cap, alloc)
807    /// };
808    /// assert_eq!(rebuilt, [4294967295, 0, 1]);
809    /// ```
810    // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
811    pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
812        let mut me = ManuallyDrop::new(self);
813        let len = me.len();
814        let capacity = me.capacity();
815        let ptr = me.as_mut_ptr();
816        let alloc = unsafe { ptr::read(me.allocator()) };
817        (ptr, len, capacity, alloc)
818    }
819
820    /// Returns the total number of elements the vector can hold without
821    /// reallocating.
822    ///
823    /// # Examples
824    ///
825    /// ```
826    /// let mut vec: Vec<i32> = Vec::with_capacity(10);
827    /// vec.push(42);
828    /// assert_eq!(vec.capacity(), 10);
829    /// ```
830    #[inline(always)]
831    pub fn capacity(&self) -> usize {
832        self.buf.capacity()
833    }
834
835    /// Reserves capacity for at least `additional` more elements to be inserted
836    /// in the given `Vec<T>`. The collection may reserve more space to
837    /// speculatively avoid frequent reallocations. After calling `reserve`,
838    /// capacity will be greater than or equal to `self.len() + additional`.
839    /// Does nothing if capacity is already sufficient.
840    ///
841    /// # Panics
842    ///
843    /// Panics if the new capacity exceeds `isize::MAX` bytes.
844    ///
845    /// # Examples
846    ///
847    /// ```
848    /// let mut vec = vec![1];
849    /// vec.reserve(10);
850    /// assert!(vec.capacity() >= 11);
851    /// ```
852    #[cfg(not(no_global_oom_handling))]
853    #[inline(always)]
854    pub fn reserve(&mut self, additional: usize) {
855        self.buf.reserve(self.len, additional);
856    }
857
858    /// Reserves the minimum capacity for at least `additional` more elements to
859    /// be inserted in the given `Vec<T>`. Unlike [`reserve`], this will not
860    /// deliberately over-allocate to speculatively avoid frequent allocations.
861    /// After calling `reserve_exact`, capacity will be greater than or equal to
862    /// `self.len() + additional`. Does nothing if the capacity is already
863    /// sufficient.
864    ///
865    /// Note that the allocator may give the collection more space than it
866    /// requests. Therefore, capacity can not be relied upon to be precisely
867    /// minimal. Prefer [`reserve`] if future insertions are expected.
868    ///
869    /// [`reserve`]: Vec::reserve
870    ///
871    /// # Panics
872    ///
873    /// Panics if the new capacity exceeds `isize::MAX` bytes.
874    ///
875    /// # Examples
876    ///
877    /// ```
878    /// let mut vec = vec![1];
879    /// vec.reserve_exact(10);
880    /// assert!(vec.capacity() >= 11);
881    /// ```
882    #[cfg(not(no_global_oom_handling))]
883    #[inline(always)]
884    pub fn reserve_exact(&mut self, additional: usize) {
885        self.buf.reserve_exact(self.len, additional);
886    }
887
888    /// Tries to reserve capacity for at least `additional` more elements to be inserted
889    /// in the given `Vec<T>`. The collection may reserve more space to speculatively avoid
890    /// frequent reallocations. After calling `try_reserve`, capacity will be
891    /// greater than or equal to `self.len() + additional` if it returns
892    /// `Ok(())`. Does nothing if capacity is already sufficient. This method
893    /// preserves the contents even if an error occurs.
894    ///
895    /// # Errors
896    ///
897    /// If the capacity overflows, or the allocator reports a failure, then an error
898    /// is returned.
899    ///
900    /// # Examples
901    ///
902    /// ```
903    /// use allocator_api2::collections::TryReserveError;
904    ///
905    /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
906    ///     let mut output = Vec::new();
907    ///
908    ///     // Pre-reserve the memory, exiting if we can't
909    ///     output.try_reserve(data.len())?;
910    ///
911    ///     // Now we know this can't OOM in the middle of our complex work
912    ///     output.extend(data.iter().map(|&val| {
913    ///         val * 2 + 5 // very complicated
914    ///     }));
915    ///
916    ///     Ok(output)
917    /// }
918    /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
919    /// ```
920    #[inline(always)]
921    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
922        self.buf.try_reserve(self.len, additional)
923    }
924
925    /// Tries to reserve the minimum capacity for at least `additional`
926    /// elements to be inserted in the given `Vec<T>`. Unlike [`try_reserve`],
927    /// this will not deliberately over-allocate to speculatively avoid frequent
928    /// allocations. After calling `try_reserve_exact`, capacity will be greater
929    /// than or equal to `self.len() + additional` if it returns `Ok(())`.
930    /// Does nothing if the capacity is already sufficient.
931    ///
932    /// Note that the allocator may give the collection more space than it
933    /// requests. Therefore, capacity can not be relied upon to be precisely
934    /// minimal. Prefer [`try_reserve`] if future insertions are expected.
935    ///
936    /// [`try_reserve`]: Vec::try_reserve
937    ///
938    /// # Errors
939    ///
940    /// If the capacity overflows, or the allocator reports a failure, then an error
941    /// is returned.
942    ///
943    /// # Examples
944    ///
945    /// ```
946    /// use allocator_api2::collections::TryReserveError;
947    ///
948    /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
949    ///     let mut output = Vec::new();
950    ///
951    ///     // Pre-reserve the memory, exiting if we can't
952    ///     output.try_reserve_exact(data.len())?;
953    ///
954    ///     // Now we know this can't OOM in the middle of our complex work
955    ///     output.extend(data.iter().map(|&val| {
956    ///         val * 2 + 5 // very complicated
957    ///     }));
958    ///
959    ///     Ok(output)
960    /// }
961    /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
962    /// ```
963    #[inline(always)]
964    pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
965        self.buf.try_reserve_exact(self.len, additional)
966    }
967
968    /// Shrinks the capacity of the vector as much as possible.
969    ///
970    /// It will drop down as close as possible to the length but the allocator
971    /// may still inform the vector that there is space for a few more elements.
972    ///
973    /// # Examples
974    ///
975    /// ```
976    /// let mut vec = Vec::with_capacity(10);
977    /// vec.extend([1, 2, 3]);
978    /// assert_eq!(vec.capacity(), 10);
979    /// vec.shrink_to_fit();
980    /// assert!(vec.capacity() >= 3);
981    /// ```
982    #[cfg(not(no_global_oom_handling))]
983    #[inline(always)]
984    pub fn shrink_to_fit(&mut self) {
985        // The capacity is never less than the length, and there's nothing to do when
986        // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
987        // by only calling it with a greater capacity.
988        if self.capacity() > self.len {
989            self.buf.shrink_to_fit(self.len);
990        }
991    }
992
993    /// Shrinks the capacity of the vector with a lower bound.
994    ///
995    /// The capacity will remain at least as large as both the length
996    /// and the supplied value.
997    ///
998    /// If the current capacity is less than the lower limit, this is a no-op.
999    ///
1000    /// # Examples
1001    ///
1002    /// ```
1003    /// let mut vec = Vec::with_capacity(10);
1004    /// vec.extend([1, 2, 3]);
1005    /// assert_eq!(vec.capacity(), 10);
1006    /// vec.shrink_to(4);
1007    /// assert!(vec.capacity() >= 4);
1008    /// vec.shrink_to(0);
1009    /// assert!(vec.capacity() >= 3);
1010    /// ```
1011    #[cfg(not(no_global_oom_handling))]
1012    #[inline(always)]
1013    pub fn shrink_to(&mut self, min_capacity: usize) {
1014        if self.capacity() > min_capacity {
1015            self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
1016        }
1017    }
1018
1019    /// Converts the vector into [`Box<[T]>`][owned slice].
1020    ///
1021    /// If the vector has excess capacity, its items will be moved into a
1022    /// newly-allocated buffer with exactly the right capacity.
1023    ///
1024    /// [owned slice]: Box
1025    ///
1026    /// # Examples
1027    ///
1028    /// ```
1029    /// let v = vec![1, 2, 3];
1030    ///
1031    /// let slice = v.into_boxed_slice();
1032    /// ```
1033    ///
1034    /// Any excess capacity is removed:
1035    ///
1036    /// ```
1037    /// let mut vec = Vec::with_capacity(10);
1038    /// vec.extend([1, 2, 3]);
1039    ///
1040    /// assert_eq!(vec.capacity(), 10);
1041    /// let slice = vec.into_boxed_slice();
1042    /// assert_eq!(slice.into_vec().capacity(), 3);
1043    /// ```
1044    #[cfg(not(no_global_oom_handling))]
1045    #[inline(always)]
1046    pub fn into_boxed_slice(mut self) -> Box<[T], A> {
1047        unsafe {
1048            self.shrink_to_fit();
1049            let me = ManuallyDrop::new(self);
1050            let buf = ptr::read(&me.buf);
1051            let len = me.len();
1052            Box::<[mem::MaybeUninit<T>], A>::assume_init(buf.into_box(len))
1053        }
1054    }
1055
1056    /// Shortens the vector, keeping the first `len` elements and dropping
1057    /// the rest.
1058    ///
1059    /// If `len` is greater than the vector's current length, this has no
1060    /// effect.
1061    ///
1062    /// The [`drain`] method can emulate `truncate`, but causes the excess
1063    /// elements to be returned instead of dropped.
1064    ///
1065    /// Note that this method has no effect on the allocated capacity
1066    /// of the vector.
1067    ///
1068    /// # Examples
1069    ///
1070    /// Truncating a five element vector to two elements:
1071    ///
1072    /// ```
1073    /// let mut vec = vec![1, 2, 3, 4, 5];
1074    /// vec.truncate(2);
1075    /// assert_eq!(vec, [1, 2]);
1076    /// ```
1077    ///
1078    /// No truncation occurs when `len` is greater than the vector's current
1079    /// length:
1080    ///
1081    /// ```
1082    /// let mut vec = vec![1, 2, 3];
1083    /// vec.truncate(8);
1084    /// assert_eq!(vec, [1, 2, 3]);
1085    /// ```
1086    ///
1087    /// Truncating when `len == 0` is equivalent to calling the [`clear`]
1088    /// method.
1089    ///
1090    /// ```
1091    /// let mut vec = vec![1, 2, 3];
1092    /// vec.truncate(0);
1093    /// assert_eq!(vec, []);
1094    /// ```
1095    ///
1096    /// [`clear`]: Vec::clear
1097    /// [`drain`]: Vec::drain
1098    #[inline(always)]
1099    pub fn truncate(&mut self, len: usize) {
1100        // This is safe because:
1101        //
1102        // * the slice passed to `drop_in_place` is valid; the `len > self.len`
1103        //   case avoids creating an invalid slice, and
1104        // * the `len` of the vector is shrunk before calling `drop_in_place`,
1105        //   such that no value will be dropped twice in case `drop_in_place`
1106        //   were to panic once (if it panics twice, the program aborts).
1107        unsafe {
1108            // Note: It's intentional that this is `>` and not `>=`.
1109            //       Changing it to `>=` has negative performance
1110            //       implications in some cases. See #78884 for more.
1111            if len > self.len {
1112                return;
1113            }
1114            let remaining_len = self.len - len;
1115            let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
1116            self.len = len;
1117            ptr::drop_in_place(s);
1118        }
1119    }
1120
1121    /// Extracts a slice containing the entire vector.
1122    ///
1123    /// Equivalent to `&s[..]`.
1124    ///
1125    /// # Examples
1126    ///
1127    /// ```
1128    /// use std::io::{self, Write};
1129    /// let buffer = vec![1, 2, 3, 5, 8];
1130    /// io::sink().write(buffer.as_slice()).unwrap();
1131    /// ```
1132    #[inline(always)]
1133    pub fn as_slice(&self) -> &[T] {
1134        self
1135    }
1136
1137    /// Extracts a mutable slice of the entire vector.
1138    ///
1139    /// Equivalent to `&mut s[..]`.
1140    ///
1141    /// # Examples
1142    ///
1143    /// ```
1144    /// use std::io::{self, Read};
1145    /// let mut buffer = vec![0; 3];
1146    /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1147    /// ```
1148    #[inline(always)]
1149    pub fn as_mut_slice(&mut self) -> &mut [T] {
1150        self
1151    }
1152
1153    /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
1154    /// valid for zero sized reads if the vector didn't allocate.
1155    ///
1156    /// The caller must ensure that the vector outlives the pointer this
1157    /// function returns, or else it will end up pointing to garbage.
1158    /// Modifying the vector may cause its buffer to be reallocated,
1159    /// which would also make any pointers to it invalid.
1160    ///
1161    /// The caller must also ensure that the memory the pointer (non-transitively) points to
1162    /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1163    /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1164    ///
1165    /// # Examples
1166    ///
1167    /// ```
1168    /// let x = vec![1, 2, 4];
1169    /// let x_ptr = x.as_ptr();
1170    ///
1171    /// unsafe {
1172    ///     for i in 0..x.len() {
1173    ///         assert_eq!(*x_ptr.add(i), 1 << i);
1174    ///     }
1175    /// }
1176    /// ```
1177    ///
1178    /// [`as_mut_ptr`]: Vec::as_mut_ptr
1179    #[inline(always)]
1180    pub fn as_ptr(&self) -> *const T {
1181        // We shadow the slice method of the same name to avoid going through
1182        // `deref`, which creates an intermediate reference.
1183        let ptr = self.buf.ptr();
1184        unsafe {
1185            assume(!ptr.is_null());
1186        }
1187        ptr
1188    }
1189
1190    /// Returns an unsafe mutable pointer to the vector's buffer, or a dangling
1191    /// raw pointer valid for zero sized reads if the vector didn't allocate.
1192    ///
1193    /// The caller must ensure that the vector outlives the pointer this
1194    /// function returns, or else it will end up pointing to garbage.
1195    /// Modifying the vector may cause its buffer to be reallocated,
1196    /// which would also make any pointers to it invalid.
1197    ///
1198    /// # Examples
1199    ///
1200    /// ```
1201    /// // Allocate vector big enough for 4 elements.
1202    /// let size = 4;
1203    /// let mut x: Vec<i32> = Vec::with_capacity(size);
1204    /// let x_ptr = x.as_mut_ptr();
1205    ///
1206    /// // Initialize elements via raw pointer writes, then set length.
1207    /// unsafe {
1208    ///     for i in 0..size {
1209    ///         *x_ptr.add(i) = i as i32;
1210    ///     }
1211    ///     x.set_len(size);
1212    /// }
1213    /// assert_eq!(&*x, &[0, 1, 2, 3]);
1214    /// ```
1215    #[inline(always)]
1216    pub fn as_mut_ptr(&mut self) -> *mut T {
1217        // We shadow the slice method of the same name to avoid going through
1218        // `deref_mut`, which creates an intermediate reference.
1219        let ptr = self.buf.ptr();
1220        unsafe {
1221            assume(!ptr.is_null());
1222        }
1223        ptr
1224    }
1225
1226    /// Returns a reference to the underlying allocator.
1227    #[inline(always)]
1228    pub fn allocator(&self) -> &A {
1229        self.buf.allocator()
1230    }
1231
1232    /// Forces the length of the vector to `new_len`.
1233    ///
1234    /// This is a low-level operation that maintains none of the normal
1235    /// invariants of the type. Normally changing the length of a vector
1236    /// is done using one of the safe operations instead, such as
1237    /// [`truncate`], [`resize`], [`extend`], or [`clear`].
1238    ///
1239    /// [`truncate`]: Vec::truncate
1240    /// [`resize`]: Vec::resize
1241    /// [`extend`]: Extend::extend
1242    /// [`clear`]: Vec::clear
1243    ///
1244    /// # Safety
1245    ///
1246    /// - `new_len` must be less than or equal to [`capacity()`].
1247    /// - The elements at `old_len..new_len` must be initialized.
1248    ///
1249    /// [`capacity()`]: Vec::capacity
1250    ///
1251    /// # Examples
1252    ///
1253    /// This method can be useful for situations in which the vector
1254    /// is serving as a buffer for other code, particularly over FFI:
1255    ///
1256    /// ```no_run
1257    /// # #![allow(dead_code)]
1258    /// # // This is just a minimal skeleton for the doc example;
1259    /// # // don't use this as a starting point for a real library.
1260    /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
1261    /// # const Z_OK: i32 = 0;
1262    /// # extern "C" {
1263    /// #     fn deflateGetDictionary(
1264    /// #         strm: *mut std::ffi::c_void,
1265    /// #         dictionary: *mut u8,
1266    /// #         dictLength: *mut usize,
1267    /// #     ) -> i32;
1268    /// # }
1269    /// # impl StreamWrapper {
1270    /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
1271    ///     // Per the FFI method's docs, "32768 bytes is always enough".
1272    ///     let mut dict = Vec::with_capacity(32_768);
1273    ///     let mut dict_length = 0;
1274    ///     // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
1275    ///     // 1. `dict_length` elements were initialized.
1276    ///     // 2. `dict_length` <= the capacity (32_768)
1277    ///     // which makes `set_len` safe to call.
1278    ///     unsafe {
1279    ///         // Make the FFI call...
1280    ///         let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
1281    ///         if r == Z_OK {
1282    ///             // ...and update the length to what was initialized.
1283    ///             dict.set_len(dict_length);
1284    ///             Some(dict)
1285    ///         } else {
1286    ///             None
1287    ///         }
1288    ///     }
1289    /// }
1290    /// # }
1291    /// ```
1292    ///
1293    /// While the following example is sound, there is a memory leak since
1294    /// the inner vectors were not freed prior to the `set_len` call:
1295    ///
1296    /// ```
1297    /// let mut vec = vec![vec![1, 0, 0],
1298    ///                    vec![0, 1, 0],
1299    ///                    vec![0, 0, 1]];
1300    /// // SAFETY:
1301    /// // 1. `old_len..0` is empty so no elements need to be initialized.
1302    /// // 2. `0 <= capacity` always holds whatever `capacity` is.
1303    /// unsafe {
1304    ///     vec.set_len(0);
1305    /// }
1306    /// ```
1307    ///
1308    /// Normally, here, one would use [`clear`] instead to correctly drop
1309    /// the contents and thus not leak memory.
1310    #[inline(always)]
1311    pub unsafe fn set_len(&mut self, new_len: usize) {
1312        debug_assert!(new_len <= self.capacity());
1313
1314        self.len = new_len;
1315    }
1316
1317    /// Removes an element from the vector and returns it.
1318    ///
1319    /// The removed element is replaced by the last element of the vector.
1320    ///
1321    /// This does not preserve ordering, but is *O*(1).
1322    /// If you need to preserve the element order, use [`remove`] instead.
1323    ///
1324    /// [`remove`]: Vec::remove
1325    ///
1326    /// # Panics
1327    ///
1328    /// Panics if `index` is out of bounds.
1329    ///
1330    /// # Examples
1331    ///
1332    /// ```
1333    /// let mut v = vec!["foo", "bar", "baz", "qux"];
1334    ///
1335    /// assert_eq!(v.swap_remove(1), "bar");
1336    /// assert_eq!(v, ["foo", "qux", "baz"]);
1337    ///
1338    /// assert_eq!(v.swap_remove(0), "foo");
1339    /// assert_eq!(v, ["baz", "qux"]);
1340    /// ```
1341    #[inline(always)]
1342    pub fn swap_remove(&mut self, index: usize) -> T {
1343        #[cold]
1344        #[inline(never)]
1345        fn assert_failed(index: usize, len: usize) -> ! {
1346            panic!(
1347                "swap_remove index (is {}) should be < len (is {})",
1348                index, len
1349            );
1350        }
1351
1352        let len = self.len();
1353        if index >= len {
1354            assert_failed(index, len);
1355        }
1356        unsafe {
1357            // We replace self[index] with the last element. Note that if the
1358            // bounds check above succeeds there must be a last element (which
1359            // can be self[index] itself).
1360            let value = ptr::read(self.as_ptr().add(index));
1361            let base_ptr = self.as_mut_ptr();
1362            ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
1363            self.set_len(len - 1);
1364            value
1365        }
1366    }
1367
1368    /// Inserts an element at position `index` within the vector, shifting all
1369    /// elements after it to the right.
1370    ///
1371    /// # Panics
1372    ///
1373    /// Panics if `index > len`.
1374    ///
1375    /// # Examples
1376    ///
1377    /// ```
1378    /// let mut vec = vec![1, 2, 3];
1379    /// vec.insert(1, 4);
1380    /// assert_eq!(vec, [1, 4, 2, 3]);
1381    /// vec.insert(4, 5);
1382    /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1383    /// ```
1384    #[cfg(not(no_global_oom_handling))]
1385    pub fn insert(&mut self, index: usize, element: T) {
1386        #[cold]
1387        #[inline(never)]
1388        fn assert_failed(index: usize, len: usize) -> ! {
1389            panic!(
1390                "insertion index (is {}) should be <= len (is {})",
1391                index, len
1392            );
1393        }
1394
1395        let len = self.len();
1396
1397        // space for the new element
1398        if len == self.buf.capacity() {
1399            self.reserve(1);
1400        }
1401
1402        unsafe {
1403            // infallible
1404            // The spot to put the new value
1405            {
1406                let p = self.as_mut_ptr().add(index);
1407                match cmp::Ord::cmp(&index, &len) {
1408                    Ordering::Less => {
1409                        // Shift everything over to make space. (Duplicating the
1410                        // `index`th element into two consecutive places.)
1411                        ptr::copy(p, p.add(1), len - index);
1412                    }
1413                    Ordering::Equal => {
1414                        // No elements need shifting.
1415                    }
1416                    Ordering::Greater => {
1417                        assert_failed(index, len);
1418                    }
1419                }
1420                // Write it in, overwriting the first copy of the `index`th
1421                // element.
1422                ptr::write(p, element);
1423            }
1424            self.set_len(len + 1);
1425        }
1426    }
1427
1428    /// Removes and returns the element at position `index` within the vector,
1429    /// shifting all elements after it to the left.
1430    ///
1431    /// Note: Because this shifts over the remaining elements, it has a
1432    /// worst-case performance of *O*(*n*). If you don't need the order of elements
1433    /// to be preserved, use [`swap_remove`] instead. If you'd like to remove
1434    /// elements from the beginning of the `Vec`, consider using
1435    /// [`VecDeque::pop_front`] instead.
1436    ///
1437    /// [`swap_remove`]: Vec::swap_remove
1438    /// [`VecDeque::pop_front`]: alloc_crate::collections::VecDeque::pop_front
1439    ///
1440    /// # Panics
1441    ///
1442    /// Panics if `index` is out of bounds.
1443    ///
1444    /// # Examples
1445    ///
1446    /// ```
1447    /// let mut v = vec![1, 2, 3];
1448    /// assert_eq!(v.remove(1), 2);
1449    /// assert_eq!(v, [1, 3]);
1450    /// ```
1451    #[track_caller]
1452    #[inline(always)]
1453    pub fn remove(&mut self, index: usize) -> T {
1454        #[cold]
1455        #[inline(never)]
1456        #[track_caller]
1457        fn assert_failed(index: usize, len: usize) -> ! {
1458            panic!("removal index (is {}) should be < len (is {})", index, len);
1459        }
1460
1461        let len = self.len();
1462        if index >= len {
1463            assert_failed(index, len);
1464        }
1465        unsafe {
1466            // infallible
1467            let ret;
1468            {
1469                // the place we are taking from.
1470                let ptr = self.as_mut_ptr().add(index);
1471                // copy it out, unsafely having a copy of the value on
1472                // the stack and in the vector at the same time.
1473                ret = ptr::read(ptr);
1474
1475                // Shift everything down to fill in that spot.
1476                ptr::copy(ptr.add(1), ptr, len - index - 1);
1477            }
1478            self.set_len(len - 1);
1479            ret
1480        }
1481    }
1482
1483    /// Retains only the elements specified by the predicate.
1484    ///
1485    /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
1486    /// This method operates in place, visiting each element exactly once in the
1487    /// original order, and preserves the order of the retained elements.
1488    ///
1489    /// # Examples
1490    ///
1491    /// ```
1492    /// let mut vec = vec![1, 2, 3, 4];
1493    /// vec.retain(|&x| x % 2 == 0);
1494    /// assert_eq!(vec, [2, 4]);
1495    /// ```
1496    ///
1497    /// Because the elements are visited exactly once in the original order,
1498    /// external state may be used to decide which elements to keep.
1499    ///
1500    /// ```
1501    /// let mut vec = vec![1, 2, 3, 4, 5];
1502    /// let keep = [false, true, true, false, true];
1503    /// let mut iter = keep.iter();
1504    /// vec.retain(|_| *iter.next().unwrap());
1505    /// assert_eq!(vec, [2, 3, 5]);
1506    /// ```
1507    #[inline(always)]
1508    pub fn retain<F>(&mut self, mut f: F)
1509    where
1510        F: FnMut(&T) -> bool,
1511    {
1512        self.retain_mut(|elem| f(elem));
1513    }
1514
1515    /// Retains only the elements specified by the predicate, passing a mutable reference to it.
1516    ///
1517    /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
1518    /// This method operates in place, visiting each element exactly once in the
1519    /// original order, and preserves the order of the retained elements.
1520    ///
1521    /// # Examples
1522    ///
1523    /// ```
1524    /// let mut vec = vec![1, 2, 3, 4];
1525    /// vec.retain_mut(|x| if *x <= 3 {
1526    ///     *x += 1;
1527    ///     true
1528    /// } else {
1529    ///     false
1530    /// });
1531    /// assert_eq!(vec, [2, 3, 4]);
1532    /// ```
1533    #[inline]
1534    pub fn retain_mut<F>(&mut self, mut f: F)
1535    where
1536        F: FnMut(&mut T) -> bool,
1537    {
1538        let original_len = self.len();
1539        // Avoid double drop if the drop guard is not executed,
1540        // since we may make some holes during the process.
1541        unsafe { self.set_len(0) };
1542
1543        // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
1544        //      |<-              processed len   ->| ^- next to check
1545        //                  |<-  deleted cnt     ->|
1546        //      |<-              original_len                          ->|
1547        // Kept: Elements which predicate returns true on.
1548        // Hole: Moved or dropped element slot.
1549        // Unchecked: Unchecked valid elements.
1550        //
1551        // This drop guard will be invoked when predicate or `drop` of element panicked.
1552        // It shifts unchecked elements to cover holes and `set_len` to the correct length.
1553        // In cases when predicate and `drop` never panick, it will be optimized out.
1554        struct BackshiftOnDrop<'a, T, A: Allocator> {
1555            v: &'a mut Vec<T, A>,
1556            processed_len: usize,
1557            deleted_cnt: usize,
1558            original_len: usize,
1559        }
1560
1561        impl<T, A: Allocator> Drop for BackshiftOnDrop<'_, T, A> {
1562            fn drop(&mut self) {
1563                if self.deleted_cnt > 0 {
1564                    // SAFETY: Trailing unchecked items must be valid since we never touch them.
1565                    unsafe {
1566                        ptr::copy(
1567                            self.v.as_ptr().add(self.processed_len),
1568                            self.v
1569                                .as_mut_ptr()
1570                                .add(self.processed_len - self.deleted_cnt),
1571                            self.original_len - self.processed_len,
1572                        );
1573                    }
1574                }
1575                // SAFETY: After filling holes, all items are in contiguous memory.
1576                unsafe {
1577                    self.v.set_len(self.original_len - self.deleted_cnt);
1578                }
1579            }
1580        }
1581
1582        let mut g = BackshiftOnDrop {
1583            v: self,
1584            processed_len: 0,
1585            deleted_cnt: 0,
1586            original_len,
1587        };
1588
1589        fn process_loop<F, T, A: Allocator, const DELETED: bool>(
1590            original_len: usize,
1591            f: &mut F,
1592            g: &mut BackshiftOnDrop<'_, T, A>,
1593        ) where
1594            F: FnMut(&mut T) -> bool,
1595        {
1596            while g.processed_len != original_len {
1597                // SAFETY: Unchecked element must be valid.
1598                let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
1599                if !f(cur) {
1600                    // Advance early to avoid double drop if `drop_in_place` panicked.
1601                    g.processed_len += 1;
1602                    g.deleted_cnt += 1;
1603                    // SAFETY: We never touch this element again after dropped.
1604                    unsafe { ptr::drop_in_place(cur) };
1605                    // We already advanced the counter.
1606                    if DELETED {
1607                        continue;
1608                    } else {
1609                        break;
1610                    }
1611                }
1612                if DELETED {
1613                    // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
1614                    // We use copy for move, and never touch this element again.
1615                    unsafe {
1616                        let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
1617                        ptr::copy_nonoverlapping(cur, hole_slot, 1);
1618                    }
1619                }
1620                g.processed_len += 1;
1621            }
1622        }
1623
1624        // Stage 1: Nothing was deleted.
1625        process_loop::<F, T, A, false>(original_len, &mut f, &mut g);
1626
1627        // Stage 2: Some elements were deleted.
1628        process_loop::<F, T, A, true>(original_len, &mut f, &mut g);
1629
1630        // All item are processed. This can be optimized to `set_len` by LLVM.
1631        drop(g);
1632    }
1633
1634    /// Removes all but the first of consecutive elements in the vector that resolve to the same
1635    /// key.
1636    ///
1637    /// If the vector is sorted, this removes all duplicates.
1638    ///
1639    /// # Examples
1640    ///
1641    /// ```
1642    /// let mut vec = vec![10, 20, 21, 30, 20];
1643    ///
1644    /// vec.dedup_by_key(|i| *i / 10);
1645    ///
1646    /// assert_eq!(vec, [10, 20, 30, 20]);
1647    /// ```
1648    #[inline(always)]
1649    pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1650    where
1651        F: FnMut(&mut T) -> K,
1652        K: PartialEq,
1653    {
1654        self.dedup_by(|a, b| key(a) == key(b))
1655    }
1656
1657    /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1658    /// relation.
1659    ///
1660    /// The `same_bucket` function is passed references to two elements from the vector and
1661    /// must determine if the elements compare equal. The elements are passed in opposite order
1662    /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1663    ///
1664    /// If the vector is sorted, this removes all duplicates.
1665    ///
1666    /// # Examples
1667    ///
1668    /// ```
1669    /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1670    ///
1671    /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1672    ///
1673    /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1674    /// ```
1675    #[inline]
1676    pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1677    where
1678        F: FnMut(&mut T, &mut T) -> bool,
1679    {
1680        let len = self.len();
1681        if len <= 1 {
1682            return;
1683        }
1684
1685        /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */
1686        struct FillGapOnDrop<'a, T, A: Allocator> {
1687            /* Offset of the element we want to check if it is duplicate */
1688            read: usize,
1689
1690            /* Offset of the place where we want to place the non-duplicate
1691             * when we find it. */
1692            write: usize,
1693
1694            /* The Vec that would need correction if `same_bucket` panicked */
1695            vec: &'a mut Vec<T, A>,
1696        }
1697
1698        impl<'a, T, A: Allocator> Drop for FillGapOnDrop<'a, T, A> {
1699            fn drop(&mut self) {
1700                /* This code gets executed when `same_bucket` panics */
1701
1702                /* SAFETY: invariant guarantees that `read - write`
1703                 * and `len - read` never overflow and that the copy is always
1704                 * in-bounds. */
1705                unsafe {
1706                    let ptr = self.vec.as_mut_ptr();
1707                    let len = self.vec.len();
1708
1709                    /* How many items were left when `same_bucket` panicked.
1710                     * Basically vec[read..].len() */
1711                    let items_left = len.wrapping_sub(self.read);
1712
1713                    /* Pointer to first item in vec[write..write+items_left] slice */
1714                    let dropped_ptr = ptr.add(self.write);
1715                    /* Pointer to first item in vec[read..] slice */
1716                    let valid_ptr = ptr.add(self.read);
1717
1718                    /* Copy `vec[read..]` to `vec[write..write+items_left]`.
1719                     * The slices can overlap, so `copy_nonoverlapping` cannot be used */
1720                    ptr::copy(valid_ptr, dropped_ptr, items_left);
1721
1722                    /* How many items have been already dropped
1723                     * Basically vec[read..write].len() */
1724                    let dropped = self.read.wrapping_sub(self.write);
1725
1726                    self.vec.set_len(len - dropped);
1727                }
1728            }
1729        }
1730
1731        let mut gap = FillGapOnDrop {
1732            read: 1,
1733            write: 1,
1734            vec: self,
1735        };
1736        let ptr = gap.vec.as_mut_ptr();
1737
1738        /* Drop items while going through Vec, it should be more efficient than
1739         * doing slice partition_dedup + truncate */
1740
1741        /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
1742         * are always in-bounds and read_ptr never aliases prev_ptr */
1743        unsafe {
1744            while gap.read < len {
1745                let read_ptr = ptr.add(gap.read);
1746                let prev_ptr = ptr.add(gap.write.wrapping_sub(1));
1747
1748                if same_bucket(&mut *read_ptr, &mut *prev_ptr) {
1749                    // Increase `gap.read` now since the drop may panic.
1750                    gap.read += 1;
1751                    /* We have found duplicate, drop it in-place */
1752                    ptr::drop_in_place(read_ptr);
1753                } else {
1754                    let write_ptr = ptr.add(gap.write);
1755
1756                    /* Because `read_ptr` can be equal to `write_ptr`, we either
1757                     * have to use `copy` or conditional `copy_nonoverlapping`.
1758                     * Looks like the first option is faster. */
1759                    ptr::copy(read_ptr, write_ptr, 1);
1760
1761                    /* We have filled that place, so go further */
1762                    gap.write += 1;
1763                    gap.read += 1;
1764                }
1765            }
1766
1767            /* Technically we could let `gap` clean up with its Drop, but
1768             * when `same_bucket` is guaranteed to not panic, this bloats a little
1769             * the codegen, so we just do it manually */
1770            gap.vec.set_len(gap.write);
1771            mem::forget(gap);
1772        }
1773    }
1774
1775    /// Appends an element to the back of a collection.
1776    ///
1777    /// # Panics
1778    ///
1779    /// Panics if the new capacity exceeds `isize::MAX` bytes.
1780    ///
1781    /// # Examples
1782    ///
1783    /// ```
1784    /// let mut vec = vec![1, 2];
1785    /// vec.push(3);
1786    /// assert_eq!(vec, [1, 2, 3]);
1787    /// ```
1788    #[cfg(not(no_global_oom_handling))]
1789    #[inline(always)]
1790    pub fn push(&mut self, value: T) {
1791        // This will panic or abort if we would allocate > isize::MAX bytes
1792        // or if the length increment would overflow for zero-sized types.
1793        if self.len == self.buf.capacity() {
1794            self.buf.reserve_for_push(self.len);
1795        }
1796        unsafe {
1797            let end = self.as_mut_ptr().add(self.len);
1798            ptr::write(end, value);
1799            self.len += 1;
1800        }
1801    }
1802
1803    /// Appends an element if there is sufficient spare capacity, otherwise an error is returned
1804    /// with the element.
1805    ///
1806    /// Unlike [`push`] this method will not reallocate when there's insufficient capacity.
1807    /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity.
1808    ///
1809    /// [`push`]: Vec::push
1810    /// [`reserve`]: Vec::reserve
1811    /// [`try_reserve`]: Vec::try_reserve
1812    ///
1813    /// # Examples
1814    ///
1815    /// A manual, panic-free alternative to [`FromIterator`]:
1816    ///
1817    /// ```
1818    /// #![feature(vec_push_within_capacity)]
1819    ///
1820    /// use std::collections::TryReserveError;
1821    /// fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
1822    ///     let mut vec = Vec::new();
1823    ///     for value in iter {
1824    ///         if let Err(value) = vec.push_within_capacity(value) {
1825    ///             vec.try_reserve(1)?;
1826    ///             // this cannot fail, the previous line either returned or added at least 1 free slot
1827    ///             let _ = vec.push_within_capacity(value);
1828    ///         }
1829    ///     }
1830    ///     Ok(vec)
1831    /// }
1832    /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
1833    /// ```
1834    #[inline(always)]
1835    pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> {
1836        if self.len == self.buf.capacity() {
1837            return Err(value);
1838        }
1839        unsafe {
1840            let end = self.as_mut_ptr().add(self.len);
1841            ptr::write(end, value);
1842            self.len += 1;
1843        }
1844        Ok(())
1845    }
1846
1847    /// Removes the last element from a vector and returns it, or [`None`] if it
1848    /// is empty.
1849    ///
1850    /// If you'd like to pop the first element, consider using
1851    /// [`VecDeque::pop_front`] instead.
1852    ///
1853    /// [`VecDeque::pop_front`]: alloc_crate::collections::VecDeque::pop_front
1854    ///
1855    /// # Examples
1856    ///
1857    /// ```
1858    /// let mut vec = vec![1, 2, 3];
1859    /// assert_eq!(vec.pop(), Some(3));
1860    /// assert_eq!(vec, [1, 2]);
1861    /// ```
1862    #[inline(always)]
1863    pub fn pop(&mut self) -> Option<T> {
1864        if self.len == 0 {
1865            None
1866        } else {
1867            unsafe {
1868                self.len -= 1;
1869                Some(ptr::read(self.as_ptr().add(self.len())))
1870            }
1871        }
1872    }
1873
1874    /// Moves all the elements of `other` into `self`, leaving `other` empty.
1875    ///
1876    /// # Panics
1877    ///
1878    /// Panics if the new capacity exceeds `isize::MAX` bytes.
1879    ///
1880    /// # Examples
1881    ///
1882    /// ```
1883    /// let mut vec = vec![1, 2, 3];
1884    /// let mut vec2 = vec![4, 5, 6];
1885    /// vec.append(&mut vec2);
1886    /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1887    /// assert_eq!(vec2, []);
1888    /// ```
1889    #[cfg(not(no_global_oom_handling))]
1890    #[inline(always)]
1891    pub fn append(&mut self, other: &mut Self) {
1892        unsafe {
1893            self.append_elements(other.as_slice() as _);
1894            other.set_len(0);
1895        }
1896    }
1897
1898    /// Appends elements to `self` from other buffer.
1899    #[cfg(not(no_global_oom_handling))]
1900    #[inline(always)]
1901    unsafe fn append_elements(&mut self, other: *const [T]) {
1902        let count = unsafe { (*other).len() };
1903        self.reserve(count);
1904        let len = self.len();
1905        unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1906        self.len += count;
1907    }
1908
1909    /// Removes the specified range from the vector in bulk, returning all
1910    /// removed elements as an iterator. If the iterator is dropped before
1911    /// being fully consumed, it drops the remaining removed elements.
1912    ///
1913    /// The returned iterator keeps a mutable borrow on the vector to optimize
1914    /// its implementation.
1915    ///
1916    /// # Panics
1917    ///
1918    /// Panics if the starting point is greater than the end point or if
1919    /// the end point is greater than the length of the vector.
1920    ///
1921    /// # Leaking
1922    ///
1923    /// If the returned iterator goes out of scope without being dropped (due to
1924    /// [`mem::forget`], for example), the vector may have lost and leaked
1925    /// elements arbitrarily, including elements outside the range.
1926    ///
1927    /// # Examples
1928    ///
1929    /// ```
1930    /// let mut v = vec![1, 2, 3];
1931    /// let u: Vec<_> = v.drain(1..).collect();
1932    /// assert_eq!(v, &[1]);
1933    /// assert_eq!(u, &[2, 3]);
1934    ///
1935    /// // A full range clears the vector, like `clear()` does
1936    /// v.drain(..);
1937    /// assert_eq!(v, &[]);
1938    /// ```
1939    #[inline(always)]
1940    pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1941    where
1942        R: RangeBounds<usize>,
1943    {
1944        // Memory safety
1945        //
1946        // When the Drain is first created, it shortens the length of
1947        // the source vector to make sure no uninitialized or moved-from elements
1948        // are accessible at all if the Drain's destructor never gets to run.
1949        //
1950        // Drain will ptr::read out the values to remove.
1951        // When finished, remaining tail of the vec is copied back to cover
1952        // the hole, and the vector length is restored to the new length.
1953        //
1954        let len = self.len();
1955
1956        // Replaced by code below
1957        // let Range { start, end } = slice::range(range, ..len);
1958
1959        // Panics if range is out of bounds
1960        let _ = &self.as_slice()[(range.start_bound().cloned(), range.end_bound().cloned())];
1961
1962        let start = match range.start_bound() {
1963            Bound::Included(&n) => n,
1964            Bound::Excluded(&n) => n + 1,
1965            Bound::Unbounded => 0,
1966        };
1967        let end = match range.end_bound() {
1968            Bound::Included(&n) => n + 1,
1969            Bound::Excluded(&n) => n,
1970            Bound::Unbounded => len,
1971        };
1972
1973        unsafe {
1974            // set self.vec length's to start, to be safe in case Drain is leaked
1975            self.set_len(start);
1976            let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
1977            Drain {
1978                tail_start: end,
1979                tail_len: len - end,
1980                iter: range_slice.iter(),
1981                vec: NonNull::from(self),
1982            }
1983        }
1984    }
1985
1986    /// Clears the vector, removing all values.
1987    ///
1988    /// Note that this method has no effect on the allocated capacity
1989    /// of the vector.
1990    ///
1991    /// # Examples
1992    ///
1993    /// ```
1994    /// let mut v = vec![1, 2, 3];
1995    ///
1996    /// v.clear();
1997    ///
1998    /// assert!(v.is_empty());
1999    /// ```
2000    #[inline(always)]
2001    pub fn clear(&mut self) {
2002        let elems: *mut [T] = self.as_mut_slice();
2003
2004        // SAFETY:
2005        // - `elems` comes directly from `as_mut_slice` and is therefore valid.
2006        // - Setting `self.len` before calling `drop_in_place` means that,
2007        //   if an element's `Drop` impl panics, the vector's `Drop` impl will
2008        //   do nothing (leaking the rest of the elements) instead of dropping
2009        //   some twice.
2010        unsafe {
2011            self.len = 0;
2012            ptr::drop_in_place(elems);
2013        }
2014    }
2015
2016    /// Returns the number of elements in the vector, also referred to
2017    /// as its 'length'.
2018    ///
2019    /// # Examples
2020    ///
2021    /// ```
2022    /// let a = vec![1, 2, 3];
2023    /// assert_eq!(a.len(), 3);
2024    /// ```
2025    #[inline(always)]
2026    pub fn len(&self) -> usize {
2027        self.len
2028    }
2029
2030    /// Returns `true` if the vector contains no elements.
2031    ///
2032    /// # Examples
2033    ///
2034    /// ```
2035    /// let mut v = Vec::new();
2036    /// assert!(v.is_empty());
2037    ///
2038    /// v.push(1);
2039    /// assert!(!v.is_empty());
2040    /// ```
2041    #[inline(always)]
2042    pub fn is_empty(&self) -> bool {
2043        self.len() == 0
2044    }
2045
2046    /// Splits the collection into two at the given index.
2047    ///
2048    /// Returns a newly allocated vector containing the elements in the range
2049    /// `[at, len)`. After the call, the original vector will be left containing
2050    /// the elements `[0, at)` with its previous capacity unchanged.
2051    ///
2052    /// # Panics
2053    ///
2054    /// Panics if `at > len`.
2055    ///
2056    /// # Examples
2057    ///
2058    /// ```
2059    /// let mut vec = vec![1, 2, 3];
2060    /// let vec2 = vec.split_off(1);
2061    /// assert_eq!(vec, [1]);
2062    /// assert_eq!(vec2, [2, 3]);
2063    /// ```
2064    #[cfg(not(no_global_oom_handling))]
2065    #[inline(always)]
2066    #[must_use = "use `.truncate()` if you don't need the other half"]
2067    pub fn split_off(&mut self, at: usize) -> Self
2068    where
2069        A: Clone,
2070    {
2071        #[cold]
2072        #[inline(never)]
2073        fn assert_failed(at: usize, len: usize) -> ! {
2074            panic!("`at` split index (is {}) should be <= len (is {})", at, len);
2075        }
2076
2077        if at > self.len() {
2078            assert_failed(at, self.len());
2079        }
2080
2081        if at == 0 {
2082            // the new vector can take over the original buffer and avoid the copy
2083            return mem::replace(
2084                self,
2085                Vec::with_capacity_in(self.capacity(), self.allocator().clone()),
2086            );
2087        }
2088
2089        let other_len = self.len - at;
2090        let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
2091
2092        // Unsafely `set_len` and copy items to `other`.
2093        unsafe {
2094            self.set_len(at);
2095            other.set_len(other_len);
2096
2097            ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
2098        }
2099        other
2100    }
2101
2102    /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2103    ///
2104    /// If `new_len` is greater than `len`, the `Vec` is extended by the
2105    /// difference, with each additional slot filled with the result of
2106    /// calling the closure `f`. The return values from `f` will end up
2107    /// in the `Vec` in the order they have been generated.
2108    ///
2109    /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2110    ///
2111    /// This method uses a closure to create new values on every push. If
2112    /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
2113    /// want to use the [`Default`] trait to generate values, you can
2114    /// pass [`Default::default`] as the second argument.
2115    ///
2116    /// # Examples
2117    ///
2118    /// ```
2119    /// let mut vec = vec![1, 2, 3];
2120    /// vec.resize_with(5, Default::default);
2121    /// assert_eq!(vec, [1, 2, 3, 0, 0]);
2122    ///
2123    /// let mut vec = vec![];
2124    /// let mut p = 1;
2125    /// vec.resize_with(4, || { p *= 2; p });
2126    /// assert_eq!(vec, [2, 4, 8, 16]);
2127    /// ```
2128    #[cfg(not(no_global_oom_handling))]
2129    #[inline(always)]
2130    pub fn resize_with<F>(&mut self, new_len: usize, f: F)
2131    where
2132        F: FnMut() -> T,
2133    {
2134        let len = self.len();
2135        if new_len > len {
2136            self.extend(iter::repeat_with(f).take(new_len - len));
2137        } else {
2138            self.truncate(new_len);
2139        }
2140    }
2141
2142    /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
2143    /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
2144    /// `'a`. If the type has only static references, or none at all, then this
2145    /// may be chosen to be `'static`.
2146    ///
2147    /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
2148    /// so the leaked allocation may include unused capacity that is not part
2149    /// of the returned slice.
2150    ///
2151    /// This function is mainly useful for data that lives for the remainder of
2152    /// the program's life. Dropping the returned reference will cause a memory
2153    /// leak.
2154    ///
2155    /// # Examples
2156    ///
2157    /// Simple usage:
2158    ///
2159    /// ```
2160    /// let x = vec![1, 2, 3];
2161    /// let static_ref: &'static mut [usize] = x.leak();
2162    /// static_ref[0] += 1;
2163    /// assert_eq!(static_ref, &[2, 2, 3]);
2164    /// ```
2165    #[inline(always)]
2166    pub fn leak<'a>(self) -> &'a mut [T]
2167    where
2168        A: 'a,
2169    {
2170        let mut me = ManuallyDrop::new(self);
2171        unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
2172    }
2173
2174    /// Returns the remaining spare capacity of the vector as a slice of
2175    /// `MaybeUninit<T>`.
2176    ///
2177    /// The returned slice can be used to fill the vector with data (e.g. by
2178    /// reading from a file) before marking the data as initialized using the
2179    /// [`set_len`] method.
2180    ///
2181    /// [`set_len`]: Vec::set_len
2182    ///
2183    /// # Examples
2184    ///
2185    /// ```
2186    /// // Allocate vector big enough for 10 elements.
2187    /// let mut v = Vec::with_capacity(10);
2188    ///
2189    /// // Fill in the first 3 elements.
2190    /// let uninit = v.spare_capacity_mut();
2191    /// uninit[0].write(0);
2192    /// uninit[1].write(1);
2193    /// uninit[2].write(2);
2194    ///
2195    /// // Mark the first 3 elements of the vector as being initialized.
2196    /// unsafe {
2197    ///     v.set_len(3);
2198    /// }
2199    ///
2200    /// assert_eq!(&v, &[0, 1, 2]);
2201    /// ```
2202    #[inline(always)]
2203    pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
2204        // Note:
2205        // This method is not implemented in terms of `split_at_spare_mut`,
2206        // to prevent invalidation of pointers to the buffer.
2207        unsafe {
2208            slice::from_raw_parts_mut(
2209                self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
2210                self.buf.capacity() - self.len,
2211            )
2212        }
2213    }
2214
2215    /// Returns vector content as a slice of `T`, along with the remaining spare
2216    /// capacity of the vector as a slice of `MaybeUninit<T>`.
2217    ///
2218    /// The returned spare capacity slice can be used to fill the vector with data
2219    /// (e.g. by reading from a file) before marking the data as initialized using
2220    /// the [`set_len`] method.
2221    ///
2222    /// [`set_len`]: Vec::set_len
2223    ///
2224    /// Note that this is a low-level API, which should be used with care for
2225    /// optimization purposes. If you need to append data to a `Vec`
2226    /// you can use [`push`], [`extend`], [`extend_from_slice`],
2227    /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
2228    /// [`resize_with`], depending on your exact needs.
2229    ///
2230    /// [`push`]: Vec::push
2231    /// [`extend`]: Vec::extend
2232    /// [`extend_from_slice`]: Vec::extend_from_slice
2233    /// [`extend_from_within`]: Vec::extend_from_within
2234    /// [`insert`]: Vec::insert
2235    /// [`append`]: Vec::append
2236    /// [`resize`]: Vec::resize
2237    /// [`resize_with`]: Vec::resize_with
2238    ///
2239    /// # Examples
2240    ///
2241    /// ```
2242    /// #![feature(vec_split_at_spare)]
2243    ///
2244    /// let mut v = vec![1, 1, 2];
2245    ///
2246    /// // Reserve additional space big enough for 10 elements.
2247    /// v.reserve(10);
2248    ///
2249    /// let (init, uninit) = v.split_at_spare_mut();
2250    /// let sum = init.iter().copied().sum::<u32>();
2251    ///
2252    /// // Fill in the next 4 elements.
2253    /// uninit[0].write(sum);
2254    /// uninit[1].write(sum * 2);
2255    /// uninit[2].write(sum * 3);
2256    /// uninit[3].write(sum * 4);
2257    ///
2258    /// // Mark the 4 elements of the vector as being initialized.
2259    /// unsafe {
2260    ///     let len = v.len();
2261    ///     v.set_len(len + 4);
2262    /// }
2263    ///
2264    /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
2265    /// ```
2266    #[inline(always)]
2267    pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
2268        // SAFETY:
2269        // - len is ignored and so never changed
2270        let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
2271        (init, spare)
2272    }
2273
2274    /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
2275    ///
2276    /// This method provides unique access to all vec parts at once in `extend_from_within`.
2277    unsafe fn split_at_spare_mut_with_len(
2278        &mut self,
2279    ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
2280        let ptr = self.as_mut_ptr();
2281        // SAFETY:
2282        // - `ptr` is guaranteed to be valid for `self.len` elements
2283        // - but the allocation extends out to `self.buf.capacity()` elements, possibly
2284        // uninitialized
2285        let spare_ptr = unsafe { ptr.add(self.len) };
2286        let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>();
2287        let spare_len = self.buf.capacity() - self.len;
2288
2289        // SAFETY:
2290        // - `ptr` is guaranteed to be valid for `self.len` elements
2291        // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
2292        unsafe {
2293            let initialized = slice::from_raw_parts_mut(ptr, self.len);
2294            let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
2295
2296            (initialized, spare, &mut self.len)
2297        }
2298    }
2299}
2300
2301impl<T: Clone, A: Allocator> Vec<T, A> {
2302    /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2303    ///
2304    /// If `new_len` is greater than `len`, the `Vec` is extended by the
2305    /// difference, with each additional slot filled with `value`.
2306    /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2307    ///
2308    /// This method requires `T` to implement [`Clone`],
2309    /// in order to be able to clone the passed value.
2310    /// If you need more flexibility (or want to rely on [`Default`] instead of
2311    /// [`Clone`]), use [`Vec::resize_with`].
2312    /// If you only need to resize to a smaller size, use [`Vec::truncate`].
2313    ///
2314    /// # Examples
2315    ///
2316    /// ```
2317    /// let mut vec = vec!["hello"];
2318    /// vec.resize(3, "world");
2319    /// assert_eq!(vec, ["hello", "world", "world"]);
2320    ///
2321    /// let mut vec = vec![1, 2, 3, 4];
2322    /// vec.resize(2, 0);
2323    /// assert_eq!(vec, [1, 2]);
2324    /// ```
2325    #[cfg(not(no_global_oom_handling))]
2326    #[inline(always)]
2327    pub fn resize(&mut self, new_len: usize, value: T) {
2328        let len = self.len();
2329
2330        if new_len > len {
2331            self.extend_with(new_len - len, ExtendElement(value))
2332        } else {
2333            self.truncate(new_len);
2334        }
2335    }
2336
2337    /// Clones and appends all elements in a slice to the `Vec`.
2338    ///
2339    /// Iterates over the slice `other`, clones each element, and then appends
2340    /// it to this `Vec`. The `other` slice is traversed in-order.
2341    ///
2342    /// Note that this function is same as [`extend`] except that it is
2343    /// specialized to work with slices instead. If and when Rust gets
2344    /// specialization this function will likely be deprecated (but still
2345    /// available).
2346    ///
2347    /// # Examples
2348    ///
2349    /// ```
2350    /// let mut vec = vec![1];
2351    /// vec.extend_from_slice(&[2, 3, 4]);
2352    /// assert_eq!(vec, [1, 2, 3, 4]);
2353    /// ```
2354    ///
2355    /// [`extend`]: Vec::extend
2356    #[cfg(not(no_global_oom_handling))]
2357    #[inline(always)]
2358    pub fn extend_from_slice(&mut self, other: &[T]) {
2359        self.extend(other.iter().cloned())
2360    }
2361
2362    /// Copies elements from `src` range to the end of the vector.
2363    ///
2364    /// # Panics
2365    ///
2366    /// Panics if the starting point is greater than the end point or if
2367    /// the end point is greater than the length of the vector.
2368    ///
2369    /// # Examples
2370    ///
2371    /// ```
2372    /// let mut vec = vec![0, 1, 2, 3, 4];
2373    ///
2374    /// vec.extend_from_within(2..);
2375    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
2376    ///
2377    /// vec.extend_from_within(..2);
2378    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
2379    ///
2380    /// vec.extend_from_within(4..8);
2381    /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
2382    /// ```
2383    #[cfg(not(no_global_oom_handling))]
2384    #[inline(always)]
2385    pub fn extend_from_within<R>(&mut self, src: R)
2386    where
2387        R: RangeBounds<usize>,
2388    {
2389        // let range = slice::range(src, ..self.len());
2390
2391        let _ = &self.as_slice()[(src.start_bound().cloned(), src.end_bound().cloned())];
2392
2393        let len = self.len();
2394
2395        let start: ops::Bound<&usize> = src.start_bound();
2396        let start = match start {
2397            ops::Bound::Included(&start) => start,
2398            ops::Bound::Excluded(start) => start + 1,
2399            ops::Bound::Unbounded => 0,
2400        };
2401
2402        let end: ops::Bound<&usize> = src.end_bound();
2403        let end = match end {
2404            ops::Bound::Included(end) => end + 1,
2405            ops::Bound::Excluded(&end) => end,
2406            ops::Bound::Unbounded => len,
2407        };
2408
2409        let range = start..end;
2410
2411        self.reserve(range.len());
2412
2413        // SAFETY:
2414        // - len is increased only after initializing elements
2415        let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
2416
2417        // SAFETY:
2418        // - caller guarantees that src is a valid index
2419        let to_clone = unsafe { this.get_unchecked(range) };
2420
2421        iter::zip(to_clone, spare)
2422            .map(|(src, dst)| dst.write(src.clone()))
2423            // Note:
2424            // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
2425            // - len is increased after each element to prevent leaks (see issue #82533)
2426            .for_each(|_| *len += 1);
2427    }
2428}
2429
2430impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
2431    /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
2432    ///
2433    /// # Panics
2434    ///
2435    /// Panics if the length of the resulting vector would overflow a `usize`.
2436    ///
2437    /// This is only possible when flattening a vector of arrays of zero-sized
2438    /// types, and thus tends to be irrelevant in practice. If
2439    /// `size_of::<T>() > 0`, this will never panic.
2440    ///
2441    /// # Examples
2442    ///
2443    /// ```
2444    /// #![feature(slice_flatten)]
2445    ///
2446    /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
2447    /// assert_eq!(vec.pop(), Some([7, 8, 9]));
2448    ///
2449    /// let mut flattened = vec.into_flattened();
2450    /// assert_eq!(flattened.pop(), Some(6));
2451    /// ```
2452    #[inline(always)]
2453    pub fn into_flattened(self) -> Vec<T, A> {
2454        let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
2455        let (new_len, new_cap) = if size_of::<T>() == 0 {
2456            (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
2457        } else {
2458            // SAFETY:
2459            // - `cap * N` cannot overflow because the allocation is already in
2460            // the address space.
2461            // - Each `[T; N]` has `N` valid elements, so there are `len * N`
2462            // valid elements in the allocation.
2463            (len * N, cap * N)
2464        };
2465        // SAFETY:
2466        // - `ptr` was allocated by `self`
2467        // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
2468        // - `new_cap` refers to the same sized allocation as `cap` because
2469        // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
2470        // - `len` <= `cap`, so `len * N` <= `cap * N`.
2471        unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
2472    }
2473}
2474
2475// This code generalizes `extend_with_{element,default}`.
2476trait ExtendWith<T> {
2477    fn next(&mut self) -> T;
2478    fn last(self) -> T;
2479}
2480
2481struct ExtendElement<T>(T);
2482impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
2483    #[inline(always)]
2484    fn next(&mut self) -> T {
2485        self.0.clone()
2486    }
2487
2488    #[inline(always)]
2489    fn last(self) -> T {
2490        self.0
2491    }
2492}
2493
2494impl<T, A: Allocator> Vec<T, A> {
2495    #[cfg(not(no_global_oom_handling))]
2496    #[inline(always)]
2497    /// Extend the vector by `n` values, using the given generator.
2498    fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
2499        self.reserve(n);
2500
2501        unsafe {
2502            let mut ptr = self.as_mut_ptr().add(self.len());
2503            // Use SetLenOnDrop to work around bug where compiler
2504            // might not realize the store through `ptr` through self.set_len()
2505            // don't alias.
2506            let mut local_len = SetLenOnDrop::new(&mut self.len);
2507
2508            // Write all elements except the last one
2509            for _ in 1..n {
2510                ptr::write(ptr, value.next());
2511                ptr = ptr.add(1);
2512                // Increment the length in every step in case next() panics
2513                local_len.increment_len(1);
2514            }
2515
2516            if n > 0 {
2517                // We can write the last element directly without cloning needlessly
2518                ptr::write(ptr, value.last());
2519                local_len.increment_len(1);
2520            }
2521
2522            // len set by scope guard
2523        }
2524    }
2525}
2526
2527impl<T: PartialEq, A: Allocator> Vec<T, A> {
2528    /// Removes consecutive repeated elements in the vector according to the
2529    /// [`PartialEq`] trait implementation.
2530    ///
2531    /// If the vector is sorted, this removes all duplicates.
2532    ///
2533    /// # Examples
2534    ///
2535    /// ```
2536    /// let mut vec = vec![1, 2, 2, 3, 2];
2537    ///
2538    /// vec.dedup();
2539    ///
2540    /// assert_eq!(vec, [1, 2, 3, 2]);
2541    /// ```
2542    #[inline(always)]
2543    pub fn dedup(&mut self) {
2544        self.dedup_by(|a, b| a == b)
2545    }
2546}
2547
2548////////////////////////////////////////////////////////////////////////////////
2549// Common trait implementations for Vec
2550////////////////////////////////////////////////////////////////////////////////
2551
2552impl<T, A: Allocator> ops::Deref for Vec<T, A> {
2553    type Target = [T];
2554
2555    #[inline(always)]
2556    fn deref(&self) -> &[T] {
2557        unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
2558    }
2559}
2560
2561impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
2562    #[inline(always)]
2563    fn deref_mut(&mut self) -> &mut [T] {
2564        unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
2565    }
2566}
2567
2568#[cfg(not(no_global_oom_handling))]
2569impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
2570    #[inline(always)]
2571    fn clone(&self) -> Self {
2572        let alloc = self.allocator().clone();
2573        let mut vec = Vec::with_capacity_in(self.len(), alloc);
2574        vec.extend_from_slice(self);
2575        vec
2576    }
2577
2578    #[inline(always)]
2579    fn clone_from(&mut self, other: &Self) {
2580        // drop anything that will not be overwritten
2581        self.truncate(other.len());
2582
2583        // self.len <= other.len due to the truncate above, so the
2584        // slices here are always in-bounds.
2585        let (init, tail) = other.split_at(self.len());
2586
2587        // reuse the contained values' allocations/resources.
2588        self.clone_from_slice(init);
2589        self.extend_from_slice(tail);
2590    }
2591}
2592
2593/// The hash of a vector is the same as that of the corresponding slice,
2594/// as required by the `core::borrow::Borrow` implementation.
2595///
2596/// ```
2597/// #![feature(build_hasher_simple_hash_one)]
2598/// use std::hash::BuildHasher;
2599///
2600/// let b = std::collections::hash_map::RandomState::new();
2601/// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
2602/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
2603/// assert_eq!(b.hash_one(v), b.hash_one(s));
2604/// ```
2605impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
2606    #[inline(always)]
2607    fn hash<H: Hasher>(&self, state: &mut H) {
2608        Hash::hash(&**self, state)
2609    }
2610}
2611
2612impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
2613    type Output = I::Output;
2614
2615    #[inline(always)]
2616    fn index(&self, index: I) -> &Self::Output {
2617        Index::index(&**self, index)
2618    }
2619}
2620
2621impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
2622    #[inline(always)]
2623    fn index_mut(&mut self, index: I) -> &mut Self::Output {
2624        IndexMut::index_mut(&mut **self, index)
2625    }
2626}
2627
2628#[cfg(not(no_global_oom_handling))]
2629impl<T> FromIterator<T> for Vec<T> {
2630    #[inline(always)]
2631    fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2632        let mut vec = Vec::new();
2633        vec.extend(iter);
2634        vec
2635    }
2636}
2637
2638impl<T, A: Allocator> IntoIterator for Vec<T, A> {
2639    type Item = T;
2640    type IntoIter = IntoIter<T, A>;
2641
2642    /// Creates a consuming iterator, that is, one that moves each value out of
2643    /// the vector (from start to end). The vector cannot be used after calling
2644    /// this.
2645    ///
2646    /// # Examples
2647    ///
2648    /// ```
2649    /// let v = vec!["a".to_string(), "b".to_string()];
2650    /// let mut v_iter = v.into_iter();
2651    ///
2652    /// let first_element: Option<String> = v_iter.next();
2653    ///
2654    /// assert_eq!(first_element, Some("a".to_string()));
2655    /// assert_eq!(v_iter.next(), Some("b".to_string()));
2656    /// assert_eq!(v_iter.next(), None);
2657    /// ```
2658    #[inline(always)]
2659    fn into_iter(self) -> Self::IntoIter {
2660        unsafe {
2661            let mut me = ManuallyDrop::new(self);
2662            let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
2663            let begin = me.as_mut_ptr();
2664            let end = if size_of::<T>() == 0 {
2665                begin.cast::<u8>().wrapping_add(me.len()).cast()
2666            } else {
2667                begin.add(me.len()) as *const T
2668            };
2669            let cap = me.buf.capacity();
2670            IntoIter {
2671                buf: NonNull::new_unchecked(begin),
2672                phantom: PhantomData,
2673                cap,
2674                alloc,
2675                ptr: begin,
2676                end,
2677            }
2678        }
2679    }
2680}
2681
2682impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
2683    type Item = &'a T;
2684    type IntoIter = slice::Iter<'a, T>;
2685
2686    #[inline(always)]
2687    fn into_iter(self) -> Self::IntoIter {
2688        self.iter()
2689    }
2690}
2691
2692impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
2693    type Item = &'a mut T;
2694    type IntoIter = slice::IterMut<'a, T>;
2695
2696    fn into_iter(self) -> Self::IntoIter {
2697        self.iter_mut()
2698    }
2699}
2700
2701#[cfg(not(no_global_oom_handling))]
2702impl<T, A: Allocator> Extend<T> for Vec<T, A> {
2703    #[inline(always)]
2704    fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2705        // This is the case for a general iter.
2706        //
2707        // This function should be the moral equivalent of:
2708        //
2709        //      for item in iter {
2710        //          self.push(item);
2711        //      }
2712
2713        let mut iter = iter.into_iter();
2714        while let Some(element) = iter.next() {
2715            let len = self.len();
2716            if len == self.capacity() {
2717                let (lower, _) = iter.size_hint();
2718                self.reserve(lower.saturating_add(1));
2719            }
2720            unsafe {
2721                ptr::write(self.as_mut_ptr().add(len), element);
2722                // Since next() executes user code which can panic we have to bump the length
2723                // after each step.
2724                // NB can't overflow since we would have had to alloc the address space
2725                self.set_len(len + 1);
2726            }
2727        }
2728    }
2729}
2730
2731impl<T, A: Allocator> Vec<T, A> {
2732    /// Creates a splicing iterator that replaces the specified range in the vector
2733    /// with the given `replace_with` iterator and yields the removed items.
2734    /// `replace_with` does not need to be the same length as `range`.
2735    ///
2736    /// `range` is removed even if the iterator is not consumed until the end.
2737    ///
2738    /// It is unspecified how many elements are removed from the vector
2739    /// if the `Splice` value is leaked.
2740    ///
2741    /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2742    ///
2743    /// This is optimal if:
2744    ///
2745    /// * The tail (elements in the vector after `range`) is empty,
2746    /// * or `replace_with` yields fewer or equal elements than `range`’s length
2747    /// * or the lower bound of its `size_hint()` is exact.
2748    ///
2749    /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2750    ///
2751    /// # Panics
2752    ///
2753    /// Panics if the starting point is greater than the end point or if
2754    /// the end point is greater than the length of the vector.
2755    ///
2756    /// # Examples
2757    ///
2758    /// ```
2759    /// let mut v = vec![1, 2, 3, 4];
2760    /// let new = [7, 8, 9];
2761    /// let u: Vec<_> = v.splice(1..3, new).collect();
2762    /// assert_eq!(v, &[1, 7, 8, 9, 4]);
2763    /// assert_eq!(u, &[2, 3]);
2764    /// ```
2765    #[cfg(not(no_global_oom_handling))]
2766    #[inline(always)]
2767    pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
2768    where
2769        R: RangeBounds<usize>,
2770        I: IntoIterator<Item = T>,
2771    {
2772        Splice {
2773            drain: self.drain(range),
2774            replace_with: replace_with.into_iter(),
2775        }
2776    }
2777}
2778
2779/// Extend implementation that copies elements out of references before pushing them onto the Vec.
2780///
2781/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2782/// append the entire slice at once.
2783///
2784/// [`copy_from_slice`]: slice::copy_from_slice
2785#[cfg(not(no_global_oom_handling))]
2786impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec<T, A> {
2787    #[inline(always)]
2788    fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2789        let mut iter = iter.into_iter();
2790        while let Some(element) = iter.next() {
2791            let len = self.len();
2792            if len == self.capacity() {
2793                let (lower, _) = iter.size_hint();
2794                self.reserve(lower.saturating_add(1));
2795            }
2796            unsafe {
2797                ptr::write(self.as_mut_ptr().add(len), *element);
2798                // Since next() executes user code which can panic we have to bump the length
2799                // after each step.
2800                // NB can't overflow since we would have had to alloc the address space
2801                self.set_len(len + 1);
2802            }
2803        }
2804    }
2805}
2806
2807/// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2808impl<T: PartialOrd, A: Allocator> PartialOrd for Vec<T, A> {
2809    #[inline(always)]
2810    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2811        PartialOrd::partial_cmp(&**self, &**other)
2812    }
2813}
2814
2815impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
2816
2817/// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2818impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
2819    #[inline(always)]
2820    fn cmp(&self, other: &Self) -> Ordering {
2821        Ord::cmp(&**self, &**other)
2822    }
2823}
2824
2825impl<T, A: Allocator> Drop for Vec<T, A> {
2826    #[inline(always)]
2827    fn drop(&mut self) {
2828        unsafe {
2829            // use drop for [T]
2830            // use a raw slice to refer to the elements of the vector as weakest necessary type;
2831            // could avoid questions of validity in certain cases
2832            ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2833        }
2834        // RawVec handles deallocation
2835    }
2836}
2837
2838impl<T> Default for Vec<T> {
2839    /// Creates an empty `Vec<T>`.
2840    ///
2841    /// The vector will not allocate until elements are pushed onto it.
2842    #[inline(always)]
2843    fn default() -> Vec<T> {
2844        Vec::new()
2845    }
2846}
2847
2848impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
2849    #[inline(always)]
2850    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2851        fmt::Debug::fmt(&**self, f)
2852    }
2853}
2854
2855impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
2856    #[inline(always)]
2857    fn as_ref(&self) -> &Vec<T, A> {
2858        self
2859    }
2860}
2861
2862impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
2863    #[inline(always)]
2864    fn as_mut(&mut self) -> &mut Vec<T, A> {
2865        self
2866    }
2867}
2868
2869impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
2870    #[inline(always)]
2871    fn as_ref(&self) -> &[T] {
2872        self
2873    }
2874}
2875
2876impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
2877    #[inline(always)]
2878    fn as_mut(&mut self) -> &mut [T] {
2879        self
2880    }
2881}
2882
2883#[cfg(not(no_global_oom_handling))]
2884impl<T: Clone> From<&[T]> for Vec<T> {
2885    /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
2886    ///
2887    /// # Examples
2888    ///
2889    /// ```
2890    /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
2891    /// ```
2892    #[inline(always)]
2893    fn from(s: &[T]) -> Vec<T> {
2894        let mut vec = Vec::with_capacity(s.len());
2895        vec.extend_from_slice(s);
2896        vec
2897    }
2898}
2899
2900#[cfg(not(no_global_oom_handling))]
2901impl<T: Clone> From<&mut [T]> for Vec<T> {
2902    /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
2903    ///
2904    /// # Examples
2905    ///
2906    /// ```
2907    /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
2908    /// ```
2909    #[inline(always)]
2910    fn from(s: &mut [T]) -> Vec<T> {
2911        let mut vec = Vec::with_capacity(s.len());
2912        vec.extend_from_slice(s);
2913        vec
2914    }
2915}
2916
2917#[cfg(not(no_global_oom_handling))]
2918impl<T, const N: usize> From<[T; N]> for Vec<T> {
2919    #[inline(always)]
2920    fn from(s: [T; N]) -> Vec<T> {
2921        Box::slice(Box::new(s)).into_vec()
2922    }
2923}
2924
2925impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
2926    /// Convert a boxed slice into a vector by transferring ownership of
2927    /// the existing heap allocation.
2928    ///
2929    /// # Examples
2930    ///
2931    /// ```
2932    /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
2933    /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
2934    /// ```
2935    #[inline(always)]
2936    fn from(s: Box<[T], A>) -> Self {
2937        s.into_vec()
2938    }
2939}
2940
2941impl<T, A: Allocator, const N: usize> From<Box<[T; N], A>> for Vec<T, A> {
2942    /// Convert a boxed array into a vector by transferring ownership of
2943    /// the existing heap allocation.
2944    ///
2945    /// # Examples
2946    ///
2947    /// ```
2948    /// let b: Box<[i32; 3]> = Box::new([1, 2, 3]);
2949    /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
2950    /// ```
2951    #[inline(always)]
2952    fn from(s: Box<[T; N], A>) -> Self {
2953        s.into_vec()
2954    }
2955}
2956
2957// note: test pulls in libstd, which causes errors here
2958#[cfg(not(no_global_oom_handling))]
2959impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
2960    /// Convert a vector into a boxed slice.
2961    ///
2962    /// If `v` has excess capacity, its items will be moved into a
2963    /// newly-allocated buffer with exactly the right capacity.
2964    ///
2965    /// # Examples
2966    ///
2967    /// ```
2968    /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
2969    /// ```
2970    ///
2971    /// Any excess capacity is removed:
2972    /// ```
2973    /// let mut vec = Vec::with_capacity(10);
2974    /// vec.extend([1, 2, 3]);
2975    ///
2976    /// assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice());
2977    /// ```
2978    #[inline(always)]
2979    fn from(v: Vec<T, A>) -> Self {
2980        v.into_boxed_slice()
2981    }
2982}
2983
2984#[cfg(not(no_global_oom_handling))]
2985impl From<&str> for Vec<u8> {
2986    /// Allocate a `Vec<u8>` and fill it with a UTF-8 string.
2987    ///
2988    /// # Examples
2989    ///
2990    /// ```
2991    /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
2992    /// ```
2993    #[inline(always)]
2994    fn from(s: &str) -> Vec<u8> {
2995        From::from(s.as_bytes())
2996    }
2997}
2998
2999impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
3000    type Error = Vec<T, A>;
3001
3002    /// Gets the entire contents of the `Vec<T>` as an array,
3003    /// if its size exactly matches that of the requested array.
3004    ///
3005    /// # Examples
3006    ///
3007    /// ```
3008    /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
3009    /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
3010    /// ```
3011    ///
3012    /// If the length doesn't match, the input comes back in `Err`:
3013    /// ```
3014    /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
3015    /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
3016    /// ```
3017    ///
3018    /// If you're fine with just getting a prefix of the `Vec<T>`,
3019    /// you can call [`.truncate(N)`](Vec::truncate) first.
3020    /// ```
3021    /// let mut v = String::from("hello world").into_bytes();
3022    /// v.sort();
3023    /// v.truncate(2);
3024    /// let [a, b]: [_; 2] = v.try_into().unwrap();
3025    /// assert_eq!(a, b' ');
3026    /// assert_eq!(b, b'd');
3027    /// ```
3028    #[inline(always)]
3029    fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
3030        if vec.len() != N {
3031            return Err(vec);
3032        }
3033
3034        // SAFETY: `.set_len(0)` is always sound.
3035        unsafe { vec.set_len(0) };
3036
3037        // SAFETY: A `Vec`'s pointer is always aligned properly, and
3038        // the alignment the array needs is the same as the items.
3039        // We checked earlier that we have sufficient items.
3040        // The items will not double-drop as the `set_len`
3041        // tells the `Vec` not to also drop them.
3042        let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
3043        Ok(array)
3044    }
3045}
3046
3047#[inline(always)]
3048#[cfg(not(no_global_oom_handling))]
3049#[doc(hidden)]
3050pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
3051    let mut v = Vec::with_capacity_in(n, alloc);
3052    v.extend_with(n, ExtendElement(elem));
3053    v
3054}
3055
3056#[inline(always)]
3057#[cfg(not(no_global_oom_handling))]
3058#[doc(hidden)]
3059pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
3060    let mut v = Vec::with_capacity(n);
3061    v.extend_with(n, ExtendElement(elem));
3062    v
3063}
3064
3065/// Write is implemented for `Vec<u8>` by appending to the vector.
3066/// The vector will grow as needed.
3067#[cfg(feature = "std")]
3068impl<A: Allocator> io::Write for Vec<u8, A> {
3069    #[inline]
3070    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
3071        self.extend_from_slice(buf);
3072        Ok(buf.len())
3073    }
3074
3075    #[inline]
3076    fn write_vectored(&mut self, bufs: &[io::IoSlice<'_>]) -> io::Result<usize> {
3077        let len = bufs.iter().map(|b| b.len()).sum();
3078        self.reserve(len);
3079        for buf in bufs {
3080            self.extend_from_slice(buf);
3081        }
3082        Ok(len)
3083    }
3084
3085    #[inline]
3086    fn write_all(&mut self, buf: &[u8]) -> io::Result<()> {
3087        self.extend_from_slice(buf);
3088        Ok(())
3089    }
3090
3091    #[inline]
3092    fn flush(&mut self) -> io::Result<()> {
3093        Ok(())
3094    }
3095}
3096
3097#[cfg(feature = "serde")]
3098impl<T, A> serde::Serialize for Vec<T, A>
3099where
3100    T: serde::Serialize,
3101    A: Allocator,
3102{
3103    #[inline(always)]
3104    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
3105    where
3106        S: serde::ser::Serializer,
3107    {
3108        serializer.collect_seq(self)
3109    }
3110}
3111
3112#[cfg(feature = "serde")]
3113impl<'de, T, A> serde::de::Deserialize<'de> for Vec<T, A>
3114where
3115    T: serde::de::Deserialize<'de>,
3116    A: Allocator + Default,
3117{
3118    #[inline(always)]
3119    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
3120    where
3121        D: serde::de::Deserializer<'de>,
3122    {
3123        struct VecVisitor<T, A> {
3124            marker: PhantomData<(T, A)>,
3125        }
3126
3127        impl<'de, T, A> serde::de::Visitor<'de> for VecVisitor<T, A>
3128        where
3129            T: serde::de::Deserialize<'de>,
3130            A: Allocator + Default,
3131        {
3132            type Value = Vec<T, A>;
3133
3134            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3135                formatter.write_str("a sequence")
3136            }
3137
3138            fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
3139            where
3140                S: serde::de::SeqAccess<'de>,
3141            {
3142                let mut values = Vec::with_capacity_in(cautious(seq.size_hint()), A::default());
3143
3144                while let Some(value) = seq.next_element()? {
3145                    values.push(value);
3146                }
3147
3148                Ok(values)
3149            }
3150        }
3151
3152        let visitor = VecVisitor {
3153            marker: PhantomData,
3154        };
3155        deserializer.deserialize_seq(visitor)
3156    }
3157
3158    #[inline(always)]
3159    fn deserialize_in_place<D>(deserializer: D, place: &mut Self) -> Result<(), D::Error>
3160    where
3161        D: serde::de::Deserializer<'de>,
3162    {
3163        struct VecInPlaceVisitor<'a, T: 'a, A: Allocator + 'a>(&'a mut Vec<T, A>);
3164
3165        impl<'a, 'de, T, A> serde::de::Visitor<'de> for VecInPlaceVisitor<'a, T, A>
3166        where
3167            T: serde::de::Deserialize<'de>,
3168            A: Allocator + Default,
3169        {
3170            type Value = ();
3171
3172            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3173                formatter.write_str("a sequence")
3174            }
3175
3176            fn visit_seq<S>(self, mut seq: S) -> Result<Self::Value, S::Error>
3177            where
3178                S: serde::de::SeqAccess<'de>,
3179            {
3180                let hint = cautious(seq.size_hint());
3181                if let Some(additional) = hint.checked_sub(self.0.len()) {
3182                    self.0.reserve(additional);
3183                }
3184
3185                for i in 0..self.0.len() {
3186                    let next = {
3187                        let next_place = InPlaceSeed(&mut self.0[i]);
3188                        seq.next_element_seed(next_place)?
3189                    };
3190                    if next.is_none() {
3191                        self.0.truncate(i);
3192                        return Ok(());
3193                    }
3194                }
3195
3196                while let Some(value) = seq.next_element()? {
3197                    self.0.push(value);
3198                }
3199
3200                Ok(())
3201            }
3202        }
3203
3204        deserializer.deserialize_seq(VecInPlaceVisitor(place))
3205    }
3206}
3207
3208#[cfg(feature = "serde")]
3209pub fn cautious(hint: Option<usize>) -> usize {
3210    cmp::min(hint.unwrap_or(0), 4096)
3211}
3212
3213/// A DeserializeSeed helper for implementing deserialize_in_place Visitors.
3214///
3215/// Wraps a mutable reference and calls deserialize_in_place on it.
3216
3217#[cfg(feature = "serde")]
3218pub struct InPlaceSeed<'a, T: 'a>(pub &'a mut T);
3219
3220#[cfg(feature = "serde")]
3221impl<'a, 'de, T> serde::de::DeserializeSeed<'de> for InPlaceSeed<'a, T>
3222where
3223    T: serde::de::Deserialize<'de>,
3224{
3225    type Value = ();
3226    fn deserialize<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
3227    where
3228        D: serde::de::Deserializer<'de>,
3229    {
3230        T::deserialize_in_place(deserializer, self.0)
3231    }
3232}