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