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