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