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