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