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