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