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