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