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