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