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