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