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::{Hash, Hasher};
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);
346 /// assert_eq!(vec.capacity(), 10);
348 /// // These are all done without reallocating...
352 /// assert_eq!(vec.len(), 10);
353 /// assert_eq!(vec.capacity(), 10);
355 /// // ...but this may make the vector reallocate
357 /// assert_eq!(vec.len(), 11);
358 /// assert!(vec.capacity() >= 11);
361 #[stable(feature = "rust1", since = "1.0.0")]
362 pub fn with_capacity(capacity: usize) -> Vec<T> {
363 Vec { buf: RawVec::with_capacity(capacity), len: 0 }
366 /// Decomposes a `Vec<T>` into its raw components.
368 /// Returns the raw pointer to the underlying data, the length of
369 /// the vector (in elements), and the allocated capacity of the
370 /// data (in elements). These are the same arguments in the same
371 /// order as the arguments to [`from_raw_parts`].
373 /// After calling this function, the caller is responsible for the
374 /// memory previously managed by the `Vec`. The only way to do
375 /// this is to convert the raw pointer, length, and capacity back
376 /// into a `Vec` with the [`from_raw_parts`] function, allowing
377 /// the destructor to perform the cleanup.
379 /// [`from_raw_parts`]: #method.from_raw_parts
384 /// #![feature(vec_into_raw_parts)]
385 /// let v: Vec<i32> = vec![-1, 0, 1];
387 /// let (ptr, len, cap) = v.into_raw_parts();
389 /// let rebuilt = unsafe {
390 /// // We can now make changes to the components, such as
391 /// // transmuting the raw pointer to a compatible type.
392 /// let ptr = ptr as *mut u32;
394 /// Vec::from_raw_parts(ptr, len, cap)
396 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
398 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
399 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
400 let mut me = ManuallyDrop::new(self);
401 (me.as_mut_ptr(), me.len(), me.capacity())
404 /// Creates a `Vec<T>` directly from the raw components of another vector.
408 /// This is highly unsafe, due to the number of invariants that aren't
411 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
412 /// (at least, it's highly likely to be incorrect if it wasn't).
413 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
414 /// (`T` having a less strict alignment is not sufficient, the alignment really
415 /// needs to be equal to satsify the [`dealloc`] requirement that memory must be
416 /// allocated and deallocated with the same layout.)
417 /// * `length` needs to be less than or equal to `capacity`.
418 /// * `capacity` needs to be the capacity that the pointer was allocated with.
420 /// Violating these may cause problems like corrupting the allocator's
421 /// internal data structures. For example it is **not** safe
422 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
423 /// It's also not safe to build one from a `Vec<u16>` and its length, because
424 /// the allocator cares about the alignment, and these two types have different
425 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
426 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
428 /// The ownership of `ptr` is effectively transferred to the
429 /// `Vec<T>` which may then deallocate, reallocate or change the
430 /// contents of memory pointed to by the pointer at will. Ensure
431 /// that nothing else uses the pointer after calling this
434 /// [`String`]: ../../std/string/struct.String.html
435 /// [`dealloc`]: ../../alloc/alloc/trait.GlobalAlloc.html#tymethod.dealloc
443 /// let v = vec![1, 2, 3];
445 // FIXME Update this when vec_into_raw_parts is stabilized
446 /// // Prevent running `v`'s destructor so we are in complete control
447 /// // of the allocation.
448 /// let mut v = mem::ManuallyDrop::new(v);
450 /// // Pull out the various important pieces of information about `v`
451 /// let p = v.as_mut_ptr();
452 /// let len = v.len();
453 /// let cap = v.capacity();
456 /// // Overwrite memory with 4, 5, 6
457 /// for i in 0..len as isize {
458 /// ptr::write(p.offset(i), 4 + i);
461 /// // Put everything back together into a Vec
462 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
463 /// assert_eq!(rebuilt, [4, 5, 6]);
466 #[stable(feature = "rust1", since = "1.0.0")]
467 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
468 unsafe { Vec { buf: RawVec::from_raw_parts(ptr, capacity), len: length } }
471 /// Returns the number of elements the vector can hold without
477 /// let vec: Vec<i32> = Vec::with_capacity(10);
478 /// assert_eq!(vec.capacity(), 10);
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub fn capacity(&self) -> usize {
486 /// Reserves capacity for at least `additional` more elements to be inserted
487 /// in the given `Vec<T>`. The collection may reserve more space to avoid
488 /// frequent reallocations. After calling `reserve`, capacity will be
489 /// greater than or equal to `self.len() + additional`. Does nothing if
490 /// capacity is already sufficient.
494 /// Panics if the new capacity exceeds `isize::MAX` bytes.
499 /// let mut vec = vec![1];
501 /// assert!(vec.capacity() >= 11);
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn reserve(&mut self, additional: usize) {
505 self.buf.reserve(self.len, additional);
508 /// Reserves the minimum capacity for exactly `additional` more elements to
509 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
510 /// capacity will be greater than or equal to `self.len() + additional`.
511 /// Does nothing if the capacity is already sufficient.
513 /// Note that the allocator may give the collection more space than it
514 /// requests. Therefore, capacity can not be relied upon to be precisely
515 /// minimal. Prefer `reserve` if future insertions are expected.
519 /// Panics if the new capacity overflows `usize`.
524 /// let mut vec = vec![1];
525 /// vec.reserve_exact(10);
526 /// assert!(vec.capacity() >= 11);
528 #[stable(feature = "rust1", since = "1.0.0")]
529 pub fn reserve_exact(&mut self, additional: usize) {
530 self.buf.reserve_exact(self.len, additional);
533 /// Tries to reserve capacity for at least `additional` more elements to be inserted
534 /// in the given `Vec<T>`. The collection may reserve more space to avoid
535 /// frequent reallocations. After calling `reserve`, capacity will be
536 /// greater than or equal to `self.len() + additional`. Does nothing if
537 /// capacity is already sufficient.
541 /// If the capacity overflows, or the allocator reports a failure, then an error
547 /// #![feature(try_reserve)]
548 /// use std::collections::TryReserveError;
550 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
551 /// let mut output = Vec::new();
553 /// // Pre-reserve the memory, exiting if we can't
554 /// output.try_reserve(data.len())?;
556 /// // Now we know this can't OOM in the middle of our complex work
557 /// output.extend(data.iter().map(|&val| {
558 /// val * 2 + 5 // very complicated
563 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
565 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
566 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
567 self.buf.try_reserve(self.len, additional)
570 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
571 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
572 /// capacity will be greater than or equal to `self.len() + additional`.
573 /// Does nothing if the capacity is already sufficient.
575 /// Note that the allocator may give the collection more space than it
576 /// requests. Therefore, capacity can not be relied upon to be precisely
577 /// minimal. Prefer `reserve` if future insertions are expected.
581 /// If the capacity overflows, or the allocator reports a failure, then an error
587 /// #![feature(try_reserve)]
588 /// use std::collections::TryReserveError;
590 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
591 /// let mut output = Vec::new();
593 /// // Pre-reserve the memory, exiting if we can't
594 /// output.try_reserve(data.len())?;
596 /// // Now we know this can't OOM in the middle of our complex work
597 /// output.extend(data.iter().map(|&val| {
598 /// val * 2 + 5 // very complicated
603 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
605 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
606 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
607 self.buf.try_reserve_exact(self.len, additional)
610 /// Shrinks the capacity of the vector as much as possible.
612 /// It will drop down as close as possible to the length but the allocator
613 /// may still inform the vector that there is space for a few more elements.
618 /// let mut vec = Vec::with_capacity(10);
619 /// vec.extend([1, 2, 3].iter().cloned());
620 /// assert_eq!(vec.capacity(), 10);
621 /// vec.shrink_to_fit();
622 /// assert!(vec.capacity() >= 3);
624 #[stable(feature = "rust1", since = "1.0.0")]
625 pub fn shrink_to_fit(&mut self) {
626 if self.capacity() != self.len {
627 self.buf.shrink_to_fit(self.len);
631 /// Shrinks the capacity of the vector with a lower bound.
633 /// The capacity will remain at least as large as both the length
634 /// and the supplied value.
638 /// Panics if the current capacity is smaller than the supplied
639 /// minimum capacity.
644 /// #![feature(shrink_to)]
645 /// let mut vec = Vec::with_capacity(10);
646 /// vec.extend([1, 2, 3].iter().cloned());
647 /// assert_eq!(vec.capacity(), 10);
648 /// vec.shrink_to(4);
649 /// assert!(vec.capacity() >= 4);
650 /// vec.shrink_to(0);
651 /// assert!(vec.capacity() >= 3);
653 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
654 pub fn shrink_to(&mut self, min_capacity: usize) {
655 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
658 /// Converts the vector into [`Box<[T]>`][owned slice].
660 /// Note that this will drop any excess capacity.
662 /// [owned slice]: ../../std/boxed/struct.Box.html
667 /// let v = vec![1, 2, 3];
669 /// let slice = v.into_boxed_slice();
672 /// Any excess capacity is removed:
675 /// let mut vec = Vec::with_capacity(10);
676 /// vec.extend([1, 2, 3].iter().cloned());
678 /// assert_eq!(vec.capacity(), 10);
679 /// let slice = vec.into_boxed_slice();
680 /// assert_eq!(slice.into_vec().capacity(), 3);
682 #[stable(feature = "rust1", since = "1.0.0")]
683 pub fn into_boxed_slice(mut self) -> Box<[T]> {
685 self.shrink_to_fit();
686 let me = ManuallyDrop::new(self);
687 let buf = ptr::read(&me.buf);
689 buf.into_box(len).assume_init()
693 /// Shortens the vector, keeping the first `len` elements and dropping
696 /// If `len` is greater than the vector's current length, this has no
699 /// The [`drain`] method can emulate `truncate`, but causes the excess
700 /// elements to be returned instead of dropped.
702 /// Note that this method has no effect on the allocated capacity
707 /// Truncating a five element vector to two elements:
710 /// let mut vec = vec![1, 2, 3, 4, 5];
712 /// assert_eq!(vec, [1, 2]);
715 /// No truncation occurs when `len` is greater than the vector's current
719 /// let mut vec = vec![1, 2, 3];
721 /// assert_eq!(vec, [1, 2, 3]);
724 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
728 /// let mut vec = vec![1, 2, 3];
730 /// assert_eq!(vec, []);
733 /// [`clear`]: #method.clear
734 /// [`drain`]: #method.drain
735 #[stable(feature = "rust1", since = "1.0.0")]
736 pub fn truncate(&mut self, len: usize) {
737 // This is safe because:
739 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
740 // case avoids creating an invalid slice, and
741 // * the `len` of the vector is shrunk before calling `drop_in_place`,
742 // such that no value will be dropped twice in case `drop_in_place`
743 // were to panic once (if it panics twice, the program aborts).
748 let remaining_len = self.len - len;
749 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
751 ptr::drop_in_place(s);
755 /// Extracts a slice containing the entire vector.
757 /// Equivalent to `&s[..]`.
762 /// use std::io::{self, Write};
763 /// let buffer = vec![1, 2, 3, 5, 8];
764 /// io::sink().write(buffer.as_slice()).unwrap();
767 #[stable(feature = "vec_as_slice", since = "1.7.0")]
768 pub fn as_slice(&self) -> &[T] {
772 /// Extracts a mutable slice of the entire vector.
774 /// Equivalent to `&mut s[..]`.
779 /// use std::io::{self, Read};
780 /// let mut buffer = vec![0; 3];
781 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
784 #[stable(feature = "vec_as_slice", since = "1.7.0")]
785 pub fn as_mut_slice(&mut self) -> &mut [T] {
789 /// Returns a raw pointer to the vector's buffer.
791 /// The caller must ensure that the vector outlives the pointer this
792 /// function returns, or else it will end up pointing to garbage.
793 /// Modifying the vector may cause its buffer to be reallocated,
794 /// which would also make any pointers to it invalid.
796 /// The caller must also ensure that the memory the pointer (non-transitively) points to
797 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
798 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
803 /// let x = vec![1, 2, 4];
804 /// let x_ptr = x.as_ptr();
807 /// for i in 0..x.len() {
808 /// assert_eq!(*x_ptr.add(i), 1 << i);
813 /// [`as_mut_ptr`]: #method.as_mut_ptr
814 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
816 pub fn as_ptr(&self) -> *const T {
817 // We shadow the slice method of the same name to avoid going through
818 // `deref`, which creates an intermediate reference.
819 let ptr = self.buf.ptr();
821 assume(!ptr.is_null());
826 /// Returns an unsafe mutable pointer to the vector's buffer.
828 /// The caller must ensure that the vector outlives the pointer this
829 /// function returns, or else it will end up pointing to garbage.
830 /// Modifying the vector may cause its buffer to be reallocated,
831 /// which would also make any pointers to it invalid.
836 /// // Allocate vector big enough for 4 elements.
838 /// let mut x: Vec<i32> = Vec::with_capacity(size);
839 /// let x_ptr = x.as_mut_ptr();
841 /// // Initialize elements via raw pointer writes, then set length.
843 /// for i in 0..size {
844 /// *x_ptr.add(i) = i as i32;
848 /// assert_eq!(&*x, &[0,1,2,3]);
850 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
852 pub fn as_mut_ptr(&mut self) -> *mut T {
853 // We shadow the slice method of the same name to avoid going through
854 // `deref_mut`, which creates an intermediate reference.
855 let ptr = self.buf.ptr();
857 assume(!ptr.is_null());
862 /// Forces the length of the vector to `new_len`.
864 /// This is a low-level operation that maintains none of the normal
865 /// invariants of the type. Normally changing the length of a vector
866 /// is done using one of the safe operations instead, such as
867 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
869 /// [`truncate`]: #method.truncate
870 /// [`resize`]: #method.resize
871 /// [`extend`]: ../../std/iter/trait.Extend.html#tymethod.extend
872 /// [`clear`]: #method.clear
876 /// - `new_len` must be less than or equal to [`capacity()`].
877 /// - The elements at `old_len..new_len` must be initialized.
879 /// [`capacity()`]: #method.capacity
883 /// This method can be useful for situations in which the vector
884 /// is serving as a buffer for other code, particularly over FFI:
887 /// # #![allow(dead_code)]
888 /// # // This is just a minimal skeleton for the doc example;
889 /// # // don't use this as a starting point for a real library.
890 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
891 /// # const Z_OK: i32 = 0;
893 /// # fn deflateGetDictionary(
894 /// # strm: *mut std::ffi::c_void,
895 /// # dictionary: *mut u8,
896 /// # dictLength: *mut usize,
899 /// # impl StreamWrapper {
900 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
901 /// // Per the FFI method's docs, "32768 bytes is always enough".
902 /// let mut dict = Vec::with_capacity(32_768);
903 /// let mut dict_length = 0;
904 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
905 /// // 1. `dict_length` elements were initialized.
906 /// // 2. `dict_length` <= the capacity (32_768)
907 /// // which makes `set_len` safe to call.
909 /// // Make the FFI call...
910 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
912 /// // ...and update the length to what was initialized.
913 /// dict.set_len(dict_length);
923 /// While the following example is sound, there is a memory leak since
924 /// the inner vectors were not freed prior to the `set_len` call:
927 /// let mut vec = vec![vec![1, 0, 0],
931 /// // 1. `old_len..0` is empty so no elements need to be initialized.
932 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
938 /// Normally, here, one would use [`clear`] instead to correctly drop
939 /// the contents and thus not leak memory.
941 #[stable(feature = "rust1", since = "1.0.0")]
942 pub unsafe fn set_len(&mut self, new_len: usize) {
943 debug_assert!(new_len <= self.capacity());
948 /// Removes an element from the vector and returns it.
950 /// The removed element is replaced by the last element of the vector.
952 /// This does not preserve ordering, but is O(1).
956 /// Panics if `index` is out of bounds.
961 /// let mut v = vec!["foo", "bar", "baz", "qux"];
963 /// assert_eq!(v.swap_remove(1), "bar");
964 /// assert_eq!(v, ["foo", "qux", "baz"]);
966 /// assert_eq!(v.swap_remove(0), "foo");
967 /// assert_eq!(v, ["baz", "qux"]);
970 #[stable(feature = "rust1", since = "1.0.0")]
971 pub fn swap_remove(&mut self, index: usize) -> T {
974 fn assert_failed(index: usize, len: usize) -> ! {
975 panic!("swap_remove index (is {}) should be < len (is {})", index, len);
978 let len = self.len();
980 assert_failed(index, len);
983 // We replace self[index] with the last element. Note that if the
984 // bounds check above succeeds there must be a last element (which
985 // can be self[index] itself).
986 let last = ptr::read(self.as_ptr().add(len - 1));
987 let hole = self.as_mut_ptr().add(index);
988 self.set_len(len - 1);
989 ptr::replace(hole, last)
993 /// Inserts an element at position `index` within the vector, shifting all
994 /// elements after it to the right.
998 /// Panics if `index > len`.
1003 /// let mut vec = vec![1, 2, 3];
1004 /// vec.insert(1, 4);
1005 /// assert_eq!(vec, [1, 4, 2, 3]);
1006 /// vec.insert(4, 5);
1007 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1009 #[stable(feature = "rust1", since = "1.0.0")]
1010 pub fn insert(&mut self, index: usize, element: T) {
1013 fn assert_failed(index: usize, len: usize) -> ! {
1014 panic!("insertion index (is {}) should be <= len (is {})", index, len);
1017 let len = self.len();
1019 assert_failed(index, len);
1022 // space for the new element
1023 if len == self.buf.capacity() {
1029 // The spot to put the new value
1031 let p = self.as_mut_ptr().add(index);
1032 // Shift everything over to make space. (Duplicating the
1033 // `index`th element into two consecutive places.)
1034 ptr::copy(p, p.offset(1), len - index);
1035 // Write it in, overwriting the first copy of the `index`th
1037 ptr::write(p, element);
1039 self.set_len(len + 1);
1043 /// Removes and returns the element at position `index` within the vector,
1044 /// shifting all elements after it to the left.
1048 /// Panics if `index` is out of bounds.
1053 /// let mut v = vec![1, 2, 3];
1054 /// assert_eq!(v.remove(1), 2);
1055 /// assert_eq!(v, [1, 3]);
1057 #[stable(feature = "rust1", since = "1.0.0")]
1058 pub fn remove(&mut self, index: usize) -> T {
1061 fn assert_failed(index: usize, len: usize) -> ! {
1062 panic!("removal index (is {}) should be < len (is {})", index, len);
1065 let len = self.len();
1067 assert_failed(index, len);
1073 // the place we are taking from.
1074 let ptr = self.as_mut_ptr().add(index);
1075 // copy it out, unsafely having a copy of the value on
1076 // the stack and in the vector at the same time.
1077 ret = ptr::read(ptr);
1079 // Shift everything down to fill in that spot.
1080 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1082 self.set_len(len - 1);
1087 /// Retains only the elements specified by the predicate.
1089 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1090 /// This method operates in place, visiting each element exactly once in the
1091 /// original order, and preserves the order of the retained elements.
1096 /// let mut vec = vec![1, 2, 3, 4];
1097 /// vec.retain(|&x| x % 2 == 0);
1098 /// assert_eq!(vec, [2, 4]);
1101 /// The exact order may be useful for tracking external state, like an index.
1104 /// let mut vec = vec![1, 2, 3, 4, 5];
1105 /// let keep = [false, true, true, false, true];
1107 /// vec.retain(|_| (keep[i], i += 1).0);
1108 /// assert_eq!(vec, [2, 3, 5]);
1110 #[stable(feature = "rust1", since = "1.0.0")]
1111 pub fn retain<F>(&mut self, mut f: F)
1113 F: FnMut(&T) -> bool,
1115 let len = self.len();
1118 let v = &mut **self;
1129 self.truncate(len - del);
1133 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1136 /// If the vector is sorted, this removes all duplicates.
1141 /// let mut vec = vec![10, 20, 21, 30, 20];
1143 /// vec.dedup_by_key(|i| *i / 10);
1145 /// assert_eq!(vec, [10, 20, 30, 20]);
1147 #[stable(feature = "dedup_by", since = "1.16.0")]
1149 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1151 F: FnMut(&mut T) -> K,
1154 self.dedup_by(|a, b| key(a) == key(b))
1157 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1160 /// The `same_bucket` function is passed references to two elements from the vector and
1161 /// must determine if the elements compare equal. The elements are passed in opposite order
1162 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1164 /// If the vector is sorted, this removes all duplicates.
1169 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1171 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1173 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1175 #[stable(feature = "dedup_by", since = "1.16.0")]
1176 pub fn dedup_by<F>(&mut self, same_bucket: F)
1178 F: FnMut(&mut T, &mut T) -> bool,
1181 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1187 /// Appends an element to the back of a collection.
1191 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1196 /// let mut vec = vec![1, 2];
1198 /// assert_eq!(vec, [1, 2, 3]);
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 pub fn push(&mut self, value: T) {
1203 // This will panic or abort if we would allocate > isize::MAX bytes
1204 // or if the length increment would overflow for zero-sized types.
1205 if self.len == self.buf.capacity() {
1209 let end = self.as_mut_ptr().add(self.len);
1210 ptr::write(end, value);
1215 /// Removes the last element from a vector and returns it, or [`None`] if it
1218 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1223 /// let mut vec = vec![1, 2, 3];
1224 /// assert_eq!(vec.pop(), Some(3));
1225 /// assert_eq!(vec, [1, 2]);
1228 #[stable(feature = "rust1", since = "1.0.0")]
1229 pub fn pop(&mut self) -> Option<T> {
1235 Some(ptr::read(self.as_ptr().add(self.len())))
1240 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1244 /// Panics if the number of elements in the vector overflows a `usize`.
1249 /// let mut vec = vec![1, 2, 3];
1250 /// let mut vec2 = vec![4, 5, 6];
1251 /// vec.append(&mut vec2);
1252 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1253 /// assert_eq!(vec2, []);
1256 #[stable(feature = "append", since = "1.4.0")]
1257 pub fn append(&mut self, other: &mut Self) {
1259 self.append_elements(other.as_slice() as _);
1264 /// Appends elements to `Self` from other buffer.
1266 unsafe fn append_elements(&mut self, other: *const [T]) {
1267 let count = unsafe { (*other).len() };
1268 self.reserve(count);
1269 let len = self.len();
1270 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1274 /// Creates a draining iterator that removes the specified range in the vector
1275 /// and yields the removed items.
1277 /// The element range is removed even if the iterator is only partially
1278 /// consumed or not consumed at all.
1280 /// Note: Be aware that if the iterator is leaked (eg: [`mem::forget`]), it
1281 /// cancels this property so it is unspecified how many elements are removed
1282 /// from the vector in this case.
1286 /// Panics if the starting point is greater than the end point or if
1287 /// the end point is greater than the length of the vector.
1292 /// let mut v = vec![1, 2, 3];
1293 /// let u: Vec<_> = v.drain(1..).collect();
1294 /// assert_eq!(v, &[1]);
1295 /// assert_eq!(u, &[2, 3]);
1297 /// // A full range clears the vector
1299 /// assert_eq!(v, &[]);
1301 #[stable(feature = "drain", since = "1.6.0")]
1302 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T>
1304 R: RangeBounds<usize>,
1308 // When the Drain is first created, it shortens the length of
1309 // the source vector to make sure no uninitialized or moved-from elements
1310 // are accessible at all if the Drain's destructor never gets to run.
1312 // Drain will ptr::read out the values to remove.
1313 // When finished, remaining tail of the vec is copied back to cover
1314 // the hole, and the vector length is restored to the new length.
1316 let len = self.len();
1317 let start = match range.start_bound() {
1319 Excluded(&n) => n + 1,
1322 let end = match range.end_bound() {
1323 Included(&n) => n + 1,
1330 fn start_assert_failed(start: usize, end: usize) -> ! {
1331 panic!("start drain index (is {}) should be <= end drain index (is {})", start, end);
1336 fn end_assert_failed(end: usize, len: usize) -> ! {
1337 panic!("end drain index (is {}) should be <= len (is {})", end, len);
1341 start_assert_failed(start, end);
1344 end_assert_failed(end, len);
1348 // set self.vec length's to start, to be safe in case Drain is leaked
1349 self.set_len(start);
1350 // Use the borrow in the IterMut to indicate borrowing behavior of the
1351 // whole Drain iterator (like &mut T).
1352 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1355 tail_len: len - end,
1356 iter: range_slice.iter(),
1357 vec: NonNull::from(self),
1362 /// Clears the vector, removing all values.
1364 /// Note that this method has no effect on the allocated capacity
1370 /// let mut v = vec![1, 2, 3];
1374 /// assert!(v.is_empty());
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 pub fn clear(&mut self) {
1382 /// Returns the number of elements in the vector, also referred to
1383 /// as its 'length'.
1388 /// let a = vec![1, 2, 3];
1389 /// assert_eq!(a.len(), 3);
1392 #[stable(feature = "rust1", since = "1.0.0")]
1393 pub fn len(&self) -> usize {
1397 /// Returns `true` if the vector contains no elements.
1402 /// let mut v = Vec::new();
1403 /// assert!(v.is_empty());
1406 /// assert!(!v.is_empty());
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 pub fn is_empty(&self) -> bool {
1413 /// Splits the collection into two at the given index.
1415 /// Returns a newly allocated vector containing the elements in the range
1416 /// `[at, len)`. After the call, the original vector will be left containing
1417 /// the elements `[0, at)` with its previous capacity unchanged.
1421 /// Panics if `at > len`.
1426 /// let mut vec = vec![1,2,3];
1427 /// let vec2 = vec.split_off(1);
1428 /// assert_eq!(vec, [1]);
1429 /// assert_eq!(vec2, [2, 3]);
1432 #[must_use = "use `.truncate()` if you don't need the other half"]
1433 #[stable(feature = "split_off", since = "1.4.0")]
1434 pub fn split_off(&mut self, at: usize) -> Self {
1437 fn assert_failed(at: usize, len: usize) -> ! {
1438 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1441 if at > self.len() {
1442 assert_failed(at, self.len());
1445 let other_len = self.len - at;
1446 let mut other = Vec::with_capacity(other_len);
1448 // Unsafely `set_len` and copy items to `other`.
1451 other.set_len(other_len);
1453 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1458 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1460 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1461 /// difference, with each additional slot filled with the result of
1462 /// calling the closure `f`. The return values from `f` will end up
1463 /// in the `Vec` in the order they have been generated.
1465 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1467 /// This method uses a closure to create new values on every push. If
1468 /// you'd rather [`Clone`] a given value, use [`resize`]. If you want
1469 /// to use the [`Default`] trait to generate values, you can pass
1470 /// [`Default::default()`] as the second argument.
1475 /// let mut vec = vec![1, 2, 3];
1476 /// vec.resize_with(5, Default::default);
1477 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1479 /// let mut vec = vec![];
1481 /// vec.resize_with(4, || { p *= 2; p });
1482 /// assert_eq!(vec, [2, 4, 8, 16]);
1485 /// [`resize`]: #method.resize
1486 /// [`Clone`]: ../../std/clone/trait.Clone.html
1487 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1488 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1492 let len = self.len();
1494 self.extend_with(new_len - len, ExtendFunc(f));
1496 self.truncate(new_len);
1500 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1501 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1502 /// `'a`. If the type has only static references, or none at all, then this
1503 /// may be chosen to be `'static`.
1505 /// This function is similar to the `leak` function on `Box`.
1507 /// This function is mainly useful for data that lives for the remainder of
1508 /// the program's life. Dropping the returned reference will cause a memory
1516 /// #![feature(vec_leak)]
1518 /// let x = vec![1, 2, 3];
1519 /// let static_ref: &'static mut [usize] = Vec::leak(x);
1520 /// static_ref[0] += 1;
1521 /// assert_eq!(static_ref, &[2, 2, 3]);
1523 #[unstable(feature = "vec_leak", issue = "62195")]
1525 pub fn leak<'a>(vec: Vec<T>) -> &'a mut [T]
1527 T: 'a, // Technically not needed, but kept to be explicit.
1529 Box::leak(vec.into_boxed_slice())
1533 impl<T: Clone> Vec<T> {
1534 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1536 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1537 /// difference, with each additional slot filled with `value`.
1538 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1540 /// This method requires `T` to implement [`Clone`],
1541 /// in order to be able to clone the passed value.
1542 /// If you need more flexibility (or want to rely on [`Default`] instead of
1543 /// [`Clone`]), use [`resize_with`].
1548 /// let mut vec = vec!["hello"];
1549 /// vec.resize(3, "world");
1550 /// assert_eq!(vec, ["hello", "world", "world"]);
1552 /// let mut vec = vec![1, 2, 3, 4];
1553 /// vec.resize(2, 0);
1554 /// assert_eq!(vec, [1, 2]);
1557 /// [`Clone`]: ../../std/clone/trait.Clone.html
1558 /// [`Default`]: ../../std/default/trait.Default.html
1559 /// [`resize_with`]: #method.resize_with
1560 #[stable(feature = "vec_resize", since = "1.5.0")]
1561 pub fn resize(&mut self, new_len: usize, value: T) {
1562 let len = self.len();
1565 self.extend_with(new_len - len, ExtendElement(value))
1567 self.truncate(new_len);
1571 /// Clones and appends all elements in a slice to the `Vec`.
1573 /// Iterates over the slice `other`, clones each element, and then appends
1574 /// it to this `Vec`. The `other` vector is traversed in-order.
1576 /// Note that this function is same as [`extend`] except that it is
1577 /// specialized to work with slices instead. If and when Rust gets
1578 /// specialization this function will likely be deprecated (but still
1584 /// let mut vec = vec![1];
1585 /// vec.extend_from_slice(&[2, 3, 4]);
1586 /// assert_eq!(vec, [1, 2, 3, 4]);
1589 /// [`extend`]: #method.extend
1590 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1591 pub fn extend_from_slice(&mut self, other: &[T]) {
1592 self.spec_extend(other.iter())
1596 impl<T: Default> Vec<T> {
1597 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1599 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1600 /// difference, with each additional slot filled with [`Default::default()`].
1601 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1603 /// This method uses [`Default`] to create new values on every push. If
1604 /// you'd rather [`Clone`] a given value, use [`resize`].
1609 /// # #![allow(deprecated)]
1610 /// #![feature(vec_resize_default)]
1612 /// let mut vec = vec![1, 2, 3];
1613 /// vec.resize_default(5);
1614 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1616 /// let mut vec = vec![1, 2, 3, 4];
1617 /// vec.resize_default(2);
1618 /// assert_eq!(vec, [1, 2]);
1621 /// [`resize`]: #method.resize
1622 /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default
1623 /// [`Default`]: ../../std/default/trait.Default.html
1624 /// [`Clone`]: ../../std/clone/trait.Clone.html
1625 #[unstable(feature = "vec_resize_default", issue = "41758")]
1627 reason = "This is moving towards being removed in favor \
1628 of `.resize_with(Default::default)`. If you disagree, please comment \
1629 in the tracking issue.",
1632 pub fn resize_default(&mut self, new_len: usize) {
1633 let len = self.len();
1636 self.extend_with(new_len - len, ExtendDefault);
1638 self.truncate(new_len);
1643 // This code generalizes `extend_with_{element,default}`.
1644 trait ExtendWith<T> {
1645 fn next(&mut self) -> T;
1649 struct ExtendElement<T>(T);
1650 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1651 fn next(&mut self) -> T {
1654 fn last(self) -> T {
1659 struct ExtendDefault;
1660 impl<T: Default> ExtendWith<T> for ExtendDefault {
1661 fn next(&mut self) -> T {
1664 fn last(self) -> T {
1669 struct ExtendFunc<F>(F);
1670 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1671 fn next(&mut self) -> T {
1674 fn last(mut self) -> T {
1680 /// Extend the vector by `n` values, using the given generator.
1681 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1685 let mut ptr = self.as_mut_ptr().add(self.len());
1686 // Use SetLenOnDrop to work around bug where compiler
1687 // may not realize the store through `ptr` through self.set_len()
1689 let mut local_len = SetLenOnDrop::new(&mut self.len);
1691 // Write all elements except the last one
1693 ptr::write(ptr, value.next());
1694 ptr = ptr.offset(1);
1695 // Increment the length in every step in case next() panics
1696 local_len.increment_len(1);
1700 // We can write the last element directly without cloning needlessly
1701 ptr::write(ptr, value.last());
1702 local_len.increment_len(1);
1705 // len set by scope guard
1710 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1712 // The idea is: The length field in SetLenOnDrop is a local variable
1713 // that the optimizer will see does not alias with any stores through the Vec's data
1714 // pointer. This is a workaround for alias analysis issue #32155
1715 struct SetLenOnDrop<'a> {
1720 impl<'a> SetLenOnDrop<'a> {
1722 fn new(len: &'a mut usize) -> Self {
1723 SetLenOnDrop { local_len: *len, len }
1727 fn increment_len(&mut self, increment: usize) {
1728 self.local_len += increment;
1732 impl Drop for SetLenOnDrop<'_> {
1734 fn drop(&mut self) {
1735 *self.len = self.local_len;
1739 impl<T: PartialEq> Vec<T> {
1740 /// Removes consecutive repeated elements in the vector according to the
1741 /// [`PartialEq`] trait implementation.
1743 /// If the vector is sorted, this removes all duplicates.
1748 /// let mut vec = vec![1, 2, 2, 3, 2];
1752 /// assert_eq!(vec, [1, 2, 3, 2]);
1754 #[stable(feature = "rust1", since = "1.0.0")]
1756 pub fn dedup(&mut self) {
1757 self.dedup_by(|a, b| a == b)
1762 /// Removes the first instance of `item` from the vector if the item exists.
1764 /// This method will be removed soon.
1765 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1767 reason = "Removing the first item equal to a needle is already easily possible \
1768 with iterators and the current Vec methods. Furthermore, having a method for \
1769 one particular case of removal (linear search, only the first item, no swap remove) \
1770 but not for others is inconsistent. This method will be removed soon.",
1773 pub fn remove_item<V>(&mut self, item: &V) -> Option<T>
1777 let pos = self.iter().position(|x| *x == *item)?;
1778 Some(self.remove(pos))
1782 ////////////////////////////////////////////////////////////////////////////////
1783 // Internal methods and functions
1784 ////////////////////////////////////////////////////////////////////////////////
1787 #[stable(feature = "rust1", since = "1.0.0")]
1788 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1789 <T as SpecFromElem>::from_elem(elem, n)
1792 // Specialization trait used for Vec::from_elem
1793 trait SpecFromElem: Sized {
1794 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1797 impl<T: Clone> SpecFromElem for T {
1798 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1799 let mut v = Vec::with_capacity(n);
1800 v.extend_with(n, ExtendElement(elem));
1805 impl SpecFromElem for i8 {
1807 fn from_elem(elem: i8, n: usize) -> Vec<i8> {
1809 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1812 let mut v = Vec::with_capacity(n);
1813 ptr::write_bytes(v.as_mut_ptr(), elem as u8, n);
1820 impl SpecFromElem for u8 {
1822 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1824 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1827 let mut v = Vec::with_capacity(n);
1828 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1835 impl<T: Clone + IsZero> SpecFromElem for T {
1837 fn from_elem(elem: T, n: usize) -> Vec<T> {
1839 return Vec { buf: RawVec::with_capacity_zeroed(n), len: n };
1841 let mut v = Vec::with_capacity(n);
1842 v.extend_with(n, ExtendElement(elem));
1847 #[rustc_specialization_trait]
1848 unsafe trait IsZero {
1849 /// Whether this value is zero
1850 fn is_zero(&self) -> bool;
1853 macro_rules! impl_is_zero {
1854 ($t:ty, $is_zero:expr) => {
1855 unsafe impl IsZero for $t {
1857 fn is_zero(&self) -> bool {
1864 impl_is_zero!(i16, |x| x == 0);
1865 impl_is_zero!(i32, |x| x == 0);
1866 impl_is_zero!(i64, |x| x == 0);
1867 impl_is_zero!(i128, |x| x == 0);
1868 impl_is_zero!(isize, |x| x == 0);
1870 impl_is_zero!(u16, |x| x == 0);
1871 impl_is_zero!(u32, |x| x == 0);
1872 impl_is_zero!(u64, |x| x == 0);
1873 impl_is_zero!(u128, |x| x == 0);
1874 impl_is_zero!(usize, |x| x == 0);
1876 impl_is_zero!(bool, |x| x == false);
1877 impl_is_zero!(char, |x| x == '\0');
1879 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1880 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1882 unsafe impl<T> IsZero for *const T {
1884 fn is_zero(&self) -> bool {
1889 unsafe impl<T> IsZero for *mut T {
1891 fn is_zero(&self) -> bool {
1896 // `Option<&T>` and `Option<Box<T>>` are guaranteed to represent `None` as null.
1897 // For fat pointers, the bytes that would be the pointer metadata in the `Some`
1898 // variant are padding in the `None` variant, so ignoring them and
1899 // zero-initializing instead is ok.
1900 // `Option<&mut T>` never implements `Clone`, so there's no need for an impl of
1903 unsafe impl<T: ?Sized> IsZero for Option<&T> {
1905 fn is_zero(&self) -> bool {
1910 unsafe impl<T: ?Sized> IsZero for Option<Box<T>> {
1912 fn is_zero(&self) -> bool {
1917 ////////////////////////////////////////////////////////////////////////////////
1918 // Common trait implementations for Vec
1919 ////////////////////////////////////////////////////////////////////////////////
1921 #[stable(feature = "rust1", since = "1.0.0")]
1922 impl<T> ops::Deref for Vec<T> {
1925 fn deref(&self) -> &[T] {
1926 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
1930 #[stable(feature = "rust1", since = "1.0.0")]
1931 impl<T> ops::DerefMut for Vec<T> {
1932 fn deref_mut(&mut self) -> &mut [T] {
1933 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1937 #[stable(feature = "rust1", since = "1.0.0")]
1938 impl<T: Clone> Clone for Vec<T> {
1940 fn clone(&self) -> Vec<T> {
1941 <[T]>::to_vec(&**self)
1944 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1945 // required for this method definition, is not available. Instead use the
1946 // `slice::to_vec` function which is only available with cfg(test)
1947 // NB see the slice::hack module in slice.rs for more information
1949 fn clone(&self) -> Vec<T> {
1950 crate::slice::to_vec(&**self)
1953 fn clone_from(&mut self, other: &Vec<T>) {
1954 other.as_slice().clone_into(self);
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 impl<T: Hash> Hash for Vec<T> {
1961 fn hash<H: Hasher>(&self, state: &mut H) {
1962 Hash::hash(&**self, state)
1966 #[stable(feature = "rust1", since = "1.0.0")]
1967 #[rustc_on_unimplemented(
1968 message = "vector indices are of type `usize` or ranges of `usize`",
1969 label = "vector indices are of type `usize` or ranges of `usize`"
1971 impl<T, I: SliceIndex<[T]>> Index<I> for Vec<T> {
1972 type Output = I::Output;
1975 fn index(&self, index: I) -> &Self::Output {
1976 Index::index(&**self, index)
1980 #[stable(feature = "rust1", since = "1.0.0")]
1981 #[rustc_on_unimplemented(
1982 message = "vector indices are of type `usize` or ranges of `usize`",
1983 label = "vector indices are of type `usize` or ranges of `usize`"
1985 impl<T, I: SliceIndex<[T]>> IndexMut<I> for Vec<T> {
1987 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1988 IndexMut::index_mut(&mut **self, index)
1992 #[stable(feature = "rust1", since = "1.0.0")]
1993 impl<T> FromIterator<T> for Vec<T> {
1995 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1996 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
2000 #[stable(feature = "rust1", since = "1.0.0")]
2001 impl<T> IntoIterator for Vec<T> {
2003 type IntoIter = IntoIter<T>;
2005 /// Creates a consuming iterator, that is, one that moves each value out of
2006 /// the vector (from start to end). The vector cannot be used after calling
2012 /// let v = vec!["a".to_string(), "b".to_string()];
2013 /// for s in v.into_iter() {
2014 /// // s has type String, not &String
2015 /// println!("{}", s);
2019 fn into_iter(self) -> IntoIter<T> {
2021 let mut me = ManuallyDrop::new(self);
2022 let begin = me.as_mut_ptr();
2023 let end = if mem::size_of::<T>() == 0 {
2024 arith_offset(begin as *const i8, me.len() as isize) as *const T
2026 begin.add(me.len()) as *const T
2028 let cap = me.buf.capacity();
2030 buf: NonNull::new_unchecked(begin),
2031 phantom: PhantomData,
2040 #[stable(feature = "rust1", since = "1.0.0")]
2041 impl<'a, T> IntoIterator for &'a Vec<T> {
2043 type IntoIter = slice::Iter<'a, T>;
2045 fn into_iter(self) -> slice::Iter<'a, T> {
2050 #[stable(feature = "rust1", since = "1.0.0")]
2051 impl<'a, T> IntoIterator for &'a mut Vec<T> {
2052 type Item = &'a mut T;
2053 type IntoIter = slice::IterMut<'a, T>;
2055 fn into_iter(self) -> slice::IterMut<'a, T> {
2060 #[stable(feature = "rust1", since = "1.0.0")]
2061 impl<T> Extend<T> for Vec<T> {
2063 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2064 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2068 fn extend_one(&mut self, item: T) {
2073 fn extend_reserve(&mut self, additional: usize) {
2074 self.reserve(additional);
2078 // Specialization trait used for Vec::from_iter and Vec::extend
2079 trait SpecExtend<T, I> {
2080 fn from_iter(iter: I) -> Self;
2081 fn spec_extend(&mut self, iter: I);
2084 impl<T, I> SpecExtend<T, I> for Vec<T>
2086 I: Iterator<Item = T>,
2088 default fn from_iter(mut iterator: I) -> Self {
2089 // Unroll the first iteration, as the vector is going to be
2090 // expanded on this iteration in every case when the iterable is not
2091 // empty, but the loop in extend_desugared() is not going to see the
2092 // vector being full in the few subsequent loop iterations.
2093 // So we get better branch prediction.
2094 let mut vector = match iterator.next() {
2095 None => return Vec::new(),
2097 let (lower, _) = iterator.size_hint();
2098 let mut vector = Vec::with_capacity(lower.saturating_add(1));
2100 ptr::write(vector.as_mut_ptr(), element);
2106 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
2110 default fn spec_extend(&mut self, iter: I) {
2111 self.extend_desugared(iter)
2115 impl<T, I> SpecExtend<T, I> for Vec<T>
2117 I: TrustedLen<Item = T>,
2119 default fn from_iter(iterator: I) -> Self {
2120 let mut vector = Vec::new();
2121 vector.spec_extend(iterator);
2125 default fn spec_extend(&mut self, iterator: I) {
2126 // This is the case for a TrustedLen iterator.
2127 let (low, high) = iterator.size_hint();
2128 if let Some(high_value) = high {
2132 "TrustedLen iterator's size hint is not exact: {:?}",
2136 if let Some(additional) = high {
2137 self.reserve(additional);
2139 let mut ptr = self.as_mut_ptr().add(self.len());
2140 let mut local_len = SetLenOnDrop::new(&mut self.len);
2141 iterator.for_each(move |element| {
2142 ptr::write(ptr, element);
2143 ptr = ptr.offset(1);
2144 // NB can't overflow since we would have had to alloc the address space
2145 local_len.increment_len(1);
2149 self.extend_desugared(iterator)
2154 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
2155 fn from_iter(iterator: IntoIter<T>) -> Self {
2156 // A common case is passing a vector into a function which immediately
2157 // re-collects into a vector. We can short circuit this if the IntoIter
2158 // has not been advanced at all.
2159 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
2161 let it = ManuallyDrop::new(iterator);
2162 Vec::from_raw_parts(it.buf.as_ptr(), it.len(), it.cap)
2165 let mut vector = Vec::new();
2166 vector.spec_extend(iterator);
2171 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
2173 self.append_elements(iterator.as_slice() as _);
2175 iterator.ptr = iterator.end;
2179 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
2181 I: Iterator<Item = &'a T>,
2184 default fn from_iter(iterator: I) -> Self {
2185 SpecExtend::from_iter(iterator.cloned())
2188 default fn spec_extend(&mut self, iterator: I) {
2189 self.spec_extend(iterator.cloned())
2193 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
2197 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
2198 let slice = iterator.as_slice();
2199 self.reserve(slice.len());
2201 let len = self.len();
2202 let dst_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(len), slice.len());
2203 dst_slice.copy_from_slice(slice);
2204 self.set_len(len + slice.len());
2210 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2211 // This is the case for a general iterator.
2213 // This function should be the moral equivalent of:
2215 // for item in iterator {
2218 while let Some(element) = iterator.next() {
2219 let len = self.len();
2220 if len == self.capacity() {
2221 let (lower, _) = iterator.size_hint();
2222 self.reserve(lower.saturating_add(1));
2225 ptr::write(self.as_mut_ptr().add(len), element);
2226 // NB can't overflow since we would have had to alloc the address space
2227 self.set_len(len + 1);
2232 /// Creates a splicing iterator that replaces the specified range in the vector
2233 /// with the given `replace_with` iterator and yields the removed items.
2234 /// `replace_with` does not need to be the same length as `range`.
2236 /// The element range is removed even if the iterator is not consumed until the end.
2238 /// It is unspecified how many elements are removed from the vector
2239 /// if the `Splice` value is leaked.
2241 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2243 /// This is optimal if:
2245 /// * The tail (elements in the vector after `range`) is empty,
2246 /// * or `replace_with` yields fewer elements than `range`’s length
2247 /// * or the lower bound of its `size_hint()` is exact.
2249 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2253 /// Panics if the starting point is greater than the end point or if
2254 /// the end point is greater than the length of the vector.
2259 /// let mut v = vec![1, 2, 3];
2260 /// let new = [7, 8];
2261 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2262 /// assert_eq!(v, &[7, 8, 3]);
2263 /// assert_eq!(u, &[1, 2]);
2266 #[stable(feature = "vec_splice", since = "1.21.0")]
2267 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter>
2269 R: RangeBounds<usize>,
2270 I: IntoIterator<Item = T>,
2272 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2275 /// Creates an iterator which uses a closure to determine if an element should be removed.
2277 /// If the closure returns true, then the element is removed and yielded.
2278 /// If the closure returns false, the element will remain in the vector and will not be yielded
2279 /// by the iterator.
2281 /// Using this method is equivalent to the following code:
2284 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2285 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2287 /// while i != vec.len() {
2288 /// if some_predicate(&mut vec[i]) {
2289 /// let val = vec.remove(i);
2290 /// // your code here
2296 /// # assert_eq!(vec, vec![1, 4, 5]);
2299 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2300 /// because it can backshift the elements of the array in bulk.
2302 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2303 /// regardless of whether you choose to keep or remove it.
2308 /// Splitting an array into evens and odds, reusing the original allocation:
2311 /// #![feature(drain_filter)]
2312 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2314 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2315 /// let odds = numbers;
2317 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2318 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2320 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2321 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F>
2323 F: FnMut(&mut T) -> bool,
2325 let old_len = self.len();
2327 // Guard against us getting leaked (leak amplification)
2332 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2336 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2338 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2339 /// append the entire slice at once.
2341 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2342 #[stable(feature = "extend_ref", since = "1.2.0")]
2343 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2344 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2345 self.spec_extend(iter.into_iter())
2349 fn extend_one(&mut self, &item: &'a T) {
2354 fn extend_reserve(&mut self, additional: usize) {
2355 self.reserve(additional);
2359 macro_rules! __impl_slice_eq1 {
2360 ([$($vars:tt)*] $lhs:ty, $rhs:ty $(where $ty:ty: $bound:ident)?, #[$stability:meta]) => {
2362 impl<A, B, $($vars)*> PartialEq<$rhs> for $lhs
2368 fn eq(&self, other: &$rhs) -> bool { self[..] == other[..] }
2370 fn ne(&self, other: &$rhs) -> bool { self[..] != other[..] }
2375 __impl_slice_eq1! { [] Vec<A>, Vec<B>, #[stable(feature = "rust1", since = "1.0.0")] }
2376 __impl_slice_eq1! { [] Vec<A>, &[B], #[stable(feature = "rust1", since = "1.0.0")] }
2377 __impl_slice_eq1! { [] Vec<A>, &mut [B], #[stable(feature = "rust1", since = "1.0.0")] }
2378 __impl_slice_eq1! { [] &[A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2379 __impl_slice_eq1! { [] &mut [A], Vec<B>, #[stable(feature = "partialeq_vec_for_ref_slice", since = "1.46.0")] }
2380 __impl_slice_eq1! { [] Cow<'_, [A]>, Vec<B> where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2381 __impl_slice_eq1! { [] Cow<'_, [A]>, &[B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2382 __impl_slice_eq1! { [] Cow<'_, [A]>, &mut [B] where A: Clone, #[stable(feature = "rust1", since = "1.0.0")] }
2383 __impl_slice_eq1! { [const N: usize] Vec<A>, [B; N] where [B; N]: LengthAtMost32, #[stable(feature = "rust1", since = "1.0.0")] }
2384 __impl_slice_eq1! { [const N: usize] Vec<A>, &[B; N] where [B; N]: LengthAtMost32, #[stable(feature = "rust1", since = "1.0.0")] }
2386 // NOTE: some less important impls are omitted to reduce code bloat
2387 // FIXME(Centril): Reconsider this?
2388 //__impl_slice_eq1! { [const N: usize] Vec<A>, &mut [B; N], [B; N]: LengthAtMost32 }
2389 //__impl_slice_eq1! { [const N: usize] [A; N], Vec<B>, [A; N]: LengthAtMost32 }
2390 //__impl_slice_eq1! { [const N: usize] &[A; N], Vec<B>, [A; N]: LengthAtMost32 }
2391 //__impl_slice_eq1! { [const N: usize] &mut [A; N], Vec<B>, [A; N]: LengthAtMost32 }
2392 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, [B; N], [B; N]: LengthAtMost32 }
2393 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &[B; N], [B; N]: LengthAtMost32 }
2394 //__impl_slice_eq1! { [const N: usize] Cow<'a, [A]>, &mut [B; N], [B; N]: LengthAtMost32 }
2396 /// Implements comparison of vectors, lexicographically.
2397 #[stable(feature = "rust1", since = "1.0.0")]
2398 impl<T: PartialOrd> PartialOrd for Vec<T> {
2400 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2401 PartialOrd::partial_cmp(&**self, &**other)
2405 #[stable(feature = "rust1", since = "1.0.0")]
2406 impl<T: Eq> Eq for Vec<T> {}
2408 /// Implements ordering of vectors, lexicographically.
2409 #[stable(feature = "rust1", since = "1.0.0")]
2410 impl<T: Ord> Ord for Vec<T> {
2412 fn cmp(&self, other: &Vec<T>) -> Ordering {
2413 Ord::cmp(&**self, &**other)
2417 #[stable(feature = "rust1", since = "1.0.0")]
2418 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2419 fn drop(&mut self) {
2422 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2423 // could avoid questions of validity in certain cases
2424 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2426 // RawVec handles deallocation
2430 #[stable(feature = "rust1", since = "1.0.0")]
2431 impl<T> Default for Vec<T> {
2432 /// Creates an empty `Vec<T>`.
2433 fn default() -> Vec<T> {
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2441 fmt::Debug::fmt(&**self, f)
2445 #[stable(feature = "rust1", since = "1.0.0")]
2446 impl<T> AsRef<Vec<T>> for Vec<T> {
2447 fn as_ref(&self) -> &Vec<T> {
2452 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2453 impl<T> AsMut<Vec<T>> for Vec<T> {
2454 fn as_mut(&mut self) -> &mut Vec<T> {
2459 #[stable(feature = "rust1", since = "1.0.0")]
2460 impl<T> AsRef<[T]> for Vec<T> {
2461 fn as_ref(&self) -> &[T] {
2466 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2467 impl<T> AsMut<[T]> for Vec<T> {
2468 fn as_mut(&mut self) -> &mut [T] {
2473 #[stable(feature = "rust1", since = "1.0.0")]
2474 impl<T: Clone> From<&[T]> for Vec<T> {
2476 fn from(s: &[T]) -> Vec<T> {
2480 fn from(s: &[T]) -> Vec<T> {
2481 crate::slice::to_vec(s)
2485 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2486 impl<T: Clone> From<&mut [T]> for Vec<T> {
2488 fn from(s: &mut [T]) -> Vec<T> {
2492 fn from(s: &mut [T]) -> Vec<T> {
2493 crate::slice::to_vec(s)
2497 #[stable(feature = "vec_from_array", since = "1.44.0")]
2498 impl<T, const N: usize> From<[T; N]> for Vec<T>
2500 [T; N]: LengthAtMost32,
2503 fn from(s: [T; N]) -> Vec<T> {
2504 <[T]>::into_vec(box s)
2507 fn from(s: [T; N]) -> Vec<T> {
2508 crate::slice::into_vec(box s)
2512 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2513 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2515 [T]: ToOwned<Owned = Vec<T>>,
2517 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2522 // note: test pulls in libstd, which causes errors here
2524 #[stable(feature = "vec_from_box", since = "1.18.0")]
2525 impl<T> From<Box<[T]>> for Vec<T> {
2526 fn from(s: Box<[T]>) -> Vec<T> {
2531 // note: test pulls in libstd, which causes errors here
2533 #[stable(feature = "box_from_vec", since = "1.20.0")]
2534 impl<T> From<Vec<T>> for Box<[T]> {
2535 fn from(v: Vec<T>) -> Box<[T]> {
2536 v.into_boxed_slice()
2540 #[stable(feature = "rust1", since = "1.0.0")]
2541 impl From<&str> for Vec<u8> {
2542 fn from(s: &str) -> Vec<u8> {
2543 From::from(s.as_bytes())
2547 ////////////////////////////////////////////////////////////////////////////////
2549 ////////////////////////////////////////////////////////////////////////////////
2551 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2552 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2553 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2558 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2559 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2560 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2565 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2566 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2567 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2568 Cow::Borrowed(v.as_slice())
2572 #[stable(feature = "rust1", since = "1.0.0")]
2573 impl<'a, T> FromIterator<T> for Cow<'a, [T]>
2577 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2578 Cow::Owned(FromIterator::from_iter(it))
2582 ////////////////////////////////////////////////////////////////////////////////
2584 ////////////////////////////////////////////////////////////////////////////////
2586 /// An iterator that moves out of a vector.
2588 /// This `struct` is created by the `into_iter` method on [`Vec`] (provided
2589 /// by the [`IntoIterator`] trait).
2591 /// [`Vec`]: struct.Vec.html
2592 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2593 #[stable(feature = "rust1", since = "1.0.0")]
2594 pub struct IntoIter<T> {
2596 phantom: PhantomData<T>,
2602 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2603 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2604 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2605 f.debug_tuple("IntoIter").field(&self.as_slice()).finish()
2609 impl<T> IntoIter<T> {
2610 /// Returns the remaining items of this iterator as a slice.
2615 /// let vec = vec!['a', 'b', 'c'];
2616 /// let mut into_iter = vec.into_iter();
2617 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2618 /// let _ = into_iter.next().unwrap();
2619 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2621 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2622 pub fn as_slice(&self) -> &[T] {
2623 unsafe { slice::from_raw_parts(self.ptr, self.len()) }
2626 /// Returns the remaining items of this iterator as a mutable slice.
2631 /// let vec = vec!['a', 'b', 'c'];
2632 /// let mut into_iter = vec.into_iter();
2633 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2634 /// into_iter.as_mut_slice()[2] = 'z';
2635 /// assert_eq!(into_iter.next().unwrap(), 'a');
2636 /// assert_eq!(into_iter.next().unwrap(), 'b');
2637 /// assert_eq!(into_iter.next().unwrap(), 'z');
2639 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2640 pub fn as_mut_slice(&mut self) -> &mut [T] {
2641 unsafe { &mut *self.as_raw_mut_slice() }
2644 fn as_raw_mut_slice(&mut self) -> *mut [T] {
2645 ptr::slice_from_raw_parts_mut(self.ptr as *mut T, self.len())
2649 #[stable(feature = "vec_intoiter_as_ref", since = "1.46.0")]
2650 impl<T> AsRef<[T]> for IntoIter<T> {
2651 fn as_ref(&self) -> &[T] {
2656 #[stable(feature = "rust1", since = "1.0.0")]
2657 unsafe impl<T: Send> Send for IntoIter<T> {}
2658 #[stable(feature = "rust1", since = "1.0.0")]
2659 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2661 #[stable(feature = "rust1", since = "1.0.0")]
2662 impl<T> Iterator for IntoIter<T> {
2666 fn next(&mut self) -> Option<T> {
2668 if self.ptr as *const _ == self.end {
2671 if mem::size_of::<T>() == 0 {
2672 // purposefully don't use 'ptr.offset' because for
2673 // vectors with 0-size elements this would return the
2675 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2677 // Make up a value of this ZST.
2681 self.ptr = self.ptr.offset(1);
2683 Some(ptr::read(old))
2690 fn size_hint(&self) -> (usize, Option<usize>) {
2691 let exact = if mem::size_of::<T>() == 0 {
2692 (self.end as usize).wrapping_sub(self.ptr as usize)
2694 unsafe { self.end.offset_from(self.ptr) as usize }
2696 (exact, Some(exact))
2700 fn count(self) -> usize {
2705 #[stable(feature = "rust1", since = "1.0.0")]
2706 impl<T> DoubleEndedIterator for IntoIter<T> {
2708 fn next_back(&mut self) -> Option<T> {
2710 if self.end == self.ptr {
2713 if mem::size_of::<T>() == 0 {
2714 // See above for why 'ptr.offset' isn't used
2715 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2717 // Make up a value of this ZST.
2720 self.end = self.end.offset(-1);
2722 Some(ptr::read(self.end))
2729 #[stable(feature = "rust1", since = "1.0.0")]
2730 impl<T> ExactSizeIterator for IntoIter<T> {
2731 fn is_empty(&self) -> bool {
2732 self.ptr == self.end
2736 #[stable(feature = "fused", since = "1.26.0")]
2737 impl<T> FusedIterator for IntoIter<T> {}
2739 #[unstable(feature = "trusted_len", issue = "37572")]
2740 unsafe impl<T> TrustedLen for IntoIter<T> {}
2742 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2743 impl<T: Clone> Clone for IntoIter<T> {
2744 fn clone(&self) -> IntoIter<T> {
2745 self.as_slice().to_owned().into_iter()
2749 #[stable(feature = "rust1", since = "1.0.0")]
2750 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2751 fn drop(&mut self) {
2752 struct DropGuard<'a, T>(&'a mut IntoIter<T>);
2754 impl<T> Drop for DropGuard<'_, T> {
2755 fn drop(&mut self) {
2756 // RawVec handles deallocation
2757 let _ = unsafe { RawVec::from_raw_parts(self.0.buf.as_ptr(), self.0.cap) };
2761 let guard = DropGuard(self);
2762 // destroy the remaining elements
2764 ptr::drop_in_place(guard.0.as_raw_mut_slice());
2766 // now `guard` will be dropped and do the rest
2770 /// A draining iterator for `Vec<T>`.
2772 /// This `struct` is created by the [`drain`] method on [`Vec`].
2774 /// [`drain`]: struct.Vec.html#method.drain
2775 /// [`Vec`]: struct.Vec.html
2776 #[stable(feature = "drain", since = "1.6.0")]
2777 pub struct Drain<'a, T: 'a> {
2778 /// Index of tail to preserve
2782 /// Current remaining range to remove
2783 iter: slice::Iter<'a, T>,
2784 vec: NonNull<Vec<T>>,
2787 #[stable(feature = "collection_debug", since = "1.17.0")]
2788 impl<T: fmt::Debug> fmt::Debug for Drain<'_, T> {
2789 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2790 f.debug_tuple("Drain").field(&self.iter.as_slice()).finish()
2794 impl<'a, T> Drain<'a, T> {
2795 /// Returns the remaining items of this iterator as a slice.
2800 /// let mut vec = vec!['a', 'b', 'c'];
2801 /// let mut drain = vec.drain(..);
2802 /// assert_eq!(drain.as_slice(), &['a', 'b', 'c']);
2803 /// let _ = drain.next().unwrap();
2804 /// assert_eq!(drain.as_slice(), &['b', 'c']);
2806 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
2807 pub fn as_slice(&self) -> &[T] {
2808 self.iter.as_slice()
2812 #[stable(feature = "vec_drain_as_slice", since = "1.46.0")]
2813 impl<'a, T> AsRef<[T]> for Drain<'a, T> {
2814 fn as_ref(&self) -> &[T] {
2819 #[stable(feature = "drain", since = "1.6.0")]
2820 unsafe impl<T: Sync> Sync for Drain<'_, T> {}
2821 #[stable(feature = "drain", since = "1.6.0")]
2822 unsafe impl<T: Send> Send for Drain<'_, T> {}
2824 #[stable(feature = "drain", since = "1.6.0")]
2825 impl<T> Iterator for Drain<'_, T> {
2829 fn next(&mut self) -> Option<T> {
2830 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2833 fn size_hint(&self) -> (usize, Option<usize>) {
2834 self.iter.size_hint()
2838 #[stable(feature = "drain", since = "1.6.0")]
2839 impl<T> DoubleEndedIterator for Drain<'_, T> {
2841 fn next_back(&mut self) -> Option<T> {
2842 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2846 #[stable(feature = "drain", since = "1.6.0")]
2847 impl<T> Drop for Drain<'_, T> {
2848 fn drop(&mut self) {
2849 /// Continues dropping the remaining elements in the `Drain`, then moves back the
2850 /// un-`Drain`ed elements to restore the original `Vec`.
2851 struct DropGuard<'r, 'a, T>(&'r mut Drain<'a, T>);
2853 impl<'r, 'a, T> Drop for DropGuard<'r, 'a, T> {
2854 fn drop(&mut self) {
2855 // Continue the same loop we have below. If the loop already finished, this does
2857 self.0.for_each(drop);
2859 if self.0.tail_len > 0 {
2861 let source_vec = self.0.vec.as_mut();
2862 // memmove back untouched tail, update to new length
2863 let start = source_vec.len();
2864 let tail = self.0.tail_start;
2866 let src = source_vec.as_ptr().add(tail);
2867 let dst = source_vec.as_mut_ptr().add(start);
2868 ptr::copy(src, dst, self.0.tail_len);
2870 source_vec.set_len(start + self.0.tail_len);
2876 // exhaust self first
2877 while let Some(item) = self.next() {
2878 let guard = DropGuard(self);
2883 // Drop a `DropGuard` to move back the non-drained tail of `self`.
2888 #[stable(feature = "drain", since = "1.6.0")]
2889 impl<T> ExactSizeIterator for Drain<'_, T> {
2890 fn is_empty(&self) -> bool {
2891 self.iter.is_empty()
2895 #[unstable(feature = "trusted_len", issue = "37572")]
2896 unsafe impl<T> TrustedLen for Drain<'_, T> {}
2898 #[stable(feature = "fused", since = "1.26.0")]
2899 impl<T> FusedIterator for Drain<'_, T> {}
2901 /// A splicing iterator for `Vec`.
2903 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2904 /// documentation for more.
2906 /// [`splice()`]: struct.Vec.html#method.splice
2907 /// [`Vec`]: struct.Vec.html
2909 #[stable(feature = "vec_splice", since = "1.21.0")]
2910 pub struct Splice<'a, I: Iterator + 'a> {
2911 drain: Drain<'a, I::Item>,
2915 #[stable(feature = "vec_splice", since = "1.21.0")]
2916 impl<I: Iterator> Iterator for Splice<'_, I> {
2917 type Item = I::Item;
2919 fn next(&mut self) -> Option<Self::Item> {
2923 fn size_hint(&self) -> (usize, Option<usize>) {
2924 self.drain.size_hint()
2928 #[stable(feature = "vec_splice", since = "1.21.0")]
2929 impl<I: Iterator> DoubleEndedIterator for Splice<'_, I> {
2930 fn next_back(&mut self) -> Option<Self::Item> {
2931 self.drain.next_back()
2935 #[stable(feature = "vec_splice", since = "1.21.0")]
2936 impl<I: Iterator> ExactSizeIterator for Splice<'_, I> {}
2938 #[stable(feature = "vec_splice", since = "1.21.0")]
2939 impl<I: Iterator> Drop for Splice<'_, I> {
2940 fn drop(&mut self) {
2941 self.drain.by_ref().for_each(drop);
2944 if self.drain.tail_len == 0 {
2945 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2949 // First fill the range left by drain().
2950 if !self.drain.fill(&mut self.replace_with) {
2954 // There may be more elements. Use the lower bound as an estimate.
2955 // FIXME: Is the upper bound a better guess? Or something else?
2956 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2957 if lower_bound > 0 {
2958 self.drain.move_tail(lower_bound);
2959 if !self.drain.fill(&mut self.replace_with) {
2964 // Collect any remaining elements.
2965 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2966 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2967 // Now we have an exact count.
2968 if collected.len() > 0 {
2969 self.drain.move_tail(collected.len());
2970 let filled = self.drain.fill(&mut collected);
2971 debug_assert!(filled);
2972 debug_assert_eq!(collected.len(), 0);
2975 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2979 /// Private helper methods for `Splice::drop`
2980 impl<T> Drain<'_, T> {
2981 /// The range from `self.vec.len` to `self.tail_start` contains elements
2982 /// that have been moved out.
2983 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2984 /// Returns `true` if we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2985 unsafe fn fill<I: Iterator<Item = T>>(&mut self, replace_with: &mut I) -> bool {
2986 let vec = unsafe { self.vec.as_mut() };
2987 let range_start = vec.len;
2988 let range_end = self.tail_start;
2989 let range_slice = unsafe {
2990 slice::from_raw_parts_mut(vec.as_mut_ptr().add(range_start), range_end - range_start)
2993 for place in range_slice {
2994 if let Some(new_item) = replace_with.next() {
2995 unsafe { ptr::write(place, new_item) };
3004 /// Makes room for inserting more elements before the tail.
3005 unsafe fn move_tail(&mut self, additional: usize) {
3006 let vec = unsafe { self.vec.as_mut() };
3007 let len = self.tail_start + self.tail_len;
3008 vec.buf.reserve(len, additional);
3010 let new_tail_start = self.tail_start + additional;
3012 let src = vec.as_ptr().add(self.tail_start);
3013 let dst = vec.as_mut_ptr().add(new_tail_start);
3014 ptr::copy(src, dst, self.tail_len);
3016 self.tail_start = new_tail_start;
3020 /// An iterator produced by calling `drain_filter` on Vec.
3021 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3023 pub struct DrainFilter<'a, T, F>
3025 F: FnMut(&mut T) -> bool,
3027 vec: &'a mut Vec<T>,
3028 /// The index of the item that will be inspected by the next call to `next`.
3030 /// The number of items that have been drained (removed) thus far.
3032 /// The original length of `vec` prior to draining.
3034 /// The filter test predicate.
3036 /// A flag that indicates a panic has occurred in the filter test prodicate.
3037 /// This is used as a hint in the drop implementation to prevent consumption
3038 /// of the remainder of the `DrainFilter`. Any unprocessed items will be
3039 /// backshifted in the `vec`, but no further items will be dropped or
3040 /// tested by the filter predicate.
3044 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3045 impl<T, F> Iterator for DrainFilter<'_, T, F>
3047 F: FnMut(&mut T) -> bool,
3051 fn next(&mut self) -> Option<T> {
3053 while self.idx < self.old_len {
3055 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
3056 self.panic_flag = true;
3057 let drained = (self.pred)(&mut v[i]);
3058 self.panic_flag = false;
3059 // Update the index *after* the predicate is called. If the index
3060 // is updated prior and the predicate panics, the element at this
3061 // index would be leaked.
3065 return Some(ptr::read(&v[i]));
3066 } else if self.del > 0 {
3068 let src: *const T = &v[i];
3069 let dst: *mut T = &mut v[i - del];
3070 ptr::copy_nonoverlapping(src, dst, 1);
3077 fn size_hint(&self) -> (usize, Option<usize>) {
3078 (0, Some(self.old_len - self.idx))
3082 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
3083 impl<T, F> Drop for DrainFilter<'_, T, F>
3085 F: FnMut(&mut T) -> bool,
3087 fn drop(&mut self) {
3088 struct BackshiftOnDrop<'a, 'b, T, F>
3090 F: FnMut(&mut T) -> bool,
3092 drain: &'b mut DrainFilter<'a, T, F>,
3095 impl<'a, 'b, T, F> Drop for BackshiftOnDrop<'a, 'b, T, F>
3097 F: FnMut(&mut T) -> bool,
3099 fn drop(&mut self) {
3101 if self.drain.idx < self.drain.old_len && self.drain.del > 0 {
3102 // This is a pretty messed up state, and there isn't really an
3103 // obviously right thing to do. We don't want to keep trying
3104 // to execute `pred`, so we just backshift all the unprocessed
3105 // elements and tell the vec that they still exist. The backshift
3106 // is required to prevent a double-drop of the last successfully
3107 // drained item prior to a panic in the predicate.
3108 let ptr = self.drain.vec.as_mut_ptr();
3109 let src = ptr.add(self.drain.idx);
3110 let dst = src.sub(self.drain.del);
3111 let tail_len = self.drain.old_len - self.drain.idx;
3112 src.copy_to(dst, tail_len);
3114 self.drain.vec.set_len(self.drain.old_len - self.drain.del);
3119 let backshift = BackshiftOnDrop { drain: self };
3121 // Attempt to consume any remaining elements if the filter predicate
3122 // has not yet panicked. We'll backshift any remaining elements
3123 // whether we've already panicked or if the consumption here panics.
3124 if !backshift.drain.panic_flag {
3125 backshift.drain.for_each(drop);