]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/vec.rs
restore SpecFrom<T, TrustedLen<Item=T>> specialization by nesting
[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, InPlaceIterable, SourceIter, 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 `try_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 `try_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_exact(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 SpecFrom<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         if self.capacity() > 0 {
2084             <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2085         } else {
2086             // if self has no allocation then use the more powerful from_iter specializations
2087             let other = SpecFrom::from_iter(iter.into_iter());
2088             // replace self, don't run drop since self was empty
2089             unsafe {
2090                 ptr::write(self, other);
2091             }
2092         }
2093     }
2094
2095     #[inline]
2096     fn extend_one(&mut self, item: T) {
2097         self.push(item);
2098     }
2099
2100     #[inline]
2101     fn extend_reserve(&mut self, additional: usize) {
2102         self.reserve(additional);
2103     }
2104 }
2105
2106 // Specialization trait used for Vec::from_iter
2107 trait SpecFrom<T, I> {
2108     fn from_iter(iter: I) -> Self;
2109 }
2110
2111 // Another specialization trait for Vec::from_iter
2112 // necessary to manually prioritize overlapping specializations
2113 trait SpecFromNested<T, I> {
2114     fn from_iter(iter: I) -> Self;
2115 }
2116
2117 impl<T, I> SpecFromNested<T, I> for Vec<T>
2118 where
2119     I: Iterator<Item = T>,
2120 {
2121     default fn from_iter(mut iterator: I) -> Self {
2122         // Unroll the first iteration, as the vector is going to be
2123         // expanded on this iteration in every case when the iterable is not
2124         // empty, but the loop in extend_desugared() is not going to see the
2125         // vector being full in the few subsequent loop iterations.
2126         // So we get better branch prediction.
2127         let mut vector = match iterator.next() {
2128             None => return Vec::new(),
2129             Some(element) => {
2130                 let (lower, _) = iterator.size_hint();
2131                 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2132                 unsafe {
2133                     ptr::write(vector.as_mut_ptr(), element);
2134                     vector.set_len(1);
2135                 }
2136                 vector
2137             }
2138         };
2139         // must delegate to spec_extend() since extend() itself delegates
2140         // to spec_from for empty Vecs
2141         <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2142         vector
2143     }
2144 }
2145
2146 impl<T, I> SpecFromNested<T, I> for Vec<T>
2147 where
2148     I: TrustedLen<Item = T>,
2149 {
2150     fn from_iter(iterator: I) -> Self {
2151         let mut vector = Vec::new();
2152         // must delegate to spec_extend() since extend() itself delegates
2153         // to spec_from for empty Vecs
2154         vector.spec_extend(iterator);
2155         vector
2156     }
2157 }
2158
2159 impl<T, I> SpecFrom<T, I> for Vec<T>
2160 where
2161     I: Iterator<Item = T>,
2162 {
2163     default fn from_iter(iterator: I) -> Self {
2164         SpecFromNested::from_iter(iterator)
2165     }
2166 }
2167
2168 struct InPlaceDrop<T> {
2169     inner: *mut T,
2170     dst: *mut T,
2171     did_panic: bool,
2172 }
2173
2174 impl<T> InPlaceDrop<T> {
2175     unsafe fn len(&self) -> usize {
2176         self.dst.offset_from(self.inner) as usize
2177     }
2178 }
2179
2180 impl<T> Drop for InPlaceDrop<T> {
2181     #[inline]
2182     fn drop(&mut self) {
2183         unsafe {
2184             if self.did_panic {
2185                 ptr::drop_in_place(slice::from_raw_parts_mut(self.inner, self.len()) as *mut _);
2186             }
2187         }
2188     }
2189 }
2190
2191 fn from_into_iter_source<T, I>(mut iterator: I) -> Vec<T>
2192 where
2193     I: Iterator<Item = T> + InPlaceIterable + SourceIter<Source = IntoIter<T>>,
2194 {
2195     let src_buf = iterator.as_inner().buf.as_ptr();
2196     let src_end = iterator.as_inner().end;
2197     let dst = src_buf;
2198
2199     let dst = if mem::needs_drop::<T>() {
2200         // special-case drop handling since it prevents vectorization
2201         let mut sink = InPlaceDrop { inner: src_buf, dst, did_panic: true };
2202         let _ = iterator.try_for_each::<_, Result<_, !>>(|item| {
2203             unsafe {
2204                 debug_assert!(
2205                     sink.dst as *const _ <= src_end,
2206                     "InPlaceIterable contract violation"
2207                 );
2208                 ptr::write(sink.dst, item);
2209                 sink.dst = sink.dst.add(1);
2210             }
2211             Ok(())
2212         });
2213         sink.did_panic = false;
2214         sink.dst
2215     } else {
2216         // use try-fold since it vectorizes better, does not take ownership and lets us thread the
2217         // write pointer through its innards
2218         iterator
2219             .try_fold::<_, _, Result<_, !>>(dst, move |mut dst, item| {
2220                 unsafe {
2221                     // the InPlaceIterable contract cannot be verified precisely here since
2222                     // try_fold has an exclusive reference to the source pointer
2223                     // all we can do is check if it's still in range
2224                     debug_assert!(dst as *const _ <= src_end, "InPlaceIterable contract violation");
2225                     ptr::write(dst, item);
2226                     dst = dst.add(1);
2227                 }
2228                 Ok(dst)
2229             })
2230             .unwrap()
2231     };
2232
2233     let src = iterator.as_inner();
2234     // check if SourceIter and InPlaceIterable contracts were upheld.
2235     // but if they weren't we may not even make it to this point
2236     debug_assert_eq!(src_buf, src.buf.as_ptr());
2237     debug_assert!(dst as *const _ <= src.ptr, "InPlaceIterable contract violation");
2238
2239     let vec = unsafe {
2240         let len = dst.offset_from(src_buf) as usize;
2241         Vec::from_raw_parts(src.buf.as_ptr(), len, src.cap)
2242     };
2243     // prevent drop of the underlying storage by turning the IntoIter into
2244     // the equivalent of Vec::new().into_iter()
2245     src.cap = 0;
2246     src.buf = unsafe { NonNull::new_unchecked(RawVec::NEW.ptr()) };
2247     src.ptr = src.buf.as_ptr();
2248     src.end = src.buf.as_ptr();
2249
2250     vec
2251 }
2252
2253 impl<T> SpecFrom<T, IntoIter<T>> for Vec<T> {
2254     fn from_iter(iterator: IntoIter<T>) -> Self {
2255         // A common case is passing a vector into a function which immediately
2256         // re-collects into a vector. We can short circuit this if the IntoIter
2257         // has not been advanced at all.
2258         // We can also reuse the memory and move the data to the front if
2259         // allocating a new vector and moving to it would result in the same capacity
2260         let non_zero_offset = iterator.buf.as_ptr() as *const _ != iterator.ptr;
2261         if !non_zero_offset || iterator.len() >= iterator.cap / 2 {
2262             unsafe {
2263                 let it = ManuallyDrop::new(iterator);
2264                 if non_zero_offset {
2265                     ptr::copy(it.ptr, it.buf.as_ptr(), it.len());
2266                 }
2267                 return Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap);
2268             }
2269         }
2270
2271         let mut vec = Vec::new();
2272         // must delegate to spec_extend() since extend() itself delegates
2273         // to spec_from for empty Vecs
2274         vec.spec_extend(iterator);
2275         vec
2276     }
2277 }
2278
2279 // Further specialization potential once lattice specialization exists
2280 // and https://github.com/rust-lang/rust/issues/62645 has been solved:
2281 // This can be broadened to only require size and alignment equality between
2282 // input and output Item types.
2283 impl<T, I> SpecFrom<T, I> for Vec<T>
2284 where
2285     I: Iterator<Item = T> + InPlaceIterable + SourceIter<Source = IntoIter<T>>,
2286 {
2287     default fn from_iter(iterator: I) -> Self {
2288         from_into_iter_source(iterator)
2289     }
2290 }
2291
2292 impl<'a, T: 'a, I> SpecFrom<&'a T, I> for Vec<T>
2293 where
2294     I: Iterator<Item = &'a T>,
2295     T: Clone,
2296 {
2297     default fn from_iter(iterator: I) -> Self {
2298         SpecFrom::from_iter(iterator.cloned())
2299     }
2300 }
2301
2302 // Specialization trait used for Vec::extend
2303 trait SpecExtend<T, I> {
2304     fn spec_extend(&mut self, iter: I);
2305 }
2306
2307 impl<T, I> SpecExtend<T, I> for Vec<T>
2308 where
2309     I: Iterator<Item = T>,
2310 {
2311     default fn spec_extend(&mut self, iter: I) {
2312         self.extend_desugared(iter)
2313     }
2314 }
2315
2316 impl<T, I> SpecExtend<T, I> for Vec<T>
2317 where
2318     I: TrustedLen<Item = T>,
2319 {
2320     default fn spec_extend(&mut self, iterator: I) {
2321         // This is the case for a TrustedLen iterator.
2322         let (low, high) = iterator.size_hint();
2323         if let Some(high_value) = high {
2324             debug_assert_eq!(
2325                 low,
2326                 high_value,
2327                 "TrustedLen iterator's size hint is not exact: {:?}",
2328                 (low, high)
2329             );
2330         }
2331         if let Some(additional) = high {
2332             self.reserve(additional);
2333             unsafe {
2334                 let mut ptr = self.as_mut_ptr().add(self.len());
2335                 let mut local_len = SetLenOnDrop::new(&mut self.len);
2336                 iterator.for_each(move |element| {
2337                     ptr::write(ptr, element);
2338                     ptr = ptr.offset(1);
2339                     // NB can't overflow since we would have had to alloc the address space
2340                     local_len.increment_len(1);
2341                 });
2342             }
2343         } else {
2344             self.extend_desugared(iterator)
2345         }
2346     }
2347 }
2348
2349 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2350     fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2351         unsafe {
2352             self.append_elements(iterator.as_slice() as _);
2353         }
2354         iterator.ptr = iterator.end;
2355     }
2356 }
2357
2358 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2359 where
2360     I: Iterator<Item = &'a T>,
2361     T: Clone,
2362 {
2363     default fn spec_extend(&mut self, iterator: I) {
2364         self.spec_extend(iterator.cloned())
2365     }
2366 }
2367
2368 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2369 where
2370     T: Copy,
2371 {
2372     fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2373         let slice = iterator.as_slice();
2374         self.reserve(slice.len());
2375         unsafe {
2376             let len = self.len();
2377             let dst_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(len), slice.len());
2378             dst_slice.copy_from_slice(slice);
2379             self.set_len(len + slice.len());
2380         }
2381     }
2382 }
2383
2384 impl<T> Vec<T> {
2385     fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2386         // This is the case for a general iterator.
2387         //
2388         // This function should be the moral equivalent of:
2389         //
2390         //      for item in iterator {
2391         //          self.push(item);
2392         //      }
2393         while let Some(element) = iterator.next() {
2394             let len = self.len();
2395             if len == self.capacity() {
2396                 let (lower, _) = iterator.size_hint();
2397                 self.reserve(lower.saturating_add(1));
2398             }
2399             unsafe {
2400                 ptr::write(self.as_mut_ptr().add(len), element);
2401                 // NB can't overflow since we would have had to alloc the address space
2402                 self.set_len(len + 1);
2403             }
2404         }
2405     }
2406
2407     /// Creates a splicing iterator that replaces the specified range in the vector
2408     /// with the given `replace_with` iterator and yields the removed items.
2409     /// `replace_with` does not need to be the same length as `range`.
2410     ///
2411     /// `range` is removed even if the iterator is not consumed until the end.
2412     ///
2413     /// It is unspecified how many elements are removed from the vector
2414     /// if the `Splice` value is leaked.
2415     ///
2416     /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2417     ///
2418     /// This is optimal if:
2419     ///
2420     /// * The tail (elements in the vector after `range`) is empty,
2421     /// * or `replace_with` yields fewer elements than `range`’s length
2422     /// * or the lower bound of its `size_hint()` is exact.
2423     ///
2424     /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2425     ///
2426     /// # Panics
2427     ///
2428     /// Panics if the starting point is greater than the end point or if
2429     /// the end point is greater than the length of the vector.
2430     ///
2431     /// # Examples
2432     ///
2433     /// ```
2434     /// let mut v = vec![1, 2, 3];
2435     /// let new = [7, 8];
2436     /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2437     /// assert_eq!(v, &[7, 8, 3]);
2438     /// assert_eq!(u, &[1, 2]);
2439     /// ```
2440     #[inline]
2441     #[stable(feature = "vec_splice", since = "1.21.0")]
2442     pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2443     where
2444         R: RangeBounds<usize>,
2445         I: IntoIterator<Item = T>,
2446     {
2447         Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2448     }
2449
2450     /// Creates an iterator which uses a closure to determine if an element should be removed.
2451     ///
2452     /// If the closure returns true, then the element is removed and yielded.
2453     /// If the closure returns false, the element will remain in the vector and will not be yielded
2454     /// by the iterator.
2455     ///
2456     /// Using this method is equivalent to the following code:
2457     ///
2458     /// ```
2459     /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2460     /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2461     /// let mut i = 0;
2462     /// while i != vec.len() {
2463     ///     if some_predicate(&mut vec[i]) {
2464     ///         let val = vec.remove(i);
2465     ///         // your code here
2466     ///     } else {
2467     ///         i += 1;
2468     ///     }
2469     /// }
2470     ///
2471     /// # assert_eq!(vec, vec![1, 4, 5]);
2472     /// ```
2473     ///
2474     /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2475     /// because it can backshift the elements of the array in bulk.
2476     ///
2477     /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2478     /// regardless of whether you choose to keep or remove it.
2479     ///
2480     /// # Examples
2481     ///
2482     /// Splitting an array into evens and odds, reusing the original allocation:
2483     ///
2484     /// ```
2485     /// #![feature(drain_filter)]
2486     /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2487     ///
2488     /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2489     /// let odds = numbers;
2490     ///
2491     /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2492     /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2493     /// ```
2494     #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2495     pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2496     where
2497         F: FnMut(&mut T) -> bool,
2498     {
2499         let old_len = self.len();
2500
2501         // Guard against us getting leaked (leak amplification)
2502         unsafe {
2503             self.set_len(0);
2504         }
2505
2506         DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2507     }
2508 }
2509
2510 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2511 ///
2512 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2513 /// append the entire slice at once.
2514 ///
2515 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2516 #[stable(feature = "extend_ref", since = "1.2.0")]
2517 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2518     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2519         if self.capacity() > 0 {
2520             self.spec_extend(iter.into_iter())
2521         } else {
2522             // if self has no allocation then use the more powerful from_iter specializations
2523             let other = SpecFrom::from_iter(iter.into_iter());
2524             // replace self, don't run drop since self was empty
2525             unsafe {
2526                 ptr::write(self, other);
2527             }
2528         }
2529     }
2530
2531     #[inline]
2532     fn extend_one(&mut self, &item: &'a T) {
2533         self.push(item);
2534     }
2535
2536     #[inline]
2537     fn extend_reserve(&mut self, additional: usize) {
2538         self.reserve(additional);
2539     }
2540 }
2541
2542 macro_rules! __impl_slice_eq1 {
2543     ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => {
2544         #[$stability]
2545         impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2546         where
2547             A: PartialEq<B>,
2548             $($ty: $bound)?
2549         {
2550             #[inline]
2551             fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2552             #[inline]
2553             fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2554         }
2555     }
2556 }
2557
2558 __impl_slice_eq1! { [] Vec<A>, Vec<B>, #[stable(feature = "rust1", since = "1.0.0")] }
2559 __impl_slice_eq1! { [] Vec<A>, &[B], #[stable(feature = "rust1", since = "1.0.0")] }
2560 __impl_slice_eq1! { [] Vec<A>, &mut [B], #[stable(feature = "rust1", since = "1.0.0")] }
2561 __impl_slice_eq1! { [] &[A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2562 __impl_slice_eq1! { [] &mut [A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2563 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B> where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2564 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2565 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2566 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2567 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2568
2569 // NOTE: some less important impls are omitted to reduce code bloat
2570 // FIXME(Centril): Reconsider this?
2571 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], }
2572 //__impl_slice_eq1! { [const N: usize] [A; N], Vec<B>, }
2573 //__impl_slice_eq1! { [const N: usize] &[A; N], Vec<B>, }
2574 //__impl_slice_eq1! { [const N: usize] &mut [A; N], Vec<B>, }
2575 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], }
2576 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], }
2577 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], }
2578
2579 /// Implements comparison of vectors, lexicographically.
2580 #[stable(feature = "rust1", since = "1.0.0")]
2581 impl<T: PartialOrd> PartialOrd for Vec<T> {
2582     #[inline]
2583     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2584         PartialOrd::partial_cmp(&**self, &**other)
2585     }
2586 }
2587
2588 #[stable(feature = "rust1", since = "1.0.0")]
2589 impl<T: Eq> Eq for Vec<T> {}
2590
2591 /// Implements ordering of vectors, lexicographically.
2592 #[stable(feature = "rust1", since = "1.0.0")]
2593 impl<T: Ord> Ord for Vec<T> {
2594     #[inline]
2595     fn cmp(&self, other: &Vec<T>) -> Ordering {
2596         Ord::cmp(&**self, &**other)
2597     }
2598 }
2599
2600 #[stable(feature = "rust1", since = "1.0.0")]
2601 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2602     fn drop(&mut self) {
2603         unsafe {
2604             // use drop for [T]
2605             // use a raw slice to refer to the elements of the vector as weakest necessary type;
2606             // could avoid questions of validity in certain cases
2607             ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2608         }
2609         // RawVec handles deallocation
2610     }
2611 }
2612
2613 #[stable(feature = "rust1", since = "1.0.0")]
2614 impl<T> Default for Vec<T> {
2615     /// Creates an empty `Vec<T>`.
2616     fn default() -> Vec<T> {
2617         Vec::new()
2618     }
2619 }
2620
2621 #[stable(feature = "rust1", since = "1.0.0")]
2622 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2623     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2624         fmt::Debug::fmt(&**self, f)
2625     }
2626 }
2627
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 impl<T> AsRef<Vec<T>> for Vec<T> {
2630     fn as_ref(&self) -> &Vec<T> {
2631         self
2632     }
2633 }
2634
2635 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2636 impl<T> AsMut<Vec<T>> for Vec<T> {
2637     fn as_mut(&mut self) -> &mut Vec<T> {
2638         self
2639     }
2640 }
2641
2642 #[stable(feature = "rust1", since = "1.0.0")]
2643 impl<T> AsRef<[T]> for Vec<T> {
2644     fn as_ref(&self) -> &[T] {
2645         self
2646     }
2647 }
2648
2649 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2650 impl<T> AsMut<[T]> for Vec<T> {
2651     fn as_mut(&mut self) -> &mut [T] {
2652         self
2653     }
2654 }
2655
2656 #[stable(feature = "rust1", since = "1.0.0")]
2657 impl<T: Clone> From<&[T]> for Vec<T> {
2658     #[cfg(not(test))]
2659     fn from(s: &[T]) -> Vec<T> {
2660         s.to_vec()
2661     }
2662     #[cfg(test)]
2663     fn from(s: &[T]) -> Vec<T> {
2664         crate::slice::to_vec(s)
2665     }
2666 }
2667
2668 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2669 impl<T: Clone> From<&mut [T]> for Vec<T> {
2670     #[cfg(not(test))]
2671     fn from(s: &mut [T]) -> Vec<T> {
2672         s.to_vec()
2673     }
2674     #[cfg(test)]
2675     fn from(s: &mut [T]) -> Vec<T> {
2676         crate::slice::to_vec(s)
2677     }
2678 }
2679
2680 #[stable(feature = "vec_from_array", since = "1.44.0")]
2681 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2682     #[cfg(not(test))]
2683     fn from(s: [T; N]) -> Vec<T> {
2684         <[T]>::into_vec(box s)
2685     }
2686     #[cfg(test)]
2687     fn from(s: [T; N]) -> Vec<T> {
2688         crate::slice::into_vec(box s)
2689     }
2690 }
2691
2692 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2693 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2694 where
2695     [T]: ToOwned<Owned = Vec<T>>,
2696 {
2697     fn from(s: Cow<'a, [T]>) -> Vec<T> {
2698         s.into_owned()
2699     }
2700 }
2701
2702 // note: test pulls in libstd, which causes errors here
2703 #[cfg(not(test))]
2704 #[stable(feature = "vec_from_box", since = "1.18.0")]
2705 impl<T> From<Box<[T]>> for Vec<T> {
2706     fn from(s: Box<[T]>) -> Vec<T> {
2707         s.into_vec()
2708     }
2709 }
2710
2711 // note: test pulls in libstd, which causes errors here
2712 #[cfg(not(test))]
2713 #[stable(feature = "box_from_vec", since = "1.20.0")]
2714 impl<T> From<Vec<T>> for Box<[T]> {
2715     fn from(v: Vec<T>) -> Box<[T]> {
2716         v.into_boxed_slice()
2717     }
2718 }
2719
2720 #[stable(feature = "rust1", since = "1.0.0")]
2721 impl From<&str> for Vec<u8> {
2722     fn from(s: &str) -> Vec<u8> {
2723         From::from(s.as_bytes())
2724     }
2725 }
2726
2727 ////////////////////////////////////////////////////////////////////////////////
2728 // Clone-on-write
2729 ////////////////////////////////////////////////////////////////////////////////
2730
2731 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2732 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2733     fn from(s: &'a [T]) -> Cow<'a, [T]> {
2734         Cow::Borrowed(s)
2735     }
2736 }
2737
2738 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2739 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2740     fn from(v: Vec<T>) -> Cow<'a, [T]> {
2741         Cow::Owned(v)
2742     }
2743 }
2744
2745 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2746 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2747     fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2748         Cow::Borrowed(v.as_slice())
2749     }
2750 }
2751
2752 #[stable(feature = "rust1", since = "1.0.0")]
2753 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
2754 where
2755     T: Clone,
2756 {
2757     fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2758         Cow::Owned(FromIterator::from_iter(it))
2759     }
2760 }
2761
2762 ////////////////////////////////////////////////////////////////////////////////
2763 // Iterators
2764 ////////////////////////////////////////////////////////////////////////////////
2765
2766 /// An iterator that moves out of a vector.
2767 ///
2768 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
2769 /// by the [`IntoIterator`] trait).
2770 #[stable(feature = "rust1", since = "1.0.0")]
2771 pub struct IntoIter<T> {
2772     buf: NonNull<T>,
2773     phantom: PhantomData<T>,
2774     cap: usize,
2775     ptr: *const T,
2776     end: *const T,
2777 }
2778
2779 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2780 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2781     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2782         f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2783     }
2784 }
2785
2786 impl<T> IntoIter<T> {
2787     /// Returns the remaining items of this iterator as a slice.
2788     ///
2789     /// # Examples
2790     ///
2791     /// ```
2792     /// let vec = vec!['a', 'b', 'c'];
2793     /// let mut into_iter = vec.into_iter();
2794     /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2795     /// let _ = into_iter.next().unwrap();
2796     /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2797     /// ```
2798     #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2799     pub fn as_slice(&self) -> &[T] {
2800         unsafe { slice::from_raw_parts(self.ptr, self.len()) }
2801     }
2802
2803     /// Returns the remaining items of this iterator as a mutable slice.
2804     ///
2805     /// # Examples
2806     ///
2807     /// ```
2808     /// let vec = vec!['a', 'b', 'c'];
2809     /// let mut into_iter = vec.into_iter();
2810     /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2811     /// into_iter.as_mut_slice()[2] = 'z';
2812     /// assert_eq!(into_iter.next().unwrap(), 'a');
2813     /// assert_eq!(into_iter.next().unwrap(), 'b');
2814     /// assert_eq!(into_iter.next().unwrap(), 'z');
2815     /// ```
2816     #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2817     pub fn as_mut_slice(&mut self) -> &mut [T] {
2818         unsafe { &mut *self.as_raw_mut_slice() }
2819     }
2820
2821     fn as_raw_mut_slice(&mut self) -> *mut [T] {
2822         ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
2823     }
2824 }
2825
2826 #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
2827 impl<T> AsRef<[T]> for IntoIter<T> {
2828     fn as_ref(&self) -> &[T] {
2829         self.as_slice()
2830     }
2831 }
2832
2833 #[stable(feature = "rust1", since = "1.0.0")]
2834 unsafe impl<T: Send> Send for IntoIter<T> {}
2835 #[stable(feature = "rust1", since = "1.0.0")]
2836 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2837
2838 #[stable(feature = "rust1", since = "1.0.0")]
2839 impl<T> Iterator for IntoIter<T> {
2840     type Item = T;
2841
2842     #[inline]
2843     fn next(&mut self) -> Option<T> {
2844         unsafe {
2845             if self.ptr as *const _ == self.end {
2846                 None
2847             } else {
2848                 if mem::size_of::<T>() == 0 {
2849                     // purposefully don't use 'ptr.offset' because for
2850                     // vectors with 0-size elements this would return the
2851                     // same pointer.
2852                     self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2853
2854                     // Make up a value of this ZST.
2855                     Some(mem::zeroed())
2856                 } else {
2857                     let old = self.ptr;
2858                     self.ptr = self.ptr.offset(1);
2859
2860                     Some(ptr::read(old))
2861                 }
2862             }
2863         }
2864     }
2865
2866     #[inline]
2867     fn size_hint(&self) -> (usize, Option<usize>) {
2868         let exact = if mem::size_of::<T>() == 0 {
2869             (self.end as usize).wrapping_sub(self.ptr as usize)
2870         } else {
2871             unsafe { self.end.offset_from(self.ptr) as usize }
2872         };
2873         (exact, Some(exact))
2874     }
2875
2876     #[inline]
2877     fn count(self) -> usize {
2878         self.len()
2879     }
2880 }
2881
2882 #[stable(feature = "rust1", since = "1.0.0")]
2883 impl<T> DoubleEndedIterator for IntoIter<T> {
2884     #[inline]
2885     fn next_back(&mut self) -> Option<T> {
2886         unsafe {
2887             if self.end == self.ptr {
2888                 None
2889             } else {
2890                 if mem::size_of::<T>() == 0 {
2891                     // See above for why 'ptr.offset' isn't used
2892                     self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2893
2894                     // Make up a value of this ZST.
2895                     Some(mem::zeroed())
2896                 } else {
2897                     self.end = self.end.offset(-1);
2898
2899                     Some(ptr::read(self.end))
2900                 }
2901             }
2902         }
2903     }
2904 }
2905
2906 #[stable(feature = "rust1", since = "1.0.0")]
2907 impl<T> ExactSizeIterator for IntoIter<T> {
2908     fn is_empty(&self) -> bool {
2909         self.ptr == self.end
2910     }
2911 }
2912
2913 #[stable(feature = "fused", since = "1.26.0")]
2914 impl<T> FusedIterator for IntoIter<T> {}
2915
2916 #[unstable(feature = "trusted_len", issue = "37572")]
2917 unsafe impl<T> TrustedLen for IntoIter<T> {}
2918
2919 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2920 impl<T: Clone> Clone for IntoIter<T> {
2921     fn clone(&self) -> IntoIter<T> {
2922         self.as_slice().to_owned().into_iter()
2923     }
2924 }
2925
2926 #[stable(feature = "rust1", since = "1.0.0")]
2927 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2928     fn drop(&mut self) {
2929         struct DropGuard<'a, T>(&'a mut IntoIter<T>);
2930
2931         impl<T> Drop for DropGuard<'_, T> {
2932             fn drop(&mut self) {
2933                 // RawVec handles deallocation
2934                 let _ = unsafe { RawVec::from_raw_parts(self.0.buf.as_ptr(), self.0.cap) };
2935             }
2936         }
2937
2938         let guard = DropGuard(self);
2939         // destroy the remaining elements
2940         unsafe {
2941             ptr::drop_in_place(guard.0.as_raw_mut_slice());
2942         }
2943         // now `guard` will be dropped and do the rest
2944     }
2945 }
2946
2947 #[unstable(issue = "0", feature = "inplace_iteration")]
2948 unsafe impl<T> InPlaceIterable for IntoIter<T> {}
2949
2950 #[unstable(issue = "0", feature = "inplace_iteration")]
2951 unsafe impl<T> SourceIter for IntoIter<T> {
2952     type Source = IntoIter<T>;
2953
2954     #[inline]
2955     fn as_inner(&mut self) -> &mut Self::Source {
2956         self
2957     }
2958 }
2959
2960 /// A draining iterator for `Vec<T>`.
2961 ///
2962 /// This `struct` is created by [`Vec::drain`].
2963 #[stable(feature = "drain", since = "1.6.0")]
2964 pub struct Drain<'a, T: 'a> {
2965     /// Index of tail to preserve
2966     tail_start: usize,
2967     /// Length of tail
2968     tail_len: usize,
2969     /// Current remaining range to remove
2970     iter: slice::Iter<'a, T>,
2971     vec: NonNull<Vec<T>>,
2972 }
2973
2974 #[stable(feature = "collection_debug", since = "1.17.0")]
2975 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2976     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2977         f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
2978     }
2979 }
2980
2981 impl<'a, T> Drain<'a, T> {
2982     /// Returns the remaining items of this iterator as a slice.
2983     ///
2984     /// # Examples
2985     ///
2986     /// ```
2987     /// let mut vec = vec!['a', 'b', 'c'];
2988     /// let mut drain = vec.drain(..);
2989     /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
2990     /// let _ = drain.next().unwrap();
2991     /// assert_eq!(drain.as_slice(), &['b', 'c']);
2992     /// ```
2993     #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
2994     pub fn as_slice(&self) -> &[T] {
2995         self.iter.as_slice()
2996     }
2997 }
2998
2999 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3000 impl<'a, T> AsRef<[T]> for Drain<'a, T> {
3001     fn as_ref(&self) -> &[T] {
3002         self.as_slice()
3003     }
3004 }
3005
3006 #[stable(feature = "drain", since = "1.6.0")]
3007 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
3008 #[stable(feature = "drain", since = "1.6.0")]
3009 unsafe impl<T: Send> Send for Drain<'_, T> {}
3010
3011 #[stable(feature = "drain", since = "1.6.0")]
3012 impl<T> Iterator for Drain<'_, T> {
3013     type Item = T;
3014
3015     #[inline]
3016     fn next(&mut self) -> Option<T> {
3017         self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
3018     }
3019
3020     fn size_hint(&self) -> (usize, Option<usize>) {
3021         self.iter.size_hint()
3022     }
3023 }
3024
3025 #[stable(feature = "drain", since = "1.6.0")]
3026 impl<T> DoubleEndedIterator for Drain<'_, T> {
3027     #[inline]
3028     fn next_back(&mut self) -> Option<T> {
3029         self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
3030     }
3031 }
3032
3033 #[stable(feature = "drain", since = "1.6.0")]
3034 impl<T> Drop for Drain<'_, T> {
3035     fn drop(&mut self) {
3036         /// Continues dropping the remaining elements in the `Drain`, then moves back the
3037         /// un-`Drain`ed elements to restore the original `Vec`.
3038         struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>);
3039
3040         impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> {
3041             fn drop(&mut self) {
3042                 // Continue the same loop we have below. If the loop already finished, this does
3043                 // nothing.
3044                 self.0.for_each(drop);
3045
3046                 if self.0.tail_len > 0 {
3047                     unsafe {
3048                         let source_vec = self.0.vec.as_mut();
3049                         // memmove back untouched tail, update to new length
3050                         let start = source_vec.len();
3051                         let tail = self.0.tail_start;
3052                         if tail != start {
3053                             let src = source_vec.as_ptr().add(tail);
3054                             let dst = source_vec.as_mut_ptr().add(start);
3055                             ptr::copy(src, dst, self.0.tail_len);
3056                         }
3057                         source_vec.set_len(start + self.0.tail_len);
3058                     }
3059                 }
3060             }
3061         }
3062
3063         // exhaust self first
3064         while let Some(item) = self.next() {
3065             let guard = DropGuard(self);
3066             drop(item);
3067             mem::forget(guard);
3068         }
3069
3070         // Drop a `DropGuard` to move back the non-drained tail of `self`.
3071         DropGuard(self);
3072     }
3073 }
3074
3075 #[stable(feature = "drain", since = "1.6.0")]
3076 impl<T> ExactSizeIterator for Drain<'_, T> {
3077     fn is_empty(&self) -> bool {
3078         self.iter.is_empty()
3079     }
3080 }
3081
3082 #[unstable(feature = "trusted_len", issue = "37572")]
3083 unsafe impl<T> TrustedLen for Drain<'_, T> {}
3084
3085 #[stable(feature = "fused", since = "1.26.0")]
3086 impl<T> FusedIterator for Drain<'_, T> {}
3087
3088 /// A splicing iterator for `Vec`.
3089 ///
3090 /// This struct is created by [`Vec::splice()`].
3091 /// See its documentation for more.
3092 #[derive(Debug)]
3093 #[stable(feature = "vec_splice", since = "1.21.0")]
3094 pub struct Splice<'a, I: Iterator + 'a> {
3095     drain: Drain<'a, I::Item>,
3096     replace_with: I,
3097 }
3098
3099 #[stable(feature = "vec_splice", since = "1.21.0")]
3100 impl<I: Iterator> Iterator for Splice<'_, I> {
3101     type Item = I::Item;
3102
3103     fn next(&mut self) -> Option<Self::Item> {
3104         self.drain.next()
3105     }
3106
3107     fn size_hint(&self) -> (usize, Option<usize>) {
3108         self.drain.size_hint()
3109     }
3110 }
3111
3112 #[stable(feature = "vec_splice", since = "1.21.0")]
3113 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
3114     fn next_back(&mut self) -> Option<Self::Item> {
3115         self.drain.next_back()
3116     }
3117 }
3118
3119 #[stable(feature = "vec_splice", since = "1.21.0")]
3120 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
3121
3122 #[stable(feature = "vec_splice", since = "1.21.0")]
3123 impl<I: Iterator> Drop for Splice<'_, I> {
3124     fn drop(&mut self) {
3125         self.drain.by_ref().for_each(drop);
3126
3127         unsafe {
3128             if self.drain.tail_len == 0 {
3129                 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
3130                 return;
3131             }
3132
3133             // First fill the range left by drain().
3134             if !self.drain.fill(&mut self.replace_with) {
3135                 return;
3136             }
3137
3138             // There may be more elements. Use the lower bound as an estimate.
3139             // FIXME: Is the upper bound a better guess? Or something else?
3140             let (lower_bound, _upper_bound) = self.replace_with.size_hint();
3141             if lower_bound > 0 {
3142                 self.drain.move_tail(lower_bound);
3143                 if !self.drain.fill(&mut self.replace_with) {
3144                     return;
3145                 }
3146             }
3147
3148             // Collect any remaining elements.
3149             // This is a zero-length vector which does not allocate if `lower_bound` was exact.
3150             let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
3151             // Now we have an exact count.
3152             if collected.len() > 0 {
3153                 self.drain.move_tail(collected.len());
3154                 let filled = self.drain.fill(&mut collected);
3155                 debug_assert!(filled);
3156                 debug_assert_eq!(collected.len(), 0);
3157             }
3158         }
3159         // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
3160     }
3161 }
3162
3163 /// Private helper methods for `Splice::drop`
3164 impl<T> Drain<'_, T> {
3165     /// The range from `self.vec.len` to `self.tail_start` contains elements
3166     /// that have been moved out.
3167     /// Fill that range as much as possible with new elements from the `replace_with` iterator.
3168     /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
3169     unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
3170         let vec = unsafe { self.vec.as_mut() };
3171         let range_start = vec.len;
3172         let range_end = self.tail_start;
3173         let range_slice = unsafe {
3174             slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
3175         };
3176
3177         for place in range_slice {
3178             if let Some(new_item) = replace_with.next() {
3179                 unsafe { ptr::write(place, new_item) };
3180                 vec.len += 1;
3181             } else {
3182                 return false;
3183             }
3184         }
3185         true
3186     }
3187
3188     /// Makes room for inserting more elements before the tail.
3189     unsafe fn move_tail(&mut self, additional: usize) {
3190         let vec = unsafe { self.vec.as_mut() };
3191         let len = self.tail_start + self.tail_len;
3192         vec.buf.reserve(len, additional);
3193
3194         let new_tail_start = self.tail_start + additional;
3195         unsafe {
3196             let src = vec.as_ptr().add(self.tail_start);
3197             let dst = vec.as_mut_ptr().add(new_tail_start);
3198             ptr::copy(src, dst, self.tail_len);
3199         }
3200         self.tail_start = new_tail_start;
3201     }
3202 }
3203
3204 /// An iterator which uses a closure to determine if an element should be removed.
3205 ///
3206 /// This struct is created by [`Vec::drain_filter`].
3207 /// See its documentation for more.
3208 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3209 #[derive(Debug)]
3210 pub struct DrainFilter<'a, T, F>
3211 where
3212     F: FnMut(&mut T) -> bool,
3213 {
3214     vec: &'a mut Vec<T>,
3215     /// The index of the item that will be inspected by the next call to `next`.
3216     idx: usize,
3217     /// The number of items that have been drained (removed) thus far.
3218     del: usize,
3219     /// The original length of `vec` prior to draining.
3220     old_len: usize,
3221     /// The filter test predicate.
3222     pred: F,
3223     /// A flag that indicates a panic has occurred in the filter test predicate.
3224     /// This is used as a hint in the drop implementation to prevent consumption
3225     /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3226     /// backshifted in the `vec`, but no further items will be dropped or
3227     /// tested by the filter predicate.
3228     panic_flag: bool,
3229 }
3230
3231 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3232 impl<T, F> Iterator for DrainFilter<'_, T, F>
3233 where
3234     F: FnMut(&mut T) -> bool,
3235 {
3236     type Item = T;
3237
3238     fn next(&mut self) -> Option<T> {
3239         unsafe {
3240             while self.idx < self.old_len {
3241                 let i = self.idx;
3242                 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3243                 self.panic_flag = true;
3244                 let drained = (self.pred)(&mut v[i]);
3245                 self.panic_flag = false;
3246                 // Update the index *after* the predicate is called. If the index
3247                 // is updated prior and the predicate panics, the element at this
3248                 // index would be leaked.
3249                 self.idx += 1;
3250                 if drained {
3251                     self.del += 1;
3252                     return Some(ptr::read(&v[i]));
3253                 } else if self.del > 0 {
3254                     let del = self.del;
3255                     let src: *const T = &v[i];
3256                     let dst: *mut T = &mut v[i - del];
3257                     ptr::copy_nonoverlapping(src, dst, 1);
3258                 }
3259             }
3260             None
3261         }
3262     }
3263
3264     fn size_hint(&self) -> (usize, Option<usize>) {
3265         (0, Some(self.old_len - self.idx))
3266     }
3267 }
3268
3269 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3270 impl<T, F> Drop for DrainFilter<'_, T, F>
3271 where
3272     F: FnMut(&mut T) -> bool,
3273 {
3274     fn drop(&mut self) {
3275         struct BackshiftOnDrop<'a, 'b, T, F>
3276         where
3277             F: FnMut(&mut T) -> bool,
3278         {
3279             drain: &'b mut DrainFilter<'a, T, F>,
3280         }
3281
3282         impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
3283         where
3284             F: FnMut(&mut T) -> bool,
3285         {
3286             fn drop(&mut self) {
3287                 unsafe {
3288                     if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3289                         // This is a pretty messed up state, and there isn't really an
3290                         // obviously right thing to do. We don't want to keep trying
3291                         // to execute `pred`, so we just backshift all the unprocessed
3292                         // elements and tell the vec that they still exist. The backshift
3293                         // is required to prevent a double-drop of the last successfully
3294                         // drained item prior to a panic in the predicate.
3295                         let ptr = self.drain.vec.as_mut_ptr();
3296                         let src = ptr.add(self.drain.idx);
3297                         let dst = src.sub(self.drain.del);
3298                         let tail_len = self.drain.old_len - self.drain.idx;
3299                         src.copy_to(dst, tail_len);
3300                     }
3301                     self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3302                 }
3303             }
3304         }
3305
3306         let backshift = BackshiftOnDrop { drain: self };
3307
3308         // Attempt to consume any remaining elements if the filter predicate
3309         // has not yet panicked. We'll backshift any remaining elements
3310         // whether we've already panicked or if the consumption here panics.
3311         if !backshift.drain.panic_flag {
3312             backshift.drain.for_each(drop);
3313         }
3314     }
3315 }