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<T>`] with [`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 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
54 //! [`new`]: ../../std/vec/struct.Vec.html#method.new
55 //! [`push`]: ../../std/vec/struct.Vec.html#method.push
56 //! [`Index`]: ../../std/ops/trait.Index.html
57 //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
58 //! [`vec!`]: ../../std/macro.vec.html
60 #![stable(feature = "rust1", since = "1.0.0")]
62 use core::array::LengthAtMost32;
63 use core::cmp::{self, Ordering};
65 use core::hash::{self, Hash};
66 use core::intrinsics::{arith_offset, assume};
67 use core::iter::{FromIterator, FusedIterator, TrustedLen};
68 use core::marker::PhantomData;
69 use core::mem::{self, ManuallyDrop};
70 use core::ops::Bound::{Excluded, Included, Unbounded};
71 use core::ops::{self, Index, IndexMut, RangeBounds};
72 use core::ptr::{self, NonNull};
73 use core::slice::{self, SliceIndex};
75 use crate::borrow::{Cow, ToOwned};
76 use crate::boxed::Box;
77 use crate::collections::TryReserveError;
78 use crate::raw_vec::RawVec;
80 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
85 /// let mut vec = Vec::new();
89 /// assert_eq!(vec.len(), 2);
90 /// assert_eq!(vec[0], 1);
92 /// assert_eq!(vec.pop(), Some(2));
93 /// assert_eq!(vec.len(), 1);
96 /// assert_eq!(vec[0], 7);
98 /// vec.extend([1, 2, 3].iter().copied());
101 /// println!("{}", x);
103 /// assert_eq!(vec, [7, 1, 2, 3]);
106 /// The [`vec!`] macro is provided to make initialization more convenient:
109 /// let mut vec = vec![1, 2, 3];
111 /// assert_eq!(vec, [1, 2, 3, 4]);
114 /// It can also initialize each element of a `Vec<T>` with a given value.
115 /// This may be more efficient than performing allocation and initialization
116 /// in separate steps, especially when initializing a vector of zeros:
119 /// let vec = vec![0; 5];
120 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
122 /// // The following is equivalent, but potentially slower:
123 /// let mut vec1 = Vec::with_capacity(5);
124 /// vec1.resize(5, 0);
127 /// Use a `Vec<T>` as an efficient stack:
130 /// let mut stack = Vec::new();
136 /// while let Some(top) = stack.pop() {
137 /// // Prints 3, 2, 1
138 /// println!("{}", top);
144 /// The `Vec` type allows to access values by index, because it implements the
145 /// [`Index`] trait. An example will be more explicit:
148 /// let v = vec![0, 2, 4, 6];
149 /// println!("{}", v[1]); // it will display '2'
152 /// However be careful: if you try to access an index which isn't in the `Vec`,
153 /// your software will panic! You cannot do this:
156 /// let v = vec![0, 2, 4, 6];
157 /// println!("{}", v[6]); // it will panic!
160 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
165 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
166 /// To get a slice, use `&`. Example:
169 /// fn read_slice(slice: &[usize]) {
173 /// let v = vec![0, 1];
176 /// // ... and that's all!
177 /// // you can also do it like this:
178 /// let x : &[usize] = &v;
181 /// In Rust, it's more common to pass slices as arguments rather than vectors
182 /// when you just want to provide read access. The same goes for [`String`] and
185 /// # Capacity and reallocation
187 /// The capacity of a vector is the amount of space allocated for any future
188 /// elements that will be added onto the vector. This is not to be confused with
189 /// the *length* of a vector, which specifies the number of actual elements
190 /// within the vector. If a vector's length exceeds its capacity, its capacity
191 /// will automatically be increased, but its elements will have to be
194 /// For example, a vector with capacity 10 and length 0 would be an empty vector
195 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
196 /// vector will not change its capacity or cause reallocation to occur. However,
197 /// if the vector's length is increased to 11, it will have to reallocate, which
198 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
199 /// whenever possible to specify how big the vector is expected to get.
203 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
204 /// about its design. This ensures that it's as low-overhead as possible in
205 /// the general case, and can be correctly manipulated in primitive ways
206 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
207 /// If additional type parameters are added (e.g., to support custom allocators),
208 /// overriding their defaults may change the behavior.
210 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
211 /// triplet. No more, no less. The order of these fields is completely
212 /// unspecified, and you should use the appropriate methods to modify these.
213 /// The pointer will never be null, so this type is null-pointer-optimized.
215 /// However, the pointer may not actually point to allocated memory. In particular,
216 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
217 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
218 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
219 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
220 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
221 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
222 /// details are very subtle — if you intend to allocate memory using a `Vec`
223 /// and use it for something else (either to pass to unsafe code, or to build your
224 /// own memory-backed collection), be sure to deallocate this memory by using
225 /// `from_raw_parts` to recover the `Vec` and then dropping it.
227 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
228 /// (as defined by the allocator Rust is configured to use by default), and its
229 /// pointer points to [`len`] initialized, contiguous elements in order (what
230 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
231 /// `[`len`] logically uninitialized, contiguous elements.
233 /// `Vec` will never perform a "small optimization" where elements are actually
234 /// stored on the stack for two reasons:
236 /// * It would make it more difficult for unsafe code to correctly manipulate
237 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
238 /// only moved, and it would be more difficult to determine if a `Vec` had
239 /// actually allocated memory.
241 /// * It would penalize the general case, incurring an additional branch
244 /// `Vec` will never automatically shrink itself, even if completely empty. This
245 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
246 /// and then filling it back up to the same [`len`] should incur no calls to
247 /// the allocator. If you wish to free up unused memory, use
248 /// [`shrink_to_fit`].
250 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
251 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
252 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
253 /// accurate, and can be relied on. It can even be used to manually free the memory
254 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
255 /// when not necessary.
257 /// `Vec` does not guarantee any particular growth strategy when reallocating
258 /// when full, nor when [`reserve`] is called. The current strategy is basic
259 /// and it may prove desirable to use a non-constant growth factor. Whatever
260 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
262 /// `vec![x; n]`, `vec![a, b, c, d]`, and
263 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
264 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
265 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
266 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
268 /// `Vec` will not specifically overwrite any data that is removed from it,
269 /// but also won't specifically preserve it. Its uninitialized memory is
270 /// scratch space that it may use however it wants. It will generally just do
271 /// whatever is most efficient or otherwise easy to implement. Do not rely on
272 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
273 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
274 /// first, that may not actually happen because the optimizer does not consider
275 /// this a side-effect that must be preserved. There is one case which we will
276 /// not break, however: using `unsafe` code to write to the excess capacity,
277 /// and then increasing the length to match, is always valid.
279 /// `Vec` does not currently guarantee the order in which elements are dropped.
280 /// The order has changed in the past and may change again.
282 /// [`vec!`]: ../../std/macro.vec.html
283 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
284 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
285 /// [`Index`]: ../../std/ops/trait.Index.html
286 /// [`String`]: ../../std/string/struct.String.html
287 /// [`&str`]: ../../std/primitive.str.html
288 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
289 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
290 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
291 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
292 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
293 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
294 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
295 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
296 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
297 /// [owned slice]: ../../std/boxed/struct.Box.html
298 #[stable(feature = "rust1", since = "1.0.0")]
299 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
305 ////////////////////////////////////////////////////////////////////////////////
307 ////////////////////////////////////////////////////////////////////////////////
310 /// Constructs a new, empty `Vec<T>`.
312 /// The vector will not allocate until elements are pushed onto it.
317 /// # #![allow(unused_mut)]
318 /// let mut vec: Vec<i32> = Vec::new();
321 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
322 #[stable(feature = "rust1", since = "1.0.0")]
323 pub const fn new() -> Vec<T> {
324 Vec { buf: RawVec::NEW, len: 0 }
327 /// Constructs a new, empty `Vec<T>` with the specified capacity.
329 /// The vector will be able to hold exactly `capacity` elements without
330 /// reallocating. If `capacity` is 0, the vector will not allocate.
332 /// It is important to note that although the returned vector has the
333 /// *capacity* specified, the vector will have a zero *length*. For an
334 /// explanation of the difference between length and capacity, see
335 /// *[Capacity and reallocation]*.
337 /// [Capacity and reallocation]: #capacity-and-reallocation
342 /// let mut vec = Vec::with_capacity(10);
344 /// // The vector contains no items, even though it has capacity for more
345 /// assert_eq!(vec.len(), 0);
347 /// // These are all done without reallocating...
351 /// assert_eq!(vec.capacity(), 10);
353 /// // ...but this may make the vector reallocate
355 /// assert!(vec.capacity() >= 11);
358 #[stable(feature = "rust1", since = "1.0.0")]
359 pub fn with_capacity(capacity: usize) -> Vec<T> {
360 Vec { buf: RawVec::with_capacity(capacity), len: 0 }
363 /// Decomposes a `Vec<T>` into its raw components.
365 /// Returns the raw pointer to the underlying data, the length of
366 /// the vector (in elements), and the allocated capacity of the
367 /// data (in elements). These are the same arguments in the same
368 /// order as the arguments to [`from_raw_parts`].
370 /// After calling this function, the caller is responsible for the
371 /// memory previously managed by the `Vec`. The only way to do
372 /// this is to convert the raw pointer, length, and capacity back
373 /// into a `Vec` with the [`from_raw_parts`] function, allowing
374 /// the destructor to perform the cleanup.
376 /// [`from_raw_parts`]: #method.from_raw_parts
381 /// #![feature(vec_into_raw_parts)]
382 /// let v: Vec<i32> = vec![-1, 0, 1];
384 /// let (ptr, len, cap) = v.into_raw_parts();
386 /// let rebuilt = unsafe {
387 /// // We can now make changes to the components, such as
388 /// // transmuting the raw pointer to a compatible type.
389 /// let ptr = ptr as *mut u32;
391 /// Vec::from_raw_parts(ptr, len, cap)
393 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
395 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
396 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
397 let mut me = ManuallyDrop::new(self);
398 (me.as_mut_ptr(), me.len(), me.capacity())
401 /// Creates a `Vec<T>` directly from the raw components of another vector.
405 /// This is highly unsafe, due to the number of invariants that aren't
408 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
409 /// (at least, it's highly likely to be incorrect if it wasn't).
410 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
411 /// (`T` having a less strict alignment is not sufficient, the alignment really
412 /// needs to be equal to satsify the [`dealloc`] requirement that memory must be
413 /// allocated and deallocated with the same layout.)
414 /// * `length` needs to be less than or equal to `capacity`.
415 /// * `capacity` needs to be the capacity that the pointer was allocated with.
417 /// Violating these may cause problems like corrupting the allocator's
418 /// internal data structures. For example it is **not** safe
419 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
420 /// It's also not safe to build one from a `Vec<u16>` and its length, because
421 /// the allocator cares about the alignment, and these two types have different
422 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
423 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
425 /// The ownership of `ptr` is effectively transferred to the
426 /// `Vec<T>` which may then deallocate, reallocate or change the
427 /// contents of memory pointed to by the pointer at will. Ensure
428 /// that nothing else uses the pointer after calling this
431 /// [`String`]: ../../std/string/struct.String.html
432 /// [`dealloc`]: ../../alloc/alloc/trait.GlobalAlloc.html#tymethod.dealloc
440 /// let v = vec![1, 2, 3];
442 // FIXME Update this when vec_into_raw_parts is stabilized
443 /// // Prevent running `v`'s destructor so we are in complete control
444 /// // of the allocation.
445 /// let mut v = mem::ManuallyDrop::new(v);
447 /// // Pull out the various important pieces of information about `v`
448 /// let p = v.as_mut_ptr();
449 /// let len = v.len();
450 /// let cap = v.capacity();
453 /// // Overwrite memory with 4, 5, 6
454 /// for i in 0..len as isize {
455 /// ptr::write(p.offset(i), 4 + i);
458 /// // Put everything back together into a Vec
459 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
460 /// assert_eq!(rebuilt, [4, 5, 6]);
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
465 Vec { buf: RawVec::from_raw_parts(ptr, capacity), len: length }
468 /// Returns the number of elements the vector can hold without
474 /// let vec: Vec<i32> = Vec::with_capacity(10);
475 /// assert_eq!(vec.capacity(), 10);
478 #[stable(feature = "rust1", since = "1.0.0")]
479 pub fn capacity(&self) -> usize {
483 /// Reserves capacity for at least `additional` more elements to be inserted
484 /// in the given `Vec<T>`. The collection may reserve more space to avoid
485 /// frequent reallocations. After calling `reserve`, capacity will be
486 /// greater than or equal to `self.len() + additional`. Does nothing if
487 /// capacity is already sufficient.
491 /// Panics if the new capacity overflows `usize`.
496 /// let mut vec = vec![1];
498 /// assert!(vec.capacity() >= 11);
500 #[stable(feature = "rust1", since = "1.0.0")]
501 pub fn reserve(&mut self, additional: usize) {
502 self.buf.reserve(self.len, additional);
505 /// Reserves the minimum capacity for exactly `additional` more elements to
506 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
507 /// capacity will be greater than or equal to `self.len() + additional`.
508 /// Does nothing if the capacity is already sufficient.
510 /// Note that the allocator may give the collection more space than it
511 /// requests. Therefore, capacity can not be relied upon to be precisely
512 /// minimal. Prefer `reserve` if future insertions are expected.
516 /// Panics if the new capacity overflows `usize`.
521 /// let mut vec = vec![1];
522 /// vec.reserve_exact(10);
523 /// assert!(vec.capacity() >= 11);
525 #[stable(feature = "rust1", since = "1.0.0")]
526 pub fn reserve_exact(&mut self, additional: usize) {
527 self.buf.reserve_exact(self.len, additional);
530 /// Tries to reserve capacity for at least `additional` more elements to be inserted
531 /// in the given `Vec<T>`. The collection may reserve more space to avoid
532 /// frequent reallocations. After calling `reserve`, capacity will be
533 /// greater than or equal to `self.len() + additional`. Does nothing if
534 /// capacity is already sufficient.
538 /// If the capacity overflows, or the allocator reports a failure, then an error
544 /// #![feature(try_reserve)]
545 /// use std::collections::TryReserveError;
547 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
548 /// let mut output = Vec::new();
550 /// // Pre-reserve the memory, exiting if we can't
551 /// output.try_reserve(data.len())?;
553 /// // Now we know this can't OOM in the middle of our complex work
554 /// output.extend(data.iter().map(|&val| {
555 /// val * 2 + 5 // very complicated
560 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
562 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
563 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
564 self.buf.try_reserve(self.len, additional)
567 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
568 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
569 /// capacity will be greater than or equal to `self.len() + additional`.
570 /// Does nothing if the capacity is already sufficient.
572 /// Note that the allocator may give the collection more space than it
573 /// requests. Therefore, capacity can not be relied upon to be precisely
574 /// minimal. Prefer `reserve` if future insertions are expected.
578 /// If the capacity overflows, or the allocator reports a failure, then an error
584 /// #![feature(try_reserve)]
585 /// use std::collections::TryReserveError;
587 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
588 /// let mut output = Vec::new();
590 /// // Pre-reserve the memory, exiting if we can't
591 /// output.try_reserve(data.len())?;
593 /// // Now we know this can't OOM in the middle of our complex work
594 /// output.extend(data.iter().map(|&val| {
595 /// val * 2 + 5 // very complicated
600 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
602 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
603 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
604 self.buf.try_reserve_exact(self.len, additional)
607 /// Shrinks the capacity of the vector as much as possible.
609 /// It will drop down as close as possible to the length but the allocator
610 /// may still inform the vector that there is space for a few more elements.
615 /// let mut vec = Vec::with_capacity(10);
616 /// vec.extend([1, 2, 3].iter().cloned());
617 /// assert_eq!(vec.capacity(), 10);
618 /// vec.shrink_to_fit();
619 /// assert!(vec.capacity() >= 3);
621 #[stable(feature = "rust1", since = "1.0.0")]
622 pub fn shrink_to_fit(&mut self) {
623 if self.capacity() != self.len {
624 self.buf.shrink_to_fit(self.len);
628 /// Shrinks the capacity of the vector with a lower bound.
630 /// The capacity will remain at least as large as both the length
631 /// and the supplied value.
635 /// Panics if the current capacity is smaller than the supplied
636 /// minimum capacity.
641 /// #![feature(shrink_to)]
642 /// let mut vec = Vec::with_capacity(10);
643 /// vec.extend([1, 2, 3].iter().cloned());
644 /// assert_eq!(vec.capacity(), 10);
645 /// vec.shrink_to(4);
646 /// assert!(vec.capacity() >= 4);
647 /// vec.shrink_to(0);
648 /// assert!(vec.capacity() >= 3);
650 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
651 pub fn shrink_to(&mut self, min_capacity: usize) {
652 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
655 /// Converts the vector into [`Box<[T]>`][owned slice].
657 /// Note that this will drop any excess capacity.
659 /// [owned slice]: ../../std/boxed/struct.Box.html
664 /// let v = vec![1, 2, 3];
666 /// let slice = v.into_boxed_slice();
669 /// Any excess capacity is removed:
672 /// let mut vec = Vec::with_capacity(10);
673 /// vec.extend([1, 2, 3].iter().cloned());
675 /// assert_eq!(vec.capacity(), 10);
676 /// let slice = vec.into_boxed_slice();
677 /// assert_eq!(slice.into_vec().capacity(), 3);
679 #[stable(feature = "rust1", since = "1.0.0")]
680 pub fn into_boxed_slice(mut self) -> Box<[T]> {
682 self.shrink_to_fit();
683 let me = ManuallyDrop::new(self);
684 let buf = ptr::read(&me.buf);
686 buf.into_box(len).assume_init()
690 /// Shortens the vector, keeping the first `len` elements and dropping
693 /// If `len` is greater than the vector's current length, this has no
696 /// The [`drain`] method can emulate `truncate`, but causes the excess
697 /// elements to be returned instead of dropped.
699 /// Note that this method has no effect on the allocated capacity
704 /// Truncating a five element vector to two elements:
707 /// let mut vec = vec![1, 2, 3, 4, 5];
709 /// assert_eq!(vec, [1, 2]);
712 /// No truncation occurs when `len` is greater than the vector's current
716 /// let mut vec = vec![1, 2, 3];
718 /// assert_eq!(vec, [1, 2, 3]);
721 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
725 /// let mut vec = vec![1, 2, 3];
727 /// assert_eq!(vec, []);
730 /// [`clear`]: #method.clear
731 /// [`drain`]: #method.drain
732 #[stable(feature = "rust1", since = "1.0.0")]
733 pub fn truncate(&mut self, len: usize) {
734 // This is safe because:
736 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
737 // case avoids creating an invalid slice, and
738 // * the `len` of the vector is shrunk before calling `drop_in_place`,
739 // such that no value will be dropped twice in case `drop_in_place`
740 // were to panic once (if it panics twice, the program aborts).
745 let remaining_len = self.len - len;
746 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
748 ptr::drop_in_place(s);
752 /// Extracts a slice containing the entire vector.
754 /// Equivalent to `&s[..]`.
759 /// use std::io::{self, Write};
760 /// let buffer = vec![1, 2, 3, 5, 8];
761 /// io::sink().write(buffer.as_slice()).unwrap();
764 #[stable(feature = "vec_as_slice", since = "1.7.0")]
765 pub fn as_slice(&self) -> &[T] {
769 /// Extracts a mutable slice of the entire vector.
771 /// Equivalent to `&mut s[..]`.
776 /// use std::io::{self, Read};
777 /// let mut buffer = vec![0; 3];
778 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
781 #[stable(feature = "vec_as_slice", since = "1.7.0")]
782 pub fn as_mut_slice(&mut self) -> &mut [T] {
786 /// Returns a raw pointer to the vector's buffer.
788 /// The caller must ensure that the vector outlives the pointer this
789 /// function returns, or else it will end up pointing to garbage.
790 /// Modifying the vector may cause its buffer to be reallocated,
791 /// which would also make any pointers to it invalid.
793 /// The caller must also ensure that the memory the pointer (non-transitively) points to
794 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
795 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
800 /// let x = vec![1, 2, 4];
801 /// let x_ptr = x.as_ptr();
804 /// for i in 0..x.len() {
805 /// assert_eq!(*x_ptr.add(i), 1 << i);
810 /// [`as_mut_ptr`]: #method.as_mut_ptr
811 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
813 pub fn as_ptr(&self) -> *const T {
814 // We shadow the slice method of the same name to avoid going through
815 // `deref`, which creates an intermediate reference.
816 let ptr = self.buf.ptr();
818 assume(!ptr.is_null());
823 /// Returns an unsafe mutable pointer to the vector's buffer.
825 /// The caller must ensure that the vector outlives the pointer this
826 /// function returns, or else it will end up pointing to garbage.
827 /// Modifying the vector may cause its buffer to be reallocated,
828 /// which would also make any pointers to it invalid.
833 /// // Allocate vector big enough for 4 elements.
835 /// let mut x: Vec<i32> = Vec::with_capacity(size);
836 /// let x_ptr = x.as_mut_ptr();
838 /// // Initialize elements via raw pointer writes, then set length.
840 /// for i in 0..size {
841 /// *x_ptr.add(i) = i as i32;
845 /// assert_eq!(&*x, &[0,1,2,3]);
847 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
849 pub fn as_mut_ptr(&mut self) -> *mut T {
850 // We shadow the slice method of the same name to avoid going through
851 // `deref_mut`, which creates an intermediate reference.
852 let ptr = self.buf.ptr();
854 assume(!ptr.is_null());
859 /// Forces the length of the vector to `new_len`.
861 /// This is a low-level operation that maintains none of the normal
862 /// invariants of the type. Normally changing the length of a vector
863 /// is done using one of the safe operations instead, such as
864 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
866 /// [`truncate`]: #method.truncate
867 /// [`resize`]: #method.resize
868 /// [`extend`]: ../../std/iter/trait.Extend.html#tymethod.extend
869 /// [`clear`]: #method.clear
873 /// - `new_len` must be less than or equal to [`capacity()`].
874 /// - The elements at `old_len..new_len` must be initialized.
876 /// [`capacity()`]: #method.capacity
880 /// This method can be useful for situations in which the vector
881 /// is serving as a buffer for other code, particularly over FFI:
884 /// # #![allow(dead_code)]
885 /// # // This is just a minimal skeleton for the doc example;
886 /// # // don't use this as a starting point for a real library.
887 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
888 /// # const Z_OK: i32 = 0;
890 /// # fn deflateGetDictionary(
891 /// # strm: *mut std::ffi::c_void,
892 /// # dictionary: *mut u8,
893 /// # dictLength: *mut usize,
896 /// # impl StreamWrapper {
897 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
898 /// // Per the FFI method's docs, "32768 bytes is always enough".
899 /// let mut dict = Vec::with_capacity(32_768);
900 /// let mut dict_length = 0;
901 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
902 /// // 1. `dict_length` elements were initialized.
903 /// // 2. `dict_length` <= the capacity (32_768)
904 /// // which makes `set_len` safe to call.
906 /// // Make the FFI call...
907 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
909 /// // ...and update the length to what was initialized.
910 /// dict.set_len(dict_length);
920 /// While the following example is sound, there is a memory leak since
921 /// the inner vectors were not freed prior to the `set_len` call:
924 /// let mut vec = vec![vec![1, 0, 0],
928 /// // 1. `old_len..0` is empty so no elements need to be initialized.
929 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
935 /// Normally, here, one would use [`clear`] instead to correctly drop
936 /// the contents and thus not leak memory.
938 #[stable(feature = "rust1", since = "1.0.0")]
939 pub unsafe fn set_len(&mut self, new_len: usize) {
940 debug_assert!(new_len <= self.capacity());
945 /// Removes an element from the vector and returns it.
947 /// The removed element is replaced by the last element of the vector.
949 /// This does not preserve ordering, but is O(1).
953 /// Panics if `index` is out of bounds.
958 /// let mut v = vec!["foo", "bar", "baz", "qux"];
960 /// assert_eq!(v.swap_remove(1), "bar");
961 /// assert_eq!(v, ["foo", "qux", "baz"]);
963 /// assert_eq!(v.swap_remove(0), "foo");
964 /// assert_eq!(v, ["baz", "qux"]);
967 #[stable(feature = "rust1", since = "1.0.0")]
968 pub fn swap_remove(&mut self, index: usize) -> T {
971 fn assert_failed(index: usize, len: usize) -> ! {
972 panic!("swap_remove index (is {}) should be < len (is {})", index, len);
975 let len = self.len();
977 assert_failed(index, len);
980 // We replace self[index] with the last element. Note that if the
981 // bounds check above succeeds there must be a last element (which
982 // can be self[index] itself).
983 let last = ptr::read(self.as_ptr().add(len - 1));
984 let hole: *mut T = self.as_mut_ptr().add(index);
985 self.set_len(len - 1);
986 ptr::replace(hole, last)
990 /// Inserts an element at position `index` within the vector, shifting all
991 /// elements after it to the right.
995 /// Panics if `index > len`.
1000 /// let mut vec = vec![1, 2, 3];
1001 /// vec.insert(1, 4);
1002 /// assert_eq!(vec, [1, 4, 2, 3]);
1003 /// vec.insert(4, 5);
1004 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1006 #[stable(feature = "rust1", since = "1.0.0")]
1007 pub fn insert(&mut self, index: usize, element: T) {
1010 fn assert_failed(index: usize, len: usize) -> ! {
1011 panic!("insertion index (is {}) should be <= len (is {})", index, len);
1014 let len = self.len();
1016 assert_failed(index, len);
1019 // space for the new element
1020 if len == self.buf.capacity() {
1026 // The spot to put the new value
1028 let p = self.as_mut_ptr().add(index);
1029 // Shift everything over to make space. (Duplicating the
1030 // `index`th element into two consecutive places.)
1031 ptr::copy(p, p.offset(1), len - index);
1032 // Write it in, overwriting the first copy of the `index`th
1034 ptr::write(p, element);
1036 self.set_len(len + 1);
1040 /// Removes and returns the element at position `index` within the vector,
1041 /// shifting all elements after it to the left.
1045 /// Panics if `index` is out of bounds.
1050 /// let mut v = vec![1, 2, 3];
1051 /// assert_eq!(v.remove(1), 2);
1052 /// assert_eq!(v, [1, 3]);
1054 #[stable(feature = "rust1", since = "1.0.0")]
1055 pub fn remove(&mut self, index: usize) -> T {
1058 fn assert_failed(index: usize, len: usize) -> ! {
1059 panic!("removal index (is {}) should be < len (is {})", index, len);
1062 let len = self.len();
1064 assert_failed(index, len);
1070 // the place we are taking from.
1071 let ptr = self.as_mut_ptr().add(index);
1072 // copy it out, unsafely having a copy of the value on
1073 // the stack and in the vector at the same time.
1074 ret = ptr::read(ptr);
1076 // Shift everything down to fill in that spot.
1077 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1079 self.set_len(len - 1);
1084 /// Retains only the elements specified by the predicate.
1086 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1087 /// This method operates in place, visiting each element exactly once in the
1088 /// original order, and preserves the order of the retained elements.
1093 /// let mut vec = vec![1, 2, 3, 4];
1094 /// vec.retain(|&x| x % 2 == 0);
1095 /// assert_eq!(vec, [2, 4]);
1098 /// The exact order may be useful for tracking external state, like an index.
1101 /// let mut vec = vec![1, 2, 3, 4, 5];
1102 /// let keep = [false, true, true, false, true];
1104 /// vec.retain(|_| (keep[i], i += 1).0);
1105 /// assert_eq!(vec, [2, 3, 5]);
1107 #[stable(feature = "rust1", since = "1.0.0")]
1108 pub fn retain<F>(&mut self, mut f: F)
1110 F: FnMut(&T) -> bool,
1112 let len = self.len();
1115 let v = &mut **self;
1126 self.truncate(len - del);
1130 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1133 /// If the vector is sorted, this removes all duplicates.
1138 /// let mut vec = vec![10, 20, 21, 30, 20];
1140 /// vec.dedup_by_key(|i| *i / 10);
1142 /// assert_eq!(vec, [10, 20, 30, 20]);
1144 #[stable(feature = "dedup_by", since = "1.16.0")]
1146 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1148 F: FnMut(&mut T) -> K,
1151 self.dedup_by(|a, b| key(a) == key(b))
1154 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1157 /// The `same_bucket` function is passed references to two elements from the vector and
1158 /// must determine if the elements compare equal. The elements are passed in opposite order
1159 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1161 /// If the vector is sorted, this removes all duplicates.
1166 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1168 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1170 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1172 #[stable(feature = "dedup_by", since = "1.16.0")]
1173 pub fn dedup_by<F>(&mut self, same_bucket: F)
1175 F: FnMut(&mut T, &mut T) -> bool,
1178 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1184 /// Appends an element to the back of a collection.
1188 /// Panics if the number of elements in the vector overflows a `usize`.
1193 /// let mut vec = vec![1, 2];
1195 /// assert_eq!(vec, [1, 2, 3]);
1198 #[stable(feature = "rust1", since = "1.0.0")]
1199 pub fn push(&mut self, value: T) {
1200 // This will panic or abort if we would allocate > isize::MAX bytes
1201 // or if the length increment would overflow for zero-sized types.
1202 if self.len == self.buf.capacity() {
1206 let end = self.as_mut_ptr().add(self.len);
1207 ptr::write(end, value);
1212 /// Removes the last element from a vector and returns it, or [`None`] if it
1215 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1220 /// let mut vec = vec![1, 2, 3];
1221 /// assert_eq!(vec.pop(), Some(3));
1222 /// assert_eq!(vec, [1, 2]);
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 pub fn pop(&mut self) -> Option<T> {
1232 Some(ptr::read(self.as_ptr().add(self.len())))
1237 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1241 /// Panics if the number of elements in the vector overflows a `usize`.
1246 /// let mut vec = vec![1, 2, 3];
1247 /// let mut vec2 = vec![4, 5, 6];
1248 /// vec.append(&mut vec2);
1249 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1250 /// assert_eq!(vec2, []);
1253 #[stable(feature = "append", since = "1.4.0")]
1254 pub fn append(&mut self, other: &mut Self) {
1256 self.append_elements(other.as_slice() as _);
1261 /// Appends elements to `Self` from other buffer.
1263 unsafe fn append_elements(&mut self, other: *const [T]) {
1264 let count = (*other).len();
1265 self.reserve(count);
1266 let len = self.len();
1267 ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count);
1271 /// Creates a draining iterator that removes the specified range in the vector
1272 /// and yields the removed items.
1274 /// Note 1: The element range is removed even if the iterator is only
1275 /// partially consumed or not consumed at all.
1277 /// Note 2: It is unspecified how many elements are removed from the vector
1278 /// if the `Drain` value is leaked.
1282 /// Panics if the starting point is greater than the end point or if
1283 /// the end point is greater than the length of the vector.
1288 /// let mut v = vec![1, 2, 3];
1289 /// let u: Vec<_> = v.drain(1..).collect();
1290 /// assert_eq!(v, &[1]);
1291 /// assert_eq!(u, &[2, 3]);
1293 /// // A full range clears the vector
1295 /// assert_eq!(v, &[]);
1297 #[stable(feature = "drain", since = "1.6.0")]
1298 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1300 R: RangeBounds<usize>,
1304 // When the Drain is first created, it shortens the length of
1305 // the source vector to make sure no uninitialized or moved-from elements
1306 // are accessible at all if the Drain's destructor never gets to run.
1308 // Drain will ptr::read out the values to remove.
1309 // When finished, remaining tail of the vec is copied back to cover
1310 // the hole, and the vector length is restored to the new length.
1312 let len = self.len();
1313 let start = match range.start_bound() {
1315 Excluded(&n) => n + 1,
1318 let end = match range.end_bound() {
1319 Included(&n) => n + 1,
1326 fn start_assert_failed(start: usize, end: usize) -> ! {
1327 panic!("start drain index (is {}) should be <= end drain index (is {})", start, end);
1332 fn end_assert_failed(end: usize, len: usize) -> ! {
1333 panic!("end drain index (is {}) should be <= len (is {})", end, len);
1337 start_assert_failed(start, end);
1340 end_assert_failed(end, len);
1344 // set self.vec length's to start, to be safe in case Drain is leaked
1345 self.set_len(start);
1346 // Use the borrow in the IterMut to indicate borrowing behavior of the
1347 // whole Drain iterator (like &mut T).
1348 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1351 tail_len: len - end,
1352 iter: range_slice.iter(),
1353 vec: NonNull::from(self),
1358 /// Clears the vector, removing all values.
1360 /// Note that this method has no effect on the allocated capacity
1366 /// let mut v = vec![1, 2, 3];
1370 /// assert!(v.is_empty());
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 pub fn clear(&mut self) {
1378 /// Returns the number of elements in the vector, also referred to
1379 /// as its 'length'.
1384 /// let a = vec![1, 2, 3];
1385 /// assert_eq!(a.len(), 3);
1388 #[stable(feature = "rust1", since = "1.0.0")]
1389 pub fn len(&self) -> usize {
1393 /// Returns `true` if the vector contains no elements.
1398 /// let mut v = Vec::new();
1399 /// assert!(v.is_empty());
1402 /// assert!(!v.is_empty());
1404 #[stable(feature = "rust1", since = "1.0.0")]
1405 pub fn is_empty(&self) -> bool {
1409 /// Splits the collection into two at the given index.
1411 /// Returns a newly allocated vector containing the elements in the range
1412 /// `[at, len)`. After the call, the original vector will be left containing
1413 /// the elements `[0, at)` with its previous capacity unchanged.
1417 /// Panics if `at > len`.
1422 /// let mut vec = vec![1,2,3];
1423 /// let vec2 = vec.split_off(1);
1424 /// assert_eq!(vec, [1]);
1425 /// assert_eq!(vec2, [2, 3]);
1428 #[must_use = "use `.truncate()` if you don't need the other half"]
1429 #[stable(feature = "split_off", since = "1.4.0")]
1430 pub fn split_off(&mut self, at: usize) -> Self {
1433 fn assert_failed(at: usize, len: usize) -> ! {
1434 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1437 if at > self.len() {
1438 assert_failed(at, self.len());
1441 let other_len = self.len - at;
1442 let mut other = Vec::with_capacity(other_len);
1444 // Unsafely `set_len` and copy items to `other`.
1447 other.set_len(other_len);
1449 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1454 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1456 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1457 /// difference, with each additional slot filled with the result of
1458 /// calling the closure `f`. The return values from `f` will end up
1459 /// in the `Vec` in the order they have been generated.
1461 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1463 /// This method uses a closure to create new values on every push. If
1464 /// you'd rather [`Clone`] a given value, use [`resize`]. If you want
1465 /// to use the [`Default`] trait to generate values, you can pass
1466 /// [`Default::default()`] as the second argument.
1471 /// let mut vec = vec![1, 2, 3];
1472 /// vec.resize_with(5, Default::default);
1473 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1475 /// let mut vec = vec![];
1477 /// vec.resize_with(4, || { p *= 2; p });
1478 /// assert_eq!(vec, [2, 4, 8, 16]);
1481 /// [`resize`]: #method.resize
1482 /// [`Clone`]: ../../std/clone/trait.Clone.html
1483 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1484 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1488 let len = self.len();
1490 self.extend_with(new_len - len, ExtendFunc(f));
1492 self.truncate(new_len);
1496 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1497 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1498 /// `'a`. If the type has only static references, or none at all, then this
1499 /// may be chosen to be `'static`.
1501 /// This function is similar to the `leak` function on `Box`.
1503 /// This function is mainly useful for data that lives for the remainder of
1504 /// the program's life. Dropping the returned reference will cause a memory
1512 /// #![feature(vec_leak)]
1514 /// let x = vec![1, 2, 3];
1515 /// let static_ref: &'static mut [usize] = Vec::leak(x);
1516 /// static_ref[0] += 1;
1517 /// assert_eq!(static_ref, &[2, 2, 3]);
1519 #[unstable(feature = "vec_leak", issue = "62195")]
1521 pub fn leak<'a>(vec: Vec<T>) -> &'a mut [T]
1523 T: 'a, // Technically not needed, but kept to be explicit.
1525 Box::leak(vec.into_boxed_slice())
1529 impl<T: Clone> Vec<T> {
1530 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1532 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1533 /// difference, with each additional slot filled with `value`.
1534 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1536 /// This method requires `T` to implement [`Clone`],
1537 /// in order to be able to clone the passed value.
1538 /// If you need more flexibility (or want to rely on [`Default`] instead of
1539 /// [`Clone`]), use [`resize_with`].
1544 /// let mut vec = vec!["hello"];
1545 /// vec.resize(3, "world");
1546 /// assert_eq!(vec, ["hello", "world", "world"]);
1548 /// let mut vec = vec![1, 2, 3, 4];
1549 /// vec.resize(2, 0);
1550 /// assert_eq!(vec, [1, 2]);
1553 /// [`Clone`]: ../../std/clone/trait.Clone.html
1554 /// [`Default`]: ../../std/default/trait.Default.html
1555 /// [`resize_with`]: #method.resize_with
1556 #[stable(feature = "vec_resize", since = "1.5.0")]
1557 pub fn resize(&mut self, new_len: usize, value: T) {
1558 let len = self.len();
1561 self.extend_with(new_len - len, ExtendElement(value))
1563 self.truncate(new_len);
1567 /// Clones and appends all elements in a slice to the `Vec`.
1569 /// Iterates over the slice `other`, clones each element, and then appends
1570 /// it to this `Vec`. The `other` vector is traversed in-order.
1572 /// Note that this function is same as [`extend`] except that it is
1573 /// specialized to work with slices instead. If and when Rust gets
1574 /// specialization this function will likely be deprecated (but still
1580 /// let mut vec = vec![1];
1581 /// vec.extend_from_slice(&[2, 3, 4]);
1582 /// assert_eq!(vec, [1, 2, 3, 4]);
1585 /// [`extend`]: #method.extend
1586 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1587 pub fn extend_from_slice(&mut self, other: &[T]) {
1588 self.spec_extend(other.iter())
1592 impl<T: Default> Vec<T> {
1593 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1595 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1596 /// difference, with each additional slot filled with [`Default::default()`].
1597 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1599 /// This method uses [`Default`] to create new values on every push. If
1600 /// you'd rather [`Clone`] a given value, use [`resize`].
1605 /// # #![allow(deprecated)]
1606 /// #![feature(vec_resize_default)]
1608 /// let mut vec = vec![1, 2, 3];
1609 /// vec.resize_default(5);
1610 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1612 /// let mut vec = vec![1, 2, 3, 4];
1613 /// vec.resize_default(2);
1614 /// assert_eq!(vec, [1, 2]);
1617 /// [`resize`]: #method.resize
1618 /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default
1619 /// [`Default`]: ../../std/default/trait.Default.html
1620 /// [`Clone`]: ../../std/clone/trait.Clone.html
1621 #[unstable(feature = "vec_resize_default", issue = "41758")]
1623 reason = "This is moving towards being removed in favor \
1624 of `.resize_with(Default::default)`. If you disagree, please comment \
1625 in the tracking issue.",
1628 pub fn resize_default(&mut self, new_len: usize) {
1629 let len = self.len();
1632 self.extend_with(new_len - len, ExtendDefault);
1634 self.truncate(new_len);
1639 // This code generalises `extend_with_{element,default}`.
1640 trait ExtendWith<T> {
1641 fn next(&mut self) -> T;
1645 struct ExtendElement<T>(T);
1646 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1647 fn next(&mut self) -> T {
1650 fn last(self) -> T {
1655 struct ExtendDefault;
1656 impl<T: Default> ExtendWith<T> for ExtendDefault {
1657 fn next(&mut self) -> T {
1660 fn last(self) -> T {
1665 struct ExtendFunc<F>(F);
1666 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1667 fn next(&mut self) -> T {
1670 fn last(mut self) -> T {
1676 /// Extend the vector by `n` values, using the given generator.
1677 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1681 let mut ptr = self.as_mut_ptr().add(self.len());
1682 // Use SetLenOnDrop to work around bug where compiler
1683 // may not realize the store through `ptr` through self.set_len()
1685 let mut local_len = SetLenOnDrop::new(&mut self.len);
1687 // Write all elements except the last one
1689 ptr::write(ptr, value.next());
1690 ptr = ptr.offset(1);
1691 // Increment the length in every step in case next() panics
1692 local_len.increment_len(1);
1696 // We can write the last element directly without cloning needlessly
1697 ptr::write(ptr, value.last());
1698 local_len.increment_len(1);
1701 // len set by scope guard
1706 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1708 // The idea is: The length field in SetLenOnDrop is a local variable
1709 // that the optimizer will see does not alias with any stores through the Vec's data
1710 // pointer. This is a workaround for alias analysis issue #32155
1711 struct SetLenOnDrop<'a> {
1716 impl<'a> SetLenOnDrop<'a> {
1718 fn new(len: &'a mut usize) -> Self {
1719 SetLenOnDrop { local_len: *len, len }
1723 fn increment_len(&mut self, increment: usize) {
1724 self.local_len += increment;
1728 impl Drop for SetLenOnDrop<'_> {
1730 fn drop(&mut self) {
1731 *self.len = self.local_len;
1735 impl<T: PartialEq> Vec<T> {
1736 /// Removes consecutive repeated elements in the vector according to the
1737 /// [`PartialEq`] trait implementation.
1739 /// If the vector is sorted, this removes all duplicates.
1744 /// let mut vec = vec![1, 2, 2, 3, 2];
1748 /// assert_eq!(vec, [1, 2, 3, 2]);
1750 #[stable(feature = "rust1", since = "1.0.0")]
1752 pub fn dedup(&mut self) {
1753 self.dedup_by(|a, b| a == b)
1758 /// Removes the first instance of `item` from the vector if the item exists.
1763 /// # #![feature(vec_remove_item)]
1764 /// let mut vec = vec![1, 2, 3, 1];
1766 /// vec.remove_item(&1);
1768 /// assert_eq!(vec, vec![2, 3, 1]);
1770 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1771 pub fn remove_item<V>(&mut self, item: &V) -> Option<T>
1775 let pos = self.iter().position(|x| *x == *item)?;
1776 Some(self.remove(pos))
1780 ////////////////////////////////////////////////////////////////////////////////
1781 // Internal methods and functions
1782 ////////////////////////////////////////////////////////////////////////////////
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1787 <T as SpecFromElem>::from_elem(elem, n)
1790 // Specialization trait used for Vec::from_elem
1791 trait SpecFromElem: Sized {
1792 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1795 impl<T: Clone> SpecFromElem for T {
1796 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1797 let mut v = Vec::with_capacity(n);
1798 v.extend_with(n, ExtendElement(elem));
1803 impl SpecFromElem for u8 {
1805 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1807 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1810 let mut v = Vec::with_capacity(n);
1811 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1818 impl<T: Clone + IsZero> SpecFromElem for T {
1820 fn from_elem(elem: T, n: usize) -> Vec<T> {
1822 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1824 let mut v = Vec::with_capacity(n);
1825 v.extend_with(n, ExtendElement(elem));
1830 #[rustc_specialization_trait]
1831 unsafe trait IsZero {
1832 /// Whether this value is zero
1833 fn is_zero(&self) -> bool;
1836 macro_rules! impl_is_zero {
1837 ($t: ty, $is_zero: expr) => {
1838 unsafe impl IsZero for $t {
1840 fn is_zero(&self) -> bool {
1847 impl_is_zero!(i8, |x| x == 0);
1848 impl_is_zero!(i16, |x| x == 0);
1849 impl_is_zero!(i32, |x| x == 0);
1850 impl_is_zero!(i64, |x| x == 0);
1851 impl_is_zero!(i128, |x| x == 0);
1852 impl_is_zero!(isize, |x| x == 0);
1854 impl_is_zero!(u16, |x| x == 0);
1855 impl_is_zero!(u32, |x| x == 0);
1856 impl_is_zero!(u64, |x| x == 0);
1857 impl_is_zero!(u128, |x| x == 0);
1858 impl_is_zero!(usize, |x| x == 0);
1860 impl_is_zero!(bool, |x| x == false);
1861 impl_is_zero!(char, |x| x == '\0');
1863 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1864 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1866 unsafe impl<T> IsZero for *const T {
1868 fn is_zero(&self) -> bool {
1873 unsafe impl<T> IsZero for *mut T {
1875 fn is_zero(&self) -> bool {
1880 // `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
1881 // For fat pointers, the bytes that would be the pointer metadata in the `Some`
1882 // variant are padding in the `None` variant, so ignoring them and
1883 // zero-initializing instead is ok.
1884 // `Option<&mut T>` never implements `Clone`, so there's no need for an impl of
1887 unsafe impl<T: ?Sized> IsZero for Option<&T> {
1889 fn is_zero(&self) -> bool {
1894 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
1896 fn is_zero(&self) -> bool {
1901 ////////////////////////////////////////////////////////////////////////////////
1902 // Common trait implementations for Vec
1903 ////////////////////////////////////////////////////////////////////////////////
1905 #[stable(feature = "rust1", since = "1.0.0")]
1906 impl<T: Clone> Clone for Vec<T> {
1908 fn clone(&self) -> Vec<T> {
1909 <[T]>::to_vec(&**self)
1912 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1913 // required for this method definition, is not available. Instead use the
1914 // `slice::to_vec` function which is only available with cfg(test)
1915 // NB see the slice::hack module in slice.rs for more information
1917 fn clone(&self) -> Vec<T> {
1918 crate::slice::to_vec(&**self)
1921 fn clone_from(&mut self, other: &Vec<T>) {
1922 other.as_slice().clone_into(self);
1926 #[stable(feature = "rust1", since = "1.0.0")]
1927 impl<T: Hash> Hash for Vec<T> {
1929 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1930 Hash::hash(&**self, state)
1934 #[stable(feature = "rust1", since = "1.0.0")]
1935 #[rustc_on_unimplemented(
1936 message = "vector indices are of type `usize` or ranges of `usize`",
1937 label = "vector indices are of type `usize` or ranges of `usize`"
1939 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
1940 type Output = I::Output;
1943 fn index(&self, index: I) -> &Self::Output {
1944 Index::index(&**self, index)
1948 #[stable(feature = "rust1", since = "1.0.0")]
1949 #[rustc_on_unimplemented(
1950 message = "vector indices are of type `usize` or ranges of `usize`",
1951 label = "vector indices are of type `usize` or ranges of `usize`"
1953 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
1955 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1956 IndexMut::index_mut(&mut **self, index)
1960 #[stable(feature = "rust1", since = "1.0.0")]
1961 impl<T> ops::Deref for Vec<T> {
1964 fn deref(&self) -> &[T] {
1965 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
1969 #[stable(feature = "rust1", since = "1.0.0")]
1970 impl<T> ops::DerefMut for Vec<T> {
1971 fn deref_mut(&mut self) -> &mut [T] {
1972 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1976 #[stable(feature = "rust1", since = "1.0.0")]
1977 impl<T> FromIterator<T> for Vec<T> {
1979 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1980 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1984 #[stable(feature = "rust1", since = "1.0.0")]
1985 impl<T> IntoIterator for Vec<T> {
1987 type IntoIter = IntoIter<T>;
1989 /// Creates a consuming iterator, that is, one that moves each value out of
1990 /// the vector (from start to end). The vector cannot be used after calling
1996 /// let v = vec!["a".to_string(), "b".to_string()];
1997 /// for s in v.into_iter() {
1998 /// // s has type String, not &String
1999 /// println!("{}", s);
2003 fn into_iter(self) -> IntoIter<T> {
2005 let mut me = ManuallyDrop::new(self);
2006 let begin = me.as_mut_ptr();
2007 let end = if mem::size_of::<T>() == 0 {
2008 arith_offset(begin as *const i8, me.len() as isize) as *const T
2010 begin.add(me.len()) as *const T
2012 let cap = me.buf.capacity();
2014 buf: NonNull::new_unchecked(begin),
2015 phantom: PhantomData,
2024 #[stable(feature = "rust1", since = "1.0.0")]
2025 impl<'a, T> IntoIterator for &'a Vec<T> {
2027 type IntoIter = slice::Iter<'a, T>;
2029 fn into_iter(self) -> slice::Iter<'a, T> {
2034 #[stable(feature = "rust1", since = "1.0.0")]
2035 impl<'a, T> IntoIterator for &'a mut Vec<T> {
2036 type Item = &'a mut T;
2037 type IntoIter = slice::IterMut<'a, T>;
2039 fn into_iter(self) -> slice::IterMut<'a, T> {
2044 #[stable(feature = "rust1", since = "1.0.0")]
2045 impl<T> Extend<T> for Vec<T> {
2047 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2048 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2052 fn extend_one(&mut self, item: T) {
2057 fn extend_reserve(&mut self, additional: usize) {
2058 self.reserve(additional);
2062 // Specialization trait used for Vec::from_iter and Vec::extend
2063 trait SpecExtend<T, I> {
2064 fn from_iter(iter: I) -> Self;
2065 fn spec_extend(&mut self, iter: I);
2068 impl<T, I> SpecExtend<T, I> for Vec<T>
2070 I: Iterator<Item = T>,
2072 default fn from_iter(mut iterator: I) -> Self {
2073 // Unroll the first iteration, as the vector is going to be
2074 // expanded on this iteration in every case when the iterable is not
2075 // empty, but the loop in extend_desugared() is not going to see the
2076 // vector being full in the few subsequent loop iterations.
2077 // So we get better branch prediction.
2078 let mut vector = match iterator.next() {
2079 None => return Vec::new(),
2081 let (lower, _) = iterator.size_hint();
2082 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2084 ptr::write(vector.as_mut_ptr(), element);
2090 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2094 default fn spec_extend(&mut self, iter: I) {
2095 self.extend_desugared(iter)
2099 impl<T, I> SpecExtend<T, I> for Vec<T>
2101 I: TrustedLen<Item = T>,
2103 default fn from_iter(iterator: I) -> Self {
2104 let mut vector = Vec::new();
2105 vector.spec_extend(iterator);
2109 default fn spec_extend(&mut self, iterator: I) {
2110 // This is the case for a TrustedLen iterator.
2111 let (low, high) = iterator.size_hint();
2112 if let Some(high_value) = high {
2116 "TrustedLen iterator's size hint is not exact: {:?}",
2120 if let Some(additional) = high {
2121 self.reserve(additional);
2123 let mut ptr = self.as_mut_ptr().add(self.len());
2124 let mut local_len = SetLenOnDrop::new(&mut self.len);
2125 iterator.for_each(move |element| {
2126 ptr::write(ptr, element);
2127 ptr = ptr.offset(1);
2128 // NB can't overflow since we would have had to alloc the address space
2129 local_len.increment_len(1);
2133 self.extend_desugared(iterator)
2138 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2139 fn from_iter(iterator: IntoIter<T>) -> Self {
2140 // A common case is passing a vector into a function which immediately
2141 // re-collects into a vector. We can short circuit this if the IntoIter
2142 // has not been advanced at all.
2143 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
2145 let it = ManuallyDrop::new(iterator);
2146 Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap)
2149 let mut vector = Vec::new();
2150 vector.spec_extend(iterator);
2155 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2157 self.append_elements(iterator.as_slice() as _);
2159 iterator.ptr = iterator.end;
2163 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2165 I: Iterator<Item = &'a T>,
2168 default fn from_iter(iterator: I) -> Self {
2169 SpecExtend::from_iter(iterator.cloned())
2172 default fn spec_extend(&mut self, iterator: I) {
2173 self.spec_extend(iterator.cloned())
2177 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2181 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2182 let slice = iterator.as_slice();
2183 self.reserve(slice.len());
2185 let len = self.len();
2186 let dst_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(len), slice.len());
2187 dst_slice.copy_from_slice(slice);
2188 self.set_len(len + slice.len());
2194 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2195 // This is the case for a general iterator.
2197 // This function should be the moral equivalent of:
2199 // for item in iterator {
2202 while let Some(element) = iterator.next() {
2203 let len = self.len();
2204 if len == self.capacity() {
2205 let (lower, _) = iterator.size_hint();
2206 self.reserve(lower.saturating_add(1));
2209 ptr::write(self.as_mut_ptr().add(len), element);
2210 // NB can't overflow since we would have had to alloc the address space
2211 self.set_len(len + 1);
2216 /// Creates a splicing iterator that replaces the specified range in the vector
2217 /// with the given `replace_with` iterator and yields the removed items.
2218 /// `replace_with` does not need to be the same length as `range`.
2220 /// The element range is removed even if the iterator is not consumed until the end.
2222 /// It is unspecified how many elements are removed from the vector
2223 /// if the `Splice` value is leaked.
2225 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2227 /// This is optimal if:
2229 /// * The tail (elements in the vector after `range`) is empty,
2230 /// * or `replace_with` yields fewer elements than `range`’s length
2231 /// * or the lower bound of its `size_hint()` is exact.
2233 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2237 /// Panics if the starting point is greater than the end point or if
2238 /// the end point is greater than the length of the vector.
2243 /// let mut v = vec![1, 2, 3];
2244 /// let new = [7, 8];
2245 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2246 /// assert_eq!(v, &[7, 8, 3]);
2247 /// assert_eq!(u, &[1, 2]);
2250 #[stable(feature = "vec_splice", since = "1.21.0")]
2251 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2253 R: RangeBounds<usize>,
2254 I: IntoIterator<Item = T>,
2256 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2259 /// Creates an iterator which uses a closure to determine if an element should be removed.
2261 /// If the closure returns true, then the element is removed and yielded.
2262 /// If the closure returns false, the element will remain in the vector and will not be yielded
2263 /// by the iterator.
2265 /// Using this method is equivalent to the following code:
2268 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2269 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2271 /// while i != vec.len() {
2272 /// if some_predicate(&mut vec[i]) {
2273 /// let val = vec.remove(i);
2274 /// // your code here
2280 /// # assert_eq!(vec, vec![1, 4, 5]);
2283 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2284 /// because it can backshift the elements of the array in bulk.
2286 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2287 /// regardless of whether you choose to keep or remove it.
2292 /// Splitting an array into evens and odds, reusing the original allocation:
2295 /// #![feature(drain_filter)]
2296 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2298 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2299 /// let odds = numbers;
2301 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2302 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2304 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2305 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2307 F: FnMut(&mut T) -> bool,
2309 let old_len = self.len();
2311 // Guard against us getting leaked (leak amplification)
2316 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2320 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2322 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2323 /// append the entire slice at once.
2325 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2326 #[stable(feature = "extend_ref", since = "1.2.0")]
2327 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2328 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2329 self.spec_extend(iter.into_iter())
2333 fn extend_one(&mut self, &item: &'a T) {
2338 fn extend_reserve(&mut self, additional: usize) {
2339 self.reserve(additional);
2343 macro_rules! __impl_slice_eq1 {
2344 ([$($vars:tt)*] $lhs:ty, $rhs:ty, $($constraints:tt)*) => {
2345 #[stable(feature = "rust1", since = "1.0.0")]
2346 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2352 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2354 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2359 __impl_slice_eq1! { [] Vec<A>, Vec<B>, }
2360 __impl_slice_eq1! { [] Vec<A>, &[B], }
2361 __impl_slice_eq1! { [] Vec<A>, &mut [B], }
2362 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B], A: Clone }
2363 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B], A: Clone }
2364 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B>, A: Clone }
2365 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N], [B; N]: LengthAtMost32 }
2366 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N], [B; N]: LengthAtMost32 }
2368 // NOTE: some less important impls are omitted to reduce code bloat
2369 // FIXME(Centril): Reconsider this?
2370 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], [B; N]: LengthAtMost32 }
2371 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], [B; N]: LengthAtMost32 }
2372 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], [B; N]: LengthAtMost32 }
2373 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], [B; N]: LengthAtMost32 }
2375 /// Implements comparison of vectors, lexicographically.
2376 #[stable(feature = "rust1", since = "1.0.0")]
2377 impl<T: PartialOrd> PartialOrd for Vec<T> {
2379 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2380 PartialOrd::partial_cmp(&**self, &**other)
2384 #[stable(feature = "rust1", since = "1.0.0")]
2385 impl<T: Eq> Eq for Vec<T> {}
2387 /// Implements ordering of vectors, lexicographically.
2388 #[stable(feature = "rust1", since = "1.0.0")]
2389 impl<T: Ord> Ord for Vec<T> {
2391 fn cmp(&self, other: &Vec<T>) -> Ordering {
2392 Ord::cmp(&**self, &**other)
2396 #[stable(feature = "rust1", since = "1.0.0")]
2397 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2398 fn drop(&mut self) {
2401 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2402 // could avoid questions of validity in certain cases
2403 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2405 // RawVec handles deallocation
2409 #[stable(feature = "rust1", since = "1.0.0")]
2410 impl<T> Default for Vec<T> {
2411 /// Creates an empty `Vec<T>`.
2412 fn default() -> Vec<T> {
2417 #[stable(feature = "rust1", since = "1.0.0")]
2418 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2419 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2420 fmt::Debug::fmt(&**self, f)
2424 #[stable(feature = "rust1", since = "1.0.0")]
2425 impl<T> AsRef<Vec<T>> for Vec<T> {
2426 fn as_ref(&self) -> &Vec<T> {
2431 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2432 impl<T> AsMut<Vec<T>> for Vec<T> {
2433 fn as_mut(&mut self) -> &mut Vec<T> {
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 impl<T> AsRef<[T]> for Vec<T> {
2440 fn as_ref(&self) -> &[T] {
2445 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2446 impl<T> AsMut<[T]> for Vec<T> {
2447 fn as_mut(&mut self) -> &mut [T] {
2452 #[stable(feature = "rust1", since = "1.0.0")]
2453 impl<T: Clone> From<&[T]> for Vec<T> {
2455 fn from(s: &[T]) -> Vec<T> {
2459 fn from(s: &[T]) -> Vec<T> {
2460 crate::slice::to_vec(s)
2464 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2465 impl<T: Clone> From<&mut [T]> for Vec<T> {
2467 fn from(s: &mut [T]) -> Vec<T> {
2471 fn from(s: &mut [T]) -> Vec<T> {
2472 crate::slice::to_vec(s)
2476 #[stable(feature = "vec_from_array", since = "1.44.0")]
2477 impl<T, const N: usize> From<[T; N]> for Vec<T>
2479 [T; N]: LengthAtMost32,
2482 fn from(s: [T; N]) -> Vec<T> {
2483 <[T]>::into_vec(box s)
2486 fn from(s: [T; N]) -> Vec<T> {
2487 crate::slice::into_vec(box s)
2491 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2492 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2494 [T]: ToOwned<Owned = Vec<T>>,
2496 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2501 // note: test pulls in libstd, which causes errors here
2503 #[stable(feature = "vec_from_box", since = "1.18.0")]
2504 impl<T> From<Box<[T]>> for Vec<T> {
2505 fn from(s: Box<[T]>) -> Vec<T> {
2510 // note: test pulls in libstd, which causes errors here
2512 #[stable(feature = "box_from_vec", since = "1.20.0")]
2513 impl<T> From<Vec<T>> for Box<[T]> {
2514 fn from(v: Vec<T>) -> Box<[T]> {
2515 v.into_boxed_slice()
2519 #[stable(feature = "rust1", since = "1.0.0")]
2520 impl From<&str> for Vec<u8> {
2521 fn from(s: &str) -> Vec<u8> {
2522 From::from(s.as_bytes())
2526 ////////////////////////////////////////////////////////////////////////////////
2528 ////////////////////////////////////////////////////////////////////////////////
2530 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2531 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2532 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2537 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2538 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2539 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2544 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2545 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2546 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2547 Cow::Borrowed(v.as_slice())
2551 #[stable(feature = "rust1", since = "1.0.0")]
2552 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
2556 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2557 Cow::Owned(FromIterator::from_iter(it))
2561 ////////////////////////////////////////////////////////////////////////////////
2563 ////////////////////////////////////////////////////////////////////////////////
2565 /// An iterator that moves out of a vector.
2567 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
2568 /// by the [`IntoIterator`] trait).
2570 /// [`Vec`]: struct.Vec.html
2571 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2572 #[stable(feature = "rust1", since = "1.0.0")]
2573 pub struct IntoIter<T> {
2575 phantom: PhantomData<T>,
2581 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2582 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2583 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2584 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2588 impl<T> IntoIter<T> {
2589 /// Returns the remaining items of this iterator as a slice.
2594 /// let vec = vec!['a', 'b', 'c'];
2595 /// let mut into_iter = vec.into_iter();
2596 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2597 /// let _ = into_iter.next().unwrap();
2598 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2600 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2601 pub fn as_slice(&self) -> &[T] {
2602 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
2605 /// Returns the remaining items of this iterator as a mutable slice.
2610 /// let vec = vec!['a', 'b', 'c'];
2611 /// let mut into_iter = vec.into_iter();
2612 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2613 /// into_iter.as_mut_slice()[2] = 'z';
2614 /// assert_eq!(into_iter.next().unwrap(), 'a');
2615 /// assert_eq!(into_iter.next().unwrap(), 'b');
2616 /// assert_eq!(into_iter.next().unwrap(), 'z');
2618 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2619 pub fn as_mut_slice(&mut self) -> &mut [T] {
2620 unsafe { &mut *self.as_raw_mut_slice() }
2623 fn as_raw_mut_slice(&mut self) -> *mut [T] {
2624 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
2628 #[stable(feature = "rust1", since = "1.0.0")]
2629 unsafe impl<T: Send> Send for IntoIter<T> {}
2630 #[stable(feature = "rust1", since = "1.0.0")]
2631 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2633 #[stable(feature = "rust1", since = "1.0.0")]
2634 impl<T> Iterator for IntoIter<T> {
2638 fn next(&mut self) -> Option<T> {
2640 if self.ptr as *const _ == self.end {
2643 if mem::size_of::<T>() == 0 {
2644 // purposefully don't use 'ptr.offset' because for
2645 // vectors with 0-size elements this would return the
2647 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2649 // Make up a value of this ZST.
2653 self.ptr = self.ptr.offset(1);
2655 Some(ptr::read(old))
2662 fn size_hint(&self) -> (usize, Option<usize>) {
2663 let exact = if mem::size_of::<T>() == 0 {
2664 (self.end as usize).wrapping_sub(self.ptr as usize)
2666 unsafe { self.end.offset_from(self.ptr) as usize }
2668 (exact, Some(exact))
2672 fn count(self) -> usize {
2677 #[stable(feature = "rust1", since = "1.0.0")]
2678 impl<T> DoubleEndedIterator for IntoIter<T> {
2680 fn next_back(&mut self) -> Option<T> {
2682 if self.end == self.ptr {
2685 if mem::size_of::<T>() == 0 {
2686 // See above for why 'ptr.offset' isn't used
2687 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2689 // Make up a value of this ZST.
2692 self.end = self.end.offset(-1);
2694 Some(ptr::read(self.end))
2701 #[stable(feature = "rust1", since = "1.0.0")]
2702 impl<T> ExactSizeIterator for IntoIter<T> {
2703 fn is_empty(&self) -> bool {
2704 self.ptr == self.end
2708 #[stable(feature = "fused", since = "1.26.0")]
2709 impl<T> FusedIterator for IntoIter<T> {}
2711 #[unstable(feature = "trusted_len", issue = "37572")]
2712 unsafe impl<T> TrustedLen for IntoIter<T> {}
2714 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2715 impl<T: Clone> Clone for IntoIter<T> {
2716 fn clone(&self) -> IntoIter<T> {
2717 self.as_slice().to_owned().into_iter()
2721 #[stable(feature = "rust1", since = "1.0.0")]
2722 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2723 fn drop(&mut self) {
2724 struct DropGuard<'a, T>(&'a mut IntoIter<T>);
2726 impl<T> Drop for DropGuard<'_, T> {
2727 fn drop(&mut self) {
2728 // RawVec handles deallocation
2729 let _ = unsafe { RawVec::from_raw_parts(self.0.buf.as_ptr(), self.0.cap) };
2733 let guard = DropGuard(self);
2734 // destroy the remaining elements
2736 ptr::drop_in_place(guard.0.as_raw_mut_slice());
2738 // now `guard` will be dropped and do the rest
2742 /// A draining iterator for `Vec<T>`.
2744 /// This `struct` is created by the [`drain`] method on [`Vec`].
2746 /// [`drain`]: struct.Vec.html#method.drain
2747 /// [`Vec`]: struct.Vec.html
2748 #[stable(feature = "drain", since = "1.6.0")]
2749 pub struct Drain<'a, T: 'a> {
2750 /// Index of tail to preserve
2754 /// Current remaining range to remove
2755 iter: slice::Iter<'a, T>,
2756 vec: NonNull<Vec<T>>,
2759 #[stable(feature = "collection_debug", since = "1.17.0")]
2760 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2761 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2762 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
2766 impl<'a, T> Drain<'a, T> {
2767 /// Returns the remaining items of this iterator as a slice.
2772 /// # #![feature(vec_drain_as_slice)]
2773 /// let mut vec = vec!['a', 'b', 'c'];
2774 /// let mut drain = vec.drain(..);
2775 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
2776 /// let _ = drain.next().unwrap();
2777 /// assert_eq!(drain.as_slice(), &['b', 'c']);
2779 #[unstable(feature = "vec_drain_as_slice", reason = "recently added", issue = "58957")]
2780 pub fn as_slice(&self) -> &[T] {
2781 self.iter.as_slice()
2785 #[stable(feature = "drain", since = "1.6.0")]
2786 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2787 #[stable(feature = "drain", since = "1.6.0")]
2788 unsafe impl<T: Send> Send for Drain<'_, T> {}
2790 #[stable(feature = "drain", since = "1.6.0")]
2791 impl<T> Iterator for Drain<'_, T> {
2795 fn next(&mut self) -> Option<T> {
2796 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2799 fn size_hint(&self) -> (usize, Option<usize>) {
2800 self.iter.size_hint()
2804 #[stable(feature = "drain", since = "1.6.0")]
2805 impl<T> DoubleEndedIterator for Drain<'_, T> {
2807 fn next_back(&mut self) -> Option<T> {
2808 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2812 #[stable(feature = "drain", since = "1.6.0")]
2813 impl<T> Drop for Drain<'_, T> {
2814 fn drop(&mut self) {
2815 /// Continues dropping the remaining elements in the `Drain`, then moves back the
2816 /// un-`Drain`ed elements to restore the original `Vec`.
2817 struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>);
2819 impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> {
2820 fn drop(&mut self) {
2821 // Continue the same loop we have below. If the loop already finished, this does
2823 self.0.for_each(drop);
2825 if self.0.tail_len > 0 {
2827 let source_vec = self.0.vec.as_mut();
2828 // memmove back untouched tail, update to new length
2829 let start = source_vec.len();
2830 let tail = self.0.tail_start;
2832 let src = source_vec.as_ptr().add(tail);
2833 let dst = source_vec.as_mut_ptr().add(start);
2834 ptr::copy(src, dst, self.0.tail_len);
2836 source_vec.set_len(start + self.0.tail_len);
2842 // exhaust self first
2843 while let Some(item) = self.next() {
2844 let guard = DropGuard(self);
2849 // Drop a `DropGuard` to move back the non-drained tail of `self`.
2854 #[stable(feature = "drain", since = "1.6.0")]
2855 impl<T> ExactSizeIterator for Drain<'_, T> {
2856 fn is_empty(&self) -> bool {
2857 self.iter.is_empty()
2861 #[unstable(feature = "trusted_len", issue = "37572")]
2862 unsafe impl<T> TrustedLen for Drain<'_, T> {}
2864 #[stable(feature = "fused", since = "1.26.0")]
2865 impl<T> FusedIterator for Drain<'_, T> {}
2867 /// A splicing iterator for `Vec`.
2869 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2870 /// documentation for more.
2872 /// [`splice()`]: struct.Vec.html#method.splice
2873 /// [`Vec`]: struct.Vec.html
2875 #[stable(feature = "vec_splice", since = "1.21.0")]
2876 pub struct Splice<'a, I: Iterator + 'a> {
2877 drain: Drain<'a, I::Item>,
2881 #[stable(feature = "vec_splice", since = "1.21.0")]
2882 impl<I: Iterator> Iterator for Splice<'_, I> {
2883 type Item = I::Item;
2885 fn next(&mut self) -> Option<Self::Item> {
2889 fn size_hint(&self) -> (usize, Option<usize>) {
2890 self.drain.size_hint()
2894 #[stable(feature = "vec_splice", since = "1.21.0")]
2895 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
2896 fn next_back(&mut self) -> Option<Self::Item> {
2897 self.drain.next_back()
2901 #[stable(feature = "vec_splice", since = "1.21.0")]
2902 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
2904 #[stable(feature = "vec_splice", since = "1.21.0")]
2905 impl<I: Iterator> Drop for Splice<'_, I> {
2906 fn drop(&mut self) {
2907 self.drain.by_ref().for_each(drop);
2910 if self.drain.tail_len == 0 {
2911 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2915 // First fill the range left by drain().
2916 if !self.drain.fill(&mut self.replace_with) {
2920 // There may be more elements. Use the lower bound as an estimate.
2921 // FIXME: Is the upper bound a better guess? Or something else?
2922 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2923 if lower_bound > 0 {
2924 self.drain.move_tail(lower_bound);
2925 if !self.drain.fill(&mut self.replace_with) {
2930 // Collect any remaining elements.
2931 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2932 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2933 // Now we have an exact count.
2934 if collected.len() > 0 {
2935 self.drain.move_tail(collected.len());
2936 let filled = self.drain.fill(&mut collected);
2937 debug_assert!(filled);
2938 debug_assert_eq!(collected.len(), 0);
2941 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2945 /// Private helper methods for `Splice::drop`
2946 impl<T> Drain<'_, T> {
2947 /// The range from `self.vec.len` to `self.tail_start` contains elements
2948 /// that have been moved out.
2949 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2950 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2951 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
2952 let vec = self.vec.as_mut();
2953 let range_start = vec.len;
2954 let range_end = self.tail_start;
2956 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start);
2958 for place in range_slice {
2959 if let Some(new_item) = replace_with.next() {
2960 ptr::write(place, new_item);
2969 /// Makes room for inserting more elements before the tail.
2970 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2971 let vec = self.vec.as_mut();
2972 let used_capacity = self.tail_start + self.tail_len;
2973 vec.buf.reserve(used_capacity, extra_capacity);
2975 let new_tail_start = self.tail_start + extra_capacity;
2976 let src = vec.as_ptr().add(self.tail_start);
2977 let dst = vec.as_mut_ptr().add(new_tail_start);
2978 ptr::copy(src, dst, self.tail_len);
2979 self.tail_start = new_tail_start;
2983 /// An iterator produced by calling `drain_filter` on Vec.
2984 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2986 pub struct DrainFilter<'a, T, F>
2988 F: FnMut(&mut T) -> bool,
2990 vec: &'a mut Vec<T>,
2991 /// The index of the item that will be inspected by the next call to `next`.
2993 /// The number of items that have been drained (removed) thus far.
2995 /// The original length of `vec` prior to draining.
2997 /// The filter test predicate.
2999 /// A flag that indicates a panic has occurred in the filter test prodicate.
3000 /// This is used as a hint in the drop implementation to prevent consumption
3001 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3002 /// backshifted in the `vec`, but no further items will be dropped or
3003 /// tested by the filter predicate.
3007 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3008 impl<T, F> Iterator for DrainFilter<'_, T, F>
3010 F: FnMut(&mut T) -> bool,
3014 fn next(&mut self) -> Option<T> {
3016 while self.idx < self.old_len {
3018 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3019 self.panic_flag = true;
3020 let drained = (self.pred)(&mut v[i]);
3021 self.panic_flag = false;
3022 // Update the index *after* the predicate is called. If the index
3023 // is updated prior and the predicate panics, the element at this
3024 // index would be leaked.
3028 return Some(ptr::read(&v[i]));
3029 } else if self.del > 0 {
3031 let src: *const T = &v[i];
3032 let dst: *mut T = &mut v[i - del];
3033 ptr::copy_nonoverlapping(src, dst, 1);
3040 fn size_hint(&self) -> (usize, Option<usize>) {
3041 (0, Some(self.old_len - self.idx))
3045 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3046 impl<T, F> Drop for DrainFilter<'_, T, F>
3048 F: FnMut(&mut T) -> bool,
3050 fn drop(&mut self) {
3051 struct BackshiftOnDrop<'a, 'b, T, F>
3053 F: FnMut(&mut T) -> bool,
3055 drain: &'b mut DrainFilter<'a, T, F>,
3058 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
3060 F: FnMut(&mut T) -> bool,
3062 fn drop(&mut self) {
3064 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3065 // This is a pretty messed up state, and there isn't really an
3066 // obviously right thing to do. We don't want to keep trying
3067 // to execute `pred`, so we just backshift all the unprocessed
3068 // elements and tell the vec that they still exist. The backshift
3069 // is required to prevent a double-drop of the last successfully
3070 // drained item prior to a panic in the predicate.
3071 let ptr = self.drain.vec.as_mut_ptr();
3072 let src = ptr.add(self.drain.idx);
3073 let dst = src.sub(self.drain.del);
3074 let tail_len = self.drain.old_len - self.drain.idx;
3075 src.copy_to(dst, tail_len);
3077 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3082 let backshift = BackshiftOnDrop { drain: self };
3084 // Attempt to consume any remaining elements if the filter predicate
3085 // has not yet panicked. We'll backshift any remaining elements
3086 // whether we've already panicked or if the consumption here panics.
3087 if !backshift.drain.panic_flag {
3088 backshift.drain.for_each(drop);