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