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;
62 use core::hash::{Hash, Hasher};
64 use core::marker::PhantomData;
65 use core::mem::{self, ManuallyDrop, MaybeUninit, SizedTypeProperties};
66 use core::ops::{self, Index, IndexMut, Range, RangeBounds};
67 use core::ptr::{self, NonNull};
68 use core::slice::{self, SliceIndex};
70 use crate::alloc::{Allocator, Global};
71 #[cfg(not(no_borrow))]
72 use crate::borrow::{Cow, ToOwned};
73 use crate::boxed::Box;
74 use crate::collections::{TryReserveError, TryReserveErrorKind};
75 use crate::raw_vec::RawVec;
77 #[unstable(feature = "extract_if", reason = "recently added", issue = "43244")]
78 pub use self::extract_if::ExtractIf;
82 #[cfg(not(no_global_oom_handling))]
83 #[stable(feature = "vec_splice", since = "1.21.0")]
84 pub use self::splice::Splice;
86 #[cfg(not(no_global_oom_handling))]
89 #[stable(feature = "drain", since = "1.6.0")]
90 pub use self::drain::Drain;
94 #[cfg(not(no_borrow))]
95 #[cfg(not(no_global_oom_handling))]
98 #[cfg(not(no_global_oom_handling))]
99 pub(crate) use self::in_place_collect::AsVecIntoIter;
100 #[stable(feature = "rust1", since = "1.0.0")]
101 pub use self::into_iter::IntoIter;
105 #[cfg(not(no_global_oom_handling))]
106 use self::is_zero::IsZero;
110 #[cfg(not(no_global_oom_handling))]
111 mod in_place_collect;
115 #[cfg(not(no_global_oom_handling))]
116 use self::spec_from_elem::SpecFromElem;
118 #[cfg(not(no_global_oom_handling))]
121 use self::set_len_on_drop::SetLenOnDrop;
125 #[cfg(not(no_global_oom_handling))]
126 use self::in_place_drop::{InPlaceDrop, InPlaceDstBufDrop};
128 #[cfg(not(no_global_oom_handling))]
131 #[cfg(not(no_global_oom_handling))]
132 use self::spec_from_iter_nested::SpecFromIterNested;
134 #[cfg(not(no_global_oom_handling))]
135 mod spec_from_iter_nested;
137 #[cfg(not(no_global_oom_handling))]
138 use self::spec_from_iter::SpecFromIter;
140 #[cfg(not(no_global_oom_handling))]
143 #[cfg(not(no_global_oom_handling))]
144 use self::spec_extend::SpecExtend;
146 use self::spec_extend::TrySpecExtend;
150 /// A contiguous growable array type, written as `Vec<T>`, short for 'vector'.
155 /// let mut vec = Vec::new();
159 /// assert_eq!(vec.len(), 2);
160 /// assert_eq!(vec[0], 1);
162 /// assert_eq!(vec.pop(), Some(2));
163 /// assert_eq!(vec.len(), 1);
166 /// assert_eq!(vec[0], 7);
168 /// vec.extend([1, 2, 3]);
173 /// assert_eq!(vec, [7, 1, 2, 3]);
176 /// The [`vec!`] macro is provided for convenient initialization:
179 /// let mut vec1 = vec![1, 2, 3];
181 /// let vec2 = Vec::from([1, 2, 3, 4]);
182 /// assert_eq!(vec1, vec2);
185 /// It can also initialize each element of a `Vec<T>` with a given value.
186 /// This may be more efficient than performing allocation and initialization
187 /// in separate steps, especially when initializing a vector of zeros:
190 /// let vec = vec![0; 5];
191 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
193 /// // The following is equivalent, but potentially slower:
194 /// let mut vec = Vec::with_capacity(5);
195 /// vec.resize(5, 0);
196 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
199 /// For more information, see
200 /// [Capacity and Reallocation](#capacity-and-reallocation).
202 /// Use a `Vec<T>` as an efficient stack:
205 /// let mut stack = Vec::new();
211 /// while let Some(top) = stack.pop() {
212 /// // Prints 3, 2, 1
213 /// println!("{top}");
219 /// The `Vec` type allows access to values by index, because it implements the
220 /// [`Index`] trait. An example will be more explicit:
223 /// let v = vec![0, 2, 4, 6];
224 /// println!("{}", v[1]); // it will display '2'
227 /// However be careful: if you try to access an index which isn't in the `Vec`,
228 /// your software will panic! You cannot do this:
231 /// let v = vec![0, 2, 4, 6];
232 /// println!("{}", v[6]); // it will panic!
235 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
240 /// A `Vec` can be mutable. On the other hand, slices are read-only objects.
241 /// To get a [slice][prim@slice], use [`&`]. Example:
244 /// fn read_slice(slice: &[usize]) {
248 /// let v = vec![0, 1];
251 /// // ... and that's all!
252 /// // you can also do it like this:
253 /// let u: &[usize] = &v;
255 /// let u: &[_] = &v;
258 /// In Rust, it's more common to pass slices as arguments rather than vectors
259 /// when you just want to provide read access. The same goes for [`String`] and
262 /// # Capacity and reallocation
264 /// The capacity of a vector is the amount of space allocated for any future
265 /// elements that will be added onto the vector. This is not to be confused with
266 /// the *length* of a vector, which specifies the number of actual elements
267 /// within the vector. If a vector's length exceeds its capacity, its capacity
268 /// will automatically be increased, but its elements will have to be
271 /// For example, a vector with capacity 10 and length 0 would be an empty vector
272 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
273 /// vector will not change its capacity or cause reallocation to occur. However,
274 /// if the vector's length is increased to 11, it will have to reallocate, which
275 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
276 /// whenever possible to specify how big the vector is expected to get.
280 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
281 /// about its design. This ensures that it's as low-overhead as possible in
282 /// the general case, and can be correctly manipulated in primitive ways
283 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
284 /// If additional type parameters are added (e.g., to support custom allocators),
285 /// overriding their defaults may change the behavior.
287 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
288 /// triplet. No more, no less. The order of these fields is completely
289 /// unspecified, and you should use the appropriate methods to modify these.
290 /// The pointer will never be null, so this type is null-pointer-optimized.
292 /// However, the pointer might not actually point to allocated memory. In particular,
293 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
294 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
295 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
296 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
297 /// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only
298 /// if <code>[mem::size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation
299 /// details are very subtle --- if you intend to allocate memory using a `Vec`
300 /// and use it for something else (either to pass to unsafe code, or to build your
301 /// own memory-backed collection), be sure to deallocate this memory by using
302 /// `from_raw_parts` to recover the `Vec` and then dropping it.
304 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
305 /// (as defined by the allocator Rust is configured to use by default), and its
306 /// pointer points to [`len`] initialized, contiguous elements in order (what
307 /// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>
308 /// logically uninitialized, contiguous elements.
310 /// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
311 /// visualized as below. The top part is the `Vec` struct, it contains a
312 /// pointer to the head of the allocation in the heap, length and capacity.
313 /// The bottom part is the allocation on the heap, a contiguous memory block.
317 /// +--------+--------+--------+
318 /// | 0x0123 | 2 | 4 |
319 /// +--------+--------+--------+
322 /// Heap +--------+--------+--------+--------+
323 /// | 'a' | 'b' | uninit | uninit |
324 /// +--------+--------+--------+--------+
327 /// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
328 /// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
329 /// layout (including the order of fields).
331 /// `Vec` will never perform a "small optimization" where elements are actually
332 /// stored on the stack for two reasons:
334 /// * It would make it more difficult for unsafe code to correctly manipulate
335 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
336 /// only moved, and it would be more difficult to determine if a `Vec` had
337 /// actually allocated memory.
339 /// * It would penalize the general case, incurring an additional branch
342 /// `Vec` will never automatically shrink itself, even if completely empty. This
343 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
344 /// and then filling it back up to the same [`len`] should incur no calls to
345 /// the allocator. If you wish to free up unused memory, use
346 /// [`shrink_to_fit`] or [`shrink_to`].
348 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
349 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
350 /// <code>[len] == [capacity]</code>. That is, the reported capacity is completely
351 /// accurate, and can be relied on. It can even be used to manually free the memory
352 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
353 /// when not necessary.
355 /// `Vec` does not guarantee any particular growth strategy when reallocating
356 /// when full, nor when [`reserve`] is called. The current strategy is basic
357 /// and it may prove desirable to use a non-constant growth factor. Whatever
358 /// strategy is used will of course guarantee *O*(1) amortized [`push`].
360 /// `vec![x; n]`, `vec![a, b, c, d]`, and
361 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
362 /// with exactly the requested capacity. If <code>[len] == [capacity]</code>,
363 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
364 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
366 /// `Vec` will not specifically overwrite any data that is removed from it,
367 /// but also won't specifically preserve it. Its uninitialized memory is
368 /// scratch space that it may use however it wants. It will generally just do
369 /// whatever is most efficient or otherwise easy to implement. Do not rely on
370 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
371 /// buffer may simply be reused by another allocation. Even if you zero a `Vec`'s memory
372 /// first, that might not actually happen because the optimizer does not consider
373 /// this a side-effect that must be preserved. There is one case which we will
374 /// not break, however: using `unsafe` code to write to the excess capacity,
375 /// and then increasing the length to match, is always valid.
377 /// Currently, `Vec` does not guarantee the order in which elements are dropped.
378 /// The order has changed in the past and may change again.
380 /// [`get`]: slice::get
381 /// [`get_mut`]: slice::get_mut
382 /// [`String`]: crate::string::String
383 /// [`&str`]: type@str
384 /// [`shrink_to_fit`]: Vec::shrink_to_fit
385 /// [`shrink_to`]: Vec::shrink_to
386 /// [capacity]: Vec::capacity
387 /// [`capacity`]: Vec::capacity
388 /// [mem::size_of::\<T>]: core::mem::size_of
390 /// [`len`]: Vec::len
391 /// [`push`]: Vec::push
392 /// [`insert`]: Vec::insert
393 /// [`reserve`]: Vec::reserve
394 /// [`MaybeUninit`]: core::mem::MaybeUninit
395 /// [owned slice]: Box
396 #[stable(feature = "rust1", since = "1.0.0")]
397 #[cfg_attr(not(test), rustc_diagnostic_item = "Vec")]
398 #[rustc_insignificant_dtor]
399 pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
404 ////////////////////////////////////////////////////////////////////////////////
406 ////////////////////////////////////////////////////////////////////////////////
409 /// Constructs a new, empty `Vec<T>`.
411 /// The vector will not allocate until elements are pushed onto it.
416 /// # #![allow(unused_mut)]
417 /// let mut vec: Vec<i32> = Vec::new();
420 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
421 #[stable(feature = "rust1", since = "1.0.0")]
423 pub const fn new() -> Self {
424 Vec { buf: RawVec::NEW, len: 0 }
427 /// Constructs a new, empty `Vec<T>` with at least the specified capacity.
429 /// The vector will be able to hold at least `capacity` elements without
430 /// reallocating. This method is allowed to allocate for more elements than
431 /// `capacity`. If `capacity` is 0, the vector will not allocate.
433 /// It is important to note that although the returned vector has the
434 /// minimum *capacity* specified, the vector will have a zero *length*. For
435 /// an explanation of the difference between length and capacity, see
436 /// *[Capacity and reallocation]*.
438 /// If it is important to know the exact allocated capacity of a `Vec`,
439 /// always use the [`capacity`] method after construction.
441 /// For `Vec<T>` where `T` is a zero-sized type, there will be no allocation
442 /// and the capacity will always be `usize::MAX`.
444 /// [Capacity and reallocation]: #capacity-and-reallocation
445 /// [`capacity`]: Vec::capacity
449 /// Panics if the new capacity exceeds `isize::MAX` bytes.
454 /// let mut vec = Vec::with_capacity(10);
456 /// // The vector contains no items, even though it has capacity for more
457 /// assert_eq!(vec.len(), 0);
458 /// assert!(vec.capacity() >= 10);
460 /// // These are all done without reallocating...
464 /// assert_eq!(vec.len(), 10);
465 /// assert!(vec.capacity() >= 10);
467 /// // ...but this may make the vector reallocate
469 /// assert_eq!(vec.len(), 11);
470 /// assert!(vec.capacity() >= 11);
472 /// // A vector of a zero-sized type will always over-allocate, since no
473 /// // allocation is necessary
474 /// let vec_units = Vec::<()>::with_capacity(10);
475 /// assert_eq!(vec_units.capacity(), usize::MAX);
477 #[cfg(not(no_global_oom_handling))]
479 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn with_capacity(capacity: usize) -> Self {
482 Self::with_capacity_in(capacity, Global)
485 /// Tries to construct a new, empty `Vec<T>` with at least the specified capacity.
487 /// The vector will be able to hold at least `capacity` elements without
488 /// reallocating. This method is allowed to allocate for more elements than
489 /// `capacity`. If `capacity` is 0, the vector will not allocate.
491 /// It is important to note that although the returned vector has the
492 /// minimum *capacity* specified, the vector will have a zero *length*. For
493 /// an explanation of the difference between length and capacity, see
494 /// *[Capacity and reallocation]*.
496 /// If it is important to know the exact allocated capacity of a `Vec`,
497 /// always use the [`capacity`] method after construction.
499 /// For `Vec<T>` where `T` is a zero-sized type, there will be no allocation
500 /// and the capacity will always be `usize::MAX`.
502 /// [Capacity and reallocation]: #capacity-and-reallocation
503 /// [`capacity`]: Vec::capacity
508 /// let mut vec = Vec::try_with_capacity(10).unwrap();
510 /// // The vector contains no items, even though it has capacity for more
511 /// assert_eq!(vec.len(), 0);
512 /// assert!(vec.capacity() >= 10);
514 /// // These are all done without reallocating...
518 /// assert_eq!(vec.len(), 10);
519 /// assert!(vec.capacity() >= 10);
521 /// // ...but this may make the vector reallocate
523 /// assert_eq!(vec.len(), 11);
524 /// assert!(vec.capacity() >= 11);
526 /// let mut result = Vec::try_with_capacity(usize::MAX);
527 /// assert!(result.is_err());
529 /// // A vector of a zero-sized type will always over-allocate, since no
530 /// // allocation is necessary
531 /// let vec_units = Vec::<()>::try_with_capacity(10).unwrap();
532 /// assert_eq!(vec_units.capacity(), usize::MAX);
535 #[stable(feature = "kernel", since = "1.0.0")]
536 pub fn try_with_capacity(capacity: usize) -> Result<Self, TryReserveError> {
537 Self::try_with_capacity_in(capacity, Global)
540 /// Creates a `Vec<T>` directly from a pointer, a capacity, and a length.
544 /// This is highly unsafe, due to the number of invariants that aren't
547 /// * `ptr` must have been allocated using the global allocator, such as via
548 /// the [`alloc::alloc`] function.
549 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
550 /// (`T` having a less strict alignment is not sufficient, the alignment really
551 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
552 /// allocated and deallocated with the same layout.)
553 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
554 /// to be the same size as the pointer was allocated with. (Because similar to
555 /// alignment, [`dealloc`] must be called with the same layout `size`.)
556 /// * `length` needs to be less than or equal to `capacity`.
557 /// * The first `length` values must be properly initialized values of type `T`.
558 /// * `capacity` needs to be the capacity that the pointer was allocated with.
559 /// * The allocated size in bytes must be no larger than `isize::MAX`.
560 /// See the safety documentation of [`pointer::offset`].
562 /// These requirements are always upheld by any `ptr` that has been allocated
563 /// via `Vec<T>`. Other allocation sources are allowed if the invariants are
566 /// Violating these may cause problems like corrupting the allocator's
567 /// internal data structures. For example it is normally **not** safe
568 /// to build a `Vec<u8>` from a pointer to a C `char` array with length
569 /// `size_t`, doing so is only safe if the array was initially allocated by
570 /// a `Vec` or `String`.
571 /// It's also not safe to build one from a `Vec<u16>` and its length, because
572 /// the allocator cares about the alignment, and these two types have different
573 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
574 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1. To avoid
575 /// these issues, it is often preferable to do casting/transmuting using
576 /// [`slice::from_raw_parts`] instead.
578 /// The ownership of `ptr` is effectively transferred to the
579 /// `Vec<T>` which may then deallocate, reallocate or change the
580 /// contents of memory pointed to by the pointer at will. Ensure
581 /// that nothing else uses the pointer after calling this
584 /// [`String`]: crate::string::String
585 /// [`alloc::alloc`]: crate::alloc::alloc
586 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
594 /// let v = vec![1, 2, 3];
596 // FIXME Update this when vec_into_raw_parts is stabilized
597 /// // Prevent running `v`'s destructor so we are in complete control
598 /// // of the allocation.
599 /// let mut v = mem::ManuallyDrop::new(v);
601 /// // Pull out the various important pieces of information about `v`
602 /// let p = v.as_mut_ptr();
603 /// let len = v.len();
604 /// let cap = v.capacity();
607 /// // Overwrite memory with 4, 5, 6
608 /// for i in 0..len {
609 /// ptr::write(p.add(i), 4 + i);
612 /// // Put everything back together into a Vec
613 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
614 /// assert_eq!(rebuilt, [4, 5, 6]);
618 /// Using memory that was allocated elsewhere:
621 /// use std::alloc::{alloc, Layout};
624 /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
626 /// let vec = unsafe {
627 /// let mem = alloc(layout).cast::<u32>();
628 /// if mem.is_null() {
632 /// mem.write(1_000_000);
634 /// Vec::from_raw_parts(mem, 1, 16)
637 /// assert_eq!(vec, &[1_000_000]);
638 /// assert_eq!(vec.capacity(), 16);
642 #[stable(feature = "rust1", since = "1.0.0")]
643 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
644 unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
648 impl<T, A: Allocator> Vec<T, A> {
649 /// Constructs a new, empty `Vec<T, A>`.
651 /// The vector will not allocate until elements are pushed onto it.
656 /// #![feature(allocator_api)]
658 /// use std::alloc::System;
660 /// # #[allow(unused_mut)]
661 /// let mut vec: Vec<i32, _> = Vec::new_in(System);
664 #[unstable(feature = "allocator_api", issue = "32838")]
665 pub const fn new_in(alloc: A) -> Self {
666 Vec { buf: RawVec::new_in(alloc), len: 0 }
669 /// Constructs a new, empty `Vec<T, A>` with at least the specified capacity
670 /// with the provided allocator.
672 /// The vector will be able to hold at least `capacity` elements without
673 /// reallocating. This method is allowed to allocate for more elements than
674 /// `capacity`. If `capacity` is 0, the vector will not allocate.
676 /// It is important to note that although the returned vector has the
677 /// minimum *capacity* specified, the vector will have a zero *length*. For
678 /// an explanation of the difference between length and capacity, see
679 /// *[Capacity and reallocation]*.
681 /// If it is important to know the exact allocated capacity of a `Vec`,
682 /// always use the [`capacity`] method after construction.
684 /// For `Vec<T, A>` where `T` is a zero-sized type, there will be no allocation
685 /// and the capacity will always be `usize::MAX`.
687 /// [Capacity and reallocation]: #capacity-and-reallocation
688 /// [`capacity`]: Vec::capacity
692 /// Panics if the new capacity exceeds `isize::MAX` bytes.
697 /// #![feature(allocator_api)]
699 /// use std::alloc::System;
701 /// let mut vec = Vec::with_capacity_in(10, System);
703 /// // The vector contains no items, even though it has capacity for more
704 /// assert_eq!(vec.len(), 0);
705 /// assert!(vec.capacity() >= 10);
707 /// // These are all done without reallocating...
711 /// assert_eq!(vec.len(), 10);
712 /// assert!(vec.capacity() >= 10);
714 /// // ...but this may make the vector reallocate
716 /// assert_eq!(vec.len(), 11);
717 /// assert!(vec.capacity() >= 11);
719 /// // A vector of a zero-sized type will always over-allocate, since no
720 /// // allocation is necessary
721 /// let vec_units = Vec::<(), System>::with_capacity_in(10, System);
722 /// assert_eq!(vec_units.capacity(), usize::MAX);
724 #[cfg(not(no_global_oom_handling))]
726 #[unstable(feature = "allocator_api", issue = "32838")]
727 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
728 Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
731 /// Tries to construct a new, empty `Vec<T, A>` with at least the specified capacity
732 /// with the provided allocator.
734 /// The vector will be able to hold at least `capacity` elements without
735 /// reallocating. This method is allowed to allocate for more elements than
736 /// `capacity`. If `capacity` is 0, the vector will not allocate.
738 /// It is important to note that although the returned vector has the
739 /// minimum *capacity* specified, the vector will have a zero *length*. For
740 /// an explanation of the difference between length and capacity, see
741 /// *[Capacity and reallocation]*.
743 /// If it is important to know the exact allocated capacity of a `Vec`,
744 /// always use the [`capacity`] method after construction.
746 /// For `Vec<T, A>` where `T` is a zero-sized type, there will be no allocation
747 /// and the capacity will always be `usize::MAX`.
749 /// [Capacity and reallocation]: #capacity-and-reallocation
750 /// [`capacity`]: Vec::capacity
755 /// #![feature(allocator_api)]
757 /// use std::alloc::System;
759 /// let mut vec = Vec::try_with_capacity_in(10, System).unwrap();
761 /// // The vector contains no items, even though it has capacity for more
762 /// assert_eq!(vec.len(), 0);
763 /// assert!(vec.capacity() >= 10);
765 /// // These are all done without reallocating...
769 /// assert_eq!(vec.len(), 10);
770 /// assert!(vec.capacity() >= 10);
772 /// // ...but this may make the vector reallocate
774 /// assert_eq!(vec.len(), 11);
775 /// assert!(vec.capacity() >= 11);
777 /// let mut result = Vec::try_with_capacity_in(usize::MAX, System);
778 /// assert!(result.is_err());
780 /// // A vector of a zero-sized type will always over-allocate, since no
781 /// // allocation is necessary
782 /// let vec_units = Vec::<(), System>::try_with_capacity_in(10, System).unwrap();
783 /// assert_eq!(vec_units.capacity(), usize::MAX);
786 #[stable(feature = "kernel", since = "1.0.0")]
787 pub fn try_with_capacity_in(capacity: usize, alloc: A) -> Result<Self, TryReserveError> {
788 Ok(Vec { buf: RawVec::try_with_capacity_in(capacity, alloc)?, len: 0 })
791 /// Creates a `Vec<T, A>` directly from a pointer, a capacity, a length,
792 /// and an allocator.
796 /// This is highly unsafe, due to the number of invariants that aren't
799 /// * `ptr` must be [*currently allocated*] via the given allocator `alloc`.
800 /// * `T` needs to have the same alignment as what `ptr` was allocated with.
801 /// (`T` having a less strict alignment is not sufficient, the alignment really
802 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
803 /// allocated and deallocated with the same layout.)
804 /// * The size of `T` times the `capacity` (ie. the allocated size in bytes) needs
805 /// to be the same size as the pointer was allocated with. (Because similar to
806 /// alignment, [`dealloc`] must be called with the same layout `size`.)
807 /// * `length` needs to be less than or equal to `capacity`.
808 /// * The first `length` values must be properly initialized values of type `T`.
809 /// * `capacity` needs to [*fit*] the layout size that the pointer was allocated with.
810 /// * The allocated size in bytes must be no larger than `isize::MAX`.
811 /// See the safety documentation of [`pointer::offset`].
813 /// These requirements are always upheld by any `ptr` that has been allocated
814 /// via `Vec<T, A>`. Other allocation sources are allowed if the invariants are
817 /// Violating these may cause problems like corrupting the allocator's
818 /// internal data structures. For example it is **not** safe
819 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
820 /// It's also not safe to build one from a `Vec<u16>` and its length, because
821 /// the allocator cares about the alignment, and these two types have different
822 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
823 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
825 /// The ownership of `ptr` is effectively transferred to the
826 /// `Vec<T>` which may then deallocate, reallocate or change the
827 /// contents of memory pointed to by the pointer at will. Ensure
828 /// that nothing else uses the pointer after calling this
831 /// [`String`]: crate::string::String
832 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
833 /// [*currently allocated*]: crate::alloc::Allocator#currently-allocated-memory
834 /// [*fit*]: crate::alloc::Allocator#memory-fitting
839 /// #![feature(allocator_api)]
841 /// use std::alloc::System;
846 /// let mut v = Vec::with_capacity_in(3, System);
851 // FIXME Update this when vec_into_raw_parts is stabilized
852 /// // Prevent running `v`'s destructor so we are in complete control
853 /// // of the allocation.
854 /// let mut v = mem::ManuallyDrop::new(v);
856 /// // Pull out the various important pieces of information about `v`
857 /// let p = v.as_mut_ptr();
858 /// let len = v.len();
859 /// let cap = v.capacity();
860 /// let alloc = v.allocator();
863 /// // Overwrite memory with 4, 5, 6
864 /// for i in 0..len {
865 /// ptr::write(p.add(i), 4 + i);
868 /// // Put everything back together into a Vec
869 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
870 /// assert_eq!(rebuilt, [4, 5, 6]);
874 /// Using memory that was allocated elsewhere:
877 /// #![feature(allocator_api)]
879 /// use std::alloc::{AllocError, Allocator, Global, Layout};
882 /// let layout = Layout::array::<u32>(16).expect("overflow cannot happen");
884 /// let vec = unsafe {
885 /// let mem = match Global.allocate(layout) {
886 /// Ok(mem) => mem.cast::<u32>().as_ptr(),
887 /// Err(AllocError) => return,
890 /// mem.write(1_000_000);
892 /// Vec::from_raw_parts_in(mem, 1, 16, Global)
895 /// assert_eq!(vec, &[1_000_000]);
896 /// assert_eq!(vec.capacity(), 16);
900 #[unstable(feature = "allocator_api", issue = "32838")]
901 pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
902 unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
905 /// Decomposes a `Vec<T>` into its raw components.
907 /// Returns the raw pointer to the underlying data, the length of
908 /// the vector (in elements), and the allocated capacity of the
909 /// data (in elements). These are the same arguments in the same
910 /// order as the arguments to [`from_raw_parts`].
912 /// After calling this function, the caller is responsible for the
913 /// memory previously managed by the `Vec`. The only way to do
914 /// this is to convert the raw pointer, length, and capacity back
915 /// into a `Vec` with the [`from_raw_parts`] function, allowing
916 /// the destructor to perform the cleanup.
918 /// [`from_raw_parts`]: Vec::from_raw_parts
923 /// #![feature(vec_into_raw_parts)]
924 /// let v: Vec<i32> = vec![-1, 0, 1];
926 /// let (ptr, len, cap) = v.into_raw_parts();
928 /// let rebuilt = unsafe {
929 /// // We can now make changes to the components, such as
930 /// // transmuting the raw pointer to a compatible type.
931 /// let ptr = ptr as *mut u32;
933 /// Vec::from_raw_parts(ptr, len, cap)
935 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
937 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
938 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
939 let mut me = ManuallyDrop::new(self);
940 (me.as_mut_ptr(), me.len(), me.capacity())
943 /// Decomposes a `Vec<T>` into its raw components.
945 /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
946 /// the allocated capacity of the data (in elements), and the allocator. These are the same
947 /// arguments in the same order as the arguments to [`from_raw_parts_in`].
949 /// After calling this function, the caller is responsible for the
950 /// memory previously managed by the `Vec`. The only way to do
951 /// this is to convert the raw pointer, length, and capacity back
952 /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
953 /// the destructor to perform the cleanup.
955 /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
960 /// #![feature(allocator_api, vec_into_raw_parts)]
962 /// use std::alloc::System;
964 /// let mut v: Vec<i32, System> = Vec::new_in(System);
969 /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
971 /// let rebuilt = unsafe {
972 /// // We can now make changes to the components, such as
973 /// // transmuting the raw pointer to a compatible type.
974 /// let ptr = ptr as *mut u32;
976 /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
978 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
980 #[unstable(feature = "allocator_api", issue = "32838")]
981 // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
982 pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
983 let mut me = ManuallyDrop::new(self);
985 let capacity = me.capacity();
986 let ptr = me.as_mut_ptr();
987 let alloc = unsafe { ptr::read(me.allocator()) };
988 (ptr, len, capacity, alloc)
991 /// Returns the total number of elements the vector can hold without
997 /// let mut vec: Vec<i32> = Vec::with_capacity(10);
999 /// assert!(vec.capacity() >= 10);
1002 #[stable(feature = "rust1", since = "1.0.0")]
1003 pub fn capacity(&self) -> usize {
1007 /// Reserves capacity for at least `additional` more elements to be inserted
1008 /// in the given `Vec<T>`. The collection may reserve more space to
1009 /// speculatively avoid frequent reallocations. After calling `reserve`,
1010 /// capacity will be greater than or equal to `self.len() + additional`.
1011 /// Does nothing if capacity is already sufficient.
1015 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1020 /// let mut vec = vec![1];
1021 /// vec.reserve(10);
1022 /// assert!(vec.capacity() >= 11);
1024 #[cfg(not(no_global_oom_handling))]
1025 #[stable(feature = "rust1", since = "1.0.0")]
1026 pub fn reserve(&mut self, additional: usize) {
1027 self.buf.reserve(self.len, additional);
1030 /// Reserves the minimum capacity for at least `additional` more elements to
1031 /// be inserted in the given `Vec<T>`. Unlike [`reserve`], this will not
1032 /// deliberately over-allocate to speculatively avoid frequent allocations.
1033 /// After calling `reserve_exact`, capacity will be greater than or equal to
1034 /// `self.len() + additional`. Does nothing if the capacity is already
1037 /// Note that the allocator may give the collection more space than it
1038 /// requests. Therefore, capacity can not be relied upon to be precisely
1039 /// minimal. Prefer [`reserve`] if future insertions are expected.
1041 /// [`reserve`]: Vec::reserve
1045 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1050 /// let mut vec = vec![1];
1051 /// vec.reserve_exact(10);
1052 /// assert!(vec.capacity() >= 11);
1054 #[cfg(not(no_global_oom_handling))]
1055 #[stable(feature = "rust1", since = "1.0.0")]
1056 pub fn reserve_exact(&mut self, additional: usize) {
1057 self.buf.reserve_exact(self.len, additional);
1060 /// Tries to reserve capacity for at least `additional` more elements to be inserted
1061 /// in the given `Vec<T>`. The collection may reserve more space to speculatively avoid
1062 /// frequent reallocations. After calling `try_reserve`, capacity will be
1063 /// greater than or equal to `self.len() + additional` if it returns
1064 /// `Ok(())`. Does nothing if capacity is already sufficient. This method
1065 /// preserves the contents even if an error occurs.
1069 /// If the capacity overflows, or the allocator reports a failure, then an error
1075 /// use std::collections::TryReserveError;
1077 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
1078 /// let mut output = Vec::new();
1080 /// // Pre-reserve the memory, exiting if we can't
1081 /// output.try_reserve(data.len())?;
1083 /// // Now we know this can't OOM in the middle of our complex work
1084 /// output.extend(data.iter().map(|&val| {
1085 /// val * 2 + 5 // very complicated
1090 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
1092 #[stable(feature = "try_reserve", since = "1.57.0")]
1093 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
1094 self.buf.try_reserve(self.len, additional)
1097 /// Tries to reserve the minimum capacity for at least `additional`
1098 /// elements to be inserted in the given `Vec<T>`. Unlike [`try_reserve`],
1099 /// this will not deliberately over-allocate to speculatively avoid frequent
1100 /// allocations. After calling `try_reserve_exact`, capacity will be greater
1101 /// than or equal to `self.len() + additional` if it returns `Ok(())`.
1102 /// Does nothing if the capacity is already sufficient.
1104 /// Note that the allocator may give the collection more space than it
1105 /// requests. Therefore, capacity can not be relied upon to be precisely
1106 /// minimal. Prefer [`try_reserve`] if future insertions are expected.
1108 /// [`try_reserve`]: Vec::try_reserve
1112 /// If the capacity overflows, or the allocator reports a failure, then an error
1118 /// use std::collections::TryReserveError;
1120 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
1121 /// let mut output = Vec::new();
1123 /// // Pre-reserve the memory, exiting if we can't
1124 /// output.try_reserve_exact(data.len())?;
1126 /// // Now we know this can't OOM in the middle of our complex work
1127 /// output.extend(data.iter().map(|&val| {
1128 /// val * 2 + 5 // very complicated
1133 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
1135 #[stable(feature = "try_reserve", since = "1.57.0")]
1136 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
1137 self.buf.try_reserve_exact(self.len, additional)
1140 /// Shrinks the capacity of the vector as much as possible.
1142 /// It will drop down as close as possible to the length but the allocator
1143 /// may still inform the vector that there is space for a few more elements.
1148 /// let mut vec = Vec::with_capacity(10);
1149 /// vec.extend([1, 2, 3]);
1150 /// assert!(vec.capacity() >= 10);
1151 /// vec.shrink_to_fit();
1152 /// assert!(vec.capacity() >= 3);
1154 #[cfg(not(no_global_oom_handling))]
1155 #[stable(feature = "rust1", since = "1.0.0")]
1156 pub fn shrink_to_fit(&mut self) {
1157 // The capacity is never less than the length, and there's nothing to do when
1158 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
1159 // by only calling it with a greater capacity.
1160 if self.capacity() > self.len {
1161 self.buf.shrink_to_fit(self.len);
1165 /// Shrinks the capacity of the vector with a lower bound.
1167 /// The capacity will remain at least as large as both the length
1168 /// and the supplied value.
1170 /// If the current capacity is less than the lower limit, this is a no-op.
1175 /// let mut vec = Vec::with_capacity(10);
1176 /// vec.extend([1, 2, 3]);
1177 /// assert!(vec.capacity() >= 10);
1178 /// vec.shrink_to(4);
1179 /// assert!(vec.capacity() >= 4);
1180 /// vec.shrink_to(0);
1181 /// assert!(vec.capacity() >= 3);
1183 #[cfg(not(no_global_oom_handling))]
1184 #[stable(feature = "shrink_to", since = "1.56.0")]
1185 pub fn shrink_to(&mut self, min_capacity: usize) {
1186 if self.capacity() > min_capacity {
1187 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
1191 /// Converts the vector into [`Box<[T]>`][owned slice].
1193 /// If the vector has excess capacity, its items will be moved into a
1194 /// newly-allocated buffer with exactly the right capacity.
1196 /// [owned slice]: Box
1201 /// let v = vec![1, 2, 3];
1203 /// let slice = v.into_boxed_slice();
1206 /// Any excess capacity is removed:
1209 /// let mut vec = Vec::with_capacity(10);
1210 /// vec.extend([1, 2, 3]);
1212 /// assert!(vec.capacity() >= 10);
1213 /// let slice = vec.into_boxed_slice();
1214 /// assert_eq!(slice.into_vec().capacity(), 3);
1216 #[cfg(not(no_global_oom_handling))]
1217 #[stable(feature = "rust1", since = "1.0.0")]
1218 pub fn into_boxed_slice(mut self) -> Box<[T], A> {
1220 self.shrink_to_fit();
1221 let me = ManuallyDrop::new(self);
1222 let buf = ptr::read(&me.buf);
1224 buf.into_box(len).assume_init()
1228 /// Shortens the vector, keeping the first `len` elements and dropping
1231 /// If `len` is greater than the vector's current length, this has no
1234 /// The [`drain`] method can emulate `truncate`, but causes the excess
1235 /// elements to be returned instead of dropped.
1237 /// Note that this method has no effect on the allocated capacity
1242 /// Truncating a five element vector to two elements:
1245 /// let mut vec = vec![1, 2, 3, 4, 5];
1246 /// vec.truncate(2);
1247 /// assert_eq!(vec, [1, 2]);
1250 /// No truncation occurs when `len` is greater than the vector's current
1254 /// let mut vec = vec![1, 2, 3];
1255 /// vec.truncate(8);
1256 /// assert_eq!(vec, [1, 2, 3]);
1259 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
1263 /// let mut vec = vec![1, 2, 3];
1264 /// vec.truncate(0);
1265 /// assert_eq!(vec, []);
1268 /// [`clear`]: Vec::clear
1269 /// [`drain`]: Vec::drain
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 pub fn truncate(&mut self, len: usize) {
1272 // This is safe because:
1274 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
1275 // case avoids creating an invalid slice, and
1276 // * the `len` of the vector is shrunk before calling `drop_in_place`,
1277 // such that no value will be dropped twice in case `drop_in_place`
1278 // were to panic once (if it panics twice, the program aborts).
1280 // Note: It's intentional that this is `>` and not `>=`.
1281 // Changing it to `>=` has negative performance
1282 // implications in some cases. See #78884 for more.
1286 let remaining_len = self.len - len;
1287 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
1289 ptr::drop_in_place(s);
1293 /// Extracts a slice containing the entire vector.
1295 /// Equivalent to `&s[..]`.
1300 /// use std::io::{self, Write};
1301 /// let buffer = vec![1, 2, 3, 5, 8];
1302 /// io::sink().write(buffer.as_slice()).unwrap();
1305 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1306 pub fn as_slice(&self) -> &[T] {
1310 /// Extracts a mutable slice of the entire vector.
1312 /// Equivalent to `&mut s[..]`.
1317 /// use std::io::{self, Read};
1318 /// let mut buffer = vec![0; 3];
1319 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1322 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1323 pub fn as_mut_slice(&mut self) -> &mut [T] {
1327 /// Returns a raw pointer to the vector's buffer, or a dangling raw pointer
1328 /// valid for zero sized reads if the vector didn't allocate.
1330 /// The caller must ensure that the vector outlives the pointer this
1331 /// function returns, or else it will end up pointing to garbage.
1332 /// Modifying the vector may cause its buffer to be reallocated,
1333 /// which would also make any pointers to it invalid.
1335 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1336 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1337 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1342 /// let x = vec![1, 2, 4];
1343 /// let x_ptr = x.as_ptr();
1346 /// for i in 0..x.len() {
1347 /// assert_eq!(*x_ptr.add(i), 1 << i);
1352 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1353 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1355 pub fn as_ptr(&self) -> *const T {
1356 // We shadow the slice method of the same name to avoid going through
1357 // `deref`, which creates an intermediate reference.
1361 /// Returns an unsafe mutable pointer to the vector's buffer, or a dangling
1362 /// raw pointer valid for zero sized reads if the vector didn't allocate.
1364 /// The caller must ensure that the vector outlives the pointer this
1365 /// function returns, or else it will end up pointing to garbage.
1366 /// Modifying the vector may cause its buffer to be reallocated,
1367 /// which would also make any pointers to it invalid.
1372 /// // Allocate vector big enough for 4 elements.
1374 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1375 /// let x_ptr = x.as_mut_ptr();
1377 /// // Initialize elements via raw pointer writes, then set length.
1379 /// for i in 0..size {
1380 /// *x_ptr.add(i) = i as i32;
1382 /// x.set_len(size);
1384 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1386 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1388 pub fn as_mut_ptr(&mut self) -> *mut T {
1389 // We shadow the slice method of the same name to avoid going through
1390 // `deref_mut`, which creates an intermediate reference.
1394 /// Returns a reference to the underlying allocator.
1395 #[unstable(feature = "allocator_api", issue = "32838")]
1397 pub fn allocator(&self) -> &A {
1398 self.buf.allocator()
1401 /// Forces the length of the vector to `new_len`.
1403 /// This is a low-level operation that maintains none of the normal
1404 /// invariants of the type. Normally changing the length of a vector
1405 /// is done using one of the safe operations instead, such as
1406 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
1408 /// [`truncate`]: Vec::truncate
1409 /// [`resize`]: Vec::resize
1410 /// [`extend`]: Extend::extend
1411 /// [`clear`]: Vec::clear
1415 /// - `new_len` must be less than or equal to [`capacity()`].
1416 /// - The elements at `old_len..new_len` must be initialized.
1418 /// [`capacity()`]: Vec::capacity
1422 /// This method can be useful for situations in which the vector
1423 /// is serving as a buffer for other code, particularly over FFI:
1426 /// # #![allow(dead_code)]
1427 /// # // This is just a minimal skeleton for the doc example;
1428 /// # // don't use this as a starting point for a real library.
1429 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
1430 /// # const Z_OK: i32 = 0;
1432 /// # fn deflateGetDictionary(
1433 /// # strm: *mut std::ffi::c_void,
1434 /// # dictionary: *mut u8,
1435 /// # dictLength: *mut usize,
1438 /// # impl StreamWrapper {
1439 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
1440 /// // Per the FFI method's docs, "32768 bytes is always enough".
1441 /// let mut dict = Vec::with_capacity(32_768);
1442 /// let mut dict_length = 0;
1443 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
1444 /// // 1. `dict_length` elements were initialized.
1445 /// // 2. `dict_length` <= the capacity (32_768)
1446 /// // which makes `set_len` safe to call.
1448 /// // Make the FFI call...
1449 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
1451 /// // ...and update the length to what was initialized.
1452 /// dict.set_len(dict_length);
1462 /// While the following example is sound, there is a memory leak since
1463 /// the inner vectors were not freed prior to the `set_len` call:
1466 /// let mut vec = vec![vec![1, 0, 0],
1470 /// // 1. `old_len..0` is empty so no elements need to be initialized.
1471 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
1477 /// Normally, here, one would use [`clear`] instead to correctly drop
1478 /// the contents and thus not leak memory.
1480 #[stable(feature = "rust1", since = "1.0.0")]
1481 pub unsafe fn set_len(&mut self, new_len: usize) {
1482 debug_assert!(new_len <= self.capacity());
1487 /// Removes an element from the vector and returns it.
1489 /// The removed element is replaced by the last element of the vector.
1491 /// This does not preserve ordering, but is *O*(1).
1492 /// If you need to preserve the element order, use [`remove`] instead.
1494 /// [`remove`]: Vec::remove
1498 /// Panics if `index` is out of bounds.
1503 /// let mut v = vec!["foo", "bar", "baz", "qux"];
1505 /// assert_eq!(v.swap_remove(1), "bar");
1506 /// assert_eq!(v, ["foo", "qux", "baz"]);
1508 /// assert_eq!(v.swap_remove(0), "foo");
1509 /// assert_eq!(v, ["baz", "qux"]);
1512 #[stable(feature = "rust1", since = "1.0.0")]
1513 pub fn swap_remove(&mut self, index: usize) -> T {
1516 fn assert_failed(index: usize, len: usize) -> ! {
1517 panic!("swap_remove index (is {index}) should be < len (is {len})");
1520 let len = self.len();
1522 assert_failed(index, len);
1525 // We replace self[index] with the last element. Note that if the
1526 // bounds check above succeeds there must be a last element (which
1527 // can be self[index] itself).
1528 let value = ptr::read(self.as_ptr().add(index));
1529 let base_ptr = self.as_mut_ptr();
1530 ptr::copy(base_ptr.add(len - 1), base_ptr.add(index), 1);
1531 self.set_len(len - 1);
1536 /// Inserts an element at position `index` within the vector, shifting all
1537 /// elements after it to the right.
1541 /// Panics if `index > len`.
1546 /// let mut vec = vec![1, 2, 3];
1547 /// vec.insert(1, 4);
1548 /// assert_eq!(vec, [1, 4, 2, 3]);
1549 /// vec.insert(4, 5);
1550 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1552 #[cfg(not(no_global_oom_handling))]
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 pub fn insert(&mut self, index: usize, element: T) {
1557 fn assert_failed(index: usize, len: usize) -> ! {
1558 panic!("insertion index (is {index}) should be <= len (is {len})");
1561 let len = self.len();
1563 // space for the new element
1564 if len == self.buf.capacity() {
1570 // The spot to put the new value
1572 let p = self.as_mut_ptr().add(index);
1574 // Shift everything over to make space. (Duplicating the
1575 // `index`th element into two consecutive places.)
1576 ptr::copy(p, p.add(1), len - index);
1577 } else if index == len {
1578 // No elements need shifting.
1580 assert_failed(index, len);
1582 // Write it in, overwriting the first copy of the `index`th
1584 ptr::write(p, element);
1586 self.set_len(len + 1);
1590 /// Removes and returns the element at position `index` within the vector,
1591 /// shifting all elements after it to the left.
1593 /// Note: Because this shifts over the remaining elements, it has a
1594 /// worst-case performance of *O*(*n*). If you don't need the order of elements
1595 /// to be preserved, use [`swap_remove`] instead. If you'd like to remove
1596 /// elements from the beginning of the `Vec`, consider using
1597 /// [`VecDeque::pop_front`] instead.
1599 /// [`swap_remove`]: Vec::swap_remove
1600 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
1604 /// Panics if `index` is out of bounds.
1609 /// let mut v = vec![1, 2, 3];
1610 /// assert_eq!(v.remove(1), 2);
1611 /// assert_eq!(v, [1, 3]);
1613 #[stable(feature = "rust1", since = "1.0.0")]
1615 pub fn remove(&mut self, index: usize) -> T {
1619 fn assert_failed(index: usize, len: usize) -> ! {
1620 panic!("removal index (is {index}) should be < len (is {len})");
1623 let len = self.len();
1625 assert_failed(index, len);
1631 // the place we are taking from.
1632 let ptr = self.as_mut_ptr().add(index);
1633 // copy it out, unsafely having a copy of the value on
1634 // the stack and in the vector at the same time.
1635 ret = ptr::read(ptr);
1637 // Shift everything down to fill in that spot.
1638 ptr::copy(ptr.add(1), ptr, len - index - 1);
1640 self.set_len(len - 1);
1645 /// Retains only the elements specified by the predicate.
1647 /// In other words, remove all elements `e` for which `f(&e)` returns `false`.
1648 /// This method operates in place, visiting each element exactly once in the
1649 /// original order, and preserves the order of the retained elements.
1654 /// let mut vec = vec![1, 2, 3, 4];
1655 /// vec.retain(|&x| x % 2 == 0);
1656 /// assert_eq!(vec, [2, 4]);
1659 /// Because the elements are visited exactly once in the original order,
1660 /// external state may be used to decide which elements to keep.
1663 /// let mut vec = vec![1, 2, 3, 4, 5];
1664 /// let keep = [false, true, true, false, true];
1665 /// let mut iter = keep.iter();
1666 /// vec.retain(|_| *iter.next().unwrap());
1667 /// assert_eq!(vec, [2, 3, 5]);
1669 #[stable(feature = "rust1", since = "1.0.0")]
1670 pub fn retain<F>(&mut self, mut f: F)
1672 F: FnMut(&T) -> bool,
1674 self.retain_mut(|elem| f(elem));
1677 /// Retains only the elements specified by the predicate, passing a mutable reference to it.
1679 /// In other words, remove all elements `e` such that `f(&mut e)` returns `false`.
1680 /// This method operates in place, visiting each element exactly once in the
1681 /// original order, and preserves the order of the retained elements.
1686 /// let mut vec = vec![1, 2, 3, 4];
1687 /// vec.retain_mut(|x| if *x <= 3 {
1693 /// assert_eq!(vec, [2, 3, 4]);
1695 #[stable(feature = "vec_retain_mut", since = "1.61.0")]
1696 pub fn retain_mut<F>(&mut self, mut f: F)
1698 F: FnMut(&mut T) -> bool,
1700 let original_len = self.len();
1701 // Avoid double drop if the drop guard is not executed,
1702 // since we may make some holes during the process.
1703 unsafe { self.set_len(0) };
1705 // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
1706 // |<- processed len ->| ^- next to check
1707 // |<- deleted cnt ->|
1708 // |<- original_len ->|
1709 // Kept: Elements which predicate returns true on.
1710 // Hole: Moved or dropped element slot.
1711 // Unchecked: Unchecked valid elements.
1713 // This drop guard will be invoked when predicate or `drop` of element panicked.
1714 // It shifts unchecked elements to cover holes and `set_len` to the correct length.
1715 // In cases when predicate and `drop` never panick, it will be optimized out.
1716 struct BackshiftOnDrop<'a, T, A: Allocator> {
1717 v: &'a mut Vec<T, A>,
1718 processed_len: usize,
1720 original_len: usize,
1723 impl<T, A: Allocator> Drop for BackshiftOnDrop<'_, T, A> {
1724 fn drop(&mut self) {
1725 if self.deleted_cnt > 0 {
1726 // SAFETY: Trailing unchecked items must be valid since we never touch them.
1729 self.v.as_ptr().add(self.processed_len),
1730 self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt),
1731 self.original_len - self.processed_len,
1735 // SAFETY: After filling holes, all items are in contiguous memory.
1737 self.v.set_len(self.original_len - self.deleted_cnt);
1742 let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len };
1744 fn process_loop<F, T, A: Allocator, const DELETED: bool>(
1745 original_len: usize,
1747 g: &mut BackshiftOnDrop<'_, T, A>,
1749 F: FnMut(&mut T) -> bool,
1751 while g.processed_len != original_len {
1752 // SAFETY: Unchecked element must be valid.
1753 let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
1755 // Advance early to avoid double drop if `drop_in_place` panicked.
1756 g.processed_len += 1;
1758 // SAFETY: We never touch this element again after dropped.
1759 unsafe { ptr::drop_in_place(cur) };
1760 // We already advanced the counter.
1768 // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
1769 // We use copy for move, and never touch this element again.
1771 let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
1772 ptr::copy_nonoverlapping(cur, hole_slot, 1);
1775 g.processed_len += 1;
1779 // Stage 1: Nothing was deleted.
1780 process_loop::<F, T, A, false>(original_len, &mut f, &mut g);
1782 // Stage 2: Some elements were deleted.
1783 process_loop::<F, T, A, true>(original_len, &mut f, &mut g);
1785 // All item are processed. This can be optimized to `set_len` by LLVM.
1789 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1792 /// If the vector is sorted, this removes all duplicates.
1797 /// let mut vec = vec![10, 20, 21, 30, 20];
1799 /// vec.dedup_by_key(|i| *i / 10);
1801 /// assert_eq!(vec, [10, 20, 30, 20]);
1803 #[stable(feature = "dedup_by", since = "1.16.0")]
1805 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1807 F: FnMut(&mut T) -> K,
1810 self.dedup_by(|a, b| key(a) == key(b))
1813 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1816 /// The `same_bucket` function is passed references to two elements from the vector and
1817 /// must determine if the elements compare equal. The elements are passed in opposite order
1818 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1820 /// If the vector is sorted, this removes all duplicates.
1825 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1827 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1829 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1831 #[stable(feature = "dedup_by", since = "1.16.0")]
1832 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1834 F: FnMut(&mut T, &mut T) -> bool,
1836 let len = self.len();
1841 /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */
1842 struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> {
1843 /* Offset of the element we want to check if it is duplicate */
1846 /* Offset of the place where we want to place the non-duplicate
1847 * when we find it. */
1850 /* The Vec that would need correction if `same_bucket` panicked */
1851 vec: &'a mut Vec<T, A>,
1854 impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
1855 fn drop(&mut self) {
1856 /* This code gets executed when `same_bucket` panics */
1858 /* SAFETY: invariant guarantees that `read - write`
1859 * and `len - read` never overflow and that the copy is always
1862 let ptr = self.vec.as_mut_ptr();
1863 let len = self.vec.len();
1865 /* How many items were left when `same_bucket` panicked.
1866 * Basically vec[read..].len() */
1867 let items_left = len.wrapping_sub(self.read);
1869 /* Pointer to first item in vec[write..write+items_left] slice */
1870 let dropped_ptr = ptr.add(self.write);
1871 /* Pointer to first item in vec[read..] slice */
1872 let valid_ptr = ptr.add(self.read);
1874 /* Copy `vec[read..]` to `vec[write..write+items_left]`.
1875 * The slices can overlap, so `copy_nonoverlapping` cannot be used */
1876 ptr::copy(valid_ptr, dropped_ptr, items_left);
1878 /* How many items have been already dropped
1879 * Basically vec[read..write].len() */
1880 let dropped = self.read.wrapping_sub(self.write);
1882 self.vec.set_len(len - dropped);
1887 let mut gap = FillGapOnDrop { read: 1, write: 1, vec: self };
1888 let ptr = gap.vec.as_mut_ptr();
1890 /* Drop items while going through Vec, it should be more efficient than
1891 * doing slice partition_dedup + truncate */
1893 /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
1894 * are always in-bounds and read_ptr never aliases prev_ptr */
1896 while gap.read < len {
1897 let read_ptr = ptr.add(gap.read);
1898 let prev_ptr = ptr.add(gap.write.wrapping_sub(1));
1900 if same_bucket(&mut *read_ptr, &mut *prev_ptr) {
1901 // Increase `gap.read` now since the drop may panic.
1903 /* We have found duplicate, drop it in-place */
1904 ptr::drop_in_place(read_ptr);
1906 let write_ptr = ptr.add(gap.write);
1908 /* Because `read_ptr` can be equal to `write_ptr`, we either
1909 * have to use `copy` or conditional `copy_nonoverlapping`.
1910 * Looks like the first option is faster. */
1911 ptr::copy(read_ptr, write_ptr, 1);
1913 /* We have filled that place, so go further */
1919 /* Technically we could let `gap` clean up with its Drop, but
1920 * when `same_bucket` is guaranteed to not panic, this bloats a little
1921 * the codegen, so we just do it manually */
1922 gap.vec.set_len(gap.write);
1927 /// Appends an element to the back of a collection.
1931 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1936 /// let mut vec = vec![1, 2];
1938 /// assert_eq!(vec, [1, 2, 3]);
1940 #[cfg(not(no_global_oom_handling))]
1942 #[stable(feature = "rust1", since = "1.0.0")]
1943 pub fn push(&mut self, value: T) {
1944 // This will panic or abort if we would allocate > isize::MAX bytes
1945 // or if the length increment would overflow for zero-sized types.
1946 if self.len == self.buf.capacity() {
1947 self.buf.reserve_for_push(self.len);
1950 let end = self.as_mut_ptr().add(self.len);
1951 ptr::write(end, value);
1956 /// Tries to append an element to the back of a collection.
1961 /// let mut vec = vec![1, 2];
1962 /// vec.try_push(3).unwrap();
1963 /// assert_eq!(vec, [1, 2, 3]);
1966 #[stable(feature = "kernel", since = "1.0.0")]
1967 pub fn try_push(&mut self, value: T) -> Result<(), TryReserveError> {
1968 if self.len == self.buf.capacity() {
1969 self.buf.try_reserve_for_push(self.len)?;
1972 let end = self.as_mut_ptr().add(self.len);
1973 ptr::write(end, value);
1979 /// Appends an element if there is sufficient spare capacity, otherwise an error is returned
1980 /// with the element.
1982 /// Unlike [`push`] this method will not reallocate when there's insufficient capacity.
1983 /// The caller should use [`reserve`] or [`try_reserve`] to ensure that there is enough capacity.
1985 /// [`push`]: Vec::push
1986 /// [`reserve`]: Vec::reserve
1987 /// [`try_reserve`]: Vec::try_reserve
1991 /// A manual, panic-free alternative to [`FromIterator`]:
1994 /// #![feature(vec_push_within_capacity)]
1996 /// use std::collections::TryReserveError;
1997 /// fn from_iter_fallible<T>(iter: impl Iterator<Item=T>) -> Result<Vec<T>, TryReserveError> {
1998 /// let mut vec = Vec::new();
1999 /// for value in iter {
2000 /// if let Err(value) = vec.push_within_capacity(value) {
2001 /// vec.try_reserve(1)?;
2002 /// // this cannot fail, the previous line either returned or added at least 1 free slot
2003 /// let _ = vec.push_within_capacity(value);
2008 /// assert_eq!(from_iter_fallible(0..100), Ok(Vec::from_iter(0..100)));
2011 #[unstable(feature = "vec_push_within_capacity", issue = "100486")]
2012 pub fn push_within_capacity(&mut self, value: T) -> Result<(), T> {
2013 if self.len == self.buf.capacity() {
2017 let end = self.as_mut_ptr().add(self.len);
2018 ptr::write(end, value);
2024 /// Removes the last element from a vector and returns it, or [`None`] if it
2027 /// If you'd like to pop the first element, consider using
2028 /// [`VecDeque::pop_front`] instead.
2030 /// [`VecDeque::pop_front`]: crate::collections::VecDeque::pop_front
2035 /// let mut vec = vec![1, 2, 3];
2036 /// assert_eq!(vec.pop(), Some(3));
2037 /// assert_eq!(vec, [1, 2]);
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 pub fn pop(&mut self) -> Option<T> {
2047 Some(ptr::read(self.as_ptr().add(self.len())))
2052 /// Moves all the elements of `other` into `self`, leaving `other` empty.
2056 /// Panics if the new capacity exceeds `isize::MAX` bytes.
2061 /// let mut vec = vec![1, 2, 3];
2062 /// let mut vec2 = vec![4, 5, 6];
2063 /// vec.append(&mut vec2);
2064 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
2065 /// assert_eq!(vec2, []);
2067 #[cfg(not(no_global_oom_handling))]
2069 #[stable(feature = "append", since = "1.4.0")]
2070 pub fn append(&mut self, other: &mut Self) {
2072 self.append_elements(other.as_slice() as _);
2077 /// Appends elements to `self` from other buffer.
2078 #[cfg(not(no_global_oom_handling))]
2080 unsafe fn append_elements(&mut self, other: *const [T]) {
2081 let count = unsafe { (*other).len() };
2082 self.reserve(count);
2083 let len = self.len();
2084 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
2088 /// Tries to append elements to `self` from other buffer.
2090 unsafe fn try_append_elements(&mut self, other: *const [T]) -> Result<(), TryReserveError> {
2091 let count = unsafe { (*other).len() };
2092 self.try_reserve(count)?;
2093 let len = self.len();
2094 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
2099 /// Removes the specified range from the vector in bulk, returning all
2100 /// removed elements as an iterator. If the iterator is dropped before
2101 /// being fully consumed, it drops the remaining removed elements.
2103 /// The returned iterator keeps a mutable borrow on the vector to optimize
2104 /// its implementation.
2108 /// Panics if the starting point is greater than the end point or if
2109 /// the end point is greater than the length of the vector.
2113 /// If the returned iterator goes out of scope without being dropped (due to
2114 /// [`mem::forget`], for example), the vector may have lost and leaked
2115 /// elements arbitrarily, including elements outside the range.
2120 /// let mut v = vec![1, 2, 3];
2121 /// let u: Vec<_> = v.drain(1..).collect();
2122 /// assert_eq!(v, &[1]);
2123 /// assert_eq!(u, &[2, 3]);
2125 /// // A full range clears the vector, like `clear()` does
2127 /// assert_eq!(v, &[]);
2129 #[stable(feature = "drain", since = "1.6.0")]
2130 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
2132 R: RangeBounds<usize>,
2136 // When the Drain is first created, it shortens the length of
2137 // the source vector to make sure no uninitialized or moved-from elements
2138 // are accessible at all if the Drain's destructor never gets to run.
2140 // Drain will ptr::read out the values to remove.
2141 // When finished, remaining tail of the vec is copied back to cover
2142 // the hole, and the vector length is restored to the new length.
2144 let len = self.len();
2145 let Range { start, end } = slice::range(range, ..len);
2148 // set self.vec length's to start, to be safe in case Drain is leaked
2149 self.set_len(start);
2150 let range_slice = slice::from_raw_parts(self.as_ptr().add(start), end - start);
2153 tail_len: len - end,
2154 iter: range_slice.iter(),
2155 vec: NonNull::from(self),
2160 /// Clears the vector, removing all values.
2162 /// Note that this method has no effect on the allocated capacity
2168 /// let mut v = vec![1, 2, 3];
2172 /// assert!(v.is_empty());
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 pub fn clear(&mut self) {
2177 let elems: *mut [T] = self.as_mut_slice();
2180 // - `elems` comes directly from `as_mut_slice` and is therefore valid.
2181 // - Setting `self.len` before calling `drop_in_place` means that,
2182 // if an element's `Drop` impl panics, the vector's `Drop` impl will
2183 // do nothing (leaking the rest of the elements) instead of dropping
2187 ptr::drop_in_place(elems);
2191 /// Returns the number of elements in the vector, also referred to
2192 /// as its 'length'.
2197 /// let a = vec![1, 2, 3];
2198 /// assert_eq!(a.len(), 3);
2201 #[stable(feature = "rust1", since = "1.0.0")]
2202 pub fn len(&self) -> usize {
2206 /// Returns `true` if the vector contains no elements.
2211 /// let mut v = Vec::new();
2212 /// assert!(v.is_empty());
2215 /// assert!(!v.is_empty());
2217 #[stable(feature = "rust1", since = "1.0.0")]
2218 pub fn is_empty(&self) -> bool {
2222 /// Splits the collection into two at the given index.
2224 /// Returns a newly allocated vector containing the elements in the range
2225 /// `[at, len)`. After the call, the original vector will be left containing
2226 /// the elements `[0, at)` with its previous capacity unchanged.
2230 /// Panics if `at > len`.
2235 /// let mut vec = vec![1, 2, 3];
2236 /// let vec2 = vec.split_off(1);
2237 /// assert_eq!(vec, [1]);
2238 /// assert_eq!(vec2, [2, 3]);
2240 #[cfg(not(no_global_oom_handling))]
2242 #[must_use = "use `.truncate()` if you don't need the other half"]
2243 #[stable(feature = "split_off", since = "1.4.0")]
2244 pub fn split_off(&mut self, at: usize) -> Self
2250 fn assert_failed(at: usize, len: usize) -> ! {
2251 panic!("`at` split index (is {at}) should be <= len (is {len})");
2254 if at > self.len() {
2255 assert_failed(at, self.len());
2259 // the new vector can take over the original buffer and avoid the copy
2260 return mem::replace(
2262 Vec::with_capacity_in(self.capacity(), self.allocator().clone()),
2266 let other_len = self.len - at;
2267 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
2269 // Unsafely `set_len` and copy items to `other`.
2272 other.set_len(other_len);
2274 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
2279 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2281 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2282 /// difference, with each additional slot filled with the result of
2283 /// calling the closure `f`. The return values from `f` will end up
2284 /// in the `Vec` in the order they have been generated.
2286 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2288 /// This method uses a closure to create new values on every push. If
2289 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
2290 /// want to use the [`Default`] trait to generate values, you can
2291 /// pass [`Default::default`] as the second argument.
2296 /// let mut vec = vec![1, 2, 3];
2297 /// vec.resize_with(5, Default::default);
2298 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
2300 /// let mut vec = vec![];
2302 /// vec.resize_with(4, || { p *= 2; p });
2303 /// assert_eq!(vec, [2, 4, 8, 16]);
2305 #[cfg(not(no_global_oom_handling))]
2306 #[stable(feature = "vec_resize_with", since = "1.33.0")]
2307 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
2311 let len = self.len();
2313 self.extend_trusted(iter::repeat_with(f).take(new_len - len));
2315 self.truncate(new_len);
2319 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
2320 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
2321 /// `'a`. If the type has only static references, or none at all, then this
2322 /// may be chosen to be `'static`.
2324 /// As of Rust 1.57, this method does not reallocate or shrink the `Vec`,
2325 /// so the leaked allocation may include unused capacity that is not part
2326 /// of the returned slice.
2328 /// This function is mainly useful for data that lives for the remainder of
2329 /// the program's life. Dropping the returned reference will cause a memory
2337 /// let x = vec![1, 2, 3];
2338 /// let static_ref: &'static mut [usize] = x.leak();
2339 /// static_ref[0] += 1;
2340 /// assert_eq!(static_ref, &[2, 2, 3]);
2342 #[stable(feature = "vec_leak", since = "1.47.0")]
2344 pub fn leak<'a>(self) -> &'a mut [T]
2348 let mut me = ManuallyDrop::new(self);
2349 unsafe { slice::from_raw_parts_mut(me.as_mut_ptr(), me.len) }
2352 /// Returns the remaining spare capacity of the vector as a slice of
2353 /// `MaybeUninit<T>`.
2355 /// The returned slice can be used to fill the vector with data (e.g. by
2356 /// reading from a file) before marking the data as initialized using the
2357 /// [`set_len`] method.
2359 /// [`set_len`]: Vec::set_len
2364 /// // Allocate vector big enough for 10 elements.
2365 /// let mut v = Vec::with_capacity(10);
2367 /// // Fill in the first 3 elements.
2368 /// let uninit = v.spare_capacity_mut();
2369 /// uninit[0].write(0);
2370 /// uninit[1].write(1);
2371 /// uninit[2].write(2);
2373 /// // Mark the first 3 elements of the vector as being initialized.
2378 /// assert_eq!(&v, &[0, 1, 2]);
2380 #[stable(feature = "vec_spare_capacity", since = "1.60.0")]
2382 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
2384 // This method is not implemented in terms of `split_at_spare_mut`,
2385 // to prevent invalidation of pointers to the buffer.
2387 slice::from_raw_parts_mut(
2388 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
2389 self.buf.capacity() - self.len,
2394 /// Returns vector content as a slice of `T`, along with the remaining spare
2395 /// capacity of the vector as a slice of `MaybeUninit<T>`.
2397 /// The returned spare capacity slice can be used to fill the vector with data
2398 /// (e.g. by reading from a file) before marking the data as initialized using
2399 /// the [`set_len`] method.
2401 /// [`set_len`]: Vec::set_len
2403 /// Note that this is a low-level API, which should be used with care for
2404 /// optimization purposes. If you need to append data to a `Vec`
2405 /// you can use [`push`], [`extend`], [`extend_from_slice`],
2406 /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
2407 /// [`resize_with`], depending on your exact needs.
2409 /// [`push`]: Vec::push
2410 /// [`extend`]: Vec::extend
2411 /// [`extend_from_slice`]: Vec::extend_from_slice
2412 /// [`extend_from_within`]: Vec::extend_from_within
2413 /// [`insert`]: Vec::insert
2414 /// [`append`]: Vec::append
2415 /// [`resize`]: Vec::resize
2416 /// [`resize_with`]: Vec::resize_with
2421 /// #![feature(vec_split_at_spare)]
2423 /// let mut v = vec![1, 1, 2];
2425 /// // Reserve additional space big enough for 10 elements.
2428 /// let (init, uninit) = v.split_at_spare_mut();
2429 /// let sum = init.iter().copied().sum::<u32>();
2431 /// // Fill in the next 4 elements.
2432 /// uninit[0].write(sum);
2433 /// uninit[1].write(sum * 2);
2434 /// uninit[2].write(sum * 3);
2435 /// uninit[3].write(sum * 4);
2437 /// // Mark the 4 elements of the vector as being initialized.
2439 /// let len = v.len();
2440 /// v.set_len(len + 4);
2443 /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
2445 #[unstable(feature = "vec_split_at_spare", issue = "81944")]
2447 pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
2449 // - len is ignored and so never changed
2450 let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
2454 /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
2456 /// This method provides unique access to all vec parts at once in `extend_from_within`.
2457 unsafe fn split_at_spare_mut_with_len(
2459 ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
2460 let ptr = self.as_mut_ptr();
2462 // - `ptr` is guaranteed to be valid for `self.len` elements
2463 // - but the allocation extends out to `self.buf.capacity()` elements, possibly
2465 let spare_ptr = unsafe { ptr.add(self.len) };
2466 let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>();
2467 let spare_len = self.buf.capacity() - self.len;
2470 // - `ptr` is guaranteed to be valid for `self.len` elements
2471 // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
2473 let initialized = slice::from_raw_parts_mut(ptr, self.len);
2474 let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
2476 (initialized, spare, &mut self.len)
2481 impl<T: Clone, A: Allocator> Vec<T, A> {
2482 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2484 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2485 /// difference, with each additional slot filled with `value`.
2486 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2488 /// This method requires `T` to implement [`Clone`],
2489 /// in order to be able to clone the passed value.
2490 /// If you need more flexibility (or want to rely on [`Default`] instead of
2491 /// [`Clone`]), use [`Vec::resize_with`].
2492 /// If you only need to resize to a smaller size, use [`Vec::truncate`].
2497 /// let mut vec = vec!["hello"];
2498 /// vec.resize(3, "world");
2499 /// assert_eq!(vec, ["hello", "world", "world"]);
2501 /// let mut vec = vec![1, 2, 3, 4];
2502 /// vec.resize(2, 0);
2503 /// assert_eq!(vec, [1, 2]);
2505 #[cfg(not(no_global_oom_handling))]
2506 #[stable(feature = "vec_resize", since = "1.5.0")]
2507 pub fn resize(&mut self, new_len: usize, value: T) {
2508 let len = self.len();
2511 self.extend_with(new_len - len, value)
2513 self.truncate(new_len);
2517 /// Tries to resize the `Vec` in-place so that `len` is equal to `new_len`.
2519 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2520 /// difference, with each additional slot filled with `value`.
2521 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2523 /// This method requires `T` to implement [`Clone`],
2524 /// in order to be able to clone the passed value.
2525 /// If you need more flexibility (or want to rely on [`Default`] instead of
2526 /// [`Clone`]), use [`Vec::resize_with`].
2527 /// If you only need to resize to a smaller size, use [`Vec::truncate`].
2532 /// let mut vec = vec!["hello"];
2533 /// vec.try_resize(3, "world").unwrap();
2534 /// assert_eq!(vec, ["hello", "world", "world"]);
2536 /// let mut vec = vec![1, 2, 3, 4];
2537 /// vec.try_resize(2, 0).unwrap();
2538 /// assert_eq!(vec, [1, 2]);
2540 /// let mut vec = vec![42];
2541 /// let result = vec.try_resize(usize::MAX, 0);
2542 /// assert!(result.is_err());
2544 #[stable(feature = "kernel", since = "1.0.0")]
2545 pub fn try_resize(&mut self, new_len: usize, value: T) -> Result<(), TryReserveError> {
2546 let len = self.len();
2549 self.try_extend_with(new_len - len, value)
2551 self.truncate(new_len);
2556 /// Clones and appends all elements in a slice to the `Vec`.
2558 /// Iterates over the slice `other`, clones each element, and then appends
2559 /// it to this `Vec`. The `other` slice is traversed in-order.
2561 /// Note that this function is same as [`extend`] except that it is
2562 /// specialized to work with slices instead. If and when Rust gets
2563 /// specialization this function will likely be deprecated (but still
2569 /// let mut vec = vec![1];
2570 /// vec.extend_from_slice(&[2, 3, 4]);
2571 /// assert_eq!(vec, [1, 2, 3, 4]);
2574 /// [`extend`]: Vec::extend
2575 #[cfg(not(no_global_oom_handling))]
2576 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
2577 pub fn extend_from_slice(&mut self, other: &[T]) {
2578 self.spec_extend(other.iter())
2581 /// Tries to clone and append all elements in a slice to the `Vec`.
2583 /// Iterates over the slice `other`, clones each element, and then appends
2584 /// it to this `Vec`. The `other` slice is traversed in-order.
2586 /// Note that this function is same as [`extend`] except that it is
2587 /// specialized to work with slices instead. If and when Rust gets
2588 /// specialization this function will likely be deprecated (but still
2594 /// let mut vec = vec![1];
2595 /// vec.try_extend_from_slice(&[2, 3, 4]).unwrap();
2596 /// assert_eq!(vec, [1, 2, 3, 4]);
2599 /// [`extend`]: Vec::extend
2600 #[stable(feature = "kernel", since = "1.0.0")]
2601 pub fn try_extend_from_slice(&mut self, other: &[T]) -> Result<(), TryReserveError> {
2602 self.try_spec_extend(other.iter())
2605 /// Copies elements from `src` range to the end of the vector.
2609 /// Panics if the starting point is greater than the end point or if
2610 /// the end point is greater than the length of the vector.
2615 /// let mut vec = vec![0, 1, 2, 3, 4];
2617 /// vec.extend_from_within(2..);
2618 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
2620 /// vec.extend_from_within(..2);
2621 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
2623 /// vec.extend_from_within(4..8);
2624 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
2626 #[cfg(not(no_global_oom_handling))]
2627 #[stable(feature = "vec_extend_from_within", since = "1.53.0")]
2628 pub fn extend_from_within<R>(&mut self, src: R)
2630 R: RangeBounds<usize>,
2632 let range = slice::range(src, ..self.len());
2633 self.reserve(range.len());
2636 // - `slice::range` guarantees that the given range is valid for indexing self
2638 self.spec_extend_from_within(range);
2643 impl<T, A: Allocator, const N: usize> Vec<[T; N], A> {
2644 /// Takes a `Vec<[T; N]>` and flattens it into a `Vec<T>`.
2648 /// Panics if the length of the resulting vector would overflow a `usize`.
2650 /// This is only possible when flattening a vector of arrays of zero-sized
2651 /// types, and thus tends to be irrelevant in practice. If
2652 /// `size_of::<T>() > 0`, this will never panic.
2657 /// #![feature(slice_flatten)]
2659 /// let mut vec = vec![[1, 2, 3], [4, 5, 6], [7, 8, 9]];
2660 /// assert_eq!(vec.pop(), Some([7, 8, 9]));
2662 /// let mut flattened = vec.into_flattened();
2663 /// assert_eq!(flattened.pop(), Some(6));
2665 #[unstable(feature = "slice_flatten", issue = "95629")]
2666 pub fn into_flattened(self) -> Vec<T, A> {
2667 let (ptr, len, cap, alloc) = self.into_raw_parts_with_alloc();
2668 let (new_len, new_cap) = if T::IS_ZST {
2669 (len.checked_mul(N).expect("vec len overflow"), usize::MAX)
2672 // - `cap * N` cannot overflow because the allocation is already in
2673 // the address space.
2674 // - Each `[T; N]` has `N` valid elements, so there are `len * N`
2675 // valid elements in the allocation.
2676 unsafe { (len.unchecked_mul(N), cap.unchecked_mul(N)) }
2679 // - `ptr` was allocated by `self`
2680 // - `ptr` is well-aligned because `[T; N]` has the same alignment as `T`.
2681 // - `new_cap` refers to the same sized allocation as `cap` because
2682 // `new_cap * size_of::<T>()` == `cap * size_of::<[T; N]>()`
2683 // - `len` <= `cap`, so `len * N` <= `cap * N`.
2684 unsafe { Vec::<T, A>::from_raw_parts_in(ptr.cast(), new_len, new_cap, alloc) }
2688 impl<T: Clone, A: Allocator> Vec<T, A> {
2689 #[cfg(not(no_global_oom_handling))]
2690 /// Extend the vector by `n` clones of value.
2691 fn extend_with(&mut self, n: usize, value: T) {
2695 let mut ptr = self.as_mut_ptr().add(self.len());
2696 // Use SetLenOnDrop to work around bug where compiler
2697 // might not realize the store through `ptr` through self.set_len()
2699 let mut local_len = SetLenOnDrop::new(&mut self.len);
2701 // Write all elements except the last one
2703 ptr::write(ptr, value.clone());
2705 // Increment the length in every step in case clone() panics
2706 local_len.increment_len(1);
2710 // We can write the last element directly without cloning needlessly
2711 ptr::write(ptr, value);
2712 local_len.increment_len(1);
2715 // len set by scope guard
2719 /// Try to extend the vector by `n` clones of value.
2720 fn try_extend_with(&mut self, n: usize, value: T) -> Result<(), TryReserveError> {
2721 self.try_reserve(n)?;
2724 let mut ptr = self.as_mut_ptr().add(self.len());
2725 // Use SetLenOnDrop to work around bug where compiler
2726 // might not realize the store through `ptr` through self.set_len()
2728 let mut local_len = SetLenOnDrop::new(&mut self.len);
2730 // Write all elements except the last one
2732 ptr::write(ptr, value.clone());
2734 // Increment the length in every step in case clone() panics
2735 local_len.increment_len(1);
2739 // We can write the last element directly without cloning needlessly
2740 ptr::write(ptr, value);
2741 local_len.increment_len(1);
2744 // len set by scope guard
2750 impl<T: PartialEq, A: Allocator> Vec<T, A> {
2751 /// Removes consecutive repeated elements in the vector according to the
2752 /// [`PartialEq`] trait implementation.
2754 /// If the vector is sorted, this removes all duplicates.
2759 /// let mut vec = vec![1, 2, 2, 3, 2];
2763 /// assert_eq!(vec, [1, 2, 3, 2]);
2765 #[stable(feature = "rust1", since = "1.0.0")]
2767 pub fn dedup(&mut self) {
2768 self.dedup_by(|a, b| a == b)
2772 ////////////////////////////////////////////////////////////////////////////////
2773 // Internal methods and functions
2774 ////////////////////////////////////////////////////////////////////////////////
2777 #[cfg(not(no_global_oom_handling))]
2778 #[stable(feature = "rust1", since = "1.0.0")]
2779 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
2780 <T as SpecFromElem>::from_elem(elem, n, Global)
2784 #[cfg(not(no_global_oom_handling))]
2785 #[unstable(feature = "allocator_api", issue = "32838")]
2786 pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
2787 <T as SpecFromElem>::from_elem(elem, n, alloc)
2790 trait ExtendFromWithinSpec {
2793 /// - `src` needs to be valid index
2794 /// - `self.capacity() - self.len()` must be `>= src.len()`
2795 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
2798 impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
2799 default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
2801 // - len is increased only after initializing elements
2802 let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
2805 // - caller guarantees that src is a valid index
2806 let to_clone = unsafe { this.get_unchecked(src) };
2808 iter::zip(to_clone, spare)
2809 .map(|(src, dst)| dst.write(src.clone()))
2811 // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
2812 // - len is increased after each element to prevent leaks (see issue #82533)
2813 .for_each(|_| *len += 1);
2817 impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
2818 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
2819 let count = src.len();
2821 let (init, spare) = self.split_at_spare_mut();
2824 // - caller guarantees that `src` is a valid index
2825 let source = unsafe { init.get_unchecked(src) };
2828 // - Both pointers are created from unique slice references (`&mut [_]`)
2829 // so they are valid and do not overlap.
2830 // - Elements are :Copy so it's OK to copy them, without doing
2831 // anything with the original values
2832 // - `count` is equal to the len of `source`, so source is valid for
2834 // - `.reserve(count)` guarantees that `spare.len() >= count` so spare
2835 // is valid for `count` writes
2836 unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
2840 // - The elements were just initialized by `copy_nonoverlapping`
2845 ////////////////////////////////////////////////////////////////////////////////
2846 // Common trait implementations for Vec
2847 ////////////////////////////////////////////////////////////////////////////////
2849 #[stable(feature = "rust1", since = "1.0.0")]
2850 impl<T, A: Allocator> ops::Deref for Vec<T, A> {
2854 fn deref(&self) -> &[T] {
2855 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
2859 #[stable(feature = "rust1", since = "1.0.0")]
2860 impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
2862 fn deref_mut(&mut self) -> &mut [T] {
2863 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
2867 #[cfg(not(no_global_oom_handling))]
2868 #[stable(feature = "rust1", since = "1.0.0")]
2869 impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
2871 fn clone(&self) -> Self {
2872 let alloc = self.allocator().clone();
2873 <[T]>::to_vec_in(&**self, alloc)
2876 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
2877 // required for this method definition, is not available. Instead use the
2878 // `slice::to_vec` function which is only available with cfg(test)
2879 // NB see the slice::hack module in slice.rs for more information
2881 fn clone(&self) -> Self {
2882 let alloc = self.allocator().clone();
2883 crate::slice::to_vec(&**self, alloc)
2886 fn clone_from(&mut self, other: &Self) {
2887 crate::slice::SpecCloneIntoVec::clone_into(other.as_slice(), self);
2891 /// The hash of a vector is the same as that of the corresponding slice,
2892 /// as required by the `core::borrow::Borrow` implementation.
2895 /// use std::hash::BuildHasher;
2897 /// let b = std::collections::hash_map::RandomState::new();
2898 /// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
2899 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
2900 /// assert_eq!(b.hash_one(v), b.hash_one(s));
2902 #[stable(feature = "rust1", since = "1.0.0")]
2903 impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
2905 fn hash<H: Hasher>(&self, state: &mut H) {
2906 Hash::hash(&**self, state)
2910 #[stable(feature = "rust1", since = "1.0.0")]
2911 #[rustc_on_unimplemented(
2912 message = "vector indices are of type `usize` or ranges of `usize`",
2913 label = "vector indices are of type `usize` or ranges of `usize`"
2915 impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
2916 type Output = I::Output;
2919 fn index(&self, index: I) -> &Self::Output {
2920 Index::index(&**self, index)
2924 #[stable(feature = "rust1", since = "1.0.0")]
2925 #[rustc_on_unimplemented(
2926 message = "vector indices are of type `usize` or ranges of `usize`",
2927 label = "vector indices are of type `usize` or ranges of `usize`"
2929 impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
2931 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2932 IndexMut::index_mut(&mut **self, index)
2936 #[cfg(not(no_global_oom_handling))]
2937 #[stable(feature = "rust1", since = "1.0.0")]
2938 impl<T> FromIterator<T> for Vec<T> {
2940 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2941 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
2945 #[stable(feature = "rust1", since = "1.0.0")]
2946 impl<T, A: Allocator> IntoIterator for Vec<T, A> {
2948 type IntoIter = IntoIter<T, A>;
2950 /// Creates a consuming iterator, that is, one that moves each value out of
2951 /// the vector (from start to end). The vector cannot be used after calling
2957 /// let v = vec!["a".to_string(), "b".to_string()];
2958 /// let mut v_iter = v.into_iter();
2960 /// let first_element: Option<String> = v_iter.next();
2962 /// assert_eq!(first_element, Some("a".to_string()));
2963 /// assert_eq!(v_iter.next(), Some("b".to_string()));
2964 /// assert_eq!(v_iter.next(), None);
2967 fn into_iter(self) -> Self::IntoIter {
2969 let mut me = ManuallyDrop::new(self);
2970 let alloc = ManuallyDrop::new(ptr::read(me.allocator()));
2971 let begin = me.as_mut_ptr();
2972 let end = if T::IS_ZST {
2973 begin.wrapping_byte_add(me.len())
2975 begin.add(me.len()) as *const T
2977 let cap = me.buf.capacity();
2979 buf: NonNull::new_unchecked(begin),
2980 phantom: PhantomData,
2990 #[stable(feature = "rust1", since = "1.0.0")]
2991 impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
2993 type IntoIter = slice::Iter<'a, T>;
2995 fn into_iter(self) -> Self::IntoIter {
3000 #[stable(feature = "rust1", since = "1.0.0")]
3001 impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
3002 type Item = &'a mut T;
3003 type IntoIter = slice::IterMut<'a, T>;
3005 fn into_iter(self) -> Self::IntoIter {
3010 #[cfg(not(no_global_oom_handling))]
3011 #[stable(feature = "rust1", since = "1.0.0")]
3012 impl<T, A: Allocator> Extend<T> for Vec<T, A> {
3014 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
3015 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
3019 fn extend_one(&mut self, item: T) {
3024 fn extend_reserve(&mut self, additional: usize) {
3025 self.reserve(additional);
3029 impl<T, A: Allocator> Vec<T, A> {
3030 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
3031 // they have no further optimizations to apply
3032 #[cfg(not(no_global_oom_handling))]
3033 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
3034 // This is the case for a general iterator.
3036 // This function should be the moral equivalent of:
3038 // for item in iterator {
3041 while let Some(element) = iterator.next() {
3042 let len = self.len();
3043 if len == self.capacity() {
3044 let (lower, _) = iterator.size_hint();
3045 self.reserve(lower.saturating_add(1));
3048 ptr::write(self.as_mut_ptr().add(len), element);
3049 // Since next() executes user code which can panic we have to bump the length
3051 // NB can't overflow since we would have had to alloc the address space
3052 self.set_len(len + 1);
3057 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
3058 // they have no further optimizations to apply
3059 fn try_extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) -> Result<(), TryReserveError> {
3060 // This is the case for a general iterator.
3062 // This function should be the moral equivalent of:
3064 // for item in iterator {
3067 while let Some(element) = iterator.next() {
3068 let len = self.len();
3069 if len == self.capacity() {
3070 let (lower, _) = iterator.size_hint();
3071 self.try_reserve(lower.saturating_add(1))?;
3074 ptr::write(self.as_mut_ptr().add(len), element);
3075 // Since next() executes user code which can panic we have to bump the length
3077 // NB can't overflow since we would have had to alloc the address space
3078 self.set_len(len + 1);
3085 // specific extend for `TrustedLen` iterators, called both by the specializations
3086 // and internal places where resolving specialization makes compilation slower
3087 #[cfg(not(no_global_oom_handling))]
3088 fn extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) {
3089 let (low, high) = iterator.size_hint();
3090 if let Some(additional) = high {
3094 "TrustedLen iterator's size hint is not exact: {:?}",
3097 self.reserve(additional);
3099 let ptr = self.as_mut_ptr();
3100 let mut local_len = SetLenOnDrop::new(&mut self.len);
3101 iterator.for_each(move |element| {
3102 ptr::write(ptr.add(local_len.current_len()), element);
3103 // Since the loop executes user code which can panic we have to update
3104 // the length every step to correctly drop what we've written.
3105 // NB can't overflow since we would have had to alloc the address space
3106 local_len.increment_len(1);
3110 // Per TrustedLen contract a `None` upper bound means that the iterator length
3111 // truly exceeds usize::MAX, which would eventually lead to a capacity overflow anyway.
3112 // Since the other branch already panics eagerly (via `reserve()`) we do the same here.
3113 // This avoids additional codegen for a fallback code path which would eventually
3115 panic!("capacity overflow");
3119 // specific extend for `TrustedLen` iterators, called both by the specializations
3120 // and internal places where resolving specialization makes compilation slower
3121 fn try_extend_trusted(&mut self, iterator: impl iter::TrustedLen<Item = T>) -> Result<(), TryReserveError> {
3122 let (low, high) = iterator.size_hint();
3123 if let Some(additional) = high {
3127 "TrustedLen iterator's size hint is not exact: {:?}",
3130 self.try_reserve(additional)?;
3132 let ptr = self.as_mut_ptr();
3133 let mut local_len = SetLenOnDrop::new(&mut self.len);
3134 iterator.for_each(move |element| {
3135 ptr::write(ptr.add(local_len.current_len()), element);
3136 // Since the loop executes user code which can panic we have to update
3137 // the length every step to correctly drop what we've written.
3138 // NB can't overflow since we would have had to alloc the address space
3139 local_len.increment_len(1);
3144 Err(TryReserveErrorKind::CapacityOverflow.into())
3148 /// Creates a splicing iterator that replaces the specified range in the vector
3149 /// with the given `replace_with` iterator and yields the removed items.
3150 /// `replace_with` does not need to be the same length as `range`.
3152 /// `range` is removed even if the iterator is not consumed until the end.
3154 /// It is unspecified how many elements are removed from the vector
3155 /// if the `Splice` value is leaked.
3157 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
3159 /// This is optimal if:
3161 /// * The tail (elements in the vector after `range`) is empty,
3162 /// * or `replace_with` yields fewer or equal elements than `range`’s length
3163 /// * or the lower bound of its `size_hint()` is exact.
3165 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
3169 /// Panics if the starting point is greater than the end point or if
3170 /// the end point is greater than the length of the vector.
3175 /// let mut v = vec![1, 2, 3, 4];
3176 /// let new = [7, 8, 9];
3177 /// let u: Vec<_> = v.splice(1..3, new).collect();
3178 /// assert_eq!(v, &[1, 7, 8, 9, 4]);
3179 /// assert_eq!(u, &[2, 3]);
3181 #[cfg(not(no_global_oom_handling))]
3183 #[stable(feature = "vec_splice", since = "1.21.0")]
3184 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
3186 R: RangeBounds<usize>,
3187 I: IntoIterator<Item = T>,
3189 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
3192 /// Creates an iterator which uses a closure to determine if an element should be removed.
3194 /// If the closure returns true, then the element is removed and yielded.
3195 /// If the closure returns false, the element will remain in the vector and will not be yielded
3196 /// by the iterator.
3198 /// If the returned `ExtractIf` is not exhausted, e.g. because it is dropped without iterating
3199 /// or the iteration short-circuits, then the remaining elements will be retained.
3200 /// Use [`retain`] with a negated predicate if you do not need the returned iterator.
3202 /// [`retain`]: Vec::retain
3204 /// Using this method is equivalent to the following code:
3207 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
3208 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
3210 /// while i < vec.len() {
3211 /// if some_predicate(&mut vec[i]) {
3212 /// let val = vec.remove(i);
3213 /// // your code here
3219 /// # assert_eq!(vec, vec![1, 4, 5]);
3222 /// But `extract_if` is easier to use. `extract_if` is also more efficient,
3223 /// because it can backshift the elements of the array in bulk.
3225 /// Note that `extract_if` also lets you mutate every element in the filter closure,
3226 /// regardless of whether you choose to keep or remove it.
3230 /// Splitting an array into evens and odds, reusing the original allocation:
3233 /// #![feature(extract_if)]
3234 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
3236 /// let evens = numbers.extract_if(|x| *x % 2 == 0).collect::<Vec<_>>();
3237 /// let odds = numbers;
3239 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
3240 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
3242 #[unstable(feature = "extract_if", reason = "recently added", issue = "43244")]
3243 pub fn extract_if<F>(&mut self, filter: F) -> ExtractIf<'_, T, F, A>
3245 F: FnMut(&mut T) -> bool,
3247 let old_len = self.len();
3249 // Guard against us getting leaked (leak amplification)
3254 ExtractIf { vec: self, idx: 0, del: 0, old_len, pred: filter }
3258 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
3260 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
3261 /// append the entire slice at once.
3263 /// [`copy_from_slice`]: slice::copy_from_slice
3264 #[cfg(not(no_global_oom_handling))]
3265 #[stable(feature = "extend_ref", since = "1.2.0")]
3266 impl<'a, T: Copy + 'a, A: Allocator> Extend<&'a T> for Vec<T, A> {
3267 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
3268 self.spec_extend(iter.into_iter())
3272 fn extend_one(&mut self, &item: &'a T) {
3277 fn extend_reserve(&mut self, additional: usize) {
3278 self.reserve(additional);
3282 /// Implements comparison of vectors, [lexicographically](Ord#lexicographical-comparison).
3283 #[stable(feature = "rust1", since = "1.0.0")]
3284 impl<T, A1, A2> PartialOrd<Vec<T, A2>> for Vec<T, A1>
3291 fn partial_cmp(&self, other: &Vec<T, A2>) -> Option<Ordering> {
3292 PartialOrd::partial_cmp(&**self, &**other)
3296 #[stable(feature = "rust1", since = "1.0.0")]
3297 impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
3299 /// Implements ordering of vectors, [lexicographically](Ord#lexicographical-comparison).
3300 #[stable(feature = "rust1", since = "1.0.0")]
3301 impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
3303 fn cmp(&self, other: &Self) -> Ordering {
3304 Ord::cmp(&**self, &**other)
3308 #[stable(feature = "rust1", since = "1.0.0")]
3309 unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
3310 fn drop(&mut self) {
3313 // use a raw slice to refer to the elements of the vector as weakest necessary type;
3314 // could avoid questions of validity in certain cases
3315 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
3317 // RawVec handles deallocation
3321 #[stable(feature = "rust1", since = "1.0.0")]
3322 impl<T> Default for Vec<T> {
3323 /// Creates an empty `Vec<T>`.
3325 /// The vector will not allocate until elements are pushed onto it.
3326 fn default() -> Vec<T> {
3331 #[stable(feature = "rust1", since = "1.0.0")]
3332 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
3333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3334 fmt::Debug::fmt(&**self, f)
3338 #[stable(feature = "rust1", since = "1.0.0")]
3339 impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
3340 fn as_ref(&self) -> &Vec<T, A> {
3345 #[stable(feature = "vec_as_mut", since = "1.5.0")]
3346 impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
3347 fn as_mut(&mut self) -> &mut Vec<T, A> {
3352 #[stable(feature = "rust1", since = "1.0.0")]
3353 impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
3354 fn as_ref(&self) -> &[T] {
3359 #[stable(feature = "vec_as_mut", since = "1.5.0")]
3360 impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
3361 fn as_mut(&mut self) -> &mut [T] {
3366 #[cfg(not(no_global_oom_handling))]
3367 #[stable(feature = "rust1", since = "1.0.0")]
3368 impl<T: Clone> From<&[T]> for Vec<T> {
3369 /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
3374 /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
3377 fn from(s: &[T]) -> Vec<T> {
3381 fn from(s: &[T]) -> Vec<T> {
3382 crate::slice::to_vec(s, Global)
3386 #[cfg(not(no_global_oom_handling))]
3387 #[stable(feature = "vec_from_mut", since = "1.19.0")]
3388 impl<T: Clone> From<&mut [T]> for Vec<T> {
3389 /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
3394 /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
3397 fn from(s: &mut [T]) -> Vec<T> {
3401 fn from(s: &mut [T]) -> Vec<T> {
3402 crate::slice::to_vec(s, Global)
3406 #[cfg(not(no_global_oom_handling))]
3407 #[stable(feature = "vec_from_array", since = "1.44.0")]
3408 impl<T, const N: usize> From<[T; N]> for Vec<T> {
3409 /// Allocate a `Vec<T>` and move `s`'s items into it.
3414 /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
3417 fn from(s: [T; N]) -> Vec<T> {
3418 <[T]>::into_vec(Box::new(s))
3422 fn from(s: [T; N]) -> Vec<T> {
3423 crate::slice::into_vec(Box::new(s))
3427 #[cfg(not(no_borrow))]
3428 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
3429 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
3431 [T]: ToOwned<Owned = Vec<T>>,
3433 /// Convert a clone-on-write slice into a vector.
3435 /// If `s` already owns a `Vec<T>`, it will be returned directly.
3436 /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and
3437 /// filled by cloning `s`'s items into it.
3442 /// # use std::borrow::Cow;
3443 /// let o: Cow<'_, [i32]> = Cow::Owned(vec![1, 2, 3]);
3444 /// let b: Cow<'_, [i32]> = Cow::Borrowed(&[1, 2, 3]);
3445 /// assert_eq!(Vec::from(o), Vec::from(b));
3447 fn from(s: Cow<'a, [T]>) -> Vec<T> {
3452 // note: test pulls in std, which causes errors here
3454 #[stable(feature = "vec_from_box", since = "1.18.0")]
3455 impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
3456 /// Convert a boxed slice into a vector by transferring ownership of
3457 /// the existing heap allocation.
3462 /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
3463 /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
3465 fn from(s: Box<[T], A>) -> Self {
3470 // note: test pulls in std, which causes errors here
3471 #[cfg(not(no_global_oom_handling))]
3473 #[stable(feature = "box_from_vec", since = "1.20.0")]
3474 impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
3475 /// Convert a vector into a boxed slice.
3477 /// If `v` has excess capacity, its items will be moved into a
3478 /// newly-allocated buffer with exactly the right capacity.
3483 /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
3486 /// Any excess capacity is removed:
3488 /// let mut vec = Vec::with_capacity(10);
3489 /// vec.extend([1, 2, 3]);
3491 /// assert_eq!(Box::from(vec), vec![1, 2, 3].into_boxed_slice());
3493 fn from(v: Vec<T, A>) -> Self {
3494 v.into_boxed_slice()
3498 #[cfg(not(no_global_oom_handling))]
3499 #[stable(feature = "rust1", since = "1.0.0")]
3500 impl From<&str> for Vec<u8> {
3501 /// Allocate a `Vec<u8>` and fill it with a UTF-8 string.
3506 /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
3508 fn from(s: &str) -> Vec<u8> {
3509 From::from(s.as_bytes())
3513 #[stable(feature = "array_try_from_vec", since = "1.48.0")]
3514 impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
3515 type Error = Vec<T, A>;
3517 /// Gets the entire contents of the `Vec<T>` as an array,
3518 /// if its size exactly matches that of the requested array.
3523 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
3524 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
3527 /// If the length doesn't match, the input comes back in `Err`:
3529 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
3530 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
3533 /// If you're fine with just getting a prefix of the `Vec<T>`,
3534 /// you can call [`.truncate(N)`](Vec::truncate) first.
3536 /// let mut v = String::from("hello world").into_bytes();
3539 /// let [a, b]: [_; 2] = v.try_into().unwrap();
3540 /// assert_eq!(a, b' ');
3541 /// assert_eq!(b, b'd');
3543 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
3548 // SAFETY: `.set_len(0)` is always sound.
3549 unsafe { vec.set_len(0) };
3551 // SAFETY: A `Vec`'s pointer is always aligned properly, and
3552 // the alignment the array needs is the same as the items.
3553 // We checked earlier that we have sufficient items.
3554 // The items will not double-drop as the `set_len`
3555 // tells the `Vec` not to also drop them.
3556 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };