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