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 and returns a reference to it if there is sufficient spare capacity,
2568 /// otherwise an error is returned 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 // #[unstable(feature = "push_mut", issue = "135974")]
2605 pub fn push_within_capacity(&mut self, value: T) -> Result<&mut T, T> {
2606 if self.len == self.buf.capacity() {
2607 return Err(value);
2608 }
2609
2610 unsafe {
2611 let end = self.as_mut_ptr().add(self.len);
2612 ptr::write(end, value);
2613 self.len += 1;
2614
2615 // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference.
2616 Ok(&mut *end)
2617 }
2618 }
2619
2620 /// Appends an element to the back of a collection, returning a reference to it.
2621 ///
2622 /// # Panics
2623 ///
2624 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
2625 ///
2626 /// # Examples
2627 ///
2628 /// ```
2629 /// #![feature(push_mut)]
2630 ///
2631 ///
2632 /// let mut vec = vec![1, 2];
2633 /// let last = vec.push_mut(3);
2634 /// assert_eq!(*last, 3);
2635 /// assert_eq!(vec, [1, 2, 3]);
2636 ///
2637 /// let last = vec.push_mut(3);
2638 /// *last += 1;
2639 /// assert_eq!(vec, [1, 2, 3, 4]);
2640 /// ```
2641 ///
2642 /// # Time complexity
2643 ///
2644 /// Takes amortized *O*(1) time. If the vector's length would exceed its
2645 /// capacity after the push, *O*(*capacity*) time is taken to copy the
2646 /// vector's elements to a larger allocation. This expensive operation is
2647 /// offset by the *capacity* *O*(1) insertions it allows.
2648 #[cfg(not(no_global_oom_handling))]
2649 #[inline]
2650 #[unstable(feature = "push_mut", issue = "135974")]
2651 #[must_use = "if you don't need a reference to the value, use `Vec::push` instead"]
2652 pub fn push_mut(&mut self, value: T) -> &mut T {
2653 // Inform codegen that the length does not change across grow_one().
2654 let len = self.len;
2655 // This will panic or abort if we would allocate > isize::MAX bytes
2656 // or if the length increment would overflow for zero-sized types.
2657 if len == self.buf.capacity() {
2658 self.buf.grow_one();
2659 }
2660 unsafe {
2661 let end = self.as_mut_ptr().add(len);
2662 ptr::write(end, value);
2663 self.len = len + 1;
2664 // SAFETY: We just wrote a value to the pointer that will live the lifetime of the reference.
2665 &mut *end
2666 }
2667 }
2668
2669 /// Removes the last element from a vector and returns it, or [`None`] if it
2670 /// is empty.
2671 ///
2672 /// If you'd like to pop the first element, consider using
2673 /// [`VecDeque::pop_front`] instead.
2674 ///
2675 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2676 ///
2677 /// # Examples
2678 ///
2679 /// ```
2680 /// let mut vec = vec![1, 2, 3];
2681 /// assert_eq!(vec.pop(), Some(3));
2682 /// assert_eq!(vec, [1, 2]);
2683 /// ```
2684 ///
2685 /// # Time complexity
2686 ///
2687 /// Takes *O*(1) time.
2688 #[inline]
2689 #[stable(feature = "rust1", since = "1.0.0")]
2690 #[rustc_diagnostic_item = "vec_pop"]
2691 pub fn pop(&mut self) -> Option<T> {
2692 if self.len == 0 {
2693 None
2694 } else {
2695 unsafe {
2696 self.len -= 1;
2697 core::hint::assert_unchecked(self.len < self.capacity());
2698 Some(ptr::read(self.as_ptr().add(self.len())))
2699 }
2700 }
2701 }
2702
2703 /// Removes and returns the last element from a vector if the predicate
2704 /// returns `true`, or [`None`] if the predicate returns false or the vector
2705 /// is empty (the predicate will not be called in that case).
2706 ///
2707 /// # Examples
2708 ///
2709 /// ```
2710 /// let mut vec = vec![1, 2, 3, 4];
2711 /// let pred = |x: &mut i32| *x % 2 == 0;
2712 ///
2713 /// assert_eq!(vec.pop_if(pred), Some(4));
2714 /// assert_eq!(vec, [1, 2, 3]);
2715 /// assert_eq!(vec.pop_if(pred), None);
2716 /// ```
2717 #[stable(feature = "vec_pop_if", since = "1.86.0")]
2718 pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T> {
2719 let last = self.last_mut()?;
2720 if predicate(last) { self.pop() } else { None }
2721 }
2722
2723 /// Returns a mutable reference to the last item in the vector, or
2724 /// `None` if it is empty.
2725 ///
2726 /// # Examples
2727 ///
2728 /// Basic usage:
2729 ///
2730 /// ```
2731 /// #![feature(vec_peek_mut)]
2732 /// let mut vec = Vec::new();
2733 /// assert!(vec.peek_mut().is_none());
2734 ///
2735 /// vec.push(1);
2736 /// vec.push(5);
2737 /// vec.push(2);
2738 /// assert_eq!(vec.last(), Some(&2));
2739 /// if let Some(mut val) = vec.peek_mut() {
2740 /// *val = 0;
2741 /// }
2742 /// assert_eq!(vec.last(), Some(&0));
2743 /// ```
2744 #[inline]
2745 #[unstable(feature = "vec_peek_mut", issue = "122742")]
2746 pub fn peek_mut(&mut self) -> Option<PeekMut<'_, T, A>> {
2747 PeekMut::new(self)
2748 }
2749
2750 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2751 ///
2752 /// # Panics
2753 ///
2754 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
2755 ///
2756 /// # Examples
2757 ///
2758 /// ```
2759 /// let mut vec = vec![1, 2, 3];
2760 /// let mut vec2 = vec![4, 5, 6];
2761 /// vec.append(&mut vec2);
2762 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
2763 /// assert_eq!(vec2, []);
2764 /// ```
2765 #[cfg(not(no_global_oom_handling))]
2766 #[inline]
2767 #[stable(feature = "append", since = "1.4.0")]
2768 pub fn append(&mut self, other: &mut Self) {
2769 unsafe {
2770 self.append_elements(other.as_slice() as _);
2771 other.set_len(0);
2772 }
2773 }
2774
2775 /// Appends elements to `self` from other buffer.
2776 #[cfg(not(no_global_oom_handling))]
2777 #[inline]
2778 unsafe fn append_elements(&mut self, other: *const [T]) {
2779 let count = other.len();
2780 self.reserve(count);
2781 let len = self.len();
2782 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
2783 self.len += count;
2784 }
2785
2786 /// Removes the subslice indicated by the given range from the vector,
2787 /// returning a double-ended iterator over the removed subslice.
2788 ///
2789 /// If the iterator is dropped before being fully consumed,
2790 /// it drops the remaining removed elements.
2791 ///
2792 /// The returned iterator keeps a mutable borrow on the vector to optimize
2793 /// its implementation.
2794 ///
2795 /// # Panics
2796 ///
2797 /// Panics if the range has `start_bound > end_bound`, or, if the range is
2798 /// bounded on either end and past the length of the vector.
2799 ///
2800 /// # Leaking
2801 ///
2802 /// If the returned iterator goes out of scope without being dropped (due to
2803 /// [`mem::forget`], for example), the vector may have lost and leaked
2804 /// elements arbitrarily, including elements outside the range.
2805 ///
2806 /// # Examples
2807 ///
2808 /// ```
2809 /// let mut v = vec![1, 2, 3];
2810 /// let u: Vec<_> = v.drain(1..).collect();
2811 /// assert_eq!(v, &[1]);
2812 /// assert_eq!(u, &[2, 3]);
2813 ///
2814 /// // A full range clears the vector, like `clear()` does
2815 /// v.drain(..);
2816 /// assert_eq!(v, &[]);
2817 /// ```
2818 #[stable(feature = "drain", since = "1.6.0")]
2819 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
2820 where
2821 R: RangeBounds<usize>,
2822 {
2823 // Memory safety
2824 //
2825 // When the Drain is first created, it shortens the length of
2826 // the source vector to make sure no uninitialized or moved-from elements
2827 // are accessible at all if the Drain's destructor never gets to run.
2828 //
2829 // Drain will ptr::read out the values to remove.
2830 // When finished, remaining tail of the vec is copied back to cover
2831 // the hole, and the vector length is restored to the new length.
2832 //
2833 let len = self.len();
2834 let Range { start, end } = slice::range(range, ..len);
2835
2836 unsafe {
2837 // set self.vec length's to start, to be safe in case Drain is leaked
2838 self.set_len(start);
2839 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
2840 Drain {
2841 tail_start: end,
2842 tail_len: len - end,
2843 iter: range_slice.iter(),
2844 vec: NonNull::from(self),
2845 }
2846 }
2847 }
2848
2849 /// Clears the vector, removing all values.
2850 ///
2851 /// Note that this method has no effect on the allocated capacity
2852 /// of the vector.
2853 ///
2854 /// # Examples
2855 ///
2856 /// ```
2857 /// let mut v = vec![1, 2, 3];
2858 ///
2859 /// v.clear();
2860 ///
2861 /// assert!(v.is_empty());
2862 /// ```
2863 #[inline]
2864 #[stable(feature = "rust1", since = "1.0.0")]
2865 pub fn clear(&mut self) {
2866 let elems: *mut [T] = self.as_mut_slice();
2867
2868 // SAFETY:
2869 // - `elems` comes directly from `as_mut_slice` and is therefore valid.
2870 // - Setting `self.len` before calling `drop_in_place` means that,
2871 // if an element's `Drop` impl panics, the vector's `Drop` impl will
2872 // do nothing (leaking the rest of the elements) instead of dropping
2873 // some twice.
2874 unsafe {
2875 self.len = 0;
2876 ptr::drop_in_place(elems);
2877 }
2878 }
2879
2880 /// Returns the number of elements in the vector, also referred to
2881 /// as its 'length'.
2882 ///
2883 /// # Examples
2884 ///
2885 /// ```
2886 /// let a = vec![1, 2, 3];
2887 /// assert_eq!(a.len(), 3);
2888 /// ```
2889 #[inline]
2890 #[stable(feature = "rust1", since = "1.0.0")]
2891 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
2892 #[rustc_confusables("length", "size")]
2893 pub const fn len(&self) -> usize {
2894 let len = self.len;
2895
2896 // SAFETY: The maximum capacity of `Vec<T>` is `isize::MAX` bytes, so the maximum value can
2897 // be returned is `usize::checked_div(size_of::<T>()).unwrap_or(usize::MAX)`, which
2898 // matches the definition of `T::MAX_SLICE_LEN`.
2899 unsafe { intrinsics::assume(len <= T::MAX_SLICE_LEN) };
2900
2901 len
2902 }
2903
2904 /// Returns `true` if the vector contains no elements.
2905 ///
2906 /// # Examples
2907 ///
2908 /// ```
2909 /// let mut v = Vec::new();
2910 /// assert!(v.is_empty());
2911 ///
2912 /// v.push(1);
2913 /// assert!(!v.is_empty());
2914 /// ```
2915 #[stable(feature = "rust1", since = "1.0.0")]
2916 #[rustc_diagnostic_item = "vec_is_empty"]
2917 #[rustc_const_stable(feature = "const_vec_string_slice", since = "1.87.0")]
2918 pub const fn is_empty(&self) -> bool {
2919 self.len() == 0
2920 }
2921
2922 /// Splits the collection into two at the given index.
2923 ///
2924 /// Returns a newly allocated vector containing the elements in the range
2925 /// `[at, len)`. After the call, the original vector will be left containing
2926 /// the elements `[0, at)` with its previous capacity unchanged.
2927 ///
2928 /// - If you want to take ownership of the entire contents and capacity of
2929 /// the vector, see [`mem::take`] or [`mem::replace`].
2930 /// - If you don't need the returned vector at all, see [`Vec::truncate`].
2931 /// - If you want to take ownership of an arbitrary subslice, or you don't
2932 /// necessarily want to store the removed items in a vector, see [`Vec::drain`].
2933 ///
2934 /// # Panics
2935 ///
2936 /// Panics if `at > len`.
2937 ///
2938 /// # Examples
2939 ///
2940 /// ```
2941 /// let mut vec = vec!['a', 'b', 'c'];
2942 /// let vec2 = vec.split_off(1);
2943 /// assert_eq!(vec, ['a']);
2944 /// assert_eq!(vec2, ['b', 'c']);
2945 /// ```
2946 #[cfg(not(no_global_oom_handling))]
2947 #[inline]
2948 #[must_use = "use `.truncate()` if you don't need the other half"]
2949 #[stable(feature = "split_off", since = "1.4.0")]
2950 #[track_caller]
2951 pub fn split_off(&mut self, at: usize) -> Self
2952 where
2953 A: Clone,
2954 {
2955 #[cold]
2956 #[cfg_attr(not(panic = "immediate-abort"), inline(never))]
2957 #[track_caller]
2958 #[optimize(size)]
2959 fn assert_failed(at: usize, len: usize) -> ! {
2960 panic!("`at` split index (is {at}) should be <= len (is {len})");
2961 }
2962
2963 if at > self.len() {
2964 assert_failed(at, self.len());
2965 }
2966
2967 let other_len = self.len - at;
2968 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
2969
2970 // Unsafely `set_len` and copy items to `other`.
2971 unsafe {
2972 self.set_len(at);
2973 other.set_len(other_len);
2974
2975 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
2976 }
2977 other
2978 }
2979
2980 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2981 ///
2982 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2983 /// difference, with each additional slot filled with the result of
2984 /// calling the closure `f`. The return values from `f` will end up
2985 /// in the `Vec` in the order they have been generated.
2986 ///
2987 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2988 ///
2989 /// This method uses a closure to create new values on every push. If
2990 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
2991 /// want to use the [`Default`] trait to generate values, you can
2992 /// pass [`Default::default`] as the second argument.
2993 ///
2994 /// # Panics
2995 ///
2996 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
2997 ///
2998 /// # Examples
2999 ///
3000 /// ```
3001 /// let mut vec = vec![1, 2, 3];
3002 /// vec.resize_with(5, Default::default);
3003 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
3004 ///
3005 /// let mut vec = vec![];
3006 /// let mut p = 1;
3007 /// vec.resize_with(4, || { p *= 2; p });
3008 /// assert_eq!(vec, [2, 4, 8, 16]);
3009 /// ```
3010 #[cfg(not(no_global_oom_handling))]
3011 #[stable(feature = "vec_resize_with", since = "1.33.0")]
3012 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
3013 where
3014 F: FnMut() -> T,
3015 {
3016 let len = self.len();
3017 if new_len > len {
3018 self.extend_trusted(iter::repeat_with(f).take(new_len - len));
3019 } else {
3020 self.truncate(new_len);
3021 }
3022 }
3023
3024 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
3025 /// `&'a mut [T]`.
3026 ///
3027 /// Note that the type `T` must outlive the chosen lifetime `'a`. If the type
3028 /// has only static references, or none at all, then this may be chosen to be
3029 /// `'static`.
3030 ///
3031 /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
3032 /// so the leaked allocation may include unused capacity that is not part
3033 /// of the returned slice.
3034 ///
3035 /// This function is mainly useful for data that lives for the remainder of
3036 /// the program's life. Dropping the returned reference will cause a memory
3037 /// leak.
3038 ///
3039 /// # Examples
3040 ///
3041 /// Simple usage:
3042 ///
3043 /// ```
3044 /// let x = vec![1, 2, 3];
3045 /// let static_ref: &'static mut [usize] = x.leak();
3046 /// static_ref[0] += 1;
3047 /// assert_eq!(static_ref, &[2, 2, 3]);
3048 /// # // FIXME(https://github.com/rust-lang/miri/issues/3670):
3049 /// # // use -Zmiri-disable-leak-check instead of unleaking in tests meant to leak.
3050 /// # drop(unsafe { Box::from_raw(static_ref) });
3051 /// ```
3052 #[stable(feature = "vec_leak", since = "1.47.0")]
3053 #[inline]
3054 pub fn leak<'a>(self) -> &'a mut [T]
3055 where
3056 A: 'a,
3057 {
3058 let mut me = ManuallyDrop::new(self);
3059 unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
3060 }
3061
3062 /// Returns the remaining spare capacity of the vector as a slice of
3063 /// `MaybeUninit<T>`.
3064 ///
3065 /// The returned slice can be used to fill the vector with data (e.g. by
3066 /// reading from a file) before marking the data as initialized using the
3067 /// [`set_len`] method.
3068 ///
3069 /// [`set_len`]: Vec::set_len
3070 ///
3071 /// # Examples
3072 ///
3073 /// ```
3074 /// // Allocate vector big enough for 10 elements.
3075 /// let mut v = Vec::with_capacity(10);
3076 ///
3077 /// // Fill in the first 3 elements.
3078 /// let uninit = v.spare_capacity_mut();
3079 /// uninit[0].write(0);
3080 /// uninit[1].write(1);
3081 /// uninit[2].write(2);
3082 ///
3083 /// // Mark the first 3 elements of the vector as being initialized.
3084 /// unsafe {
3085 /// v.set_len(3);
3086 /// }
3087 ///
3088 /// assert_eq!(&v, &[0, 1, 2]);
3089 /// ```
3090 #[stable(feature = "vec_spare_capacity", since = "1.60.0")]
3091 #[inline]
3092 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
3093 // Note:
3094 // This method is not implemented in terms of `split_at_spare_mut`,
3095 // to prevent invalidation of pointers to the buffer.
3096 unsafe {
3097 slice::from_raw_parts_mut(
3098 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
3099 self.buf.capacity() - self.len,
3100 )
3101 }
3102 }
3103
3104 /// Returns vector content as a slice of `T`, along with the remaining spare
3105 /// capacity of the vector as a slice of `MaybeUninit<T>`.
3106 ///
3107 /// The returned spare capacity slice can be used to fill the vector with data
3108 /// (e.g. by reading from a file) before marking the data as initialized using
3109 /// the [`set_len`] method.
3110 ///
3111 /// [`set_len`]: Vec::set_len
3112 ///
3113 /// Note that this is a low-level API, which should be used with care for
3114 /// optimization purposes. If you need to append data to a `Vec`
3115 /// you can use [`push`], [`extend`], [`extend_from_slice`],
3116 /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
3117 /// [`resize_with`], depending on your exact needs.
3118 ///
3119 /// [`push`]: Vec::push
3120 /// [`extend`]: Vec::extend
3121 /// [`extend_from_slice`]: Vec::extend_from_slice
3122 /// [`extend_from_within`]: Vec::extend_from_within
3123 /// [`insert`]: Vec::insert
3124 /// [`append`]: Vec::append
3125 /// [`resize`]: Vec::resize
3126 /// [`resize_with`]: Vec::resize_with
3127 ///
3128 /// # Examples
3129 ///
3130 /// ```
3131 /// #![feature(vec_split_at_spare)]
3132 ///
3133 /// let mut v = vec![1, 1, 2];
3134 ///
3135 /// // Reserve additional space big enough for 10 elements.
3136 /// v.reserve(10);
3137 ///
3138 /// let (init, uninit) = v.split_at_spare_mut();
3139 /// let sum = init.iter().copied().sum::<u32>();
3140 ///
3141 /// // Fill in the next 4 elements.
3142 /// uninit[0].write(sum);
3143 /// uninit[1].write(sum * 2);
3144 /// uninit[2].write(sum * 3);
3145 /// uninit[3].write(sum * 4);
3146 ///
3147 /// // Mark the 4 elements of the vector as being initialized.
3148 /// unsafe {
3149 /// let len = v.len();
3150 /// v.set_len(len + 4);
3151 /// }
3152 ///
3153 /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
3154 /// ```
3155 #[unstable(feature = "vec_split_at_spare", issue = "81944")]
3156 #[inline]
3157 pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
3158 // SAFETY:
3159 // - len is ignored and so never changed
3160 let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
3161 (init, spare)
3162 }
3163
3164 /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
3165 ///
3166 /// This method provides unique access to all vec parts at once in `extend_from_within`.
3167 unsafe fn split_at_spare_mut_with_len(
3168 &mut self,
3169 ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
3170 let ptr = self.as_mut_ptr();
3171 // SAFETY:
3172 // - `ptr` is guaranteed to be valid for `self.len` elements
3173 // - but the allocation extends out to `self.buf.capacity()` elements, possibly
3174 // uninitialized
3175 let spare_ptr = unsafe { ptr.add(self.len) };
3176 let spare_ptr = spare_ptr.cast_uninit();
3177 let spare_len = self.buf.capacity() - self.len;
3178
3179 // SAFETY:
3180 // - `ptr` is guaranteed to be valid for `self.len` elements
3181 // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
3182 unsafe {
3183 let initialized = slice::from_raw_parts_mut(ptr, self.len);
3184 let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
3185
3186 (initialized, spare, &mut self.len)
3187 }
3188 }
3189
3190 /// Groups every `N` elements in the `Vec<T>` into chunks to produce a `Vec<[T; N]>`, dropping
3191 /// elements in the remainder. `N` must be greater than zero.
3192 ///
3193 /// If the capacity is not a multiple of the chunk size, the buffer will shrink down to the
3194 /// nearest multiple with a reallocation or deallocation.
3195 ///
3196 /// This function can be used to reverse [`Vec::into_flattened`].
3197 ///
3198 /// # Examples
3199 ///
3200 /// ```
3201 /// #![feature(vec_into_chunks)]
3202 ///
3203 /// let vec = vec![0, 1, 2, 3, 4, 5, 6, 7];
3204 /// assert_eq!(vec.into_chunks::<3>(), [[0, 1, 2], [3, 4, 5]]);
3205 ///
3206 /// let vec = vec![0, 1, 2, 3];
3207 /// let chunks: Vec<[u8; 10]> = vec.into_chunks();
3208 /// assert!(chunks.is_empty());
3209 ///
3210 /// let flat = vec![0; 8 * 8 * 8];
3211 /// let reshaped: Vec<[[[u8; 8]; 8]; 8]> = flat.into_chunks().into_chunks().into_chunks();
3212 /// assert_eq!(reshaped.len(), 1);
3213 /// ```
3214 #[cfg(not(no_global_oom_handling))]
3215 #[unstable(feature = "vec_into_chunks", issue = "142137")]
3216 pub fn into_chunks<const N: usize>(mut self) -> Vec<[T; N], A> {
3217 const {
3218 assert!(N != 0, "chunk size must be greater than zero");
3219 }
3220
3221 let (len, cap) = (self.len(), self.capacity());
3222
3223 let len_remainder = len % N;
3224 if len_remainder != 0 {
3225 self.truncate(len - len_remainder);
3226 }
3227
3228 let cap_remainder = cap % N;
3229 if !T::IS_ZST && cap_remainder != 0 {
3230 self.buf.shrink_to_fit(cap - cap_remainder);
3231 }
3232
3233 let (ptr, _, _, alloc) = self.into_raw_parts_with_alloc();
3234
3235 // SAFETY:
3236 // - `ptr` and `alloc` were just returned from `self.into_raw_parts_with_alloc()`
3237 // - `[T; N]` has the same alignment as `T`
3238 // - `size_of::<[T; N]>() * cap / N == size_of::<T>() * cap`
3239 // - `len / N <= cap / N` because `len <= cap`
3240 // - the allocated memory consists of `len / N` valid values of type `[T; N]`
3241 // - `cap / N` fits the size of the allocated memory after shrinking
3242 unsafe { Vec::from_raw_parts_in(ptr.cast(), len / N, cap / N, alloc) }
3243 }
3244}
3245
3246impl<T: Clone, A: Allocator> Vec<T, A> {
3247 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
3248 ///
3249 /// If `new_len` is greater than `len`, the `Vec` is extended by the
3250 /// difference, with each additional slot filled with `value`.
3251 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
3252 ///
3253 /// This method requires `T` to implement [`Clone`],
3254 /// in order to be able to clone the passed value.
3255 /// If you need more flexibility (or want to rely on [`Default`] instead of
3256 /// [`Clone`]), use [`Vec::resize_with`].
3257 /// If you only need to resize to a smaller size, use [`Vec::truncate`].
3258 ///
3259 /// # Panics
3260 ///
3261 /// Panics if the new capacity exceeds `isize::MAX` _bytes_.
3262 ///
3263 /// # Examples
3264 ///
3265 /// ```
3266 /// let mut vec = vec!["hello"];
3267 /// vec.resize(3, "world");
3268 /// assert_eq!(vec, ["hello", "world", "world"]);
3269 ///
3270 /// let mut vec = vec!['a', 'b', 'c', 'd'];
3271 /// vec.resize(2, '_');
3272 /// assert_eq!(vec, ['a', 'b']);
3273 /// ```
3274 #[cfg(not(no_global_oom_handling))]
3275 #[stable(feature = "vec_resize", since = "1.5.0")]
3276 pub fn resize(&mut self, new_len: usize, value: T) {
3277 let len = self.len();
3278
3279 if new_len > len {
3280 self.extend_with(new_len - len, value)
3281 } else {
3282 self.truncate(new_len);
3283 }
3284 }
3285
3286 /// Clones and appends all elements in a slice to the `Vec`.
3287 ///
3288 /// Iterates over the slice `other`, clones each element, and then appends
3289 /// it to this `Vec`. The `other` slice is traversed in-order.
3290 ///
3291 /// Note that this function is the same as [`extend`],
3292 /// except that it also works with slice elements that are Clone but not Copy.
3293 /// If Rust gets specialization this function may be deprecated.
3294 ///
3295 /// # Examples
3296 ///
3297 /// ```
3298 /// let mut vec = vec![1];
3299 /// vec.extend_from_slice(&[2, 3, 4]);
3300 /// assert_eq!(vec, [1, 2, 3, 4]);
3301 /// ```
3302 ///
3303 /// [`extend`]: Vec::extend
3304 #[cfg(not(no_global_oom_handling))]
3305 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
3306 pub fn extend_from_slice(&mut self, other: &[T]) {
3307 self.spec_extend(other.iter())
3308 }
3309
3310 /// Given a range `src`, clones a slice of elements in that range and appends it to the end.
3311 ///
3312 /// `src` must be a range that can form a valid subslice of the `Vec`.
3313 ///
3314 /// # Panics
3315 ///
3316 /// Panics if starting index is greater than the end index
3317 /// or if the index is greater than the length of the vector.
3318 ///
3319 /// # Examples
3320 ///
3321 /// ```
3322 /// let mut characters = vec!['a', 'b', 'c', 'd', 'e'];
3323 /// characters.extend_from_within(2..);
3324 /// assert_eq!(characters, ['a', 'b', 'c', 'd', 'e', 'c', 'd', 'e']);
3325 ///
3326 /// let mut numbers = vec![0, 1, 2, 3, 4];
3327 /// numbers.extend_from_within(..2);
3328 /// assert_eq!(numbers, [0, 1, 2, 3, 4, 0, 1]);
3329 ///
3330 /// let mut strings = vec![String::from("hello"), String::from("world"), String::from("!")];
3331 /// strings.extend_from_within(1..=2);
3332 /// assert_eq!(strings, ["hello", "world", "!", "world", "!"]);
3333 /// ```
3334 #[cfg(not(no_global_oom_handling))]
3335 #[stable(feature = "vec_extend_from_within", since = "1.53.0")]
3336 pub fn extend_from_within<R>(&mut self, src: R)
3337 where
3338 R: RangeBounds<usize>,
3339 {
3340 let range = slice::range(src, ..self.len());
3341 self.reserve(range.len());
3342
3343 // SAFETY:
3344 // - `slice::range` guarantees that the given range is valid for indexing self
3345 unsafe {
3346 self.spec_extend_from_within(range);
3347 }
3348 }
3349}
3350
3351impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
3352 /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
3353 ///
3354 /// # Panics
3355 ///
3356 /// Panics if the length of the resulting vector would overflow a `usize`.
3357 ///
3358 /// This is only possible when flattening a vector of arrays of zero-sized
3359 /// types, and thus tends to be irrelevant in practice. If
3360 /// `size_of::<T>() > 0`, this will never panic.
3361 ///
3362 /// # Examples
3363 ///
3364 /// ```
3365 /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
3366 /// assert_eq!(vec.pop(), Some([7, 8, 9]));
3367 ///
3368 /// let mut flattened = vec.into_flattened();
3369 /// assert_eq!(flattened.pop(), Some(6));
3370 /// ```
3371 #[stable(feature = "slice_flatten", since = "1.80.0")]
3372 pub fn into_flattened(self) -> Vec<T, A> {
3373 let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
3374 let (new_len, new_cap) = if T::IS_ZST {
3375 (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
3376 } else {
3377 // SAFETY:
3378 // - `cap * N` cannot overflow because the allocation is already in
3379 // the address space.
3380 // - Each `[T; N]` has `N` valid elements, so there are `len * N`
3381 // valid elements in the allocation.
3382 unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) }
3383 };
3384 // SAFETY:
3385 // - `ptr` was allocated by `self`
3386 // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
3387 // - `new_cap` refers to the same sized allocation as `cap` because
3388 // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
3389 // - `len` <= `cap`, so `len * N` <= `cap * N`.
3390 unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
3391 }
3392}
3393
3394impl<T: Clone, A: Allocator> Vec<T, A> {
3395 #[cfg(not(no_global_oom_handling))]
3396 /// Extend the vector by `n` clones of value.
3397 fn extend_with(&mut self, n: usize, value: T) {
3398 self.reserve(n);
3399
3400 unsafe {
3401 let mut ptr = self.as_mut_ptr().add(self.len());
3402 // Use SetLenOnDrop to work around bug where compiler
3403 // might not realize the store through `ptr` through self.set_len()
3404 // don't alias.
3405 let mut local_len = SetLenOnDrop::new(&mut self.len);
3406
3407 // Write all elements except the last one
3408 for _ in 1..n {
3409 ptr::write(ptr, value.clone());
3410 ptr = ptr.add(1);
3411 // Increment the length in every step in case clone() panics
3412 local_len.increment_len(1);
3413 }
3414
3415 if n > 0 {
3416 // We can write the last element directly without cloning needlessly
3417 ptr::write(ptr, value);
3418 local_len.increment_len(1);
3419 }
3420
3421 // len set by scope guard
3422 }
3423 }
3424}
3425
3426impl<T: PartialEq, A: Allocator> Vec<T, A> {
3427 /// Removes consecutive repeated elements in the vector according to the
3428 /// [`PartialEq`] trait implementation.
3429 ///
3430 /// If the vector is sorted, this removes all duplicates.
3431 ///
3432 /// # Examples
3433 ///
3434 /// ```
3435 /// let mut vec = vec![1, 2, 2, 3, 2];
3436 ///
3437 /// vec.dedup();
3438 ///
3439 /// assert_eq!(vec, [1, 2, 3, 2]);
3440 /// ```
3441 #[stable(feature = "rust1", since = "1.0.0")]
3442 #[inline]
3443 pub fn dedup(&mut self) {
3444 self.dedup_by(|a, b| a == b)
3445 }
3446}
3447
3448////////////////////////////////////////////////////////////////////////////////
3449// Internal methods and functions
3450////////////////////////////////////////////////////////////////////////////////
3451
3452#[doc(hidden)]
3453#[cfg(not(no_global_oom_handling))]
3454#[stable(feature = "rust1", since = "1.0.0")]
3455#[rustc_diagnostic_item = "vec_from_elem"]
3456pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
3457 <T as SpecFromElem>::from_elem(elem, n, Global)
3458}
3459
3460#[doc(hidden)]
3461#[cfg(not(no_global_oom_handling))]
3462#[unstable(feature = "allocator_api", issue = "32838")]
3463pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
3464 <T as SpecFromElem>::from_elem(elem, n, alloc)
3465}
3466
3467#[cfg(not(no_global_oom_handling))]
3468trait ExtendFromWithinSpec {
3469 /// # Safety
3470 ///
3471 /// - `src` needs to be valid index
3472 /// - `self.capacity() - self.len()` must be `>= src.len()`
3473 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
3474}
3475
3476#[cfg(not(no_global_oom_handling))]
3477impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3478 default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3479 // SAFETY:
3480 // - len is increased only after initializing elements
3481 let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
3482
3483 // SAFETY:
3484 // - caller guarantees that src is a valid index
3485 let to_clone = unsafe { this.get_unchecked(src) };
3486
3487 iter::zip(to_clone, spare)
3488 .map(|(src, dst)| dst.write(src.clone()))
3489 // Note:
3490 // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
3491 // - len is increased after each element to prevent leaks (see issue #82533)
3492 .for_each(|_| *len += 1);
3493 }
3494}
3495
3496#[cfg(not(no_global_oom_handling))]
3497impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
3498 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
3499 let count = src.len();
3500 {
3501 let (init, spare) = self.split_at_spare_mut();
3502
3503 // SAFETY:
3504 // - caller guarantees that `src` is a valid index
3505 let source = unsafe { init.get_unchecked(src) };
3506
3507 // SAFETY:
3508 // - Both pointers are created from unique slice references (`&mut [_]`)
3509 // so they are valid and do not overlap.
3510 // - Elements are :Copy so it's OK to copy them, without doing
3511 // anything with the original values
3512 // - `count` is equal to the len of `source`, so source is valid for
3513 // `count` reads
3514 // - `.reserve(count)` guarantees that `spare.len() >= count` so spare
3515 // is valid for `count` writes
3516 unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
3517 }
3518
3519 // SAFETY:
3520 // - The elements were just initialized by `copy_nonoverlapping`
3521 self.len += count;
3522 }
3523}
3524
3525////////////////////////////////////////////////////////////////////////////////
3526// Common trait implementations for Vec
3527////////////////////////////////////////////////////////////////////////////////
3528
3529#[stable(feature = "rust1", since = "1.0.0")]
3530impl<T, A: Allocator> ops::Deref for Vec<T, A> {
3531 type Target = [T];
3532
3533 #[inline]
3534 fn deref(&self) -> &[T] {
3535 self.as_slice()
3536 }
3537}
3538
3539#[stable(feature = "rust1", since = "1.0.0")]
3540impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
3541 #[inline]
3542 fn deref_mut(&mut self) -> &mut [T] {
3543 self.as_mut_slice()
3544 }
3545}
3546
3547#[unstable(feature = "deref_pure_trait", issue = "87121")]
3548unsafe impl<T, A: Allocator> ops::DerefPure for Vec<T, A> {}
3549
3550#[cfg(not(no_global_oom_handling))]
3551#[stable(feature = "rust1", since = "1.0.0")]
3552impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
3553 fn clone(&self) -> Self {
3554 let alloc = self.allocator().clone();
3555 <[T]>::to_vec_in(&**self, alloc)
3556 }
3557
3558 /// Overwrites the contents of `self` with a clone of the contents of `source`.
3559 ///
3560 /// This method is preferred over simply assigning `source.clone()` to `self`,
3561 /// as it avoids reallocation if possible. Additionally, if the element type
3562 /// `T` overrides `clone_from()`, this will reuse the resources of `self`'s
3563 /// elements as well.
3564 ///
3565 /// # Examples
3566 ///
3567 /// ```
3568 /// let x = vec![5, 6, 7];
3569 /// let mut y = vec![8, 9, 10];
3570 /// let yp: *const i32 = y.as_ptr();
3571 ///
3572 /// y.clone_from(&x);
3573 ///
3574 /// // The value is the same
3575 /// assert_eq!(x, y);
3576 ///
3577 /// // And no reallocation occurred
3578 /// assert_eq!(yp, y.as_ptr());
3579 /// ```
3580 fn clone_from(&mut self, source: &Self) {
3581 crate::slice::SpecCloneIntoVec::clone_into(source.as_slice(), self);
3582 }
3583}
3584
3585/// The hash of a vector is the same as that of the corresponding slice,
3586/// as required by the `core::borrow::Borrow` implementation.
3587///
3588/// ```
3589/// use std::hash::BuildHasher;
3590///
3591/// let b = std::hash::RandomState::new();
3592/// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
3593/// let s: &[u8] = &[0xa8, 0x3c, 0x09];
3594/// assert_eq!(b.hash_one(v), b.hash_one(s));
3595/// ```
3596#[stable(feature = "rust1", since = "1.0.0")]
3597impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
3598 #[inline]
3599 fn hash<H: Hasher>(&self, state: &mut H) {
3600 Hash::hash(&**self, state)
3601 }
3602}
3603
3604#[stable(feature = "rust1", since = "1.0.0")]
3605impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
3606 type Output = I::Output;
3607
3608 #[inline]
3609 fn index(&self, index: I) -> &Self::Output {
3610 Index::index(&**self, index)
3611 }
3612}
3613
3614#[stable(feature = "rust1", since = "1.0.0")]
3615impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
3616 #[inline]
3617 fn index_mut(&mut self, index: I) -> &mut Self::Output {
3618 IndexMut::index_mut(&mut **self, index)
3619 }
3620}
3621
3622/// Collects an iterator into a Vec, commonly called via [`Iterator::collect()`]
3623///
3624/// # Allocation behavior
3625///
3626/// In general `Vec` does not guarantee any particular growth or allocation strategy.
3627/// That also applies to this trait impl.
3628///
3629/// **Note:** This section covers implementation details and is therefore exempt from
3630/// stability guarantees.
3631///
3632/// Vec may use any or none of the following strategies,
3633/// depending on the supplied iterator:
3634///
3635/// * preallocate based on [`Iterator::size_hint()`]
3636/// * and panic if the number of items is outside the provided lower/upper bounds
3637/// * use an amortized growth strategy similar to `pushing` one item at a time
3638/// * perform the iteration in-place on the original allocation backing the iterator
3639///
3640/// The last case warrants some attention. It is an optimization that in many cases reduces peak memory
3641/// consumption and improves cache locality. But when big, short-lived allocations are created,
3642/// only a small fraction of their items get collected, no further use is made of the spare capacity
3643/// and the resulting `Vec` is moved into a longer-lived structure, then this can lead to the large
3644/// allocations having their lifetimes unnecessarily extended which can result in increased memory
3645/// footprint.
3646///
3647/// In cases where this is an issue, the excess capacity can be discarded with [`Vec::shrink_to()`],
3648/// [`Vec::shrink_to_fit()`] or by collecting into [`Box<[T]>`][owned slice] instead, which additionally reduces
3649/// the size of the long-lived struct.
3650///
3651/// [owned slice]: Box
3652///
3653/// ```rust
3654/// # use std::sync::Mutex;
3655/// static LONG_LIVED: Mutex<Vec<Vec<u16>>> = Mutex::new(Vec::new());
3656///
3657/// for i in 0..10 {
3658/// let big_temporary: Vec<u16> = (0..1024).collect();
3659/// // discard most items
3660/// let mut result: Vec<_> = big_temporary.into_iter().filter(|i| i % 100 == 0).collect();
3661/// // without this a lot of unused capacity might be moved into the global
3662/// result.shrink_to_fit();
3663/// LONG_LIVED.lock().unwrap().push(result);
3664/// }
3665/// ```
3666#[cfg(not(no_global_oom_handling))]
3667#[stable(feature = "rust1", since = "1.0.0")]
3668impl<T> FromIterator<T> for Vec<T> {
3669 #[inline]
3670 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
3671 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
3672 }
3673}
3674
3675#[stable(feature = "rust1", since = "1.0.0")]
3676impl<T, A: Allocator> IntoIterator for Vec<T, A> {
3677 type Item = T;
3678 type IntoIter = IntoIter<T, A>;
3679
3680 /// Creates a consuming iterator, that is, one that moves each value out of
3681 /// the vector (from start to end). The vector cannot be used after calling
3682 /// this.
3683 ///
3684 /// # Examples
3685 ///
3686 /// ```
3687 /// let v = vec!["a".to_string(), "b".to_string()];
3688 /// let mut v_iter = v.into_iter();
3689 ///
3690 /// let first_element: Option<String> = v_iter.next();
3691 ///
3692 /// assert_eq!(first_element, Some("a".to_string()));
3693 /// assert_eq!(v_iter.next(), Some("b".to_string()));
3694 /// assert_eq!(v_iter.next(), None);
3695 /// ```
3696 #[inline]
3697 fn into_iter(self) -> Self::IntoIter {
3698 unsafe {
3699 let me = ManuallyDrop::new(self);
3700 let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
3701 let buf = me.buf.non_null();
3702 let begin = buf.as_ptr();
3703 let end = if T::IS_ZST {
3704 begin.wrapping_byte_add(me.len())
3705 } else {
3706 begin.add(me.len()) as *const T
3707 };
3708 let cap = me.buf.capacity();
3709 IntoIter { buf, phantom: PhantomData, cap, alloc, ptr: buf, end }
3710 }
3711 }
3712}
3713
3714#[stable(feature = "rust1", since = "1.0.0")]
3715impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
3716 type Item = &'a T;
3717 type IntoIter = slice::Iter<'a, T>;
3718
3719 fn into_iter(self) -> Self::IntoIter {
3720 self.iter()
3721 }
3722}
3723
3724#[stable(feature = "rust1", since = "1.0.0")]
3725impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
3726 type Item = &'a mut T;
3727 type IntoIter = slice::IterMut<'a, T>;
3728
3729 fn into_iter(self) -> Self::IntoIter {
3730 self.iter_mut()
3731 }
3732}
3733
3734#[cfg(not(no_global_oom_handling))]
3735#[stable(feature = "rust1", since = "1.0.0")]
3736impl<T, A: Allocator> Extend<T> for Vec<T, A> {
3737 #[inline]
3738 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
3739 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
3740 }
3741
3742 #[inline]
3743 fn extend_one(&mut self, item: T) {
3744 self.push(item);
3745 }
3746
3747 #[inline]
3748 fn extend_reserve(&mut self, additional: usize) {
3749 self.reserve(additional);
3750 }
3751
3752 #[inline]
3753 unsafe fn extend_one_unchecked(&mut self, item: T) {
3754 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
3755 unsafe {
3756 let len = self.len();
3757 ptr::write(self.as_mut_ptr().add(len), item);
3758 self.set_len(len + 1);
3759 }
3760 }
3761}
3762
3763impl<T, A: Allocator> Vec<T, A> {
3764 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
3765 // they have no further optimizations to apply
3766 #[cfg(not(no_global_oom_handling))]
3767 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
3768 // This is the case for a general iterator.
3769 //
3770 // This function should be the moral equivalent of:
3771 //
3772 // for item in iterator {
3773 // self.push(item);
3774 // }
3775 while let Some(element) = iterator.next() {
3776 let len = self.len();
3777 if len == self.capacity() {
3778 let (lower, _) = iterator.size_hint();
3779 self.reserve(lower.saturating_add(1));
3780 }
3781 unsafe {
3782 ptr::write(self.as_mut_ptr().add(len), element);
3783 // Since next() executes user code which can panic we have to bump the length
3784 // after each step.
3785 // NB can't overflow since we would have had to alloc the address space
3786 self.set_len(len + 1);
3787 }
3788 }
3789 }
3790
3791 // specific extend for `TrustedLen` iterators, called both by the specializations
3792 // and internal places where resolving specialization makes compilation slower
3793 #[cfg(not(no_global_oom_handling))]
3794 fn extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) {
3795 let (low, high) = iterator.size_hint();
3796 if let Some(additional) = high {
3797 debug_assert_eq!(
3798 low,
3799 additional,
3800 "TrustedLen iterator's size hint is not exact: {:?}",
3801 (low, high)
3802 );
3803 self.reserve(additional);
3804 unsafe {
3805 let ptr = self.as_mut_ptr();
3806 let mut local_len = SetLenOnDrop::new(&mut self.len);
3807 iterator.for_each(move |element| {
3808 ptr::write(ptr.add(local_len.current_len()), element);
3809 // Since the loop executes user code which can panic we have to update
3810 // the length every step to correctly drop what we've written.
3811 // NB can't overflow since we would have had to alloc the address space
3812 local_len.increment_len(1);
3813 });
3814 }
3815 } else {
3816 // Per TrustedLen contract a `None` upper bound means that the iterator length
3817 // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
3818 // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
3819 // This avoids additional codegen for a fallback code path which would eventually
3820 // panic anyway.
3821 panic!("capacity overflow");
3822 }
3823 }
3824
3825 /// Creates a splicing iterator that replaces the specified range in the vector
3826 /// with the given `replace_with` iterator and yields the removed items.
3827 /// `replace_with` does not need to be the same length as `range`.
3828 ///
3829 /// `range` is removed even if the `Splice` iterator is not consumed before it is dropped.
3830 ///
3831 /// It is unspecified how many elements are removed from the vector
3832 /// if the `Splice` value is leaked.
3833 ///
3834 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
3835 ///
3836 /// This is optimal if:
3837 ///
3838 /// * The tail (elements in the vector after `range`) is empty,
3839 /// * or `replace_with` yields fewer or equal elements than `range`'s length
3840 /// * or the lower bound of its `size_hint()` is exact.
3841 ///
3842 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
3843 ///
3844 /// # Panics
3845 ///
3846 /// Panics if the range has `start_bound > end_bound`, or, if the range is
3847 /// bounded on either end and past the length of the vector.
3848 ///
3849 /// # Examples
3850 ///
3851 /// ```
3852 /// let mut v = vec![1, 2, 3, 4];
3853 /// let new = [7, 8, 9];
3854 /// let u: Vec<_> = v.splice(1..3, new).collect();
3855 /// assert_eq!(v, [1, 7, 8, 9, 4]);
3856 /// assert_eq!(u, [2, 3]);
3857 /// ```
3858 ///
3859 /// Using `splice` to insert new items into a vector efficiently at a specific position
3860 /// indicated by an empty range:
3861 ///
3862 /// ```
3863 /// let mut v = vec![1, 5];
3864 /// let new = [2, 3, 4];
3865 /// v.splice(1..1, new);
3866 /// assert_eq!(v, [1, 2, 3, 4, 5]);
3867 /// ```
3868 #[cfg(not(no_global_oom_handling))]
3869 #[inline]
3870 #[stable(feature = "vec_splice", since = "1.21.0")]
3871 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
3872 where
3873 R: RangeBounds<usize>,
3874 I: IntoIterator<Item = T>,
3875 {
3876 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
3877 }
3878
3879 /// Creates an iterator which uses a closure to determine if an element in the range should be removed.
3880 ///
3881 /// If the closure returns `true`, the element is removed from the vector
3882 /// and yielded. If the closure returns `false`, or panics, the element
3883 /// remains in the vector and will not be yielded.
3884 ///
3885 /// Only elements that fall in the provided range are considered for extraction, but any elements
3886 /// after the range will still have to be moved if any element has been extracted.
3887 ///
3888 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
3889 /// or the iteration short-circuits, then the remaining elements will be retained.
3890 /// Use [`retain_mut`] with a negated predicate if you do not need the returned iterator.
3891 ///
3892 /// [`retain_mut`]: Vec::retain_mut
3893 ///
3894 /// Using this method is equivalent to the following code:
3895 ///
3896 /// ```
3897 /// # let some_predicate = |x: &mut i32| { *x % 2 == 1 };
3898 /// # let mut vec = vec![0, 1, 2, 3, 4, 5, 6];
3899 /// # let mut vec2 = vec.clone();
3900 /// # let range = 1..5;
3901 /// let mut i = range.start;
3902 /// let end_items = vec.len() - range.end;
3903 /// # let mut extracted = vec![];
3904 ///
3905 /// while i < vec.len() - end_items {
3906 /// if some_predicate(&mut vec[i]) {
3907 /// let val = vec.remove(i);
3908 /// // your code here
3909 /// # extracted.push(val);
3910 /// } else {
3911 /// i += 1;
3912 /// }
3913 /// }
3914 ///
3915 /// # let extracted2: Vec<_> = vec2.extract_if(range, some_predicate).collect();
3916 /// # assert_eq!(vec, vec2);
3917 /// # assert_eq!(extracted, extracted2);
3918 /// ```
3919 ///
3920 /// But `extract_if` is easier to use. `extract_if` is also more efficient,
3921 /// because it can backshift the elements of the array in bulk.
3922 ///
3923 /// The iterator also lets you mutate the value of each element in the
3924 /// closure, regardless of whether you choose to keep or remove it.
3925 ///
3926 /// # Panics
3927 ///
3928 /// If `range` is out of bounds.
3929 ///
3930 /// # Examples
3931 ///
3932 /// Splitting a vector into even and odd values, reusing the original vector:
3933 ///
3934 /// ```
3935 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
3936 ///
3937 /// let evens = numbers.extract_if(.., |x| *x % 2 == 0).collect::<Vec<_>>();
3938 /// let odds = numbers;
3939 ///
3940 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
3941 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
3942 /// ```
3943 ///
3944 /// Using the range argument to only process a part of the vector:
3945 ///
3946 /// ```
3947 /// let mut items = vec![0, 0, 0, 0, 0, 0, 0, 1, 2, 1, 2, 1, 2];
3948 /// let |x| *x == 1).collect::<Vec<_>>();
3949 /// assert_eq!(items, vec![0, 0, 0, 0, 0, 0, 0, 2, 2, 2]);
3950 /// assert_eq!(ones.len(), 3);
3951 /// ```
3952 #[stable(feature = "extract_if", since = "1.87.0")]
3953 pub fn extract_if<F, R>(&mut self, range: R, filter: F) -> ExtractIf<'_, T, F, A>
3954 where
3955 F: FnMut(&mut T) -> bool,
3956 R: RangeBounds<usize>,
3957 {
3958 ExtractIf::new(self, filter, range)
3959 }
3960}
3961
3962/// Extend implementation that copies elements out of references before pushing them onto the Vec.
3963///
3964/// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
3965/// append the entire slice at once.
3966///
3967/// [`copy_from_slice`]: slice::copy_from_slice
3968#[cfg(not(no_global_oom_handling))]
3969#[stable(feature = "extend_ref", since = "1.2.0")]
3970impl<'a, T: Copy + 'a, A: Allocator> Extend<&'a T> for Vec<T, A> {
3971 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3972 self.spec_extend(iter.into_iter())
3973 }
3974
3975 #[inline]
3976 fn extend_one(&mut self, &item: &'a T) {
3977 self.push(item);
3978 }
3979
3980 #[inline]
3981 fn extend_reserve(&mut self, additional: usize) {
3982 self.reserve(additional);
3983 }
3984
3985 #[inline]
3986 unsafe fn extend_one_unchecked(&mut self, &item: &'a T) {
3987 // SAFETY: Our preconditions ensure the space has been reserved, and `extend_reserve` is implemented correctly.
3988 unsafe {
3989 let len = self.len();
3990 ptr::write(self.as_mut_ptr().add(len), item);
3991 self.set_len(len + 1);
3992 }
3993 }
3994}
3995
3996/// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison).
3997#[stable(feature = "rust1", since = "1.0.0")]
3998impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1>
3999where
4000 T: PartialOrd,
4001 A1: Allocator,
4002 A2: Allocator,
4003{
4004 #[inline]
4005 fn partial_cmp(&self, other: &Vec<T, A2>) -> Option<Ordering> {
4006 PartialOrd::partial_cmp(&**self, &**other)
4007 }
4008}
4009
4010#[stable(feature = "rust1", since = "1.0.0")]
4011impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
4012
4013/// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison).
4014#[stable(feature = "rust1", since = "1.0.0")]
4015impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
4016 #[inline]
4017 fn cmp(&self, other: &Self) -> Ordering {
4018 Ord::cmp(&**self, &**other)
4019 }
4020}
4021
4022#[stable(feature = "rust1", since = "1.0.0")]
4023unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
4024 fn drop(&mut self) {
4025 unsafe {
4026 // use drop for [T]
4027 // use a raw slice to refer to the elements of the vector as weakest necessary type;
4028 // could avoid questions of validity in certain cases
4029 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
4030 }
4031 // RawVec handles deallocation
4032 }
4033}
4034
4035#[stable(feature = "rust1", since = "1.0.0")]
4036#[rustc_const_unstable(feature = "const_default", issue = "143894")]
4037impl<T> const Default for Vec<T> {
4038 /// Creates an empty `Vec<T>`.
4039 ///
4040 /// The vector will not allocate until elements are pushed onto it.
4041 fn default() -> Vec<T> {
4042 Vec::new()
4043 }
4044}
4045
4046#[stable(feature = "rust1", since = "1.0.0")]
4047impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
4048 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
4049 fmt::Debug::fmt(&**self, f)
4050 }
4051}
4052
4053#[stable(feature = "rust1", since = "1.0.0")]
4054impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
4055 fn as_ref(&self) -> &Vec<T, A> {
4056 self
4057 }
4058}
4059
4060#[stable(feature = "vec_as_mut", since = "1.5.0")]
4061impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
4062 fn as_mut(&mut self) -> &mut Vec<T, A> {
4063 self
4064 }
4065}
4066
4067#[stable(feature = "rust1", since = "1.0.0")]
4068impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
4069 fn as_ref(&self) -> &[T] {
4070 self
4071 }
4072}
4073
4074#[stable(feature = "vec_as_mut", since = "1.5.0")]
4075impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
4076 fn as_mut(&mut self) -> &mut [T] {
4077 self
4078 }
4079}
4080
4081#[cfg(not(no_global_oom_handling))]
4082#[stable(feature = "rust1", since = "1.0.0")]
4083impl<T: Clone> From<&[T]> for Vec<T> {
4084 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4085 ///
4086 /// # Examples
4087 ///
4088 /// ```
4089 /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
4090 /// ```
4091 fn from(s: &[T]) -> Vec<T> {
4092 s.to_vec()
4093 }
4094}
4095
4096#[cfg(not(no_global_oom_handling))]
4097#[stable(feature = "vec_from_mut", since = "1.19.0")]
4098impl<T: Clone> From<&mut [T]> for Vec<T> {
4099 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4100 ///
4101 /// # Examples
4102 ///
4103 /// ```
4104 /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
4105 /// ```
4106 fn from(s: &mut [T]) -> Vec<T> {
4107 s.to_vec()
4108 }
4109}
4110
4111#[cfg(not(no_global_oom_handling))]
4112#[stable(feature = "vec_from_array_ref", since = "1.74.0")]
4113impl<T: Clone, const N: usize> From<&[T; N]> for Vec<T> {
4114 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4115 ///
4116 /// # Examples
4117 ///
4118 /// ```
4119 /// assert_eq!(Vec::from(&[1, 2, 3]), vec![1, 2, 3]);
4120 /// ```
4121 fn from(s: &[T; N]) -> Vec<T> {
4122 Self::from(s.as_slice())
4123 }
4124}
4125
4126#[cfg(not(no_global_oom_handling))]
4127#[stable(feature = "vec_from_array_ref", since = "1.74.0")]
4128impl<T: Clone, const N: usize> From<&mut [T; N]> for Vec<T> {
4129 /// Allocates a `Vec<T>` and fills it by cloning `s`'s items.
4130 ///
4131 /// # Examples
4132 ///
4133 /// ```
4134 /// assert_eq!(Vec::from(&mut [1, 2, 3]), vec![1, 2, 3]);
4135 /// ```
4136 fn from(s: &mut [T; N]) -> Vec<T> {
4137 Self::from(s.as_mut_slice())
4138 }
4139}
4140
4141#[cfg(not(no_global_oom_handling))]
4142#[stable(feature = "vec_from_array", since = "1.44.0")]
4143impl<T, const N: usize> From<[T; N]> for Vec<T> {
4144 /// Allocates a `Vec<T>` and moves `s`'s items into it.
4145 ///
4146 /// # Examples
4147 ///
4148 /// ```
4149 /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
4150 /// ```
4151 fn from(s: [T; N]) -> Vec<T> {
4152 <[T]>::into_vec(Box::new(s))
4153 }
4154}
4155
4156#[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
4157impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
4158where
4159 [T]: ToOwned<Owned = Vec<T>>,
4160{
4161 /// Converts a clone-on-write slice into a vector.
4162 ///
4163 /// If `s` already owns a `Vec<T>`, it will be returned directly.
4164 /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and
4165 /// filled by cloning `s`'s items into it.
4166 ///
4167 /// # Examples
4168 ///
4169 /// ```
4170 /// # use std::borrow::Cow;
4171 /// let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);
4172 /// let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);
4173 /// assert_eq!(Vec::from(o), Vec::from(b));
4174 /// ```
4175 fn from(s: Cow<'a, [T]>) -> Vec<T> {
4176 s.into_owned()
4177 }
4178}
4179
4180// note: test pulls in std, which causes errors here
4181#[stable(feature = "vec_from_box", since = "1.18.0")]
4182impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
4183 /// Converts a boxed slice into a vector by transferring ownership of
4184 /// the existing heap allocation.
4185 ///
4186 /// # Examples
4187 ///
4188 /// ```
4189 /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
4190 /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
4191 /// ```
4192 fn from(s: Box<[T], A>) -> Self {
4193 s.into_vec()
4194 }
4195}
4196
4197// note: test pulls in std, which causes errors here
4198#[cfg(not(no_global_oom_handling))]
4199#[stable(feature = "box_from_vec", since = "1.20.0")]
4200impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
4201 /// Converts a vector into a boxed slice.
4202 ///
4203 /// Before doing the conversion, this method discards excess capacity like [`Vec::shrink_to_fit`].
4204 ///
4205 /// [owned slice]: Box
4206 /// [`Vec::shrink_to_fit`]: Vec::shrink_to_fit
4207 ///
4208 /// # Examples
4209 ///
4210 /// ```
4211 /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
4212 /// ```
4213 ///
4214 /// Any excess capacity is removed:
4215 /// ```
4216 /// let mut vec = Vec::with_capacity(10);
4217 /// vec.extend([1, 2, 3]);
4218 ///
4219 /// assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice());
4220 /// ```
4221 fn from(v: Vec<T, A>) -> Self {
4222 v.into_boxed_slice()
4223 }
4224}
4225
4226#[cfg(not(no_global_oom_handling))]
4227#[stable(feature = "rust1", since = "1.0.0")]
4228impl From<&str> for Vec<u8> {
4229 /// Allocates a `Vec<u8>` and fills it with a UTF-8 string.
4230 ///
4231 /// # Examples
4232 ///
4233 /// ```
4234 /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
4235 /// ```
4236 fn from(s: &str) -> Vec<u8> {
4237 From::from(s.as_bytes())
4238 }
4239}
4240
4241#[stable(feature = "array_try_from_vec", since = "1.48.0")]
4242impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
4243 type Error = Vec<T, A>;
4244
4245 /// Gets the entire contents of the `Vec<T>` as an array,
4246 /// if its size exactly matches that of the requested array.
4247 ///
4248 /// # Examples
4249 ///
4250 /// ```
4251 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
4252 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
4253 /// ```
4254 ///
4255 /// If the length doesn't match, the input comes back in `Err`:
4256 /// ```
4257 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
4258 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
4259 /// ```
4260 ///
4261 /// If you're fine with just getting a prefix of the `Vec<T>`,
4262 /// you can call [`.truncate(N)`](Vec::truncate) first.
4263 /// ```
4264 /// let mut v = String::from("hello world").into_bytes();
4265 /// v.sort();
4266 /// v.truncate(2);
4267 /// let [a, b]: [_; 2] = v.try_into().unwrap();
4268 /// assert_eq!(a, b' ');
4269 /// assert_eq!(b, b'd');
4270 /// ```
4271 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
4272 if vec.len() != N {
4273 return Err(vec);
4274 }
4275
4276 // SAFETY: `.set_len(0)` is always sound.
4277 unsafe { vec.set_len(0) };
4278
4279 // SAFETY: A `Vec`'s pointer is always aligned properly, and
4280 // the alignment the array needs is the same as the items.
4281 // We checked earlier that we have sufficient items.
4282 // The items will not double-drop as the `set_len`
4283 // tells the `Vec` not to also drop them.
4284 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
4285 Ok(array)
4286 }
4287}