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