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