]> git.lizzy.rs Git - rust.git/blob - library/alloc/src/vec.rs
pin docs: add some forward references
[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         if self.capacity() != self.len {
626             self.buf.shrink_to_fit(self.len);
627         }
628     }
629
630     /// Shrinks the capacity of the vector with a lower bound.
631     ///
632     /// The capacity will remain at least as large as both the length
633     /// and the supplied value.
634     ///
635     /// # Panics
636     ///
637     /// Panics if the current capacity is smaller than the supplied
638     /// minimum capacity.
639     ///
640     /// # Examples
641     ///
642     /// ```
643     /// #![feature(shrink_to)]
644     /// let mut vec = Vec::with_capacity(10);
645     /// vec.extend([1, 2, 3].iter().cloned());
646     /// assert_eq!(vec.capacity(), 10);
647     /// vec.shrink_to(4);
648     /// assert!(vec.capacity() >= 4);
649     /// vec.shrink_to(0);
650     /// assert!(vec.capacity() >= 3);
651     /// ```
652     #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
653     pub fn shrink_to(&mut self, min_capacity: usize) {
654         self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
655     }
656
657     /// Converts the vector into [`Box<[T]>`][owned slice].
658     ///
659     /// Note that this will drop any excess capacity.
660     ///
661     /// [owned slice]: ../../std/boxed/struct.Box.html
662     ///
663     /// # Examples
664     ///
665     /// ```
666     /// let v = vec![1, 2, 3];
667     ///
668     /// let slice = v.into_boxed_slice();
669     /// ```
670     ///
671     /// Any excess capacity is removed:
672     ///
673     /// ```
674     /// let mut vec = Vec::with_capacity(10);
675     /// vec.extend([1, 2, 3].iter().cloned());
676     ///
677     /// assert_eq!(vec.capacity(), 10);
678     /// let slice = vec.into_boxed_slice();
679     /// assert_eq!(slice.into_vec().capacity(), 3);
680     /// ```
681     #[stable(feature = "rust1", since = "1.0.0")]
682     pub fn into_boxed_slice(mut self) -> Box<[T]> {
683         unsafe {
684             self.shrink_to_fit();
685             let me = ManuallyDrop::new(self);
686             let buf = ptr::read(&me.buf);
687             let len = me.len();
688             buf.into_box(len).assume_init()
689         }
690     }
691
692     /// Shortens the vector, keeping the first `len` elements and dropping
693     /// the rest.
694     ///
695     /// If `len` is greater than the vector's current length, this has no
696     /// effect.
697     ///
698     /// The [`drain`] method can emulate `truncate`, but causes the excess
699     /// elements to be returned instead of dropped.
700     ///
701     /// Note that this method has no effect on the allocated capacity
702     /// of the vector.
703     ///
704     /// # Examples
705     ///
706     /// Truncating a five element vector to two elements:
707     ///
708     /// ```
709     /// let mut vec = vec![1, 2, 3, 4, 5];
710     /// vec.truncate(2);
711     /// assert_eq!(vec, [1, 2]);
712     /// ```
713     ///
714     /// No truncation occurs when `len` is greater than the vector's current
715     /// length:
716     ///
717     /// ```
718     /// let mut vec = vec![1, 2, 3];
719     /// vec.truncate(8);
720     /// assert_eq!(vec, [1, 2, 3]);
721     /// ```
722     ///
723     /// Truncating when `len == 0` is equivalent to calling the [`clear`]
724     /// method.
725     ///
726     /// ```
727     /// let mut vec = vec![1, 2, 3];
728     /// vec.truncate(0);
729     /// assert_eq!(vec, []);
730     /// ```
731     ///
732     /// [`clear`]: #method.clear
733     /// [`drain`]: #method.drain
734     #[stable(feature = "rust1", since = "1.0.0")]
735     pub fn truncate(&mut self, len: usize) {
736         // This is safe because:
737         //
738         // * the slice passed to `drop_in_place` is valid; the `len > self.len`
739         //   case avoids creating an invalid slice, and
740         // * the `len` of the vector is shrunk before calling `drop_in_place`,
741         //   such that no value will be dropped twice in case `drop_in_place`
742         //   were to panic once (if it panics twice, the program aborts).
743         unsafe {
744             if len > self.len {
745                 return;
746             }
747             let remaining_len = self.len - len;
748             let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
749             self.len = len;
750             ptr::drop_in_place(s);
751         }
752     }
753
754     /// Extracts a slice containing the entire vector.
755     ///
756     /// Equivalent to `&s[..]`.
757     ///
758     /// # Examples
759     ///
760     /// ```
761     /// use std::io::{self, Write};
762     /// let buffer = vec![1, 2, 3, 5, 8];
763     /// io::sink().write(buffer.as_slice()).unwrap();
764     /// ```
765     #[inline]
766     #[stable(feature = "vec_as_slice", since = "1.7.0")]
767     pub fn as_slice(&self) -> &[T] {
768         self
769     }
770
771     /// Extracts a mutable slice of the entire vector.
772     ///
773     /// Equivalent to `&mut s[..]`.
774     ///
775     /// # Examples
776     ///
777     /// ```
778     /// use std::io::{self, Read};
779     /// let mut buffer = vec![0; 3];
780     /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
781     /// ```
782     #[inline]
783     #[stable(feature = "vec_as_slice", since = "1.7.0")]
784     pub fn as_mut_slice(&mut self) -> &mut [T] {
785         self
786     }
787
788     /// Returns a raw pointer to the vector's buffer.
789     ///
790     /// The caller must ensure that the vector outlives the pointer this
791     /// function returns, or else it will end up pointing to garbage.
792     /// Modifying the vector may cause its buffer to be reallocated,
793     /// which would also make any pointers to it invalid.
794     ///
795     /// The caller must also ensure that the memory the pointer (non-transitively) points to
796     /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
797     /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
798     ///
799     /// # Examples
800     ///
801     /// ```
802     /// let x = vec![1, 2, 4];
803     /// let x_ptr = x.as_ptr();
804     ///
805     /// unsafe {
806     ///     for i in 0..x.len() {
807     ///         assert_eq!(*x_ptr.add(i), 1 << i);
808     ///     }
809     /// }
810     /// ```
811     ///
812     /// [`as_mut_ptr`]: #method.as_mut_ptr
813     #[stable(feature = "vec_as_ptr", since = "1.37.0")]
814     #[inline]
815     pub fn as_ptr(&self) -> *const T {
816         // We shadow the slice method of the same name to avoid going through
817         // `deref`, which creates an intermediate reference.
818         let ptr = self.buf.ptr();
819         unsafe {
820             assume(!ptr.is_null());
821         }
822         ptr
823     }
824
825     /// Returns an unsafe mutable pointer to the vector's buffer.
826     ///
827     /// The caller must ensure that the vector outlives the pointer this
828     /// function returns, or else it will end up pointing to garbage.
829     /// Modifying the vector may cause its buffer to be reallocated,
830     /// which would also make any pointers to it invalid.
831     ///
832     /// # Examples
833     ///
834     /// ```
835     /// // Allocate vector big enough for 4 elements.
836     /// let size = 4;
837     /// let mut x: Vec<i32> = Vec::with_capacity(size);
838     /// let x_ptr = x.as_mut_ptr();
839     ///
840     /// // Initialize elements via raw pointer writes, then set length.
841     /// unsafe {
842     ///     for i in 0..size {
843     ///         *x_ptr.add(i) = i as i32;
844     ///     }
845     ///     x.set_len(size);
846     /// }
847     /// assert_eq!(&*x, &[0,1,2,3]);
848     /// ```
849     #[stable(feature = "vec_as_ptr", since = "1.37.0")]
850     #[inline]
851     pub fn as_mut_ptr(&mut self) -> *mut T {
852         // We shadow the slice method of the same name to avoid going through
853         // `deref_mut`, which creates an intermediate reference.
854         let ptr = self.buf.ptr();
855         unsafe {
856             assume(!ptr.is_null());
857         }
858         ptr
859     }
860
861     /// Forces the length of the vector to `new_len`.
862     ///
863     /// This is a low-level operation that maintains none of the normal
864     /// invariants of the type. Normally changing the length of a vector
865     /// is done using one of the safe operations instead, such as
866     /// [`truncate`], [`resize`], [`extend`], or [`clear`].
867     ///
868     /// [`truncate`]: #method.truncate
869     /// [`resize`]: #method.resize
870     /// [`extend`]: ../../std/iter/trait.Extend.html#tymethod.extend
871     /// [`clear`]: #method.clear
872     ///
873     /// # Safety
874     ///
875     /// - `new_len` must be less than or equal to [`capacity()`].
876     /// - The elements at `old_len..new_len` must be initialized.
877     ///
878     /// [`capacity()`]: #method.capacity
879     ///
880     /// # Examples
881     ///
882     /// This method can be useful for situations in which the vector
883     /// is serving as a buffer for other code, particularly over FFI:
884     ///
885     /// ```no_run
886     /// # #![allow(dead_code)]
887     /// # // This is just a minimal skeleton for the doc example;
888     /// # // don't use this as a starting point for a real library.
889     /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
890     /// # const Z_OK: i32 = 0;
891     /// # extern "C" {
892     /// #     fn deflateGetDictionary(
893     /// #         strm: *mut std::ffi::c_void,
894     /// #         dictionary: *mut u8,
895     /// #         dictLength: *mut usize,
896     /// #     ) -> i32;
897     /// # }
898     /// # impl StreamWrapper {
899     /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
900     ///     // Per the FFI method's docs, "32768 bytes is always enough".
901     ///     let mut dict = Vec::with_capacity(32_768);
902     ///     let mut dict_length = 0;
903     ///     // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
904     ///     // 1. `dict_length` elements were initialized.
905     ///     // 2. `dict_length` <= the capacity (32_768)
906     ///     // which makes `set_len` safe to call.
907     ///     unsafe {
908     ///         // Make the FFI call...
909     ///         let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
910     ///         if r == Z_OK {
911     ///             // ...and update the length to what was initialized.
912     ///             dict.set_len(dict_length);
913     ///             Some(dict)
914     ///         } else {
915     ///             None
916     ///         }
917     ///     }
918     /// }
919     /// # }
920     /// ```
921     ///
922     /// While the following example is sound, there is a memory leak since
923     /// the inner vectors were not freed prior to the `set_len` call:
924     ///
925     /// ```
926     /// let mut vec = vec![vec![1, 0, 0],
927     ///                    vec![0, 1, 0],
928     ///                    vec![0, 0, 1]];
929     /// // SAFETY:
930     /// // 1. `old_len..0` is empty so no elements need to be initialized.
931     /// // 2. `0 <= capacity` always holds whatever `capacity` is.
932     /// unsafe {
933     ///     vec.set_len(0);
934     /// }
935     /// ```
936     ///
937     /// Normally, here, one would use [`clear`] instead to correctly drop
938     /// the contents and thus not leak memory.
939     #[inline]
940     #[stable(feature = "rust1", since = "1.0.0")]
941     pub unsafe fn set_len(&mut self, new_len: usize) {
942         debug_assert!(new_len <= self.capacity());
943
944         self.len = new_len;
945     }
946
947     /// Removes an element from the vector and returns it.
948     ///
949     /// The removed element is replaced by the last element of the vector.
950     ///
951     /// This does not preserve ordering, but is O(1).
952     ///
953     /// # Panics
954     ///
955     /// Panics if `index` is out of bounds.
956     ///
957     /// # Examples
958     ///
959     /// ```
960     /// let mut v = vec!["foo", "bar", "baz", "qux"];
961     ///
962     /// assert_eq!(v.swap_remove(1), "bar");
963     /// assert_eq!(v, ["foo", "qux", "baz"]);
964     ///
965     /// assert_eq!(v.swap_remove(0), "foo");
966     /// assert_eq!(v, ["baz", "qux"]);
967     /// ```
968     #[inline]
969     #[stable(feature = "rust1", since = "1.0.0")]
970     pub fn swap_remove(&mut self, index: usize) -> T {
971         #[cold]
972         #[inline(never)]
973         fn assert_failed(index: usize, len: usize) -> ! {
974             panic!("swap_remove index (is {}) should be < len (is {})", index, len);
975         }
976
977         let len = self.len();
978         if index >= len {
979             assert_failed(index, len);
980         }
981         unsafe {
982             // We replace self[index] with the last element. Note that if the
983             // bounds check above succeeds there must be a last element (which
984             // can be self[index] itself).
985             let last = ptr::read(self.as_ptr().add(len - 1));
986             let hole = self.as_mut_ptr().add(index);
987             self.set_len(len - 1);
988             ptr::replace(hole, last)
989         }
990     }
991
992     /// Inserts an element at position `index` within the vector, shifting all
993     /// elements after it to the right.
994     ///
995     /// # Panics
996     ///
997     /// Panics if `index > len`.
998     ///
999     /// # Examples
1000     ///
1001     /// ```
1002     /// let mut vec = vec![1, 2, 3];
1003     /// vec.insert(1, 4);
1004     /// assert_eq!(vec, [1, 4, 2, 3]);
1005     /// vec.insert(4, 5);
1006     /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1007     /// ```
1008     #[stable(feature = "rust1", since = "1.0.0")]
1009     pub fn insert(&mut self, index: usize, element: T) {
1010         #[cold]
1011         #[inline(never)]
1012         fn assert_failed(index: usize, len: usize) -> ! {
1013             panic!("insertion index (is {}) should be <= len (is {})", index, len);
1014         }
1015
1016         let len = self.len();
1017         if index > len {
1018             assert_failed(index, len);
1019         }
1020
1021         // space for the new element
1022         if len == self.buf.capacity() {
1023             self.reserve(1);
1024         }
1025
1026         unsafe {
1027             // infallible
1028             // The spot to put the new value
1029             {
1030                 let p = self.as_mut_ptr().add(index);
1031                 // Shift everything over to make space. (Duplicating the
1032                 // `index`th element into two consecutive places.)
1033                 ptr::copy(p, p.offset(1), len - index);
1034                 // Write it in, overwriting the first copy of the `index`th
1035                 // element.
1036                 ptr::write(p, element);
1037             }
1038             self.set_len(len + 1);
1039         }
1040     }
1041
1042     /// Removes and returns the element at position `index` within the vector,
1043     /// shifting all elements after it to the left.
1044     ///
1045     /// # Panics
1046     ///
1047     /// Panics if `index` is out of bounds.
1048     ///
1049     /// # Examples
1050     ///
1051     /// ```
1052     /// let mut v = vec![1, 2, 3];
1053     /// assert_eq!(v.remove(1), 2);
1054     /// assert_eq!(v, [1, 3]);
1055     /// ```
1056     #[stable(feature = "rust1", since = "1.0.0")]
1057     pub fn remove(&mut self, index: usize) -> T {
1058         #[cold]
1059         #[inline(never)]
1060         fn assert_failed(index: usize, len: usize) -> ! {
1061             panic!("removal index (is {}) should be < len (is {})", index, len);
1062         }
1063
1064         let len = self.len();
1065         if index >= len {
1066             assert_failed(index, len);
1067         }
1068         unsafe {
1069             // infallible
1070             let ret;
1071             {
1072                 // the place we are taking from.
1073                 let ptr = self.as_mut_ptr().add(index);
1074                 // copy it out, unsafely having a copy of the value on
1075                 // the stack and in the vector at the same time.
1076                 ret = ptr::read(ptr);
1077
1078                 // Shift everything down to fill in that spot.
1079                 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1080             }
1081             self.set_len(len - 1);
1082             ret
1083         }
1084     }
1085
1086     /// Retains only the elements specified by the predicate.
1087     ///
1088     /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1089     /// This method operates in place, visiting each element exactly once in the
1090     /// original order, and preserves the order of the retained elements.
1091     ///
1092     /// # Examples
1093     ///
1094     /// ```
1095     /// let mut vec = vec![1, 2, 3, 4];
1096     /// vec.retain(|&x| x % 2 == 0);
1097     /// assert_eq!(vec, [2, 4]);
1098     /// ```
1099     ///
1100     /// The exact order may be useful for tracking external state, like an index.
1101     ///
1102     /// ```
1103     /// let mut vec = vec![1, 2, 3, 4, 5];
1104     /// let keep = [false, true, true, false, true];
1105     /// let mut i = 0;
1106     /// vec.retain(|_| (keep[i], i += 1).0);
1107     /// assert_eq!(vec, [2, 3, 5]);
1108     /// ```
1109     #[stable(feature = "rust1", since = "1.0.0")]
1110     pub fn retain<F>(&mut self, mut f: F)
1111     where
1112         F: FnMut(&T) -> bool,
1113     {
1114         let len = self.len();
1115         let mut del = 0;
1116         {
1117             let v = &mut **self;
1118
1119             for i in 0..len {
1120                 if !f(&v[i]) {
1121                     del += 1;
1122                 } else if del > 0 {
1123                     v.swap(i - del, i);
1124                 }
1125             }
1126         }
1127         if del > 0 {
1128             self.truncate(len - del);
1129         }
1130     }
1131
1132     /// Removes all but the first of consecutive elements in the vector that resolve to the same
1133     /// key.
1134     ///
1135     /// If the vector is sorted, this removes all duplicates.
1136     ///
1137     /// # Examples
1138     ///
1139     /// ```
1140     /// let mut vec = vec![10, 20, 21, 30, 20];
1141     ///
1142     /// vec.dedup_by_key(|i| *i / 10);
1143     ///
1144     /// assert_eq!(vec, [10, 20, 30, 20]);
1145     /// ```
1146     #[stable(feature = "dedup_by", since = "1.16.0")]
1147     #[inline]
1148     pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1149     where
1150         F: FnMut(&mut T) -> K,
1151         K: PartialEq,
1152     {
1153         self.dedup_by(|a, b| key(a) == key(b))
1154     }
1155
1156     /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1157     /// relation.
1158     ///
1159     /// The `same_bucket` function is passed references to two elements from the vector and
1160     /// must determine if the elements compare equal. The elements are passed in opposite order
1161     /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1162     ///
1163     /// If the vector is sorted, this removes all duplicates.
1164     ///
1165     /// # Examples
1166     ///
1167     /// ```
1168     /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1169     ///
1170     /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1171     ///
1172     /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1173     /// ```
1174     #[stable(feature = "dedup_by", since = "1.16.0")]
1175     pub fn dedup_by<F>(&mut self, same_bucket: F)
1176     where
1177         F: FnMut(&mut T, &mut T) -> bool,
1178     {
1179         let len = {
1180             let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1181             dedup.len()
1182         };
1183         self.truncate(len);
1184     }
1185
1186     /// Appends an element to the back of a collection.
1187     ///
1188     /// # Panics
1189     ///
1190     /// Panics if the new capacity exceeds `isize::MAX` bytes.
1191     ///
1192     /// # Examples
1193     ///
1194     /// ```
1195     /// let mut vec = vec![1, 2];
1196     /// vec.push(3);
1197     /// assert_eq!(vec, [1, 2, 3]);
1198     /// ```
1199     #[inline]
1200     #[stable(feature = "rust1", since = "1.0.0")]
1201     pub fn push(&mut self, value: T) {
1202         // This will panic or abort if we would allocate > isize::MAX bytes
1203         // or if the length increment would overflow for zero-sized types.
1204         if self.len == self.buf.capacity() {
1205             self.reserve(1);
1206         }
1207         unsafe {
1208             let end = self.as_mut_ptr().add(self.len);
1209             ptr::write(end, value);
1210             self.len += 1;
1211         }
1212     }
1213
1214     /// Removes the last element from a vector and returns it, or [`None`] if it
1215     /// is empty.
1216     ///
1217     /// [`None`]: ../../std/option/enum.Option.html#variant.None
1218     ///
1219     /// # Examples
1220     ///
1221     /// ```
1222     /// let mut vec = vec![1, 2, 3];
1223     /// assert_eq!(vec.pop(), Some(3));
1224     /// assert_eq!(vec, [1, 2]);
1225     /// ```
1226     #[inline]
1227     #[stable(feature = "rust1", since = "1.0.0")]
1228     pub fn pop(&mut self) -> Option<T> {
1229         if self.len == 0 {
1230             None
1231         } else {
1232             unsafe {
1233                 self.len -= 1;
1234                 Some(ptr::read(self.as_ptr().add(self.len())))
1235             }
1236         }
1237     }
1238
1239     /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1240     ///
1241     /// # Panics
1242     ///
1243     /// Panics if the number of elements in the vector overflows a `usize`.
1244     ///
1245     /// # Examples
1246     ///
1247     /// ```
1248     /// let mut vec = vec![1, 2, 3];
1249     /// let mut vec2 = vec![4, 5, 6];
1250     /// vec.append(&mut vec2);
1251     /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1252     /// assert_eq!(vec2, []);
1253     /// ```
1254     #[inline]
1255     #[stable(feature = "append", since = "1.4.0")]
1256     pub fn append(&mut self, other: &mut Self) {
1257         unsafe {
1258             self.append_elements(other.as_slice() as _);
1259             other.set_len(0);
1260         }
1261     }
1262
1263     /// Appends elements to `Self` from other buffer.
1264     #[inline]
1265     unsafe fn append_elements(&mut self, other: *const [T]) {
1266         let count = unsafe { (*other).len() };
1267         self.reserve(count);
1268         let len = self.len();
1269         unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1270         self.len += count;
1271     }
1272
1273     /// Creates a draining iterator that removes the specified range in the vector
1274     /// and yields the removed items.
1275     ///
1276     /// When the iterator **is** dropped, all elements in the range are removed
1277     /// from the vector, even if the iterator was not fully consumed. If the
1278     /// iterator **is not** dropped (with [`mem::forget`] for example), it is
1279     /// unspecified how many elements are removed.
1280     ///
1281     /// # Panics
1282     ///
1283     /// Panics if the starting point is greater than the end point or if
1284     /// the end point is greater than the length of the vector.
1285     ///
1286     /// # Examples
1287     ///
1288     /// ```
1289     /// let mut v = vec![1, 2, 3];
1290     /// let u: Vec<_> = v.drain(1..).collect();
1291     /// assert_eq!(v, &[1]);
1292     /// assert_eq!(u, &[2, 3]);
1293     ///
1294     /// // A full range clears the vector
1295     /// v.drain(..);
1296     /// assert_eq!(v, &[]);
1297     /// ```
1298     #[stable(feature = "drain", since = "1.6.0")]
1299     pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1300     where
1301         R: RangeBounds<usize>,
1302     {
1303         // Memory safety
1304         //
1305         // When the Drain is first created, it shortens the length of
1306         // the source vector to make sure no uninitialized or moved-from elements
1307         // are accessible at all if the Drain's destructor never gets to run.
1308         //
1309         // Drain will ptr::read out the values to remove.
1310         // When finished, remaining tail of the vec is copied back to cover
1311         // the hole, and the vector length is restored to the new length.
1312         //
1313         let len = self.len();
1314         let start = match range.start_bound() {
1315             Included(&n) => n,
1316             Excluded(&n) => n + 1,
1317             Unbounded => 0,
1318         };
1319         let end = match range.end_bound() {
1320             Included(&n) => n + 1,
1321             Excluded(&n) => n,
1322             Unbounded => len,
1323         };
1324
1325         #[cold]
1326         #[inline(never)]
1327         fn start_assert_failed(start: usize, end: usize) -> ! {
1328             panic!("start drain index (is {}) should be <= end drain index (is {})", start, end);
1329         }
1330
1331         #[cold]
1332         #[inline(never)]
1333         fn end_assert_failed(end: usize, len: usize) -> ! {
1334             panic!("end drain index (is {}) should be <= len (is {})", end, len);
1335         }
1336
1337         if start > end {
1338             start_assert_failed(start, end);
1339         }
1340         if end > len {
1341             end_assert_failed(end, len);
1342         }
1343
1344         unsafe {
1345             // set self.vec length's to start, to be safe in case Drain is leaked
1346             self.set_len(start);
1347             // Use the borrow in the IterMut to indicate borrowing behavior of the
1348             // whole Drain iterator (like &mut T).
1349             let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1350             Drain {
1351                 tail_start: end,
1352                 tail_len: len - end,
1353                 iter: range_slice.iter(),
1354                 vec: NonNull::from(self),
1355             }
1356         }
1357     }
1358
1359     /// Clears the vector, removing all values.
1360     ///
1361     /// Note that this method has no effect on the allocated capacity
1362     /// of the vector.
1363     ///
1364     /// # Examples
1365     ///
1366     /// ```
1367     /// let mut v = vec![1, 2, 3];
1368     ///
1369     /// v.clear();
1370     ///
1371     /// assert!(v.is_empty());
1372     /// ```
1373     #[inline]
1374     #[stable(feature = "rust1", since = "1.0.0")]
1375     pub fn clear(&mut self) {
1376         self.truncate(0)
1377     }
1378
1379     /// Returns the number of elements in the vector, also referred to
1380     /// as its 'length'.
1381     ///
1382     /// # Examples
1383     ///
1384     /// ```
1385     /// let a = vec![1, 2, 3];
1386     /// assert_eq!(a.len(), 3);
1387     /// ```
1388     #[inline]
1389     #[stable(feature = "rust1", since = "1.0.0")]
1390     pub fn len(&self) -> usize {
1391         self.len
1392     }
1393
1394     /// Returns `true` if the vector contains no elements.
1395     ///
1396     /// # Examples
1397     ///
1398     /// ```
1399     /// let mut v = Vec::new();
1400     /// assert!(v.is_empty());
1401     ///
1402     /// v.push(1);
1403     /// assert!(!v.is_empty());
1404     /// ```
1405     #[stable(feature = "rust1", since = "1.0.0")]
1406     pub fn is_empty(&self) -> bool {
1407         self.len() == 0
1408     }
1409
1410     /// Splits the collection into two at the given index.
1411     ///
1412     /// Returns a newly allocated vector containing the elements in the range
1413     /// `[at, len)`. After the call, the original vector will be left containing
1414     /// the elements `[0, at)` with its previous capacity unchanged.
1415     ///
1416     /// # Panics
1417     ///
1418     /// Panics if `at > len`.
1419     ///
1420     /// # Examples
1421     ///
1422     /// ```
1423     /// let mut vec = vec![1,2,3];
1424     /// let vec2 = vec.split_off(1);
1425     /// assert_eq!(vec, [1]);
1426     /// assert_eq!(vec2, [2, 3]);
1427     /// ```
1428     #[inline]
1429     #[must_use = "use `.truncate()` if you don't need the other half"]
1430     #[stable(feature = "split_off", since = "1.4.0")]
1431     pub fn split_off(&mut self, at: usize) -> Self {
1432         #[cold]
1433         #[inline(never)]
1434         fn assert_failed(at: usize, len: usize) -> ! {
1435             panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1436         }
1437
1438         if at > self.len() {
1439             assert_failed(at, self.len());
1440         }
1441
1442         let other_len = self.len - at;
1443         let mut other = Vec::with_capacity(other_len);
1444
1445         // Unsafely `set_len` and copy items to `other`.
1446         unsafe {
1447             self.set_len(at);
1448             other.set_len(other_len);
1449
1450             ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1451         }
1452         other
1453     }
1454
1455     /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1456     ///
1457     /// If `new_len` is greater than `len`, the `Vec` is extended by the
1458     /// difference, with each additional slot filled with the result of
1459     /// calling the closure `f`. The return values from `f` will end up
1460     /// in the `Vec` in the order they have been generated.
1461     ///
1462     /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1463     ///
1464     /// This method uses a closure to create new values on every push. If
1465     /// you'd rather [`Clone`] a given value, use [`resize`]. If you want
1466     /// to use the [`Default`] trait to generate values, you can pass
1467     /// [`Default::default()`] as the second argument.
1468     ///
1469     /// # Examples
1470     ///
1471     /// ```
1472     /// let mut vec = vec![1, 2, 3];
1473     /// vec.resize_with(5, Default::default);
1474     /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1475     ///
1476     /// let mut vec = vec![];
1477     /// let mut p = 1;
1478     /// vec.resize_with(4, || { p *= 2; p });
1479     /// assert_eq!(vec, [2, 4, 8, 16]);
1480     /// ```
1481     ///
1482     /// [`resize`]: #method.resize
1483     /// [`Clone`]: ../../std/clone/trait.Clone.html
1484     #[stable(feature = "vec_resize_with", since = "1.33.0")]
1485     pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1486     where
1487         F: FnMut() -> T,
1488     {
1489         let len = self.len();
1490         if new_len > len {
1491             self.extend_with(new_len - len, ExtendFunc(f));
1492         } else {
1493             self.truncate(new_len);
1494         }
1495     }
1496
1497     /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1498     /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1499     /// `'a`. If the type has only static references, or none at all, then this
1500     /// may be chosen to be `'static`.
1501     ///
1502     /// This function is similar to the `leak` function on `Box`.
1503     ///
1504     /// This function is mainly useful for data that lives for the remainder of
1505     /// the program's life. Dropping the returned reference will cause a memory
1506     /// leak.
1507     ///
1508     /// # Examples
1509     ///
1510     /// Simple usage:
1511     ///
1512     /// ```
1513     /// let x = vec![1, 2, 3];
1514     /// let static_ref: &'static mut [usize] = x.leak();
1515     /// static_ref[0] += 1;
1516     /// assert_eq!(static_ref, &[2, 2, 3]);
1517     /// ```
1518     #[stable(feature = "vec_leak", since = "1.47.0")]
1519     #[inline]
1520     pub fn leak<'a>(self) -> &'a mut [T]
1521     where
1522         T: 'a, // Technically not needed, but kept to be explicit.
1523     {
1524         Box::leak(self.into_boxed_slice())
1525     }
1526
1527     /// Returns the remaining spare capacity of the vector as a slice of
1528     /// `MaybeUninit<T>`.
1529     ///
1530     /// The returned slice can be used to fill the vector with data (e.g. by
1531     /// reading from a file) before marking the data as initialized using the
1532     /// [`set_len`] method.
1533     ///
1534     /// [`set_len`]: #method.set_len
1535     ///
1536     /// # Examples
1537     ///
1538     /// ```
1539     /// #![feature(vec_spare_capacity, maybe_uninit_extra)]
1540     ///
1541     /// // Allocate vector big enough for 10 elements.
1542     /// let mut v = Vec::with_capacity(10);
1543     ///
1544     /// // Fill in the first 3 elements.
1545     /// let uninit = v.spare_capacity_mut();
1546     /// uninit[0].write(0);
1547     /// uninit[1].write(1);
1548     /// uninit[2].write(2);
1549     ///
1550     /// // Mark the first 3 elements of the vector as being initialized.
1551     /// unsafe {
1552     ///     v.set_len(3);
1553     /// }
1554     ///
1555     /// assert_eq!(&v, &[0, 1, 2]);
1556     /// ```
1557     #[unstable(feature = "vec_spare_capacity", issue = "75017")]
1558     #[inline]
1559     pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1560         unsafe {
1561             slice::from_raw_parts_mut(
1562                 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
1563                 self.buf.capacity() - self.len,
1564             )
1565         }
1566     }
1567 }
1568
1569 impl<T: Clone> Vec<T> {
1570     /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1571     ///
1572     /// If `new_len` is greater than `len`, the `Vec` is extended by the
1573     /// difference, with each additional slot filled with `value`.
1574     /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1575     ///
1576     /// This method requires `T` to implement [`Clone`],
1577     /// in order to be able to clone the passed value.
1578     /// If you need more flexibility (or want to rely on [`Default`] instead of
1579     /// [`Clone`]), use [`resize_with`].
1580     ///
1581     /// # Examples
1582     ///
1583     /// ```
1584     /// let mut vec = vec!["hello"];
1585     /// vec.resize(3, "world");
1586     /// assert_eq!(vec, ["hello", "world", "world"]);
1587     ///
1588     /// let mut vec = vec![1, 2, 3, 4];
1589     /// vec.resize(2, 0);
1590     /// assert_eq!(vec, [1, 2]);
1591     /// ```
1592     ///
1593     /// [`Clone`]: ../../std/clone/trait.Clone.html
1594     /// [`Default`]: ../../std/default/trait.Default.html
1595     /// [`resize_with`]: #method.resize_with
1596     #[stable(feature = "vec_resize", since = "1.5.0")]
1597     pub fn resize(&mut self, new_len: usize, value: T) {
1598         let len = self.len();
1599
1600         if new_len > len {
1601             self.extend_with(new_len - len, ExtendElement(value))
1602         } else {
1603             self.truncate(new_len);
1604         }
1605     }
1606
1607     /// Clones and appends all elements in a slice to the `Vec`.
1608     ///
1609     /// Iterates over the slice `other`, clones each element, and then appends
1610     /// it to this `Vec`. The `other` vector is traversed in-order.
1611     ///
1612     /// Note that this function is same as [`extend`] except that it is
1613     /// specialized to work with slices instead. If and when Rust gets
1614     /// specialization this function will likely be deprecated (but still
1615     /// available).
1616     ///
1617     /// # Examples
1618     ///
1619     /// ```
1620     /// let mut vec = vec![1];
1621     /// vec.extend_from_slice(&[2, 3, 4]);
1622     /// assert_eq!(vec, [1, 2, 3, 4]);
1623     /// ```
1624     ///
1625     /// [`extend`]: #method.extend
1626     #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1627     pub fn extend_from_slice(&mut self, other: &[T]) {
1628         self.spec_extend(other.iter())
1629     }
1630 }
1631
1632 impl<T: Default> Vec<T> {
1633     /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1634     ///
1635     /// If `new_len` is greater than `len`, the `Vec` is extended by the
1636     /// difference, with each additional slot filled with [`Default::default()`].
1637     /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1638     ///
1639     /// This method uses [`Default`] to create new values on every push. If
1640     /// you'd rather [`Clone`] a given value, use [`resize`].
1641     ///
1642     /// # Examples
1643     ///
1644     /// ```
1645     /// # #![allow(deprecated)]
1646     /// #![feature(vec_resize_default)]
1647     ///
1648     /// let mut vec = vec![1, 2, 3];
1649     /// vec.resize_default(5);
1650     /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1651     ///
1652     /// let mut vec = vec![1, 2, 3, 4];
1653     /// vec.resize_default(2);
1654     /// assert_eq!(vec, [1, 2]);
1655     /// ```
1656     ///
1657     /// [`resize`]: #method.resize
1658     /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default
1659     /// [`Default`]: ../../std/default/trait.Default.html
1660     /// [`Clone`]: ../../std/clone/trait.Clone.html
1661     #[unstable(feature = "vec_resize_default", issue = "41758")]
1662     #[rustc_deprecated(
1663         reason = "This is moving towards being removed in favor \
1664                   of `.resize_with(Default::default)`.  If you disagree, please comment \
1665                   in the tracking issue.",
1666         since = "1.33.0"
1667     )]
1668     pub fn resize_default(&mut self, new_len: usize) {
1669         let len = self.len();
1670
1671         if new_len > len {
1672             self.extend_with(new_len - len, ExtendDefault);
1673         } else {
1674             self.truncate(new_len);
1675         }
1676     }
1677 }
1678
1679 // This code generalizes `extend_with_{element,default}`.
1680 trait ExtendWith<T> {
1681     fn next(&mut self) -> T;
1682     fn last(self) -> T;
1683 }
1684
1685 struct ExtendElement<T>(T);
1686 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1687     fn next(&mut self) -> T {
1688         self.0.clone()
1689     }
1690     fn last(self) -> T {
1691         self.0
1692     }
1693 }
1694
1695 struct ExtendDefault;
1696 impl<T: Default> ExtendWith<T> for ExtendDefault {
1697     fn next(&mut self) -> T {
1698         Default::default()
1699     }
1700     fn last(self) -> T {
1701         Default::default()
1702     }
1703 }
1704
1705 struct ExtendFunc<F>(F);
1706 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1707     fn next(&mut self) -> T {
1708         (self.0)()
1709     }
1710     fn last(mut self) -> T {
1711         (self.0)()
1712     }
1713 }
1714
1715 impl<T> Vec<T> {
1716     /// Extend the vector by `n` values, using the given generator.
1717     fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1718         self.reserve(n);
1719
1720         unsafe {
1721             let mut ptr = self.as_mut_ptr().add(self.len());
1722             // Use SetLenOnDrop to work around bug where compiler
1723             // may not realize the store through `ptr` through self.set_len()
1724             // don't alias.
1725             let mut local_len = SetLenOnDrop::new(&mut self.len);
1726
1727             // Write all elements except the last one
1728             for _ in 1..n {
1729                 ptr::write(ptr, value.next());
1730                 ptr = ptr.offset(1);
1731                 // Increment the length in every step in case next() panics
1732                 local_len.increment_len(1);
1733             }
1734
1735             if n > 0 {
1736                 // We can write the last element directly without cloning needlessly
1737                 ptr::write(ptr, value.last());
1738                 local_len.increment_len(1);
1739             }
1740
1741             // len set by scope guard
1742         }
1743     }
1744 }
1745
1746 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1747 //
1748 // The idea is: The length field in SetLenOnDrop is a local variable
1749 // that the optimizer will see does not alias with any stores through the Vec's data
1750 // pointer. This is a workaround for alias analysis issue #32155
1751 struct SetLenOnDrop<'a> {
1752     len: &'a mut usize,
1753     local_len: usize,
1754 }
1755
1756 impl<'a> SetLenOnDrop<'a> {
1757     #[inline]
1758     fn new(len: &'a mut usize) -> Self {
1759         SetLenOnDrop { local_len: *len, len }
1760     }
1761
1762     #[inline]
1763     fn increment_len(&mut self, increment: usize) {
1764         self.local_len += increment;
1765     }
1766 }
1767
1768 impl Drop for SetLenOnDrop<'_> {
1769     #[inline]
1770     fn drop(&mut self) {
1771         *self.len = self.local_len;
1772     }
1773 }
1774
1775 impl<T: PartialEq> Vec<T> {
1776     /// Removes consecutive repeated elements in the vector according to the
1777     /// [`PartialEq`] trait implementation.
1778     ///
1779     /// If the vector is sorted, this removes all duplicates.
1780     ///
1781     /// # Examples
1782     ///
1783     /// ```
1784     /// let mut vec = vec![1, 2, 2, 3, 2];
1785     ///
1786     /// vec.dedup();
1787     ///
1788     /// assert_eq!(vec, [1, 2, 3, 2]);
1789     /// ```
1790     #[stable(feature = "rust1", since = "1.0.0")]
1791     #[inline]
1792     pub fn dedup(&mut self) {
1793         self.dedup_by(|a, b| a == b)
1794     }
1795 }
1796
1797 impl<T> Vec<T> {
1798     /// Removes the first instance of `item` from the vector if the item exists.
1799     ///
1800     /// This method will be removed soon.
1801     #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1802     #[rustc_deprecated(
1803         reason = "Removing the first item equal to a needle is already easily possible \
1804             with iterators and the current Vec methods. Furthermore, having a method for \
1805             one particular case of removal (linear search, only the first item, no swap remove) \
1806             but not for others is inconsistent. This method will be removed soon.",
1807         since = "1.46.0"
1808     )]
1809     pub fn remove_item<V>(&mut self, item: &V) -> Option<T>
1810     where
1811         T: PartialEq<V>,
1812     {
1813         let pos = self.iter().position(|x| *x == *item)?;
1814         Some(self.remove(pos))
1815     }
1816 }
1817
1818 ////////////////////////////////////////////////////////////////////////////////
1819 // Internal methods and functions
1820 ////////////////////////////////////////////////////////////////////////////////
1821
1822 #[doc(hidden)]
1823 #[stable(feature = "rust1", since = "1.0.0")]
1824 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1825     <T as SpecFromElem>::from_elem(elem, n)
1826 }
1827
1828 // Specialization trait used for Vec::from_elem
1829 trait SpecFromElem: Sized {
1830     fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1831 }
1832
1833 impl<T: Clone> SpecFromElem for T {
1834     default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1835         let mut v = Vec::with_capacity(n);
1836         v.extend_with(n, ExtendElement(elem));
1837         v
1838     }
1839 }
1840
1841 impl SpecFromElem for i8 {
1842     #[inline]
1843     fn from_elem(elem: i8, n: usize) -> Vec<i8> {
1844         if elem == 0 {
1845             return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1846         }
1847         unsafe {
1848             let mut v = Vec::with_capacity(n);
1849             ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
1850             v.set_len(n);
1851             v
1852         }
1853     }
1854 }
1855
1856 impl SpecFromElem for u8 {
1857     #[inline]
1858     fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1859         if elem == 0 {
1860             return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1861         }
1862         unsafe {
1863             let mut v = Vec::with_capacity(n);
1864             ptr::write_bytes(v.as_mut_ptr(), elem, n);
1865             v.set_len(n);
1866             v
1867         }
1868     }
1869 }
1870
1871 impl<T: Clone + IsZero> SpecFromElem for T {
1872     #[inline]
1873     fn from_elem(elem: T, n: usize) -> Vec<T> {
1874         if elem.is_zero() {
1875             return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1876         }
1877         let mut v = Vec::with_capacity(n);
1878         v.extend_with(n, ExtendElement(elem));
1879         v
1880     }
1881 }
1882
1883 #[rustc_specialization_trait]
1884 unsafe trait IsZero {
1885     /// Whether this value is zero
1886     fn is_zero(&self) -> bool;
1887 }
1888
1889 macro_rules! impl_is_zero {
1890     ($t:ty, $is_zero:expr) => {
1891         unsafe impl IsZero for $t {
1892             #[inline]
1893             fn is_zero(&self) -> bool {
1894                 $is_zero(*self)
1895             }
1896         }
1897     };
1898 }
1899
1900 impl_is_zero!(i16, |x| x == 0);
1901 impl_is_zero!(i32, |x| x == 0);
1902 impl_is_zero!(i64, |x| x == 0);
1903 impl_is_zero!(i128, |x| x == 0);
1904 impl_is_zero!(isize, |x| x == 0);
1905
1906 impl_is_zero!(u16, |x| x == 0);
1907 impl_is_zero!(u32, |x| x == 0);
1908 impl_is_zero!(u64, |x| x == 0);
1909 impl_is_zero!(u128, |x| x == 0);
1910 impl_is_zero!(usize, |x| x == 0);
1911
1912 impl_is_zero!(bool, |x| x == false);
1913 impl_is_zero!(char, |x| x == '\0');
1914
1915 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1916 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1917
1918 unsafe impl<T> IsZero for *const T {
1919     #[inline]
1920     fn is_zero(&self) -> bool {
1921         (*self).is_null()
1922     }
1923 }
1924
1925 unsafe impl<T> IsZero for *mut T {
1926     #[inline]
1927     fn is_zero(&self) -> bool {
1928         (*self).is_null()
1929     }
1930 }
1931
1932 // `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
1933 // For fat pointers, the bytes that would be the pointer metadata in the `Some`
1934 // variant are padding in the `None` variant, so ignoring them and
1935 // zero-initializing instead is ok.
1936 // `Option<&mut T>` never implements `Clone`, so there's no need for an impl of
1937 // `SpecFromElem`.
1938
1939 unsafe impl<T: ?Sized> IsZero for Option<&T> {
1940     #[inline]
1941     fn is_zero(&self) -> bool {
1942         self.is_none()
1943     }
1944 }
1945
1946 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
1947     #[inline]
1948     fn is_zero(&self) -> bool {
1949         self.is_none()
1950     }
1951 }
1952
1953 ////////////////////////////////////////////////////////////////////////////////
1954 // Common trait implementations for Vec
1955 ////////////////////////////////////////////////////////////////////////////////
1956
1957 #[stable(feature = "rust1", since = "1.0.0")]
1958 impl<T> ops::Deref for Vec<T> {
1959     type Target = [T];
1960
1961     fn deref(&self) -> &[T] {
1962         unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
1963     }
1964 }
1965
1966 #[stable(feature = "rust1", since = "1.0.0")]
1967 impl<T> ops::DerefMut for Vec<T> {
1968     fn deref_mut(&mut self) -> &mut [T] {
1969         unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1970     }
1971 }
1972
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 impl<T: Clone> Clone for Vec<T> {
1975     #[cfg(not(test))]
1976     fn clone(&self) -> Vec<T> {
1977         <[T]>::to_vec(&**self)
1978     }
1979
1980     // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1981     // required for this method definition, is not available. Instead use the
1982     // `slice::to_vec`  function which is only available with cfg(test)
1983     // NB see the slice::hack module in slice.rs for more information
1984     #[cfg(test)]
1985     fn clone(&self) -> Vec<T> {
1986         crate::slice::to_vec(&**self)
1987     }
1988
1989     fn clone_from(&mut self, other: &Vec<T>) {
1990         other.as_slice().clone_into(self);
1991     }
1992 }
1993
1994 #[stable(feature = "rust1", since = "1.0.0")]
1995 impl<T: Hash> Hash for Vec<T> {
1996     #[inline]
1997     fn hash<H: Hasher>(&self, state: &mut H) {
1998         Hash::hash(&**self, state)
1999     }
2000 }
2001
2002 #[stable(feature = "rust1", since = "1.0.0")]
2003 #[rustc_on_unimplemented(
2004     message = "vector indices are of type `usize` or ranges of `usize`",
2005     label = "vector indices are of type `usize` or ranges of `usize`"
2006 )]
2007 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
2008     type Output = I::Output;
2009
2010     #[inline]
2011     fn index(&self, index: I) -> &Self::Output {
2012         Index::index(&**self, index)
2013     }
2014 }
2015
2016 #[stable(feature = "rust1", since = "1.0.0")]
2017 #[rustc_on_unimplemented(
2018     message = "vector indices are of type `usize` or ranges of `usize`",
2019     label = "vector indices are of type `usize` or ranges of `usize`"
2020 )]
2021 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
2022     #[inline]
2023     fn index_mut(&mut self, index: I) -> &mut Self::Output {
2024         IndexMut::index_mut(&mut **self, index)
2025     }
2026 }
2027
2028 #[stable(feature = "rust1", since = "1.0.0")]
2029 impl<T> FromIterator<T> for Vec<T> {
2030     #[inline]
2031     fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2032         <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
2033     }
2034 }
2035
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 impl<T> IntoIterator for Vec<T> {
2038     type Item = T;
2039     type IntoIter = IntoIter<T>;
2040
2041     /// Creates a consuming iterator, that is, one that moves each value out of
2042     /// the vector (from start to end). The vector cannot be used after calling
2043     /// this.
2044     ///
2045     /// # Examples
2046     ///
2047     /// ```
2048     /// let v = vec!["a".to_string(), "b".to_string()];
2049     /// for s in v.into_iter() {
2050     ///     // s has type String, not &String
2051     ///     println!("{}", s);
2052     /// }
2053     /// ```
2054     #[inline]
2055     fn into_iter(self) -> IntoIter<T> {
2056         unsafe {
2057             let mut me = ManuallyDrop::new(self);
2058             let begin = me.as_mut_ptr();
2059             let end = if mem::size_of::<T>() == 0 {
2060                 arith_offset(begin as *const i8, me.len() as isize) as *const T
2061             } else {
2062                 begin.add(me.len()) as *const T
2063             };
2064             let cap = me.buf.capacity();
2065             IntoIter {
2066                 buf: NonNull::new_unchecked(begin),
2067                 phantom: PhantomData,
2068                 cap,
2069                 ptr: begin,
2070                 end,
2071             }
2072         }
2073     }
2074 }
2075
2076 #[stable(feature = "rust1", since = "1.0.0")]
2077 impl<'a, T> IntoIterator for &'a Vec<T> {
2078     type Item = &'a T;
2079     type IntoIter = slice::Iter<'a, T>;
2080
2081     fn into_iter(self) -> slice::Iter<'a, T> {
2082         self.iter()
2083     }
2084 }
2085
2086 #[stable(feature = "rust1", since = "1.0.0")]
2087 impl<'a, T> IntoIterator for &'a mut Vec<T> {
2088     type Item = &'a mut T;
2089     type IntoIter = slice::IterMut<'a, T>;
2090
2091     fn into_iter(self) -> slice::IterMut<'a, T> {
2092         self.iter_mut()
2093     }
2094 }
2095
2096 #[stable(feature = "rust1", since = "1.0.0")]
2097 impl<T> Extend<T> for Vec<T> {
2098     #[inline]
2099     fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2100         <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2101     }
2102
2103     #[inline]
2104     fn extend_one(&mut self, item: T) {
2105         self.push(item);
2106     }
2107
2108     #[inline]
2109     fn extend_reserve(&mut self, additional: usize) {
2110         self.reserve(additional);
2111     }
2112 }
2113
2114 // Specialization trait used for Vec::from_iter and Vec::extend
2115 trait SpecExtend<T, I> {
2116     fn from_iter(iter: I) -> Self;
2117     fn spec_extend(&mut self, iter: I);
2118 }
2119
2120 impl<T, I> SpecExtend<T, I> for Vec<T>
2121 where
2122     I: Iterator<Item = T>,
2123 {
2124     default fn from_iter(mut iterator: I) -> Self {
2125         // Unroll the first iteration, as the vector is going to be
2126         // expanded on this iteration in every case when the iterable is not
2127         // empty, but the loop in extend_desugared() is not going to see the
2128         // vector being full in the few subsequent loop iterations.
2129         // So we get better branch prediction.
2130         let mut vector = match iterator.next() {
2131             None => return Vec::new(),
2132             Some(element) => {
2133                 let (lower, _) = iterator.size_hint();
2134                 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2135                 unsafe {
2136                     ptr::write(vector.as_mut_ptr(), element);
2137                     vector.set_len(1);
2138                 }
2139                 vector
2140             }
2141         };
2142         <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2143         vector
2144     }
2145
2146     default fn spec_extend(&mut self, iter: I) {
2147         self.extend_desugared(iter)
2148     }
2149 }
2150
2151 impl<T, I> SpecExtend<T, I> for Vec<T>
2152 where
2153     I: TrustedLen<Item = T>,
2154 {
2155     default fn from_iter(iterator: I) -> Self {
2156         let mut vector = Vec::new();
2157         vector.spec_extend(iterator);
2158         vector
2159     }
2160
2161     default fn spec_extend(&mut self, iterator: I) {
2162         // This is the case for a TrustedLen iterator.
2163         let (low, high) = iterator.size_hint();
2164         if let Some(high_value) = high {
2165             debug_assert_eq!(
2166                 low,
2167                 high_value,
2168                 "TrustedLen iterator's size hint is not exact: {:?}",
2169                 (low, high)
2170             );
2171         }
2172         if let Some(additional) = high {
2173             self.reserve(additional);
2174             unsafe {
2175                 let mut ptr = self.as_mut_ptr().add(self.len());
2176                 let mut local_len = SetLenOnDrop::new(&mut self.len);
2177                 iterator.for_each(move |element| {
2178                     ptr::write(ptr, element);
2179                     ptr = ptr.offset(1);
2180                     // NB can't overflow since we would have had to alloc the address space
2181                     local_len.increment_len(1);
2182                 });
2183             }
2184         } else {
2185             self.extend_desugared(iterator)
2186         }
2187     }
2188 }
2189
2190 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2191     fn from_iter(iterator: IntoIter<T>) -> Self {
2192         // A common case is passing a vector into a function which immediately
2193         // re-collects into a vector. We can short circuit this if the IntoIter
2194         // has not been advanced at all.
2195         if iterator.buf.as_ptr() as *const _ == iterator.ptr {
2196             unsafe {
2197                 let it = ManuallyDrop::new(iterator);
2198                 Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap)
2199             }
2200         } else {
2201             let mut vector = Vec::new();
2202             vector.spec_extend(iterator);
2203             vector
2204         }
2205     }
2206
2207     fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2208         unsafe {
2209             self.append_elements(iterator.as_slice() as _);
2210         }
2211         iterator.ptr = iterator.end;
2212     }
2213 }
2214
2215 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2216 where
2217     I: Iterator<Item = &'a T>,
2218     T: Clone,
2219 {
2220     default fn from_iter(iterator: I) -> Self {
2221         SpecExtend::from_iter(iterator.cloned())
2222     }
2223
2224     default fn spec_extend(&mut self, iterator: I) {
2225         self.spec_extend(iterator.cloned())
2226     }
2227 }
2228
2229 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2230 where
2231     T: Copy,
2232 {
2233     fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2234         let slice = iterator.as_slice();
2235         self.reserve(slice.len());
2236         unsafe {
2237             let len = self.len();
2238             let dst_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(len), slice.len());
2239             dst_slice.copy_from_slice(slice);
2240             self.set_len(len + slice.len());
2241         }
2242     }
2243 }
2244
2245 impl<T> Vec<T> {
2246     fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2247         // This is the case for a general iterator.
2248         //
2249         // This function should be the moral equivalent of:
2250         //
2251         //      for item in iterator {
2252         //          self.push(item);
2253         //      }
2254         while let Some(element) = iterator.next() {
2255             let len = self.len();
2256             if len == self.capacity() {
2257                 let (lower, _) = iterator.size_hint();
2258                 self.reserve(lower.saturating_add(1));
2259             }
2260             unsafe {
2261                 ptr::write(self.as_mut_ptr().add(len), element);
2262                 // NB can't overflow since we would have had to alloc the address space
2263                 self.set_len(len + 1);
2264             }
2265         }
2266     }
2267
2268     /// Creates a splicing iterator that replaces the specified range in the vector
2269     /// with the given `replace_with` iterator and yields the removed items.
2270     /// `replace_with` does not need to be the same length as `range`.
2271     ///
2272     /// `range` is removed even if the iterator is not consumed until the end.
2273     ///
2274     /// It is unspecified how many elements are removed from the vector
2275     /// if the `Splice` value is leaked.
2276     ///
2277     /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2278     ///
2279     /// This is optimal if:
2280     ///
2281     /// * The tail (elements in the vector after `range`) is empty,
2282     /// * or `replace_with` yields fewer elements than `range`’s length
2283     /// * or the lower bound of its `size_hint()` is exact.
2284     ///
2285     /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2286     ///
2287     /// # Panics
2288     ///
2289     /// Panics if the starting point is greater than the end point or if
2290     /// the end point is greater than the length of the vector.
2291     ///
2292     /// # Examples
2293     ///
2294     /// ```
2295     /// let mut v = vec![1, 2, 3];
2296     /// let new = [7, 8];
2297     /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2298     /// assert_eq!(v, &[7, 8, 3]);
2299     /// assert_eq!(u, &[1, 2]);
2300     /// ```
2301     #[inline]
2302     #[stable(feature = "vec_splice", since = "1.21.0")]
2303     pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2304     where
2305         R: RangeBounds<usize>,
2306         I: IntoIterator<Item = T>,
2307     {
2308         Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2309     }
2310
2311     /// Creates an iterator which uses a closure to determine if an element should be removed.
2312     ///
2313     /// If the closure returns true, then the element is removed and yielded.
2314     /// If the closure returns false, the element will remain in the vector and will not be yielded
2315     /// by the iterator.
2316     ///
2317     /// Using this method is equivalent to the following code:
2318     ///
2319     /// ```
2320     /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2321     /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2322     /// let mut i = 0;
2323     /// while i != vec.len() {
2324     ///     if some_predicate(&mut vec[i]) {
2325     ///         let val = vec.remove(i);
2326     ///         // your code here
2327     ///     } else {
2328     ///         i += 1;
2329     ///     }
2330     /// }
2331     ///
2332     /// # assert_eq!(vec, vec![1, 4, 5]);
2333     /// ```
2334     ///
2335     /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2336     /// because it can backshift the elements of the array in bulk.
2337     ///
2338     /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2339     /// regardless of whether you choose to keep or remove it.
2340     ///
2341     ///
2342     /// # Examples
2343     ///
2344     /// Splitting an array into evens and odds, reusing the original allocation:
2345     ///
2346     /// ```
2347     /// #![feature(drain_filter)]
2348     /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2349     ///
2350     /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2351     /// let odds = numbers;
2352     ///
2353     /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2354     /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2355     /// ```
2356     #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2357     pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2358     where
2359         F: FnMut(&mut T) -> bool,
2360     {
2361         let old_len = self.len();
2362
2363         // Guard against us getting leaked (leak amplification)
2364         unsafe {
2365             self.set_len(0);
2366         }
2367
2368         DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2369     }
2370 }
2371
2372 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2373 ///
2374 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2375 /// append the entire slice at once.
2376 ///
2377 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2378 #[stable(feature = "extend_ref", since = "1.2.0")]
2379 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2380     fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2381         self.spec_extend(iter.into_iter())
2382     }
2383
2384     #[inline]
2385     fn extend_one(&mut self, &item: &'a T) {
2386         self.push(item);
2387     }
2388
2389     #[inline]
2390     fn extend_reserve(&mut self, additional: usize) {
2391         self.reserve(additional);
2392     }
2393 }
2394
2395 macro_rules! __impl_slice_eq1 {
2396     ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => {
2397         #[$stability]
2398         impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2399         where
2400             A: PartialEq<B>,
2401             $($ty: $bound)?
2402         {
2403             #[inline]
2404             fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2405             #[inline]
2406             fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2407         }
2408     }
2409 }
2410
2411 __impl_slice_eq1! { [] Vec<A>, Vec<B>, #[stable(feature = "rust1", since = "1.0.0")] }
2412 __impl_slice_eq1! { [] Vec<A>, &[B], #[stable(feature = "rust1", since = "1.0.0")] }
2413 __impl_slice_eq1! { [] Vec<A>, &mut [B], #[stable(feature = "rust1", since = "1.0.0")] }
2414 __impl_slice_eq1! { [] &[A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2415 __impl_slice_eq1! { [] &mut [A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2416 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B> where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2417 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2418 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2419 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2420 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2421
2422 // NOTE: some less important impls are omitted to reduce code bloat
2423 // FIXME(Centril): Reconsider this?
2424 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], }
2425 //__impl_slice_eq1! { [const N: usize] [A; N], Vec<B>, }
2426 //__impl_slice_eq1! { [const N: usize] &[A; N], Vec<B>, }
2427 //__impl_slice_eq1! { [const N: usize] &mut [A; N], Vec<B>, }
2428 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], }
2429 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], }
2430 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], }
2431
2432 /// Implements comparison of vectors, lexicographically.
2433 #[stable(feature = "rust1", since = "1.0.0")]
2434 impl<T: PartialOrd> PartialOrd for Vec<T> {
2435     #[inline]
2436     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2437         PartialOrd::partial_cmp(&**self, &**other)
2438     }
2439 }
2440
2441 #[stable(feature = "rust1", since = "1.0.0")]
2442 impl<T: Eq> Eq for Vec<T> {}
2443
2444 /// Implements ordering of vectors, lexicographically.
2445 #[stable(feature = "rust1", since = "1.0.0")]
2446 impl<T: Ord> Ord for Vec<T> {
2447     #[inline]
2448     fn cmp(&self, other: &Vec<T>) -> Ordering {
2449         Ord::cmp(&**self, &**other)
2450     }
2451 }
2452
2453 #[stable(feature = "rust1", since = "1.0.0")]
2454 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2455     fn drop(&mut self) {
2456         unsafe {
2457             // use drop for [T]
2458             // use a raw slice to refer to the elements of the vector as weakest necessary type;
2459             // could avoid questions of validity in certain cases
2460             ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2461         }
2462         // RawVec handles deallocation
2463     }
2464 }
2465
2466 #[stable(feature = "rust1", since = "1.0.0")]
2467 impl<T> Default for Vec<T> {
2468     /// Creates an empty `Vec<T>`.
2469     fn default() -> Vec<T> {
2470         Vec::new()
2471     }
2472 }
2473
2474 #[stable(feature = "rust1", since = "1.0.0")]
2475 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2476     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2477         fmt::Debug::fmt(&**self, f)
2478     }
2479 }
2480
2481 #[stable(feature = "rust1", since = "1.0.0")]
2482 impl<T> AsRef<Vec<T>> for Vec<T> {
2483     fn as_ref(&self) -> &Vec<T> {
2484         self
2485     }
2486 }
2487
2488 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2489 impl<T> AsMut<Vec<T>> for Vec<T> {
2490     fn as_mut(&mut self) -> &mut Vec<T> {
2491         self
2492     }
2493 }
2494
2495 #[stable(feature = "rust1", since = "1.0.0")]
2496 impl<T> AsRef<[T]> for Vec<T> {
2497     fn as_ref(&self) -> &[T] {
2498         self
2499     }
2500 }
2501
2502 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2503 impl<T> AsMut<[T]> for Vec<T> {
2504     fn as_mut(&mut self) -> &mut [T] {
2505         self
2506     }
2507 }
2508
2509 #[stable(feature = "rust1", since = "1.0.0")]
2510 impl<T: Clone> From<&[T]> for Vec<T> {
2511     #[cfg(not(test))]
2512     fn from(s: &[T]) -> Vec<T> {
2513         s.to_vec()
2514     }
2515     #[cfg(test)]
2516     fn from(s: &[T]) -> Vec<T> {
2517         crate::slice::to_vec(s)
2518     }
2519 }
2520
2521 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2522 impl<T: Clone> From<&mut [T]> for Vec<T> {
2523     #[cfg(not(test))]
2524     fn from(s: &mut [T]) -> Vec<T> {
2525         s.to_vec()
2526     }
2527     #[cfg(test)]
2528     fn from(s: &mut [T]) -> Vec<T> {
2529         crate::slice::to_vec(s)
2530     }
2531 }
2532
2533 #[stable(feature = "vec_from_array", since = "1.44.0")]
2534 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2535     #[cfg(not(test))]
2536     fn from(s: [T; N]) -> Vec<T> {
2537         <[T]>::into_vec(box s)
2538     }
2539     #[cfg(test)]
2540     fn from(s: [T; N]) -> Vec<T> {
2541         crate::slice::into_vec(box s)
2542     }
2543 }
2544
2545 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2546 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2547 where
2548     [T]: ToOwned<Owned = Vec<T>>,
2549 {
2550     fn from(s: Cow<'a, [T]>) -> Vec<T> {
2551         s.into_owned()
2552     }
2553 }
2554
2555 // note: test pulls in libstd, which causes errors here
2556 #[cfg(not(test))]
2557 #[stable(feature = "vec_from_box", since = "1.18.0")]
2558 impl<T> From<Box<[T]>> for Vec<T> {
2559     fn from(s: Box<[T]>) -> Vec<T> {
2560         s.into_vec()
2561     }
2562 }
2563
2564 // note: test pulls in libstd, which causes errors here
2565 #[cfg(not(test))]
2566 #[stable(feature = "box_from_vec", since = "1.20.0")]
2567 impl<T> From<Vec<T>> for Box<[T]> {
2568     fn from(v: Vec<T>) -> Box<[T]> {
2569         v.into_boxed_slice()
2570     }
2571 }
2572
2573 #[stable(feature = "rust1", since = "1.0.0")]
2574 impl From<&str> for Vec<u8> {
2575     fn from(s: &str) -> Vec<u8> {
2576         From::from(s.as_bytes())
2577     }
2578 }
2579
2580 ////////////////////////////////////////////////////////////////////////////////
2581 // Clone-on-write
2582 ////////////////////////////////////////////////////////////////////////////////
2583
2584 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2585 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2586     fn from(s: &'a [T]) -> Cow<'a, [T]> {
2587         Cow::Borrowed(s)
2588     }
2589 }
2590
2591 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2592 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2593     fn from(v: Vec<T>) -> Cow<'a, [T]> {
2594         Cow::Owned(v)
2595     }
2596 }
2597
2598 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2599 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2600     fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2601         Cow::Borrowed(v.as_slice())
2602     }
2603 }
2604
2605 #[stable(feature = "rust1", since = "1.0.0")]
2606 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
2607 where
2608     T: Clone,
2609 {
2610     fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2611         Cow::Owned(FromIterator::from_iter(it))
2612     }
2613 }
2614
2615 ////////////////////////////////////////////////////////////////////////////////
2616 // Iterators
2617 ////////////////////////////////////////////////////////////////////////////////
2618
2619 /// An iterator that moves out of a vector.
2620 ///
2621 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
2622 /// by the [`IntoIterator`] trait).
2623 ///
2624 /// [`Vec`]: struct.Vec.html
2625 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
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 the [`drain`] method on [`Vec`].
2806 ///
2807 /// [`drain`]: struct.Vec.html#method.drain
2808 /// [`Vec`]: struct.Vec.html
2809 #[stable(feature = "drain", since = "1.6.0")]
2810 pub struct Drain<'a, T: 'a> {
2811     /// Index of tail to preserve
2812     tail_start: usize,
2813     /// Length of tail
2814     tail_len: usize,
2815     /// Current remaining range to remove
2816     iter: slice::Iter<'a, T>,
2817     vec: NonNull<Vec<T>>,
2818 }
2819
2820 #[stable(feature = "collection_debug", since = "1.17.0")]
2821 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2822     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2823         f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
2824     }
2825 }
2826
2827 impl<'a, T> Drain<'a, T> {
2828     /// Returns the remaining items of this iterator as a slice.
2829     ///
2830     /// # Examples
2831     ///
2832     /// ```
2833     /// let mut vec = vec!['a', 'b', 'c'];
2834     /// let mut drain = vec.drain(..);
2835     /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
2836     /// let _ = drain.next().unwrap();
2837     /// assert_eq!(drain.as_slice(), &['b', 'c']);
2838     /// ```
2839     #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
2840     pub fn as_slice(&self) -> &[T] {
2841         self.iter.as_slice()
2842     }
2843 }
2844
2845 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
2846 impl<'a, T> AsRef<[T]> for Drain<'a, T> {
2847     fn as_ref(&self) -> &[T] {
2848         self.as_slice()
2849     }
2850 }
2851
2852 #[stable(feature = "drain", since = "1.6.0")]
2853 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2854 #[stable(feature = "drain", since = "1.6.0")]
2855 unsafe impl<T: Send> Send for Drain<'_, T> {}
2856
2857 #[stable(feature = "drain", since = "1.6.0")]
2858 impl<T> Iterator for Drain<'_, T> {
2859     type Item = T;
2860
2861     #[inline]
2862     fn next(&mut self) -> Option<T> {
2863         self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2864     }
2865
2866     fn size_hint(&self) -> (usize, Option<usize>) {
2867         self.iter.size_hint()
2868     }
2869 }
2870
2871 #[stable(feature = "drain", since = "1.6.0")]
2872 impl<T> DoubleEndedIterator for Drain<'_, T> {
2873     #[inline]
2874     fn next_back(&mut self) -> Option<T> {
2875         self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2876     }
2877 }
2878
2879 #[stable(feature = "drain", since = "1.6.0")]
2880 impl<T> Drop for Drain<'_, T> {
2881     fn drop(&mut self) {
2882         /// Continues dropping the remaining elements in the `Drain`, then moves back the
2883         /// un-`Drain`ed elements to restore the original `Vec`.
2884         struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>);
2885
2886         impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> {
2887             fn drop(&mut self) {
2888                 // Continue the same loop we have below. If the loop already finished, this does
2889                 // nothing.
2890                 self.0.for_each(drop);
2891
2892                 if self.0.tail_len > 0 {
2893                     unsafe {
2894                         let source_vec = self.0.vec.as_mut();
2895                         // memmove back untouched tail, update to new length
2896                         let start = source_vec.len();
2897                         let tail = self.0.tail_start;
2898                         if tail != start {
2899                             let src = source_vec.as_ptr().add(tail);
2900                             let dst = source_vec.as_mut_ptr().add(start);
2901                             ptr::copy(src, dst, self.0.tail_len);
2902                         }
2903                         source_vec.set_len(start + self.0.tail_len);
2904                     }
2905                 }
2906             }
2907         }
2908
2909         // exhaust self first
2910         while let Some(item) = self.next() {
2911             let guard = DropGuard(self);
2912             drop(item);
2913             mem::forget(guard);
2914         }
2915
2916         // Drop a `DropGuard` to move back the non-drained tail of `self`.
2917         DropGuard(self);
2918     }
2919 }
2920
2921 #[stable(feature = "drain", since = "1.6.0")]
2922 impl<T> ExactSizeIterator for Drain<'_, T> {
2923     fn is_empty(&self) -> bool {
2924         self.iter.is_empty()
2925     }
2926 }
2927
2928 #[unstable(feature = "trusted_len", issue = "37572")]
2929 unsafe impl<T> TrustedLen for Drain<'_, T> {}
2930
2931 #[stable(feature = "fused", since = "1.26.0")]
2932 impl<T> FusedIterator for Drain<'_, T> {}
2933
2934 /// A splicing iterator for `Vec`.
2935 ///
2936 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2937 /// documentation for more.
2938 ///
2939 /// [`splice()`]: struct.Vec.html#method.splice
2940 /// [`Vec`]: struct.Vec.html
2941 #[derive(Debug)]
2942 #[stable(feature = "vec_splice", since = "1.21.0")]
2943 pub struct Splice<'a, I: Iterator + 'a> {
2944     drain: Drain<'a, I::Item>,
2945     replace_with: I,
2946 }
2947
2948 #[stable(feature = "vec_splice", since = "1.21.0")]
2949 impl<I: Iterator> Iterator for Splice<'_, I> {
2950     type Item = I::Item;
2951
2952     fn next(&mut self) -> Option<Self::Item> {
2953         self.drain.next()
2954     }
2955
2956     fn size_hint(&self) -> (usize, Option<usize>) {
2957         self.drain.size_hint()
2958     }
2959 }
2960
2961 #[stable(feature = "vec_splice", since = "1.21.0")]
2962 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
2963     fn next_back(&mut self) -> Option<Self::Item> {
2964         self.drain.next_back()
2965     }
2966 }
2967
2968 #[stable(feature = "vec_splice", since = "1.21.0")]
2969 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
2970
2971 #[stable(feature = "vec_splice", since = "1.21.0")]
2972 impl<I: Iterator> Drop for Splice<'_, I> {
2973     fn drop(&mut self) {
2974         self.drain.by_ref().for_each(drop);
2975
2976         unsafe {
2977             if self.drain.tail_len == 0 {
2978                 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2979                 return;
2980             }
2981
2982             // First fill the range left by drain().
2983             if !self.drain.fill(&mut self.replace_with) {
2984                 return;
2985             }
2986
2987             // There may be more elements. Use the lower bound as an estimate.
2988             // FIXME: Is the upper bound a better guess? Or something else?
2989             let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2990             if lower_bound > 0 {
2991                 self.drain.move_tail(lower_bound);
2992                 if !self.drain.fill(&mut self.replace_with) {
2993                     return;
2994                 }
2995             }
2996
2997             // Collect any remaining elements.
2998             // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2999             let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
3000             // Now we have an exact count.
3001             if collected.len() > 0 {
3002                 self.drain.move_tail(collected.len());
3003                 let filled = self.drain.fill(&mut collected);
3004                 debug_assert!(filled);
3005                 debug_assert_eq!(collected.len(), 0);
3006             }
3007         }
3008         // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
3009     }
3010 }
3011
3012 /// Private helper methods for `Splice::drop`
3013 impl<T> Drain<'_, T> {
3014     /// The range from `self.vec.len` to `self.tail_start` contains elements
3015     /// that have been moved out.
3016     /// Fill that range as much as possible with new elements from the `replace_with` iterator.
3017     /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
3018     unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
3019         let vec = unsafe { self.vec.as_mut() };
3020         let range_start = vec.len;
3021         let range_end = self.tail_start;
3022         let range_slice = unsafe {
3023             slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
3024         };
3025
3026         for place in range_slice {
3027             if let Some(new_item) = replace_with.next() {
3028                 unsafe { ptr::write(place, new_item) };
3029                 vec.len += 1;
3030             } else {
3031                 return false;
3032             }
3033         }
3034         true
3035     }
3036
3037     /// Makes room for inserting more elements before the tail.
3038     unsafe fn move_tail(&mut self, additional: usize) {
3039         let vec = unsafe { self.vec.as_mut() };
3040         let len = self.tail_start + self.tail_len;
3041         vec.buf.reserve(len, additional);
3042
3043         let new_tail_start = self.tail_start + additional;
3044         unsafe {
3045             let src = vec.as_ptr().add(self.tail_start);
3046             let dst = vec.as_mut_ptr().add(new_tail_start);
3047             ptr::copy(src, dst, self.tail_len);
3048         }
3049         self.tail_start = new_tail_start;
3050     }
3051 }
3052
3053 /// An iterator produced by calling `drain_filter` on Vec.
3054 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3055 #[derive(Debug)]
3056 pub struct DrainFilter<'a, T, F>
3057 where
3058     F: FnMut(&mut T) -> bool,
3059 {
3060     vec: &'a mut Vec<T>,
3061     /// The index of the item that will be inspected by the next call to `next`.
3062     idx: usize,
3063     /// The number of items that have been drained (removed) thus far.
3064     del: usize,
3065     /// The original length of `vec` prior to draining.
3066     old_len: usize,
3067     /// The filter test predicate.
3068     pred: F,
3069     /// A flag that indicates a panic has occurred in the filter test prodicate.
3070     /// This is used as a hint in the drop implementation to prevent consumption
3071     /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3072     /// backshifted in the `vec`, but no further items will be dropped or
3073     /// tested by the filter predicate.
3074     panic_flag: bool,
3075 }
3076
3077 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3078 impl<T, F> Iterator for DrainFilter<'_, T, F>
3079 where
3080     F: FnMut(&mut T) -> bool,
3081 {
3082     type Item = T;
3083
3084     fn next(&mut self) -> Option<T> {
3085         unsafe {
3086             while self.idx < self.old_len {
3087                 let i = self.idx;
3088                 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3089                 self.panic_flag = true;
3090                 let drained = (self.pred)(&mut v[i]);
3091                 self.panic_flag = false;
3092                 // Update the index *after* the predicate is called. If the index
3093                 // is updated prior and the predicate panics, the element at this
3094                 // index would be leaked.
3095                 self.idx += 1;
3096                 if drained {
3097                     self.del += 1;
3098                     return Some(ptr::read(&v[i]));
3099                 } else if self.del > 0 {
3100                     let del = self.del;
3101                     let src: *const T = &v[i];
3102                     let dst: *mut T = &mut v[i - del];
3103                     ptr::copy_nonoverlapping(src, dst, 1);
3104                 }
3105             }
3106             None
3107         }
3108     }
3109
3110     fn size_hint(&self) -> (usize, Option<usize>) {
3111         (0, Some(self.old_len - self.idx))
3112     }
3113 }
3114
3115 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3116 impl<T, F> Drop for DrainFilter<'_, T, F>
3117 where
3118     F: FnMut(&mut T) -> bool,
3119 {
3120     fn drop(&mut self) {
3121         struct BackshiftOnDrop<'a, 'b, T, F>
3122         where
3123             F: FnMut(&mut T) -> bool,
3124         {
3125             drain: &'b mut DrainFilter<'a, T, F>,
3126         }
3127
3128         impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
3129         where
3130             F: FnMut(&mut T) -> bool,
3131         {
3132             fn drop(&mut self) {
3133                 unsafe {
3134                     if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3135                         // This is a pretty messed up state, and there isn't really an
3136                         // obviously right thing to do. We don't want to keep trying
3137                         // to execute `pred`, so we just backshift all the unprocessed
3138                         // elements and tell the vec that they still exist. The backshift
3139                         // is required to prevent a double-drop of the last successfully
3140                         // drained item prior to a panic in the predicate.
3141                         let ptr = self.drain.vec.as_mut_ptr();
3142                         let src = ptr.add(self.drain.idx);
3143                         let dst = src.sub(self.drain.del);
3144                         let tail_len = self.drain.old_len - self.drain.idx;
3145                         src.copy_to(dst, tail_len);
3146                     }
3147                     self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3148                 }
3149             }
3150         }
3151
3152         let backshift = BackshiftOnDrop { drain: self };
3153
3154         // Attempt to consume any remaining elements if the filter predicate
3155         // has not yet panicked. We'll backshift any remaining elements
3156         // whether we've already panicked or if the consumption here panics.
3157         if !backshift.drain.panic_flag {
3158             backshift.drain.for_each(drop);
3159         }
3160     }
3161 }