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