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