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