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::{AllocRef, 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: AllocRef = 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: AllocRef> 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.alloc_ref();
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.alloc_ref()) };
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 alloc_ref(&self) -> &A {
1062 self.buf.alloc_ref()
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.alloc_ref().clone()),
1627 let other_len = self.len - at;
1628 let mut other = Vec::with_capacity_in(other_len, self.alloc_ref().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: AllocRef> 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: AllocRef> 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: AllocRef> 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: AllocRef> 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: AllocRef>(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: AllocRef>(elem: Self, n: usize, alloc: A) -> Vec<Self, A>;
1971 impl<T: Clone> SpecFromElem for T {
1972 default fn from_elem<A: AllocRef>(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: AllocRef>(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: AllocRef>(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: AllocRef>(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: AllocRef> 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: AllocRef> 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: AllocRef + Clone> Clone for Vec<T, A> {
2114 fn clone(&self) -> Self {
2115 let alloc = self.alloc_ref().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.alloc_ref().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: AllocRef> 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: AllocRef> 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: AllocRef> 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: AllocRef> 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.alloc_ref());
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: AllocRef> 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: AllocRef> 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: AllocRef> 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 = Vec::new();
2331 // must delegate to spec_extend() since extend() itself delegates
2332 // to spec_from for empty Vecs
2333 vector.spec_extend(iterator);
2338 impl<T, I> SpecFromIter<T, I> for Vec<T>
2340 I: Iterator<Item = T>,
2342 default fn from_iter(iterator: I) -> Self {
2343 SpecFromIterNested::from_iter(iterator)
2347 // A helper struct for in-place iteration that drops the destination slice of iteration,
2348 // i.e. the head. The source slice (the tail) is dropped by IntoIter.
2349 struct InPlaceDrop<T> {
2354 impl<T> InPlaceDrop<T> {
2355 fn len(&self) -> usize {
2356 unsafe { self.dst.offset_from(self.inner) as usize }
2360 impl<T> Drop for InPlaceDrop<T> {
2362 fn drop(&mut self) {
2364 ptr::drop_in_place(slice::from_raw_parts_mut(self.inner, self.len()));
2369 impl<T> SpecFromIter<T, IntoIter<T>> for Vec<T> {
2370 fn from_iter(iterator: IntoIter<T>) -> Self {
2371 // A common case is passing a vector into a function which immediately
2372 // re-collects into a vector. We can short circuit this if the IntoIter
2373 // has not been advanced at all.
2374 // When it has been advanced We can also reuse the memory and move the data to the front.
2375 // But we only do so when the resulting Vec wouldn't have more unused capacity
2376 // than creating it through the generic FromIterator implementation would. That limitation
2377 // is not strictly necessary as Vec's allocation behavior is intentionally unspecified.
2378 // But it is a conservative choice.
2379 let has_advanced = iterator.buf.as_ptr() as *const _ != iterator.ptr;
2380 if !has_advanced || iterator.len() >= iterator.cap / 2 {
2382 let it = ManuallyDrop::new(iterator);
2384 ptr::copy(it.ptr, it.buf.as_ptr(), it.len());
2386 return Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap);
2390 let mut vec = Vec::new();
2391 // must delegate to spec_extend() since extend() itself delegates
2392 // to spec_from for empty Vecs
2393 vec.spec_extend(iterator);
2398 fn write_in_place_with_drop<T>(
2400 ) -> impl FnMut(InPlaceDrop<T>, T) -> Result<InPlaceDrop<T>, !> {
2401 move |mut sink, item| {
2403 // the InPlaceIterable contract cannot be verified precisely here since
2404 // try_fold has an exclusive reference to the source pointer
2405 // all we can do is check if it's still in range
2406 debug_assert!(sink.dst as *const _ <= src_end, "InPlaceIterable contract violation");
2407 ptr::write(sink.dst, item);
2408 sink.dst = sink.dst.add(1);
2414 /// Specialization marker for collecting an iterator pipeline into a Vec while reusing the
2415 /// source allocation, i.e. executing the pipeline in place.
2417 /// The SourceIter parent trait is necessary for the specializing function to access the allocation
2418 /// which is to be reused. But it is not sufficient for the specialization to be valid. See
2419 /// additional bounds on the impl.
2420 #[rustc_unsafe_specialization_marker]
2421 trait SourceIterMarker: SourceIter<Source: AsIntoIter> {}
2423 // The std-internal SourceIter/InPlaceIterable traits are only implemented by chains of
2424 // Adapter<Adapter<Adapter<IntoIter>>> (all owned by core/std). Additional bounds
2425 // on the adapter implementations (beyond `impl<I: Trait> Trait for Adapter<I>`) only depend on other
2426 // traits already marked as specialization traits (Copy, TrustedRandomAccess, FusedIterator).
2427 // I.e. the marker does not depend on lifetimes of user-supplied types. Modulo the Copy hole, which
2428 // several other specializations already depend on.
2429 impl<T> SourceIterMarker for T where T: SourceIter<Source: AsIntoIter> + InPlaceIterable {}
2431 impl<T, I> SpecFromIter<T, I> for Vec<T>
2433 I: Iterator<Item = T> + SourceIterMarker,
2435 default fn from_iter(mut iterator: I) -> Self {
2436 // Additional requirements which cannot expressed via trait bounds. We rely on const eval
2438 // a) no ZSTs as there would be no allocation to reuse and pointer arithmetic would panic
2439 // b) size match as required by Alloc contract
2440 // c) alignments match as required by Alloc contract
2441 if mem::size_of::<T>() == 0
2442 || mem::size_of::<T>()
2443 != mem::size_of::<<<I as SourceIter>::Source as AsIntoIter>::Item>()
2444 || mem::align_of::<T>()
2445 != mem::align_of::<<<I as SourceIter>::Source as AsIntoIter>::Item>()
2447 // fallback to more generic implementations
2448 return SpecFromIterNested::from_iter(iterator);
2451 let (src_buf, src_ptr, dst_buf, dst_end, cap) = unsafe {
2452 let inner = iterator.as_inner().as_into_iter();
2456 inner.buf.as_ptr() as *mut T,
2457 inner.end as *const T,
2462 // use try-fold since
2463 // - it vectorizes better for some iterator adapters
2464 // - unlike most internal iteration methods, it only takes a &mut self
2465 // - it lets us thread the write pointer through its innards and get it back in the end
2466 let sink = InPlaceDrop { inner: dst_buf, dst: dst_buf };
2468 .try_fold::<_, _, Result<_, !>>(sink, write_in_place_with_drop(dst_end))
2470 // iteration succeeded, don't drop head
2471 let dst = ManuallyDrop::new(sink).dst;
2473 let src = unsafe { iterator.as_inner().as_into_iter() };
2474 // check if SourceIter contract was upheld
2475 // caveat: if they weren't we may not even make it to this point
2476 debug_assert_eq!(src_buf, src.buf.as_ptr());
2477 // check InPlaceIterable contract. This is only possible if the iterator advanced the
2478 // source pointer at all. If it uses unchecked access via TrustedRandomAccess
2479 // then the source pointer will stay in its initial position and we can't use it as reference
2480 if src.ptr != src_ptr {
2482 dst as *const _ <= src.ptr,
2483 "InPlaceIterable contract violation, write pointer advanced beyond read pointer"
2487 // drop any remaining values at the tail of the source
2488 src.drop_remaining();
2489 // but prevent drop of the allocation itself once IntoIter goes out of scope
2490 src.forget_allocation();
2493 let len = dst.offset_from(dst_buf) as usize;
2494 Vec::from_raw_parts(dst_buf, len, cap)
2501 impl<'a, T: 'a, I> SpecFromIter<&'a T, I> for Vec<T>
2503 I: Iterator<Item = &'a T>,
2506 default fn from_iter(iterator: I) -> Self {
2507 SpecFromIter::from_iter(iterator.cloned())
2511 impl<'a, T: 'a> SpecFromIter<&'a T, slice::Iter<'a, T>> for Vec<T>
2515 // reuses the extend specialization for T: Copy
2516 fn from_iter(iterator: slice::Iter<'a, T>) -> Self {
2517 let mut vec = Vec::new();
2518 // must delegate to spec_extend() since extend() itself delegates
2519 // to spec_from for empty Vecs
2520 vec.spec_extend(iterator);
2525 // Specialization trait used for Vec::extend
2526 trait SpecExtend<T, I> {
2527 fn spec_extend(&mut self, iter: I);
2530 impl<T, I, A: AllocRef> SpecExtend<T, I> for Vec<T, A>
2532 I: Iterator<Item = T>,
2534 default fn spec_extend(&mut self, iter: I) {
2535 self.extend_desugared(iter)
2539 impl<T, I, A: AllocRef> SpecExtend<T, I> for Vec<T, A>
2541 I: TrustedLen<Item = T>,
2543 default fn spec_extend(&mut self, iterator: I) {
2544 // This is the case for a TrustedLen iterator.
2545 let (low, high) = iterator.size_hint();
2546 if let Some(high_value) = high {
2550 "TrustedLen iterator's size hint is not exact: {:?}",
2554 if let Some(additional) = high {
2555 self.reserve(additional);
2557 let mut ptr = self.as_mut_ptr().add(self.len());
2558 let mut local_len = SetLenOnDrop::new(&mut self.len);
2559 iterator.for_each(move |element| {
2560 ptr::write(ptr, element);
2561 ptr = ptr.offset(1);
2562 // NB can't overflow since we would have had to alloc the address space
2563 local_len.increment_len(1);
2567 self.extend_desugared(iterator)
2572 impl<T, A: AllocRef> SpecExtend<T, IntoIter<T>> for Vec<T, A> {
2573 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2575 self.append_elements(iterator.as_slice() as _);
2577 iterator.ptr = iterator.end;
2581 impl<'a, T: 'a, I, A: AllocRef + 'a> SpecExtend<&'a T, I> for Vec<T, A>
2583 I: Iterator<Item = &'a T>,
2586 default fn spec_extend(&mut self, iterator: I) {
2587 self.spec_extend(iterator.cloned())
2591 impl<'a, T: 'a, A: AllocRef + 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T, A>
2595 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2596 let slice = iterator.as_slice();
2597 unsafe { self.append_elements(slice) };
2601 impl<T, A: AllocRef> Vec<T, A> {
2602 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2603 // they have no further optimizations to apply
2604 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2605 // This is the case for a general iterator.
2607 // This function should be the moral equivalent of:
2609 // for item in iterator {
2612 while let Some(element) = iterator.next() {
2613 let len = self.len();
2614 if len == self.capacity() {
2615 let (lower, _) = iterator.size_hint();
2616 self.reserve(lower.saturating_add(1));
2619 ptr::write(self.as_mut_ptr().add(len), element);
2620 // NB can't overflow since we would have had to alloc the address space
2621 self.set_len(len + 1);
2626 /// Creates a splicing iterator that replaces the specified range in the vector
2627 /// with the given `replace_with` iterator and yields the removed items.
2628 /// `replace_with` does not need to be the same length as `range`.
2630 /// `range` is removed even if the iterator is not consumed until the end.
2632 /// It is unspecified how many elements are removed from the vector
2633 /// if the `Splice` value is leaked.
2635 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2637 /// This is optimal if:
2639 /// * The tail (elements in the vector after `range`) is empty,
2640 /// * or `replace_with` yields fewer elements than `range`’s length
2641 /// * or the lower bound of its `size_hint()` is exact.
2643 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2647 /// Panics if the starting point is greater than the end point or if
2648 /// the end point is greater than the length of the vector.
2653 /// let mut v = vec![1, 2, 3];
2654 /// let new = [7, 8];
2655 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2656 /// assert_eq!(v, &[7, 8, 3]);
2657 /// assert_eq!(u, &[1, 2]);
2660 #[stable(feature = "vec_splice", since = "1.21.0")]
2661 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
2663 R: RangeBounds<usize>,
2664 I: IntoIterator<Item = T>,
2666 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2669 /// Creates an iterator which uses a closure to determine if an element should be removed.
2671 /// If the closure returns true, then the element is removed and yielded.
2672 /// If the closure returns false, the element will remain in the vector and will not be yielded
2673 /// by the iterator.
2675 /// Using this method is equivalent to the following code:
2678 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2679 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2681 /// while i != vec.len() {
2682 /// if some_predicate(&mut vec[i]) {
2683 /// let val = vec.remove(i);
2684 /// // your code here
2690 /// # assert_eq!(vec, vec![1, 4, 5]);
2693 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2694 /// because it can backshift the elements of the array in bulk.
2696 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2697 /// regardless of whether you choose to keep or remove it.
2701 /// Splitting an array into evens and odds, reusing the original allocation:
2704 /// #![feature(drain_filter)]
2705 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2707 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2708 /// let odds = numbers;
2710 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2711 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2713 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2714 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F, A>
2716 F: FnMut(&mut T) -> bool,
2718 let old_len = self.len();
2720 // Guard against us getting leaked (leak amplification)
2725 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2729 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2731 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2732 /// append the entire slice at once.
2734 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2735 #[stable(feature = "extend_ref", since = "1.2.0")]
2736 impl<'a, T: Copy + 'a, A: AllocRef + 'a> Extend<&'a T> for Vec<T, A> {
2737 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2738 self.spec_extend(iter.into_iter())
2742 fn extend_one(&mut self, &item: &'a T) {
2747 fn extend_reserve(&mut self, additional: usize) {
2748 self.reserve(additional);
2752 macro_rules! __impl_slice_eq1 {
2753 ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => {
2755 impl<T, U, $($vars)*> PartialEq<$rhs> for $lhs
2761 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2763 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2768 __impl_slice_eq1! { [A: AllocRef] Vec<T, A>, Vec<U, A>, #[stable(feature = "rust1", since = "1.0.0")] }
2769 __impl_slice_eq1! { [A: AllocRef] Vec<T, A>, &[U], #[stable(feature = "rust1", since = "1.0.0")] }
2770 __impl_slice_eq1! { [A: AllocRef] Vec<T, A>, &mut [U], #[stable(feature = "rust1", since = "1.0.0")] }
2771 __impl_slice_eq1! { [A: AllocRef] &[T], Vec<U, A>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2772 __impl_slice_eq1! { [A: AllocRef] &mut [T], Vec<U, A>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2773 __impl_slice_eq1! { [A: AllocRef] Vec<T, A>, [U], #[stable(feature = "partialeq_vec_for_slice", since = "1.48.0")] }
2774 __impl_slice_eq1! { [A: AllocRef] [T], Vec<U, A>, #[stable(feature = "partialeq_vec_for_slice", since = "1.48.0")] }
2775 __impl_slice_eq1! { [A: AllocRef] Cow<'_, [T]>, Vec<U, A> where T: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2776 __impl_slice_eq1! { [] Cow<'_, [T]>, &[U] where T: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2777 __impl_slice_eq1! { [] Cow<'_, [T]>, &mut [U] where T: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2778 __impl_slice_eq1! { [A: AllocRef, const N: usize] Vec<T, A>, [U; N], #[stable(feature = "rust1", since = "1.0.0")] }
2779 __impl_slice_eq1! { [A: AllocRef, const N: usize] Vec<T, A>, &[U; N], #[stable(feature = "rust1", since = "1.0.0")] }
2781 // NOTE: some less important impls are omitted to reduce code bloat
2782 // FIXME(Centril): Reconsider this?
2783 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], }
2784 //__impl_slice_eq1! { [const N: usize] [A; N], Vec<B>, }
2785 //__impl_slice_eq1! { [const N: usize] &[A; N], Vec<B>, }
2786 //__impl_slice_eq1! { [const N: usize] &mut [A; N], Vec<B>, }
2787 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], }
2788 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], }
2789 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], }
2791 /// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2792 #[stable(feature = "rust1", since = "1.0.0")]
2793 impl<T: PartialOrd, A: AllocRef> PartialOrd for Vec<T, A> {
2795 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2796 PartialOrd::partial_cmp(&**self, &**other)
2800 #[stable(feature = "rust1", since = "1.0.0")]
2801 impl<T: Eq, A: AllocRef> Eq for Vec<T, A> {}
2803 /// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2804 #[stable(feature = "rust1", since = "1.0.0")]
2805 impl<T: Ord, A: AllocRef> Ord for Vec<T, A> {
2807 fn cmp(&self, other: &Self) -> Ordering {
2808 Ord::cmp(&**self, &**other)
2812 #[stable(feature = "rust1", since = "1.0.0")]
2813 unsafe impl<#[may_dangle] T, A: AllocRef> Drop for Vec<T, A> {
2814 fn drop(&mut self) {
2817 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2818 // could avoid questions of validity in certain cases
2819 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2821 // RawVec handles deallocation
2825 #[stable(feature = "rust1", since = "1.0.0")]
2826 impl<T> Default for Vec<T> {
2827 /// Creates an empty `Vec<T>`.
2828 fn default() -> Vec<T> {
2833 #[stable(feature = "rust1", since = "1.0.0")]
2834 impl<T: fmt::Debug, A: AllocRef> fmt::Debug for Vec<T, A> {
2835 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2836 fmt::Debug::fmt(&**self, f)
2840 #[stable(feature = "rust1", since = "1.0.0")]
2841 impl<T, A: AllocRef> AsRef<Vec<T, A>> for Vec<T, A> {
2842 fn as_ref(&self) -> &Vec<T, A> {
2847 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2848 impl<T, A: AllocRef> AsMut<Vec<T, A>> for Vec<T, A> {
2849 fn as_mut(&mut self) -> &mut Vec<T, A> {
2854 #[stable(feature = "rust1", since = "1.0.0")]
2855 impl<T, A: AllocRef> AsRef<[T]> for Vec<T, A> {
2856 fn as_ref(&self) -> &[T] {
2861 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2862 impl<T, A: AllocRef> AsMut<[T]> for Vec<T, A> {
2863 fn as_mut(&mut self) -> &mut [T] {
2868 #[stable(feature = "rust1", since = "1.0.0")]
2869 impl<T: Clone> From<&[T]> for Vec<T> {
2871 fn from(s: &[T]) -> Vec<T> {
2875 fn from(s: &[T]) -> Vec<T> {
2876 crate::slice::to_vec(s, Global)
2880 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2881 impl<T: Clone> From<&mut [T]> for Vec<T> {
2883 fn from(s: &mut [T]) -> Vec<T> {
2887 fn from(s: &mut [T]) -> Vec<T> {
2888 crate::slice::to_vec(s, Global)
2892 #[stable(feature = "vec_from_array", since = "1.44.0")]
2893 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2895 fn from(s: [T; N]) -> Vec<T> {
2896 <[T]>::into_vec(box s)
2899 fn from(s: [T; N]) -> Vec<T> {
2900 crate::slice::into_vec(box s)
2904 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2905 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2907 [T]: ToOwned<Owned = Vec<T>>,
2909 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2914 // note: test pulls in libstd, which causes errors here
2916 #[stable(feature = "vec_from_box", since = "1.18.0")]
2917 impl<T, A: AllocRef> From<Box<[T], A>> for Vec<T, A> {
2918 fn from(s: Box<[T], A>) -> Self {
2920 Self { buf: RawVec::from_box(s), len }
2924 // note: test pulls in libstd, which causes errors here
2926 #[stable(feature = "box_from_vec", since = "1.20.0")]
2927 impl<T, A: AllocRef> From<Vec<T, A>> for Box<[T], A> {
2928 fn from(v: Vec<T, A>) -> Self {
2929 v.into_boxed_slice()
2933 #[stable(feature = "rust1", since = "1.0.0")]
2934 impl From<&str> for Vec<u8> {
2935 fn from(s: &str) -> Vec<u8> {
2936 From::from(s.as_bytes())
2940 #[stable(feature = "array_try_from_vec", since = "1.48.0")]
2941 impl<T, A: AllocRef, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
2942 type Error = Vec<T, A>;
2944 /// Gets the entire contents of the `Vec<T>` as an array,
2945 /// if its size exactly matches that of the requested array.
2950 /// use std::convert::TryInto;
2951 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
2952 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
2955 /// If the length doesn't match, the input comes back in `Err`:
2957 /// use std::convert::TryInto;
2958 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
2959 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
2962 /// If you're fine with just getting a prefix of the `Vec<T>`,
2963 /// you can call [`.truncate(N)`](Vec::truncate) first.
2965 /// use std::convert::TryInto;
2966 /// let mut v = String::from("hello world").into_bytes();
2969 /// let [a, b]: [_; 2] = v.try_into().unwrap();
2970 /// assert_eq!(a, b' ');
2971 /// assert_eq!(b, b'd');
2973 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
2978 // SAFETY: `.set_len(0)` is always sound.
2979 unsafe { vec.set_len(0) };
2981 // SAFETY: A `Vec`'s pointer is always aligned properly, and
2982 // the alignment the array needs is the same as the items.
2983 // We checked earlier that we have sufficient items.
2984 // The items will not double-drop as the `set_len`
2985 // tells the `Vec` not to also drop them.
2986 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };
2991 ////////////////////////////////////////////////////////////////////////////////
2993 ////////////////////////////////////////////////////////////////////////////////
2995 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2996 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2997 fn from(s: &'a [T]) -> Cow<'a, [T]> {
3002 #[stable(feature = "cow_from_vec", since = "1.8.0")]
3003 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
3004 fn from(v: Vec<T>) -> Cow<'a, [T]> {
3009 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
3010 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
3011 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
3012 Cow::Borrowed(v.as_slice())
3016 #[stable(feature = "rust1", since = "1.0.0")]
3017 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
3021 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
3022 Cow::Owned(FromIterator::from_iter(it))
3026 ////////////////////////////////////////////////////////////////////////////////
3028 ////////////////////////////////////////////////////////////////////////////////
3030 /// An iterator that moves out of a vector.
3032 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
3033 /// by the [`IntoIterator`] trait).
3038 /// let v = vec![0, 1, 2];
3039 /// let iter: std::vec::IntoIter<_> = v.into_iter();
3041 #[stable(feature = "rust1", since = "1.0.0")]
3042 pub struct IntoIter<T, #[unstable(feature = "allocator_api", issue = "32838")] A: AllocRef = Global>
3045 phantom: PhantomData<T>,
3052 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
3053 impl<T: fmt::Debug, A: AllocRef> fmt::Debug for IntoIter<T, A> {
3054 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3055 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
3059 impl<T, A: AllocRef> IntoIter<T, A> {
3060 /// Returns the remaining items of this iterator as a slice.
3065 /// let vec = vec!['a', 'b', 'c'];
3066 /// let mut into_iter = vec.into_iter();
3067 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
3068 /// let _ = into_iter.next().unwrap();
3069 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
3071 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
3072 pub fn as_slice(&self) -> &[T] {
3073 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
3076 /// Returns the remaining items of this iterator as a mutable slice.
3081 /// let vec = vec!['a', 'b', 'c'];
3082 /// let mut into_iter = vec.into_iter();
3083 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
3084 /// into_iter.as_mut_slice()[2] = 'z';
3085 /// assert_eq!(into_iter.next().unwrap(), 'a');
3086 /// assert_eq!(into_iter.next().unwrap(), 'b');
3087 /// assert_eq!(into_iter.next().unwrap(), 'z');
3089 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
3090 pub fn as_mut_slice(&mut self) -> &mut [T] {
3091 unsafe { &mut *self.as_raw_mut_slice() }
3094 /// Returns a reference to the underlying allocator.
3095 #[unstable(feature = "allocator_api", issue = "32838")]
3097 pub fn alloc_ref(&self) -> &A {
3101 fn as_raw_mut_slice(&mut self) -> *mut [T] {
3102 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
3105 fn drop_remaining(&mut self) {
3107 ptr::drop_in_place(self.as_mut_slice());
3109 self.ptr = self.end;
3112 /// Relinquishes the backing allocation, equivalent to
3113 /// `ptr::write(&mut self, Vec::new().into_iter())`
3114 fn forget_allocation(&mut self) {
3116 self.buf = unsafe { NonNull::new_unchecked(RawVec::NEW.ptr()) };
3117 self.ptr = self.buf.as_ptr();
3118 self.end = self.buf.as_ptr();
3122 #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
3123 impl<T, A: AllocRef> AsRef<[T]> for IntoIter<T, A> {
3124 fn as_ref(&self) -> &[T] {
3129 #[stable(feature = "rust1", since = "1.0.0")]
3130 unsafe impl<T: Send, A: AllocRef + Send> Send for IntoIter<T, A> {}
3131 #[stable(feature = "rust1", since = "1.0.0")]
3132 unsafe impl<T: Sync, A: AllocRef> Sync for IntoIter<T, A> {}
3134 #[stable(feature = "rust1", since = "1.0.0")]
3135 impl<T, A: AllocRef> Iterator for IntoIter<T, A> {
3139 fn next(&mut self) -> Option<T> {
3140 if self.ptr as *const _ == self.end {
3142 } else if mem::size_of::<T>() == 0 {
3143 // purposefully don't use 'ptr.offset' because for
3144 // vectors with 0-size elements this would return the
3146 self.ptr = unsafe { arith_offset(self.ptr as *const i8, 1) as *mut T };
3148 // Make up a value of this ZST.
3149 Some(unsafe { mem::zeroed() })
3152 self.ptr = unsafe { self.ptr.offset(1) };
3154 Some(unsafe { ptr::read(old) })
3159 fn size_hint(&self) -> (usize, Option<usize>) {
3160 let exact = if mem::size_of::<T>() == 0 {
3161 (self.end as usize).wrapping_sub(self.ptr as usize)
3163 unsafe { self.end.offset_from(self.ptr) as usize }
3165 (exact, Some(exact))
3169 fn count(self) -> usize {
3173 unsafe fn __iterator_get_unchecked(&mut self, i: usize) -> Self::Item
3175 Self: TrustedRandomAccess,
3177 // SAFETY: the caller must guarantee that `i` is in bounds of the
3178 // `Vec<T>`, so `i` cannot overflow an `isize`, and the `self.ptr.add(i)`
3179 // is guaranteed to pointer to an element of the `Vec<T>` and
3180 // thus guaranteed to be valid to dereference.
3182 // Also note the implementation of `Self: TrustedRandomAccess` requires
3183 // that `T: Copy` so reading elements from the buffer doesn't invalidate
3186 if mem::size_of::<T>() == 0 { mem::zeroed() } else { ptr::read(self.ptr.add(i)) }
3191 #[stable(feature = "rust1", since = "1.0.0")]
3192 impl<T, A: AllocRef> DoubleEndedIterator for IntoIter<T, A> {
3194 fn next_back(&mut self) -> Option<T> {
3195 if self.end == self.ptr {
3197 } else if mem::size_of::<T>() == 0 {
3198 // See above for why 'ptr.offset' isn't used
3199 self.end = unsafe { arith_offset(self.end as *const i8, -1) as *mut T };
3201 // Make up a value of this ZST.
3202 Some(unsafe { mem::zeroed() })
3204 self.end = unsafe { self.end.offset(-1) };
3206 Some(unsafe { ptr::read(self.end) })
3211 #[stable(feature = "rust1", since = "1.0.0")]
3212 impl<T, A: AllocRef> ExactSizeIterator for IntoIter<T, A> {
3213 fn is_empty(&self) -> bool {
3214 self.ptr == self.end
3218 #[stable(feature = "fused", since = "1.26.0")]
3219 impl<T, A: AllocRef> FusedIterator for IntoIter<T, A> {}
3221 #[unstable(feature = "trusted_len", issue = "37572")]
3222 unsafe impl<T, A: AllocRef> TrustedLen for IntoIter<T, A> {}
3225 #[unstable(issue = "none", feature = "std_internals")]
3226 // T: Copy as approximation for !Drop since get_unchecked does not advance self.ptr
3227 // and thus we can't implement drop-handling
3228 unsafe impl<T, A: AllocRef> TrustedRandomAccess for IntoIter<T, A>
3232 fn may_have_side_effect() -> bool {
3237 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
3238 impl<T: Clone, A: AllocRef + Clone> Clone for IntoIter<T, A> {
3240 fn clone(&self) -> Self {
3241 self.as_slice().to_vec_in(self.alloc.clone()).into_iter()
3244 fn clone(&self) -> Self {
3245 crate::slice::to_vec(self.as_slice(), self.alloc.clone()).into_iter()
3249 #[stable(feature = "rust1", since = "1.0.0")]
3250 unsafe impl<#[may_dangle] T, A: AllocRef> Drop for IntoIter<T, A> {
3251 fn drop(&mut self) {
3252 struct DropGuard<'a, T, A: AllocRef>(&'a mut IntoIter<T, A>);
3254 impl<T, A: AllocRef> Drop for DropGuard<'_, T, A> {
3255 fn drop(&mut self) {
3257 // `IntoIter::alloc` is not used anymore after this
3258 let alloc = ptr::read(&self.0.alloc);
3259 // RawVec handles deallocation
3260 let _ = RawVec::from_raw_parts_in(self.0.buf.as_ptr(), self.0.cap, alloc);
3265 let guard = DropGuard(self);
3266 // destroy the remaining elements
3268 ptr::drop_in_place(guard.0.as_raw_mut_slice());
3270 // now `guard` will be dropped and do the rest
3274 #[unstable(issue = "none", feature = "inplace_iteration")]
3275 unsafe impl<T, A: AllocRef> InPlaceIterable for IntoIter<T, A> {}
3277 #[unstable(issue = "none", feature = "inplace_iteration")]
3278 unsafe impl<T, A: AllocRef> SourceIter for IntoIter<T, A> {
3282 unsafe fn as_inner(&mut self) -> &mut Self::Source {
3287 // internal helper trait for in-place iteration specialization.
3288 #[rustc_specialization_trait]
3289 pub(crate) trait AsIntoIter {
3291 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item>;
3294 impl<T> AsIntoIter for IntoIter<T> {
3297 fn as_into_iter(&mut self) -> &mut IntoIter<Self::Item> {
3302 /// A draining iterator for `Vec<T>`.
3304 /// This `struct` is created by [`Vec::drain`].
3305 /// See its documentation for more.
3310 /// let mut v = vec![0, 1, 2];
3311 /// let iter: std::vec::Drain<_> = v.drain(..);
3313 #[stable(feature = "drain", since = "1.6.0")]
3317 #[unstable(feature = "allocator_api", issue = "32838")] A: AllocRef + 'a = Global,
3319 /// Index of tail to preserve
3323 /// Current remaining range to remove
3324 iter: slice::Iter<'a, T>,
3325 vec: NonNull<Vec<T, A>>,
3328 #[stable(feature = "collection_debug", since = "1.17.0")]
3329 impl<T: fmt::Debug, A: AllocRef> fmt::Debug for Drain<'_, T, A> {
3330 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3331 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
3335 impl<'a, T, A: AllocRef> Drain<'a, T, A> {
3336 /// Returns the remaining items of this iterator as a slice.
3341 /// let mut vec = vec!['a', 'b', 'c'];
3342 /// let mut drain = vec.drain(..);
3343 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
3344 /// let _ = drain.next().unwrap();
3345 /// assert_eq!(drain.as_slice(), &['b', 'c']);
3347 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3348 pub fn as_slice(&self) -> &[T] {
3349 self.iter.as_slice()
3352 /// Returns a reference to the underlying allocator.
3353 #[unstable(feature = "allocator_api", issue = "32838")]
3355 pub fn alloc_ref(&self) -> &A {
3356 unsafe { self.vec.as_ref().alloc_ref() }
3360 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
3361 impl<'a, T, A: AllocRef> AsRef<[T]> for Drain<'a, T, A> {
3362 fn as_ref(&self) -> &[T] {
3367 #[stable(feature = "drain", since = "1.6.0")]
3368 unsafe impl<T: Sync, A: Sync + AllocRef> Sync for Drain<'_, T, A> {}
3369 #[stable(feature = "drain", since = "1.6.0")]
3370 unsafe impl<T: Send, A: Send + AllocRef> Send for Drain<'_, T, A> {}
3372 #[stable(feature = "drain", since = "1.6.0")]
3373 impl<T, A: AllocRef> Iterator for Drain<'_, T, A> {
3377 fn next(&mut self) -> Option<T> {
3378 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
3381 fn size_hint(&self) -> (usize, Option<usize>) {
3382 self.iter.size_hint()
3386 #[stable(feature = "drain", since = "1.6.0")]
3387 impl<T, A: AllocRef> DoubleEndedIterator for Drain<'_, T, A> {
3389 fn next_back(&mut self) -> Option<T> {
3390 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
3394 #[stable(feature = "drain", since = "1.6.0")]
3395 impl<T, A: AllocRef> Drop for Drain<'_, T, A> {
3396 fn drop(&mut self) {
3397 /// Continues dropping the remaining elements in the `Drain`, then moves back the
3398 /// un-`Drain`ed elements to restore the original `Vec`.
3399 struct DropGuard<'r, 'a, T, A: AllocRef>(&'r mut Drain<'a, T, A>);
3401 impl<'r, 'a, T, A: AllocRef> Drop for DropGuard<'r, 'a, T, A> {
3402 fn drop(&mut self) {
3403 // Continue the same loop we have below. If the loop already finished, this does
3405 self.0.for_each(drop);
3407 if self.0.tail_len > 0 {
3409 let source_vec = self.0.vec.as_mut();
3410 // memmove back untouched tail, update to new length
3411 let start = source_vec.len();
3412 let tail = self.0.tail_start;
3414 let src = source_vec.as_ptr().add(tail);
3415 let dst = source_vec.as_mut_ptr().add(start);
3416 ptr::copy(src, dst, self.0.tail_len);
3418 source_vec.set_len(start + self.0.tail_len);
3424 // exhaust self first
3425 while let Some(item) = self.next() {
3426 let guard = DropGuard(self);
3431 // Drop a `DropGuard` to move back the non-drained tail of `self`.
3436 #[stable(feature = "drain", since = "1.6.0")]
3437 impl<T, A: AllocRef> ExactSizeIterator for Drain<'_, T, A> {
3438 fn is_empty(&self) -> bool {
3439 self.iter.is_empty()
3443 #[unstable(feature = "trusted_len", issue = "37572")]
3444 unsafe impl<T, A: AllocRef> TrustedLen for Drain<'_, T, A> {}
3446 #[stable(feature = "fused", since = "1.26.0")]
3447 impl<T, A: AllocRef> FusedIterator for Drain<'_, T, A> {}
3449 /// A splicing iterator for `Vec`.
3451 /// This struct is created by [`Vec::splice()`].
3452 /// See its documentation for more.
3457 /// let mut v = vec![0, 1, 2];
3458 /// let new = [7, 8];
3459 /// let iter: std::vec::Splice<_> = v.splice(1.., new.iter().cloned());
3462 #[stable(feature = "vec_splice", since = "1.21.0")]
3466 #[unstable(feature = "allocator_api", issue = "32838")] A: AllocRef + 'a = Global,
3468 drain: Drain<'a, I::Item, A>,
3472 #[stable(feature = "vec_splice", since = "1.21.0")]
3473 impl<I: Iterator, A: AllocRef> Iterator for Splice<'_, I, A> {
3474 type Item = I::Item;
3476 fn next(&mut self) -> Option<Self::Item> {
3480 fn size_hint(&self) -> (usize, Option<usize>) {
3481 self.drain.size_hint()
3485 #[stable(feature = "vec_splice", since = "1.21.0")]
3486 impl<I: Iterator, A: AllocRef> DoubleEndedIterator for Splice<'_, I, A> {
3487 fn next_back(&mut self) -> Option<Self::Item> {
3488 self.drain.next_back()
3492 #[stable(feature = "vec_splice", since = "1.21.0")]
3493 impl<I: Iterator, A: AllocRef> ExactSizeIterator for Splice<'_, I, A> {}
3495 #[stable(feature = "vec_splice", since = "1.21.0")]
3496 impl<I: Iterator, A: AllocRef> Drop for Splice<'_, I, A> {
3497 fn drop(&mut self) {
3498 self.drain.by_ref().for_each(drop);
3501 if self.drain.tail_len == 0 {
3502 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
3506 // First fill the range left by drain().
3507 if !self.drain.fill(&mut self.replace_with) {
3511 // There may be more elements. Use the lower bound as an estimate.
3512 // FIXME: Is the upper bound a better guess? Or something else?
3513 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
3514 if lower_bound > 0 {
3515 self.drain.move_tail(lower_bound);
3516 if !self.drain.fill(&mut self.replace_with) {
3521 // Collect any remaining elements.
3522 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
3523 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
3524 // Now we have an exact count.
3525 if collected.len() > 0 {
3526 self.drain.move_tail(collected.len());
3527 let filled = self.drain.fill(&mut collected);
3528 debug_assert!(filled);
3529 debug_assert_eq!(collected.len(), 0);
3532 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
3536 /// Private helper methods for `Splice::drop`
3537 impl<T, A: AllocRef> Drain<'_, T, A> {
3538 /// The range from `self.vec.len` to `self.tail_start` contains elements
3539 /// that have been moved out.
3540 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
3541 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
3542 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
3543 let vec = unsafe { self.vec.as_mut() };
3544 let range_start = vec.len;
3545 let range_end = self.tail_start;
3546 let range_slice = unsafe {
3547 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
3550 for place in range_slice {
3551 if let Some(new_item) = replace_with.next() {
3552 unsafe { ptr::write(place, new_item) };
3561 /// Makes room for inserting more elements before the tail.
3562 unsafe fn move_tail(&mut self, additional: usize) {
3563 let vec = unsafe { self.vec.as_mut() };
3564 let len = self.tail_start + self.tail_len;
3565 vec.buf.reserve(len, additional);
3567 let new_tail_start = self.tail_start + additional;
3569 let src = vec.as_ptr().add(self.tail_start);
3570 let dst = vec.as_mut_ptr().add(new_tail_start);
3571 ptr::copy(src, dst, self.tail_len);
3573 self.tail_start = new_tail_start;
3577 /// An iterator which uses a closure to determine if an element should be removed.
3579 /// This struct is created by [`Vec::drain_filter`].
3580 /// See its documentation for more.
3585 /// #![feature(drain_filter)]
3587 /// let mut v = vec![0, 1, 2];
3588 /// let iter: std::vec::DrainFilter<_, _> = v.drain_filter(|x| *x % 2 == 0);
3590 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3592 pub struct DrainFilter<
3596 #[unstable(feature = "allocator_api", issue = "32838")] A: AllocRef = Global,
3598 F: FnMut(&mut T) -> bool,
3600 vec: &'a mut Vec<T, A>,
3601 /// The index of the item that will be inspected by the next call to `next`.
3603 /// The number of items that have been drained (removed) thus far.
3605 /// The original length of `vec` prior to draining.
3607 /// The filter test predicate.
3609 /// A flag that indicates a panic has occurred in the filter test predicate.
3610 /// This is used as a hint in the drop implementation to prevent consumption
3611 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3612 /// backshifted in the `vec`, but no further items will be dropped or
3613 /// tested by the filter predicate.
3617 impl<T, F, A: AllocRef> DrainFilter<'_, T, F, A>
3619 F: FnMut(&mut T) -> bool,
3621 /// Returns a reference to the underlying allocator.
3622 #[unstable(feature = "allocator_api", issue = "32838")]
3624 pub fn alloc_ref(&self) -> &A {
3625 self.vec.alloc_ref()
3629 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3630 impl<T, F, A: AllocRef> Iterator for DrainFilter<'_, T, F, A>
3632 F: FnMut(&mut T) -> bool,
3636 fn next(&mut self) -> Option<T> {
3638 while self.idx < self.old_len {
3640 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3641 self.panic_flag = true;
3642 let drained = (self.pred)(&mut v[i]);
3643 self.panic_flag = false;
3644 // Update the index *after* the predicate is called. If the index
3645 // is updated prior and the predicate panics, the element at this
3646 // index would be leaked.
3650 return Some(ptr::read(&v[i]));
3651 } else if self.del > 0 {
3653 let src: *const T = &v[i];
3654 let dst: *mut T = &mut v[i - del];
3655 ptr::copy_nonoverlapping(src, dst, 1);
3662 fn size_hint(&self) -> (usize, Option<usize>) {
3663 (0, Some(self.old_len - self.idx))
3667 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3668 impl<T, F, A: AllocRef> Drop for DrainFilter<'_, T, F, A>
3670 F: FnMut(&mut T) -> bool,
3672 fn drop(&mut self) {
3673 struct BackshiftOnDrop<'a, 'b, T, F, A: AllocRef>
3675 F: FnMut(&mut T) -> bool,
3677 drain: &'b mut DrainFilter<'a, T, F, A>,
3680 impl<'a, 'b, T, F, A: AllocRef> Drop for BackshiftOnDrop<'a, 'b, T, F, A>
3682 F: FnMut(&mut T) -> bool,
3684 fn drop(&mut self) {
3686 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3687 // This is a pretty messed up state, and there isn't really an
3688 // obviously right thing to do. We don't want to keep trying
3689 // to execute `pred`, so we just backshift all the unprocessed
3690 // elements and tell the vec that they still exist. The backshift
3691 // is required to prevent a double-drop of the last successfully
3692 // drained item prior to a panic in the predicate.
3693 let ptr = self.drain.vec.as_mut_ptr();
3694 let src = ptr.add(self.drain.idx);
3695 let dst = src.sub(self.drain.del);
3696 let tail_len = self.drain.old_len - self.drain.idx;
3697 src.copy_to(dst, tail_len);
3699 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3704 let backshift = BackshiftOnDrop { drain: self };
3706 // Attempt to consume any remaining elements if the filter predicate
3707 // has not yet panicked. We'll backshift any remaining elements
3708 // whether we've already panicked or if the consumption here panics.
3709 if !backshift.drain.panic_flag {
3710 backshift.drain.for_each(drop);