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