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 { slice::from_raw_parts(self.as_ptr(), self.len) }
1751 }
1752
1753 /// Extracts a mutable slice of the entire vector.
1754 ///
1755 /// Equivalent to `&mut s[..]`.
1756 ///
1757 /// # Examples
1758 ///
1759 /// ```
1760 /// use std::io::{self, Read};
1761 /// let mut buffer = vec![0; 3];
1762 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1763 /// ```
1764 #[inline]
1765 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1766 #[rustc_diagnostic_item = "vec_as_mut_slice"]
1767 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1768 pub const fn as_mut_slice(&mut self) -> &mut [T] {
1769 // SAFETY: `slice::from_raw_parts_mut` requires pointee is a contiguous, aligned buffer of
1770 // size `len` containing properly-initialized `T`s. Data must not be accessed through any
1771 // other pointer for the returned lifetime. Further, `len * size_of::<T>` <=
1772 // `ISIZE::MAX` and allocation does not "wrap" through overflowing memory addresses.
1773 //
1774 // * Vec API guarantees that self.buf:
1775 // * contains only properly-initialized items within 0..len
1776 // * is aligned, contiguous, and valid for `len` reads
1777 // * obeys size and address-wrapping constraints
1778 //
1779 // * We only construct references to `self.buf` through `&self` and `&mut self` methods;
1780 // borrow-check ensures that it is not possible to construct a reference to `self.buf`
1781 // within the returned lifetime.
1782 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1783 }
1784
1785 /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
1786 /// valid for zero sized reads if the vector didn't allocate.
1787 ///
1788 /// The caller must ensure that the vector outlives the pointer this
1789 /// function returns, or else it will end up dangling.
1790 /// Modifying the vector may cause its buffer to be reallocated,
1791 /// which would also make any pointers to it invalid.
1792 ///
1793 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1794 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1795 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1796 ///
1797 /// This method guarantees that for the purpose of the aliasing model, this method
1798 /// does not materialize a reference to the underlying slice, and thus the returned pointer
1799 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1800 /// and [`as_non_null`].
1801 /// Note that calling other methods that materialize mutable references to the slice,
1802 /// or mutable references to specific elements you are planning on accessing through this pointer,
1803 /// as well as writing to those elements, may still invalidate this pointer.
1804 /// See the second example below for how this guarantee can be used.
1805 ///
1806 ///
1807 /// # Examples
1808 ///
1809 /// ```
1810 /// let x = vec![1, 2, 4];
1811 /// let x_ptr = x.as_ptr();
1812 ///
1813 /// unsafe {
1814 /// for i in 0..x.len() {
1815 /// assert_eq!(*x_ptr.add(i), 1 << i);
1816 /// }
1817 /// }
1818 /// ```
1819 ///
1820 /// Due to the aliasing guarantee, the following code is legal:
1821 ///
1822 /// ```rust
1823 /// unsafe {
1824 /// let mut v = vec![0, 1, 2];
1825 /// let ptr1 = v.as_ptr();
1826 /// let _ = ptr1.read();
1827 /// let ptr2 = v.as_mut_ptr().offset(2);
1828 /// ptr2.write(2);
1829 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`
1830 /// // because it mutated a different element:
1831 /// let _ = ptr1.read();
1832 /// }
1833 /// ```
1834 ///
1835 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1836 /// [`as_ptr`]: Vec::as_ptr
1837 /// [`as_non_null`]: Vec::as_non_null
1838 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1839 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1840 #[rustc_never_returns_null_ptr]
1841 #[rustc_as_ptr]
1842 #[inline]
1843 pub const fn as_ptr(&self) -> *const T {
1844 // We shadow the slice method of the same name to avoid going through
1845 // `deref`, which creates an intermediate reference.
1846 self.buf.ptr()
1847 }
1848
1849 /// Returns a raw mutable pointer to the vector's buffer, or a dangling
1850 /// raw pointer valid for zero sized reads if the vector didn't allocate.
1851 ///
1852 /// The caller must ensure that the vector outlives the pointer this
1853 /// function returns, or else it will end up dangling.
1854 /// Modifying the vector may cause its buffer to be reallocated,
1855 /// which would also make any pointers to it invalid.
1856 ///
1857 /// This method guarantees that for the purpose of the aliasing model, this method
1858 /// does not materialize a reference to the underlying slice, and thus the returned pointer
1859 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1860 /// and [`as_non_null`].
1861 /// Note that calling other methods that materialize references to the slice,
1862 /// or references to specific elements you are planning on accessing through this pointer,
1863 /// may still invalidate this pointer.
1864 /// See the second example below for how this guarantee can be used.
1865 ///
1866 /// The method also guarantees that, as long as `T` is not zero-sized and the capacity is
1867 /// nonzero, the pointer may be passed into [`dealloc`] with a layout of
1868 /// `Layout::array::<T>(capacity)` in order to deallocate the backing memory. If this is done,
1869 /// be careful not to run the destructor of the `Vec`, as dropping it will result in
1870 /// double-frees. Wrapping the `Vec` in a [`ManuallyDrop`] is the typical way to achieve this.
1871 ///
1872 /// # Examples
1873 ///
1874 /// ```
1875 /// // Allocate vector big enough for 4 elements.
1876 /// let size = 4;
1877 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1878 /// let x_ptr = x.as_mut_ptr();
1879 ///
1880 /// // Initialize elements via raw pointer writes, then set length.
1881 /// unsafe {
1882 /// for i in 0..size {
1883 /// *x_ptr.add(i) = i as i32;
1884 /// }
1885 /// x.set_len(size);
1886 /// }
1887 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1888 /// ```
1889 ///
1890 /// Due to the aliasing guarantee, the following code is legal:
1891 ///
1892 /// ```rust
1893 /// unsafe {
1894 /// let mut v = vec![0];
1895 /// let ptr1 = v.as_mut_ptr();
1896 /// ptr1.write(1);
1897 /// let ptr2 = v.as_mut_ptr();
1898 /// ptr2.write(2);
1899 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1900 /// ptr1.write(3);
1901 /// }
1902 /// ```
1903 ///
1904 /// Deallocating a vector using [`Box`] (which uses [`dealloc`] internally):
1905 ///
1906 /// ```
1907 /// use std::mem::{ManuallyDrop, MaybeUninit};
1908 ///
1909 /// let mut v = ManuallyDrop::new(vec![0, 1, 2]);
1910 /// let ptr = v.as_mut_ptr();
1911 /// let capacity = v.capacity();
1912 /// let slice_ptr: *mut [MaybeUninit<i32>] =
1913 /// std::ptr::slice_from_raw_parts_mut(ptr.cast(), capacity);
1914 /// drop(unsafe { Box::from_raw(slice_ptr) });
1915 /// ```
1916 ///
1917 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1918 /// [`as_ptr`]: Vec::as_ptr
1919 /// [`as_non_null`]: Vec::as_non_null
1920 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
1921 /// [`ManuallyDrop`]: core::mem::ManuallyDrop
1922 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1923 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
1924 #[rustc_never_returns_null_ptr]
1925 #[rustc_as_ptr]
1926 #[inline]
1927 pub const fn as_mut_ptr(&mut self) -> *mut T {
1928 // We shadow the slice method of the same name to avoid going through
1929 // `deref_mut`, which creates an intermediate reference.
1930 self.buf.ptr()
1931 }
1932
1933 /// Returns a `NonNull` pointer to the vector's buffer, or a dangling
1934 /// `NonNull` pointer valid for zero sized reads if the vector didn't allocate.
1935 ///
1936 /// The caller must ensure that the vector outlives the pointer this
1937 /// function returns, or else it will end up dangling.
1938 /// Modifying the vector may cause its buffer to be reallocated,
1939 /// which would also make any pointers to it invalid.
1940 ///
1941 /// This method guarantees that for the purpose of the aliasing model, this method
1942 /// does not materialize a reference to the underlying slice, and thus the returned pointer
1943 /// will remain valid when mixed with other calls to [`as_ptr`], [`as_mut_ptr`],
1944 /// and [`as_non_null`].
1945 /// Note that calling other methods that materialize references to the slice,
1946 /// or references to specific elements you are planning on accessing through this pointer,
1947 /// may still invalidate this pointer.
1948 /// See the second example below for how this guarantee can be used.
1949 ///
1950 /// # Examples
1951 ///
1952 /// ```
1953 /// #![feature(box_vec_non_null)]
1954 ///
1955 /// // Allocate vector big enough for 4 elements.
1956 /// let size = 4;
1957 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1958 /// let x_ptr = x.as_non_null();
1959 ///
1960 /// // Initialize elements via raw pointer writes, then set length.
1961 /// unsafe {
1962 /// for i in 0..size {
1963 /// x_ptr.add(i).write(i as i32);
1964 /// }
1965 /// x.set_len(size);
1966 /// }
1967 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1968 /// ```
1969 ///
1970 /// Due to the aliasing guarantee, the following code is legal:
1971 ///
1972 /// ```rust
1973 /// #![feature(box_vec_non_null)]
1974 ///
1975 /// unsafe {
1976 /// let mut v = vec![0];
1977 /// let ptr1 = v.as_non_null();
1978 /// ptr1.write(1);
1979 /// let ptr2 = v.as_non_null();
1980 /// ptr2.write(2);
1981 /// // Notably, the write to `ptr2` did *not* invalidate `ptr1`:
1982 /// ptr1.write(3);
1983 /// }
1984 /// ```
1985 ///
1986 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1987 /// [`as_ptr`]: Vec::as_ptr
1988 /// [`as_non_null`]: Vec::as_non_null
1989 #[unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")]
1990 #[rustc_const_unstable(feature = "box_vec_non_null", reason = "new API", issue = "130364")]
1991 #[inline]
1992 pub const fn as_non_null(&mut self) -> NonNull<T> {
1993 self.buf.non_null()
1994 }
1995
1996 /// Returns a reference to the underlying allocator.
1997 #[unstable(feature = "allocator_api", issue = "32838")]
1998 #[inline]
1999 pub fn allocator(&self) -> &A {
2000 self.buf.allocator()
2001 }
2002
2003 /// Forces the length of the vector to `new_len`.
2004 ///
2005 /// This is a low-level operation that maintains none of the normal
2006 /// invariants of the type. Normally changing the length of a vector
2007 /// is done using one of the safe operations instead, such as
2008 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
2009 ///
2010 /// [`truncate`]: Vec::truncate
2011 /// [`resize`]: Vec::resize
2012 /// [`extend`]: Extend::extend
2013 /// [`clear`]: Vec::clear
2014 ///
2015 /// # Safety
2016 ///
2017 /// - `new_len` must be less than or equal to [`capacity()`].
2018 /// - The elements at `old_len..new_len` must be initialized.
2019 ///
2020 /// [`capacity()`]: Vec::capacity
2021 ///
2022 /// # Examples
2023 ///
2024 /// See [`spare_capacity_mut()`] for an example with safe
2025 /// initialization of capacity elements and use of this method.
2026 ///
2027 /// `set_len()` can be useful for situations in which the vector
2028 /// is serving as a buffer for other code, particularly over FFI:
2029 ///
2030 /// ```no_run
2031 /// # #![allow(dead_code)]
2032 /// # // This is just a minimal skeleton for the doc example;
2033 /// # // don't use this as a starting point for a real library.
2034 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
2035 /// # const Z_OK: i32 = 0;
2036 /// # unsafe extern "C" {
2037 /// # fn deflateGetDictionary(
2038 /// # strm: *mut std::ffi::c_void,
2039 /// # dictionary: *mut u8,
2040 /// # dictLength: *mut usize,
2041 /// # ) -> i32;
2042 /// # }
2043 /// # impl StreamWrapper {
2044 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
2045 /// // Per the FFI method's docs, "32768 bytes is always enough".
2046 /// let mut dict = Vec::with_capacity(32_768);
2047 /// let mut dict_length = 0;
2048 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
2049 /// // 1. `dict_length` elements were initialized.
2050 /// // 2. `dict_length` <= the capacity (32_768)
2051 /// // which makes `set_len` safe to call.
2052 /// unsafe {
2053 /// // Make the FFI call...
2054 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
2055 /// if r == Z_OK {
2056 /// // ...and update the length to what was initialized.
2057 /// dict.set_len(dict_length);
2058 /// Some(dict)
2059 /// } else {
2060 /// None
2061 /// }
2062 /// }
2063 /// }
2064 /// # }
2065 /// ```
2066 ///
2067 /// While the following example is sound, there is a memory leak since
2068 /// the inner vectors were not freed prior to the `set_len` call:
2069 ///
2070 /// ```
2071 /// let mut vec = vec![vec![1, 0, 0],
2072 /// vec![0, 1, 0],
2073 /// vec![0, 0, 1]];
2074 /// // SAFETY:
2075 /// // 1. `old_len..0` is empty so no elements need to be initialized.
2076 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
2077 /// unsafe {
2078 /// vec.set_len(0);
2079 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
2080 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
2081 /// # vec.set_len(3);
2082 /// }
2083 /// ```
2084 ///
2085 /// Normally, here, one would use [`clear`] instead to correctly drop
2086 /// the contents and thus not leak memory.
2087 ///
2088 /// [`spare_capacity_mut()`]: Vec::spare_capacity_mut
2089 #[inline]
2090 #[stable(feature = "rust1", since = "1.0.0")]
2091 pub unsafe fn set_len(&mut self, new_len: usize) {
2092 ub_checks::assert_unsafe_precondition!(
2093 check_library_ub,
2094 "Vec::set_len requires that new_len <= capacity()",
2095 (new_len: usize = new_len, capacity: usize = self.capacity()) => new_len <= capacity
2096 );
2097
2098 self.len = new_len;
2099 }
2100
2101 /// Removes an element from the vector and returns it.
2102 ///
2103 /// The removed element is replaced by the last element of the vector.
2104 ///
2105 /// This does not preserve ordering of the remaining elements, but is *O*(1).
2106 /// If you need to preserve the element order, use [`remove`] instead.
2107 ///
2108 /// [`remove`]: Vec::remove
2109 ///
2110 /// # Panics
2111 ///
2112 /// Panics if `index` is out of bounds.
2113 ///
2114 /// # Examples
2115 ///
2116 /// ```
2117 /// let mut v = vec!["foo", "bar", "baz", "qux"];
2118 ///
2119 /// assert_eq!(v.swap_remove(1), "bar");
2120 /// assert_eq!(v, ["foo", "qux", "baz"]);
2121 ///
2122 /// assert_eq!(v.swap_remove(0), "foo");
2123 /// assert_eq!(v, ["baz", "qux"]);
2124 /// ```
2125 #[inline]
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 pub fn swap_remove(&mut self, index: usize) -> T {
2128 #[cold]
2129 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2130 #[optimize(size)]
2131 fn assert_failed(index: usize, len: usize) -> ! {
2132 panic!("swap_remove index (is {index}) should be < len (is {len})");
2133 }
2134
2135 let len = self.len();
2136 if index >= len {
2137 assert_failed(index, len);
2138 }
2139 unsafe {
2140 // We replace self[index] with the last element. Note that if the
2141 // bounds check above succeeds there must be a last element (which
2142 // can be self[index] itself).
2143 let value = ptr::read(self.as_ptr().add(index));
2144 let base_ptr = self.as_mut_ptr();
2145 ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
2146 self.set_len(len - 1);
2147 value
2148 }
2149 }
2150
2151 /// Inserts an element at position `index` within the vector, shifting all
2152 /// elements after it to the right.
2153 ///
2154 /// # Panics
2155 ///
2156 /// Panics if `index > len`.
2157 ///
2158 /// # Examples
2159 ///
2160 /// ```
2161 /// let mut vec = vec!['a', 'b', 'c'];
2162 /// vec.insert(1, 'd');
2163 /// assert_eq!(vec, ['a', 'd', 'b', 'c']);
2164 /// vec.insert(4, 'e');
2165 /// assert_eq!(vec, ['a', 'd', 'b', 'c', 'e']);
2166 /// ```
2167 ///
2168 /// # Time complexity
2169 ///
2170 /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be
2171 /// shifted to the right. In the worst case, all elements are shifted when
2172 /// the insertion index is 0.
2173 #[cfg(not(no_global_oom_handling))]
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 #[track_caller]
2176 pub fn insert(&mut self, index: usize, element: T) {
2177 let _ = self.insert_mut(index, element);
2178 }
2179
2180 /// Inserts an element at position `index` within the vector, shifting all
2181 /// elements after it to the right, and returning a reference to the new
2182 /// element.
2183 ///
2184 /// # Panics
2185 ///
2186 /// Panics if `index > len`.
2187 ///
2188 /// # Examples
2189 ///
2190 /// ```
2191 /// #![feature(push_mut)]
2192 /// let mut vec = vec![1, 3, 5, 9];
2193 /// let x = vec.insert_mut(3, 6);
2194 /// *x += 1;
2195 /// assert_eq!(vec, [1, 3, 5, 7, 9]);
2196 /// ```
2197 ///
2198 /// # Time complexity
2199 ///
2200 /// Takes *O*([`Vec::len`]) time. All items after the insertion index must be
2201 /// shifted to the right. In the worst case, all elements are shifted when
2202 /// the insertion index is 0.
2203 #[cfg(not(no_global_oom_handling))]
2204 #[inline]
2205 #[unstable(feature = "push_mut", issue = "135974")]
2206 #[track_caller]
2207 #[must_use = "if you don't need a reference to the value, use `Vec::insert` instead"]
2208 pub fn insert_mut(&mut self, index: usize, element: T) -> &mut T {
2209 #[cold]
2210 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2211 #[track_caller]
2212 #[optimize(size)]
2213 fn assert_failed(index: usize, len: usize) -> ! {
2214 panic!("insertion index (is {index}) should be <= len (is {len})");
2215 }
2216
2217 let len = self.len();
2218 if index > len {
2219 assert_failed(index, len);
2220 }
2221
2222 // space for the new element
2223 if len == self.buf.capacity() {
2224 self.buf.grow_one();
2225 }
2226
2227 unsafe {
2228 // infallible
2229 // The spot to put the new value
2230 let p = self.as_mut_ptr().add(index);
2231 {
2232 if index < len {
2233 // Shift everything over to make space. (Duplicating the
2234 // `index`th element into two consecutive places.)
2235 ptr::copy(p, p.add(1), len - index);
2236 }
2237 // Write it in, overwriting the first copy of the `index`th
2238 // element.
2239 ptr::write(p, element);
2240 }
2241 self.set_len(len + 1);
2242 &mut *p
2243 }
2244 }
2245
2246 /// Removes and returns the element at position `index` within the vector,
2247 /// shifting all elements after it to the left.
2248 ///
2249 /// Note: Because this shifts over the remaining elements, it has a
2250 /// worst-case performance of *O*(*n*). If you don't need the order of elements
2251 /// to be preserved, use [`swap_remove`] instead. If you'd like to remove
2252 /// elements from the beginning of the `Vec`, consider using
2253 /// [`VecDeque::pop_front`] instead.
2254 ///
2255 /// [`swap_remove`]: Vec::swap_remove
2256 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2257 ///
2258 /// # Panics
2259 ///
2260 /// Panics if `index` is out of bounds.
2261 ///
2262 /// # Examples
2263 ///
2264 /// ```
2265 /// let mut v = vec!['a', 'b', 'c'];
2266 /// assert_eq!(v.remove(1), 'b');
2267 /// assert_eq!(v, ['a', 'c']);
2268 /// ```
2269 #[stable(feature = "rust1", since = "1.0.0")]
2270 #[track_caller]
2271 #[rustc_confusables("delete", "take")]
2272 pub fn remove(&mut self, index: usize) -> T {
2273 #[cold]
2274 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2275 #[track_caller]
2276 #[optimize(size)]
2277 fn assert_failed(index: usize, len: usize) -> ! {
2278 panic!("removal index (is {index}) should be < len (is {len})");
2279 }
2280
2281 match self.try_remove(index) {
2282 Some(elem) => elem,
2283 None => assert_failed(index, self.len()),
2284 }
2285 }
2286
2287 /// Remove and return the element at position `index` within the vector,
2288 /// shifting all elements after it to the left, or [`None`] if it does not
2289 /// exist.
2290 ///
2291 /// Note: Because this shifts over the remaining elements, it has a
2292 /// worst-case performance of *O*(*n*). If you'd like to remove
2293 /// elements from the beginning of the `Vec`, consider using
2294 /// [`VecDeque::pop_front`] instead.
2295 ///
2296 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2297 ///
2298 /// # Examples
2299 ///
2300 /// ```
2301 /// #![feature(vec_try_remove)]
2302 /// let mut v = vec![1, 2, 3];
2303 /// assert_eq!(v.try_remove(0), Some(1));
2304 /// assert_eq!(v.try_remove(2), None);
2305 /// ```
2306 #[unstable(feature = "vec_try_remove", issue = "146954")]
2307 #[rustc_confusables("delete", "take", "remove")]
2308 pub fn try_remove(&mut self, index: usize) -> Option<T> {
2309 let len = self.len();
2310 if index >= len {
2311 return None;
2312 }
2313 unsafe {
2314 // infallible
2315 let ret;
2316 {
2317 // the place we are taking from.
2318 let ptr = self.as_mut_ptr().add(index);
2319 // copy it out, unsafely having a copy of the value on
2320 // the stack and in the vector at the same time.
2321 ret = ptr::read(ptr);
2322
2323 // Shift everything down to fill in that spot.
2324 ptr::copy(ptr.add(1), ptr, len - index - 1);
2325 }
2326 self.set_len(len - 1);
2327 Some(ret)
2328 }
2329 }
2330
2331 /// Retains only the elements specified by the predicate.
2332 ///
2333 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
2334 /// This method operates in place, visiting each element exactly once in the
2335 /// original order, and preserves the order of the retained elements.
2336 ///
2337 /// # Examples
2338 ///
2339 /// ```
2340 /// let mut vec = vec![1, 2, 3, 4];
2341 /// vec.retain(|&x| x % 2 == 0);
2342 /// assert_eq!(vec, [2, 4]);
2343 /// ```
2344 ///
2345 /// Because the elements are visited exactly once in the original order,
2346 /// external state may be used to decide which elements to keep.
2347 ///
2348 /// ```
2349 /// let mut vec = vec![1, 2, 3, 4, 5];
2350 /// let keep = [false, true, true, false, true];
2351 /// let mut iter = keep.iter();
2352 /// vec.retain(|_| *iter.next().unwrap());
2353 /// assert_eq!(vec, [2, 3, 5]);
2354 /// ```
2355 #[stable(feature = "rust1", since = "1.0.0")]
2356 pub fn retain<F>(&mut self, mut f: F)
2357 where
2358 F: FnMut(&T) -> bool,
2359 {
2360 self.retain_mut(|elem| f(elem));
2361 }
2362
2363 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
2364 ///
2365 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
2366 /// This method operates in place, visiting each element exactly once in the
2367 /// original order, and preserves the order of the retained elements.
2368 ///
2369 /// # Examples
2370 ///
2371 /// ```
2372 /// let mut vec = vec![1, 2, 3, 4];
2373 /// vec.retain_mut(|x| if *x <= 3 {
2374 /// *x += 1;
2375 /// true
2376 /// } else {
2377 /// false
2378 /// });
2379 /// assert_eq!(vec, [2, 3, 4]);
2380 /// ```
2381 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
2382 pub fn retain_mut<F>(&mut self, mut f: F)
2383 where
2384 F: FnMut(&mut T) -> bool,
2385 {
2386 let original_len = self.len();
2387
2388 if original_len == 0 {
2389 // Empty case: explicit return allows better optimization, vs letting compiler infer it
2390 return;
2391 }
2392
2393 // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
2394 // | ^- write ^- read |
2395 // |<- original_len ->|
2396 // Kept: Elements which predicate returns true on.
2397 // Hole: Moved or dropped element slot.
2398 // Unchecked: Unchecked valid elements.
2399 //
2400 // This drop guard will be invoked when predicate or `drop` of element panicked.
2401 // It shifts unchecked elements to cover holes and `set_len` to the correct length.
2402 // In cases when predicate and `drop` never panick, it will be optimized out.
2403 struct PanicGuard<'a, T, A: Allocator> {
2404 v: &'a mut Vec<T, A>,
2405 read: usize,
2406 write: usize,
2407 original_len: usize,
2408 }
2409
2410 impl<T, A: Allocator> Drop for PanicGuard<'_, T, A> {
2411 #[cold]
2412 fn drop(&mut self) {
2413 let remaining = self.original_len - self.read;
2414 // SAFETY: Trailing unchecked items must be valid since we never touch them.
2415 unsafe {
2416 ptr::copy(
2417 self.v.as_ptr().add(self.read),
2418 self.v.as_mut_ptr().add(self.write),
2419 remaining,
2420 );
2421 }
2422 // SAFETY: After filling holes, all items are in contiguous memory.
2423 unsafe {
2424 self.v.set_len(self.write + remaining);
2425 }
2426 }
2427 }
2428
2429 let mut read = 0;
2430 loop {
2431 // SAFETY: read < original_len
2432 let cur = unsafe { self.get_unchecked_mut(read) };
2433 if hint::unlikely(!f(cur)) {
2434 break;
2435 }
2436 read += 1;
2437 if read == original_len {
2438 // All elements are kept, return early.
2439 return;
2440 }
2441 }
2442
2443 // Critical section starts here and at least one element is going to be removed.
2444 // Advance `g.read` early to avoid double drop if `drop_in_place` panicked.
2445 let mut g = PanicGuard { v: self, read: read + 1, write: read, original_len };
2446 // SAFETY: previous `read` is always less than original_len.
2447 unsafe { ptr::drop_in_place(&mut *g.v.as_mut_ptr().add(read)) };
2448
2449 while g.read < g.original_len {
2450 // SAFETY: `read` is always less than original_len.
2451 let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.read) };
2452 if !f(cur) {
2453 // Advance `read` early to avoid double drop if `drop_in_place` panicked.
2454 g.read += 1;
2455 // SAFETY: We never touch this element again after dropped.
2456 unsafe { ptr::drop_in_place(cur) };
2457 } else {
2458 // SAFETY: `read` > `write`, so the slots don't overlap.
2459 // We use copy for move, and never touch the source element again.
2460 unsafe {
2461 let hole = g.v.as_mut_ptr().add(g.write);
2462 ptr::copy_nonoverlapping(cur, hole, 1);
2463 }
2464 g.write += 1;
2465 g.read += 1;
2466 }
2467 }
2468
2469 // We are leaving the critical section and no panic happened,
2470 // Commit the length change and forget the guard.
2471 // SAFETY: `write` is always less than or equal to original_len.
2472 unsafe { g.v.set_len(g.write) };
2473 mem::forget(g);
2474 }
2475
2476 /// Removes all but the first of consecutive elements in the vector that resolve to the same
2477 /// key.
2478 ///
2479 /// If the vector is sorted, this removes all duplicates.
2480 ///
2481 /// # Examples
2482 ///
2483 /// ```
2484 /// let mut vec = vec![10, 20, 21, 30, 20];
2485 ///
2486 /// vec.dedup_by_key(|i| *i / 10);
2487 ///
2488 /// assert_eq!(vec, [10, 20, 30, 20]);
2489 /// ```
2490 #[stable(feature = "dedup_by", since = "1.16.0")]
2491 #[inline]
2492 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
2493 where
2494 F: FnMut(&mut T) -> K,
2495 K: PartialEq,
2496 {
2497 self.dedup_by(|a, b| key(a) == key(b))
2498 }
2499
2500 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
2501 /// relation.
2502 ///
2503 /// The `same_bucket` function is passed references to two elements from the vector and
2504 /// must determine if the elements compare equal. The elements are passed in opposite order
2505 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
2506 ///
2507 /// If the vector is sorted, this removes all duplicates.
2508 ///
2509 /// # Examples
2510 ///
2511 /// ```
2512 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
2513 ///
2514 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
2515 ///
2516 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
2517 /// ```
2518 #[stable(feature = "dedup_by", since = "1.16.0")]
2519 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
2520 where
2521 F: FnMut(&mut T, &mut T) -> bool,
2522 {
2523 let len = self.len();
2524 if len <= 1 {
2525 return;
2526 }
2527
2528 // Check if we ever want to remove anything.
2529 // This allows to use copy_non_overlapping in next cycle.
2530 // And avoids any memory writes if we don't need to remove anything.
2531 let mut first_duplicate_idx: usize = 1;
2532 let start = self.as_mut_ptr();
2533 while first_duplicate_idx != len {
2534 let found_duplicate = unsafe {
2535 // SAFETY: first_duplicate always in range [1..len)
2536 // Note that we start iteration from 1 so we never overflow.
2537 let prev = start.add(first_duplicate_idx.wrapping_sub(1));
2538 let current = start.add(first_duplicate_idx);
2539 // We explicitly say in docs that references are reversed.
2540 same_bucket(&mut *current, &mut *prev)
2541 };
2542 if found_duplicate {
2543 break;
2544 }
2545 first_duplicate_idx += 1;
2546 }
2547 // Don't need to remove anything.
2548 // We cannot get bigger than len.
2549 if first_duplicate_idx == len {
2550 return;
2551 }
2552
2553 /* INVARIANT: vec.len() > read > write > write-1 >= 0 */
2554 struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> {
2555 /* Offset of the element we want to check if it is duplicate */
2556 read: usize,
2557
2558 /* Offset of the place where we want to place the non-duplicate
2559 * when we find it. */
2560 write: usize,
2561
2562 /* The Vec that would need correction if `same_bucket` panicked */
2563 vec: &'a mut Vec<T, A>,
2564 }
2565
2566 impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
2567 fn drop(&mut self) {
2568 /* This code gets executed when `same_bucket` panics */
2569
2570 /* SAFETY: invariant guarantees that `read - write`
2571 * and `len - read` never overflow and that the copy is always
2572 * in-bounds. */
2573 unsafe {
2574 let ptr = self.vec.as_mut_ptr();
2575 let len = self.vec.len();
2576
2577 /* How many items were left when `same_bucket` panicked.
2578 * Basically vec[read..].len() */
2579 let items_left = len.wrapping_sub(self.read);
2580
2581 /* Pointer to first item in vec[write..write+items_left] slice */
2582 let dropped_ptr = ptr.add(self.write);
2583 /* Pointer to first item in vec[read..] slice */
2584 let valid_ptr = ptr.add(self.read);
2585
2586 /* Copy `vec[read..]` to `vec[write..write+items_left]`.
2587 * The slices can overlap, so `copy_nonoverlapping` cannot be used */
2588 ptr::copy(valid_ptr, dropped_ptr, items_left);
2589
2590 /* How many items have been already dropped
2591 * Basically vec[read..write].len() */
2592 let dropped = self.read.wrapping_sub(self.write);
2593
2594 self.vec.set_len(len - dropped);
2595 }
2596 }
2597 }
2598
2599 /* Drop items while going through Vec, it should be more efficient than
2600 * doing slice partition_dedup + truncate */
2601
2602 // Construct gap first and then drop item to avoid memory corruption if `T::drop` panics.
2603 let mut gap =
2604 FillGapOnDrop { read: first_duplicate_idx + 1, write: first_duplicate_idx, vec: self };
2605 unsafe {
2606 // SAFETY: we checked that first_duplicate_idx in bounds before.
2607 // If drop panics, `gap` would remove this item without drop.
2608 ptr::drop_in_place(start.add(first_duplicate_idx));
2609 }
2610
2611 /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
2612 * are always in-bounds and read_ptr never aliases prev_ptr */
2613 unsafe {
2614 while gap.read < len {
2615 let read_ptr = start.add(gap.read);
2616 let prev_ptr = start.add(gap.write.wrapping_sub(1));
2617
2618 // We explicitly say in docs that references are reversed.
2619 let found_duplicate = same_bucket(&mut *read_ptr, &mut *prev_ptr);
2620 if found_duplicate {
2621 // Increase `gap.read` now since the drop may panic.
2622 gap.read += 1;
2623 /* We have found duplicate, drop it in-place */
2624 ptr::drop_in_place(read_ptr);
2625 } else {
2626 let write_ptr = start.add(gap.write);
2627
2628 /* read_ptr cannot be equal to write_ptr because at this point
2629 * we guaranteed to skip at least one element (before loop starts).
2630 */
2631 ptr::copy_nonoverlapping(read_ptr, write_ptr, 1);
2632
2633 /* We have filled that place, so go further */
2634 gap.write += 1;
2635 gap.read += 1;
2636 }
2637 }
2638
2639 /* Technically we could let `gap` clean up with its Drop, but
2640 * when `same_bucket` is guaranteed to not panic, this bloats a little
2641 * the codegen, so we just do it manually */
2642 gap.vec.set_len(gap.write);
2643 mem::forget(gap);
2644 }
2645 }
2646
2647 /// Appends an element and returns a reference to it if there is sufficient spare capacity,
2648 /// otherwise an error is returned with the element.
2649 ///
2650 /// Unlike [`push`] this method will not reallocate when there's insufficient capacity.
2651 /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity.
2652 ///
2653 /// [`push`]: Vec::push
2654 /// [`reserve`]: Vec::reserve
2655 /// [`try_reserve`]: Vec::try_reserve
2656 ///
2657 /// # Examples
2658 ///
2659 /// A manual, panic-free alternative to [`FromIterator`]:
2660 ///
2661 /// ```
2662 /// #![feature(vec_push_within_capacity)]
2663 ///
2664 /// use std::collections::TryReserveError;
2665 /// fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
2666 /// let mut vec = Vec::new();
2667 /// for value in iter {
2668 /// if let Err(value) = vec.push_within_capacity(value) {
2669 /// vec.try_reserve(1)?;
2670 /// // this cannot fail, the previous line either returned or added at least 1 free slot
2671 /// let _ = vec.push_within_capacity(value);
2672 /// }
2673 /// }
2674 /// Ok(vec)
2675 /// }
2676 /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
2677 /// ```
2678 ///
2679 /// # Time complexity
2680 ///
2681 /// Takes *O*(1) time.
2682 #[inline]
2683 #[unstable(feature = "vec_push_within_capacity", issue = "100486")]
2684 // #[unstable(feature = "push_mut", issue = "135974")]
2685 pub fn push_within_capacity(&mut self, value: T) -> Result<&mut T, T> {
2686 if self.len == self.buf.capacity() {
2687 return Err(value);
2688 }
2689
2690 unsafe {
2691 let end = self.as_mut_ptr().add(self.len);
2692 ptr::write(end, value);
2693 self.len += 1;
2694
2695 // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference.
2696 Ok(&mut *end)
2697 }
2698 }
2699
2700 /// Removes the last element from a vector and returns it, or [`None`] if it
2701 /// is empty.
2702 ///
2703 /// If you'd like to pop the first element, consider using
2704 /// [`VecDeque::pop_front`] instead.
2705 ///
2706 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2707 ///
2708 /// # Examples
2709 ///
2710 /// ```
2711 /// let mut vec = vec![1, 2, 3];
2712 /// assert_eq!(vec.pop(), Some(3));
2713 /// assert_eq!(vec, [1, 2]);
2714 /// ```
2715 ///
2716 /// # Time complexity
2717 ///
2718 /// Takes *O*(1) time.
2719 #[inline]
2720 #[stable(feature = "rust1", since = "1.0.0")]
2721 #[rustc_diagnostic_item = "vec_pop"]
2722 pub fn pop(&mut self) -> Option<T> {
2723 if self.len == 0 {
2724 None
2725 } else {
2726 unsafe {
2727 self.len -= 1;
2728 core::hint::assert_unchecked(self.len < self.capacity());
2729 Some(ptr::read(self.as_ptr().add(self.len())))
2730 }
2731 }
2732 }
2733
2734 /// Removes and returns the last element from a vector if the predicate
2735 /// returns `true`, or [`None`] if the predicate returns false or the vector
2736 /// is empty (the predicate will not be called in that case).
2737 ///
2738 /// # Examples
2739 ///
2740 /// ```
2741 /// let mut vec = vec![1, 2, 3, 4];
2742 /// let pred = |x: &mut i32| *x % 2 == 0;
2743 ///
2744 /// assert_eq!(vec.pop_if(pred), Some(4));
2745 /// assert_eq!(vec, [1, 2, 3]);
2746 /// assert_eq!(vec.pop_if(pred), None);
2747 /// ```
2748 #[stable(feature = "vec_pop_if", since = "1.86.0")]
2749 pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2750 let last = self.last_mut()?;
2751 if predicate(last) { self.pop() } else { None }
2752 }
2753
2754 /// Returns a mutable reference to the last item in the vector, or
2755 /// `None` if it is empty.
2756 ///
2757 /// # Examples
2758 ///
2759 /// Basic usage:
2760 ///
2761 /// ```
2762 /// #![feature(vec_peek_mut)]
2763 /// let mut vec = Vec::new();
2764 /// assert!(vec.peek_mut().is_none());
2765 ///
2766 /// vec.push(1);
2767 /// vec.push(5);
2768 /// vec.push(2);
2769 /// assert_eq!(vec.last(), Some(&2));
2770 /// if let Some(mut val) = vec.peek_mut() {
2771 /// *val = 0;
2772 /// }
2773 /// assert_eq!(vec.last(), Some(&0));
2774 /// ```
2775 #[inline]
2776 #[unstable(feature = "vec_peek_mut", issue = "122742")]
2777 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, A>> {
2778 PeekMut::new(self)
2779 }
2780
2781 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2782 ///
2783 /// # Panics
2784 ///
2785 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
2786 ///
2787 /// # Examples
2788 ///
2789 /// ```
2790 /// let mut vec = vec![1, 2, 3];
2791 /// let mut vec2 = vec![4, 5, 6];
2792 /// vec.append(&mut vec2);
2793 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
2794 /// assert_eq!(vec2, []);
2795 /// ```
2796 #[cfg(not(no_global_oom_handling))]
2797 #[inline]
2798 #[stable(feature = "append", since = "1.4.0")]
2799 pub fn append(&mut self, other: &mut Self) {
2800 unsafe {
2801 self.append_elements(other.as_slice() as _);
2802 other.set_len(0);
2803 }
2804 }
2805
2806 /// Appends elements to `self` from other buffer.
2807 #[cfg(not(no_global_oom_handling))]
2808 #[inline]
2809 unsafe fn append_elements(&mut self, other: *const [T]) {
2810 let count = other.len();
2811 self.reserve(count);
2812 let len = self.len();
2813 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
2814 self.len += count;
2815 }
2816
2817 /// Removes the subslice indicated by the given range from the vector,
2818 /// returning a double-ended iterator over the removed subslice.
2819 ///
2820 /// If the iterator is dropped before being fully consumed,
2821 /// it drops the remaining removed elements.
2822 ///
2823 /// The returned iterator keeps a mutable borrow on the vector to optimize
2824 /// its implementation.
2825 ///
2826 /// # Panics
2827 ///
2828 /// Panics if the range has `start_bound > end_bound`, or, if the range is
2829 /// bounded on either end and past the length of the vector.
2830 ///
2831 /// # Leaking
2832 ///
2833 /// If the returned iterator goes out of scope without being dropped (due to
2834 /// [`mem::forget`], for example), the vector may have lost and leaked
2835 /// elements arbitrarily, including elements outside the range.
2836 ///
2837 /// # Examples
2838 ///
2839 /// ```
2840 /// let mut v = vec![1, 2, 3];
2841 /// let u: Vec<_> = v.drain(1..).collect();
2842 /// assert_eq!(v, &[1]);
2843 /// assert_eq!(u, &[2, 3]);
2844 ///
2845 /// // A full range clears the vector, like `clear()` does
2846 /// v.drain(..);
2847 /// assert_eq!(v, &[]);
2848 /// ```
2849 #[stable(feature = "drain", since = "1.6.0")]
2850 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
2851 where
2852 R: RangeBounds<usize>,
2853 {
2854 // Memory safety
2855 //
2856 // When the Drain is first created, it shortens the length of
2857 // the source vector to make sure no uninitialized or moved-from elements
2858 // are accessible at all if the Drain's destructor never gets to run.
2859 //
2860 // Drain will ptr::read out the values to remove.
2861 // When finished, remaining tail of the vec is copied back to cover
2862 // the hole, and the vector length is restored to the new length.
2863 //
2864 let len = self.len();
2865 let Range { start, end } = slice::range(range, ..len);
2866
2867 unsafe {
2868 // set self.vec length's to start, to be safe in case Drain is leaked
2869 self.set_len(start);
2870 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
2871 Drain {
2872 tail_start: end,
2873 tail_len: len - end,
2874 iter: range_slice.iter(),
2875 vec: NonNull::from(self),
2876 }
2877 }
2878 }
2879
2880 /// Clears the vector, removing all values.
2881 ///
2882 /// Note that this method has no effect on the allocated capacity
2883 /// of the vector.
2884 ///
2885 /// # Examples
2886 ///
2887 /// ```
2888 /// let mut v = vec![1, 2, 3];
2889 ///
2890 /// v.clear();
2891 ///
2892 /// assert!(v.is_empty());
2893 /// ```
2894 #[inline]
2895 #[stable(feature = "rust1", since = "1.0.0")]
2896 pub fn clear(&mut self) {
2897 let elems: *mut [T] = self.as_mut_slice();
2898
2899 // SAFETY:
2900 // - `elems` comes directly from `as_mut_slice` and is therefore valid.
2901 // - Setting `self.len` before calling `drop_in_place` means that,
2902 // if an element's `Drop` impl panics, the vector's `Drop` impl will
2903 // do nothing (leaking the rest of the elements) instead of dropping
2904 // some twice.
2905 unsafe {
2906 self.len = 0;
2907 ptr::drop_in_place(elems);
2908 }
2909 }
2910
2911 /// Returns the number of elements in the vector, also referred to
2912 /// as its 'length'.
2913 ///
2914 /// # Examples
2915 ///
2916 /// ```
2917 /// let a = vec![1, 2, 3];
2918 /// assert_eq!(a.len(), 3);
2919 /// ```
2920 #[inline]
2921 #[stable(feature = "rust1", since = "1.0.0")]
2922 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
2923 #[rustc_confusables("length", "size")]
2924 pub const fn len(&self) -> usize {
2925 let len = self.len;
2926
2927 // SAFETY: The maximum capacity of `Vec<T>` is `isize::MAX` bytes, so the maximum value can
2928 // be returned is `usize::checked_div(size_of::<T>()).unwrap_or(usize::MAX)`, which
2929 // matches the definition of `T::MAX_SLICE_LEN`.
2930 unsafe { intrinsics::assume(len <= T::MAX_SLICE_LEN) };
2931
2932 len
2933 }
2934
2935 /// Returns `true` if the vector contains no elements.
2936 ///
2937 /// # Examples
2938 ///
2939 /// ```
2940 /// let mut v = Vec::new();
2941 /// assert!(v.is_empty());
2942 ///
2943 /// v.push(1);
2944 /// assert!(!v.is_empty());
2945 /// ```
2946 #[stable(feature = "rust1", since = "1.0.0")]
2947 #[rustc_diagnostic_item = "vec_is_empty"]
2948 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
2949 pub const fn is_empty(&self) -> bool {
2950 self.len() == 0
2951 }
2952
2953 /// Splits the collection into two at the given index.
2954 ///
2955 /// Returns a newly allocated vector containing the elements in the range
2956 /// `[at, len)`. After the call, the original vector will be left containing
2957 /// the elements `[0, at)` with its previous capacity unchanged.
2958 ///
2959 /// - If you want to take ownership of the entire contents and capacity of
2960 /// the vector, see [`mem::take`] or [`mem::replace`].
2961 /// - If you don't need the returned vector at all, see [`Vec::truncate`].
2962 /// - If you want to take ownership of an arbitrary subslice, or you don't
2963 /// necessarily want to store the removed items in a vector, see [`Vec::drain`].
2964 ///
2965 /// # Panics
2966 ///
2967 /// Panics if `at > len`.
2968 ///
2969 /// # Examples
2970 ///
2971 /// ```
2972 /// let mut vec = vec!['a', 'b', 'c'];
2973 /// let vec2 = vec.split_off(1);
2974 /// assert_eq!(vec, ['a']);
2975 /// assert_eq!(vec2, ['b', 'c']);
2976 /// ```
2977 #[cfg(not(no_global_oom_handling))]
2978 #[inline]
2979 #[must_use = "use `.truncate()` if you don't need the other half"]
2980 #[stable(feature = "split_off", since = "1.4.0")]
2981 #[track_caller]
2982 pub fn split_off(&mut self, at: usize) -> Self
2983 where
2984 A: Clone,
2985 {
2986 #[cold]
2987 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2988 #[track_caller]
2989 #[optimize(size)]
2990 fn assert_failed(at: usize, len: usize) -> ! {
2991 panic!("`at` split index (is {at}) should be <= len (is {len})");
2992 }
2993
2994 if at > self.len() {
2995 assert_failed(at, self.len());
2996 }
2997
2998 let other_len = self.len - at;
2999 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
3000
3001 // Unsafely `set_len` and copy items to `other`.
3002 unsafe {
3003 self.set_len(at);
3004 other.set_len(other_len);
3005
3006 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
3007 }
3008 other
3009 }
3010
3011 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
3012 ///
3013 /// If `new_len` is greater than `len`, the `Vec` is extended by the
3014 /// difference, with each additional slot filled with the result of
3015 /// calling the closure `f`. The return values from `f` will end up
3016 /// in the `Vec` in the order they have been generated.
3017 ///
3018 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
3019 ///
3020 /// This method uses a closure to create new values on every push. If
3021 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
3022 /// want to use the [`Default`] trait to generate values, you can
3023 /// pass [`Default::default`] as the second argument.
3024 ///
3025 /// # Panics
3026 ///
3027 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3028 ///
3029 /// # Examples
3030 ///
3031 /// ```
3032 /// let mut vec = vec![1, 2, 3];
3033 /// vec.resize_with(5, Default::default);
3034 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
3035 ///
3036 /// let mut vec = vec![];
3037 /// let mut p = 1;
3038 /// vec.resize_with(4, || { p *= 2; p });
3039 /// assert_eq!(vec, [2, 4, 8, 16]);
3040 /// ```
3041 #[cfg(not(no_global_oom_handling))]
3042 #[stable(feature = "vec_resize_with", since = "1.33.0")]
3043 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
3044 where
3045 F: FnMut() -> T,
3046 {
3047 let len = self.len();
3048 if new_len > len {
3049 self.extend_trusted(iter::repeat_with(f).take(new_len - len));
3050 } else {
3051 self.truncate(new_len);
3052 }
3053 }
3054
3055 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
3056 /// `&'a mut [T]`.
3057 ///
3058 /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
3059 /// has only static references, or none at all, then this may be chosen to be
3060 /// `'static`.
3061 ///
3062 /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
3063 /// so the leaked allocation may include unused capacity that is not part
3064 /// of the returned slice.
3065 ///
3066 /// This function is mainly useful for data that lives for the remainder of
3067 /// the program's life. Dropping the returned reference will cause a memory
3068 /// leak.
3069 ///
3070 /// # Examples
3071 ///
3072 /// Simple usage:
3073 ///
3074 /// ```
3075 /// let x = vec![1, 2, 3];
3076 /// let static_ref: &'static mut [usize] = x.leak();
3077 /// static_ref[0] += 1;
3078 /// assert_eq!(static_ref, &[2, 2, 3]);
3079 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
3080 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
3081 /// # drop(unsafe { Box::from_raw(static_ref) });
3082 /// ```
3083 #[stable(feature = "vec_leak", since = "1.47.0")]
3084 #[inline]
3085 pub fn leak<'a>(self) -> &'a mut [T]
3086 where
3087 A: 'a,
3088 {
3089 let mut me = ManuallyDrop::new(self);
3090 unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
3091 }
3092
3093 /// Returns the remaining spare capacity of the vector as a slice of
3094 /// `MaybeUninit<T>`.
3095 ///
3096 /// The returned slice can be used to fill the vector with data (e.g. by
3097 /// reading from a file) before marking the data as initialized using the
3098 /// [`set_len`] method.
3099 ///
3100 /// [`set_len`]: Vec::set_len
3101 ///
3102 /// # Examples
3103 ///
3104 /// ```
3105 /// // Allocate vector big enough for 10 elements.
3106 /// let mut v = Vec::with_capacity(10);
3107 ///
3108 /// // Fill in the first 3 elements.
3109 /// let uninit = v.spare_capacity_mut();
3110 /// uninit[0].write(0);
3111 /// uninit[1].write(1);
3112 /// uninit[2].write(2);
3113 ///
3114 /// // Mark the first 3 elements of the vector as being initialized.
3115 /// unsafe {
3116 /// v.set_len(3);
3117 /// }
3118 ///
3119 /// assert_eq!(&v, &[0, 1, 2]);
3120 /// ```
3121 #[stable(feature = "vec_spare_capacity", since = "1.60.0")]
3122 #[inline]
3123 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
3124 // Note:
3125 // This method is not implemented in terms of `split_at_spare_mut`,
3126 // to prevent invalidation of pointers to the buffer.
3127 unsafe {
3128 slice::from_raw_parts_mut(
3129 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
3130 self.buf.capacity() - self.len,
3131 )
3132 }
3133 }
3134
3135 /// Returns vector content as a slice of `T`, along with the remaining spare
3136 /// capacity of the vector as a slice of `MaybeUninit<T>`.
3137 ///
3138 /// The returned spare capacity slice can be used to fill the vector with data
3139 /// (e.g. by reading from a file) before marking the data as initialized using
3140 /// the [`set_len`] method.
3141 ///
3142 /// [`set_len`]: Vec::set_len
3143 ///
3144 /// Note that this is a low-level API, which should be used with care for
3145 /// optimization purposes. If you need to append data to a `Vec`
3146 /// you can use [`push`], [`extend`], [`extend_from_slice`],
3147 /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
3148 /// [`resize_with`], depending on your exact needs.
3149 ///
3150 /// [`push`]: Vec::push
3151 /// [`extend`]: Vec::extend
3152 /// [`extend_from_slice`]: Vec::extend_from_slice
3153 /// [`extend_from_within`]: Vec::extend_from_within
3154 /// [`insert`]: Vec::insert
3155 /// [`append`]: Vec::append
3156 /// [`resize`]: Vec::resize
3157 /// [`resize_with`]: Vec::resize_with
3158 ///
3159 /// # Examples
3160 ///
3161 /// ```
3162 /// #![feature(vec_split_at_spare)]
3163 ///
3164 /// let mut v = vec![1, 1, 2];
3165 ///
3166 /// // Reserve additional space big enough for 10 elements.
3167 /// v.reserve(10);
3168 ///
3169 /// let (init, uninit) = v.split_at_spare_mut();
3170 /// let sum = init.iter().copied().sum::<u32>();
3171 ///
3172 /// // Fill in the next 4 elements.
3173 /// uninit[0].write(sum);
3174 /// uninit[1].write(sum * 2);
3175 /// uninit[2].write(sum * 3);
3176 /// uninit[3].write(sum * 4);
3177 ///
3178 /// // Mark the 4 elements of the vector as being initialized.
3179 /// unsafe {
3180 /// let len = v.len();
3181 /// v.set_len(len + 4);
3182 /// }
3183 ///
3184 /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
3185 /// ```
3186 #[unstable(feature = "vec_split_at_spare", issue = "81944")]
3187 #[inline]
3188 pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
3189 // SAFETY:
3190 // - len is ignored and so never changed
3191 let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
3192 (init, spare)
3193 }
3194
3195 /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
3196 ///
3197 /// This method provides unique access to all vec parts at once in `extend_from_within`.
3198 unsafe fn split_at_spare_mut_with_len(
3199 &mut self,
3200 ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
3201 let ptr = self.as_mut_ptr();
3202 // SAFETY:
3203 // - `ptr` is guaranteed to be valid for `self.len` elements
3204 // - but the allocation extends out to `self.buf.capacity()` elements, possibly
3205 // uninitialized
3206 let spare_ptr = unsafe { ptr.add(self.len) };
3207 let spare_ptr = spare_ptr.cast_uninit();
3208 let spare_len = self.buf.capacity() - self.len;
3209
3210 // SAFETY:
3211 // - `ptr` is guaranteed to be valid for `self.len` elements
3212 // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
3213 unsafe {
3214 let initialized = slice::from_raw_parts_mut(ptr, self.len);
3215 let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
3216
3217 (initialized, spare, &mut self.len)
3218 }
3219 }
3220
3221 /// Groups every `N` elements in the `Vec<T>` into chunks to produce a `Vec<[T; N]>`, dropping
3222 /// elements in the remainder. `N` must be greater than zero.
3223 ///
3224 /// If the capacity is not a multiple of the chunk size, the buffer will shrink down to the
3225 /// nearest multiple with a reallocation or deallocation.
3226 ///
3227 /// This function can be used to reverse [`Vec::into_flattened`].
3228 ///
3229 /// # Examples
3230 ///
3231 /// ```
3232 /// #![feature(vec_into_chunks)]
3233 ///
3234 /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7];
3235 /// assert_eq!(vec.into_chunks::<3>(), [[0, 1, 2], [3, 4, 5]]);
3236 ///
3237 /// let vec = vec![0, 1, 2, 3];
3238 /// let chunks: Vec<[u8; 10]> = vec.into_chunks();
3239 /// assert!(chunks.is_empty());
3240 ///
3241 /// let flat = vec![0; 8 * 8 * 8];
3242 /// let reshaped: Vec<[[[u8; 8]; 8]; 8]> = flat.into_chunks().into_chunks().into_chunks();
3243 /// assert_eq!(reshaped.len(), 1);
3244 /// ```
3245 #[cfg(not(no_global_oom_handling))]
3246 #[unstable(feature = "vec_into_chunks", issue = "142137")]
3247 pub fn into_chunks<const N: usize>(mut self) -> Vec<[T; N], A> {
3248 const {
3249 assert!(N != 0, "chunk size must be greater than zero");
3250 }
3251
3252 let (len, cap) = (self.len(), self.capacity());
3253
3254 let len_remainder = len % N;
3255 if len_remainder != 0 {
3256 self.truncate(len - len_remainder);
3257 }
3258
3259 let cap_remainder = cap % N;
3260 if !T::IS_ZST && cap_remainder != 0 {
3261 self.buf.shrink_to_fit(cap - cap_remainder);
3262 }
3263
3264 let (ptr, _, _, alloc) = self.into_raw_parts_with_alloc();
3265
3266 // SAFETY:
3267 // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_alloc()`
3268 // - `[T; N]` has the same alignment as `T`
3269 // - `size_of::<[T; N]>() * cap / N == size_of::<T>() * cap`
3270 // - `len / N <= cap / N` because `len <= cap`
3271 // - the allocated memory consists of `len / N` valid values of type `[T; N]`
3272 // - `cap / N` fits the size of the allocated memory after shrinking
3273 unsafe { Vec::from_raw_parts_in(ptr.cast(), len / N, cap / N, alloc) }
3274 }
3275
3276 /// This clears out this `Vec` and recycles the allocation into a new `Vec`.
3277 /// The item type of the resulting `Vec` needs to have the same size and
3278 /// alignment as the item type of the original `Vec`.
3279 ///
3280 /// # Examples
3281 ///
3282 /// ```
3283 /// #![feature(vec_recycle, transmutability)]
3284 /// let a: Vec<u8> = vec![0; 100];
3285 /// let capacity = a.capacity();
3286 /// let addr = a.as_ptr().addr();
3287 /// let b: Vec<i8> = a.recycle();
3288 /// assert_eq!(b.len(), 0);
3289 /// assert_eq!(b.capacity(), capacity);
3290 /// assert_eq!(b.as_ptr().addr(), addr);
3291 /// ```
3292 ///
3293 /// The `Recyclable` bound prevents this method from being called when `T` and `U` have different sizes; e.g.:
3294 ///
3295 /// ```compile_fail,E0277
3296 /// #![feature(vec_recycle, transmutability)]
3297 /// let vec: Vec<[u8; 2]> = Vec::new();
3298 /// let _: Vec<[u8; 1]> = vec.recycle();
3299 /// ```
3300 /// ...or different alignments:
3301 ///
3302 /// ```compile_fail,E0277
3303 /// #![feature(vec_recycle, transmutability)]
3304 /// let vec: Vec<[u16; 0]> = Vec::new();
3305 /// let _: Vec<[u8; 0]> = vec.recycle();
3306 /// ```
3307 ///
3308 /// However, due to temporary implementation limitations of `Recyclable`,
3309 /// this method is not yet callable when `T` or `U` are slices, trait objects,
3310 /// or other exotic types; e.g.:
3311 ///
3312 /// ```compile_fail,E0277
3313 /// #![feature(vec_recycle, transmutability)]
3314 /// # let inputs = ["a b c", "d e f"];
3315 /// # fn process(_: &[&str]) {}
3316 /// let mut storage: Vec<&[&str]> = Vec::new();
3317 ///
3318 /// for input in inputs {
3319 /// let mut buffer: Vec<&str> = storage.recycle();
3320 /// buffer.extend(input.split(" "));
3321 /// process(&buffer);
3322 /// storage = buffer.recycle();
3323 /// }
3324 /// ```
3325 #[unstable(feature = "vec_recycle", issue = "148227")]
3326 #[expect(private_bounds)]
3327 pub fn recycle<U>(mut self) -> Vec<U, A>
3328 where
3329 U: Recyclable<T>,
3330 {
3331 self.clear();
3332 const {
3333 // FIXME(const-hack, 146097): compare `Layout`s
3334 assert!(size_of::<T>() == size_of::<U>());
3335 assert!(align_of::<T>() == align_of::<U>());
3336 };
3337 let (ptr, length, capacity, alloc) = self.into_parts_with_alloc();
3338 debug_assert_eq!(length, 0);
3339 // SAFETY:
3340 // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_alloc()`
3341 // - `T` & `U` have the same layout, so `capacity` does not need to be changed and we can safely use `alloc.dealloc` later
3342 // - the original vector was cleared, so there is no problem with "transmuting" the stored values
3343 unsafe { Vec::from_parts_in(ptr.cast::<U>(), length, capacity, alloc) }
3344 }
3345}
3346
3347/// Denotes that an allocation of `From` can be recycled into an allocation of `Self`.
3348///
3349/// # Safety
3350///
3351/// `Self` is `Recyclable<From>` if `Layout::new::<Self>() == Layout::new::<From>()`.
3352unsafe trait Recyclable<From: Sized>: Sized {}
3353
3354#[unstable_feature_bound(transmutability)]
3355// SAFETY: enforced by `TransmuteFrom`
3356unsafe impl<From, To> Recyclable<From> for To
3357where
3358 for<'a> &'a MaybeUninit<To>: TransmuteFrom<&'a MaybeUninit<From>, { Assume::SAFETY }>,
3359 for<'a> &'a MaybeUninit<From>: TransmuteFrom<&'a MaybeUninit<To>, { Assume::SAFETY }>,
3360{
3361}
3362
3363impl<T: Clone, A: Allocator> Vec<T, A> {
3364 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
3365 ///
3366 /// If `new_len` is greater than `len`, the `Vec` is extended by the
3367 /// difference, with each additional slot filled with `value`.
3368 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
3369 ///
3370 /// This method requires `T` to implement [`Clone`],
3371 /// in order to be able to clone the passed value.
3372 /// If you need more flexibility (or want to rely on [`Default`] instead of
3373 /// [`Clone`]), use [`Vec::resize_with`].
3374 /// If you only need to resize to a smaller size, use [`Vec::truncate`].
3375 ///
3376 /// # Panics
3377 ///
3378 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3379 ///
3380 /// # Examples
3381 ///
3382 /// ```
3383 /// let mut vec = vec!["hello"];
3384 /// vec.resize(3, "world");
3385 /// assert_eq!(vec, ["hello", "world", "world"]);
3386 ///
3387 /// let mut vec = vec!['a', 'b', 'c', 'd'];
3388 /// vec.resize(2, '_');
3389 /// assert_eq!(vec, ['a', 'b']);
3390 /// ```
3391 #[cfg(not(no_global_oom_handling))]
3392 #[stable(feature = "vec_resize", since = "1.5.0")]
3393 pub fn resize(&mut self, new_len: usize, value: T) {
3394 let len = self.len();
3395
3396 if new_len > len {
3397 self.extend_with(new_len - len, value)
3398 } else {
3399 self.truncate(new_len);
3400 }
3401 }
3402
3403 /// Clones and appends all elements in a slice to the `Vec`.
3404 ///
3405 /// Iterates over the slice `other`, clones each element, and then appends
3406 /// it to this `Vec`. The `other` slice is traversed in-order.
3407 ///
3408 /// Note that this function is the same as [`extend`],
3409 /// except that it also works with slice elements that are Clone but not Copy.
3410 /// If Rust gets specialization this function may be deprecated.
3411 ///
3412 /// # Panics
3413 ///
3414 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3415 ///
3416 /// # Examples
3417 ///
3418 /// ```
3419 /// let mut vec = vec![1];
3420 /// vec.extend_from_slice(&[2, 3, 4]);
3421 /// assert_eq!(vec, [1, 2, 3, 4]);
3422 /// ```
3423 ///
3424 /// [`extend`]: Vec::extend
3425 #[cfg(not(no_global_oom_handling))]
3426 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
3427 pub fn extend_from_slice(&mut self, other: &[T]) {
3428 self.spec_extend(other.iter())
3429 }
3430
3431 /// Given a range `src`, clones a slice of elements in that range and appends it to the end.
3432 ///
3433 /// `src` must be a range that can form a valid subslice of the `Vec`.
3434 ///
3435 /// # Panics
3436 ///
3437 /// Panics if starting index is greater than the end index, if the index is
3438 /// greater than the length of the vector, or if the new capacity exceeds
3439 /// `isize::MAX` _bytes_.
3440 ///
3441 /// # Examples
3442 ///
3443 /// ```
3444 /// let mut characters = vec!['a', 'b', 'c', 'd', 'e'];
3445 /// characters.extend_from_within(2..);
3446 /// assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
3447 ///
3448 /// let mut numbers = vec![0, 1, 2, 3, 4];
3449 /// numbers.extend_from_within(..2);
3450 /// assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
3451 ///
3452 /// let mut strings = vec![String::from("hello"), String::from("world"), String::from("!")];
3453 /// strings.extend_from_within(1..=2);
3454 /// assert_eq!(strings, ["hello", "world", "!", "world", "!"]);
3455 /// ```
3456 #[cfg(not(no_global_oom_handling))]
3457 #[stable(feature = "vec_extend_from_within", since = "1.53.0")]
3458 pub fn extend_from_within<R>(&mut self, src: R)
3459 where
3460 R: RangeBounds<usize>,
3461 {
3462 let range = slice::range(src, ..self.len());
3463 self.reserve(range.len());
3464
3465 // SAFETY:
3466 // - `slice::range` guarantees that the given range is valid for indexing self
3467 unsafe {
3468 self.spec_extend_from_within(range);
3469 }
3470 }
3471}
3472
3473impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
3474 /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
3475 ///
3476 /// # Panics
3477 ///
3478 /// Panics if the length of the resulting vector would overflow a `usize`.
3479 ///
3480 /// This is only possible when flattening a vector of arrays of zero-sized
3481 /// types, and thus tends to be irrelevant in practice. If
3482 /// `size_of::<T>() > 0`, this will never panic.
3483 ///
3484 /// # Examples
3485 ///
3486 /// ```
3487 /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
3488 /// assert_eq!(vec.pop(), Some([7, 8, 9]));
3489 ///
3490 /// let mut flattened = vec.into_flattened();
3491 /// assert_eq!(flattened.pop(), Some(6));
3492 /// ```
3493 #[stable(feature = "slice_flatten", since = "1.80.0")]
3494 pub fn into_flattened(self) -> Vec<T, A> {
3495 let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
3496 let (new_len, new_cap) = if T::IS_ZST {
3497 (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
3498 } else {
3499 // SAFETY:
3500 // - `cap * N` cannot overflow because the allocation is already in
3501 // the address space.
3502 // - Each `[T; N]` has `N` valid elements, so there are `len * N`
3503 // valid elements in the allocation.
3504 unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) }
3505 };
3506 // SAFETY:
3507 // - `ptr` was allocated by `self`
3508 // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
3509 // - `new_cap` refers to the same sized allocation as `cap` because
3510 // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
3511 // - `len` <= `cap`, so `len * N` <= `cap * N`.
3512 unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
3513 }
3514}
3515
3516impl<T: Clone, A: Allocator> Vec<T, A> {
3517 #[cfg(not(no_global_oom_handling))]
3518 /// Extend the vector by `n` clones of value.
3519 fn extend_with(&mut self, n: usize, value: T) {
3520 self.reserve(n);
3521
3522 unsafe {
3523 let mut ptr = self.as_mut_ptr().add(self.len());
3524 // Use SetLenOnDrop to work around bug where compiler
3525 // might not realize the store through `ptr` through self.set_len()
3526 // don't alias.
3527 let mut local_len = SetLenOnDrop::new(&mut self.len);
3528
3529 // Write all elements except the last one
3530 for _ in 1..n {
3531 ptr::write(ptr, value.clone());
3532 ptr = ptr.add(1);
3533 // Increment the length in every step in case clone() panics
3534 local_len.increment_len(1);
3535 }
3536
3537 if n > 0 {
3538 // We can write the last element directly without cloning needlessly
3539 ptr::write(ptr, value);
3540 local_len.increment_len(1);
3541 }
3542
3543 // len set by scope guard
3544 }
3545 }
3546}
3547
3548impl<T: PartialEq, A: Allocator> Vec<T, A> {
3549 /// Removes consecutive repeated elements in the vector according to the
3550 /// [`PartialEq`] trait implementation.
3551 ///
3552 /// If the vector is sorted, this removes all duplicates.
3553 ///
3554 /// # Examples
3555 ///
3556 /// ```
3557 /// let mut vec = vec![1, 2, 2, 3, 2];
3558 ///
3559 /// vec.dedup();
3560 ///
3561 /// assert_eq!(vec, [1, 2, 3, 2]);
3562 /// ```
3563 #[stable(feature = "rust1", since = "1.0.0")]
3564 #[inline]
3565 pub fn dedup(&mut self) {
3566 self.dedup_by(|a, b| a == b)
3567 }
3568}
3569
3570////////////////////////////////////////////////////////////////////////////////
3571// Internal methods and functions
3572////////////////////////////////////////////////////////////////////////////////
3573
3574#[doc(hidden)]
3575#[cfg(not(no_global_oom_handling))]
3576#[stable(feature = "rust1", since = "1.0.0")]
3577#[rustc_diagnostic_item = "vec_from_elem"]
3578pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
3579 <T as SpecFromElem>::from_elem(elem, n, Global)
3580}
3581
3582#[doc(hidden)]
3583#[cfg(not(no_global_oom_handling))]
3584#[unstable(feature = "allocator_api", issue = "32838")]
3585pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
3586 <T as SpecFromElem>::from_elem(elem, n, alloc)
3587}
3588
3589#[cfg(not(no_global_oom_handling))]
3590trait ExtendFromWithinSpec {
3591 /// # Safety
3592 ///
3593 /// - `src` needs to be valid index
3594 /// - `self.capacity() - self.len()` must be `>= src.len()`
3595 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
3596}
3597
3598#[cfg(not(no_global_oom_handling))]
3599impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3600 default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3601 // SAFETY:
3602 // - len is increased only after initializing elements
3603 let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
3604
3605 // SAFETY:
3606 // - caller guarantees that src is a valid index
3607 let to_clone = unsafe { this.get_unchecked(src) };
3608
3609 iter::zip(to_clone, spare)
3610 .map(|(src, dst)| dst.write(src.clone()))
3611 // Note:
3612 // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
3613 // - len is increased after each element to prevent leaks (see issue #82533)
3614 .for_each(|_| *len += 1);
3615 }
3616}
3617
3618#[cfg(not(no_global_oom_handling))]
3619impl<T: TrivialClone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3620 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3621 let count = src.len();
3622 {
3623 let (init, spare) = self.split_at_spare_mut();
3624
3625 // SAFETY:
3626 // - caller guarantees that `src` is a valid index
3627 let source = unsafe { init.get_unchecked(src) };
3628
3629 // SAFETY:
3630 // - Both pointers are created from unique slice references (`&mut [_]`)
3631 // so they are valid and do not overlap.
3632 // - Elements implement `TrivialClone` so this is equivalent to calling
3633 // `clone` on every one of them.
3634 // - `count` is equal to the len of `source`, so source is valid for
3635 // `count` reads
3636 // - `.reserve(count)` guarantees that `spare.len() >= count` so spare
3637 // is valid for `count` writes
3638 unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
3639 }
3640
3641 // SAFETY:
3642 // - The elements were just initialized by `copy_nonoverlapping`
3643 self.len += count;
3644 }
3645}
3646
3647////////////////////////////////////////////////////////////////////////////////
3648// Common trait implementations for Vec
3649////////////////////////////////////////////////////////////////////////////////
3650
3651#[stable(feature = "rust1", since = "1.0.0")]
3652impl<T, A: Allocator> ops::Deref for Vec<T, A> {
3653 type Target = [T];
3654
3655 #[inline]
3656 fn deref(&self) -> &[T] {
3657 self.as_slice()
3658 }
3659}
3660
3661#[stable(feature = "rust1", since = "1.0.0")]
3662impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
3663 #[inline]
3664 fn deref_mut(&mut self) -> &mut [T] {
3665 self.as_mut_slice()
3666 }
3667}
3668
3669#[unstable(feature = "deref_pure_trait", issue = "87121")]
3670unsafe impl<T, A: Allocator> ops::DerefPure for Vec<T, A> {}
3671
3672#[cfg(not(no_global_oom_handling))]
3673#[stable(feature = "rust1", since = "1.0.0")]
3674impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
3675 fn clone(&self) -> Self {
3676 let alloc = self.allocator().clone();
3677 <[T]>::to_vec_in(&**self, alloc)
3678 }
3679
3680 /// Overwrites the contents of `self` with a clone of the contents of `source`.
3681 ///
3682 /// This method is preferred over simply assigning `source.clone()` to `self`,
3683 /// as it avoids reallocation if possible. Additionally, if the element type
3684 /// `T` overrides `clone_from()`, this will reuse the resources of `self`'s
3685 /// elements as well.
3686 ///
3687 /// # Examples
3688 ///
3689 /// ```
3690 /// let x = vec![5, 6, 7];
3691 /// let mut y = vec![8, 9, 10];
3692 /// let yp: *const i32 = y.as_ptr();
3693 ///
3694 /// y.clone_from(&x);
3695 ///
3696 /// // The value is the same
3697 /// assert_eq!(x, y);
3698 ///
3699 /// // And no reallocation occurred
3700 /// assert_eq!(yp, y.as_ptr());
3701 /// ```
3702 fn clone_from(&mut self, source: &Self) {
3703 crate::slice::SpecCloneIntoVec::clone_into(source.as_slice(), self);
3704 }
3705}
3706
3707/// The hash of a vector is the same as that of the corresponding slice,
3708/// as required by the `core::borrow::Borrow` implementation.
3709///
3710/// ```
3711/// use std::hash::BuildHasher;
3712///
3713/// let b = std::hash::RandomState::new();
3714/// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
3715/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
3716/// assert_eq!(b.hash_one(v), b.hash_one(s));
3717/// ```
3718#[stable(feature = "rust1", since = "1.0.0")]
3719impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
3720 #[inline]
3721 fn hash<H: Hasher>(&self, state: &mut H) {
3722 Hash::hash(&**self, state)
3723 }
3724}
3725
3726#[stable(feature = "rust1", since = "1.0.0")]
3727impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
3728 type Output = I::Output;
3729
3730 #[inline]
3731 fn index(&self, index: I) -> &Self::Output {
3732 Index::index(&**self, index)
3733 }
3734}
3735
3736#[stable(feature = "rust1", since = "1.0.0")]
3737impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
3738 #[inline]
3739 fn index_mut(&mut self, index: I) -> &mut Self::Output {
3740 IndexMut::index_mut(&mut **self, index)
3741 }
3742}
3743
3744/// Collects an iterator into a Vec, commonly called via [`Iterator::collect()`]
3745///
3746/// # Allocation behavior
3747///
3748/// In general `Vec` does not guarantee any particular growth or allocation strategy.
3749/// That also applies to this trait impl.
3750///
3751/// **Note:** This section covers implementation details and is therefore exempt from
3752/// stability guarantees.
3753///
3754/// Vec may use any or none of the following strategies,
3755/// depending on the supplied iterator:
3756///
3757/// * preallocate based on [`Iterator::size_hint()`]
3758/// * and panic if the number of items is outside the provided lower/upper bounds
3759/// * use an amortized growth strategy similar to `pushing` one item at a time
3760/// * perform the iteration in-place on the original allocation backing the iterator
3761///
3762/// The last case warrants some attention. It is an optimization that in many cases reduces peak memory
3763/// consumption and improves cache locality. But when big, short-lived allocations are created,
3764/// only a small fraction of their items get collected, no further use is made of the spare capacity
3765/// and the resulting `Vec` is moved into a longer-lived structure, then this can lead to the large
3766/// allocations having their lifetimes unnecessarily extended which can result in increased memory
3767/// footprint.
3768///
3769/// In cases where this is an issue, the excess capacity can be discarded with [`Vec::shrink_to()`],
3770/// [`Vec::shrink_to_fit()`] or by collecting into [`Box<[T]>`][owned slice] instead, which additionally reduces
3771/// the size of the long-lived struct.
3772///
3773/// [owned slice]: Box
3774///
3775/// ```rust
3776/// # use std::sync::Mutex;
3777/// static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());
3778///
3779/// for i in 0..10 {
3780/// let big_temporary: Vec<u16> = (0..1024).collect();
3781/// // discard most items
3782/// let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect();
3783/// // without this a lot of unused capacity might be moved into the global
3784/// result.shrink_to_fit();
3785/// LONG_LIVED.lock().unwrap().push(result);
3786/// }
3787/// ```
3788#[cfg(not(no_global_oom_handling))]
3789#[stable(feature = "rust1", since = "1.0.0")]
3790impl<T> FromIterator<T> for Vec<T> {
3791 #[inline]
3792 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
3793 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
3794 }
3795}
3796
3797#[stable(feature = "rust1", since = "1.0.0")]
3798impl<T, A: Allocator> IntoIterator for Vec<T, A> {
3799 type Item = T;
3800 type IntoIter = IntoIter<T, A>;
3801
3802 /// Creates a consuming iterator, that is, one that moves each value out of
3803 /// the vector (from start to end). The vector cannot be used after calling
3804 /// this.
3805 ///
3806 /// # Examples
3807 ///
3808 /// ```
3809 /// let v = vec!["a".to_string(), "b".to_string()];
3810 /// let mut v_iter = v.into_iter();
3811 ///
3812 /// let first_element: Option<String> = v_iter.next();
3813 ///
3814 /// assert_eq!(first_element, Some("a".to_string()));
3815 /// assert_eq!(v_iter.next(), Some("b".to_string()));
3816 /// assert_eq!(v_iter.next(), None);
3817 /// ```
3818 #[inline]
3819 fn into_iter(self) -> Self::IntoIter {
3820 unsafe {
3821 let me = ManuallyDrop::new(self);
3822 let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
3823 let buf = me.buf.non_null();
3824 let begin = buf.as_ptr();
3825 let end = if T::IS_ZST {
3826 begin.wrapping_byte_add(me.len())
3827 } else {
3828 begin.add(me.len()) as *const T
3829 };
3830 let cap = me.buf.capacity();
3831 IntoIter { buf, phantom: PhantomData, cap, alloc, ptr: buf, end }
3832 }
3833 }
3834}
3835
3836#[stable(feature = "rust1", since = "1.0.0")]
3837impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
3838 type Item = &'a T;
3839 type IntoIter = slice::Iter<'a, T>;
3840
3841 fn into_iter(self) -> Self::IntoIter {
3842 self.iter()
3843 }
3844}
3845
3846#[stable(feature = "rust1", since = "1.0.0")]
3847impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
3848 type Item = &'a mut T;
3849 type IntoIter = slice::IterMut<'a, T>;
3850
3851 fn into_iter(self) -> Self::IntoIter {
3852 self.iter_mut()
3853 }
3854}
3855
3856#[cfg(not(no_global_oom_handling))]
3857#[stable(feature = "rust1", since = "1.0.0")]
3858impl<T, A: Allocator> Extend<T> for Vec<T, A> {
3859 #[inline]
3860 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
3861 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
3862 }
3863
3864 #[inline]
3865 fn extend_one(&mut self, item: T) {
3866 self.push(item);
3867 }
3868
3869 #[inline]
3870 fn extend_reserve(&mut self, additional: usize) {
3871 self.reserve(additional);
3872 }
3873
3874 #[inline]
3875 unsafe fn extend_one_unchecked(&mut self, item: T) {
3876 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
3877 unsafe {
3878 let len = self.len();
3879 ptr::write(self.as_mut_ptr().add(len), item);
3880 self.set_len(len + 1);
3881 }
3882 }
3883}
3884
3885impl<T, A: Allocator> Vec<T, A> {
3886 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
3887 // they have no further optimizations to apply
3888 #[cfg(not(no_global_oom_handling))]
3889 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
3890 // This is the case for a general iterator.
3891 //
3892 // This function should be the moral equivalent of:
3893 //
3894 // for item in iterator {
3895 // self.push(item);
3896 // }
3897 while let Some(element) = iterator.next() {
3898 let len = self.len();
3899 if len == self.capacity() {
3900 let (lower, _) = iterator.size_hint();
3901 self.reserve(lower.saturating_add(1));
3902 }
3903 unsafe {
3904 ptr::write(self.as_mut_ptr().add(len), element);
3905 // Since next() executes user code which can panic we have to bump the length
3906 // after each step.
3907 // NB can't overflow since we would have had to alloc the address space
3908 self.set_len(len + 1);
3909 }
3910 }
3911 }
3912
3913 // specific extend for `TrustedLen` iterators, called both by the specializations
3914 // and internal places where resolving specialization makes compilation slower
3915 #[cfg(not(no_global_oom_handling))]
3916 fn extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) {
3917 let (low, high) = iterator.size_hint();
3918 if let Some(additional) = high {
3919 debug_assert_eq!(
3920 low,
3921 additional,
3922 "TrustedLen iterator's size hint is not exact: {:?}",
3923 (low, high)
3924 );
3925 self.reserve(additional);
3926 unsafe {
3927 let ptr = self.as_mut_ptr();
3928 let mut local_len = SetLenOnDrop::new(&mut self.len);
3929 iterator.for_each(move |element| {
3930 ptr::write(ptr.add(local_len.current_len()), element);
3931 // Since the loop executes user code which can panic we have to update
3932 // the length every step to correctly drop what we've written.
3933 // NB can't overflow since we would have had to alloc the address space
3934 local_len.increment_len(1);
3935 });
3936 }
3937 } else {
3938 // Per TrustedLen contract a `None` upper bound means that the iterator length
3939 // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
3940 // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
3941 // This avoids additional codegen for a fallback code path which would eventually
3942 // panic anyway.
3943 panic!("capacity overflow");
3944 }
3945 }
3946
3947 /// Creates a splicing iterator that replaces the specified range in the vector
3948 /// with the given `replace_with` iterator and yields the removed items.
3949 /// `replace_with` does not need to be the same length as `range`.
3950 ///
3951 /// `range` is removed even if the `Splice` iterator is not consumed before it is dropped.
3952 ///
3953 /// It is unspecified how many elements are removed from the vector
3954 /// if the `Splice` value is leaked.
3955 ///
3956 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
3957 ///
3958 /// This is optimal if:
3959 ///
3960 /// * The tail (elements in the vector after `range`) is empty,
3961 /// * or `replace_with` yields fewer or equal elements than `range`'s length
3962 /// * or the lower bound of its `size_hint()` is exact.
3963 ///
3964 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
3965 ///
3966 /// # Panics
3967 ///
3968 /// Panics if the range has `start_bound > end_bound`, or, if the range is
3969 /// bounded on either end and past the length of the vector.
3970 ///
3971 /// # Examples
3972 ///
3973 /// ```
3974 /// let mut v = vec![1, 2, 3, 4];
3975 /// let new = [7, 8, 9];
3976 /// let u: Vec<_> = v.splice(1..3, new).collect();
3977 /// assert_eq!(v, [1, 7, 8, 9, 4]);
3978 /// assert_eq!(u, [2, 3]);
3979 /// ```
3980 ///
3981 /// Using `splice` to insert new items into a vector efficiently at a specific position
3982 /// indicated by an empty range:
3983 ///
3984 /// ```
3985 /// let mut v = vec![1, 5];
3986 /// let new = [2, 3, 4];
3987 /// v.splice(1..1, new);
3988 /// assert_eq!(v, [1, 2, 3, 4, 5]);
3989 /// ```
3990 #[cfg(not(no_global_oom_handling))]
3991 #[inline]
3992 #[stable(feature = "vec_splice", since = "1.21.0")]
3993 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
3994 where
3995 R: RangeBounds<usize>,
3996 I: IntoIterator<Item = T>,
3997 {
3998 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
3999 }
4000
4001 /// Creates an iterator which uses a closure to determine if an element in the range should be removed.
4002 ///
4003 /// If the closure returns `true`, the element is removed from the vector
4004 /// and yielded. If the closure returns `false`, or panics, the element
4005 /// remains in the vector and will not be yielded.
4006 ///
4007 /// Only elements that fall in the provided range are considered for extraction, but any elements
4008 /// after the range will still have to be moved if any element has been extracted.
4009 ///
4010 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
4011 /// or the iteration short-circuits, then the remaining elements will be retained.
4012 /// Use `extract_if().for_each(drop)` if you do not need the returned iterator,
4013 /// or [`retain_mut`] with a negated predicate if you also do not need to restrict the range.
4014 ///
4015 /// [`retain_mut`]: Vec::retain_mut
4016 ///
4017 /// Using this method is equivalent to the following code:
4018 ///
4019 /// ```
4020 /// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
4021 /// # let mut vec = vec![0, 1, 2, 3, 4, 5, 6];
4022 /// # let mut vec2 = vec.clone();
4023 /// # let range = 1..5;
4024 /// let mut i = range.start;
4025 /// let end_items = vec.len() - range.end;
4026 /// # let mut extracted = vec![];
4027 ///
4028 /// while i < vec.len() - end_items {
4029 /// if some_predicate(&mut vec[i]) {
4030 /// let val = vec.remove(i);
4031 /// // your code here
4032 /// # extracted.push(val);
4033 /// } else {
4034 /// i += 1;
4035 /// }
4036 /// }
4037 ///
4038 /// # let extracted2: Vec<_> = vec2.extract_if(range, some_predicate).collect();
4039 /// # assert_eq!(vec, vec2);
4040 /// # assert_eq!(extracted, extracted2);
4041 /// ```
4042 ///
4043 /// But `extract_if` is easier to use. `extract_if` is also more efficient,
4044 /// because it can backshift the elements of the array in bulk.
4045 ///
4046 /// The iterator also lets you mutate the value of each element in the
4047 /// closure, regardless of whether you choose to keep or remove it.
4048 ///
4049 /// # Panics
4050 ///
4051 /// If `range` is out of bounds.
4052 ///
4053 /// # Examples
4054 ///
4055 /// Splitting a vector into even and odd values, reusing the original vector:
4056 ///
4057 /// ```
4058 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
4059 ///
4060 /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<Vec<_>>();
4061 /// let odds = numbers;
4062 ///
4063 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
4064 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
4065 /// ```
4066 ///
4067 /// Using the range argument to only process a part of the vector:
4068 ///
4069 /// ```
4070 /// let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2];
4071 /// let ones = items.extract_if(7.., |x| *x == 1).collect::<Vec<_>>();
4072 /// assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]);
4073 /// assert_eq!(ones.len(), 3);
4074 /// ```
4075 #[stable(feature = "extract_if", since = "1.87.0")]
4076 pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A>
4077 where
4078 F: FnMut(&mut T) -> bool,
4079 R: RangeBounds<usize>,
4080 {
4081 ExtractIf::new(self, filter, range)
4082 }
4083}
4084
4085/// Extend implementation that copies elements out of references before pushing them onto the Vec.
4086///
4087/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
4088/// append the entire slice at once.
4089///
4090/// [`copy_from_slice`]: slice::copy_from_slice
4091#[cfg(not(no_global_oom_handling))]
4092#[stable(feature = "extend_ref", since = "1.2.0")]
4093impl<'a, T: Copy + 'a, A: Allocator> Extend<&'a T> for Vec<T, A> {
4094 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
4095 self.spec_extend(iter.into_iter())
4096 }
4097
4098 #[inline]
4099 fn extend_one(&mut self, &item: &'a T) {
4100 self.push(item);
4101 }
4102
4103 #[inline]
4104 fn extend_reserve(&mut self, additional: usize) {
4105 self.reserve(additional);
4106 }
4107
4108 #[inline]
4109 unsafe fn extend_one_unchecked(&mut self, &item: &'a T) {
4110 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
4111 unsafe {
4112 let len = self.len();
4113 ptr::write(self.as_mut_ptr().add(len), item);
4114 self.set_len(len + 1);
4115 }
4116 }
4117}
4118
4119/// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison).
4120#[stable(feature = "rust1", since = "1.0.0")]
4121impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1>
4122where
4123 T: PartialOrd,
4124 A1: Allocator,
4125 A2: Allocator,
4126{
4127 #[inline]
4128 fn partial_cmp(&self, other: &Vec<T, A2>) -> Option<Ordering> {
4129 PartialOrd::partial_cmp(&**self, &**other)
4130 }
4131}
4132
4133#[stable(feature = "rust1", since = "1.0.0")]
4134impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
4135
4136/// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison).
4137#[stable(feature = "rust1", since = "1.0.0")]
4138impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
4139 #[inline]
4140 fn cmp(&self, other: &Self) -> Ordering {
4141 Ord::cmp(&**self, &**other)
4142 }
4143}
4144
4145#[stable(feature = "rust1", since = "1.0.0")]
4146unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
4147 fn drop(&mut self) {
4148 unsafe {
4149 // use drop for [T]
4150 // use a raw slice to refer to the elements of the vector as weakest necessary type;
4151 // could avoid questions of validity in certain cases
4152 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
4153 }
4154 // RawVec handles deallocation
4155 }
4156}
4157
4158#[stable(feature = "rust1", since = "1.0.0")]
4159#[rustc_const_unstable(feature = "const_default", issue = "143894")]
4160impl<T> const Default for Vec<T> {
4161 /// Creates an empty `Vec<T>`.
4162 ///
4163 /// The vector will not allocate until elements are pushed onto it.
4164 fn default() -> Vec<T> {
4165 Vec::new()
4166 }
4167}
4168
4169#[stable(feature = "rust1", since = "1.0.0")]
4170impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
4171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4172 fmt::Debug::fmt(&**self, f)
4173 }
4174}
4175
4176#[stable(feature = "rust1", since = "1.0.0")]
4177impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
4178 fn as_ref(&self) -> &Vec<T, A> {
4179 self
4180 }
4181}
4182
4183#[stable(feature = "vec_as_mut", since = "1.5.0")]
4184impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
4185 fn as_mut(&mut self) -> &mut Vec<T, A> {
4186 self
4187 }
4188}
4189
4190#[stable(feature = "rust1", since = "1.0.0")]
4191impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
4192 fn as_ref(&self) -> &[T] {
4193 self
4194 }
4195}
4196
4197#[stable(feature = "vec_as_mut", since = "1.5.0")]
4198impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
4199 fn as_mut(&mut self) -> &mut [T] {
4200 self
4201 }
4202}
4203
4204#[cfg(not(no_global_oom_handling))]
4205#[stable(feature = "rust1", since = "1.0.0")]
4206impl<T: Clone> From<&[T]> for Vec<T> {
4207 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4208 ///
4209 /// # Examples
4210 ///
4211 /// ```
4212 /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
4213 /// ```
4214 fn from(s: &[T]) -> Vec<T> {
4215 s.to_vec()
4216 }
4217}
4218
4219#[cfg(not(no_global_oom_handling))]
4220#[stable(feature = "vec_from_mut", since = "1.19.0")]
4221impl<T: Clone> From<&mut [T]> for Vec<T> {
4222 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4223 ///
4224 /// # Examples
4225 ///
4226 /// ```
4227 /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
4228 /// ```
4229 fn from(s: &mut [T]) -> Vec<T> {
4230 s.to_vec()
4231 }
4232}
4233
4234#[cfg(not(no_global_oom_handling))]
4235#[stable(feature = "vec_from_array_ref", since = "1.74.0")]
4236impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T> {
4237 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4238 ///
4239 /// # Examples
4240 ///
4241 /// ```
4242 /// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);
4243 /// ```
4244 fn from(s: &[T; N]) -> Vec<T> {
4245 Self::from(s.as_slice())
4246 }
4247}
4248
4249#[cfg(not(no_global_oom_handling))]
4250#[stable(feature = "vec_from_array_ref", since = "1.74.0")]
4251impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T> {
4252 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4253 ///
4254 /// # Examples
4255 ///
4256 /// ```
4257 /// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
4258 /// ```
4259 fn from(s: &mut [T; N]) -> Vec<T> {
4260 Self::from(s.as_mut_slice())
4261 }
4262}
4263
4264#[cfg(not(no_global_oom_handling))]
4265#[stable(feature = "vec_from_array", since = "1.44.0")]
4266impl<T, const N: usize> From<[T; N]> for Vec<T> {
4267 /// Allocates a `Vec<T>` and moves `s`'s items into it.
4268 ///
4269 /// # Examples
4270 ///
4271 /// ```
4272 /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
4273 /// ```
4274 fn from(s: [T; N]) -> Vec<T> {
4275 <[T]>::into_vec(Box::new(s))
4276 }
4277}
4278
4279#[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
4280impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
4281where
4282 [T]: ToOwned<Owned = Vec<T>>,
4283{
4284 /// Converts a clone-on-write slice into a vector.
4285 ///
4286 /// If `s` already owns a `Vec<T>`, it will be returned directly.
4287 /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and
4288 /// filled by cloning `s`'s items into it.
4289 ///
4290 /// # Examples
4291 ///
4292 /// ```
4293 /// # use std::borrow::Cow;
4294 /// let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);
4295 /// let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);
4296 /// assert_eq!(Vec::from(o), Vec::from(b));
4297 /// ```
4298 fn from(s: Cow<'a, [T]>) -> Vec<T> {
4299 s.into_owned()
4300 }
4301}
4302
4303// note: test pulls in std, which causes errors here
4304#[stable(feature = "vec_from_box", since = "1.18.0")]
4305impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
4306 /// Converts a boxed slice into a vector by transferring ownership of
4307 /// the existing heap allocation.
4308 ///
4309 /// # Examples
4310 ///
4311 /// ```
4312 /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
4313 /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
4314 /// ```
4315 fn from(s: Box<[T], A>) -> Self {
4316 s.into_vec()
4317 }
4318}
4319
4320// note: test pulls in std, which causes errors here
4321#[cfg(not(no_global_oom_handling))]
4322#[stable(feature = "box_from_vec", since = "1.20.0")]
4323impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
4324 /// Converts a vector into a boxed slice.
4325 ///
4326 /// Before doing the conversion, this method discards excess capacity like [`Vec::shrink_to_fit`].
4327 ///
4328 /// [owned slice]: Box
4329 /// [`Vec::shrink_to_fit`]: Vec::shrink_to_fit
4330 ///
4331 /// # Examples
4332 ///
4333 /// ```
4334 /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
4335 /// ```
4336 ///
4337 /// Any excess capacity is removed:
4338 /// ```
4339 /// let mut vec = Vec::with_capacity(10);
4340 /// vec.extend([1, 2, 3]);
4341 ///
4342 /// assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice());
4343 /// ```
4344 fn from(v: Vec<T, A>) -> Self {
4345 v.into_boxed_slice()
4346 }
4347}
4348
4349#[cfg(not(no_global_oom_handling))]
4350#[stable(feature = "rust1", since = "1.0.0")]
4351impl From<&str> for Vec<u8> {
4352 /// Allocates a `Vec<u8>` and fills it with a UTF-8 string.
4353 ///
4354 /// # Examples
4355 ///
4356 /// ```
4357 /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
4358 /// ```
4359 fn from(s: &str) -> Vec<u8> {
4360 From::from(s.as_bytes())
4361 }
4362}
4363
4364#[stable(feature = "array_try_from_vec", since = "1.48.0")]
4365impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
4366 type Error = Vec<T, A>;
4367
4368 /// Gets the entire contents of the `Vec<T>` as an array,
4369 /// if its size exactly matches that of the requested array.
4370 ///
4371 /// # Examples
4372 ///
4373 /// ```
4374 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
4375 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
4376 /// ```
4377 ///
4378 /// If the length doesn't match, the input comes back in `Err`:
4379 /// ```
4380 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
4381 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
4382 /// ```
4383 ///
4384 /// If you're fine with just getting a prefix of the `Vec<T>`,
4385 /// you can call [`.truncate(N)`](Vec::truncate) first.
4386 /// ```
4387 /// let mut v = String::from("hello world").into_bytes();
4388 /// v.sort();
4389 /// v.truncate(2);
4390 /// let [a, b]: [_; 2] = v.try_into().unwrap();
4391 /// assert_eq!(a, b' ');
4392 /// assert_eq!(b, b'd');
4393 /// ```
4394 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
4395 if vec.len() != N {
4396 return Err(vec);
4397 }
4398
4399 // SAFETY: `.set_len(0)` is always sound.
4400 unsafe { vec.set_len(0) };
4401
4402 // SAFETY: A `Vec`'s pointer is always aligned properly, and
4403 // the alignment the array needs is the same as the items.
4404 // We checked earlier that we have sufficient items.
4405 // The items will not double-drop as the `set_len`
4406 // tells the `Vec` not to also drop them.
4407 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
4408 Ok(array)
4409 }
4410}