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