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