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