1 // SPDX-License-Identifier: Apache-2.0 OR MIT
3 //! A contiguous growable array type with heap-allocated contents, written
6 //! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and
7 //! *O*(1) pop (from the end).
9 //! Vectors ensure they never allocate more than `isize::MAX` bytes.
13 //! You can explicitly create a [`Vec`] with [`Vec::new`]:
16 //! let v: Vec<i32> = Vec::new();
19 //! ...or by using the [`vec!`] macro:
22 //! let v: Vec<i32> = vec![];
24 //! let v = vec![1, 2, 3, 4, 5];
26 //! let v = vec![0; 10]; // ten zeroes
29 //! You can [`push`] values onto the end of a vector (which will grow the vector
33 //! let mut v = vec![1, 2];
38 //! Popping values works in much the same way:
41 //! let mut v = vec![1, 2];
43 //! let two = v.pop();
46 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
49 //! let mut v = vec![1, 2, 3];
54 //! [`push`]: Vec::push
56 #![stable(feature = "rust1", since = "1.0.0")]
58 #[cfg(not(no_global_oom_handling))]
60 use core::cmp::Ordering;
61 use core::convert::TryFrom;
63 use core::hash::{Hash, Hasher};
64 use core::intrinsics::{arith_offset, assume};
66 #[cfg(not(no_global_oom_handling))]
67 use core::iter::FromIterator;
68 use core::marker::PhantomData;
69 use core::mem::{self, ManuallyDrop, MaybeUninit};
70 use core::ops::{self, Index, IndexMut, Range, RangeBounds};
71 use core::ptr::{self, NonNull};
72 use core::slice::{self, SliceIndex};
74 use crate::alloc::{Allocator, Global};
75 #[cfg(not(no_borrow))]
76 use crate::borrow::{Cow, ToOwned};
77 use crate::boxed::Box;
78 use crate::collections::TryReserveError;
79 use crate::raw_vec::RawVec;
81 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
82 pub use self::drain_filter::DrainFilter;
86 #[cfg(not(no_global_oom_handling))]
87 #[stable(feature = "vec_splice", since = "1.21.0")]
88 pub use self::splice::Splice;
90 #[cfg(not(no_global_oom_handling))]
93 #[stable(feature = "drain", since = "1.6.0")]
94 pub use self::drain::Drain;
98 #[cfg(not(no_borrow))]
99 #[cfg(not(no_global_oom_handling))]
102 #[cfg(not(no_global_oom_handling))]
103 pub(crate) use self::in_place_collect::AsVecIntoIter;
104 #[stable(feature = "rust1", since = "1.0.0")]
105 pub use self::into_iter::IntoIter;
109 #[cfg(not(no_global_oom_handling))]
110 use self::is_zero::IsZero;
114 #[cfg(not(no_global_oom_handling))]
115 mod in_place_collect;
119 #[cfg(not(no_global_oom_handling))]
120 use self::spec_from_elem::SpecFromElem;
122 #[cfg(not(no_global_oom_handling))]
125 use self::set_len_on_drop::SetLenOnDrop;
129 #[cfg(not(no_global_oom_handling))]
130 use self::in_place_drop::InPlaceDrop;
132 #[cfg(not(no_global_oom_handling))]
135 #[cfg(not(no_global_oom_handling))]
136 use self::spec_from_iter_nested::SpecFromIterNested;
138 #[cfg(not(no_global_oom_handling))]
139 mod spec_from_iter_nested;
141 #[cfg(not(no_global_oom_handling))]
142 use self::spec_from_iter::SpecFromIter;
144 #[cfg(not(no_global_oom_handling))]
147 #[cfg(not(no_global_oom_handling))]
148 use self::spec_extend::SpecExtend;
150 use self::spec_extend::TrySpecExtend;
154 /// A contiguous growable array type, written as `Vec<T>`, short for 'vector'.
159 /// let mut vec = Vec::new();
163 /// assert_eq!(vec.len(), 2);
164 /// assert_eq!(vec[0], 1);
166 /// assert_eq!(vec.pop(), Some(2));
167 /// assert_eq!(vec.len(), 1);
170 /// assert_eq!(vec[0], 7);
172 /// vec.extend([1, 2, 3].iter().copied());
177 /// assert_eq!(vec, [7, 1, 2, 3]);
180 /// The [`vec!`] macro is provided for convenient initialization:
183 /// let mut vec1 = vec![1, 2, 3];
185 /// let vec2 = Vec::from([1, 2, 3, 4]);
186 /// assert_eq!(vec1, vec2);
189 /// It can also initialize each element of a `Vec<T>` with a given value.
190 /// This may be more efficient than performing allocation and initialization
191 /// in separate steps, especially when initializing a vector of zeros:
194 /// let vec = vec![0; 5];
195 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
197 /// // The following is equivalent, but potentially slower:
198 /// let mut vec = Vec::with_capacity(5);
199 /// vec.resize(5, 0);
200 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
203 /// For more information, see
204 /// [Capacity and Reallocation](#capacity-and-reallocation).
206 /// Use a `Vec<T>` as an efficient stack:
209 /// let mut stack = Vec::new();
215 /// while let Some(top) = stack.pop() {
216 /// // Prints 3, 2, 1
217 /// println!("{top}");
223 /// The `Vec` type allows to access values by index, because it implements the
224 /// [`Index`] trait. An example will be more explicit:
227 /// let v = vec![0, 2, 4, 6];
228 /// println!("{}", v[1]); // it will display '2'
231 /// However be careful: if you try to access an index which isn't in the `Vec`,
232 /// your software will panic! You cannot do this:
235 /// let v = vec![0, 2, 4, 6];
236 /// println!("{}", v[6]); // it will panic!
239 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
244 /// A `Vec` can be mutable. On the other hand, slices are read-only objects.
245 /// To get a [slice][prim@slice], use [`&`]. Example:
248 /// fn read_slice(slice: &[usize]) {
252 /// let v = vec![0, 1];
255 /// // ... and that's all!
256 /// // you can also do it like this:
257 /// let u: &[usize] = &v;
259 /// let u: &[_] = &v;
262 /// In Rust, it's more common to pass slices as arguments rather than vectors
263 /// when you just want to provide read access. The same goes for [`String`] and
266 /// # Capacity and reallocation
268 /// The capacity of a vector is the amount of space allocated for any future
269 /// elements that will be added onto the vector. This is not to be confused with
270 /// the *length* of a vector, which specifies the number of actual elements
271 /// within the vector. If a vector's length exceeds its capacity, its capacity
272 /// will automatically be increased, but its elements will have to be
275 /// For example, a vector with capacity 10 and length 0 would be an empty vector
276 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
277 /// vector will not change its capacity or cause reallocation to occur. However,
278 /// if the vector's length is increased to 11, it will have to reallocate, which
279 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
280 /// whenever possible to specify how big the vector is expected to get.
284 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
285 /// about its design. This ensures that it's as low-overhead as possible in
286 /// the general case, and can be correctly manipulated in primitive ways
287 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
288 /// If additional type parameters are added (e.g., to support custom allocators),
289 /// overriding their defaults may change the behavior.
291 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
292 /// triplet. No more, no less. The order of these fields is completely
293 /// unspecified, and you should use the appropriate methods to modify these.
294 /// The pointer will never be null, so this type is null-pointer-optimized.
296 /// However, the pointer might not actually point to allocated memory. In particular,
297 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
298 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
299 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
300 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
301 /// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only
302 /// if <code>[mem::size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation
303 /// details are very subtle --- if you intend to allocate memory using a `Vec`
304 /// and use it for something else (either to pass to unsafe code, or to build your
305 /// own memory-backed collection), be sure to deallocate this memory by using
306 /// `from_raw_parts` to recover the `Vec` and then dropping it.
308 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
309 /// (as defined by the allocator Rust is configured to use by default), and its
310 /// pointer points to [`len`] initialized, contiguous elements in order (what
311 /// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>
312 /// logically uninitialized, contiguous elements.
314 /// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
315 /// visualized as below. The top part is the `Vec` struct, it contains a
316 /// pointer to the head of the allocation in the heap, length and capacity.
317 /// The bottom part is the allocation on the heap, a contiguous memory block.
321 /// +--------+--------+--------+
322 /// | 0x0123 | 2 | 4 |
323 /// +--------+--------+--------+
326 /// Heap +--------+--------+--------+--------+
327 /// | 'a' | 'b' | uninit | uninit |
328 /// +--------+--------+--------+--------+
331 /// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
332 /// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
333 /// layout (including the order of fields).
335 /// `Vec` will never perform a "small optimization" where elements are actually
336 /// stored on the stack for two reasons:
338 /// * It would make it more difficult for unsafe code to correctly manipulate
339 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
340 /// only moved, and it would be more difficult to determine if a `Vec` had
341 /// actually allocated memory.
343 /// * It would penalize the general case, incurring an additional branch
346 /// `Vec` will never automatically shrink itself, even if completely empty. This
347 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
348 /// and then filling it back up to the same [`len`] should incur no calls to
349 /// the allocator. If you wish to free up unused memory, use
350 /// [`shrink_to_fit`] or [`shrink_to`].
352 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
353 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
354 /// <code>[len] == [capacity]</code>. That is, the reported capacity is completely
355 /// accurate, and can be relied on. It can even be used to manually free the memory
356 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
357 /// when not necessary.
359 /// `Vec` does not guarantee any particular growth strategy when reallocating
360 /// when full, nor when [`reserve`] is called. The current strategy is basic
361 /// and it may prove desirable to use a non-constant growth factor. Whatever
362 /// strategy is used will of course guarantee *O*(1) amortized [`push`].
364 /// `vec![x; n]`, `vec![a, b, c, d]`, and
365 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
366 /// with exactly the requested capacity. If <code>[len] == [capacity]</code>,
367 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
368 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
370 /// `Vec` will not specifically overwrite any data that is removed from it,
371 /// but also won't specifically preserve it. Its uninitialized memory is
372 /// scratch space that it may use however it wants. It will generally just do
373 /// whatever is most efficient or otherwise easy to implement. Do not rely on
374 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
375 /// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory
376 /// first, that might not actually happen because the optimizer does not consider
377 /// this a side-effect that must be preserved. There is one case which we will
378 /// not break, however: using `unsafe` code to write to the excess capacity,
379 /// and then increasing the length to match, is always valid.
381 /// Currently, `Vec` does not guarantee the order in which elements are dropped.
382 /// The order has changed in the past and may change again.
384 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
385 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
386 /// [`String`]: crate::string::String
387 /// [`&str`]: type@str
388 /// [`shrink_to_fit`]: Vec::shrink_to_fit
389 /// [`shrink_to`]: Vec::shrink_to
390 /// [capacity]: Vec::capacity
391 /// [`capacity`]: Vec::capacity
392 /// [mem::size_of::\<T>]: core::mem::size_of
394 /// [`len`]: Vec::len
395 /// [`push`]: Vec::push
396 /// [`insert`]: Vec::insert
397 /// [`reserve`]: Vec::reserve
398 /// [`MaybeUninit`]: core::mem::MaybeUninit
399 /// [owned slice]: Box
400 #[stable(feature = "rust1", since = "1.0.0")]
401 #[cfg_attr(not(test), rustc_diagnostic_item = "Vec")]
402 #[rustc_insignificant_dtor]
403 pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
408 ////////////////////////////////////////////////////////////////////////////////
410 ////////////////////////////////////////////////////////////////////////////////
413 /// Constructs a new, empty `Vec<T>`.
415 /// The vector will not allocate until elements are pushed onto it.
420 /// # #![allow(unused_mut)]
421 /// let mut vec: Vec<i32> = Vec::new();
424 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
425 #[stable(feature = "rust1", since = "1.0.0")]
427 pub const fn new() -> Self {
428 Vec { buf: RawVec::NEW, len: 0 }
431 /// Constructs a new, empty `Vec<T>` with the specified capacity.
433 /// The vector will be able to hold exactly `capacity` elements without
434 /// reallocating. If `capacity` is 0, the vector will not allocate.
436 /// It is important to note that although the returned vector has the
437 /// *capacity* specified, the vector will have a zero *length*. For an
438 /// explanation of the difference between length and capacity, see
439 /// *[Capacity and reallocation]*.
441 /// [Capacity and reallocation]: #capacity-and-reallocation
445 /// Panics if the new capacity exceeds `isize::MAX` bytes.
450 /// let mut vec = Vec::with_capacity(10);
452 /// // The vector contains no items, even though it has capacity for more
453 /// assert_eq!(vec.len(), 0);
454 /// assert_eq!(vec.capacity(), 10);
456 /// // These are all done without reallocating...
460 /// assert_eq!(vec.len(), 10);
461 /// assert_eq!(vec.capacity(), 10);
463 /// // ...but this may make the vector reallocate
465 /// assert_eq!(vec.len(), 11);
466 /// assert!(vec.capacity() >= 11);
468 #[cfg(not(no_global_oom_handling))]
470 #[stable(feature = "rust1", since = "1.0.0")]
472 pub fn with_capacity(capacity: usize) -> Self {
473 Self::with_capacity_in(capacity, Global)
476 /// Tries to construct a new, empty `Vec<T>` with the specified capacity.
478 /// The vector will be able to hold exactly `capacity` elements without
479 /// reallocating. If `capacity` is 0, the vector will not allocate.
481 /// It is important to note that although the returned vector has the
482 /// *capacity* specified, the vector will have a zero *length*. For an
483 /// explanation of the difference between length and capacity, see
484 /// *[Capacity and reallocation]*.
486 /// [Capacity and reallocation]: #capacity-and-reallocation
491 /// let mut vec = Vec::try_with_capacity(10).unwrap();
493 /// // The vector contains no items, even though it has capacity for more
494 /// assert_eq!(vec.len(), 0);
495 /// assert_eq!(vec.capacity(), 10);
497 /// // These are all done without reallocating...
501 /// assert_eq!(vec.len(), 10);
502 /// assert_eq!(vec.capacity(), 10);
504 /// // ...but this may make the vector reallocate
506 /// assert_eq!(vec.len(), 11);
507 /// assert!(vec.capacity() >= 11);
509 /// let mut result = Vec::try_with_capacity(usize::MAX);
510 /// assert!(result.is_err());
513 #[stable(feature = "kernel", since = "1.0.0")]
514 pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> {
515 Self::try_with_capacity_in(capacity, Global)
518 /// Creates a `Vec<T>` directly from the raw components of another vector.
522 /// This is highly unsafe, due to the number of invariants that aren't
525 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
526 /// (at least, it's highly likely to be incorrect if it wasn't).
527 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
528 /// (`T` having a less strict alignment is not sufficient, the alignment really
529 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
530 /// allocated and deallocated with the same layout.)
531 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
532 /// to be the same size as the pointer was allocated with. (Because similar to
533 /// alignment, [`dealloc`] must be called with the same layout `size`.)
534 /// * `length` needs to be less than or equal to `capacity`.
536 /// Violating these may cause problems like corrupting the allocator's
537 /// internal data structures. For example it is normally **not** safe
538 /// to build a `Vec<u8>` from a pointer to a C `char` array with length
539 /// `size_t`, doing so is only safe if the array was initially allocated by
540 /// a `Vec` or `String`.
541 /// It's also not safe to build one from a `Vec<u16>` and its length, because
542 /// the allocator cares about the alignment, and these two types have different
543 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
544 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
545 /// these issues, it is often preferable to do casting/transmuting using
546 /// [`slice::from_raw_parts`] instead.
548 /// The ownership of `ptr` is effectively transferred to the
549 /// `Vec<T>` which may then deallocate, reallocate or change the
550 /// contents of memory pointed to by the pointer at will. Ensure
551 /// that nothing else uses the pointer after calling this
554 /// [`String`]: crate::string::String
555 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
563 /// let v = vec![1, 2, 3];
565 // FIXME Update this when vec_into_raw_parts is stabilized
566 /// // Prevent running `v`'s destructor so we are in complete control
567 /// // of the allocation.
568 /// let mut v = mem::ManuallyDrop::new(v);
570 /// // Pull out the various important pieces of information about `v`
571 /// let p = v.as_mut_ptr();
572 /// let len = v.len();
573 /// let cap = v.capacity();
576 /// // Overwrite memory with 4, 5, 6
577 /// for i in 0..len as isize {
578 /// ptr::write(p.offset(i), 4 + i);
581 /// // Put everything back together into a Vec
582 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
583 /// assert_eq!(rebuilt, [4, 5, 6]);
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
589 unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
593 impl<T, A: Allocator> Vec<T, A> {
594 /// Constructs a new, empty `Vec<T, A>`.
596 /// The vector will not allocate until elements are pushed onto it.
601 /// #![feature(allocator_api)]
603 /// use std::alloc::System;
605 /// # #[allow(unused_mut)]
606 /// let mut vec: Vec<i32, _> = Vec::new_in(System);
609 #[unstable(feature = "allocator_api", issue = "32838")]
610 pub const fn new_in(alloc: A) -> Self {
611 Vec { buf: RawVec::new_in(alloc), len: 0 }
614 /// Constructs a new, empty `Vec<T, A>` with the specified capacity with the provided
617 /// The vector will be able to hold exactly `capacity` elements without
618 /// reallocating. If `capacity` is 0, the vector will not allocate.
620 /// It is important to note that although the returned vector has the
621 /// *capacity* specified, the vector will have a zero *length*. For an
622 /// explanation of the difference between length and capacity, see
623 /// *[Capacity and reallocation]*.
625 /// [Capacity and reallocation]: #capacity-and-reallocation
629 /// Panics if the new capacity exceeds `isize::MAX` bytes.
634 /// #![feature(allocator_api)]
636 /// use std::alloc::System;
638 /// let mut vec = Vec::with_capacity_in(10, System);
640 /// // The vector contains no items, even though it has capacity for more
641 /// assert_eq!(vec.len(), 0);
642 /// assert_eq!(vec.capacity(), 10);
644 /// // These are all done without reallocating...
648 /// assert_eq!(vec.len(), 10);
649 /// assert_eq!(vec.capacity(), 10);
651 /// // ...but this may make the vector reallocate
653 /// assert_eq!(vec.len(), 11);
654 /// assert!(vec.capacity() >= 11);
656 #[cfg(not(no_global_oom_handling))]
658 #[unstable(feature = "allocator_api", issue = "32838")]
659 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
660 Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
663 /// Tries to construct a new, empty `Vec<T, A>` with the specified capacity
664 /// with the provided allocator.
666 /// The vector will be able to hold exactly `capacity` elements without
667 /// reallocating. If `capacity` is 0, the vector will not allocate.
669 /// It is important to note that although the returned vector has the
670 /// *capacity* specified, the vector will have a zero *length*. For an
671 /// explanation of the difference between length and capacity, see
672 /// *[Capacity and reallocation]*.
674 /// [Capacity and reallocation]: #capacity-and-reallocation
679 /// #![feature(allocator_api)]
681 /// use std::alloc::System;
683 /// let mut vec = Vec::try_with_capacity_in(10, System).unwrap();
685 /// // The vector contains no items, even though it has capacity for more
686 /// assert_eq!(vec.len(), 0);
687 /// assert_eq!(vec.capacity(), 10);
689 /// // These are all done without reallocating...
693 /// assert_eq!(vec.len(), 10);
694 /// assert_eq!(vec.capacity(), 10);
696 /// // ...but this may make the vector reallocate
698 /// assert_eq!(vec.len(), 11);
699 /// assert!(vec.capacity() >= 11);
701 /// let mut result = Vec::try_with_capacity_in(usize::MAX, System);
702 /// assert!(result.is_err());
705 #[stable(feature = "kernel", since = "1.0.0")]
706 pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
707 Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 })
710 /// Creates a `Vec<T, A>` directly from the raw components of another vector.
714 /// This is highly unsafe, due to the number of invariants that aren't
717 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
718 /// (at least, it's highly likely to be incorrect if it wasn't).
719 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
720 /// (`T` having a less strict alignment is not sufficient, the alignment really
721 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
722 /// allocated and deallocated with the same layout.)
723 /// * `length` needs to be less than or equal to `capacity`.
724 /// * `capacity` needs to be the capacity that the pointer was allocated with.
726 /// Violating these may cause problems like corrupting the allocator's
727 /// internal data structures. For example it is **not** safe
728 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
729 /// It's also not safe to build one from a `Vec<u16>` and its length, because
730 /// the allocator cares about the alignment, and these two types have different
731 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
732 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
734 /// The ownership of `ptr` is effectively transferred to the
735 /// `Vec<T>` which may then deallocate, reallocate or change the
736 /// contents of memory pointed to by the pointer at will. Ensure
737 /// that nothing else uses the pointer after calling this
740 /// [`String`]: crate::string::String
741 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
746 /// #![feature(allocator_api)]
748 /// use std::alloc::System;
753 /// let mut v = Vec::with_capacity_in(3, System);
758 // FIXME Update this when vec_into_raw_parts is stabilized
759 /// // Prevent running `v`'s destructor so we are in complete control
760 /// // of the allocation.
761 /// let mut v = mem::ManuallyDrop::new(v);
763 /// // Pull out the various important pieces of information about `v`
764 /// let p = v.as_mut_ptr();
765 /// let len = v.len();
766 /// let cap = v.capacity();
767 /// let alloc = v.allocator();
770 /// // Overwrite memory with 4, 5, 6
771 /// for i in 0..len as isize {
772 /// ptr::write(p.offset(i), 4 + i);
775 /// // Put everything back together into a Vec
776 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
777 /// assert_eq!(rebuilt, [4, 5, 6]);
781 #[unstable(feature = "allocator_api", issue = "32838")]
782 pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
783 unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
786 /// Decomposes a `Vec<T>` into its raw components.
788 /// Returns the raw pointer to the underlying data, the length of
789 /// the vector (in elements), and the allocated capacity of the
790 /// data (in elements). These are the same arguments in the same
791 /// order as the arguments to [`from_raw_parts`].
793 /// After calling this function, the caller is responsible for the
794 /// memory previously managed by the `Vec`. The only way to do
795 /// this is to convert the raw pointer, length, and capacity back
796 /// into a `Vec` with the [`from_raw_parts`] function, allowing
797 /// the destructor to perform the cleanup.
799 /// [`from_raw_parts`]: Vec::from_raw_parts
804 /// #![feature(vec_into_raw_parts)]
805 /// let v: Vec<i32> = vec![-1, 0, 1];
807 /// let (ptr, len, cap) = v.into_raw_parts();
809 /// let rebuilt = unsafe {
810 /// // We can now make changes to the components, such as
811 /// // transmuting the raw pointer to a compatible type.
812 /// let ptr = ptr as *mut u32;
814 /// Vec::from_raw_parts(ptr, len, cap)
816 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
818 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
819 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
820 let mut me = ManuallyDrop::new(self);
821 (me.as_mut_ptr(), me.len(), me.capacity())
824 /// Decomposes a `Vec<T>` into its raw components.
826 /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
827 /// the allocated capacity of the data (in elements), and the allocator. These are the same
828 /// arguments in the same order as the arguments to [`from_raw_parts_in`].
830 /// After calling this function, the caller is responsible for the
831 /// memory previously managed by the `Vec`. The only way to do
832 /// this is to convert the raw pointer, length, and capacity back
833 /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
834 /// the destructor to perform the cleanup.
836 /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
841 /// #![feature(allocator_api, vec_into_raw_parts)]
843 /// use std::alloc::System;
845 /// let mut v: Vec<i32, System> = Vec::new_in(System);
850 /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
852 /// let rebuilt = unsafe {
853 /// // We can now make changes to the components, such as
854 /// // transmuting the raw pointer to a compatible type.
855 /// let ptr = ptr as *mut u32;
857 /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
859 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
861 #[unstable(feature = "allocator_api", issue = "32838")]
862 // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
863 pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
864 let mut me = ManuallyDrop::new(self);
866 let capacity = me.capacity();
867 let ptr = me.as_mut_ptr();
868 let alloc = unsafe { ptr::read(me.allocator()) };
869 (ptr, len, capacity, alloc)
872 /// Returns the number of elements the vector can hold without
878 /// let vec: Vec<i32> = Vec::with_capacity(10);
879 /// assert_eq!(vec.capacity(), 10);
882 #[stable(feature = "rust1", since = "1.0.0")]
883 pub fn capacity(&self) -> usize {
887 /// Reserves capacity for at least `additional` more elements to be inserted
888 /// in the given `Vec<T>`. The collection may reserve more space to avoid
889 /// frequent reallocations. After calling `reserve`, capacity will be
890 /// greater than or equal to `self.len() + additional`. Does nothing if
891 /// capacity is already sufficient.
895 /// Panics if the new capacity exceeds `isize::MAX` bytes.
900 /// let mut vec = vec![1];
902 /// assert!(vec.capacity() >= 11);
904 #[cfg(not(no_global_oom_handling))]
905 #[stable(feature = "rust1", since = "1.0.0")]
906 pub fn reserve(&mut self, additional: usize) {
907 self.buf.reserve(self.len, additional);
910 /// Reserves the minimum capacity for exactly `additional` more elements to
911 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
912 /// capacity will be greater than or equal to `self.len() + additional`.
913 /// Does nothing if the capacity is already sufficient.
915 /// Note that the allocator may give the collection more space than it
916 /// requests. Therefore, capacity can not be relied upon to be precisely
917 /// minimal. Prefer [`reserve`] if future insertions are expected.
919 /// [`reserve`]: Vec::reserve
923 /// Panics if the new capacity exceeds `isize::MAX` bytes.
928 /// let mut vec = vec![1];
929 /// vec.reserve_exact(10);
930 /// assert!(vec.capacity() >= 11);
932 #[cfg(not(no_global_oom_handling))]
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn reserve_exact(&mut self, additional: usize) {
935 self.buf.reserve_exact(self.len, additional);
938 /// Tries to reserve capacity for at least `additional` more elements to be inserted
939 /// in the given `Vec<T>`. The collection may reserve more space to avoid
940 /// frequent reallocations. After calling `try_reserve`, capacity will be
941 /// greater than or equal to `self.len() + additional`. Does nothing if
942 /// capacity is already sufficient.
946 /// If the capacity overflows, or the allocator reports a failure, then an error
952 /// use std::collections::TryReserveError;
954 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
955 /// let mut output = Vec::new();
957 /// // Pre-reserve the memory, exiting if we can't
958 /// output.try_reserve(data.len())?;
960 /// // Now we know this can't OOM in the middle of our complex work
961 /// output.extend(data.iter().map(|&val| {
962 /// val * 2 + 5 // very complicated
967 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
969 #[stable(feature = "try_reserve", since = "1.57.0")]
970 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
971 self.buf.try_reserve(self.len, additional)
974 /// Tries to reserve the minimum capacity for exactly `additional`
975 /// elements to be inserted in the given `Vec<T>`. After calling
976 /// `try_reserve_exact`, capacity will be greater than or equal to
977 /// `self.len() + additional` if it returns `Ok(())`.
978 /// Does nothing if the capacity is already sufficient.
980 /// Note that the allocator may give the collection more space than it
981 /// requests. Therefore, capacity can not be relied upon to be precisely
982 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
984 /// [`try_reserve`]: Vec::try_reserve
988 /// If the capacity overflows, or the allocator reports a failure, then an error
994 /// use std::collections::TryReserveError;
996 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
997 /// let mut output = Vec::new();
999 /// // Pre-reserve the memory, exiting if we can't
1000 /// output.try_reserve_exact(data.len())?;
1002 /// // Now we know this can't OOM in the middle of our complex work
1003 /// output.extend(data.iter().map(|&val| {
1004 /// val * 2 + 5 // very complicated
1009 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
1011 #[stable(feature = "try_reserve", since = "1.57.0")]
1012 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1013 self.buf.try_reserve_exact(self.len, additional)
1016 /// Shrinks the capacity of the vector as much as possible.
1018 /// It will drop down as close as possible to the length but the allocator
1019 /// may still inform the vector that there is space for a few more elements.
1024 /// let mut vec = Vec::with_capacity(10);
1025 /// vec.extend([1, 2, 3]);
1026 /// assert_eq!(vec.capacity(), 10);
1027 /// vec.shrink_to_fit();
1028 /// assert!(vec.capacity() >= 3);
1030 #[cfg(not(no_global_oom_handling))]
1031 #[stable(feature = "rust1", since = "1.0.0")]
1032 pub fn shrink_to_fit(&mut self) {
1033 // The capacity is never less than the length, and there's nothing to do when
1034 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
1035 // by only calling it with a greater capacity.
1036 if self.capacity() > self.len {
1037 self.buf.shrink_to_fit(self.len);
1041 /// Shrinks the capacity of the vector with a lower bound.
1043 /// The capacity will remain at least as large as both the length
1044 /// and the supplied value.
1046 /// If the current capacity is less than the lower limit, this is a no-op.
1051 /// let mut vec = Vec::with_capacity(10);
1052 /// vec.extend([1, 2, 3]);
1053 /// assert_eq!(vec.capacity(), 10);
1054 /// vec.shrink_to(4);
1055 /// assert!(vec.capacity() >= 4);
1056 /// vec.shrink_to(0);
1057 /// assert!(vec.capacity() >= 3);
1059 #[cfg(not(no_global_oom_handling))]
1060 #[stable(feature = "shrink_to", since = "1.56.0")]
1061 pub fn shrink_to(&mut self, min_capacity: usize) {
1062 if self.capacity() > min_capacity {
1063 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
1067 /// Converts the vector into [`Box<[T]>`][owned slice].
1069 /// Note that this will drop any excess capacity.
1071 /// [owned slice]: Box
1076 /// let v = vec![1, 2, 3];
1078 /// let slice = v.into_boxed_slice();
1081 /// Any excess capacity is removed:
1084 /// let mut vec = Vec::with_capacity(10);
1085 /// vec.extend([1, 2, 3]);
1087 /// assert_eq!(vec.capacity(), 10);
1088 /// let slice = vec.into_boxed_slice();
1089 /// assert_eq!(slice.into_vec().capacity(), 3);
1091 #[cfg(not(no_global_oom_handling))]
1092 #[stable(feature = "rust1", since = "1.0.0")]
1093 pub fn into_boxed_slice(mut self) -> Box<[T], A> {
1095 self.shrink_to_fit();
1096 let me = ManuallyDrop::new(self);
1097 let buf = ptr::read(&me.buf);
1099 buf.into_box(len).assume_init()
1103 /// Shortens the vector, keeping the first `len` elements and dropping
1106 /// If `len` is greater than the vector's current length, this has no
1109 /// The [`drain`] method can emulate `truncate`, but causes the excess
1110 /// elements to be returned instead of dropped.
1112 /// Note that this method has no effect on the allocated capacity
1117 /// Truncating a five element vector to two elements:
1120 /// let mut vec = vec![1, 2, 3, 4, 5];
1121 /// vec.truncate(2);
1122 /// assert_eq!(vec, [1, 2]);
1125 /// No truncation occurs when `len` is greater than the vector's current
1129 /// let mut vec = vec![1, 2, 3];
1130 /// vec.truncate(8);
1131 /// assert_eq!(vec, [1, 2, 3]);
1134 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
1138 /// let mut vec = vec![1, 2, 3];
1139 /// vec.truncate(0);
1140 /// assert_eq!(vec, []);
1143 /// [`clear`]: Vec::clear
1144 /// [`drain`]: Vec::drain
1145 #[stable(feature = "rust1", since = "1.0.0")]
1146 pub fn truncate(&mut self, len: usize) {
1147 // This is safe because:
1149 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
1150 // case avoids creating an invalid slice, and
1151 // * the `len` of the vector is shrunk before calling `drop_in_place`,
1152 // such that no value will be dropped twice in case `drop_in_place`
1153 // were to panic once (if it panics twice, the program aborts).
1155 // Note: It's intentional that this is `>` and not `>=`.
1156 // Changing it to `>=` has negative performance
1157 // implications in some cases. See #78884 for more.
1161 let remaining_len = self.len - len;
1162 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
1164 ptr::drop_in_place(s);
1168 /// Extracts a slice containing the entire vector.
1170 /// Equivalent to `&s[..]`.
1175 /// use std::io::{self, Write};
1176 /// let buffer = vec![1, 2, 3, 5, 8];
1177 /// io::sink().write(buffer.as_slice()).unwrap();
1180 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1181 pub fn as_slice(&self) -> &[T] {
1185 /// Extracts a mutable slice of the entire vector.
1187 /// Equivalent to `&mut s[..]`.
1192 /// use std::io::{self, Read};
1193 /// let mut buffer = vec![0; 3];
1194 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1197 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1198 pub fn as_mut_slice(&mut self) -> &mut [T] {
1202 /// Returns a raw pointer to the vector's buffer.
1204 /// The caller must ensure that the vector outlives the pointer this
1205 /// function returns, or else it will end up pointing to garbage.
1206 /// Modifying the vector may cause its buffer to be reallocated,
1207 /// which would also make any pointers to it invalid.
1209 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1210 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1211 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1216 /// let x = vec![1, 2, 4];
1217 /// let x_ptr = x.as_ptr();
1220 /// for i in 0..x.len() {
1221 /// assert_eq!(*x_ptr.add(i), 1 << i);
1226 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1227 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1229 pub fn as_ptr(&self) -> *const T {
1230 // We shadow the slice method of the same name to avoid going through
1231 // `deref`, which creates an intermediate reference.
1232 let ptr = self.buf.ptr();
1234 assume(!ptr.is_null());
1239 /// Returns an unsafe mutable pointer to the vector's buffer.
1241 /// The caller must ensure that the vector outlives the pointer this
1242 /// function returns, or else it will end up pointing to garbage.
1243 /// Modifying the vector may cause its buffer to be reallocated,
1244 /// which would also make any pointers to it invalid.
1249 /// // Allocate vector big enough for 4 elements.
1251 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1252 /// let x_ptr = x.as_mut_ptr();
1254 /// // Initialize elements via raw pointer writes, then set length.
1256 /// for i in 0..size {
1257 /// *x_ptr.add(i) = i as i32;
1259 /// x.set_len(size);
1261 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1263 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1265 pub fn as_mut_ptr(&mut self) -> *mut T {
1266 // We shadow the slice method of the same name to avoid going through
1267 // `deref_mut`, which creates an intermediate reference.
1268 let ptr = self.buf.ptr();
1270 assume(!ptr.is_null());
1275 /// Returns a reference to the underlying allocator.
1276 #[unstable(feature = "allocator_api", issue = "32838")]
1278 pub fn allocator(&self) -> &A {
1279 self.buf.allocator()
1282 /// Forces the length of the vector to `new_len`.
1284 /// This is a low-level operation that maintains none of the normal
1285 /// invariants of the type. Normally changing the length of a vector
1286 /// is done using one of the safe operations instead, such as
1287 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
1289 /// [`truncate`]: Vec::truncate
1290 /// [`resize`]: Vec::resize
1291 /// [`extend`]: Extend::extend
1292 /// [`clear`]: Vec::clear
1296 /// - `new_len` must be less than or equal to [`capacity()`].
1297 /// - The elements at `old_len..new_len` must be initialized.
1299 /// [`capacity()`]: Vec::capacity
1303 /// This method can be useful for situations in which the vector
1304 /// is serving as a buffer for other code, particularly over FFI:
1307 /// # #![allow(dead_code)]
1308 /// # // This is just a minimal skeleton for the doc example;
1309 /// # // don't use this as a starting point for a real library.
1310 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
1311 /// # const Z_OK: i32 = 0;
1313 /// # fn deflateGetDictionary(
1314 /// # strm: *mut std::ffi::c_void,
1315 /// # dictionary: *mut u8,
1316 /// # dictLength: *mut usize,
1319 /// # impl StreamWrapper {
1320 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
1321 /// // Per the FFI method's docs, "32768 bytes is always enough".
1322 /// let mut dict = Vec::with_capacity(32_768);
1323 /// let mut dict_length = 0;
1324 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
1325 /// // 1. `dict_length` elements were initialized.
1326 /// // 2. `dict_length` <= the capacity (32_768)
1327 /// // which makes `set_len` safe to call.
1329 /// // Make the FFI call...
1330 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
1332 /// // ...and update the length to what was initialized.
1333 /// dict.set_len(dict_length);
1343 /// While the following example is sound, there is a memory leak since
1344 /// the inner vectors were not freed prior to the `set_len` call:
1347 /// let mut vec = vec![vec![1, 0, 0],
1351 /// // 1. `old_len..0` is empty so no elements need to be initialized.
1352 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
1358 /// Normally, here, one would use [`clear`] instead to correctly drop
1359 /// the contents and thus not leak memory.
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 pub unsafe fn set_len(&mut self, new_len: usize) {
1363 debug_assert!(new_len <= self.capacity());
1368 /// Removes an element from the vector and returns it.
1370 /// The removed element is replaced by the last element of the vector.
1372 /// This does not preserve ordering, but is *O*(1).
1373 /// If you need to preserve the element order, use [`remove`] instead.
1375 /// [`remove`]: Vec::remove
1379 /// Panics if `index` is out of bounds.
1384 /// let mut v = vec!["foo", "bar", "baz", "qux"];
1386 /// assert_eq!(v.swap_remove(1), "bar");
1387 /// assert_eq!(v, ["foo", "qux", "baz"]);
1389 /// assert_eq!(v.swap_remove(0), "foo");
1390 /// assert_eq!(v, ["baz", "qux"]);
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 pub fn swap_remove(&mut self, index: usize) -> T {
1397 fn assert_failed(index: usize, len: usize) -> ! {
1398 panic!("swap_remove index (is {index}) should be < len (is {len})");
1401 let len = self.len();
1403 assert_failed(index, len);
1406 // We replace self[index] with the last element. Note that if the
1407 // bounds check above succeeds there must be a last element (which
1408 // can be self[index] itself).
1409 let value = ptr::read(self.as_ptr().add(index));
1410 let base_ptr = self.as_mut_ptr();
1411 ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
1412 self.set_len(len - 1);
1417 /// Inserts an element at position `index` within the vector, shifting all
1418 /// elements after it to the right.
1422 /// Panics if `index > len`.
1427 /// let mut vec = vec![1, 2, 3];
1428 /// vec.insert(1, 4);
1429 /// assert_eq!(vec, [1, 4, 2, 3]);
1430 /// vec.insert(4, 5);
1431 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1433 #[cfg(not(no_global_oom_handling))]
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 pub fn insert(&mut self, index: usize, element: T) {
1438 fn assert_failed(index: usize, len: usize) -> ! {
1439 panic!("insertion index (is {index}) should be <= len (is {len})");
1442 let len = self.len();
1444 assert_failed(index, len);
1447 // space for the new element
1448 if len == self.buf.capacity() {
1454 // The spot to put the new value
1456 let p = self.as_mut_ptr().add(index);
1457 // Shift everything over to make space. (Duplicating the
1458 // `index`th element into two consecutive places.)
1459 ptr::copy(p, p.offset(1), len - index);
1460 // Write it in, overwriting the first copy of the `index`th
1462 ptr::write(p, element);
1464 self.set_len(len + 1);
1468 /// Removes and returns the element at position `index` within the vector,
1469 /// shifting all elements after it to the left.
1471 /// Note: Because this shifts over the remaining elements, it has a
1472 /// worst-case performance of *O*(*n*). If you don't need the order of elements
1473 /// to be preserved, use [`swap_remove`] instead. If you'd like to remove
1474 /// elements from the beginning of the `Vec`, consider using
1475 /// [`VecDeque::pop_front`] instead.
1477 /// [`swap_remove`]: Vec::swap_remove
1478 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
1482 /// Panics if `index` is out of bounds.
1487 /// let mut v = vec![1, 2, 3];
1488 /// assert_eq!(v.remove(1), 2);
1489 /// assert_eq!(v, [1, 3]);
1491 #[stable(feature = "rust1", since = "1.0.0")]
1493 pub fn remove(&mut self, index: usize) -> T {
1497 fn assert_failed(index: usize, len: usize) -> ! {
1498 panic!("removal index (is {index}) should be < len (is {len})");
1501 let len = self.len();
1503 assert_failed(index, len);
1509 // the place we are taking from.
1510 let ptr = self.as_mut_ptr().add(index);
1511 // copy it out, unsafely having a copy of the value on
1512 // the stack and in the vector at the same time.
1513 ret = ptr::read(ptr);
1515 // Shift everything down to fill in that spot.
1516 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1518 self.set_len(len - 1);
1523 /// Retains only the elements specified by the predicate.
1525 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
1526 /// This method operates in place, visiting each element exactly once in the
1527 /// original order, and preserves the order of the retained elements.
1532 /// let mut vec = vec![1, 2, 3, 4];
1533 /// vec.retain(|&x| x % 2 == 0);
1534 /// assert_eq!(vec, [2, 4]);
1537 /// Because the elements are visited exactly once in the original order,
1538 /// external state may be used to decide which elements to keep.
1541 /// let mut vec = vec![1, 2, 3, 4, 5];
1542 /// let keep = [false, true, true, false, true];
1543 /// let mut iter = keep.iter();
1544 /// vec.retain(|_| *iter.next().unwrap());
1545 /// assert_eq!(vec, [2, 3, 5]);
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 pub fn retain<F>(&mut self, mut f: F)
1550 F: FnMut(&T) -> bool,
1552 self.retain_mut(|elem| f(elem));
1555 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
1557 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
1558 /// This method operates in place, visiting each element exactly once in the
1559 /// original order, and preserves the order of the retained elements.
1564 /// let mut vec = vec![1, 2, 3, 4];
1565 /// vec.retain_mut(|x| if *x > 3 {
1571 /// assert_eq!(vec, [2, 3, 4]);
1573 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
1574 pub fn retain_mut<F>(&mut self, mut f: F)
1576 F: FnMut(&mut T) -> bool,
1578 let original_len = self.len();
1579 // Avoid double drop if the drop guard is not executed,
1580 // since we may make some holes during the process.
1581 unsafe { self.set_len(0) };
1583 // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
1584 // |<- processed len ->| ^- next to check
1585 // |<- deleted cnt ->|
1586 // |<- original_len ->|
1587 // Kept: Elements which predicate returns true on.
1588 // Hole: Moved or dropped element slot.
1589 // Unchecked: Unchecked valid elements.
1591 // This drop guard will be invoked when predicate or `drop` of element panicked.
1592 // It shifts unchecked elements to cover holes and `set_len` to the correct length.
1593 // In cases when predicate and `drop` never panick, it will be optimized out.
1594 struct BackshiftOnDrop<'a, T, A: Allocator> {
1595 v: &'a mut Vec<T, A>,
1596 processed_len: usize,
1598 original_len: usize,
1601 impl<T, A: Allocator> Drop for BackshiftOnDrop<'_, T, A> {
1602 fn drop(&mut self) {
1603 if self.deleted_cnt > 0 {
1604 // SAFETY: Trailing unchecked items must be valid since we never touch them.
1607 self.v.as_ptr().add(self.processed_len),
1608 self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt),
1609 self.original_len - self.processed_len,
1613 // SAFETY: After filling holes, all items are in contiguous memory.
1615 self.v.set_len(self.original_len - self.deleted_cnt);
1620 let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len };
1622 fn process_loop<F, T, A: Allocator, const DELETED: bool>(
1623 original_len: usize,
1625 g: &mut BackshiftOnDrop<'_, T, A>,
1627 F: FnMut(&mut T) -> bool,
1629 while g.processed_len != original_len {
1630 // SAFETY: Unchecked element must be valid.
1631 let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
1633 // Advance early to avoid double drop if `drop_in_place` panicked.
1634 g.processed_len += 1;
1636 // SAFETY: We never touch this element again after dropped.
1637 unsafe { ptr::drop_in_place(cur) };
1638 // We already advanced the counter.
1646 // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
1647 // We use copy for move, and never touch this element again.
1649 let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
1650 ptr::copy_nonoverlapping(cur, hole_slot, 1);
1653 g.processed_len += 1;
1657 // Stage 1: Nothing was deleted.
1658 process_loop::<F, T, A, false>(original_len, &mut f, &mut g);
1660 // Stage 2: Some elements were deleted.
1661 process_loop::<F, T, A, true>(original_len, &mut f, &mut g);
1663 // All item are processed. This can be optimized to `set_len` by LLVM.
1667 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1670 /// If the vector is sorted, this removes all duplicates.
1675 /// let mut vec = vec![10, 20, 21, 30, 20];
1677 /// vec.dedup_by_key(|i| *i / 10);
1679 /// assert_eq!(vec, [10, 20, 30, 20]);
1681 #[stable(feature = "dedup_by", since = "1.16.0")]
1683 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1685 F: FnMut(&mut T) -> K,
1688 self.dedup_by(|a, b| key(a) == key(b))
1691 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1694 /// The `same_bucket` function is passed references to two elements from the vector and
1695 /// must determine if the elements compare equal. The elements are passed in opposite order
1696 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1698 /// If the vector is sorted, this removes all duplicates.
1703 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1705 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1707 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1709 #[stable(feature = "dedup_by", since = "1.16.0")]
1710 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1712 F: FnMut(&mut T, &mut T) -> bool,
1714 let len = self.len();
1719 /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */
1720 struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> {
1721 /* Offset of the element we want to check if it is duplicate */
1724 /* Offset of the place where we want to place the non-duplicate
1725 * when we find it. */
1728 /* The Vec that would need correction if `same_bucket` panicked */
1729 vec: &'a mut Vec<T, A>,
1732 impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
1733 fn drop(&mut self) {
1734 /* This code gets executed when `same_bucket` panics */
1736 /* SAFETY: invariant guarantees that `read - write`
1737 * and `len - read` never overflow and that the copy is always
1740 let ptr = self.vec.as_mut_ptr();
1741 let len = self.vec.len();
1743 /* How many items were left when `same_bucket` panicked.
1744 * Basically vec[read..].len() */
1745 let items_left = len.wrapping_sub(self.read);
1747 /* Pointer to first item in vec[write..write+items_left] slice */
1748 let dropped_ptr = ptr.add(self.write);
1749 /* Pointer to first item in vec[read..] slice */
1750 let valid_ptr = ptr.add(self.read);
1752 /* Copy `vec[read..]` to `vec[write..write+items_left]`.
1753 * The slices can overlap, so `copy_nonoverlapping` cannot be used */
1754 ptr::copy(valid_ptr, dropped_ptr, items_left);
1756 /* How many items have been already dropped
1757 * Basically vec[read..write].len() */
1758 let dropped = self.read.wrapping_sub(self.write);
1760 self.vec.set_len(len - dropped);
1765 let mut gap = FillGapOnDrop { read: 1, write: 1, vec: self };
1766 let ptr = gap.vec.as_mut_ptr();
1768 /* Drop items while going through Vec, it should be more efficient than
1769 * doing slice partition_dedup + truncate */
1771 /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
1772 * are always in-bounds and read_ptr never aliases prev_ptr */
1774 while gap.read < len {
1775 let read_ptr = ptr.add(gap.read);
1776 let prev_ptr = ptr.add(gap.write.wrapping_sub(1));
1778 if same_bucket(&mut *read_ptr, &mut *prev_ptr) {
1779 // Increase `gap.read` now since the drop may panic.
1781 /* We have found duplicate, drop it in-place */
1782 ptr::drop_in_place(read_ptr);
1784 let write_ptr = ptr.add(gap.write);
1786 /* Because `read_ptr` can be equal to `write_ptr`, we either
1787 * have to use `copy` or conditional `copy_nonoverlapping`.
1788 * Looks like the first option is faster. */
1789 ptr::copy(read_ptr, write_ptr, 1);
1791 /* We have filled that place, so go further */
1797 /* Technically we could let `gap` clean up with its Drop, but
1798 * when `same_bucket` is guaranteed to not panic, this bloats a little
1799 * the codegen, so we just do it manually */
1800 gap.vec.set_len(gap.write);
1805 /// Appends an element to the back of a collection.
1809 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1814 /// let mut vec = vec![1, 2];
1816 /// assert_eq!(vec, [1, 2, 3]);
1818 #[cfg(not(no_global_oom_handling))]
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 pub fn push(&mut self, value: T) {
1822 // This will panic or abort if we would allocate > isize::MAX bytes
1823 // or if the length increment would overflow for zero-sized types.
1824 if self.len == self.buf.capacity() {
1825 self.buf.reserve_for_push(self.len);
1828 let end = self.as_mut_ptr().add(self.len);
1829 ptr::write(end, value);
1834 /// Tries to append an element to the back of a collection.
1839 /// let mut vec = vec![1, 2];
1840 /// vec.try_push(3).unwrap();
1841 /// assert_eq!(vec, [1, 2, 3]);
1844 #[stable(feature = "kernel", since = "1.0.0")]
1845 pub fn try_push(&mut self, value: T) -> Result<(), TryReserveError> {
1846 if self.len == self.buf.capacity() {
1847 self.buf.try_reserve_for_push(self.len)?;
1850 let end = self.as_mut_ptr().add(self.len);
1851 ptr::write(end, value);
1857 /// Removes the last element from a vector and returns it, or [`None`] if it
1860 /// If you'd like to pop the first element, consider using
1861 /// [`VecDeque::pop_front`] instead.
1863 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
1868 /// let mut vec = vec![1, 2, 3];
1869 /// assert_eq!(vec.pop(), Some(3));
1870 /// assert_eq!(vec, [1, 2]);
1873 #[stable(feature = "rust1", since = "1.0.0")]
1874 pub fn pop(&mut self) -> Option<T> {
1880 Some(ptr::read(self.as_ptr().add(self.len())))
1885 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1889 /// Panics if the number of elements in the vector overflows a `usize`.
1894 /// let mut vec = vec![1, 2, 3];
1895 /// let mut vec2 = vec![4, 5, 6];
1896 /// vec.append(&mut vec2);
1897 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1898 /// assert_eq!(vec2, []);
1900 #[cfg(not(no_global_oom_handling))]
1902 #[stable(feature = "append", since = "1.4.0")]
1903 pub fn append(&mut self, other: &mut Self) {
1905 self.append_elements(other.as_slice() as _);
1910 /// Appends elements to `self` from other buffer.
1911 #[cfg(not(no_global_oom_handling))]
1913 unsafe fn append_elements(&mut self, other: *const [T]) {
1914 let count = unsafe { (*other).len() };
1915 self.reserve(count);
1916 let len = self.len();
1917 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1921 /// Tries to append elements to `self` from other buffer.
1923 unsafe fn try_append_elements(&mut self, other: *const [T]) -> Result<(), TryReserveError> {
1924 let count = unsafe { (*other).len() };
1925 self.try_reserve(count)?;
1926 let len = self.len();
1927 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1932 /// Removes the specified range from the vector in bulk, returning all
1933 /// removed elements as an iterator. If the iterator is dropped before
1934 /// being fully consumed, it drops the remaining removed elements.
1936 /// The returned iterator keeps a mutable borrow on the vector to optimize
1937 /// its implementation.
1941 /// Panics if the starting point is greater than the end point or if
1942 /// the end point is greater than the length of the vector.
1946 /// If the returned iterator goes out of scope without being dropped (due to
1947 /// [`mem::forget`], for example), the vector may have lost and leaked
1948 /// elements arbitrarily, including elements outside the range.
1953 /// let mut v = vec![1, 2, 3];
1954 /// let u: Vec<_> = v.drain(1..).collect();
1955 /// assert_eq!(v, &[1]);
1956 /// assert_eq!(u, &[2, 3]);
1958 /// // A full range clears the vector, like `clear()` does
1960 /// assert_eq!(v, &[]);
1962 #[stable(feature = "drain", since = "1.6.0")]
1963 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1965 R: RangeBounds<usize>,
1969 // When the Drain is first created, it shortens the length of
1970 // the source vector to make sure no uninitialized or moved-from elements
1971 // are accessible at all if the Drain's destructor never gets to run.
1973 // Drain will ptr::read out the values to remove.
1974 // When finished, remaining tail of the vec is copied back to cover
1975 // the hole, and the vector length is restored to the new length.
1977 let len = self.len();
1978 let Range { start, end } = slice::range(range, ..len);
1981 // set self.vec length's to start, to be safe in case Drain is leaked
1982 self.set_len(start);
1983 // Use the borrow in the IterMut to indicate borrowing behavior of the
1984 // whole Drain iterator (like &mut T).
1985 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1988 tail_len: len - end,
1989 iter: range_slice.iter(),
1990 vec: NonNull::from(self),
1995 /// Clears the vector, removing all values.
1997 /// Note that this method has no effect on the allocated capacity
2003 /// let mut v = vec![1, 2, 3];
2007 /// assert!(v.is_empty());
2010 #[stable(feature = "rust1", since = "1.0.0")]
2011 pub fn clear(&mut self) {
2012 let elems: *mut [T] = self.as_mut_slice();
2015 // - `elems` comes directly from `as_mut_slice` and is therefore valid.
2016 // - Setting `self.len` before calling `drop_in_place` means that,
2017 // if an element's `Drop` impl panics, the vector's `Drop` impl will
2018 // do nothing (leaking the rest of the elements) instead of dropping
2022 ptr::drop_in_place(elems);
2026 /// Returns the number of elements in the vector, also referred to
2027 /// as its 'length'.
2032 /// let a = vec![1, 2, 3];
2033 /// assert_eq!(a.len(), 3);
2036 #[stable(feature = "rust1", since = "1.0.0")]
2037 pub fn len(&self) -> usize {
2041 /// Returns `true` if the vector contains no elements.
2046 /// let mut v = Vec::new();
2047 /// assert!(v.is_empty());
2050 /// assert!(!v.is_empty());
2052 #[stable(feature = "rust1", since = "1.0.0")]
2053 pub fn is_empty(&self) -> bool {
2057 /// Splits the collection into two at the given index.
2059 /// Returns a newly allocated vector containing the elements in the range
2060 /// `[at, len)`. After the call, the original vector will be left containing
2061 /// the elements `[0, at)` with its previous capacity unchanged.
2065 /// Panics if `at > len`.
2070 /// let mut vec = vec![1, 2, 3];
2071 /// let vec2 = vec.split_off(1);
2072 /// assert_eq!(vec, [1]);
2073 /// assert_eq!(vec2, [2, 3]);
2075 #[cfg(not(no_global_oom_handling))]
2077 #[must_use = "use `.truncate()` if you don't need the other half"]
2078 #[stable(feature = "split_off", since = "1.4.0")]
2079 pub fn split_off(&mut self, at: usize) -> Self
2085 fn assert_failed(at: usize, len: usize) -> ! {
2086 panic!("`at` split index (is {at}) should be <= len (is {len})");
2089 if at > self.len() {
2090 assert_failed(at, self.len());
2094 // the new vector can take over the original buffer and avoid the copy
2095 return mem::replace(
2097 Vec::with_capacity_in(self.capacity(), self.allocator().clone()),
2101 let other_len = self.len - at;
2102 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
2104 // Unsafely `set_len` and copy items to `other`.
2107 other.set_len(other_len);
2109 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
2114 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2116 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2117 /// difference, with each additional slot filled with the result of
2118 /// calling the closure `f`. The return values from `f` will end up
2119 /// in the `Vec` in the order they have been generated.
2121 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2123 /// This method uses a closure to create new values on every push. If
2124 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
2125 /// want to use the [`Default`] trait to generate values, you can
2126 /// pass [`Default::default`] as the second argument.
2131 /// let mut vec = vec![1, 2, 3];
2132 /// vec.resize_with(5, Default::default);
2133 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
2135 /// let mut vec = vec![];
2137 /// vec.resize_with(4, || { p *= 2; p });
2138 /// assert_eq!(vec, [2, 4, 8, 16]);
2140 #[cfg(not(no_global_oom_handling))]
2141 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2142 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
2146 let len = self.len();
2148 self.extend_with(new_len - len, ExtendFunc(f));
2150 self.truncate(new_len);
2154 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
2155 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
2156 /// `'a`. If the type has only static references, or none at all, then this
2157 /// may be chosen to be `'static`.
2159 /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
2160 /// so the leaked allocation may include unused capacity that is not part
2161 /// of the returned slice.
2163 /// This function is mainly useful for data that lives for the remainder of
2164 /// the program's life. Dropping the returned reference will cause a memory
2172 /// let x = vec![1, 2, 3];
2173 /// let static_ref: &'static mut [usize] = x.leak();
2174 /// static_ref[0] += 1;
2175 /// assert_eq!(static_ref, &[2, 2, 3]);
2177 #[cfg(not(no_global_oom_handling))]
2178 #[stable(feature = "vec_leak", since = "1.47.0")]
2180 pub fn leak<'a>(self) -> &'a mut [T]
2184 let mut me = ManuallyDrop::new(self);
2185 unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
2188 /// Returns the remaining spare capacity of the vector as a slice of
2189 /// `MaybeUninit<T>`.
2191 /// The returned slice can be used to fill the vector with data (e.g. by
2192 /// reading from a file) before marking the data as initialized using the
2193 /// [`set_len`] method.
2195 /// [`set_len`]: Vec::set_len
2200 /// // Allocate vector big enough for 10 elements.
2201 /// let mut v = Vec::with_capacity(10);
2203 /// // Fill in the first 3 elements.
2204 /// let uninit = v.spare_capacity_mut();
2205 /// uninit[0].write(0);
2206 /// uninit[1].write(1);
2207 /// uninit[2].write(2);
2209 /// // Mark the first 3 elements of the vector as being initialized.
2214 /// assert_eq!(&v, &[0, 1, 2]);
2216 #[stable(feature = "vec_spare_capacity", since = "1.60.0")]
2218 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
2220 // This method is not implemented in terms of `split_at_spare_mut`,
2221 // to prevent invalidation of pointers to the buffer.
2223 slice::from_raw_parts_mut(
2224 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
2225 self.buf.capacity() - self.len,
2230 /// Returns vector content as a slice of `T`, along with the remaining spare
2231 /// capacity of the vector as a slice of `MaybeUninit<T>`.
2233 /// The returned spare capacity slice can be used to fill the vector with data
2234 /// (e.g. by reading from a file) before marking the data as initialized using
2235 /// the [`set_len`] method.
2237 /// [`set_len`]: Vec::set_len
2239 /// Note that this is a low-level API, which should be used with care for
2240 /// optimization purposes. If you need to append data to a `Vec`
2241 /// you can use [`push`], [`extend`], [`extend_from_slice`],
2242 /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
2243 /// [`resize_with`], depending on your exact needs.
2245 /// [`push`]: Vec::push
2246 /// [`extend`]: Vec::extend
2247 /// [`extend_from_slice`]: Vec::extend_from_slice
2248 /// [`extend_from_within`]: Vec::extend_from_within
2249 /// [`insert`]: Vec::insert
2250 /// [`append`]: Vec::append
2251 /// [`resize`]: Vec::resize
2252 /// [`resize_with`]: Vec::resize_with
2257 /// #![feature(vec_split_at_spare)]
2259 /// let mut v = vec![1, 1, 2];
2261 /// // Reserve additional space big enough for 10 elements.
2264 /// let (init, uninit) = v.split_at_spare_mut();
2265 /// let sum = init.iter().copied().sum::<u32>();
2267 /// // Fill in the next 4 elements.
2268 /// uninit[0].write(sum);
2269 /// uninit[1].write(sum * 2);
2270 /// uninit[2].write(sum * 3);
2271 /// uninit[3].write(sum * 4);
2273 /// // Mark the 4 elements of the vector as being initialized.
2275 /// let len = v.len();
2276 /// v.set_len(len + 4);
2279 /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
2281 #[unstable(feature = "vec_split_at_spare", issue = "81944")]
2283 pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
2285 // - len is ignored and so never changed
2286 let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
2290 /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
2292 /// This method provides unique access to all vec parts at once in `extend_from_within`.
2293 unsafe fn split_at_spare_mut_with_len(
2295 ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
2296 let ptr = self.as_mut_ptr();
2298 // - `ptr` is guaranteed to be valid for `self.len` elements
2299 // - but the allocation extends out to `self.buf.capacity()` elements, possibly
2301 let spare_ptr = unsafe { ptr.add(self.len) };
2302 let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>();
2303 let spare_len = self.buf.capacity() - self.len;
2306 // - `ptr` is guaranteed to be valid for `self.len` elements
2307 // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
2309 let initialized = slice::from_raw_parts_mut(ptr, self.len);
2310 let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
2312 (initialized, spare, &mut self.len)
2317 impl<T: Clone, A: Allocator> Vec<T, A> {
2318 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2320 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2321 /// difference, with each additional slot filled with `value`.
2322 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2324 /// This method requires `T` to implement [`Clone`],
2325 /// in order to be able to clone the passed value.
2326 /// If you need more flexibility (or want to rely on [`Default`] instead of
2327 /// [`Clone`]), use [`Vec::resize_with`].
2328 /// If you only need to resize to a smaller size, use [`Vec::truncate`].
2333 /// let mut vec = vec!["hello"];
2334 /// vec.resize(3, "world");
2335 /// assert_eq!(vec, ["hello", "world", "world"]);
2337 /// let mut vec = vec![1, 2, 3, 4];
2338 /// vec.resize(2, 0);
2339 /// assert_eq!(vec, [1, 2]);
2341 #[cfg(not(no_global_oom_handling))]
2342 #[stable(feature = "vec_resize", since = "1.5.0")]
2343 pub fn resize(&mut self, new_len: usize, value: T) {
2344 let len = self.len();
2347 self.extend_with(new_len - len, ExtendElement(value))
2349 self.truncate(new_len);
2353 /// Tries to resize the `Vec` in-place so that `len` is equal to `new_len`.
2355 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2356 /// difference, with each additional slot filled with `value`.
2357 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2359 /// This method requires `T` to implement [`Clone`],
2360 /// in order to be able to clone the passed value.
2361 /// If you need more flexibility (or want to rely on [`Default`] instead of
2362 /// [`Clone`]), use [`Vec::resize_with`].
2363 /// If you only need to resize to a smaller size, use [`Vec::truncate`].
2368 /// let mut vec = vec!["hello"];
2369 /// vec.try_resize(3, "world").unwrap();
2370 /// assert_eq!(vec, ["hello", "world", "world"]);
2372 /// let mut vec = vec![1, 2, 3, 4];
2373 /// vec.try_resize(2, 0).unwrap();
2374 /// assert_eq!(vec, [1, 2]);
2376 /// let mut vec = vec![42];
2377 /// let result = vec.try_resize(usize::MAX, 0);
2378 /// assert!(result.is_err());
2380 #[stable(feature = "kernel", since = "1.0.0")]
2381 pub fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), TryReserveError> {
2382 let len = self.len();
2385 self.try_extend_with(new_len - len, ExtendElement(value))
2387 self.truncate(new_len);
2392 /// Clones and appends all elements in a slice to the `Vec`.
2394 /// Iterates over the slice `other`, clones each element, and then appends
2395 /// it to this `Vec`. The `other` slice is traversed in-order.
2397 /// Note that this function is same as [`extend`] except that it is
2398 /// specialized to work with slices instead. If and when Rust gets
2399 /// specialization this function will likely be deprecated (but still
2405 /// let mut vec = vec![1];
2406 /// vec.extend_from_slice(&[2, 3, 4]);
2407 /// assert_eq!(vec, [1, 2, 3, 4]);
2410 /// [`extend`]: Vec::extend
2411 #[cfg(not(no_global_oom_handling))]
2412 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
2413 pub fn extend_from_slice(&mut self, other: &[T]) {
2414 self.spec_extend(other.iter())
2417 /// Tries to clone and append all elements in a slice to the `Vec`.
2419 /// Iterates over the slice `other`, clones each element, and then appends
2420 /// it to this `Vec`. The `other` slice is traversed in-order.
2422 /// Note that this function is same as [`extend`] except that it is
2423 /// specialized to work with slices instead. If and when Rust gets
2424 /// specialization this function will likely be deprecated (but still
2430 /// let mut vec = vec![1];
2431 /// vec.try_extend_from_slice(&[2, 3, 4]).unwrap();
2432 /// assert_eq!(vec, [1, 2, 3, 4]);
2435 /// [`extend`]: Vec::extend
2436 #[stable(feature = "kernel", since = "1.0.0")]
2437 pub fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), TryReserveError> {
2438 self.try_spec_extend(other.iter())
2441 /// Copies elements from `src` range to the end of the vector.
2445 /// Panics if the starting point is greater than the end point or if
2446 /// the end point is greater than the length of the vector.
2451 /// let mut vec = vec![0, 1, 2, 3, 4];
2453 /// vec.extend_from_within(2..);
2454 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
2456 /// vec.extend_from_within(..2);
2457 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
2459 /// vec.extend_from_within(4..8);
2460 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
2462 #[cfg(not(no_global_oom_handling))]
2463 #[stable(feature = "vec_extend_from_within", since = "1.53.0")]
2464 pub fn extend_from_within<R>(&mut self, src: R)
2466 R: RangeBounds<usize>,
2468 let range = slice::range(src, ..self.len());
2469 self.reserve(range.len());
2472 // - `slice::range` guarantees that the given range is valid for indexing self
2474 self.spec_extend_from_within(range);
2479 impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
2480 /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
2484 /// Panics if the length of the resulting vector would overflow a `usize`.
2486 /// This is only possible when flattening a vector of arrays of zero-sized
2487 /// types, and thus tends to be irrelevant in practice. If
2488 /// `size_of::<T>() > 0`, this will never panic.
2493 /// #![feature(slice_flatten)]
2495 /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
2496 /// assert_eq!(vec.pop(), Some([7, 8, 9]));
2498 /// let mut flattened = vec.into_flattened();
2499 /// assert_eq!(flattened.pop(), Some(6));
2501 #[unstable(feature = "slice_flatten", issue = "95629")]
2502 pub fn into_flattened(self) -> Vec<T, A> {
2503 let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
2504 let (new_len, new_cap) = if mem::size_of::<T>() == 0 {
2505 (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
2508 // - `cap * N` cannot overflow because the allocation is already in
2509 // the address space.
2510 // - Each `[T; N]` has `N` valid elements, so there are `len * N`
2511 // valid elements in the allocation.
2512 unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) }
2515 // - `ptr` was allocated by `self`
2516 // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
2517 // - `new_cap` refers to the same sized allocation as `cap` because
2518 // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
2519 // - `len` <= `cap`, so `len * N` <= `cap * N`.
2520 unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
2524 // This code generalizes `extend_with_{element,default}`.
2525 trait ExtendWith<T> {
2526 fn next(&mut self) -> T;
2530 struct ExtendElement<T>(T);
2531 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
2532 fn next(&mut self) -> T {
2535 fn last(self) -> T {
2540 struct ExtendFunc<F>(F);
2541 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
2542 fn next(&mut self) -> T {
2545 fn last(mut self) -> T {
2550 impl<T, A: Allocator> Vec<T, A> {
2551 #[cfg(not(no_global_oom_handling))]
2552 /// Extend the vector by `n` values, using the given generator.
2553 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
2557 let mut ptr = self.as_mut_ptr().add(self.len());
2558 // Use SetLenOnDrop to work around bug where compiler
2559 // might not realize the store through `ptr` through self.set_len()
2561 let mut local_len = SetLenOnDrop::new(&mut self.len);
2563 // Write all elements except the last one
2565 ptr::write(ptr, value.next());
2566 ptr = ptr.offset(1);
2567 // Increment the length in every step in case next() panics
2568 local_len.increment_len(1);
2572 // We can write the last element directly without cloning needlessly
2573 ptr::write(ptr, value.last());
2574 local_len.increment_len(1);
2577 // len set by scope guard
2581 /// Try to extend the vector by `n` values, using the given generator.
2582 fn try_extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) -> Result<(), TryReserveError> {
2583 self.try_reserve(n)?;
2586 let mut ptr = self.as_mut_ptr().add(self.len());
2587 // Use SetLenOnDrop to work around bug where compiler
2588 // might not realize the store through `ptr` through self.set_len()
2590 let mut local_len = SetLenOnDrop::new(&mut self.len);
2592 // Write all elements except the last one
2594 ptr::write(ptr, value.next());
2595 ptr = ptr.offset(1);
2596 // Increment the length in every step in case next() panics
2597 local_len.increment_len(1);
2601 // We can write the last element directly without cloning needlessly
2602 ptr::write(ptr, value.last());
2603 local_len.increment_len(1);
2606 // len set by scope guard
2612 impl<T: PartialEq, A: Allocator> Vec<T, A> {
2613 /// Removes consecutive repeated elements in the vector according to the
2614 /// [`PartialEq`] trait implementation.
2616 /// If the vector is sorted, this removes all duplicates.
2621 /// let mut vec = vec![1, 2, 2, 3, 2];
2625 /// assert_eq!(vec, [1, 2, 3, 2]);
2627 #[stable(feature = "rust1", since = "1.0.0")]
2629 pub fn dedup(&mut self) {
2630 self.dedup_by(|a, b| a == b)
2634 ////////////////////////////////////////////////////////////////////////////////
2635 // Internal methods and functions
2636 ////////////////////////////////////////////////////////////////////////////////
2639 #[cfg(not(no_global_oom_handling))]
2640 #[stable(feature = "rust1", since = "1.0.0")]
2641 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
2642 <T as SpecFromElem>::from_elem(elem, n, Global)
2646 #[cfg(not(no_global_oom_handling))]
2647 #[unstable(feature = "allocator_api", issue = "32838")]
2648 pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
2649 <T as SpecFromElem>::from_elem(elem, n, alloc)
2652 trait ExtendFromWithinSpec {
2655 /// - `src` needs to be valid index
2656 /// - `self.capacity() - self.len()` must be `>= src.len()`
2657 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
2660 impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
2661 default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
2663 // - len is increased only after initializing elements
2664 let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
2667 // - caller guaratees that src is a valid index
2668 let to_clone = unsafe { this.get_unchecked(src) };
2670 iter::zip(to_clone, spare)
2671 .map(|(src, dst)| dst.write(src.clone()))
2673 // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
2674 // - len is increased after each element to prevent leaks (see issue #82533)
2675 .for_each(|_| *len += 1);
2679 impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
2680 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
2681 let count = src.len();
2683 let (init, spare) = self.split_at_spare_mut();
2686 // - caller guaratees that `src` is a valid index
2687 let source = unsafe { init.get_unchecked(src) };
2690 // - Both pointers are created from unique slice references (`&mut [_]`)
2691 // so they are valid and do not overlap.
2692 // - Elements are :Copy so it's OK to to copy them, without doing
2693 // anything with the original values
2694 // - `count` is equal to the len of `source`, so source is valid for
2696 // - `.reserve(count)` guarantees that `spare.len() >= count` so spare
2697 // is valid for `count` writes
2698 unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
2702 // - The elements were just initialized by `copy_nonoverlapping`
2707 ////////////////////////////////////////////////////////////////////////////////
2708 // Common trait implementations for Vec
2709 ////////////////////////////////////////////////////////////////////////////////
2711 #[stable(feature = "rust1", since = "1.0.0")]
2712 impl<T, A: Allocator> ops::Deref for Vec<T, A> {
2715 fn deref(&self) -> &[T] {
2716 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
2720 #[stable(feature = "rust1", since = "1.0.0")]
2721 impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
2722 fn deref_mut(&mut self) -> &mut [T] {
2723 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
2727 #[cfg(not(no_global_oom_handling))]
2728 trait SpecCloneFrom {
2729 fn clone_from(this: &mut Self, other: &Self);
2732 #[cfg(not(no_global_oom_handling))]
2733 impl<T: Clone, A: Allocator> SpecCloneFrom for Vec<T, A> {
2734 default fn clone_from(this: &mut Self, other: &Self) {
2735 // drop anything that will not be overwritten
2736 this.truncate(other.len());
2738 // self.len <= other.len due to the truncate above, so the
2739 // slices here are always in-bounds.
2740 let (init, tail) = other.split_at(this.len());
2742 // reuse the contained values' allocations/resources.
2743 this.clone_from_slice(init);
2744 this.extend_from_slice(tail);
2748 #[cfg(not(no_global_oom_handling))]
2749 impl<T: Copy, A: Allocator> SpecCloneFrom for Vec<T, A> {
2750 fn clone_from(this: &mut Self, other: &Self) {
2752 this.extend_from_slice(other);
2756 #[cfg(not(no_global_oom_handling))]
2757 #[stable(feature = "rust1", since = "1.0.0")]
2758 impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
2760 fn clone(&self) -> Self {
2761 let alloc = self.allocator().clone();
2762 <[T]>::to_vec_in(&**self, alloc)
2765 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
2766 // required for this method definition, is not available. Instead use the
2767 // `slice::to_vec` function which is only available with cfg(test)
2768 // NB see the slice::hack module in slice.rs for more information
2770 fn clone(&self) -> Self {
2771 let alloc = self.allocator().clone();
2772 crate::slice::to_vec(&**self, alloc)
2775 fn clone_from(&mut self, other: &Self) {
2776 SpecCloneFrom::clone_from(self, other)
2780 /// The hash of a vector is the same as that of the corresponding slice,
2781 /// as required by the `core::borrow::Borrow` implementation.
2784 /// #![feature(build_hasher_simple_hash_one)]
2785 /// use std::hash::BuildHasher;
2787 /// let b = std::collections::hash_map::RandomState::new();
2788 /// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
2789 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
2790 /// assert_eq!(b.hash_one(v), b.hash_one(s));
2792 #[stable(feature = "rust1", since = "1.0.0")]
2793 impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
2795 fn hash<H: Hasher>(&self, state: &mut H) {
2796 Hash::hash(&**self, state)
2800 #[stable(feature = "rust1", since = "1.0.0")]
2801 #[rustc_on_unimplemented(
2802 message = "vector indices are of type `usize` or ranges of `usize`",
2803 label = "vector indices are of type `usize` or ranges of `usize`"
2805 impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
2806 type Output = I::Output;
2809 fn index(&self, index: I) -> &Self::Output {
2810 Index::index(&**self, index)
2814 #[stable(feature = "rust1", since = "1.0.0")]
2815 #[rustc_on_unimplemented(
2816 message = "vector indices are of type `usize` or ranges of `usize`",
2817 label = "vector indices are of type `usize` or ranges of `usize`"
2819 impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
2821 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2822 IndexMut::index_mut(&mut **self, index)
2826 #[cfg(not(no_global_oom_handling))]
2827 #[stable(feature = "rust1", since = "1.0.0")]
2828 impl<T> FromIterator<T> for Vec<T> {
2830 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2831 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
2835 #[stable(feature = "rust1", since = "1.0.0")]
2836 impl<T, A: Allocator> IntoIterator for Vec<T, A> {
2838 type IntoIter = IntoIter<T, A>;
2840 /// Creates a consuming iterator, that is, one that moves each value out of
2841 /// the vector (from start to end). The vector cannot be used after calling
2847 /// let v = vec!["a".to_string(), "b".to_string()];
2848 /// for s in v.into_iter() {
2849 /// // s has type String, not &String
2850 /// println!("{s}");
2854 fn into_iter(self) -> IntoIter<T, A> {
2856 let mut me = ManuallyDrop::new(self);
2857 let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
2858 let begin = me.as_mut_ptr();
2859 let end = if mem::size_of::<T>() == 0 {
2860 arith_offset(begin as *const i8, me.len() as isize) as *const T
2862 begin.add(me.len()) as *const T
2864 let cap = me.buf.capacity();
2866 buf: NonNull::new_unchecked(begin),
2867 phantom: PhantomData,
2877 #[stable(feature = "rust1", since = "1.0.0")]
2878 impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
2880 type IntoIter = slice::Iter<'a, T>;
2882 fn into_iter(self) -> slice::Iter<'a, T> {
2887 #[stable(feature = "rust1", since = "1.0.0")]
2888 impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
2889 type Item = &'a mut T;
2890 type IntoIter = slice::IterMut<'a, T>;
2892 fn into_iter(self) -> slice::IterMut<'a, T> {
2897 #[cfg(not(no_global_oom_handling))]
2898 #[stable(feature = "rust1", since = "1.0.0")]
2899 impl<T, A: Allocator> Extend<T> for Vec<T, A> {
2901 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2902 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2906 fn extend_one(&mut self, item: T) {
2911 fn extend_reserve(&mut self, additional: usize) {
2912 self.reserve(additional);
2916 impl<T, A: Allocator> Vec<T, A> {
2917 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2918 // they have no further optimizations to apply
2919 #[cfg(not(no_global_oom_handling))]
2920 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2921 // This is the case for a general iterator.
2923 // This function should be the moral equivalent of:
2925 // for item in iterator {
2928 while let Some(element) = iterator.next() {
2929 let len = self.len();
2930 if len == self.capacity() {
2931 let (lower, _) = iterator.size_hint();
2932 self.reserve(lower.saturating_add(1));
2935 ptr::write(self.as_mut_ptr().add(len), element);
2936 // Since next() executes user code which can panic we have to bump the length
2938 // NB can't overflow since we would have had to alloc the address space
2939 self.set_len(len + 1);
2944 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2945 // they have no further optimizations to apply
2946 fn try_extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) -> Result<(), TryReserveError> {
2947 // This is the case for a general iterator.
2949 // This function should be the moral equivalent of:
2951 // for item in iterator {
2954 while let Some(element) = iterator.next() {
2955 let len = self.len();
2956 if len == self.capacity() {
2957 let (lower, _) = iterator.size_hint();
2958 self.try_reserve(lower.saturating_add(1))?;
2961 ptr::write(self.as_mut_ptr().add(len), element);
2962 // Since next() executes user code which can panic we have to bump the length
2964 // NB can't overflow since we would have had to alloc the address space
2965 self.set_len(len + 1);
2972 /// Creates a splicing iterator that replaces the specified range in the vector
2973 /// with the given `replace_with` iterator and yields the removed items.
2974 /// `replace_with` does not need to be the same length as `range`.
2976 /// `range` is removed even if the iterator is not consumed until the end.
2978 /// It is unspecified how many elements are removed from the vector
2979 /// if the `Splice` value is leaked.
2981 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2983 /// This is optimal if:
2985 /// * The tail (elements in the vector after `range`) is empty,
2986 /// * or `replace_with` yields fewer or equal elements than `range`’s length
2987 /// * or the lower bound of its `size_hint()` is exact.
2989 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2993 /// Panics if the starting point is greater than the end point or if
2994 /// the end point is greater than the length of the vector.
2999 /// let mut v = vec![1, 2, 3, 4];
3000 /// let new = [7, 8, 9];
3001 /// let u: Vec<_> = v.splice(1..3, new).collect();
3002 /// assert_eq!(v, &[1, 7, 8, 9, 4]);
3003 /// assert_eq!(u, &[2, 3]);
3005 #[cfg(not(no_global_oom_handling))]
3007 #[stable(feature = "vec_splice", since = "1.21.0")]
3008 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
3010 R: RangeBounds<usize>,
3011 I: IntoIterator<Item = T>,
3013 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
3016 /// Creates an iterator which uses a closure to determine if an element should be removed.
3018 /// If the closure returns true, then the element is removed and yielded.
3019 /// If the closure returns false, the element will remain in the vector and will not be yielded
3020 /// by the iterator.
3022 /// Using this method is equivalent to the following code:
3025 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
3026 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
3028 /// while i < vec.len() {
3029 /// if some_predicate(&mut vec[i]) {
3030 /// let val = vec.remove(i);
3031 /// // your code here
3037 /// # assert_eq!(vec, vec![1, 4, 5]);
3040 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
3041 /// because it can backshift the elements of the array in bulk.
3043 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
3044 /// regardless of whether you choose to keep or remove it.
3048 /// Splitting an array into evens and odds, reusing the original allocation:
3051 /// #![feature(drain_filter)]
3052 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
3054 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
3055 /// let odds = numbers;
3057 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
3058 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
3060 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3061 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F, A>
3063 F: FnMut(&mut T) -> bool,
3065 let old_len = self.len();
3067 // Guard against us getting leaked (leak amplification)
3072 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
3076 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
3078 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
3079 /// append the entire slice at once.
3081 /// [`copy_from_slice`]: slice::copy_from_slice
3082 #[cfg(not(no_global_oom_handling))]
3083 #[stable(feature = "extend_ref", since = "1.2.0")]
3084 impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec<T, A> {
3085 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3086 self.spec_extend(iter.into_iter())
3090 fn extend_one(&mut self, &item: &'a T) {
3095 fn extend_reserve(&mut self, additional: usize) {
3096 self.reserve(additional);
3100 /// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
3101 #[stable(feature = "rust1", since = "1.0.0")]
3102 impl<T: PartialOrd, A: Allocator> PartialOrd for Vec<T, A> {
3104 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
3105 PartialOrd::partial_cmp(&**self, &**other)
3109 #[stable(feature = "rust1", since = "1.0.0")]
3110 impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
3112 /// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
3113 #[stable(feature = "rust1", since = "1.0.0")]
3114 impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
3116 fn cmp(&self, other: &Self) -> Ordering {
3117 Ord::cmp(&**self, &**other)
3121 #[stable(feature = "rust1", since = "1.0.0")]
3122 unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
3123 fn drop(&mut self) {
3126 // use a raw slice to refer to the elements of the vector as weakest necessary type;
3127 // could avoid questions of validity in certain cases
3128 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
3130 // RawVec handles deallocation
3134 #[stable(feature = "rust1", since = "1.0.0")]
3135 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
3136 impl<T> const Default for Vec<T> {
3137 /// Creates an empty `Vec<T>`.
3138 fn default() -> Vec<T> {
3143 #[stable(feature = "rust1", since = "1.0.0")]
3144 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
3145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3146 fmt::Debug::fmt(&**self, f)
3150 #[stable(feature = "rust1", since = "1.0.0")]
3151 impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
3152 fn as_ref(&self) -> &Vec<T, A> {
3157 #[stable(feature = "vec_as_mut", since = "1.5.0")]
3158 impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
3159 fn as_mut(&mut self) -> &mut Vec<T, A> {
3164 #[stable(feature = "rust1", since = "1.0.0")]
3165 impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
3166 fn as_ref(&self) -> &[T] {
3171 #[stable(feature = "vec_as_mut", since = "1.5.0")]
3172 impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
3173 fn as_mut(&mut self) -> &mut [T] {
3178 #[cfg(not(no_global_oom_handling))]
3179 #[stable(feature = "rust1", since = "1.0.0")]
3180 impl<T: Clone> From<&[T]> for Vec<T> {
3181 /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
3186 /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
3189 fn from(s: &[T]) -> Vec<T> {
3193 fn from(s: &[T]) -> Vec<T> {
3194 crate::slice::to_vec(s, Global)
3198 #[cfg(not(no_global_oom_handling))]
3199 #[stable(feature = "vec_from_mut", since = "1.19.0")]
3200 impl<T: Clone> From<&mut [T]> for Vec<T> {
3201 /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
3206 /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
3209 fn from(s: &mut [T]) -> Vec<T> {
3213 fn from(s: &mut [T]) -> Vec<T> {
3214 crate::slice::to_vec(s, Global)
3218 #[cfg(not(no_global_oom_handling))]
3219 #[stable(feature = "vec_from_array", since = "1.44.0")]
3220 impl<T, const N: usize> From<[T; N]> for Vec<T> {
3221 /// Allocate a `Vec<T>` and move `s`'s items into it.
3226 /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
3229 fn from(s: [T; N]) -> Vec<T> {
3230 <[T]>::into_vec(box s)
3234 fn from(s: [T; N]) -> Vec<T> {
3235 crate::slice::into_vec(box s)
3239 #[cfg(not(no_borrow))]
3240 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
3241 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
3243 [T]: ToOwned<Owned = Vec<T>>,
3245 /// Convert a clone-on-write slice into a vector.
3247 /// If `s` already owns a `Vec<T>`, it will be returned directly.
3248 /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and
3249 /// filled by cloning `s`'s items into it.
3254 /// # use std::borrow::Cow;
3255 /// let o: Cow<[i32]> = Cow::Owned(vec![1, 2, 3]);
3256 /// let b: Cow<[i32]> = Cow::Borrowed(&[1, 2, 3]);
3257 /// assert_eq!(Vec::from(o), Vec::from(b));
3259 fn from(s: Cow<'a, [T]>) -> Vec<T> {
3264 // note: test pulls in libstd, which causes errors here
3266 #[stable(feature = "vec_from_box", since = "1.18.0")]
3267 impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
3268 /// Convert a boxed slice into a vector by transferring ownership of
3269 /// the existing heap allocation.
3274 /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
3275 /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
3277 fn from(s: Box<[T], A>) -> Self {
3282 // note: test pulls in libstd, which causes errors here
3283 #[cfg(not(no_global_oom_handling))]
3285 #[stable(feature = "box_from_vec", since = "1.20.0")]
3286 impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
3287 /// Convert a vector into a boxed slice.
3289 /// If `v` has excess capacity, its items will be moved into a
3290 /// newly-allocated buffer with exactly the right capacity.
3295 /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
3297 fn from(v: Vec<T, A>) -> Self {
3298 v.into_boxed_slice()
3302 #[cfg(not(no_global_oom_handling))]
3303 #[stable(feature = "rust1", since = "1.0.0")]
3304 impl From<&str> for Vec<u8> {
3305 /// Allocate a `Vec<u8>` and fill it with a UTF-8 string.
3310 /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
3312 fn from(s: &str) -> Vec<u8> {
3313 From::from(s.as_bytes())
3317 #[stable(feature = "array_try_from_vec", since = "1.48.0")]
3318 impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
3319 type Error = Vec<T, A>;
3321 /// Gets the entire contents of the `Vec<T>` as an array,
3322 /// if its size exactly matches that of the requested array.
3327 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
3328 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
3331 /// If the length doesn't match, the input comes back in `Err`:
3333 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
3334 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
3337 /// If you're fine with just getting a prefix of the `Vec<T>`,
3338 /// you can call [`.truncate(N)`](Vec::truncate) first.
3340 /// let mut v = String::from("hello world").into_bytes();
3343 /// let [a, b]: [_; 2] = v.try_into().unwrap();
3344 /// assert_eq!(a, b' ');
3345 /// assert_eq!(b, b'd');
3347 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
3352 // SAFETY: `.set_len(0)` is always sound.
3353 unsafe { vec.set_len(0) };
3355 // SAFETY: A `Vec`'s pointer is always aligned properly, and
3356 // the alignment the array needs is the same as the items.
3357 // We checked earlier that we have sufficient items.
3358 // The items will not double-drop as the `set_len`
3359 // tells the `Vec` not to also drop them.
3360 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };