]> git.lizzy.rs Git - rust.git/blob - src/liballoc/vec.rs
Overhaul of the `AllocRef` trait to match allocator-wg's latest consens
[rust.git] / src / liballoc / vec.rs
1 //! A contiguous growable array type with heap-allocated contents, written
2 //! `Vec<T>`.
3 //!
4 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
5 //! `O(1)` pop (from the end).
6 //!
7 //! Vectors ensure they never allocate more than `isize::MAX` bytes.
8 //!
9 //! # Examples
10 //!
11 //! You can explicitly create a [`Vec<T>`] with [`new`]:
12 //!
13 //! ```
14 //! let v: Vec<i32> = Vec::new();
15 //! ```
16 //!
17 //! ...or by using the [`vec!`] macro:
18 //!
19 //! ```
20 //! let v: Vec<i32> = vec![];
21 //!
22 //! let v = vec![1, 2, 3, 4, 5];
23 //!
24 //! let v = vec![0; 10]; // ten zeroes
25 //! ```
26 //!
27 //! You can [`push`] values onto the end of a vector (which will grow the vector
28 //! as needed):
29 //!
30 //! ```
31 //! let mut v = vec![1, 2];
32 //!
33 //! v.push(3);
34 //! ```
35 //!
36 //! Popping values works in much the same way:
37 //!
38 //! ```
39 //! let mut v = vec![1, 2];
40 //!
41 //! let two = v.pop();
42 //! ```
43 //!
44 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
45 //!
46 //! ```
47 //! let mut v = vec![1, 2, 3];
48 //! let three = v[2];
49 //! v[1] = v[1] + 5;
50 //! ```
51 //!
52 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
53 //! [`new`]: ../../std/vec/struct.Vec.html#method.new
54 //! [`push`]: ../../std/vec/struct.Vec.html#method.push
55 //! [`Index`]: ../../std/ops/trait.Index.html
56 //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
57 //! [`vec!`]: ../../std/macro.vec.html
58
59 #![stable(feature = "rust1", since = "1.0.0")]
60
61 use core::array::LengthAtMost32;
62 use core::cmp::{self, Ordering};
63 use core::fmt;
64 use core::hash::{self, Hash};
65 use core::intrinsics::{arith_offset, assume};
66 use core::iter::{FromIterator, FusedIterator, TrustedLen};
67 use core::marker::PhantomData;
68 use core::mem;
69 use core::ops::Bound::{Excluded, Included, Unbounded};
70 use core::ops::{self, Index, IndexMut, RangeBounds};
71 use core::ptr::{self, NonNull};
72 use core::slice::{self, SliceIndex};
73
74 use crate::borrow::{Cow, ToOwned};
75 use crate::boxed::Box;
76 use crate::collections::TryReserveError;
77 use crate::raw_vec::RawVec;
78
79 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
80 ///
81 /// # Examples
82 ///
83 /// ```
84 /// let mut vec = Vec::new();
85 /// vec.push(1);
86 /// vec.push(2);
87 ///
88 /// assert_eq!(vec.len(), 2);
89 /// assert_eq!(vec[0], 1);
90 ///
91 /// assert_eq!(vec.pop(), Some(2));
92 /// assert_eq!(vec.len(), 1);
93 ///
94 /// vec[0] = 7;
95 /// assert_eq!(vec[0], 7);
96 ///
97 /// vec.extend([1, 2, 3].iter().copied());
98 ///
99 /// for x in &vec {
100 ///     println!("{}", x);
101 /// }
102 /// assert_eq!(vec, [7, 1, 2, 3]);
103 /// ```
104 ///
105 /// The [`vec!`] macro is provided to make initialization more convenient:
106 ///
107 /// ```
108 /// let mut vec = vec![1, 2, 3];
109 /// vec.push(4);
110 /// assert_eq!(vec, [1, 2, 3, 4]);
111 /// ```
112 ///
113 /// It can also initialize each element of a `Vec<T>` with a given value.
114 /// This may be more efficient than performing allocation and initialization
115 /// in separate steps, especially when initializing a vector of zeros:
116 ///
117 /// ```
118 /// let vec = vec![0; 5];
119 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
120 ///
121 /// // The following is equivalent, but potentially slower:
122 /// let mut vec1 = Vec::with_capacity(5);
123 /// vec1.resize(5, 0);
124 /// ```
125 ///
126 /// Use a `Vec<T>` as an efficient stack:
127 ///
128 /// ```
129 /// let mut stack = Vec::new();
130 ///
131 /// stack.push(1);
132 /// stack.push(2);
133 /// stack.push(3);
134 ///
135 /// while let Some(top) = stack.pop() {
136 ///     // Prints 3, 2, 1
137 ///     println!("{}", top);
138 /// }
139 /// ```
140 ///
141 /// # Indexing
142 ///
143 /// The `Vec` type allows to access values by index, because it implements the
144 /// [`Index`] trait. An example will be more explicit:
145 ///
146 /// ```
147 /// let v = vec![0, 2, 4, 6];
148 /// println!("{}", v[1]); // it will display '2'
149 /// ```
150 ///
151 /// However be careful: if you try to access an index which isn't in the `Vec`,
152 /// your software will panic! You cannot do this:
153 ///
154 /// ```should_panic
155 /// let v = vec![0, 2, 4, 6];
156 /// println!("{}", v[6]); // it will panic!
157 /// ```
158 ///
159 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
160 /// the `Vec`.
161 ///
162 /// # Slicing
163 ///
164 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
165 /// To get a slice, use `&`. Example:
166 ///
167 /// ```
168 /// fn read_slice(slice: &[usize]) {
169 ///     // ...
170 /// }
171 ///
172 /// let v = vec![0, 1];
173 /// read_slice(&v);
174 ///
175 /// // ... and that's all!
176 /// // you can also do it like this:
177 /// let x : &[usize] = &v;
178 /// ```
179 ///
180 /// In Rust, it's more common to pass slices as arguments rather than vectors
181 /// when you just want to provide read access. The same goes for [`String`] and
182 /// [`&str`].
183 ///
184 /// # Capacity and reallocation
185 ///
186 /// The capacity of a vector is the amount of space allocated for any future
187 /// elements that will be added onto the vector. This is not to be confused with
188 /// the *length* of a vector, which specifies the number of actual elements
189 /// within the vector. If a vector's length exceeds its capacity, its capacity
190 /// will automatically be increased, but its elements will have to be
191 /// reallocated.
192 ///
193 /// For example, a vector with capacity 10 and length 0 would be an empty vector
194 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
195 /// vector will not change its capacity or cause reallocation to occur. However,
196 /// if the vector's length is increased to 11, it will have to reallocate, which
197 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
198 /// whenever possible to specify how big the vector is expected to get.
199 ///
200 /// # Guarantees
201 ///
202 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
203 /// about its design. This ensures that it's as low-overhead as possible in
204 /// the general case, and can be correctly manipulated in primitive ways
205 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
206 /// If additional type parameters are added (e.g., to support custom allocators),
207 /// overriding their defaults may change the behavior.
208 ///
209 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
210 /// triplet. No more, no less. The order of these fields is completely
211 /// unspecified, and you should use the appropriate methods to modify these.
212 /// The pointer will never be null, so this type is null-pointer-optimized.
213 ///
214 /// However, the pointer may not actually point to allocated memory. In particular,
215 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
216 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
217 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
218 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
219 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
220 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
221 /// details are very subtle &mdash; if you intend to allocate memory using a `Vec`
222 /// and use it for something else (either to pass to unsafe code, or to build your
223 /// own memory-backed collection), be sure to deallocate this memory by using
224 /// `from_raw_parts` to recover the `Vec` and then dropping it.
225 ///
226 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
227 /// (as defined by the allocator Rust is configured to use by default), and its
228 /// pointer points to [`len`] initialized, contiguous elements in order (what
229 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
230 /// `[`len`] logically uninitialized, contiguous elements.
231 ///
232 /// `Vec` will never perform a "small optimization" where elements are actually
233 /// stored on the stack for two reasons:
234 ///
235 /// * It would make it more difficult for unsafe code to correctly manipulate
236 ///   a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
237 ///   only moved, and it would be more difficult to determine if a `Vec` had
238 ///   actually allocated memory.
239 ///
240 /// * It would penalize the general case, incurring an additional branch
241 ///   on every access.
242 ///
243 /// `Vec` will never automatically shrink itself, even if completely empty. This
244 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
245 /// and then filling it back up to the same [`len`] should incur no calls to
246 /// the allocator. If you wish to free up unused memory, use
247 /// [`shrink_to_fit`].
248 ///
249 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
250 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
251 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
252 /// accurate, and can be relied on. It can even be used to manually free the memory
253 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
254 /// when not necessary.
255 ///
256 /// `Vec` does not guarantee any particular growth strategy when reallocating
257 /// when full, nor when [`reserve`] is called. The current strategy is basic
258 /// and it may prove desirable to use a non-constant growth factor. Whatever
259 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
260 ///
261 /// `vec![x; n]`, `vec![a, b, c, d]`, and
262 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
263 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
264 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
265 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
266 ///
267 /// `Vec` will not specifically overwrite any data that is removed from it,
268 /// but also won't specifically preserve it. Its uninitialized memory is
269 /// scratch space that it may use however it wants. It will generally just do
270 /// whatever is most efficient or otherwise easy to implement. Do not rely on
271 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
272 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
273 /// first, that may not actually happen because the optimizer does not consider
274 /// this a side-effect that must be preserved. There is one case which we will
275 /// not break, however: using `unsafe` code to write to the excess capacity,
276 /// and then increasing the length to match, is always valid.
277 ///
278 /// `Vec` does not currently guarantee the order in which elements are dropped.
279 /// The order has changed in the past and may change again.
280 ///
281 /// [`vec!`]: ../../std/macro.vec.html
282 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
283 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
284 /// [`Index`]: ../../std/ops/trait.Index.html
285 /// [`String`]: ../../std/string/struct.String.html
286 /// [`&str`]: ../../std/primitive.str.html
287 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
288 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
289 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
290 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
291 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
292 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
293 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
294 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
295 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
296 /// [owned slice]: ../../std/boxed/struct.Box.html
297 #[stable(feature = "rust1", since = "1.0.0")]
298 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
299 pub struct Vec<T> {
300     buf: RawVec<T>,
301     len: usize,
302 }
303
304 ////////////////////////////////////////////////////////////////////////////////
305 // Inherent methods
306 ////////////////////////////////////////////////////////////////////////////////
307
308 impl<T> Vec<T> {
309     /// Constructs a new, empty `Vec<T>`.
310     ///
311     /// The vector will not allocate until elements are pushed onto it.
312     ///
313     /// # Examples
314     ///
315     /// ```
316     /// # #![allow(unused_mut)]
317     /// let mut vec: Vec<i32> = Vec::new();
318     /// ```
319     #[inline]
320     #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
321     #[stable(feature = "rust1", since = "1.0.0")]
322     pub const fn new() -> Vec<T> {
323         Vec { buf: RawVec::NEW, len: 0 }
324     }
325
326     /// Constructs a new, empty `Vec<T>` with the specified capacity.
327     ///
328     /// The vector will be able to hold exactly `capacity` elements without
329     /// reallocating. If `capacity` is 0, the vector will not allocate.
330     ///
331     /// It is important to note that although the returned vector has the
332     /// *capacity* specified, the vector will have a zero *length*. For an
333     /// explanation of the difference between length and capacity, see
334     /// *[Capacity and reallocation]*.
335     ///
336     /// [Capacity and reallocation]: #capacity-and-reallocation
337     ///
338     /// # Examples
339     ///
340     /// ```
341     /// let mut vec = Vec::with_capacity(10);
342     ///
343     /// // The vector contains no items, even though it has capacity for more
344     /// assert_eq!(vec.len(), 0);
345     ///
346     /// // These are all done without reallocating...
347     /// for i in 0..10 {
348     ///     vec.push(i);
349     /// }
350     ///
351     /// // ...but this may make the vector reallocate
352     /// vec.push(11);
353     /// ```
354     #[inline]
355     #[stable(feature = "rust1", since = "1.0.0")]
356     pub fn with_capacity(capacity: usize) -> Vec<T> {
357         Vec { buf: RawVec::with_capacity(capacity), len: 0 }
358     }
359
360     /// Decomposes a `Vec<T>` into its raw components.
361     ///
362     /// Returns the raw pointer to the underlying data, the length of
363     /// the vector (in elements), and the allocated capacity of the
364     /// data (in elements). These are the same arguments in the same
365     /// order as the arguments to [`from_raw_parts`].
366     ///
367     /// After calling this function, the caller is responsible for the
368     /// memory previously managed by the `Vec`. The only way to do
369     /// this is to convert the raw pointer, length, and capacity back
370     /// into a `Vec` with the [`from_raw_parts`] function, allowing
371     /// the destructor to perform the cleanup.
372     ///
373     /// [`from_raw_parts`]: #method.from_raw_parts
374     ///
375     /// # Examples
376     ///
377     /// ```
378     /// #![feature(vec_into_raw_parts)]
379     /// let v: Vec<i32> = vec![-1, 0, 1];
380     ///
381     /// let (ptr, len, cap) = v.into_raw_parts();
382     ///
383     /// let rebuilt = unsafe {
384     ///     // We can now make changes to the components, such as
385     ///     // transmuting the raw pointer to a compatible type.
386     ///     let ptr = ptr as *mut u32;
387     ///
388     ///     Vec::from_raw_parts(ptr, len, cap)
389     /// };
390     /// assert_eq!(rebuilt, [4294967295, 0, 1]);
391     /// ```
392     #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
393     pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
394         let mut me = mem::ManuallyDrop::new(self);
395         (me.as_mut_ptr(), me.len(), me.capacity())
396     }
397
398     /// Creates a `Vec<T>` directly from the raw components of another vector.
399     ///
400     /// # Safety
401     ///
402     /// This is highly unsafe, due to the number of invariants that aren't
403     /// checked:
404     ///
405     /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
406     ///   (at least, it's highly likely to be incorrect if it wasn't).
407     /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
408     ///   (`T` having a less strict alignment is not sufficient, the alignment really
409     ///   needs to be equal to satsify the [`dealloc`] requirement that memory must be
410     ///   allocated and deallocated with the same layout.)
411     /// * `length` needs to be less than or equal to `capacity`.
412     /// * `capacity` needs to be the capacity that the pointer was allocated with.
413     ///
414     /// Violating these may cause problems like corrupting the allocator's
415     /// internal data structures. For example it is **not** safe
416     /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
417     /// It's also not safe to build one from a `Vec<u16>` and its length, because
418     /// the allocator cares about the alignment, and these two types have different
419     /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
420     /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
421     ///
422     /// The ownership of `ptr` is effectively transferred to the
423     /// `Vec<T>` which may then deallocate, reallocate or change the
424     /// contents of memory pointed to by the pointer at will. Ensure
425     /// that nothing else uses the pointer after calling this
426     /// function.
427     ///
428     /// [`String`]: ../../std/string/struct.String.html
429     /// [`dealloc`]: ../../alloc/alloc/trait.GlobalAlloc.html#tymethod.dealloc
430     ///
431     /// # Examples
432     ///
433     /// ```
434     /// use std::ptr;
435     /// use std::mem;
436     ///
437     /// let v = vec![1, 2, 3];
438     ///
439     // FIXME Update this when vec_into_raw_parts is stabilized
440     /// // Prevent running `v`'s destructor so we are in complete control
441     /// // of the allocation.
442     /// let mut v = mem::ManuallyDrop::new(v);
443     ///
444     /// // Pull out the various important pieces of information about `v`
445     /// let p = v.as_mut_ptr();
446     /// let len = v.len();
447     /// let cap = v.capacity();
448     ///
449     /// unsafe {
450     ///     // Overwrite memory with 4, 5, 6
451     ///     for i in 0..len as isize {
452     ///         ptr::write(p.offset(i), 4 + i);
453     ///     }
454     ///
455     ///     // Put everything back together into a Vec
456     ///     let rebuilt = Vec::from_raw_parts(p, len, cap);
457     ///     assert_eq!(rebuilt, [4, 5, 6]);
458     /// }
459     /// ```
460     #[stable(feature = "rust1", since = "1.0.0")]
461     pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
462         Vec { buf: RawVec::from_raw_parts(ptr, capacity), len: length }
463     }
464
465     /// Returns the number of elements the vector can hold without
466     /// reallocating.
467     ///
468     /// # Examples
469     ///
470     /// ```
471     /// let vec: Vec<i32> = Vec::with_capacity(10);
472     /// assert_eq!(vec.capacity(), 10);
473     /// ```
474     #[inline]
475     #[stable(feature = "rust1", since = "1.0.0")]
476     pub fn capacity(&self) -> usize {
477         self.buf.capacity()
478     }
479
480     /// Reserves capacity for at least `additional` more elements to be inserted
481     /// in the given `Vec<T>`. The collection may reserve more space to avoid
482     /// frequent reallocations. After calling `reserve`, capacity will be
483     /// greater than or equal to `self.len() + additional`. Does nothing if
484     /// capacity is already sufficient.
485     ///
486     /// # Panics
487     ///
488     /// Panics if the new capacity overflows `usize`.
489     ///
490     /// # Examples
491     ///
492     /// ```
493     /// let mut vec = vec![1];
494     /// vec.reserve(10);
495     /// assert!(vec.capacity() >= 11);
496     /// ```
497     #[stable(feature = "rust1", since = "1.0.0")]
498     pub fn reserve(&mut self, additional: usize) {
499         self.buf.reserve(self.len, additional);
500     }
501
502     /// Reserves the minimum capacity for exactly `additional` more elements to
503     /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
504     /// capacity will be greater than or equal to `self.len() + additional`.
505     /// Does nothing if the capacity is already sufficient.
506     ///
507     /// Note that the allocator may give the collection more space than it
508     /// requests. Therefore, capacity can not be relied upon to be precisely
509     /// minimal. Prefer `reserve` if future insertions are expected.
510     ///
511     /// # Panics
512     ///
513     /// Panics if the new capacity overflows `usize`.
514     ///
515     /// # Examples
516     ///
517     /// ```
518     /// let mut vec = vec![1];
519     /// vec.reserve_exact(10);
520     /// assert!(vec.capacity() >= 11);
521     /// ```
522     #[stable(feature = "rust1", since = "1.0.0")]
523     pub fn reserve_exact(&mut self, additional: usize) {
524         self.buf.reserve_exact(self.len, additional);
525     }
526
527     /// Tries to reserve capacity for at least `additional` more elements to be inserted
528     /// in the given `Vec<T>`. The collection may reserve more space to avoid
529     /// frequent reallocations. After calling `reserve`, capacity will be
530     /// greater than or equal to `self.len() + additional`. Does nothing if
531     /// capacity is already sufficient.
532     ///
533     /// # Errors
534     ///
535     /// If the capacity overflows, or the allocator reports a failure, then an error
536     /// is returned.
537     ///
538     /// # Examples
539     ///
540     /// ```
541     /// #![feature(try_reserve)]
542     /// use std::collections::TryReserveError;
543     ///
544     /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
545     ///     let mut output = Vec::new();
546     ///
547     ///     // Pre-reserve the memory, exiting if we can't
548     ///     output.try_reserve(data.len())?;
549     ///
550     ///     // Now we know this can't OOM in the middle of our complex work
551     ///     output.extend(data.iter().map(|&val| {
552     ///         val * 2 + 5 // very complicated
553     ///     }));
554     ///
555     ///     Ok(output)
556     /// }
557     /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
558     /// ```
559     #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
560     pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
561         self.buf.try_reserve(self.len, additional)
562     }
563
564     /// Tries to reserves the minimum capacity for exactly `additional` more elements to
565     /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
566     /// capacity will be greater than or equal to `self.len() + additional`.
567     /// Does nothing if the capacity is already sufficient.
568     ///
569     /// Note that the allocator may give the collection more space than it
570     /// requests. Therefore, capacity can not be relied upon to be precisely
571     /// minimal. Prefer `reserve` if future insertions are expected.
572     ///
573     /// # Errors
574     ///
575     /// If the capacity overflows, or the allocator reports a failure, then an error
576     /// is returned.
577     ///
578     /// # Examples
579     ///
580     /// ```
581     /// #![feature(try_reserve)]
582     /// use std::collections::TryReserveError;
583     ///
584     /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
585     ///     let mut output = Vec::new();
586     ///
587     ///     // Pre-reserve the memory, exiting if we can't
588     ///     output.try_reserve(data.len())?;
589     ///
590     ///     // Now we know this can't OOM in the middle of our complex work
591     ///     output.extend(data.iter().map(|&val| {
592     ///         val * 2 + 5 // very complicated
593     ///     }));
594     ///
595     ///     Ok(output)
596     /// }
597     /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
598     /// ```
599     #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
600     pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
601         self.buf.try_reserve_exact(self.len, additional)
602     }
603
604     /// Shrinks the capacity of the vector as much as possible.
605     ///
606     /// It will drop down as close as possible to the length but the allocator
607     /// may still inform the vector that there is space for a few more elements.
608     ///
609     /// # Examples
610     ///
611     /// ```
612     /// let mut vec = Vec::with_capacity(10);
613     /// vec.extend([1, 2, 3].iter().cloned());
614     /// assert_eq!(vec.capacity(), 10);
615     /// vec.shrink_to_fit();
616     /// assert!(vec.capacity() >= 3);
617     /// ```
618     #[stable(feature = "rust1", since = "1.0.0")]
619     pub fn shrink_to_fit(&mut self) {
620         if self.capacity() != self.len {
621             self.buf.shrink_to_fit(self.len);
622         }
623     }
624
625     /// Shrinks the capacity of the vector with a lower bound.
626     ///
627     /// The capacity will remain at least as large as both the length
628     /// and the supplied value.
629     ///
630     /// # Panics
631     ///
632     /// Panics if the current capacity is smaller than the supplied
633     /// minimum capacity.
634     ///
635     /// # Examples
636     ///
637     /// ```
638     /// #![feature(shrink_to)]
639     /// let mut vec = Vec::with_capacity(10);
640     /// vec.extend([1, 2, 3].iter().cloned());
641     /// assert_eq!(vec.capacity(), 10);
642     /// vec.shrink_to(4);
643     /// assert!(vec.capacity() >= 4);
644     /// vec.shrink_to(0);
645     /// assert!(vec.capacity() >= 3);
646     /// ```
647     #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
648     pub fn shrink_to(&mut self, min_capacity: usize) {
649         self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
650     }
651
652     /// Converts the vector into [`Box<[T]>`][owned slice].
653     ///
654     /// Note that this will drop any excess capacity.
655     ///
656     /// [owned slice]: ../../std/boxed/struct.Box.html
657     ///
658     /// # Examples
659     ///
660     /// ```
661     /// let v = vec![1, 2, 3];
662     ///
663     /// let slice = v.into_boxed_slice();
664     /// ```
665     ///
666     /// Any excess capacity is removed:
667     ///
668     /// ```
669     /// let mut vec = Vec::with_capacity(10);
670     /// vec.extend([1, 2, 3].iter().cloned());
671     ///
672     /// assert_eq!(vec.capacity(), 10);
673     /// let slice = vec.into_boxed_slice();
674     /// assert_eq!(slice.into_vec().capacity(), 3);
675     /// ```
676     #[stable(feature = "rust1", since = "1.0.0")]
677     pub fn into_boxed_slice(mut self) -> Box<[T]> {
678         unsafe {
679             self.shrink_to_fit();
680             let buf = ptr::read(&self.buf);
681             mem::forget(self);
682             buf.into_box().assume_init()
683         }
684     }
685
686     /// Shortens the vector, keeping the first `len` elements and dropping
687     /// the rest.
688     ///
689     /// If `len` is greater than the vector's current length, this has no
690     /// effect.
691     ///
692     /// The [`drain`] method can emulate `truncate`, but causes the excess
693     /// elements to be returned instead of dropped.
694     ///
695     /// Note that this method has no effect on the allocated capacity
696     /// of the vector.
697     ///
698     /// # Examples
699     ///
700     /// Truncating a five element vector to two elements:
701     ///
702     /// ```
703     /// let mut vec = vec![1, 2, 3, 4, 5];
704     /// vec.truncate(2);
705     /// assert_eq!(vec, [1, 2]);
706     /// ```
707     ///
708     /// No truncation occurs when `len` is greater than the vector's current
709     /// length:
710     ///
711     /// ```
712     /// let mut vec = vec![1, 2, 3];
713     /// vec.truncate(8);
714     /// assert_eq!(vec, [1, 2, 3]);
715     /// ```
716     ///
717     /// Truncating when `len == 0` is equivalent to calling the [`clear`]
718     /// method.
719     ///
720     /// ```
721     /// let mut vec = vec![1, 2, 3];
722     /// vec.truncate(0);
723     /// assert_eq!(vec, []);
724     /// ```
725     ///
726     /// [`clear`]: #method.clear
727     /// [`drain`]: #method.drain
728     #[stable(feature = "rust1", since = "1.0.0")]
729     pub fn truncate(&mut self, len: usize) {
730         // This is safe because:
731         //
732         // * the slice passed to `drop_in_place` is valid; the `len > self.len`
733         //   case avoids creating an invalid slice, and
734         // * the `len` of the vector is shrunk before calling `drop_in_place`,
735         //   such that no value will be dropped twice in case `drop_in_place`
736         //   were to panic once (if it panics twice, the program aborts).
737         unsafe {
738             if len > self.len {
739                 return;
740             }
741             let s = self.get_unchecked_mut(len..) as *mut _;
742             self.len = len;
743             ptr::drop_in_place(s);
744         }
745     }
746
747     /// Extracts a slice containing the entire vector.
748     ///
749     /// Equivalent to `&s[..]`.
750     ///
751     /// # Examples
752     ///
753     /// ```
754     /// use std::io::{self, Write};
755     /// let buffer = vec![1, 2, 3, 5, 8];
756     /// io::sink().write(buffer.as_slice()).unwrap();
757     /// ```
758     #[inline]
759     #[stable(feature = "vec_as_slice", since = "1.7.0")]
760     pub fn as_slice(&self) -> &[T] {
761         self
762     }
763
764     /// Extracts a mutable slice of the entire vector.
765     ///
766     /// Equivalent to `&mut s[..]`.
767     ///
768     /// # Examples
769     ///
770     /// ```
771     /// use std::io::{self, Read};
772     /// let mut buffer = vec![0; 3];
773     /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
774     /// ```
775     #[inline]
776     #[stable(feature = "vec_as_slice", since = "1.7.0")]
777     pub fn as_mut_slice(&mut self) -> &mut [T] {
778         self
779     }
780
781     /// Returns a raw pointer to the vector's buffer.
782     ///
783     /// The caller must ensure that the vector outlives the pointer this
784     /// function returns, or else it will end up pointing to garbage.
785     /// Modifying the vector may cause its buffer to be reallocated,
786     /// which would also make any pointers to it invalid.
787     ///
788     /// The caller must also ensure that the memory the pointer (non-transitively) points to
789     /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
790     /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
791     ///
792     /// # Examples
793     ///
794     /// ```
795     /// let x = vec![1, 2, 4];
796     /// let x_ptr = x.as_ptr();
797     ///
798     /// unsafe {
799     ///     for i in 0..x.len() {
800     ///         assert_eq!(*x_ptr.add(i), 1 << i);
801     ///     }
802     /// }
803     /// ```
804     ///
805     /// [`as_mut_ptr`]: #method.as_mut_ptr
806     #[stable(feature = "vec_as_ptr", since = "1.37.0")]
807     #[inline]
808     pub fn as_ptr(&self) -> *const T {
809         // We shadow the slice method of the same name to avoid going through
810         // `deref`, which creates an intermediate reference.
811         let ptr = self.buf.ptr();
812         unsafe {
813             assume(!ptr.is_null());
814         }
815         ptr
816     }
817
818     /// Returns an unsafe mutable pointer to the vector's buffer.
819     ///
820     /// The caller must ensure that the vector outlives the pointer this
821     /// function returns, or else it will end up pointing to garbage.
822     /// Modifying the vector may cause its buffer to be reallocated,
823     /// which would also make any pointers to it invalid.
824     ///
825     /// # Examples
826     ///
827     /// ```
828     /// // Allocate vector big enough for 4 elements.
829     /// let size = 4;
830     /// let mut x: Vec<i32> = Vec::with_capacity(size);
831     /// let x_ptr = x.as_mut_ptr();
832     ///
833     /// // Initialize elements via raw pointer writes, then set length.
834     /// unsafe {
835     ///     for i in 0..size {
836     ///         *x_ptr.add(i) = i as i32;
837     ///     }
838     ///     x.set_len(size);
839     /// }
840     /// assert_eq!(&*x, &[0,1,2,3]);
841     /// ```
842     #[stable(feature = "vec_as_ptr", since = "1.37.0")]
843     #[inline]
844     pub fn as_mut_ptr(&mut self) -> *mut T {
845         // We shadow the slice method of the same name to avoid going through
846         // `deref_mut`, which creates an intermediate reference.
847         let ptr = self.buf.ptr();
848         unsafe {
849             assume(!ptr.is_null());
850         }
851         ptr
852     }
853
854     /// Forces the length of the vector to `new_len`.
855     ///
856     /// This is a low-level operation that maintains none of the normal
857     /// invariants of the type. Normally changing the length of a vector
858     /// is done using one of the safe operations instead, such as
859     /// [`truncate`], [`resize`], [`extend`], or [`clear`].
860     ///
861     /// [`truncate`]: #method.truncate
862     /// [`resize`]: #method.resize
863     /// [`extend`]: ../../std/iter/trait.Extend.html#tymethod.extend
864     /// [`clear`]: #method.clear
865     ///
866     /// # Safety
867     ///
868     /// - `new_len` must be less than or equal to [`capacity()`].
869     /// - The elements at `old_len..new_len` must be initialized.
870     ///
871     /// [`capacity()`]: #method.capacity
872     ///
873     /// # Examples
874     ///
875     /// This method can be useful for situations in which the vector
876     /// is serving as a buffer for other code, particularly over FFI:
877     ///
878     /// ```no_run
879     /// # #![allow(dead_code)]
880     /// # // This is just a minimal skeleton for the doc example;
881     /// # // don't use this as a starting point for a real library.
882     /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
883     /// # const Z_OK: i32 = 0;
884     /// # extern "C" {
885     /// #     fn deflateGetDictionary(
886     /// #         strm: *mut std::ffi::c_void,
887     /// #         dictionary: *mut u8,
888     /// #         dictLength: *mut usize,
889     /// #     ) -> i32;
890     /// # }
891     /// # impl StreamWrapper {
892     /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
893     ///     // Per the FFI method's docs, "32768 bytes is always enough".
894     ///     let mut dict = Vec::with_capacity(32_768);
895     ///     let mut dict_length = 0;
896     ///     // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
897     ///     // 1. `dict_length` elements were initialized.
898     ///     // 2. `dict_length` <= the capacity (32_768)
899     ///     // which makes `set_len` safe to call.
900     ///     unsafe {
901     ///         // Make the FFI call...
902     ///         let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
903     ///         if r == Z_OK {
904     ///             // ...and update the length to what was initialized.
905     ///             dict.set_len(dict_length);
906     ///             Some(dict)
907     ///         } else {
908     ///             None
909     ///         }
910     ///     }
911     /// }
912     /// # }
913     /// ```
914     ///
915     /// While the following example is sound, there is a memory leak since
916     /// the inner vectors were not freed prior to the `set_len` call:
917     ///
918     /// ```
919     /// let mut vec = vec![vec![1, 0, 0],
920     ///                    vec![0, 1, 0],
921     ///                    vec![0, 0, 1]];
922     /// // SAFETY:
923     /// // 1. `old_len..0` is empty so no elements need to be initialized.
924     /// // 2. `0 <= capacity` always holds whatever `capacity` is.
925     /// unsafe {
926     ///     vec.set_len(0);
927     /// }
928     /// ```
929     ///
930     /// Normally, here, one would use [`clear`] instead to correctly drop
931     /// the contents and thus not leak memory.
932     #[inline]
933     #[stable(feature = "rust1", since = "1.0.0")]
934     pub unsafe fn set_len(&mut self, new_len: usize) {
935         debug_assert!(new_len <= self.capacity());
936
937         self.len = new_len;
938     }
939
940     /// Removes an element from the vector and returns it.
941     ///
942     /// The removed element is replaced by the last element of the vector.
943     ///
944     /// This does not preserve ordering, but is O(1).
945     ///
946     /// # Panics
947     ///
948     /// Panics if `index` is out of bounds.
949     ///
950     /// # Examples
951     ///
952     /// ```
953     /// let mut v = vec!["foo", "bar", "baz", "qux"];
954     ///
955     /// assert_eq!(v.swap_remove(1), "bar");
956     /// assert_eq!(v, ["foo", "qux", "baz"]);
957     ///
958     /// assert_eq!(v.swap_remove(0), "foo");
959     /// assert_eq!(v, ["baz", "qux"]);
960     /// ```
961     #[inline]
962     #[stable(feature = "rust1", since = "1.0.0")]
963     pub fn swap_remove(&mut self, index: usize) -> T {
964         unsafe {
965             // We replace self[index] with the last element. Note that if the
966             // bounds check on hole succeeds there must be a last element (which
967             // can be self[index] itself).
968             let hole: *mut T = &mut self[index];
969             let last = ptr::read(self.get_unchecked(self.len - 1));
970             self.len -= 1;
971             ptr::replace(hole, last)
972         }
973     }
974
975     /// Inserts an element at position `index` within the vector, shifting all
976     /// elements after it to the right.
977     ///
978     /// # Panics
979     ///
980     /// Panics if `index > len`.
981     ///
982     /// # Examples
983     ///
984     /// ```
985     /// let mut vec = vec![1, 2, 3];
986     /// vec.insert(1, 4);
987     /// assert_eq!(vec, [1, 4, 2, 3]);
988     /// vec.insert(4, 5);
989     /// assert_eq!(vec, [1, 4, 2, 3, 5]);
990     /// ```
991     #[stable(feature = "rust1", since = "1.0.0")]
992     pub fn insert(&mut self, index: usize, element: T) {
993         let len = self.len();
994         assert!(index <= len);
995
996         // space for the new element
997         if len == self.buf.capacity() {
998             self.reserve(1);
999         }
1000
1001         unsafe {
1002             // infallible
1003             // The spot to put the new value
1004             {
1005                 let p = self.as_mut_ptr().add(index);
1006                 // Shift everything over to make space. (Duplicating the
1007                 // `index`th element into two consecutive places.)
1008                 ptr::copy(p, p.offset(1), len - index);
1009                 // Write it in, overwriting the first copy of the `index`th
1010                 // element.
1011                 ptr::write(p, element);
1012             }
1013             self.set_len(len + 1);
1014         }
1015     }
1016
1017     /// Removes and returns the element at position `index` within the vector,
1018     /// shifting all elements after it to the left.
1019     ///
1020     /// # Panics
1021     ///
1022     /// Panics if `index` is out of bounds.
1023     ///
1024     /// # Examples
1025     ///
1026     /// ```
1027     /// let mut v = vec![1, 2, 3];
1028     /// assert_eq!(v.remove(1), 2);
1029     /// assert_eq!(v, [1, 3]);
1030     /// ```
1031     #[stable(feature = "rust1", since = "1.0.0")]
1032     pub fn remove(&mut self, index: usize) -> T {
1033         let len = self.len();
1034         assert!(index < len);
1035         unsafe {
1036             // infallible
1037             let ret;
1038             {
1039                 // the place we are taking from.
1040                 let ptr = self.as_mut_ptr().add(index);
1041                 // copy it out, unsafely having a copy of the value on
1042                 // the stack and in the vector at the same time.
1043                 ret = ptr::read(ptr);
1044
1045                 // Shift everything down to fill in that spot.
1046                 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1047             }
1048             self.set_len(len - 1);
1049             ret
1050         }
1051     }
1052
1053     /// Retains only the elements specified by the predicate.
1054     ///
1055     /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1056     /// This method operates in place, visiting each element exactly once in the
1057     /// original order, and preserves the order of the retained elements.
1058     ///
1059     /// # Examples
1060     ///
1061     /// ```
1062     /// let mut vec = vec![1, 2, 3, 4];
1063     /// vec.retain(|&x| x % 2 == 0);
1064     /// assert_eq!(vec, [2, 4]);
1065     /// ```
1066     ///
1067     /// The exact order may be useful for tracking external state, like an index.
1068     ///
1069     /// ```
1070     /// let mut vec = vec![1, 2, 3, 4, 5];
1071     /// let keep = [false, true, true, false, true];
1072     /// let mut i = 0;
1073     /// vec.retain(|_| (keep[i], i += 1).0);
1074     /// assert_eq!(vec, [2, 3, 5]);
1075     /// ```
1076     #[stable(feature = "rust1", since = "1.0.0")]
1077     pub fn retain<F>(&mut self, mut f: F)
1078     where
1079         F: FnMut(&T) -> bool,
1080     {
1081         let len = self.len();
1082         let mut del = 0;
1083         {
1084             let v = &mut **self;
1085
1086             for i in 0..len {
1087                 if !f(&v[i]) {
1088                     del += 1;
1089                 } else if del > 0 {
1090                     v.swap(i - del, i);
1091                 }
1092             }
1093         }
1094         if del > 0 {
1095             self.truncate(len - del);
1096         }
1097     }
1098
1099     /// Removes all but the first of consecutive elements in the vector that resolve to the same
1100     /// key.
1101     ///
1102     /// If the vector is sorted, this removes all duplicates.
1103     ///
1104     /// # Examples
1105     ///
1106     /// ```
1107     /// let mut vec = vec![10, 20, 21, 30, 20];
1108     ///
1109     /// vec.dedup_by_key(|i| *i / 10);
1110     ///
1111     /// assert_eq!(vec, [10, 20, 30, 20]);
1112     /// ```
1113     #[stable(feature = "dedup_by", since = "1.16.0")]
1114     #[inline]
1115     pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1116     where
1117         F: FnMut(&mut T) -> K,
1118         K: PartialEq,
1119     {
1120         self.dedup_by(|a, b| key(a) == key(b))
1121     }
1122
1123     /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1124     /// relation.
1125     ///
1126     /// The `same_bucket` function is passed references to two elements from the vector and
1127     /// must determine if the elements compare equal. The elements are passed in opposite order
1128     /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1129     ///
1130     /// If the vector is sorted, this removes all duplicates.
1131     ///
1132     /// # Examples
1133     ///
1134     /// ```
1135     /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1136     ///
1137     /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1138     ///
1139     /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1140     /// ```
1141     #[stable(feature = "dedup_by", since = "1.16.0")]
1142     pub fn dedup_by<F>(&mut self, same_bucket: F)
1143     where
1144         F: FnMut(&mut T, &mut T) -> bool,
1145     {
1146         let len = {
1147             let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1148             dedup.len()
1149         };
1150         self.truncate(len);
1151     }
1152
1153     /// Appends an element to the back of a collection.
1154     ///
1155     /// # Panics
1156     ///
1157     /// Panics if the number of elements in the vector overflows a `usize`.
1158     ///
1159     /// # Examples
1160     ///
1161     /// ```
1162     /// let mut vec = vec![1, 2];
1163     /// vec.push(3);
1164     /// assert_eq!(vec, [1, 2, 3]);
1165     /// ```
1166     #[inline]
1167     #[stable(feature = "rust1", since = "1.0.0")]
1168     pub fn push(&mut self, value: T) {
1169         // This will panic or abort if we would allocate > isize::MAX bytes
1170         // or if the length increment would overflow for zero-sized types.
1171         if self.len == self.buf.capacity() {
1172             self.reserve(1);
1173         }
1174         unsafe {
1175             let end = self.as_mut_ptr().add(self.len);
1176             ptr::write(end, value);
1177             self.len += 1;
1178         }
1179     }
1180
1181     /// Removes the last element from a vector and returns it, or [`None`] if it
1182     /// is empty.
1183     ///
1184     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1185     ///
1186     /// # Examples
1187     ///
1188     /// ```
1189     /// let mut vec = vec![1, 2, 3];
1190     /// assert_eq!(vec.pop(), Some(3));
1191     /// assert_eq!(vec, [1, 2]);
1192     /// ```
1193     #[inline]
1194     #[stable(feature = "rust1", since = "1.0.0")]
1195     pub fn pop(&mut self) -> Option<T> {
1196         if self.len == 0 {
1197             None
1198         } else {
1199             unsafe {
1200                 self.len -= 1;
1201                 Some(ptr::read(self.get_unchecked(self.len())))
1202             }
1203         }
1204     }
1205
1206     /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1207     ///
1208     /// # Panics
1209     ///
1210     /// Panics if the number of elements in the vector overflows a `usize`.
1211     ///
1212     /// # Examples
1213     ///
1214     /// ```
1215     /// let mut vec = vec![1, 2, 3];
1216     /// let mut vec2 = vec![4, 5, 6];
1217     /// vec.append(&mut vec2);
1218     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1219     /// assert_eq!(vec2, []);
1220     /// ```
1221     #[inline]
1222     #[stable(feature = "append", since = "1.4.0")]
1223     pub fn append(&mut self, other: &mut Self) {
1224         unsafe {
1225             self.append_elements(other.as_slice() as _);
1226             other.set_len(0);
1227         }
1228     }
1229
1230     /// Appends elements to `Self` from other buffer.
1231     #[inline]
1232     unsafe fn append_elements(&mut self, other: *const [T]) {
1233         let count = (*other).len();
1234         self.reserve(count);
1235         let len = self.len();
1236         ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count);
1237         self.len += count;
1238     }
1239
1240     /// Creates a draining iterator that removes the specified range in the vector
1241     /// and yields the removed items.
1242     ///
1243     /// Note 1: The element range is removed even if the iterator is only
1244     /// partially consumed or not consumed at all.
1245     ///
1246     /// Note 2: It is unspecified how many elements are removed from the vector
1247     /// if the `Drain` value is leaked.
1248     ///
1249     /// # Panics
1250     ///
1251     /// Panics if the starting point is greater than the end point or if
1252     /// the end point is greater than the length of the vector.
1253     ///
1254     /// # Examples
1255     ///
1256     /// ```
1257     /// let mut v = vec![1, 2, 3];
1258     /// let u: Vec<_> = v.drain(1..).collect();
1259     /// assert_eq!(v, &[1]);
1260     /// assert_eq!(u, &[2, 3]);
1261     ///
1262     /// // A full range clears the vector
1263     /// v.drain(..);
1264     /// assert_eq!(v, &[]);
1265     /// ```
1266     #[stable(feature = "drain", since = "1.6.0")]
1267     pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1268     where
1269         R: RangeBounds<usize>,
1270     {
1271         // Memory safety
1272         //
1273         // When the Drain is first created, it shortens the length of
1274         // the source vector to make sure no uninitialized or moved-from elements
1275         // are accessible at all if the Drain's destructor never gets to run.
1276         //
1277         // Drain will ptr::read out the values to remove.
1278         // When finished, remaining tail of the vec is copied back to cover
1279         // the hole, and the vector length is restored to the new length.
1280         //
1281         let len = self.len();
1282         let start = match range.start_bound() {
1283             Included(&n) => n,
1284             Excluded(&n) => n + 1,
1285             Unbounded => 0,
1286         };
1287         let end = match range.end_bound() {
1288             Included(&n) => n + 1,
1289             Excluded(&n) => n,
1290             Unbounded => len,
1291         };
1292         assert!(start <= end);
1293         assert!(end <= len);
1294
1295         unsafe {
1296             // set self.vec length's to start, to be safe in case Drain is leaked
1297             self.set_len(start);
1298             // Use the borrow in the IterMut to indicate borrowing behavior of the
1299             // whole Drain iterator (like &mut T).
1300             let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1301             Drain {
1302                 tail_start: end,
1303                 tail_len: len - end,
1304                 iter: range_slice.iter(),
1305                 vec: NonNull::from(self),
1306             }
1307         }
1308     }
1309
1310     /// Clears the vector, removing all values.
1311     ///
1312     /// Note that this method has no effect on the allocated capacity
1313     /// of the vector.
1314     ///
1315     /// # Examples
1316     ///
1317     /// ```
1318     /// let mut v = vec![1, 2, 3];
1319     ///
1320     /// v.clear();
1321     ///
1322     /// assert!(v.is_empty());
1323     /// ```
1324     #[inline]
1325     #[stable(feature = "rust1", since = "1.0.0")]
1326     pub fn clear(&mut self) {
1327         self.truncate(0)
1328     }
1329
1330     /// Returns the number of elements in the vector, also referred to
1331     /// as its 'length'.
1332     ///
1333     /// # Examples
1334     ///
1335     /// ```
1336     /// let a = vec![1, 2, 3];
1337     /// assert_eq!(a.len(), 3);
1338     /// ```
1339     #[inline]
1340     #[stable(feature = "rust1", since = "1.0.0")]
1341     pub fn len(&self) -> usize {
1342         self.len
1343     }
1344
1345     /// Returns `true` if the vector contains no elements.
1346     ///
1347     /// # Examples
1348     ///
1349     /// ```
1350     /// let mut v = Vec::new();
1351     /// assert!(v.is_empty());
1352     ///
1353     /// v.push(1);
1354     /// assert!(!v.is_empty());
1355     /// ```
1356     #[stable(feature = "rust1", since = "1.0.0")]
1357     pub fn is_empty(&self) -> bool {
1358         self.len() == 0
1359     }
1360
1361     /// Splits the collection into two at the given index.
1362     ///
1363     /// Returns a newly allocated vector containing the elements in the range
1364     /// `[at, len)`. After the call, the original vector will be left containing
1365     /// the elements `[0, at)` with its previous capacity unchanged.
1366     ///
1367     /// # Panics
1368     ///
1369     /// Panics if `at > len`.
1370     ///
1371     /// # Examples
1372     ///
1373     /// ```
1374     /// let mut vec = vec![1,2,3];
1375     /// let vec2 = vec.split_off(1);
1376     /// assert_eq!(vec, [1]);
1377     /// assert_eq!(vec2, [2, 3]);
1378     /// ```
1379     #[inline]
1380     #[must_use = "use `.truncate()` if you don't need the other half"]
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_cow_slice", since = "1.14.0")]
2402 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2403 where
2404     [T]: ToOwned<Owned = Vec<T>>,
2405 {
2406     fn from(s: Cow<'a, [T]>) -> Vec<T> {
2407         s.into_owned()
2408     }
2409 }
2410
2411 // note: test pulls in libstd, which causes errors here
2412 #[cfg(not(test))]
2413 #[stable(feature = "vec_from_box", since = "1.18.0")]
2414 impl<T> From<Box<[T]>> for Vec<T> {
2415     fn from(s: Box<[T]>) -> Vec<T> {
2416         s.into_vec()
2417     }
2418 }
2419
2420 // note: test pulls in libstd, which causes errors here
2421 #[cfg(not(test))]
2422 #[stable(feature = "box_from_vec", since = "1.20.0")]
2423 impl<T> From<Vec<T>> for Box<[T]> {
2424     fn from(v: Vec<T>) -> Box<[T]> {
2425         v.into_boxed_slice()
2426     }
2427 }
2428
2429 #[stable(feature = "rust1", since = "1.0.0")]
2430 impl From<&str> for Vec<u8> {
2431     fn from(s: &str) -> Vec<u8> {
2432         From::from(s.as_bytes())
2433     }
2434 }
2435
2436 ////////////////////////////////////////////////////////////////////////////////
2437 // Clone-on-write
2438 ////////////////////////////////////////////////////////////////////////////////
2439
2440 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2441 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2442     fn from(s: &'a [T]) -> Cow<'a, [T]> {
2443         Cow::Borrowed(s)
2444     }
2445 }
2446
2447 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2448 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2449     fn from(v: Vec<T>) -> Cow<'a, [T]> {
2450         Cow::Owned(v)
2451     }
2452 }
2453
2454 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2455 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2456     fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2457         Cow::Borrowed(v.as_slice())
2458     }
2459 }
2460
2461 #[stable(feature = "rust1", since = "1.0.0")]
2462 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
2463 where
2464     T: Clone,
2465 {
2466     fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2467         Cow::Owned(FromIterator::from_iter(it))
2468     }
2469 }
2470
2471 ////////////////////////////////////////////////////////////////////////////////
2472 // Iterators
2473 ////////////////////////////////////////////////////////////////////////////////
2474
2475 /// An iterator that moves out of a vector.
2476 ///
2477 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
2478 /// by the [`IntoIterator`] trait).
2479 ///
2480 /// [`Vec`]: struct.Vec.html
2481 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2482 #[stable(feature = "rust1", since = "1.0.0")]
2483 pub struct IntoIter<T> {
2484     buf: NonNull<T>,
2485     phantom: PhantomData<T>,
2486     cap: usize,
2487     ptr: *const T,
2488     end: *const T,
2489 }
2490
2491 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2492 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2493     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2494         f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2495     }
2496 }
2497
2498 impl<T> IntoIter<T> {
2499     /// Returns the remaining items of this iterator as a slice.
2500     ///
2501     /// # Examples
2502     ///
2503     /// ```
2504     /// let vec = vec!['a', 'b', 'c'];
2505     /// let mut into_iter = vec.into_iter();
2506     /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2507     /// let _ = into_iter.next().unwrap();
2508     /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2509     /// ```
2510     #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2511     pub fn as_slice(&self) -> &[T] {
2512         unsafe { slice::from_raw_parts(self.ptr, self.len()) }
2513     }
2514
2515     /// Returns the remaining items of this iterator as a mutable slice.
2516     ///
2517     /// # Examples
2518     ///
2519     /// ```
2520     /// let vec = vec!['a', 'b', 'c'];
2521     /// let mut into_iter = vec.into_iter();
2522     /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2523     /// into_iter.as_mut_slice()[2] = 'z';
2524     /// assert_eq!(into_iter.next().unwrap(), 'a');
2525     /// assert_eq!(into_iter.next().unwrap(), 'b');
2526     /// assert_eq!(into_iter.next().unwrap(), 'z');
2527     /// ```
2528     #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2529     pub fn as_mut_slice(&mut self) -> &mut [T] {
2530         unsafe { slice::from_raw_parts_mut(self.ptr as *mut T, self.len()) }
2531     }
2532 }
2533
2534 #[stable(feature = "rust1", since = "1.0.0")]
2535 unsafe impl<T: Send> Send for IntoIter<T> {}
2536 #[stable(feature = "rust1", since = "1.0.0")]
2537 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2538
2539 #[stable(feature = "rust1", since = "1.0.0")]
2540 impl<T> Iterator for IntoIter<T> {
2541     type Item = T;
2542
2543     #[inline]
2544     fn next(&mut self) -> Option<T> {
2545         unsafe {
2546             if self.ptr as *const _ == self.end {
2547                 None
2548             } else {
2549                 if mem::size_of::<T>() == 0 {
2550                     // purposefully don't use 'ptr.offset' because for
2551                     // vectors with 0-size elements this would return the
2552                     // same pointer.
2553                     self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2554
2555                     // Make up a value of this ZST.
2556                     Some(mem::zeroed())
2557                 } else {
2558                     let old = self.ptr;
2559                     self.ptr = self.ptr.offset(1);
2560
2561                     Some(ptr::read(old))
2562                 }
2563             }
2564         }
2565     }
2566
2567     #[inline]
2568     fn size_hint(&self) -> (usize, Option<usize>) {
2569         let exact = if mem::size_of::<T>() == 0 {
2570             (self.end as usize).wrapping_sub(self.ptr as usize)
2571         } else {
2572             unsafe { self.end.offset_from(self.ptr) as usize }
2573         };
2574         (exact, Some(exact))
2575     }
2576
2577     #[inline]
2578     fn count(self) -> usize {
2579         self.len()
2580     }
2581 }
2582
2583 #[stable(feature = "rust1", since = "1.0.0")]
2584 impl<T> DoubleEndedIterator for IntoIter<T> {
2585     #[inline]
2586     fn next_back(&mut self) -> Option<T> {
2587         unsafe {
2588             if self.end == self.ptr {
2589                 None
2590             } else {
2591                 if mem::size_of::<T>() == 0 {
2592                     // See above for why 'ptr.offset' isn't used
2593                     self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2594
2595                     // Make up a value of this ZST.
2596                     Some(mem::zeroed())
2597                 } else {
2598                     self.end = self.end.offset(-1);
2599
2600                     Some(ptr::read(self.end))
2601                 }
2602             }
2603         }
2604     }
2605 }
2606
2607 #[stable(feature = "rust1", since = "1.0.0")]
2608 impl<T> ExactSizeIterator for IntoIter<T> {
2609     fn is_empty(&self) -> bool {
2610         self.ptr == self.end
2611     }
2612 }
2613
2614 #[stable(feature = "fused", since = "1.26.0")]
2615 impl<T> FusedIterator for IntoIter<T> {}
2616
2617 #[unstable(feature = "trusted_len", issue = "37572")]
2618 unsafe impl<T> TrustedLen for IntoIter<T> {}
2619
2620 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2621 impl<T: Clone> Clone for IntoIter<T> {
2622     fn clone(&self) -> IntoIter<T> {
2623         self.as_slice().to_owned().into_iter()
2624     }
2625 }
2626
2627 #[stable(feature = "rust1", since = "1.0.0")]
2628 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2629     fn drop(&mut self) {
2630         struct DropGuard<'a, T>(&'a mut IntoIter<T>);
2631
2632         impl<T> Drop for DropGuard<'_, T> {
2633             fn drop(&mut self) {
2634                 // RawVec handles deallocation
2635                 let _ = unsafe { RawVec::from_raw_parts(self.0.buf.as_ptr(), self.0.cap) };
2636             }
2637         }
2638
2639         let guard = DropGuard(self);
2640         // destroy the remaining elements
2641         unsafe {
2642             ptr::drop_in_place(guard.0.as_mut_slice());
2643         }
2644         // now `guard` will be dropped and do the rest
2645     }
2646 }
2647
2648 /// A draining iterator for `Vec<T>`.
2649 ///
2650 /// This `struct` is created by the [`drain`] method on [`Vec`].
2651 ///
2652 /// [`drain`]: struct.Vec.html#method.drain
2653 /// [`Vec`]: struct.Vec.html
2654 #[stable(feature = "drain", since = "1.6.0")]
2655 pub struct Drain<'a, T: 'a> {
2656     /// Index of tail to preserve
2657     tail_start: usize,
2658     /// Length of tail
2659     tail_len: usize,
2660     /// Current remaining range to remove
2661     iter: slice::Iter<'a, T>,
2662     vec: NonNull<Vec<T>>,
2663 }
2664
2665 #[stable(feature = "collection_debug", since = "1.17.0")]
2666 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2667     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2668         f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
2669     }
2670 }
2671
2672 impl<'a, T> Drain<'a, T> {
2673     /// Returns the remaining items of this iterator as a slice.
2674     ///
2675     /// # Examples
2676     ///
2677     /// ```
2678     /// # #![feature(vec_drain_as_slice)]
2679     /// let mut vec = vec!['a', 'b', 'c'];
2680     /// let mut drain = vec.drain(..);
2681     /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
2682     /// let _ = drain.next().unwrap();
2683     /// assert_eq!(drain.as_slice(), &['b', 'c']);
2684     /// ```
2685     #[unstable(feature = "vec_drain_as_slice", reason = "recently added", issue = "58957")]
2686     pub fn as_slice(&self) -> &[T] {
2687         self.iter.as_slice()
2688     }
2689 }
2690
2691 #[stable(feature = "drain", since = "1.6.0")]
2692 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2693 #[stable(feature = "drain", since = "1.6.0")]
2694 unsafe impl<T: Send> Send for Drain<'_, T> {}
2695
2696 #[stable(feature = "drain", since = "1.6.0")]
2697 impl<T> Iterator for Drain<'_, T> {
2698     type Item = T;
2699
2700     #[inline]
2701     fn next(&mut self) -> Option<T> {
2702         self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2703     }
2704
2705     fn size_hint(&self) -> (usize, Option<usize>) {
2706         self.iter.size_hint()
2707     }
2708 }
2709
2710 #[stable(feature = "drain", since = "1.6.0")]
2711 impl<T> DoubleEndedIterator for Drain<'_, T> {
2712     #[inline]
2713     fn next_back(&mut self) -> Option<T> {
2714         self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2715     }
2716 }
2717
2718 #[stable(feature = "drain", since = "1.6.0")]
2719 impl<T> Drop for Drain<'_, T> {
2720     fn drop(&mut self) {
2721         /// Continues dropping the remaining elements in the `Drain`, then moves back the
2722         /// un-`Drain`ed elements to restore the original `Vec`.
2723         struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>);
2724
2725         impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> {
2726             fn drop(&mut self) {
2727                 // Continue the same loop we have below. If the loop already finished, this does
2728                 // nothing.
2729                 self.0.for_each(drop);
2730
2731                 if self.0.tail_len > 0 {
2732                     unsafe {
2733                         let source_vec = self.0.vec.as_mut();
2734                         // memmove back untouched tail, update to new length
2735                         let start = source_vec.len();
2736                         let tail = self.0.tail_start;
2737                         if tail != start {
2738                             let src = source_vec.as_ptr().add(tail);
2739                             let dst = source_vec.as_mut_ptr().add(start);
2740                             ptr::copy(src, dst, self.0.tail_len);
2741                         }
2742                         source_vec.set_len(start + self.0.tail_len);
2743                     }
2744                 }
2745             }
2746         }
2747
2748         // exhaust self first
2749         while let Some(item) = self.next() {
2750             let guard = DropGuard(self);
2751             drop(item);
2752             mem::forget(guard);
2753         }
2754
2755         // Drop a `DropGuard` to move back the non-drained tail of `self`.
2756         DropGuard(self);
2757     }
2758 }
2759
2760 #[stable(feature = "drain", since = "1.6.0")]
2761 impl<T> ExactSizeIterator for Drain<'_, T> {
2762     fn is_empty(&self) -> bool {
2763         self.iter.is_empty()
2764     }
2765 }
2766
2767 #[unstable(feature = "trusted_len", issue = "37572")]
2768 unsafe impl<T> TrustedLen for Drain<'_, T> {}
2769
2770 #[stable(feature = "fused", since = "1.26.0")]
2771 impl<T> FusedIterator for Drain<'_, T> {}
2772
2773 /// A splicing iterator for `Vec`.
2774 ///
2775 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2776 /// documentation for more.
2777 ///
2778 /// [`splice()`]: struct.Vec.html#method.splice
2779 /// [`Vec`]: struct.Vec.html
2780 #[derive(Debug)]
2781 #[stable(feature = "vec_splice", since = "1.21.0")]
2782 pub struct Splice<'a, I: Iterator + 'a> {
2783     drain: Drain<'a, I::Item>,
2784     replace_with: I,
2785 }
2786
2787 #[stable(feature = "vec_splice", since = "1.21.0")]
2788 impl<I: Iterator> Iterator for Splice<'_, I> {
2789     type Item = I::Item;
2790
2791     fn next(&mut self) -> Option<Self::Item> {
2792         self.drain.next()
2793     }
2794
2795     fn size_hint(&self) -> (usize, Option<usize>) {
2796         self.drain.size_hint()
2797     }
2798 }
2799
2800 #[stable(feature = "vec_splice", since = "1.21.0")]
2801 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
2802     fn next_back(&mut self) -> Option<Self::Item> {
2803         self.drain.next_back()
2804     }
2805 }
2806
2807 #[stable(feature = "vec_splice", since = "1.21.0")]
2808 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
2809
2810 #[stable(feature = "vec_splice", since = "1.21.0")]
2811 impl<I: Iterator> Drop for Splice<'_, I> {
2812     fn drop(&mut self) {
2813         self.drain.by_ref().for_each(drop);
2814
2815         unsafe {
2816             if self.drain.tail_len == 0 {
2817                 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2818                 return;
2819             }
2820
2821             // First fill the range left by drain().
2822             if !self.drain.fill(&mut self.replace_with) {
2823                 return;
2824             }
2825
2826             // There may be more elements. Use the lower bound as an estimate.
2827             // FIXME: Is the upper bound a better guess? Or something else?
2828             let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2829             if lower_bound > 0 {
2830                 self.drain.move_tail(lower_bound);
2831                 if !self.drain.fill(&mut self.replace_with) {
2832                     return;
2833                 }
2834             }
2835
2836             // Collect any remaining elements.
2837             // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2838             let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2839             // Now we have an exact count.
2840             if collected.len() > 0 {
2841                 self.drain.move_tail(collected.len());
2842                 let filled = self.drain.fill(&mut collected);
2843                 debug_assert!(filled);
2844                 debug_assert_eq!(collected.len(), 0);
2845             }
2846         }
2847         // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2848     }
2849 }
2850
2851 /// Private helper methods for `Splice::drop`
2852 impl<T> Drain<'_, T> {
2853     /// The range from `self.vec.len` to `self.tail_start` contains elements
2854     /// that have been moved out.
2855     /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2856     /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2857     unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
2858         let vec = self.vec.as_mut();
2859         let range_start = vec.len;
2860         let range_end = self.tail_start;
2861         let range_slice =
2862             slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start);
2863
2864         for place in range_slice {
2865             if let Some(new_item) = replace_with.next() {
2866                 ptr::write(place, new_item);
2867                 vec.len += 1;
2868             } else {
2869                 return false;
2870             }
2871         }
2872         true
2873     }
2874
2875     /// Makes room for inserting more elements before the tail.
2876     unsafe fn move_tail(&mut self, extra_capacity: usize) {
2877         let vec = self.vec.as_mut();
2878         let used_capacity = self.tail_start + self.tail_len;
2879         vec.buf.reserve(used_capacity, extra_capacity);
2880
2881         let new_tail_start = self.tail_start + extra_capacity;
2882         let src = vec.as_ptr().add(self.tail_start);
2883         let dst = vec.as_mut_ptr().add(new_tail_start);
2884         ptr::copy(src, dst, self.tail_len);
2885         self.tail_start = new_tail_start;
2886     }
2887 }
2888
2889 /// An iterator produced by calling `drain_filter` on Vec.
2890 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2891 #[derive(Debug)]
2892 pub struct DrainFilter<'a, T, F>
2893 where
2894     F: FnMut(&mut T) -> bool,
2895 {
2896     vec: &'a mut Vec<T>,
2897     /// The index of the item that will be inspected by the next call to `next`.
2898     idx: usize,
2899     /// The number of items that have been drained (removed) thus far.
2900     del: usize,
2901     /// The original length of `vec` prior to draining.
2902     old_len: usize,
2903     /// The filter test predicate.
2904     pred: F,
2905     /// A flag that indicates a panic has occurred in the filter test prodicate.
2906     /// This is used as a hint in the drop implementation to prevent consumption
2907     /// of the remainder of the `DrainFilter`. Any unprocessed items will be
2908     /// backshifted in the `vec`, but no further items will be dropped or
2909     /// tested by the filter predicate.
2910     panic_flag: bool,
2911 }
2912
2913 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2914 impl<T, F> Iterator for DrainFilter<'_, T, F>
2915 where
2916     F: FnMut(&mut T) -> bool,
2917 {
2918     type Item = T;
2919
2920     fn next(&mut self) -> Option<T> {
2921         unsafe {
2922             while self.idx < self.old_len {
2923                 let i = self.idx;
2924                 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
2925                 self.panic_flag = true;
2926                 let drained = (self.pred)(&mut v[i]);
2927                 self.panic_flag = false;
2928                 // Update the index *after* the predicate is called. If the index
2929                 // is updated prior and the predicate panics, the element at this
2930                 // index would be leaked.
2931                 self.idx += 1;
2932                 if drained {
2933                     self.del += 1;
2934                     return Some(ptr::read(&v[i]));
2935                 } else if self.del > 0 {
2936                     let del = self.del;
2937                     let src: *const T = &v[i];
2938                     let dst: *mut T = &mut v[i - del];
2939                     ptr::copy_nonoverlapping(src, dst, 1);
2940                 }
2941             }
2942             None
2943         }
2944     }
2945
2946     fn size_hint(&self) -> (usize, Option<usize>) {
2947         (0, Some(self.old_len - self.idx))
2948     }
2949 }
2950
2951 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2952 impl<T, F> Drop for DrainFilter<'_, T, F>
2953 where
2954     F: FnMut(&mut T) -> bool,
2955 {
2956     fn drop(&mut self) {
2957         struct BackshiftOnDrop<'a, 'b, T, F>
2958         where
2959             F: FnMut(&mut T) -> bool,
2960         {
2961             drain: &'b mut DrainFilter<'a, T, F>,
2962         }
2963
2964         impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
2965         where
2966             F: FnMut(&mut T) -> bool,
2967         {
2968             fn drop(&mut self) {
2969                 unsafe {
2970                     if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
2971                         // This is a pretty messed up state, and there isn't really an
2972                         // obviously right thing to do. We don't want to keep trying
2973                         // to execute `pred`, so we just backshift all the unprocessed
2974                         // elements and tell the vec that they still exist. The backshift
2975                         // is required to prevent a double-drop of the last successfully
2976                         // drained item prior to a panic in the predicate.
2977                         let ptr = self.drain.vec.as_mut_ptr();
2978                         let src = ptr.add(self.drain.idx);
2979                         let dst = src.sub(self.drain.del);
2980                         let tail_len = self.drain.old_len - self.drain.idx;
2981                         src.copy_to(dst, tail_len);
2982                     }
2983                     self.drain.vec.set_len(self.drain.old_len - self.drain.del);
2984                 }
2985             }
2986         }
2987
2988         let backshift = BackshiftOnDrop { drain: self };
2989
2990         // Attempt to consume any remaining elements if the filter predicate
2991         // has not yet panicked. We'll backshift any remaining elements
2992         // whether we've already panicked or if the consumption here panics.
2993         if !backshift.drain.panic_flag {
2994             backshift.drain.for_each(drop);
2995         }
2996     }
2997 }