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