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