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 use crate::borrow::{Cow, ToOwned};
76 use crate::boxed::Box;
77 use crate::collections::TryReserveError;
78 use crate::raw_vec::RawVec;
80 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
81 pub use self::drain_filter::DrainFilter;
85 #[cfg(not(no_global_oom_handling))]
86 #[stable(feature = "vec_splice", since = "1.21.0")]
87 pub use self::splice::Splice;
89 #[cfg(not(no_global_oom_handling))]
92 #[stable(feature = "drain", since = "1.6.0")]
93 pub use self::drain::Drain;
97 #[cfg(not(no_global_oom_handling))]
100 #[cfg(not(no_global_oom_handling))]
101 pub(crate) use self::in_place_collect::AsVecIntoIter;
102 #[stable(feature = "rust1", since = "1.0.0")]
103 pub use self::into_iter::IntoIter;
107 #[cfg(not(no_global_oom_handling))]
108 use self::is_zero::IsZero;
112 #[cfg(not(no_global_oom_handling))]
113 mod in_place_collect;
117 #[cfg(not(no_global_oom_handling))]
118 use self::spec_from_elem::SpecFromElem;
120 #[cfg(not(no_global_oom_handling))]
123 #[cfg(not(no_global_oom_handling))]
124 use self::set_len_on_drop::SetLenOnDrop;
126 #[cfg(not(no_global_oom_handling))]
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 #[cfg(not(no_global_oom_handling))]
153 /// A contiguous growable array type, written as `Vec<T>`, short for 'vector'.
158 /// let mut vec = Vec::new();
162 /// assert_eq!(vec.len(), 2);
163 /// assert_eq!(vec[0], 1);
165 /// assert_eq!(vec.pop(), Some(2));
166 /// assert_eq!(vec.len(), 1);
169 /// assert_eq!(vec[0], 7);
171 /// vec.extend([1, 2, 3].iter().copied());
176 /// assert_eq!(vec, [7, 1, 2, 3]);
179 /// The [`vec!`] macro is provided for convenient initialization:
182 /// let mut vec1 = vec![1, 2, 3];
184 /// let vec2 = Vec::from([1, 2, 3, 4]);
185 /// assert_eq!(vec1, vec2);
188 /// It can also initialize each element of a `Vec<T>` with a given value.
189 /// This may be more efficient than performing allocation and initialization
190 /// in separate steps, especially when initializing a vector of zeros:
193 /// let vec = vec![0; 5];
194 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
196 /// // The following is equivalent, but potentially slower:
197 /// let mut vec = Vec::with_capacity(5);
198 /// vec.resize(5, 0);
199 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
202 /// For more information, see
203 /// [Capacity and Reallocation](#capacity-and-reallocation).
205 /// Use a `Vec<T>` as an efficient stack:
208 /// let mut stack = Vec::new();
214 /// while let Some(top) = stack.pop() {
215 /// // Prints 3, 2, 1
216 /// println!("{top}");
222 /// The `Vec` type allows to access values by index, because it implements the
223 /// [`Index`] trait. An example will be more explicit:
226 /// let v = vec![0, 2, 4, 6];
227 /// println!("{}", v[1]); // it will display '2'
230 /// However be careful: if you try to access an index which isn't in the `Vec`,
231 /// your software will panic! You cannot do this:
234 /// let v = vec![0, 2, 4, 6];
235 /// println!("{}", v[6]); // it will panic!
238 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
243 /// A `Vec` can be mutable. On the other hand, slices are read-only objects.
244 /// To get a [slice][prim@slice], use [`&`]. Example:
247 /// fn read_slice(slice: &[usize]) {
251 /// let v = vec![0, 1];
254 /// // ... and that's all!
255 /// // you can also do it like this:
256 /// let u: &[usize] = &v;
258 /// let u: &[_] = &v;
261 /// In Rust, it's more common to pass slices as arguments rather than vectors
262 /// when you just want to provide read access. The same goes for [`String`] and
265 /// # Capacity and reallocation
267 /// The capacity of a vector is the amount of space allocated for any future
268 /// elements that will be added onto the vector. This is not to be confused with
269 /// the *length* of a vector, which specifies the number of actual elements
270 /// within the vector. If a vector's length exceeds its capacity, its capacity
271 /// will automatically be increased, but its elements will have to be
274 /// For example, a vector with capacity 10 and length 0 would be an empty vector
275 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
276 /// vector will not change its capacity or cause reallocation to occur. However,
277 /// if the vector's length is increased to 11, it will have to reallocate, which
278 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
279 /// whenever possible to specify how big the vector is expected to get.
283 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
284 /// about its design. This ensures that it's as low-overhead as possible in
285 /// the general case, and can be correctly manipulated in primitive ways
286 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
287 /// If additional type parameters are added (e.g., to support custom allocators),
288 /// overriding their defaults may change the behavior.
290 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
291 /// triplet. No more, no less. The order of these fields is completely
292 /// unspecified, and you should use the appropriate methods to modify these.
293 /// The pointer will never be null, so this type is null-pointer-optimized.
295 /// However, the pointer might not actually point to allocated memory. In particular,
296 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
297 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
298 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
299 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
300 /// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only
301 /// if <code>[mem::size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation
302 /// details are very subtle --- if you intend to allocate memory using a `Vec`
303 /// and use it for something else (either to pass to unsafe code, or to build your
304 /// own memory-backed collection), be sure to deallocate this memory by using
305 /// `from_raw_parts` to recover the `Vec` and then dropping it.
307 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
308 /// (as defined by the allocator Rust is configured to use by default), and its
309 /// pointer points to [`len`] initialized, contiguous elements in order (what
310 /// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>
311 /// logically uninitialized, contiguous elements.
313 /// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
314 /// visualized as below. The top part is the `Vec` struct, it contains a
315 /// pointer to the head of the allocation in the heap, length and capacity.
316 /// The bottom part is the allocation on the heap, a contiguous memory block.
320 /// +--------+--------+--------+
321 /// | 0x0123 | 2 | 4 |
322 /// +--------+--------+--------+
325 /// Heap +--------+--------+--------+--------+
326 /// | 'a' | 'b' | uninit | uninit |
327 /// +--------+--------+--------+--------+
330 /// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
331 /// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
332 /// layout (including the order of fields).
334 /// `Vec` will never perform a "small optimization" where elements are actually
335 /// stored on the stack for two reasons:
337 /// * It would make it more difficult for unsafe code to correctly manipulate
338 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
339 /// only moved, and it would be more difficult to determine if a `Vec` had
340 /// actually allocated memory.
342 /// * It would penalize the general case, incurring an additional branch
345 /// `Vec` will never automatically shrink itself, even if completely empty. This
346 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
347 /// and then filling it back up to the same [`len`] should incur no calls to
348 /// the allocator. If you wish to free up unused memory, use
349 /// [`shrink_to_fit`] or [`shrink_to`].
351 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
352 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
353 /// <code>[len] == [capacity]</code>. That is, the reported capacity is completely
354 /// accurate, and can be relied on. It can even be used to manually free the memory
355 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
356 /// when not necessary.
358 /// `Vec` does not guarantee any particular growth strategy when reallocating
359 /// when full, nor when [`reserve`] is called. The current strategy is basic
360 /// and it may prove desirable to use a non-constant growth factor. Whatever
361 /// strategy is used will of course guarantee *O*(1) amortized [`push`].
363 /// `vec![x; n]`, `vec![a, b, c, d]`, and
364 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
365 /// with exactly the requested capacity. If <code>[len] == [capacity]</code>,
366 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
367 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
369 /// `Vec` will not specifically overwrite any data that is removed from it,
370 /// but also won't specifically preserve it. Its uninitialized memory is
371 /// scratch space that it may use however it wants. It will generally just do
372 /// whatever is most efficient or otherwise easy to implement. Do not rely on
373 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
374 /// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory
375 /// first, that might not actually happen because the optimizer does not consider
376 /// this a side-effect that must be preserved. There is one case which we will
377 /// not break, however: using `unsafe` code to write to the excess capacity,
378 /// and then increasing the length to match, is always valid.
380 /// Currently, `Vec` does not guarantee the order in which elements are dropped.
381 /// The order has changed in the past and may change again.
383 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
384 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
385 /// [`String`]: crate::string::String
386 /// [`&str`]: type@str
387 /// [`shrink_to_fit`]: Vec::shrink_to_fit
388 /// [`shrink_to`]: Vec::shrink_to
389 /// [capacity]: Vec::capacity
390 /// [`capacity`]: Vec::capacity
391 /// [mem::size_of::\<T>]: core::mem::size_of
393 /// [`len`]: Vec::len
394 /// [`push`]: Vec::push
395 /// [`insert`]: Vec::insert
396 /// [`reserve`]: Vec::reserve
397 /// [`MaybeUninit`]: core::mem::MaybeUninit
398 /// [owned slice]: Box
399 #[stable(feature = "rust1", since = "1.0.0")]
400 #[cfg_attr(not(test), rustc_diagnostic_item = "Vec")]
401 #[rustc_insignificant_dtor]
402 pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
407 ////////////////////////////////////////////////////////////////////////////////
409 ////////////////////////////////////////////////////////////////////////////////
412 /// Constructs a new, empty `Vec<T>`.
414 /// The vector will not allocate until elements are pushed onto it.
419 /// # #![allow(unused_mut)]
420 /// let mut vec: Vec<i32> = Vec::new();
423 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
424 #[stable(feature = "rust1", since = "1.0.0")]
426 pub const fn new() -> Self {
427 Vec { buf: RawVec::NEW, len: 0 }
430 /// Constructs a new, empty `Vec<T>` with the specified capacity.
432 /// The vector will be able to hold exactly `capacity` elements without
433 /// reallocating. If `capacity` is 0, the vector will not allocate.
435 /// It is important to note that although the returned vector has the
436 /// *capacity* specified, the vector will have a zero *length*. For an
437 /// explanation of the difference between length and capacity, see
438 /// *[Capacity and reallocation]*.
440 /// [Capacity and reallocation]: #capacity-and-reallocation
444 /// Panics if the new capacity exceeds `isize::MAX` bytes.
449 /// let mut vec = Vec::with_capacity(10);
451 /// // The vector contains no items, even though it has capacity for more
452 /// assert_eq!(vec.len(), 0);
453 /// assert_eq!(vec.capacity(), 10);
455 /// // These are all done without reallocating...
459 /// assert_eq!(vec.len(), 10);
460 /// assert_eq!(vec.capacity(), 10);
462 /// // ...but this may make the vector reallocate
464 /// assert_eq!(vec.len(), 11);
465 /// assert!(vec.capacity() >= 11);
467 #[cfg(not(no_global_oom_handling))]
469 #[stable(feature = "rust1", since = "1.0.0")]
471 pub fn with_capacity(capacity: usize) -> Self {
472 Self::with_capacity_in(capacity, Global)
475 /// Tries to construct a new, empty `Vec<T>` with the specified capacity.
477 /// The vector will be able to hold exactly `capacity` elements without
478 /// reallocating. If `capacity` is 0, the vector will not allocate.
480 /// It is important to note that although the returned vector has the
481 /// *capacity* specified, the vector will have a zero *length*. For an
482 /// explanation of the difference between length and capacity, see
483 /// *[Capacity and reallocation]*.
485 /// [Capacity and reallocation]: #capacity-and-reallocation
490 /// let mut vec = Vec::try_with_capacity(10).unwrap();
492 /// // The vector contains no items, even though it has capacity for more
493 /// assert_eq!(vec.len(), 0);
494 /// assert_eq!(vec.capacity(), 10);
496 /// // These are all done without reallocating...
500 /// assert_eq!(vec.len(), 10);
501 /// assert_eq!(vec.capacity(), 10);
503 /// // ...but this may make the vector reallocate
505 /// assert_eq!(vec.len(), 11);
506 /// assert!(vec.capacity() >= 11);
508 /// let mut result = Vec::try_with_capacity(usize::MAX);
509 /// assert!(result.is_err());
512 #[stable(feature = "kernel", since = "1.0.0")]
513 pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> {
514 Self::try_with_capacity_in(capacity, Global)
517 /// Creates a `Vec<T>` directly from the raw components of another vector.
521 /// This is highly unsafe, due to the number of invariants that aren't
524 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
525 /// (at least, it's highly likely to be incorrect if it wasn't).
526 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
527 /// (`T` having a less strict alignment is not sufficient, the alignment really
528 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
529 /// allocated and deallocated with the same layout.)
530 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
531 /// to be the same size as the pointer was allocated with. (Because similar to
532 /// alignment, [`dealloc`] must be called with the same layout `size`.)
533 /// * `length` needs to be less than or equal to `capacity`.
535 /// Violating these may cause problems like corrupting the allocator's
536 /// internal data structures. For example it is normally **not** safe
537 /// to build a `Vec<u8>` from a pointer to a C `char` array with length
538 /// `size_t`, doing so is only safe if the array was initially allocated by
539 /// a `Vec` or `String`.
540 /// It's also not safe to build one from a `Vec<u16>` and its length, because
541 /// the allocator cares about the alignment, and these two types have different
542 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
543 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
544 /// these issues, it is often preferable to do casting/transmuting using
545 /// [`slice::from_raw_parts`] instead.
547 /// The ownership of `ptr` is effectively transferred to the
548 /// `Vec<T>` which may then deallocate, reallocate or change the
549 /// contents of memory pointed to by the pointer at will. Ensure
550 /// that nothing else uses the pointer after calling this
553 /// [`String`]: crate::string::String
554 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
562 /// let v = vec![1, 2, 3];
564 // FIXME Update this when vec_into_raw_parts is stabilized
565 /// // Prevent running `v`'s destructor so we are in complete control
566 /// // of the allocation.
567 /// let mut v = mem::ManuallyDrop::new(v);
569 /// // Pull out the various important pieces of information about `v`
570 /// let p = v.as_mut_ptr();
571 /// let len = v.len();
572 /// let cap = v.capacity();
575 /// // Overwrite memory with 4, 5, 6
576 /// for i in 0..len as isize {
577 /// ptr::write(p.offset(i), 4 + i);
580 /// // Put everything back together into a Vec
581 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
582 /// assert_eq!(rebuilt, [4, 5, 6]);
586 #[stable(feature = "rust1", since = "1.0.0")]
587 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
588 unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
592 impl<T, A: Allocator> Vec<T, A> {
593 /// Constructs a new, empty `Vec<T, A>`.
595 /// The vector will not allocate until elements are pushed onto it.
600 /// #![feature(allocator_api)]
602 /// use std::alloc::System;
604 /// # #[allow(unused_mut)]
605 /// let mut vec: Vec<i32, _> = Vec::new_in(System);
608 #[unstable(feature = "allocator_api", issue = "32838")]
609 pub const fn new_in(alloc: A) -> Self {
610 Vec { buf: RawVec::new_in(alloc), len: 0 }
613 /// Constructs a new, empty `Vec<T, A>` with the specified capacity with the provided
616 /// The vector will be able to hold exactly `capacity` elements without
617 /// reallocating. If `capacity` is 0, the vector will not allocate.
619 /// It is important to note that although the returned vector has the
620 /// *capacity* specified, the vector will have a zero *length*. For an
621 /// explanation of the difference between length and capacity, see
622 /// *[Capacity and reallocation]*.
624 /// [Capacity and reallocation]: #capacity-and-reallocation
628 /// Panics if the new capacity exceeds `isize::MAX` bytes.
633 /// #![feature(allocator_api)]
635 /// use std::alloc::System;
637 /// let mut vec = Vec::with_capacity_in(10, System);
639 /// // The vector contains no items, even though it has capacity for more
640 /// assert_eq!(vec.len(), 0);
641 /// assert_eq!(vec.capacity(), 10);
643 /// // These are all done without reallocating...
647 /// assert_eq!(vec.len(), 10);
648 /// assert_eq!(vec.capacity(), 10);
650 /// // ...but this may make the vector reallocate
652 /// assert_eq!(vec.len(), 11);
653 /// assert!(vec.capacity() >= 11);
655 #[cfg(not(no_global_oom_handling))]
657 #[unstable(feature = "allocator_api", issue = "32838")]
658 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
659 Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
662 /// Tries to construct a new, empty `Vec<T, A>` with the specified capacity
663 /// with the provided allocator.
665 /// The vector will be able to hold exactly `capacity` elements without
666 /// reallocating. If `capacity` is 0, the vector will not allocate.
668 /// It is important to note that although the returned vector has the
669 /// *capacity* specified, the vector will have a zero *length*. For an
670 /// explanation of the difference between length and capacity, see
671 /// *[Capacity and reallocation]*.
673 /// [Capacity and reallocation]: #capacity-and-reallocation
678 /// #![feature(allocator_api)]
680 /// use std::alloc::System;
682 /// let mut vec = Vec::try_with_capacity_in(10, System).unwrap();
684 /// // The vector contains no items, even though it has capacity for more
685 /// assert_eq!(vec.len(), 0);
686 /// assert_eq!(vec.capacity(), 10);
688 /// // These are all done without reallocating...
692 /// assert_eq!(vec.len(), 10);
693 /// assert_eq!(vec.capacity(), 10);
695 /// // ...but this may make the vector reallocate
697 /// assert_eq!(vec.len(), 11);
698 /// assert!(vec.capacity() >= 11);
700 /// let mut result = Vec::try_with_capacity_in(usize::MAX, System);
701 /// assert!(result.is_err());
704 #[stable(feature = "kernel", since = "1.0.0")]
705 pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
706 Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 })
709 /// Creates a `Vec<T, A>` directly from the raw components of another vector.
713 /// This is highly unsafe, due to the number of invariants that aren't
716 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
717 /// (at least, it's highly likely to be incorrect if it wasn't).
718 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
719 /// (`T` having a less strict alignment is not sufficient, the alignment really
720 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
721 /// allocated and deallocated with the same layout.)
722 /// * `length` needs to be less than or equal to `capacity`.
723 /// * `capacity` needs to be the capacity that the pointer was allocated with.
725 /// Violating these may cause problems like corrupting the allocator's
726 /// internal data structures. For example it is **not** safe
727 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
728 /// It's also not safe to build one from a `Vec<u16>` and its length, because
729 /// the allocator cares about the alignment, and these two types have different
730 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
731 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
733 /// The ownership of `ptr` is effectively transferred to the
734 /// `Vec<T>` which may then deallocate, reallocate or change the
735 /// contents of memory pointed to by the pointer at will. Ensure
736 /// that nothing else uses the pointer after calling this
739 /// [`String`]: crate::string::String
740 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
745 /// #![feature(allocator_api)]
747 /// use std::alloc::System;
752 /// let mut v = Vec::with_capacity_in(3, System);
757 // FIXME Update this when vec_into_raw_parts is stabilized
758 /// // Prevent running `v`'s destructor so we are in complete control
759 /// // of the allocation.
760 /// let mut v = mem::ManuallyDrop::new(v);
762 /// // Pull out the various important pieces of information about `v`
763 /// let p = v.as_mut_ptr();
764 /// let len = v.len();
765 /// let cap = v.capacity();
766 /// let alloc = v.allocator();
769 /// // Overwrite memory with 4, 5, 6
770 /// for i in 0..len as isize {
771 /// ptr::write(p.offset(i), 4 + i);
774 /// // Put everything back together into a Vec
775 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
776 /// assert_eq!(rebuilt, [4, 5, 6]);
780 #[unstable(feature = "allocator_api", issue = "32838")]
781 pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
782 unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
785 /// Decomposes a `Vec<T>` into its raw components.
787 /// Returns the raw pointer to the underlying data, the length of
788 /// the vector (in elements), and the allocated capacity of the
789 /// data (in elements). These are the same arguments in the same
790 /// order as the arguments to [`from_raw_parts`].
792 /// After calling this function, the caller is responsible for the
793 /// memory previously managed by the `Vec`. The only way to do
794 /// this is to convert the raw pointer, length, and capacity back
795 /// into a `Vec` with the [`from_raw_parts`] function, allowing
796 /// the destructor to perform the cleanup.
798 /// [`from_raw_parts`]: Vec::from_raw_parts
803 /// #![feature(vec_into_raw_parts)]
804 /// let v: Vec<i32> = vec![-1, 0, 1];
806 /// let (ptr, len, cap) = v.into_raw_parts();
808 /// let rebuilt = unsafe {
809 /// // We can now make changes to the components, such as
810 /// // transmuting the raw pointer to a compatible type.
811 /// let ptr = ptr as *mut u32;
813 /// Vec::from_raw_parts(ptr, len, cap)
815 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
817 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
818 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
819 let mut me = ManuallyDrop::new(self);
820 (me.as_mut_ptr(), me.len(), me.capacity())
823 /// Decomposes a `Vec<T>` into its raw components.
825 /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
826 /// the allocated capacity of the data (in elements), and the allocator. These are the same
827 /// arguments in the same order as the arguments to [`from_raw_parts_in`].
829 /// After calling this function, the caller is responsible for the
830 /// memory previously managed by the `Vec`. The only way to do
831 /// this is to convert the raw pointer, length, and capacity back
832 /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
833 /// the destructor to perform the cleanup.
835 /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
840 /// #![feature(allocator_api, vec_into_raw_parts)]
842 /// use std::alloc::System;
844 /// let mut v: Vec<i32, System> = Vec::new_in(System);
849 /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
851 /// let rebuilt = unsafe {
852 /// // We can now make changes to the components, such as
853 /// // transmuting the raw pointer to a compatible type.
854 /// let ptr = ptr as *mut u32;
856 /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
858 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
860 #[unstable(feature = "allocator_api", issue = "32838")]
861 // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
862 pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
863 let mut me = ManuallyDrop::new(self);
865 let capacity = me.capacity();
866 let ptr = me.as_mut_ptr();
867 let alloc = unsafe { ptr::read(me.allocator()) };
868 (ptr, len, capacity, alloc)
871 /// Returns the number of elements the vector can hold without
877 /// let vec: Vec<i32> = Vec::with_capacity(10);
878 /// assert_eq!(vec.capacity(), 10);
881 #[stable(feature = "rust1", since = "1.0.0")]
882 pub fn capacity(&self) -> usize {
886 /// Reserves capacity for at least `additional` more elements to be inserted
887 /// in the given `Vec<T>`. The collection may reserve more space to avoid
888 /// frequent reallocations. After calling `reserve`, capacity will be
889 /// greater than or equal to `self.len() + additional`. Does nothing if
890 /// capacity is already sufficient.
894 /// Panics if the new capacity exceeds `isize::MAX` bytes.
899 /// let mut vec = vec![1];
901 /// assert!(vec.capacity() >= 11);
903 #[cfg(not(no_global_oom_handling))]
904 #[stable(feature = "rust1", since = "1.0.0")]
905 pub fn reserve(&mut self, additional: usize) {
906 self.buf.reserve(self.len, additional);
909 /// Reserves the minimum capacity for exactly `additional` more elements to
910 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
911 /// capacity will be greater than or equal to `self.len() + additional`.
912 /// Does nothing if the capacity is already sufficient.
914 /// Note that the allocator may give the collection more space than it
915 /// requests. Therefore, capacity can not be relied upon to be precisely
916 /// minimal. Prefer [`reserve`] if future insertions are expected.
918 /// [`reserve`]: Vec::reserve
922 /// Panics if the new capacity exceeds `isize::MAX` bytes.
927 /// let mut vec = vec![1];
928 /// vec.reserve_exact(10);
929 /// assert!(vec.capacity() >= 11);
931 #[cfg(not(no_global_oom_handling))]
932 #[stable(feature = "rust1", since = "1.0.0")]
933 pub fn reserve_exact(&mut self, additional: usize) {
934 self.buf.reserve_exact(self.len, additional);
937 /// Tries to reserve capacity for at least `additional` more elements to be inserted
938 /// in the given `Vec<T>`. The collection may reserve more space to avoid
939 /// frequent reallocations. After calling `try_reserve`, capacity will be
940 /// greater than or equal to `self.len() + additional`. Does nothing if
941 /// capacity is already sufficient.
945 /// If the capacity overflows, or the allocator reports a failure, then an error
951 /// use std::collections::TryReserveError;
953 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
954 /// let mut output = Vec::new();
956 /// // Pre-reserve the memory, exiting if we can't
957 /// output.try_reserve(data.len())?;
959 /// // Now we know this can't OOM in the middle of our complex work
960 /// output.extend(data.iter().map(|&val| {
961 /// val * 2 + 5 // very complicated
966 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
968 #[stable(feature = "try_reserve", since = "1.57.0")]
969 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
970 self.buf.try_reserve(self.len, additional)
973 /// Tries to reserve the minimum capacity for exactly `additional`
974 /// elements to be inserted in the given `Vec<T>`. After calling
975 /// `try_reserve_exact`, capacity will be greater than or equal to
976 /// `self.len() + additional` if it returns `Ok(())`.
977 /// Does nothing if the capacity is already sufficient.
979 /// Note that the allocator may give the collection more space than it
980 /// requests. Therefore, capacity can not be relied upon to be precisely
981 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
983 /// [`try_reserve`]: Vec::try_reserve
987 /// If the capacity overflows, or the allocator reports a failure, then an error
993 /// use std::collections::TryReserveError;
995 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
996 /// let mut output = Vec::new();
998 /// // Pre-reserve the memory, exiting if we can't
999 /// output.try_reserve_exact(data.len())?;
1001 /// // Now we know this can't OOM in the middle of our complex work
1002 /// output.extend(data.iter().map(|&val| {
1003 /// val * 2 + 5 // very complicated
1008 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
1010 #[stable(feature = "try_reserve", since = "1.57.0")]
1011 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1012 self.buf.try_reserve_exact(self.len, additional)
1015 /// Shrinks the capacity of the vector as much as possible.
1017 /// It will drop down as close as possible to the length but the allocator
1018 /// may still inform the vector that there is space for a few more elements.
1023 /// let mut vec = Vec::with_capacity(10);
1024 /// vec.extend([1, 2, 3]);
1025 /// assert_eq!(vec.capacity(), 10);
1026 /// vec.shrink_to_fit();
1027 /// assert!(vec.capacity() >= 3);
1029 #[cfg(not(no_global_oom_handling))]
1030 #[stable(feature = "rust1", since = "1.0.0")]
1031 pub fn shrink_to_fit(&mut self) {
1032 // The capacity is never less than the length, and there's nothing to do when
1033 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
1034 // by only calling it with a greater capacity.
1035 if self.capacity() > self.len {
1036 self.buf.shrink_to_fit(self.len);
1040 /// Shrinks the capacity of the vector with a lower bound.
1042 /// The capacity will remain at least as large as both the length
1043 /// and the supplied value.
1045 /// If the current capacity is less than the lower limit, this is a no-op.
1050 /// let mut vec = Vec::with_capacity(10);
1051 /// vec.extend([1, 2, 3]);
1052 /// assert_eq!(vec.capacity(), 10);
1053 /// vec.shrink_to(4);
1054 /// assert!(vec.capacity() >= 4);
1055 /// vec.shrink_to(0);
1056 /// assert!(vec.capacity() >= 3);
1058 #[cfg(not(no_global_oom_handling))]
1059 #[stable(feature = "shrink_to", since = "1.56.0")]
1060 pub fn shrink_to(&mut self, min_capacity: usize) {
1061 if self.capacity() > min_capacity {
1062 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
1066 /// Converts the vector into [`Box<[T]>`][owned slice].
1068 /// Note that this will drop any excess capacity.
1070 /// [owned slice]: Box
1075 /// let v = vec![1, 2, 3];
1077 /// let slice = v.into_boxed_slice();
1080 /// Any excess capacity is removed:
1083 /// let mut vec = Vec::with_capacity(10);
1084 /// vec.extend([1, 2, 3]);
1086 /// assert_eq!(vec.capacity(), 10);
1087 /// let slice = vec.into_boxed_slice();
1088 /// assert_eq!(slice.into_vec().capacity(), 3);
1090 #[cfg(not(no_global_oom_handling))]
1091 #[stable(feature = "rust1", since = "1.0.0")]
1092 pub fn into_boxed_slice(mut self) -> Box<[T], A> {
1094 self.shrink_to_fit();
1095 let me = ManuallyDrop::new(self);
1096 let buf = ptr::read(&me.buf);
1098 buf.into_box(len).assume_init()
1102 /// Shortens the vector, keeping the first `len` elements and dropping
1105 /// If `len` is greater than the vector's current length, this has no
1108 /// The [`drain`] method can emulate `truncate`, but causes the excess
1109 /// elements to be returned instead of dropped.
1111 /// Note that this method has no effect on the allocated capacity
1116 /// Truncating a five element vector to two elements:
1119 /// let mut vec = vec![1, 2, 3, 4, 5];
1120 /// vec.truncate(2);
1121 /// assert_eq!(vec, [1, 2]);
1124 /// No truncation occurs when `len` is greater than the vector's current
1128 /// let mut vec = vec![1, 2, 3];
1129 /// vec.truncate(8);
1130 /// assert_eq!(vec, [1, 2, 3]);
1133 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
1137 /// let mut vec = vec![1, 2, 3];
1138 /// vec.truncate(0);
1139 /// assert_eq!(vec, []);
1142 /// [`clear`]: Vec::clear
1143 /// [`drain`]: Vec::drain
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 pub fn truncate(&mut self, len: usize) {
1146 // This is safe because:
1148 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
1149 // case avoids creating an invalid slice, and
1150 // * the `len` of the vector is shrunk before calling `drop_in_place`,
1151 // such that no value will be dropped twice in case `drop_in_place`
1152 // were to panic once (if it panics twice, the program aborts).
1154 // Note: It's intentional that this is `>` and not `>=`.
1155 // Changing it to `>=` has negative performance
1156 // implications in some cases. See #78884 for more.
1160 let remaining_len = self.len - len;
1161 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
1163 ptr::drop_in_place(s);
1167 /// Extracts a slice containing the entire vector.
1169 /// Equivalent to `&s[..]`.
1174 /// use std::io::{self, Write};
1175 /// let buffer = vec![1, 2, 3, 5, 8];
1176 /// io::sink().write(buffer.as_slice()).unwrap();
1179 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1180 pub fn as_slice(&self) -> &[T] {
1184 /// Extracts a mutable slice of the entire vector.
1186 /// Equivalent to `&mut s[..]`.
1191 /// use std::io::{self, Read};
1192 /// let mut buffer = vec![0; 3];
1193 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1196 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1197 pub fn as_mut_slice(&mut self) -> &mut [T] {
1201 /// Returns a raw pointer to the vector's buffer.
1203 /// The caller must ensure that the vector outlives the pointer this
1204 /// function returns, or else it will end up pointing to garbage.
1205 /// Modifying the vector may cause its buffer to be reallocated,
1206 /// which would also make any pointers to it invalid.
1208 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1209 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1210 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1215 /// let x = vec![1, 2, 4];
1216 /// let x_ptr = x.as_ptr();
1219 /// for i in 0..x.len() {
1220 /// assert_eq!(*x_ptr.add(i), 1 << i);
1225 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1226 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1228 pub fn as_ptr(&self) -> *const T {
1229 // We shadow the slice method of the same name to avoid going through
1230 // `deref`, which creates an intermediate reference.
1231 let ptr = self.buf.ptr();
1233 assume(!ptr.is_null());
1238 /// Returns an unsafe mutable pointer to the vector's buffer.
1240 /// The caller must ensure that the vector outlives the pointer this
1241 /// function returns, or else it will end up pointing to garbage.
1242 /// Modifying the vector may cause its buffer to be reallocated,
1243 /// which would also make any pointers to it invalid.
1248 /// // Allocate vector big enough for 4 elements.
1250 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1251 /// let x_ptr = x.as_mut_ptr();
1253 /// // Initialize elements via raw pointer writes, then set length.
1255 /// for i in 0..size {
1256 /// *x_ptr.add(i) = i as i32;
1258 /// x.set_len(size);
1260 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1262 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1264 pub fn as_mut_ptr(&mut self) -> *mut T {
1265 // We shadow the slice method of the same name to avoid going through
1266 // `deref_mut`, which creates an intermediate reference.
1267 let ptr = self.buf.ptr();
1269 assume(!ptr.is_null());
1274 /// Returns a reference to the underlying allocator.
1275 #[unstable(feature = "allocator_api", issue = "32838")]
1277 pub fn allocator(&self) -> &A {
1278 self.buf.allocator()
1281 /// Forces the length of the vector to `new_len`.
1283 /// This is a low-level operation that maintains none of the normal
1284 /// invariants of the type. Normally changing the length of a vector
1285 /// is done using one of the safe operations instead, such as
1286 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
1288 /// [`truncate`]: Vec::truncate
1289 /// [`resize`]: Vec::resize
1290 /// [`extend`]: Extend::extend
1291 /// [`clear`]: Vec::clear
1295 /// - `new_len` must be less than or equal to [`capacity()`].
1296 /// - The elements at `old_len..new_len` must be initialized.
1298 /// [`capacity()`]: Vec::capacity
1302 /// This method can be useful for situations in which the vector
1303 /// is serving as a buffer for other code, particularly over FFI:
1306 /// # #![allow(dead_code)]
1307 /// # // This is just a minimal skeleton for the doc example;
1308 /// # // don't use this as a starting point for a real library.
1309 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
1310 /// # const Z_OK: i32 = 0;
1312 /// # fn deflateGetDictionary(
1313 /// # strm: *mut std::ffi::c_void,
1314 /// # dictionary: *mut u8,
1315 /// # dictLength: *mut usize,
1318 /// # impl StreamWrapper {
1319 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
1320 /// // Per the FFI method's docs, "32768 bytes is always enough".
1321 /// let mut dict = Vec::with_capacity(32_768);
1322 /// let mut dict_length = 0;
1323 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
1324 /// // 1. `dict_length` elements were initialized.
1325 /// // 2. `dict_length` <= the capacity (32_768)
1326 /// // which makes `set_len` safe to call.
1328 /// // Make the FFI call...
1329 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
1331 /// // ...and update the length to what was initialized.
1332 /// dict.set_len(dict_length);
1342 /// While the following example is sound, there is a memory leak since
1343 /// the inner vectors were not freed prior to the `set_len` call:
1346 /// let mut vec = vec![vec![1, 0, 0],
1350 /// // 1. `old_len..0` is empty so no elements need to be initialized.
1351 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
1357 /// Normally, here, one would use [`clear`] instead to correctly drop
1358 /// the contents and thus not leak memory.
1360 #[stable(feature = "rust1", since = "1.0.0")]
1361 pub unsafe fn set_len(&mut self, new_len: usize) {
1362 debug_assert!(new_len <= self.capacity());
1367 /// Removes an element from the vector and returns it.
1369 /// The removed element is replaced by the last element of the vector.
1371 /// This does not preserve ordering, but is *O*(1).
1372 /// If you need to preserve the element order, use [`remove`] instead.
1374 /// [`remove`]: Vec::remove
1378 /// Panics if `index` is out of bounds.
1383 /// let mut v = vec!["foo", "bar", "baz", "qux"];
1385 /// assert_eq!(v.swap_remove(1), "bar");
1386 /// assert_eq!(v, ["foo", "qux", "baz"]);
1388 /// assert_eq!(v.swap_remove(0), "foo");
1389 /// assert_eq!(v, ["baz", "qux"]);
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 pub fn swap_remove(&mut self, index: usize) -> T {
1396 fn assert_failed(index: usize, len: usize) -> ! {
1397 panic!("swap_remove index (is {index}) should be < len (is {len})");
1400 let len = self.len();
1402 assert_failed(index, len);
1405 // We replace self[index] with the last element. Note that if the
1406 // bounds check above succeeds there must be a last element (which
1407 // can be self[index] itself).
1408 let value = ptr::read(self.as_ptr().add(index));
1409 let base_ptr = self.as_mut_ptr();
1410 ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
1411 self.set_len(len - 1);
1416 /// Inserts an element at position `index` within the vector, shifting all
1417 /// elements after it to the right.
1421 /// Panics if `index > len`.
1426 /// let mut vec = vec![1, 2, 3];
1427 /// vec.insert(1, 4);
1428 /// assert_eq!(vec, [1, 4, 2, 3]);
1429 /// vec.insert(4, 5);
1430 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1432 #[cfg(not(no_global_oom_handling))]
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 pub fn insert(&mut self, index: usize, element: T) {
1437 fn assert_failed(index: usize, len: usize) -> ! {
1438 panic!("insertion index (is {index}) should be <= len (is {len})");
1441 let len = self.len();
1443 assert_failed(index, len);
1446 // space for the new element
1447 if len == self.buf.capacity() {
1453 // The spot to put the new value
1455 let p = self.as_mut_ptr().add(index);
1456 // Shift everything over to make space. (Duplicating the
1457 // `index`th element into two consecutive places.)
1458 ptr::copy(p, p.offset(1), len - index);
1459 // Write it in, overwriting the first copy of the `index`th
1461 ptr::write(p, element);
1463 self.set_len(len + 1);
1467 /// Removes and returns the element at position `index` within the vector,
1468 /// shifting all elements after it to the left.
1470 /// Note: Because this shifts over the remaining elements, it has a
1471 /// worst-case performance of *O*(*n*). If you don't need the order of elements
1472 /// to be preserved, use [`swap_remove`] instead. If you'd like to remove
1473 /// elements from the beginning of the `Vec`, consider using
1474 /// [`VecDeque::pop_front`] instead.
1476 /// [`swap_remove`]: Vec::swap_remove
1477 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
1481 /// Panics if `index` is out of bounds.
1486 /// let mut v = vec![1, 2, 3];
1487 /// assert_eq!(v.remove(1), 2);
1488 /// assert_eq!(v, [1, 3]);
1490 #[stable(feature = "rust1", since = "1.0.0")]
1492 pub fn remove(&mut self, index: usize) -> T {
1496 fn assert_failed(index: usize, len: usize) -> ! {
1497 panic!("removal index (is {index}) should be < len (is {len})");
1500 let len = self.len();
1502 assert_failed(index, len);
1508 // the place we are taking from.
1509 let ptr = self.as_mut_ptr().add(index);
1510 // copy it out, unsafely having a copy of the value on
1511 // the stack and in the vector at the same time.
1512 ret = ptr::read(ptr);
1514 // Shift everything down to fill in that spot.
1515 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1517 self.set_len(len - 1);
1522 /// Retains only the elements specified by the predicate.
1524 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
1525 /// This method operates in place, visiting each element exactly once in the
1526 /// original order, and preserves the order of the retained elements.
1531 /// let mut vec = vec![1, 2, 3, 4];
1532 /// vec.retain(|&x| x % 2 == 0);
1533 /// assert_eq!(vec, [2, 4]);
1536 /// Because the elements are visited exactly once in the original order,
1537 /// external state may be used to decide which elements to keep.
1540 /// let mut vec = vec![1, 2, 3, 4, 5];
1541 /// let keep = [false, true, true, false, true];
1542 /// let mut iter = keep.iter();
1543 /// vec.retain(|_| *iter.next().unwrap());
1544 /// assert_eq!(vec, [2, 3, 5]);
1546 #[stable(feature = "rust1", since = "1.0.0")]
1547 pub fn retain<F>(&mut self, mut f: F)
1549 F: FnMut(&T) -> bool,
1551 self.retain_mut(|elem| f(elem));
1554 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
1556 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
1557 /// This method operates in place, visiting each element exactly once in the
1558 /// original order, and preserves the order of the retained elements.
1563 /// let mut vec = vec![1, 2, 3, 4];
1564 /// vec.retain_mut(|x| if *x > 3 {
1570 /// assert_eq!(vec, [2, 3, 4]);
1572 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
1573 pub fn retain_mut<F>(&mut self, mut f: F)
1575 F: FnMut(&mut T) -> bool,
1577 let original_len = self.len();
1578 // Avoid double drop if the drop guard is not executed,
1579 // since we may make some holes during the process.
1580 unsafe { self.set_len(0) };
1582 // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
1583 // |<- processed len ->| ^- next to check
1584 // |<- deleted cnt ->|
1585 // |<- original_len ->|
1586 // Kept: Elements which predicate returns true on.
1587 // Hole: Moved or dropped element slot.
1588 // Unchecked: Unchecked valid elements.
1590 // This drop guard will be invoked when predicate or `drop` of element panicked.
1591 // It shifts unchecked elements to cover holes and `set_len` to the correct length.
1592 // In cases when predicate and `drop` never panick, it will be optimized out.
1593 struct BackshiftOnDrop<'a, T, A: Allocator> {
1594 v: &'a mut Vec<T, A>,
1595 processed_len: usize,
1597 original_len: usize,
1600 impl<T, A: Allocator> Drop for BackshiftOnDrop<'_, T, A> {
1601 fn drop(&mut self) {
1602 if self.deleted_cnt > 0 {
1603 // SAFETY: Trailing unchecked items must be valid since we never touch them.
1606 self.v.as_ptr().add(self.processed_len),
1607 self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt),
1608 self.original_len - self.processed_len,
1612 // SAFETY: After filling holes, all items are in contiguous memory.
1614 self.v.set_len(self.original_len - self.deleted_cnt);
1619 let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len };
1621 fn process_loop<F, T, A: Allocator, const DELETED: bool>(
1622 original_len: usize,
1624 g: &mut BackshiftOnDrop<'_, T, A>,
1626 F: FnMut(&mut T) -> bool,
1628 while g.processed_len != original_len {
1629 // SAFETY: Unchecked element must be valid.
1630 let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
1632 // Advance early to avoid double drop if `drop_in_place` panicked.
1633 g.processed_len += 1;
1635 // SAFETY: We never touch this element again after dropped.
1636 unsafe { ptr::drop_in_place(cur) };
1637 // We already advanced the counter.
1645 // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
1646 // We use copy for move, and never touch this element again.
1648 let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
1649 ptr::copy_nonoverlapping(cur, hole_slot, 1);
1652 g.processed_len += 1;
1656 // Stage 1: Nothing was deleted.
1657 process_loop::<F, T, A, false>(original_len, &mut f, &mut g);
1659 // Stage 2: Some elements were deleted.
1660 process_loop::<F, T, A, true>(original_len, &mut f, &mut g);
1662 // All item are processed. This can be optimized to `set_len` by LLVM.
1666 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1669 /// If the vector is sorted, this removes all duplicates.
1674 /// let mut vec = vec![10, 20, 21, 30, 20];
1676 /// vec.dedup_by_key(|i| *i / 10);
1678 /// assert_eq!(vec, [10, 20, 30, 20]);
1680 #[stable(feature = "dedup_by", since = "1.16.0")]
1682 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1684 F: FnMut(&mut T) -> K,
1687 self.dedup_by(|a, b| key(a) == key(b))
1690 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1693 /// The `same_bucket` function is passed references to two elements from the vector and
1694 /// must determine if the elements compare equal. The elements are passed in opposite order
1695 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1697 /// If the vector is sorted, this removes all duplicates.
1702 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1704 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1706 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1708 #[stable(feature = "dedup_by", since = "1.16.0")]
1709 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1711 F: FnMut(&mut T, &mut T) -> bool,
1713 let len = self.len();
1718 /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */
1719 struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> {
1720 /* Offset of the element we want to check if it is duplicate */
1723 /* Offset of the place where we want to place the non-duplicate
1724 * when we find it. */
1727 /* The Vec that would need correction if `same_bucket` panicked */
1728 vec: &'a mut Vec<T, A>,
1731 impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
1732 fn drop(&mut self) {
1733 /* This code gets executed when `same_bucket` panics */
1735 /* SAFETY: invariant guarantees that `read - write`
1736 * and `len - read` never overflow and that the copy is always
1739 let ptr = self.vec.as_mut_ptr();
1740 let len = self.vec.len();
1742 /* How many items were left when `same_bucket` panicked.
1743 * Basically vec[read..].len() */
1744 let items_left = len.wrapping_sub(self.read);
1746 /* Pointer to first item in vec[write..write+items_left] slice */
1747 let dropped_ptr = ptr.add(self.write);
1748 /* Pointer to first item in vec[read..] slice */
1749 let valid_ptr = ptr.add(self.read);
1751 /* Copy `vec[read..]` to `vec[write..write+items_left]`.
1752 * The slices can overlap, so `copy_nonoverlapping` cannot be used */
1753 ptr::copy(valid_ptr, dropped_ptr, items_left);
1755 /* How many items have been already dropped
1756 * Basically vec[read..write].len() */
1757 let dropped = self.read.wrapping_sub(self.write);
1759 self.vec.set_len(len - dropped);
1764 let mut gap = FillGapOnDrop { read: 1, write: 1, vec: self };
1765 let ptr = gap.vec.as_mut_ptr();
1767 /* Drop items while going through Vec, it should be more efficient than
1768 * doing slice partition_dedup + truncate */
1770 /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
1771 * are always in-bounds and read_ptr never aliases prev_ptr */
1773 while gap.read < len {
1774 let read_ptr = ptr.add(gap.read);
1775 let prev_ptr = ptr.add(gap.write.wrapping_sub(1));
1777 if same_bucket(&mut *read_ptr, &mut *prev_ptr) {
1778 // Increase `gap.read` now since the drop may panic.
1780 /* We have found duplicate, drop it in-place */
1781 ptr::drop_in_place(read_ptr);
1783 let write_ptr = ptr.add(gap.write);
1785 /* Because `read_ptr` can be equal to `write_ptr`, we either
1786 * have to use `copy` or conditional `copy_nonoverlapping`.
1787 * Looks like the first option is faster. */
1788 ptr::copy(read_ptr, write_ptr, 1);
1790 /* We have filled that place, so go further */
1796 /* Technically we could let `gap` clean up with its Drop, but
1797 * when `same_bucket` is guaranteed to not panic, this bloats a little
1798 * the codegen, so we just do it manually */
1799 gap.vec.set_len(gap.write);
1804 /// Appends an element to the back of a collection.
1808 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1813 /// let mut vec = vec![1, 2];
1815 /// assert_eq!(vec, [1, 2, 3]);
1817 #[cfg(not(no_global_oom_handling))]
1819 #[stable(feature = "rust1", since = "1.0.0")]
1820 pub fn push(&mut self, value: T) {
1821 // This will panic or abort if we would allocate > isize::MAX bytes
1822 // or if the length increment would overflow for zero-sized types.
1823 if self.len == self.buf.capacity() {
1824 self.buf.reserve_for_push(self.len);
1827 let end = self.as_mut_ptr().add(self.len);
1828 ptr::write(end, value);
1833 /// Tries to append an element to the back of a collection.
1838 /// let mut vec = vec![1, 2];
1839 /// vec.try_push(3).unwrap();
1840 /// assert_eq!(vec, [1, 2, 3]);
1843 #[stable(feature = "kernel", since = "1.0.0")]
1844 pub fn try_push(&mut self, value: T) -> Result<(), TryReserveError> {
1845 if self.len == self.buf.capacity() {
1846 self.buf.try_reserve_for_push(self.len)?;
1849 let end = self.as_mut_ptr().add(self.len);
1850 ptr::write(end, value);
1856 /// Removes the last element from a vector and returns it, or [`None`] if it
1859 /// If you'd like to pop the first element, consider using
1860 /// [`VecDeque::pop_front`] instead.
1862 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
1867 /// let mut vec = vec![1, 2, 3];
1868 /// assert_eq!(vec.pop(), Some(3));
1869 /// assert_eq!(vec, [1, 2]);
1872 #[stable(feature = "rust1", since = "1.0.0")]
1873 pub fn pop(&mut self) -> Option<T> {
1879 Some(ptr::read(self.as_ptr().add(self.len())))
1884 /// Moves all the elements of `other` into `self`, leaving `other` empty.
1888 /// Panics if the number of elements in the vector overflows a `usize`.
1893 /// let mut vec = vec![1, 2, 3];
1894 /// let mut vec2 = vec![4, 5, 6];
1895 /// vec.append(&mut vec2);
1896 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1897 /// assert_eq!(vec2, []);
1899 #[cfg(not(no_global_oom_handling))]
1901 #[stable(feature = "append", since = "1.4.0")]
1902 pub fn append(&mut self, other: &mut Self) {
1904 self.append_elements(other.as_slice() as _);
1909 /// Appends elements to `self` from other buffer.
1910 #[cfg(not(no_global_oom_handling))]
1912 unsafe fn append_elements(&mut self, other: *const [T]) {
1913 let count = unsafe { (*other).len() };
1914 self.reserve(count);
1915 let len = self.len();
1916 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1920 /// Removes the specified range from the vector in bulk, returning all
1921 /// removed elements as an iterator. If the iterator is dropped before
1922 /// being fully consumed, it drops the remaining removed elements.
1924 /// The returned iterator keeps a mutable borrow on the vector to optimize
1925 /// its implementation.
1929 /// Panics if the starting point is greater than the end point or if
1930 /// the end point is greater than the length of the vector.
1934 /// If the returned iterator goes out of scope without being dropped (due to
1935 /// [`mem::forget`], for example), the vector may have lost and leaked
1936 /// elements arbitrarily, including elements outside the range.
1941 /// let mut v = vec![1, 2, 3];
1942 /// let u: Vec<_> = v.drain(1..).collect();
1943 /// assert_eq!(v, &[1]);
1944 /// assert_eq!(u, &[2, 3]);
1946 /// // A full range clears the vector, like `clear()` does
1948 /// assert_eq!(v, &[]);
1950 #[stable(feature = "drain", since = "1.6.0")]
1951 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1953 R: RangeBounds<usize>,
1957 // When the Drain is first created, it shortens the length of
1958 // the source vector to make sure no uninitialized or moved-from elements
1959 // are accessible at all if the Drain's destructor never gets to run.
1961 // Drain will ptr::read out the values to remove.
1962 // When finished, remaining tail of the vec is copied back to cover
1963 // the hole, and the vector length is restored to the new length.
1965 let len = self.len();
1966 let Range { start, end } = slice::range(range, ..len);
1969 // set self.vec length's to start, to be safe in case Drain is leaked
1970 self.set_len(start);
1971 // Use the borrow in the IterMut to indicate borrowing behavior of the
1972 // whole Drain iterator (like &mut T).
1973 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1976 tail_len: len - end,
1977 iter: range_slice.iter(),
1978 vec: NonNull::from(self),
1983 /// Clears the vector, removing all values.
1985 /// Note that this method has no effect on the allocated capacity
1991 /// let mut v = vec![1, 2, 3];
1995 /// assert!(v.is_empty());
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 pub fn clear(&mut self) {
2000 let elems: *mut [T] = self.as_mut_slice();
2003 // - `elems` comes directly from `as_mut_slice` and is therefore valid.
2004 // - Setting `self.len` before calling `drop_in_place` means that,
2005 // if an element's `Drop` impl panics, the vector's `Drop` impl will
2006 // do nothing (leaking the rest of the elements) instead of dropping
2010 ptr::drop_in_place(elems);
2014 /// Returns the number of elements in the vector, also referred to
2015 /// as its 'length'.
2020 /// let a = vec![1, 2, 3];
2021 /// assert_eq!(a.len(), 3);
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 pub fn len(&self) -> usize {
2029 /// Returns `true` if the vector contains no elements.
2034 /// let mut v = Vec::new();
2035 /// assert!(v.is_empty());
2038 /// assert!(!v.is_empty());
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 pub fn is_empty(&self) -> bool {
2045 /// Splits the collection into two at the given index.
2047 /// Returns a newly allocated vector containing the elements in the range
2048 /// `[at, len)`. After the call, the original vector will be left containing
2049 /// the elements `[0, at)` with its previous capacity unchanged.
2053 /// Panics if `at > len`.
2058 /// let mut vec = vec![1, 2, 3];
2059 /// let vec2 = vec.split_off(1);
2060 /// assert_eq!(vec, [1]);
2061 /// assert_eq!(vec2, [2, 3]);
2063 #[cfg(not(no_global_oom_handling))]
2065 #[must_use = "use `.truncate()` if you don't need the other half"]
2066 #[stable(feature = "split_off", since = "1.4.0")]
2067 pub fn split_off(&mut self, at: usize) -> Self
2073 fn assert_failed(at: usize, len: usize) -> ! {
2074 panic!("`at` split index (is {at}) should be <= len (is {len})");
2077 if at > self.len() {
2078 assert_failed(at, self.len());
2082 // the new vector can take over the original buffer and avoid the copy
2083 return mem::replace(
2085 Vec::with_capacity_in(self.capacity(), self.allocator().clone()),
2089 let other_len = self.len - at;
2090 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
2092 // Unsafely `set_len` and copy items to `other`.
2095 other.set_len(other_len);
2097 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
2102 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2104 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2105 /// difference, with each additional slot filled with the result of
2106 /// calling the closure `f`. The return values from `f` will end up
2107 /// in the `Vec` in the order they have been generated.
2109 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2111 /// This method uses a closure to create new values on every push. If
2112 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
2113 /// want to use the [`Default`] trait to generate values, you can
2114 /// pass [`Default::default`] as the second argument.
2119 /// let mut vec = vec![1, 2, 3];
2120 /// vec.resize_with(5, Default::default);
2121 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
2123 /// let mut vec = vec![];
2125 /// vec.resize_with(4, || { p *= 2; p });
2126 /// assert_eq!(vec, [2, 4, 8, 16]);
2128 #[cfg(not(no_global_oom_handling))]
2129 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2130 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
2134 let len = self.len();
2136 self.extend_with(new_len - len, ExtendFunc(f));
2138 self.truncate(new_len);
2142 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
2143 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
2144 /// `'a`. If the type has only static references, or none at all, then this
2145 /// may be chosen to be `'static`.
2147 /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
2148 /// so the leaked allocation may include unused capacity that is not part
2149 /// of the returned slice.
2151 /// This function is mainly useful for data that lives for the remainder of
2152 /// the program's life. Dropping the returned reference will cause a memory
2160 /// let x = vec![1, 2, 3];
2161 /// let static_ref: &'static mut [usize] = x.leak();
2162 /// static_ref[0] += 1;
2163 /// assert_eq!(static_ref, &[2, 2, 3]);
2165 #[cfg(not(no_global_oom_handling))]
2166 #[stable(feature = "vec_leak", since = "1.47.0")]
2168 pub fn leak<'a>(self) -> &'a mut [T]
2172 let mut me = ManuallyDrop::new(self);
2173 unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
2176 /// Returns the remaining spare capacity of the vector as a slice of
2177 /// `MaybeUninit<T>`.
2179 /// The returned slice can be used to fill the vector with data (e.g. by
2180 /// reading from a file) before marking the data as initialized using the
2181 /// [`set_len`] method.
2183 /// [`set_len`]: Vec::set_len
2188 /// // Allocate vector big enough for 10 elements.
2189 /// let mut v = Vec::with_capacity(10);
2191 /// // Fill in the first 3 elements.
2192 /// let uninit = v.spare_capacity_mut();
2193 /// uninit[0].write(0);
2194 /// uninit[1].write(1);
2195 /// uninit[2].write(2);
2197 /// // Mark the first 3 elements of the vector as being initialized.
2202 /// assert_eq!(&v, &[0, 1, 2]);
2204 #[stable(feature = "vec_spare_capacity", since = "1.60.0")]
2206 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
2208 // This method is not implemented in terms of `split_at_spare_mut`,
2209 // to prevent invalidation of pointers to the buffer.
2211 slice::from_raw_parts_mut(
2212 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
2213 self.buf.capacity() - self.len,
2218 /// Returns vector content as a slice of `T`, along with the remaining spare
2219 /// capacity of the vector as a slice of `MaybeUninit<T>`.
2221 /// The returned spare capacity slice can be used to fill the vector with data
2222 /// (e.g. by reading from a file) before marking the data as initialized using
2223 /// the [`set_len`] method.
2225 /// [`set_len`]: Vec::set_len
2227 /// Note that this is a low-level API, which should be used with care for
2228 /// optimization purposes. If you need to append data to a `Vec`
2229 /// you can use [`push`], [`extend`], [`extend_from_slice`],
2230 /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
2231 /// [`resize_with`], depending on your exact needs.
2233 /// [`push`]: Vec::push
2234 /// [`extend`]: Vec::extend
2235 /// [`extend_from_slice`]: Vec::extend_from_slice
2236 /// [`extend_from_within`]: Vec::extend_from_within
2237 /// [`insert`]: Vec::insert
2238 /// [`append`]: Vec::append
2239 /// [`resize`]: Vec::resize
2240 /// [`resize_with`]: Vec::resize_with
2245 /// #![feature(vec_split_at_spare)]
2247 /// let mut v = vec![1, 1, 2];
2249 /// // Reserve additional space big enough for 10 elements.
2252 /// let (init, uninit) = v.split_at_spare_mut();
2253 /// let sum = init.iter().copied().sum::<u32>();
2255 /// // Fill in the next 4 elements.
2256 /// uninit[0].write(sum);
2257 /// uninit[1].write(sum * 2);
2258 /// uninit[2].write(sum * 3);
2259 /// uninit[3].write(sum * 4);
2261 /// // Mark the 4 elements of the vector as being initialized.
2263 /// let len = v.len();
2264 /// v.set_len(len + 4);
2267 /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
2269 #[unstable(feature = "vec_split_at_spare", issue = "81944")]
2271 pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
2273 // - len is ignored and so never changed
2274 let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
2278 /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
2280 /// This method provides unique access to all vec parts at once in `extend_from_within`.
2281 unsafe fn split_at_spare_mut_with_len(
2283 ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
2284 let ptr = self.as_mut_ptr();
2286 // - `ptr` is guaranteed to be valid for `self.len` elements
2287 // - but the allocation extends out to `self.buf.capacity()` elements, possibly
2289 let spare_ptr = unsafe { ptr.add(self.len) };
2290 let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>();
2291 let spare_len = self.buf.capacity() - self.len;
2294 // - `ptr` is guaranteed to be valid for `self.len` elements
2295 // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
2297 let initialized = slice::from_raw_parts_mut(ptr, self.len);
2298 let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
2300 (initialized, spare, &mut self.len)
2305 impl<T: Clone, A: Allocator> Vec<T, A> {
2306 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2308 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2309 /// difference, with each additional slot filled with `value`.
2310 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2312 /// This method requires `T` to implement [`Clone`],
2313 /// in order to be able to clone the passed value.
2314 /// If you need more flexibility (or want to rely on [`Default`] instead of
2315 /// [`Clone`]), use [`Vec::resize_with`].
2316 /// If you only need to resize to a smaller size, use [`Vec::truncate`].
2321 /// let mut vec = vec!["hello"];
2322 /// vec.resize(3, "world");
2323 /// assert_eq!(vec, ["hello", "world", "world"]);
2325 /// let mut vec = vec![1, 2, 3, 4];
2326 /// vec.resize(2, 0);
2327 /// assert_eq!(vec, [1, 2]);
2329 #[cfg(not(no_global_oom_handling))]
2330 #[stable(feature = "vec_resize", since = "1.5.0")]
2331 pub fn resize(&mut self, new_len: usize, value: T) {
2332 let len = self.len();
2335 self.extend_with(new_len - len, ExtendElement(value))
2337 self.truncate(new_len);
2341 /// Clones and appends all elements in a slice to the `Vec`.
2343 /// Iterates over the slice `other`, clones each element, and then appends
2344 /// it to this `Vec`. The `other` slice is traversed in-order.
2346 /// Note that this function is same as [`extend`] except that it is
2347 /// specialized to work with slices instead. If and when Rust gets
2348 /// specialization this function will likely be deprecated (but still
2354 /// let mut vec = vec![1];
2355 /// vec.extend_from_slice(&[2, 3, 4]);
2356 /// assert_eq!(vec, [1, 2, 3, 4]);
2359 /// [`extend`]: Vec::extend
2360 #[cfg(not(no_global_oom_handling))]
2361 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
2362 pub fn extend_from_slice(&mut self, other: &[T]) {
2363 self.spec_extend(other.iter())
2366 /// Copies elements from `src` range to the end of the vector.
2370 /// Panics if the starting point is greater than the end point or if
2371 /// the end point is greater than the length of the vector.
2376 /// let mut vec = vec![0, 1, 2, 3, 4];
2378 /// vec.extend_from_within(2..);
2379 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
2381 /// vec.extend_from_within(..2);
2382 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
2384 /// vec.extend_from_within(4..8);
2385 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
2387 #[cfg(not(no_global_oom_handling))]
2388 #[stable(feature = "vec_extend_from_within", since = "1.53.0")]
2389 pub fn extend_from_within<R>(&mut self, src: R)
2391 R: RangeBounds<usize>,
2393 let range = slice::range(src, ..self.len());
2394 self.reserve(range.len());
2397 // - `slice::range` guarantees that the given range is valid for indexing self
2399 self.spec_extend_from_within(range);
2404 impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
2405 /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
2409 /// Panics if the length of the resulting vector would overflow a `usize`.
2411 /// This is only possible when flattening a vector of arrays of zero-sized
2412 /// types, and thus tends to be irrelevant in practice. If
2413 /// `size_of::<T>() > 0`, this will never panic.
2418 /// #![feature(slice_flatten)]
2420 /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
2421 /// assert_eq!(vec.pop(), Some([7, 8, 9]));
2423 /// let mut flattened = vec.into_flattened();
2424 /// assert_eq!(flattened.pop(), Some(6));
2426 #[unstable(feature = "slice_flatten", issue = "95629")]
2427 pub fn into_flattened(self) -> Vec<T, A> {
2428 let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
2429 let (new_len, new_cap) = if mem::size_of::<T>() == 0 {
2430 (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
2433 // - `cap * N` cannot overflow because the allocation is already in
2434 // the address space.
2435 // - Each `[T; N]` has `N` valid elements, so there are `len * N`
2436 // valid elements in the allocation.
2437 unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) }
2440 // - `ptr` was allocated by `self`
2441 // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
2442 // - `new_cap` refers to the same sized allocation as `cap` because
2443 // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
2444 // - `len` <= `cap`, so `len * N` <= `cap * N`.
2445 unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
2449 // This code generalizes `extend_with_{element,default}`.
2450 trait ExtendWith<T> {
2451 fn next(&mut self) -> T;
2455 struct ExtendElement<T>(T);
2456 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
2457 fn next(&mut self) -> T {
2460 fn last(self) -> T {
2465 struct ExtendFunc<F>(F);
2466 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
2467 fn next(&mut self) -> T {
2470 fn last(mut self) -> T {
2475 impl<T, A: Allocator> Vec<T, A> {
2476 #[cfg(not(no_global_oom_handling))]
2477 /// Extend the vector by `n` values, using the given generator.
2478 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
2482 let mut ptr = self.as_mut_ptr().add(self.len());
2483 // Use SetLenOnDrop to work around bug where compiler
2484 // might not realize the store through `ptr` through self.set_len()
2486 let mut local_len = SetLenOnDrop::new(&mut self.len);
2488 // Write all elements except the last one
2490 ptr::write(ptr, value.next());
2491 ptr = ptr.offset(1);
2492 // Increment the length in every step in case next() panics
2493 local_len.increment_len(1);
2497 // We can write the last element directly without cloning needlessly
2498 ptr::write(ptr, value.last());
2499 local_len.increment_len(1);
2502 // len set by scope guard
2507 impl<T: PartialEq, A: Allocator> Vec<T, A> {
2508 /// Removes consecutive repeated elements in the vector according to the
2509 /// [`PartialEq`] trait implementation.
2511 /// If the vector is sorted, this removes all duplicates.
2516 /// let mut vec = vec![1, 2, 2, 3, 2];
2520 /// assert_eq!(vec, [1, 2, 3, 2]);
2522 #[stable(feature = "rust1", since = "1.0.0")]
2524 pub fn dedup(&mut self) {
2525 self.dedup_by(|a, b| a == b)
2529 ////////////////////////////////////////////////////////////////////////////////
2530 // Internal methods and functions
2531 ////////////////////////////////////////////////////////////////////////////////
2534 #[cfg(not(no_global_oom_handling))]
2535 #[stable(feature = "rust1", since = "1.0.0")]
2536 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
2537 <T as SpecFromElem>::from_elem(elem, n, Global)
2541 #[cfg(not(no_global_oom_handling))]
2542 #[unstable(feature = "allocator_api", issue = "32838")]
2543 pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
2544 <T as SpecFromElem>::from_elem(elem, n, alloc)
2547 trait ExtendFromWithinSpec {
2550 /// - `src` needs to be valid index
2551 /// - `self.capacity() - self.len()` must be `>= src.len()`
2552 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
2555 impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
2556 default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
2558 // - len is increased only after initializing elements
2559 let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
2562 // - caller guaratees that src is a valid index
2563 let to_clone = unsafe { this.get_unchecked(src) };
2565 iter::zip(to_clone, spare)
2566 .map(|(src, dst)| dst.write(src.clone()))
2568 // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
2569 // - len is increased after each element to prevent leaks (see issue #82533)
2570 .for_each(|_| *len += 1);
2574 impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
2575 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
2576 let count = src.len();
2578 let (init, spare) = self.split_at_spare_mut();
2581 // - caller guaratees that `src` is a valid index
2582 let source = unsafe { init.get_unchecked(src) };
2585 // - Both pointers are created from unique slice references (`&mut [_]`)
2586 // so they are valid and do not overlap.
2587 // - Elements are :Copy so it's OK to to copy them, without doing
2588 // anything with the original values
2589 // - `count` is equal to the len of `source`, so source is valid for
2591 // - `.reserve(count)` guarantees that `spare.len() >= count` so spare
2592 // is valid for `count` writes
2593 unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
2597 // - The elements were just initialized by `copy_nonoverlapping`
2602 ////////////////////////////////////////////////////////////////////////////////
2603 // Common trait implementations for Vec
2604 ////////////////////////////////////////////////////////////////////////////////
2606 #[stable(feature = "rust1", since = "1.0.0")]
2607 impl<T, A: Allocator> ops::Deref for Vec<T, A> {
2610 fn deref(&self) -> &[T] {
2611 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
2615 #[stable(feature = "rust1", since = "1.0.0")]
2616 impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
2617 fn deref_mut(&mut self) -> &mut [T] {
2618 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
2622 #[cfg(not(no_global_oom_handling))]
2623 trait SpecCloneFrom {
2624 fn clone_from(this: &mut Self, other: &Self);
2627 #[cfg(not(no_global_oom_handling))]
2628 impl<T: Clone, A: Allocator> SpecCloneFrom for Vec<T, A> {
2629 default fn clone_from(this: &mut Self, other: &Self) {
2630 // drop anything that will not be overwritten
2631 this.truncate(other.len());
2633 // self.len <= other.len due to the truncate above, so the
2634 // slices here are always in-bounds.
2635 let (init, tail) = other.split_at(this.len());
2637 // reuse the contained values' allocations/resources.
2638 this.clone_from_slice(init);
2639 this.extend_from_slice(tail);
2643 #[cfg(not(no_global_oom_handling))]
2644 impl<T: Copy, A: Allocator> SpecCloneFrom for Vec<T, A> {
2645 fn clone_from(this: &mut Self, other: &Self) {
2647 this.extend_from_slice(other);
2651 #[cfg(not(no_global_oom_handling))]
2652 #[stable(feature = "rust1", since = "1.0.0")]
2653 impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
2655 fn clone(&self) -> Self {
2656 let alloc = self.allocator().clone();
2657 <[T]>::to_vec_in(&**self, alloc)
2660 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
2661 // required for this method definition, is not available. Instead use the
2662 // `slice::to_vec` function which is only available with cfg(test)
2663 // NB see the slice::hack module in slice.rs for more information
2665 fn clone(&self) -> Self {
2666 let alloc = self.allocator().clone();
2667 crate::slice::to_vec(&**self, alloc)
2670 fn clone_from(&mut self, other: &Self) {
2671 SpecCloneFrom::clone_from(self, other)
2675 /// The hash of a vector is the same as that of the corresponding slice,
2676 /// as required by the `core::borrow::Borrow` implementation.
2679 /// #![feature(build_hasher_simple_hash_one)]
2680 /// use std::hash::BuildHasher;
2682 /// let b = std::collections::hash_map::RandomState::new();
2683 /// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
2684 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
2685 /// assert_eq!(b.hash_one(v), b.hash_one(s));
2687 #[stable(feature = "rust1", since = "1.0.0")]
2688 impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
2690 fn hash<H: Hasher>(&self, state: &mut H) {
2691 Hash::hash(&**self, state)
2695 #[stable(feature = "rust1", since = "1.0.0")]
2696 #[rustc_on_unimplemented(
2697 message = "vector indices are of type `usize` or ranges of `usize`",
2698 label = "vector indices are of type `usize` or ranges of `usize`"
2700 impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
2701 type Output = I::Output;
2704 fn index(&self, index: I) -> &Self::Output {
2705 Index::index(&**self, index)
2709 #[stable(feature = "rust1", since = "1.0.0")]
2710 #[rustc_on_unimplemented(
2711 message = "vector indices are of type `usize` or ranges of `usize`",
2712 label = "vector indices are of type `usize` or ranges of `usize`"
2714 impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
2716 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2717 IndexMut::index_mut(&mut **self, index)
2721 #[cfg(not(no_global_oom_handling))]
2722 #[stable(feature = "rust1", since = "1.0.0")]
2723 impl<T> FromIterator<T> for Vec<T> {
2725 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2726 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
2730 #[stable(feature = "rust1", since = "1.0.0")]
2731 impl<T, A: Allocator> IntoIterator for Vec<T, A> {
2733 type IntoIter = IntoIter<T, A>;
2735 /// Creates a consuming iterator, that is, one that moves each value out of
2736 /// the vector (from start to end). The vector cannot be used after calling
2742 /// let v = vec!["a".to_string(), "b".to_string()];
2743 /// for s in v.into_iter() {
2744 /// // s has type String, not &String
2745 /// println!("{s}");
2749 fn into_iter(self) -> IntoIter<T, A> {
2751 let mut me = ManuallyDrop::new(self);
2752 let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
2753 let begin = me.as_mut_ptr();
2754 let end = if mem::size_of::<T>() == 0 {
2755 arith_offset(begin as *const i8, me.len() as isize) as *const T
2757 begin.add(me.len()) as *const T
2759 let cap = me.buf.capacity();
2761 buf: NonNull::new_unchecked(begin),
2762 phantom: PhantomData,
2772 #[stable(feature = "rust1", since = "1.0.0")]
2773 impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
2775 type IntoIter = slice::Iter<'a, T>;
2777 fn into_iter(self) -> slice::Iter<'a, T> {
2782 #[stable(feature = "rust1", since = "1.0.0")]
2783 impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
2784 type Item = &'a mut T;
2785 type IntoIter = slice::IterMut<'a, T>;
2787 fn into_iter(self) -> slice::IterMut<'a, T> {
2792 #[cfg(not(no_global_oom_handling))]
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 impl<T, A: Allocator> Extend<T> for Vec<T, A> {
2796 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2797 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2801 fn extend_one(&mut self, item: T) {
2806 fn extend_reserve(&mut self, additional: usize) {
2807 self.reserve(additional);
2811 impl<T, A: Allocator> Vec<T, A> {
2812 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2813 // they have no further optimizations to apply
2814 #[cfg(not(no_global_oom_handling))]
2815 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2816 // This is the case for a general iterator.
2818 // This function should be the moral equivalent of:
2820 // for item in iterator {
2823 while let Some(element) = iterator.next() {
2824 let len = self.len();
2825 if len == self.capacity() {
2826 let (lower, _) = iterator.size_hint();
2827 self.reserve(lower.saturating_add(1));
2830 ptr::write(self.as_mut_ptr().add(len), element);
2831 // Since next() executes user code which can panic we have to bump the length
2833 // NB can't overflow since we would have had to alloc the address space
2834 self.set_len(len + 1);
2839 /// Creates a splicing iterator that replaces the specified range in the vector
2840 /// with the given `replace_with` iterator and yields the removed items.
2841 /// `replace_with` does not need to be the same length as `range`.
2843 /// `range` is removed even if the iterator is not consumed until the end.
2845 /// It is unspecified how many elements are removed from the vector
2846 /// if the `Splice` value is leaked.
2848 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2850 /// This is optimal if:
2852 /// * The tail (elements in the vector after `range`) is empty,
2853 /// * or `replace_with` yields fewer or equal elements than `range`’s length
2854 /// * or the lower bound of its `size_hint()` is exact.
2856 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2860 /// Panics if the starting point is greater than the end point or if
2861 /// the end point is greater than the length of the vector.
2866 /// let mut v = vec![1, 2, 3, 4];
2867 /// let new = [7, 8, 9];
2868 /// let u: Vec<_> = v.splice(1..3, new).collect();
2869 /// assert_eq!(v, &[1, 7, 8, 9, 4]);
2870 /// assert_eq!(u, &[2, 3]);
2872 #[cfg(not(no_global_oom_handling))]
2874 #[stable(feature = "vec_splice", since = "1.21.0")]
2875 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
2877 R: RangeBounds<usize>,
2878 I: IntoIterator<Item = T>,
2880 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2883 /// Creates an iterator which uses a closure to determine if an element should be removed.
2885 /// If the closure returns true, then the element is removed and yielded.
2886 /// If the closure returns false, the element will remain in the vector and will not be yielded
2887 /// by the iterator.
2889 /// Using this method is equivalent to the following code:
2892 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2893 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2895 /// while i < vec.len() {
2896 /// if some_predicate(&mut vec[i]) {
2897 /// let val = vec.remove(i);
2898 /// // your code here
2904 /// # assert_eq!(vec, vec![1, 4, 5]);
2907 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2908 /// because it can backshift the elements of the array in bulk.
2910 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2911 /// regardless of whether you choose to keep or remove it.
2915 /// Splitting an array into evens and odds, reusing the original allocation:
2918 /// #![feature(drain_filter)]
2919 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2921 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2922 /// let odds = numbers;
2924 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2925 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2927 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2928 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F, A>
2930 F: FnMut(&mut T) -> bool,
2932 let old_len = self.len();
2934 // Guard against us getting leaked (leak amplification)
2939 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2943 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2945 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2946 /// append the entire slice at once.
2948 /// [`copy_from_slice`]: slice::copy_from_slice
2949 #[cfg(not(no_global_oom_handling))]
2950 #[stable(feature = "extend_ref", since = "1.2.0")]
2951 impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec<T, A> {
2952 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2953 self.spec_extend(iter.into_iter())
2957 fn extend_one(&mut self, &item: &'a T) {
2962 fn extend_reserve(&mut self, additional: usize) {
2963 self.reserve(additional);
2967 /// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2968 #[stable(feature = "rust1", since = "1.0.0")]
2969 impl<T: PartialOrd, A: Allocator> PartialOrd for Vec<T, A> {
2971 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2972 PartialOrd::partial_cmp(&**self, &**other)
2976 #[stable(feature = "rust1", since = "1.0.0")]
2977 impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
2979 /// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2980 #[stable(feature = "rust1", since = "1.0.0")]
2981 impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
2983 fn cmp(&self, other: &Self) -> Ordering {
2984 Ord::cmp(&**self, &**other)
2988 #[stable(feature = "rust1", since = "1.0.0")]
2989 unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
2990 fn drop(&mut self) {
2993 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2994 // could avoid questions of validity in certain cases
2995 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2997 // RawVec handles deallocation
3001 #[stable(feature = "rust1", since = "1.0.0")]
3002 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
3003 impl<T> const Default for Vec<T> {
3004 /// Creates an empty `Vec<T>`.
3005 fn default() -> Vec<T> {
3010 #[stable(feature = "rust1", since = "1.0.0")]
3011 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
3012 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3013 fmt::Debug::fmt(&**self, f)
3017 #[stable(feature = "rust1", since = "1.0.0")]
3018 impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
3019 fn as_ref(&self) -> &Vec<T, A> {
3024 #[stable(feature = "vec_as_mut", since = "1.5.0")]
3025 impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
3026 fn as_mut(&mut self) -> &mut Vec<T, A> {
3031 #[stable(feature = "rust1", since = "1.0.0")]
3032 impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
3033 fn as_ref(&self) -> &[T] {
3038 #[stable(feature = "vec_as_mut", since = "1.5.0")]
3039 impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
3040 fn as_mut(&mut self) -> &mut [T] {
3045 #[cfg(not(no_global_oom_handling))]
3046 #[stable(feature = "rust1", since = "1.0.0")]
3047 impl<T: Clone> From<&[T]> for Vec<T> {
3048 /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
3053 /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
3056 fn from(s: &[T]) -> Vec<T> {
3060 fn from(s: &[T]) -> Vec<T> {
3061 crate::slice::to_vec(s, Global)
3065 #[cfg(not(no_global_oom_handling))]
3066 #[stable(feature = "vec_from_mut", since = "1.19.0")]
3067 impl<T: Clone> From<&mut [T]> for Vec<T> {
3068 /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
3073 /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
3076 fn from(s: &mut [T]) -> Vec<T> {
3080 fn from(s: &mut [T]) -> Vec<T> {
3081 crate::slice::to_vec(s, Global)
3085 #[cfg(not(no_global_oom_handling))]
3086 #[stable(feature = "vec_from_array", since = "1.44.0")]
3087 impl<T, const N: usize> From<[T; N]> for Vec<T> {
3088 /// Allocate a `Vec<T>` and move `s`'s items into it.
3093 /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
3096 fn from(s: [T; N]) -> Vec<T> {
3097 <[T]>::into_vec(box s)
3101 fn from(s: [T; N]) -> Vec<T> {
3102 crate::slice::into_vec(box s)
3106 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
3107 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
3109 [T]: ToOwned<Owned = Vec<T>>,
3111 /// Convert a clone-on-write slice into a vector.
3113 /// If `s` already owns a `Vec<T>`, it will be returned directly.
3114 /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and
3115 /// filled by cloning `s`'s items into it.
3120 /// # use std::borrow::Cow;
3121 /// let o: Cow<[i32]> = Cow::Owned(vec![1, 2, 3]);
3122 /// let b: Cow<[i32]> = Cow::Borrowed(&[1, 2, 3]);
3123 /// assert_eq!(Vec::from(o), Vec::from(b));
3125 fn from(s: Cow<'a, [T]>) -> Vec<T> {
3130 // note: test pulls in libstd, which causes errors here
3132 #[stable(feature = "vec_from_box", since = "1.18.0")]
3133 impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
3134 /// Convert a boxed slice into a vector by transferring ownership of
3135 /// the existing heap allocation.
3140 /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
3141 /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
3143 fn from(s: Box<[T], A>) -> Self {
3148 // note: test pulls in libstd, which causes errors here
3149 #[cfg(not(no_global_oom_handling))]
3151 #[stable(feature = "box_from_vec", since = "1.20.0")]
3152 impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
3153 /// Convert a vector into a boxed slice.
3155 /// If `v` has excess capacity, its items will be moved into a
3156 /// newly-allocated buffer with exactly the right capacity.
3161 /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
3163 fn from(v: Vec<T, A>) -> Self {
3164 v.into_boxed_slice()
3168 #[cfg(not(no_global_oom_handling))]
3169 #[stable(feature = "rust1", since = "1.0.0")]
3170 impl From<&str> for Vec<u8> {
3171 /// Allocate a `Vec<u8>` and fill it with a UTF-8 string.
3176 /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
3178 fn from(s: &str) -> Vec<u8> {
3179 From::from(s.as_bytes())
3183 #[stable(feature = "array_try_from_vec", since = "1.48.0")]
3184 impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
3185 type Error = Vec<T, A>;
3187 /// Gets the entire contents of the `Vec<T>` as an array,
3188 /// if its size exactly matches that of the requested array.
3193 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
3194 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
3197 /// If the length doesn't match, the input comes back in `Err`:
3199 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
3200 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
3203 /// If you're fine with just getting a prefix of the `Vec<T>`,
3204 /// you can call [`.truncate(N)`](Vec::truncate) first.
3206 /// let mut v = String::from("hello world").into_bytes();
3209 /// let [a, b]: [_; 2] = v.try_into().unwrap();
3210 /// assert_eq!(a, b' ');
3211 /// assert_eq!(b, b'd');
3213 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
3218 // SAFETY: `.set_len(0)` is always sound.
3219 unsafe { vec.set_len(0) };
3221 // SAFETY: A `Vec`'s pointer is always aligned properly, and
3222 // the alignment the array needs is the same as the items.
3223 // We checked earlier that we have sufficient items.
3224 // The items will not double-drop as the `set_len`
3225 // tells the `Vec` not to also drop them.
3226 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };