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