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