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