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