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