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 or equal to the
1705 /// vector's current 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 if len >= self.len {
1738 return;
1739 }
1740 let remaining_len = self.len - len;
1741 let s = self.as_mut_ptr().add(len).cast_slice(remaining_len);
1742 self.len = len;
1743 ptr::drop_in_place(s);
1744 }
1745 }
1746
1747 /// Extracts a slice containing the entire vector.
1748 ///
1749 /// Equivalent to `&s[..]`.
1750 ///
1751 /// # Examples
1752 ///
1753 /// ```
1754 /// use std::io::{self, Write};
1755 /// let buffer = vec![1, 2, 3, 5, 8];
1756 /// io::sink().write(buffer.as_slice()).unwrap();
1757 /// ```
1758 #[inline]
1759 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1760 #[rustc_diagnostic_item = "vec_as_slice"]
1761 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1762 pub const fn as_slice(&self) -> &[T] {
1763 // SAFETY: `slice::from_raw_parts` requires pointee is a contiguous, aligned buffer of size
1764 // `len` containing properly-initialized `T`s. Data must not be mutated for the returned
1765 // lifetime. Further, `len * size_of::<T>` <= `isize::MAX`, and allocation does not
1766 // "wrap" through overflowing memory addresses.
1767 //
1768 // * Vec API guarantees that self.buf:
1769 // * contains only properly-initialized items within 0..len
1770 // * is aligned, contiguous, and valid for `len` reads
1771 // * obeys size and address-wrapping constraints
1772 //
1773 // * We only construct `&mut` references to `self.buf` through `&mut self` methods; borrow-
1774 // check ensures that it is not possible to mutably alias `self.buf` within the
1775 // returned lifetime.
1776 unsafe {
1777 // normally this would use `slice::from_raw_parts`, but it's
1778 // instantiated often enough that avoiding the UB check is worth it
1779 &*core::intrinsics::aggregate_raw_ptr::<*const [T], _, _>(self.as_ptr(), self.len)
1780 }
1781 }
1782
1783 /// Extracts a mutable slice of the entire vector.
1784 ///
1785 /// Equivalent to `&mut s[..]`.
1786 ///
1787 /// # Examples
1788 ///
1789 /// ```
1790 /// use std::io::{self, Read};
1791 /// let mut buffer = vec![0; 3];
1792 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1793 /// ```
1794 #[inline]
1795 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1796 #[rustc_diagnostic_item = "vec_as_mut_slice"]
1797 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1798 pub const fn as_mut_slice(&mut self) -> &mut [T] {
1799 // SAFETY: `BufWriter::flush_buf` assumes that this will not
1800 // de-initialize any elements of the spare capacity.
1801
1802 // SAFETY: `slice::from_raw_parts_mut` requires pointee is a contiguous, aligned buffer of
1803 // size `len` containing properly-initialized `T`s. Data must not be accessed through any
1804 // other pointer for the returned lifetime. Further, `len * size_of::<T>` <=
1805 // `isize::MAX` and allocation does not "wrap" through overflowing memory addresses.
1806 //
1807 // * Vec API guarantees that self.buf:
1808 // * contains only properly-initialized items within 0..len
1809 // * is aligned, contiguous, and valid for `len` reads
1810 // * obeys size and address-wrapping constraints
1811 //
1812 // * We only construct references to `self.buf` through `&self` and `&mut self` methods;
1813 // borrow-check ensures that it is not possible to construct a reference to `self.buf`
1814 // within the returned lifetime.
1815 unsafe {
1816 // normally this would use `slice::from_raw_parts_mut`, but it's
1817 // instantiated often enough that avoiding the UB check is worth it
1818 &mut *core::intrinsics::aggregate_raw_ptr::<*mut [T], _, _>(self.as_mut_ptr(), self.len)
1819 }
1820 }
1821
1822 /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
1823 /// valid for zero sized reads if the vector [didn't allocate].
1824 ///
1825 /// The caller must ensure that the vector outlives the pointer this
1826 /// function returns, or else it will end up dangling.
1827 /// Modifying the vector may cause its buffer to be reallocated,
1828 /// which would also make any pointers to it invalid.
1829 ///
1830 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1831 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1832 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1833 ///
1834 /// This method guarantees that for the purpose of the aliasing model, this method
1835 /// does not materialize a reference to the underlying slice, and thus the returned pointer
1836 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1837 /// and [`as_non_null`].
1838 /// Note that calling other methods that materialize mutable references to the slice,
1839 /// or mutable references to specific elements you are planning on accessing through this pointer,
1840 /// as well as writing to those elements, may still invalidate this pointer.
1841 /// See the second example below for how this guarantee can be used.
1842 ///
1843 ///
1844 /// # Examples
1845 ///
1846 /// ```
1847 /// let x = vec![1, 2, 4];
1848 /// let x_ptr = x.as_ptr();
1849 ///
1850 /// unsafe {
1851 /// for i in 0..x.len() {
1852 /// assert_eq!(*x_ptr.add(i), 1 << i);
1853 /// }
1854 /// }
1855 /// ```
1856 ///
1857 /// Due to the aliasing guarantee, the following code is legal:
1858 ///
1859 /// ```rust
1860 /// unsafe {
1861 /// let mut v = vec![0, 1, 2];
1862 /// let ptr1 = v.as_ptr();
1863 /// let _ = ptr1.read();
1864 /// let ptr2 = v.as_mut_ptr().offset(2);
1865 /// ptr2.write(2);
1866 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`
1867 /// // because it mutated a different element:
1868 /// let _ = ptr1.read();
1869 /// }
1870 /// ```
1871 ///
1872 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1873 /// [`as_ptr`]: Vec::as_ptr
1874 /// [`as_non_null`]: Vec::as_non_null
1875 /// [didn't allocate]: self#memory-layout
1876 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1877 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1878 #[rustc_never_returns_null_ptr]
1879 #[rustc_as_ptr]
1880 #[inline]
1881 pub const fn as_ptr(&self) -> *const T {
1882 // We shadow the slice method of the same name to avoid going through
1883 // `deref`, which creates an intermediate reference.
1884 self.buf.ptr()
1885 }
1886
1887 /// Returns a raw mutable pointer to the vector's buffer, or a dangling
1888 /// raw pointer valid for zero sized reads if the vector [didn't allocate].
1889 ///
1890 /// The caller must ensure that the vector outlives the pointer this
1891 /// function returns, or else it will end up dangling.
1892 /// Modifying the vector may cause its buffer to be reallocated,
1893 /// which would also make any pointers to it invalid.
1894 ///
1895 /// This method guarantees that for the purpose of the aliasing model, this method
1896 /// does not materialize a reference to the underlying slice, and thus the returned pointer
1897 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1898 /// and [`as_non_null`].
1899 /// Note that calling other methods that materialize references to the slice,
1900 /// or references to specific elements you are planning on accessing through this pointer,
1901 /// may still invalidate this pointer.
1902 /// See the second example below for how this guarantee can be used.
1903 ///
1904 /// The method also guarantees that, as long as `T` is not zero-sized and the capacity is
1905 /// nonzero, the pointer may be passed into [`dealloc`] with a layout of
1906 /// `Layout::array::<T>(capacity)` in order to deallocate the backing memory. If this is done,
1907 /// be careful not to run the destructor of the `Vec`, as dropping it will result in
1908 /// double-frees. Wrapping the `Vec` in a [`ManuallyDrop`] is the typical way to achieve this.
1909 ///
1910 /// # Examples
1911 ///
1912 /// ```
1913 /// // Allocate vector big enough for 4 elements.
1914 /// let size = 4;
1915 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1916 /// let x_ptr = x.as_mut_ptr();
1917 ///
1918 /// // Initialize elements via raw pointer writes, then set length.
1919 /// unsafe {
1920 /// for i in 0..size {
1921 /// *x_ptr.add(i) = i as i32;
1922 /// }
1923 /// x.set_len(size);
1924 /// }
1925 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1926 /// ```
1927 ///
1928 /// Due to the aliasing guarantee, the following code is legal:
1929 ///
1930 /// ```rust
1931 /// unsafe {
1932 /// let mut v = vec![0];
1933 /// let ptr1 = v.as_mut_ptr();
1934 /// ptr1.write(1);
1935 /// let ptr2 = v.as_mut_ptr();
1936 /// ptr2.write(2);
1937 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1938 /// ptr1.write(3);
1939 /// }
1940 /// ```
1941 ///
1942 /// Deallocating a vector using [`Box`] (which uses [`dealloc`] internally):
1943 ///
1944 /// ```
1945 /// use std::mem::{ManuallyDrop, MaybeUninit};
1946 ///
1947 /// let mut v = ManuallyDrop::new(vec![0, 1, 2]);
1948 /// let ptr = v.as_mut_ptr();
1949 /// let capacity = v.capacity();
1950 /// let slice_ptr: *mut [MaybeUninit<i32>] =
1951 /// std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity);
1952 /// drop(unsafe { Box::from_raw(slice_ptr) });
1953 /// ```
1954 ///
1955 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1956 /// [`as_ptr`]: Vec::as_ptr
1957 /// [`as_non_null`]: Vec::as_non_null
1958 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
1959 /// [`ManuallyDrop`]: core::mem::ManuallyDrop
1960 /// [didn't allocate]: self#memory-layout
1961 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1962 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1963 #[rustc_never_returns_null_ptr]
1964 #[rustc_as_ptr]
1965 #[inline]
1966 pub const fn as_mut_ptr(&mut self) -> *mut T {
1967 // We shadow the slice method of the same name to avoid going through
1968 // `deref_mut`, which creates an intermediate reference.
1969 self.buf.ptr()
1970 }
1971
1972 /// Returns a `NonNull` pointer to the vector's buffer, or a dangling
1973 /// `NonNull` pointer valid for zero sized reads if the vector [didn't allocate].
1974 ///
1975 /// The caller must ensure that the vector outlives the pointer this
1976 /// function returns, or else it will end up dangling.
1977 /// Modifying the vector may cause its buffer to be reallocated,
1978 /// which would also make any pointers to it invalid.
1979 ///
1980 /// This method guarantees that for the purpose of the aliasing model, this method
1981 /// does not materialize a reference to the underlying slice, and thus the returned pointer
1982 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1983 /// and [`as_non_null`].
1984 /// Note that calling other methods that materialize references to the slice,
1985 /// or references to specific elements you are planning on accessing through this pointer,
1986 /// may still invalidate this pointer.
1987 /// See the second example below for how this guarantee can be used.
1988 ///
1989 /// # Examples
1990 ///
1991 /// ```
1992 /// #![feature(vec_as_non_null)]
1993 ///
1994 /// // Allocate vector big enough for 4 elements.
1995 /// let size = 4;
1996 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1997 /// let x_ptr = x.as_non_null();
1998 ///
1999 /// // Initialize elements via raw pointer writes, then set length.
2000 /// unsafe {
2001 /// for i in 0..size {
2002 /// x_ptr.add(i).write(i as i32);
2003 /// }
2004 /// x.set_len(size);
2005 /// }
2006 /// assert_eq!(&*x, &[0, 1, 2, 3]);
2007 /// ```
2008 ///
2009 /// Due to the aliasing guarantee, the following code is legal:
2010 ///
2011 /// ```rust
2012 /// #![feature(vec_as_non_null)]
2013 ///
2014 /// unsafe {
2015 /// let mut v = vec![0];
2016 /// let ptr1 = v.as_non_null();
2017 /// ptr1.write(1);
2018 /// let ptr2 = v.as_non_null();
2019 /// ptr2.write(2);
2020 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
2021 /// ptr1.write(3);
2022 /// }
2023 /// ```
2024 ///
2025 /// [`as_mut_ptr`]: Vec::as_mut_ptr
2026 /// [`as_ptr`]: Vec::as_ptr
2027 /// [`as_non_null`]: Vec::as_non_null
2028 /// [didn't allocate]: self#memory-layout
2029 #[unstable(feature = "vec_as_non_null", issue = "157843")]
2030 #[rustc_const_unstable(feature = "vec_as_non_null", issue = "157843")]
2031 #[rustc_as_ptr]
2032 #[inline]
2033 pub const fn as_non_null(&mut self) -> NonNull<T> {
2034 self.buf.non_null()
2035 }
2036
2037 /// Returns a reference to the underlying allocator.
2038 #[stable(feature = "allocator_api", since = "1.100.0")]
2039 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2040 #[inline]
2041 pub const fn allocator(&self) -> &A {
2042 self.buf.allocator()
2043 }
2044
2045 /// Forces the length of the vector to `new_len`.
2046 ///
2047 /// This is a low-level operation that maintains none of the normal
2048 /// invariants of the type. Normally changing the length of a vector
2049 /// is done using one of the safe operations instead, such as
2050 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
2051 ///
2052 /// [`truncate`]: Vec::truncate
2053 /// [`resize`]: Vec::resize
2054 /// [`extend`]: Extend::extend
2055 /// [`clear`]: Vec::clear
2056 ///
2057 /// # Safety
2058 ///
2059 /// - `new_len` must be less than or equal to [`capacity()`].
2060 /// - The elements at `old_len..new_len` must be initialized.
2061 ///
2062 /// [`capacity()`]: Vec::capacity
2063 ///
2064 /// # Examples
2065 ///
2066 /// See [`spare_capacity_mut()`] for an example with safe
2067 /// initialization of capacity elements and use of this method.
2068 ///
2069 /// `set_len()` can be useful for situations in which the vector
2070 /// is serving as a buffer for other code, particularly over FFI:
2071 ///
2072 /// ```no_run
2073 /// # #![allow(dead_code)]
2074 /// # // This is just a minimal skeleton for the doc example;
2075 /// # // don't use this as a starting point for a real library.
2076 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
2077 /// # const Z_OK: i32 = 0;
2078 /// # unsafe extern "C" {
2079 /// # fn deflateGetDictionary(
2080 /// # strm: *mut std::ffi::c_void,
2081 /// # dictionary: *mut u8,
2082 /// # dictLength: *mut usize,
2083 /// # ) -> i32;
2084 /// # }
2085 /// # impl StreamWrapper {
2086 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
2087 /// // Per the FFI method's docs, "32768 bytes is always enough".
2088 /// let mut dict = Vec::with_capacity(32_768);
2089 /// let mut dict_length = 0;
2090 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
2091 /// // 1. `dict_length` elements were initialized.
2092 /// // 2. `dict_length` <= the capacity (32_768)
2093 /// // which makes `set_len` safe to call.
2094 /// unsafe {
2095 /// // Make the FFI call...
2096 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
2097 /// if r == Z_OK {
2098 /// // ...and update the length to what was initialized.
2099 /// dict.set_len(dict_length);
2100 /// Some(dict)
2101 /// } else {
2102 /// None
2103 /// }
2104 /// }
2105 /// }
2106 /// # }
2107 /// ```
2108 ///
2109 /// While the following example is sound, there is a memory leak since
2110 /// the inner vectors were not freed prior to the `set_len` call:
2111 ///
2112 /// ```
2113 /// let mut vec = vec![vec![1, 0, 0],
2114 /// vec![0, 1, 0],
2115 /// vec![0, 0, 1]];
2116 /// // SAFETY:
2117 /// // 1. `old_len..0` is empty so no elements need to be initialized.
2118 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
2119 /// unsafe {
2120 /// vec.set_len(0);
2121 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
2122 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
2123 /// # vec.set_len(3);
2124 /// }
2125 /// ```
2126 ///
2127 /// Normally, here, one would use [`clear`] instead to correctly drop
2128 /// the contents and thus not leak memory.
2129 ///
2130 /// [`spare_capacity_mut()`]: Vec::spare_capacity_mut
2131 #[inline]
2132 #[stable(feature = "rust1", since = "1.0.0")]
2133 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
2134 pub const unsafe fn set_len(&mut self, new_len: usize) {
2135 ub_checks::assert_unsafe_precondition!(
2136 check_library_ub,
2137 "Vec::set_len requires that new_len <= capacity()",
2138 (new_len: usize = new_len, capacity: usize = self.capacity()) => new_len <= capacity
2139 );
2140
2141 self.len = new_len;
2142 }
2143
2144 /// Removes an element from the vector and returns it.
2145 ///
2146 /// The removed element is replaced by the last element of the vector.
2147 ///
2148 /// This does not preserve ordering of the remaining elements, but is *O*(1).
2149 /// If you need to preserve the element order, use [`remove`] instead.
2150 ///
2151 /// [`remove`]: Vec::remove
2152 ///
2153 /// # Panics
2154 ///
2155 /// Panics if `index` is out of bounds.
2156 ///
2157 /// # Examples
2158 ///
2159 /// ```
2160 /// let mut v = vec!["foo", "bar", "baz", "qux"];
2161 ///
2162 /// assert_eq!(v.swap_remove(1), "bar");
2163 /// assert_eq!(v, ["foo", "qux", "baz"]);
2164 ///
2165 /// assert_eq!(v.swap_remove(0), "foo");
2166 /// assert_eq!(v, ["baz", "qux"]);
2167 /// ```
2168 #[inline]
2169 #[stable(feature = "rust1", since = "1.0.0")]
2170 pub fn swap_remove(&mut self, index: usize) -> T {
2171 #[cold]
2172 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2173 #[optimize(size)]
2174 fn assert_failed(index: usize, len: usize) -> ! {
2175 panic!("swap_remove index (is {index}) should be < len (is {len})");
2176 }
2177
2178 let len = self.len();
2179 if index >= len {
2180 assert_failed(index, len);
2181 }
2182 // ignore-tidy-undocumented-unsafe
2183 unsafe {
2184 // We replace self[index] with the last element. Note that if the
2185 // bounds check above succeeds there must be a last element (which
2186 // can be self[index] itself).
2187 let value = ptr::read(self.as_ptr().add(index));
2188 let base_ptr = self.as_mut_ptr();
2189 ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
2190 self.set_len(len - 1);
2191 value
2192 }
2193 }
2194
2195 /// Inserts an element at position `index` within the vector, shifting all
2196 /// elements after it to the right.
2197 ///
2198 /// # Panics
2199 ///
2200 /// Panics if `index > len`.
2201 ///
2202 /// # Examples
2203 ///
2204 /// ```
2205 /// let mut vec = vec!['a', 'b', 'c'];
2206 /// vec.insert(1, 'd');
2207 /// assert_eq!(vec, ['a', 'd', 'b', 'c']);
2208 /// vec.insert(4, 'e');
2209 /// assert_eq!(vec, ['a', 'd', 'b', 'c', 'e']);
2210 /// ```
2211 ///
2212 /// # Time complexity
2213 ///
2214 /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be
2215 /// shifted to the right. In the worst case, all elements are shifted when
2216 /// the insertion index is 0.
2217 #[cfg(not(no_global_oom_handling))]
2218 #[stable(feature = "rust1", since = "1.0.0")]
2219 #[track_caller]
2220 pub fn insert(&mut self, index: usize, element: T) {
2221 let _ = self.insert_mut(index, element);
2222 }
2223
2224 /// Inserts an element at position `index` within the vector, shifting all
2225 /// elements after it to the right, and returning a reference to the new
2226 /// element.
2227 ///
2228 /// # Panics
2229 ///
2230 /// Panics if `index > len`.
2231 ///
2232 /// # Examples
2233 ///
2234 /// ```
2235 /// let mut vec = vec![1, 3, 5, 9];
2236 /// let x = vec.insert_mut(3, 6);
2237 /// *x += 1;
2238 /// assert_eq!(vec, [1, 3, 5, 7, 9]);
2239 /// ```
2240 ///
2241 /// # Time complexity
2242 ///
2243 /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be
2244 /// shifted to the right. In the worst case, all elements are shifted when
2245 /// the insertion index is 0.
2246 #[cfg(not(no_global_oom_handling))]
2247 #[inline]
2248 #[stable(feature = "push_mut", since = "1.95.0")]
2249 #[track_caller]
2250 #[must_use = "if you don't need a reference to the value, use `Vec::insert` instead"]
2251 pub fn insert_mut(&mut self, index: usize, element: T) -> &mut T {
2252 #[cold]
2253 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2254 #[track_caller]
2255 #[optimize(size)]
2256 fn assert_failed(index: usize, len: usize) -> ! {
2257 panic!("insertion index (is {index}) should be <= len (is {len})");
2258 }
2259
2260 let len = self.len();
2261 if index > len {
2262 assert_failed(index, len);
2263 }
2264
2265 // space for the new element
2266 if len == self.buf.capacity() {
2267 self.buf.grow_one();
2268 }
2269
2270 // ignore-tidy-undocumented-unsafe
2271 unsafe {
2272 // infallible
2273 // The spot to put the new value
2274 let p = self.as_mut_ptr().add(index);
2275 {
2276 if index < len {
2277 // Shift everything over to make space. (Duplicating the
2278 // `index`th element into two consecutive places.)
2279 ptr::copy(p, p.add(1), len - index);
2280 }
2281 // Write it in, overwriting the first copy of the `index`th
2282 // element.
2283 ptr::write(p, element);
2284 }
2285 self.set_len(len + 1);
2286 &mut *p
2287 }
2288 }
2289
2290 /// Removes and returns the element at position `index` within the vector,
2291 /// shifting all elements after it to the left.
2292 ///
2293 /// Note: Because this shifts over the remaining elements, it has a
2294 /// worst-case performance of *O*(*n*). If you don't need the order of elements
2295 /// to be preserved, use [`swap_remove`] instead. If you'd like to remove
2296 /// elements from the beginning of the `Vec`, consider using
2297 /// [`VecDeque::pop_front`] instead.
2298 ///
2299 /// [`swap_remove`]: Vec::swap_remove
2300 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2301 ///
2302 /// # Panics
2303 ///
2304 /// Panics if `index` is out of bounds.
2305 ///
2306 /// # Examples
2307 ///
2308 /// ```
2309 /// let mut v = vec!['a', 'b', 'c'];
2310 /// assert_eq!(v.remove(1), 'b');
2311 /// assert_eq!(v, ['a', 'c']);
2312 /// ```
2313 #[stable(feature = "rust1", since = "1.0.0")]
2314 #[track_caller]
2315 #[rustc_confusables("delete", "take")]
2316 pub fn remove(&mut self, index: usize) -> T {
2317 #[cold]
2318 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2319 #[track_caller]
2320 #[optimize(size)]
2321 fn assert_failed(index: usize, len: usize) -> ! {
2322 panic!("removal index (is {index}) should be < len (is {len})");
2323 }
2324
2325 match self.try_remove(index) {
2326 Some(elem) => elem,
2327 None => assert_failed(index, self.len()),
2328 }
2329 }
2330
2331 /// Remove and return the element at position `index` within the vector,
2332 /// shifting all elements after it to the left, or [`None`] if it does not
2333 /// exist.
2334 ///
2335 /// Note: Because this shifts over the remaining elements, it has a
2336 /// worst-case performance of *O*(*n*). If you'd like to remove
2337 /// elements from the beginning of the `Vec`, consider using
2338 /// [`VecDeque::pop_front`] instead.
2339 ///
2340 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2341 ///
2342 /// # Examples
2343 ///
2344 /// ```
2345 /// let mut v = vec![1, 2, 3];
2346 /// assert_eq!(v.try_remove(0), Some(1));
2347 /// assert_eq!(v.try_remove(2), None);
2348 /// ```
2349 #[stable(feature = "vec_try_remove", since = "CURRENT_RUSTC_VERSION")]
2350 #[rustc_confusables("delete", "take", "remove")]
2351 pub fn try_remove(&mut self, index: usize) -> Option<T> {
2352 let len = self.len();
2353 if index >= len {
2354 return None;
2355 }
2356 // infallible
2357 let ret;
2358 // ignore-tidy-undocumented-unsafe
2359 unsafe {
2360 {
2361 // the place we are taking from.
2362 let ptr = self.as_mut_ptr().add(index);
2363 // copy it out, unsafely having a copy of the value on
2364 // the stack and in the vector at the same time.
2365 ret = ptr::read(ptr);
2366
2367 // Shift everything down to fill in that spot.
2368 ptr::copy(ptr.add(1), ptr, len - index - 1);
2369 }
2370 self.set_len(len - 1);
2371 }
2372 Some(ret)
2373 }
2374
2375 /// Retains only the elements specified by the predicate.
2376 ///
2377 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
2378 /// This method operates in place, visiting each element exactly once in the
2379 /// original order, and preserves the order of the retained elements.
2380 ///
2381 /// # Examples
2382 ///
2383 /// ```
2384 /// let mut vec = vec![1, 2, 3, 4];
2385 /// vec.retain(|&x| x % 2 == 0);
2386 /// assert_eq!(vec, [2, 4]);
2387 /// ```
2388 ///
2389 /// Because the elements are visited exactly once in the original order,
2390 /// external state may be used to decide which elements to keep.
2391 ///
2392 /// ```
2393 /// let mut vec = vec![1, 2, 3, 4, 5];
2394 /// let keep = [false, true, true, false, true];
2395 /// let mut iter = keep.iter();
2396 /// vec.retain(|_| *iter.next().unwrap());
2397 /// assert_eq!(vec, [2, 3, 5]);
2398 /// ```
2399 #[stable(feature = "rust1", since = "1.0.0")]
2400 pub fn retain<F>(&mut self, mut f: F)
2401 where
2402 F: FnMut(&T) -> bool,
2403 {
2404 self.retain_mut(|elem| f(elem));
2405 }
2406
2407 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
2408 ///
2409 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
2410 /// This method operates in place, visiting each element exactly once in the
2411 /// original order, and preserves the order of the retained elements.
2412 ///
2413 /// # Examples
2414 ///
2415 /// ```
2416 /// let mut vec = vec![1, 2, 3, 4];
2417 /// vec.retain_mut(|x| if *x <= 3 {
2418 /// *x += 1;
2419 /// true
2420 /// } else {
2421 /// false
2422 /// });
2423 /// assert_eq!(vec, [2, 3, 4]);
2424 /// ```
2425 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2426 pub fn retain_mut<F>(&mut self, mut f: F)
2427 where
2428 F: FnMut(&mut T) -> bool,
2429 {
2430 let original_len = self.len();
2431
2432 if original_len == 0 {
2433 // Empty case: explicit return allows better optimization, vs letting compiler infer it
2434 return;
2435 }
2436
2437 #[cfg(all(target_arch = "aarch64", target_feature = "sve"))]
2438 {
2439 let long_enough = match mem::size_of::<T>() {
2440 1 => original_len >= sve_retain::MIN_SVE_SIZE_1,
2441 2 => original_len >= sve_retain::MIN_SVE_SIZE_2,
2442 4 => original_len >= sve_retain::MIN_SVE_SIZE_4,
2443 8 => original_len >= sve_retain::MIN_SVE_SIZE_8,
2444 _ => false,
2445 };
2446 if long_enough {
2447 // SAFETY: size_of::<T>() is 1, 2, 4 or 8, matching
2448 // the kernel lane widths.
2449 return unsafe { sve_retain::chunked_retain(self, f) };
2450 }
2451 }
2452
2453 // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
2454 // | ^- write ^- read |
2455 // |<- original_len ->|
2456 // Kept: Elements which predicate returns true on.
2457 // Hole: Moved or dropped element slot.
2458 // Unchecked: Unchecked valid elements.
2459 //
2460 // This drop guard will be invoked when predicate or `drop` of element panicked.
2461 // It shifts unchecked elements to cover holes and `set_len` to the correct length.
2462 // In cases when predicate and `drop` never panick, it will be optimized out.
2463 struct PanicGuard<'a, T, A: Allocator> {
2464 v: &'a mut Vec<T, A>,
2465 read: usize,
2466 write: usize,
2467 original_len: usize,
2468 }
2469
2470 impl<T, A: Allocator> Drop for PanicGuard<'_, T, A> {
2471 #[cold]
2472 fn drop(&mut self) {
2473 let remaining = self.original_len - self.read;
2474 // SAFETY: Trailing unchecked items must be valid since we never touch them.
2475 unsafe {
2476 ptr::copy(
2477 self.v.as_ptr().add(self.read),
2478 self.v.as_mut_ptr().add(self.write),
2479 remaining,
2480 );
2481 }
2482 // SAFETY: After filling holes, all items are in contiguous memory.
2483 unsafe {
2484 self.v.set_len(self.write + remaining);
2485 }
2486 }
2487 }
2488
2489 let mut read = 0;
2490 loop {
2491 // SAFETY: read < original_len
2492 let cur = unsafe { self.get_unchecked_mut(read) };
2493 if hint::unlikely(!f(cur)) {
2494 break;
2495 }
2496 read += 1;
2497 if read == original_len {
2498 // All elements are kept, return early.
2499 return;
2500 }
2501 }
2502
2503 // Critical section starts here and at least one element is going to be removed.
2504 // Advance `g.read` early to avoid double drop if `drop_in_place` panicked.
2505 let mut g = PanicGuard { v: self, read: read + 1, write: read, original_len };
2506 // SAFETY: previous `read` is always less than original_len.
2507 unsafe { ptr::drop_in_place(&mut *g.v.as_mut_ptr().add(read)) };
2508
2509 while g.read < g.original_len {
2510 // SAFETY: `read` is always less than original_len.
2511 let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.read) };
2512 if !f(cur) {
2513 // Advance `read` early to avoid double drop if `drop_in_place` panicked.
2514 g.read += 1;
2515 // SAFETY: We never touch this element again after dropped.
2516 unsafe { ptr::drop_in_place(cur) };
2517 } else {
2518 // SAFETY: `read` > `write`, so the slots don't overlap.
2519 // We use copy for move, and never touch the source element again.
2520 unsafe {
2521 let hole = g.v.as_mut_ptr().add(g.write);
2522 ptr::copy_nonoverlapping(cur, hole, 1);
2523 }
2524 g.write += 1;
2525 g.read += 1;
2526 }
2527 }
2528
2529 // We are leaving the critical section and no panic happened,
2530 // Commit the length change and forget the guard.
2531 // SAFETY: `write` is always less than or equal to original_len.
2532 unsafe { g.v.set_len(g.write) };
2533 mem::forget(g);
2534 }
2535
2536 /// Removes all but the first of consecutive elements in the vector that resolve to the same
2537 /// key.
2538 ///
2539 /// If the vector is sorted, this removes all duplicates.
2540 ///
2541 /// # Examples
2542 ///
2543 /// ```
2544 /// let mut vec = vec![10, 20, 21, 30, 20];
2545 ///
2546 /// vec.dedup_by_key(|i| *i / 10);
2547 ///
2548 /// assert_eq!(vec, [10, 20, 30, 20]);
2549 /// ```
2550 #[stable(feature = "dedup_by", since = "1.16.0")]
2551 #[inline]
2552 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
2553 where
2554 F: FnMut(&mut T) -> K,
2555 K: PartialEq,
2556 {
2557 self.dedup_by(|a, b| key(a) == key(b))
2558 }
2559
2560 /// Removes all but the first of consecutive elements in the vector that are
2561 /// "equal" according to the given predicate function.
2562 ///
2563 /// The predicate `same_bucket(x, p)` is passed references to two elements.
2564 /// If it returns `true`, the element `x` is removed from the vector.
2565 ///
2566 /// The element `p` occurs *before* `x` in the vector (`[.., p, .., x, ..]`),
2567 /// so `same_bucket(x, p)` is receiving them in reversed order (unlike [`windows`]).
2568 ///
2569 /// If the vector is sorted, this removes all duplicates. For more complicated predicates
2570 /// however, the order (ascending vs. descending) can matter.
2571 ///
2572 /// [`windows`]: slice::windows
2573 ///
2574 /// # Examples
2575 ///
2576 /// ```
2577 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
2578 /// vec.dedup_by(|x, p| x.eq_ignore_ascii_case(p));
2579 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
2580 /// ```
2581 ///
2582 /// Both references passed to `same_bucket` are mutable.
2583 /// This allows merging elements by mutating `p` and returning `true`:
2584 ///
2585 /// ```
2586 /// let mut ranges = vec![1..2, 2..4, 2..5, 8..9];
2587 ///
2588 /// // Sort ranges by start, and if equal, by end (lexicographically)
2589 /// // Sorting in reverse instead (`x.start.cmp(&p.start)...`) would later fail
2590 /// ranges.sort_unstable_by(|p, x| p.start.cmp(&x.start).then(p.end.cmp(&x.end)));
2591 ///
2592 /// // Merge touching (`1..2` and `2..4`) and then overlapping (`1..4` and `2..5`) ranges
2593 /// ranges.dedup_by(|x, p| {
2594 /// if p.end >= x.start {
2595 /// p.end = p.end.max(x.end);
2596 /// true
2597 /// } else {
2598 /// false
2599 /// }
2600 /// });
2601 ///
2602 /// assert_eq!(ranges, [1..5, 8..9]);
2603 /// ```
2604 #[stable(feature = "dedup_by", since = "1.16.0")]
2605 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
2606 where
2607 F: FnMut(&mut T, &mut T) -> bool,
2608 {
2609 let len = self.len();
2610 if len <= 1 {
2611 return;
2612 }
2613
2614 // Check if we ever want to remove anything.
2615 // This allows to use copy_non_overlapping in next cycle.
2616 // And avoids any memory writes if we don't need to remove anything.
2617 let mut first_duplicate_idx: usize = 1;
2618 let start = self.as_mut_ptr();
2619 while first_duplicate_idx != len {
2620 let found_duplicate = {
2621 // SAFETY: first_duplicate always in range [1..len).
2622 // Note that we start iteration from 1 so we never overflow.
2623 let prev = unsafe { start.add(first_duplicate_idx.wrapping_sub(1)) };
2624 // ignore-tidy-undocumented-unsafe
2625 let current = unsafe { start.add(first_duplicate_idx) };
2626 // We explicitly say in docs that references are reversed.
2627 // ignore-tidy-undocumented-unsafe
2628 unsafe { same_bucket(&mut *current, &mut *prev) }
2629 };
2630 if found_duplicate {
2631 break;
2632 }
2633 first_duplicate_idx += 1;
2634 }
2635 // Don't need to remove anything.
2636 // We cannot get bigger than len.
2637 if first_duplicate_idx == len {
2638 return;
2639 }
2640 // SAFETY: first_duplicate_idx always in range [1..len)
2641 unsafe {
2642 self.dedup_tail(same_bucket, first_duplicate_idx);
2643 }
2644 }
2645
2646 /// Continues deduplication after the first duplicate is found.
2647 ///
2648 /// The function treats `self[first_duplicate]` as the first duplicated
2649 /// element and drops it.
2650 ///
2651 /// # Safety
2652 ///
2653 /// `1 <= first_duplicate < self.len()`
2654 unsafe fn dedup_tail<F>(&mut self, mut same_bucket: F, first_duplicate: usize)
2655 where
2656 F: FnMut(&mut T, &mut T) -> bool,
2657 {
2658 /* INVARIANT: vec.len() > read > write > write-1 >= 0 */
2659 struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> {
2660 /* Offset of the element we want to check if it is duplicate */
2661 read: usize,
2662
2663 /* Offset of the place where we want to place the non-duplicate
2664 * when we find it. */
2665 write: usize,
2666
2667 /* The Vec that would need correction if `same_bucket` panicked */
2668 vec: &'a mut Vec<T, A>,
2669 }
2670
2671 impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
2672 fn drop(&mut self) {
2673 /* This code gets executed when `same_bucket` panics */
2674
2675 // SAFETY: invariant guarantees that `read - write`
2676 // and `len - read` never overflow and that the copy is always
2677 // in-bounds.
2678 unsafe {
2679 let ptr = self.vec.as_mut_ptr();
2680 let len = self.vec.len();
2681
2682 /* How many items were left when `same_bucket` panicked.
2683 * Basically vec[read..].len() */
2684 let items_left = len.wrapping_sub(self.read);
2685
2686 /* Pointer to first item in vec[write..write+items_left] slice */
2687 let dropped_ptr = ptr.add(self.write);
2688 /* Pointer to first item in vec[read..] slice */
2689 let valid_ptr = ptr.add(self.read);
2690
2691 /* Copy `vec[read..]` to `vec[write..write+items_left]`.
2692 * The slices can overlap, so `copy_nonoverlapping` cannot be used */
2693 ptr::copy(valid_ptr, dropped_ptr, items_left);
2694
2695 /* How many items have been already dropped
2696 * Basically vec[read..write].len() */
2697 let dropped = self.read.wrapping_sub(self.write);
2698
2699 self.vec.set_len(len - dropped);
2700 }
2701 }
2702 }
2703
2704 let start = self.as_mut_ptr();
2705 let len = self.len();
2706
2707 /* Drop items while going through Vec, it should be more efficient than
2708 * doing slice partition_dedup + truncate */
2709
2710 // Construct gap first and then drop item to avoid memory corruption if `T::drop` panics.
2711 let mut gap =
2712 FillGapOnDrop { read: first_duplicate + 1, write: first_duplicate, vec: self };
2713
2714 // SAFETY: By this function's safety contract, `first_duplicate < self.len()`.
2715 // If drop panics, `gap` would remove this item without drop.
2716 unsafe {
2717 ptr::drop_in_place(start.add(first_duplicate));
2718 }
2719
2720 // SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
2721 // are always in-bounds and read_ptr never aliases prev_ptr
2722 unsafe {
2723 while gap.read < len {
2724 let read_ptr = start.add(gap.read);
2725 let prev_ptr = start.add(gap.write.wrapping_sub(1));
2726
2727 // We explicitly say in docs that references are reversed.
2728 let found_duplicate = same_bucket(&mut *read_ptr, &mut *prev_ptr);
2729 if found_duplicate {
2730 // Increase `gap.read` now since the drop may panic.
2731 gap.read += 1;
2732 /* We have found duplicate, drop it in-place */
2733 ptr::drop_in_place(read_ptr);
2734 } else {
2735 let write_ptr = start.add(gap.write);
2736
2737 /* read_ptr cannot be equal to write_ptr because at this point
2738 * we guaranteed to skip at least one element (before loop starts).
2739 */
2740 ptr::copy_nonoverlapping(read_ptr, write_ptr, 1);
2741
2742 /* We have filled that place, so go further */
2743 gap.write += 1;
2744 gap.read += 1;
2745 }
2746 }
2747
2748 /* Technically we could let `gap` clean up with its Drop, but
2749 * when `same_bucket` is guaranteed to not panic, this bloats a little
2750 * the codegen, so we just do it manually */
2751 gap.vec.set_len(gap.write);
2752 mem::forget(gap);
2753 }
2754 }
2755
2756 /// Appends an element and returns a reference to it if there is sufficient spare capacity,
2757 /// otherwise an error is returned with the element.
2758 ///
2759 /// Unlike [`push`] this method will not reallocate when there's insufficient capacity.
2760 /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity.
2761 ///
2762 /// [`push`]: Vec::push
2763 /// [`reserve`]: Vec::reserve
2764 /// [`try_reserve`]: Vec::try_reserve
2765 ///
2766 /// # Examples
2767 ///
2768 /// A manual, panic-free alternative to [`FromIterator`]:
2769 ///
2770 /// ```
2771 /// #![feature(vec_push_within_capacity)]
2772 ///
2773 /// use std::collections::TryReserveError;
2774 /// fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
2775 /// let mut vec = Vec::new();
2776 /// for value in iter {
2777 /// if let Err(value) = vec.push_within_capacity(value) {
2778 /// vec.try_reserve(1)?;
2779 /// // this cannot fail, the previous line either returned or added at least 1 free slot
2780 /// let _ = vec.push_within_capacity(value);
2781 /// }
2782 /// }
2783 /// Ok(vec)
2784 /// }
2785 /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
2786 /// ```
2787 ///
2788 /// # Time complexity
2789 ///
2790 /// Takes *O*(1) time.
2791 #[inline]
2792 #[unstable(feature = "vec_push_within_capacity", issue = "100486")]
2793 pub fn push_within_capacity(&mut self, value: T) -> Result<&mut T, T> {
2794 if self.len == self.buf.capacity() {
2795 return Err(value);
2796 }
2797
2798 // ignore-tidy-undocumented-unsafe
2799 let end = unsafe { self.as_mut_ptr().add(self.len) };
2800 // ignore-tidy-undocumented-unsafe
2801 unsafe { ptr::write(end, value) };
2802 self.len += 1;
2803
2804 // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference.
2805 Ok(unsafe { &mut *end })
2806 }
2807
2808 /// Removes the last element from a vector and returns it, or [`None`] if it
2809 /// is empty.
2810 ///
2811 /// If you'd like to pop the first element, consider using
2812 /// [`VecDeque::pop_front`] instead.
2813 ///
2814 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2815 ///
2816 /// # Examples
2817 ///
2818 /// ```
2819 /// let mut vec = vec![1, 2, 3];
2820 /// assert_eq!(vec.pop(), Some(3));
2821 /// assert_eq!(vec, [1, 2]);
2822 /// ```
2823 ///
2824 /// # Time complexity
2825 ///
2826 /// Takes *O*(1) time.
2827 #[inline]
2828 #[stable(feature = "rust1", since = "1.0.0")]
2829 #[rustc_diagnostic_item = "vec_pop"]
2830 pub fn pop(&mut self) -> Option<T> {
2831 if self.len == 0 {
2832 None
2833 } else {
2834 self.len -= 1;
2835 // ignore-tidy-undocumented-unsafe
2836 unsafe {
2837 core::hint::assert_unchecked(self.len < self.capacity());
2838 Some(ptr::read(self.as_ptr().add(self.len())))
2839 }
2840 }
2841 }
2842
2843 /// Removes and returns the last element from a vector if the predicate
2844 /// returns `true`, or [`None`] if the predicate returns false or the vector
2845 /// is empty (the predicate will not be called in that case).
2846 ///
2847 /// # Examples
2848 ///
2849 /// ```
2850 /// let mut vec = vec![1, 2, 3, 4];
2851 /// let pred = |x: &mut i32| *x % 2 == 0;
2852 ///
2853 /// assert_eq!(vec.pop_if(pred), Some(4));
2854 /// assert_eq!(vec, [1, 2, 3]);
2855 /// assert_eq!(vec.pop_if(pred), None);
2856 /// ```
2857 #[stable(feature = "vec_pop_if", since = "1.86.0")]
2858 pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2859 let last = self.last_mut()?;
2860 if predicate(last) { self.pop() } else { None }
2861 }
2862
2863 /// Returns a mutable reference to the last item in the vector, or
2864 /// `None` if it is empty.
2865 ///
2866 /// # Examples
2867 ///
2868 /// Basic usage:
2869 ///
2870 /// ```
2871 /// #![feature(vec_peek_mut)]
2872 /// let mut vec = Vec::new();
2873 /// assert!(vec.peek_mut().is_none());
2874 ///
2875 /// vec.push(1);
2876 /// vec.push(5);
2877 /// vec.push(2);
2878 /// assert_eq!(vec.last(), Some(&2));
2879 /// if let Some(mut val) = vec.peek_mut() {
2880 /// *val = 0;
2881 /// }
2882 /// assert_eq!(vec.last(), Some(&0));
2883 /// ```
2884 #[inline]
2885 #[unstable(feature = "vec_peek_mut", issue = "122742")]
2886 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, A>>
2887 where
2888 A: AllocatorNightly,
2889 {
2890 PeekMut::new(self)
2891 }
2892
2893 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2894 ///
2895 /// # Panics
2896 ///
2897 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
2898 ///
2899 /// # Examples
2900 ///
2901 /// ```
2902 /// let mut vec = vec![1, 2, 3];
2903 /// let mut vec2 = vec![4, 5, 6];
2904 /// vec.append(&mut vec2);
2905 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
2906 /// assert_eq!(vec2, []);
2907 /// ```
2908 #[cfg(not(no_global_oom_handling))]
2909 #[inline]
2910 #[stable(feature = "append", since = "1.4.0")]
2911 pub fn append(&mut self, other: &mut Self) {
2912 // ignore-tidy-undocumented-unsafe
2913 unsafe {
2914 self.append_elements(other.as_slice() as _);
2915 other.set_len(0);
2916 }
2917 }
2918
2919 /// Appends elements to `self` from other buffer.
2920 #[cfg(not(no_global_oom_handling))]
2921 #[inline]
2922 unsafe fn append_elements(&mut self, other: *const [T]) {
2923 self.reserve(other.len());
2924 // ignore-tidy-undocumented-unsafe
2925 unsafe {
2926 self.append_elements_unreserved(other);
2927 }
2928 }
2929
2930 /// Appends elements to `self` from other buffer, returning [`TryReserveError`] on OOM.
2931 #[inline]
2932 unsafe fn try_append_elements(&mut self, other: *const [T]) -> Result<(), TryReserveError> {
2933 self.try_reserve(other.len())?;
2934 // ignore-tidy-undocumented-unsafe
2935 unsafe {
2936 self.append_elements_unreserved(other);
2937 }
2938 Ok(())
2939 }
2940
2941 /// Appends elements to `self` from other buffer without reserving additional capacity.
2942 #[inline]
2943 unsafe fn append_elements_unreserved(&mut self, other: *const [T]) {
2944 let count = other.len();
2945 let len = self.len();
2946 if count > 0 {
2947 // ignore-tidy-undocumented-unsafe
2948 unsafe {
2949 ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count)
2950 };
2951 }
2952 self.len += count;
2953 }
2954
2955 /// Removes the subslice indicated by the given range from the vector,
2956 /// returning a double-ended iterator over the removed subslice.
2957 ///
2958 /// If the iterator is dropped before being fully consumed,
2959 /// it drops the remaining removed elements.
2960 ///
2961 /// The returned iterator keeps a mutable borrow on the vector to optimize
2962 /// its implementation.
2963 ///
2964 /// # Panics
2965 ///
2966 /// Panics if the range has `start_bound > end_bound`, or, if the range is
2967 /// bounded on either end and past the length of the vector.
2968 ///
2969 /// # Leaking
2970 ///
2971 /// If the returned iterator goes out of scope without being dropped (due to
2972 /// [`mem::forget`], for example), the vector may have lost and leaked
2973 /// elements arbitrarily, including elements outside the range.
2974 ///
2975 /// # Examples
2976 ///
2977 /// ```
2978 /// let mut v = vec![1, 2, 3];
2979 /// let u: Vec<_> = v.drain(1..).collect();
2980 /// assert_eq!(v, &[1]);
2981 /// assert_eq!(u, &[2, 3]);
2982 ///
2983 /// // A full range clears the vector, like `clear()` does
2984 /// v.drain(..);
2985 /// assert_eq!(v, &[]);
2986 /// ```
2987 #[stable(feature = "drain", since = "1.6.0")]
2988 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
2989 where
2990 A: AllocatorNightly,
2991 R: RangeBounds<usize>,
2992 {
2993 // Memory safety
2994 //
2995 // When the Drain is first created, it shortens the length of
2996 // the source vector to make sure no uninitialized or moved-from elements
2997 // are accessible at all if the Drain's destructor never gets to run.
2998 //
2999 // Drain will ptr::read out the values to remove.
3000 // When finished, remaining tail of the vec is copied back to cover
3001 // the hole, and the vector length is restored to the new length.
3002 //
3003 let len = self.len();
3004 let Range { start, end } = slice::range(range, ..len);
3005
3006 // ignore-tidy-undocumented-unsafe
3007 unsafe {
3008 // set self.vec length's to start, to be safe in case Drain is leaked
3009 self.set_len(start);
3010 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
3011 Drain {
3012 tail_start: end,
3013 tail_len: len - end,
3014 iter: range_slice.iter(),
3015 vec: NonNull::from(self),
3016 }
3017 }
3018 }
3019
3020 /// Clears the vector, removing all values.
3021 ///
3022 /// Note that this method has no effect on the allocated capacity
3023 /// of the vector.
3024 ///
3025 /// # Examples
3026 ///
3027 /// ```
3028 /// let mut v = vec![1, 2, 3];
3029 ///
3030 /// v.clear();
3031 ///
3032 /// assert!(v.is_empty());
3033 /// ```
3034 #[inline]
3035 #[stable(feature = "rust1", since = "1.0.0")]
3036 pub fn clear(&mut self) {
3037 // Though this is equivalent to `truncate(0)`, the manual version
3038 // optimizes better, justifying the additional complexity
3039 // (see #96002 and #154095 for context).
3040
3041 let elems: *mut [T] = self.as_mut_slice();
3042
3043 // SAFETY:
3044 // - `elems` comes directly from `as_mut_slice` and is therefore valid.
3045 // - Setting `self.len` before calling `drop_in_place` means that,
3046 // if an element's `Drop` impl panics, the vector's `Drop` impl will
3047 // do nothing (leaking the rest of the elements) instead of dropping
3048 // some twice.
3049 unsafe {
3050 self.len = 0;
3051 ptr::drop_in_place(elems);
3052 }
3053 }
3054
3055 /// Returns the number of elements in the vector, also referred to
3056 /// as its 'length'.
3057 ///
3058 /// # Examples
3059 ///
3060 /// ```
3061 /// let a = vec![1, 2, 3];
3062 /// assert_eq!(a.len(), 3);
3063 /// ```
3064 #[inline]
3065 #[stable(feature = "rust1", since = "1.0.0")]
3066 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
3067 #[rustc_confusables("length", "size")]
3068 pub const fn len(&self) -> usize {
3069 let len = self.len;
3070
3071 // SAFETY: The maximum capacity of `Vec<T>` is `isize::MAX` bytes, so the maximum value can
3072 // be returned is `usize::checked_div(size_of::<T>()).unwrap_or(usize::MAX)`, which
3073 // matches the definition of `T::MAX_SLICE_LEN`.
3074 unsafe { intrinsics::assume(len <= T::MAX_SLICE_LEN) };
3075
3076 len
3077 }
3078
3079 /// Returns `true` if the vector contains no elements.
3080 ///
3081 /// # Examples
3082 ///
3083 /// ```
3084 /// let mut v = Vec::new();
3085 /// assert!(v.is_empty());
3086 ///
3087 /// v.push(1);
3088 /// assert!(!v.is_empty());
3089 /// ```
3090 #[stable(feature = "rust1", since = "1.0.0")]
3091 #[rustc_diagnostic_item = "vec_is_empty"]
3092 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
3093 pub const fn is_empty(&self) -> bool {
3094 self.len() == 0
3095 }
3096
3097 /// Splits the collection into two at the given index.
3098 ///
3099 /// Returns a newly allocated vector containing the elements in the range
3100 /// `[at, len)`. After the call, the original vector will be left containing
3101 /// the elements `[0, at)` with its previous capacity unchanged.
3102 ///
3103 /// - If you want to take ownership of the entire contents and capacity of
3104 /// the vector, see [`mem::take`] or [`mem::replace`].
3105 /// - If you don't need the returned vector at all, see [`Vec::truncate`].
3106 /// - If you want to take ownership of an arbitrary subslice, or you don't
3107 /// necessarily want to store the removed items in a vector, see [`Vec::drain`].
3108 ///
3109 /// # Panics
3110 ///
3111 /// Panics if `at > len`.
3112 ///
3113 /// # Examples
3114 ///
3115 /// ```
3116 /// let mut vec = vec!['a', 'b', 'c'];
3117 /// let vec2 = vec.split_off(1);
3118 /// assert_eq!(vec, ['a']);
3119 /// assert_eq!(vec2, ['b', 'c']);
3120 /// ```
3121 #[cfg(not(no_global_oom_handling))]
3122 #[inline]
3123 #[must_use = "use `.truncate()` if you don't need the other half"]
3124 #[stable(feature = "split_off", since = "1.4.0")]
3125 #[track_caller]
3126 pub fn split_off(&mut self, at: usize) -> Self
3127 where
3128 A: Clone,
3129 {
3130 #[cold]
3131 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
3132 #[track_caller]
3133 #[optimize(size)]
3134 fn assert_failed(at: usize, len: usize) -> ! {
3135 panic!("`at` split index (is {at}) should be <= len (is {len})");
3136 }
3137
3138 if at > self.len() {
3139 assert_failed(at, self.len());
3140 }
3141
3142 let other_len = self.len - at;
3143 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
3144
3145 // Unsafely `set_len` and copy items to `other`.
3146 // ignore-tidy-undocumented-unsafe
3147 unsafe {
3148 self.set_len(at);
3149 other.set_len(other_len);
3150
3151 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
3152 }
3153 other
3154 }
3155
3156 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
3157 ///
3158 /// If `new_len` is greater than `len`, the `Vec` is extended by the
3159 /// difference, with each additional slot filled with the result of
3160 /// calling the closure `f`. The return values from `f` will end up
3161 /// in the `Vec` in the order they have been generated.
3162 ///
3163 /// If `new_len` is less than or equal to `len`, the `Vec` is simply
3164 /// truncated.
3165 ///
3166 /// This method uses a closure to create new values on every push. If
3167 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
3168 /// want to use the [`Default`] trait to generate values, you can
3169 /// pass [`Default::default`] as the second argument.
3170 ///
3171 /// # Panics
3172 ///
3173 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3174 ///
3175 /// # Examples
3176 ///
3177 /// ```
3178 /// let mut vec = vec![1, 2, 3];
3179 /// vec.resize_with(5, Default::default);
3180 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
3181 ///
3182 /// let mut vec = vec![];
3183 /// let mut p = 1;
3184 /// vec.resize_with(4, || { p *= 2; p });
3185 /// assert_eq!(vec, [2, 4, 8, 16]);
3186 /// ```
3187 #[cfg(not(no_global_oom_handling))]
3188 #[stable(feature = "vec_resize_with", since = "1.33.0")]
3189 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
3190 where
3191 F: FnMut() -> T,
3192 {
3193 let len = self.len();
3194 if new_len > len {
3195 self.extend_trusted(iter::repeat_with(f).take(new_len - len));
3196 } else {
3197 self.truncate(new_len);
3198 }
3199 }
3200
3201 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
3202 /// `&'a mut [T]`.
3203 ///
3204 /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
3205 /// has only static references, or none at all, then this may be chosen to be
3206 /// `'static`.
3207 ///
3208 /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
3209 /// so the leaked allocation may include unused capacity that is not part
3210 /// of the returned slice.
3211 ///
3212 /// This function is mainly useful for data that lives for the remainder of
3213 /// the program's life. Dropping the returned reference will cause a memory
3214 /// leak.
3215 ///
3216 /// # Examples
3217 ///
3218 /// Simple usage:
3219 ///
3220 /// ```
3221 /// let x = vec![1, 2, 3];
3222 /// let static_ref: &'static mut [usize] = x.leak();
3223 /// static_ref[0] += 1;
3224 /// assert_eq!(static_ref, &[2, 2, 3]);
3225 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
3226 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
3227 /// # drop(unsafe { Box::from_raw(static_ref) });
3228 /// ```
3229 #[stable(feature = "vec_leak", since = "1.47.0")]
3230 #[inline]
3231 pub fn leak<'a>(self) -> &'a mut [T]
3232 where
3233 A: 'a,
3234 {
3235 let mut me = ManuallyDrop::new(self);
3236 // ignore-tidy-undocumented-unsafe
3237 unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
3238 }
3239
3240 /// Returns the remaining spare capacity of the vector as a slice of
3241 /// `MaybeUninit<T>`.
3242 ///
3243 /// The returned slice can be used to fill the vector with data (e.g. by
3244 /// reading from a file) before marking the data as initialized using the
3245 /// [`set_len`] method.
3246 ///
3247 /// [`set_len`]: Vec::set_len
3248 ///
3249 /// # Examples
3250 ///
3251 /// ```
3252 /// // Allocate vector big enough for 10 elements.
3253 /// let mut v = Vec::with_capacity(10);
3254 ///
3255 /// // Fill in the first 3 elements.
3256 /// let uninit = v.spare_capacity_mut();
3257 /// uninit[0].write(0);
3258 /// uninit[1].write(1);
3259 /// uninit[2].write(2);
3260 ///
3261 /// // Mark the first 3 elements of the vector as being initialized.
3262 /// unsafe {
3263 /// v.set_len(3);
3264 /// }
3265 ///
3266 /// assert_eq!(&v, &[0, 1, 2]);
3267 /// ```
3268 #[stable(feature = "vec_spare_capacity", since = "1.60.0")]
3269 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
3270 #[inline]
3271 pub const fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
3272 // Note:
3273 // This method is not implemented in terms of `split_at_spare_mut`,
3274 // to prevent invalidation of pointers to the buffer.
3275 // ignore-tidy-undocumented-unsafe
3276 unsafe {
3277 slice::from_raw_parts_mut(
3278 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
3279 self.buf.capacity() - self.len,
3280 )
3281 }
3282 }
3283
3284 /// Returns vector content as a slice of `T`, along with the remaining spare
3285 /// capacity of the vector as a slice of `MaybeUninit<T>`.
3286 ///
3287 /// The returned spare capacity slice can be used to fill the vector with data
3288 /// (e.g. by reading from a file) before marking the data as initialized using
3289 /// the [`set_len`] method.
3290 ///
3291 /// [`set_len`]: Vec::set_len
3292 ///
3293 /// Note that this is a low-level API, which should be used with care for
3294 /// optimization purposes. If you need to append data to a `Vec`
3295 /// you can use [`push`], [`extend`], [`extend_from_slice`],
3296 /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
3297 /// [`resize_with`], depending on your exact needs.
3298 ///
3299 /// [`push`]: Vec::push
3300 /// [`extend`]: Vec::extend
3301 /// [`extend_from_slice`]: Vec::extend_from_slice
3302 /// [`extend_from_within`]: Vec::extend_from_within
3303 /// [`insert`]: Vec::insert
3304 /// [`append`]: Vec::append
3305 /// [`resize`]: Vec::resize
3306 /// [`resize_with`]: Vec::resize_with
3307 ///
3308 /// # Examples
3309 ///
3310 /// ```
3311 /// #![feature(vec_split_at_spare)]
3312 ///
3313 /// let mut v = vec![1, 1, 2];
3314 ///
3315 /// // Reserve additional space big enough for 10 elements.
3316 /// v.reserve(10);
3317 ///
3318 /// let (init, uninit) = v.split_at_spare_mut();
3319 /// let sum = init.iter().copied().sum::<u32>();
3320 ///
3321 /// // Fill in the next 4 elements.
3322 /// uninit[0].write(sum);
3323 /// uninit[1].write(sum * 2);
3324 /// uninit[2].write(sum * 3);
3325 /// uninit[3].write(sum * 4);
3326 ///
3327 /// // Mark the 4 elements of the vector as being initialized.
3328 /// unsafe {
3329 /// let len = v.len();
3330 /// v.set_len(len + 4);
3331 /// }
3332 ///
3333 /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
3334 /// ```
3335 #[unstable(feature = "vec_split_at_spare", issue = "81944")]
3336 #[rustc_const_unstable(feature = "const_heap", issue = "79597")]
3337 #[inline]
3338 pub const fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
3339 // SAFETY:
3340 // - len is ignored and so never changed
3341 let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
3342 (init, spare)
3343 }
3344
3345 /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
3346 ///
3347 /// This method provides unique access to all vec parts at once in `extend_from_within`.
3348 const unsafe fn split_at_spare_mut_with_len(
3349 &mut self,
3350 ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
3351 let ptr = self.as_mut_ptr();
3352 // SAFETY:
3353 // - `ptr` is guaranteed to be valid for `self.len` elements
3354 // - but the allocation extends out to `self.buf.capacity()` elements, possibly
3355 // uninitialized
3356 let spare_ptr = unsafe { ptr.add(self.len) };
3357 let spare_ptr = spare_ptr.cast_uninit();
3358 let spare_len = self.buf.capacity() - self.len;
3359
3360 // SAFETY:
3361 // - `ptr` is guaranteed to be valid for `self.len` elements
3362 // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
3363 unsafe {
3364 let initialized = slice::from_raw_parts_mut(ptr, self.len);
3365 let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
3366
3367 (initialized, spare, &mut self.len)
3368 }
3369 }
3370
3371 /// Groups every `N` elements in the `Vec<T>` into chunks to produce a `Vec<[T; N]>`, dropping
3372 /// elements in the remainder. `N` must be greater than zero.
3373 ///
3374 /// If the capacity is not a multiple of the chunk size, the buffer will shrink down to the
3375 /// nearest multiple with a reallocation or deallocation.
3376 ///
3377 /// This function can be used to reverse [`Vec::into_flattened`].
3378 ///
3379 /// # Examples
3380 ///
3381 /// ```
3382 /// #![feature(vec_into_chunks)]
3383 ///
3384 /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7];
3385 /// assert_eq!(vec.into_chunks::<3>(), [[0, 1, 2], [3, 4, 5]]);
3386 ///
3387 /// let vec = vec![0, 1, 2, 3];
3388 /// let chunks: Vec<[u8; 10]> = vec.into_chunks();
3389 /// assert!(chunks.is_empty());
3390 ///
3391 /// let flat = vec![0; 8 * 8 * 8];
3392 /// let reshaped: Vec<[[[u8; 8]; 8]; 8]> = flat.into_chunks().into_chunks().into_chunks();
3393 /// assert_eq!(reshaped.len(), 1);
3394 /// ```
3395 #[cfg(not(no_global_oom_handling))]
3396 #[unstable(feature = "vec_into_chunks", issue = "142137")]
3397 pub fn into_chunks<const N: usize>(mut self) -> Vec<[T; N], A> {
3398 const {
3399 assert!(N != 0, "chunk size must be greater than zero");
3400 }
3401
3402 let (len, cap) = (self.len(), self.capacity());
3403
3404 let len_remainder = len % N;
3405 if len_remainder != 0 {
3406 self.truncate(len - len_remainder);
3407 }
3408
3409 let cap_remainder = cap % N;
3410 if !T::IS_ZST && cap_remainder != 0 {
3411 self.buf.shrink_to_fit(cap - cap_remainder);
3412 }
3413
3414 let (ptr, _, _, alloc) = self.into_raw_parts_with_allocator();
3415
3416 // SAFETY:
3417 // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_allocator()`
3418 // - `[T; N]` has the same alignment as `T`
3419 // - `size_of::<[T; N]>() * cap / N == size_of::<T>() * cap`
3420 // - `len / N <= cap / N` because `len <= cap`
3421 // - the allocated memory consists of `len / N` valid values of type `[T; N]`
3422 // - `cap / N` fits the size of the allocated memory after shrinking
3423 unsafe { Vec::from_raw_parts_in(ptr.cast(), len / N, cap / N, alloc) }
3424 }
3425
3426 /// This clears out this `Vec` and recycles the allocation into a new `Vec`.
3427 /// The item type of the resulting `Vec` needs to have the same size and
3428 /// alignment as the item type of the original `Vec`.
3429 ///
3430 /// # Examples
3431 ///
3432 /// ```
3433 /// #![feature(vec_recycle, transmutability)]
3434 /// let a: Vec<u8> = vec![0; 100];
3435 /// let capacity = a.capacity();
3436 /// let addr = a.as_ptr().addr();
3437 /// let b: Vec<i8> = a.recycle();
3438 /// assert_eq!(b.len(), 0);
3439 /// assert_eq!(b.capacity(), capacity);
3440 /// assert_eq!(b.as_ptr().addr(), addr);
3441 /// ```
3442 ///
3443 /// The `Recyclable` bound prevents this method from being called when `T` and `U` have different sizes; e.g.:
3444 ///
3445 /// ```compile_fail,E0277
3446 /// #![feature(vec_recycle, transmutability)]
3447 /// let vec: Vec<[u8; 2]> = Vec::new();
3448 /// let _: Vec<[u8; 1]> = vec.recycle();
3449 /// ```
3450 /// ...or different alignments:
3451 ///
3452 /// ```compile_fail,E0277
3453 /// #![feature(vec_recycle, transmutability)]
3454 /// let vec: Vec<[u16; 0]> = Vec::new();
3455 /// let _: Vec<[u8; 0]> = vec.recycle();
3456 /// ```
3457 ///
3458 /// However, due to temporary implementation limitations of `Recyclable`,
3459 /// this method is not yet callable when `T` or `U` are slices, trait objects,
3460 /// or other exotic types; e.g.:
3461 ///
3462 /// ```compile_fail,E0277
3463 /// #![feature(vec_recycle, transmutability)]
3464 /// # let inputs = ["a b c", "d e f"];
3465 /// # fn process(_: &[&str]) {}
3466 /// let mut storage: Vec<&[&str]> = Vec::new();
3467 ///
3468 /// for input in inputs {
3469 /// let mut buffer: Vec<&str> = storage.recycle();
3470 /// buffer.extend(input.split(" "));
3471 /// process(&buffer);
3472 /// storage = buffer.recycle();
3473 /// }
3474 /// ```
3475 #[unstable(feature = "vec_recycle", issue = "148227")]
3476 #[expect(private_bounds)]
3477 pub fn recycle<U>(mut self) -> Vec<U, A>
3478 where
3479 U: Recyclable<T>,
3480 {
3481 self.clear();
3482 const {
3483 // FIXME(const-hack, 146097): compare `Layout`s
3484 assert!(size_of::<T>() == size_of::<U>());
3485 assert!(align_of::<T>() == align_of::<U>());
3486 };
3487 let (ptr, length, capacity, alloc) = self.into_parts_with_allocator();
3488 debug_assert_eq!(length, 0);
3489 // SAFETY:
3490 // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_allocator()`
3491 // - `T` & `U` have the same layout, so `capacity` does not need to be changed and we can safely use `alloc.dealloc` later
3492 // - the original vector was cleared, so there is no problem with "transmuting" the stored values
3493 unsafe { Vec::from_parts_in(ptr.cast::<U>(), length, capacity, alloc) }
3494 }
3495}
3496
3497/// Denotes that an allocation of `From` can be recycled into an allocation of `Self`.
3498///
3499/// # Safety
3500///
3501/// `Self` is `Recyclable<From>` if `Layout::new::<Self>() == Layout::new::<From>()`.
3502unsafe trait Recyclable<From: Sized>: Sized {}
3503
3504#[unstable_feature_bound(transmutability)]
3505// SAFETY: enforced by `TransmuteFrom`
3506unsafe impl<From, To> Recyclable<From> for To
3507where
3508 for<'a> &'a MaybeUninit<To>: TransmuteFrom<&'a MaybeUninit<From>, { Assume::SAFETY }>,
3509 for<'a> &'a MaybeUninit<From>: TransmuteFrom<&'a MaybeUninit<To>, { Assume::SAFETY }>,
3510{
3511}
3512
3513impl<T: Clone, A: Allocator> Vec<T, A> {
3514 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
3515 ///
3516 /// If `new_len` is greater than `len`, the `Vec` is extended by the
3517 /// difference, with each additional slot filled with `value`.
3518 /// If `new_len` is less than or equal to `len`, the `Vec` is simply
3519 /// truncated.
3520 ///
3521 /// This method requires `T` to implement [`Clone`],
3522 /// in order to be able to clone the passed value.
3523 /// If you need more flexibility (or want to rely on [`Default`] instead of
3524 /// [`Clone`]), use [`Vec::resize_with`].
3525 /// If you only need to resize to a smaller size, use [`Vec::truncate`].
3526 ///
3527 /// # Panics
3528 ///
3529 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3530 ///
3531 /// # Examples
3532 ///
3533 /// ```
3534 /// let mut vec = vec!["hello"];
3535 /// vec.resize(3, "world");
3536 /// assert_eq!(vec, ["hello", "world", "world"]);
3537 ///
3538 /// let mut vec = vec!['a', 'b', 'c', 'd'];
3539 /// vec.resize(2, '_');
3540 /// assert_eq!(vec, ['a', 'b']);
3541 /// ```
3542 #[cfg(not(no_global_oom_handling))]
3543 #[stable(feature = "vec_resize", since = "1.5.0")]
3544 pub fn resize(&mut self, new_len: usize, value: T) {
3545 let len = self.len();
3546
3547 if new_len > len {
3548 self.extend_with(new_len - len, value)
3549 } else {
3550 self.truncate(new_len);
3551 }
3552 }
3553
3554 /// Clones and appends all elements in a slice to the `Vec`.
3555 ///
3556 /// Iterates over the slice `other`, clones each element, and then appends
3557 /// it to this `Vec`. The `other` slice is traversed in-order.
3558 ///
3559 /// Note that this function is the same as [`extend`],
3560 /// except that it also works with slice elements that are Clone but not Copy.
3561 /// If Rust gets specialization this function may be deprecated.
3562 ///
3563 /// # Panics
3564 ///
3565 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3566 ///
3567 /// # Examples
3568 ///
3569 /// ```
3570 /// let mut vec = vec![1];
3571 /// vec.extend_from_slice(&[2, 3, 4]);
3572 /// assert_eq!(vec, [1, 2, 3, 4]);
3573 /// ```
3574 ///
3575 /// [`extend`]: Vec::extend
3576 #[cfg(not(no_global_oom_handling))]
3577 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
3578 pub fn extend_from_slice(&mut self, other: &[T]) {
3579 self.spec_extend(other.iter())
3580 }
3581
3582 /// Given a range `src`, clones a slice of elements in that range and appends it to the end.
3583 ///
3584 /// `src` must be a range that can form a valid subslice of the `Vec`.
3585 ///
3586 /// # Panics
3587 ///
3588 /// Panics if starting index is greater than the end index, if the index is
3589 /// greater than the length of the vector, or if the new capacity exceeds
3590 /// `isize::MAX` _bytes_.
3591 ///
3592 /// # Examples
3593 ///
3594 /// ```
3595 /// let mut characters = vec!['a', 'b', 'c', 'd', 'e'];
3596 /// characters.extend_from_within(2..);
3597 /// assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
3598 ///
3599 /// let mut numbers = vec![0, 1, 2, 3, 4];
3600 /// numbers.extend_from_within(..2);
3601 /// assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
3602 ///
3603 /// let mut strings = vec![String::from("hello"), String::from("world"), String::from("!")];
3604 /// strings.extend_from_within(1..=2);
3605 /// assert_eq!(strings, ["hello", "world", "!", "world", "!"]);
3606 /// ```
3607 #[cfg(not(no_global_oom_handling))]
3608 #[stable(feature = "vec_extend_from_within", since = "1.53.0")]
3609 pub fn extend_from_within<R>(&mut self, src: R)
3610 where
3611 R: RangeBounds<usize>,
3612 {
3613 let range = slice::range(src, ..self.len());
3614 self.reserve(range.len());
3615
3616 // SAFETY:
3617 // - `slice::range` guarantees that the given range is valid for indexing self
3618 unsafe {
3619 self.spec_extend_from_within(range);
3620 }
3621 }
3622}
3623
3624impl<A: Allocator> Vec<u8, A> {
3625 #[cfg_attr(
3626 not(no_global_oom_handling),
3627 expect(
3628 dead_code,
3629 reason = "currently only used in IO module when global OOM handling is disabled"
3630 )
3631 )]
3632 pub(crate) fn try_extend_from_slice_of_bytes(
3633 &mut self,
3634 other: &[u8],
3635 ) -> Result<(), TryReserveError> {
3636 // ignore-tidy-undocumented-unsafe
3637 unsafe { self.try_append_elements(other) }
3638 }
3639}
3640
3641impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
3642 /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
3643 ///
3644 /// # Panics
3645 ///
3646 /// Panics if the length of the resulting vector would overflow a `usize`.
3647 ///
3648 /// This is only possible when flattening a vector of arrays of zero-sized
3649 /// types, and thus tends to be irrelevant in practice. If
3650 /// `size_of::<T>() > 0`, this will never panic.
3651 ///
3652 /// # Examples
3653 ///
3654 /// ```
3655 /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
3656 /// assert_eq!(vec.pop(), Some([7, 8, 9]));
3657 ///
3658 /// let mut flattened = vec.into_flattened();
3659 /// assert_eq!(flattened.pop(), Some(6));
3660 /// ```
3661 #[stable(feature = "slice_flatten", since = "1.80.0")]
3662 pub fn into_flattened(self) -> Vec<T, A> {
3663 let (ptr, len, cap, alloc) = self.into_raw_parts_with_allocator();
3664 let (new_len, new_cap) = if T::IS_ZST {
3665 (
3666 len.checked_mul(N).expect("the product of vec len and N shouldn't overflow"),
3667 usize::MAX,
3668 )
3669 } else {
3670 // SAFETY:
3671 // - `cap * N` cannot overflow because the allocation is already in
3672 // the address space.
3673 // - Each `[T; N]` has `N` valid elements, so there are `len * N`
3674 // valid elements in the allocation.
3675 unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) }
3676 };
3677 // SAFETY:
3678 // - `ptr` was allocated by `self`
3679 // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
3680 // - `new_cap` refers to the same sized allocation as `cap` because
3681 // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
3682 // - `len` <= `cap`, so `len * N` <= `cap * N`.
3683 unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
3684 }
3685}
3686
3687impl<T: Clone, A: Allocator> Vec<T, A> {
3688 #[cfg(not(no_global_oom_handling))]
3689 /// Extend the vector by `n` clones of value.
3690 fn extend_with(&mut self, n: usize, value: T) {
3691 self.reserve(n);
3692
3693 // ignore-tidy-undocumented-unsafe
3694 unsafe {
3695 let mut ptr = self.as_mut_ptr().add(self.len());
3696 // Use SetLenOnDrop to work around bug where compiler
3697 // might not realize the store through `ptr` through self.set_len()
3698 // don't alias.
3699 let mut local_len = SetLenOnDrop::new(&mut self.len);
3700
3701 // Write all elements except the last one
3702 for _ in 1..n {
3703 ptr::write(ptr, value.clone());
3704 ptr = ptr.add(1);
3705 // Increment the length in every step in case clone() panics
3706 local_len.increment_len(1);
3707 }
3708
3709 if n > 0 {
3710 // We can write the last element directly without cloning needlessly
3711 ptr::write(ptr, value);
3712 local_len.increment_len(1);
3713 }
3714
3715 // len set by scope guard
3716 }
3717 }
3718}
3719
3720impl<T: PartialEq, A: Allocator> Vec<T, A> {
3721 /// Removes consecutive repeated elements in the vector according to the
3722 /// [`PartialEq`] trait implementation.
3723 ///
3724 /// If the vector is sorted, this removes all duplicates.
3725 ///
3726 /// # Examples
3727 ///
3728 /// ```
3729 /// let mut vec = vec![1, 2, 2, 3, 2];
3730 ///
3731 /// vec.dedup();
3732 ///
3733 /// assert_eq!(vec, [1, 2, 3, 2]);
3734 /// ```
3735 #[stable(feature = "rust1", since = "1.0.0")]
3736 #[inline]
3737 pub fn dedup(&mut self) {
3738 // Vectorize the process of finding first duplicate if possible
3739 if let Some(chunk_size) = dedup_simd_chunk_size::<T>() {
3740 // Unlike dedup_by, we don't guarantee the order
3741 // and time in which we call `PartialEq::eq`.
3742 let Some(first_duplicate) = find_first_duplicate(self.as_slice(), chunk_size) else {
3743 return;
3744 };
3745
3746 // SAFETY: `1 <= first_duplicate < self.len()`
3747 unsafe {
3748 self.dedup_tail(|a, b| a == b, first_duplicate);
3749 }
3750 } else {
3751 self.dedup_by(|a, b| a == b);
3752 }
3753 }
3754}
3755
3756const fn dedup_simd_chunk_size<T>() -> Option<usize> {
3757 // The minimal SIMD width on supported platforms
3758 #[allow(unused)]
3759 const SIMD_WIDTH: usize = 16;
3760 let size = size_of::<T>();
3761
3762 // We only have SIMD implementations for these element sizes.
3763 if !matches!(size, 1 | 2 | 4 | 8) {
3764 return None;
3765 }
3766
3767 let simd_width: Option<usize> = cfg_select! {
3768 all(target_arch = "arm", target_feature = "neon") => {
3769 // Packed 64-bit integer lane equality is unavailable on arm neon
3770 if size == 8 { None } else { Some(SIMD_WIDTH) }
3771 }
3772
3773 all(target_arch = "aarch64", target_feature = "neon") => {
3774 Some(SIMD_WIDTH)
3775 }
3776
3777 all(
3778 any(target_arch = "x86", target_arch = "x86_64"),
3779 target_feature = "sse4.1"
3780 ) => Some(SIMD_WIDTH),
3781
3782 all(
3783 any(target_arch = "x86", target_arch = "x86_64"),
3784 target_feature = "sse2"
3785 ) => {
3786 // Packed 64-bit integer lane equality is only available on sse4.1
3787 if size == 8 { None } else { Some(SIMD_WIDTH) }
3788 }
3789
3790 all(
3791 any(target_arch = "riscv32", target_arch = "riscv64"),
3792 target_feature = "v"
3793 ) => Some(SIMD_WIDTH),
3794
3795 all(
3796 any(target_arch = "loongarch32", target_arch = "loongarch64"),
3797 target_feature = "lsx"
3798 ) => Some(SIMD_WIDTH),
3799
3800 _ => None,
3801 };
3802
3803 if let Some(simd_width) = simd_width { Some(simd_width * 2 / size) } else { None }
3804}
3805
3806fn find_first_duplicate<T: PartialEq>(v: &[T], chunk_size: usize) -> Option<usize> {
3807 let len = v.len();
3808 if len <= 1 {
3809 return None;
3810 }
3811
3812 let mut i = 1;
3813
3814 // The scalar fallback path if the length is not long enough
3815 if len < chunk_size + 1 {
3816 while i < len {
3817 // It keeps the same comparison order as `dedup_tail`
3818 //
3819 // SAFETY: i always in range [1..len)
3820 if unsafe { v.get_unchecked(i) == v.get_unchecked(i - 1) } {
3821 return Some(i);
3822 }
3823 i += 1;
3824 }
3825 return None;
3826 }
3827
3828 /// # Safety
3829 /// - `start > 0` and `start + chunk_size <= v.len()`
3830 /// - `0 < chunk_size <= 32`
3831 #[inline(always)]
3832 unsafe fn find_duplicate<T: PartialEq>(
3833 v: &[T],
3834 start: usize,
3835 chunk_size: usize,
3836 ) -> Option<usize> {
3837 let mut mask: u32 = 0;
3838 debug_assert!(
3839 u32::BITS as usize >= chunk_size,
3840 "the bit width of mask must be greater than or equal to chunk_size"
3841 );
3842 for j in 0..chunk_size {
3843 // SAFETY: start + j always in range [1..v.len())
3844 let eq = unsafe { v.get_unchecked(start + j) == v.get_unchecked(start + j - 1) };
3845 mask |= (eq as u32) << j;
3846 }
3847 if mask != 0 {
3848 return Some(start + mask.trailing_zeros() as usize);
3849 }
3850 None
3851 }
3852
3853 // This loop performs chunk_size comparisons in parallel without early exit,
3854 // which is what allows for SIMD optimization.
3855 while i + chunk_size <= len {
3856 // SAFETY: `i >= 1` and `i + chunk_size <= len`
3857 if let Some(duplicate) = unsafe { find_duplicate(v, i, chunk_size) } {
3858 return Some(duplicate);
3859 }
3860 i += chunk_size;
3861 }
3862
3863 // This may check the same elements multiple times.
3864 // However we don't guarantee `PartialEq::eq` is only called once per pair.
3865 if i < len {
3866 let start = len - chunk_size;
3867 // SAFETY: `len - chunk_size >= 1` and `start + chunk_size <= len`
3868 if let Some(duplicate) = unsafe { find_duplicate(v, start, chunk_size) } {
3869 return Some(duplicate);
3870 }
3871 }
3872
3873 None
3874}
3875
3876////////////////////////////////////////////////////////////////////////////////
3877// Internal methods and functions
3878////////////////////////////////////////////////////////////////////////////////
3879
3880#[doc(hidden)]
3881#[cfg(not(no_global_oom_handling))]
3882#[stable(feature = "rust1", since = "1.0.0")]
3883#[rustc_diagnostic_item = "vec_from_elem"]
3884pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
3885 <T as SpecFromElem>::from_elem(elem, n, Global)
3886}
3887
3888#[doc(hidden)]
3889#[cfg(not(no_global_oom_handling))]
3890#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
3891pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
3892 <T as SpecFromElem>::from_elem(elem, n, alloc)
3893}
3894
3895#[cfg(not(no_global_oom_handling))]
3896trait ExtendFromWithinSpec {
3897 /// # Safety
3898 ///
3899 /// - `src` needs to be valid index
3900 /// - `self.capacity() - self.len()` must be `>= src.len()`
3901 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
3902}
3903
3904#[cfg(not(no_global_oom_handling))]
3905impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3906 default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3907 // SAFETY:
3908 // - len is increased only after initializing elements
3909 let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
3910
3911 // SAFETY:
3912 // - caller guarantees that src is a valid index
3913 let to_clone = unsafe { this.get_unchecked(src) };
3914
3915 iter::zip(to_clone, spare)
3916 .map(|(src, dst)| dst.write(src.clone()))
3917 // Note:
3918 // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
3919 // - len is increased after each element to prevent leaks (see issue #82533)
3920 .for_each(|_| *len += 1);
3921 }
3922}
3923
3924#[cfg(not(no_global_oom_handling))]
3925impl<T: TrivialClone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3926 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3927 let count = src.len();
3928 {
3929 let (init, spare) = self.split_at_spare_mut();
3930
3931 // SAFETY:
3932 // - caller guarantees that `src` is a valid index
3933 let source = unsafe { init.get_unchecked(src) };
3934
3935 // SAFETY:
3936 // - Both pointers are created from unique slice references (`&mut [_]`)
3937 // so they are valid and do not overlap.
3938 // - Elements implement `TrivialClone` so this is equivalent to calling
3939 // `clone` on every one of them.
3940 // - `count` is equal to the len of `source`, so source is valid for
3941 // `count` reads
3942 // - `.reserve(count)` guarantees that `spare.len() >= count` so spare
3943 // is valid for `count` writes
3944 unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
3945 }
3946
3947 // SAFETY:
3948 // - The elements were just initialized by `copy_nonoverlapping`
3949 self.len += count;
3950 }
3951}
3952
3953////////////////////////////////////////////////////////////////////////////////
3954// Common trait implementations for Vec
3955////////////////////////////////////////////////////////////////////////////////
3956
3957#[stable(feature = "rust1", since = "1.0.0")]
3958#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3959const impl<T, A: Allocator> ops::Deref for Vec<T, A> {
3960 type Target = [T];
3961
3962 #[inline]
3963 fn deref(&self) -> &[T] {
3964 self.as_slice()
3965 }
3966}
3967
3968#[stable(feature = "rust1", since = "1.0.0")]
3969#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
3970const impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
3971 #[inline]
3972 fn deref_mut(&mut self) -> &mut [T] {
3973 self.as_mut_slice()
3974 }
3975}
3976
3977#[unstable(feature = "deref_pure_trait", issue = "87121")]
3978unsafe impl<T, A: Allocator> ops::DerefPure for Vec<T, A> {}
3979
3980#[cfg(not(no_global_oom_handling))]
3981#[stable(feature = "rust1", since = "1.0.0")]
3982impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
3983 /// Creates a new `Vec` by deep-copying the contents of an existing `Vec`.
3984 ///
3985 /// This method will allocate a new `Vec` and `clone` all of `self`'s contents
3986 /// into it. The capacity of the duplicate `Vec` is not forced to match the
3987 /// capacity of the original.
3988 fn clone(&self) -> Self {
3989 let alloc = self.allocator().clone();
3990 <[T]>::to_vec_in(self, alloc)
3991 }
3992
3993 /// Overwrites the contents of `self` with a clone of the contents of `source`.
3994 ///
3995 /// This method is preferred over simply assigning `source.clone()` to `self`,
3996 /// as it avoids reallocation if possible. Additionally, if the element type
3997 /// `T` overrides `clone_from()`, this will reuse the resources of `self`'s
3998 /// elements as well.
3999 ///
4000 /// # Examples
4001 ///
4002 /// ```
4003 /// let x = vec![5, 6, 7];
4004 /// let mut y = vec![8, 9, 10];
4005 /// let yp: *const i32 = y.as_ptr();
4006 ///
4007 /// y.clone_from(&x);
4008 ///
4009 /// // The value is the same
4010 /// assert_eq!(x, y);
4011 ///
4012 /// // And no reallocation occurred
4013 /// assert_eq!(yp, y.as_ptr());
4014 /// ```
4015 fn clone_from(&mut self, source: &Self) {
4016 crate::slice::SpecCloneIntoVec::clone_into(source.as_slice(), self);
4017 }
4018}
4019
4020/// The hash of a vector is the same as that of the corresponding slice,
4021/// as required by the `core::borrow::Borrow` implementation.
4022///
4023/// ```
4024/// use std::hash::BuildHasher;
4025///
4026/// let b = std::hash::RandomState::new();
4027/// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
4028/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
4029/// assert_eq!(b.hash_one(v), b.hash_one(s));
4030/// ```
4031#[stable(feature = "rust1", since = "1.0.0")]
4032impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
4033 #[inline]
4034 fn hash<H: Hasher>(&self, state: &mut H) {
4035 Hash::hash(&**self, state)
4036 }
4037}
4038
4039#[stable(feature = "rust1", since = "1.0.0")]
4040#[rustc_const_unstable(feature = "const_index", issue = "143775")]
4041const impl<T, I: [const] SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
4042 type Output = I::Output;
4043
4044 #[inline]
4045 fn index(&self, index: I) -> &Self::Output {
4046 Index::index(&**self, index)
4047 }
4048}
4049
4050#[stable(feature = "rust1", since = "1.0.0")]
4051#[rustc_const_unstable(feature = "const_index", issue = "143775")]
4052const impl<T, I: [const] SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
4053 #[inline]
4054 fn index_mut(&mut self, index: I) -> &mut Self::Output {
4055 IndexMut::index_mut(&mut **self, index)
4056 }
4057}
4058
4059/// Collects an iterator into a Vec, commonly called via [`Iterator::collect()`]
4060///
4061/// # Allocation behavior
4062///
4063/// In general `Vec` does not guarantee any particular growth or allocation strategy.
4064/// That also applies to this trait impl.
4065///
4066/// **Note:** This section covers implementation details and is therefore exempt from
4067/// stability guarantees.
4068///
4069/// Vec may use any or none of the following strategies,
4070/// depending on the supplied iterator:
4071///
4072/// * preallocate based on [`Iterator::size_hint()`]
4073/// * and panic if the number of items is outside the provided lower/upper bounds
4074/// * use an amortized growth strategy similar to `pushing` one item at a time
4075/// * perform the iteration in-place on the original allocation backing the iterator
4076///
4077/// The last case warrants some attention. It is an optimization that in many cases reduces peak memory
4078/// consumption and improves cache locality. But when big, short-lived allocations are created,
4079/// only a small fraction of their items get collected, no further use is made of the spare capacity
4080/// and the resulting `Vec` is moved into a longer-lived structure, then this can lead to the large
4081/// allocations having their lifetimes unnecessarily extended which can result in increased memory
4082/// footprint.
4083///
4084/// In cases where this is an issue, the excess capacity can be discarded with [`Vec::shrink_to()`],
4085/// [`Vec::shrink_to_fit()`] or by collecting into [`Box<[T]>`][owned slice] instead, which additionally reduces
4086/// the size of the long-lived struct.
4087///
4088/// [owned slice]: Box
4089///
4090/// ```rust
4091/// # use std::sync::Mutex;
4092/// static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());
4093///
4094/// for i in 0..10 {
4095/// let big_temporary: Vec<u16> = (0..1024).collect();
4096/// // discard most items
4097/// let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect();
4098/// // without this a lot of unused capacity might be moved into the global
4099/// result.shrink_to_fit();
4100/// LONG_LIVED.lock().unwrap().push(result);
4101/// }
4102/// ```
4103#[cfg(not(no_global_oom_handling))]
4104#[stable(feature = "rust1", since = "1.0.0")]
4105impl<T> FromIterator<T> for Vec<T> {
4106 #[inline]
4107 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
4108 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
4109 }
4110}
4111
4112#[stable(feature = "rust1", since = "1.0.0")]
4113impl<T, A: Allocator> IntoIterator for Vec<T, A> {
4114 type Item = T;
4115 type IntoIter = IntoIter<T, A>;
4116
4117 /// Creates a consuming iterator, that is, one that moves each value out of
4118 /// the vector (from start to end). The vector cannot be used after calling
4119 /// this.
4120 ///
4121 /// # Examples
4122 ///
4123 /// ```
4124 /// let v = vec!["a".to_string(), "b".to_string()];
4125 /// let mut v_iter = v.into_iter();
4126 ///
4127 /// let first_element: Option<String> = v_iter.next();
4128 ///
4129 /// assert_eq!(first_element, Some("a".to_string()));
4130 /// assert_eq!(v_iter.next(), Some("b".to_string()));
4131 /// assert_eq!(v_iter.next(), None);
4132 /// ```
4133 #[inline]
4134 fn into_iter(self) -> Self::IntoIter {
4135 let me = ManuallyDrop::new(self);
4136 // ignore-tidy-undocumented-unsafe
4137 unsafe {
4138 let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
4139 let buf = me.buf.non_null();
4140 let begin = buf.as_ptr();
4141 let end = if T::IS_ZST {
4142 begin.wrapping_byte_add(me.len())
4143 } else {
4144 begin.add(me.len()) as *const T
4145 };
4146 let cap = me.buf.capacity();
4147 IntoIter { buf, phantom: PhantomData, cap, alloc, ptr: buf, end }
4148 }
4149 }
4150}
4151
4152#[stable(feature = "rust1", since = "1.0.0")]
4153impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
4154 type Item = &'a T;
4155 type IntoIter = slice::Iter<'a, T>;
4156
4157 fn into_iter(self) -> Self::IntoIter {
4158 self.iter()
4159 }
4160}
4161
4162#[stable(feature = "rust1", since = "1.0.0")]
4163impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
4164 type Item = &'a mut T;
4165 type IntoIter = slice::IterMut<'a, T>;
4166
4167 fn into_iter(self) -> Self::IntoIter {
4168 self.iter_mut()
4169 }
4170}
4171
4172#[cfg(not(no_global_oom_handling))]
4173#[stable(feature = "rust1", since = "1.0.0")]
4174impl<T, A: Allocator> Extend<T> for Vec<T, A> {
4175 #[inline]
4176 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
4177 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
4178 }
4179
4180 #[inline]
4181 fn extend_one(&mut self, item: T) {
4182 self.push(item);
4183 }
4184
4185 #[inline]
4186 fn extend_reserve(&mut self, additional: usize) {
4187 self.reserve(additional);
4188 }
4189
4190 #[inline]
4191 unsafe fn extend_one_unchecked(&mut self, item: T) {
4192 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
4193 unsafe {
4194 let len = self.len();
4195 ptr::write(self.as_mut_ptr().add(len), item);
4196 self.set_len(len + 1);
4197 }
4198 }
4199}
4200
4201impl<T, A: Allocator> Vec<T, A> {
4202 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
4203 // they have no further optimizations to apply
4204 #[cfg(not(no_global_oom_handling))]
4205 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
4206 // This is the case for a general iterator.
4207 //
4208 // This function should be the moral equivalent of:
4209 //
4210 // for item in iterator {
4211 // self.push(item);
4212 // }
4213 while let Some(element) = iterator.next() {
4214 let len = self.len();
4215 if len == self.capacity() {
4216 let (lower, _) = iterator.size_hint();
4217 self.reserve(lower.saturating_add(1));
4218 }
4219 // ignore-tidy-undocumented-unsafe
4220 unsafe {
4221 ptr::write(self.as_mut_ptr().add(len), element);
4222 // Since next() executes user code which can panic we have to bump the length
4223 // after each step.
4224 // NB can't overflow since we would have had to alloc the address space
4225 self.set_len(len + 1);
4226 }
4227 }
4228 }
4229
4230 // specific extend for `TrustedLen` iterators, called both by the specializations
4231 // and internal places where resolving specialization makes compilation slower
4232 #[cfg(not(no_global_oom_handling))]
4233 fn extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) {
4234 let (low, high) = iterator.size_hint();
4235 if let Some(additional) = high {
4236 debug_assert_eq!(
4237 low,
4238 additional,
4239 "TrustedLen iterator's size hint is not exact: {:?}",
4240 (low, high)
4241 );
4242 self.reserve(additional);
4243 let ptr = self.as_mut_ptr();
4244 let mut local_len = SetLenOnDrop::new(&mut self.len);
4245 // ignore-tidy-undocumented-unsafe
4246 unsafe {
4247 iterator.for_each(move |element| {
4248 ptr::write(ptr.add(local_len.current_len()), element);
4249 // Since the loop executes user code which can panic we have to update
4250 // the length every step to correctly drop what we've written.
4251 // NB can't overflow since we would have had to alloc the address space
4252 local_len.increment_len(1);
4253 });
4254 }
4255 } else {
4256 // Per TrustedLen contract a `None` upper bound means that the iterator length
4257 // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
4258 // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
4259 // This avoids additional codegen for a fallback code path which would eventually
4260 // panic anyway.
4261 panic!("capacity overflow");
4262 }
4263 }
4264
4265 /// Creates a splicing iterator that replaces the specified range in the vector
4266 /// with the given `replace_with` iterator and yields the removed items.
4267 /// `replace_with` does not need to be the same length as `range`.
4268 ///
4269 /// `range` is removed even if the `Splice` iterator is not consumed before it is dropped.
4270 ///
4271 /// It is unspecified how many elements are removed from the vector
4272 /// if the `Splice` value is leaked.
4273 ///
4274 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
4275 ///
4276 /// This is optimal if:
4277 ///
4278 /// * The tail (elements in the vector after `range`) is empty,
4279 /// * or `replace_with` yields fewer or equal elements than `range`'s length
4280 /// * or the lower bound of its `size_hint()` is exact.
4281 ///
4282 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
4283 ///
4284 /// # Panics
4285 ///
4286 /// Panics if the range has `start_bound > end_bound`, or, if the range is
4287 /// bounded on either end and past the length of the vector.
4288 ///
4289 /// # Examples
4290 ///
4291 /// ```
4292 /// let mut v = vec![1, 2, 3, 4];
4293 /// let new = [7, 8, 9];
4294 /// let u: Vec<_> = v.splice(1..3, new).collect();
4295 /// assert_eq!(v, [1, 7, 8, 9, 4]);
4296 /// assert_eq!(u, [2, 3]);
4297 /// ```
4298 ///
4299 /// Using `splice` to insert new items into a vector efficiently at a specific position
4300 /// indicated by an empty range:
4301 ///
4302 /// ```
4303 /// let mut v = vec![1, 5];
4304 /// let new = [2, 3, 4];
4305 /// v.splice(1..1, new);
4306 /// assert_eq!(v, [1, 2, 3, 4, 5]);
4307 /// ```
4308 #[cfg(not(no_global_oom_handling))]
4309 #[inline]
4310 #[stable(feature = "vec_splice", since = "1.21.0")]
4311 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
4312 where
4313 A: AllocatorNightly,
4314 R: RangeBounds<usize>,
4315 I: IntoIterator<Item = T>,
4316 {
4317 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
4318 }
4319
4320 /// Creates an iterator which uses a closure to determine if an element in the range should be removed.
4321 ///
4322 /// If the closure returns `true`, the element is removed from the vector
4323 /// and yielded. If the closure returns `false`, or panics, the element
4324 /// remains in the vector and will not be yielded.
4325 ///
4326 /// Only elements that fall in the provided range are considered for extraction, but any elements
4327 /// after the range will still have to be moved if any element has been extracted.
4328 ///
4329 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
4330 /// or the iteration short-circuits, then the remaining elements will be retained.
4331 /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
4332 /// or [`retain_mut`] with a negated predicate if you also do not need to restrict the range.
4333 ///
4334 /// [`retain_mut`]: Vec::retain_mut
4335 ///
4336 /// Using this method is equivalent to the following code:
4337 ///
4338 /// ```
4339 /// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
4340 /// # let mut vec = vec![0, 1, 2, 3, 4, 5, 6];
4341 /// # let mut vec2 = vec.clone();
4342 /// # let range = 1..5;
4343 /// let mut i = range.start;
4344 /// let end_items = vec.len() - range.end;
4345 /// # let mut extracted = vec![];
4346 ///
4347 /// while i < vec.len() - end_items {
4348 /// if some_predicate(&mut vec[i]) {
4349 /// let val = vec.remove(i);
4350 /// // your code here
4351 /// # extracted.push(val);
4352 /// } else {
4353 /// i += 1;
4354 /// }
4355 /// }
4356 ///
4357 /// # let extracted2: Vec<_> = vec2.extract_if(range, some_predicate).collect();
4358 /// # assert_eq!(vec, vec2);
4359 /// # assert_eq!(extracted, extracted2);
4360 /// ```
4361 ///
4362 /// But `extract_if` is easier to use. `extract_if` is also more efficient,
4363 /// because it can backshift the elements of the array in bulk.
4364 ///
4365 /// The iterator also lets you mutate the value of each element in the
4366 /// closure, regardless of whether you choose to keep or remove it.
4367 ///
4368 /// # Panics
4369 ///
4370 /// If `range` is out of bounds.
4371 ///
4372 /// # Examples
4373 ///
4374 /// Splitting a vector into even and odd values, reusing the original vector:
4375 ///
4376 /// ```
4377 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
4378 ///
4379 /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<Vec<_>>();
4380 /// let odds = numbers;
4381 ///
4382 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
4383 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
4384 /// ```
4385 ///
4386 /// Using the range argument to only process a part of the vector:
4387 ///
4388 /// ```
4389 /// let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2];
4390 /// let ones = items.extract_if(7.., |x| *x == 1).collect::<Vec<_>>();
4391 /// assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]);
4392 /// assert_eq!(ones.len(), 3);
4393 /// ```
4394 #[stable(feature = "extract_if", since = "1.87.0")]
4395 pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A>
4396 where
4397 A: AllocatorNightly,
4398 F: FnMut(&mut T) -> bool,
4399 R: RangeBounds<usize>,
4400 {
4401 ExtractIf::new(self, filter, range)
4402 }
4403}
4404
4405/// Extend implementation that copies elements out of references before pushing them onto the Vec.
4406///
4407/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
4408/// append the entire slice at once.
4409///
4410/// [`copy_from_slice`]: slice::copy_from_slice
4411#[cfg(not(no_global_oom_handling))]
4412#[stable(feature = "extend_ref", since = "1.2.0")]
4413impl<'a, T: Copy + 'a, A: Allocator> Extend<&'a T> for Vec<T, A> {
4414 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
4415 self.spec_extend(iter.into_iter())
4416 }
4417
4418 #[inline]
4419 fn extend_one(&mut self, &item: &'a T) {
4420 self.push(item);
4421 }
4422
4423 #[inline]
4424 fn extend_reserve(&mut self, additional: usize) {
4425 self.reserve(additional);
4426 }
4427
4428 #[inline]
4429 unsafe fn extend_one_unchecked(&mut self, &item: &'a T) {
4430 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
4431 unsafe {
4432 let len = self.len();
4433 ptr::write(self.as_mut_ptr().add(len), item);
4434 self.set_len(len + 1);
4435 }
4436 }
4437}
4438
4439/// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison).
4440#[stable(feature = "rust1", since = "1.0.0")]
4441impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1>
4442where
4443 T: PartialOrd,
4444 A1: Allocator,
4445 A2: Allocator,
4446{
4447 #[inline]
4448 fn partial_cmp(&self, other: &Vec<T, A2>) -> Option<Ordering> {
4449 PartialOrd::partial_cmp(&**self, &**other)
4450 }
4451}
4452
4453#[stable(feature = "rust1", since = "1.0.0")]
4454impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
4455
4456/// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison).
4457#[stable(feature = "rust1", since = "1.0.0")]
4458impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
4459 #[inline]
4460 fn cmp(&self, other: &Self) -> Ordering {
4461 Ord::cmp(&**self, &**other)
4462 }
4463}
4464
4465#[stable(feature = "rust1", since = "1.0.0")]
4466#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
4467const unsafe impl<#[may_dangle] T: [const] Destruct, A: [const] Allocator + [const] Destruct> Drop
4468 for Vec<T, A>
4469{
4470 fn drop(&mut self) {
4471 // ignore-tidy-undocumented-unsafe
4472 unsafe {
4473 // use drop for [T]
4474 // use a raw slice to refer to the elements of the vector as weakest necessary type;
4475 // could avoid questions of validity in certain cases
4476 self.as_mut_ptr().cast_slice(self.len).drop_in_place()
4477 }
4478 // RawVec handles deallocation
4479 }
4480}
4481
4482#[stable(feature = "rust1", since = "1.0.0")]
4483#[rustc_const_unstable(feature = "const_default", issue = "143894")]
4484const impl<T> Default for Vec<T> {
4485 /// Creates an empty `Vec<T>`.
4486 ///
4487 /// The vector will not allocate until elements are pushed onto it.
4488 fn default() -> Vec<T> {
4489 Vec::new()
4490 }
4491}
4492
4493#[stable(feature = "rust1", since = "1.0.0")]
4494impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
4495 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4496 fmt::Debug::fmt(&**self, f)
4497 }
4498}
4499
4500#[stable(feature = "rust1", since = "1.0.0")]
4501impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
4502 fn as_ref(&self) -> &Vec<T, A> {
4503 self
4504 }
4505}
4506
4507#[stable(feature = "vec_as_mut", since = "1.5.0")]
4508impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
4509 fn as_mut(&mut self) -> &mut Vec<T, A> {
4510 self
4511 }
4512}
4513
4514#[stable(feature = "rust1", since = "1.0.0")]
4515impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
4516 fn as_ref(&self) -> &[T] {
4517 self
4518 }
4519}
4520
4521#[stable(feature = "vec_as_mut", since = "1.5.0")]
4522impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
4523 fn as_mut(&mut self) -> &mut [T] {
4524 self
4525 }
4526}
4527
4528#[cfg(not(no_global_oom_handling))]
4529#[stable(feature = "rust1", since = "1.0.0")]
4530impl<T: Clone> From<&[T]> for Vec<T> {
4531 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4532 ///
4533 /// # Examples
4534 ///
4535 /// ```
4536 /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
4537 /// ```
4538 fn from(s: &[T]) -> Vec<T> {
4539 s.to_vec()
4540 }
4541}
4542
4543#[cfg(not(no_global_oom_handling))]
4544#[stable(feature = "vec_from_mut", since = "1.19.0")]
4545impl<T: Clone> From<&mut [T]> for Vec<T> {
4546 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4547 ///
4548 /// # Examples
4549 ///
4550 /// ```
4551 /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
4552 /// ```
4553 fn from(s: &mut [T]) -> Vec<T> {
4554 s.to_vec()
4555 }
4556}
4557
4558#[cfg(not(no_global_oom_handling))]
4559#[stable(feature = "vec_from_array_ref", since = "1.74.0")]
4560impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T> {
4561 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4562 ///
4563 /// # Examples
4564 ///
4565 /// ```
4566 /// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);
4567 /// ```
4568 fn from(s: &[T; N]) -> Vec<T> {
4569 Self::from(s.as_slice())
4570 }
4571}
4572
4573#[cfg(not(no_global_oom_handling))]
4574#[stable(feature = "vec_from_array_ref", since = "1.74.0")]
4575impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T> {
4576 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4577 ///
4578 /// # Examples
4579 ///
4580 /// ```
4581 /// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
4582 /// ```
4583 fn from(s: &mut [T; N]) -> Vec<T> {
4584 Self::from(s.as_mut_slice())
4585 }
4586}
4587
4588#[cfg(not(no_global_oom_handling))]
4589#[stable(feature = "vec_from_array", since = "1.44.0")]
4590impl<T, const N: usize> From<[T; N]> for Vec<T> {
4591 /// Allocates a `Vec<T>` and moves `s`'s items into it.
4592 ///
4593 /// # Examples
4594 ///
4595 /// ```
4596 /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
4597 /// ```
4598 fn from(s: [T; N]) -> Vec<T> {
4599 <[T]>::into_vec(Box::new(s))
4600 }
4601}
4602
4603#[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
4604impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
4605where
4606 [T]: ToOwned<Owned = Vec<T>>,
4607{
4608 /// Converts a clone-on-write slice into a vector.
4609 ///
4610 /// If `s` already owns a `Vec<T>`, it will be returned directly.
4611 /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and
4612 /// filled by cloning `s`'s items into it.
4613 ///
4614 /// # Examples
4615 ///
4616 /// ```
4617 /// # use std::borrow::Cow;
4618 /// let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);
4619 /// let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);
4620 /// assert_eq!(Vec::from(o), Vec::from(b));
4621 /// ```
4622 fn from(s: Cow<'a, [T]>) -> Vec<T> {
4623 s.into_owned()
4624 }
4625}
4626
4627// note: test pulls in std, which causes errors here
4628#[stable(feature = "vec_from_box", since = "1.18.0")]
4629impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
4630 /// Converts a boxed slice into a vector by transferring ownership of
4631 /// the existing heap allocation.
4632 ///
4633 /// # Examples
4634 ///
4635 /// ```
4636 /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
4637 /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
4638 /// ```
4639 fn from(s: Box<[T], A>) -> Self {
4640 s.into_vec()
4641 }
4642}
4643
4644// note: test pulls in std, which causes errors here
4645#[cfg(not(no_global_oom_handling))]
4646#[stable(feature = "box_from_vec", since = "1.20.0")]
4647impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
4648 /// Converts a vector into a boxed slice.
4649 ///
4650 /// Before doing the conversion, this method discards excess capacity like [`Vec::shrink_to_fit`].
4651 ///
4652 /// [owned slice]: Box
4653 /// [`Vec::shrink_to_fit`]: Vec::shrink_to_fit
4654 ///
4655 /// # Examples
4656 ///
4657 /// ```
4658 /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
4659 /// ```
4660 ///
4661 /// Any excess capacity is removed:
4662 /// ```
4663 /// let mut vec = Vec::with_capacity(10);
4664 /// vec.extend([1, 2, 3]);
4665 ///
4666 /// assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice());
4667 /// ```
4668 fn from(v: Vec<T, A>) -> Self {
4669 v.into_boxed_slice()
4670 }
4671}
4672
4673#[cfg(not(no_global_oom_handling))]
4674#[stable(feature = "rust1", since = "1.0.0")]
4675impl From<&str> for Vec<u8> {
4676 /// Allocates a `Vec<u8>` and fills it with a UTF-8 string.
4677 ///
4678 /// # Examples
4679 ///
4680 /// ```
4681 /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
4682 /// ```
4683 fn from(s: &str) -> Vec<u8> {
4684 From::from(s.as_bytes())
4685 }
4686}
4687
4688#[stable(feature = "array_try_from_vec", since = "1.48.0")]
4689#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
4690const impl<T: [const] Destruct, A: [const] Allocator + [const] Destruct, const N: usize>
4691 TryFrom<Vec<T, A>> for [T; N]
4692{
4693 type Error = Vec<T, A>;
4694
4695 /// Gets the entire contents of the `Vec<T>` as an array,
4696 /// if its size exactly matches that of the requested array.
4697 ///
4698 /// # Examples
4699 ///
4700 /// ```
4701 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
4702 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
4703 /// ```
4704 ///
4705 /// If the length doesn't match, the input comes back in `Err`:
4706 /// ```
4707 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
4708 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
4709 /// ```
4710 ///
4711 /// If you're fine with just getting a prefix of the `Vec<T>`,
4712 /// you can call [`.truncate(N)`](Vec::truncate) first.
4713 /// ```
4714 /// let mut v = String::from("hello world").into_bytes();
4715 /// v.sort();
4716 /// v.truncate(2);
4717 /// let [a, b]: [_; 2] = v.try_into().unwrap();
4718 /// assert_eq!(a, b' ');
4719 /// assert_eq!(b, b'd');
4720 /// ```
4721 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
4722 if vec.len() != N {
4723 return Err(vec);
4724 }
4725
4726 // SAFETY: `.set_len(0)` is always sound.
4727 unsafe { vec.set_len(0) };
4728
4729 // SAFETY: A `Vec`'s pointer is always aligned properly, and
4730 // the alignment the array needs is the same as the items.
4731 // We checked earlier that we have sufficient items.
4732 // The items will not double-drop as the `set_len`
4733 // tells the `Vec` not to also drop them.
4734 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
4735 Ok(array)
4736 }
4737}