1 // ignore-tidy-filelength
2 //! A contiguous growable array type with heap-allocated contents, written
5 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
6 //! `O(1)` pop (from the end).
8 //! Vectors ensure they never allocate more than `isize::MAX` bytes.
12 //! You can explicitly create a [`Vec`] with [`Vec::new`]:
15 //! let v: Vec<i32> = Vec::new();
18 //! ...or by using the [`vec!`] macro:
21 //! let v: Vec<i32> = vec![];
23 //! let v = vec![1, 2, 3, 4, 5];
25 //! let v = vec![0; 10]; // ten zeroes
28 //! You can [`push`] values onto the end of a vector (which will grow the vector
32 //! let mut v = vec![1, 2];
37 //! Popping values works in much the same way:
40 //! let mut v = vec![1, 2];
42 //! let two = v.pop();
45 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
48 //! let mut v = vec![1, 2, 3];
53 //! [`push`]: Vec::push
55 #![stable(feature = "rust1", since = "1.0.0")]
57 use core::cmp::{self, Ordering};
59 use core::hash::{Hash, Hasher};
60 use core::intrinsics::{arith_offset, assume};
61 use core::iter::{FromIterator, FusedIterator, TrustedLen};
62 use core::marker::PhantomData;
63 use core::mem::{self, ManuallyDrop, MaybeUninit};
64 use core::ops::Bound::{Excluded, Included, Unbounded};
65 use core::ops::{self, Index, IndexMut, RangeBounds};
66 use core::ptr::{self, NonNull};
67 use core::slice::{self, SliceIndex};
69 use crate::borrow::{Cow, ToOwned};
70 use crate::boxed::Box;
71 use crate::collections::TryReserveError;
72 use crate::raw_vec::RawVec;
74 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
79 /// let mut vec = Vec::new();
83 /// assert_eq!(vec.len(), 2);
84 /// assert_eq!(vec[0], 1);
86 /// assert_eq!(vec.pop(), Some(2));
87 /// assert_eq!(vec.len(), 1);
90 /// assert_eq!(vec[0], 7);
92 /// vec.extend([1, 2, 3].iter().copied());
95 /// println!("{}", x);
97 /// assert_eq!(vec, [7, 1, 2, 3]);
100 /// The [`vec!`] macro is provided to make initialization more convenient:
103 /// let mut vec = vec![1, 2, 3];
105 /// assert_eq!(vec, [1, 2, 3, 4]);
108 /// It can also initialize each element of a `Vec<T>` with a given value.
109 /// This may be more efficient than performing allocation and initialization
110 /// in separate steps, especially when initializing a vector of zeros:
113 /// let vec = vec![0; 5];
114 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
116 /// // The following is equivalent, but potentially slower:
117 /// let mut vec = Vec::with_capacity(5);
118 /// vec.resize(5, 0);
119 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
122 /// Use a `Vec<T>` as an efficient stack:
125 /// let mut stack = Vec::new();
131 /// while let Some(top) = stack.pop() {
132 /// // Prints 3, 2, 1
133 /// println!("{}", top);
139 /// The `Vec` type allows to access values by index, because it implements the
140 /// [`Index`] trait. An example will be more explicit:
143 /// let v = vec![0, 2, 4, 6];
144 /// println!("{}", v[1]); // it will display '2'
147 /// However be careful: if you try to access an index which isn't in the `Vec`,
148 /// your software will panic! You cannot do this:
151 /// let v = vec![0, 2, 4, 6];
152 /// println!("{}", v[6]); // it will panic!
155 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
160 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
161 /// To get a slice, use `&`. Example:
164 /// fn read_slice(slice: &[usize]) {
168 /// let v = vec![0, 1];
171 /// // ... and that's all!
172 /// // you can also do it like this:
173 /// let x : &[usize] = &v;
176 /// In Rust, it's more common to pass slices as arguments rather than vectors
177 /// when you just want to provide read access. The same goes for [`String`] and
180 /// # Capacity and reallocation
182 /// The capacity of a vector is the amount of space allocated for any future
183 /// elements that will be added onto the vector. This is not to be confused with
184 /// the *length* of a vector, which specifies the number of actual elements
185 /// within the vector. If a vector's length exceeds its capacity, its capacity
186 /// will automatically be increased, but its elements will have to be
189 /// For example, a vector with capacity 10 and length 0 would be an empty vector
190 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
191 /// vector will not change its capacity or cause reallocation to occur. However,
192 /// if the vector's length is increased to 11, it will have to reallocate, which
193 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
194 /// whenever possible to specify how big the vector is expected to get.
198 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
199 /// about its design. This ensures that it's as low-overhead as possible in
200 /// the general case, and can be correctly manipulated in primitive ways
201 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
202 /// If additional type parameters are added (e.g., to support custom allocators),
203 /// overriding their defaults may change the behavior.
205 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
206 /// triplet. No more, no less. The order of these fields is completely
207 /// unspecified, and you should use the appropriate methods to modify these.
208 /// The pointer will never be null, so this type is null-pointer-optimized.
210 /// However, the pointer may not actually point to allocated memory. In particular,
211 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
212 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
213 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
214 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
215 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
216 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
217 /// details are very subtle — if you intend to allocate memory using a `Vec`
218 /// and use it for something else (either to pass to unsafe code, or to build your
219 /// own memory-backed collection), be sure to deallocate this memory by using
220 /// `from_raw_parts` to recover the `Vec` and then dropping it.
222 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
223 /// (as defined by the allocator Rust is configured to use by default), and its
224 /// pointer points to [`len`] initialized, contiguous elements in order (what
225 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
226 /// `[`len`] logically uninitialized, contiguous elements.
228 /// `Vec` will never perform a "small optimization" where elements are actually
229 /// stored on the stack for two reasons:
231 /// * It would make it more difficult for unsafe code to correctly manipulate
232 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
233 /// only moved, and it would be more difficult to determine if a `Vec` had
234 /// actually allocated memory.
236 /// * It would penalize the general case, incurring an additional branch
239 /// `Vec` will never automatically shrink itself, even if completely empty. This
240 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
241 /// and then filling it back up to the same [`len`] should incur no calls to
242 /// the allocator. If you wish to free up unused memory, use
243 /// [`shrink_to_fit`].
245 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
246 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
247 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
248 /// accurate, and can be relied on. It can even be used to manually free the memory
249 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
250 /// when not necessary.
252 /// `Vec` does not guarantee any particular growth strategy when reallocating
253 /// when full, nor when [`reserve`] is called. The current strategy is basic
254 /// and it may prove desirable to use a non-constant growth factor. Whatever
255 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
257 /// `vec![x; n]`, `vec![a, b, c, d]`, and
258 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
259 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
260 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
261 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
263 /// `Vec` will not specifically overwrite any data that is removed from it,
264 /// but also won't specifically preserve it. Its uninitialized memory is
265 /// scratch space that it may use however it wants. It will generally just do
266 /// whatever is most efficient or otherwise easy to implement. Do not rely on
267 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
268 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
269 /// first, that may not actually happen because the optimizer does not consider
270 /// this a side-effect that must be preserved. There is one case which we will
271 /// not break, however: using `unsafe` code to write to the excess capacity,
272 /// and then increasing the length to match, is always valid.
274 /// `Vec` does not currently guarantee the order in which elements are dropped.
275 /// The order has changed in the past and may change again.
277 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
278 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
279 /// [`String`]: crate::string::String
280 /// [`&str`]: type@str
281 /// [`shrink_to_fit`]: Vec::shrink_to_fit
282 /// [`capacity`]: Vec::capacity
283 /// [`mem::size_of::<T>`]: core::mem::size_of
284 /// [`len`]: Vec::len
285 /// [`push`]: Vec::push
286 /// [`insert`]: Vec::insert
287 /// [`reserve`]: Vec::reserve
288 /// [owned slice]: Box
289 #[stable(feature = "rust1", since = "1.0.0")]
290 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
296 ////////////////////////////////////////////////////////////////////////////////
298 ////////////////////////////////////////////////////////////////////////////////
301 /// Constructs a new, empty `Vec<T>`.
303 /// The vector will not allocate until elements are pushed onto it.
308 /// # #![allow(unused_mut)]
309 /// let mut vec: Vec<i32> = Vec::new();
312 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
313 #[stable(feature = "rust1", since = "1.0.0")]
314 pub const fn new() -> Vec<T> {
315 Vec { buf: RawVec::NEW, len: 0 }
318 /// Constructs a new, empty `Vec<T>` with the specified capacity.
320 /// The vector will be able to hold exactly `capacity` elements without
321 /// reallocating. If `capacity` is 0, the vector will not allocate.
323 /// It is important to note that although the returned vector has the
324 /// *capacity* specified, the vector will have a zero *length*. For an
325 /// explanation of the difference between length and capacity, see
326 /// *[Capacity and reallocation]*.
328 /// [Capacity and reallocation]: #capacity-and-reallocation
333 /// let mut vec = Vec::with_capacity(10);
335 /// // The vector contains no items, even though it has capacity for more
336 /// assert_eq!(vec.len(), 0);
337 /// assert_eq!(vec.capacity(), 10);
339 /// // These are all done without reallocating...
343 /// assert_eq!(vec.len(), 10);
344 /// assert_eq!(vec.capacity(), 10);
346 /// // ...but this may make the vector reallocate
348 /// assert_eq!(vec.len(), 11);
349 /// assert!(vec.capacity() >= 11);
352 #[stable(feature = "rust1", since = "1.0.0")]
353 pub fn with_capacity(capacity: usize) -> Vec<T> {
354 Vec { buf: RawVec::with_capacity(capacity), len: 0 }
357 /// Decomposes a `Vec<T>` into its raw components.
359 /// Returns the raw pointer to the underlying data, the length of
360 /// the vector (in elements), and the allocated capacity of the
361 /// data (in elements). These are the same arguments in the same
362 /// order as the arguments to [`from_raw_parts`].
364 /// After calling this function, the caller is responsible for the
365 /// memory previously managed by the `Vec`. The only way to do
366 /// this is to convert the raw pointer, length, and capacity back
367 /// into a `Vec` with the [`from_raw_parts`] function, allowing
368 /// the destructor to perform the cleanup.
370 /// [`from_raw_parts`]: Vec::from_raw_parts
375 /// #![feature(vec_into_raw_parts)]
376 /// let v: Vec<i32> = vec![-1, 0, 1];
378 /// let (ptr, len, cap) = v.into_raw_parts();
380 /// let rebuilt = unsafe {
381 /// // We can now make changes to the components, such as
382 /// // transmuting the raw pointer to a compatible type.
383 /// let ptr = ptr as *mut u32;
385 /// Vec::from_raw_parts(ptr, len, cap)
387 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
389 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
390 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
391 let mut me = ManuallyDrop::new(self);
392 (me.as_mut_ptr(), me.len(), me.capacity())
395 /// Creates a `Vec<T>` directly from the raw components of another vector.
399 /// This is highly unsafe, due to the number of invariants that aren't
402 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
403 /// (at least, it's highly likely to be incorrect if it wasn't).
404 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
405 /// (`T` having a less strict alignment is not sufficient, the alignment really
406 /// needs to be equal to satsify the [`dealloc`] requirement that memory must be
407 /// allocated and deallocated with the same layout.)
408 /// * `length` needs to be less than or equal to `capacity`.
409 /// * `capacity` needs to be the capacity that the pointer was allocated with.
411 /// Violating these may cause problems like corrupting the allocator's
412 /// internal data structures. For example it is **not** safe
413 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
414 /// It's also not safe to build one from a `Vec<u16>` and its length, because
415 /// the allocator cares about the alignment, and these two types have different
416 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
417 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
419 /// The ownership of `ptr` is effectively transferred to the
420 /// `Vec<T>` which may then deallocate, reallocate or change the
421 /// contents of memory pointed to by the pointer at will. Ensure
422 /// that nothing else uses the pointer after calling this
425 /// [`String`]: crate::string::String
426 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
434 /// let v = vec![1, 2, 3];
436 // FIXME Update this when vec_into_raw_parts is stabilized
437 /// // Prevent running `v`'s destructor so we are in complete control
438 /// // of the allocation.
439 /// let mut v = mem::ManuallyDrop::new(v);
441 /// // Pull out the various important pieces of information about `v`
442 /// let p = v.as_mut_ptr();
443 /// let len = v.len();
444 /// let cap = v.capacity();
447 /// // Overwrite memory with 4, 5, 6
448 /// for i in 0..len as isize {
449 /// ptr::write(p.offset(i), 4 + i);
452 /// // Put everything back together into a Vec
453 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
454 /// assert_eq!(rebuilt, [4, 5, 6]);
457 #[stable(feature = "rust1", since = "1.0.0")]
458 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
459 unsafe { Vec { buf: RawVec::from_raw_parts(ptr, capacity), len: length } }
462 /// Returns the number of elements the vector can hold without
468 /// let vec: Vec<i32> = Vec::with_capacity(10);
469 /// assert_eq!(vec.capacity(), 10);
472 #[stable(feature = "rust1", since = "1.0.0")]
473 pub fn capacity(&self) -> usize {
477 /// Reserves capacity for at least `additional` more elements to be inserted
478 /// in the given `Vec<T>`. The collection may reserve more space to avoid
479 /// frequent reallocations. After calling `reserve`, capacity will be
480 /// greater than or equal to `self.len() + additional`. Does nothing if
481 /// capacity is already sufficient.
485 /// Panics if the new capacity exceeds `isize::MAX` bytes.
490 /// let mut vec = vec![1];
492 /// assert!(vec.capacity() >= 11);
494 #[stable(feature = "rust1", since = "1.0.0")]
495 pub fn reserve(&mut self, additional: usize) {
496 self.buf.reserve(self.len, additional);
499 /// Reserves the minimum capacity for exactly `additional` more elements to
500 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
501 /// capacity will be greater than or equal to `self.len() + additional`.
502 /// Does nothing if the capacity is already sufficient.
504 /// Note that the allocator may give the collection more space than it
505 /// requests. Therefore, capacity can not be relied upon to be precisely
506 /// minimal. Prefer `reserve` if future insertions are expected.
510 /// Panics if the new capacity overflows `usize`.
515 /// let mut vec = vec![1];
516 /// vec.reserve_exact(10);
517 /// assert!(vec.capacity() >= 11);
519 #[stable(feature = "rust1", since = "1.0.0")]
520 pub fn reserve_exact(&mut self, additional: usize) {
521 self.buf.reserve_exact(self.len, additional);
524 /// Tries to reserve capacity for at least `additional` more elements to be inserted
525 /// in the given `Vec<T>`. The collection may reserve more space to avoid
526 /// frequent reallocations. After calling `try_reserve`, capacity will be
527 /// greater than or equal to `self.len() + additional`. Does nothing if
528 /// capacity is already sufficient.
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(&mut self, additional: usize) -> Result<(), TryReserveError> {
558 self.buf.try_reserve(self.len, additional)
561 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
562 /// be inserted in the given `Vec<T>`. After calling `try_reserve_exact`,
563 /// capacity will be greater than or equal to `self.len() + additional`.
564 /// Does nothing if the capacity is already sufficient.
566 /// Note that the allocator may give the collection more space than it
567 /// requests. Therefore, capacity can not be relied upon to be precisely
568 /// minimal. Prefer `reserve` if future insertions are expected.
572 /// If the capacity overflows, or the allocator reports a failure, then an error
578 /// #![feature(try_reserve)]
579 /// use std::collections::TryReserveError;
581 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
582 /// let mut output = Vec::new();
584 /// // Pre-reserve the memory, exiting if we can't
585 /// output.try_reserve_exact(data.len())?;
587 /// // Now we know this can't OOM in the middle of our complex work
588 /// output.extend(data.iter().map(|&val| {
589 /// val * 2 + 5 // very complicated
594 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
596 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
597 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
598 self.buf.try_reserve_exact(self.len, additional)
601 /// Shrinks the capacity of the vector as much as possible.
603 /// It will drop down as close as possible to the length but the allocator
604 /// may still inform the vector that there is space for a few more elements.
609 /// let mut vec = Vec::with_capacity(10);
610 /// vec.extend([1, 2, 3].iter().cloned());
611 /// assert_eq!(vec.capacity(), 10);
612 /// vec.shrink_to_fit();
613 /// assert!(vec.capacity() >= 3);
615 #[stable(feature = "rust1", since = "1.0.0")]
616 pub fn shrink_to_fit(&mut self) {
617 // The capacity is never less than the length, and there's nothing to do when
618 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
619 // by only calling it with a greater capacity.
620 if self.capacity() > self.len {
621 self.buf.shrink_to_fit(self.len);
625 /// Shrinks the capacity of the vector with a lower bound.
627 /// The capacity will remain at least as large as both the length
628 /// and the supplied value.
632 /// Panics if the current capacity is smaller than the supplied
633 /// minimum capacity.
638 /// #![feature(shrink_to)]
639 /// let mut vec = Vec::with_capacity(10);
640 /// vec.extend([1, 2, 3].iter().cloned());
641 /// assert_eq!(vec.capacity(), 10);
642 /// vec.shrink_to(4);
643 /// assert!(vec.capacity() >= 4);
644 /// vec.shrink_to(0);
645 /// assert!(vec.capacity() >= 3);
647 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
648 pub fn shrink_to(&mut self, min_capacity: usize) {
649 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
652 /// Converts the vector into [`Box<[T]>`][owned slice].
654 /// Note that this will drop any excess capacity.
656 /// [owned slice]: Box
661 /// let v = vec![1, 2, 3];
663 /// let slice = v.into_boxed_slice();
666 /// Any excess capacity is removed:
669 /// let mut vec = Vec::with_capacity(10);
670 /// vec.extend([1, 2, 3].iter().cloned());
672 /// assert_eq!(vec.capacity(), 10);
673 /// let slice = vec.into_boxed_slice();
674 /// assert_eq!(slice.into_vec().capacity(), 3);
676 #[stable(feature = "rust1", since = "1.0.0")]
677 pub fn into_boxed_slice(mut self) -> Box<[T]> {
679 self.shrink_to_fit();
680 let me = ManuallyDrop::new(self);
681 let buf = ptr::read(&me.buf);
683 buf.into_box(len).assume_init()
687 /// Shortens the vector, keeping the first `len` elements and dropping
690 /// If `len` is greater than the vector's current length, this has no
693 /// The [`drain`] method can emulate `truncate`, but causes the excess
694 /// elements to be returned instead of dropped.
696 /// Note that this method has no effect on the allocated capacity
701 /// Truncating a five element vector to two elements:
704 /// let mut vec = vec![1, 2, 3, 4, 5];
706 /// assert_eq!(vec, [1, 2]);
709 /// No truncation occurs when `len` is greater than the vector's current
713 /// let mut vec = vec![1, 2, 3];
715 /// assert_eq!(vec, [1, 2, 3]);
718 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
722 /// let mut vec = vec![1, 2, 3];
724 /// assert_eq!(vec, []);
727 /// [`clear`]: Vec::clear
728 /// [`drain`]: Vec::drain
729 #[stable(feature = "rust1", since = "1.0.0")]
730 pub fn truncate(&mut self, len: usize) {
731 // This is safe because:
733 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
734 // case avoids creating an invalid slice, and
735 // * the `len` of the vector is shrunk before calling `drop_in_place`,
736 // such that no value will be dropped twice in case `drop_in_place`
737 // were to panic once (if it panics twice, the program aborts).
742 let remaining_len = self.len - len;
743 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
745 ptr::drop_in_place(s);
749 /// Extracts a slice containing the entire vector.
751 /// Equivalent to `&s[..]`.
756 /// use std::io::{self, Write};
757 /// let buffer = vec![1, 2, 3, 5, 8];
758 /// io::sink().write(buffer.as_slice()).unwrap();
761 #[stable(feature = "vec_as_slice", since = "1.7.0")]
762 pub fn as_slice(&self) -> &[T] {
766 /// Extracts a mutable slice of the entire vector.
768 /// Equivalent to `&mut s[..]`.
773 /// use std::io::{self, Read};
774 /// let mut buffer = vec![0; 3];
775 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
778 #[stable(feature = "vec_as_slice", since = "1.7.0")]
779 pub fn as_mut_slice(&mut self) -> &mut [T] {
783 /// Returns a raw pointer to the vector's buffer.
785 /// The caller must ensure that the vector outlives the pointer this
786 /// function returns, or else it will end up pointing to garbage.
787 /// Modifying the vector may cause its buffer to be reallocated,
788 /// which would also make any pointers to it invalid.
790 /// The caller must also ensure that the memory the pointer (non-transitively) points to
791 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
792 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
797 /// let x = vec![1, 2, 4];
798 /// let x_ptr = x.as_ptr();
801 /// for i in 0..x.len() {
802 /// assert_eq!(*x_ptr.add(i), 1 << i);
807 /// [`as_mut_ptr`]: Vec::as_mut_ptr
808 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
810 pub fn as_ptr(&self) -> *const T {
811 // We shadow the slice method of the same name to avoid going through
812 // `deref`, which creates an intermediate reference.
813 let ptr = self.buf.ptr();
815 assume(!ptr.is_null());
820 /// Returns an unsafe mutable pointer to the vector's buffer.
822 /// The caller must ensure that the vector outlives the pointer this
823 /// function returns, or else it will end up pointing to garbage.
824 /// Modifying the vector may cause its buffer to be reallocated,
825 /// which would also make any pointers to it invalid.
830 /// // Allocate vector big enough for 4 elements.
832 /// let mut x: Vec<i32> = Vec::with_capacity(size);
833 /// let x_ptr = x.as_mut_ptr();
835 /// // Initialize elements via raw pointer writes, then set length.
837 /// for i in 0..size {
838 /// *x_ptr.add(i) = i as i32;
842 /// assert_eq!(&*x, &[0,1,2,3]);
844 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
846 pub fn as_mut_ptr(&mut self) -> *mut T {
847 // We shadow the slice method of the same name to avoid going through
848 // `deref_mut`, which creates an intermediate reference.
849 let ptr = self.buf.ptr();
851 assume(!ptr.is_null());
856 /// Forces the length of the vector to `new_len`.
858 /// This is a low-level operation that maintains none of the normal
859 /// invariants of the type. Normally changing the length of a vector
860 /// is done using one of the safe operations instead, such as
861 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
863 /// [`truncate`]: Vec::truncate
864 /// [`resize`]: Vec::resize
865 /// [`extend`]: Extend::extend
866 /// [`clear`]: Vec::clear
870 /// - `new_len` must be less than or equal to [`capacity()`].
871 /// - The elements at `old_len..new_len` must be initialized.
873 /// [`capacity()`]: Vec::capacity
877 /// This method can be useful for situations in which the vector
878 /// is serving as a buffer for other code, particularly over FFI:
881 /// # #![allow(dead_code)]
882 /// # // This is just a minimal skeleton for the doc example;
883 /// # // don't use this as a starting point for a real library.
884 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
885 /// # const Z_OK: i32 = 0;
887 /// # fn deflateGetDictionary(
888 /// # strm: *mut std::ffi::c_void,
889 /// # dictionary: *mut u8,
890 /// # dictLength: *mut usize,
893 /// # impl StreamWrapper {
894 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
895 /// // Per the FFI method's docs, "32768 bytes is always enough".
896 /// let mut dict = Vec::with_capacity(32_768);
897 /// let mut dict_length = 0;
898 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
899 /// // 1. `dict_length` elements were initialized.
900 /// // 2. `dict_length` <= the capacity (32_768)
901 /// // which makes `set_len` safe to call.
903 /// // Make the FFI call...
904 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
906 /// // ...and update the length to what was initialized.
907 /// dict.set_len(dict_length);
917 /// While the following example is sound, there is a memory leak since
918 /// the inner vectors were not freed prior to the `set_len` call:
921 /// let mut vec = vec![vec![1, 0, 0],
925 /// // 1. `old_len..0` is empty so no elements need to be initialized.
926 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
932 /// Normally, here, one would use [`clear`] instead to correctly drop
933 /// the contents and thus not leak memory.
935 #[stable(feature = "rust1", since = "1.0.0")]
936 pub unsafe fn set_len(&mut self, new_len: usize) {
937 debug_assert!(new_len <= self.capacity());
942 /// Removes an element from the vector and returns it.
944 /// The removed element is replaced by the last element of the vector.
946 /// This does not preserve ordering, but is O(1).
950 /// Panics if `index` is out of bounds.
955 /// let mut v = vec!["foo", "bar", "baz", "qux"];
957 /// assert_eq!(v.swap_remove(1), "bar");
958 /// assert_eq!(v, ["foo", "qux", "baz"]);
960 /// assert_eq!(v.swap_remove(0), "foo");
961 /// assert_eq!(v, ["baz", "qux"]);
964 #[stable(feature = "rust1", since = "1.0.0")]
965 pub fn swap_remove(&mut self, index: usize) -> T {
968 fn assert_failed(index: usize, len: usize) -> ! {
969 panic!("swap_remove index (is {}) should be < len (is {})", index, len);
972 let len = self.len();
974 assert_failed(index, len);
977 // We replace self[index] with the last element. Note that if the
978 // bounds check above succeeds there must be a last element (which
979 // can be self[index] itself).
980 let last = ptr::read(self.as_ptr().add(len - 1));
981 let hole = self.as_mut_ptr().add(index);
982 self.set_len(len - 1);
983 ptr::replace(hole, last)
987 /// Inserts an element at position `index` within the vector, shifting all
988 /// elements after it to the right.
992 /// Panics if `index > len`.
997 /// let mut vec = vec![1, 2, 3];
998 /// vec.insert(1, 4);
999 /// assert_eq!(vec, [1, 4, 2, 3]);
1000 /// vec.insert(4, 5);
1001 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1003 #[stable(feature = "rust1", since = "1.0.0")]
1004 pub fn insert(&mut self, index: usize, element: T) {
1007 fn assert_failed(index: usize, len: usize) -> ! {
1008 panic!("insertion index (is {}) should be <= len (is {})", index, len);
1011 let len = self.len();
1013 assert_failed(index, len);
1016 // space for the new element
1017 if len == self.buf.capacity() {
1023 // The spot to put the new value
1025 let p = self.as_mut_ptr().add(index);
1026 // Shift everything over to make space. (Duplicating the
1027 // `index`th element into two consecutive places.)
1028 ptr::copy(p, p.offset(1), len - index);
1029 // Write it in, overwriting the first copy of the `index`th
1031 ptr::write(p, element);
1033 self.set_len(len + 1);
1037 /// Removes and returns the element at position `index` within the vector,
1038 /// shifting all elements after it to the left.
1042 /// Panics if `index` is out of bounds.
1047 /// let mut v = vec![1, 2, 3];
1048 /// assert_eq!(v.remove(1), 2);
1049 /// assert_eq!(v, [1, 3]);
1051 #[stable(feature = "rust1", since = "1.0.0")]
1052 pub fn remove(&mut self, index: usize) -> T {
1055 fn assert_failed(index: usize, len: usize) -> ! {
1056 panic!("removal index (is {}) should be < len (is {})", index, len);
1059 let len = self.len();
1061 assert_failed(index, len);
1067 // the place we are taking from.
1068 let ptr = self.as_mut_ptr().add(index);
1069 // copy it out, unsafely having a copy of the value on
1070 // the stack and in the vector at the same time.
1071 ret = ptr::read(ptr);
1073 // Shift everything down to fill in that spot.
1074 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1076 self.set_len(len - 1);
1081 /// Retains only the elements specified by the predicate.
1083 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1084 /// This method operates in place, visiting each element exactly once in the
1085 /// original order, and preserves the order of the retained elements.
1090 /// let mut vec = vec![1, 2, 3, 4];
1091 /// vec.retain(|&x| x % 2 == 0);
1092 /// assert_eq!(vec, [2, 4]);
1095 /// The exact order may be useful for tracking external state, like an index.
1098 /// let mut vec = vec![1, 2, 3, 4, 5];
1099 /// let keep = [false, true, true, false, true];
1101 /// vec.retain(|_| (keep[i], i += 1).0);
1102 /// assert_eq!(vec, [2, 3, 5]);
1104 #[stable(feature = "rust1", since = "1.0.0")]
1105 pub fn retain<F>(&mut self, mut f: F)
1107 F: FnMut(&T) -> bool,
1109 let len = self.len();
1112 let v = &mut **self;
1123 self.truncate(len - del);
1127 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1130 /// If the vector is sorted, this removes all duplicates.
1135 /// let mut vec = vec![10, 20, 21, 30, 20];
1137 /// vec.dedup_by_key(|i| *i / 10);
1139 /// assert_eq!(vec, [10, 20, 30, 20]);
1141 #[stable(feature = "dedup_by", since = "1.16.0")]
1143 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1145 F: FnMut(&mut T) -> K,
1148 self.dedup_by(|a, b| key(a) == key(b))
1151 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1154 /// The `same_bucket` function is passed references to two elements from the vector and
1155 /// must determine if the elements compare equal. The elements are passed in opposite order
1156 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1158 /// If the vector is sorted, this removes all duplicates.
1163 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1165 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1167 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1169 #[stable(feature = "dedup_by", since = "1.16.0")]
1170 pub fn dedup_by<F>(&mut self, same_bucket: F)
1172 F: FnMut(&mut T, &mut T) -> bool,
1175 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1181 /// Appends an element to the back of a collection.
1185 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1190 /// let mut vec = vec![1, 2];
1192 /// assert_eq!(vec, [1, 2, 3]);
1195 #[stable(feature = "rust1", since = "1.0.0")]
1196 pub fn push(&mut self, value: T) {
1197 // This will panic or abort if we would allocate > isize::MAX bytes
1198 // or if the length increment would overflow for zero-sized types.
1199 if self.len == self.buf.capacity() {
1203 let end = self.as_mut_ptr().add(self.len);
1204 ptr::write(end, value);
1209 /// Removes the last element from a vector and returns it, or [`None`] if it
1215 /// let mut vec = vec![1, 2, 3];
1216 /// assert_eq!(vec.pop(), Some(3));
1217 /// assert_eq!(vec, [1, 2]);
1220 #[stable(feature = "rust1", since = "1.0.0")]
1221 pub fn pop(&mut self) -> Option<T> {
1227 Some(ptr::read(self.as_ptr().add(self.len())))
1232 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1236 /// Panics if the number of elements in the vector overflows a `usize`.
1241 /// let mut vec = vec![1, 2, 3];
1242 /// let mut vec2 = vec![4, 5, 6];
1243 /// vec.append(&mut vec2);
1244 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1245 /// assert_eq!(vec2, []);
1248 #[stable(feature = "append", since = "1.4.0")]
1249 pub fn append(&mut self, other: &mut Self) {
1251 self.append_elements(other.as_slice() as _);
1256 /// Appends elements to `Self` from other buffer.
1258 unsafe fn append_elements(&mut self, other: *const [T]) {
1259 let count = unsafe { (*other).len() };
1260 self.reserve(count);
1261 let len = self.len();
1262 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1266 /// Creates a draining iterator that removes the specified range in the vector
1267 /// and yields the removed items.
1269 /// When the iterator **is** dropped, all elements in the range are removed
1270 /// from the vector, even if the iterator was not fully consumed. If the
1271 /// iterator **is not** dropped (with [`mem::forget`] for example), it is
1272 /// unspecified how many elements are removed.
1276 /// Panics if the starting point is greater than the end point or if
1277 /// the end point is greater than the length of the vector.
1282 /// let mut v = vec![1, 2, 3];
1283 /// let u: Vec<_> = v.drain(1..).collect();
1284 /// assert_eq!(v, &[1]);
1285 /// assert_eq!(u, &[2, 3]);
1287 /// // A full range clears the vector
1289 /// assert_eq!(v, &[]);
1291 #[stable(feature = "drain", since = "1.6.0")]
1292 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1294 R: RangeBounds<usize>,
1298 // When the Drain is first created, it shortens the length of
1299 // the source vector to make sure no uninitialized or moved-from elements
1300 // are accessible at all if the Drain's destructor never gets to run.
1302 // Drain will ptr::read out the values to remove.
1303 // When finished, remaining tail of the vec is copied back to cover
1304 // the hole, and the vector length is restored to the new length.
1306 let len = self.len();
1307 let start = match range.start_bound() {
1309 Excluded(&n) => n + 1,
1312 let end = match range.end_bound() {
1313 Included(&n) => n + 1,
1320 fn start_assert_failed(start: usize, end: usize) -> ! {
1321 panic!("start drain index (is {}) should be <= end drain index (is {})", start, end);
1326 fn end_assert_failed(end: usize, len: usize) -> ! {
1327 panic!("end drain index (is {}) should be <= len (is {})", end, len);
1331 start_assert_failed(start, end);
1334 end_assert_failed(end, len);
1338 // set self.vec length's to start, to be safe in case Drain is leaked
1339 self.set_len(start);
1340 // Use the borrow in the IterMut to indicate borrowing behavior of the
1341 // whole Drain iterator (like &mut T).
1342 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1345 tail_len: len - end,
1346 iter: range_slice.iter(),
1347 vec: NonNull::from(self),
1352 /// Clears the vector, removing all values.
1354 /// Note that this method has no effect on the allocated capacity
1360 /// let mut v = vec![1, 2, 3];
1364 /// assert!(v.is_empty());
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 pub fn clear(&mut self) {
1372 /// Returns the number of elements in the vector, also referred to
1373 /// as its 'length'.
1378 /// let a = vec![1, 2, 3];
1379 /// assert_eq!(a.len(), 3);
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 pub fn len(&self) -> usize {
1387 /// Returns `true` if the vector contains no elements.
1392 /// let mut v = Vec::new();
1393 /// assert!(v.is_empty());
1396 /// assert!(!v.is_empty());
1398 #[stable(feature = "rust1", since = "1.0.0")]
1399 pub fn is_empty(&self) -> bool {
1403 /// Splits the collection into two at the given index.
1405 /// Returns a newly allocated vector containing the elements in the range
1406 /// `[at, len)`. After the call, the original vector will be left containing
1407 /// the elements `[0, at)` with its previous capacity unchanged.
1411 /// Panics if `at > len`.
1416 /// let mut vec = vec![1,2,3];
1417 /// let vec2 = vec.split_off(1);
1418 /// assert_eq!(vec, [1]);
1419 /// assert_eq!(vec2, [2, 3]);
1422 #[must_use = "use `.truncate()` if you don't need the other half"]
1423 #[stable(feature = "split_off", since = "1.4.0")]
1424 pub fn split_off(&mut self, at: usize) -> Self {
1427 fn assert_failed(at: usize, len: usize) -> ! {
1428 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1431 if at > self.len() {
1432 assert_failed(at, self.len());
1435 let other_len = self.len - at;
1436 let mut other = Vec::with_capacity(other_len);
1438 // Unsafely `set_len` and copy items to `other`.
1441 other.set_len(other_len);
1443 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1448 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1450 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1451 /// difference, with each additional slot filled with the result of
1452 /// calling the closure `f`. The return values from `f` will end up
1453 /// in the `Vec` in the order they have been generated.
1455 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1457 /// This method uses a closure to create new values on every push. If
1458 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
1459 /// want to use the [`Default`] trait to generate values, you can
1460 /// pass [`Default::default`] as the second argument.
1465 /// let mut vec = vec![1, 2, 3];
1466 /// vec.resize_with(5, Default::default);
1467 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1469 /// let mut vec = vec![];
1471 /// vec.resize_with(4, || { p *= 2; p });
1472 /// assert_eq!(vec, [2, 4, 8, 16]);
1474 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1475 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1479 let len = self.len();
1481 self.extend_with(new_len - len, ExtendFunc(f));
1483 self.truncate(new_len);
1487 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1488 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1489 /// `'a`. If the type has only static references, or none at all, then this
1490 /// may be chosen to be `'static`.
1492 /// This function is similar to the `leak` function on `Box`.
1494 /// This function is mainly useful for data that lives for the remainder of
1495 /// the program's life. Dropping the returned reference will cause a memory
1503 /// let x = vec![1, 2, 3];
1504 /// let static_ref: &'static mut [usize] = x.leak();
1505 /// static_ref[0] += 1;
1506 /// assert_eq!(static_ref, &[2, 2, 3]);
1508 #[stable(feature = "vec_leak", since = "1.47.0")]
1510 pub fn leak<'a>(self) -> &'a mut [T]
1512 T: 'a, // Technically not needed, but kept to be explicit.
1514 Box::leak(self.into_boxed_slice())
1517 /// Returns the remaining spare capacity of the vector as a slice of
1518 /// `MaybeUninit<T>`.
1520 /// The returned slice can be used to fill the vector with data (e.g. by
1521 /// reading from a file) before marking the data as initialized using the
1522 /// [`set_len`] method.
1524 /// [`set_len`]: Vec::set_len
1529 /// #![feature(vec_spare_capacity, maybe_uninit_extra)]
1531 /// // Allocate vector big enough for 10 elements.
1532 /// let mut v = Vec::with_capacity(10);
1534 /// // Fill in the first 3 elements.
1535 /// let uninit = v.spare_capacity_mut();
1536 /// uninit[0].write(0);
1537 /// uninit[1].write(1);
1538 /// uninit[2].write(2);
1540 /// // Mark the first 3 elements of the vector as being initialized.
1545 /// assert_eq!(&v, &[0, 1, 2]);
1547 #[unstable(feature = "vec_spare_capacity", issue = "75017")]
1549 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1551 slice::from_raw_parts_mut(
1552 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
1553 self.buf.capacity() - self.len,
1559 impl<T: Clone> Vec<T> {
1560 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1562 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1563 /// difference, with each additional slot filled with `value`.
1564 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1566 /// This method requires `T` to implement [`Clone`],
1567 /// in order to be able to clone the passed value.
1568 /// If you need more flexibility (or want to rely on [`Default`] instead of
1569 /// [`Clone`]), use [`Vec::resize_with`].
1574 /// let mut vec = vec!["hello"];
1575 /// vec.resize(3, "world");
1576 /// assert_eq!(vec, ["hello", "world", "world"]);
1578 /// let mut vec = vec![1, 2, 3, 4];
1579 /// vec.resize(2, 0);
1580 /// assert_eq!(vec, [1, 2]);
1582 #[stable(feature = "vec_resize", since = "1.5.0")]
1583 pub fn resize(&mut self, new_len: usize, value: T) {
1584 let len = self.len();
1587 self.extend_with(new_len - len, ExtendElement(value))
1589 self.truncate(new_len);
1593 /// Clones and appends all elements in a slice to the `Vec`.
1595 /// Iterates over the slice `other`, clones each element, and then appends
1596 /// it to this `Vec`. The `other` vector is traversed in-order.
1598 /// Note that this function is same as [`extend`] except that it is
1599 /// specialized to work with slices instead. If and when Rust gets
1600 /// specialization this function will likely be deprecated (but still
1606 /// let mut vec = vec![1];
1607 /// vec.extend_from_slice(&[2, 3, 4]);
1608 /// assert_eq!(vec, [1, 2, 3, 4]);
1611 /// [`extend`]: Vec::extend
1612 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1613 pub fn extend_from_slice(&mut self, other: &[T]) {
1614 self.spec_extend(other.iter())
1618 impl<T: Default> Vec<T> {
1619 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1621 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1622 /// difference, with each additional slot filled with [`Default::default()`].
1623 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1625 /// This method uses [`Default`] to create new values on every push. If
1626 /// you'd rather [`Clone`] a given value, use [`resize`].
1631 /// # #![allow(deprecated)]
1632 /// #![feature(vec_resize_default)]
1634 /// let mut vec = vec![1, 2, 3];
1635 /// vec.resize_default(5);
1636 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1638 /// let mut vec = vec![1, 2, 3, 4];
1639 /// vec.resize_default(2);
1640 /// assert_eq!(vec, [1, 2]);
1643 /// [`resize`]: Vec::resize
1644 #[unstable(feature = "vec_resize_default", issue = "41758")]
1646 reason = "This is moving towards being removed in favor \
1647 of `.resize_with(Default::default)`. If you disagree, please comment \
1648 in the tracking issue.",
1651 pub fn resize_default(&mut self, new_len: usize) {
1652 let len = self.len();
1655 self.extend_with(new_len - len, ExtendDefault);
1657 self.truncate(new_len);
1662 // This code generalizes `extend_with_{element,default}`.
1663 trait ExtendWith<T> {
1664 fn next(&mut self) -> T;
1668 struct ExtendElement<T>(T);
1669 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1670 fn next(&mut self) -> T {
1673 fn last(self) -> T {
1678 struct ExtendDefault;
1679 impl<T: Default> ExtendWith<T> for ExtendDefault {
1680 fn next(&mut self) -> T {
1683 fn last(self) -> T {
1688 struct ExtendFunc<F>(F);
1689 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1690 fn next(&mut self) -> T {
1693 fn last(mut self) -> T {
1699 /// Extend the vector by `n` values, using the given generator.
1700 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1704 let mut ptr = self.as_mut_ptr().add(self.len());
1705 // Use SetLenOnDrop to work around bug where compiler
1706 // may not realize the store through `ptr` through self.set_len()
1708 let mut local_len = SetLenOnDrop::new(&mut self.len);
1710 // Write all elements except the last one
1712 ptr::write(ptr, value.next());
1713 ptr = ptr.offset(1);
1714 // Increment the length in every step in case next() panics
1715 local_len.increment_len(1);
1719 // We can write the last element directly without cloning needlessly
1720 ptr::write(ptr, value.last());
1721 local_len.increment_len(1);
1724 // len set by scope guard
1729 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1731 // The idea is: The length field in SetLenOnDrop is a local variable
1732 // that the optimizer will see does not alias with any stores through the Vec's data
1733 // pointer. This is a workaround for alias analysis issue #32155
1734 struct SetLenOnDrop<'a> {
1739 impl<'a> SetLenOnDrop<'a> {
1741 fn new(len: &'a mut usize) -> Self {
1742 SetLenOnDrop { local_len: *len, len }
1746 fn increment_len(&mut self, increment: usize) {
1747 self.local_len += increment;
1751 impl Drop for SetLenOnDrop<'_> {
1753 fn drop(&mut self) {
1754 *self.len = self.local_len;
1758 impl<T: PartialEq> Vec<T> {
1759 /// Removes consecutive repeated elements in the vector according to the
1760 /// [`PartialEq`] trait implementation.
1762 /// If the vector is sorted, this removes all duplicates.
1767 /// let mut vec = vec![1, 2, 2, 3, 2];
1771 /// assert_eq!(vec, [1, 2, 3, 2]);
1773 #[stable(feature = "rust1", since = "1.0.0")]
1775 pub fn dedup(&mut self) {
1776 self.dedup_by(|a, b| a == b)
1781 /// Removes the first instance of `item` from the vector if the item exists.
1783 /// This method will be removed soon.
1784 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1786 reason = "Removing the first item equal to a needle is already easily possible \
1787 with iterators and the current Vec methods. Furthermore, having a method for \
1788 one particular case of removal (linear search, only the first item, no swap remove) \
1789 but not for others is inconsistent. This method will be removed soon.",
1792 pub fn remove_item<V>(&mut self, item: &V) -> Option<T>
1796 let pos = self.iter().position(|x| *x == *item)?;
1797 Some(self.remove(pos))
1801 ////////////////////////////////////////////////////////////////////////////////
1802 // Internal methods and functions
1803 ////////////////////////////////////////////////////////////////////////////////
1806 #[stable(feature = "rust1", since = "1.0.0")]
1807 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1808 <T as SpecFromElem>::from_elem(elem, n)
1811 // Specialization trait used for Vec::from_elem
1812 trait SpecFromElem: Sized {
1813 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1816 impl<T: Clone> SpecFromElem for T {
1817 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1818 let mut v = Vec::with_capacity(n);
1819 v.extend_with(n, ExtendElement(elem));
1824 impl SpecFromElem for i8 {
1826 fn from_elem(elem: i8, n: usize) -> Vec<i8> {
1828 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1831 let mut v = Vec::with_capacity(n);
1832 ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
1839 impl SpecFromElem for u8 {
1841 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1843 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1846 let mut v = Vec::with_capacity(n);
1847 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1854 impl<T: Clone + IsZero> SpecFromElem for T {
1856 fn from_elem(elem: T, n: usize) -> Vec<T> {
1858 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1860 let mut v = Vec::with_capacity(n);
1861 v.extend_with(n, ExtendElement(elem));
1866 #[rustc_specialization_trait]
1867 unsafe trait IsZero {
1868 /// Whether this value is zero
1869 fn is_zero(&self) -> bool;
1872 macro_rules! impl_is_zero {
1873 ($t:ty, $is_zero:expr) => {
1874 unsafe impl IsZero for $t {
1876 fn is_zero(&self) -> bool {
1883 impl_is_zero!(i16, |x| x == 0);
1884 impl_is_zero!(i32, |x| x == 0);
1885 impl_is_zero!(i64, |x| x == 0);
1886 impl_is_zero!(i128, |x| x == 0);
1887 impl_is_zero!(isize, |x| x == 0);
1889 impl_is_zero!(u16, |x| x == 0);
1890 impl_is_zero!(u32, |x| x == 0);
1891 impl_is_zero!(u64, |x| x == 0);
1892 impl_is_zero!(u128, |x| x == 0);
1893 impl_is_zero!(usize, |x| x == 0);
1895 impl_is_zero!(bool, |x| x == false);
1896 impl_is_zero!(char, |x| x == '\0');
1898 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1899 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1901 unsafe impl<T> IsZero for *const T {
1903 fn is_zero(&self) -> bool {
1908 unsafe impl<T> IsZero for *mut T {
1910 fn is_zero(&self) -> bool {
1915 // `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
1916 // For fat pointers, the bytes that would be the pointer metadata in the `Some`
1917 // variant are padding in the `None` variant, so ignoring them and
1918 // zero-initializing instead is ok.
1919 // `Option<&mut T>` never implements `Clone`, so there's no need for an impl of
1922 unsafe impl<T: ?Sized> IsZero for Option<&T> {
1924 fn is_zero(&self) -> bool {
1929 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
1931 fn is_zero(&self) -> bool {
1936 ////////////////////////////////////////////////////////////////////////////////
1937 // Common trait implementations for Vec
1938 ////////////////////////////////////////////////////////////////////////////////
1940 #[stable(feature = "rust1", since = "1.0.0")]
1941 impl<T> ops::Deref for Vec<T> {
1944 fn deref(&self) -> &[T] {
1945 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
1949 #[stable(feature = "rust1", since = "1.0.0")]
1950 impl<T> ops::DerefMut for Vec<T> {
1951 fn deref_mut(&mut self) -> &mut [T] {
1952 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1956 #[stable(feature = "rust1", since = "1.0.0")]
1957 impl<T: Clone> Clone for Vec<T> {
1959 fn clone(&self) -> Vec<T> {
1960 <[T]>::to_vec(&**self)
1963 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1964 // required for this method definition, is not available. Instead use the
1965 // `slice::to_vec` function which is only available with cfg(test)
1966 // NB see the slice::hack module in slice.rs for more information
1968 fn clone(&self) -> Vec<T> {
1969 crate::slice::to_vec(&**self)
1972 fn clone_from(&mut self, other: &Vec<T>) {
1973 other.as_slice().clone_into(self);
1977 #[stable(feature = "rust1", since = "1.0.0")]
1978 impl<T: Hash> Hash for Vec<T> {
1980 fn hash<H: Hasher>(&self, state: &mut H) {
1981 Hash::hash(&**self, state)
1985 #[stable(feature = "rust1", since = "1.0.0")]
1986 #[rustc_on_unimplemented(
1987 message = "vector indices are of type `usize` or ranges of `usize`",
1988 label = "vector indices are of type `usize` or ranges of `usize`"
1990 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
1991 type Output = I::Output;
1994 fn index(&self, index: I) -> &Self::Output {
1995 Index::index(&**self, index)
1999 #[stable(feature = "rust1", since = "1.0.0")]
2000 #[rustc_on_unimplemented(
2001 message = "vector indices are of type `usize` or ranges of `usize`",
2002 label = "vector indices are of type `usize` or ranges of `usize`"
2004 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
2006 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2007 IndexMut::index_mut(&mut **self, index)
2011 #[stable(feature = "rust1", since = "1.0.0")]
2012 impl<T> FromIterator<T> for Vec<T> {
2014 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2015 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
2019 #[stable(feature = "rust1", since = "1.0.0")]
2020 impl<T> IntoIterator for Vec<T> {
2022 type IntoIter = IntoIter<T>;
2024 /// Creates a consuming iterator, that is, one that moves each value out of
2025 /// the vector (from start to end). The vector cannot be used after calling
2031 /// let v = vec!["a".to_string(), "b".to_string()];
2032 /// for s in v.into_iter() {
2033 /// // s has type String, not &String
2034 /// println!("{}", s);
2038 fn into_iter(self) -> IntoIter<T> {
2040 let mut me = ManuallyDrop::new(self);
2041 let begin = me.as_mut_ptr();
2042 let end = if mem::size_of::<T>() == 0 {
2043 arith_offset(begin as *const i8, me.len() as isize) as *const T
2045 begin.add(me.len()) as *const T
2047 let cap = me.buf.capacity();
2049 buf: NonNull::new_unchecked(begin),
2050 phantom: PhantomData,
2059 #[stable(feature = "rust1", since = "1.0.0")]
2060 impl<'a, T> IntoIterator for &'a Vec<T> {
2062 type IntoIter = slice::Iter<'a, T>;
2064 fn into_iter(self) -> slice::Iter<'a, T> {
2069 #[stable(feature = "rust1", since = "1.0.0")]
2070 impl<'a, T> IntoIterator for &'a mut Vec<T> {
2071 type Item = &'a mut T;
2072 type IntoIter = slice::IterMut<'a, T>;
2074 fn into_iter(self) -> slice::IterMut<'a, T> {
2079 #[stable(feature = "rust1", since = "1.0.0")]
2080 impl<T> Extend<T> for Vec<T> {
2082 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2083 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2087 fn extend_one(&mut self, item: T) {
2092 fn extend_reserve(&mut self, additional: usize) {
2093 self.reserve(additional);
2097 // Specialization trait used for Vec::from_iter and Vec::extend
2098 trait SpecExtend<T, I> {
2099 fn from_iter(iter: I) -> Self;
2100 fn spec_extend(&mut self, iter: I);
2103 impl<T, I> SpecExtend<T, I> for Vec<T>
2105 I: Iterator<Item = T>,
2107 default fn from_iter(mut iterator: I) -> Self {
2108 // Unroll the first iteration, as the vector is going to be
2109 // expanded on this iteration in every case when the iterable is not
2110 // empty, but the loop in extend_desugared() is not going to see the
2111 // vector being full in the few subsequent loop iterations.
2112 // So we get better branch prediction.
2113 let mut vector = match iterator.next() {
2114 None => return Vec::new(),
2116 let (lower, _) = iterator.size_hint();
2117 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2119 ptr::write(vector.as_mut_ptr(), element);
2125 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2129 default fn spec_extend(&mut self, iter: I) {
2130 self.extend_desugared(iter)
2134 impl<T, I> SpecExtend<T, I> for Vec<T>
2136 I: TrustedLen<Item = T>,
2138 default fn from_iter(iterator: I) -> Self {
2139 let mut vector = Vec::new();
2140 vector.spec_extend(iterator);
2144 default fn spec_extend(&mut self, iterator: I) {
2145 // This is the case for a TrustedLen iterator.
2146 let (low, high) = iterator.size_hint();
2147 if let Some(high_value) = high {
2151 "TrustedLen iterator's size hint is not exact: {:?}",
2155 if let Some(additional) = high {
2156 self.reserve(additional);
2158 let mut ptr = self.as_mut_ptr().add(self.len());
2159 let mut local_len = SetLenOnDrop::new(&mut self.len);
2160 iterator.for_each(move |element| {
2161 ptr::write(ptr, element);
2162 ptr = ptr.offset(1);
2163 // NB can't overflow since we would have had to alloc the address space
2164 local_len.increment_len(1);
2168 self.extend_desugared(iterator)
2173 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2174 fn from_iter(iterator: IntoIter<T>) -> Self {
2175 // A common case is passing a vector into a function which immediately
2176 // re-collects into a vector. We can short circuit this if the IntoIter
2177 // has not been advanced at all.
2178 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
2180 let it = ManuallyDrop::new(iterator);
2181 Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap)
2184 let mut vector = Vec::new();
2185 vector.spec_extend(iterator);
2190 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2192 self.append_elements(iterator.as_slice() as _);
2194 iterator.ptr = iterator.end;
2198 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2200 I: Iterator<Item = &'a T>,
2203 default fn from_iter(iterator: I) -> Self {
2204 SpecExtend::from_iter(iterator.cloned())
2207 default fn spec_extend(&mut self, iterator: I) {
2208 self.spec_extend(iterator.cloned())
2212 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2216 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2217 let slice = iterator.as_slice();
2218 self.reserve(slice.len());
2220 let len = self.len();
2221 let dst_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(len), slice.len());
2222 dst_slice.copy_from_slice(slice);
2223 self.set_len(len + slice.len());
2229 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2230 // This is the case for a general iterator.
2232 // This function should be the moral equivalent of:
2234 // for item in iterator {
2237 while let Some(element) = iterator.next() {
2238 let len = self.len();
2239 if len == self.capacity() {
2240 let (lower, _) = iterator.size_hint();
2241 self.reserve(lower.saturating_add(1));
2244 ptr::write(self.as_mut_ptr().add(len), element);
2245 // NB can't overflow since we would have had to alloc the address space
2246 self.set_len(len + 1);
2251 /// Creates a splicing iterator that replaces the specified range in the vector
2252 /// with the given `replace_with` iterator and yields the removed items.
2253 /// `replace_with` does not need to be the same length as `range`.
2255 /// `range` is removed even if the iterator is not consumed until the end.
2257 /// It is unspecified how many elements are removed from the vector
2258 /// if the `Splice` value is leaked.
2260 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2262 /// This is optimal if:
2264 /// * The tail (elements in the vector after `range`) is empty,
2265 /// * or `replace_with` yields fewer elements than `range`’s length
2266 /// * or the lower bound of its `size_hint()` is exact.
2268 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2272 /// Panics if the starting point is greater than the end point or if
2273 /// the end point is greater than the length of the vector.
2278 /// let mut v = vec![1, 2, 3];
2279 /// let new = [7, 8];
2280 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2281 /// assert_eq!(v, &[7, 8, 3]);
2282 /// assert_eq!(u, &[1, 2]);
2285 #[stable(feature = "vec_splice", since = "1.21.0")]
2286 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2288 R: RangeBounds<usize>,
2289 I: IntoIterator<Item = T>,
2291 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2294 /// Creates an iterator which uses a closure to determine if an element should be removed.
2296 /// If the closure returns true, then the element is removed and yielded.
2297 /// If the closure returns false, the element will remain in the vector and will not be yielded
2298 /// by the iterator.
2300 /// Using this method is equivalent to the following code:
2303 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2304 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2306 /// while i != vec.len() {
2307 /// if some_predicate(&mut vec[i]) {
2308 /// let val = vec.remove(i);
2309 /// // your code here
2315 /// # assert_eq!(vec, vec![1, 4, 5]);
2318 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2319 /// because it can backshift the elements of the array in bulk.
2321 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2322 /// regardless of whether you choose to keep or remove it.
2326 /// Splitting an array into evens and odds, reusing the original allocation:
2329 /// #![feature(drain_filter)]
2330 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2332 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2333 /// let odds = numbers;
2335 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2336 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2338 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2339 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2341 F: FnMut(&mut T) -> bool,
2343 let old_len = self.len();
2345 // Guard against us getting leaked (leak amplification)
2350 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2354 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2356 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2357 /// append the entire slice at once.
2359 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2360 #[stable(feature = "extend_ref", since = "1.2.0")]
2361 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2362 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2363 self.spec_extend(iter.into_iter())
2367 fn extend_one(&mut self, &item: &'a T) {
2372 fn extend_reserve(&mut self, additional: usize) {
2373 self.reserve(additional);
2377 macro_rules! __impl_slice_eq1 {
2378 ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => {
2380 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2386 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2388 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2393 __impl_slice_eq1! { [] Vec<A>, Vec<B>, #[stable(feature = "rust1", since = "1.0.0")] }
2394 __impl_slice_eq1! { [] Vec<A>, &[B], #[stable(feature = "rust1", since = "1.0.0")] }
2395 __impl_slice_eq1! { [] Vec<A>, &mut [B], #[stable(feature = "rust1", since = "1.0.0")] }
2396 __impl_slice_eq1! { [] &[A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2397 __impl_slice_eq1! { [] &mut [A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2398 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B> where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2399 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2400 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2401 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2402 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N], #[stable(feature = "rust1", since = "1.0.0")] }
2404 // NOTE: some less important impls are omitted to reduce code bloat
2405 // FIXME(Centril): Reconsider this?
2406 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], }
2407 //__impl_slice_eq1! { [const N: usize] [A; N], Vec<B>, }
2408 //__impl_slice_eq1! { [const N: usize] &[A; N], Vec<B>, }
2409 //__impl_slice_eq1! { [const N: usize] &mut [A; N], Vec<B>, }
2410 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], }
2411 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], }
2412 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], }
2414 /// Implements comparison of vectors, lexicographically.
2415 #[stable(feature = "rust1", since = "1.0.0")]
2416 impl<T: PartialOrd> PartialOrd for Vec<T> {
2418 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2419 PartialOrd::partial_cmp(&**self, &**other)
2423 #[stable(feature = "rust1", since = "1.0.0")]
2424 impl<T: Eq> Eq for Vec<T> {}
2426 /// Implements ordering of vectors, lexicographically.
2427 #[stable(feature = "rust1", since = "1.0.0")]
2428 impl<T: Ord> Ord for Vec<T> {
2430 fn cmp(&self, other: &Vec<T>) -> Ordering {
2431 Ord::cmp(&**self, &**other)
2435 #[stable(feature = "rust1", since = "1.0.0")]
2436 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2437 fn drop(&mut self) {
2440 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2441 // could avoid questions of validity in certain cases
2442 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2444 // RawVec handles deallocation
2448 #[stable(feature = "rust1", since = "1.0.0")]
2449 impl<T> Default for Vec<T> {
2450 /// Creates an empty `Vec<T>`.
2451 fn default() -> Vec<T> {
2456 #[stable(feature = "rust1", since = "1.0.0")]
2457 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2458 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2459 fmt::Debug::fmt(&**self, f)
2463 #[stable(feature = "rust1", since = "1.0.0")]
2464 impl<T> AsRef<Vec<T>> for Vec<T> {
2465 fn as_ref(&self) -> &Vec<T> {
2470 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2471 impl<T> AsMut<Vec<T>> for Vec<T> {
2472 fn as_mut(&mut self) -> &mut Vec<T> {
2477 #[stable(feature = "rust1", since = "1.0.0")]
2478 impl<T> AsRef<[T]> for Vec<T> {
2479 fn as_ref(&self) -> &[T] {
2484 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2485 impl<T> AsMut<[T]> for Vec<T> {
2486 fn as_mut(&mut self) -> &mut [T] {
2491 #[stable(feature = "rust1", since = "1.0.0")]
2492 impl<T: Clone> From<&[T]> for Vec<T> {
2494 fn from(s: &[T]) -> Vec<T> {
2498 fn from(s: &[T]) -> Vec<T> {
2499 crate::slice::to_vec(s)
2503 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2504 impl<T: Clone> From<&mut [T]> for Vec<T> {
2506 fn from(s: &mut [T]) -> Vec<T> {
2510 fn from(s: &mut [T]) -> Vec<T> {
2511 crate::slice::to_vec(s)
2515 #[stable(feature = "vec_from_array", since = "1.44.0")]
2516 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2518 fn from(s: [T; N]) -> Vec<T> {
2519 <[T]>::into_vec(box s)
2522 fn from(s: [T; N]) -> Vec<T> {
2523 crate::slice::into_vec(box s)
2527 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2528 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2530 [T]: ToOwned<Owned = Vec<T>>,
2532 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2537 // note: test pulls in libstd, which causes errors here
2539 #[stable(feature = "vec_from_box", since = "1.18.0")]
2540 impl<T> From<Box<[T]>> for Vec<T> {
2541 fn from(s: Box<[T]>) -> Vec<T> {
2546 // note: test pulls in libstd, which causes errors here
2548 #[stable(feature = "box_from_vec", since = "1.20.0")]
2549 impl<T> From<Vec<T>> for Box<[T]> {
2550 fn from(v: Vec<T>) -> Box<[T]> {
2551 v.into_boxed_slice()
2555 #[stable(feature = "rust1", since = "1.0.0")]
2556 impl From<&str> for Vec<u8> {
2557 fn from(s: &str) -> Vec<u8> {
2558 From::from(s.as_bytes())
2562 ////////////////////////////////////////////////////////////////////////////////
2564 ////////////////////////////////////////////////////////////////////////////////
2566 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2567 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2568 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2573 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2574 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2575 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2580 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2581 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2582 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2583 Cow::Borrowed(v.as_slice())
2587 #[stable(feature = "rust1", since = "1.0.0")]
2588 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
2592 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2593 Cow::Owned(FromIterator::from_iter(it))
2597 ////////////////////////////////////////////////////////////////////////////////
2599 ////////////////////////////////////////////////////////////////////////////////
2601 /// An iterator that moves out of a vector.
2603 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
2604 /// by the [`IntoIterator`] trait).
2605 #[stable(feature = "rust1", since = "1.0.0")]
2606 pub struct IntoIter<T> {
2608 phantom: PhantomData<T>,
2614 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2615 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2616 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2617 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2621 impl<T> IntoIter<T> {
2622 /// Returns the remaining items of this iterator as a slice.
2627 /// let vec = vec!['a', 'b', 'c'];
2628 /// let mut into_iter = vec.into_iter();
2629 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2630 /// let _ = into_iter.next().unwrap();
2631 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2633 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2634 pub fn as_slice(&self) -> &[T] {
2635 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
2638 /// Returns the remaining items of this iterator as a mutable slice.
2643 /// let vec = vec!['a', 'b', 'c'];
2644 /// let mut into_iter = vec.into_iter();
2645 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2646 /// into_iter.as_mut_slice()[2] = 'z';
2647 /// assert_eq!(into_iter.next().unwrap(), 'a');
2648 /// assert_eq!(into_iter.next().unwrap(), 'b');
2649 /// assert_eq!(into_iter.next().unwrap(), 'z');
2651 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2652 pub fn as_mut_slice(&mut self) -> &mut [T] {
2653 unsafe { &mut *self.as_raw_mut_slice() }
2656 fn as_raw_mut_slice(&mut self) -> *mut [T] {
2657 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
2661 #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
2662 impl<T> AsRef<[T]> for IntoIter<T> {
2663 fn as_ref(&self) -> &[T] {
2668 #[stable(feature = "rust1", since = "1.0.0")]
2669 unsafe impl<T: Send> Send for IntoIter<T> {}
2670 #[stable(feature = "rust1", since = "1.0.0")]
2671 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2673 #[stable(feature = "rust1", since = "1.0.0")]
2674 impl<T> Iterator for IntoIter<T> {
2678 fn next(&mut self) -> Option<T> {
2680 if self.ptr as *const _ == self.end {
2683 if mem::size_of::<T>() == 0 {
2684 // purposefully don't use 'ptr.offset' because for
2685 // vectors with 0-size elements this would return the
2687 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2689 // Make up a value of this ZST.
2693 self.ptr = self.ptr.offset(1);
2695 Some(ptr::read(old))
2702 fn size_hint(&self) -> (usize, Option<usize>) {
2703 let exact = if mem::size_of::<T>() == 0 {
2704 (self.end as usize).wrapping_sub(self.ptr as usize)
2706 unsafe { self.end.offset_from(self.ptr) as usize }
2708 (exact, Some(exact))
2712 fn count(self) -> usize {
2717 #[stable(feature = "rust1", since = "1.0.0")]
2718 impl<T> DoubleEndedIterator for IntoIter<T> {
2720 fn next_back(&mut self) -> Option<T> {
2722 if self.end == self.ptr {
2725 if mem::size_of::<T>() == 0 {
2726 // See above for why 'ptr.offset' isn't used
2727 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2729 // Make up a value of this ZST.
2732 self.end = self.end.offset(-1);
2734 Some(ptr::read(self.end))
2741 #[stable(feature = "rust1", since = "1.0.0")]
2742 impl<T> ExactSizeIterator for IntoIter<T> {
2743 fn is_empty(&self) -> bool {
2744 self.ptr == self.end
2748 #[stable(feature = "fused", since = "1.26.0")]
2749 impl<T> FusedIterator for IntoIter<T> {}
2751 #[unstable(feature = "trusted_len", issue = "37572")]
2752 unsafe impl<T> TrustedLen for IntoIter<T> {}
2754 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2755 impl<T: Clone> Clone for IntoIter<T> {
2756 fn clone(&self) -> IntoIter<T> {
2757 self.as_slice().to_owned().into_iter()
2761 #[stable(feature = "rust1", since = "1.0.0")]
2762 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2763 fn drop(&mut self) {
2764 struct DropGuard<'a, T>(&'a mut IntoIter<T>);
2766 impl<T> Drop for DropGuard<'_, T> {
2767 fn drop(&mut self) {
2768 // RawVec handles deallocation
2769 let _ = unsafe { RawVec::from_raw_parts(self.0.buf.as_ptr(), self.0.cap) };
2773 let guard = DropGuard(self);
2774 // destroy the remaining elements
2776 ptr::drop_in_place(guard.0.as_raw_mut_slice());
2778 // now `guard` will be dropped and do the rest
2782 /// A draining iterator for `Vec<T>`.
2784 /// This `struct` is created by [`Vec::drain`].
2785 #[stable(feature = "drain", since = "1.6.0")]
2786 pub struct Drain<'a, T: 'a> {
2787 /// Index of tail to preserve
2791 /// Current remaining range to remove
2792 iter: slice::Iter<'a, T>,
2793 vec: NonNull<Vec<T>>,
2796 #[stable(feature = "collection_debug", since = "1.17.0")]
2797 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2798 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2799 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
2803 impl<'a, T> Drain<'a, T> {
2804 /// Returns the remaining items of this iterator as a slice.
2809 /// let mut vec = vec!['a', 'b', 'c'];
2810 /// let mut drain = vec.drain(..);
2811 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
2812 /// let _ = drain.next().unwrap();
2813 /// assert_eq!(drain.as_slice(), &['b', 'c']);
2815 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
2816 pub fn as_slice(&self) -> &[T] {
2817 self.iter.as_slice()
2821 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
2822 impl<'a, T> AsRef<[T]> for Drain<'a, T> {
2823 fn as_ref(&self) -> &[T] {
2828 #[stable(feature = "drain", since = "1.6.0")]
2829 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2830 #[stable(feature = "drain", since = "1.6.0")]
2831 unsafe impl<T: Send> Send for Drain<'_, T> {}
2833 #[stable(feature = "drain", since = "1.6.0")]
2834 impl<T> Iterator for Drain<'_, T> {
2838 fn next(&mut self) -> Option<T> {
2839 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2842 fn size_hint(&self) -> (usize, Option<usize>) {
2843 self.iter.size_hint()
2847 #[stable(feature = "drain", since = "1.6.0")]
2848 impl<T> DoubleEndedIterator for Drain<'_, T> {
2850 fn next_back(&mut self) -> Option<T> {
2851 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2855 #[stable(feature = "drain", since = "1.6.0")]
2856 impl<T> Drop for Drain<'_, T> {
2857 fn drop(&mut self) {
2858 /// Continues dropping the remaining elements in the `Drain`, then moves back the
2859 /// un-`Drain`ed elements to restore the original `Vec`.
2860 struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>);
2862 impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> {
2863 fn drop(&mut self) {
2864 // Continue the same loop we have below. If the loop already finished, this does
2866 self.0.for_each(drop);
2868 if self.0.tail_len > 0 {
2870 let source_vec = self.0.vec.as_mut();
2871 // memmove back untouched tail, update to new length
2872 let start = source_vec.len();
2873 let tail = self.0.tail_start;
2875 let src = source_vec.as_ptr().add(tail);
2876 let dst = source_vec.as_mut_ptr().add(start);
2877 ptr::copy(src, dst, self.0.tail_len);
2879 source_vec.set_len(start + self.0.tail_len);
2885 // exhaust self first
2886 while let Some(item) = self.next() {
2887 let guard = DropGuard(self);
2892 // Drop a `DropGuard` to move back the non-drained tail of `self`.
2897 #[stable(feature = "drain", since = "1.6.0")]
2898 impl<T> ExactSizeIterator for Drain<'_, T> {
2899 fn is_empty(&self) -> bool {
2900 self.iter.is_empty()
2904 #[unstable(feature = "trusted_len", issue = "37572")]
2905 unsafe impl<T> TrustedLen for Drain<'_, T> {}
2907 #[stable(feature = "fused", since = "1.26.0")]
2908 impl<T> FusedIterator for Drain<'_, T> {}
2910 /// A splicing iterator for `Vec`.
2912 /// This struct is created by [`Vec::splice()`].
2913 /// See its documentation for more.
2915 #[stable(feature = "vec_splice", since = "1.21.0")]
2916 pub struct Splice<'a, I: Iterator + 'a> {
2917 drain: Drain<'a, I::Item>,
2921 #[stable(feature = "vec_splice", since = "1.21.0")]
2922 impl<I: Iterator> Iterator for Splice<'_, I> {
2923 type Item = I::Item;
2925 fn next(&mut self) -> Option<Self::Item> {
2929 fn size_hint(&self) -> (usize, Option<usize>) {
2930 self.drain.size_hint()
2934 #[stable(feature = "vec_splice", since = "1.21.0")]
2935 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
2936 fn next_back(&mut self) -> Option<Self::Item> {
2937 self.drain.next_back()
2941 #[stable(feature = "vec_splice", since = "1.21.0")]
2942 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
2944 #[stable(feature = "vec_splice", since = "1.21.0")]
2945 impl<I: Iterator> Drop for Splice<'_, I> {
2946 fn drop(&mut self) {
2947 self.drain.by_ref().for_each(drop);
2950 if self.drain.tail_len == 0 {
2951 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2955 // First fill the range left by drain().
2956 if !self.drain.fill(&mut self.replace_with) {
2960 // There may be more elements. Use the lower bound as an estimate.
2961 // FIXME: Is the upper bound a better guess? Or something else?
2962 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2963 if lower_bound > 0 {
2964 self.drain.move_tail(lower_bound);
2965 if !self.drain.fill(&mut self.replace_with) {
2970 // Collect any remaining elements.
2971 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2972 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2973 // Now we have an exact count.
2974 if collected.len() > 0 {
2975 self.drain.move_tail(collected.len());
2976 let filled = self.drain.fill(&mut collected);
2977 debug_assert!(filled);
2978 debug_assert_eq!(collected.len(), 0);
2981 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2985 /// Private helper methods for `Splice::drop`
2986 impl<T> Drain<'_, T> {
2987 /// The range from `self.vec.len` to `self.tail_start` contains elements
2988 /// that have been moved out.
2989 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2990 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2991 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
2992 let vec = unsafe { self.vec.as_mut() };
2993 let range_start = vec.len;
2994 let range_end = self.tail_start;
2995 let range_slice = unsafe {
2996 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
2999 for place in range_slice {
3000 if let Some(new_item) = replace_with.next() {
3001 unsafe { ptr::write(place, new_item) };
3010 /// Makes room for inserting more elements before the tail.
3011 unsafe fn move_tail(&mut self, additional: usize) {
3012 let vec = unsafe { self.vec.as_mut() };
3013 let len = self.tail_start + self.tail_len;
3014 vec.buf.reserve(len, additional);
3016 let new_tail_start = self.tail_start + additional;
3018 let src = vec.as_ptr().add(self.tail_start);
3019 let dst = vec.as_mut_ptr().add(new_tail_start);
3020 ptr::copy(src, dst, self.tail_len);
3022 self.tail_start = new_tail_start;
3026 /// An iterator which uses a closure to determine if an element should be removed.
3028 /// This struct is created by [`Vec::drain_filter`].
3029 /// See its documentation for more.
3030 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3032 pub struct DrainFilter<'a, T, F>
3034 F: FnMut(&mut T) -> bool,
3036 vec: &'a mut Vec<T>,
3037 /// The index of the item that will be inspected by the next call to `next`.
3039 /// The number of items that have been drained (removed) thus far.
3041 /// The original length of `vec` prior to draining.
3043 /// The filter test predicate.
3045 /// A flag that indicates a panic has occurred in the filter test prodicate.
3046 /// This is used as a hint in the drop implementation to prevent consumption
3047 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3048 /// backshifted in the `vec`, but no further items will be dropped or
3049 /// tested by the filter predicate.
3053 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3054 impl<T, F> Iterator for DrainFilter<'_, T, F>
3056 F: FnMut(&mut T) -> bool,
3060 fn next(&mut self) -> Option<T> {
3062 while self.idx < self.old_len {
3064 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3065 self.panic_flag = true;
3066 let drained = (self.pred)(&mut v[i]);
3067 self.panic_flag = false;
3068 // Update the index *after* the predicate is called. If the index
3069 // is updated prior and the predicate panics, the element at this
3070 // index would be leaked.
3074 return Some(ptr::read(&v[i]));
3075 } else if self.del > 0 {
3077 let src: *const T = &v[i];
3078 let dst: *mut T = &mut v[i - del];
3079 ptr::copy_nonoverlapping(src, dst, 1);
3086 fn size_hint(&self) -> (usize, Option<usize>) {
3087 (0, Some(self.old_len - self.idx))
3091 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3092 impl<T, F> Drop for DrainFilter<'_, T, F>
3094 F: FnMut(&mut T) -> bool,
3096 fn drop(&mut self) {
3097 struct BackshiftOnDrop<'a, 'b, T, F>
3099 F: FnMut(&mut T) -> bool,
3101 drain: &'b mut DrainFilter<'a, T, F>,
3104 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
3106 F: FnMut(&mut T) -> bool,
3108 fn drop(&mut self) {
3110 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3111 // This is a pretty messed up state, and there isn't really an
3112 // obviously right thing to do. We don't want to keep trying
3113 // to execute `pred`, so we just backshift all the unprocessed
3114 // elements and tell the vec that they still exist. The backshift
3115 // is required to prevent a double-drop of the last successfully
3116 // drained item prior to a panic in the predicate.
3117 let ptr = self.drain.vec.as_mut_ptr();
3118 let src = ptr.add(self.drain.idx);
3119 let dst = src.sub(self.drain.del);
3120 let tail_len = self.drain.old_len - self.drain.idx;
3121 src.copy_to(dst, tail_len);
3123 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3128 let backshift = BackshiftOnDrop { drain: self };
3130 // Attempt to consume any remaining elements if the filter predicate
3131 // has not yet panicked. We'll backshift any remaining elements
3132 // whether we've already panicked or if the consumption here panics.
3133 if !backshift.drain.panic_flag {
3134 backshift.drain.for_each(drop);