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