alloc/vec/mod.rs
1//! A contiguous growable array type with heap-allocated contents, written
2//! `Vec<T>`.
3//!
4//! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and
5//! *O*(1) pop (from the end).
6//!
7//! Vectors ensure they never allocate more than `isize::MAX` bytes.
8//!
9//! # Examples
10//!
11//! You can explicitly create a [`Vec`] with [`Vec::new`]:
12//!
13//! ```
14//! let v: Vec<i32> = Vec::new();
15//! ```
16//!
17//! ...or by using the [`vec!`] macro:
18//!
19//! ```
20//! let v: Vec<i32> = vec![];
21//!
22//! let v = vec![1, 2, 3, 4, 5];
23//!
24//! let v = vec![0; 10]; // ten zeroes
25//! ```
26//!
27//! You can [`push`] values onto the end of a vector (which will grow the vector
28//! as needed):
29//!
30//! ```
31//! let mut v = vec![1, 2];
32//!
33//! v.push(3);
34//! ```
35//!
36//! Popping values works in much the same way:
37//!
38//! ```
39//! let mut v = vec![1, 2];
40//!
41//! let two = v.pop();
42//! ```
43//!
44//! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
45//!
46//! ```
47//! let mut v = vec![1, 2, 3];
48//! let three = v[2];
49//! v[1] = v[1] + 5;
50//! ```
51//!
52//! # Memory layout
53//!
54//! When the type is non-zero-sized and the capacity is nonzero, [`Vec`] uses the [`Global`]
55//! allocator for its allocation. It is valid to convert both ways between such a [`Vec`] and a raw
56//! pointer allocated with the [`Global`] allocator, provided that the [`Layout`] used with the
57//! allocator is correct for a sequence of `capacity` elements of the type, and the first `len`
58//! values pointed to by the raw pointer are valid. More precisely, a `ptr: *mut T` that has been
59//! allocated with the [`Global`] allocator with [`Layout::array::<T>(capacity)`][Layout::array] may
60//! be converted into a vec using
61//! [`Vec::<T>::from_raw_parts(ptr, len, capacity)`](Vec::from_raw_parts). Conversely, the memory
62//! backing a `value: *mut T` obtained from [`Vec::<T>::as_mut_ptr`] may be deallocated using the
63//! [`Global`] allocator with the same layout.
64//!
65//! For zero-sized types (ZSTs), or when the capacity is zero, the `Vec` pointer must be non-null
66//! and sufficiently aligned. The recommended way to build a `Vec` of ZSTs if [`vec!`] cannot be
67//! used is to use [`ptr::NonNull::dangling`].
68//!
69//! [`push`]: Vec::push
70//! [`ptr::NonNull::dangling`]: NonNull::dangling
71//! [`Layout`]: crate::alloc::Layout
72//! [Layout::array]: crate::alloc::Layout::array
73
74#![stable(feature = "rust1", since = "1.0.0")]
75
76#[cfg(not(no_global_oom_handling))]
77use core::clone::TrivialClone;
78#[cfg(not(no_global_oom_handling))]
79use core::cmp;
80use core::cmp::Ordering;
81use core::hash::{Hash, Hasher};
82#[cfg(not(no_global_oom_handling))]
83use core::iter;
84#[cfg(not(no_global_oom_handling))]
85use core::marker::Destruct;
86use core::marker::{Freeze, PhantomData};
87use core::mem::{self, Assume, ManuallyDrop, MaybeUninit, SizedTypeProperties, TransmuteFrom};
88use core::ops::{self, Index, IndexMut, Range, RangeBounds};
89use core::ptr::{self, NonNull};
90use core::slice::{self, SliceIndex};
91use core::{fmt, hint, intrinsics, ub_checks};
92
93#[stable(feature = "extract_if", since = "1.87.0")]
94pub use self::extract_if::ExtractIf;
95use crate::alloc::{Allocator, Global};
96use crate::borrow::{Cow, ToOwned};
97use crate::boxed::Box;
98use crate::collections::TryReserveError;
99use crate::raw_vec::RawVec;
100
101mod extract_if;
102
103#[cfg(not(no_global_oom_handling))]
104#[stable(feature = "vec_splice", since = "1.21.0")]
105pub use self::splice::Splice;
106
107#[cfg(not(no_global_oom_handling))]
108mod splice;
109
110#[stable(feature = "drain", since = "1.6.0")]
111pub use self::drain::Drain;
112
113mod drain;
114
115#[cfg(not(no_global_oom_handling))]
116mod cow;
117
118#[cfg(not(no_global_oom_handling))]
119pub(crate) use self::in_place_collect::AsVecIntoIter;
120#[stable(feature = "rust1", since = "1.0.0")]
121pub use self::into_iter::IntoIter;
122
123mod into_iter;
124
125#[cfg(not(no_global_oom_handling))]
126use self::is_zero::IsZero;
127
128#[cfg(not(no_global_oom_handling))]
129mod is_zero;
130
131#[cfg(not(no_global_oom_handling))]
132mod in_place_collect;
133
134mod partial_eq;
135
136#[unstable(feature = "vec_peek_mut", issue = "122742")]
137pub use self::peek_mut::PeekMut;
138
139mod peek_mut;
140
141#[cfg(not(no_global_oom_handling))]
142use self::spec_from_elem::SpecFromElem;
143
144#[cfg(not(no_global_oom_handling))]
145mod spec_from_elem;
146
147#[cfg(not(no_global_oom_handling))]
148use self::set_len_on_drop::SetLenOnDrop;
149
150#[cfg(not(no_global_oom_handling))]
151mod set_len_on_drop;
152
153#[cfg(not(no_global_oom_handling))]
154use self::in_place_drop::{InPlaceDrop, InPlaceDstDataSrcBufDrop};
155
156#[cfg(not(no_global_oom_handling))]
157mod in_place_drop;
158
159#[cfg(not(no_global_oom_handling))]
160use self::spec_from_iter_nested::SpecFromIterNested;
161
162#[cfg(not(no_global_oom_handling))]
163mod spec_from_iter_nested;
164
165#[cfg(not(no_global_oom_handling))]
166use self::spec_from_iter::SpecFromIter;
167
168#[cfg(not(no_global_oom_handling))]
169mod spec_from_iter;
170
171#[cfg(not(no_global_oom_handling))]
172use self::spec_extend::SpecExtend;
173
174#[cfg(not(no_global_oom_handling))]
175mod spec_extend;
176
177/// A contiguous growable array type, written as `Vec<T>`, short for 'vector'.
178///
179/// # Examples
180///
181/// ```
182/// let mut vec = Vec::new();
183/// vec.push(1);
184/// vec.push(2);
185///
186/// assert_eq!(vec.len(), 2);
187/// assert_eq!(vec[0], 1);
188///
189/// assert_eq!(vec.pop(), Some(2));
190/// assert_eq!(vec.len(), 1);
191///
192/// vec[0] = 7;
193/// assert_eq!(vec[0], 7);
194///
195/// vec.extend([1, 2, 3]);
196///
197/// for x in &vec {
198/// println!("{x}");
199/// }
200/// assert_eq!(vec, [7, 1, 2, 3]);
201/// ```
202///
203/// The [`vec!`] macro is provided for convenient initialization:
204///
205/// ```
206/// let mut vec1 = vec![1, 2, 3];
207/// vec1.push(4);
208/// let vec2 = Vec::from([1, 2, 3, 4]);
209/// assert_eq!(vec1, vec2);
210/// ```
211///
212/// It can also initialize each element of a `Vec<T>` with a given value.
213/// This may be more efficient than performing allocation and initialization
214/// in separate steps, especially when initializing a vector of zeros:
215///
216/// ```
217/// let vec = vec![0; 5];
218/// assert_eq!(vec, [0, 0, 0, 0, 0]);
219///
220/// // The following is equivalent, but potentially slower:
221/// let mut vec = Vec::with_capacity(5);
222/// vec.resize(5, 0);
223/// assert_eq!(vec, [0, 0, 0, 0, 0]);
224/// ```
225///
226/// For more information, see
227/// [Capacity and Reallocation](#capacity-and-reallocation).
228///
229/// Use a `Vec<T>` as an efficient stack:
230///
231/// ```
232/// let mut stack = Vec::new();
233///
234/// stack.push(1);
235/// stack.push(2);
236/// stack.push(3);
237///
238/// while let Some(top) = stack.pop() {
239/// // Prints 3, 2, 1
240/// println!("{top}");
241/// }
242/// ```
243///
244/// # Indexing
245///
246/// The `Vec` type allows access to values by index, because it implements the
247/// [`Index`] trait. An example will be more explicit:
248///
249/// ```
250/// let v = vec![0, 2, 4, 6];
251/// println!("{}", v[1]); // it will display '2'
252/// ```
253///
254/// However be careful: if you try to access an index which isn't in the `Vec`,
255/// your software will panic! You cannot do this:
256///
257/// ```should_panic
258/// let v = vec![0, 2, 4, 6];
259/// println!("{}", v[6]); // it will panic!
260/// ```
261///
262/// Use [`get`] and [`get_mut`] if you want to check whether the index is in
263/// the `Vec`.
264///
265/// # Slicing
266///
267/// A `Vec` can be mutable. On the other hand, slices are read-only objects.
268/// To get a [slice][prim@slice], use [`&`]. Example:
269///
270/// ```
271/// fn read_slice(slice: &[usize]) {
272/// // ...
273/// }
274///
275/// let v = vec![0, 1];
276/// read_slice(&v);
277///
278/// // ... and that's all!
279/// // you can also do it like this:
280/// let u: &[usize] = &v;
281/// // or like this:
282/// let u: &[_] = &v;
283/// ```
284///
285/// In Rust, it's more common to pass slices as arguments rather than vectors
286/// when you just want to provide read access. The same goes for [`String`] and
287/// [`&str`].
288///
289/// # Capacity and reallocation
290///
291/// The capacity of a vector is the amount of space allocated for any future
292/// elements that will be added onto the vector. This is not to be confused with
293/// the *length* of a vector, which specifies the number of actual elements
294/// within the vector. If a vector's length exceeds its capacity, its capacity
295/// will automatically be increased, but its elements will have to be
296/// reallocated.
297///
298/// For example, a vector with capacity 10 and length 0 would be an empty vector
299/// with space for 10 more elements. Pushing 10 or fewer elements onto the
300/// vector will not change its capacity or cause reallocation to occur. However,
301/// if the vector's length is increased to 11, it will have to reallocate, which
302/// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
303/// whenever possible to specify how big the vector is expected to get.
304///
305/// # Guarantees
306///
307/// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
308/// about its design. This ensures that it's as low-overhead as possible in
309/// the general case, and can be correctly manipulated in primitive ways
310/// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
311/// If additional type parameters are added (e.g., to support custom allocators),
312/// overriding their defaults may change the behavior.
313///
314/// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
315/// triplet. No more, no less. The order of these fields is completely
316/// unspecified, and you should use the appropriate methods to modify these.
317/// The pointer will never be null, so this type is null-pointer-optimized.
318///
319/// However, the pointer might not actually point to allocated memory. In particular,
320/// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
321/// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
322/// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
323/// types inside a `Vec`, it will not allocate space for them. *Note that in this case
324/// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only
325/// if <code>[size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation
326/// details are very subtle --- if you intend to allocate memory using a `Vec`
327/// and use it for something else (either to pass to unsafe code, or to build your
328/// own memory-backed collection), be sure to deallocate this memory by using
329/// `from_raw_parts` to recover the `Vec` and then dropping it.
330///
331/// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
332/// (as defined by the allocator Rust is configured to use by default), and its
333/// pointer points to [`len`] initialized, contiguous elements in order (what
334/// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>
335/// logically uninitialized, contiguous elements.
336///
337/// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
338/// visualized as below. The top part is the `Vec` struct, it contains a
339/// pointer to the head of the allocation in the heap, length and capacity.
340/// The bottom part is the allocation on the heap, a contiguous memory block.
341///
342/// ```text
343/// ptr len capacity
344/// +--------+--------+--------+
345/// | 0x0123 | 2 | 4 |
346/// +--------+--------+--------+
347/// |
348/// v
349/// Heap +--------+--------+--------+--------+
350/// | 'a' | 'b' | uninit | uninit |
351/// +--------+--------+--------+--------+
352/// ```
353///
354/// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
355/// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
356/// layout (including the order of fields).
357///
358/// `Vec` will never perform a "small optimization" where elements are actually
359/// stored on the stack for two reasons:
360///
361/// * It would make it more difficult for unsafe code to correctly manipulate
362/// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
363/// only moved, and it would be more difficult to determine if a `Vec` had
364/// actually allocated memory.
365///
366/// * It would penalize the general case, incurring an additional branch
367/// on every access.
368///
369/// `Vec` will never automatically shrink itself, even if completely empty. This
370/// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
371/// and then filling it back up to the same [`len`] should incur no calls to
372/// the allocator. If you wish to free up unused memory, use
373/// [`shrink_to_fit`] or [`shrink_to`].
374///
375/// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
376/// sufficient. [`push`] and [`insert`] *will* (re)allocate if
377/// <code>[len] == [capacity]</code>. That is, the reported capacity is completely
378/// accurate, and can be relied on. It can even be used to manually free the memory
379/// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
380/// when not necessary.
381///
382/// `Vec` does not guarantee any particular growth strategy when reallocating
383/// when full, nor when [`reserve`] is called. The current strategy is basic
384/// and it may prove desirable to use a non-constant growth factor. Whatever
385/// strategy is used will of course guarantee *O*(1) amortized [`push`].
386///
387/// It is guaranteed, in order to respect the intentions of the programmer, that
388/// all of `vec![e_1, e_2, ..., e_n]`, `vec![x; n]`, and [`Vec::with_capacity(n)`] produce a `Vec`
389/// that requests an allocation of the exact size needed for precisely `n` elements from the allocator,
390/// and no other size (such as, for example: a size rounded up to the nearest power of 2).
391/// The allocator will return an allocation that is at least as large as requested, but it may be larger.
392///
393/// It is guaranteed that the [`Vec::capacity`] method returns a value that is at least the requested capacity
394/// and not more than the allocated capacity.
395///
396/// The method [`Vec::shrink_to_fit`] will attempt to discard excess capacity an allocator has given to a `Vec`.
397/// If <code>[len] == [capacity]</code>, then a `Vec<T>` can be converted
398/// to and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
399/// `Vec` exploits this fact as much as reasonable when implementing common conversions
400/// such as [`into_boxed_slice`].
401///
402/// `Vec` will not specifically overwrite any data that is removed from it,
403/// but also won't specifically preserve it. Its uninitialized memory is
404/// scratch space that it may use however it wants. It will generally just do
405/// whatever is most efficient or otherwise easy to implement. Do not rely on
406/// removed data to be erased for security purposes. Even if you drop a `Vec`, its
407/// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory
408/// first, that might not actually happen because the optimizer does not consider
409/// this a side-effect that must be preserved. There is one case which we will
410/// not break, however: using `unsafe` code to write to the excess capacity,
411/// and then increasing the length to match, is always valid.
412///
413/// Currently, `Vec` does not guarantee the order in which elements are dropped.
414/// The order has changed in the past and may change again.
415///
416/// [`get`]: slice::get
417/// [`get_mut`]: slice::get_mut
418/// [`String`]: crate::string::String
419/// [`&str`]: type@str
420/// [`shrink_to_fit`]: Vec::shrink_to_fit
421/// [`shrink_to`]: Vec::shrink_to
422/// [capacity]: Vec::capacity
423/// [`capacity`]: Vec::capacity
424/// [`Vec::capacity`]: Vec::capacity
425/// [size_of::\<T>]: size_of
426/// [len]: Vec::len
427/// [`len`]: Vec::len
428/// [`push`]: Vec::push
429/// [`insert`]: Vec::insert
430/// [`reserve`]: Vec::reserve
431/// [`Vec::with_capacity(n)`]: Vec::with_capacity
432/// [`MaybeUninit`]: core::mem::MaybeUninit
433/// [owned slice]: Box
434/// [`into_boxed_slice`]: Vec::into_boxed_slice
435#[stable(feature = "rust1", since = "1.0.0")]
436#[rustc_diagnostic_item = "Vec"]
437#[rustc_insignificant_dtor]
438#[doc(alias = "list")]
439#[doc(alias = "vector")]
440pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
441 buf: RawVec<T, A>,
442 len: usize,
443}
444
445////////////////////////////////////////////////////////////////////////////////
446// Inherent methods
447////////////////////////////////////////////////////////////////////////////////
448
449impl<T> Vec<T> {
450 /// Constructs a new, empty `Vec<T>`.
451 ///
452 /// The vector will not allocate until elements are pushed onto it.
453 ///
454 /// # Examples
455 ///
456 /// ```
457 /// # #![allow(unused_mut)]
458 /// let mut vec: Vec<i32> = Vec::new();
459 /// ```
460 #[inline]
461 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
462 #[rustc_diagnostic_item = "vec_new"]
463 #[stable(feature = "rust1", since = "1.0.0")]
464 #[must_use]
465 pub const fn new() -> Self {
466 Vec { buf: RawVec::new(), len: 0 }
467 }
468
469 /// Constructs a new, empty `Vec<T>` with at least the specified capacity.
470 ///
471 /// The vector will be able to hold at least `capacity` elements without
472 /// reallocating. This method is allowed to allocate for more elements than
473 /// `capacity`. If `capacity` is zero, the vector will not allocate.
474 ///
475 /// It is important to note that although the returned vector has the
476 /// minimum *capacity* specified, the vector will have a zero *length*. For
477 /// an explanation of the difference between length and capacity, see
478 /// *[Capacity and reallocation]*.
479 ///
480 /// If it is important to know the exact allocated capacity of a `Vec`,
481 /// always use the [`capacity`] method after construction.
482 ///
483 /// For `Vec<T>` where `T` is a zero-sized type, there will be no allocation
484 /// and the capacity will always be `usize::MAX`.
485 ///
486 /// [Capacity and reallocation]: #capacity-and-reallocation
487 /// [`capacity`]: Vec::capacity
488 ///
489 /// # Panics
490 ///
491 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
492 ///
493 /// # Examples
494 ///
495 /// ```
496 /// let mut vec = Vec::with_capacity(10);
497 ///
498 /// // The vector contains no items, even though it has capacity for more
499 /// assert_eq!(vec.len(), 0);
500 /// assert!(vec.capacity() >= 10);
501 ///
502 /// // These are all done without reallocating...
503 /// for i in 0..10 {
504 /// vec.push(i);
505 /// }
506 /// assert_eq!(vec.len(), 10);
507 /// assert!(vec.capacity() >= 10);
508 ///
509 /// // ...but this may make the vector reallocate
510 /// vec.push(11);
511 /// assert_eq!(vec.len(), 11);
512 /// assert!(vec.capacity() >= 11);
513 ///
514 /// // A vector of a zero-sized type will always over-allocate, since no
515 /// // allocation is necessary
516 /// let vec_units = Vec::<()>::with_capacity(10);
517 /// assert_eq!(vec_units.capacity(), usize::MAX);
518 /// ```
519 #[cfg(not(no_global_oom_handling))]
520 #[inline]
521 #[stable(feature = "rust1", since = "1.0.0")]
522 #[must_use]
523 #[rustc_diagnostic_item = "vec_with_capacity"]
524 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
525 pub const fn with_capacity(capacity: usize) -> Self {
526 Self::with_capacity_in(capacity, Global)
527 }
528
529 /// Constructs a new, empty `Vec<T>` with at least the specified capacity.
530 ///
531 /// The vector will be able to hold at least `capacity` elements without
532 /// reallocating. This method is allowed to allocate for more elements than
533 /// `capacity`. If `capacity` is zero, the vector will not allocate.
534 ///
535 /// # Errors
536 ///
537 /// Returns an error if the capacity exceeds `isize::MAX` _bytes_,
538 /// or if the allocator reports allocation failure.
539 #[inline]
540 #[unstable(feature = "try_with_capacity", issue = "91913")]
541 pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> {
542 Self::try_with_capacity_in(capacity, Global)
543 }
544
545 /// Creates a `Vec<T>` directly from a pointer, a length, and a capacity.
546 ///
547 /// # Safety
548 ///
549 /// This is highly unsafe, due to the number of invariants that aren't
550 /// checked:
551 ///
552 /// * If `T` is not a zero-sized type and the capacity is nonzero, `ptr` must have
553 /// been allocated using the global allocator, such as via the [`alloc::alloc`]
554 /// function. If `T` is a zero-sized type or the capacity is zero, `ptr` need
555 /// only be non-null and aligned.
556 /// * `T` needs to have the same alignment as what `ptr` was allocated with,
557 /// if the pointer is required to be allocated.
558 /// (`T` having a less strict alignment is not sufficient, the alignment really
559 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
560 /// allocated and deallocated with the same layout.)
561 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes), if
562 /// nonzero, needs to be the same size as the pointer was allocated with.
563 /// (Because similar to alignment, [`dealloc`] must be called with the same
564 /// layout `size`.)
565 /// * `length` needs to be less than or equal to `capacity`.
566 /// * The first `length` values must be properly initialized values of type `T`.
567 /// * `capacity` needs to be the capacity that the pointer was allocated with,
568 /// if the pointer is required to be allocated.
569 /// * The allocated size in bytes must be no larger than `isize::MAX`.
570 /// See the safety documentation of [`pointer::offset`].
571 ///
572 /// These requirements are always upheld by any `ptr` that has been allocated
573 /// via `Vec<T>`. Other allocation sources are allowed if the invariants are
574 /// upheld.
575 ///
576 /// Violating these may cause problems like corrupting the allocator's
577 /// internal data structures. For example it is normally **not** safe
578 /// to build a `Vec<u8>` from a pointer to a C `char` array with length
579 /// `size_t`, doing so is only safe if the array was initially allocated by
580 /// a `Vec` or `String`.
581 /// It's also not safe to build one from a `Vec<u16>` and its length, because
582 /// the allocator cares about the alignment, and these two types have different
583 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
584 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
585 /// these issues, it is often preferable to do casting/transmuting using
586 /// [`slice::from_raw_parts`] instead.
587 ///
588 /// The ownership of `ptr` is effectively transferred to the
589 /// `Vec<T>` which may then deallocate, reallocate or change the
590 /// contents of memory pointed to by the pointer at will. Ensure
591 /// that nothing else uses the pointer after calling this
592 /// function.
593 ///
594 /// [`String`]: crate::string::String
595 /// [`alloc::alloc`]: crate::alloc::alloc
596 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
597 ///
598 /// # Examples
599 ///
600 /// ```
601 /// use std::ptr;
602 ///
603 /// let v = vec![1, 2, 3];
604 ///
605 /// // Deconstruct the vector into parts.
606 /// let (p, len, cap) = v.into_raw_parts();
607 ///
608 /// unsafe {
609 /// // Overwrite memory with 4, 5, 6
610 /// for i in 0..len {
611 /// ptr::write(p.add(i), 4 + i);
612 /// }
613 ///
614 /// // Put everything back together into a Vec
615 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
616 /// assert_eq!(rebuilt, [4, 5, 6]);
617 /// }
618 /// ```
619 ///
620 /// Using memory that was allocated elsewhere:
621 ///
622 /// ```rust
623 /// use std::alloc::{alloc, Layout};
624 ///
625 /// fn main() {
626 /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
627 ///
628 /// let vec = unsafe {
629 /// let mem = alloc(layout).cast::<u32>();
630 /// if mem.is_null() {
631 /// return;
632 /// }
633 ///
634 /// mem.write(1_000_000);
635 ///
636 /// Vec::from_raw_parts(mem, 1, 16)
637 /// };
638 ///
639 /// assert_eq!(vec, &[1_000_000]);
640 /// assert_eq!(vec.capacity(), 16);
641 /// }
642 /// ```
643 #[inline]
644 #[stable(feature = "rust1", since = "1.0.0")]
645 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
646 unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
647 }
648
649 #[doc(alias = "from_non_null_parts")]
650 /// Creates a `Vec<T>` directly from a `NonNull` pointer, a length, and a capacity.
651 ///
652 /// # Safety
653 ///
654 /// This is highly unsafe, due to the number of invariants that aren't
655 /// checked:
656 ///
657 /// * `ptr` must have been allocated using the global allocator, such as via
658 /// the [`alloc::alloc`] function.
659 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
660 /// (`T` having a less strict alignment is not sufficient, the alignment really
661 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
662 /// allocated and deallocated with the same layout.)
663 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
664 /// to be the same size as the pointer was allocated with. (Because similar to
665 /// alignment, [`dealloc`] must be called with the same layout `size`.)
666 /// * `length` needs to be less than or equal to `capacity`.
667 /// * The first `length` values must be properly initialized values of type `T`.
668 /// * `capacity` needs to be the capacity that the pointer was allocated with.
669 /// * The allocated size in bytes must be no larger than `isize::MAX`.
670 /// See the safety documentation of [`pointer::offset`].
671 ///
672 /// These requirements are always upheld by any `ptr` that has been allocated
673 /// via `Vec<T>`. Other allocation sources are allowed if the invariants are
674 /// upheld.
675 ///
676 /// Violating these may cause problems like corrupting the allocator's
677 /// internal data structures. For example it is normally **not** safe
678 /// to build a `Vec<u8>` from a pointer to a C `char` array with length
679 /// `size_t`, doing so is only safe if the array was initially allocated by
680 /// a `Vec` or `String`.
681 /// It's also not safe to build one from a `Vec<u16>` and its length, because
682 /// the allocator cares about the alignment, and these two types have different
683 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
684 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
685 /// these issues, it is often preferable to do casting/transmuting using
686 /// [`NonNull::slice_from_raw_parts`] instead.
687 ///
688 /// The ownership of `ptr` is effectively transferred to the
689 /// `Vec<T>` which may then deallocate, reallocate or change the
690 /// contents of memory pointed to by the pointer at will. Ensure
691 /// that nothing else uses the pointer after calling this
692 /// function.
693 ///
694 /// [`String`]: crate::string::String
695 /// [`alloc::alloc`]: crate::alloc::alloc
696 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
697 ///
698 /// # Examples
699 ///
700 /// ```
701 /// #![feature(box_vec_non_null)]
702 ///
703 /// let v = vec![1, 2, 3];
704 ///
705 /// // Deconstruct the vector into parts.
706 /// let (p, len, cap) = v.into_parts();
707 ///
708 /// unsafe {
709 /// // Overwrite memory with 4, 5, 6
710 /// for i in 0..len {
711 /// p.add(i).write(4 + i);
712 /// }
713 ///
714 /// // Put everything back together into a Vec
715 /// let rebuilt = Vec::from_parts(p, len, cap);
716 /// assert_eq!(rebuilt, [4, 5, 6]);
717 /// }
718 /// ```
719 ///
720 /// Using memory that was allocated elsewhere:
721 ///
722 /// ```rust
723 /// #![feature(box_vec_non_null)]
724 ///
725 /// use std::alloc::{alloc, Layout};
726 /// use std::ptr::NonNull;
727 ///
728 /// fn main() {
729 /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
730 ///
731 /// let vec = unsafe {
732 /// let Some(mem) = NonNull::new(alloc(layout).cast::<u32>()) else {
733 /// return;
734 /// };
735 ///
736 /// mem.write(1_000_000);
737 ///
738 /// Vec::from_parts(mem, 1, 16)
739 /// };
740 ///
741 /// assert_eq!(vec, &[1_000_000]);
742 /// assert_eq!(vec.capacity(), 16);
743 /// }
744 /// ```
745 #[inline]
746 #[unstable(feature = "box_vec_non_null", issue = "130364")]
747 pub unsafe fn from_parts(ptr: NonNull<T>, length: usize, capacity: usize) -> Self {
748 unsafe { Self::from_parts_in(ptr, length, capacity, Global) }
749 }
750
751 /// Creates a `Vec<T>` where each element is produced by calling `f` with
752 /// that element's index while walking forward through the `Vec<T>`.
753 ///
754 /// This is essentially the same as writing
755 ///
756 /// ```text
757 /// vec![f(0), f(1), f(2), …, f(length - 2), f(length - 1)]
758 /// ```
759 /// and is similar to `(0..i).map(f)`, just for `Vec<T>`s not iterators.
760 ///
761 /// If `length == 0`, this produces an empty `Vec<T>` without ever calling `f`.
762 ///
763 /// # Example
764 ///
765 /// ```rust
766 /// #![feature(vec_from_fn)]
767 ///
768 /// let vec = Vec::from_fn(5, |i| i);
769 ///
770 /// // indexes are: 0 1 2 3 4
771 /// assert_eq!(vec, [0, 1, 2, 3, 4]);
772 ///
773 /// let vec2 = Vec::from_fn(8, |i| i * 2);
774 ///
775 /// // indexes are: 0 1 2 3 4 5 6 7
776 /// assert_eq!(vec2, [0, 2, 4, 6, 8, 10, 12, 14]);
777 ///
778 /// let bool_vec = Vec::from_fn(5, |i| i % 2 == 0);
779 ///
780 /// // indexes are: 0 1 2 3 4
781 /// assert_eq!(bool_vec, [true, false, true, false, true]);
782 /// ```
783 ///
784 /// The `Vec<T>` is generated in ascending index order, starting from the front
785 /// and going towards the back, so you can use closures with mutable state:
786 /// ```
787 /// #![feature(vec_from_fn)]
788 ///
789 /// let mut state = 1;
790 /// let a = Vec::from_fn(6, |_| { let x = state; state *= 2; x });
791 ///
792 /// assert_eq!(a, [1, 2, 4, 8, 16, 32]);
793 /// ```
794 #[cfg(not(no_global_oom_handling))]
795 #[inline]
796 #[unstable(feature = "vec_from_fn", issue = "149698")]
797 pub fn from_fn<F>(length: usize, f: F) -> Self
798 where
799 F: FnMut(usize) -> T,
800 {
801 (0..length).map(f).collect()
802 }
803
804 /// Decomposes a `Vec<T>` into its raw components: `(pointer, length, capacity)`.
805 ///
806 /// Returns the raw pointer to the underlying data, the length of
807 /// the vector (in elements), and the allocated capacity of the
808 /// data (in elements). These are the same arguments in the same
809 /// order as the arguments to [`from_raw_parts`].
810 ///
811 /// After calling this function, the caller is responsible for the
812 /// memory previously managed by the `Vec`. Most often, one does
813 /// this by converting the raw pointer, length, and capacity back
814 /// into a `Vec` with the [`from_raw_parts`] function; more generally,
815 /// if `T` is non-zero-sized and the capacity is nonzero, one may use
816 /// any method that calls [`dealloc`] with a layout of
817 /// `Layout::array::<T>(capacity)`; if `T` is zero-sized or the
818 /// capacity is zero, nothing needs to be done.
819 ///
820 /// [`from_raw_parts`]: Vec::from_raw_parts
821 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
822 ///
823 /// # Examples
824 ///
825 /// ```
826 /// let v: Vec<i32> = vec![-1, 0, 1];
827 ///
828 /// let (ptr, len, cap) = v.into_raw_parts();
829 ///
830 /// let rebuilt = unsafe {
831 /// // We can now make changes to the components, such as
832 /// // transmuting the raw pointer to a compatible type.
833 /// let ptr = ptr as *mut u32;
834 ///
835 /// Vec::from_raw_parts(ptr, len, cap)
836 /// };
837 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
838 /// ```
839 #[must_use = "losing the pointer will leak memory"]
840 #[stable(feature = "vec_into_raw_parts", since = "1.93.0")]
841 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
842 let mut me = ManuallyDrop::new(self);
843 (me.as_mut_ptr(), me.len(), me.capacity())
844 }
845
846 #[doc(alias = "into_non_null_parts")]
847 /// Decomposes a `Vec<T>` into its raw components: `(NonNull pointer, length, capacity)`.
848 ///
849 /// Returns the `NonNull` pointer to the underlying data, the length of
850 /// the vector (in elements), and the allocated capacity of the
851 /// data (in elements). These are the same arguments in the same
852 /// order as the arguments to [`from_parts`].
853 ///
854 /// After calling this function, the caller is responsible for the
855 /// memory previously managed by the `Vec`. The only way to do
856 /// this is to convert the `NonNull` pointer, length, and capacity back
857 /// into a `Vec` with the [`from_parts`] function, allowing
858 /// the destructor to perform the cleanup.
859 ///
860 /// [`from_parts`]: Vec::from_parts
861 ///
862 /// # Examples
863 ///
864 /// ```
865 /// #![feature(box_vec_non_null)]
866 ///
867 /// let v: Vec<i32> = vec![-1, 0, 1];
868 ///
869 /// let (ptr, len, cap) = v.into_parts();
870 ///
871 /// let rebuilt = unsafe {
872 /// // We can now make changes to the components, such as
873 /// // transmuting the raw pointer to a compatible type.
874 /// let ptr = ptr.cast::<u32>();
875 ///
876 /// Vec::from_parts(ptr, len, cap)
877 /// };
878 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
879 /// ```
880 #[must_use = "losing the pointer will leak memory"]
881 #[unstable(feature = "box_vec_non_null", issue = "130364")]
882 pub fn into_parts(self) -> (NonNull<T>, usize, usize) {
883 let (ptr, len, capacity) = self.into_raw_parts();
884 // SAFETY: A `Vec` always has a non-null pointer.
885 (unsafe { NonNull::new_unchecked(ptr) }, len, capacity)
886 }
887
888 /// Interns the `Vec<T>`, making the underlying memory read-only. This method should be
889 /// called during compile time. (This is a no-op if called during runtime)
890 ///
891 /// This method must be called if the memory used by `Vec` needs to appear in the final
892 /// values of constants.
893 #[unstable(feature = "const_heap", issue = "79597")]
894 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
895 pub const fn const_make_global(mut self) -> &'static [T]
896 where
897 T: Freeze,
898 {
899 unsafe { core::intrinsics::const_make_global(self.as_mut_ptr().cast()) };
900 let me = ManuallyDrop::new(self);
901 unsafe { slice::from_raw_parts(me.as_ptr(), me.len) }
902 }
903}
904
905#[cfg(not(no_global_oom_handling))]
906#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
907#[rustfmt::skip] // FIXME(fee1-dead): temporary measure before rustfmt is bumped
908const impl<T, A: [const] Allocator + [const] Destruct> Vec<T, A> {
909 /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity
910 /// with the provided allocator.
911 ///
912 /// The vector will be able to hold at least `capacity` elements without
913 /// reallocating. This method is allowed to allocate for more elements than
914 /// `capacity`. If `capacity` is zero, the vector will not allocate.
915 ///
916 /// It is important to note that although the returned vector has the
917 /// minimum *capacity* specified, the vector will have a zero *length*. For
918 /// an explanation of the difference between length and capacity, see
919 /// *[Capacity and reallocation]*.
920 ///
921 /// If it is important to know the exact allocated capacity of a `Vec`,
922 /// always use the [`capacity`] method after construction.
923 ///
924 /// For `Vec<T, A>` where `T` is a zero-sized type, there will be no allocation
925 /// and the capacity will always be `usize::MAX`.
926 ///
927 /// [Capacity and reallocation]: #capacity-and-reallocation
928 /// [`capacity`]: Vec::capacity
929 ///
930 /// # Panics
931 ///
932 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
933 ///
934 /// # Examples
935 ///
936 /// ```
937 /// #![feature(allocator_api)]
938 ///
939 /// use std::alloc::System;
940 ///
941 /// let mut vec = Vec::with_capacity_in(10, System);
942 ///
943 /// // The vector contains no items, even though it has capacity for more
944 /// assert_eq!(vec.len(), 0);
945 /// assert!(vec.capacity() >= 10);
946 ///
947 /// // These are all done without reallocating...
948 /// for i in 0..10 {
949 /// vec.push(i);
950 /// }
951 /// assert_eq!(vec.len(), 10);
952 /// assert!(vec.capacity() >= 10);
953 ///
954 /// // ...but this may make the vector reallocate
955 /// vec.push(11);
956 /// assert_eq!(vec.len(), 11);
957 /// assert!(vec.capacity() >= 11);
958 ///
959 /// // A vector of a zero-sized type will always over-allocate, since no
960 /// // allocation is necessary
961 /// let vec_units = Vec::<(), System>::with_capacity_in(10, System);
962 /// assert_eq!(vec_units.capacity(), usize::MAX);
963 /// ```
964 #[inline]
965 #[unstable(feature = "allocator_api", issue = "32838")]
966 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
967 Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
968 }
969
970 /// Appends an element to the back of a collection.
971 ///
972 /// # Panics
973 ///
974 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
975 ///
976 /// # Examples
977 ///
978 /// ```
979 /// let mut vec = vec![1, 2];
980 /// vec.push(3);
981 /// assert_eq!(vec, [1, 2, 3]);
982 /// ```
983 ///
984 /// # Time complexity
985 ///
986 /// Takes amortized *O*(1) time. If the vector's length would exceed its
987 /// capacity after the push, *O*(*capacity*) time is taken to copy the
988 /// vector's elements to a larger allocation. This expensive operation is
989 /// offset by the *capacity* *O*(1) insertions it allows.
990 #[inline]
991 #[stable(feature = "rust1", since = "1.0.0")]
992 #[rustc_confusables("push_back", "put", "append")]
993 pub fn push(&mut self, value: T) {
994 let _ = self.push_mut(value);
995 }
996
997 /// Appends an element to the back of a collection, returning a reference to it.
998 ///
999 /// # Panics
1000 ///
1001 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1002 ///
1003 /// # Examples
1004 ///
1005 /// ```
1006 /// let mut vec = vec![1, 2];
1007 /// let last = vec.push_mut(3);
1008 /// assert_eq!(*last, 3);
1009 /// assert_eq!(vec, [1, 2, 3]);
1010 ///
1011 /// let last = vec.push_mut(3);
1012 /// *last += 1;
1013 /// assert_eq!(vec, [1, 2, 3, 4]);
1014 /// ```
1015 ///
1016 /// # Time complexity
1017 ///
1018 /// Takes amortized *O*(1) time. If the vector's length would exceed its
1019 /// capacity after the push, *O*(*capacity*) time is taken to copy the
1020 /// vector's elements to a larger allocation. This expensive operation is
1021 /// offset by the *capacity* *O*(1) insertions it allows.
1022 #[inline]
1023 #[stable(feature = "push_mut", since = "CURRENT_RUSTC_VERSION")]
1024 #[must_use = "if you don't need a reference to the value, use `Vec::push` instead"]
1025 pub fn push_mut(&mut self, value: T) -> &mut T {
1026 // Inform codegen that the length does not change across grow_one().
1027 let len = self.len;
1028 // This will panic or abort if we would allocate > isize::MAX bytes
1029 // or if the length increment would overflow for zero-sized types.
1030 if len == self.buf.capacity() {
1031 self.buf.grow_one();
1032 }
1033 unsafe {
1034 let end = self.as_mut_ptr().add(len);
1035 ptr::write(end, value);
1036 self.len = len + 1;
1037 // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference.
1038 &mut *end
1039 }
1040 }
1041}
1042
1043impl<T, A: Allocator> Vec<T, A> {
1044 /// Constructs a new, empty `Vec<T, A>`.
1045 ///
1046 /// The vector will not allocate until elements are pushed onto it.
1047 ///
1048 /// # Examples
1049 ///
1050 /// ```
1051 /// #![feature(allocator_api)]
1052 ///
1053 /// use std::alloc::System;
1054 ///
1055 /// # #[allow(unused_mut)]
1056 /// let mut vec: Vec<i32, _> = Vec::new_in(System);
1057 /// ```
1058 #[inline]
1059 #[unstable(feature = "allocator_api", issue = "32838")]
1060 pub const fn new_in(alloc: A) -> Self {
1061 Vec { buf: RawVec::new_in(alloc), len: 0 }
1062 }
1063
1064 /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity
1065 /// with the provided allocator.
1066 ///
1067 /// The vector will be able to hold at least `capacity` elements without
1068 /// reallocating. This method is allowed to allocate for more elements than
1069 /// `capacity`. If `capacity` is zero, the vector will not allocate.
1070 ///
1071 /// # Errors
1072 ///
1073 /// Returns an error if the capacity exceeds `isize::MAX` _bytes_,
1074 /// or if the allocator reports allocation failure.
1075 #[inline]
1076 #[unstable(feature = "allocator_api", issue = "32838")]
1077 // #[unstable(feature = "try_with_capacity", issue = "91913")]
1078 pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
1079 Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 })
1080 }
1081
1082 /// Creates a `Vec<T, A>` directly from a pointer, a length, a capacity,
1083 /// and an allocator.
1084 ///
1085 /// # Safety
1086 ///
1087 /// This is highly unsafe, due to the number of invariants that aren't
1088 /// checked:
1089 ///
1090 /// * `ptr` must be [*currently allocated*] via the given allocator `alloc`.
1091 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
1092 /// (`T` having a less strict alignment is not sufficient, the alignment really
1093 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
1094 /// allocated and deallocated with the same layout.)
1095 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
1096 /// to be the same size as the pointer was allocated with. (Because similar to
1097 /// alignment, [`dealloc`] must be called with the same layout `size`.)
1098 /// * `length` needs to be less than or equal to `capacity`.
1099 /// * The first `length` values must be properly initialized values of type `T`.
1100 /// * `capacity` needs to [*fit*] the layout size that the pointer was allocated with.
1101 /// * The allocated size in bytes must be no larger than `isize::MAX`.
1102 /// See the safety documentation of [`pointer::offset`].
1103 ///
1104 /// These requirements are always upheld by any `ptr` that has been allocated
1105 /// via `Vec<T, A>`. Other allocation sources are allowed if the invariants are
1106 /// upheld.
1107 ///
1108 /// Violating these may cause problems like corrupting the allocator's
1109 /// internal data structures. For example it is **not** safe
1110 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
1111 /// It's also not safe to build one from a `Vec<u16>` and its length, because
1112 /// the allocator cares about the alignment, and these two types have different
1113 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
1114 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
1115 ///
1116 /// The ownership of `ptr` is effectively transferred to the
1117 /// `Vec<T>` which may then deallocate, reallocate or change the
1118 /// contents of memory pointed to by the pointer at will. Ensure
1119 /// that nothing else uses the pointer after calling this
1120 /// function.
1121 ///
1122 /// [`String`]: crate::string::String
1123 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
1124 /// [*currently allocated*]: crate::alloc::Allocator#currently-allocated-memory
1125 /// [*fit*]: crate::alloc::Allocator#memory-fitting
1126 ///
1127 /// # Examples
1128 ///
1129 /// ```
1130 /// #![feature(allocator_api)]
1131 ///
1132 /// use std::alloc::System;
1133 ///
1134 /// use std::ptr;
1135 ///
1136 /// let mut v = Vec::with_capacity_in(3, System);
1137 /// v.push(1);
1138 /// v.push(2);
1139 /// v.push(3);
1140 ///
1141 /// // Deconstruct the vector into parts.
1142 /// let (p, len, cap, alloc) = v.into_raw_parts_with_alloc();
1143 ///
1144 /// unsafe {
1145 /// // Overwrite memory with 4, 5, 6
1146 /// for i in 0..len {
1147 /// ptr::write(p.add(i), 4 + i);
1148 /// }
1149 ///
1150 /// // Put everything back together into a Vec
1151 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
1152 /// assert_eq!(rebuilt, [4, 5, 6]);
1153 /// }
1154 /// ```
1155 ///
1156 /// Using memory that was allocated elsewhere:
1157 ///
1158 /// ```rust
1159 /// #![feature(allocator_api)]
1160 ///
1161 /// use std::alloc::{AllocError, Allocator, Global, Layout};
1162 ///
1163 /// fn main() {
1164 /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
1165 ///
1166 /// let vec = unsafe {
1167 /// let mem = match Global.allocate(layout) {
1168 /// Ok(mem) => mem.cast::<u32>().as_ptr(),
1169 /// Err(AllocError) => return,
1170 /// };
1171 ///
1172 /// mem.write(1_000_000);
1173 ///
1174 /// Vec::from_raw_parts_in(mem, 1, 16, Global)
1175 /// };
1176 ///
1177 /// assert_eq!(vec, &[1_000_000]);
1178 /// assert_eq!(vec.capacity(), 16);
1179 /// }
1180 /// ```
1181 #[inline]
1182 #[unstable(feature = "allocator_api", issue = "32838")]
1183 pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
1184 ub_checks::assert_unsafe_precondition!(
1185 check_library_ub,
1186 "Vec::from_raw_parts_in requires that length <= capacity",
1187 (length: usize = length, capacity: usize = capacity) => length <= capacity
1188 );
1189 unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
1190 }
1191
1192 #[doc(alias = "from_non_null_parts_in")]
1193 /// Creates a `Vec<T, A>` directly from a `NonNull` pointer, a length, a capacity,
1194 /// and an allocator.
1195 ///
1196 /// # Safety
1197 ///
1198 /// This is highly unsafe, due to the number of invariants that aren't
1199 /// checked:
1200 ///
1201 /// * `ptr` must be [*currently allocated*] via the given allocator `alloc`.
1202 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
1203 /// (`T` having a less strict alignment is not sufficient, the alignment really
1204 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
1205 /// allocated and deallocated with the same layout.)
1206 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
1207 /// to be the same size as the pointer was allocated with. (Because similar to
1208 /// alignment, [`dealloc`] must be called with the same layout `size`.)
1209 /// * `length` needs to be less than or equal to `capacity`.
1210 /// * The first `length` values must be properly initialized values of type `T`.
1211 /// * `capacity` needs to [*fit*] the layout size that the pointer was allocated with.
1212 /// * The allocated size in bytes must be no larger than `isize::MAX`.
1213 /// See the safety documentation of [`pointer::offset`].
1214 ///
1215 /// These requirements are always upheld by any `ptr` that has been allocated
1216 /// via `Vec<T, A>`. Other allocation sources are allowed if the invariants are
1217 /// upheld.
1218 ///
1219 /// Violating these may cause problems like corrupting the allocator's
1220 /// internal data structures. For example it is **not** safe
1221 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
1222 /// It's also not safe to build one from a `Vec<u16>` and its length, because
1223 /// the allocator cares about the alignment, and these two types have different
1224 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
1225 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
1226 ///
1227 /// The ownership of `ptr` is effectively transferred to the
1228 /// `Vec<T>` which may then deallocate, reallocate or change the
1229 /// contents of memory pointed to by the pointer at will. Ensure
1230 /// that nothing else uses the pointer after calling this
1231 /// function.
1232 ///
1233 /// [`String`]: crate::string::String
1234 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
1235 /// [*currently allocated*]: crate::alloc::Allocator#currently-allocated-memory
1236 /// [*fit*]: crate::alloc::Allocator#memory-fitting
1237 ///
1238 /// # Examples
1239 ///
1240 /// ```
1241 /// #![feature(allocator_api, box_vec_non_null)]
1242 ///
1243 /// use std::alloc::System;
1244 ///
1245 /// let mut v = Vec::with_capacity_in(3, System);
1246 /// v.push(1);
1247 /// v.push(2);
1248 /// v.push(3);
1249 ///
1250 /// // Deconstruct the vector into parts.
1251 /// let (p, len, cap, alloc) = v.into_parts_with_alloc();
1252 ///
1253 /// unsafe {
1254 /// // Overwrite memory with 4, 5, 6
1255 /// for i in 0..len {
1256 /// p.add(i).write(4 + i);
1257 /// }
1258 ///
1259 /// // Put everything back together into a Vec
1260 /// let rebuilt = Vec::from_parts_in(p, len, cap, alloc.clone());
1261 /// assert_eq!(rebuilt, [4, 5, 6]);
1262 /// }
1263 /// ```
1264 ///
1265 /// Using memory that was allocated elsewhere:
1266 ///
1267 /// ```rust
1268 /// #![feature(allocator_api, box_vec_non_null)]
1269 ///
1270 /// use std::alloc::{AllocError, Allocator, Global, Layout};
1271 ///
1272 /// fn main() {
1273 /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
1274 ///
1275 /// let vec = unsafe {
1276 /// let mem = match Global.allocate(layout) {
1277 /// Ok(mem) => mem.cast::<u32>(),
1278 /// Err(AllocError) => return,
1279 /// };
1280 ///
1281 /// mem.write(1_000_000);
1282 ///
1283 /// Vec::from_parts_in(mem, 1, 16, Global)
1284 /// };
1285 ///
1286 /// assert_eq!(vec, &[1_000_000]);
1287 /// assert_eq!(vec.capacity(), 16);
1288 /// }
1289 /// ```
1290 #[inline]
1291 #[unstable(feature = "allocator_api", issue = "32838")]
1292 // #[unstable(feature = "box_vec_non_null", issue = "130364")]
1293 pub unsafe fn from_parts_in(ptr: NonNull<T>, length: usize, capacity: usize, alloc: A) -> Self {
1294 ub_checks::assert_unsafe_precondition!(
1295 check_library_ub,
1296 "Vec::from_parts_in requires that length <= capacity",
1297 (length: usize = length, capacity: usize = capacity) => length <= capacity
1298 );
1299 unsafe { Vec { buf: RawVec::from_nonnull_in(ptr, capacity, alloc), len: length } }
1300 }
1301
1302 /// Decomposes a `Vec<T>` into its raw components: `(pointer, length, capacity, allocator)`.
1303 ///
1304 /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
1305 /// the allocated capacity of the data (in elements), and the allocator. These are the same
1306 /// arguments in the same order as the arguments to [`from_raw_parts_in`].
1307 ///
1308 /// After calling this function, the caller is responsible for the
1309 /// memory previously managed by the `Vec`. The only way to do
1310 /// this is to convert the raw pointer, length, and capacity back
1311 /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
1312 /// the destructor to perform the cleanup.
1313 ///
1314 /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
1315 ///
1316 /// # Examples
1317 ///
1318 /// ```
1319 /// #![feature(allocator_api)]
1320 ///
1321 /// use std::alloc::System;
1322 ///
1323 /// let mut v: Vec<i32, System> = Vec::new_in(System);
1324 /// v.push(-1);
1325 /// v.push(0);
1326 /// v.push(1);
1327 ///
1328 /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
1329 ///
1330 /// let rebuilt = unsafe {
1331 /// // We can now make changes to the components, such as
1332 /// // transmuting the raw pointer to a compatible type.
1333 /// let ptr = ptr as *mut u32;
1334 ///
1335 /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
1336 /// };
1337 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
1338 /// ```
1339 #[must_use = "losing the pointer will leak memory"]
1340 #[unstable(feature = "allocator_api", issue = "32838")]
1341 pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
1342 let mut me = ManuallyDrop::new(self);
1343 let len = me.len();
1344 let capacity = me.capacity();
1345 let ptr = me.as_mut_ptr();
1346 let alloc = unsafe { ptr::read(me.allocator()) };
1347 (ptr, len, capacity, alloc)
1348 }
1349
1350 #[doc(alias = "into_non_null_parts_with_alloc")]
1351 /// Decomposes a `Vec<T>` into its raw components: `(NonNull pointer, length, capacity, allocator)`.
1352 ///
1353 /// Returns the `NonNull` pointer to the underlying data, the length of the vector (in elements),
1354 /// the allocated capacity of the data (in elements), and the allocator. These are the same
1355 /// arguments in the same order as the arguments to [`from_parts_in`].
1356 ///
1357 /// After calling this function, the caller is responsible for the
1358 /// memory previously managed by the `Vec`. The only way to do
1359 /// this is to convert the `NonNull` pointer, length, and capacity back
1360 /// into a `Vec` with the [`from_parts_in`] function, allowing
1361 /// the destructor to perform the cleanup.
1362 ///
1363 /// [`from_parts_in`]: Vec::from_parts_in
1364 ///
1365 /// # Examples
1366 ///
1367 /// ```
1368 /// #![feature(allocator_api, box_vec_non_null)]
1369 ///
1370 /// use std::alloc::System;
1371 ///
1372 /// let mut v: Vec<i32, System> = Vec::new_in(System);
1373 /// v.push(-1);
1374 /// v.push(0);
1375 /// v.push(1);
1376 ///
1377 /// let (ptr, len, cap, alloc) = v.into_parts_with_alloc();
1378 ///
1379 /// let rebuilt = unsafe {
1380 /// // We can now make changes to the components, such as
1381 /// // transmuting the raw pointer to a compatible type.
1382 /// let ptr = ptr.cast::<u32>();
1383 ///
1384 /// Vec::from_parts_in(ptr, len, cap, alloc)
1385 /// };
1386 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
1387 /// ```
1388 #[must_use = "losing the pointer will leak memory"]
1389 #[unstable(feature = "allocator_api", issue = "32838")]
1390 // #[unstable(feature = "box_vec_non_null", issue = "130364")]
1391 pub fn into_parts_with_alloc(self) -> (NonNull<T>, usize, usize, A) {
1392 let (ptr, len, capacity, alloc) = self.into_raw_parts_with_alloc();
1393 // SAFETY: A `Vec` always has a non-null pointer.
1394 (unsafe { NonNull::new_unchecked(ptr) }, len, capacity, alloc)
1395 }
1396
1397 /// Returns the total number of elements the vector can hold without
1398 /// reallocating.
1399 ///
1400 /// # Examples
1401 ///
1402 /// ```
1403 /// let mut vec: Vec<i32> = Vec::with_capacity(10);
1404 /// vec.push(42);
1405 /// assert!(vec.capacity() >= 10);
1406 /// ```
1407 ///
1408 /// A vector with zero-sized elements will always have a capacity of usize::MAX:
1409 ///
1410 /// ```
1411 /// #[derive(Clone)]
1412 /// struct ZeroSized;
1413 ///
1414 /// fn main() {
1415 /// assert_eq!(std::mem::size_of::<ZeroSized>(), 0);
1416 /// let v = vec![ZeroSized; 0];
1417 /// assert_eq!(v.capacity(), usize::MAX);
1418 /// }
1419 /// ```
1420 #[inline]
1421 #[stable(feature = "rust1", since = "1.0.0")]
1422 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1423 pub const fn capacity(&self) -> usize {
1424 self.buf.capacity()
1425 }
1426
1427 /// Reserves capacity for at least `additional` more elements to be inserted
1428 /// in the given `Vec<T>`. The collection may reserve more space to
1429 /// speculatively avoid frequent reallocations. After calling `reserve`,
1430 /// capacity will be greater than or equal to `self.len() + additional`.
1431 /// Does nothing if capacity is already sufficient.
1432 ///
1433 /// # Panics
1434 ///
1435 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1436 ///
1437 /// # Examples
1438 ///
1439 /// ```
1440 /// let mut vec = vec![1];
1441 /// vec.reserve(10);
1442 /// assert!(vec.capacity() >= 11);
1443 /// ```
1444 #[cfg(not(no_global_oom_handling))]
1445 #[stable(feature = "rust1", since = "1.0.0")]
1446 #[rustc_diagnostic_item = "vec_reserve"]
1447 pub fn reserve(&mut self, additional: usize) {
1448 self.buf.reserve(self.len, additional);
1449 }
1450
1451 /// Reserves the minimum capacity for at least `additional` more elements to
1452 /// be inserted in the given `Vec<T>`. Unlike [`reserve`], this will not
1453 /// deliberately over-allocate to speculatively avoid frequent allocations.
1454 /// After calling `reserve_exact`, capacity will be greater than or equal to
1455 /// `self.len() + additional`. Does nothing if the capacity is already
1456 /// sufficient.
1457 ///
1458 /// Note that the allocator may give the collection more space than it
1459 /// requests. Therefore, capacity can not be relied upon to be precisely
1460 /// minimal. Prefer [`reserve`] if future insertions are expected.
1461 ///
1462 /// [`reserve`]: Vec::reserve
1463 ///
1464 /// # Panics
1465 ///
1466 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
1467 ///
1468 /// # Examples
1469 ///
1470 /// ```
1471 /// let mut vec = vec![1];
1472 /// vec.reserve_exact(10);
1473 /// assert!(vec.capacity() >= 11);
1474 /// ```
1475 #[cfg(not(no_global_oom_handling))]
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 pub fn reserve_exact(&mut self, additional: usize) {
1478 self.buf.reserve_exact(self.len, additional);
1479 }
1480
1481 /// Tries to reserve capacity for at least `additional` more elements to be inserted
1482 /// in the given `Vec<T>`. The collection may reserve more space to speculatively avoid
1483 /// frequent reallocations. After calling `try_reserve`, capacity will be
1484 /// greater than or equal to `self.len() + additional` if it returns
1485 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1486 /// preserves the contents even if an error occurs.
1487 ///
1488 /// # Errors
1489 ///
1490 /// If the capacity overflows, or the allocator reports a failure, then an error
1491 /// is returned.
1492 ///
1493 /// # Examples
1494 ///
1495 /// ```
1496 /// use std::collections::TryReserveError;
1497 ///
1498 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
1499 /// let mut output = Vec::new();
1500 ///
1501 /// // Pre-reserve the memory, exiting if we can't
1502 /// output.try_reserve(data.len())?;
1503 ///
1504 /// // Now we know this can't OOM in the middle of our complex work
1505 /// output.extend(data.iter().map(|&val| {
1506 /// val * 2 + 5 // very complicated
1507 /// }));
1508 ///
1509 /// Ok(output)
1510 /// }
1511 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
1512 /// ```
1513 #[stable(feature = "try_reserve", since = "1.57.0")]
1514 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1515 self.buf.try_reserve(self.len, additional)
1516 }
1517
1518 /// Tries to reserve the minimum capacity for at least `additional`
1519 /// elements to be inserted in the given `Vec<T>`. Unlike [`try_reserve`],
1520 /// this will not deliberately over-allocate to speculatively avoid frequent
1521 /// allocations. After calling `try_reserve_exact`, capacity will be greater
1522 /// than or equal to `self.len() + additional` if it returns `Ok(())`.
1523 /// Does nothing if the capacity is already sufficient.
1524 ///
1525 /// Note that the allocator may give the collection more space than it
1526 /// requests. Therefore, capacity can not be relied upon to be precisely
1527 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1528 ///
1529 /// [`try_reserve`]: Vec::try_reserve
1530 ///
1531 /// # Errors
1532 ///
1533 /// If the capacity overflows, or the allocator reports a failure, then an error
1534 /// is returned.
1535 ///
1536 /// # Examples
1537 ///
1538 /// ```
1539 /// use std::collections::TryReserveError;
1540 ///
1541 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
1542 /// let mut output = Vec::new();
1543 ///
1544 /// // Pre-reserve the memory, exiting if we can't
1545 /// output.try_reserve_exact(data.len())?;
1546 ///
1547 /// // Now we know this can't OOM in the middle of our complex work
1548 /// output.extend(data.iter().map(|&val| {
1549 /// val * 2 + 5 // very complicated
1550 /// }));
1551 ///
1552 /// Ok(output)
1553 /// }
1554 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
1555 /// ```
1556 #[stable(feature = "try_reserve", since = "1.57.0")]
1557 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1558 self.buf.try_reserve_exact(self.len, additional)
1559 }
1560
1561 /// Shrinks the capacity of the vector as much as possible.
1562 ///
1563 /// The behavior of this method depends on the allocator, which may either shrink the vector
1564 /// in-place or reallocate. The resulting vector might still have some excess capacity, just as
1565 /// is the case for [`with_capacity`]. See [`Allocator::shrink`] for more details.
1566 ///
1567 /// [`with_capacity`]: Vec::with_capacity
1568 ///
1569 /// # Examples
1570 ///
1571 /// ```
1572 /// let mut vec = Vec::with_capacity(10);
1573 /// vec.extend([1, 2, 3]);
1574 /// assert!(vec.capacity() >= 10);
1575 /// vec.shrink_to_fit();
1576 /// assert!(vec.capacity() >= 3);
1577 /// ```
1578 #[cfg(not(no_global_oom_handling))]
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 #[inline]
1581 pub fn shrink_to_fit(&mut self) {
1582 // The capacity is never less than the length, and there's nothing to do when
1583 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
1584 // by only calling it with a greater capacity.
1585 if self.capacity() > self.len {
1586 self.buf.shrink_to_fit(self.len);
1587 }
1588 }
1589
1590 /// Shrinks the capacity of the vector with a lower bound.
1591 ///
1592 /// The capacity will remain at least as large as both the length
1593 /// and the supplied value.
1594 ///
1595 /// If the current capacity is less than the lower limit, this is a no-op.
1596 ///
1597 /// # Examples
1598 ///
1599 /// ```
1600 /// let mut vec = Vec::with_capacity(10);
1601 /// vec.extend([1, 2, 3]);
1602 /// assert!(vec.capacity() >= 10);
1603 /// vec.shrink_to(4);
1604 /// assert!(vec.capacity() >= 4);
1605 /// vec.shrink_to(0);
1606 /// assert!(vec.capacity() >= 3);
1607 /// ```
1608 #[cfg(not(no_global_oom_handling))]
1609 #[stable(feature = "shrink_to", since = "1.56.0")]
1610 pub fn shrink_to(&mut self, min_capacity: usize) {
1611 if self.capacity() > min_capacity {
1612 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
1613 }
1614 }
1615
1616 /// Converts the vector into [`Box<[T]>`][owned slice].
1617 ///
1618 /// Before doing the conversion, this method discards excess capacity like [`shrink_to_fit`].
1619 ///
1620 /// [owned slice]: Box
1621 /// [`shrink_to_fit`]: Vec::shrink_to_fit
1622 ///
1623 /// # Examples
1624 ///
1625 /// ```
1626 /// let v = vec![1, 2, 3];
1627 ///
1628 /// let slice = v.into_boxed_slice();
1629 /// ```
1630 ///
1631 /// Any excess capacity is removed:
1632 ///
1633 /// ```
1634 /// let mut vec = Vec::with_capacity(10);
1635 /// vec.extend([1, 2, 3]);
1636 ///
1637 /// assert!(vec.capacity() >= 10);
1638 /// let slice = vec.into_boxed_slice();
1639 /// assert_eq!(slice.into_vec().capacity(), 3);
1640 /// ```
1641 #[cfg(not(no_global_oom_handling))]
1642 #[stable(feature = "rust1", since = "1.0.0")]
1643 pub fn into_boxed_slice(mut self) -> Box<[T], A> {
1644 unsafe {
1645 self.shrink_to_fit();
1646 let me = ManuallyDrop::new(self);
1647 let buf = ptr::read(&me.buf);
1648 let len = me.len();
1649 buf.into_box(len).assume_init()
1650 }
1651 }
1652
1653 /// Shortens the vector, keeping the first `len` elements and dropping
1654 /// the rest.
1655 ///
1656 /// If `len` is greater or equal to the vector's current length, this has
1657 /// no effect.
1658 ///
1659 /// The [`drain`] method can emulate `truncate`, but causes the excess
1660 /// elements to be returned instead of dropped.
1661 ///
1662 /// Note that this method has no effect on the allocated capacity
1663 /// of the vector.
1664 ///
1665 /// # Examples
1666 ///
1667 /// Truncating a five element vector to two elements:
1668 ///
1669 /// ```
1670 /// let mut vec = vec![1, 2, 3, 4, 5];
1671 /// vec.truncate(2);
1672 /// assert_eq!(vec, [1, 2]);
1673 /// ```
1674 ///
1675 /// No truncation occurs when `len` is greater than the vector's current
1676 /// length:
1677 ///
1678 /// ```
1679 /// let mut vec = vec![1, 2, 3];
1680 /// vec.truncate(8);
1681 /// assert_eq!(vec, [1, 2, 3]);
1682 /// ```
1683 ///
1684 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
1685 /// method.
1686 ///
1687 /// ```
1688 /// let mut vec = vec![1, 2, 3];
1689 /// vec.truncate(0);
1690 /// assert_eq!(vec, []);
1691 /// ```
1692 ///
1693 /// [`clear`]: Vec::clear
1694 /// [`drain`]: Vec::drain
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 pub fn truncate(&mut self, len: usize) {
1697 // This is safe because:
1698 //
1699 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
1700 // case avoids creating an invalid slice, and
1701 // * the `len` of the vector is shrunk before calling `drop_in_place`,
1702 // such that no value will be dropped twice in case `drop_in_place`
1703 // were to panic once (if it panics twice, the program aborts).
1704 unsafe {
1705 // Note: It's intentional that this is `>` and not `>=`.
1706 // Changing it to `>=` has negative performance
1707 // implications in some cases. See #78884 for more.
1708 if len > self.len {
1709 return;
1710 }
1711 let remaining_len = self.len - len;
1712 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
1713 self.len = len;
1714 ptr::drop_in_place(s);
1715 }
1716 }
1717
1718 /// Extracts a slice containing the entire vector.
1719 ///
1720 /// Equivalent to `&s[..]`.
1721 ///
1722 /// # Examples
1723 ///
1724 /// ```
1725 /// use std::io::{self, Write};
1726 /// let buffer = vec![1, 2, 3, 5, 8];
1727 /// io::sink().write(buffer.as_slice()).unwrap();
1728 /// ```
1729 #[inline]
1730 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1731 #[rustc_diagnostic_item = "vec_as_slice"]
1732 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1733 pub const fn as_slice(&self) -> &[T] {
1734 // SAFETY: `slice::from_raw_parts` requires pointee is a contiguous, aligned buffer of size
1735 // `len` containing properly-initialized `T`s. Data must not be mutated for the returned
1736 // lifetime. Further, `len * size_of::<T>` <= `isize::MAX`, and allocation does not
1737 // "wrap" through overflowing memory addresses.
1738 //
1739 // * Vec API guarantees that self.buf:
1740 // * contains only properly-initialized items within 0..len
1741 // * is aligned, contiguous, and valid for `len` reads
1742 // * obeys size and address-wrapping constraints
1743 //
1744 // * We only construct `&mut` references to `self.buf` through `&mut self` methods; borrow-
1745 // check ensures that it is not possible to mutably alias `self.buf` within the
1746 // returned lifetime.
1747 unsafe {
1748 // normally this would use `slice::from_raw_parts`, but it's
1749 // instantiated often enough that avoiding the UB check is worth it
1750 &*core::intrinsics::aggregate_raw_ptr::<*const [T], _, _>(self.as_ptr(), self.len)
1751 }
1752 }
1753
1754 /// Extracts a mutable slice of the entire vector.
1755 ///
1756 /// Equivalent to `&mut s[..]`.
1757 ///
1758 /// # Examples
1759 ///
1760 /// ```
1761 /// use std::io::{self, Read};
1762 /// let mut buffer = vec![0; 3];
1763 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1764 /// ```
1765 #[inline]
1766 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1767 #[rustc_diagnostic_item = "vec_as_mut_slice"]
1768 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1769 pub const fn as_mut_slice(&mut self) -> &mut [T] {
1770 // SAFETY: `slice::from_raw_parts_mut` requires pointee is a contiguous, aligned buffer of
1771 // size `len` containing properly-initialized `T`s. Data must not be accessed through any
1772 // other pointer for the returned lifetime. Further, `len * size_of::<T>` <=
1773 // `ISIZE::MAX` and allocation does not "wrap" through overflowing memory addresses.
1774 //
1775 // * Vec API guarantees that self.buf:
1776 // * contains only properly-initialized items within 0..len
1777 // * is aligned, contiguous, and valid for `len` reads
1778 // * obeys size and address-wrapping constraints
1779 //
1780 // * We only construct references to `self.buf` through `&self` and `&mut self` methods;
1781 // borrow-check ensures that it is not possible to construct a reference to `self.buf`
1782 // within the returned lifetime.
1783 unsafe {
1784 // normally this would use `slice::from_raw_parts_mut`, but it's
1785 // instantiated often enough that avoiding the UB check is worth it
1786 &mut *core::intrinsics::aggregate_raw_ptr::<*mut [T], _, _>(self.as_mut_ptr(), self.len)
1787 }
1788 }
1789
1790 /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
1791 /// valid for zero sized reads if the vector didn't allocate.
1792 ///
1793 /// The caller must ensure that the vector outlives the pointer this
1794 /// function returns, or else it will end up dangling.
1795 /// Modifying the vector may cause its buffer to be reallocated,
1796 /// which would also make any pointers to it invalid.
1797 ///
1798 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1799 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1800 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1801 ///
1802 /// This method guarantees that for the purpose of the aliasing model, this method
1803 /// does not materialize a reference to the underlying slice, and thus the returned pointer
1804 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1805 /// and [`as_non_null`].
1806 /// Note that calling other methods that materialize mutable references to the slice,
1807 /// or mutable references to specific elements you are planning on accessing through this pointer,
1808 /// as well as writing to those elements, may still invalidate this pointer.
1809 /// See the second example below for how this guarantee can be used.
1810 ///
1811 ///
1812 /// # Examples
1813 ///
1814 /// ```
1815 /// let x = vec![1, 2, 4];
1816 /// let x_ptr = x.as_ptr();
1817 ///
1818 /// unsafe {
1819 /// for i in 0..x.len() {
1820 /// assert_eq!(*x_ptr.add(i), 1 << i);
1821 /// }
1822 /// }
1823 /// ```
1824 ///
1825 /// Due to the aliasing guarantee, the following code is legal:
1826 ///
1827 /// ```rust
1828 /// unsafe {
1829 /// let mut v = vec![0, 1, 2];
1830 /// let ptr1 = v.as_ptr();
1831 /// let _ = ptr1.read();
1832 /// let ptr2 = v.as_mut_ptr().offset(2);
1833 /// ptr2.write(2);
1834 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`
1835 /// // because it mutated a different element:
1836 /// let _ = ptr1.read();
1837 /// }
1838 /// ```
1839 ///
1840 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1841 /// [`as_ptr`]: Vec::as_ptr
1842 /// [`as_non_null`]: Vec::as_non_null
1843 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1844 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1845 #[rustc_never_returns_null_ptr]
1846 #[rustc_as_ptr]
1847 #[inline]
1848 pub const fn as_ptr(&self) -> *const T {
1849 // We shadow the slice method of the same name to avoid going through
1850 // `deref`, which creates an intermediate reference.
1851 self.buf.ptr()
1852 }
1853
1854 /// Returns a raw mutable pointer to the vector's buffer, or a dangling
1855 /// raw pointer valid for zero sized reads if the vector didn't allocate.
1856 ///
1857 /// The caller must ensure that the vector outlives the pointer this
1858 /// function returns, or else it will end up dangling.
1859 /// Modifying the vector may cause its buffer to be reallocated,
1860 /// which would also make any pointers to it invalid.
1861 ///
1862 /// This method guarantees that for the purpose of the aliasing model, this method
1863 /// does not materialize a reference to the underlying slice, and thus the returned pointer
1864 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1865 /// and [`as_non_null`].
1866 /// Note that calling other methods that materialize references to the slice,
1867 /// or references to specific elements you are planning on accessing through this pointer,
1868 /// may still invalidate this pointer.
1869 /// See the second example below for how this guarantee can be used.
1870 ///
1871 /// The method also guarantees that, as long as `T` is not zero-sized and the capacity is
1872 /// nonzero, the pointer may be passed into [`dealloc`] with a layout of
1873 /// `Layout::array::<T>(capacity)` in order to deallocate the backing memory. If this is done,
1874 /// be careful not to run the destructor of the `Vec`, as dropping it will result in
1875 /// double-frees. Wrapping the `Vec` in a [`ManuallyDrop`] is the typical way to achieve this.
1876 ///
1877 /// # Examples
1878 ///
1879 /// ```
1880 /// // Allocate vector big enough for 4 elements.
1881 /// let size = 4;
1882 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1883 /// let x_ptr = x.as_mut_ptr();
1884 ///
1885 /// // Initialize elements via raw pointer writes, then set length.
1886 /// unsafe {
1887 /// for i in 0..size {
1888 /// *x_ptr.add(i) = i as i32;
1889 /// }
1890 /// x.set_len(size);
1891 /// }
1892 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1893 /// ```
1894 ///
1895 /// Due to the aliasing guarantee, the following code is legal:
1896 ///
1897 /// ```rust
1898 /// unsafe {
1899 /// let mut v = vec![0];
1900 /// let ptr1 = v.as_mut_ptr();
1901 /// ptr1.write(1);
1902 /// let ptr2 = v.as_mut_ptr();
1903 /// ptr2.write(2);
1904 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1905 /// ptr1.write(3);
1906 /// }
1907 /// ```
1908 ///
1909 /// Deallocating a vector using [`Box`] (which uses [`dealloc`] internally):
1910 ///
1911 /// ```
1912 /// use std::mem::{ManuallyDrop, MaybeUninit};
1913 ///
1914 /// let mut v = ManuallyDrop::new(vec![0, 1, 2]);
1915 /// let ptr = v.as_mut_ptr();
1916 /// let capacity = v.capacity();
1917 /// let slice_ptr: *mut [MaybeUninit<i32>] =
1918 /// std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity);
1919 /// drop(unsafe { Box::from_raw(slice_ptr) });
1920 /// ```
1921 ///
1922 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1923 /// [`as_ptr`]: Vec::as_ptr
1924 /// [`as_non_null`]: Vec::as_non_null
1925 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
1926 /// [`ManuallyDrop`]: core::mem::ManuallyDrop
1927 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1928 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1929 #[rustc_never_returns_null_ptr]
1930 #[rustc_as_ptr]
1931 #[inline]
1932 pub const fn as_mut_ptr(&mut self) -> *mut T {
1933 // We shadow the slice method of the same name to avoid going through
1934 // `deref_mut`, which creates an intermediate reference.
1935 self.buf.ptr()
1936 }
1937
1938 /// Returns a `NonNull` pointer to the vector's buffer, or a dangling
1939 /// `NonNull` pointer valid for zero sized reads if the vector didn't allocate.
1940 ///
1941 /// The caller must ensure that the vector outlives the pointer this
1942 /// function returns, or else it will end up dangling.
1943 /// Modifying the vector may cause its buffer to be reallocated,
1944 /// which would also make any pointers to it invalid.
1945 ///
1946 /// This method guarantees that for the purpose of the aliasing model, this method
1947 /// does not materialize a reference to the underlying slice, and thus the returned pointer
1948 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1949 /// and [`as_non_null`].
1950 /// Note that calling other methods that materialize references to the slice,
1951 /// or references to specific elements you are planning on accessing through this pointer,
1952 /// may still invalidate this pointer.
1953 /// See the second example below for how this guarantee can be used.
1954 ///
1955 /// # Examples
1956 ///
1957 /// ```
1958 /// #![feature(box_vec_non_null)]
1959 ///
1960 /// // Allocate vector big enough for 4 elements.
1961 /// let size = 4;
1962 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1963 /// let x_ptr = x.as_non_null();
1964 ///
1965 /// // Initialize elements via raw pointer writes, then set length.
1966 /// unsafe {
1967 /// for i in 0..size {
1968 /// x_ptr.add(i).write(i as i32);
1969 /// }
1970 /// x.set_len(size);
1971 /// }
1972 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1973 /// ```
1974 ///
1975 /// Due to the aliasing guarantee, the following code is legal:
1976 ///
1977 /// ```rust
1978 /// #![feature(box_vec_non_null)]
1979 ///
1980 /// unsafe {
1981 /// let mut v = vec![0];
1982 /// let ptr1 = v.as_non_null();
1983 /// ptr1.write(1);
1984 /// let ptr2 = v.as_non_null();
1985 /// ptr2.write(2);
1986 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1987 /// ptr1.write(3);
1988 /// }
1989 /// ```
1990 ///
1991 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1992 /// [`as_ptr`]: Vec::as_ptr
1993 /// [`as_non_null`]: Vec::as_non_null
1994 #[unstable(feature = "box_vec_non_null", issue = "130364")]
1995 #[rustc_const_unstable(feature = "box_vec_non_null", issue = "130364")]
1996 #[inline]
1997 pub const fn as_non_null(&mut self) -> NonNull<T> {
1998 self.buf.non_null()
1999 }
2000
2001 /// Returns a reference to the underlying allocator.
2002 #[unstable(feature = "allocator_api", issue = "32838")]
2003 #[inline]
2004 pub fn allocator(&self) -> &A {
2005 self.buf.allocator()
2006 }
2007
2008 /// Forces the length of the vector to `new_len`.
2009 ///
2010 /// This is a low-level operation that maintains none of the normal
2011 /// invariants of the type. Normally changing the length of a vector
2012 /// is done using one of the safe operations instead, such as
2013 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
2014 ///
2015 /// [`truncate`]: Vec::truncate
2016 /// [`resize`]: Vec::resize
2017 /// [`extend`]: Extend::extend
2018 /// [`clear`]: Vec::clear
2019 ///
2020 /// # Safety
2021 ///
2022 /// - `new_len` must be less than or equal to [`capacity()`].
2023 /// - The elements at `old_len..new_len` must be initialized.
2024 ///
2025 /// [`capacity()`]: Vec::capacity
2026 ///
2027 /// # Examples
2028 ///
2029 /// See [`spare_capacity_mut()`] for an example with safe
2030 /// initialization of capacity elements and use of this method.
2031 ///
2032 /// `set_len()` can be useful for situations in which the vector
2033 /// is serving as a buffer for other code, particularly over FFI:
2034 ///
2035 /// ```no_run
2036 /// # #![allow(dead_code)]
2037 /// # // This is just a minimal skeleton for the doc example;
2038 /// # // don't use this as a starting point for a real library.
2039 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
2040 /// # const Z_OK: i32 = 0;
2041 /// # unsafe extern "C" {
2042 /// # fn deflateGetDictionary(
2043 /// # strm: *mut std::ffi::c_void,
2044 /// # dictionary: *mut u8,
2045 /// # dictLength: *mut usize,
2046 /// # ) -> i32;
2047 /// # }
2048 /// # impl StreamWrapper {
2049 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
2050 /// // Per the FFI method's docs, "32768 bytes is always enough".
2051 /// let mut dict = Vec::with_capacity(32_768);
2052 /// let mut dict_length = 0;
2053 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
2054 /// // 1. `dict_length` elements were initialized.
2055 /// // 2. `dict_length` <= the capacity (32_768)
2056 /// // which makes `set_len` safe to call.
2057 /// unsafe {
2058 /// // Make the FFI call...
2059 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
2060 /// if r == Z_OK {
2061 /// // ...and update the length to what was initialized.
2062 /// dict.set_len(dict_length);
2063 /// Some(dict)
2064 /// } else {
2065 /// None
2066 /// }
2067 /// }
2068 /// }
2069 /// # }
2070 /// ```
2071 ///
2072 /// While the following example is sound, there is a memory leak since
2073 /// the inner vectors were not freed prior to the `set_len` call:
2074 ///
2075 /// ```
2076 /// let mut vec = vec![vec![1, 0, 0],
2077 /// vec![0, 1, 0],
2078 /// vec![0, 0, 1]];
2079 /// // SAFETY:
2080 /// // 1. `old_len..0` is empty so no elements need to be initialized.
2081 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
2082 /// unsafe {
2083 /// vec.set_len(0);
2084 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
2085 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
2086 /// # vec.set_len(3);
2087 /// }
2088 /// ```
2089 ///
2090 /// Normally, here, one would use [`clear`] instead to correctly drop
2091 /// the contents and thus not leak memory.
2092 ///
2093 /// [`spare_capacity_mut()`]: Vec::spare_capacity_mut
2094 #[inline]
2095 #[stable(feature = "rust1", since = "1.0.0")]
2096 pub unsafe fn set_len(&mut self, new_len: usize) {
2097 ub_checks::assert_unsafe_precondition!(
2098 check_library_ub,
2099 "Vec::set_len requires that new_len <= capacity()",
2100 (new_len: usize = new_len, capacity: usize = self.capacity()) => new_len <= capacity
2101 );
2102
2103 self.len = new_len;
2104 }
2105
2106 /// Removes an element from the vector and returns it.
2107 ///
2108 /// The removed element is replaced by the last element of the vector.
2109 ///
2110 /// This does not preserve ordering of the remaining elements, but is *O*(1).
2111 /// If you need to preserve the element order, use [`remove`] instead.
2112 ///
2113 /// [`remove`]: Vec::remove
2114 ///
2115 /// # Panics
2116 ///
2117 /// Panics if `index` is out of bounds.
2118 ///
2119 /// # Examples
2120 ///
2121 /// ```
2122 /// let mut v = vec!["foo", "bar", "baz", "qux"];
2123 ///
2124 /// assert_eq!(v.swap_remove(1), "bar");
2125 /// assert_eq!(v, ["foo", "qux", "baz"]);
2126 ///
2127 /// assert_eq!(v.swap_remove(0), "foo");
2128 /// assert_eq!(v, ["baz", "qux"]);
2129 /// ```
2130 #[inline]
2131 #[stable(feature = "rust1", since = "1.0.0")]
2132 pub fn swap_remove(&mut self, index: usize) -> T {
2133 #[cold]
2134 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2135 #[optimize(size)]
2136 fn assert_failed(index: usize, len: usize) -> ! {
2137 panic!("swap_remove index (is {index}) should be < len (is {len})");
2138 }
2139
2140 let len = self.len();
2141 if index >= len {
2142 assert_failed(index, len);
2143 }
2144 unsafe {
2145 // We replace self[index] with the last element. Note that if the
2146 // bounds check above succeeds there must be a last element (which
2147 // can be self[index] itself).
2148 let value = ptr::read(self.as_ptr().add(index));
2149 let base_ptr = self.as_mut_ptr();
2150 ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
2151 self.set_len(len - 1);
2152 value
2153 }
2154 }
2155
2156 /// Inserts an element at position `index` within the vector, shifting all
2157 /// elements after it to the right.
2158 ///
2159 /// # Panics
2160 ///
2161 /// Panics if `index > len`.
2162 ///
2163 /// # Examples
2164 ///
2165 /// ```
2166 /// let mut vec = vec!['a', 'b', 'c'];
2167 /// vec.insert(1, 'd');
2168 /// assert_eq!(vec, ['a', 'd', 'b', 'c']);
2169 /// vec.insert(4, 'e');
2170 /// assert_eq!(vec, ['a', 'd', 'b', 'c', 'e']);
2171 /// ```
2172 ///
2173 /// # Time complexity
2174 ///
2175 /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be
2176 /// shifted to the right. In the worst case, all elements are shifted when
2177 /// the insertion index is 0.
2178 #[cfg(not(no_global_oom_handling))]
2179 #[stable(feature = "rust1", since = "1.0.0")]
2180 #[track_caller]
2181 pub fn insert(&mut self, index: usize, element: T) {
2182 let _ = self.insert_mut(index, element);
2183 }
2184
2185 /// Inserts an element at position `index` within the vector, shifting all
2186 /// elements after it to the right, and returning a reference to the new
2187 /// element.
2188 ///
2189 /// # Panics
2190 ///
2191 /// Panics if `index > len`.
2192 ///
2193 /// # Examples
2194 ///
2195 /// ```
2196 /// let mut vec = vec![1, 3, 5, 9];
2197 /// let x = vec.insert_mut(3, 6);
2198 /// *x += 1;
2199 /// assert_eq!(vec, [1, 3, 5, 7, 9]);
2200 /// ```
2201 ///
2202 /// # Time complexity
2203 ///
2204 /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be
2205 /// shifted to the right. In the worst case, all elements are shifted when
2206 /// the insertion index is 0.
2207 #[cfg(not(no_global_oom_handling))]
2208 #[inline]
2209 #[stable(feature = "push_mut", since = "CURRENT_RUSTC_VERSION")]
2210 #[track_caller]
2211 #[must_use = "if you don't need a reference to the value, use `Vec::insert` instead"]
2212 pub fn insert_mut(&mut self, index: usize, element: T) -> &mut T {
2213 #[cold]
2214 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2215 #[track_caller]
2216 #[optimize(size)]
2217 fn assert_failed(index: usize, len: usize) -> ! {
2218 panic!("insertion index (is {index}) should be <= len (is {len})");
2219 }
2220
2221 let len = self.len();
2222 if index > len {
2223 assert_failed(index, len);
2224 }
2225
2226 // space for the new element
2227 if len == self.buf.capacity() {
2228 self.buf.grow_one();
2229 }
2230
2231 unsafe {
2232 // infallible
2233 // The spot to put the new value
2234 let p = self.as_mut_ptr().add(index);
2235 {
2236 if index < len {
2237 // Shift everything over to make space. (Duplicating the
2238 // `index`th element into two consecutive places.)
2239 ptr::copy(p, p.add(1), len - index);
2240 }
2241 // Write it in, overwriting the first copy of the `index`th
2242 // element.
2243 ptr::write(p, element);
2244 }
2245 self.set_len(len + 1);
2246 &mut *p
2247 }
2248 }
2249
2250 /// Removes and returns the element at position `index` within the vector,
2251 /// shifting all elements after it to the left.
2252 ///
2253 /// Note: Because this shifts over the remaining elements, it has a
2254 /// worst-case performance of *O*(*n*). If you don't need the order of elements
2255 /// to be preserved, use [`swap_remove`] instead. If you'd like to remove
2256 /// elements from the beginning of the `Vec`, consider using
2257 /// [`VecDeque::pop_front`] instead.
2258 ///
2259 /// [`swap_remove`]: Vec::swap_remove
2260 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2261 ///
2262 /// # Panics
2263 ///
2264 /// Panics if `index` is out of bounds.
2265 ///
2266 /// # Examples
2267 ///
2268 /// ```
2269 /// let mut v = vec!['a', 'b', 'c'];
2270 /// assert_eq!(v.remove(1), 'b');
2271 /// assert_eq!(v, ['a', 'c']);
2272 /// ```
2273 #[stable(feature = "rust1", since = "1.0.0")]
2274 #[track_caller]
2275 #[rustc_confusables("delete", "take")]
2276 pub fn remove(&mut self, index: usize) -> T {
2277 #[cold]
2278 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2279 #[track_caller]
2280 #[optimize(size)]
2281 fn assert_failed(index: usize, len: usize) -> ! {
2282 panic!("removal index (is {index}) should be < len (is {len})");
2283 }
2284
2285 match self.try_remove(index) {
2286 Some(elem) => elem,
2287 None => assert_failed(index, self.len()),
2288 }
2289 }
2290
2291 /// Remove and return the element at position `index` within the vector,
2292 /// shifting all elements after it to the left, or [`None`] if it does not
2293 /// exist.
2294 ///
2295 /// Note: Because this shifts over the remaining elements, it has a
2296 /// worst-case performance of *O*(*n*). If you'd like to remove
2297 /// elements from the beginning of the `Vec`, consider using
2298 /// [`VecDeque::pop_front`] instead.
2299 ///
2300 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2301 ///
2302 /// # Examples
2303 ///
2304 /// ```
2305 /// #![feature(vec_try_remove)]
2306 /// let mut v = vec![1, 2, 3];
2307 /// assert_eq!(v.try_remove(0), Some(1));
2308 /// assert_eq!(v.try_remove(2), None);
2309 /// ```
2310 #[unstable(feature = "vec_try_remove", issue = "146954")]
2311 #[rustc_confusables("delete", "take", "remove")]
2312 pub fn try_remove(&mut self, index: usize) -> Option<T> {
2313 let len = self.len();
2314 if index >= len {
2315 return None;
2316 }
2317 unsafe {
2318 // infallible
2319 let ret;
2320 {
2321 // the place we are taking from.
2322 let ptr = self.as_mut_ptr().add(index);
2323 // copy it out, unsafely having a copy of the value on
2324 // the stack and in the vector at the same time.
2325 ret = ptr::read(ptr);
2326
2327 // Shift everything down to fill in that spot.
2328 ptr::copy(ptr.add(1), ptr, len - index - 1);
2329 }
2330 self.set_len(len - 1);
2331 Some(ret)
2332 }
2333 }
2334
2335 /// Retains only the elements specified by the predicate.
2336 ///
2337 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
2338 /// This method operates in place, visiting each element exactly once in the
2339 /// original order, and preserves the order of the retained elements.
2340 ///
2341 /// # Examples
2342 ///
2343 /// ```
2344 /// let mut vec = vec![1, 2, 3, 4];
2345 /// vec.retain(|&x| x % 2 == 0);
2346 /// assert_eq!(vec, [2, 4]);
2347 /// ```
2348 ///
2349 /// Because the elements are visited exactly once in the original order,
2350 /// external state may be used to decide which elements to keep.
2351 ///
2352 /// ```
2353 /// let mut vec = vec![1, 2, 3, 4, 5];
2354 /// let keep = [false, true, true, false, true];
2355 /// let mut iter = keep.iter();
2356 /// vec.retain(|_| *iter.next().unwrap());
2357 /// assert_eq!(vec, [2, 3, 5]);
2358 /// ```
2359 #[stable(feature = "rust1", since = "1.0.0")]
2360 pub fn retain<F>(&mut self, mut f: F)
2361 where
2362 F: FnMut(&T) -> bool,
2363 {
2364 self.retain_mut(|elem| f(elem));
2365 }
2366
2367 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
2368 ///
2369 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
2370 /// This method operates in place, visiting each element exactly once in the
2371 /// original order, and preserves the order of the retained elements.
2372 ///
2373 /// # Examples
2374 ///
2375 /// ```
2376 /// let mut vec = vec![1, 2, 3, 4];
2377 /// vec.retain_mut(|x| if *x <= 3 {
2378 /// *x += 1;
2379 /// true
2380 /// } else {
2381 /// false
2382 /// });
2383 /// assert_eq!(vec, [2, 3, 4]);
2384 /// ```
2385 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2386 pub fn retain_mut<F>(&mut self, mut f: F)
2387 where
2388 F: FnMut(&mut T) -> bool,
2389 {
2390 let original_len = self.len();
2391
2392 if original_len == 0 {
2393 // Empty case: explicit return allows better optimization, vs letting compiler infer it
2394 return;
2395 }
2396
2397 // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
2398 // | ^- write ^- read |
2399 // |<- original_len ->|
2400 // Kept: Elements which predicate returns true on.
2401 // Hole: Moved or dropped element slot.
2402 // Unchecked: Unchecked valid elements.
2403 //
2404 // This drop guard will be invoked when predicate or `drop` of element panicked.
2405 // It shifts unchecked elements to cover holes and `set_len` to the correct length.
2406 // In cases when predicate and `drop` never panick, it will be optimized out.
2407 struct PanicGuard<'a, T, A: Allocator> {
2408 v: &'a mut Vec<T, A>,
2409 read: usize,
2410 write: usize,
2411 original_len: usize,
2412 }
2413
2414 impl<T, A: Allocator> Drop for PanicGuard<'_, T, A> {
2415 #[cold]
2416 fn drop(&mut self) {
2417 let remaining = self.original_len - self.read;
2418 // SAFETY: Trailing unchecked items must be valid since we never touch them.
2419 unsafe {
2420 ptr::copy(
2421 self.v.as_ptr().add(self.read),
2422 self.v.as_mut_ptr().add(self.write),
2423 remaining,
2424 );
2425 }
2426 // SAFETY: After filling holes, all items are in contiguous memory.
2427 unsafe {
2428 self.v.set_len(self.write + remaining);
2429 }
2430 }
2431 }
2432
2433 let mut read = 0;
2434 loop {
2435 // SAFETY: read < original_len
2436 let cur = unsafe { self.get_unchecked_mut(read) };
2437 if hint::unlikely(!f(cur)) {
2438 break;
2439 }
2440 read += 1;
2441 if read == original_len {
2442 // All elements are kept, return early.
2443 return;
2444 }
2445 }
2446
2447 // Critical section starts here and at least one element is going to be removed.
2448 // Advance `g.read` early to avoid double drop if `drop_in_place` panicked.
2449 let mut g = PanicGuard { v: self, read: read + 1, write: read, original_len };
2450 // SAFETY: previous `read` is always less than original_len.
2451 unsafe { ptr::drop_in_place(&mut *g.v.as_mut_ptr().add(read)) };
2452
2453 while g.read < g.original_len {
2454 // SAFETY: `read` is always less than original_len.
2455 let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.read) };
2456 if !f(cur) {
2457 // Advance `read` early to avoid double drop if `drop_in_place` panicked.
2458 g.read += 1;
2459 // SAFETY: We never touch this element again after dropped.
2460 unsafe { ptr::drop_in_place(cur) };
2461 } else {
2462 // SAFETY: `read` > `write`, so the slots don't overlap.
2463 // We use copy for move, and never touch the source element again.
2464 unsafe {
2465 let hole = g.v.as_mut_ptr().add(g.write);
2466 ptr::copy_nonoverlapping(cur, hole, 1);
2467 }
2468 g.write += 1;
2469 g.read += 1;
2470 }
2471 }
2472
2473 // We are leaving the critical section and no panic happened,
2474 // Commit the length change and forget the guard.
2475 // SAFETY: `write` is always less than or equal to original_len.
2476 unsafe { g.v.set_len(g.write) };
2477 mem::forget(g);
2478 }
2479
2480 /// Removes all but the first of consecutive elements in the vector that resolve to the same
2481 /// key.
2482 ///
2483 /// If the vector is sorted, this removes all duplicates.
2484 ///
2485 /// # Examples
2486 ///
2487 /// ```
2488 /// let mut vec = vec![10, 20, 21, 30, 20];
2489 ///
2490 /// vec.dedup_by_key(|i| *i / 10);
2491 ///
2492 /// assert_eq!(vec, [10, 20, 30, 20]);
2493 /// ```
2494 #[stable(feature = "dedup_by", since = "1.16.0")]
2495 #[inline]
2496 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
2497 where
2498 F: FnMut(&mut T) -> K,
2499 K: PartialEq,
2500 {
2501 self.dedup_by(|a, b| key(a) == key(b))
2502 }
2503
2504 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
2505 /// relation.
2506 ///
2507 /// The `same_bucket` function is passed references to two elements from the vector and
2508 /// must determine if the elements compare equal. The elements are passed in opposite order
2509 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
2510 ///
2511 /// If the vector is sorted, this removes all duplicates.
2512 ///
2513 /// # Examples
2514 ///
2515 /// ```
2516 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
2517 ///
2518 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2519 ///
2520 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
2521 /// ```
2522 #[stable(feature = "dedup_by", since = "1.16.0")]
2523 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
2524 where
2525 F: FnMut(&mut T, &mut T) -> bool,
2526 {
2527 let len = self.len();
2528 if len <= 1 {
2529 return;
2530 }
2531
2532 // Check if we ever want to remove anything.
2533 // This allows to use copy_non_overlapping in next cycle.
2534 // And avoids any memory writes if we don't need to remove anything.
2535 let mut first_duplicate_idx: usize = 1;
2536 let start = self.as_mut_ptr();
2537 while first_duplicate_idx != len {
2538 let found_duplicate = unsafe {
2539 // SAFETY: first_duplicate always in range [1..len)
2540 // Note that we start iteration from 1 so we never overflow.
2541 let prev = start.add(first_duplicate_idx.wrapping_sub(1));
2542 let current = start.add(first_duplicate_idx);
2543 // We explicitly say in docs that references are reversed.
2544 same_bucket(&mut *current, &mut *prev)
2545 };
2546 if found_duplicate {
2547 break;
2548 }
2549 first_duplicate_idx += 1;
2550 }
2551 // Don't need to remove anything.
2552 // We cannot get bigger than len.
2553 if first_duplicate_idx == len {
2554 return;
2555 }
2556
2557 /* INVARIANT: vec.len() > read > write > write-1 >= 0 */
2558 struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> {
2559 /* Offset of the element we want to check if it is duplicate */
2560 read: usize,
2561
2562 /* Offset of the place where we want to place the non-duplicate
2563 * when we find it. */
2564 write: usize,
2565
2566 /* The Vec that would need correction if `same_bucket` panicked */
2567 vec: &'a mut Vec<T, A>,
2568 }
2569
2570 impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
2571 fn drop(&mut self) {
2572 /* This code gets executed when `same_bucket` panics */
2573
2574 /* SAFETY: invariant guarantees that `read - write`
2575 * and `len - read` never overflow and that the copy is always
2576 * in-bounds. */
2577 unsafe {
2578 let ptr = self.vec.as_mut_ptr();
2579 let len = self.vec.len();
2580
2581 /* How many items were left when `same_bucket` panicked.
2582 * Basically vec[read..].len() */
2583 let items_left = len.wrapping_sub(self.read);
2584
2585 /* Pointer to first item in vec[write..write+items_left] slice */
2586 let dropped_ptr = ptr.add(self.write);
2587 /* Pointer to first item in vec[read..] slice */
2588 let valid_ptr = ptr.add(self.read);
2589
2590 /* Copy `vec[read..]` to `vec[write..write+items_left]`.
2591 * The slices can overlap, so `copy_nonoverlapping` cannot be used */
2592 ptr::copy(valid_ptr, dropped_ptr, items_left);
2593
2594 /* How many items have been already dropped
2595 * Basically vec[read..write].len() */
2596 let dropped = self.read.wrapping_sub(self.write);
2597
2598 self.vec.set_len(len - dropped);
2599 }
2600 }
2601 }
2602
2603 /* Drop items while going through Vec, it should be more efficient than
2604 * doing slice partition_dedup + truncate */
2605
2606 // Construct gap first and then drop item to avoid memory corruption if `T::drop` panics.
2607 let mut gap =
2608 FillGapOnDrop { read: first_duplicate_idx + 1, write: first_duplicate_idx, vec: self };
2609 unsafe {
2610 // SAFETY: we checked that first_duplicate_idx in bounds before.
2611 // If drop panics, `gap` would remove this item without drop.
2612 ptr::drop_in_place(start.add(first_duplicate_idx));
2613 }
2614
2615 /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
2616 * are always in-bounds and read_ptr never aliases prev_ptr */
2617 unsafe {
2618 while gap.read < len {
2619 let read_ptr = start.add(gap.read);
2620 let prev_ptr = start.add(gap.write.wrapping_sub(1));
2621
2622 // We explicitly say in docs that references are reversed.
2623 let found_duplicate = same_bucket(&mut *read_ptr, &mut *prev_ptr);
2624 if found_duplicate {
2625 // Increase `gap.read` now since the drop may panic.
2626 gap.read += 1;
2627 /* We have found duplicate, drop it in-place */
2628 ptr::drop_in_place(read_ptr);
2629 } else {
2630 let write_ptr = start.add(gap.write);
2631
2632 /* read_ptr cannot be equal to write_ptr because at this point
2633 * we guaranteed to skip at least one element (before loop starts).
2634 */
2635 ptr::copy_nonoverlapping(read_ptr, write_ptr, 1);
2636
2637 /* We have filled that place, so go further */
2638 gap.write += 1;
2639 gap.read += 1;
2640 }
2641 }
2642
2643 /* Technically we could let `gap` clean up with its Drop, but
2644 * when `same_bucket` is guaranteed to not panic, this bloats a little
2645 * the codegen, so we just do it manually */
2646 gap.vec.set_len(gap.write);
2647 mem::forget(gap);
2648 }
2649 }
2650
2651 /// Appends an element and returns a reference to it if there is sufficient spare capacity,
2652 /// otherwise an error is returned with the element.
2653 ///
2654 /// Unlike [`push`] this method will not reallocate when there's insufficient capacity.
2655 /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity.
2656 ///
2657 /// [`push`]: Vec::push
2658 /// [`reserve`]: Vec::reserve
2659 /// [`try_reserve`]: Vec::try_reserve
2660 ///
2661 /// # Examples
2662 ///
2663 /// A manual, panic-free alternative to [`FromIterator`]:
2664 ///
2665 /// ```
2666 /// #![feature(vec_push_within_capacity)]
2667 ///
2668 /// use std::collections::TryReserveError;
2669 /// fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
2670 /// let mut vec = Vec::new();
2671 /// for value in iter {
2672 /// if let Err(value) = vec.push_within_capacity(value) {
2673 /// vec.try_reserve(1)?;
2674 /// // this cannot fail, the previous line either returned or added at least 1 free slot
2675 /// let _ = vec.push_within_capacity(value);
2676 /// }
2677 /// }
2678 /// Ok(vec)
2679 /// }
2680 /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
2681 /// ```
2682 ///
2683 /// # Time complexity
2684 ///
2685 /// Takes *O*(1) time.
2686 #[inline]
2687 #[unstable(feature = "vec_push_within_capacity", issue = "100486")]
2688 pub fn push_within_capacity(&mut self, value: T) -> Result<&mut T, T> {
2689 if self.len == self.buf.capacity() {
2690 return Err(value);
2691 }
2692
2693 unsafe {
2694 let end = self.as_mut_ptr().add(self.len);
2695 ptr::write(end, value);
2696 self.len += 1;
2697
2698 // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference.
2699 Ok(&mut *end)
2700 }
2701 }
2702
2703 /// Removes the last element from a vector and returns it, or [`None`] if it
2704 /// is empty.
2705 ///
2706 /// If you'd like to pop the first element, consider using
2707 /// [`VecDeque::pop_front`] instead.
2708 ///
2709 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2710 ///
2711 /// # Examples
2712 ///
2713 /// ```
2714 /// let mut vec = vec![1, 2, 3];
2715 /// assert_eq!(vec.pop(), Some(3));
2716 /// assert_eq!(vec, [1, 2]);
2717 /// ```
2718 ///
2719 /// # Time complexity
2720 ///
2721 /// Takes *O*(1) time.
2722 #[inline]
2723 #[stable(feature = "rust1", since = "1.0.0")]
2724 #[rustc_diagnostic_item = "vec_pop"]
2725 pub fn pop(&mut self) -> Option<T> {
2726 if self.len == 0 {
2727 None
2728 } else {
2729 unsafe {
2730 self.len -= 1;
2731 core::hint::assert_unchecked(self.len < self.capacity());
2732 Some(ptr::read(self.as_ptr().add(self.len())))
2733 }
2734 }
2735 }
2736
2737 /// Removes and returns the last element from a vector if the predicate
2738 /// returns `true`, or [`None`] if the predicate returns false or the vector
2739 /// is empty (the predicate will not be called in that case).
2740 ///
2741 /// # Examples
2742 ///
2743 /// ```
2744 /// let mut vec = vec![1, 2, 3, 4];
2745 /// let pred = |x: &mut i32| *x % 2 == 0;
2746 ///
2747 /// assert_eq!(vec.pop_if(pred), Some(4));
2748 /// assert_eq!(vec, [1, 2, 3]);
2749 /// assert_eq!(vec.pop_if(pred), None);
2750 /// ```
2751 #[stable(feature = "vec_pop_if", since = "1.86.0")]
2752 pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2753 let last = self.last_mut()?;
2754 if predicate(last) { self.pop() } else { None }
2755 }
2756
2757 /// Returns a mutable reference to the last item in the vector, or
2758 /// `None` if it is empty.
2759 ///
2760 /// # Examples
2761 ///
2762 /// Basic usage:
2763 ///
2764 /// ```
2765 /// #![feature(vec_peek_mut)]
2766 /// let mut vec = Vec::new();
2767 /// assert!(vec.peek_mut().is_none());
2768 ///
2769 /// vec.push(1);
2770 /// vec.push(5);
2771 /// vec.push(2);
2772 /// assert_eq!(vec.last(), Some(&2));
2773 /// if let Some(mut val) = vec.peek_mut() {
2774 /// *val = 0;
2775 /// }
2776 /// assert_eq!(vec.last(), Some(&0));
2777 /// ```
2778 #[inline]
2779 #[unstable(feature = "vec_peek_mut", issue = "122742")]
2780 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, A>> {
2781 PeekMut::new(self)
2782 }
2783
2784 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2785 ///
2786 /// # Panics
2787 ///
2788 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
2789 ///
2790 /// # Examples
2791 ///
2792 /// ```
2793 /// let mut vec = vec![1, 2, 3];
2794 /// let mut vec2 = vec![4, 5, 6];
2795 /// vec.append(&mut vec2);
2796 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
2797 /// assert_eq!(vec2, []);
2798 /// ```
2799 #[cfg(not(no_global_oom_handling))]
2800 #[inline]
2801 #[stable(feature = "append", since = "1.4.0")]
2802 pub fn append(&mut self, other: &mut Self) {
2803 unsafe {
2804 self.append_elements(other.as_slice() as _);
2805 other.set_len(0);
2806 }
2807 }
2808
2809 /// Appends elements to `self` from other buffer.
2810 #[cfg(not(no_global_oom_handling))]
2811 #[inline]
2812 unsafe fn append_elements(&mut self, other: *const [T]) {
2813 let count = other.len();
2814 self.reserve(count);
2815 let len = self.len();
2816 if count > 0 {
2817 unsafe {
2818 ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count)
2819 };
2820 }
2821 self.len += count;
2822 }
2823
2824 /// Removes the subslice indicated by the given range from the vector,
2825 /// returning a double-ended iterator over the removed subslice.
2826 ///
2827 /// If the iterator is dropped before being fully consumed,
2828 /// it drops the remaining removed elements.
2829 ///
2830 /// The returned iterator keeps a mutable borrow on the vector to optimize
2831 /// its implementation.
2832 ///
2833 /// # Panics
2834 ///
2835 /// Panics if the range has `start_bound > end_bound`, or, if the range is
2836 /// bounded on either end and past the length of the vector.
2837 ///
2838 /// # Leaking
2839 ///
2840 /// If the returned iterator goes out of scope without being dropped (due to
2841 /// [`mem::forget`], for example), the vector may have lost and leaked
2842 /// elements arbitrarily, including elements outside the range.
2843 ///
2844 /// # Examples
2845 ///
2846 /// ```
2847 /// let mut v = vec![1, 2, 3];
2848 /// let u: Vec<_> = v.drain(1..).collect();
2849 /// assert_eq!(v, &[1]);
2850 /// assert_eq!(u, &[2, 3]);
2851 ///
2852 /// // A full range clears the vector, like `clear()` does
2853 /// v.drain(..);
2854 /// assert_eq!(v, &[]);
2855 /// ```
2856 #[stable(feature = "drain", since = "1.6.0")]
2857 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
2858 where
2859 R: RangeBounds<usize>,
2860 {
2861 // Memory safety
2862 //
2863 // When the Drain is first created, it shortens the length of
2864 // the source vector to make sure no uninitialized or moved-from elements
2865 // are accessible at all if the Drain's destructor never gets to run.
2866 //
2867 // Drain will ptr::read out the values to remove.
2868 // When finished, remaining tail of the vec is copied back to cover
2869 // the hole, and the vector length is restored to the new length.
2870 //
2871 let len = self.len();
2872 let Range { start, end } = slice::range(range, ..len);
2873
2874 unsafe {
2875 // set self.vec length's to start, to be safe in case Drain is leaked
2876 self.set_len(start);
2877 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
2878 Drain {
2879 tail_start: end,
2880 tail_len: len - end,
2881 iter: range_slice.iter(),
2882 vec: NonNull::from(self),
2883 }
2884 }
2885 }
2886
2887 /// Clears the vector, removing all values.
2888 ///
2889 /// Note that this method has no effect on the allocated capacity
2890 /// of the vector.
2891 ///
2892 /// # Examples
2893 ///
2894 /// ```
2895 /// let mut v = vec![1, 2, 3];
2896 ///
2897 /// v.clear();
2898 ///
2899 /// assert!(v.is_empty());
2900 /// ```
2901 #[inline]
2902 #[stable(feature = "rust1", since = "1.0.0")]
2903 pub fn clear(&mut self) {
2904 let elems: *mut [T] = self.as_mut_slice();
2905
2906 // SAFETY:
2907 // - `elems` comes directly from `as_mut_slice` and is therefore valid.
2908 // - Setting `self.len` before calling `drop_in_place` means that,
2909 // if an element's `Drop` impl panics, the vector's `Drop` impl will
2910 // do nothing (leaking the rest of the elements) instead of dropping
2911 // some twice.
2912 unsafe {
2913 self.len = 0;
2914 ptr::drop_in_place(elems);
2915 }
2916 }
2917
2918 /// Returns the number of elements in the vector, also referred to
2919 /// as its 'length'.
2920 ///
2921 /// # Examples
2922 ///
2923 /// ```
2924 /// let a = vec![1, 2, 3];
2925 /// assert_eq!(a.len(), 3);
2926 /// ```
2927 #[inline]
2928 #[stable(feature = "rust1", since = "1.0.0")]
2929 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
2930 #[rustc_confusables("length", "size")]
2931 pub const fn len(&self) -> usize {
2932 let len = self.len;
2933
2934 // SAFETY: The maximum capacity of `Vec<T>` is `isize::MAX` bytes, so the maximum value can
2935 // be returned is `usize::checked_div(size_of::<T>()).unwrap_or(usize::MAX)`, which
2936 // matches the definition of `T::MAX_SLICE_LEN`.
2937 unsafe { intrinsics::assume(len <= T::MAX_SLICE_LEN) };
2938
2939 len
2940 }
2941
2942 /// Returns `true` if the vector contains no elements.
2943 ///
2944 /// # Examples
2945 ///
2946 /// ```
2947 /// let mut v = Vec::new();
2948 /// assert!(v.is_empty());
2949 ///
2950 /// v.push(1);
2951 /// assert!(!v.is_empty());
2952 /// ```
2953 #[stable(feature = "rust1", since = "1.0.0")]
2954 #[rustc_diagnostic_item = "vec_is_empty"]
2955 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
2956 pub const fn is_empty(&self) -> bool {
2957 self.len() == 0
2958 }
2959
2960 /// Splits the collection into two at the given index.
2961 ///
2962 /// Returns a newly allocated vector containing the elements in the range
2963 /// `[at, len)`. After the call, the original vector will be left containing
2964 /// the elements `[0, at)` with its previous capacity unchanged.
2965 ///
2966 /// - If you want to take ownership of the entire contents and capacity of
2967 /// the vector, see [`mem::take`] or [`mem::replace`].
2968 /// - If you don't need the returned vector at all, see [`Vec::truncate`].
2969 /// - If you want to take ownership of an arbitrary subslice, or you don't
2970 /// necessarily want to store the removed items in a vector, see [`Vec::drain`].
2971 ///
2972 /// # Panics
2973 ///
2974 /// Panics if `at > len`.
2975 ///
2976 /// # Examples
2977 ///
2978 /// ```
2979 /// let mut vec = vec!['a', 'b', 'c'];
2980 /// let vec2 = vec.split_off(1);
2981 /// assert_eq!(vec, ['a']);
2982 /// assert_eq!(vec2, ['b', 'c']);
2983 /// ```
2984 #[cfg(not(no_global_oom_handling))]
2985 #[inline]
2986 #[must_use = "use `.truncate()` if you don't need the other half"]
2987 #[stable(feature = "split_off", since = "1.4.0")]
2988 #[track_caller]
2989 pub fn split_off(&mut self, at: usize) -> Self
2990 where
2991 A: Clone,
2992 {
2993 #[cold]
2994 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2995 #[track_caller]
2996 #[optimize(size)]
2997 fn assert_failed(at: usize, len: usize) -> ! {
2998 panic!("`at` split index (is {at}) should be <= len (is {len})");
2999 }
3000
3001 if at > self.len() {
3002 assert_failed(at, self.len());
3003 }
3004
3005 let other_len = self.len - at;
3006 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
3007
3008 // Unsafely `set_len` and copy items to `other`.
3009 unsafe {
3010 self.set_len(at);
3011 other.set_len(other_len);
3012
3013 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
3014 }
3015 other
3016 }
3017
3018 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
3019 ///
3020 /// If `new_len` is greater than `len`, the `Vec` is extended by the
3021 /// difference, with each additional slot filled with the result of
3022 /// calling the closure `f`. The return values from `f` will end up
3023 /// in the `Vec` in the order they have been generated.
3024 ///
3025 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
3026 ///
3027 /// This method uses a closure to create new values on every push. If
3028 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
3029 /// want to use the [`Default`] trait to generate values, you can
3030 /// pass [`Default::default`] as the second argument.
3031 ///
3032 /// # Panics
3033 ///
3034 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3035 ///
3036 /// # Examples
3037 ///
3038 /// ```
3039 /// let mut vec = vec![1, 2, 3];
3040 /// vec.resize_with(5, Default::default);
3041 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
3042 ///
3043 /// let mut vec = vec![];
3044 /// let mut p = 1;
3045 /// vec.resize_with(4, || { p *= 2; p });
3046 /// assert_eq!(vec, [2, 4, 8, 16]);
3047 /// ```
3048 #[cfg(not(no_global_oom_handling))]
3049 #[stable(feature = "vec_resize_with", since = "1.33.0")]
3050 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
3051 where
3052 F: FnMut() -> T,
3053 {
3054 let len = self.len();
3055 if new_len > len {
3056 self.extend_trusted(iter::repeat_with(f).take(new_len - len));
3057 } else {
3058 self.truncate(new_len);
3059 }
3060 }
3061
3062 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
3063 /// `&'a mut [T]`.
3064 ///
3065 /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
3066 /// has only static references, or none at all, then this may be chosen to be
3067 /// `'static`.
3068 ///
3069 /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
3070 /// so the leaked allocation may include unused capacity that is not part
3071 /// of the returned slice.
3072 ///
3073 /// This function is mainly useful for data that lives for the remainder of
3074 /// the program's life. Dropping the returned reference will cause a memory
3075 /// leak.
3076 ///
3077 /// # Examples
3078 ///
3079 /// Simple usage:
3080 ///
3081 /// ```
3082 /// let x = vec![1, 2, 3];
3083 /// let static_ref: &'static mut [usize] = x.leak();
3084 /// static_ref[0] += 1;
3085 /// assert_eq!(static_ref, &[2, 2, 3]);
3086 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
3087 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
3088 /// # drop(unsafe { Box::from_raw(static_ref) });
3089 /// ```
3090 #[stable(feature = "vec_leak", since = "1.47.0")]
3091 #[inline]
3092 pub fn leak<'a>(self) -> &'a mut [T]
3093 where
3094 A: 'a,
3095 {
3096 let mut me = ManuallyDrop::new(self);
3097 unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
3098 }
3099
3100 /// Returns the remaining spare capacity of the vector as a slice of
3101 /// `MaybeUninit<T>`.
3102 ///
3103 /// The returned slice can be used to fill the vector with data (e.g. by
3104 /// reading from a file) before marking the data as initialized using the
3105 /// [`set_len`] method.
3106 ///
3107 /// [`set_len`]: Vec::set_len
3108 ///
3109 /// # Examples
3110 ///
3111 /// ```
3112 /// // Allocate vector big enough for 10 elements.
3113 /// let mut v = Vec::with_capacity(10);
3114 ///
3115 /// // Fill in the first 3 elements.
3116 /// let uninit = v.spare_capacity_mut();
3117 /// uninit[0].write(0);
3118 /// uninit[1].write(1);
3119 /// uninit[2].write(2);
3120 ///
3121 /// // Mark the first 3 elements of the vector as being initialized.
3122 /// unsafe {
3123 /// v.set_len(3);
3124 /// }
3125 ///
3126 /// assert_eq!(&v, &[0, 1, 2]);
3127 /// ```
3128 #[stable(feature = "vec_spare_capacity", since = "1.60.0")]
3129 #[inline]
3130 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
3131 // Note:
3132 // This method is not implemented in terms of `split_at_spare_mut`,
3133 // to prevent invalidation of pointers to the buffer.
3134 unsafe {
3135 slice::from_raw_parts_mut(
3136 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
3137 self.buf.capacity() - self.len,
3138 )
3139 }
3140 }
3141
3142 /// Returns vector content as a slice of `T`, along with the remaining spare
3143 /// capacity of the vector as a slice of `MaybeUninit<T>`.
3144 ///
3145 /// The returned spare capacity slice can be used to fill the vector with data
3146 /// (e.g. by reading from a file) before marking the data as initialized using
3147 /// the [`set_len`] method.
3148 ///
3149 /// [`set_len`]: Vec::set_len
3150 ///
3151 /// Note that this is a low-level API, which should be used with care for
3152 /// optimization purposes. If you need to append data to a `Vec`
3153 /// you can use [`push`], [`extend`], [`extend_from_slice`],
3154 /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
3155 /// [`resize_with`], depending on your exact needs.
3156 ///
3157 /// [`push`]: Vec::push
3158 /// [`extend`]: Vec::extend
3159 /// [`extend_from_slice`]: Vec::extend_from_slice
3160 /// [`extend_from_within`]: Vec::extend_from_within
3161 /// [`insert`]: Vec::insert
3162 /// [`append`]: Vec::append
3163 /// [`resize`]: Vec::resize
3164 /// [`resize_with`]: Vec::resize_with
3165 ///
3166 /// # Examples
3167 ///
3168 /// ```
3169 /// #![feature(vec_split_at_spare)]
3170 ///
3171 /// let mut v = vec![1, 1, 2];
3172 ///
3173 /// // Reserve additional space big enough for 10 elements.
3174 /// v.reserve(10);
3175 ///
3176 /// let (init, uninit) = v.split_at_spare_mut();
3177 /// let sum = init.iter().copied().sum::<u32>();
3178 ///
3179 /// // Fill in the next 4 elements.
3180 /// uninit[0].write(sum);
3181 /// uninit[1].write(sum * 2);
3182 /// uninit[2].write(sum * 3);
3183 /// uninit[3].write(sum * 4);
3184 ///
3185 /// // Mark the 4 elements of the vector as being initialized.
3186 /// unsafe {
3187 /// let len = v.len();
3188 /// v.set_len(len + 4);
3189 /// }
3190 ///
3191 /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
3192 /// ```
3193 #[unstable(feature = "vec_split_at_spare", issue = "81944")]
3194 #[inline]
3195 pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
3196 // SAFETY:
3197 // - len is ignored and so never changed
3198 let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
3199 (init, spare)
3200 }
3201
3202 /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
3203 ///
3204 /// This method provides unique access to all vec parts at once in `extend_from_within`.
3205 unsafe fn split_at_spare_mut_with_len(
3206 &mut self,
3207 ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
3208 let ptr = self.as_mut_ptr();
3209 // SAFETY:
3210 // - `ptr` is guaranteed to be valid for `self.len` elements
3211 // - but the allocation extends out to `self.buf.capacity()` elements, possibly
3212 // uninitialized
3213 let spare_ptr = unsafe { ptr.add(self.len) };
3214 let spare_ptr = spare_ptr.cast_uninit();
3215 let spare_len = self.buf.capacity() - self.len;
3216
3217 // SAFETY:
3218 // - `ptr` is guaranteed to be valid for `self.len` elements
3219 // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
3220 unsafe {
3221 let initialized = slice::from_raw_parts_mut(ptr, self.len);
3222 let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
3223
3224 (initialized, spare, &mut self.len)
3225 }
3226 }
3227
3228 /// Groups every `N` elements in the `Vec<T>` into chunks to produce a `Vec<[T; N]>`, dropping
3229 /// elements in the remainder. `N` must be greater than zero.
3230 ///
3231 /// If the capacity is not a multiple of the chunk size, the buffer will shrink down to the
3232 /// nearest multiple with a reallocation or deallocation.
3233 ///
3234 /// This function can be used to reverse [`Vec::into_flattened`].
3235 ///
3236 /// # Examples
3237 ///
3238 /// ```
3239 /// #![feature(vec_into_chunks)]
3240 ///
3241 /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7];
3242 /// assert_eq!(vec.into_chunks::<3>(), [[0, 1, 2], [3, 4, 5]]);
3243 ///
3244 /// let vec = vec![0, 1, 2, 3];
3245 /// let chunks: Vec<[u8; 10]> = vec.into_chunks();
3246 /// assert!(chunks.is_empty());
3247 ///
3248 /// let flat = vec![0; 8 * 8 * 8];
3249 /// let reshaped: Vec<[[[u8; 8]; 8]; 8]> = flat.into_chunks().into_chunks().into_chunks();
3250 /// assert_eq!(reshaped.len(), 1);
3251 /// ```
3252 #[cfg(not(no_global_oom_handling))]
3253 #[unstable(feature = "vec_into_chunks", issue = "142137")]
3254 pub fn into_chunks<const N: usize>(mut self) -> Vec<[T; N], A> {
3255 const {
3256 assert!(N != 0, "chunk size must be greater than zero");
3257 }
3258
3259 let (len, cap) = (self.len(), self.capacity());
3260
3261 let len_remainder = len % N;
3262 if len_remainder != 0 {
3263 self.truncate(len - len_remainder);
3264 }
3265
3266 let cap_remainder = cap % N;
3267 if !T::IS_ZST && cap_remainder != 0 {
3268 self.buf.shrink_to_fit(cap - cap_remainder);
3269 }
3270
3271 let (ptr, _, _, alloc) = self.into_raw_parts_with_alloc();
3272
3273 // SAFETY:
3274 // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_alloc()`
3275 // - `[T; N]` has the same alignment as `T`
3276 // - `size_of::<[T; N]>() * cap / N == size_of::<T>() * cap`
3277 // - `len / N <= cap / N` because `len <= cap`
3278 // - the allocated memory consists of `len / N` valid values of type `[T; N]`
3279 // - `cap / N` fits the size of the allocated memory after shrinking
3280 unsafe { Vec::from_raw_parts_in(ptr.cast(), len / N, cap / N, alloc) }
3281 }
3282
3283 /// This clears out this `Vec` and recycles the allocation into a new `Vec`.
3284 /// The item type of the resulting `Vec` needs to have the same size and
3285 /// alignment as the item type of the original `Vec`.
3286 ///
3287 /// # Examples
3288 ///
3289 /// ```
3290 /// #![feature(vec_recycle, transmutability)]
3291 /// let a: Vec<u8> = vec![0; 100];
3292 /// let capacity = a.capacity();
3293 /// let addr = a.as_ptr().addr();
3294 /// let b: Vec<i8> = a.recycle();
3295 /// assert_eq!(b.len(), 0);
3296 /// assert_eq!(b.capacity(), capacity);
3297 /// assert_eq!(b.as_ptr().addr(), addr);
3298 /// ```
3299 ///
3300 /// The `Recyclable` bound prevents this method from being called when `T` and `U` have different sizes; e.g.:
3301 ///
3302 /// ```compile_fail,E0277
3303 /// #![feature(vec_recycle, transmutability)]
3304 /// let vec: Vec<[u8; 2]> = Vec::new();
3305 /// let _: Vec<[u8; 1]> = vec.recycle();
3306 /// ```
3307 /// ...or different alignments:
3308 ///
3309 /// ```compile_fail,E0277
3310 /// #![feature(vec_recycle, transmutability)]
3311 /// let vec: Vec<[u16; 0]> = Vec::new();
3312 /// let _: Vec<[u8; 0]> = vec.recycle();
3313 /// ```
3314 ///
3315 /// However, due to temporary implementation limitations of `Recyclable`,
3316 /// this method is not yet callable when `T` or `U` are slices, trait objects,
3317 /// or other exotic types; e.g.:
3318 ///
3319 /// ```compile_fail,E0277
3320 /// #![feature(vec_recycle, transmutability)]
3321 /// # let inputs = ["a b c", "d e f"];
3322 /// # fn process(_: &[&str]) {}
3323 /// let mut storage: Vec<&[&str]> = Vec::new();
3324 ///
3325 /// for input in inputs {
3326 /// let mut buffer: Vec<&str> = storage.recycle();
3327 /// buffer.extend(input.split(" "));
3328 /// process(&buffer);
3329 /// storage = buffer.recycle();
3330 /// }
3331 /// ```
3332 #[unstable(feature = "vec_recycle", issue = "148227")]
3333 #[expect(private_bounds)]
3334 pub fn recycle<U>(mut self) -> Vec<U, A>
3335 where
3336 U: Recyclable<T>,
3337 {
3338 self.clear();
3339 const {
3340 // FIXME(const-hack, 146097): compare `Layout`s
3341 assert!(size_of::<T>() == size_of::<U>());
3342 assert!(align_of::<T>() == align_of::<U>());
3343 };
3344 let (ptr, length, capacity, alloc) = self.into_parts_with_alloc();
3345 debug_assert_eq!(length, 0);
3346 // SAFETY:
3347 // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_alloc()`
3348 // - `T` & `U` have the same layout, so `capacity` does not need to be changed and we can safely use `alloc.dealloc` later
3349 // - the original vector was cleared, so there is no problem with "transmuting" the stored values
3350 unsafe { Vec::from_parts_in(ptr.cast::<U>(), length, capacity, alloc) }
3351 }
3352}
3353
3354/// Denotes that an allocation of `From` can be recycled into an allocation of `Self`.
3355///
3356/// # Safety
3357///
3358/// `Self` is `Recyclable<From>` if `Layout::new::<Self>() == Layout::new::<From>()`.
3359unsafe trait Recyclable<From: Sized>: Sized {}
3360
3361#[unstable_feature_bound(transmutability)]
3362// SAFETY: enforced by `TransmuteFrom`
3363unsafe impl<From, To> Recyclable<From> for To
3364where
3365 for<'a> &'a MaybeUninit<To>: TransmuteFrom<&'a MaybeUninit<From>, { Assume::SAFETY }>,
3366 for<'a> &'a MaybeUninit<From>: TransmuteFrom<&'a MaybeUninit<To>, { Assume::SAFETY }>,
3367{
3368}
3369
3370impl<T: Clone, A: Allocator> Vec<T, A> {
3371 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
3372 ///
3373 /// If `new_len` is greater than `len`, the `Vec` is extended by the
3374 /// difference, with each additional slot filled with `value`.
3375 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
3376 ///
3377 /// This method requires `T` to implement [`Clone`],
3378 /// in order to be able to clone the passed value.
3379 /// If you need more flexibility (or want to rely on [`Default`] instead of
3380 /// [`Clone`]), use [`Vec::resize_with`].
3381 /// If you only need to resize to a smaller size, use [`Vec::truncate`].
3382 ///
3383 /// # Panics
3384 ///
3385 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3386 ///
3387 /// # Examples
3388 ///
3389 /// ```
3390 /// let mut vec = vec!["hello"];
3391 /// vec.resize(3, "world");
3392 /// assert_eq!(vec, ["hello", "world", "world"]);
3393 ///
3394 /// let mut vec = vec!['a', 'b', 'c', 'd'];
3395 /// vec.resize(2, '_');
3396 /// assert_eq!(vec, ['a', 'b']);
3397 /// ```
3398 #[cfg(not(no_global_oom_handling))]
3399 #[stable(feature = "vec_resize", since = "1.5.0")]
3400 pub fn resize(&mut self, new_len: usize, value: T) {
3401 let len = self.len();
3402
3403 if new_len > len {
3404 self.extend_with(new_len - len, value)
3405 } else {
3406 self.truncate(new_len);
3407 }
3408 }
3409
3410 /// Clones and appends all elements in a slice to the `Vec`.
3411 ///
3412 /// Iterates over the slice `other`, clones each element, and then appends
3413 /// it to this `Vec`. The `other` slice is traversed in-order.
3414 ///
3415 /// Note that this function is the same as [`extend`],
3416 /// except that it also works with slice elements that are Clone but not Copy.
3417 /// If Rust gets specialization this function may be deprecated.
3418 ///
3419 /// # Panics
3420 ///
3421 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3422 ///
3423 /// # Examples
3424 ///
3425 /// ```
3426 /// let mut vec = vec![1];
3427 /// vec.extend_from_slice(&[2, 3, 4]);
3428 /// assert_eq!(vec, [1, 2, 3, 4]);
3429 /// ```
3430 ///
3431 /// [`extend`]: Vec::extend
3432 #[cfg(not(no_global_oom_handling))]
3433 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
3434 pub fn extend_from_slice(&mut self, other: &[T]) {
3435 self.spec_extend(other.iter())
3436 }
3437
3438 /// Given a range `src`, clones a slice of elements in that range and appends it to the end.
3439 ///
3440 /// `src` must be a range that can form a valid subslice of the `Vec`.
3441 ///
3442 /// # Panics
3443 ///
3444 /// Panics if starting index is greater than the end index, if the index is
3445 /// greater than the length of the vector, or if the new capacity exceeds
3446 /// `isize::MAX` _bytes_.
3447 ///
3448 /// # Examples
3449 ///
3450 /// ```
3451 /// let mut characters = vec!['a', 'b', 'c', 'd', 'e'];
3452 /// characters.extend_from_within(2..);
3453 /// assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
3454 ///
3455 /// let mut numbers = vec![0, 1, 2, 3, 4];
3456 /// numbers.extend_from_within(..2);
3457 /// assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
3458 ///
3459 /// let mut strings = vec![String::from("hello"), String::from("world"), String::from("!")];
3460 /// strings.extend_from_within(1..=2);
3461 /// assert_eq!(strings, ["hello", "world", "!", "world", "!"]);
3462 /// ```
3463 #[cfg(not(no_global_oom_handling))]
3464 #[stable(feature = "vec_extend_from_within", since = "1.53.0")]
3465 pub fn extend_from_within<R>(&mut self, src: R)
3466 where
3467 R: RangeBounds<usize>,
3468 {
3469 let range = slice::range(src, ..self.len());
3470 self.reserve(range.len());
3471
3472 // SAFETY:
3473 // - `slice::range` guarantees that the given range is valid for indexing self
3474 unsafe {
3475 self.spec_extend_from_within(range);
3476 }
3477 }
3478}
3479
3480impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
3481 /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
3482 ///
3483 /// # Panics
3484 ///
3485 /// Panics if the length of the resulting vector would overflow a `usize`.
3486 ///
3487 /// This is only possible when flattening a vector of arrays of zero-sized
3488 /// types, and thus tends to be irrelevant in practice. If
3489 /// `size_of::<T>() > 0`, this will never panic.
3490 ///
3491 /// # Examples
3492 ///
3493 /// ```
3494 /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
3495 /// assert_eq!(vec.pop(), Some([7, 8, 9]));
3496 ///
3497 /// let mut flattened = vec.into_flattened();
3498 /// assert_eq!(flattened.pop(), Some(6));
3499 /// ```
3500 #[stable(feature = "slice_flatten", since = "1.80.0")]
3501 pub fn into_flattened(self) -> Vec<T, A> {
3502 let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
3503 let (new_len, new_cap) = if T::IS_ZST {
3504 (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
3505 } else {
3506 // SAFETY:
3507 // - `cap * N` cannot overflow because the allocation is already in
3508 // the address space.
3509 // - Each `[T; N]` has `N` valid elements, so there are `len * N`
3510 // valid elements in the allocation.
3511 unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) }
3512 };
3513 // SAFETY:
3514 // - `ptr` was allocated by `self`
3515 // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
3516 // - `new_cap` refers to the same sized allocation as `cap` because
3517 // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
3518 // - `len` <= `cap`, so `len * N` <= `cap * N`.
3519 unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
3520 }
3521}
3522
3523impl<T: Clone, A: Allocator> Vec<T, A> {
3524 #[cfg(not(no_global_oom_handling))]
3525 /// Extend the vector by `n` clones of value.
3526 fn extend_with(&mut self, n: usize, value: T) {
3527 self.reserve(n);
3528
3529 unsafe {
3530 let mut ptr = self.as_mut_ptr().add(self.len());
3531 // Use SetLenOnDrop to work around bug where compiler
3532 // might not realize the store through `ptr` through self.set_len()
3533 // don't alias.
3534 let mut local_len = SetLenOnDrop::new(&mut self.len);
3535
3536 // Write all elements except the last one
3537 for _ in 1..n {
3538 ptr::write(ptr, value.clone());
3539 ptr = ptr.add(1);
3540 // Increment the length in every step in case clone() panics
3541 local_len.increment_len(1);
3542 }
3543
3544 if n > 0 {
3545 // We can write the last element directly without cloning needlessly
3546 ptr::write(ptr, value);
3547 local_len.increment_len(1);
3548 }
3549
3550 // len set by scope guard
3551 }
3552 }
3553}
3554
3555impl<T: PartialEq, A: Allocator> Vec<T, A> {
3556 /// Removes consecutive repeated elements in the vector according to the
3557 /// [`PartialEq`] trait implementation.
3558 ///
3559 /// If the vector is sorted, this removes all duplicates.
3560 ///
3561 /// # Examples
3562 ///
3563 /// ```
3564 /// let mut vec = vec![1, 2, 2, 3, 2];
3565 ///
3566 /// vec.dedup();
3567 ///
3568 /// assert_eq!(vec, [1, 2, 3, 2]);
3569 /// ```
3570 #[stable(feature = "rust1", since = "1.0.0")]
3571 #[inline]
3572 pub fn dedup(&mut self) {
3573 self.dedup_by(|a, b| a == b)
3574 }
3575}
3576
3577////////////////////////////////////////////////////////////////////////////////
3578// Internal methods and functions
3579////////////////////////////////////////////////////////////////////////////////
3580
3581#[doc(hidden)]
3582#[cfg(not(no_global_oom_handling))]
3583#[stable(feature = "rust1", since = "1.0.0")]
3584#[rustc_diagnostic_item = "vec_from_elem"]
3585pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
3586 <T as SpecFromElem>::from_elem(elem, n, Global)
3587}
3588
3589#[doc(hidden)]
3590#[cfg(not(no_global_oom_handling))]
3591#[unstable(feature = "allocator_api", issue = "32838")]
3592pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
3593 <T as SpecFromElem>::from_elem(elem, n, alloc)
3594}
3595
3596#[cfg(not(no_global_oom_handling))]
3597trait ExtendFromWithinSpec {
3598 /// # Safety
3599 ///
3600 /// - `src` needs to be valid index
3601 /// - `self.capacity() - self.len()` must be `>= src.len()`
3602 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
3603}
3604
3605#[cfg(not(no_global_oom_handling))]
3606impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3607 default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3608 // SAFETY:
3609 // - len is increased only after initializing elements
3610 let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
3611
3612 // SAFETY:
3613 // - caller guarantees that src is a valid index
3614 let to_clone = unsafe { this.get_unchecked(src) };
3615
3616 iter::zip(to_clone, spare)
3617 .map(|(src, dst)| dst.write(src.clone()))
3618 // Note:
3619 // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
3620 // - len is increased after each element to prevent leaks (see issue #82533)
3621 .for_each(|_| *len += 1);
3622 }
3623}
3624
3625#[cfg(not(no_global_oom_handling))]
3626impl<T: TrivialClone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3627 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3628 let count = src.len();
3629 {
3630 let (init, spare) = self.split_at_spare_mut();
3631
3632 // SAFETY:
3633 // - caller guarantees that `src` is a valid index
3634 let source = unsafe { init.get_unchecked(src) };
3635
3636 // SAFETY:
3637 // - Both pointers are created from unique slice references (`&mut [_]`)
3638 // so they are valid and do not overlap.
3639 // - Elements implement `TrivialClone` so this is equivalent to calling
3640 // `clone` on every one of them.
3641 // - `count` is equal to the len of `source`, so source is valid for
3642 // `count` reads
3643 // - `.reserve(count)` guarantees that `spare.len() >= count` so spare
3644 // is valid for `count` writes
3645 unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
3646 }
3647
3648 // SAFETY:
3649 // - The elements were just initialized by `copy_nonoverlapping`
3650 self.len += count;
3651 }
3652}
3653
3654////////////////////////////////////////////////////////////////////////////////
3655// Common trait implementations for Vec
3656////////////////////////////////////////////////////////////////////////////////
3657
3658#[stable(feature = "rust1", since = "1.0.0")]
3659impl<T, A: Allocator> ops::Deref for Vec<T, A> {
3660 type Target = [T];
3661
3662 #[inline]
3663 fn deref(&self) -> &[T] {
3664 self.as_slice()
3665 }
3666}
3667
3668#[stable(feature = "rust1", since = "1.0.0")]
3669impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
3670 #[inline]
3671 fn deref_mut(&mut self) -> &mut [T] {
3672 self.as_mut_slice()
3673 }
3674}
3675
3676#[unstable(feature = "deref_pure_trait", issue = "87121")]
3677unsafe impl<T, A: Allocator> ops::DerefPure for Vec<T, A> {}
3678
3679#[cfg(not(no_global_oom_handling))]
3680#[stable(feature = "rust1", since = "1.0.0")]
3681impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
3682 fn clone(&self) -> Self {
3683 let alloc = self.allocator().clone();
3684 <[T]>::to_vec_in(&**self, alloc)
3685 }
3686
3687 /// Overwrites the contents of `self` with a clone of the contents of `source`.
3688 ///
3689 /// This method is preferred over simply assigning `source.clone()` to `self`,
3690 /// as it avoids reallocation if possible. Additionally, if the element type
3691 /// `T` overrides `clone_from()`, this will reuse the resources of `self`'s
3692 /// elements as well.
3693 ///
3694 /// # Examples
3695 ///
3696 /// ```
3697 /// let x = vec![5, 6, 7];
3698 /// let mut y = vec![8, 9, 10];
3699 /// let yp: *const i32 = y.as_ptr();
3700 ///
3701 /// y.clone_from(&x);
3702 ///
3703 /// // The value is the same
3704 /// assert_eq!(x, y);
3705 ///
3706 /// // And no reallocation occurred
3707 /// assert_eq!(yp, y.as_ptr());
3708 /// ```
3709 fn clone_from(&mut self, source: &Self) {
3710 crate::slice::SpecCloneIntoVec::clone_into(source.as_slice(), self);
3711 }
3712}
3713
3714/// The hash of a vector is the same as that of the corresponding slice,
3715/// as required by the `core::borrow::Borrow` implementation.
3716///
3717/// ```
3718/// use std::hash::BuildHasher;
3719///
3720/// let b = std::hash::RandomState::new();
3721/// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
3722/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
3723/// assert_eq!(b.hash_one(v), b.hash_one(s));
3724/// ```
3725#[stable(feature = "rust1", since = "1.0.0")]
3726impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
3727 #[inline]
3728 fn hash<H: Hasher>(&self, state: &mut H) {
3729 Hash::hash(&**self, state)
3730 }
3731}
3732
3733#[stable(feature = "rust1", since = "1.0.0")]
3734impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
3735 type Output = I::Output;
3736
3737 #[inline]
3738 fn index(&self, index: I) -> &Self::Output {
3739 Index::index(&**self, index)
3740 }
3741}
3742
3743#[stable(feature = "rust1", since = "1.0.0")]
3744impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
3745 #[inline]
3746 fn index_mut(&mut self, index: I) -> &mut Self::Output {
3747 IndexMut::index_mut(&mut **self, index)
3748 }
3749}
3750
3751/// Collects an iterator into a Vec, commonly called via [`Iterator::collect()`]
3752///
3753/// # Allocation behavior
3754///
3755/// In general `Vec` does not guarantee any particular growth or allocation strategy.
3756/// That also applies to this trait impl.
3757///
3758/// **Note:** This section covers implementation details and is therefore exempt from
3759/// stability guarantees.
3760///
3761/// Vec may use any or none of the following strategies,
3762/// depending on the supplied iterator:
3763///
3764/// * preallocate based on [`Iterator::size_hint()`]
3765/// * and panic if the number of items is outside the provided lower/upper bounds
3766/// * use an amortized growth strategy similar to `pushing` one item at a time
3767/// * perform the iteration in-place on the original allocation backing the iterator
3768///
3769/// The last case warrants some attention. It is an optimization that in many cases reduces peak memory
3770/// consumption and improves cache locality. But when big, short-lived allocations are created,
3771/// only a small fraction of their items get collected, no further use is made of the spare capacity
3772/// and the resulting `Vec` is moved into a longer-lived structure, then this can lead to the large
3773/// allocations having their lifetimes unnecessarily extended which can result in increased memory
3774/// footprint.
3775///
3776/// In cases where this is an issue, the excess capacity can be discarded with [`Vec::shrink_to()`],
3777/// [`Vec::shrink_to_fit()`] or by collecting into [`Box<[T]>`][owned slice] instead, which additionally reduces
3778/// the size of the long-lived struct.
3779///
3780/// [owned slice]: Box
3781///
3782/// ```rust
3783/// # use std::sync::Mutex;
3784/// static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());
3785///
3786/// for i in 0..10 {
3787/// let big_temporary: Vec<u16> = (0..1024).collect();
3788/// // discard most items
3789/// let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect();
3790/// // without this a lot of unused capacity might be moved into the global
3791/// result.shrink_to_fit();
3792/// LONG_LIVED.lock().unwrap().push(result);
3793/// }
3794/// ```
3795#[cfg(not(no_global_oom_handling))]
3796#[stable(feature = "rust1", since = "1.0.0")]
3797impl<T> FromIterator<T> for Vec<T> {
3798 #[inline]
3799 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
3800 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
3801 }
3802}
3803
3804#[stable(feature = "rust1", since = "1.0.0")]
3805impl<T, A: Allocator> IntoIterator for Vec<T, A> {
3806 type Item = T;
3807 type IntoIter = IntoIter<T, A>;
3808
3809 /// Creates a consuming iterator, that is, one that moves each value out of
3810 /// the vector (from start to end). The vector cannot be used after calling
3811 /// this.
3812 ///
3813 /// # Examples
3814 ///
3815 /// ```
3816 /// let v = vec!["a".to_string(), "b".to_string()];
3817 /// let mut v_iter = v.into_iter();
3818 ///
3819 /// let first_element: Option<String> = v_iter.next();
3820 ///
3821 /// assert_eq!(first_element, Some("a".to_string()));
3822 /// assert_eq!(v_iter.next(), Some("b".to_string()));
3823 /// assert_eq!(v_iter.next(), None);
3824 /// ```
3825 #[inline]
3826 fn into_iter(self) -> Self::IntoIter {
3827 unsafe {
3828 let me = ManuallyDrop::new(self);
3829 let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
3830 let buf = me.buf.non_null();
3831 let begin = buf.as_ptr();
3832 let end = if T::IS_ZST {
3833 begin.wrapping_byte_add(me.len())
3834 } else {
3835 begin.add(me.len()) as *const T
3836 };
3837 let cap = me.buf.capacity();
3838 IntoIter { buf, phantom: PhantomData, cap, alloc, ptr: buf, end }
3839 }
3840 }
3841}
3842
3843#[stable(feature = "rust1", since = "1.0.0")]
3844impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
3845 type Item = &'a T;
3846 type IntoIter = slice::Iter<'a, T>;
3847
3848 fn into_iter(self) -> Self::IntoIter {
3849 self.iter()
3850 }
3851}
3852
3853#[stable(feature = "rust1", since = "1.0.0")]
3854impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
3855 type Item = &'a mut T;
3856 type IntoIter = slice::IterMut<'a, T>;
3857
3858 fn into_iter(self) -> Self::IntoIter {
3859 self.iter_mut()
3860 }
3861}
3862
3863#[cfg(not(no_global_oom_handling))]
3864#[stable(feature = "rust1", since = "1.0.0")]
3865impl<T, A: Allocator> Extend<T> for Vec<T, A> {
3866 #[inline]
3867 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
3868 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
3869 }
3870
3871 #[inline]
3872 fn extend_one(&mut self, item: T) {
3873 self.push(item);
3874 }
3875
3876 #[inline]
3877 fn extend_reserve(&mut self, additional: usize) {
3878 self.reserve(additional);
3879 }
3880
3881 #[inline]
3882 unsafe fn extend_one_unchecked(&mut self, item: T) {
3883 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
3884 unsafe {
3885 let len = self.len();
3886 ptr::write(self.as_mut_ptr().add(len), item);
3887 self.set_len(len + 1);
3888 }
3889 }
3890}
3891
3892impl<T, A: Allocator> Vec<T, A> {
3893 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
3894 // they have no further optimizations to apply
3895 #[cfg(not(no_global_oom_handling))]
3896 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
3897 // This is the case for a general iterator.
3898 //
3899 // This function should be the moral equivalent of:
3900 //
3901 // for item in iterator {
3902 // self.push(item);
3903 // }
3904 while let Some(element) = iterator.next() {
3905 let len = self.len();
3906 if len == self.capacity() {
3907 let (lower, _) = iterator.size_hint();
3908 self.reserve(lower.saturating_add(1));
3909 }
3910 unsafe {
3911 ptr::write(self.as_mut_ptr().add(len), element);
3912 // Since next() executes user code which can panic we have to bump the length
3913 // after each step.
3914 // NB can't overflow since we would have had to alloc the address space
3915 self.set_len(len + 1);
3916 }
3917 }
3918 }
3919
3920 // specific extend for `TrustedLen` iterators, called both by the specializations
3921 // and internal places where resolving specialization makes compilation slower
3922 #[cfg(not(no_global_oom_handling))]
3923 fn extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) {
3924 let (low, high) = iterator.size_hint();
3925 if let Some(additional) = high {
3926 debug_assert_eq!(
3927 low,
3928 additional,
3929 "TrustedLen iterator's size hint is not exact: {:?}",
3930 (low, high)
3931 );
3932 self.reserve(additional);
3933 unsafe {
3934 let ptr = self.as_mut_ptr();
3935 let mut local_len = SetLenOnDrop::new(&mut self.len);
3936 iterator.for_each(move |element| {
3937 ptr::write(ptr.add(local_len.current_len()), element);
3938 // Since the loop executes user code which can panic we have to update
3939 // the length every step to correctly drop what we've written.
3940 // NB can't overflow since we would have had to alloc the address space
3941 local_len.increment_len(1);
3942 });
3943 }
3944 } else {
3945 // Per TrustedLen contract a `None` upper bound means that the iterator length
3946 // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
3947 // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
3948 // This avoids additional codegen for a fallback code path which would eventually
3949 // panic anyway.
3950 panic!("capacity overflow");
3951 }
3952 }
3953
3954 /// Creates a splicing iterator that replaces the specified range in the vector
3955 /// with the given `replace_with` iterator and yields the removed items.
3956 /// `replace_with` does not need to be the same length as `range`.
3957 ///
3958 /// `range` is removed even if the `Splice` iterator is not consumed before it is dropped.
3959 ///
3960 /// It is unspecified how many elements are removed from the vector
3961 /// if the `Splice` value is leaked.
3962 ///
3963 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
3964 ///
3965 /// This is optimal if:
3966 ///
3967 /// * The tail (elements in the vector after `range`) is empty,
3968 /// * or `replace_with` yields fewer or equal elements than `range`'s length
3969 /// * or the lower bound of its `size_hint()` is exact.
3970 ///
3971 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
3972 ///
3973 /// # Panics
3974 ///
3975 /// Panics if the range has `start_bound > end_bound`, or, if the range is
3976 /// bounded on either end and past the length of the vector.
3977 ///
3978 /// # Examples
3979 ///
3980 /// ```
3981 /// let mut v = vec![1, 2, 3, 4];
3982 /// let new = [7, 8, 9];
3983 /// let u: Vec<_> = v.splice(1..3, new).collect();
3984 /// assert_eq!(v, [1, 7, 8, 9, 4]);
3985 /// assert_eq!(u, [2, 3]);
3986 /// ```
3987 ///
3988 /// Using `splice` to insert new items into a vector efficiently at a specific position
3989 /// indicated by an empty range:
3990 ///
3991 /// ```
3992 /// let mut v = vec![1, 5];
3993 /// let new = [2, 3, 4];
3994 /// v.splice(1..1, new);
3995 /// assert_eq!(v, [1, 2, 3, 4, 5]);
3996 /// ```
3997 #[cfg(not(no_global_oom_handling))]
3998 #[inline]
3999 #[stable(feature = "vec_splice", since = "1.21.0")]
4000 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
4001 where
4002 R: RangeBounds<usize>,
4003 I: IntoIterator<Item = T>,
4004 {
4005 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
4006 }
4007
4008 /// Creates an iterator which uses a closure to determine if an element in the range should be removed.
4009 ///
4010 /// If the closure returns `true`, the element is removed from the vector
4011 /// and yielded. If the closure returns `false`, or panics, the element
4012 /// remains in the vector and will not be yielded.
4013 ///
4014 /// Only elements that fall in the provided range are considered for extraction, but any elements
4015 /// after the range will still have to be moved if any element has been extracted.
4016 ///
4017 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
4018 /// or the iteration short-circuits, then the remaining elements will be retained.
4019 /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
4020 /// or [`retain_mut`] with a negated predicate if you also do not need to restrict the range.
4021 ///
4022 /// [`retain_mut`]: Vec::retain_mut
4023 ///
4024 /// Using this method is equivalent to the following code:
4025 ///
4026 /// ```
4027 /// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
4028 /// # let mut vec = vec![0, 1, 2, 3, 4, 5, 6];
4029 /// # let mut vec2 = vec.clone();
4030 /// # let range = 1..5;
4031 /// let mut i = range.start;
4032 /// let end_items = vec.len() - range.end;
4033 /// # let mut extracted = vec![];
4034 ///
4035 /// while i < vec.len() - end_items {
4036 /// if some_predicate(&mut vec[i]) {
4037 /// let val = vec.remove(i);
4038 /// // your code here
4039 /// # extracted.push(val);
4040 /// } else {
4041 /// i += 1;
4042 /// }
4043 /// }
4044 ///
4045 /// # let extracted2: Vec<_> = vec2.extract_if(range, some_predicate).collect();
4046 /// # assert_eq!(vec, vec2);
4047 /// # assert_eq!(extracted, extracted2);
4048 /// ```
4049 ///
4050 /// But `extract_if` is easier to use. `extract_if` is also more efficient,
4051 /// because it can backshift the elements of the array in bulk.
4052 ///
4053 /// The iterator also lets you mutate the value of each element in the
4054 /// closure, regardless of whether you choose to keep or remove it.
4055 ///
4056 /// # Panics
4057 ///
4058 /// If `range` is out of bounds.
4059 ///
4060 /// # Examples
4061 ///
4062 /// Splitting a vector into even and odd values, reusing the original vector:
4063 ///
4064 /// ```
4065 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
4066 ///
4067 /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<Vec<_>>();
4068 /// let odds = numbers;
4069 ///
4070 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
4071 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
4072 /// ```
4073 ///
4074 /// Using the range argument to only process a part of the vector:
4075 ///
4076 /// ```
4077 /// let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2];
4078 /// let ones = items.extract_if(7.., |x| *x == 1).collect::<Vec<_>>();
4079 /// assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]);
4080 /// assert_eq!(ones.len(), 3);
4081 /// ```
4082 #[stable(feature = "extract_if", since = "1.87.0")]
4083 pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A>
4084 where
4085 F: FnMut(&mut T) -> bool,
4086 R: RangeBounds<usize>,
4087 {
4088 ExtractIf::new(self, filter, range)
4089 }
4090}
4091
4092/// Extend implementation that copies elements out of references before pushing them onto the Vec.
4093///
4094/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
4095/// append the entire slice at once.
4096///
4097/// [`copy_from_slice`]: slice::copy_from_slice
4098#[cfg(not(no_global_oom_handling))]
4099#[stable(feature = "extend_ref", since = "1.2.0")]
4100impl<'a, T: Copy + 'a, A: Allocator> Extend<&'a T> for Vec<T, A> {
4101 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
4102 self.spec_extend(iter.into_iter())
4103 }
4104
4105 #[inline]
4106 fn extend_one(&mut self, &item: &'a T) {
4107 self.push(item);
4108 }
4109
4110 #[inline]
4111 fn extend_reserve(&mut self, additional: usize) {
4112 self.reserve(additional);
4113 }
4114
4115 #[inline]
4116 unsafe fn extend_one_unchecked(&mut self, &item: &'a T) {
4117 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
4118 unsafe {
4119 let len = self.len();
4120 ptr::write(self.as_mut_ptr().add(len), item);
4121 self.set_len(len + 1);
4122 }
4123 }
4124}
4125
4126/// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison).
4127#[stable(feature = "rust1", since = "1.0.0")]
4128impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1>
4129where
4130 T: PartialOrd,
4131 A1: Allocator,
4132 A2: Allocator,
4133{
4134 #[inline]
4135 fn partial_cmp(&self, other: &Vec<T, A2>) -> Option<Ordering> {
4136 PartialOrd::partial_cmp(&**self, &**other)
4137 }
4138}
4139
4140#[stable(feature = "rust1", since = "1.0.0")]
4141impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
4142
4143/// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison).
4144#[stable(feature = "rust1", since = "1.0.0")]
4145impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
4146 #[inline]
4147 fn cmp(&self, other: &Self) -> Ordering {
4148 Ord::cmp(&**self, &**other)
4149 }
4150}
4151
4152#[stable(feature = "rust1", since = "1.0.0")]
4153unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
4154 fn drop(&mut self) {
4155 unsafe {
4156 // use drop for [T]
4157 // use a raw slice to refer to the elements of the vector as weakest necessary type;
4158 // could avoid questions of validity in certain cases
4159 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
4160 }
4161 // RawVec handles deallocation
4162 }
4163}
4164
4165#[stable(feature = "rust1", since = "1.0.0")]
4166#[rustc_const_unstable(feature = "const_default", issue = "143894")]
4167impl<T> const Default for Vec<T> {
4168 /// Creates an empty `Vec<T>`.
4169 ///
4170 /// The vector will not allocate until elements are pushed onto it.
4171 fn default() -> Vec<T> {
4172 Vec::new()
4173 }
4174}
4175
4176#[stable(feature = "rust1", since = "1.0.0")]
4177impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
4178 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4179 fmt::Debug::fmt(&**self, f)
4180 }
4181}
4182
4183#[stable(feature = "rust1", since = "1.0.0")]
4184impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
4185 fn as_ref(&self) -> &Vec<T, A> {
4186 self
4187 }
4188}
4189
4190#[stable(feature = "vec_as_mut", since = "1.5.0")]
4191impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
4192 fn as_mut(&mut self) -> &mut Vec<T, A> {
4193 self
4194 }
4195}
4196
4197#[stable(feature = "rust1", since = "1.0.0")]
4198impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
4199 fn as_ref(&self) -> &[T] {
4200 self
4201 }
4202}
4203
4204#[stable(feature = "vec_as_mut", since = "1.5.0")]
4205impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
4206 fn as_mut(&mut self) -> &mut [T] {
4207 self
4208 }
4209}
4210
4211#[cfg(not(no_global_oom_handling))]
4212#[stable(feature = "rust1", since = "1.0.0")]
4213impl<T: Clone> From<&[T]> for Vec<T> {
4214 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4215 ///
4216 /// # Examples
4217 ///
4218 /// ```
4219 /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
4220 /// ```
4221 fn from(s: &[T]) -> Vec<T> {
4222 s.to_vec()
4223 }
4224}
4225
4226#[cfg(not(no_global_oom_handling))]
4227#[stable(feature = "vec_from_mut", since = "1.19.0")]
4228impl<T: Clone> From<&mut [T]> for Vec<T> {
4229 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4230 ///
4231 /// # Examples
4232 ///
4233 /// ```
4234 /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
4235 /// ```
4236 fn from(s: &mut [T]) -> Vec<T> {
4237 s.to_vec()
4238 }
4239}
4240
4241#[cfg(not(no_global_oom_handling))]
4242#[stable(feature = "vec_from_array_ref", since = "1.74.0")]
4243impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T> {
4244 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4245 ///
4246 /// # Examples
4247 ///
4248 /// ```
4249 /// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);
4250 /// ```
4251 fn from(s: &[T; N]) -> Vec<T> {
4252 Self::from(s.as_slice())
4253 }
4254}
4255
4256#[cfg(not(no_global_oom_handling))]
4257#[stable(feature = "vec_from_array_ref", since = "1.74.0")]
4258impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T> {
4259 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4260 ///
4261 /// # Examples
4262 ///
4263 /// ```
4264 /// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
4265 /// ```
4266 fn from(s: &mut [T; N]) -> Vec<T> {
4267 Self::from(s.as_mut_slice())
4268 }
4269}
4270
4271#[cfg(not(no_global_oom_handling))]
4272#[stable(feature = "vec_from_array", since = "1.44.0")]
4273impl<T, const N: usize> From<[T; N]> for Vec<T> {
4274 /// Allocates a `Vec<T>` and moves `s`'s items into it.
4275 ///
4276 /// # Examples
4277 ///
4278 /// ```
4279 /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
4280 /// ```
4281 fn from(s: [T; N]) -> Vec<T> {
4282 <[T]>::into_vec(Box::new(s))
4283 }
4284}
4285
4286#[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
4287impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
4288where
4289 [T]: ToOwned<Owned = Vec<T>>,
4290{
4291 /// Converts a clone-on-write slice into a vector.
4292 ///
4293 /// If `s` already owns a `Vec<T>`, it will be returned directly.
4294 /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and
4295 /// filled by cloning `s`'s items into it.
4296 ///
4297 /// # Examples
4298 ///
4299 /// ```
4300 /// # use std::borrow::Cow;
4301 /// let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);
4302 /// let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);
4303 /// assert_eq!(Vec::from(o), Vec::from(b));
4304 /// ```
4305 fn from(s: Cow<'a, [T]>) -> Vec<T> {
4306 s.into_owned()
4307 }
4308}
4309
4310// note: test pulls in std, which causes errors here
4311#[stable(feature = "vec_from_box", since = "1.18.0")]
4312impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
4313 /// Converts a boxed slice into a vector by transferring ownership of
4314 /// the existing heap allocation.
4315 ///
4316 /// # Examples
4317 ///
4318 /// ```
4319 /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
4320 /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
4321 /// ```
4322 fn from(s: Box<[T], A>) -> Self {
4323 s.into_vec()
4324 }
4325}
4326
4327// note: test pulls in std, which causes errors here
4328#[cfg(not(no_global_oom_handling))]
4329#[stable(feature = "box_from_vec", since = "1.20.0")]
4330impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
4331 /// Converts a vector into a boxed slice.
4332 ///
4333 /// Before doing the conversion, this method discards excess capacity like [`Vec::shrink_to_fit`].
4334 ///
4335 /// [owned slice]: Box
4336 /// [`Vec::shrink_to_fit`]: Vec::shrink_to_fit
4337 ///
4338 /// # Examples
4339 ///
4340 /// ```
4341 /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
4342 /// ```
4343 ///
4344 /// Any excess capacity is removed:
4345 /// ```
4346 /// let mut vec = Vec::with_capacity(10);
4347 /// vec.extend([1, 2, 3]);
4348 ///
4349 /// assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice());
4350 /// ```
4351 fn from(v: Vec<T, A>) -> Self {
4352 v.into_boxed_slice()
4353 }
4354}
4355
4356#[cfg(not(no_global_oom_handling))]
4357#[stable(feature = "rust1", since = "1.0.0")]
4358impl From<&str> for Vec<u8> {
4359 /// Allocates a `Vec<u8>` and fills it with a UTF-8 string.
4360 ///
4361 /// # Examples
4362 ///
4363 /// ```
4364 /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
4365 /// ```
4366 fn from(s: &str) -> Vec<u8> {
4367 From::from(s.as_bytes())
4368 }
4369}
4370
4371#[stable(feature = "array_try_from_vec", since = "1.48.0")]
4372impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
4373 type Error = Vec<T, A>;
4374
4375 /// Gets the entire contents of the `Vec<T>` as an array,
4376 /// if its size exactly matches that of the requested array.
4377 ///
4378 /// # Examples
4379 ///
4380 /// ```
4381 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
4382 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
4383 /// ```
4384 ///
4385 /// If the length doesn't match, the input comes back in `Err`:
4386 /// ```
4387 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
4388 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
4389 /// ```
4390 ///
4391 /// If you're fine with just getting a prefix of the `Vec<T>`,
4392 /// you can call [`.truncate(N)`](Vec::truncate) first.
4393 /// ```
4394 /// let mut v = String::from("hello world").into_bytes();
4395 /// v.sort();
4396 /// v.truncate(2);
4397 /// let [a, b]: [_; 2] = v.try_into().unwrap();
4398 /// assert_eq!(a, b' ');
4399 /// assert_eq!(b, b'd');
4400 /// ```
4401 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
4402 if vec.len() != N {
4403 return Err(vec);
4404 }
4405
4406 // SAFETY: `.set_len(0)` is always sound.
4407 unsafe { vec.set_len(0) };
4408
4409 // SAFETY: A `Vec`'s pointer is always aligned properly, and
4410 // the alignment the array needs is the same as the items.
4411 // We checked earlier that we have sufficient items.
4412 // The items will not double-drop as the `set_len`
4413 // tells the `Vec` not to also drop them.
4414 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
4415 Ok(array)
4416 }
4417}