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