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