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