1 //! A contiguous growable array type with heap-allocated contents, written
4 //! Vectors have *O*(1) indexing, amortized *O*(1) push (to the end) and
5 //! *O*(1) pop (from the end).
7 //! Vectors ensure they never allocate more than `isize::MAX` bytes.
11 //! You can explicitly create a [`Vec`] with [`Vec::new`]:
14 //! let v: Vec<i32> = Vec::new();
17 //! ...or by using the [`vec!`] macro:
20 //! let v: Vec<i32> = vec![];
22 //! let v = vec![1, 2, 3, 4, 5];
24 //! let v = vec![0; 10]; // ten zeroes
27 //! You can [`push`] values onto the end of a vector (which will grow the vector
31 //! let mut v = vec![1, 2];
36 //! Popping values works in much the same way:
39 //! let mut v = vec![1, 2];
41 //! let two = v.pop();
44 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
47 //! let mut v = vec![1, 2, 3];
52 //! [`push`]: Vec::push
54 #![stable(feature = "rust1", since = "1.0.0")]
56 #[cfg(not(no_global_oom_handling))]
58 use core::cmp::Ordering;
59 use core::convert::TryFrom;
61 use core::hash::{Hash, Hasher};
62 use core::intrinsics::{arith_offset, assume};
64 #[cfg(not(no_global_oom_handling))]
65 use core::iter::FromIterator;
66 use core::marker::PhantomData;
67 use core::mem::{self, ManuallyDrop, MaybeUninit};
68 use core::ops::{self, Index, IndexMut, Range, RangeBounds};
69 use core::ptr::{self, NonNull};
70 use core::slice::{self, SliceIndex};
72 use crate::alloc::{Allocator, Global};
73 use crate::borrow::{Cow, ToOwned};
74 use crate::boxed::Box;
75 use crate::collections::TryReserveError;
76 use crate::raw_vec::RawVec;
78 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
79 pub use self::drain_filter::DrainFilter;
83 #[cfg(not(no_global_oom_handling))]
84 #[stable(feature = "vec_splice", since = "1.21.0")]
85 pub use self::splice::Splice;
87 #[cfg(not(no_global_oom_handling))]
90 #[stable(feature = "drain", since = "1.6.0")]
91 pub use self::drain::Drain;
95 #[cfg(not(no_global_oom_handling))]
98 #[cfg(not(no_global_oom_handling))]
99 pub(crate) use self::into_iter::AsIntoIter;
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 source_iter_marker;
115 #[cfg(not(no_global_oom_handling))]
116 use self::spec_from_elem::SpecFromElem;
118 #[cfg(not(no_global_oom_handling))]
121 #[cfg(not(no_global_oom_handling))]
122 use self::set_len_on_drop::SetLenOnDrop;
124 #[cfg(not(no_global_oom_handling))]
127 #[cfg(not(no_global_oom_handling))]
128 use self::in_place_drop::InPlaceDrop;
130 #[cfg(not(no_global_oom_handling))]
133 #[cfg(not(no_global_oom_handling))]
134 use self::spec_from_iter_nested::SpecFromIterNested;
136 #[cfg(not(no_global_oom_handling))]
137 mod spec_from_iter_nested;
139 #[cfg(not(no_global_oom_handling))]
140 use self::spec_from_iter::SpecFromIter;
142 #[cfg(not(no_global_oom_handling))]
145 #[cfg(not(no_global_oom_handling))]
146 use self::spec_extend::SpecExtend;
148 #[cfg(not(no_global_oom_handling))]
151 /// A contiguous growable array type, written as `Vec<T>` and pronounced 'vector'.
156 /// let mut vec = Vec::new();
160 /// assert_eq!(vec.len(), 2);
161 /// assert_eq!(vec[0], 1);
163 /// assert_eq!(vec.pop(), Some(2));
164 /// assert_eq!(vec.len(), 1);
167 /// assert_eq!(vec[0], 7);
169 /// vec.extend([1, 2, 3].iter().copied());
172 /// println!("{}", x);
174 /// assert_eq!(vec, [7, 1, 2, 3]);
177 /// The [`vec!`] macro is provided for convenient initialization:
180 /// let mut vec1 = vec![1, 2, 3];
182 /// let vec2 = Vec::from([1, 2, 3, 4]);
183 /// assert_eq!(vec1, vec2);
186 /// It can also initialize each element of a `Vec<T>` with a given value.
187 /// This may be more efficient than performing allocation and initialization
188 /// in separate steps, especially when initializing a vector of zeros:
191 /// let vec = vec![0; 5];
192 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
194 /// // The following is equivalent, but potentially slower:
195 /// let mut vec = Vec::with_capacity(5);
196 /// vec.resize(5, 0);
197 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
200 /// For more information, see
201 /// [Capacity and Reallocation](#capacity-and-reallocation).
203 /// Use a `Vec<T>` as an efficient stack:
206 /// let mut stack = Vec::new();
212 /// while let Some(top) = stack.pop() {
213 /// // Prints 3, 2, 1
214 /// println!("{}", top);
220 /// The `Vec` type allows to access values by index, because it implements the
221 /// [`Index`] trait. An example will be more explicit:
224 /// let v = vec![0, 2, 4, 6];
225 /// println!("{}", v[1]); // it will display '2'
228 /// However be careful: if you try to access an index which isn't in the `Vec`,
229 /// your software will panic! You cannot do this:
232 /// let v = vec![0, 2, 4, 6];
233 /// println!("{}", v[6]); // it will panic!
236 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
241 /// A `Vec` can be mutable. On the other hand, slices are read-only objects.
242 /// To get a [slice][prim@slice], use [`&`]. Example:
245 /// fn read_slice(slice: &[usize]) {
249 /// let v = vec![0, 1];
252 /// // ... and that's all!
253 /// // you can also do it like this:
254 /// let u: &[usize] = &v;
256 /// let u: &[_] = &v;
259 /// In Rust, it's more common to pass slices as arguments rather than vectors
260 /// when you just want to provide read access. The same goes for [`String`] and
263 /// # Capacity and reallocation
265 /// The capacity of a vector is the amount of space allocated for any future
266 /// elements that will be added onto the vector. This is not to be confused with
267 /// the *length* of a vector, which specifies the number of actual elements
268 /// within the vector. If a vector's length exceeds its capacity, its capacity
269 /// will automatically be increased, but its elements will have to be
272 /// For example, a vector with capacity 10 and length 0 would be an empty vector
273 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
274 /// vector will not change its capacity or cause reallocation to occur. However,
275 /// if the vector's length is increased to 11, it will have to reallocate, which
276 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
277 /// whenever possible to specify how big the vector is expected to get.
281 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
282 /// about its design. This ensures that it's as low-overhead as possible in
283 /// the general case, and can be correctly manipulated in primitive ways
284 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
285 /// If additional type parameters are added (e.g., to support custom allocators),
286 /// overriding their defaults may change the behavior.
288 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
289 /// triplet. No more, no less. The order of these fields is completely
290 /// unspecified, and you should use the appropriate methods to modify these.
291 /// The pointer will never be null, so this type is null-pointer-optimized.
293 /// However, the pointer might not actually point to allocated memory. In particular,
294 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
295 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
296 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
297 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
298 /// the `Vec` might not report a [`capacity`] of 0*. `Vec` will allocate if and only
299 /// if <code>[mem::size_of::\<T>]\() * [capacity]\() > 0</code>. In general, `Vec`'s allocation
300 /// details are very subtle --- if you intend to allocate memory using a `Vec`
301 /// and use it for something else (either to pass to unsafe code, or to build your
302 /// own memory-backed collection), be sure to deallocate this memory by using
303 /// `from_raw_parts` to recover the `Vec` and then dropping it.
305 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
306 /// (as defined by the allocator Rust is configured to use by default), and its
307 /// pointer points to [`len`] initialized, contiguous elements in order (what
308 /// you would see if you coerced it to a slice), followed by <code>[capacity] - [len]</code>
309 /// logically uninitialized, contiguous elements.
311 /// A vector containing the elements `'a'` and `'b'` with capacity 4 can be
312 /// visualized as below. The top part is the `Vec` struct, it contains a
313 /// pointer to the head of the allocation in the heap, length and capacity.
314 /// The bottom part is the allocation on the heap, a contiguous memory block.
318 /// +--------+--------+--------+
319 /// | 0x0123 | 2 | 4 |
320 /// +--------+--------+--------+
323 /// Heap +--------+--------+--------+--------+
324 /// | 'a' | 'b' | uninit | uninit |
325 /// +--------+--------+--------+--------+
328 /// - **uninit** represents memory that is not initialized, see [`MaybeUninit`].
329 /// - Note: the ABI is not stable and `Vec` makes no guarantees about its memory
330 /// layout (including the order of fields).
332 /// `Vec` will never perform a "small optimization" where elements are actually
333 /// stored on the stack for two reasons:
335 /// * It would make it more difficult for unsafe code to correctly manipulate
336 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
337 /// only moved, and it would be more difficult to determine if a `Vec` had
338 /// actually allocated memory.
340 /// * It would penalize the general case, incurring an additional branch
343 /// `Vec` will never automatically shrink itself, even if completely empty. This
344 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
345 /// and then filling it back up to the same [`len`] should incur no calls to
346 /// the allocator. If you wish to free up unused memory, use
347 /// [`shrink_to_fit`] or [`shrink_to`].
349 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
350 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
351 /// <code>[len] == [capacity]</code>. That is, the reported capacity is completely
352 /// accurate, and can be relied on. It can even be used to manually free the memory
353 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
354 /// when not necessary.
356 /// `Vec` does not guarantee any particular growth strategy when reallocating
357 /// when full, nor when [`reserve`] is called. The current strategy is basic
358 /// and it may prove desirable to use a non-constant growth factor. Whatever
359 /// strategy is used will of course guarantee *O*(1) amortized [`push`].
361 /// `vec![x; n]`, `vec![a, b, c, d]`, and
362 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
363 /// with exactly the requested capacity. If <code>[len] == [capacity]</code>,
364 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
365 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
367 /// `Vec` will not specifically overwrite any data that is removed from it,
368 /// but also won't specifically preserve it. Its uninitialized memory is
369 /// scratch space that it may use however it wants. It will generally just do
370 /// whatever is most efficient or otherwise easy to implement. Do not rely on
371 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
372 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
373 /// first, that might not actually happen because the optimizer does not consider
374 /// this a side-effect that must be preserved. There is one case which we will
375 /// not break, however: using `unsafe` code to write to the excess capacity,
376 /// and then increasing the length to match, is always valid.
378 /// Currently, `Vec` does not guarantee the order in which elements are dropped.
379 /// The order has changed in the past and may change again.
381 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
382 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
383 /// [`String`]: crate::string::String
384 /// [`&str`]: type@str
385 /// [`shrink_to_fit`]: Vec::shrink_to_fit
386 /// [`shrink_to`]: Vec::shrink_to
387 /// [capacity]: Vec::capacity
388 /// [`capacity`]: Vec::capacity
389 /// [mem::size_of::\<T>]: core::mem::size_of
391 /// [`len`]: Vec::len
392 /// [`push`]: Vec::push
393 /// [`insert`]: Vec::insert
394 /// [`reserve`]: Vec::reserve
395 /// [`MaybeUninit`]: core::mem::MaybeUninit
396 /// [owned slice]: Box
397 #[stable(feature = "rust1", since = "1.0.0")]
398 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
399 #[rustc_insignificant_dtor]
400 pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
405 ////////////////////////////////////////////////////////////////////////////////
407 ////////////////////////////////////////////////////////////////////////////////
410 /// Constructs a new, empty `Vec<T>`.
412 /// The vector will not allocate until elements are pushed onto it.
417 /// # #![allow(unused_mut)]
418 /// let mut vec: Vec<i32> = Vec::new();
421 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
422 #[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 the specified capacity.
429 /// The vector will be able to hold exactly `capacity` elements without
430 /// reallocating. If `capacity` is 0, the vector will not allocate.
432 /// It is important to note that although the returned vector has the
433 /// *capacity* specified, the vector will have a zero *length*. For an
434 /// explanation of the difference between length and capacity, see
435 /// *[Capacity and reallocation]*.
437 /// [Capacity and reallocation]: #capacity-and-reallocation
441 /// Panics if the new capacity exceeds `isize::MAX` bytes.
446 /// let mut vec = Vec::with_capacity(10);
448 /// // The vector contains no items, even though it has capacity for more
449 /// assert_eq!(vec.len(), 0);
450 /// assert_eq!(vec.capacity(), 10);
452 /// // These are all done without reallocating...
456 /// assert_eq!(vec.len(), 10);
457 /// assert_eq!(vec.capacity(), 10);
459 /// // ...but this may make the vector reallocate
461 /// assert_eq!(vec.len(), 11);
462 /// assert!(vec.capacity() >= 11);
464 #[cfg(not(no_global_oom_handling))]
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub fn with_capacity(capacity: usize) -> Self {
468 Self::with_capacity_in(capacity, Global)
471 /// Creates a `Vec<T>` directly from the raw components of another vector.
475 /// This is highly unsafe, due to the number of invariants that aren't
478 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
479 /// (at least, it's highly likely to be incorrect if it wasn't).
480 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
481 /// (`T` having a less strict alignment is not sufficient, the alignment really
482 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
483 /// allocated and deallocated with the same layout.)
484 /// * `length` needs to be less than or equal to `capacity`.
485 /// * `capacity` needs to be the capacity that the pointer was allocated with.
487 /// Violating these may cause problems like corrupting the allocator's
488 /// internal data structures. For example it is **not** safe
489 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
490 /// It's also not safe to build one from a `Vec<u16>` and its length, because
491 /// the allocator cares about the alignment, and these two types have different
492 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
493 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
495 /// The ownership of `ptr` is effectively transferred to the
496 /// `Vec<T>` which may then deallocate, reallocate or change the
497 /// contents of memory pointed to by the pointer at will. Ensure
498 /// that nothing else uses the pointer after calling this
501 /// [`String`]: crate::string::String
502 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
510 /// let v = vec![1, 2, 3];
512 // FIXME Update this when vec_into_raw_parts is stabilized
513 /// // Prevent running `v`'s destructor so we are in complete control
514 /// // of the allocation.
515 /// let mut v = mem::ManuallyDrop::new(v);
517 /// // Pull out the various important pieces of information about `v`
518 /// let p = v.as_mut_ptr();
519 /// let len = v.len();
520 /// let cap = v.capacity();
523 /// // Overwrite memory with 4, 5, 6
524 /// for i in 0..len as isize {
525 /// ptr::write(p.offset(i), 4 + i);
528 /// // Put everything back together into a Vec
529 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
530 /// assert_eq!(rebuilt, [4, 5, 6]);
534 #[stable(feature = "rust1", since = "1.0.0")]
535 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
536 unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
540 impl<T, A: Allocator> Vec<T, A> {
541 /// Constructs a new, empty `Vec<T, A>`.
543 /// The vector will not allocate until elements are pushed onto it.
548 /// #![feature(allocator_api)]
550 /// use std::alloc::System;
552 /// # #[allow(unused_mut)]
553 /// let mut vec: Vec<i32, _> = Vec::new_in(System);
556 #[unstable(feature = "allocator_api", issue = "32838")]
557 pub const fn new_in(alloc: A) -> Self {
558 Vec { buf: RawVec::new_in(alloc), len: 0 }
561 /// Constructs a new, empty `Vec<T, A>` with the specified capacity with the provided
564 /// The vector will be able to hold exactly `capacity` elements without
565 /// reallocating. If `capacity` is 0, the vector will not allocate.
567 /// It is important to note that although the returned vector has the
568 /// *capacity* specified, the vector will have a zero *length*. For an
569 /// explanation of the difference between length and capacity, see
570 /// *[Capacity and reallocation]*.
572 /// [Capacity and reallocation]: #capacity-and-reallocation
576 /// Panics if the new capacity exceeds `isize::MAX` bytes.
581 /// #![feature(allocator_api)]
583 /// use std::alloc::System;
585 /// let mut vec = Vec::with_capacity_in(10, System);
587 /// // The vector contains no items, even though it has capacity for more
588 /// assert_eq!(vec.len(), 0);
589 /// assert_eq!(vec.capacity(), 10);
591 /// // These are all done without reallocating...
595 /// assert_eq!(vec.len(), 10);
596 /// assert_eq!(vec.capacity(), 10);
598 /// // ...but this may make the vector reallocate
600 /// assert_eq!(vec.len(), 11);
601 /// assert!(vec.capacity() >= 11);
603 #[cfg(not(no_global_oom_handling))]
605 #[unstable(feature = "allocator_api", issue = "32838")]
606 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
607 Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
610 /// Creates a `Vec<T, A>` directly from the raw components of another vector.
614 /// This is highly unsafe, due to the number of invariants that aren't
617 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
618 /// (at least, it's highly likely to be incorrect if it wasn't).
619 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
620 /// (`T` having a less strict alignment is not sufficient, the alignment really
621 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
622 /// allocated and deallocated with the same layout.)
623 /// * `length` needs to be less than or equal to `capacity`.
624 /// * `capacity` needs to be the capacity that the pointer was allocated with.
626 /// Violating these may cause problems like corrupting the allocator's
627 /// internal data structures. For example it is **not** safe
628 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
629 /// It's also not safe to build one from a `Vec<u16>` and its length, because
630 /// the allocator cares about the alignment, and these two types have different
631 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
632 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
634 /// The ownership of `ptr` is effectively transferred to the
635 /// `Vec<T>` which may then deallocate, reallocate or change the
636 /// contents of memory pointed to by the pointer at will. Ensure
637 /// that nothing else uses the pointer after calling this
640 /// [`String`]: crate::string::String
641 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
646 /// #![feature(allocator_api)]
648 /// use std::alloc::System;
653 /// let mut v = Vec::with_capacity_in(3, System);
658 // FIXME Update this when vec_into_raw_parts is stabilized
659 /// // Prevent running `v`'s destructor so we are in complete control
660 /// // of the allocation.
661 /// let mut v = mem::ManuallyDrop::new(v);
663 /// // Pull out the various important pieces of information about `v`
664 /// let p = v.as_mut_ptr();
665 /// let len = v.len();
666 /// let cap = v.capacity();
667 /// let alloc = v.allocator();
670 /// // Overwrite memory with 4, 5, 6
671 /// for i in 0..len as isize {
672 /// ptr::write(p.offset(i), 4 + i);
675 /// // Put everything back together into a Vec
676 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
677 /// assert_eq!(rebuilt, [4, 5, 6]);
681 #[unstable(feature = "allocator_api", issue = "32838")]
682 pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
683 unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
686 /// Decomposes a `Vec<T>` into its raw components.
688 /// Returns the raw pointer to the underlying data, the length of
689 /// the vector (in elements), and the allocated capacity of the
690 /// data (in elements). These are the same arguments in the same
691 /// order as the arguments to [`from_raw_parts`].
693 /// After calling this function, the caller is responsible for the
694 /// memory previously managed by the `Vec`. The only way to do
695 /// this is to convert the raw pointer, length, and capacity back
696 /// into a `Vec` with the [`from_raw_parts`] function, allowing
697 /// the destructor to perform the cleanup.
699 /// [`from_raw_parts`]: Vec::from_raw_parts
704 /// #![feature(vec_into_raw_parts)]
705 /// let v: Vec<i32> = vec![-1, 0, 1];
707 /// let (ptr, len, cap) = v.into_raw_parts();
709 /// let rebuilt = unsafe {
710 /// // We can now make changes to the components, such as
711 /// // transmuting the raw pointer to a compatible type.
712 /// let ptr = ptr as *mut u32;
714 /// Vec::from_raw_parts(ptr, len, cap)
716 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
718 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
719 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
720 let mut me = ManuallyDrop::new(self);
721 (me.as_mut_ptr(), me.len(), me.capacity())
724 /// Decomposes a `Vec<T>` into its raw components.
726 /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
727 /// the allocated capacity of the data (in elements), and the allocator. These are the same
728 /// arguments in the same order as the arguments to [`from_raw_parts_in`].
730 /// After calling this function, the caller is responsible for the
731 /// memory previously managed by the `Vec`. The only way to do
732 /// this is to convert the raw pointer, length, and capacity back
733 /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
734 /// the destructor to perform the cleanup.
736 /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
741 /// #![feature(allocator_api, vec_into_raw_parts)]
743 /// use std::alloc::System;
745 /// let mut v: Vec<i32, System> = Vec::new_in(System);
750 /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
752 /// let rebuilt = unsafe {
753 /// // We can now make changes to the components, such as
754 /// // transmuting the raw pointer to a compatible type.
755 /// let ptr = ptr as *mut u32;
757 /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
759 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
761 #[unstable(feature = "allocator_api", issue = "32838")]
762 // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
763 pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
764 let mut me = ManuallyDrop::new(self);
766 let capacity = me.capacity();
767 let ptr = me.as_mut_ptr();
768 let alloc = unsafe { ptr::read(me.allocator()) };
769 (ptr, len, capacity, alloc)
772 /// Returns the number of elements the vector can hold without
778 /// let vec: Vec<i32> = Vec::with_capacity(10);
779 /// assert_eq!(vec.capacity(), 10);
782 #[stable(feature = "rust1", since = "1.0.0")]
783 pub fn capacity(&self) -> usize {
787 /// Reserves capacity for at least `additional` more elements to be inserted
788 /// in the given `Vec<T>`. The collection may reserve more space to avoid
789 /// frequent reallocations. After calling `reserve`, capacity will be
790 /// greater than or equal to `self.len() + additional`. Does nothing if
791 /// capacity is already sufficient.
795 /// Panics if the new capacity exceeds `isize::MAX` bytes.
800 /// let mut vec = vec![1];
802 /// assert!(vec.capacity() >= 11);
804 #[cfg(not(no_global_oom_handling))]
805 #[stable(feature = "rust1", since = "1.0.0")]
806 pub fn reserve(&mut self, additional: usize) {
807 self.buf.reserve(self.len, additional);
810 /// Reserves the minimum capacity for exactly `additional` more elements to
811 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
812 /// capacity will be greater than or equal to `self.len() + additional`.
813 /// Does nothing if the capacity is already sufficient.
815 /// Note that the allocator may give the collection more space than it
816 /// requests. Therefore, capacity can not be relied upon to be precisely
817 /// minimal. Prefer [`reserve`] if future insertions are expected.
819 /// [`reserve`]: Vec::reserve
823 /// Panics if the new capacity overflows `usize`.
828 /// let mut vec = vec![1];
829 /// vec.reserve_exact(10);
830 /// assert!(vec.capacity() >= 11);
832 #[cfg(not(no_global_oom_handling))]
833 #[stable(feature = "rust1", since = "1.0.0")]
834 pub fn reserve_exact(&mut self, additional: usize) {
835 self.buf.reserve_exact(self.len, additional);
838 /// Tries to reserve capacity for at least `additional` more elements to be inserted
839 /// in the given `Vec<T>`. The collection may reserve more space to avoid
840 /// frequent reallocations. After calling `try_reserve`, capacity will be
841 /// greater than or equal to `self.len() + additional`. Does nothing if
842 /// capacity is already sufficient.
846 /// If the capacity overflows, or the allocator reports a failure, then an error
852 /// #![feature(try_reserve)]
853 /// use std::collections::TryReserveError;
855 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
856 /// let mut output = Vec::new();
858 /// // Pre-reserve the memory, exiting if we can't
859 /// output.try_reserve(data.len())?;
861 /// // Now we know this can't OOM in the middle of our complex work
862 /// output.extend(data.iter().map(|&val| {
863 /// val * 2 + 5 // very complicated
868 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
870 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
871 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
872 self.buf.try_reserve(self.len, additional)
875 /// Tries to reserve the minimum capacity for exactly `additional`
876 /// elements to be inserted in the given `Vec<T>`. After calling
877 /// `try_reserve_exact`, capacity will be greater than or equal to
878 /// `self.len() + additional` if it returns `Ok(())`.
879 /// Does nothing if the capacity is already sufficient.
881 /// Note that the allocator may give the collection more space than it
882 /// requests. Therefore, capacity can not be relied upon to be precisely
883 /// minimal. Prefer [`reserve`] if future insertions are expected.
885 /// [`reserve`]: Vec::reserve
889 /// If the capacity overflows, or the allocator reports a failure, then an error
895 /// #![feature(try_reserve)]
896 /// use std::collections::TryReserveError;
898 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
899 /// let mut output = Vec::new();
901 /// // Pre-reserve the memory, exiting if we can't
902 /// output.try_reserve_exact(data.len())?;
904 /// // Now we know this can't OOM in the middle of our complex work
905 /// output.extend(data.iter().map(|&val| {
906 /// val * 2 + 5 // very complicated
911 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
913 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
914 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
915 self.buf.try_reserve_exact(self.len, additional)
918 /// Shrinks the capacity of the vector as much as possible.
920 /// It will drop down as close as possible to the length but the allocator
921 /// may still inform the vector that there is space for a few more elements.
926 /// let mut vec = Vec::with_capacity(10);
927 /// vec.extend([1, 2, 3]);
928 /// assert_eq!(vec.capacity(), 10);
929 /// vec.shrink_to_fit();
930 /// assert!(vec.capacity() >= 3);
932 #[cfg(not(no_global_oom_handling))]
933 #[stable(feature = "rust1", since = "1.0.0")]
934 pub fn shrink_to_fit(&mut self) {
935 // The capacity is never less than the length, and there's nothing to do when
936 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
937 // by only calling it with a greater capacity.
938 if self.capacity() > self.len {
939 self.buf.shrink_to_fit(self.len);
943 /// Shrinks the capacity of the vector with a lower bound.
945 /// The capacity will remain at least as large as both the length
946 /// and the supplied value.
948 /// If the current capacity is less than the lower limit, this is a no-op.
953 /// let mut vec = Vec::with_capacity(10);
954 /// vec.extend([1, 2, 3]);
955 /// assert_eq!(vec.capacity(), 10);
956 /// vec.shrink_to(4);
957 /// assert!(vec.capacity() >= 4);
958 /// vec.shrink_to(0);
959 /// assert!(vec.capacity() >= 3);
961 #[cfg(not(no_global_oom_handling))]
962 #[stable(feature = "shrink_to", since = "1.56.0")]
963 pub fn shrink_to(&mut self, min_capacity: usize) {
964 if self.capacity() > min_capacity {
965 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
969 /// Converts the vector into [`Box<[T]>`][owned slice].
971 /// Note that this will drop any excess capacity.
973 /// [owned slice]: Box
978 /// let v = vec![1, 2, 3];
980 /// let slice = v.into_boxed_slice();
983 /// Any excess capacity is removed:
986 /// let mut vec = Vec::with_capacity(10);
987 /// vec.extend([1, 2, 3]);
989 /// assert_eq!(vec.capacity(), 10);
990 /// let slice = vec.into_boxed_slice();
991 /// assert_eq!(slice.into_vec().capacity(), 3);
993 #[cfg(not(no_global_oom_handling))]
994 #[stable(feature = "rust1", since = "1.0.0")]
995 pub fn into_boxed_slice(mut self) -> Box<[T], A> {
997 self.shrink_to_fit();
998 let me = ManuallyDrop::new(self);
999 let buf = ptr::read(&me.buf);
1001 buf.into_box(len).assume_init()
1005 /// Shortens the vector, keeping the first `len` elements and dropping
1008 /// If `len` is greater than the vector's current length, this has no
1011 /// The [`drain`] method can emulate `truncate`, but causes the excess
1012 /// elements to be returned instead of dropped.
1014 /// Note that this method has no effect on the allocated capacity
1019 /// Truncating a five element vector to two elements:
1022 /// let mut vec = vec![1, 2, 3, 4, 5];
1023 /// vec.truncate(2);
1024 /// assert_eq!(vec, [1, 2]);
1027 /// No truncation occurs when `len` is greater than the vector's current
1031 /// let mut vec = vec![1, 2, 3];
1032 /// vec.truncate(8);
1033 /// assert_eq!(vec, [1, 2, 3]);
1036 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
1040 /// let mut vec = vec![1, 2, 3];
1041 /// vec.truncate(0);
1042 /// assert_eq!(vec, []);
1045 /// [`clear`]: Vec::clear
1046 /// [`drain`]: Vec::drain
1047 #[stable(feature = "rust1", since = "1.0.0")]
1048 pub fn truncate(&mut self, len: usize) {
1049 // This is safe because:
1051 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
1052 // case avoids creating an invalid slice, and
1053 // * the `len` of the vector is shrunk before calling `drop_in_place`,
1054 // such that no value will be dropped twice in case `drop_in_place`
1055 // were to panic once (if it panics twice, the program aborts).
1057 // Note: It's intentional that this is `>` and not `>=`.
1058 // Changing it to `>=` has negative performance
1059 // implications in some cases. See #78884 for more.
1063 let remaining_len = self.len - len;
1064 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
1066 ptr::drop_in_place(s);
1070 /// Extracts a slice containing the entire vector.
1072 /// Equivalent to `&s[..]`.
1077 /// use std::io::{self, Write};
1078 /// let buffer = vec![1, 2, 3, 5, 8];
1079 /// io::sink().write(buffer.as_slice()).unwrap();
1082 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1083 pub fn as_slice(&self) -> &[T] {
1087 /// Extracts a mutable slice of the entire vector.
1089 /// Equivalent to `&mut s[..]`.
1094 /// use std::io::{self, Read};
1095 /// let mut buffer = vec![0; 3];
1096 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1099 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1100 pub fn as_mut_slice(&mut self) -> &mut [T] {
1104 /// Returns a raw pointer to the vector's buffer.
1106 /// The caller must ensure that the vector outlives the pointer this
1107 /// function returns, or else it will end up pointing to garbage.
1108 /// Modifying the vector may cause its buffer to be reallocated,
1109 /// which would also make any pointers to it invalid.
1111 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1112 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1113 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1118 /// let x = vec![1, 2, 4];
1119 /// let x_ptr = x.as_ptr();
1122 /// for i in 0..x.len() {
1123 /// assert_eq!(*x_ptr.add(i), 1 << i);
1128 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1129 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1131 pub fn as_ptr(&self) -> *const T {
1132 // We shadow the slice method of the same name to avoid going through
1133 // `deref`, which creates an intermediate reference.
1134 let ptr = self.buf.ptr();
1136 assume(!ptr.is_null());
1141 /// Returns an unsafe mutable pointer to the vector's buffer.
1143 /// The caller must ensure that the vector outlives the pointer this
1144 /// function returns, or else it will end up pointing to garbage.
1145 /// Modifying the vector may cause its buffer to be reallocated,
1146 /// which would also make any pointers to it invalid.
1151 /// // Allocate vector big enough for 4 elements.
1153 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1154 /// let x_ptr = x.as_mut_ptr();
1156 /// // Initialize elements via raw pointer writes, then set length.
1158 /// for i in 0..size {
1159 /// *x_ptr.add(i) = i as i32;
1161 /// x.set_len(size);
1163 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1165 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1167 pub fn as_mut_ptr(&mut self) -> *mut T {
1168 // We shadow the slice method of the same name to avoid going through
1169 // `deref_mut`, which creates an intermediate reference.
1170 let ptr = self.buf.ptr();
1172 assume(!ptr.is_null());
1177 /// Returns a reference to the underlying allocator.
1178 #[unstable(feature = "allocator_api", issue = "32838")]
1180 pub fn allocator(&self) -> &A {
1181 self.buf.allocator()
1184 /// Forces the length of the vector to `new_len`.
1186 /// This is a low-level operation that maintains none of the normal
1187 /// invariants of the type. Normally changing the length of a vector
1188 /// is done using one of the safe operations instead, such as
1189 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
1191 /// [`truncate`]: Vec::truncate
1192 /// [`resize`]: Vec::resize
1193 /// [`extend`]: Extend::extend
1194 /// [`clear`]: Vec::clear
1198 /// - `new_len` must be less than or equal to [`capacity()`].
1199 /// - The elements at `old_len..new_len` must be initialized.
1201 /// [`capacity()`]: Vec::capacity
1205 /// This method can be useful for situations in which the vector
1206 /// is serving as a buffer for other code, particularly over FFI:
1209 /// # #![allow(dead_code)]
1210 /// # // This is just a minimal skeleton for the doc example;
1211 /// # // don't use this as a starting point for a real library.
1212 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
1213 /// # const Z_OK: i32 = 0;
1215 /// # fn deflateGetDictionary(
1216 /// # strm: *mut std::ffi::c_void,
1217 /// # dictionary: *mut u8,
1218 /// # dictLength: *mut usize,
1221 /// # impl StreamWrapper {
1222 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
1223 /// // Per the FFI method's docs, "32768 bytes is always enough".
1224 /// let mut dict = Vec::with_capacity(32_768);
1225 /// let mut dict_length = 0;
1226 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
1227 /// // 1. `dict_length` elements were initialized.
1228 /// // 2. `dict_length` <= the capacity (32_768)
1229 /// // which makes `set_len` safe to call.
1231 /// // Make the FFI call...
1232 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
1234 /// // ...and update the length to what was initialized.
1235 /// dict.set_len(dict_length);
1245 /// While the following example is sound, there is a memory leak since
1246 /// the inner vectors were not freed prior to the `set_len` call:
1249 /// let mut vec = vec![vec![1, 0, 0],
1253 /// // 1. `old_len..0` is empty so no elements need to be initialized.
1254 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
1260 /// Normally, here, one would use [`clear`] instead to correctly drop
1261 /// the contents and thus not leak memory.
1263 #[stable(feature = "rust1", since = "1.0.0")]
1264 pub unsafe fn set_len(&mut self, new_len: usize) {
1265 debug_assert!(new_len <= self.capacity());
1270 /// Removes an element from the vector and returns it.
1272 /// The removed element is replaced by the last element of the vector.
1274 /// This does not preserve ordering, but is *O*(1).
1278 /// Panics if `index` is out of bounds.
1283 /// let mut v = vec!["foo", "bar", "baz", "qux"];
1285 /// assert_eq!(v.swap_remove(1), "bar");
1286 /// assert_eq!(v, ["foo", "qux", "baz"]);
1288 /// assert_eq!(v.swap_remove(0), "foo");
1289 /// assert_eq!(v, ["baz", "qux"]);
1292 #[stable(feature = "rust1", since = "1.0.0")]
1293 pub fn swap_remove(&mut self, index: usize) -> T {
1296 fn assert_failed(index: usize, len: usize) -> ! {
1297 panic!("swap_remove index (is {}) should be < len (is {})", index, len);
1300 let len = self.len();
1302 assert_failed(index, len);
1305 // We replace self[index] with the last element. Note that if the
1306 // bounds check above succeeds there must be a last element (which
1307 // can be self[index] itself).
1308 let last = ptr::read(self.as_ptr().add(len - 1));
1309 let hole = self.as_mut_ptr().add(index);
1310 self.set_len(len - 1);
1311 ptr::replace(hole, last)
1315 /// Inserts an element at position `index` within the vector, shifting all
1316 /// elements after it to the right.
1320 /// Panics if `index > len`.
1325 /// let mut vec = vec![1, 2, 3];
1326 /// vec.insert(1, 4);
1327 /// assert_eq!(vec, [1, 4, 2, 3]);
1328 /// vec.insert(4, 5);
1329 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1331 #[cfg(not(no_global_oom_handling))]
1332 #[stable(feature = "rust1", since = "1.0.0")]
1333 pub fn insert(&mut self, index: usize, element: T) {
1336 fn assert_failed(index: usize, len: usize) -> ! {
1337 panic!("insertion index (is {}) should be <= len (is {})", index, len);
1340 let len = self.len();
1342 assert_failed(index, len);
1345 // space for the new element
1346 if len == self.buf.capacity() {
1352 // The spot to put the new value
1354 let p = self.as_mut_ptr().add(index);
1355 // Shift everything over to make space. (Duplicating the
1356 // `index`th element into two consecutive places.)
1357 ptr::copy(p, p.offset(1), len - index);
1358 // Write it in, overwriting the first copy of the `index`th
1360 ptr::write(p, element);
1362 self.set_len(len + 1);
1366 /// Removes and returns the element at position `index` within the vector,
1367 /// shifting all elements after it to the left.
1369 /// Note: Because this shifts over the remaining elements, it has a
1370 /// worst-case performance of O(n). If you don't need the order of elements
1371 /// to be preserved, use [`swap_remove`] instead.
1373 /// [`swap_remove`]: Vec::swap_remove
1377 /// Panics if `index` is out of bounds.
1382 /// let mut v = vec![1, 2, 3];
1383 /// assert_eq!(v.remove(1), 2);
1384 /// assert_eq!(v, [1, 3]);
1386 #[stable(feature = "rust1", since = "1.0.0")]
1388 pub fn remove(&mut self, index: usize) -> T {
1392 fn assert_failed(index: usize, len: usize) -> ! {
1393 panic!("removal index (is {}) should be < len (is {})", index, len);
1396 let len = self.len();
1398 assert_failed(index, len);
1404 // the place we are taking from.
1405 let ptr = self.as_mut_ptr().add(index);
1406 // copy it out, unsafely having a copy of the value on
1407 // the stack and in the vector at the same time.
1408 ret = ptr::read(ptr);
1410 // Shift everything down to fill in that spot.
1411 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1413 self.set_len(len - 1);
1418 /// Retains only the elements specified by the predicate.
1420 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1421 /// This method operates in place, visiting each element exactly once in the
1422 /// original order, and preserves the order of the retained elements.
1427 /// let mut vec = vec![1, 2, 3, 4];
1428 /// vec.retain(|&x| x % 2 == 0);
1429 /// assert_eq!(vec, [2, 4]);
1432 /// Because the elements are visited exactly once in the original order,
1433 /// external state may be used to decide which elements to keep.
1436 /// let mut vec = vec![1, 2, 3, 4, 5];
1437 /// let keep = [false, true, true, false, true];
1438 /// let mut iter = keep.iter();
1439 /// vec.retain(|_| *iter.next().unwrap());
1440 /// assert_eq!(vec, [2, 3, 5]);
1442 #[stable(feature = "rust1", since = "1.0.0")]
1443 pub fn retain<F>(&mut self, mut f: F)
1445 F: FnMut(&T) -> bool,
1447 let original_len = self.len();
1448 // Avoid double drop if the drop guard is not executed,
1449 // since we may make some holes during the process.
1450 unsafe { self.set_len(0) };
1452 // Vec: [Kept, Kept, Hole, Hole, Hole, Hole, Unchecked, Unchecked]
1453 // |<- processed len ->| ^- next to check
1454 // |<- deleted cnt ->|
1455 // |<- original_len ->|
1456 // Kept: Elements which predicate returns true on.
1457 // Hole: Moved or dropped element slot.
1458 // Unchecked: Unchecked valid elements.
1460 // This drop guard will be invoked when predicate or `drop` of element panicked.
1461 // It shifts unchecked elements to cover holes and `set_len` to the correct length.
1462 // In cases when predicate and `drop` never panick, it will be optimized out.
1463 struct BackshiftOnDrop<'a, T, A: Allocator> {
1464 v: &'a mut Vec<T, A>,
1465 processed_len: usize,
1467 original_len: usize,
1470 impl<T, A: Allocator> Drop for BackshiftOnDrop<'_, T, A> {
1471 fn drop(&mut self) {
1472 if self.deleted_cnt > 0 {
1473 // SAFETY: Trailing unchecked items must be valid since we never touch them.
1476 self.v.as_ptr().add(self.processed_len),
1477 self.v.as_mut_ptr().add(self.processed_len - self.deleted_cnt),
1478 self.original_len - self.processed_len,
1482 // SAFETY: After filling holes, all items are in contiguous memory.
1484 self.v.set_len(self.original_len - self.deleted_cnt);
1489 let mut g = BackshiftOnDrop { v: self, processed_len: 0, deleted_cnt: 0, original_len };
1491 while g.processed_len < original_len {
1492 // SAFETY: Unchecked element must be valid.
1493 let cur = unsafe { &mut *g.v.as_mut_ptr().add(g.processed_len) };
1495 // Advance early to avoid double drop if `drop_in_place` panicked.
1496 g.processed_len += 1;
1498 // SAFETY: We never touch this element again after dropped.
1499 unsafe { ptr::drop_in_place(cur) };
1500 // We already advanced the counter.
1503 if g.deleted_cnt > 0 {
1504 // SAFETY: `deleted_cnt` > 0, so the hole slot must not overlap with current element.
1505 // We use copy for move, and never touch this element again.
1507 let hole_slot = g.v.as_mut_ptr().add(g.processed_len - g.deleted_cnt);
1508 ptr::copy_nonoverlapping(cur, hole_slot, 1);
1511 g.processed_len += 1;
1514 // All item are processed. This can be optimized to `set_len` by LLVM.
1518 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1521 /// If the vector is sorted, this removes all duplicates.
1526 /// let mut vec = vec![10, 20, 21, 30, 20];
1528 /// vec.dedup_by_key(|i| *i / 10);
1530 /// assert_eq!(vec, [10, 20, 30, 20]);
1532 #[stable(feature = "dedup_by", since = "1.16.0")]
1534 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1536 F: FnMut(&mut T) -> K,
1539 self.dedup_by(|a, b| key(a) == key(b))
1542 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1545 /// The `same_bucket` function is passed references to two elements from the vector and
1546 /// must determine if the elements compare equal. The elements are passed in opposite order
1547 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1549 /// If the vector is sorted, this removes all duplicates.
1554 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1556 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1558 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1560 #[stable(feature = "dedup_by", since = "1.16.0")]
1561 pub fn dedup_by<F>(&mut self, mut same_bucket: F)
1563 F: FnMut(&mut T, &mut T) -> bool,
1565 let len = self.len();
1570 /* INVARIANT: vec.len() > read >= write > write-1 >= 0 */
1571 struct FillGapOnDrop<'a, T, A: core::alloc::Allocator> {
1572 /* Offset of the element we want to check if it is duplicate */
1575 /* Offset of the place where we want to place the non-duplicate
1576 * when we find it. */
1579 /* The Vec that would need correction if `same_bucket` panicked */
1580 vec: &'a mut Vec<T, A>,
1583 impl<'a, T, A: core::alloc::Allocator> Drop for FillGapOnDrop<'a, T, A> {
1584 fn drop(&mut self) {
1585 /* This code gets executed when `same_bucket` panics */
1587 /* SAFETY: invariant guarantees that `read - write`
1588 * and `len - read` never overflow and that the copy is always
1591 let ptr = self.vec.as_mut_ptr();
1592 let len = self.vec.len();
1594 /* How many items were left when `same_bucket` paniced.
1595 * Basically vec[read..].len() */
1596 let items_left = len.wrapping_sub(self.read);
1598 /* Pointer to first item in vec[write..write+items_left] slice */
1599 let dropped_ptr = ptr.add(self.write);
1600 /* Pointer to first item in vec[read..] slice */
1601 let valid_ptr = ptr.add(self.read);
1603 /* Copy `vec[read..]` to `vec[write..write+items_left]`.
1604 * The slices can overlap, so `copy_nonoverlapping` cannot be used */
1605 ptr::copy(valid_ptr, dropped_ptr, items_left);
1607 /* How many items have been already dropped
1608 * Basically vec[read..write].len() */
1609 let dropped = self.read.wrapping_sub(self.write);
1611 self.vec.set_len(len - dropped);
1616 let mut gap = FillGapOnDrop { read: 1, write: 1, vec: self };
1617 let ptr = gap.vec.as_mut_ptr();
1619 /* Drop items while going through Vec, it should be more efficient than
1620 * doing slice partition_dedup + truncate */
1622 /* SAFETY: Because of the invariant, read_ptr, prev_ptr and write_ptr
1623 * are always in-bounds and read_ptr never aliases prev_ptr */
1625 while gap.read < len {
1626 let read_ptr = ptr.add(gap.read);
1627 let prev_ptr = ptr.add(gap.write.wrapping_sub(1));
1629 if same_bucket(&mut *read_ptr, &mut *prev_ptr) {
1630 // Increase `gap.read` now since the drop may panic.
1632 /* We have found duplicate, drop it in-place */
1633 ptr::drop_in_place(read_ptr);
1635 let write_ptr = ptr.add(gap.write);
1637 /* Because `read_ptr` can be equal to `write_ptr`, we either
1638 * have to use `copy` or conditional `copy_nonoverlapping`.
1639 * Looks like the first option is faster. */
1640 ptr::copy(read_ptr, write_ptr, 1);
1642 /* We have filled that place, so go further */
1648 /* Technically we could let `gap` clean up with its Drop, but
1649 * when `same_bucket` is guaranteed to not panic, this bloats a little
1650 * the codegen, so we just do it manually */
1651 gap.vec.set_len(gap.write);
1656 /// Appends an element to the back of a collection.
1660 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1665 /// let mut vec = vec![1, 2];
1667 /// assert_eq!(vec, [1, 2, 3]);
1669 #[cfg(not(no_global_oom_handling))]
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 pub fn push(&mut self, value: T) {
1673 // This will panic or abort if we would allocate > isize::MAX bytes
1674 // or if the length increment would overflow for zero-sized types.
1675 if self.len == self.buf.capacity() {
1679 let end = self.as_mut_ptr().add(self.len);
1680 ptr::write(end, value);
1685 /// Removes the last element from a vector and returns it, or [`None`] if it
1691 /// let mut vec = vec![1, 2, 3];
1692 /// assert_eq!(vec.pop(), Some(3));
1693 /// assert_eq!(vec, [1, 2]);
1696 #[stable(feature = "rust1", since = "1.0.0")]
1697 pub fn pop(&mut self) -> Option<T> {
1703 Some(ptr::read(self.as_ptr().add(self.len())))
1708 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1712 /// Panics if the number of elements in the vector overflows a `usize`.
1717 /// let mut vec = vec![1, 2, 3];
1718 /// let mut vec2 = vec![4, 5, 6];
1719 /// vec.append(&mut vec2);
1720 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1721 /// assert_eq!(vec2, []);
1723 #[cfg(not(no_global_oom_handling))]
1725 #[stable(feature = "append", since = "1.4.0")]
1726 pub fn append(&mut self, other: &mut Self) {
1728 self.append_elements(other.as_slice() as _);
1733 /// Appends elements to `Self` from other buffer.
1734 #[cfg(not(no_global_oom_handling))]
1736 unsafe fn append_elements(&mut self, other: *const [T]) {
1737 let count = unsafe { (*other).len() };
1738 self.reserve(count);
1739 let len = self.len();
1740 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1744 /// Creates a draining iterator that removes the specified range in the vector
1745 /// and yields the removed items.
1747 /// When the iterator **is** dropped, all elements in the range are removed
1748 /// from the vector, even if the iterator was not fully consumed. If the
1749 /// iterator **is not** dropped (with [`mem::forget`] for example), it is
1750 /// unspecified how many elements are removed.
1754 /// Panics if the starting point is greater than the end point or if
1755 /// the end point is greater than the length of the vector.
1760 /// let mut v = vec![1, 2, 3];
1761 /// let u: Vec<_> = v.drain(1..).collect();
1762 /// assert_eq!(v, &[1]);
1763 /// assert_eq!(u, &[2, 3]);
1765 /// // A full range clears the vector
1767 /// assert_eq!(v, &[]);
1769 #[stable(feature = "drain", since = "1.6.0")]
1770 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1772 R: RangeBounds<usize>,
1776 // When the Drain is first created, it shortens the length of
1777 // the source vector to make sure no uninitialized or moved-from elements
1778 // are accessible at all if the Drain's destructor never gets to run.
1780 // Drain will ptr::read out the values to remove.
1781 // When finished, remaining tail of the vec is copied back to cover
1782 // the hole, and the vector length is restored to the new length.
1784 let len = self.len();
1785 let Range { start, end } = slice::range(range, ..len);
1788 // set self.vec length's to start, to be safe in case Drain is leaked
1789 self.set_len(start);
1790 // Use the borrow in the IterMut to indicate borrowing behavior of the
1791 // whole Drain iterator (like &mut T).
1792 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1795 tail_len: len - end,
1796 iter: range_slice.iter(),
1797 vec: NonNull::from(self),
1802 /// Clears the vector, removing all values.
1804 /// Note that this method has no effect on the allocated capacity
1810 /// let mut v = vec![1, 2, 3];
1814 /// assert!(v.is_empty());
1817 #[stable(feature = "rust1", since = "1.0.0")]
1818 pub fn clear(&mut self) {
1822 /// Returns the number of elements in the vector, also referred to
1823 /// as its 'length'.
1828 /// let a = vec![1, 2, 3];
1829 /// assert_eq!(a.len(), 3);
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 pub fn len(&self) -> usize {
1837 /// Returns `true` if the vector contains no elements.
1842 /// let mut v = Vec::new();
1843 /// assert!(v.is_empty());
1846 /// assert!(!v.is_empty());
1848 #[stable(feature = "rust1", since = "1.0.0")]
1849 pub fn is_empty(&self) -> bool {
1853 /// Splits the collection into two at the given index.
1855 /// Returns a newly allocated vector containing the elements in the range
1856 /// `[at, len)`. After the call, the original vector will be left containing
1857 /// the elements `[0, at)` with its previous capacity unchanged.
1861 /// Panics if `at > len`.
1866 /// let mut vec = vec![1, 2, 3];
1867 /// let vec2 = vec.split_off(1);
1868 /// assert_eq!(vec, [1]);
1869 /// assert_eq!(vec2, [2, 3]);
1871 #[cfg(not(no_global_oom_handling))]
1873 #[must_use = "use `.truncate()` if you don't need the other half"]
1874 #[stable(feature = "split_off", since = "1.4.0")]
1875 pub fn split_off(&mut self, at: usize) -> Self
1881 fn assert_failed(at: usize, len: usize) -> ! {
1882 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1885 if at > self.len() {
1886 assert_failed(at, self.len());
1890 // the new vector can take over the original buffer and avoid the copy
1891 return mem::replace(
1893 Vec::with_capacity_in(self.capacity(), self.allocator().clone()),
1897 let other_len = self.len - at;
1898 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
1900 // Unsafely `set_len` and copy items to `other`.
1903 other.set_len(other_len);
1905 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1910 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1912 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1913 /// difference, with each additional slot filled with the result of
1914 /// calling the closure `f`. The return values from `f` will end up
1915 /// in the `Vec` in the order they have been generated.
1917 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1919 /// This method uses a closure to create new values on every push. If
1920 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
1921 /// want to use the [`Default`] trait to generate values, you can
1922 /// pass [`Default::default`] as the second argument.
1927 /// let mut vec = vec![1, 2, 3];
1928 /// vec.resize_with(5, Default::default);
1929 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1931 /// let mut vec = vec![];
1933 /// vec.resize_with(4, || { p *= 2; p });
1934 /// assert_eq!(vec, [2, 4, 8, 16]);
1936 #[cfg(not(no_global_oom_handling))]
1937 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1938 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1942 let len = self.len();
1944 self.extend_with(new_len - len, ExtendFunc(f));
1946 self.truncate(new_len);
1950 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1951 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1952 /// `'a`. If the type has only static references, or none at all, then this
1953 /// may be chosen to be `'static`.
1955 /// This function is similar to the [`leak`][Box::leak] function on [`Box`]
1956 /// except that there is no way to recover the leaked memory.
1958 /// This function is mainly useful for data that lives for the remainder of
1959 /// the program's life. Dropping the returned reference will cause a memory
1967 /// let x = vec![1, 2, 3];
1968 /// let static_ref: &'static mut [usize] = x.leak();
1969 /// static_ref[0] += 1;
1970 /// assert_eq!(static_ref, &[2, 2, 3]);
1972 #[cfg(not(no_global_oom_handling))]
1973 #[stable(feature = "vec_leak", since = "1.47.0")]
1975 pub fn leak<'a>(self) -> &'a mut [T]
1979 Box::leak(self.into_boxed_slice())
1982 /// Returns the remaining spare capacity of the vector as a slice of
1983 /// `MaybeUninit<T>`.
1985 /// The returned slice can be used to fill the vector with data (e.g. by
1986 /// reading from a file) before marking the data as initialized using the
1987 /// [`set_len`] method.
1989 /// [`set_len`]: Vec::set_len
1994 /// #![feature(vec_spare_capacity, maybe_uninit_extra)]
1996 /// // Allocate vector big enough for 10 elements.
1997 /// let mut v = Vec::with_capacity(10);
1999 /// // Fill in the first 3 elements.
2000 /// let uninit = v.spare_capacity_mut();
2001 /// uninit[0].write(0);
2002 /// uninit[1].write(1);
2003 /// uninit[2].write(2);
2005 /// // Mark the first 3 elements of the vector as being initialized.
2010 /// assert_eq!(&v, &[0, 1, 2]);
2012 #[unstable(feature = "vec_spare_capacity", issue = "75017")]
2014 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
2016 // This method is not implemented in terms of `split_at_spare_mut`,
2017 // to prevent invalidation of pointers to the buffer.
2019 slice::from_raw_parts_mut(
2020 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
2021 self.buf.capacity() - self.len,
2026 /// Returns vector content as a slice of `T`, along with the remaining spare
2027 /// capacity of the vector as a slice of `MaybeUninit<T>`.
2029 /// The returned spare capacity slice can be used to fill the vector with data
2030 /// (e.g. by reading from a file) before marking the data as initialized using
2031 /// the [`set_len`] method.
2033 /// [`set_len`]: Vec::set_len
2035 /// Note that this is a low-level API, which should be used with care for
2036 /// optimization purposes. If you need to append data to a `Vec`
2037 /// you can use [`push`], [`extend`], [`extend_from_slice`],
2038 /// [`extend_from_within`], [`insert`], [`append`], [`resize`] or
2039 /// [`resize_with`], depending on your exact needs.
2041 /// [`push`]: Vec::push
2042 /// [`extend`]: Vec::extend
2043 /// [`extend_from_slice`]: Vec::extend_from_slice
2044 /// [`extend_from_within`]: Vec::extend_from_within
2045 /// [`insert`]: Vec::insert
2046 /// [`append`]: Vec::append
2047 /// [`resize`]: Vec::resize
2048 /// [`resize_with`]: Vec::resize_with
2053 /// #![feature(vec_split_at_spare, maybe_uninit_extra)]
2055 /// let mut v = vec![1, 1, 2];
2057 /// // Reserve additional space big enough for 10 elements.
2060 /// let (init, uninit) = v.split_at_spare_mut();
2061 /// let sum = init.iter().copied().sum::<u32>();
2063 /// // Fill in the next 4 elements.
2064 /// uninit[0].write(sum);
2065 /// uninit[1].write(sum * 2);
2066 /// uninit[2].write(sum * 3);
2067 /// uninit[3].write(sum * 4);
2069 /// // Mark the 4 elements of the vector as being initialized.
2071 /// let len = v.len();
2072 /// v.set_len(len + 4);
2075 /// assert_eq!(&v, &[1, 1, 2, 4, 8, 12, 16]);
2077 #[unstable(feature = "vec_split_at_spare", issue = "81944")]
2079 pub fn split_at_spare_mut(&mut self) -> (&mut [T], &mut [MaybeUninit<T>]) {
2081 // - len is ignored and so never changed
2082 let (init, spare, _) = unsafe { self.split_at_spare_mut_with_len() };
2086 /// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
2088 /// This method provides unique access to all vec parts at once in `extend_from_within`.
2089 unsafe fn split_at_spare_mut_with_len(
2091 ) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
2092 let Range { start: ptr, end: spare_ptr } = self.as_mut_ptr_range();
2093 let spare_ptr = spare_ptr.cast::<MaybeUninit<T>>();
2094 let spare_len = self.buf.capacity() - self.len;
2097 // - `ptr` is guaranteed to be valid for `len` elements
2098 // - `spare_ptr` is pointing one element past the buffer, so it doesn't overlap with `initialized`
2100 let initialized = slice::from_raw_parts_mut(ptr, self.len);
2101 let spare = slice::from_raw_parts_mut(spare_ptr, spare_len);
2103 (initialized, spare, &mut self.len)
2108 impl<T: Clone, A: Allocator> Vec<T, A> {
2109 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
2111 /// If `new_len` is greater than `len`, the `Vec` is extended by the
2112 /// difference, with each additional slot filled with `value`.
2113 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
2115 /// This method requires `T` to implement [`Clone`],
2116 /// in order to be able to clone the passed value.
2117 /// If you need more flexibility (or want to rely on [`Default`] instead of
2118 /// [`Clone`]), use [`Vec::resize_with`].
2123 /// let mut vec = vec!["hello"];
2124 /// vec.resize(3, "world");
2125 /// assert_eq!(vec, ["hello", "world", "world"]);
2127 /// let mut vec = vec![1, 2, 3, 4];
2128 /// vec.resize(2, 0);
2129 /// assert_eq!(vec, [1, 2]);
2131 #[cfg(not(no_global_oom_handling))]
2132 #[stable(feature = "vec_resize", since = "1.5.0")]
2133 pub fn resize(&mut self, new_len: usize, value: T) {
2134 let len = self.len();
2137 self.extend_with(new_len - len, ExtendElement(value))
2139 self.truncate(new_len);
2143 /// Clones and appends all elements in a slice to the `Vec`.
2145 /// Iterates over the slice `other`, clones each element, and then appends
2146 /// it to this `Vec`. The `other` vector is traversed in-order.
2148 /// Note that this function is same as [`extend`] except that it is
2149 /// specialized to work with slices instead. If and when Rust gets
2150 /// specialization this function will likely be deprecated (but still
2156 /// let mut vec = vec![1];
2157 /// vec.extend_from_slice(&[2, 3, 4]);
2158 /// assert_eq!(vec, [1, 2, 3, 4]);
2161 /// [`extend`]: Vec::extend
2162 #[cfg(not(no_global_oom_handling))]
2163 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
2164 pub fn extend_from_slice(&mut self, other: &[T]) {
2165 self.spec_extend(other.iter())
2168 /// Copies elements from `src` range to the end of the vector.
2173 /// let mut vec = vec![0, 1, 2, 3, 4];
2175 /// vec.extend_from_within(2..);
2176 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4]);
2178 /// vec.extend_from_within(..2);
2179 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1]);
2181 /// vec.extend_from_within(4..8);
2182 /// assert_eq!(vec, [0, 1, 2, 3, 4, 2, 3, 4, 0, 1, 4, 2, 3, 4]);
2184 #[cfg(not(no_global_oom_handling))]
2185 #[stable(feature = "vec_extend_from_within", since = "1.53.0")]
2186 pub fn extend_from_within<R>(&mut self, src: R)
2188 R: RangeBounds<usize>,
2190 let range = slice::range(src, ..self.len());
2191 self.reserve(range.len());
2194 // - `slice::range` guarantees that the given range is valid for indexing self
2196 self.spec_extend_from_within(range);
2201 // This code generalizes `extend_with_{element,default}`.
2202 trait ExtendWith<T> {
2203 fn next(&mut self) -> T;
2207 struct ExtendElement<T>(T);
2208 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
2209 fn next(&mut self) -> T {
2212 fn last(self) -> T {
2217 struct ExtendDefault;
2218 impl<T: Default> ExtendWith<T> for ExtendDefault {
2219 fn next(&mut self) -> T {
2222 fn last(self) -> T {
2227 struct ExtendFunc<F>(F);
2228 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
2229 fn next(&mut self) -> T {
2232 fn last(mut self) -> T {
2237 impl<T, A: Allocator> Vec<T, A> {
2238 #[cfg(not(no_global_oom_handling))]
2239 /// Extend the vector by `n` values, using the given generator.
2240 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
2244 let mut ptr = self.as_mut_ptr().add(self.len());
2245 // Use SetLenOnDrop to work around bug where compiler
2246 // might not realize the store through `ptr` through self.set_len()
2248 let mut local_len = SetLenOnDrop::new(&mut self.len);
2250 // Write all elements except the last one
2252 ptr::write(ptr, value.next());
2253 ptr = ptr.offset(1);
2254 // Increment the length in every step in case next() panics
2255 local_len.increment_len(1);
2259 // We can write the last element directly without cloning needlessly
2260 ptr::write(ptr, value.last());
2261 local_len.increment_len(1);
2264 // len set by scope guard
2269 impl<T: PartialEq, A: Allocator> Vec<T, A> {
2270 /// Removes consecutive repeated elements in the vector according to the
2271 /// [`PartialEq`] trait implementation.
2273 /// If the vector is sorted, this removes all duplicates.
2278 /// let mut vec = vec![1, 2, 2, 3, 2];
2282 /// assert_eq!(vec, [1, 2, 3, 2]);
2284 #[stable(feature = "rust1", since = "1.0.0")]
2286 pub fn dedup(&mut self) {
2287 self.dedup_by(|a, b| a == b)
2291 ////////////////////////////////////////////////////////////////////////////////
2292 // Internal methods and functions
2293 ////////////////////////////////////////////////////////////////////////////////
2296 #[cfg(not(no_global_oom_handling))]
2297 #[stable(feature = "rust1", since = "1.0.0")]
2298 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
2299 <T as SpecFromElem>::from_elem(elem, n, Global)
2303 #[cfg(not(no_global_oom_handling))]
2304 #[unstable(feature = "allocator_api", issue = "32838")]
2305 pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
2306 <T as SpecFromElem>::from_elem(elem, n, alloc)
2309 trait ExtendFromWithinSpec {
2312 /// - `src` needs to be valid index
2313 /// - `self.capacity() - self.len()` must be `>= src.len()`
2314 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>);
2317 impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
2318 default unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
2320 // - len is increased only after initializing elements
2321 let (this, spare, len) = unsafe { self.split_at_spare_mut_with_len() };
2324 // - caller guaratees that src is a valid index
2325 let to_clone = unsafe { this.get_unchecked(src) };
2327 iter::zip(to_clone, spare)
2328 .map(|(src, dst)| dst.write(src.clone()))
2330 // - Element was just initialized with `MaybeUninit::write`, so it's ok to increase len
2331 // - len is increased after each element to prevent leaks (see issue #82533)
2332 .for_each(|_| *len += 1);
2336 impl<T: Copy, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
2337 unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
2338 let count = src.len();
2340 let (init, spare) = self.split_at_spare_mut();
2343 // - caller guaratees that `src` is a valid index
2344 let source = unsafe { init.get_unchecked(src) };
2347 // - Both pointers are created from unique slice references (`&mut [_]`)
2348 // so they are valid and do not overlap.
2349 // - Elements are :Copy so it's OK to to copy them, without doing
2350 // anything with the original values
2351 // - `count` is equal to the len of `source`, so source is valid for
2353 // - `.reserve(count)` guarantees that `spare.len() >= count` so spare
2354 // is valid for `count` writes
2355 unsafe { ptr::copy_nonoverlapping(source.as_ptr(), spare.as_mut_ptr() as _, count) };
2359 // - The elements were just initialized by `copy_nonoverlapping`
2364 ////////////////////////////////////////////////////////////////////////////////
2365 // Common trait implementations for Vec
2366 ////////////////////////////////////////////////////////////////////////////////
2368 #[stable(feature = "rust1", since = "1.0.0")]
2369 impl<T, A: Allocator> ops::Deref for Vec<T, A> {
2372 fn deref(&self) -> &[T] {
2373 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
2377 #[stable(feature = "rust1", since = "1.0.0")]
2378 impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
2379 fn deref_mut(&mut self) -> &mut [T] {
2380 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
2384 #[cfg(not(no_global_oom_handling))]
2385 trait SpecCloneFrom {
2386 fn clone_from(this: &mut Self, other: &Self);
2389 #[cfg(not(no_global_oom_handling))]
2390 impl<T: Clone, A: Allocator> SpecCloneFrom for Vec<T, A> {
2391 default fn clone_from(this: &mut Self, other: &Self) {
2392 // drop anything that will not be overwritten
2393 this.truncate(other.len());
2395 // self.len <= other.len due to the truncate above, so the
2396 // slices here are always in-bounds.
2397 let (init, tail) = other.split_at(this.len());
2399 // reuse the contained values' allocations/resources.
2400 this.clone_from_slice(init);
2401 this.extend_from_slice(tail);
2405 #[cfg(not(no_global_oom_handling))]
2406 impl<T: Copy, A: Allocator> SpecCloneFrom for Vec<T, A> {
2407 fn clone_from(this: &mut Self, other: &Self) {
2409 this.extend_from_slice(other);
2413 #[cfg(not(no_global_oom_handling))]
2414 #[stable(feature = "rust1", since = "1.0.0")]
2415 impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
2417 fn clone(&self) -> Self {
2418 let alloc = self.allocator().clone();
2419 <[T]>::to_vec_in(&**self, alloc)
2422 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
2423 // required for this method definition, is not available. Instead use the
2424 // `slice::to_vec` function which is only available with cfg(test)
2425 // NB see the slice::hack module in slice.rs for more information
2427 fn clone(&self) -> Self {
2428 let alloc = self.allocator().clone();
2429 crate::slice::to_vec(&**self, alloc)
2432 fn clone_from(&mut self, other: &Self) {
2433 SpecCloneFrom::clone_from(self, other)
2437 /// The hash of a vector is the same as that of the corresponding slice,
2438 /// as required by the `core::borrow::Borrow` implementation.
2441 /// #![feature(build_hasher_simple_hash_one)]
2442 /// use std::hash::BuildHasher;
2444 /// let b = std::collections::hash_map::RandomState::new();
2445 /// let v: Vec<u8> = vec![0xa8, 0x3c, 0x09];
2446 /// let s: &[u8] = &[0xa8, 0x3c, 0x09];
2447 /// assert_eq!(b.hash_one(v), b.hash_one(s));
2449 #[stable(feature = "rust1", since = "1.0.0")]
2450 impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
2452 fn hash<H: Hasher>(&self, state: &mut H) {
2453 Hash::hash(&**self, state)
2457 #[stable(feature = "rust1", since = "1.0.0")]
2458 #[rustc_on_unimplemented(
2459 message = "vector indices are of type `usize` or ranges of `usize`",
2460 label = "vector indices are of type `usize` or ranges of `usize`"
2462 impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
2463 type Output = I::Output;
2466 fn index(&self, index: I) -> &Self::Output {
2467 Index::index(&**self, index)
2471 #[stable(feature = "rust1", since = "1.0.0")]
2472 #[rustc_on_unimplemented(
2473 message = "vector indices are of type `usize` or ranges of `usize`",
2474 label = "vector indices are of type `usize` or ranges of `usize`"
2476 impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
2478 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2479 IndexMut::index_mut(&mut **self, index)
2483 #[cfg(not(no_global_oom_handling))]
2484 #[stable(feature = "rust1", since = "1.0.0")]
2485 impl<T> FromIterator<T> for Vec<T> {
2487 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2488 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
2492 #[stable(feature = "rust1", since = "1.0.0")]
2493 impl<T, A: Allocator> IntoIterator for Vec<T, A> {
2495 type IntoIter = IntoIter<T, A>;
2497 /// Creates a consuming iterator, that is, one that moves each value out of
2498 /// the vector (from start to end). The vector cannot be used after calling
2504 /// let v = vec!["a".to_string(), "b".to_string()];
2505 /// for s in v.into_iter() {
2506 /// // s has type String, not &String
2507 /// println!("{}", s);
2511 fn into_iter(self) -> IntoIter<T, A> {
2513 let mut me = ManuallyDrop::new(self);
2514 let alloc = ptr::read(me.allocator());
2515 let begin = me.as_mut_ptr();
2516 let end = if mem::size_of::<T>() == 0 {
2517 arith_offset(begin as *const i8, me.len() as isize) as *const T
2519 begin.add(me.len()) as *const T
2521 let cap = me.buf.capacity();
2523 buf: NonNull::new_unchecked(begin),
2524 phantom: PhantomData,
2534 #[stable(feature = "rust1", since = "1.0.0")]
2535 impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
2537 type IntoIter = slice::Iter<'a, T>;
2539 fn into_iter(self) -> slice::Iter<'a, T> {
2544 #[stable(feature = "rust1", since = "1.0.0")]
2545 impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
2546 type Item = &'a mut T;
2547 type IntoIter = slice::IterMut<'a, T>;
2549 fn into_iter(self) -> slice::IterMut<'a, T> {
2554 #[cfg(not(no_global_oom_handling))]
2555 #[stable(feature = "rust1", since = "1.0.0")]
2556 impl<T, A: Allocator> Extend<T> for Vec<T, A> {
2558 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2559 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2563 fn extend_one(&mut self, item: T) {
2568 fn extend_reserve(&mut self, additional: usize) {
2569 self.reserve(additional);
2573 impl<T, A: Allocator> Vec<T, A> {
2574 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2575 // they have no further optimizations to apply
2576 #[cfg(not(no_global_oom_handling))]
2577 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2578 // This is the case for a general iterator.
2580 // This function should be the moral equivalent of:
2582 // for item in iterator {
2585 while let Some(element) = iterator.next() {
2586 let len = self.len();
2587 if len == self.capacity() {
2588 let (lower, _) = iterator.size_hint();
2589 self.reserve(lower.saturating_add(1));
2592 ptr::write(self.as_mut_ptr().add(len), element);
2593 // Since next() executes user code which can panic we have to bump the length
2595 // NB can't overflow since we would have had to alloc the address space
2596 self.set_len(len + 1);
2601 /// Creates a splicing iterator that replaces the specified range in the vector
2602 /// with the given `replace_with` iterator and yields the removed items.
2603 /// `replace_with` does not need to be the same length as `range`.
2605 /// `range` is removed even if the iterator is not consumed until the end.
2607 /// It is unspecified how many elements are removed from the vector
2608 /// if the `Splice` value is leaked.
2610 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2612 /// This is optimal if:
2614 /// * The tail (elements in the vector after `range`) is empty,
2615 /// * or `replace_with` yields fewer or equal elements than `range`’s length
2616 /// * or the lower bound of its `size_hint()` is exact.
2618 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2622 /// Panics if the starting point is greater than the end point or if
2623 /// the end point is greater than the length of the vector.
2628 /// let mut v = vec![1, 2, 3];
2629 /// let new = [7, 8];
2630 /// let u: Vec<_> = v.splice(..2, new).collect();
2631 /// assert_eq!(v, &[7, 8, 3]);
2632 /// assert_eq!(u, &[1, 2]);
2634 #[cfg(not(no_global_oom_handling))]
2636 #[stable(feature = "vec_splice", since = "1.21.0")]
2637 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
2639 R: RangeBounds<usize>,
2640 I: IntoIterator<Item = T>,
2642 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2645 /// Creates an iterator which uses a closure to determine if an element should be removed.
2647 /// If the closure returns true, then the element is removed and yielded.
2648 /// If the closure returns false, the element will remain in the vector and will not be yielded
2649 /// by the iterator.
2651 /// Using this method is equivalent to the following code:
2654 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2655 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2657 /// while i < vec.len() {
2658 /// if some_predicate(&mut vec[i]) {
2659 /// let val = vec.remove(i);
2660 /// // your code here
2666 /// # assert_eq!(vec, vec![1, 4, 5]);
2669 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2670 /// because it can backshift the elements of the array in bulk.
2672 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2673 /// regardless of whether you choose to keep or remove it.
2677 /// Splitting an array into evens and odds, reusing the original allocation:
2680 /// #![feature(drain_filter)]
2681 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2683 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2684 /// let odds = numbers;
2686 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2687 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2689 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2690 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F, A>
2692 F: FnMut(&mut T) -> bool,
2694 let old_len = self.len();
2696 // Guard against us getting leaked (leak amplification)
2701 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2705 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2707 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2708 /// append the entire slice at once.
2710 /// [`copy_from_slice`]: slice::copy_from_slice
2711 #[cfg(not(no_global_oom_handling))]
2712 #[stable(feature = "extend_ref", since = "1.2.0")]
2713 impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec<T, A> {
2714 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2715 self.spec_extend(iter.into_iter())
2719 fn extend_one(&mut self, &item: &'a T) {
2724 fn extend_reserve(&mut self, additional: usize) {
2725 self.reserve(additional);
2729 /// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2730 #[stable(feature = "rust1", since = "1.0.0")]
2731 impl<T: PartialOrd, A: Allocator> PartialOrd for Vec<T, A> {
2733 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2734 PartialOrd::partial_cmp(&**self, &**other)
2738 #[stable(feature = "rust1", since = "1.0.0")]
2739 impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
2741 /// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2742 #[stable(feature = "rust1", since = "1.0.0")]
2743 impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
2745 fn cmp(&self, other: &Self) -> Ordering {
2746 Ord::cmp(&**self, &**other)
2750 #[stable(feature = "rust1", since = "1.0.0")]
2751 unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
2752 fn drop(&mut self) {
2755 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2756 // could avoid questions of validity in certain cases
2757 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2759 // RawVec handles deallocation
2763 #[stable(feature = "rust1", since = "1.0.0")]
2764 #[rustc_const_unstable(feature = "const_default_impls", issue = "87864")]
2765 impl<T> const Default for Vec<T> {
2766 /// Creates an empty `Vec<T>`.
2767 fn default() -> Vec<T> {
2772 #[stable(feature = "rust1", since = "1.0.0")]
2773 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
2774 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2775 fmt::Debug::fmt(&**self, f)
2779 #[stable(feature = "rust1", since = "1.0.0")]
2780 impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
2781 fn as_ref(&self) -> &Vec<T, A> {
2786 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2787 impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
2788 fn as_mut(&mut self) -> &mut Vec<T, A> {
2793 #[stable(feature = "rust1", since = "1.0.0")]
2794 impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
2795 fn as_ref(&self) -> &[T] {
2800 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2801 impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
2802 fn as_mut(&mut self) -> &mut [T] {
2807 #[cfg(not(no_global_oom_handling))]
2808 #[stable(feature = "rust1", since = "1.0.0")]
2809 impl<T: Clone> From<&[T]> for Vec<T> {
2810 /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
2815 /// assert_eq!(Vec::from(&[1, 2, 3][..]), vec![1, 2, 3]);
2818 fn from(s: &[T]) -> Vec<T> {
2822 fn from(s: &[T]) -> Vec<T> {
2823 crate::slice::to_vec(s, Global)
2827 #[cfg(not(no_global_oom_handling))]
2828 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2829 impl<T: Clone> From<&mut [T]> for Vec<T> {
2830 /// Allocate a `Vec<T>` and fill it by cloning `s`'s items.
2835 /// assert_eq!(Vec::from(&mut [1, 2, 3][..]), vec![1, 2, 3]);
2838 fn from(s: &mut [T]) -> Vec<T> {
2842 fn from(s: &mut [T]) -> Vec<T> {
2843 crate::slice::to_vec(s, Global)
2847 #[cfg(not(no_global_oom_handling))]
2848 #[stable(feature = "vec_from_array", since = "1.44.0")]
2849 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2851 fn from(s: [T; N]) -> Vec<T> {
2852 <[T]>::into_vec(box s)
2854 /// Allocate a `Vec<T>` and move `s`'s items into it.
2859 /// assert_eq!(Vec::from([1, 2, 3]), vec![1, 2, 3]);
2862 fn from(s: [T; N]) -> Vec<T> {
2863 crate::slice::into_vec(box s)
2867 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2868 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2870 [T]: ToOwned<Owned = Vec<T>>,
2872 /// Convert a clone-on-write slice into a vector.
2874 /// If `s` already owns a `Vec<T>`, it will be returned directly.
2875 /// If `s` is borrowing a slice, a new `Vec<T>` will be allocated and
2876 /// filled by cloning `s`'s items into it.
2881 /// # use std::borrow::Cow;
2882 /// let o: Cow<[i32]> = Cow::Owned(vec![1, 2, 3]);
2883 /// let b: Cow<[i32]> = Cow::Borrowed(&[1, 2, 3]);
2884 /// assert_eq!(Vec::from(o), Vec::from(b));
2886 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2891 // note: test pulls in libstd, which causes errors here
2893 #[stable(feature = "vec_from_box", since = "1.18.0")]
2894 impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
2895 /// Convert a boxed slice into a vector by transferring ownership of
2896 /// the existing heap allocation.
2901 /// let b: Box<[i32]> = vec![1, 2, 3].into_boxed_slice();
2902 /// assert_eq!(Vec::from(b), vec![1, 2, 3]);
2904 fn from(s: Box<[T], A>) -> Self {
2909 // note: test pulls in libstd, which causes errors here
2910 #[cfg(not(no_global_oom_handling))]
2912 #[stable(feature = "box_from_vec", since = "1.20.0")]
2913 impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
2914 /// Convert a vector into a boxed slice.
2916 /// If `v` has excess capacity, its items will be moved into a
2917 /// newly-allocated buffer with exactly the right capacity.
2922 /// assert_eq!(Box::from(vec![1, 2, 3]), vec![1, 2, 3].into_boxed_slice());
2924 fn from(v: Vec<T, A>) -> Self {
2925 v.into_boxed_slice()
2929 #[cfg(not(no_global_oom_handling))]
2930 #[stable(feature = "rust1", since = "1.0.0")]
2931 impl From<&str> for Vec<u8> {
2932 /// Allocate a `Vec<u8>` and fill it with a UTF-8 string.
2937 /// assert_eq!(Vec::from("123"), vec![b'1', b'2', b'3']);
2939 fn from(s: &str) -> Vec<u8> {
2940 From::from(s.as_bytes())
2944 #[stable(feature = "array_try_from_vec", since = "1.48.0")]
2945 impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
2946 type Error = Vec<T, A>;
2948 /// Gets the entire contents of the `Vec<T>` as an array,
2949 /// if its size exactly matches that of the requested array.
2954 /// use std::convert::TryInto;
2955 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
2956 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
2959 /// If the length doesn't match, the input comes back in `Err`:
2961 /// use std::convert::TryInto;
2962 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
2963 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
2966 /// If you're fine with just getting a prefix of the `Vec<T>`,
2967 /// you can call [`.truncate(N)`](Vec::truncate) first.
2969 /// use std::convert::TryInto;
2970 /// let mut v = String::from("hello world").into_bytes();
2973 /// let [a, b]: [_; 2] = v.try_into().unwrap();
2974 /// assert_eq!(a, b' ');
2975 /// assert_eq!(b, b'd');
2977 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
2982 // SAFETY: `.set_len(0)` is always sound.
2983 unsafe { vec.set_len(0) };
2985 // SAFETY: A `Vec`'s pointer is always aligned properly, and
2986 // the alignment the array needs is the same as the items.
2987 // We checked earlier that we have sufficient items.
2988 // The items will not double-drop as the `set_len`
2989 // tells the `Vec` not to also drop them.
2990 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };