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::cmp::{self, Ordering};
61 use core::hash::{self, Hash};
62 use core::intrinsics::{arith_offset, assume};
63 use core::iter::{FromIterator, FusedIterator, TrustedLen};
64 use core::marker::PhantomData;
66 use core::ops::{self, Index, IndexMut, RangeBounds};
67 use core::ops::Bound::{Excluded, Included, Unbounded};
68 use core::ptr::{self, NonNull};
69 use core::slice::{self, SliceIndex};
71 use crate::borrow::{ToOwned, Cow};
72 use crate::collections::CollectionAllocErr;
73 use crate::boxed::Box;
74 use crate::raw_vec::RawVec;
76 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
81 /// let mut vec = Vec::new();
85 /// assert_eq!(vec.len(), 2);
86 /// assert_eq!(vec[0], 1);
88 /// assert_eq!(vec.pop(), Some(2));
89 /// assert_eq!(vec.len(), 1);
92 /// assert_eq!(vec[0], 7);
94 /// vec.extend([1, 2, 3].iter().cloned());
97 /// println!("{}", x);
99 /// assert_eq!(vec, [7, 1, 2, 3]);
102 /// The [`vec!`] macro is provided to make initialization more convenient:
105 /// let mut vec = vec![1, 2, 3];
107 /// assert_eq!(vec, [1, 2, 3, 4]);
110 /// It can also initialize each element of a `Vec<T>` with a given value.
111 /// This may be more efficient than performing allocation and initialization
112 /// in separate steps, especially when initializing a vector of zeros:
115 /// let vec = vec![0; 5];
116 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
118 /// // The following is equivalent, but potentially slower:
119 /// let mut vec1 = Vec::with_capacity(5);
120 /// vec1.resize(5, 0);
123 /// Use a `Vec<T>` as an efficient stack:
126 /// let mut stack = Vec::new();
132 /// while let Some(top) = stack.pop() {
133 /// // Prints 3, 2, 1
134 /// println!("{}", top);
140 /// The `Vec` type allows to access values by index, because it implements the
141 /// [`Index`] trait. An example will be more explicit:
144 /// let v = vec![0, 2, 4, 6];
145 /// println!("{}", v[1]); // it will display '2'
148 /// However be careful: if you try to access an index which isn't in the `Vec`,
149 /// your software will panic! You cannot do this:
152 /// let v = vec![0, 2, 4, 6];
153 /// println!("{}", v[6]); // it will panic!
156 /// In conclusion: always check if the index you want to get really exists
161 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
162 /// To get a slice, use `&`. Example:
165 /// fn read_slice(slice: &[usize]) {
169 /// let v = vec![0, 1];
172 /// // ... and that's all!
173 /// // you can also do it like this:
174 /// let x : &[usize] = &v;
177 /// In Rust, it's more common to pass slices as arguments rather than vectors
178 /// when you just want to provide a read access. The same goes for [`String`] and
181 /// # Capacity and reallocation
183 /// The capacity of a vector is the amount of space allocated for any future
184 /// elements that will be added onto the vector. This is not to be confused with
185 /// the *length* of a vector, which specifies the number of actual elements
186 /// within the vector. If a vector's length exceeds its capacity, its capacity
187 /// will automatically be increased, but its elements will have to be
190 /// For example, a vector with capacity 10 and length 0 would be an empty vector
191 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
192 /// vector will not change its capacity or cause reallocation to occur. However,
193 /// if the vector's length is increased to 11, it will have to reallocate, which
194 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
195 /// whenever possible to specify how big the vector is expected to get.
199 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
200 /// about its design. This ensures that it's as low-overhead as possible in
201 /// the general case, and can be correctly manipulated in primitive ways
202 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
203 /// If additional type parameters are added (e.g., to support custom allocators),
204 /// overriding their defaults may change the behavior.
206 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
207 /// triplet. No more, no less. The order of these fields is completely
208 /// unspecified, and you should use the appropriate methods to modify these.
209 /// The pointer will never be null, so this type is null-pointer-optimized.
211 /// However, the pointer may not actually point to allocated memory. In particular,
212 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
213 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
214 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
215 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
216 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
217 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
218 /// details are very subtle — if you intend to allocate memory using a `Vec`
219 /// and use it for something else (either to pass to unsafe code, or to build your
220 /// own memory-backed collection), be sure to deallocate this memory by using
221 /// `from_raw_parts` to recover the `Vec` and then dropping it.
223 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
224 /// (as defined by the allocator Rust is configured to use by default), and its
225 /// pointer points to [`len`] initialized, contiguous elements in order (what
226 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
227 /// `[`len`] logically uninitialized, contiguous elements.
229 /// `Vec` will never perform a "small optimization" where elements are actually
230 /// stored on the stack for two reasons:
232 /// * It would make it more difficult for unsafe code to correctly manipulate
233 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
234 /// only moved, and it would be more difficult to determine if a `Vec` had
235 /// actually allocated memory.
237 /// * It would penalize the general case, incurring an additional branch
240 /// `Vec` will never automatically shrink itself, even if completely empty. This
241 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
242 /// and then filling it back up to the same [`len`] should incur no calls to
243 /// the allocator. If you wish to free up unused memory, use
244 /// [`shrink_to_fit`][`shrink_to_fit`].
246 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
247 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
248 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
249 /// accurate, and can be relied on. It can even be used to manually free the memory
250 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
251 /// when not necessary.
253 /// `Vec` does not guarantee any particular growth strategy when reallocating
254 /// when full, nor when [`reserve`] is called. The current strategy is basic
255 /// and it may prove desirable to use a non-constant growth factor. Whatever
256 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
258 /// `vec![x; n]`, `vec![a, b, c, d]`, and
259 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
260 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
261 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
262 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
264 /// `Vec` will not specifically overwrite any data that is removed from it,
265 /// but also won't specifically preserve it. Its uninitialized memory is
266 /// scratch space that it may use however it wants. It will generally just do
267 /// whatever is most efficient or otherwise easy to implement. Do not rely on
268 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
269 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
270 /// first, that may not actually happen because the optimizer does not consider
271 /// this a side-effect that must be preserved. There is one case which we will
272 /// not break, however: using `unsafe` code to write to the excess capacity,
273 /// and then increasing the length to match, is always valid.
275 /// `Vec` does not currently guarantee the order in which elements are dropped.
276 /// The order has changed in the past and may change again.
278 /// [`vec!`]: ../../std/macro.vec.html
279 /// [`Index`]: ../../std/ops/trait.Index.html
280 /// [`String`]: ../../std/string/struct.String.html
281 /// [`&str`]: ../../std/primitive.str.html
282 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
283 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
284 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
285 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
286 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
287 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
288 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
289 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
290 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
291 /// [owned slice]: ../../std/boxed/struct.Box.html
292 #[stable(feature = "rust1", since = "1.0.0")]
298 ////////////////////////////////////////////////////////////////////////////////
300 ////////////////////////////////////////////////////////////////////////////////
303 /// Constructs a new, empty `Vec<T>`.
305 /// The vector will not allocate until elements are pushed onto it.
310 /// # #![allow(unused_mut)]
311 /// let mut vec: Vec<i32> = Vec::new();
314 #[stable(feature = "rust1", since = "1.0.0")]
315 #[rustc_const_unstable(feature = "const_vec_new")]
316 pub const fn new() -> Vec<T> {
323 /// Constructs a new, empty `Vec<T>` with the specified capacity.
325 /// The vector will be able to hold exactly `capacity` elements without
326 /// reallocating. If `capacity` is 0, the vector will not allocate.
328 /// It is important to note that although the returned vector has the
329 /// *capacity* specified, the vector will have a zero *length*. For an
330 /// explanation of the difference between length and capacity, see
331 /// *[Capacity and reallocation]*.
333 /// [Capacity and reallocation]: #capacity-and-reallocation
338 /// let mut vec = Vec::with_capacity(10);
340 /// // The vector contains no items, even though it has capacity for more
341 /// assert_eq!(vec.len(), 0);
343 /// // These are all done without reallocating...
348 /// // ...but this may make the vector reallocate
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub fn with_capacity(capacity: usize) -> Vec<T> {
355 buf: RawVec::with_capacity(capacity),
360 /// Creates a `Vec<T>` directly from the raw components of another vector.
364 /// This is highly unsafe, due to the number of invariants that aren't
367 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
368 /// (at least, it's highly likely to be incorrect if it wasn't).
369 /// * `ptr`'s `T` needs to have the same size and alignment as it was allocated with.
370 /// * `length` needs to be less than or equal to `capacity`.
371 /// * `capacity` needs to be the capacity that the pointer was allocated with.
373 /// Violating these may cause problems like corrupting the allocator's
374 /// internal data structures. For example it is **not** safe
375 /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`.
377 /// The ownership of `ptr` is effectively transferred to the
378 /// `Vec<T>` which may then deallocate, reallocate or change the
379 /// contents of memory pointed to by the pointer at will. Ensure
380 /// that nothing else uses the pointer after calling this
383 /// [`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]);
415 #[stable(feature = "rust1", since = "1.0.0")]
416 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
418 buf: RawVec::from_raw_parts(ptr, capacity),
423 /// Returns the number of elements the vector can hold without
429 /// let vec: Vec<i32> = Vec::with_capacity(10);
430 /// assert_eq!(vec.capacity(), 10);
433 #[stable(feature = "rust1", since = "1.0.0")]
434 pub fn capacity(&self) -> usize {
438 /// Reserves capacity for at least `additional` more elements to be inserted
439 /// in the given `Vec<T>`. The collection may reserve more space to avoid
440 /// frequent reallocations. After calling `reserve`, capacity will be
441 /// greater than or equal to `self.len() + additional`. Does nothing if
442 /// capacity is already sufficient.
446 /// Panics if the new capacity overflows `usize`.
451 /// let mut vec = vec![1];
453 /// assert!(vec.capacity() >= 11);
455 #[stable(feature = "rust1", since = "1.0.0")]
456 pub fn reserve(&mut self, additional: usize) {
457 self.buf.reserve(self.len, additional);
460 /// Reserves the minimum capacity for exactly `additional` more elements to
461 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
462 /// capacity will be greater than or equal to `self.len() + additional`.
463 /// Does nothing if the capacity is already sufficient.
465 /// Note that the allocator may give the collection more space than it
466 /// requests. Therefore, capacity can not be relied upon to be precisely
467 /// minimal. Prefer `reserve` if future insertions are expected.
471 /// Panics if the new capacity overflows `usize`.
476 /// let mut vec = vec![1];
477 /// vec.reserve_exact(10);
478 /// assert!(vec.capacity() >= 11);
480 #[stable(feature = "rust1", since = "1.0.0")]
481 pub fn reserve_exact(&mut self, additional: usize) {
482 self.buf.reserve_exact(self.len, additional);
485 /// Tries to reserve capacity for at least `additional` more elements to be inserted
486 /// in the given `Vec<T>`. The collection may reserve more space to avoid
487 /// frequent reallocations. After calling `reserve`, capacity will be
488 /// greater than or equal to `self.len() + additional`. Does nothing if
489 /// capacity is already sufficient.
493 /// If the capacity overflows, or the allocator reports a failure, then an error
499 /// #![feature(try_reserve)]
500 /// use std::collections::CollectionAllocErr;
502 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> {
503 /// let mut output = Vec::new();
505 /// // Pre-reserve the memory, exiting if we can't
506 /// output.try_reserve(data.len())?;
508 /// // Now we know this can't OOM in the middle of our complex work
509 /// output.extend(data.iter().map(|&val| {
510 /// val * 2 + 5 // very complicated
515 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
517 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
518 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
519 self.buf.try_reserve(self.len, additional)
522 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
523 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
524 /// capacity will be greater than or equal to `self.len() + additional`.
525 /// Does nothing if the capacity is already sufficient.
527 /// Note that the allocator may give the collection more space than it
528 /// requests. Therefore, capacity can not be relied upon to be precisely
529 /// minimal. Prefer `reserve` if future insertions are expected.
533 /// If the capacity overflows, or the allocator reports a failure, then an error
539 /// #![feature(try_reserve)]
540 /// use std::collections::CollectionAllocErr;
542 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> {
543 /// let mut output = Vec::new();
545 /// // Pre-reserve the memory, exiting if we can't
546 /// output.try_reserve(data.len())?;
548 /// // Now we know this can't OOM in the middle of our complex work
549 /// output.extend(data.iter().map(|&val| {
550 /// val * 2 + 5 // very complicated
555 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
557 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
558 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
559 self.buf.try_reserve_exact(self.len, additional)
562 /// Shrinks the capacity of the vector as much as possible.
564 /// It will drop down as close as possible to the length but the allocator
565 /// may still inform the vector that there is space for a few more elements.
570 /// let mut vec = Vec::with_capacity(10);
571 /// vec.extend([1, 2, 3].iter().cloned());
572 /// assert_eq!(vec.capacity(), 10);
573 /// vec.shrink_to_fit();
574 /// assert!(vec.capacity() >= 3);
576 #[stable(feature = "rust1", since = "1.0.0")]
577 pub fn shrink_to_fit(&mut self) {
578 if self.capacity() != self.len {
579 self.buf.shrink_to_fit(self.len);
583 /// Shrinks the capacity of the vector with a lower bound.
585 /// The capacity will remain at least as large as both the length
586 /// and the supplied value.
588 /// Panics if the current capacity is smaller than the supplied
589 /// minimum capacity.
594 /// #![feature(shrink_to)]
595 /// let mut vec = Vec::with_capacity(10);
596 /// vec.extend([1, 2, 3].iter().cloned());
597 /// assert_eq!(vec.capacity(), 10);
598 /// vec.shrink_to(4);
599 /// assert!(vec.capacity() >= 4);
600 /// vec.shrink_to(0);
601 /// assert!(vec.capacity() >= 3);
603 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
604 pub fn shrink_to(&mut self, min_capacity: usize) {
605 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
608 /// Converts the vector into [`Box<[T]>`][owned slice].
610 /// Note that this will drop any excess capacity.
612 /// [owned slice]: ../../std/boxed/struct.Box.html
617 /// let v = vec![1, 2, 3];
619 /// let slice = v.into_boxed_slice();
622 /// Any excess capacity is removed:
625 /// let mut vec = Vec::with_capacity(10);
626 /// vec.extend([1, 2, 3].iter().cloned());
628 /// assert_eq!(vec.capacity(), 10);
629 /// let slice = vec.into_boxed_slice();
630 /// assert_eq!(slice.into_vec().capacity(), 3);
632 #[stable(feature = "rust1", since = "1.0.0")]
633 pub fn into_boxed_slice(mut self) -> Box<[T]> {
635 self.shrink_to_fit();
636 let buf = ptr::read(&self.buf);
642 /// Shortens the vector, keeping the first `len` elements and dropping
645 /// If `len` is greater than the vector's current length, this has no
648 /// The [`drain`] method can emulate `truncate`, but causes the excess
649 /// elements to be returned instead of dropped.
651 /// Note that this method has no effect on the allocated capacity
656 /// Truncating a five element vector to two elements:
659 /// let mut vec = vec![1, 2, 3, 4, 5];
661 /// assert_eq!(vec, [1, 2]);
664 /// No truncation occurs when `len` is greater than the vector's current
668 /// let mut vec = vec![1, 2, 3];
670 /// assert_eq!(vec, [1, 2, 3]);
673 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
677 /// let mut vec = vec![1, 2, 3];
679 /// assert_eq!(vec, []);
682 /// [`clear`]: #method.clear
683 /// [`drain`]: #method.drain
684 #[stable(feature = "rust1", since = "1.0.0")]
685 pub fn truncate(&mut self, len: usize) {
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);
704 /// Extracts a slice containing the entire vector.
706 /// Equivalent to `&s[..]`.
711 /// use std::io::{self, Write};
712 /// let buffer = vec![1, 2, 3, 5, 8];
713 /// io::sink().write(buffer.as_slice()).unwrap();
716 #[stable(feature = "vec_as_slice", since = "1.7.0")]
717 pub fn as_slice(&self) -> &[T] {
721 /// Extracts a mutable slice of the entire vector.
723 /// Equivalent to `&mut s[..]`.
728 /// use std::io::{self, Read};
729 /// let mut buffer = vec![0; 3];
730 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
733 #[stable(feature = "vec_as_slice", since = "1.7.0")]
734 pub fn as_mut_slice(&mut self) -> &mut [T] {
738 /// Returns a raw pointer to the vector's buffer.
740 /// The caller must ensure that the vector outlives the pointer this
741 /// function returns, or else it will end up pointing to garbage.
742 /// Modifying the vector may cause its buffer to be reallocated,
743 /// which would also make any pointers to it invalid.
745 /// The caller must also ensure that the memory the pointer (non-transitively) points to
746 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
747 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
752 /// let x = vec![1, 2, 4];
753 /// let x_ptr = x.as_ptr();
756 /// for i in 0..x.len() {
757 /// assert_eq!(*x_ptr.add(i), 1 << i);
762 /// [`as_mut_ptr`]: #method.as_mut_ptr
763 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
765 pub fn as_ptr(&self) -> *const T {
766 // We shadow the slice method of the same name to avoid going through
767 // `deref`, which creates an intermediate reference.
768 let ptr = self.buf.ptr();
769 unsafe { assume(!ptr.is_null()); }
773 /// Returns an unsafe mutable pointer to the vector's buffer.
775 /// The caller must ensure that the vector outlives the pointer this
776 /// function returns, or else it will end up pointing to garbage.
777 /// Modifying the vector may cause its buffer to be reallocated,
778 /// which would also make any pointers to it invalid.
783 /// // Allocate vector big enough for 4 elements.
785 /// let mut x: Vec<i32> = Vec::with_capacity(size);
786 /// let x_ptr = x.as_mut_ptr();
788 /// // Initialize elements via raw pointer writes, then set length.
790 /// for i in 0..size {
791 /// *x_ptr.add(i) = i as i32;
795 /// assert_eq!(&*x, &[0,1,2,3]);
797 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
799 pub fn as_mut_ptr(&mut self) -> *mut T {
800 // We shadow the slice method of the same name to avoid going through
801 // `deref_mut`, which creates an intermediate reference.
802 let ptr = self.buf.ptr();
803 unsafe { assume(!ptr.is_null()); }
807 /// Forces the length of the vector to `new_len`.
809 /// This is a low-level operation that maintains none of the normal
810 /// invariants of the type. Normally changing the length of a vector
811 /// is done using one of the safe operations instead, such as
812 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
814 /// [`truncate`]: #method.truncate
815 /// [`resize`]: #method.resize
816 /// [`extend`]: #method.extend-1
817 /// [`clear`]: #method.clear
821 /// - `new_len` must be less than or equal to [`capacity()`].
822 /// - The elements at `old_len..new_len` must be initialized.
824 /// [`capacity()`]: #method.capacity
828 /// This method can be useful for situations in which the vector
829 /// is serving as a buffer for other code, particularly over FFI:
832 /// # #![allow(dead_code)]
833 /// # // This is just a minimal skeleton for the doc example;
834 /// # // don't use this as a starting point for a real library.
835 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
836 /// # const Z_OK: i32 = 0;
838 /// # fn deflateGetDictionary(
839 /// # strm: *mut std::ffi::c_void,
840 /// # dictionary: *mut u8,
841 /// # dictLength: *mut usize,
844 /// # impl StreamWrapper {
845 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
846 /// // Per the FFI method's docs, "32768 bytes is always enough".
847 /// let mut dict = Vec::with_capacity(32_768);
848 /// let mut dict_length = 0;
849 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
850 /// // 1. `dict_length` elements were initialized.
851 /// // 2. `dict_length` <= the capacity (32_768)
852 /// // which makes `set_len` safe to call.
854 /// // Make the FFI call...
855 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
857 /// // ...and update the length to what was initialized.
858 /// dict.set_len(dict_length);
868 /// While the following example is sound, there is a memory leak since
869 /// the inner vectors were not freed prior to the `set_len` call:
872 /// let mut vec = vec![vec![1, 0, 0],
876 /// // 1. `old_len..0` is empty so no elements need to be initialized.
877 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
883 /// Normally, here, one would use [`clear`] instead to correctly drop
884 /// the contents and thus not leak memory.
886 #[stable(feature = "rust1", since = "1.0.0")]
887 pub unsafe fn set_len(&mut self, new_len: usize) {
888 debug_assert!(new_len <= self.capacity());
893 /// Removes an element from the vector and returns it.
895 /// The removed element is replaced by the last element of the vector.
897 /// This does not preserve ordering, but is O(1).
901 /// Panics if `index` is out of bounds.
906 /// let mut v = vec!["foo", "bar", "baz", "qux"];
908 /// assert_eq!(v.swap_remove(1), "bar");
909 /// assert_eq!(v, ["foo", "qux", "baz"]);
911 /// assert_eq!(v.swap_remove(0), "foo");
912 /// assert_eq!(v, ["baz", "qux"]);
915 #[stable(feature = "rust1", since = "1.0.0")]
916 pub fn swap_remove(&mut self, index: usize) -> T {
918 // We replace self[index] with the last element. Note that if the
919 // bounds check on hole succeeds there must be a last element (which
920 // can be self[index] itself).
921 let hole: *mut T = &mut self[index];
922 let last = ptr::read(self.get_unchecked(self.len - 1));
924 ptr::replace(hole, last)
928 /// Inserts an element at position `index` within the vector, shifting all
929 /// elements after it to the right.
933 /// Panics if `index > len`.
938 /// let mut vec = vec![1, 2, 3];
939 /// vec.insert(1, 4);
940 /// assert_eq!(vec, [1, 4, 2, 3]);
941 /// vec.insert(4, 5);
942 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
944 #[stable(feature = "rust1", since = "1.0.0")]
945 pub fn insert(&mut self, index: usize, element: T) {
946 let len = self.len();
947 assert!(index <= len);
949 // space for the new element
950 if len == self.buf.cap() {
956 // The spot to put the new value
958 let p = self.as_mut_ptr().add(index);
959 // Shift everything over to make space. (Duplicating the
960 // `index`th element into two consecutive places.)
961 ptr::copy(p, p.offset(1), len - index);
962 // Write it in, overwriting the first copy of the `index`th
964 ptr::write(p, element);
966 self.set_len(len + 1);
970 /// Removes and returns the element at position `index` within the vector,
971 /// shifting all elements after it to the left.
975 /// Panics if `index` is out of bounds.
980 /// let mut v = vec![1, 2, 3];
981 /// assert_eq!(v.remove(1), 2);
982 /// assert_eq!(v, [1, 3]);
984 #[stable(feature = "rust1", since = "1.0.0")]
985 pub fn remove(&mut self, index: usize) -> T {
986 let len = self.len();
987 assert!(index < len);
992 // the place we are taking from.
993 let ptr = self.as_mut_ptr().add(index);
994 // copy it out, unsafely having a copy of the value on
995 // the stack and in the vector at the same time.
996 ret = ptr::read(ptr);
998 // Shift everything down to fill in that spot.
999 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1001 self.set_len(len - 1);
1006 /// Retains only the elements specified by the predicate.
1008 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1009 /// This method operates in place, visiting each element exactly once in the
1010 /// original order, and preserves the order of the retained elements.
1015 /// let mut vec = vec![1, 2, 3, 4];
1016 /// vec.retain(|&x| x%2 == 0);
1017 /// assert_eq!(vec, [2, 4]);
1020 /// The exact order may be useful for tracking external state, like an index.
1023 /// let mut vec = vec![1, 2, 3, 4, 5];
1024 /// let keep = [false, true, true, false, true];
1026 /// vec.retain(|_| (keep[i], i += 1).0);
1027 /// assert_eq!(vec, [2, 3, 5]);
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 pub fn retain<F>(&mut self, mut f: F)
1031 where F: FnMut(&T) -> bool
1033 self.drain_filter(|x| !f(x));
1036 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1039 /// If the vector is sorted, this removes all duplicates.
1044 /// let mut vec = vec![10, 20, 21, 30, 20];
1046 /// vec.dedup_by_key(|i| *i / 10);
1048 /// assert_eq!(vec, [10, 20, 30, 20]);
1050 #[stable(feature = "dedup_by", since = "1.16.0")]
1052 pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
1053 self.dedup_by(|a, b| key(a) == key(b))
1056 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1059 /// The `same_bucket` function is passed references to two elements from the vector and
1060 /// must determine if the elements compare equal. The elements are passed in opposite order
1061 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1063 /// If the vector is sorted, this removes all duplicates.
1068 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1070 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1072 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1074 #[stable(feature = "dedup_by", since = "1.16.0")]
1075 pub fn dedup_by<F>(&mut self, same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
1077 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1083 /// Appends an element to the back of a collection.
1087 /// Panics if the number of elements in the vector overflows a `usize`.
1092 /// let mut vec = vec![1, 2];
1094 /// assert_eq!(vec, [1, 2, 3]);
1097 #[stable(feature = "rust1", since = "1.0.0")]
1098 pub fn push(&mut self, value: T) {
1099 // This will panic or abort if we would allocate > isize::MAX bytes
1100 // or if the length increment would overflow for zero-sized types.
1101 if self.len == self.buf.cap() {
1105 let end = self.as_mut_ptr().add(self.len);
1106 ptr::write(end, value);
1111 /// Removes the last element from a vector and returns it, or [`None`] if it
1114 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1119 /// let mut vec = vec![1, 2, 3];
1120 /// assert_eq!(vec.pop(), Some(3));
1121 /// assert_eq!(vec, [1, 2]);
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 pub fn pop(&mut self) -> Option<T> {
1131 Some(ptr::read(self.get_unchecked(self.len())))
1136 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1140 /// Panics if the number of elements in the vector overflows a `usize`.
1145 /// let mut vec = vec![1, 2, 3];
1146 /// let mut vec2 = vec![4, 5, 6];
1147 /// vec.append(&mut vec2);
1148 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1149 /// assert_eq!(vec2, []);
1152 #[stable(feature = "append", since = "1.4.0")]
1153 pub fn append(&mut self, other: &mut Self) {
1155 self.append_elements(other.as_slice() as _);
1160 /// Appends elements to `Self` from other buffer.
1162 unsafe fn append_elements(&mut self, other: *const [T]) {
1163 let count = (*other).len();
1164 self.reserve(count);
1165 let len = self.len();
1166 ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count);
1170 /// Creates a draining iterator that removes the specified range in the vector
1171 /// and yields the removed items.
1173 /// Note 1: The element range is removed even if the iterator is only
1174 /// partially consumed or not consumed at all.
1176 /// Note 2: It is unspecified how many elements are removed from the vector
1177 /// if the `Drain` value is leaked.
1181 /// Panics if the starting point is greater than the end point or if
1182 /// the end point is greater than the length of the vector.
1187 /// let mut v = vec![1, 2, 3];
1188 /// let u: Vec<_> = v.drain(1..).collect();
1189 /// assert_eq!(v, &[1]);
1190 /// assert_eq!(u, &[2, 3]);
1192 /// // A full range clears the vector
1194 /// assert_eq!(v, &[]);
1196 #[stable(feature = "drain", since = "1.6.0")]
1197 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1198 where R: RangeBounds<usize>
1202 // When the Drain is first created, it shortens the length of
1203 // the source vector to make sure no uninitialized or moved-from elements
1204 // are accessible at all if the Drain's destructor never gets to run.
1206 // Drain will ptr::read out the values to remove.
1207 // When finished, remaining tail of the vec is copied back to cover
1208 // the hole, and the vector length is restored to the new length.
1210 let len = self.len();
1211 let start = match range.start_bound() {
1213 Excluded(&n) => n + 1,
1216 let end = match range.end_bound() {
1217 Included(&n) => n + 1,
1221 assert!(start <= end);
1222 assert!(end <= len);
1225 // set self.vec length's to start, to be safe in case Drain is leaked
1226 self.set_len(start);
1227 // Use the borrow in the IterMut to indicate borrowing behavior of the
1228 // whole Drain iterator (like &mut T).
1229 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start),
1233 tail_len: len - end,
1234 iter: range_slice.iter(),
1235 vec: NonNull::from(self),
1240 /// Clears the vector, removing all values.
1242 /// Note that this method has no effect on the allocated capacity
1248 /// let mut v = vec![1, 2, 3];
1252 /// assert!(v.is_empty());
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 pub fn clear(&mut self) {
1260 /// Returns the number of elements in the vector, also referred to
1261 /// as its 'length'.
1266 /// let a = vec![1, 2, 3];
1267 /// assert_eq!(a.len(), 3);
1270 #[stable(feature = "rust1", since = "1.0.0")]
1271 pub fn len(&self) -> usize {
1275 /// Returns `true` if the vector contains no elements.
1280 /// let mut v = Vec::new();
1281 /// assert!(v.is_empty());
1284 /// assert!(!v.is_empty());
1286 #[stable(feature = "rust1", since = "1.0.0")]
1287 pub fn is_empty(&self) -> bool {
1291 /// Splits the collection into two at the given index.
1293 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1294 /// and the returned `Self` contains elements `[at, len)`.
1296 /// Note that the capacity of `self` does not change.
1300 /// Panics if `at > len`.
1305 /// let mut vec = vec![1,2,3];
1306 /// let vec2 = vec.split_off(1);
1307 /// assert_eq!(vec, [1]);
1308 /// assert_eq!(vec2, [2, 3]);
1311 #[stable(feature = "split_off", since = "1.4.0")]
1312 pub fn split_off(&mut self, at: usize) -> Self {
1313 assert!(at <= self.len(), "`at` out of bounds");
1315 let other_len = self.len - at;
1316 let mut other = Vec::with_capacity(other_len);
1318 // Unsafely `set_len` and copy items to `other`.
1321 other.set_len(other_len);
1323 ptr::copy_nonoverlapping(self.as_ptr().add(at),
1330 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1332 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1333 /// difference, with each additional slot filled with the result of
1334 /// calling the closure `f`. The return values from `f` will end up
1335 /// in the `Vec` in the order they have been generated.
1337 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1339 /// This method uses a closure to create new values on every push. If
1340 /// you'd rather [`Clone`] a given value, use [`resize`]. If you want
1341 /// to use the [`Default`] trait to generate values, you can pass
1342 /// [`Default::default()`] as the second argument.
1347 /// let mut vec = vec![1, 2, 3];
1348 /// vec.resize_with(5, Default::default);
1349 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1351 /// let mut vec = vec![];
1353 /// vec.resize_with(4, || { p *= 2; p });
1354 /// assert_eq!(vec, [2, 4, 8, 16]);
1357 /// [`resize`]: #method.resize
1358 /// [`Clone`]: ../../std/clone/trait.Clone.html
1359 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1360 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1361 where F: FnMut() -> T
1363 let len = self.len();
1365 self.extend_with(new_len - len, ExtendFunc(f));
1367 self.truncate(new_len);
1372 impl<T: Clone> Vec<T> {
1373 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1375 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1376 /// difference, with each additional slot filled with `value`.
1377 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1379 /// This method requires [`Clone`] to be able clone the passed value. If
1380 /// you need more flexibility (or want to rely on [`Default`] instead of
1381 /// [`Clone`]), use [`resize_with`].
1386 /// let mut vec = vec!["hello"];
1387 /// vec.resize(3, "world");
1388 /// assert_eq!(vec, ["hello", "world", "world"]);
1390 /// let mut vec = vec![1, 2, 3, 4];
1391 /// vec.resize(2, 0);
1392 /// assert_eq!(vec, [1, 2]);
1395 /// [`Clone`]: ../../std/clone/trait.Clone.html
1396 /// [`Default`]: ../../std/default/trait.Default.html
1397 /// [`resize_with`]: #method.resize_with
1398 #[stable(feature = "vec_resize", since = "1.5.0")]
1399 pub fn resize(&mut self, new_len: usize, value: T) {
1400 let len = self.len();
1403 self.extend_with(new_len - len, ExtendElement(value))
1405 self.truncate(new_len);
1409 /// Clones and appends all elements in a slice to the `Vec`.
1411 /// Iterates over the slice `other`, clones each element, and then appends
1412 /// it to this `Vec`. The `other` vector is traversed in-order.
1414 /// Note that this function is same as [`extend`] except that it is
1415 /// specialized to work with slices instead. If and when Rust gets
1416 /// specialization this function will likely be deprecated (but still
1422 /// let mut vec = vec![1];
1423 /// vec.extend_from_slice(&[2, 3, 4]);
1424 /// assert_eq!(vec, [1, 2, 3, 4]);
1427 /// [`extend`]: #method.extend
1428 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1429 pub fn extend_from_slice(&mut self, other: &[T]) {
1430 self.spec_extend(other.iter())
1434 impl<T: Default> Vec<T> {
1435 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1437 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1438 /// difference, with each additional slot filled with [`Default::default()`].
1439 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1441 /// This method uses [`Default`] to create new values on every push. If
1442 /// you'd rather [`Clone`] a given value, use [`resize`].
1447 /// # #![allow(deprecated)]
1448 /// #![feature(vec_resize_default)]
1450 /// let mut vec = vec![1, 2, 3];
1451 /// vec.resize_default(5);
1452 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1454 /// let mut vec = vec![1, 2, 3, 4];
1455 /// vec.resize_default(2);
1456 /// assert_eq!(vec, [1, 2]);
1459 /// [`resize`]: #method.resize
1460 /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default
1461 /// [`Default`]: ../../std/default/trait.Default.html
1462 /// [`Clone`]: ../../std/clone/trait.Clone.html
1463 #[unstable(feature = "vec_resize_default", issue = "41758")]
1464 #[rustc_deprecated(reason = "This is moving towards being removed in favor \
1465 of `.resize_with(Default::default)`. If you disagree, please comment \
1466 in the tracking issue.", since = "1.33.0")]
1467 pub fn resize_default(&mut self, new_len: usize) {
1468 let len = self.len();
1471 self.extend_with(new_len - len, ExtendDefault);
1473 self.truncate(new_len);
1478 // This code generalises `extend_with_{element,default}`.
1479 trait ExtendWith<T> {
1480 fn next(&mut self) -> T;
1484 struct ExtendElement<T>(T);
1485 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1486 fn next(&mut self) -> T { self.0.clone() }
1487 fn last(self) -> T { self.0 }
1490 struct ExtendDefault;
1491 impl<T: Default> ExtendWith<T> for ExtendDefault {
1492 fn next(&mut self) -> T { Default::default() }
1493 fn last(self) -> T { Default::default() }
1496 struct ExtendFunc<F>(F);
1497 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1498 fn next(&mut self) -> T { (self.0)() }
1499 fn last(mut self) -> T { (self.0)() }
1503 /// Extend the vector by `n` values, using the given generator.
1504 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1508 let mut ptr = self.as_mut_ptr().add(self.len());
1509 // Use SetLenOnDrop to work around bug where compiler
1510 // may not realize the store through `ptr` through self.set_len()
1512 let mut local_len = SetLenOnDrop::new(&mut self.len);
1514 // Write all elements except the last one
1516 ptr::write(ptr, value.next());
1517 ptr = ptr.offset(1);
1518 // Increment the length in every step in case next() panics
1519 local_len.increment_len(1);
1523 // We can write the last element directly without cloning needlessly
1524 ptr::write(ptr, value.last());
1525 local_len.increment_len(1);
1528 // len set by scope guard
1533 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1535 // The idea is: The length field in SetLenOnDrop is a local variable
1536 // that the optimizer will see does not alias with any stores through the Vec's data
1537 // pointer. This is a workaround for alias analysis issue #32155
1538 struct SetLenOnDrop<'a> {
1543 impl<'a> SetLenOnDrop<'a> {
1545 fn new(len: &'a mut usize) -> Self {
1546 SetLenOnDrop { local_len: *len, len: len }
1550 fn increment_len(&mut self, increment: usize) {
1551 self.local_len += increment;
1555 fn decrement_len(&mut self, decrement: usize) {
1556 self.local_len -= decrement;
1560 impl Drop for SetLenOnDrop<'_> {
1562 fn drop(&mut self) {
1563 *self.len = self.local_len;
1567 impl<T: PartialEq> Vec<T> {
1568 /// Removes consecutive repeated elements in the vector according to the
1569 /// [`PartialEq`] trait implementation.
1571 /// If the vector is sorted, this removes all duplicates.
1576 /// let mut vec = vec![1, 2, 2, 3, 2];
1580 /// assert_eq!(vec, [1, 2, 3, 2]);
1582 #[stable(feature = "rust1", since = "1.0.0")]
1584 pub fn dedup(&mut self) {
1585 self.dedup_by(|a, b| a == b)
1588 /// Removes the first instance of `item` from the vector if the item exists.
1593 /// # #![feature(vec_remove_item)]
1594 /// let mut vec = vec![1, 2, 3, 1];
1596 /// vec.remove_item(&1);
1598 /// assert_eq!(vec, vec![2, 3, 1]);
1600 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1601 pub fn remove_item(&mut self, item: &T) -> Option<T> {
1602 let pos = self.iter().position(|x| *x == *item)?;
1603 Some(self.remove(pos))
1607 ////////////////////////////////////////////////////////////////////////////////
1608 // Internal methods and functions
1609 ////////////////////////////////////////////////////////////////////////////////
1612 #[stable(feature = "rust1", since = "1.0.0")]
1613 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1614 <T as SpecFromElem>::from_elem(elem, n)
1617 // Specialization trait used for Vec::from_elem
1618 trait SpecFromElem: Sized {
1619 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1622 impl<T: Clone> SpecFromElem for T {
1623 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1624 let mut v = Vec::with_capacity(n);
1625 v.extend_with(n, ExtendElement(elem));
1630 impl SpecFromElem for u8 {
1632 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1635 buf: RawVec::with_capacity_zeroed(n),
1640 let mut v = Vec::with_capacity(n);
1641 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1648 impl<T: Clone + IsZero> SpecFromElem for T {
1650 fn from_elem(elem: T, n: usize) -> Vec<T> {
1653 buf: RawVec::with_capacity_zeroed(n),
1657 let mut v = Vec::with_capacity(n);
1658 v.extend_with(n, ExtendElement(elem));
1663 unsafe trait IsZero {
1664 /// Whether this value is zero
1665 fn is_zero(&self) -> bool;
1668 macro_rules! impl_is_zero {
1669 ($t: ty, $is_zero: expr) => {
1670 unsafe impl IsZero for $t {
1672 fn is_zero(&self) -> bool {
1679 impl_is_zero!(i8, |x| x == 0);
1680 impl_is_zero!(i16, |x| x == 0);
1681 impl_is_zero!(i32, |x| x == 0);
1682 impl_is_zero!(i64, |x| x == 0);
1683 impl_is_zero!(i128, |x| x == 0);
1684 impl_is_zero!(isize, |x| x == 0);
1686 impl_is_zero!(u16, |x| x == 0);
1687 impl_is_zero!(u32, |x| x == 0);
1688 impl_is_zero!(u64, |x| x == 0);
1689 impl_is_zero!(u128, |x| x == 0);
1690 impl_is_zero!(usize, |x| x == 0);
1692 impl_is_zero!(bool, |x| x == false);
1693 impl_is_zero!(char, |x| x == '\0');
1695 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1696 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1698 unsafe impl<T: ?Sized> IsZero for *const T {
1700 fn is_zero(&self) -> bool {
1705 unsafe impl<T: ?Sized> IsZero for *mut T {
1707 fn is_zero(&self) -> bool {
1713 ////////////////////////////////////////////////////////////////////////////////
1714 // Common trait implementations for Vec
1715 ////////////////////////////////////////////////////////////////////////////////
1717 #[stable(feature = "rust1", since = "1.0.0")]
1718 impl<T: Clone> Clone for Vec<T> {
1720 fn clone(&self) -> Vec<T> {
1721 <[T]>::to_vec(&**self)
1724 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1725 // required for this method definition, is not available. Instead use the
1726 // `slice::to_vec` function which is only available with cfg(test)
1727 // NB see the slice::hack module in slice.rs for more information
1729 fn clone(&self) -> Vec<T> {
1730 crate::slice::to_vec(&**self)
1733 fn clone_from(&mut self, other: &Vec<T>) {
1734 other.as_slice().clone_into(self);
1738 #[stable(feature = "rust1", since = "1.0.0")]
1739 impl<T: Hash> Hash for Vec<T> {
1741 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1742 Hash::hash(&**self, state)
1746 #[stable(feature = "rust1", since = "1.0.0")]
1747 #[rustc_on_unimplemented(
1748 message="vector indices are of type `usize` or ranges of `usize`",
1749 label="vector indices are of type `usize` or ranges of `usize`",
1751 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
1752 type Output = I::Output;
1755 fn index(&self, index: I) -> &Self::Output {
1756 Index::index(&**self, index)
1760 #[stable(feature = "rust1", since = "1.0.0")]
1761 #[rustc_on_unimplemented(
1762 message="vector indices are of type `usize` or ranges of `usize`",
1763 label="vector indices are of type `usize` or ranges of `usize`",
1765 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
1767 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1768 IndexMut::index_mut(&mut **self, index)
1772 #[stable(feature = "rust1", since = "1.0.0")]
1773 impl<T> ops::Deref for Vec<T> {
1776 fn deref(&self) -> &[T] {
1778 slice::from_raw_parts(self.as_ptr(), self.len)
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 impl<T> ops::DerefMut for Vec<T> {
1785 fn deref_mut(&mut self) -> &mut [T] {
1787 slice::from_raw_parts_mut(self.as_mut_ptr(), self.len)
1792 #[stable(feature = "rust1", since = "1.0.0")]
1793 impl<T> FromIterator<T> for Vec<T> {
1795 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1796 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1800 #[stable(feature = "rust1", since = "1.0.0")]
1801 impl<T> IntoIterator for Vec<T> {
1803 type IntoIter = IntoIter<T>;
1805 /// Creates a consuming iterator, that is, one that moves each value out of
1806 /// the vector (from start to end). The vector cannot be used after calling
1812 /// let v = vec!["a".to_string(), "b".to_string()];
1813 /// for s in v.into_iter() {
1814 /// // s has type String, not &String
1815 /// println!("{}", s);
1819 fn into_iter(mut self) -> IntoIter<T> {
1821 let begin = self.as_mut_ptr();
1822 let end = if mem::size_of::<T>() == 0 {
1823 arith_offset(begin as *const i8, self.len() as isize) as *const T
1825 begin.add(self.len()) as *const T
1827 let cap = self.buf.cap();
1830 buf: NonNull::new_unchecked(begin),
1831 phantom: PhantomData,
1840 #[stable(feature = "rust1", since = "1.0.0")]
1841 impl<'a, T> IntoIterator for &'a Vec<T> {
1843 type IntoIter = slice::Iter<'a, T>;
1845 fn into_iter(self) -> slice::Iter<'a, T> {
1850 #[stable(feature = "rust1", since = "1.0.0")]
1851 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1852 type Item = &'a mut T;
1853 type IntoIter = slice::IterMut<'a, T>;
1855 fn into_iter(self) -> slice::IterMut<'a, T> {
1860 #[stable(feature = "rust1", since = "1.0.0")]
1861 impl<T> Extend<T> for Vec<T> {
1863 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1864 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1868 // Specialization trait used for Vec::from_iter and Vec::extend
1869 trait SpecExtend<T, I> {
1870 fn from_iter(iter: I) -> Self;
1871 fn spec_extend(&mut self, iter: I);
1874 impl<T, I> SpecExtend<T, I> for Vec<T>
1875 where I: Iterator<Item=T>,
1877 default fn from_iter(mut iterator: I) -> Self {
1878 // Unroll the first iteration, as the vector is going to be
1879 // expanded on this iteration in every case when the iterable is not
1880 // empty, but the loop in extend_desugared() is not going to see the
1881 // vector being full in the few subsequent loop iterations.
1882 // So we get better branch prediction.
1883 let mut vector = match iterator.next() {
1884 None => return Vec::new(),
1886 let (lower, _) = iterator.size_hint();
1887 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1889 ptr::write(vector.get_unchecked_mut(0), element);
1895 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1899 default fn spec_extend(&mut self, iter: I) {
1900 self.extend_desugared(iter)
1904 impl<T, I> SpecExtend<T, I> for Vec<T>
1905 where I: TrustedLen<Item=T>,
1907 default fn from_iter(iterator: I) -> Self {
1908 let mut vector = Vec::new();
1909 vector.spec_extend(iterator);
1913 default fn spec_extend(&mut self, iterator: I) {
1914 // This is the case for a TrustedLen iterator.
1915 let (low, high) = iterator.size_hint();
1916 if let Some(high_value) = high {
1917 debug_assert_eq!(low, high_value,
1918 "TrustedLen iterator's size hint is not exact: {:?}",
1921 if let Some(additional) = high {
1922 self.reserve(additional);
1924 let mut ptr = self.as_mut_ptr().add(self.len());
1925 let mut local_len = SetLenOnDrop::new(&mut self.len);
1926 iterator.for_each(move |element| {
1927 ptr::write(ptr, element);
1928 ptr = ptr.offset(1);
1929 // NB can't overflow since we would have had to alloc the address space
1930 local_len.increment_len(1);
1934 self.extend_desugared(iterator)
1939 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
1940 fn from_iter(iterator: IntoIter<T>) -> Self {
1941 // A common case is passing a vector into a function which immediately
1942 // re-collects into a vector. We can short circuit this if the IntoIter
1943 // has not been advanced at all.
1944 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
1946 let vec = Vec::from_raw_parts(iterator.buf.as_ptr(),
1949 mem::forget(iterator);
1953 let mut vector = Vec::new();
1954 vector.spec_extend(iterator);
1959 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
1961 self.append_elements(iterator.as_slice() as _);
1963 iterator.ptr = iterator.end;
1967 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
1968 where I: Iterator<Item=&'a T>,
1971 default fn from_iter(iterator: I) -> Self {
1972 SpecExtend::from_iter(iterator.cloned())
1975 default fn spec_extend(&mut self, iterator: I) {
1976 self.spec_extend(iterator.cloned())
1980 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
1983 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
1984 let slice = iterator.as_slice();
1985 self.reserve(slice.len());
1987 let len = self.len();
1988 self.set_len(len + slice.len());
1989 self.get_unchecked_mut(len..).copy_from_slice(slice);
1995 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1996 // This is the case for a general iterator.
1998 // This function should be the moral equivalent of:
2000 // for item in iterator {
2003 while let Some(element) = iterator.next() {
2004 let len = self.len();
2005 if len == self.capacity() {
2006 let (lower, _) = iterator.size_hint();
2007 self.reserve(lower.saturating_add(1));
2010 ptr::write(self.get_unchecked_mut(len), element);
2011 // NB can't overflow since we would have had to alloc the address space
2012 self.set_len(len + 1);
2017 /// Creates a splicing iterator that replaces the specified range in the vector
2018 /// with the given `replace_with` iterator and yields the removed items.
2019 /// `replace_with` does not need to be the same length as `range`.
2021 /// Note 1: The element range is removed even if the iterator is not
2022 /// consumed until the end.
2024 /// Note 2: It is unspecified how many elements are removed from the vector,
2025 /// if the `Splice` value is leaked.
2027 /// Note 3: The input iterator `replace_with` is only consumed
2028 /// when the `Splice` value is dropped.
2030 /// Note 4: This is optimal if:
2032 /// * The tail (elements in the vector after `range`) is empty,
2033 /// * or `replace_with` yields fewer elements than `range`’s length
2034 /// * or the lower bound of its `size_hint()` is exact.
2036 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2040 /// Panics if the starting point is greater than the end point or if
2041 /// the end point is greater than the length of the vector.
2046 /// let mut v = vec![1, 2, 3];
2047 /// let new = [7, 8];
2048 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2049 /// assert_eq!(v, &[7, 8, 3]);
2050 /// assert_eq!(u, &[1, 2]);
2053 #[stable(feature = "vec_splice", since = "1.21.0")]
2054 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2055 where R: RangeBounds<usize>, I: IntoIterator<Item=T>
2058 drain: self.drain(range),
2059 replace_with: replace_with.into_iter(),
2063 /// Creates an iterator which uses a closure to determine if an element should be removed.
2065 /// If the closure returns true, then the element is removed and yielded.
2066 /// If the closure returns false, the element will remain in the vector and will not be yielded
2067 /// by the iterator.
2069 /// Using this method is equivalent to the following code:
2072 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2073 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2075 /// while i != vec.len() {
2076 /// if some_predicate(&mut vec[i]) {
2077 /// let val = vec.remove(i);
2078 /// // your code here
2084 /// # assert_eq!(vec, vec![1, 4, 5]);
2087 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2088 /// because it can backshift the elements of the array in bulk.
2090 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2091 /// regardless of whether you choose to keep or remove it.
2096 /// Splitting an array into evens and odds, reusing the original allocation:
2099 /// #![feature(drain_filter)]
2100 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2102 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2103 /// let odds = numbers;
2105 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2106 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2108 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2109 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2110 where F: FnMut(&mut T) -> bool,
2112 let old_len = self.len();
2114 // Guard against us getting leaked (leak amplification)
2115 unsafe { self.set_len(0); }
2127 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2129 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2130 /// append the entire slice at once.
2132 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2133 #[stable(feature = "extend_ref", since = "1.2.0")]
2134 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2135 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2136 self.spec_extend(iter.into_iter())
2140 macro_rules! __impl_slice_eq1 {
2141 ($Lhs: ty, $Rhs: ty) => {
2142 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2144 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2145 #[stable(feature = "rust1", since = "1.0.0")]
2146 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2148 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
2150 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
2155 __impl_slice_eq1! { Vec<A>, Vec<B> }
2156 __impl_slice_eq1! { Vec<A>, &'b [B] }
2157 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
2158 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
2159 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
2160 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
2162 macro_rules! array_impls {
2165 // NOTE: some less important impls are omitted to reduce code bloat
2166 __impl_slice_eq1! { Vec<A>, [B; $N] }
2167 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
2168 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
2169 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
2170 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
2171 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
2178 10 11 12 13 14 15 16 17 18 19
2179 20 21 22 23 24 25 26 27 28 29
2183 /// Implements comparison of vectors, lexicographically.
2184 #[stable(feature = "rust1", since = "1.0.0")]
2185 impl<T: PartialOrd> PartialOrd for Vec<T> {
2187 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2188 PartialOrd::partial_cmp(&**self, &**other)
2192 #[stable(feature = "rust1", since = "1.0.0")]
2193 impl<T: Eq> Eq for Vec<T> {}
2195 /// Implements ordering of vectors, lexicographically.
2196 #[stable(feature = "rust1", since = "1.0.0")]
2197 impl<T: Ord> Ord for Vec<T> {
2199 fn cmp(&self, other: &Vec<T>) -> Ordering {
2200 Ord::cmp(&**self, &**other)
2204 #[stable(feature = "rust1", since = "1.0.0")]
2205 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2206 fn drop(&mut self) {
2209 ptr::drop_in_place(&mut self[..]);
2211 // RawVec handles deallocation
2215 #[stable(feature = "rust1", since = "1.0.0")]
2216 impl<T> Default for Vec<T> {
2217 /// Creates an empty `Vec<T>`.
2218 fn default() -> Vec<T> {
2223 #[stable(feature = "rust1", since = "1.0.0")]
2224 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2225 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2226 fmt::Debug::fmt(&**self, f)
2230 #[stable(feature = "rust1", since = "1.0.0")]
2231 impl<T> AsRef<Vec<T>> for Vec<T> {
2232 fn as_ref(&self) -> &Vec<T> {
2237 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2238 impl<T> AsMut<Vec<T>> for Vec<T> {
2239 fn as_mut(&mut self) -> &mut Vec<T> {
2244 #[stable(feature = "rust1", since = "1.0.0")]
2245 impl<T> AsRef<[T]> for Vec<T> {
2246 fn as_ref(&self) -> &[T] {
2251 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2252 impl<T> AsMut<[T]> for Vec<T> {
2253 fn as_mut(&mut self) -> &mut [T] {
2258 #[stable(feature = "rust1", since = "1.0.0")]
2259 impl<T: Clone> From<&[T]> for Vec<T> {
2261 fn from(s: &[T]) -> Vec<T> {
2265 fn from(s: &[T]) -> Vec<T> {
2266 crate::slice::to_vec(s)
2270 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2271 impl<T: Clone> From<&mut [T]> for Vec<T> {
2273 fn from(s: &mut [T]) -> Vec<T> {
2277 fn from(s: &mut [T]) -> Vec<T> {
2278 crate::slice::to_vec(s)
2282 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2283 impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> {
2284 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2289 // note: test pulls in libstd, which causes errors here
2291 #[stable(feature = "vec_from_box", since = "1.18.0")]
2292 impl<T> From<Box<[T]>> for Vec<T> {
2293 fn from(s: Box<[T]>) -> Vec<T> {
2298 // note: test pulls in libstd, which causes errors here
2300 #[stable(feature = "box_from_vec", since = "1.20.0")]
2301 impl<T> From<Vec<T>> for Box<[T]> {
2302 fn from(v: Vec<T>) -> Box<[T]> {
2303 v.into_boxed_slice()
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 impl From<&str> for Vec<u8> {
2309 fn from(s: &str) -> Vec<u8> {
2310 From::from(s.as_bytes())
2314 ////////////////////////////////////////////////////////////////////////////////
2316 ////////////////////////////////////////////////////////////////////////////////
2318 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2319 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2320 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2325 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2326 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2327 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2332 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2333 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2334 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2335 Cow::Borrowed(v.as_slice())
2339 #[stable(feature = "rust1", since = "1.0.0")]
2340 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
2341 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2342 Cow::Owned(FromIterator::from_iter(it))
2346 ////////////////////////////////////////////////////////////////////////////////
2348 ////////////////////////////////////////////////////////////////////////////////
2350 /// An iterator that moves out of a vector.
2352 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2353 /// by the [`IntoIterator`] trait).
2355 /// [`Vec`]: struct.Vec.html
2356 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2357 #[stable(feature = "rust1", since = "1.0.0")]
2358 pub struct IntoIter<T> {
2360 phantom: PhantomData<T>,
2366 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2367 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2368 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2369 f.debug_tuple("IntoIter")
2370 .field(&self.as_slice())
2375 impl<T> IntoIter<T> {
2376 /// Returns the remaining items of this iterator as a slice.
2381 /// let vec = vec!['a', 'b', 'c'];
2382 /// let mut into_iter = vec.into_iter();
2383 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2384 /// let _ = into_iter.next().unwrap();
2385 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2387 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2388 pub fn as_slice(&self) -> &[T] {
2390 slice::from_raw_parts(self.ptr, self.len())
2394 /// Returns the remaining items of this iterator as a mutable slice.
2399 /// let vec = vec!['a', 'b', 'c'];
2400 /// let mut into_iter = vec.into_iter();
2401 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2402 /// into_iter.as_mut_slice()[2] = 'z';
2403 /// assert_eq!(into_iter.next().unwrap(), 'a');
2404 /// assert_eq!(into_iter.next().unwrap(), 'b');
2405 /// assert_eq!(into_iter.next().unwrap(), 'z');
2407 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2408 pub fn as_mut_slice(&mut self) -> &mut [T] {
2410 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
2415 #[stable(feature = "rust1", since = "1.0.0")]
2416 unsafe impl<T: Send> Send for IntoIter<T> {}
2417 #[stable(feature = "rust1", since = "1.0.0")]
2418 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2420 #[stable(feature = "rust1", since = "1.0.0")]
2421 impl<T> Iterator for IntoIter<T> {
2425 fn next(&mut self) -> Option<T> {
2427 if self.ptr as *const _ == self.end {
2430 if mem::size_of::<T>() == 0 {
2431 // purposefully don't use 'ptr.offset' because for
2432 // vectors with 0-size elements this would return the
2434 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2436 // Make up a value of this ZST.
2440 self.ptr = self.ptr.offset(1);
2442 Some(ptr::read(old))
2449 fn size_hint(&self) -> (usize, Option<usize>) {
2450 let exact = if mem::size_of::<T>() == 0 {
2451 (self.end as usize).wrapping_sub(self.ptr as usize)
2453 unsafe { self.end.offset_from(self.ptr) as usize }
2455 (exact, Some(exact))
2459 fn count(self) -> usize {
2464 #[stable(feature = "rust1", since = "1.0.0")]
2465 impl<T> DoubleEndedIterator for IntoIter<T> {
2467 fn next_back(&mut self) -> Option<T> {
2469 if self.end == self.ptr {
2472 if mem::size_of::<T>() == 0 {
2473 // See above for why 'ptr.offset' isn't used
2474 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2476 // Make up a value of this ZST.
2479 self.end = self.end.offset(-1);
2481 Some(ptr::read(self.end))
2488 #[stable(feature = "rust1", since = "1.0.0")]
2489 impl<T> ExactSizeIterator for IntoIter<T> {
2490 fn is_empty(&self) -> bool {
2491 self.ptr == self.end
2495 #[stable(feature = "fused", since = "1.26.0")]
2496 impl<T> FusedIterator for IntoIter<T> {}
2498 #[unstable(feature = "trusted_len", issue = "37572")]
2499 unsafe impl<T> TrustedLen for IntoIter<T> {}
2501 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2502 impl<T: Clone> Clone for IntoIter<T> {
2503 fn clone(&self) -> IntoIter<T> {
2504 self.as_slice().to_owned().into_iter()
2508 #[stable(feature = "rust1", since = "1.0.0")]
2509 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2510 fn drop(&mut self) {
2511 // destroy the remaining elements
2512 for _x in self.by_ref() {}
2514 // RawVec handles deallocation
2515 let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) };
2519 /// A draining iterator for `Vec<T>`.
2521 /// This `struct` is created by the [`drain`] method on [`Vec`].
2523 /// [`drain`]: struct.Vec.html#method.drain
2524 /// [`Vec`]: struct.Vec.html
2525 #[stable(feature = "drain", since = "1.6.0")]
2526 pub struct Drain<'a, T: 'a> {
2527 /// Index of tail to preserve
2531 /// Current remaining range to remove
2532 iter: slice::Iter<'a, T>,
2533 vec: NonNull<Vec<T>>,
2536 #[stable(feature = "collection_debug", since = "1.17.0")]
2537 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2538 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2539 f.debug_tuple("Drain")
2540 .field(&self.iter.as_slice())
2545 impl<'a, T> Drain<'a, T> {
2546 /// Returns the remaining items of this iterator as a slice.
2551 /// # #![feature(vec_drain_as_slice)]
2552 /// let mut vec = vec!['a', 'b', 'c'];
2553 /// let mut drain = vec.drain(..);
2554 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
2555 /// let _ = drain.next().unwrap();
2556 /// assert_eq!(drain.as_slice(), &['b', 'c']);
2558 #[unstable(feature = "vec_drain_as_slice", reason = "recently added", issue = "58957")]
2559 pub fn as_slice(&self) -> &[T] {
2560 self.iter.as_slice()
2564 #[stable(feature = "drain", since = "1.6.0")]
2565 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2566 #[stable(feature = "drain", since = "1.6.0")]
2567 unsafe impl<T: Send> Send for Drain<'_, T> {}
2569 #[stable(feature = "drain", since = "1.6.0")]
2570 impl<T> Iterator for Drain<'_, T> {
2574 fn next(&mut self) -> Option<T> {
2575 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2578 fn size_hint(&self) -> (usize, Option<usize>) {
2579 self.iter.size_hint()
2583 #[stable(feature = "drain", since = "1.6.0")]
2584 impl<T> DoubleEndedIterator for Drain<'_, T> {
2586 fn next_back(&mut self) -> Option<T> {
2587 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2591 #[stable(feature = "drain", since = "1.6.0")]
2592 impl<T> Drop for Drain<'_, T> {
2593 fn drop(&mut self) {
2594 // exhaust self first
2595 self.for_each(drop);
2597 if self.tail_len > 0 {
2599 let source_vec = self.vec.as_mut();
2600 // memmove back untouched tail, update to new length
2601 let start = source_vec.len();
2602 let tail = self.tail_start;
2604 let src = source_vec.as_ptr().add(tail);
2605 let dst = source_vec.as_mut_ptr().add(start);
2606 ptr::copy(src, dst, self.tail_len);
2608 source_vec.set_len(start + self.tail_len);
2615 #[stable(feature = "drain", since = "1.6.0")]
2616 impl<T> ExactSizeIterator for Drain<'_, T> {
2617 fn is_empty(&self) -> bool {
2618 self.iter.is_empty()
2622 #[stable(feature = "fused", since = "1.26.0")]
2623 impl<T> FusedIterator for Drain<'_, T> {}
2625 /// A splicing iterator for `Vec`.
2627 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2628 /// documentation for more.
2630 /// [`splice()`]: struct.Vec.html#method.splice
2631 /// [`Vec`]: struct.Vec.html
2633 #[stable(feature = "vec_splice", since = "1.21.0")]
2634 pub struct Splice<'a, I: Iterator + 'a> {
2635 drain: Drain<'a, I::Item>,
2639 #[stable(feature = "vec_splice", since = "1.21.0")]
2640 impl<I: Iterator> Iterator for Splice<'_, I> {
2641 type Item = I::Item;
2643 fn next(&mut self) -> Option<Self::Item> {
2647 fn size_hint(&self) -> (usize, Option<usize>) {
2648 self.drain.size_hint()
2652 #[stable(feature = "vec_splice", since = "1.21.0")]
2653 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
2654 fn next_back(&mut self) -> Option<Self::Item> {
2655 self.drain.next_back()
2659 #[stable(feature = "vec_splice", since = "1.21.0")]
2660 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
2663 #[stable(feature = "vec_splice", since = "1.21.0")]
2664 impl<I: Iterator> Drop for Splice<'_, I> {
2665 fn drop(&mut self) {
2666 self.drain.by_ref().for_each(drop);
2669 if self.drain.tail_len == 0 {
2670 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2674 // First fill the range left by drain().
2675 if !self.drain.fill(&mut self.replace_with) {
2679 // There may be more elements. Use the lower bound as an estimate.
2680 // FIXME: Is the upper bound a better guess? Or something else?
2681 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2682 if lower_bound > 0 {
2683 self.drain.move_tail(lower_bound);
2684 if !self.drain.fill(&mut self.replace_with) {
2689 // Collect any remaining elements.
2690 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2691 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2692 // Now we have an exact count.
2693 if collected.len() > 0 {
2694 self.drain.move_tail(collected.len());
2695 let filled = self.drain.fill(&mut collected);
2696 debug_assert!(filled);
2697 debug_assert_eq!(collected.len(), 0);
2700 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2704 /// Private helper methods for `Splice::drop`
2705 impl<T> Drain<'_, T> {
2706 /// The range from `self.vec.len` to `self.tail_start` contains elements
2707 /// that have been moved out.
2708 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2709 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2710 unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
2711 let vec = self.vec.as_mut();
2712 let range_start = vec.len;
2713 let range_end = self.tail_start;
2714 let range_slice = slice::from_raw_parts_mut(
2715 vec.as_mut_ptr().add(range_start),
2716 range_end - range_start);
2718 for place in range_slice {
2719 if let Some(new_item) = replace_with.next() {
2720 ptr::write(place, new_item);
2729 /// Makes room for inserting more elements before the tail.
2730 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2731 let vec = self.vec.as_mut();
2732 let used_capacity = self.tail_start + self.tail_len;
2733 vec.buf.reserve(used_capacity, extra_capacity);
2735 let new_tail_start = self.tail_start + extra_capacity;
2736 let src = vec.as_ptr().add(self.tail_start);
2737 let dst = vec.as_mut_ptr().add(new_tail_start);
2738 ptr::copy(src, dst, self.tail_len);
2739 self.tail_start = new_tail_start;
2743 /// An iterator produced by calling `drain_filter` on Vec.
2744 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2746 pub struct DrainFilter<'a, T, F>
2747 where F: FnMut(&mut T) -> bool,
2749 vec: &'a mut Vec<T>,
2756 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2757 impl<T, F> Iterator for DrainFilter<'_, T, F>
2758 where F: FnMut(&mut T) -> bool,
2762 fn next(&mut self) -> Option<T> {
2764 while self.idx != self.old_len {
2767 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
2768 if (self.pred)(&mut v[i]) {
2770 return Some(ptr::read(&v[i]));
2771 } else if self.del > 0 {
2773 let src: *const T = &v[i];
2774 let dst: *mut T = &mut v[i - del];
2775 // This is safe because self.vec has length 0
2776 // thus its elements will not have Drop::drop
2777 // called on them in the event of a panic.
2778 ptr::copy_nonoverlapping(src, dst, 1);
2785 fn size_hint(&self) -> (usize, Option<usize>) {
2786 (0, Some(self.old_len - self.idx))
2790 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2791 impl<T, F> Drop for DrainFilter<'_, T, F>
2792 where F: FnMut(&mut T) -> bool,
2794 fn drop(&mut self) {
2795 self.for_each(drop);
2797 self.vec.set_len(self.old_len - self.del);