1 //! A contiguous growable array type with heap-allocated contents, written
4 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
5 //! `O(1)` pop (from the end).
9 //! You can explicitly create a [`Vec<T>`] with [`new`]:
12 //! let v: Vec<i32> = Vec::new();
15 //! ...or by using the [`vec!`] macro:
18 //! let v: Vec<i32> = vec![];
20 //! let v = vec![1, 2, 3, 4, 5];
22 //! let v = vec![0; 10]; // ten zeroes
25 //! You can [`push`] values onto the end of a vector (which will grow the vector
29 //! let mut v = vec![1, 2];
34 //! Popping values works in much the same way:
37 //! let mut v = vec![1, 2];
39 //! let two = v.pop();
42 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
45 //! let mut v = vec![1, 2, 3];
50 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
51 //! [`new`]: ../../std/vec/struct.Vec.html#method.new
52 //! [`push`]: ../../std/vec/struct.Vec.html#method.push
53 //! [`Index`]: ../../std/ops/trait.Index.html
54 //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
55 //! [`vec!`]: ../../std/macro.vec.html
57 #![stable(feature = "rust1", since = "1.0.0")]
59 use core::array::LengthAtMost32;
60 use core::cmp::{self, Ordering};
62 use core::hash::{self, Hash};
63 use core::intrinsics::{arith_offset, assume};
64 use core::iter::{FromIterator, FusedIterator, TrustedLen};
65 use core::marker::PhantomData;
67 use core::ops::{self, Index, IndexMut, RangeBounds};
68 use core::ops::Bound::{Excluded, Included, Unbounded};
69 use core::ptr::{self, NonNull};
70 use core::slice::{self, SliceIndex};
72 use crate::borrow::{ToOwned, Cow};
73 use crate::collections::TryReserveError;
74 use crate::boxed::Box;
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().cloned());
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 vec1 = Vec::with_capacity(5);
121 /// vec1.resize(5, 0);
124 /// Use a `Vec<T>` as an efficient stack:
127 /// let mut stack = Vec::new();
133 /// while let Some(top) = stack.pop() {
134 /// // Prints 3, 2, 1
135 /// println!("{}", top);
141 /// The `Vec` type allows to access values by index, because it implements the
142 /// [`Index`] trait. An example will be more explicit:
145 /// let v = vec![0, 2, 4, 6];
146 /// println!("{}", v[1]); // it will display '2'
149 /// However be careful: if you try to access an index which isn't in the `Vec`,
150 /// your software will panic! You cannot do this:
153 /// let v = vec![0, 2, 4, 6];
154 /// println!("{}", v[6]); // it will panic!
157 /// In conclusion: always check if the index you want to get really exists
162 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
163 /// To get a slice, use `&`. Example:
166 /// fn read_slice(slice: &[usize]) {
170 /// let v = vec![0, 1];
173 /// // ... and that's all!
174 /// // you can also do it like this:
175 /// let x : &[usize] = &v;
178 /// In Rust, it's more common to pass slices as arguments rather than vectors
179 /// when you just want to provide a read access. The same goes for [`String`] and
182 /// # Capacity and reallocation
184 /// The capacity of a vector is the amount of space allocated for any future
185 /// elements that will be added onto the vector. This is not to be confused with
186 /// the *length* of a vector, which specifies the number of actual elements
187 /// within the vector. If a vector's length exceeds its capacity, its capacity
188 /// will automatically be increased, but its elements will have to be
191 /// For example, a vector with capacity 10 and length 0 would be an empty vector
192 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
193 /// vector will not change its capacity or cause reallocation to occur. However,
194 /// if the vector's length is increased to 11, it will have to reallocate, which
195 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
196 /// whenever possible to specify how big the vector is expected to get.
200 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
201 /// about its design. This ensures that it's as low-overhead as possible in
202 /// the general case, and can be correctly manipulated in primitive ways
203 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
204 /// If additional type parameters are added (e.g., to support custom allocators),
205 /// overriding their defaults may change the behavior.
207 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
208 /// triplet. No more, no less. The order of these fields is completely
209 /// unspecified, and you should use the appropriate methods to modify these.
210 /// The pointer will never be null, so this type is null-pointer-optimized.
212 /// However, the pointer may not actually point to allocated memory. In particular,
213 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
214 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
215 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
216 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
217 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
218 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
219 /// details are very subtle — if you intend to allocate memory using a `Vec`
220 /// and use it for something else (either to pass to unsafe code, or to build your
221 /// own memory-backed collection), be sure to deallocate this memory by using
222 /// `from_raw_parts` to recover the `Vec` and then dropping it.
224 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
225 /// (as defined by the allocator Rust is configured to use by default), and its
226 /// pointer points to [`len`] initialized, contiguous elements in order (what
227 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
228 /// `[`len`] logically uninitialized, contiguous elements.
230 /// `Vec` will never perform a "small optimization" where elements are actually
231 /// stored on the stack for two reasons:
233 /// * It would make it more difficult for unsafe code to correctly manipulate
234 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
235 /// only moved, and it would be more difficult to determine if a `Vec` had
236 /// actually allocated memory.
238 /// * It would penalize the general case, incurring an additional branch
241 /// `Vec` will never automatically shrink itself, even if completely empty. This
242 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
243 /// and then filling it back up to the same [`len`] should incur no calls to
244 /// the allocator. If you wish to free up unused memory, use
245 /// [`shrink_to_fit`][`shrink_to_fit`].
247 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
248 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
249 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
250 /// accurate, and can be relied on. It can even be used to manually free the memory
251 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
252 /// when not necessary.
254 /// `Vec` does not guarantee any particular growth strategy when reallocating
255 /// when full, nor when [`reserve`] is called. The current strategy is basic
256 /// and it may prove desirable to use a non-constant growth factor. Whatever
257 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
259 /// `vec![x; n]`, `vec![a, b, c, d]`, and
260 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
261 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
262 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
263 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
265 /// `Vec` will not specifically overwrite any data that is removed from it,
266 /// but also won't specifically preserve it. Its uninitialized memory is
267 /// scratch space that it may use however it wants. It will generally just do
268 /// whatever is most efficient or otherwise easy to implement. Do not rely on
269 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
270 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
271 /// first, that may not actually happen because the optimizer does not consider
272 /// this a side-effect that must be preserved. There is one case which we will
273 /// not break, however: using `unsafe` code to write to the excess capacity,
274 /// and then increasing the length to match, is always valid.
276 /// `Vec` does not currently guarantee the order in which elements are dropped.
277 /// The order has changed in the past and may change again.
279 /// [`vec!`]: ../../std/macro.vec.html
280 /// [`Index`]: ../../std/ops/trait.Index.html
281 /// [`String`]: ../../std/string/struct.String.html
282 /// [`&str`]: ../../std/primitive.str.html
283 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
284 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
285 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
286 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
287 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
288 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
289 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
290 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
291 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
292 /// [owned slice]: ../../std/boxed/struct.Box.html
293 #[stable(feature = "rust1", since = "1.0.0")]
294 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
300 ////////////////////////////////////////////////////////////////////////////////
302 ////////////////////////////////////////////////////////////////////////////////
305 /// Constructs a new, empty `Vec<T>`.
307 /// The vector will not allocate until elements are pushed onto it.
312 /// # #![allow(unused_mut)]
313 /// let mut vec: Vec<i32> = Vec::new();
316 #[stable(feature = "rust1", since = "1.0.0")]
317 pub const fn new() -> Vec<T> {
324 /// Constructs a new, empty `Vec<T>` with the specified capacity.
326 /// The vector will be able to hold exactly `capacity` elements without
327 /// reallocating. If `capacity` is 0, the vector will not allocate.
329 /// It is important to note that although the returned vector has the
330 /// *capacity* specified, the vector will have a zero *length*. For an
331 /// explanation of the difference between length and capacity, see
332 /// *[Capacity and reallocation]*.
334 /// [Capacity and reallocation]: #capacity-and-reallocation
339 /// let mut vec = Vec::with_capacity(10);
341 /// // The vector contains no items, even though it has capacity for more
342 /// assert_eq!(vec.len(), 0);
344 /// // These are all done without reallocating...
349 /// // ...but this may make the vector reallocate
353 #[stable(feature = "rust1", since = "1.0.0")]
354 pub fn with_capacity(capacity: usize) -> Vec<T> {
356 buf: RawVec::with_capacity(capacity),
361 /// Creates a `Vec<T>` directly from the raw components of another vector.
365 /// This is highly unsafe, due to the number of invariants that aren't
368 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
369 /// (at least, it's highly likely to be incorrect if it wasn't).
370 /// * `ptr`'s `T` needs to have the same size and alignment as it was allocated with.
371 /// * `length` needs to be less than or equal to `capacity`.
372 /// * `capacity` needs to be the capacity that the pointer was allocated with.
374 /// Violating these may cause problems like corrupting the allocator's
375 /// internal data structures. For example it is **not** safe
376 /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`.
378 /// The ownership of `ptr` is effectively transferred to the
379 /// `Vec<T>` which may then deallocate, reallocate or change the
380 /// contents of memory pointed to by the pointer at will. Ensure
381 /// that nothing else uses the pointer after calling this
384 /// [`String`]: ../../std/string/struct.String.html
392 /// let mut v = vec![1, 2, 3];
394 /// // Pull out the various important pieces of information about `v`
395 /// let p = v.as_mut_ptr();
396 /// let len = v.len();
397 /// let cap = v.capacity();
400 /// // Cast `v` into the void: no destructor run, so we are in
401 /// // complete control of the allocation to which `p` points.
404 /// // Overwrite memory with 4, 5, 6
405 /// for i in 0..len as isize {
406 /// ptr::write(p.offset(i), 4 + i);
409 /// // Put everything back together into a Vec
410 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
411 /// assert_eq!(rebuilt, [4, 5, 6]);
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
417 buf: RawVec::from_raw_parts(ptr, capacity),
422 /// Returns the number of elements the vector can hold without
428 /// let vec: Vec<i32> = Vec::with_capacity(10);
429 /// assert_eq!(vec.capacity(), 10);
432 #[stable(feature = "rust1", since = "1.0.0")]
433 pub fn capacity(&self) -> usize {
437 /// Reserves capacity for at least `additional` more elements to be inserted
438 /// in the given `Vec<T>`. The collection may reserve more space to avoid
439 /// frequent reallocations. After calling `reserve`, capacity will be
440 /// greater than or equal to `self.len() + additional`. Does nothing if
441 /// capacity is already sufficient.
445 /// Panics if the new capacity overflows `usize`.
450 /// let mut vec = vec![1];
452 /// assert!(vec.capacity() >= 11);
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn reserve(&mut self, additional: usize) {
456 self.buf.reserve(self.len, additional);
459 /// Reserves the minimum capacity for exactly `additional` more elements to
460 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
461 /// capacity will be greater than or equal to `self.len() + additional`.
462 /// Does nothing if the capacity is already sufficient.
464 /// Note that the allocator may give the collection more space than it
465 /// requests. Therefore, capacity can not be relied upon to be precisely
466 /// minimal. Prefer `reserve` if future insertions are expected.
470 /// Panics if the new capacity overflows `usize`.
475 /// let mut vec = vec![1];
476 /// vec.reserve_exact(10);
477 /// assert!(vec.capacity() >= 11);
479 #[stable(feature = "rust1", since = "1.0.0")]
480 pub fn reserve_exact(&mut self, additional: usize) {
481 self.buf.reserve_exact(self.len, additional);
484 /// Tries to reserve capacity for at least `additional` more elements to be inserted
485 /// in the given `Vec<T>`. The collection may reserve more space to avoid
486 /// frequent reallocations. After calling `reserve`, capacity will be
487 /// greater than or equal to `self.len() + additional`. Does nothing if
488 /// capacity is already sufficient.
492 /// If the capacity overflows, or the allocator reports a failure, then an error
498 /// #![feature(try_reserve)]
499 /// use std::collections::TryReserveError;
501 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
502 /// let mut output = Vec::new();
504 /// // Pre-reserve the memory, exiting if we can't
505 /// output.try_reserve(data.len())?;
507 /// // Now we know this can't OOM in the middle of our complex work
508 /// output.extend(data.iter().map(|&val| {
509 /// val * 2 + 5 // very complicated
514 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
516 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
517 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
518 self.buf.try_reserve(self.len, additional)
521 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
522 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
523 /// capacity will be greater than or equal to `self.len() + additional`.
524 /// Does nothing if the capacity is already sufficient.
526 /// Note that the allocator may give the collection more space than it
527 /// requests. Therefore, capacity can not be relied upon to be precisely
528 /// minimal. Prefer `reserve` if future insertions are expected.
532 /// If the capacity overflows, or the allocator reports a failure, then an error
538 /// #![feature(try_reserve)]
539 /// use std::collections::TryReserveError;
541 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
542 /// let mut output = Vec::new();
544 /// // Pre-reserve the memory, exiting if we can't
545 /// output.try_reserve(data.len())?;
547 /// // Now we know this can't OOM in the middle of our complex work
548 /// output.extend(data.iter().map(|&val| {
549 /// val * 2 + 5 // very complicated
554 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
556 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
557 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
558 self.buf.try_reserve_exact(self.len, additional)
561 /// Shrinks the capacity of the vector as much as possible.
563 /// It will drop down as close as possible to the length but the allocator
564 /// may still inform the vector that there is space for a few more elements.
569 /// let mut vec = Vec::with_capacity(10);
570 /// vec.extend([1, 2, 3].iter().cloned());
571 /// assert_eq!(vec.capacity(), 10);
572 /// vec.shrink_to_fit();
573 /// assert!(vec.capacity() >= 3);
575 #[stable(feature = "rust1", since = "1.0.0")]
576 pub fn shrink_to_fit(&mut self) {
577 if self.capacity() != self.len {
578 self.buf.shrink_to_fit(self.len);
582 /// Shrinks the capacity of the vector with a lower bound.
584 /// The capacity will remain at least as large as both the length
585 /// and the supplied value.
587 /// Panics if the current capacity is smaller than the supplied
588 /// minimum capacity.
593 /// #![feature(shrink_to)]
594 /// let mut vec = Vec::with_capacity(10);
595 /// vec.extend([1, 2, 3].iter().cloned());
596 /// assert_eq!(vec.capacity(), 10);
597 /// vec.shrink_to(4);
598 /// assert!(vec.capacity() >= 4);
599 /// vec.shrink_to(0);
600 /// assert!(vec.capacity() >= 3);
602 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
603 pub fn shrink_to(&mut self, min_capacity: usize) {
604 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
607 /// Converts the vector into [`Box<[T]>`][owned slice].
609 /// Note that this will drop any excess capacity.
611 /// [owned slice]: ../../std/boxed/struct.Box.html
616 /// let v = vec![1, 2, 3];
618 /// let slice = v.into_boxed_slice();
621 /// Any excess capacity is removed:
624 /// let mut vec = Vec::with_capacity(10);
625 /// vec.extend([1, 2, 3].iter().cloned());
627 /// assert_eq!(vec.capacity(), 10);
628 /// let slice = vec.into_boxed_slice();
629 /// assert_eq!(slice.into_vec().capacity(), 3);
631 #[stable(feature = "rust1", since = "1.0.0")]
632 pub fn into_boxed_slice(mut self) -> Box<[T]> {
634 self.shrink_to_fit();
635 let buf = ptr::read(&self.buf);
641 /// Shortens the vector, keeping the first `len` elements and dropping
644 /// If `len` is greater than the vector's current length, this has no
647 /// The [`drain`] method can emulate `truncate`, but causes the excess
648 /// elements to be returned instead of dropped.
650 /// Note that this method has no effect on the allocated capacity
655 /// Truncating a five element vector to two elements:
658 /// let mut vec = vec![1, 2, 3, 4, 5];
660 /// assert_eq!(vec, [1, 2]);
663 /// No truncation occurs when `len` is greater than the vector's current
667 /// let mut vec = vec![1, 2, 3];
669 /// assert_eq!(vec, [1, 2, 3]);
672 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
676 /// let mut vec = vec![1, 2, 3];
678 /// assert_eq!(vec, []);
681 /// [`clear`]: #method.clear
682 /// [`drain`]: #method.drain
683 #[stable(feature = "rust1", since = "1.0.0")]
684 pub fn truncate(&mut self, len: usize) {
685 if mem::needs_drop::<T>() {
686 let current_len = self.len;
688 let mut ptr = self.as_mut_ptr().add(self.len);
689 // Set the final length at the end, keeping in mind that
690 // dropping an element might panic. Works around a missed
691 // optimization, as seen in the following issue:
692 // https://github.com/rust-lang/rust/issues/51802
693 let mut local_len = SetLenOnDrop::new(&mut self.len);
695 // drop any extra elements
696 for _ in len..current_len {
697 local_len.decrement_len(1);
698 ptr = ptr.offset(-1);
699 ptr::drop_in_place(ptr);
702 } else if len <= self.len {
707 /// Extracts a slice containing the entire vector.
709 /// Equivalent to `&s[..]`.
714 /// use std::io::{self, Write};
715 /// let buffer = vec![1, 2, 3, 5, 8];
716 /// io::sink().write(buffer.as_slice()).unwrap();
719 #[stable(feature = "vec_as_slice", since = "1.7.0")]
720 pub fn as_slice(&self) -> &[T] {
724 /// Extracts a mutable slice of the entire vector.
726 /// Equivalent to `&mut s[..]`.
731 /// use std::io::{self, Read};
732 /// let mut buffer = vec![0; 3];
733 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
736 #[stable(feature = "vec_as_slice", since = "1.7.0")]
737 pub fn as_mut_slice(&mut self) -> &mut [T] {
741 /// Returns a raw pointer to the vector's buffer.
743 /// The caller must ensure that the vector outlives the pointer this
744 /// function returns, or else it will end up pointing to garbage.
745 /// Modifying the vector may cause its buffer to be reallocated,
746 /// which would also make any pointers to it invalid.
748 /// The caller must also ensure that the memory the pointer (non-transitively) points to
749 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
750 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
755 /// let x = vec![1, 2, 4];
756 /// let x_ptr = x.as_ptr();
759 /// for i in 0..x.len() {
760 /// assert_eq!(*x_ptr.add(i), 1 << i);
765 /// [`as_mut_ptr`]: #method.as_mut_ptr
766 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
768 pub fn as_ptr(&self) -> *const T {
769 // We shadow the slice method of the same name to avoid going through
770 // `deref`, which creates an intermediate reference.
771 let ptr = self.buf.ptr();
772 unsafe { assume(!ptr.is_null()); }
776 /// Returns an unsafe mutable pointer to the vector's buffer.
778 /// The caller must ensure that the vector outlives the pointer this
779 /// function returns, or else it will end up pointing to garbage.
780 /// Modifying the vector may cause its buffer to be reallocated,
781 /// which would also make any pointers to it invalid.
786 /// // Allocate vector big enough for 4 elements.
788 /// let mut x: Vec<i32> = Vec::with_capacity(size);
789 /// let x_ptr = x.as_mut_ptr();
791 /// // Initialize elements via raw pointer writes, then set length.
793 /// for i in 0..size {
794 /// *x_ptr.add(i) = i as i32;
798 /// assert_eq!(&*x, &[0,1,2,3]);
800 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
802 pub fn as_mut_ptr(&mut self) -> *mut T {
803 // We shadow the slice method of the same name to avoid going through
804 // `deref_mut`, which creates an intermediate reference.
805 let ptr = self.buf.ptr();
806 unsafe { assume(!ptr.is_null()); }
810 /// Forces the length of the vector to `new_len`.
812 /// This is a low-level operation that maintains none of the normal
813 /// invariants of the type. Normally changing the length of a vector
814 /// is done using one of the safe operations instead, such as
815 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
817 /// [`truncate`]: #method.truncate
818 /// [`resize`]: #method.resize
819 /// [`extend`]: #method.extend-1
820 /// [`clear`]: #method.clear
824 /// - `new_len` must be less than or equal to [`capacity()`].
825 /// - The elements at `old_len..new_len` must be initialized.
827 /// [`capacity()`]: #method.capacity
831 /// This method can be useful for situations in which the vector
832 /// is serving as a buffer for other code, particularly over FFI:
835 /// # #![allow(dead_code)]
836 /// # // This is just a minimal skeleton for the doc example;
837 /// # // don't use this as a starting point for a real library.
838 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
839 /// # const Z_OK: i32 = 0;
841 /// # fn deflateGetDictionary(
842 /// # strm: *mut std::ffi::c_void,
843 /// # dictionary: *mut u8,
844 /// # dictLength: *mut usize,
847 /// # impl StreamWrapper {
848 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
849 /// // Per the FFI method's docs, "32768 bytes is always enough".
850 /// let mut dict = Vec::with_capacity(32_768);
851 /// let mut dict_length = 0;
852 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
853 /// // 1. `dict_length` elements were initialized.
854 /// // 2. `dict_length` <= the capacity (32_768)
855 /// // which makes `set_len` safe to call.
857 /// // Make the FFI call...
858 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
860 /// // ...and update the length to what was initialized.
861 /// dict.set_len(dict_length);
871 /// While the following example is sound, there is a memory leak since
872 /// the inner vectors were not freed prior to the `set_len` call:
875 /// let mut vec = vec![vec![1, 0, 0],
879 /// // 1. `old_len..0` is empty so no elements need to be initialized.
880 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
886 /// Normally, here, one would use [`clear`] instead to correctly drop
887 /// the contents and thus not leak memory.
889 #[stable(feature = "rust1", since = "1.0.0")]
890 pub unsafe fn set_len(&mut self, new_len: usize) {
891 debug_assert!(new_len <= self.capacity());
896 /// Removes an element from the vector and returns it.
898 /// The removed element is replaced by the last element of the vector.
900 /// This does not preserve ordering, but is O(1).
904 /// Panics if `index` is out of bounds.
909 /// let mut v = vec!["foo", "bar", "baz", "qux"];
911 /// assert_eq!(v.swap_remove(1), "bar");
912 /// assert_eq!(v, ["foo", "qux", "baz"]);
914 /// assert_eq!(v.swap_remove(0), "foo");
915 /// assert_eq!(v, ["baz", "qux"]);
918 #[stable(feature = "rust1", since = "1.0.0")]
919 pub fn swap_remove(&mut self, index: usize) -> T {
921 // We replace self[index] with the last element. Note that if the
922 // bounds check on hole succeeds there must be a last element (which
923 // can be self[index] itself).
924 let hole: *mut T = &mut self[index];
925 let last = ptr::read(self.get_unchecked(self.len - 1));
927 ptr::replace(hole, last)
931 /// Inserts an element at position `index` within the vector, shifting all
932 /// elements after it to the right.
936 /// Panics if `index > len`.
941 /// let mut vec = vec![1, 2, 3];
942 /// vec.insert(1, 4);
943 /// assert_eq!(vec, [1, 4, 2, 3]);
944 /// vec.insert(4, 5);
945 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
947 #[stable(feature = "rust1", since = "1.0.0")]
948 pub fn insert(&mut self, index: usize, element: T) {
949 let len = self.len();
950 assert!(index <= len);
952 // space for the new element
953 if len == self.buf.capacity() {
959 // The spot to put the new value
961 let p = self.as_mut_ptr().add(index);
962 // Shift everything over to make space. (Duplicating the
963 // `index`th element into two consecutive places.)
964 ptr::copy(p, p.offset(1), len - index);
965 // Write it in, overwriting the first copy of the `index`th
967 ptr::write(p, element);
969 self.set_len(len + 1);
973 /// Removes and returns the element at position `index` within the vector,
974 /// shifting all elements after it to the left.
978 /// Panics if `index` is out of bounds.
983 /// let mut v = vec![1, 2, 3];
984 /// assert_eq!(v.remove(1), 2);
985 /// assert_eq!(v, [1, 3]);
987 #[stable(feature = "rust1", since = "1.0.0")]
988 pub fn remove(&mut self, index: usize) -> T {
989 let len = self.len();
990 assert!(index < len);
995 // the place we are taking from.
996 let ptr = self.as_mut_ptr().add(index);
997 // copy it out, unsafely having a copy of the value on
998 // the stack and in the vector at the same time.
999 ret = ptr::read(ptr);
1001 // Shift everything down to fill in that spot.
1002 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1004 self.set_len(len - 1);
1009 /// Retains only the elements specified by the predicate.
1011 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1012 /// This method operates in place, visiting each element exactly once in the
1013 /// original order, and preserves the order of the retained elements.
1018 /// let mut vec = vec![1, 2, 3, 4];
1019 /// vec.retain(|&x| x%2 == 0);
1020 /// assert_eq!(vec, [2, 4]);
1023 /// The exact order may be useful for tracking external state, like an index.
1026 /// let mut vec = vec![1, 2, 3, 4, 5];
1027 /// let keep = [false, true, true, false, true];
1029 /// vec.retain(|_| (keep[i], i += 1).0);
1030 /// assert_eq!(vec, [2, 3, 5]);
1032 #[stable(feature = "rust1", since = "1.0.0")]
1033 pub fn retain<F>(&mut self, mut f: F)
1034 where F: FnMut(&T) -> bool
1036 self.drain_filter(|x| !f(x));
1039 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1042 /// If the vector is sorted, this removes all duplicates.
1047 /// let mut vec = vec![10, 20, 21, 30, 20];
1049 /// vec.dedup_by_key(|i| *i / 10);
1051 /// assert_eq!(vec, [10, 20, 30, 20]);
1053 #[stable(feature = "dedup_by", since = "1.16.0")]
1055 pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
1056 self.dedup_by(|a, b| key(a) == key(b))
1059 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1062 /// The `same_bucket` function is passed references to two elements from the vector and
1063 /// must determine if the elements compare equal. The elements are passed in opposite order
1064 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1066 /// If the vector is sorted, this removes all duplicates.
1071 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1073 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1075 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1077 #[stable(feature = "dedup_by", since = "1.16.0")]
1078 pub fn dedup_by<F>(&mut self, same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
1080 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1086 /// Appends an element to the back of a collection.
1090 /// Panics if the number of elements in the vector overflows a `usize`.
1095 /// let mut vec = vec![1, 2];
1097 /// assert_eq!(vec, [1, 2, 3]);
1100 #[stable(feature = "rust1", since = "1.0.0")]
1101 pub fn push(&mut self, value: T) {
1102 // This will panic or abort if we would allocate > isize::MAX bytes
1103 // or if the length increment would overflow for zero-sized types.
1104 if self.len == self.buf.capacity() {
1108 let end = self.as_mut_ptr().add(self.len);
1109 ptr::write(end, value);
1114 /// Removes the last element from a vector and returns it, or [`None`] if it
1117 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1122 /// let mut vec = vec![1, 2, 3];
1123 /// assert_eq!(vec.pop(), Some(3));
1124 /// assert_eq!(vec, [1, 2]);
1127 #[stable(feature = "rust1", since = "1.0.0")]
1128 pub fn pop(&mut self) -> Option<T> {
1134 Some(ptr::read(self.get_unchecked(self.len())))
1139 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1143 /// Panics if the number of elements in the vector overflows a `usize`.
1148 /// let mut vec = vec![1, 2, 3];
1149 /// let mut vec2 = vec![4, 5, 6];
1150 /// vec.append(&mut vec2);
1151 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1152 /// assert_eq!(vec2, []);
1155 #[stable(feature = "append", since = "1.4.0")]
1156 pub fn append(&mut self, other: &mut Self) {
1158 self.append_elements(other.as_slice() as _);
1163 /// Appends elements to `Self` from other buffer.
1165 unsafe fn append_elements(&mut self, other: *const [T]) {
1166 let count = (*other).len();
1167 self.reserve(count);
1168 let len = self.len();
1169 ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count);
1173 /// Creates a draining iterator that removes the specified range in the vector
1174 /// and yields the removed items.
1176 /// Note 1: The element range is removed even if the iterator is only
1177 /// partially consumed or not consumed at all.
1179 /// Note 2: It is unspecified how many elements are removed from the vector
1180 /// if the `Drain` value is leaked.
1184 /// Panics if the starting point is greater than the end point or if
1185 /// the end point is greater than the length of the vector.
1190 /// let mut v = vec![1, 2, 3];
1191 /// let u: Vec<_> = v.drain(1..).collect();
1192 /// assert_eq!(v, &[1]);
1193 /// assert_eq!(u, &[2, 3]);
1195 /// // A full range clears the vector
1197 /// assert_eq!(v, &[]);
1199 #[stable(feature = "drain", since = "1.6.0")]
1200 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1201 where R: RangeBounds<usize>
1205 // When the Drain is first created, it shortens the length of
1206 // the source vector to make sure no uninitialized or moved-from elements
1207 // are accessible at all if the Drain's destructor never gets to run.
1209 // Drain will ptr::read out the values to remove.
1210 // When finished, remaining tail of the vec is copied back to cover
1211 // the hole, and the vector length is restored to the new length.
1213 let len = self.len();
1214 let start = match range.start_bound() {
1216 Excluded(&n) => n + 1,
1219 let end = match range.end_bound() {
1220 Included(&n) => n + 1,
1224 assert!(start <= end);
1225 assert!(end <= len);
1228 // set self.vec length's to start, to be safe in case Drain is leaked
1229 self.set_len(start);
1230 // Use the borrow in the IterMut to indicate borrowing behavior of the
1231 // whole Drain iterator (like &mut T).
1232 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start),
1236 tail_len: len - end,
1237 iter: range_slice.iter(),
1238 vec: NonNull::from(self),
1243 /// Clears the vector, removing all values.
1245 /// Note that this method has no effect on the allocated capacity
1251 /// let mut v = vec![1, 2, 3];
1255 /// assert!(v.is_empty());
1258 #[stable(feature = "rust1", since = "1.0.0")]
1259 pub fn clear(&mut self) {
1263 /// Returns the number of elements in the vector, also referred to
1264 /// as its 'length'.
1269 /// let a = vec![1, 2, 3];
1270 /// assert_eq!(a.len(), 3);
1273 #[stable(feature = "rust1", since = "1.0.0")]
1274 pub fn len(&self) -> usize {
1278 /// Returns `true` if the vector contains no elements.
1283 /// let mut v = Vec::new();
1284 /// assert!(v.is_empty());
1287 /// assert!(!v.is_empty());
1289 #[stable(feature = "rust1", since = "1.0.0")]
1290 pub fn is_empty(&self) -> bool {
1294 /// Splits the collection into two at the given index.
1296 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1297 /// and the returned `Self` contains elements `[at, len)`.
1299 /// Note that the capacity of `self` does not change.
1303 /// Panics if `at > len`.
1308 /// let mut vec = vec![1,2,3];
1309 /// let vec2 = vec.split_off(1);
1310 /// assert_eq!(vec, [1]);
1311 /// assert_eq!(vec2, [2, 3]);
1314 #[stable(feature = "split_off", since = "1.4.0")]
1315 pub fn split_off(&mut self, at: usize) -> Self {
1316 assert!(at <= self.len(), "`at` out of bounds");
1318 let other_len = self.len - at;
1319 let mut other = Vec::with_capacity(other_len);
1321 // Unsafely `set_len` and copy items to `other`.
1324 other.set_len(other_len);
1326 ptr::copy_nonoverlapping(self.as_ptr().add(at),
1333 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1335 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1336 /// difference, with each additional slot filled with the result of
1337 /// calling the closure `f`. The return values from `f` will end up
1338 /// in the `Vec` in the order they have been generated.
1340 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1342 /// This method uses a closure to create new values on every push. If
1343 /// you'd rather [`Clone`] a given value, use [`resize`]. If you want
1344 /// to use the [`Default`] trait to generate values, you can pass
1345 /// [`Default::default()`] as the second argument.
1350 /// let mut vec = vec![1, 2, 3];
1351 /// vec.resize_with(5, Default::default);
1352 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1354 /// let mut vec = vec![];
1356 /// vec.resize_with(4, || { p *= 2; p });
1357 /// assert_eq!(vec, [2, 4, 8, 16]);
1360 /// [`resize`]: #method.resize
1361 /// [`Clone`]: ../../std/clone/trait.Clone.html
1362 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1363 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1364 where F: FnMut() -> T
1366 let len = self.len();
1368 self.extend_with(new_len - len, ExtendFunc(f));
1370 self.truncate(new_len);
1374 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1375 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1376 /// `'a`. If the type has only static references, or none at all, then this
1377 /// may be chosen to be `'static`.
1379 /// This function is similar to the `leak` function on `Box`.
1381 /// This function is mainly useful for data that lives for the remainder of
1382 /// the program's life. Dropping the returned reference will cause a memory
1390 /// #![feature(vec_leak)]
1392 /// let x = vec![1, 2, 3];
1393 /// let static_ref: &'static mut [usize] = Vec::leak(x);
1394 /// static_ref[0] += 1;
1395 /// assert_eq!(static_ref, &[2, 2, 3]);
1397 #[unstable(feature = "vec_leak", issue = "62195")]
1399 pub fn leak<'a>(vec: Vec<T>) -> &'a mut [T]
1401 T: 'a // Technically not needed, but kept to be explicit.
1403 Box::leak(vec.into_boxed_slice())
1407 impl<T: Clone> Vec<T> {
1408 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1410 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1411 /// difference, with each additional slot filled with `value`.
1412 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1414 /// This method requires [`Clone`] to be able clone the passed value. If
1415 /// you need more flexibility (or want to rely on [`Default`] instead of
1416 /// [`Clone`]), use [`resize_with`].
1421 /// let mut vec = vec!["hello"];
1422 /// vec.resize(3, "world");
1423 /// assert_eq!(vec, ["hello", "world", "world"]);
1425 /// let mut vec = vec![1, 2, 3, 4];
1426 /// vec.resize(2, 0);
1427 /// assert_eq!(vec, [1, 2]);
1430 /// [`Clone`]: ../../std/clone/trait.Clone.html
1431 /// [`Default`]: ../../std/default/trait.Default.html
1432 /// [`resize_with`]: #method.resize_with
1433 #[stable(feature = "vec_resize", since = "1.5.0")]
1434 pub fn resize(&mut self, new_len: usize, value: T) {
1435 let len = self.len();
1438 self.extend_with(new_len - len, ExtendElement(value))
1440 self.truncate(new_len);
1444 /// Clones and appends all elements in a slice to the `Vec`.
1446 /// Iterates over the slice `other`, clones each element, and then appends
1447 /// it to this `Vec`. The `other` vector is traversed in-order.
1449 /// Note that this function is same as [`extend`] except that it is
1450 /// specialized to work with slices instead. If and when Rust gets
1451 /// specialization this function will likely be deprecated (but still
1457 /// let mut vec = vec![1];
1458 /// vec.extend_from_slice(&[2, 3, 4]);
1459 /// assert_eq!(vec, [1, 2, 3, 4]);
1462 /// [`extend`]: #method.extend
1463 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1464 pub fn extend_from_slice(&mut self, other: &[T]) {
1465 self.spec_extend(other.iter())
1469 impl<T: Default> Vec<T> {
1470 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1472 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1473 /// difference, with each additional slot filled with [`Default::default()`].
1474 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1476 /// This method uses [`Default`] to create new values on every push. If
1477 /// you'd rather [`Clone`] a given value, use [`resize`].
1482 /// # #![allow(deprecated)]
1483 /// #![feature(vec_resize_default)]
1485 /// let mut vec = vec![1, 2, 3];
1486 /// vec.resize_default(5);
1487 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1489 /// let mut vec = vec![1, 2, 3, 4];
1490 /// vec.resize_default(2);
1491 /// assert_eq!(vec, [1, 2]);
1494 /// [`resize`]: #method.resize
1495 /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default
1496 /// [`Default`]: ../../std/default/trait.Default.html
1497 /// [`Clone`]: ../../std/clone/trait.Clone.html
1498 #[unstable(feature = "vec_resize_default", issue = "41758")]
1499 #[rustc_deprecated(reason = "This is moving towards being removed in favor \
1500 of `.resize_with(Default::default)`. If you disagree, please comment \
1501 in the tracking issue.", since = "1.33.0")]
1502 pub fn resize_default(&mut self, new_len: usize) {
1503 let len = self.len();
1506 self.extend_with(new_len - len, ExtendDefault);
1508 self.truncate(new_len);
1513 // This code generalises `extend_with_{element,default}`.
1514 trait ExtendWith<T> {
1515 fn next(&mut self) -> T;
1519 struct ExtendElement<T>(T);
1520 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1521 fn next(&mut self) -> T { self.0.clone() }
1522 fn last(self) -> T { self.0 }
1525 struct ExtendDefault;
1526 impl<T: Default> ExtendWith<T> for ExtendDefault {
1527 fn next(&mut self) -> T { Default::default() }
1528 fn last(self) -> T { Default::default() }
1531 struct ExtendFunc<F>(F);
1532 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1533 fn next(&mut self) -> T { (self.0)() }
1534 fn last(mut self) -> T { (self.0)() }
1538 /// Extend the vector by `n` values, using the given generator.
1539 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1543 let mut ptr = self.as_mut_ptr().add(self.len());
1544 // Use SetLenOnDrop to work around bug where compiler
1545 // may not realize the store through `ptr` through self.set_len()
1547 let mut local_len = SetLenOnDrop::new(&mut self.len);
1549 // Write all elements except the last one
1551 ptr::write(ptr, value.next());
1552 ptr = ptr.offset(1);
1553 // Increment the length in every step in case next() panics
1554 local_len.increment_len(1);
1558 // We can write the last element directly without cloning needlessly
1559 ptr::write(ptr, value.last());
1560 local_len.increment_len(1);
1563 // len set by scope guard
1568 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1570 // The idea is: The length field in SetLenOnDrop is a local variable
1571 // that the optimizer will see does not alias with any stores through the Vec's data
1572 // pointer. This is a workaround for alias analysis issue #32155
1573 struct SetLenOnDrop<'a> {
1578 impl<'a> SetLenOnDrop<'a> {
1580 fn new(len: &'a mut usize) -> Self {
1581 SetLenOnDrop { local_len: *len, len: len }
1585 fn increment_len(&mut self, increment: usize) {
1586 self.local_len += increment;
1590 fn decrement_len(&mut self, decrement: usize) {
1591 self.local_len -= decrement;
1595 impl Drop for SetLenOnDrop<'_> {
1597 fn drop(&mut self) {
1598 *self.len = self.local_len;
1602 impl<T: PartialEq> Vec<T> {
1603 /// Removes consecutive repeated elements in the vector according to the
1604 /// [`PartialEq`] trait implementation.
1606 /// If the vector is sorted, this removes all duplicates.
1611 /// let mut vec = vec![1, 2, 2, 3, 2];
1615 /// assert_eq!(vec, [1, 2, 3, 2]);
1617 #[stable(feature = "rust1", since = "1.0.0")]
1619 pub fn dedup(&mut self) {
1620 self.dedup_by(|a, b| a == b)
1623 /// Removes the first instance of `item` from the vector if the item exists.
1628 /// # #![feature(vec_remove_item)]
1629 /// let mut vec = vec![1, 2, 3, 1];
1631 /// vec.remove_item(&1);
1633 /// assert_eq!(vec, vec![2, 3, 1]);
1635 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1636 pub fn remove_item(&mut self, item: &T) -> Option<T> {
1637 let pos = self.iter().position(|x| *x == *item)?;
1638 Some(self.remove(pos))
1642 ////////////////////////////////////////////////////////////////////////////////
1643 // Internal methods and functions
1644 ////////////////////////////////////////////////////////////////////////////////
1647 #[stable(feature = "rust1", since = "1.0.0")]
1648 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1649 <T as SpecFromElem>::from_elem(elem, n)
1652 // Specialization trait used for Vec::from_elem
1653 trait SpecFromElem: Sized {
1654 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1657 impl<T: Clone> SpecFromElem for T {
1658 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1659 let mut v = Vec::with_capacity(n);
1660 v.extend_with(n, ExtendElement(elem));
1665 impl SpecFromElem for u8 {
1667 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1670 buf: RawVec::with_capacity_zeroed(n),
1675 let mut v = Vec::with_capacity(n);
1676 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1683 impl<T: Clone + IsZero> SpecFromElem for T {
1685 fn from_elem(elem: T, n: usize) -> Vec<T> {
1688 buf: RawVec::with_capacity_zeroed(n),
1692 let mut v = Vec::with_capacity(n);
1693 v.extend_with(n, ExtendElement(elem));
1698 unsafe trait IsZero {
1699 /// Whether this value is zero
1700 fn is_zero(&self) -> bool;
1703 macro_rules! impl_is_zero {
1704 ($t: ty, $is_zero: expr) => {
1705 unsafe impl IsZero for $t {
1707 fn is_zero(&self) -> bool {
1714 impl_is_zero!(i8, |x| x == 0);
1715 impl_is_zero!(i16, |x| x == 0);
1716 impl_is_zero!(i32, |x| x == 0);
1717 impl_is_zero!(i64, |x| x == 0);
1718 impl_is_zero!(i128, |x| x == 0);
1719 impl_is_zero!(isize, |x| x == 0);
1721 impl_is_zero!(u16, |x| x == 0);
1722 impl_is_zero!(u32, |x| x == 0);
1723 impl_is_zero!(u64, |x| x == 0);
1724 impl_is_zero!(u128, |x| x == 0);
1725 impl_is_zero!(usize, |x| x == 0);
1727 impl_is_zero!(bool, |x| x == false);
1728 impl_is_zero!(char, |x| x == '\0');
1730 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1731 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1733 unsafe impl<T> IsZero for *const T {
1735 fn is_zero(&self) -> bool {
1740 unsafe impl<T> IsZero for *mut T {
1742 fn is_zero(&self) -> bool {
1747 // `Option<&T>`, `Option<&mut T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
1748 // For fat pointers, the bytes that would be the pointer metadata in the `Some` variant
1749 // are padding in the `None` variant, so ignoring them and zero-initializing instead is ok.
1751 unsafe impl<T: ?Sized> IsZero for Option<&T> {
1753 fn is_zero(&self) -> bool {
1758 unsafe impl<T: ?Sized> IsZero for Option<&mut T> {
1760 fn is_zero(&self) -> bool {
1765 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
1767 fn is_zero(&self) -> bool {
1773 ////////////////////////////////////////////////////////////////////////////////
1774 // Common trait implementations for Vec
1775 ////////////////////////////////////////////////////////////////////////////////
1777 #[stable(feature = "rust1", since = "1.0.0")]
1778 impl<T: Clone> Clone for Vec<T> {
1780 fn clone(&self) -> Vec<T> {
1781 <[T]>::to_vec(&**self)
1784 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1785 // required for this method definition, is not available. Instead use the
1786 // `slice::to_vec` function which is only available with cfg(test)
1787 // NB see the slice::hack module in slice.rs for more information
1789 fn clone(&self) -> Vec<T> {
1790 crate::slice::to_vec(&**self)
1793 fn clone_from(&mut self, other: &Vec<T>) {
1794 other.as_slice().clone_into(self);
1798 #[stable(feature = "rust1", since = "1.0.0")]
1799 impl<T: Hash> Hash for Vec<T> {
1801 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1802 Hash::hash(&**self, state)
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 #[rustc_on_unimplemented(
1808 message="vector indices are of type `usize` or ranges of `usize`",
1809 label="vector indices are of type `usize` or ranges of `usize`",
1811 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
1812 type Output = I::Output;
1815 fn index(&self, index: I) -> &Self::Output {
1816 Index::index(&**self, index)
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 #[rustc_on_unimplemented(
1822 message="vector indices are of type `usize` or ranges of `usize`",
1823 label="vector indices are of type `usize` or ranges of `usize`",
1825 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
1827 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1828 IndexMut::index_mut(&mut **self, index)
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 impl<T> ops::Deref for Vec<T> {
1836 fn deref(&self) -> &[T] {
1838 slice::from_raw_parts(self.as_ptr(), self.len)
1843 #[stable(feature = "rust1", since = "1.0.0")]
1844 impl<T> ops::DerefMut for Vec<T> {
1845 fn deref_mut(&mut self) -> &mut [T] {
1847 slice::from_raw_parts_mut(self.as_mut_ptr(), self.len)
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 impl<T> FromIterator<T> for Vec<T> {
1855 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1856 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1860 #[stable(feature = "rust1", since = "1.0.0")]
1861 impl<T> IntoIterator for Vec<T> {
1863 type IntoIter = IntoIter<T>;
1865 /// Creates a consuming iterator, that is, one that moves each value out of
1866 /// the vector (from start to end). The vector cannot be used after calling
1872 /// let v = vec!["a".to_string(), "b".to_string()];
1873 /// for s in v.into_iter() {
1874 /// // s has type String, not &String
1875 /// println!("{}", s);
1879 fn into_iter(mut self) -> IntoIter<T> {
1881 let begin = self.as_mut_ptr();
1882 let end = if mem::size_of::<T>() == 0 {
1883 arith_offset(begin as *const i8, self.len() as isize) as *const T
1885 begin.add(self.len()) as *const T
1887 let cap = self.buf.capacity();
1890 buf: NonNull::new_unchecked(begin),
1891 phantom: PhantomData,
1900 #[stable(feature = "rust1", since = "1.0.0")]
1901 impl<'a, T> IntoIterator for &'a Vec<T> {
1903 type IntoIter = slice::Iter<'a, T>;
1905 fn into_iter(self) -> slice::Iter<'a, T> {
1910 #[stable(feature = "rust1", since = "1.0.0")]
1911 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1912 type Item = &'a mut T;
1913 type IntoIter = slice::IterMut<'a, T>;
1915 fn into_iter(self) -> slice::IterMut<'a, T> {
1920 #[stable(feature = "rust1", since = "1.0.0")]
1921 impl<T> Extend<T> for Vec<T> {
1923 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1924 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1928 // Specialization trait used for Vec::from_iter and Vec::extend
1929 trait SpecExtend<T, I> {
1930 fn from_iter(iter: I) -> Self;
1931 fn spec_extend(&mut self, iter: I);
1934 impl<T, I> SpecExtend<T, I> for Vec<T>
1935 where I: Iterator<Item=T>,
1937 default fn from_iter(mut iterator: I) -> Self {
1938 // Unroll the first iteration, as the vector is going to be
1939 // expanded on this iteration in every case when the iterable is not
1940 // empty, but the loop in extend_desugared() is not going to see the
1941 // vector being full in the few subsequent loop iterations.
1942 // So we get better branch prediction.
1943 let mut vector = match iterator.next() {
1944 None => return Vec::new(),
1946 let (lower, _) = iterator.size_hint();
1947 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1949 ptr::write(vector.get_unchecked_mut(0), element);
1955 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1959 default fn spec_extend(&mut self, iter: I) {
1960 self.extend_desugared(iter)
1964 impl<T, I> SpecExtend<T, I> for Vec<T>
1965 where I: TrustedLen<Item=T>,
1967 default fn from_iter(iterator: I) -> Self {
1968 let mut vector = Vec::new();
1969 vector.spec_extend(iterator);
1973 default fn spec_extend(&mut self, iterator: I) {
1974 // This is the case for a TrustedLen iterator.
1975 let (low, high) = iterator.size_hint();
1976 if let Some(high_value) = high {
1977 debug_assert_eq!(low, high_value,
1978 "TrustedLen iterator's size hint is not exact: {:?}",
1981 if let Some(additional) = high {
1982 self.reserve(additional);
1984 let mut ptr = self.as_mut_ptr().add(self.len());
1985 let mut local_len = SetLenOnDrop::new(&mut self.len);
1986 iterator.for_each(move |element| {
1987 ptr::write(ptr, element);
1988 ptr = ptr.offset(1);
1989 // NB can't overflow since we would have had to alloc the address space
1990 local_len.increment_len(1);
1994 self.extend_desugared(iterator)
1999 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2000 fn from_iter(iterator: IntoIter<T>) -> Self {
2001 // A common case is passing a vector into a function which immediately
2002 // re-collects into a vector. We can short circuit this if the IntoIter
2003 // has not been advanced at all.
2004 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
2006 let vec = Vec::from_raw_parts(iterator.buf.as_ptr(),
2009 mem::forget(iterator);
2013 let mut vector = Vec::new();
2014 vector.spec_extend(iterator);
2019 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2021 self.append_elements(iterator.as_slice() as _);
2023 iterator.ptr = iterator.end;
2027 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2028 where I: Iterator<Item=&'a T>,
2031 default fn from_iter(iterator: I) -> Self {
2032 SpecExtend::from_iter(iterator.cloned())
2035 default fn spec_extend(&mut self, iterator: I) {
2036 self.spec_extend(iterator.cloned())
2040 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2043 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2044 let slice = iterator.as_slice();
2045 self.reserve(slice.len());
2047 let len = self.len();
2048 self.set_len(len + slice.len());
2049 self.get_unchecked_mut(len..).copy_from_slice(slice);
2055 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2056 // This is the case for a general iterator.
2058 // This function should be the moral equivalent of:
2060 // for item in iterator {
2063 while let Some(element) = iterator.next() {
2064 let len = self.len();
2065 if len == self.capacity() {
2066 let (lower, _) = iterator.size_hint();
2067 self.reserve(lower.saturating_add(1));
2070 ptr::write(self.get_unchecked_mut(len), element);
2071 // NB can't overflow since we would have had to alloc the address space
2072 self.set_len(len + 1);
2077 /// Creates a splicing iterator that replaces the specified range in the vector
2078 /// with the given `replace_with` iterator and yields the removed items.
2079 /// `replace_with` does not need to be the same length as `range`.
2081 /// The element range is removed even if the iterator is not consumed until the end.
2083 /// It is unspecified how many elements are removed from the vector
2084 /// if the `Splice` value is leaked.
2086 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2088 /// This is optimal if:
2090 /// * The tail (elements in the vector after `range`) is empty,
2091 /// * or `replace_with` yields fewer elements than `range`’s length
2092 /// * or the lower bound of its `size_hint()` is exact.
2094 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2098 /// Panics if the starting point is greater than the end point or if
2099 /// the end point is greater than the length of the vector.
2104 /// let mut v = vec![1, 2, 3];
2105 /// let new = [7, 8];
2106 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2107 /// assert_eq!(v, &[7, 8, 3]);
2108 /// assert_eq!(u, &[1, 2]);
2111 #[stable(feature = "vec_splice", since = "1.21.0")]
2112 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2113 where R: RangeBounds<usize>, I: IntoIterator<Item=T>
2116 drain: self.drain(range),
2117 replace_with: replace_with.into_iter(),
2121 /// Creates an iterator which uses a closure to determine if an element should be removed.
2123 /// If the closure returns true, then the element is removed and yielded.
2124 /// If the closure returns false, the element will remain in the vector and will not be yielded
2125 /// by the iterator.
2127 /// Using this method is equivalent to the following code:
2130 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2131 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2133 /// while i != vec.len() {
2134 /// if some_predicate(&mut vec[i]) {
2135 /// let val = vec.remove(i);
2136 /// // your code here
2142 /// # assert_eq!(vec, vec![1, 4, 5]);
2145 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2146 /// because it can backshift the elements of the array in bulk.
2148 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2149 /// regardless of whether you choose to keep or remove it.
2154 /// Splitting an array into evens and odds, reusing the original allocation:
2157 /// #![feature(drain_filter)]
2158 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2160 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2161 /// let odds = numbers;
2163 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2164 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2166 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2167 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2168 where F: FnMut(&mut T) -> bool,
2170 let old_len = self.len();
2172 // Guard against us getting leaked (leak amplification)
2173 unsafe { self.set_len(0); }
2186 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2188 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2189 /// append the entire slice at once.
2191 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2192 #[stable(feature = "extend_ref", since = "1.2.0")]
2193 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2194 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2195 self.spec_extend(iter.into_iter())
2199 macro_rules! __impl_slice_eq1 {
2200 ([$($vars:tt)*] $lhs:ty, $rhs:ty, $($constraints:tt)*) => {
2201 #[stable(feature = "rust1", since = "1.0.0")]
2202 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2208 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2210 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2215 __impl_slice_eq1! { [] Vec<A>, Vec<B>, }
2216 __impl_slice_eq1! { [] Vec<A>, &[B], }
2217 __impl_slice_eq1! { [] Vec<A>, &mut [B], }
2218 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B], A: Clone }
2219 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B], A: Clone }
2220 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B>, A: Clone }
2221 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N], [B; N]: LengthAtMost32 }
2222 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N], [B; N]: LengthAtMost32 }
2224 // NOTE: some less important impls are omitted to reduce code bloat
2225 // FIXME(Centril): Reconsider this?
2226 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], [B; N]: LengthAtMost32 }
2227 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], [B; N]: LengthAtMost32 }
2228 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], [B; N]: LengthAtMost32 }
2229 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], [B; N]: LengthAtMost32 }
2231 /// Implements comparison of vectors, lexicographically.
2232 #[stable(feature = "rust1", since = "1.0.0")]
2233 impl<T: PartialOrd> PartialOrd for Vec<T> {
2235 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2236 PartialOrd::partial_cmp(&**self, &**other)
2240 #[stable(feature = "rust1", since = "1.0.0")]
2241 impl<T: Eq> Eq for Vec<T> {}
2243 /// Implements ordering of vectors, lexicographically.
2244 #[stable(feature = "rust1", since = "1.0.0")]
2245 impl<T: Ord> Ord for Vec<T> {
2247 fn cmp(&self, other: &Vec<T>) -> Ordering {
2248 Ord::cmp(&**self, &**other)
2252 #[stable(feature = "rust1", since = "1.0.0")]
2253 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2254 fn drop(&mut self) {
2257 ptr::drop_in_place(&mut self[..]);
2259 // RawVec handles deallocation
2263 #[stable(feature = "rust1", since = "1.0.0")]
2264 impl<T> Default for Vec<T> {
2265 /// Creates an empty `Vec<T>`.
2266 fn default() -> Vec<T> {
2271 #[stable(feature = "rust1", since = "1.0.0")]
2272 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2273 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2274 fmt::Debug::fmt(&**self, f)
2278 #[stable(feature = "rust1", since = "1.0.0")]
2279 impl<T> AsRef<Vec<T>> for Vec<T> {
2280 fn as_ref(&self) -> &Vec<T> {
2285 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2286 impl<T> AsMut<Vec<T>> for Vec<T> {
2287 fn as_mut(&mut self) -> &mut Vec<T> {
2292 #[stable(feature = "rust1", since = "1.0.0")]
2293 impl<T> AsRef<[T]> for Vec<T> {
2294 fn as_ref(&self) -> &[T] {
2299 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2300 impl<T> AsMut<[T]> for Vec<T> {
2301 fn as_mut(&mut self) -> &mut [T] {
2306 #[stable(feature = "rust1", since = "1.0.0")]
2307 impl<T: Clone> From<&[T]> for Vec<T> {
2309 fn from(s: &[T]) -> Vec<T> {
2313 fn from(s: &[T]) -> Vec<T> {
2314 crate::slice::to_vec(s)
2318 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2319 impl<T: Clone> From<&mut [T]> for Vec<T> {
2321 fn from(s: &mut [T]) -> Vec<T> {
2325 fn from(s: &mut [T]) -> Vec<T> {
2326 crate::slice::to_vec(s)
2330 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2331 impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> {
2332 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2337 // note: test pulls in libstd, which causes errors here
2339 #[stable(feature = "vec_from_box", since = "1.18.0")]
2340 impl<T> From<Box<[T]>> for Vec<T> {
2341 fn from(s: Box<[T]>) -> Vec<T> {
2346 // note: test pulls in libstd, which causes errors here
2348 #[stable(feature = "box_from_vec", since = "1.20.0")]
2349 impl<T> From<Vec<T>> for Box<[T]> {
2350 fn from(v: Vec<T>) -> Box<[T]> {
2351 v.into_boxed_slice()
2355 #[stable(feature = "rust1", since = "1.0.0")]
2356 impl From<&str> for Vec<u8> {
2357 fn from(s: &str) -> Vec<u8> {
2358 From::from(s.as_bytes())
2362 ////////////////////////////////////////////////////////////////////////////////
2364 ////////////////////////////////////////////////////////////////////////////////
2366 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2367 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2368 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2373 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2374 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2375 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2380 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2381 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2382 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2383 Cow::Borrowed(v.as_slice())
2387 #[stable(feature = "rust1", since = "1.0.0")]
2388 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
2389 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2390 Cow::Owned(FromIterator::from_iter(it))
2394 ////////////////////////////////////////////////////////////////////////////////
2396 ////////////////////////////////////////////////////////////////////////////////
2398 /// An iterator that moves out of a vector.
2400 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2401 /// by the [`IntoIterator`] trait).
2403 /// [`Vec`]: struct.Vec.html
2404 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2405 #[stable(feature = "rust1", since = "1.0.0")]
2406 pub struct IntoIter<T> {
2408 phantom: PhantomData<T>,
2414 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2415 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2416 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2417 f.debug_tuple("IntoIter")
2418 .field(&self.as_slice())
2423 impl<T> IntoIter<T> {
2424 /// Returns the remaining items of this iterator as a slice.
2429 /// let vec = vec!['a', 'b', 'c'];
2430 /// let mut into_iter = vec.into_iter();
2431 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2432 /// let _ = into_iter.next().unwrap();
2433 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2435 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2436 pub fn as_slice(&self) -> &[T] {
2438 slice::from_raw_parts(self.ptr, self.len())
2442 /// Returns the remaining items of this iterator as a mutable slice.
2447 /// let vec = vec!['a', 'b', 'c'];
2448 /// let mut into_iter = vec.into_iter();
2449 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2450 /// into_iter.as_mut_slice()[2] = 'z';
2451 /// assert_eq!(into_iter.next().unwrap(), 'a');
2452 /// assert_eq!(into_iter.next().unwrap(), 'b');
2453 /// assert_eq!(into_iter.next().unwrap(), 'z');
2455 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2456 pub fn as_mut_slice(&mut self) -> &mut [T] {
2458 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
2463 #[stable(feature = "rust1", since = "1.0.0")]
2464 unsafe impl<T: Send> Send for IntoIter<T> {}
2465 #[stable(feature = "rust1", since = "1.0.0")]
2466 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2468 #[stable(feature = "rust1", since = "1.0.0")]
2469 impl<T> Iterator for IntoIter<T> {
2473 fn next(&mut self) -> Option<T> {
2475 if self.ptr as *const _ == self.end {
2478 if mem::size_of::<T>() == 0 {
2479 // purposefully don't use 'ptr.offset' because for
2480 // vectors with 0-size elements this would return the
2482 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2484 // Make up a value of this ZST.
2488 self.ptr = self.ptr.offset(1);
2490 Some(ptr::read(old))
2497 fn size_hint(&self) -> (usize, Option<usize>) {
2498 let exact = if mem::size_of::<T>() == 0 {
2499 (self.end as usize).wrapping_sub(self.ptr as usize)
2501 unsafe { self.end.offset_from(self.ptr) as usize }
2503 (exact, Some(exact))
2507 fn count(self) -> usize {
2512 #[stable(feature = "rust1", since = "1.0.0")]
2513 impl<T> DoubleEndedIterator for IntoIter<T> {
2515 fn next_back(&mut self) -> Option<T> {
2517 if self.end == self.ptr {
2520 if mem::size_of::<T>() == 0 {
2521 // See above for why 'ptr.offset' isn't used
2522 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2524 // Make up a value of this ZST.
2527 self.end = self.end.offset(-1);
2529 Some(ptr::read(self.end))
2536 #[stable(feature = "rust1", since = "1.0.0")]
2537 impl<T> ExactSizeIterator for IntoIter<T> {
2538 fn is_empty(&self) -> bool {
2539 self.ptr == self.end
2543 #[stable(feature = "fused", since = "1.26.0")]
2544 impl<T> FusedIterator for IntoIter<T> {}
2546 #[unstable(feature = "trusted_len", issue = "37572")]
2547 unsafe impl<T> TrustedLen for IntoIter<T> {}
2549 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2550 impl<T: Clone> Clone for IntoIter<T> {
2551 fn clone(&self) -> IntoIter<T> {
2552 self.as_slice().to_owned().into_iter()
2556 #[stable(feature = "rust1", since = "1.0.0")]
2557 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2558 fn drop(&mut self) {
2559 // destroy the remaining elements
2560 for _x in self.by_ref() {}
2562 // RawVec handles deallocation
2563 let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) };
2567 /// A draining iterator for `Vec<T>`.
2569 /// This `struct` is created by the [`drain`] method on [`Vec`].
2571 /// [`drain`]: struct.Vec.html#method.drain
2572 /// [`Vec`]: struct.Vec.html
2573 #[stable(feature = "drain", since = "1.6.0")]
2574 pub struct Drain<'a, T: 'a> {
2575 /// Index of tail to preserve
2579 /// Current remaining range to remove
2580 iter: slice::Iter<'a, T>,
2581 vec: NonNull<Vec<T>>,
2584 #[stable(feature = "collection_debug", since = "1.17.0")]
2585 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2586 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2587 f.debug_tuple("Drain")
2588 .field(&self.iter.as_slice())
2593 impl<'a, T> Drain<'a, T> {
2594 /// Returns the remaining items of this iterator as a slice.
2599 /// # #![feature(vec_drain_as_slice)]
2600 /// let mut vec = vec!['a', 'b', 'c'];
2601 /// let mut drain = vec.drain(..);
2602 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
2603 /// let _ = drain.next().unwrap();
2604 /// assert_eq!(drain.as_slice(), &['b', 'c']);
2606 #[unstable(feature = "vec_drain_as_slice", reason = "recently added", issue = "58957")]
2607 pub fn as_slice(&self) -> &[T] {
2608 self.iter.as_slice()
2612 #[stable(feature = "drain", since = "1.6.0")]
2613 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2614 #[stable(feature = "drain", since = "1.6.0")]
2615 unsafe impl<T: Send> Send for Drain<'_, T> {}
2617 #[stable(feature = "drain", since = "1.6.0")]
2618 impl<T> Iterator for Drain<'_, T> {
2622 fn next(&mut self) -> Option<T> {
2623 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2626 fn size_hint(&self) -> (usize, Option<usize>) {
2627 self.iter.size_hint()
2631 #[stable(feature = "drain", since = "1.6.0")]
2632 impl<T> DoubleEndedIterator for Drain<'_, T> {
2634 fn next_back(&mut self) -> Option<T> {
2635 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2639 #[stable(feature = "drain", since = "1.6.0")]
2640 impl<T> Drop for Drain<'_, T> {
2641 fn drop(&mut self) {
2642 // exhaust self first
2643 self.for_each(drop);
2645 if self.tail_len > 0 {
2647 let source_vec = self.vec.as_mut();
2648 // memmove back untouched tail, update to new length
2649 let start = source_vec.len();
2650 let tail = self.tail_start;
2652 let src = source_vec.as_ptr().add(tail);
2653 let dst = source_vec.as_mut_ptr().add(start);
2654 ptr::copy(src, dst, self.tail_len);
2656 source_vec.set_len(start + self.tail_len);
2663 #[stable(feature = "drain", since = "1.6.0")]
2664 impl<T> ExactSizeIterator for Drain<'_, T> {
2665 fn is_empty(&self) -> bool {
2666 self.iter.is_empty()
2670 #[stable(feature = "fused", since = "1.26.0")]
2671 impl<T> FusedIterator for Drain<'_, T> {}
2673 /// A splicing iterator for `Vec`.
2675 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2676 /// documentation for more.
2678 /// [`splice()`]: struct.Vec.html#method.splice
2679 /// [`Vec`]: struct.Vec.html
2681 #[stable(feature = "vec_splice", since = "1.21.0")]
2682 pub struct Splice<'a, I: Iterator + 'a> {
2683 drain: Drain<'a, I::Item>,
2687 #[stable(feature = "vec_splice", since = "1.21.0")]
2688 impl<I: Iterator> Iterator for Splice<'_, I> {
2689 type Item = I::Item;
2691 fn next(&mut self) -> Option<Self::Item> {
2695 fn size_hint(&self) -> (usize, Option<usize>) {
2696 self.drain.size_hint()
2700 #[stable(feature = "vec_splice", since = "1.21.0")]
2701 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
2702 fn next_back(&mut self) -> Option<Self::Item> {
2703 self.drain.next_back()
2707 #[stable(feature = "vec_splice", since = "1.21.0")]
2708 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
2711 #[stable(feature = "vec_splice", since = "1.21.0")]
2712 impl<I: Iterator> Drop for Splice<'_, I> {
2713 fn drop(&mut self) {
2714 self.drain.by_ref().for_each(drop);
2717 if self.drain.tail_len == 0 {
2718 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2722 // First fill the range left by drain().
2723 if !self.drain.fill(&mut self.replace_with) {
2727 // There may be more elements. Use the lower bound as an estimate.
2728 // FIXME: Is the upper bound a better guess? Or something else?
2729 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2730 if lower_bound > 0 {
2731 self.drain.move_tail(lower_bound);
2732 if !self.drain.fill(&mut self.replace_with) {
2737 // Collect any remaining elements.
2738 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2739 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2740 // Now we have an exact count.
2741 if collected.len() > 0 {
2742 self.drain.move_tail(collected.len());
2743 let filled = self.drain.fill(&mut collected);
2744 debug_assert!(filled);
2745 debug_assert_eq!(collected.len(), 0);
2748 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2752 /// Private helper methods for `Splice::drop`
2753 impl<T> Drain<'_, T> {
2754 /// The range from `self.vec.len` to `self.tail_start` contains elements
2755 /// that have been moved out.
2756 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2757 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2758 unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
2759 let vec = self.vec.as_mut();
2760 let range_start = vec.len;
2761 let range_end = self.tail_start;
2762 let range_slice = slice::from_raw_parts_mut(
2763 vec.as_mut_ptr().add(range_start),
2764 range_end - range_start);
2766 for place in range_slice {
2767 if let Some(new_item) = replace_with.next() {
2768 ptr::write(place, new_item);
2777 /// Makes room for inserting more elements before the tail.
2778 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2779 let vec = self.vec.as_mut();
2780 let used_capacity = self.tail_start + self.tail_len;
2781 vec.buf.reserve(used_capacity, extra_capacity);
2783 let new_tail_start = self.tail_start + extra_capacity;
2784 let src = vec.as_ptr().add(self.tail_start);
2785 let dst = vec.as_mut_ptr().add(new_tail_start);
2786 ptr::copy(src, dst, self.tail_len);
2787 self.tail_start = new_tail_start;
2791 /// An iterator produced by calling `drain_filter` on Vec.
2792 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2794 pub struct DrainFilter<'a, T, F>
2795 where F: FnMut(&mut T) -> bool,
2797 vec: &'a mut Vec<T>,
2798 /// The index of the item that will be inspected by the next call to `next`.
2800 /// The number of items that have been drained (removed) thus far.
2802 /// The original length of `vec` prior to draining.
2804 /// The filter test predicate.
2806 /// A flag that indicates a panic has occured in the filter test prodicate.
2807 /// This is used as a hint in the drop implmentation to prevent consumption
2808 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
2809 /// backshifted in the `vec`, but no further items will be dropped or
2810 /// tested by the filter predicate.
2814 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2815 impl<T, F> Iterator for DrainFilter<'_, T, F>
2816 where F: FnMut(&mut T) -> bool,
2820 fn next(&mut self) -> Option<T> {
2822 while self.idx < self.old_len {
2824 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
2825 self.panic_flag = true;
2826 let drained = (self.pred)(&mut v[i]);
2827 self.panic_flag = false;
2828 // Update the index *after* the predicate is called. If the index
2829 // is updated prior and the predicate panics, the element at this
2830 // index would be leaked.
2834 return Some(ptr::read(&v[i]));
2835 } else if self.del > 0 {
2837 let src: *const T = &v[i];
2838 let dst: *mut T = &mut v[i - del];
2839 ptr::copy_nonoverlapping(src, dst, 1);
2846 fn size_hint(&self) -> (usize, Option<usize>) {
2847 (0, Some(self.old_len - self.idx))
2851 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2852 impl<T, F> Drop for DrainFilter<'_, T, F>
2853 where F: FnMut(&mut T) -> bool,
2855 fn drop(&mut self) {
2856 struct BackshiftOnDrop<'a, 'b, T, F>
2858 F: FnMut(&mut T) -> bool,
2860 drain: &'b mut DrainFilter<'a, T, F>,
2863 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
2865 F: FnMut(&mut T) -> bool
2867 fn drop(&mut self) {
2869 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
2870 // This is a pretty messed up state, and there isn't really an
2871 // obviously right thing to do. We don't want to keep trying
2872 // to execute `pred`, so we just backshift all the unprocessed
2873 // elements and tell the vec that they still exist. The backshift
2874 // is required to prevent a double-drop of the last successfully
2875 // drained item prior to a panic in the predicate.
2876 let ptr = self.drain.vec.as_mut_ptr();
2877 let src = ptr.add(self.drain.idx);
2878 let dst = src.sub(self.drain.del);
2879 let tail_len = self.drain.old_len - self.drain.idx;
2880 src.copy_to(dst, tail_len);
2882 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
2887 let backshift = BackshiftOnDrop {
2891 // Attempt to consume any remaining elements if the filter predicate
2892 // has not yet panicked. We'll backshift any remaining elements
2893 // whether we've already panicked or if the consumption here panics.
2894 if !backshift.drain.panic_flag {
2895 backshift.drain.for_each(drop);