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