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