1 // ignore-tidy-filelength
2 //! A contiguous growable array type with heap-allocated contents, written
5 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
6 //! `O(1)` pop (from the end).
8 //! Vectors ensure they never allocate more than `isize::MAX` bytes.
12 //! You can explicitly create a [`Vec`] with [`Vec::new`]:
15 //! let v: Vec<i32> = Vec::new();
18 //! ...or by using the [`vec!`] macro:
21 //! let v: Vec<i32> = vec![];
23 //! let v = vec![1, 2, 3, 4, 5];
25 //! let v = vec![0; 10]; // ten zeroes
28 //! You can [`push`] values onto the end of a vector (which will grow the vector
32 //! let mut v = vec![1, 2];
37 //! Popping values works in much the same way:
40 //! let mut v = vec![1, 2];
42 //! let two = v.pop();
45 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
48 //! let mut v = vec![1, 2, 3];
53 //! [`push`]: Vec::push
55 #![stable(feature = "rust1", since = "1.0.0")]
57 use core::cmp::{self, Ordering};
58 use core::convert::TryFrom;
60 use core::hash::{Hash, Hasher};
61 use core::intrinsics::{arith_offset, assume};
63 FromIterator, FusedIterator, InPlaceIterable, SourceIter, TrustedLen, TrustedRandomAccess,
65 use core::marker::PhantomData;
66 use core::mem::{self, ManuallyDrop, MaybeUninit};
67 use core::ops::{self, Index, IndexMut, Range, RangeBounds};
68 use core::ptr::{self, NonNull};
69 use core::slice::{self, SliceIndex};
71 use crate::alloc::{Allocator, Global};
72 use crate::borrow::{Cow, ToOwned};
73 use crate::boxed::Box;
74 use crate::collections::TryReserveError;
75 use crate::raw_vec::RawVec;
77 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
82 /// let mut vec = Vec::new();
86 /// assert_eq!(vec.len(), 2);
87 /// assert_eq!(vec[0], 1);
89 /// assert_eq!(vec.pop(), Some(2));
90 /// assert_eq!(vec.len(), 1);
93 /// assert_eq!(vec[0], 7);
95 /// vec.extend([1, 2, 3].iter().copied());
98 /// println!("{}", x);
100 /// assert_eq!(vec, [7, 1, 2, 3]);
103 /// The [`vec!`] macro is provided to make initialization more convenient:
106 /// let mut vec = vec![1, 2, 3];
108 /// assert_eq!(vec, [1, 2, 3, 4]);
111 /// It can also initialize each element of a `Vec<T>` with a given value.
112 /// This may be more efficient than performing allocation and initialization
113 /// in separate steps, especially when initializing a vector of zeros:
116 /// let vec = vec![0; 5];
117 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
119 /// // The following is equivalent, but potentially slower:
120 /// let mut vec = Vec::with_capacity(5);
121 /// vec.resize(5, 0);
122 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
125 /// For more information, see
126 /// [Capacity and Reallocation](#capacity-and-reallocation).
128 /// Use a `Vec<T>` as an efficient stack:
131 /// let mut stack = Vec::new();
137 /// while let Some(top) = stack.pop() {
138 /// // Prints 3, 2, 1
139 /// println!("{}", top);
145 /// The `Vec` type allows to access values by index, because it implements the
146 /// [`Index`] trait. An example will be more explicit:
149 /// let v = vec![0, 2, 4, 6];
150 /// println!("{}", v[1]); // it will display '2'
153 /// However be careful: if you try to access an index which isn't in the `Vec`,
154 /// your software will panic! You cannot do this:
157 /// let v = vec![0, 2, 4, 6];
158 /// println!("{}", v[6]); // it will panic!
161 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
166 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
167 /// To get a [slice], use [`&`]. Example:
170 /// fn read_slice(slice: &[usize]) {
174 /// let v = vec![0, 1];
177 /// // ... and that's all!
178 /// // you can also do it like this:
179 /// let u: &[usize] = &v;
181 /// let u: &[_] = &v;
184 /// In Rust, it's more common to pass slices as arguments rather than vectors
185 /// when you just want to provide read access. The same goes for [`String`] and
188 /// # Capacity and reallocation
190 /// The capacity of a vector is the amount of space allocated for any future
191 /// elements that will be added onto the vector. This is not to be confused with
192 /// the *length* of a vector, which specifies the number of actual elements
193 /// within the vector. If a vector's length exceeds its capacity, its capacity
194 /// will automatically be increased, but its elements will have to be
197 /// For example, a vector with capacity 10 and length 0 would be an empty vector
198 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
199 /// vector will not change its capacity or cause reallocation to occur. However,
200 /// if the vector's length is increased to 11, it will have to reallocate, which
201 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
202 /// whenever possible to specify how big the vector is expected to get.
206 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
207 /// about its design. This ensures that it's as low-overhead as possible in
208 /// the general case, and can be correctly manipulated in primitive ways
209 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
210 /// If additional type parameters are added (e.g., to support custom allocators),
211 /// overriding their defaults may change the behavior.
213 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
214 /// triplet. No more, no less. The order of these fields is completely
215 /// unspecified, and you should use the appropriate methods to modify these.
216 /// The pointer will never be null, so this type is null-pointer-optimized.
218 /// However, the pointer may not actually point to allocated memory. In particular,
219 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
220 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
221 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
222 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
223 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
224 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
225 /// details are very subtle — if you intend to allocate memory using a `Vec`
226 /// and use it for something else (either to pass to unsafe code, or to build your
227 /// own memory-backed collection), be sure to deallocate this memory by using
228 /// `from_raw_parts` to recover the `Vec` and then dropping it.
230 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
231 /// (as defined by the allocator Rust is configured to use by default), and its
232 /// pointer points to [`len`] initialized, contiguous elements in order (what
233 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
234 /// `[`len`] logically uninitialized, contiguous elements.
236 /// `Vec` will never perform a "small optimization" where elements are actually
237 /// stored on the stack for two reasons:
239 /// * It would make it more difficult for unsafe code to correctly manipulate
240 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
241 /// only moved, and it would be more difficult to determine if a `Vec` had
242 /// actually allocated memory.
244 /// * It would penalize the general case, incurring an additional branch
247 /// `Vec` will never automatically shrink itself, even if completely empty. This
248 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
249 /// and then filling it back up to the same [`len`] should incur no calls to
250 /// the allocator. If you wish to free up unused memory, use
251 /// [`shrink_to_fit`].
253 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
254 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
255 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
256 /// accurate, and can be relied on. It can even be used to manually free the memory
257 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
258 /// when not necessary.
260 /// `Vec` does not guarantee any particular growth strategy when reallocating
261 /// when full, nor when [`reserve`] is called. The current strategy is basic
262 /// and it may prove desirable to use a non-constant growth factor. Whatever
263 /// strategy is used will of course guarantee *O*(1) amortized [`push`].
265 /// `vec![x; n]`, `vec![a, b, c, d]`, and
266 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
267 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
268 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
269 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
271 /// `Vec` will not specifically overwrite any data that is removed from it,
272 /// but also won't specifically preserve it. Its uninitialized memory is
273 /// scratch space that it may use however it wants. It will generally just do
274 /// whatever is most efficient or otherwise easy to implement. Do not rely on
275 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
276 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
277 /// first, that may not actually happen because the optimizer does not consider
278 /// this a side-effect that must be preserved. There is one case which we will
279 /// not break, however: using `unsafe` code to write to the excess capacity,
280 /// and then increasing the length to match, is always valid.
282 /// `Vec` does not currently guarantee the order in which elements are dropped.
283 /// The order has changed in the past and may change again.
285 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
286 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
287 /// [`String`]: crate::string::String
288 /// [`&str`]: type@str
289 /// [`shrink_to_fit`]: Vec::shrink_to_fit
290 /// [`capacity`]: Vec::capacity
291 /// [`mem::size_of::<T>`]: core::mem::size_of
292 /// [`len`]: Vec::len
293 /// [`push`]: Vec::push
294 /// [`insert`]: Vec::insert
295 /// [`reserve`]: Vec::reserve
296 /// [owned slice]: Box
297 /// [slice]: ../../std/primitive.slice.html
298 /// [`&`]: ../../std/primitive.reference.html
299 #[stable(feature = "rust1", since = "1.0.0")]
300 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
301 pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
306 ////////////////////////////////////////////////////////////////////////////////
308 ////////////////////////////////////////////////////////////////////////////////
311 /// Constructs a new, empty `Vec<T>`.
313 /// The vector will not allocate until elements are pushed onto it.
318 /// # #![allow(unused_mut)]
319 /// let mut vec: Vec<i32> = Vec::new();
322 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
323 #[stable(feature = "rust1", since = "1.0.0")]
324 pub const fn new() -> Self {
325 Vec { buf: RawVec::NEW, len: 0 }
328 /// Constructs a new, empty `Vec<T>` with the specified capacity.
330 /// The vector will be able to hold exactly `capacity` elements without
331 /// reallocating. If `capacity` is 0, the vector will not allocate.
333 /// It is important to note that although the returned vector has the
334 /// *capacity* specified, the vector will have a zero *length*. For an
335 /// explanation of the difference between length and capacity, see
336 /// *[Capacity and reallocation]*.
338 /// [Capacity and reallocation]: #capacity-and-reallocation
343 /// let mut vec = Vec::with_capacity(10);
345 /// // The vector contains no items, even though it has capacity for more
346 /// assert_eq!(vec.len(), 0);
347 /// assert_eq!(vec.capacity(), 10);
349 /// // These are all done without reallocating...
353 /// assert_eq!(vec.len(), 10);
354 /// assert_eq!(vec.capacity(), 10);
356 /// // ...but this may make the vector reallocate
358 /// assert_eq!(vec.len(), 11);
359 /// assert!(vec.capacity() >= 11);
362 #[stable(feature = "rust1", since = "1.0.0")]
363 pub fn with_capacity(capacity: usize) -> Self {
364 Self::with_capacity_in(capacity, Global)
367 /// Creates a `Vec<T>` directly from the raw components of another vector.
371 /// This is highly unsafe, due to the number of invariants that aren't
374 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
375 /// (at least, it's highly likely to be incorrect if it wasn't).
376 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
377 /// (`T` having a less strict alignment is not sufficient, the alignment really
378 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
379 /// allocated and deallocated with the same layout.)
380 /// * `length` needs to be less than or equal to `capacity`.
381 /// * `capacity` needs to be the capacity that the pointer was allocated with.
383 /// Violating these may cause problems like corrupting the allocator's
384 /// internal data structures. For example it is **not** safe
385 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
386 /// It's also not safe to build one from a `Vec<u16>` and its length, because
387 /// the allocator cares about the alignment, and these two types have different
388 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
389 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
391 /// The ownership of `ptr` is effectively transferred to the
392 /// `Vec<T>` which may then deallocate, reallocate or change the
393 /// contents of memory pointed to by the pointer at will. Ensure
394 /// that nothing else uses the pointer after calling this
397 /// [`String`]: crate::string::String
398 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
406 /// let v = vec![1, 2, 3];
408 // FIXME Update this when vec_into_raw_parts is stabilized
409 /// // Prevent running `v`'s destructor so we are in complete control
410 /// // of the allocation.
411 /// let mut v = mem::ManuallyDrop::new(v);
413 /// // Pull out the various important pieces of information about `v`
414 /// let p = v.as_mut_ptr();
415 /// let len = v.len();
416 /// let cap = v.capacity();
419 /// // Overwrite memory with 4, 5, 6
420 /// for i in 0..len as isize {
421 /// ptr::write(p.offset(i), 4 + i);
424 /// // Put everything back together into a Vec
425 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
426 /// assert_eq!(rebuilt, [4, 5, 6]);
430 #[stable(feature = "rust1", since = "1.0.0")]
431 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
432 unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
436 impl<T, A: Allocator> Vec<T, A> {
437 /// Constructs a new, empty `Vec<T, A>`.
439 /// The vector will not allocate until elements are pushed onto it.
444 /// #![feature(allocator_api)]
446 /// use std::alloc::System;
448 /// # #[allow(unused_mut)]
449 /// let mut vec: Vec<i32, _> = Vec::new_in(System);
452 #[unstable(feature = "allocator_api", issue = "32838")]
453 pub const fn new_in(alloc: A) -> Self {
454 Vec { buf: RawVec::new_in(alloc), len: 0 }
457 /// Constructs a new, empty `Vec<T, A>` with the specified capacity with the provided
460 /// The vector will be able to hold exactly `capacity` elements without
461 /// reallocating. If `capacity` is 0, the vector will not allocate.
463 /// It is important to note that although the returned vector has the
464 /// *capacity* specified, the vector will have a zero *length*. For an
465 /// explanation of the difference between length and capacity, see
466 /// *[Capacity and reallocation]*.
468 /// [Capacity and reallocation]: #capacity-and-reallocation
473 /// #![feature(allocator_api)]
475 /// use std::alloc::System;
477 /// let mut vec = Vec::with_capacity_in(10, System);
479 /// // The vector contains no items, even though it has capacity for more
480 /// assert_eq!(vec.len(), 0);
481 /// assert_eq!(vec.capacity(), 10);
483 /// // These are all done without reallocating...
487 /// assert_eq!(vec.len(), 10);
488 /// assert_eq!(vec.capacity(), 10);
490 /// // ...but this may make the vector reallocate
492 /// assert_eq!(vec.len(), 11);
493 /// assert!(vec.capacity() >= 11);
496 #[unstable(feature = "allocator_api", issue = "32838")]
497 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
498 Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
501 /// Creates a `Vec<T, A>` directly from the raw components of another vector.
505 /// This is highly unsafe, due to the number of invariants that aren't
508 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
509 /// (at least, it's highly likely to be incorrect if it wasn't).
510 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
511 /// (`T` having a less strict alignment is not sufficient, the alignment really
512 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
513 /// allocated and deallocated with the same layout.)
514 /// * `length` needs to be less than or equal to `capacity`.
515 /// * `capacity` needs to be the capacity that the pointer was allocated with.
517 /// Violating these may cause problems like corrupting the allocator's
518 /// internal data structures. For example it is **not** safe
519 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
520 /// It's also not safe to build one from a `Vec<u16>` and its length, because
521 /// the allocator cares about the alignment, and these two types have different
522 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
523 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
525 /// The ownership of `ptr` is effectively transferred to the
526 /// `Vec<T>` which may then deallocate, reallocate or change the
527 /// contents of memory pointed to by the pointer at will. Ensure
528 /// that nothing else uses the pointer after calling this
531 /// [`String`]: crate::string::String
532 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
537 /// #![feature(allocator_api)]
539 /// use std::alloc::System;
544 /// let mut v = Vec::with_capacity_in(3, System);
549 // FIXME Update this when vec_into_raw_parts is stabilized
550 /// // Prevent running `v`'s destructor so we are in complete control
551 /// // of the allocation.
552 /// let mut v = mem::ManuallyDrop::new(v);
554 /// // Pull out the various important pieces of information about `v`
555 /// let p = v.as_mut_ptr();
556 /// let len = v.len();
557 /// let cap = v.capacity();
558 /// let alloc = v.allocator();
561 /// // Overwrite memory with 4, 5, 6
562 /// for i in 0..len as isize {
563 /// ptr::write(p.offset(i), 4 + i);
566 /// // Put everything back together into a Vec
567 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
568 /// assert_eq!(rebuilt, [4, 5, 6]);
572 #[unstable(feature = "allocator_api", issue = "32838")]
573 pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
574 unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
577 /// Decomposes a `Vec<T>` into its raw components.
579 /// Returns the raw pointer to the underlying data, the length of
580 /// the vector (in elements), and the allocated capacity of the
581 /// data (in elements). These are the same arguments in the same
582 /// order as the arguments to [`from_raw_parts`].
584 /// After calling this function, the caller is responsible for the
585 /// memory previously managed by the `Vec`. The only way to do
586 /// this is to convert the raw pointer, length, and capacity back
587 /// into a `Vec` with the [`from_raw_parts`] function, allowing
588 /// the destructor to perform the cleanup.
590 /// [`from_raw_parts`]: Vec::from_raw_parts
595 /// #![feature(vec_into_raw_parts)]
596 /// let v: Vec<i32> = vec![-1, 0, 1];
598 /// let (ptr, len, cap) = v.into_raw_parts();
600 /// let rebuilt = unsafe {
601 /// // We can now make changes to the components, such as
602 /// // transmuting the raw pointer to a compatible type.
603 /// let ptr = ptr as *mut u32;
605 /// Vec::from_raw_parts(ptr, len, cap)
607 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
609 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
610 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
611 let mut me = ManuallyDrop::new(self);
612 (me.as_mut_ptr(), me.len(), me.capacity())
615 /// Decomposes a `Vec<T>` into its raw components.
617 /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
618 /// the allocated capacity of the data (in elements), and the allocator. These are the same
619 /// arguments in the same order as the arguments to [`from_raw_parts_in`].
621 /// After calling this function, the caller is responsible for the
622 /// memory previously managed by the `Vec`. The only way to do
623 /// this is to convert the raw pointer, length, and capacity back
624 /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
625 /// the destructor to perform the cleanup.
627 /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
632 /// #![feature(allocator_api, vec_into_raw_parts)]
634 /// use std::alloc::System;
636 /// let mut v: Vec<i32, System> = Vec::new_in(System);
641 /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
643 /// let rebuilt = unsafe {
644 /// // We can now make changes to the components, such as
645 /// // transmuting the raw pointer to a compatible type.
646 /// let ptr = ptr as *mut u32;
648 /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
650 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
652 #[unstable(feature = "allocator_api", issue = "32838")]
653 // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
654 pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
655 let mut me = ManuallyDrop::new(self);
657 let capacity = me.capacity();
658 let ptr = me.as_mut_ptr();
659 let alloc = unsafe { ptr::read(me.allocator()) };
660 (ptr, len, capacity, alloc)
663 /// Returns the number of elements the vector can hold without
669 /// let vec: Vec<i32> = Vec::with_capacity(10);
670 /// assert_eq!(vec.capacity(), 10);
673 #[stable(feature = "rust1", since = "1.0.0")]
674 pub fn capacity(&self) -> usize {
678 /// Reserves capacity for at least `additional` more elements to be inserted
679 /// in the given `Vec<T>`. The collection may reserve more space to avoid
680 /// frequent reallocations. After calling `reserve`, capacity will be
681 /// greater than or equal to `self.len() + additional`. Does nothing if
682 /// capacity is already sufficient.
686 /// Panics if the new capacity exceeds `isize::MAX` bytes.
691 /// let mut vec = vec![1];
693 /// assert!(vec.capacity() >= 11);
695 #[stable(feature = "rust1", since = "1.0.0")]
696 pub fn reserve(&mut self, additional: usize) {
697 self.buf.reserve(self.len, additional);
700 /// Reserves the minimum capacity for exactly `additional` more elements to
701 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
702 /// capacity will be greater than or equal to `self.len() + additional`.
703 /// Does nothing if the capacity is already sufficient.
705 /// Note that the allocator may give the collection more space than it
706 /// requests. Therefore, capacity can not be relied upon to be precisely
707 /// minimal. Prefer `reserve` if future insertions are expected.
711 /// Panics if the new capacity overflows `usize`.
716 /// let mut vec = vec![1];
717 /// vec.reserve_exact(10);
718 /// assert!(vec.capacity() >= 11);
720 #[stable(feature = "rust1", since = "1.0.0")]
721 pub fn reserve_exact(&mut self, additional: usize) {
722 self.buf.reserve_exact(self.len, additional);
725 /// Tries to reserve capacity for at least `additional` more elements to be inserted
726 /// in the given `Vec<T>`. The collection may reserve more space to avoid
727 /// frequent reallocations. After calling `try_reserve`, capacity will be
728 /// greater than or equal to `self.len() + additional`. Does nothing if
729 /// capacity is already sufficient.
733 /// If the capacity overflows, or the allocator reports a failure, then an error
739 /// #![feature(try_reserve)]
740 /// use std::collections::TryReserveError;
742 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
743 /// let mut output = Vec::new();
745 /// // Pre-reserve the memory, exiting if we can't
746 /// output.try_reserve(data.len())?;
748 /// // Now we know this can't OOM in the middle of our complex work
749 /// output.extend(data.iter().map(|&val| {
750 /// val * 2 + 5 // very complicated
755 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
757 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
758 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
759 self.buf.try_reserve(self.len, additional)
762 /// Tries to reserve the minimum capacity for exactly `additional`
763 /// elements to be inserted in the given `Vec<T>`. After calling
764 /// `try_reserve_exact`, capacity will be greater than or equal to
765 /// `self.len() + additional` if it returns `Ok(())`.
766 /// Does nothing if the capacity is already sufficient.
768 /// Note that the allocator may give the collection more space than it
769 /// requests. Therefore, capacity can not be relied upon to be precisely
770 /// minimal. Prefer `reserve` if future insertions are expected.
774 /// If the capacity overflows, or the allocator reports a failure, then an error
780 /// #![feature(try_reserve)]
781 /// use std::collections::TryReserveError;
783 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
784 /// let mut output = Vec::new();
786 /// // Pre-reserve the memory, exiting if we can't
787 /// output.try_reserve_exact(data.len())?;
789 /// // Now we know this can't OOM in the middle of our complex work
790 /// output.extend(data.iter().map(|&val| {
791 /// val * 2 + 5 // very complicated
796 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
798 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
799 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
800 self.buf.try_reserve_exact(self.len, additional)
803 /// Shrinks the capacity of the vector as much as possible.
805 /// It will drop down as close as possible to the length but the allocator
806 /// may still inform the vector that there is space for a few more elements.
811 /// let mut vec = Vec::with_capacity(10);
812 /// vec.extend([1, 2, 3].iter().cloned());
813 /// assert_eq!(vec.capacity(), 10);
814 /// vec.shrink_to_fit();
815 /// assert!(vec.capacity() >= 3);
817 #[stable(feature = "rust1", since = "1.0.0")]
818 pub fn shrink_to_fit(&mut self) {
819 // The capacity is never less than the length, and there's nothing to do when
820 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
821 // by only calling it with a greater capacity.
822 if self.capacity() > self.len {
823 self.buf.shrink_to_fit(self.len);
827 /// Shrinks the capacity of the vector with a lower bound.
829 /// The capacity will remain at least as large as both the length
830 /// and the supplied value.
834 /// Panics if the current capacity is smaller than the supplied
835 /// minimum capacity.
840 /// #![feature(shrink_to)]
841 /// let mut vec = Vec::with_capacity(10);
842 /// vec.extend([1, 2, 3].iter().cloned());
843 /// assert_eq!(vec.capacity(), 10);
844 /// vec.shrink_to(4);
845 /// assert!(vec.capacity() >= 4);
846 /// vec.shrink_to(0);
847 /// assert!(vec.capacity() >= 3);
849 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
850 pub fn shrink_to(&mut self, min_capacity: usize) {
851 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
854 /// Converts the vector into [`Box<[T]>`][owned slice].
856 /// Note that this will drop any excess capacity.
858 /// [owned slice]: Box
863 /// let v = vec![1, 2, 3];
865 /// let slice = v.into_boxed_slice();
868 /// Any excess capacity is removed:
871 /// let mut vec = Vec::with_capacity(10);
872 /// vec.extend([1, 2, 3].iter().cloned());
874 /// assert_eq!(vec.capacity(), 10);
875 /// let slice = vec.into_boxed_slice();
876 /// assert_eq!(slice.into_vec().capacity(), 3);
878 #[stable(feature = "rust1", since = "1.0.0")]
879 pub fn into_boxed_slice(mut self) -> Box<[T], A> {
881 self.shrink_to_fit();
882 let me = ManuallyDrop::new(self);
883 let buf = ptr::read(&me.buf);
885 buf.into_box(len).assume_init()
889 /// Shortens the vector, keeping the first `len` elements and dropping
892 /// If `len` is greater than the vector's current length, this has no
895 /// The [`drain`] method can emulate `truncate`, but causes the excess
896 /// elements to be returned instead of dropped.
898 /// Note that this method has no effect on the allocated capacity
903 /// Truncating a five element vector to two elements:
906 /// let mut vec = vec![1, 2, 3, 4, 5];
908 /// assert_eq!(vec, [1, 2]);
911 /// No truncation occurs when `len` is greater than the vector's current
915 /// let mut vec = vec![1, 2, 3];
917 /// assert_eq!(vec, [1, 2, 3]);
920 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
924 /// let mut vec = vec![1, 2, 3];
926 /// assert_eq!(vec, []);
929 /// [`clear`]: Vec::clear
930 /// [`drain`]: Vec::drain
931 #[stable(feature = "rust1", since = "1.0.0")]
932 pub fn truncate(&mut self, len: usize) {
933 // This is safe because:
935 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
936 // case avoids creating an invalid slice, and
937 // * the `len` of the vector is shrunk before calling `drop_in_place`,
938 // such that no value will be dropped twice in case `drop_in_place`
939 // were to panic once (if it panics twice, the program aborts).
944 let remaining_len = self.len - len;
945 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
947 ptr::drop_in_place(s);
951 /// Extracts a slice containing the entire vector.
953 /// Equivalent to `&s[..]`.
958 /// use std::io::{self, Write};
959 /// let buffer = vec![1, 2, 3, 5, 8];
960 /// io::sink().write(buffer.as_slice()).unwrap();
963 #[stable(feature = "vec_as_slice", since = "1.7.0")]
964 pub fn as_slice(&self) -> &[T] {
968 /// Extracts a mutable slice of the entire vector.
970 /// Equivalent to `&mut s[..]`.
975 /// use std::io::{self, Read};
976 /// let mut buffer = vec![0; 3];
977 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
980 #[stable(feature = "vec_as_slice", since = "1.7.0")]
981 pub fn as_mut_slice(&mut self) -> &mut [T] {
985 /// Returns a raw pointer to the vector's buffer.
987 /// The caller must ensure that the vector outlives the pointer this
988 /// function returns, or else it will end up pointing to garbage.
989 /// Modifying the vector may cause its buffer to be reallocated,
990 /// which would also make any pointers to it invalid.
992 /// The caller must also ensure that the memory the pointer (non-transitively) points to
993 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
994 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
999 /// let x = vec![1, 2, 4];
1000 /// let x_ptr = x.as_ptr();
1003 /// for i in 0..x.len() {
1004 /// assert_eq!(*x_ptr.add(i), 1 << i);
1009 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1010 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1012 pub fn as_ptr(&self) -> *const T {
1013 // We shadow the slice method of the same name to avoid going through
1014 // `deref`, which creates an intermediate reference.
1015 let ptr = self.buf.ptr();
1017 assume(!ptr.is_null());
1022 /// Returns an unsafe mutable pointer to the vector's buffer.
1024 /// The caller must ensure that the vector outlives the pointer this
1025 /// function returns, or else it will end up pointing to garbage.
1026 /// Modifying the vector may cause its buffer to be reallocated,
1027 /// which would also make any pointers to it invalid.
1032 /// // Allocate vector big enough for 4 elements.
1034 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1035 /// let x_ptr = x.as_mut_ptr();
1037 /// // Initialize elements via raw pointer writes, then set length.
1039 /// for i in 0..size {
1040 /// *x_ptr.add(i) = i as i32;
1042 /// x.set_len(size);
1044 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1046 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1048 pub fn as_mut_ptr(&mut self) -> *mut T {
1049 // We shadow the slice method of the same name to avoid going through
1050 // `deref_mut`, which creates an intermediate reference.
1051 let ptr = self.buf.ptr();
1053 assume(!ptr.is_null());
1058 /// Returns a reference to the underlying allocator.
1059 #[unstable(feature = "allocator_api", issue = "32838")]
1061 pub fn allocator(&self) -> &A {
1062 self.buf.allocator()
1065 /// Forces the length of the vector to `new_len`.
1067 /// This is a low-level operation that maintains none of the normal
1068 /// invariants of the type. Normally changing the length of a vector
1069 /// is done using one of the safe operations instead, such as
1070 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
1072 /// [`truncate`]: Vec::truncate
1073 /// [`resize`]: Vec::resize
1074 /// [`extend`]: Extend::extend
1075 /// [`clear`]: Vec::clear
1079 /// - `new_len` must be less than or equal to [`capacity()`].
1080 /// - The elements at `old_len..new_len` must be initialized.
1082 /// [`capacity()`]: Vec::capacity
1086 /// This method can be useful for situations in which the vector
1087 /// is serving as a buffer for other code, particularly over FFI:
1090 /// # #![allow(dead_code)]
1091 /// # // This is just a minimal skeleton for the doc example;
1092 /// # // don't use this as a starting point for a real library.
1093 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
1094 /// # const Z_OK: i32 = 0;
1096 /// # fn deflateGetDictionary(
1097 /// # strm: *mut std::ffi::c_void,
1098 /// # dictionary: *mut u8,
1099 /// # dictLength: *mut usize,
1102 /// # impl StreamWrapper {
1103 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
1104 /// // Per the FFI method's docs, "32768 bytes is always enough".
1105 /// let mut dict = Vec::with_capacity(32_768);
1106 /// let mut dict_length = 0;
1107 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
1108 /// // 1. `dict_length` elements were initialized.
1109 /// // 2. `dict_length` <= the capacity (32_768)
1110 /// // which makes `set_len` safe to call.
1112 /// // Make the FFI call...
1113 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
1115 /// // ...and update the length to what was initialized.
1116 /// dict.set_len(dict_length);
1126 /// While the following example is sound, there is a memory leak since
1127 /// the inner vectors were not freed prior to the `set_len` call:
1130 /// let mut vec = vec![vec![1, 0, 0],
1134 /// // 1. `old_len..0` is empty so no elements need to be initialized.
1135 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
1141 /// Normally, here, one would use [`clear`] instead to correctly drop
1142 /// the contents and thus not leak memory.
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 pub unsafe fn set_len(&mut self, new_len: usize) {
1146 debug_assert!(new_len <= self.capacity());
1151 /// Removes an element from the vector and returns it.
1153 /// The removed element is replaced by the last element of the vector.
1155 /// This does not preserve ordering, but is O(1).
1159 /// Panics if `index` is out of bounds.
1164 /// let mut v = vec!["foo", "bar", "baz", "qux"];
1166 /// assert_eq!(v.swap_remove(1), "bar");
1167 /// assert_eq!(v, ["foo", "qux", "baz"]);
1169 /// assert_eq!(v.swap_remove(0), "foo");
1170 /// assert_eq!(v, ["baz", "qux"]);
1173 #[stable(feature = "rust1", since = "1.0.0")]
1174 pub fn swap_remove(&mut self, index: usize) -> T {
1177 fn assert_failed(index: usize, len: usize) -> ! {
1178 panic!("swap_remove index (is {}) should be < len (is {})", index, len);
1181 let len = self.len();
1183 assert_failed(index, len);
1186 // We replace self[index] with the last element. Note that if the
1187 // bounds check above succeeds there must be a last element (which
1188 // can be self[index] itself).
1189 let last = ptr::read(self.as_ptr().add(len - 1));
1190 let hole = self.as_mut_ptr().add(index);
1191 self.set_len(len - 1);
1192 ptr::replace(hole, last)
1196 /// Inserts an element at position `index` within the vector, shifting all
1197 /// elements after it to the right.
1201 /// Panics if `index > len`.
1206 /// let mut vec = vec![1, 2, 3];
1207 /// vec.insert(1, 4);
1208 /// assert_eq!(vec, [1, 4, 2, 3]);
1209 /// vec.insert(4, 5);
1210 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1212 #[stable(feature = "rust1", since = "1.0.0")]
1213 pub fn insert(&mut self, index: usize, element: T) {
1216 fn assert_failed(index: usize, len: usize) -> ! {
1217 panic!("insertion index (is {}) should be <= len (is {})", index, len);
1220 let len = self.len();
1222 assert_failed(index, len);
1225 // space for the new element
1226 if len == self.buf.capacity() {
1232 // The spot to put the new value
1234 let p = self.as_mut_ptr().add(index);
1235 // Shift everything over to make space. (Duplicating the
1236 // `index`th element into two consecutive places.)
1237 ptr::copy(p, p.offset(1), len - index);
1238 // Write it in, overwriting the first copy of the `index`th
1240 ptr::write(p, element);
1242 self.set_len(len + 1);
1246 /// Removes and returns the element at position `index` within the vector,
1247 /// shifting all elements after it to the left.
1251 /// Panics if `index` is out of bounds.
1256 /// let mut v = vec![1, 2, 3];
1257 /// assert_eq!(v.remove(1), 2);
1258 /// assert_eq!(v, [1, 3]);
1260 #[stable(feature = "rust1", since = "1.0.0")]
1261 pub fn remove(&mut self, index: usize) -> T {
1264 fn assert_failed(index: usize, len: usize) -> ! {
1265 panic!("removal index (is {}) should be < len (is {})", index, len);
1268 let len = self.len();
1270 assert_failed(index, len);
1276 // the place we are taking from.
1277 let ptr = self.as_mut_ptr().add(index);
1278 // copy it out, unsafely having a copy of the value on
1279 // the stack and in the vector at the same time.
1280 ret = ptr::read(ptr);
1282 // Shift everything down to fill in that spot.
1283 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1285 self.set_len(len - 1);
1290 /// Retains only the elements specified by the predicate.
1292 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1293 /// This method operates in place, visiting each element exactly once in the
1294 /// original order, and preserves the order of the retained elements.
1299 /// let mut vec = vec![1, 2, 3, 4];
1300 /// vec.retain(|&x| x % 2 == 0);
1301 /// assert_eq!(vec, [2, 4]);
1304 /// The exact order may be useful for tracking external state, like an index.
1307 /// let mut vec = vec![1, 2, 3, 4, 5];
1308 /// let keep = [false, true, true, false, true];
1310 /// vec.retain(|_| (keep[i], i += 1).0);
1311 /// assert_eq!(vec, [2, 3, 5]);
1313 #[stable(feature = "rust1", since = "1.0.0")]
1314 pub fn retain<F>(&mut self, mut f: F)
1316 F: FnMut(&T) -> bool,
1318 let len = self.len();
1321 let v = &mut **self;
1332 self.truncate(len - del);
1336 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1339 /// If the vector is sorted, this removes all duplicates.
1344 /// let mut vec = vec![10, 20, 21, 30, 20];
1346 /// vec.dedup_by_key(|i| *i / 10);
1348 /// assert_eq!(vec, [10, 20, 30, 20]);
1350 #[stable(feature = "dedup_by", since = "1.16.0")]
1352 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1354 F: FnMut(&mut T) -> K,
1357 self.dedup_by(|a, b| key(a) == key(b))
1360 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1363 /// The `same_bucket` function is passed references to two elements from the vector and
1364 /// must determine if the elements compare equal. The elements are passed in opposite order
1365 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1367 /// If the vector is sorted, this removes all duplicates.
1372 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1374 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1376 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1378 #[stable(feature = "dedup_by", since = "1.16.0")]
1379 pub fn dedup_by<F>(&mut self, same_bucket: F)
1381 F: FnMut(&mut T, &mut T) -> bool,
1384 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1390 /// Appends an element to the back of a collection.
1394 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1399 /// let mut vec = vec![1, 2];
1401 /// assert_eq!(vec, [1, 2, 3]);
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 pub fn push(&mut self, value: T) {
1406 // This will panic or abort if we would allocate > isize::MAX bytes
1407 // or if the length increment would overflow for zero-sized types.
1408 if self.len == self.buf.capacity() {
1412 let end = self.as_mut_ptr().add(self.len);
1413 ptr::write(end, value);
1418 /// Removes the last element from a vector and returns it, or [`None`] if it
1424 /// let mut vec = vec![1, 2, 3];
1425 /// assert_eq!(vec.pop(), Some(3));
1426 /// assert_eq!(vec, [1, 2]);
1429 #[stable(feature = "rust1", since = "1.0.0")]
1430 pub fn pop(&mut self) -> Option<T> {
1436 Some(ptr::read(self.as_ptr().add(self.len())))
1441 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1445 /// Panics if the number of elements in the vector overflows a `usize`.
1450 /// let mut vec = vec![1, 2, 3];
1451 /// let mut vec2 = vec![4, 5, 6];
1452 /// vec.append(&mut vec2);
1453 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1454 /// assert_eq!(vec2, []);
1457 #[stable(feature = "append", since = "1.4.0")]
1458 pub fn append(&mut self, other: &mut Self) {
1460 self.append_elements(other.as_slice() as _);
1465 /// Appends elements to `Self` from other buffer.
1467 unsafe fn append_elements(&mut self, other: *const [T]) {
1468 let count = unsafe { (*other).len() };
1469 self.reserve(count);
1470 let len = self.len();
1471 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1475 /// Creates a draining iterator that removes the specified range in the vector
1476 /// and yields the removed items.
1478 /// When the iterator **is** dropped, all elements in the range are removed
1479 /// from the vector, even if the iterator was not fully consumed. If the
1480 /// iterator **is not** dropped (with [`mem::forget`] for example), it is
1481 /// unspecified how many elements are removed.
1485 /// Panics if the starting point is greater than the end point or if
1486 /// the end point is greater than the length of the vector.
1491 /// let mut v = vec![1, 2, 3];
1492 /// let u: Vec<_> = v.drain(1..).collect();
1493 /// assert_eq!(v, &[1]);
1494 /// assert_eq!(u, &[2, 3]);
1496 /// // A full range clears the vector
1498 /// assert_eq!(v, &[]);
1500 #[stable(feature = "drain", since = "1.6.0")]
1501 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1503 R: RangeBounds<usize>,
1507 // When the Drain is first created, it shortens the length of
1508 // the source vector to make sure no uninitialized or moved-from elements
1509 // are accessible at all if the Drain's destructor never gets to run.
1511 // Drain will ptr::read out the values to remove.
1512 // When finished, remaining tail of the vec is copied back to cover
1513 // the hole, and the vector length is restored to the new length.
1515 let len = self.len();
1516 let Range { start, end } = range.assert_len(len);
1519 // set self.vec length's to start, to be safe in case Drain is leaked
1520 self.set_len(start);
1521 // Use the borrow in the IterMut to indicate borrowing behavior of the
1522 // whole Drain iterator (like &mut T).
1523 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1526 tail_len: len - end,
1527 iter: range_slice.iter(),
1528 vec: NonNull::from(self),
1533 /// Clears the vector, removing all values.
1535 /// Note that this method has no effect on the allocated capacity
1541 /// let mut v = vec![1, 2, 3];
1545 /// assert!(v.is_empty());
1548 #[stable(feature = "rust1", since = "1.0.0")]
1549 pub fn clear(&mut self) {
1553 /// Returns the number of elements in the vector, also referred to
1554 /// as its 'length'.
1559 /// let a = vec![1, 2, 3];
1560 /// assert_eq!(a.len(), 3);
1563 #[stable(feature = "rust1", since = "1.0.0")]
1564 pub fn len(&self) -> usize {
1568 /// Returns `true` if the vector contains no elements.
1573 /// let mut v = Vec::new();
1574 /// assert!(v.is_empty());
1577 /// assert!(!v.is_empty());
1579 #[stable(feature = "rust1", since = "1.0.0")]
1580 pub fn is_empty(&self) -> bool {
1584 /// Splits the collection into two at the given index.
1586 /// Returns a newly allocated vector containing the elements in the range
1587 /// `[at, len)`. After the call, the original vector will be left containing
1588 /// the elements `[0, at)` with its previous capacity unchanged.
1592 /// Panics if `at > len`.
1597 /// let mut vec = vec![1, 2, 3];
1598 /// let vec2 = vec.split_off(1);
1599 /// assert_eq!(vec, [1]);
1600 /// assert_eq!(vec2, [2, 3]);
1603 #[must_use = "use `.truncate()` if you don't need the other half"]
1604 #[stable(feature = "split_off", since = "1.4.0")]
1605 pub fn split_off(&mut self, at: usize) -> Self
1611 fn assert_failed(at: usize, len: usize) -> ! {
1612 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1615 if at > self.len() {
1616 assert_failed(at, self.len());
1620 // the new vector can take over the original buffer and avoid the copy
1621 return mem::replace(
1623 Vec::with_capacity_in(self.capacity(), self.allocator().clone()),
1627 let other_len = self.len - at;
1628 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
1630 // Unsafely `set_len` and copy items to `other`.
1633 other.set_len(other_len);
1635 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1640 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1642 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1643 /// difference, with each additional slot filled with the result of
1644 /// calling the closure `f`. The return values from `f` will end up
1645 /// in the `Vec` in the order they have been generated.
1647 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1649 /// This method uses a closure to create new values on every push. If
1650 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
1651 /// want to use the [`Default`] trait to generate values, you can
1652 /// pass [`Default::default`] as the second argument.
1657 /// let mut vec = vec![1, 2, 3];
1658 /// vec.resize_with(5, Default::default);
1659 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1661 /// let mut vec = vec![];
1663 /// vec.resize_with(4, || { p *= 2; p });
1664 /// assert_eq!(vec, [2, 4, 8, 16]);
1666 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1667 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1671 let len = self.len();
1673 self.extend_with(new_len - len, ExtendFunc(f));
1675 self.truncate(new_len);
1679 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1680 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1681 /// `'a`. If the type has only static references, or none at all, then this
1682 /// may be chosen to be `'static`.
1684 /// This function is similar to the [`leak`][Box::leak] function on [`Box`]
1685 /// except that there is no way to recover the leaked memory.
1687 /// This function is mainly useful for data that lives for the remainder of
1688 /// the program's life. Dropping the returned reference will cause a memory
1696 /// let x = vec![1, 2, 3];
1697 /// let static_ref: &'static mut [usize] = x.leak();
1698 /// static_ref[0] += 1;
1699 /// assert_eq!(static_ref, &[2, 2, 3]);
1701 #[stable(feature = "vec_leak", since = "1.47.0")]
1703 pub fn leak<'a>(self) -> &'a mut [T]
1707 Box::leak(self.into_boxed_slice())
1710 /// Returns the remaining spare capacity of the vector as a slice of
1711 /// `MaybeUninit<T>`.
1713 /// The returned slice can be used to fill the vector with data (e.g. by
1714 /// reading from a file) before marking the data as initialized using the
1715 /// [`set_len`] method.
1717 /// [`set_len`]: Vec::set_len
1722 /// #![feature(vec_spare_capacity, maybe_uninit_extra)]
1724 /// // Allocate vector big enough for 10 elements.
1725 /// let mut v = Vec::with_capacity(10);
1727 /// // Fill in the first 3 elements.
1728 /// let uninit = v.spare_capacity_mut();
1729 /// uninit[0].write(0);
1730 /// uninit[1].write(1);
1731 /// uninit[2].write(2);
1733 /// // Mark the first 3 elements of the vector as being initialized.
1738 /// assert_eq!(&v, &[0, 1, 2]);
1740 #[unstable(feature = "vec_spare_capacity", issue = "75017")]
1742 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1744 slice::from_raw_parts_mut(
1745 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
1746 self.buf.capacity() - self.len,
1752 impl<T: Clone, A: Allocator> Vec<T, A> {
1753 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1755 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1756 /// difference, with each additional slot filled with `value`.
1757 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1759 /// This method requires `T` to implement [`Clone`],
1760 /// in order to be able to clone the passed value.
1761 /// If you need more flexibility (or want to rely on [`Default`] instead of
1762 /// [`Clone`]), use [`Vec::resize_with`].
1767 /// let mut vec = vec!["hello"];
1768 /// vec.resize(3, "world");
1769 /// assert_eq!(vec, ["hello", "world", "world"]);
1771 /// let mut vec = vec![1, 2, 3, 4];
1772 /// vec.resize(2, 0);
1773 /// assert_eq!(vec, [1, 2]);
1775 #[stable(feature = "vec_resize", since = "1.5.0")]
1776 pub fn resize(&mut self, new_len: usize, value: T) {
1777 let len = self.len();
1780 self.extend_with(new_len - len, ExtendElement(value))
1782 self.truncate(new_len);
1786 /// Clones and appends all elements in a slice to the `Vec`.
1788 /// Iterates over the slice `other`, clones each element, and then appends
1789 /// it to this `Vec`. The `other` vector is traversed in-order.
1791 /// Note that this function is same as [`extend`] except that it is
1792 /// specialized to work with slices instead. If and when Rust gets
1793 /// specialization this function will likely be deprecated (but still
1799 /// let mut vec = vec![1];
1800 /// vec.extend_from_slice(&[2, 3, 4]);
1801 /// assert_eq!(vec, [1, 2, 3, 4]);
1804 /// [`extend`]: Vec::extend
1805 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1806 pub fn extend_from_slice(&mut self, other: &[T]) {
1807 self.spec_extend(other.iter())
1811 // This code generalizes `extend_with_{element,default}`.
1812 trait ExtendWith<T> {
1813 fn next(&mut self) -> T;
1817 struct ExtendElement<T>(T);
1818 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1819 fn next(&mut self) -> T {
1822 fn last(self) -> T {
1827 struct ExtendDefault;
1828 impl<T: Default> ExtendWith<T> for ExtendDefault {
1829 fn next(&mut self) -> T {
1832 fn last(self) -> T {
1837 struct ExtendFunc<F>(F);
1838 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1839 fn next(&mut self) -> T {
1842 fn last(mut self) -> T {
1847 impl<T, A: Allocator> Vec<T, A> {
1848 /// Extend the vector by `n` values, using the given generator.
1849 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1853 let mut ptr = self.as_mut_ptr().add(self.len());
1854 // Use SetLenOnDrop to work around bug where compiler
1855 // may not realize the store through `ptr` through self.set_len()
1857 let mut local_len = SetLenOnDrop::new(&mut self.len);
1859 // Write all elements except the last one
1861 ptr::write(ptr, value.next());
1862 ptr = ptr.offset(1);
1863 // Increment the length in every step in case next() panics
1864 local_len.increment_len(1);
1868 // We can write the last element directly without cloning needlessly
1869 ptr::write(ptr, value.last());
1870 local_len.increment_len(1);
1873 // len set by scope guard
1878 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1880 // The idea is: The length field in SetLenOnDrop is a local variable
1881 // that the optimizer will see does not alias with any stores through the Vec's data
1882 // pointer. This is a workaround for alias analysis issue #32155
1883 struct SetLenOnDrop<'a> {
1888 impl<'a> SetLenOnDrop<'a> {
1890 fn new(len: &'a mut usize) -> Self {
1891 SetLenOnDrop { local_len: *len, len }
1895 fn increment_len(&mut self, increment: usize) {
1896 self.local_len += increment;
1900 impl Drop for SetLenOnDrop<'_> {
1902 fn drop(&mut self) {
1903 *self.len = self.local_len;
1907 impl<T: PartialEq, A: Allocator> Vec<T, A> {
1908 /// Removes consecutive repeated elements in the vector according to the
1909 /// [`PartialEq`] trait implementation.
1911 /// If the vector is sorted, this removes all duplicates.
1916 /// let mut vec = vec![1, 2, 2, 3, 2];
1920 /// assert_eq!(vec, [1, 2, 3, 2]);
1922 #[stable(feature = "rust1", since = "1.0.0")]
1924 pub fn dedup(&mut self) {
1925 self.dedup_by(|a, b| a == b)
1929 impl<T, A: Allocator> Vec<T, A> {
1930 /// Removes the first instance of `item` from the vector if the item exists.
1932 /// This method will be removed soon.
1933 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1935 reason = "Removing the first item equal to a needle is already easily possible \
1936 with iterators and the current Vec methods. Furthermore, having a method for \
1937 one particular case of removal (linear search, only the first item, no swap remove) \
1938 but not for others is inconsistent. This method will be removed soon.",
1941 pub fn remove_item<V>(&mut self, item: &V) -> Option<T>
1945 let pos = self.iter().position(|x| *x == *item)?;
1946 Some(self.remove(pos))
1950 ////////////////////////////////////////////////////////////////////////////////
1951 // Internal methods and functions
1952 ////////////////////////////////////////////////////////////////////////////////
1955 #[stable(feature = "rust1", since = "1.0.0")]
1956 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1957 <T as SpecFromElem>::from_elem(elem, n, Global)
1961 #[unstable(feature = "allocator_api", issue = "32838")]
1962 pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
1963 <T as SpecFromElem>::from_elem(elem, n, alloc)
1966 // Specialization trait used for Vec::from_elem
1967 trait SpecFromElem: Sized {
1968 fn from_elem<A: Allocator>(elem: Self, n: usize, alloc: A) -> Vec<Self, A>;
1971 impl<T: Clone> SpecFromElem for T {
1972 default fn from_elem<A: Allocator>(elem: Self, n: usize, alloc: A) -> Vec<Self, A> {
1973 let mut v = Vec::with_capacity_in(n, alloc);
1974 v.extend_with(n, ExtendElement(elem));
1979 impl SpecFromElem for i8 {
1981 fn from_elem<A: Allocator>(elem: i8, n: usize, alloc: A) -> Vec<i8, A> {
1983 return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
1986 let mut v = Vec::with_capacity_in(n, alloc);
1987 ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
1994 impl SpecFromElem for u8 {
1996 fn from_elem<A: Allocator>(elem: u8, n: usize, alloc: A) -> Vec<u8, A> {
1998 return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
2001 let mut v = Vec::with_capacity_in(n, alloc);
2002 ptr::write_bytes(v.as_mut_ptr(), elem, n);
2009 impl<T: Clone + IsZero> SpecFromElem for T {
2011 fn from_elem<A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
2013 return Vec { buf: RawVec::with_capacity_zeroed_in(n, alloc), len: n };
2015 let mut v = Vec::with_capacity_in(n, alloc);
2016 v.extend_with(n, ExtendElement(elem));
2021 #[rustc_specialization_trait]
2022 unsafe trait IsZero {
2023 /// Whether this value is zero
2024 fn is_zero(&self) -> bool;
2027 macro_rules! impl_is_zero {
2028 ($t:ty, $is_zero:expr) => {
2029 unsafe impl IsZero for $t {
2031 fn is_zero(&self) -> bool {
2038 impl_is_zero!(i16, |x| x == 0);
2039 impl_is_zero!(i32, |x| x == 0);
2040 impl_is_zero!(i64, |x| x == 0);
2041 impl_is_zero!(i128, |x| x == 0);
2042 impl_is_zero!(isize, |x| x == 0);
2044 impl_is_zero!(u16, |x| x == 0);
2045 impl_is_zero!(u32, |x| x == 0);
2046 impl_is_zero!(u64, |x| x == 0);
2047 impl_is_zero!(u128, |x| x == 0);
2048 impl_is_zero!(usize, |x| x == 0);
2050 impl_is_zero!(bool, |x| x == false);
2051 impl_is_zero!(char, |x| x == '\0');
2053 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
2054 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
2056 unsafe impl<T> IsZero for *const T {
2058 fn is_zero(&self) -> bool {
2063 unsafe impl<T> IsZero for *mut T {
2065 fn is_zero(&self) -> bool {
2070 // `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
2071 // For fat pointers, the bytes that would be the pointer metadata in the `Some`
2072 // variant are padding in the `None` variant, so ignoring them and
2073 // zero-initializing instead is ok.
2074 // `Option<&mut T>` never implements `Clone`, so there's no need for an impl of
2077 unsafe impl<T: ?Sized> IsZero for Option<&T> {
2079 fn is_zero(&self) -> bool {
2084 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
2086 fn is_zero(&self) -> bool {
2091 ////////////////////////////////////////////////////////////////////////////////
2092 // Common trait implementations for Vec
2093 ////////////////////////////////////////////////////////////////////////////////
2095 #[stable(feature = "rust1", since = "1.0.0")]
2096 impl<T, A: Allocator> ops::Deref for Vec<T, A> {
2099 fn deref(&self) -> &[T] {
2100 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
2104 #[stable(feature = "rust1", since = "1.0.0")]
2105 impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
2106 fn deref_mut(&mut self) -> &mut [T] {
2107 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
2111 #[stable(feature = "rust1", since = "1.0.0")]
2112 impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
2114 fn clone(&self) -> Self {
2115 let alloc = self.allocator().clone();
2116 <[T]>::to_vec_in(&**self, alloc)
2119 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
2120 // required for this method definition, is not available. Instead use the
2121 // `slice::to_vec` function which is only available with cfg(test)
2122 // NB see the slice::hack module in slice.rs for more information
2124 fn clone(&self) -> Self {
2125 let alloc = self.allocator().clone();
2126 crate::slice::to_vec(&**self, alloc)
2129 fn clone_from(&mut self, other: &Self) {
2130 // drop anything that will not be overwritten
2131 self.truncate(other.len());
2133 // self.len <= other.len due to the truncate above, so the
2134 // slices here are always in-bounds.
2135 let (init, tail) = other.split_at(self.len());
2137 // reuse the contained values' allocations/resources.
2138 self.clone_from_slice(init);
2139 self.extend_from_slice(tail);
2143 #[stable(feature = "rust1", since = "1.0.0")]
2144 impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
2146 fn hash<H: Hasher>(&self, state: &mut H) {
2147 Hash::hash(&**self, state)
2151 #[stable(feature = "rust1", since = "1.0.0")]
2152 #[rustc_on_unimplemented(
2153 message = "vector indices are of type `usize` or ranges of `usize`",
2154 label = "vector indices are of type `usize` or ranges of `usize`"
2156 impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
2157 type Output = I::Output;
2160 fn index(&self, index: I) -> &Self::Output {
2161 Index::index(&**self, index)
2165 #[stable(feature = "rust1", since = "1.0.0")]
2166 #[rustc_on_unimplemented(
2167 message = "vector indices are of type `usize` or ranges of `usize`",
2168 label = "vector indices are of type `usize` or ranges of `usize`"
2170 impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
2172 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2173 IndexMut::index_mut(&mut **self, index)
2177 #[stable(feature = "rust1", since = "1.0.0")]
2178 impl<T> FromIterator<T> for Vec<T> {
2180 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2181 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
2185 #[stable(feature = "rust1", since = "1.0.0")]
2186 impl<T, A: Allocator> IntoIterator for Vec<T, A> {
2188 type IntoIter = IntoIter<T, A>;
2190 /// Creates a consuming iterator, that is, one that moves each value out of
2191 /// the vector (from start to end). The vector cannot be used after calling
2197 /// let v = vec!["a".to_string(), "b".to_string()];
2198 /// for s in v.into_iter() {
2199 /// // s has type String, not &String
2200 /// println!("{}", s);
2204 fn into_iter(self) -> IntoIter<T, A> {
2206 let mut me = ManuallyDrop::new(self);
2207 let alloc = ptr::read(me.allocator());
2208 let begin = me.as_mut_ptr();
2209 let end = if mem::size_of::<T>() == 0 {
2210 arith_offset(begin as *const i8, me.len() as isize) as *const T
2212 begin.add(me.len()) as *const T
2214 let cap = me.buf.capacity();
2216 buf: NonNull::new_unchecked(begin),
2217 phantom: PhantomData,
2227 #[stable(feature = "rust1", since = "1.0.0")]
2228 impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
2230 type IntoIter = slice::Iter<'a, T>;
2232 fn into_iter(self) -> slice::Iter<'a, T> {
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
2239 type Item = &'a mut T;
2240 type IntoIter = slice::IterMut<'a, T>;
2242 fn into_iter(self) -> slice::IterMut<'a, T> {
2247 #[stable(feature = "rust1", since = "1.0.0")]
2248 impl<T, A: Allocator> Extend<T> for Vec<T, A> {
2250 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2251 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2255 fn extend_one(&mut self, item: T) {
2260 fn extend_reserve(&mut self, additional: usize) {
2261 self.reserve(additional);
2265 /// Specialization trait used for Vec::from_iter
2267 /// ## The delegation graph:
2275 /// +-+-------------------------------+ +---------------------+
2276 /// |SpecFromIter +---->+SpecFromIterNested |
2277 /// |where I: | | |where I: |
2278 /// | Iterator (default)----------+ | | Iterator (default) |
2279 /// | vec::IntoIter | | | TrustedLen |
2280 /// | SourceIterMarker---fallback-+ | | |
2281 /// | slice::Iter | | |
2282 /// | Iterator<Item = &Clone> | +---------------------+
2283 /// +---------------------------------+
2285 trait SpecFromIter<T, I> {
2286 fn from_iter(iter: I) -> Self;
2289 /// Another specialization trait for Vec::from_iter
2290 /// necessary to manually prioritize overlapping specializations
2291 /// see [`SpecFromIter`] for details.
2292 trait SpecFromIterNested<T, I> {
2293 fn from_iter(iter: I) -> Self;
2296 impl<T, I> SpecFromIterNested<T, I> for Vec<T>
2298 I: Iterator<Item = T>,
2300 default fn from_iter(mut iterator: I) -> Self {
2301 // Unroll the first iteration, as the vector is going to be
2302 // expanded on this iteration in every case when the iterable is not
2303 // empty, but the loop in extend_desugared() is not going to see the
2304 // vector being full in the few subsequent loop iterations.
2305 // So we get better branch prediction.
2306 let mut vector = match iterator.next() {
2307 None => return Vec::new(),
2309 let (lower, _) = iterator.size_hint();
2310 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2312 ptr::write(vector.as_mut_ptr(), element);
2318 // must delegate to spec_extend() since extend() itself delegates
2319 // to spec_from for empty Vecs
2320 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2325 impl<T, I> SpecFromIterNested<T, I> for Vec<T>
2327 I: TrustedLen<Item = T>,
2329 fn from_iter(iterator: I) -> Self {
2330 let mut vector = match iterator.size_hint() {
2331 (_, Some(upper)) => Vec::with_capacity(upper),
2334 // must delegate to spec_extend() since extend() itself delegates
2335 // to spec_from for empty Vecs
2336 vector.spec_extend(iterator);
2341 impl<T, I> SpecFromIter<T, I> for Vec<T>
2343 I: Iterator<Item = T>,
2345 default fn from_iter(iterator: I) -> Self {
2346 SpecFromIterNested::from_iter(iterator)
2350 // A helper struct for in-place iteration that drops the destination slice of iteration,
2351 // i.e. the head. The source slice (the tail) is dropped by IntoIter.
2352 struct InPlaceDrop<T> {
2357 impl<T> InPlaceDrop<T> {
2358 fn len(&self) -> usize {
2359 unsafe { self.dst.offset_from(self.inner) as usize }
2363 impl<T> Drop for InPlaceDrop<T> {
2365 fn drop(&mut self) {
2367 ptr::drop_in_place(slice::from_raw_parts_mut(self.inner, self.len()));
2372 impl<T> SpecFromIter<T, IntoIter<T>> for Vec<T> {
2373 fn from_iter(iterator: IntoIter<T>) -> Self {
2374 // A common case is passing a vector into a function which immediately
2375 // re-collects into a vector. We can short circuit this if the IntoIter
2376 // has not been advanced at all.
2377 // When it has been advanced We can also reuse the memory and move the data to the front.
2378 // But we only do so when the resulting Vec wouldn't have more unused capacity
2379 // than creating it through the generic FromIterator implementation would. That limitation
2380 // is not strictly necessary as Vec's allocation behavior is intentionally unspecified.
2381 // But it is a conservative choice.
2382 let has_advanced = iterator.buf.as_ptr() as *const _ != iterator.ptr;
2383 if !has_advanced || iterator.len() >= iterator.cap / 2 {
2385 let it = ManuallyDrop::new(iterator);
2387 ptr::copy(it.ptr, it.buf.as_ptr(), it.len());
2389 return Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap);
2393 let mut vec = Vec::new();
2394 // must delegate to spec_extend() since extend() itself delegates
2395 // to spec_from for empty Vecs
2396 vec.spec_extend(iterator);
2401 fn write_in_place_with_drop<T>(
2403 ) -> impl FnMut(InPlaceDrop<T>, T) -> Result<InPlaceDrop<T>, !> {
2404 move |mut sink, item| {
2406 // the InPlaceIterable contract cannot be verified precisely here since
2407 // try_fold has an exclusive reference to the source pointer
2408 // all we can do is check if it's still in range
2409 debug_assert!(sink.dst as *const _ <= src_end, "InPlaceIterable contract violation");
2410 ptr::write(sink.dst, item);
2411 sink.dst = sink.dst.add(1);
2417 /// Specialization marker for collecting an iterator pipeline into a Vec while reusing the
2418 /// source allocation, i.e. executing the pipeline in place.
2420 /// The SourceIter parent trait is necessary for the specializing function to access the allocation
2421 /// which is to be reused. But it is not sufficient for the specialization to be valid. See
2422 /// additional bounds on the impl.
2423 #[rustc_unsafe_specialization_marker]
2424 trait SourceIterMarker: SourceIter<Source: AsIntoIter> {}
2426 // The std-internal SourceIter/InPlaceIterable traits are only implemented by chains of
2427 // Adapter<Adapter<Adapter<IntoIter>>> (all owned by core/std). Additional bounds
2428 // on the adapter implementations (beyond `impl<I: Trait> Trait for Adapter<I>`) only depend on other
2429 // traits already marked as specialization traits (Copy, TrustedRandomAccess, FusedIterator).
2430 // I.e. the marker does not depend on lifetimes of user-supplied types. Modulo the Copy hole, which
2431 // several other specializations already depend on.
2432 impl<T> SourceIterMarker for T where T: SourceIter<Source: AsIntoIter> + InPlaceIterable {}
2434 impl<T, I> SpecFromIter<T, I> for Vec<T>
2436 I: Iterator<Item = T> + SourceIterMarker,
2438 default fn from_iter(mut iterator: I) -> Self {
2439 // Additional requirements which cannot expressed via trait bounds. We rely on const eval
2441 // a) no ZSTs as there would be no allocation to reuse and pointer arithmetic would panic
2442 // b) size match as required by Alloc contract
2443 // c) alignments match as required by Alloc contract
2444 if mem::size_of::<T>() == 0
2445 || mem::size_of::<T>()
2446 != mem::size_of::<<<I as SourceIter>::Source as AsIntoIter>::Item>()
2447 || mem::align_of::<T>()
2448 != mem::align_of::<<<I as SourceIter>::Source as AsIntoIter>::Item>()
2450 // fallback to more generic implementations
2451 return SpecFromIterNested::from_iter(iterator);
2454 let (src_buf, src_ptr, dst_buf, dst_end, cap) = unsafe {
2455 let inner = iterator.as_inner().as_into_iter();
2459 inner.buf.as_ptr() as *mut T,
2460 inner.end as *const T,
2465 // use try-fold since
2466 // - it vectorizes better for some iterator adapters
2467 // - unlike most internal iteration methods, it only takes a &mut self
2468 // - it lets us thread the write pointer through its innards and get it back in the end
2469 let sink = InPlaceDrop { inner: dst_buf, dst: dst_buf };
2471 .try_fold::<_, _, Result<_, !>>(sink, write_in_place_with_drop(dst_end))
2473 // iteration succeeded, don't drop head
2474 let dst = ManuallyDrop::new(sink).dst;
2476 let src = unsafe { iterator.as_inner().as_into_iter() };
2477 // check if SourceIter contract was upheld
2478 // caveat: if they weren't we may not even make it to this point
2479 debug_assert_eq!(src_buf, src.buf.as_ptr());
2480 // check InPlaceIterable contract. This is only possible if the iterator advanced the
2481 // source pointer at all. If it uses unchecked access via TrustedRandomAccess
2482 // then the source pointer will stay in its initial position and we can't use it as reference
2483 if src.ptr != src_ptr {
2485 dst as *const _ <= src.ptr,
2486 "InPlaceIterable contract violation, write pointer advanced beyond read pointer"
2490 // drop any remaining values at the tail of the source
2491 src.drop_remaining();
2492 // but prevent drop of the allocation itself once IntoIter goes out of scope
2493 src.forget_allocation();
2496 let len = dst.offset_from(dst_buf) as usize;
2497 Vec::from_raw_parts(dst_buf, len, cap)
2504 impl<'a, T: 'a, I> SpecFromIter<&'a T, I> for Vec<T>
2506 I: Iterator<Item = &'a T>,
2509 default fn from_iter(iterator: I) -> Self {
2510 SpecFromIter::from_iter(iterator.cloned())
2514 // This utilizes `iterator.as_slice().to_vec()` since spec_extend
2515 // must take more steps to reason about the final capacity + length
2516 // and thus do more work. `to_vec()` directly allocates the correct amount
2517 // and fills it exactly.
2518 impl<'a, T: 'a + Clone> SpecFromIter<&'a T, slice::Iter<'a, T>> for Vec<T> {
2520 fn from_iter(iterator: slice::Iter<'a, T>) -> Self {
2521 iterator.as_slice().to_vec()
2524 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
2525 // required for this method definition, is not available. Instead use the
2526 // `slice::to_vec` function which is only available with cfg(test)
2527 // NB see the slice::hack module in slice.rs for more information
2529 fn from_iter(iterator: slice::Iter<'a, T>) -> Self {
2530 crate::slice::to_vec(iterator.as_slice(), Global)
2534 // Specialization trait used for Vec::extend
2535 trait SpecExtend<T, I> {
2536 fn spec_extend(&mut self, iter: I);
2539 impl<T, I, A: Allocator> SpecExtend<T, I> for Vec<T, A>
2541 I: Iterator<Item = T>,
2543 default fn spec_extend(&mut self, iter: I) {
2544 self.extend_desugared(iter)
2548 impl<T, I, A: Allocator> SpecExtend<T, I> for Vec<T, A>
2550 I: TrustedLen<Item = T>,
2552 default fn spec_extend(&mut self, iterator: I) {
2553 // This is the case for a TrustedLen iterator.
2554 let (low, high) = iterator.size_hint();
2555 if let Some(high_value) = high {
2559 "TrustedLen iterator's size hint is not exact: {:?}",
2563 if let Some(additional) = high {
2564 self.reserve(additional);
2566 let mut ptr = self.as_mut_ptr().add(self.len());
2567 let mut local_len = SetLenOnDrop::new(&mut self.len);
2568 iterator.for_each(move |element| {
2569 ptr::write(ptr, element);
2570 ptr = ptr.offset(1);
2571 // NB can't overflow since we would have had to alloc the address space
2572 local_len.increment_len(1);
2576 self.extend_desugared(iterator)
2581 impl<T, A: Allocator> SpecExtend<T, IntoIter<T>> for Vec<T, A> {
2582 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2584 self.append_elements(iterator.as_slice() as _);
2586 iterator.ptr = iterator.end;
2590 impl<'a, T: 'a, I, A: Allocator + 'a> SpecExtend<&'a T, I> for Vec<T, A>
2592 I: Iterator<Item = &'a T>,
2595 default fn spec_extend(&mut self, iterator: I) {
2596 self.spec_extend(iterator.cloned())
2600 impl<'a, T: 'a, A: Allocator + 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T, A>
2604 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2605 let slice = iterator.as_slice();
2606 unsafe { self.append_elements(slice) };
2610 impl<T, A: Allocator> Vec<T, A> {
2611 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2612 // they have no further optimizations to apply
2613 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2614 // This is the case for a general iterator.
2616 // This function should be the moral equivalent of:
2618 // for item in iterator {
2621 while let Some(element) = iterator.next() {
2622 let len = self.len();
2623 if len == self.capacity() {
2624 let (lower, _) = iterator.size_hint();
2625 self.reserve(lower.saturating_add(1));
2628 ptr::write(self.as_mut_ptr().add(len), element);
2629 // NB can't overflow since we would have had to alloc the address space
2630 self.set_len(len + 1);
2635 /// Creates a splicing iterator that replaces the specified range in the vector
2636 /// with the given `replace_with` iterator and yields the removed items.
2637 /// `replace_with` does not need to be the same length as `range`.
2639 /// `range` is removed even if the iterator is not consumed until the end.
2641 /// It is unspecified how many elements are removed from the vector
2642 /// if the `Splice` value is leaked.
2644 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2646 /// This is optimal if:
2648 /// * The tail (elements in the vector after `range`) is empty,
2649 /// * or `replace_with` yields fewer elements than `range`’s length
2650 /// * or the lower bound of its `size_hint()` is exact.
2652 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2656 /// Panics if the starting point is greater than the end point or if
2657 /// the end point is greater than the length of the vector.
2662 /// let mut v = vec![1, 2, 3];
2663 /// let new = [7, 8];
2664 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2665 /// assert_eq!(v, &[7, 8, 3]);
2666 /// assert_eq!(u, &[1, 2]);
2669 #[stable(feature = "vec_splice", since = "1.21.0")]
2670 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
2672 R: RangeBounds<usize>,
2673 I: IntoIterator<Item = T>,
2675 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2678 /// Creates an iterator which uses a closure to determine if an element should be removed.
2680 /// If the closure returns true, then the element is removed and yielded.
2681 /// If the closure returns false, the element will remain in the vector and will not be yielded
2682 /// by the iterator.
2684 /// Using this method is equivalent to the following code:
2687 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2688 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2690 /// while i != vec.len() {
2691 /// if some_predicate(&mut vec[i]) {
2692 /// let val = vec.remove(i);
2693 /// // your code here
2699 /// # assert_eq!(vec, vec![1, 4, 5]);
2702 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2703 /// because it can backshift the elements of the array in bulk.
2705 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2706 /// regardless of whether you choose to keep or remove it.
2710 /// Splitting an array into evens and odds, reusing the original allocation:
2713 /// #![feature(drain_filter)]
2714 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2716 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2717 /// let odds = numbers;
2719 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2720 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2722 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2723 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F, A>
2725 F: FnMut(&mut T) -> bool,
2727 let old_len = self.len();
2729 // Guard against us getting leaked (leak amplification)
2734 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2738 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2740 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2741 /// append the entire slice at once.
2743 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2744 #[stable(feature = "extend_ref", since = "1.2.0")]
2745 impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec<T, A> {
2746 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2747 self.spec_extend(iter.into_iter())
2751 fn extend_one(&mut self, &item: &'a T) {
2756 fn extend_reserve(&mut self, additional: usize) {
2757 self.reserve(additional);
2761 macro_rules! __impl_slice_eq1 {
2762 ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => {
2764 impl<T, U, $($vars)*> PartialEq<$rhs> for $lhs
2770 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2772 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2777 __impl_slice_eq1! { [A: Allocator] Vec<T, A>, Vec<U, A>, #[stable(feature = "rust1", since = "1.0.0")] }
2778 __impl_slice_eq1! { [A: Allocator] Vec<T, A>, &[U], #[stable(feature = "rust1", since = "1.0.0")] }
2779 __impl_slice_eq1! { [A: Allocator] Vec<T, A>, &mut [U], #[stable(feature = "rust1", since = "1.0.0")] }
2780 __impl_slice_eq1! { [A: Allocator] &[T], Vec<U, A>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2781 __impl_slice_eq1! { [A: Allocator] &mut [T], Vec<U, A>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2782 __impl_slice_eq1! { [A: Allocator] Vec<T, A>, [U], #[stable(feature = "partialeq_vec_for_slice", since = "1.48.0")] }
2783 __impl_slice_eq1! { [A: Allocator] [T], Vec<U, A>, #[stable(feature = "partialeq_vec_for_slice", since = "1.48.0")] }
2784 __impl_slice_eq1! { [A: Allocator] Cow<'_, [T]>, Vec<U, A> where T: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2785 __impl_slice_eq1! { [] Cow<'_, [T]>, &[U] where T: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2786 __impl_slice_eq1! { [] Cow<'_, [T]>, &mut [U] where T: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2787 __impl_slice_eq1! { [A: Allocator, const N: usize] Vec<T, A>, [U; N], #[stable(feature = "rust1", since = "1.0.0")] }
2788 __impl_slice_eq1! { [A: Allocator, const N: usize] Vec<T, A>, &[U; N], #[stable(feature = "rust1", since = "1.0.0")] }
2790 // NOTE: some less important impls are omitted to reduce code bloat
2791 // FIXME(Centril): Reconsider this?
2792 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], }
2793 //__impl_slice_eq1! { [const N: usize] [A; N], Vec<B>, }
2794 //__impl_slice_eq1! { [const N: usize] &[A; N], Vec<B>, }
2795 //__impl_slice_eq1! { [const N: usize] &mut [A; N], Vec<B>, }
2796 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], }
2797 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], }
2798 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], }
2800 /// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2801 #[stable(feature = "rust1", since = "1.0.0")]
2802 impl<T: PartialOrd, A: Allocator> PartialOrd for Vec<T, A> {
2804 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2805 PartialOrd::partial_cmp(&**self, &**other)
2809 #[stable(feature = "rust1", since = "1.0.0")]
2810 impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
2812 /// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2813 #[stable(feature = "rust1", since = "1.0.0")]
2814 impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
2816 fn cmp(&self, other: &Self) -> Ordering {
2817 Ord::cmp(&**self, &**other)
2821 #[stable(feature = "rust1", since = "1.0.0")]
2822 unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
2823 fn drop(&mut self) {
2826 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2827 // could avoid questions of validity in certain cases
2828 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2830 // RawVec handles deallocation
2834 #[stable(feature = "rust1", since = "1.0.0")]
2835 impl<T> Default for Vec<T> {
2836 /// Creates an empty `Vec<T>`.
2837 fn default() -> Vec<T> {
2842 #[stable(feature = "rust1", since = "1.0.0")]
2843 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
2844 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2845 fmt::Debug::fmt(&**self, f)
2849 #[stable(feature = "rust1", since = "1.0.0")]
2850 impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
2851 fn as_ref(&self) -> &Vec<T, A> {
2856 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2857 impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
2858 fn as_mut(&mut self) -> &mut Vec<T, A> {
2863 #[stable(feature = "rust1", since = "1.0.0")]
2864 impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
2865 fn as_ref(&self) -> &[T] {
2870 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2871 impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
2872 fn as_mut(&mut self) -> &mut [T] {
2877 #[stable(feature = "rust1", since = "1.0.0")]
2878 impl<T: Clone> From<&[T]> for Vec<T> {
2880 fn from(s: &[T]) -> Vec<T> {
2884 fn from(s: &[T]) -> Vec<T> {
2885 crate::slice::to_vec(s, Global)
2889 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2890 impl<T: Clone> From<&mut [T]> for Vec<T> {
2892 fn from(s: &mut [T]) -> Vec<T> {
2896 fn from(s: &mut [T]) -> Vec<T> {
2897 crate::slice::to_vec(s, Global)
2901 #[stable(feature = "vec_from_array", since = "1.44.0")]
2902 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2904 fn from(s: [T; N]) -> Vec<T> {
2905 <[T]>::into_vec(box s)
2908 fn from(s: [T; N]) -> Vec<T> {
2909 crate::slice::into_vec(box s)
2913 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2914 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2916 [T]: ToOwned<Owned = Vec<T>>,
2918 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2923 // note: test pulls in libstd, which causes errors here
2925 #[stable(feature = "vec_from_box", since = "1.18.0")]
2926 impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
2927 fn from(s: Box<[T], A>) -> Self {
2929 Self { buf: RawVec::from_box(s), len }
2933 // note: test pulls in libstd, which causes errors here
2935 #[stable(feature = "box_from_vec", since = "1.20.0")]
2936 impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
2937 fn from(v: Vec<T, A>) -> Self {
2938 v.into_boxed_slice()
2942 #[stable(feature = "rust1", since = "1.0.0")]
2943 impl From<&str> for Vec<u8> {
2944 fn from(s: &str) -> Vec<u8> {
2945 From::from(s.as_bytes())
2949 #[stable(feature = "array_try_from_vec", since = "1.48.0")]
2950 impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
2951 type Error = Vec<T, A>;
2953 /// Gets the entire contents of the `Vec<T>` as an array,
2954 /// if its size exactly matches that of the requested array.
2959 /// use std::convert::TryInto;
2960 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
2961 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
2964 /// If the length doesn't match, the input comes back in `Err`:
2966 /// use std::convert::TryInto;
2967 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
2968 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
2971 /// If you're fine with just getting a prefix of the `Vec<T>`,
2972 /// you can call [`.truncate(N)`](Vec::truncate) first.
2974 /// use std::convert::TryInto;
2975 /// let mut v = String::from("hello world").into_bytes();
2978 /// let [a, b]: [_; 2] = v.try_into().unwrap();
2979 /// assert_eq!(a, b' ');
2980 /// assert_eq!(b, b'd');
2982 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
2987 // SAFETY: `.set_len(0)` is always sound.
2988 unsafe { vec.set_len(0) };
2990 // SAFETY: A `Vec`'s pointer is always aligned properly, and
2991 // the alignment the array needs is the same as the items.
2992 // We checked earlier that we have sufficient items.
2993 // The items will not double-drop as the `set_len`
2994 // tells the `Vec` not to also drop them.
2995 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
3000 ////////////////////////////////////////////////////////////////////////////////
3002 ////////////////////////////////////////////////////////////////////////////////
3004 #[stable(feature = "cow_from_vec", since = "1.8.0")]
3005 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
3006 fn from(s: &'a [T]) -> Cow<'a, [T]> {
3011 #[stable(feature = "cow_from_vec", since = "1.8.0")]
3012 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
3013 fn from(v: Vec<T>) -> Cow<'a, [T]> {
3018 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
3019 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
3020 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
3021 Cow::Borrowed(v.as_slice())
3025 #[stable(feature = "rust1", since = "1.0.0")]
3026 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
3030 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
3031 Cow::Owned(FromIterator::from_iter(it))
3035 ////////////////////////////////////////////////////////////////////////////////
3037 ////////////////////////////////////////////////////////////////////////////////
3039 /// An iterator that moves out of a vector.
3041 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
3042 /// by the [`IntoIterator`] trait).
3047 /// let v = vec![0, 1, 2];
3048 /// let iter: std::vec::IntoIter<_> = v.into_iter();
3050 #[stable(feature = "rust1", since = "1.0.0")]
3051 pub struct IntoIter<
3053 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
3056 phantom: PhantomData<T>,
3063 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
3064 impl<T: fmt::Debug, A: Allocator> fmt::Debug for IntoIter<T, A> {
3065 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3066 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
3070 impl<T, A: Allocator> IntoIter<T, A> {
3071 /// Returns the remaining items of this iterator as a slice.
3076 /// let vec = vec!['a', 'b', 'c'];
3077 /// let mut into_iter = vec.into_iter();
3078 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
3079 /// let _ = into_iter.next().unwrap();
3080 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
3082 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
3083 pub fn as_slice(&self) -> &[T] {
3084 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
3087 /// Returns the remaining items of this iterator as a mutable slice.
3092 /// let vec = vec!['a', 'b', 'c'];
3093 /// let mut into_iter = vec.into_iter();
3094 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
3095 /// into_iter.as_mut_slice()[2] = 'z';
3096 /// assert_eq!(into_iter.next().unwrap(), 'a');
3097 /// assert_eq!(into_iter.next().unwrap(), 'b');
3098 /// assert_eq!(into_iter.next().unwrap(), 'z');
3100 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
3101 pub fn as_mut_slice(&mut self) -> &mut [T] {
3102 unsafe { &mut *self.as_raw_mut_slice() }
3105 /// Returns a reference to the underlying allocator.
3106 #[unstable(feature = "allocator_api", issue = "32838")]
3108 pub fn allocator(&self) -> &A {
3112 fn as_raw_mut_slice(&mut self) -> *mut [T] {
3113 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
3116 fn drop_remaining(&mut self) {
3118 ptr::drop_in_place(self.as_mut_slice());
3120 self.ptr = self.end;
3123 /// Relinquishes the backing allocation, equivalent to
3124 /// `ptr::write(&mut self, Vec::new().into_iter())`
3125 fn forget_allocation(&mut self) {
3127 self.buf = unsafe { NonNull::new_unchecked(RawVec::NEW.ptr()) };
3128 self.ptr = self.buf.as_ptr();
3129 self.end = self.buf.as_ptr();
3133 #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
3134 impl<T, A: Allocator> AsRef<[T]> for IntoIter<T, A> {
3135 fn as_ref(&self) -> &[T] {
3140 #[stable(feature = "rust1", since = "1.0.0")]
3141 unsafe impl<T: Send, A: Allocator + Send> Send for IntoIter<T, A> {}
3142 #[stable(feature = "rust1", since = "1.0.0")]
3143 unsafe impl<T: Sync, A: Allocator> Sync for IntoIter<T, A> {}
3145 #[stable(feature = "rust1", since = "1.0.0")]
3146 impl<T, A: Allocator> Iterator for IntoIter<T, A> {
3150 fn next(&mut self) -> Option<T> {
3151 if self.ptr as *const _ == self.end {
3153 } else if mem::size_of::<T>() == 0 {
3154 // purposefully don't use 'ptr.offset' because for
3155 // vectors with 0-size elements this would return the
3157 self.ptr = unsafe { arith_offset(self.ptr as *const i8, 1) as *mut T };
3159 // Make up a value of this ZST.
3160 Some(unsafe { mem::zeroed() })
3163 self.ptr = unsafe { self.ptr.offset(1) };
3165 Some(unsafe { ptr::read(old) })
3170 fn size_hint(&self) -> (usize, Option<usize>) {
3171 let exact = if mem::size_of::<T>() == 0 {
3172 (self.end as usize).wrapping_sub(self.ptr as usize)
3174 unsafe { self.end.offset_from(self.ptr) as usize }
3176 (exact, Some(exact))
3180 fn count(self) -> usize {
3184 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item
3186 Self: TrustedRandomAccess,
3188 // SAFETY: the caller must guarantee that `i` is in bounds of the
3189 // `Vec<T>`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)`
3190 // is guaranteed to pointer to an element of the `Vec<T>` and
3191 // thus guaranteed to be valid to dereference.
3193 // Also note the implementation of `Self: TrustedRandomAccess` requires
3194 // that `T: Copy` so reading elements from the buffer doesn't invalidate
3197 if mem::size_of::<T>() == 0 { mem::zeroed() } else { ptr::read(self.ptr.add(i)) }
3202 #[stable(feature = "rust1", since = "1.0.0")]
3203 impl<T, A: Allocator> DoubleEndedIterator for IntoIter<T, A> {
3205 fn next_back(&mut self) -> Option<T> {
3206 if self.end == self.ptr {
3208 } else if mem::size_of::<T>() == 0 {
3209 // See above for why 'ptr.offset' isn't used
3210 self.end = unsafe { arith_offset(self.end as *const i8, -1) as *mut T };
3212 // Make up a value of this ZST.
3213 Some(unsafe { mem::zeroed() })
3215 self.end = unsafe { self.end.offset(-1) };
3217 Some(unsafe { ptr::read(self.end) })
3222 #[stable(feature = "rust1", since = "1.0.0")]
3223 impl<T, A: Allocator> ExactSizeIterator for IntoIter<T, A> {
3224 fn is_empty(&self) -> bool {
3225 self.ptr == self.end
3229 #[stable(feature = "fused", since = "1.26.0")]
3230 impl<T, A: Allocator> FusedIterator for IntoIter<T, A> {}
3232 #[unstable(feature = "trusted_len", issue = "37572")]
3233 unsafe impl<T, A: Allocator> TrustedLen for IntoIter<T, A> {}
3236 #[unstable(issue = "none", feature = "std_internals")]
3237 // T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr
3238 // and thus we can't implement drop-handling
3239 unsafe impl<T, A: Allocator> TrustedRandomAccess for IntoIter<T, A>
3243 fn may_have_side_effect() -> bool {
3248 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
3249 impl<T: Clone, A: Allocator + Clone> Clone for IntoIter<T, A> {
3251 fn clone(&self) -> Self {
3252 self.as_slice().to_vec_in(self.alloc.clone()).into_iter()
3255 fn clone(&self) -> Self {
3256 crate::slice::to_vec(self.as_slice(), self.alloc.clone()).into_iter()
3260 #[stable(feature = "rust1", since = "1.0.0")]
3261 unsafe impl<#[may_dangle] T, A: Allocator> Drop for IntoIter<T, A> {
3262 fn drop(&mut self) {
3263 struct DropGuard<'a, T, A: Allocator>(&'a mut IntoIter<T, A>);
3265 impl<T, A: Allocator> Drop for DropGuard<'_, T, A> {
3266 fn drop(&mut self) {
3268 // `IntoIter::alloc` is not used anymore after this
3269 let alloc = ptr::read(&self.0.alloc);
3270 // RawVec handles deallocation
3271 let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc);
3276 let guard = DropGuard(self);
3277 // destroy the remaining elements
3279 ptr::drop_in_place(guard.0.as_raw_mut_slice());
3281 // now `guard` will be dropped and do the rest
3285 #[unstable(issue = "none", feature = "inplace_iteration")]
3286 unsafe impl<T, A: Allocator> InPlaceIterable for IntoIter<T, A> {}
3288 #[unstable(issue = "none", feature = "inplace_iteration")]
3289 unsafe impl<T, A: Allocator> SourceIter for IntoIter<T, A> {
3293 unsafe fn as_inner(&mut self) -> &mut Self::Source {
3298 // internal helper trait for in-place iteration specialization.
3299 #[rustc_specialization_trait]
3300 pub(crate) trait AsIntoIter {
3302 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item>;
3305 impl<T> AsIntoIter for IntoIter<T> {
3308 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item> {
3313 /// A draining iterator for `Vec<T>`.
3315 /// This `struct` is created by [`Vec::drain`].
3316 /// See its documentation for more.
3321 /// let mut v = vec![0, 1, 2];
3322 /// let iter: std::vec::Drain<_> = v.drain(..);
3324 #[stable(feature = "drain", since = "1.6.0")]
3328 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + 'a = Global,
3330 /// Index of tail to preserve
3334 /// Current remaining range to remove
3335 iter: slice::Iter<'a, T>,
3336 vec: NonNull<Vec<T, A>>,
3339 #[stable(feature = "collection_debug", since = "1.17.0")]
3340 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Drain<'_, T, A> {
3341 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3342 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
3346 impl<'a, T, A: Allocator> Drain<'a, T, A> {
3347 /// Returns the remaining items of this iterator as a slice.
3352 /// let mut vec = vec!['a', 'b', 'c'];
3353 /// let mut drain = vec.drain(..);
3354 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
3355 /// let _ = drain.next().unwrap();
3356 /// assert_eq!(drain.as_slice(), &['b', 'c']);
3358 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3359 pub fn as_slice(&self) -> &[T] {
3360 self.iter.as_slice()
3363 /// Returns a reference to the underlying allocator.
3364 #[unstable(feature = "allocator_api", issue = "32838")]
3366 pub fn allocator(&self) -> &A {
3367 unsafe { self.vec.as_ref().allocator() }
3371 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3372 impl<'a, T, A: Allocator> AsRef<[T]> for Drain<'a, T, A> {
3373 fn as_ref(&self) -> &[T] {
3378 #[stable(feature = "drain", since = "1.6.0")]
3379 unsafe impl<T: Sync, A: Sync + Allocator> Sync for Drain<'_, T, A> {}
3380 #[stable(feature = "drain", since = "1.6.0")]
3381 unsafe impl<T: Send, A: Send + Allocator> Send for Drain<'_, T, A> {}
3383 #[stable(feature = "drain", since = "1.6.0")]
3384 impl<T, A: Allocator> Iterator for Drain<'_, T, A> {
3388 fn next(&mut self) -> Option<T> {
3389 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
3392 fn size_hint(&self) -> (usize, Option<usize>) {
3393 self.iter.size_hint()
3397 #[stable(feature = "drain", since = "1.6.0")]
3398 impl<T, A: Allocator> DoubleEndedIterator for Drain<'_, T, A> {
3400 fn next_back(&mut self) -> Option<T> {
3401 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
3405 #[stable(feature = "drain", since = "1.6.0")]
3406 impl<T, A: Allocator> Drop for Drain<'_, T, A> {
3407 fn drop(&mut self) {
3408 /// Continues dropping the remaining elements in the `Drain`, then moves back the
3409 /// un-`Drain`ed elements to restore the original `Vec`.
3410 struct DropGuard<'r, 'a, T, A: Allocator>(&'r mut Drain<'a, T, A>);
3412 impl<'r, 'a, T, A: Allocator> Drop for DropGuard<'r, 'a, T, A> {
3413 fn drop(&mut self) {
3414 // Continue the same loop we have below. If the loop already finished, this does
3416 self.0.for_each(drop);
3418 if self.0.tail_len > 0 {
3420 let source_vec = self.0.vec.as_mut();
3421 // memmove back untouched tail, update to new length
3422 let start = source_vec.len();
3423 let tail = self.0.tail_start;
3425 let src = source_vec.as_ptr().add(tail);
3426 let dst = source_vec.as_mut_ptr().add(start);
3427 ptr::copy(src, dst, self.0.tail_len);
3429 source_vec.set_len(start + self.0.tail_len);
3435 // exhaust self first
3436 while let Some(item) = self.next() {
3437 let guard = DropGuard(self);
3442 // Drop a `DropGuard` to move back the non-drained tail of `self`.
3447 #[stable(feature = "drain", since = "1.6.0")]
3448 impl<T, A: Allocator> ExactSizeIterator for Drain<'_, T, A> {
3449 fn is_empty(&self) -> bool {
3450 self.iter.is_empty()
3454 #[unstable(feature = "trusted_len", issue = "37572")]
3455 unsafe impl<T, A: Allocator> TrustedLen for Drain<'_, T, A> {}
3457 #[stable(feature = "fused", since = "1.26.0")]
3458 impl<T, A: Allocator> FusedIterator for Drain<'_, T, A> {}
3460 /// A splicing iterator for `Vec`.
3462 /// This struct is created by [`Vec::splice()`].
3463 /// See its documentation for more.
3468 /// let mut v = vec![0, 1, 2];
3469 /// let new = [7, 8];
3470 /// let iter: std::vec::Splice<_> = v.splice(1.., new.iter().cloned());
3473 #[stable(feature = "vec_splice", since = "1.21.0")]
3477 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator + 'a = Global,
3479 drain: Drain<'a, I::Item, A>,
3483 #[stable(feature = "vec_splice", since = "1.21.0")]
3484 impl<I: Iterator, A: Allocator> Iterator for Splice<'_, I, A> {
3485 type Item = I::Item;
3487 fn next(&mut self) -> Option<Self::Item> {
3491 fn size_hint(&self) -> (usize, Option<usize>) {
3492 self.drain.size_hint()
3496 #[stable(feature = "vec_splice", since = "1.21.0")]
3497 impl<I: Iterator, A: Allocator> DoubleEndedIterator for Splice<'_, I, A> {
3498 fn next_back(&mut self) -> Option<Self::Item> {
3499 self.drain.next_back()
3503 #[stable(feature = "vec_splice", since = "1.21.0")]
3504 impl<I: Iterator, A: Allocator> ExactSizeIterator for Splice<'_, I, A> {}
3506 #[stable(feature = "vec_splice", since = "1.21.0")]
3507 impl<I: Iterator, A: Allocator> Drop for Splice<'_, I, A> {
3508 fn drop(&mut self) {
3509 self.drain.by_ref().for_each(drop);
3512 if self.drain.tail_len == 0 {
3513 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
3517 // First fill the range left by drain().
3518 if !self.drain.fill(&mut self.replace_with) {
3522 // There may be more elements. Use the lower bound as an estimate.
3523 // FIXME: Is the upper bound a better guess? Or something else?
3524 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
3525 if lower_bound > 0 {
3526 self.drain.move_tail(lower_bound);
3527 if !self.drain.fill(&mut self.replace_with) {
3532 // Collect any remaining elements.
3533 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
3534 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
3535 // Now we have an exact count.
3536 if collected.len() > 0 {
3537 self.drain.move_tail(collected.len());
3538 let filled = self.drain.fill(&mut collected);
3539 debug_assert!(filled);
3540 debug_assert_eq!(collected.len(), 0);
3543 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
3547 /// Private helper methods for `Splice::drop`
3548 impl<T, A: Allocator> Drain<'_, T, A> {
3549 /// The range from `self.vec.len` to `self.tail_start` contains elements
3550 /// that have been moved out.
3551 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
3552 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
3553 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
3554 let vec = unsafe { self.vec.as_mut() };
3555 let range_start = vec.len;
3556 let range_end = self.tail_start;
3557 let range_slice = unsafe {
3558 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
3561 for place in range_slice {
3562 if let Some(new_item) = replace_with.next() {
3563 unsafe { ptr::write(place, new_item) };
3572 /// Makes room for inserting more elements before the tail.
3573 unsafe fn move_tail(&mut self, additional: usize) {
3574 let vec = unsafe { self.vec.as_mut() };
3575 let len = self.tail_start + self.tail_len;
3576 vec.buf.reserve(len, additional);
3578 let new_tail_start = self.tail_start + additional;
3580 let src = vec.as_ptr().add(self.tail_start);
3581 let dst = vec.as_mut_ptr().add(new_tail_start);
3582 ptr::copy(src, dst, self.tail_len);
3584 self.tail_start = new_tail_start;
3588 /// An iterator which uses a closure to determine if an element should be removed.
3590 /// This struct is created by [`Vec::drain_filter`].
3591 /// See its documentation for more.
3596 /// #![feature(drain_filter)]
3598 /// let mut v = vec![0, 1, 2];
3599 /// let iter: std::vec::DrainFilter<_, _> = v.drain_filter(|x| *x % 2 == 0);
3601 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3603 pub struct DrainFilter<
3607 #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global,
3609 F: FnMut(&mut T) -> bool,
3611 vec: &'a mut Vec<T, A>,
3612 /// The index of the item that will be inspected by the next call to `next`.
3614 /// The number of items that have been drained (removed) thus far.
3616 /// The original length of `vec` prior to draining.
3618 /// The filter test predicate.
3620 /// A flag that indicates a panic has occurred in the filter test predicate.
3621 /// This is used as a hint in the drop implementation to prevent consumption
3622 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3623 /// backshifted in the `vec`, but no further items will be dropped or
3624 /// tested by the filter predicate.
3628 impl<T, F, A: Allocator> DrainFilter<'_, T, F, A>
3630 F: FnMut(&mut T) -> bool,
3632 /// Returns a reference to the underlying allocator.
3633 #[unstable(feature = "allocator_api", issue = "32838")]
3635 pub fn allocator(&self) -> &A {
3636 self.vec.allocator()
3640 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3641 impl<T, F, A: Allocator> Iterator for DrainFilter<'_, T, F, A>
3643 F: FnMut(&mut T) -> bool,
3647 fn next(&mut self) -> Option<T> {
3649 while self.idx < self.old_len {
3651 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3652 self.panic_flag = true;
3653 let drained = (self.pred)(&mut v[i]);
3654 self.panic_flag = false;
3655 // Update the index *after* the predicate is called. If the index
3656 // is updated prior and the predicate panics, the element at this
3657 // index would be leaked.
3661 return Some(ptr::read(&v[i]));
3662 } else if self.del > 0 {
3664 let src: *const T = &v[i];
3665 let dst: *mut T = &mut v[i - del];
3666 ptr::copy_nonoverlapping(src, dst, 1);
3673 fn size_hint(&self) -> (usize, Option<usize>) {
3674 (0, Some(self.old_len - self.idx))
3678 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3679 impl<T, F, A: Allocator> Drop for DrainFilter<'_, T, F, A>
3681 F: FnMut(&mut T) -> bool,
3683 fn drop(&mut self) {
3684 struct BackshiftOnDrop<'a, 'b, T, F, A: Allocator>
3686 F: FnMut(&mut T) -> bool,
3688 drain: &'b mut DrainFilter<'a, T, F, A>,
3691 impl<'a, 'b, T, F, A: Allocator> Drop for BackshiftOnDrop<'a, 'b, T, F, A>
3693 F: FnMut(&mut T) -> bool,
3695 fn drop(&mut self) {
3697 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3698 // This is a pretty messed up state, and there isn't really an
3699 // obviously right thing to do. We don't want to keep trying
3700 // to execute `pred`, so we just backshift all the unprocessed
3701 // elements and tell the vec that they still exist. The backshift
3702 // is required to prevent a double-drop of the last successfully
3703 // drained item prior to a panic in the predicate.
3704 let ptr = self.drain.vec.as_mut_ptr();
3705 let src = ptr.add(self.drain.idx);
3706 let dst = src.sub(self.drain.del);
3707 let tail_len = self.drain.old_len - self.drain.idx;
3708 src.copy_to(dst, tail_len);
3710 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3715 let backshift = BackshiftOnDrop { drain: self };
3717 // Attempt to consume any remaining elements if the filter predicate
3718 // has not yet panicked. We'll backshift any remaining elements
3719 // whether we've already panicked or if the consumption here panics.
3720 if !backshift.drain.panic_flag {
3721 backshift.drain.for_each(drop);