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