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