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