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