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