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