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