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