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