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