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