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