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