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