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