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