1 //! A contiguous growable array type with heap-allocated contents, written
4 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
5 //! `O(1)` pop (from the end).
7 //! Vectors ensure they never allocate more than `isize::MAX` bytes.
11 //! You can explicitly create a [`Vec`] with [`Vec::new`]:
14 //! let v: Vec<i32> = Vec::new();
17 //! ...or by using the [`vec!`] macro:
20 //! let v: Vec<i32> = vec![];
22 //! let v = vec![1, 2, 3, 4, 5];
24 //! let v = vec![0; 10]; // ten zeroes
27 //! You can [`push`] values onto the end of a vector (which will grow the vector
31 //! let mut v = vec![1, 2];
36 //! Popping values works in much the same way:
39 //! let mut v = vec![1, 2];
41 //! let two = v.pop();
44 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
47 //! let mut v = vec![1, 2, 3];
52 //! [`push`]: Vec::push
54 #![stable(feature = "rust1", since = "1.0.0")]
56 use core::cmp::{self, Ordering};
57 use core::convert::TryFrom;
59 use core::hash::{Hash, Hasher};
60 use core::intrinsics::{arith_offset, assume};
61 use core::iter::FromIterator;
62 use core::marker::PhantomData;
63 use core::mem::{self, ManuallyDrop, MaybeUninit};
64 use core::ops::{self, Index, IndexMut, Range, RangeBounds};
65 use core::ptr::{self, NonNull};
66 use core::slice::{self, SliceIndex};
68 use crate::alloc::{Allocator, Global};
69 use crate::borrow::{Cow, ToOwned};
70 use crate::boxed::Box;
71 use crate::collections::TryReserveError;
72 use crate::raw_vec::RawVec;
74 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
75 pub use self::drain_filter::DrainFilter;
79 #[stable(feature = "vec_splice", since = "1.21.0")]
80 pub use self::splice::Splice;
84 #[stable(feature = "drain", since = "1.6.0")]
85 pub use self::drain::Drain;
91 pub(crate) use self::into_iter::AsIntoIter;
92 #[stable(feature = "rust1", since = "1.0.0")]
93 pub use self::into_iter::IntoIter;
97 use self::is_zero::IsZero;
101 mod source_iter_marker;
105 use self::spec_from_elem::SpecFromElem;
109 use self::set_len_on_drop::SetLenOnDrop;
113 use self::in_place_drop::InPlaceDrop;
117 use self::spec_from_iter_nested::SpecFromIterNested;
119 mod spec_from_iter_nested;
121 use self::spec_from_iter::SpecFromIter;
125 use self::spec_extend::SpecExtend;
129 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
134 /// let mut vec = Vec::new();
138 /// assert_eq!(vec.len(), 2);
139 /// assert_eq!(vec[0], 1);
141 /// assert_eq!(vec.pop(), Some(2));
142 /// assert_eq!(vec.len(), 1);
145 /// assert_eq!(vec[0], 7);
147 /// vec.extend([1, 2, 3].iter().copied());
150 /// println!("{}", x);
152 /// assert_eq!(vec, [7, 1, 2, 3]);
155 /// The [`vec!`] macro is provided to make initialization more convenient:
158 /// let mut vec = vec![1, 2, 3];
160 /// assert_eq!(vec, [1, 2, 3, 4]);
163 /// It can also initialize each element of a `Vec<T>` with a given value.
164 /// This may be more efficient than performing allocation and initialization
165 /// in separate steps, especially when initializing a vector of zeros:
168 /// let vec = vec![0; 5];
169 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
171 /// // The following is equivalent, but potentially slower:
172 /// let mut vec = Vec::with_capacity(5);
173 /// vec.resize(5, 0);
174 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
177 /// For more information, see
178 /// [Capacity and Reallocation](#capacity-and-reallocation).
180 /// Use a `Vec<T>` as an efficient stack:
183 /// let mut stack = Vec::new();
189 /// while let Some(top) = stack.pop() {
190 /// // Prints 3, 2, 1
191 /// println!("{}", top);
197 /// The `Vec` type allows to access values by index, because it implements the
198 /// [`Index`] trait. An example will be more explicit:
201 /// let v = vec![0, 2, 4, 6];
202 /// println!("{}", v[1]); // it will display '2'
205 /// However be careful: if you try to access an index which isn't in the `Vec`,
206 /// your software will panic! You cannot do this:
209 /// let v = vec![0, 2, 4, 6];
210 /// println!("{}", v[6]); // it will panic!
213 /// Use [`get`] and [`get_mut`] if you want to check whether the index is in
218 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
219 /// To get a [slice], use [`&`]. Example:
222 /// fn read_slice(slice: &[usize]) {
226 /// let v = vec![0, 1];
229 /// // ... and that's all!
230 /// // you can also do it like this:
231 /// let u: &[usize] = &v;
233 /// let u: &[_] = &v;
236 /// In Rust, it's more common to pass slices as arguments rather than vectors
237 /// when you just want to provide read access. The same goes for [`String`] and
240 /// # Capacity and reallocation
242 /// The capacity of a vector is the amount of space allocated for any future
243 /// elements that will be added onto the vector. This is not to be confused with
244 /// the *length* of a vector, which specifies the number of actual elements
245 /// within the vector. If a vector's length exceeds its capacity, its capacity
246 /// will automatically be increased, but its elements will have to be
249 /// For example, a vector with capacity 10 and length 0 would be an empty vector
250 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
251 /// vector will not change its capacity or cause reallocation to occur. However,
252 /// if the vector's length is increased to 11, it will have to reallocate, which
253 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
254 /// whenever possible to specify how big the vector is expected to get.
258 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
259 /// about its design. This ensures that it's as low-overhead as possible in
260 /// the general case, and can be correctly manipulated in primitive ways
261 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
262 /// If additional type parameters are added (e.g., to support custom allocators),
263 /// overriding their defaults may change the behavior.
265 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
266 /// triplet. No more, no less. The order of these fields is completely
267 /// unspecified, and you should use the appropriate methods to modify these.
268 /// The pointer will never be null, so this type is null-pointer-optimized.
270 /// However, the pointer may not actually point to allocated memory. In particular,
271 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
272 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
273 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
274 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
275 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
276 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
277 /// details are very subtle — if you intend to allocate memory using a `Vec`
278 /// and use it for something else (either to pass to unsafe code, or to build your
279 /// own memory-backed collection), be sure to deallocate this memory by using
280 /// `from_raw_parts` to recover the `Vec` and then dropping it.
282 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
283 /// (as defined by the allocator Rust is configured to use by default), and its
284 /// pointer points to [`len`] initialized, contiguous elements in order (what
285 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
286 /// `[`len`] logically uninitialized, contiguous elements.
288 /// `Vec` will never perform a "small optimization" where elements are actually
289 /// stored on the stack for two reasons:
291 /// * It would make it more difficult for unsafe code to correctly manipulate
292 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
293 /// only moved, and it would be more difficult to determine if a `Vec` had
294 /// actually allocated memory.
296 /// * It would penalize the general case, incurring an additional branch
299 /// `Vec` will never automatically shrink itself, even if completely empty. This
300 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
301 /// and then filling it back up to the same [`len`] should incur no calls to
302 /// the allocator. If you wish to free up unused memory, use
303 /// [`shrink_to_fit`].
305 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
306 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
307 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
308 /// accurate, and can be relied on. It can even be used to manually free the memory
309 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
310 /// when not necessary.
312 /// `Vec` does not guarantee any particular growth strategy when reallocating
313 /// when full, nor when [`reserve`] is called. The current strategy is basic
314 /// and it may prove desirable to use a non-constant growth factor. Whatever
315 /// strategy is used will of course guarantee *O*(1) amortized [`push`].
317 /// `vec![x; n]`, `vec![a, b, c, d]`, and
318 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
319 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
320 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
321 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
323 /// `Vec` will not specifically overwrite any data that is removed from it,
324 /// but also won't specifically preserve it. Its uninitialized memory is
325 /// scratch space that it may use however it wants. It will generally just do
326 /// whatever is most efficient or otherwise easy to implement. Do not rely on
327 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
328 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
329 /// first, that may not actually happen because the optimizer does not consider
330 /// this a side-effect that must be preserved. There is one case which we will
331 /// not break, however: using `unsafe` code to write to the excess capacity,
332 /// and then increasing the length to match, is always valid.
334 /// `Vec` does not currently guarantee the order in which elements are dropped.
335 /// The order has changed in the past and may change again.
337 /// [`get`]: ../../std/vec/struct.Vec.html#method.get
338 /// [`get_mut`]: ../../std/vec/struct.Vec.html#method.get_mut
339 /// [`String`]: crate::string::String
340 /// [`&str`]: type@str
341 /// [`shrink_to_fit`]: Vec::shrink_to_fit
342 /// [`capacity`]: Vec::capacity
343 /// [`mem::size_of::<T>`]: core::mem::size_of
344 /// [`len`]: Vec::len
345 /// [`push`]: Vec::push
346 /// [`insert`]: Vec::insert
347 /// [`reserve`]: Vec::reserve
348 /// [owned slice]: Box
349 /// [slice]: ../../std/primitive.slice.html
350 /// [`&`]: ../../std/primitive.reference.html
351 #[stable(feature = "rust1", since = "1.0.0")]
352 #[cfg_attr(not(test), rustc_diagnostic_item = "vec_type")]
353 pub struct Vec<T, #[unstable(feature = "allocator_api", issue = "32838")] A: Allocator = Global> {
358 ////////////////////////////////////////////////////////////////////////////////
360 ////////////////////////////////////////////////////////////////////////////////
363 /// Constructs a new, empty `Vec<T>`.
365 /// The vector will not allocate until elements are pushed onto it.
370 /// # #![allow(unused_mut)]
371 /// let mut vec: Vec<i32> = Vec::new();
374 #[rustc_const_stable(feature = "const_vec_new", since = "1.39.0")]
375 #[stable(feature = "rust1", since = "1.0.0")]
376 pub const fn new() -> Self {
377 Vec { buf: RawVec::NEW, len: 0 }
380 /// Constructs a new, empty `Vec<T>` with the specified capacity.
382 /// The vector will be able to hold exactly `capacity` elements without
383 /// reallocating. If `capacity` is 0, the vector will not allocate.
385 /// It is important to note that although the returned vector has the
386 /// *capacity* specified, the vector will have a zero *length*. For an
387 /// explanation of the difference between length and capacity, see
388 /// *[Capacity and reallocation]*.
390 /// [Capacity and reallocation]: #capacity-and-reallocation
395 /// let mut vec = Vec::with_capacity(10);
397 /// // The vector contains no items, even though it has capacity for more
398 /// assert_eq!(vec.len(), 0);
399 /// assert_eq!(vec.capacity(), 10);
401 /// // These are all done without reallocating...
405 /// assert_eq!(vec.len(), 10);
406 /// assert_eq!(vec.capacity(), 10);
408 /// // ...but this may make the vector reallocate
410 /// assert_eq!(vec.len(), 11);
411 /// assert!(vec.capacity() >= 11);
414 #[stable(feature = "rust1", since = "1.0.0")]
415 pub fn with_capacity(capacity: usize) -> Self {
416 Self::with_capacity_in(capacity, Global)
419 /// Creates a `Vec<T>` directly from the raw components of another vector.
423 /// This is highly unsafe, due to the number of invariants that aren't
426 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
427 /// (at least, it's highly likely to be incorrect if it wasn't).
428 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
429 /// (`T` having a less strict alignment is not sufficient, the alignment really
430 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
431 /// allocated and deallocated with the same layout.)
432 /// * `length` needs to be less than or equal to `capacity`.
433 /// * `capacity` needs to be the capacity that the pointer was allocated with.
435 /// Violating these may cause problems like corrupting the allocator's
436 /// internal data structures. For example it is **not** safe
437 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
438 /// It's also not safe to build one from a `Vec<u16>` and its length, because
439 /// the allocator cares about the alignment, and these two types have different
440 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
441 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
443 /// The ownership of `ptr` is effectively transferred to the
444 /// `Vec<T>` which may then deallocate, reallocate or change the
445 /// contents of memory pointed to by the pointer at will. Ensure
446 /// that nothing else uses the pointer after calling this
449 /// [`String`]: crate::string::String
450 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
458 /// let v = vec![1, 2, 3];
460 // FIXME Update this when vec_into_raw_parts is stabilized
461 /// // Prevent running `v`'s destructor so we are in complete control
462 /// // of the allocation.
463 /// let mut v = mem::ManuallyDrop::new(v);
465 /// // Pull out the various important pieces of information about `v`
466 /// let p = v.as_mut_ptr();
467 /// let len = v.len();
468 /// let cap = v.capacity();
471 /// // Overwrite memory with 4, 5, 6
472 /// for i in 0..len as isize {
473 /// ptr::write(p.offset(i), 4 + i);
476 /// // Put everything back together into a Vec
477 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
478 /// assert_eq!(rebuilt, [4, 5, 6]);
482 #[stable(feature = "rust1", since = "1.0.0")]
483 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
484 unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
488 impl<T, A: Allocator> Vec<T, A> {
489 /// Constructs a new, empty `Vec<T, A>`.
491 /// The vector will not allocate until elements are pushed onto it.
496 /// #![feature(allocator_api)]
498 /// use std::alloc::System;
500 /// # #[allow(unused_mut)]
501 /// let mut vec: Vec<i32, _> = Vec::new_in(System);
504 #[unstable(feature = "allocator_api", issue = "32838")]
505 pub const fn new_in(alloc: A) -> Self {
506 Vec { buf: RawVec::new_in(alloc), len: 0 }
509 /// Constructs a new, empty `Vec<T, A>` with the specified capacity with the provided
512 /// The vector will be able to hold exactly `capacity` elements without
513 /// reallocating. If `capacity` is 0, the vector will not allocate.
515 /// It is important to note that although the returned vector has the
516 /// *capacity* specified, the vector will have a zero *length*. For an
517 /// explanation of the difference between length and capacity, see
518 /// *[Capacity and reallocation]*.
520 /// [Capacity and reallocation]: #capacity-and-reallocation
525 /// #![feature(allocator_api)]
527 /// use std::alloc::System;
529 /// let mut vec = Vec::with_capacity_in(10, System);
531 /// // The vector contains no items, even though it has capacity for more
532 /// assert_eq!(vec.len(), 0);
533 /// assert_eq!(vec.capacity(), 10);
535 /// // These are all done without reallocating...
539 /// assert_eq!(vec.len(), 10);
540 /// assert_eq!(vec.capacity(), 10);
542 /// // ...but this may make the vector reallocate
544 /// assert_eq!(vec.len(), 11);
545 /// assert!(vec.capacity() >= 11);
548 #[unstable(feature = "allocator_api", issue = "32838")]
549 pub fn with_capacity_in(capacity: usize, alloc: A) -> Self {
550 Vec { buf: RawVec::with_capacity_in(capacity, alloc), len: 0 }
553 /// Creates a `Vec<T, A>` directly from the raw components of another vector.
557 /// This is highly unsafe, due to the number of invariants that aren't
560 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
561 /// (at least, it's highly likely to be incorrect if it wasn't).
562 /// * `T` needs to have the same size and alignment as what `ptr` was allocated with.
563 /// (`T` having a less strict alignment is not sufficient, the alignment really
564 /// needs to be equal to satisfy the [`dealloc`] requirement that memory must be
565 /// allocated and deallocated with the same layout.)
566 /// * `length` needs to be less than or equal to `capacity`.
567 /// * `capacity` needs to be the capacity that the pointer was allocated with.
569 /// Violating these may cause problems like corrupting the allocator's
570 /// internal data structures. For example it is **not** safe
571 /// to build a `Vec<u8>` from a pointer to a C `char` array with length `size_t`.
572 /// It's also not safe to build one from a `Vec<u16>` and its length, because
573 /// the allocator cares about the alignment, and these two types have different
574 /// alignments. The buffer was allocated with alignment 2 (for `u16`), but after
575 /// turning it into a `Vec<u8>` it'll be deallocated with alignment 1.
577 /// The ownership of `ptr` is effectively transferred to the
578 /// `Vec<T>` which may then deallocate, reallocate or change the
579 /// contents of memory pointed to by the pointer at will. Ensure
580 /// that nothing else uses the pointer after calling this
583 /// [`String`]: crate::string::String
584 /// [`dealloc`]: crate::alloc::GlobalAlloc::dealloc
589 /// #![feature(allocator_api)]
591 /// use std::alloc::System;
596 /// let mut v = Vec::with_capacity_in(3, System);
601 // FIXME Update this when vec_into_raw_parts is stabilized
602 /// // Prevent running `v`'s destructor so we are in complete control
603 /// // of the allocation.
604 /// let mut v = mem::ManuallyDrop::new(v);
606 /// // Pull out the various important pieces of information about `v`
607 /// let p = v.as_mut_ptr();
608 /// let len = v.len();
609 /// let cap = v.capacity();
610 /// let alloc = v.allocator();
613 /// // Overwrite memory with 4, 5, 6
614 /// for i in 0..len as isize {
615 /// ptr::write(p.offset(i), 4 + i);
618 /// // Put everything back together into a Vec
619 /// let rebuilt = Vec::from_raw_parts_in(p, len, cap, alloc.clone());
620 /// assert_eq!(rebuilt, [4, 5, 6]);
624 #[unstable(feature = "allocator_api", issue = "32838")]
625 pub unsafe fn from_raw_parts_in(ptr: *mut T, length: usize, capacity: usize, alloc: A) -> Self {
626 unsafe { Vec { buf: RawVec::from_raw_parts_in(ptr, capacity, alloc), len: length } }
629 /// Decomposes a `Vec<T>` into its raw components.
631 /// Returns the raw pointer to the underlying data, the length of
632 /// the vector (in elements), and the allocated capacity of the
633 /// data (in elements). These are the same arguments in the same
634 /// order as the arguments to [`from_raw_parts`].
636 /// After calling this function, the caller is responsible for the
637 /// memory previously managed by the `Vec`. The only way to do
638 /// this is to convert the raw pointer, length, and capacity back
639 /// into a `Vec` with the [`from_raw_parts`] function, allowing
640 /// the destructor to perform the cleanup.
642 /// [`from_raw_parts`]: Vec::from_raw_parts
647 /// #![feature(vec_into_raw_parts)]
648 /// let v: Vec<i32> = vec![-1, 0, 1];
650 /// let (ptr, len, cap) = v.into_raw_parts();
652 /// let rebuilt = unsafe {
653 /// // We can now make changes to the components, such as
654 /// // transmuting the raw pointer to a compatible type.
655 /// let ptr = ptr as *mut u32;
657 /// Vec::from_raw_parts(ptr, len, cap)
659 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
661 #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
662 pub fn into_raw_parts(self) -> (*mut T, usize, usize) {
663 let mut me = ManuallyDrop::new(self);
664 (me.as_mut_ptr(), me.len(), me.capacity())
667 /// Decomposes a `Vec<T>` into its raw components.
669 /// Returns the raw pointer to the underlying data, the length of the vector (in elements),
670 /// the allocated capacity of the data (in elements), and the allocator. These are the same
671 /// arguments in the same order as the arguments to [`from_raw_parts_in`].
673 /// After calling this function, the caller is responsible for the
674 /// memory previously managed by the `Vec`. The only way to do
675 /// this is to convert the raw pointer, length, and capacity back
676 /// into a `Vec` with the [`from_raw_parts_in`] function, allowing
677 /// the destructor to perform the cleanup.
679 /// [`from_raw_parts_in`]: Vec::from_raw_parts_in
684 /// #![feature(allocator_api, vec_into_raw_parts)]
686 /// use std::alloc::System;
688 /// let mut v: Vec<i32, System> = Vec::new_in(System);
693 /// let (ptr, len, cap, alloc) = v.into_raw_parts_with_alloc();
695 /// let rebuilt = unsafe {
696 /// // We can now make changes to the components, such as
697 /// // transmuting the raw pointer to a compatible type.
698 /// let ptr = ptr as *mut u32;
700 /// Vec::from_raw_parts_in(ptr, len, cap, alloc)
702 /// assert_eq!(rebuilt, [4294967295, 0, 1]);
704 #[unstable(feature = "allocator_api", issue = "32838")]
705 // #[unstable(feature = "vec_into_raw_parts", reason = "new API", issue = "65816")]
706 pub fn into_raw_parts_with_alloc(self) -> (*mut T, usize, usize, A) {
707 let mut me = ManuallyDrop::new(self);
709 let capacity = me.capacity();
710 let ptr = me.as_mut_ptr();
711 let alloc = unsafe { ptr::read(me.allocator()) };
712 (ptr, len, capacity, alloc)
715 /// Returns the number of elements the vector can hold without
721 /// let vec: Vec<i32> = Vec::with_capacity(10);
722 /// assert_eq!(vec.capacity(), 10);
725 #[stable(feature = "rust1", since = "1.0.0")]
726 pub fn capacity(&self) -> usize {
730 /// Reserves capacity for at least `additional` more elements to be inserted
731 /// in the given `Vec<T>`. The collection may reserve more space to avoid
732 /// frequent reallocations. After calling `reserve`, capacity will be
733 /// greater than or equal to `self.len() + additional`. Does nothing if
734 /// capacity is already sufficient.
738 /// Panics if the new capacity exceeds `isize::MAX` bytes.
743 /// let mut vec = vec![1];
745 /// assert!(vec.capacity() >= 11);
747 #[stable(feature = "rust1", since = "1.0.0")]
748 pub fn reserve(&mut self, additional: usize) {
749 self.buf.reserve(self.len, additional);
752 /// Reserves the minimum capacity for exactly `additional` more elements to
753 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
754 /// capacity will be greater than or equal to `self.len() + additional`.
755 /// Does nothing if the capacity is already sufficient.
757 /// Note that the allocator may give the collection more space than it
758 /// requests. Therefore, capacity can not be relied upon to be precisely
759 /// minimal. Prefer `reserve` if future insertions are expected.
763 /// Panics if the new capacity overflows `usize`.
768 /// let mut vec = vec![1];
769 /// vec.reserve_exact(10);
770 /// assert!(vec.capacity() >= 11);
772 #[stable(feature = "rust1", since = "1.0.0")]
773 pub fn reserve_exact(&mut self, additional: usize) {
774 self.buf.reserve_exact(self.len, additional);
777 /// Tries to reserve capacity for at least `additional` more elements to be inserted
778 /// in the given `Vec<T>`. The collection may reserve more space to avoid
779 /// frequent reallocations. After calling `try_reserve`, capacity will be
780 /// greater than or equal to `self.len() + additional`. Does nothing if
781 /// capacity is already sufficient.
785 /// If the capacity overflows, or the allocator reports a failure, then an error
791 /// #![feature(try_reserve)]
792 /// use std::collections::TryReserveError;
794 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
795 /// let mut output = Vec::new();
797 /// // Pre-reserve the memory, exiting if we can't
798 /// output.try_reserve(data.len())?;
800 /// // Now we know this can't OOM in the middle of our complex work
801 /// output.extend(data.iter().map(|&val| {
802 /// val * 2 + 5 // very complicated
807 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
809 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
810 pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
811 self.buf.try_reserve(self.len, additional)
814 /// Tries to reserve the minimum capacity for exactly `additional`
815 /// elements to be inserted in the given `Vec<T>`. After calling
816 /// `try_reserve_exact`, capacity will be greater than or equal to
817 /// `self.len() + additional` if it returns `Ok(())`.
818 /// Does nothing if the capacity is already sufficient.
820 /// Note that the allocator may give the collection more space than it
821 /// requests. Therefore, capacity can not be relied upon to be precisely
822 /// minimal. Prefer `reserve` if future insertions are expected.
826 /// If the capacity overflows, or the allocator reports a failure, then an error
832 /// #![feature(try_reserve)]
833 /// use std::collections::TryReserveError;
835 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, TryReserveError> {
836 /// let mut output = Vec::new();
838 /// // Pre-reserve the memory, exiting if we can't
839 /// output.try_reserve_exact(data.len())?;
841 /// // Now we know this can't OOM in the middle of our complex work
842 /// output.extend(data.iter().map(|&val| {
843 /// val * 2 + 5 // very complicated
848 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
850 #[unstable(feature = "try_reserve", reason = "new API", issue = "48043")]
851 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
852 self.buf.try_reserve_exact(self.len, additional)
855 /// Shrinks the capacity of the vector as much as possible.
857 /// It will drop down as close as possible to the length but the allocator
858 /// may still inform the vector that there is space for a few more elements.
863 /// let mut vec = Vec::with_capacity(10);
864 /// vec.extend([1, 2, 3].iter().cloned());
865 /// assert_eq!(vec.capacity(), 10);
866 /// vec.shrink_to_fit();
867 /// assert!(vec.capacity() >= 3);
869 #[stable(feature = "rust1", since = "1.0.0")]
870 pub fn shrink_to_fit(&mut self) {
871 // The capacity is never less than the length, and there's nothing to do when
872 // they are equal, so we can avoid the panic case in `RawVec::shrink_to_fit`
873 // by only calling it with a greater capacity.
874 if self.capacity() > self.len {
875 self.buf.shrink_to_fit(self.len);
879 /// Shrinks the capacity of the vector with a lower bound.
881 /// The capacity will remain at least as large as both the length
882 /// and the supplied value.
886 /// Panics if the current capacity is smaller than the supplied
887 /// minimum capacity.
892 /// #![feature(shrink_to)]
893 /// let mut vec = Vec::with_capacity(10);
894 /// vec.extend([1, 2, 3].iter().cloned());
895 /// assert_eq!(vec.capacity(), 10);
896 /// vec.shrink_to(4);
897 /// assert!(vec.capacity() >= 4);
898 /// vec.shrink_to(0);
899 /// assert!(vec.capacity() >= 3);
901 #[unstable(feature = "shrink_to", reason = "new API", issue = "56431")]
902 pub fn shrink_to(&mut self, min_capacity: usize) {
903 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
906 /// Converts the vector into [`Box<[T]>`][owned slice].
908 /// Note that this will drop any excess capacity.
910 /// [owned slice]: Box
915 /// let v = vec![1, 2, 3];
917 /// let slice = v.into_boxed_slice();
920 /// Any excess capacity is removed:
923 /// let mut vec = Vec::with_capacity(10);
924 /// vec.extend([1, 2, 3].iter().cloned());
926 /// assert_eq!(vec.capacity(), 10);
927 /// let slice = vec.into_boxed_slice();
928 /// assert_eq!(slice.into_vec().capacity(), 3);
930 #[stable(feature = "rust1", since = "1.0.0")]
931 pub fn into_boxed_slice(mut self) -> Box<[T], A> {
933 self.shrink_to_fit();
934 let me = ManuallyDrop::new(self);
935 let buf = ptr::read(&me.buf);
937 buf.into_box(len).assume_init()
941 /// Shortens the vector, keeping the first `len` elements and dropping
944 /// If `len` is greater than the vector's current length, this has no
947 /// The [`drain`] method can emulate `truncate`, but causes the excess
948 /// elements to be returned instead of dropped.
950 /// Note that this method has no effect on the allocated capacity
955 /// Truncating a five element vector to two elements:
958 /// let mut vec = vec![1, 2, 3, 4, 5];
960 /// assert_eq!(vec, [1, 2]);
963 /// No truncation occurs when `len` is greater than the vector's current
967 /// let mut vec = vec![1, 2, 3];
969 /// assert_eq!(vec, [1, 2, 3]);
972 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
976 /// let mut vec = vec![1, 2, 3];
978 /// assert_eq!(vec, []);
981 /// [`clear`]: Vec::clear
982 /// [`drain`]: Vec::drain
983 #[stable(feature = "rust1", since = "1.0.0")]
984 pub fn truncate(&mut self, len: usize) {
985 // This is safe because:
987 // * the slice passed to `drop_in_place` is valid; the `len > self.len`
988 // case avoids creating an invalid slice, and
989 // * the `len` of the vector is shrunk before calling `drop_in_place`,
990 // such that no value will be dropped twice in case `drop_in_place`
991 // were to panic once (if it panics twice, the program aborts).
996 let remaining_len = self.len - len;
997 let s = ptr::slice_from_raw_parts_mut(self.as_mut_ptr().add(len), remaining_len);
999 ptr::drop_in_place(s);
1003 /// Extracts a slice containing the entire vector.
1005 /// Equivalent to `&s[..]`.
1010 /// use std::io::{self, Write};
1011 /// let buffer = vec![1, 2, 3, 5, 8];
1012 /// io::sink().write(buffer.as_slice()).unwrap();
1015 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1016 pub fn as_slice(&self) -> &[T] {
1020 /// Extracts a mutable slice of the entire vector.
1022 /// Equivalent to `&mut s[..]`.
1027 /// use std::io::{self, Read};
1028 /// let mut buffer = vec![0; 3];
1029 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
1032 #[stable(feature = "vec_as_slice", since = "1.7.0")]
1033 pub fn as_mut_slice(&mut self) -> &mut [T] {
1037 /// Returns a raw pointer to the vector's buffer.
1039 /// The caller must ensure that the vector outlives the pointer this
1040 /// function returns, or else it will end up pointing to garbage.
1041 /// Modifying the vector may cause its buffer to be reallocated,
1042 /// which would also make any pointers to it invalid.
1044 /// The caller must also ensure that the memory the pointer (non-transitively) points to
1045 /// is never written to (except inside an `UnsafeCell`) using this pointer or any pointer
1046 /// derived from it. If you need to mutate the contents of the slice, use [`as_mut_ptr`].
1051 /// let x = vec![1, 2, 4];
1052 /// let x_ptr = x.as_ptr();
1055 /// for i in 0..x.len() {
1056 /// assert_eq!(*x_ptr.add(i), 1 << i);
1061 /// [`as_mut_ptr`]: Vec::as_mut_ptr
1062 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1064 pub fn as_ptr(&self) -> *const T {
1065 // We shadow the slice method of the same name to avoid going through
1066 // `deref`, which creates an intermediate reference.
1067 let ptr = self.buf.ptr();
1069 assume(!ptr.is_null());
1074 /// Returns an unsafe mutable pointer to the vector's buffer.
1076 /// The caller must ensure that the vector outlives the pointer this
1077 /// function returns, or else it will end up pointing to garbage.
1078 /// Modifying the vector may cause its buffer to be reallocated,
1079 /// which would also make any pointers to it invalid.
1084 /// // Allocate vector big enough for 4 elements.
1086 /// let mut x: Vec<i32> = Vec::with_capacity(size);
1087 /// let x_ptr = x.as_mut_ptr();
1089 /// // Initialize elements via raw pointer writes, then set length.
1091 /// for i in 0..size {
1092 /// *x_ptr.add(i) = i as i32;
1094 /// x.set_len(size);
1096 /// assert_eq!(&*x, &[0, 1, 2, 3]);
1098 #[stable(feature = "vec_as_ptr", since = "1.37.0")]
1100 pub fn as_mut_ptr(&mut self) -> *mut T {
1101 // We shadow the slice method of the same name to avoid going through
1102 // `deref_mut`, which creates an intermediate reference.
1103 let ptr = self.buf.ptr();
1105 assume(!ptr.is_null());
1110 /// Returns a reference to the underlying allocator.
1111 #[unstable(feature = "allocator_api", issue = "32838")]
1113 pub fn allocator(&self) -> &A {
1114 self.buf.allocator()
1117 /// Forces the length of the vector to `new_len`.
1119 /// This is a low-level operation that maintains none of the normal
1120 /// invariants of the type. Normally changing the length of a vector
1121 /// is done using one of the safe operations instead, such as
1122 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
1124 /// [`truncate`]: Vec::truncate
1125 /// [`resize`]: Vec::resize
1126 /// [`extend`]: Extend::extend
1127 /// [`clear`]: Vec::clear
1131 /// - `new_len` must be less than or equal to [`capacity()`].
1132 /// - The elements at `old_len..new_len` must be initialized.
1134 /// [`capacity()`]: Vec::capacity
1138 /// This method can be useful for situations in which the vector
1139 /// is serving as a buffer for other code, particularly over FFI:
1142 /// # #![allow(dead_code)]
1143 /// # // This is just a minimal skeleton for the doc example;
1144 /// # // don't use this as a starting point for a real library.
1145 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
1146 /// # const Z_OK: i32 = 0;
1148 /// # fn deflateGetDictionary(
1149 /// # strm: *mut std::ffi::c_void,
1150 /// # dictionary: *mut u8,
1151 /// # dictLength: *mut usize,
1154 /// # impl StreamWrapper {
1155 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
1156 /// // Per the FFI method's docs, "32768 bytes is always enough".
1157 /// let mut dict = Vec::with_capacity(32_768);
1158 /// let mut dict_length = 0;
1159 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
1160 /// // 1. `dict_length` elements were initialized.
1161 /// // 2. `dict_length` <= the capacity (32_768)
1162 /// // which makes `set_len` safe to call.
1164 /// // Make the FFI call...
1165 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
1167 /// // ...and update the length to what was initialized.
1168 /// dict.set_len(dict_length);
1178 /// While the following example is sound, there is a memory leak since
1179 /// the inner vectors were not freed prior to the `set_len` call:
1182 /// let mut vec = vec![vec![1, 0, 0],
1186 /// // 1. `old_len..0` is empty so no elements need to be initialized.
1187 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
1193 /// Normally, here, one would use [`clear`] instead to correctly drop
1194 /// the contents and thus not leak memory.
1196 #[stable(feature = "rust1", since = "1.0.0")]
1197 pub unsafe fn set_len(&mut self, new_len: usize) {
1198 debug_assert!(new_len <= self.capacity());
1203 /// Removes an element from the vector and returns it.
1205 /// The removed element is replaced by the last element of the vector.
1207 /// This does not preserve ordering, but is O(1).
1211 /// Panics if `index` is out of bounds.
1216 /// let mut v = vec!["foo", "bar", "baz", "qux"];
1218 /// assert_eq!(v.swap_remove(1), "bar");
1219 /// assert_eq!(v, ["foo", "qux", "baz"]);
1221 /// assert_eq!(v.swap_remove(0), "foo");
1222 /// assert_eq!(v, ["baz", "qux"]);
1225 #[stable(feature = "rust1", since = "1.0.0")]
1226 pub fn swap_remove(&mut self, index: usize) -> T {
1229 fn assert_failed(index: usize, len: usize) -> ! {
1230 panic!("swap_remove index (is {}) should be < len (is {})", index, len);
1233 let len = self.len();
1235 assert_failed(index, len);
1238 // We replace self[index] with the last element. Note that if the
1239 // bounds check above succeeds there must be a last element (which
1240 // can be self[index] itself).
1241 let last = ptr::read(self.as_ptr().add(len - 1));
1242 let hole = self.as_mut_ptr().add(index);
1243 self.set_len(len - 1);
1244 ptr::replace(hole, last)
1248 /// Inserts an element at position `index` within the vector, shifting all
1249 /// elements after it to the right.
1253 /// Panics if `index > len`.
1258 /// let mut vec = vec![1, 2, 3];
1259 /// vec.insert(1, 4);
1260 /// assert_eq!(vec, [1, 4, 2, 3]);
1261 /// vec.insert(4, 5);
1262 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
1264 #[stable(feature = "rust1", since = "1.0.0")]
1265 pub fn insert(&mut self, index: usize, element: T) {
1268 fn assert_failed(index: usize, len: usize) -> ! {
1269 panic!("insertion index (is {}) should be <= len (is {})", index, len);
1272 let len = self.len();
1274 assert_failed(index, len);
1277 // space for the new element
1278 if len == self.buf.capacity() {
1284 // The spot to put the new value
1286 let p = self.as_mut_ptr().add(index);
1287 // Shift everything over to make space. (Duplicating the
1288 // `index`th element into two consecutive places.)
1289 ptr::copy(p, p.offset(1), len - index);
1290 // Write it in, overwriting the first copy of the `index`th
1292 ptr::write(p, element);
1294 self.set_len(len + 1);
1298 /// Removes and returns the element at position `index` within the vector,
1299 /// shifting all elements after it to the left.
1303 /// Panics if `index` is out of bounds.
1308 /// let mut v = vec![1, 2, 3];
1309 /// assert_eq!(v.remove(1), 2);
1310 /// assert_eq!(v, [1, 3]);
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 pub fn remove(&mut self, index: usize) -> T {
1316 fn assert_failed(index: usize, len: usize) -> ! {
1317 panic!("removal index (is {}) should be < len (is {})", index, len);
1320 let len = self.len();
1322 assert_failed(index, len);
1328 // the place we are taking from.
1329 let ptr = self.as_mut_ptr().add(index);
1330 // copy it out, unsafely having a copy of the value on
1331 // the stack and in the vector at the same time.
1332 ret = ptr::read(ptr);
1334 // Shift everything down to fill in that spot.
1335 ptr::copy(ptr.offset(1), ptr, len - index - 1);
1337 self.set_len(len - 1);
1342 /// Retains only the elements specified by the predicate.
1344 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
1345 /// This method operates in place, visiting each element exactly once in the
1346 /// original order, and preserves the order of the retained elements.
1351 /// let mut vec = vec![1, 2, 3, 4];
1352 /// vec.retain(|&x| x % 2 == 0);
1353 /// assert_eq!(vec, [2, 4]);
1356 /// The exact order may be useful for tracking external state, like an index.
1359 /// let mut vec = vec![1, 2, 3, 4, 5];
1360 /// let keep = [false, true, true, false, true];
1362 /// vec.retain(|_| (keep[i], i += 1).0);
1363 /// assert_eq!(vec, [2, 3, 5]);
1365 #[stable(feature = "rust1", since = "1.0.0")]
1366 pub fn retain<F>(&mut self, mut f: F)
1368 F: FnMut(&T) -> bool,
1370 let len = self.len();
1373 let v = &mut **self;
1384 self.truncate(len - del);
1388 /// Removes all but the first of consecutive elements in the vector that resolve to the same
1391 /// If the vector is sorted, this removes all duplicates.
1396 /// let mut vec = vec![10, 20, 21, 30, 20];
1398 /// vec.dedup_by_key(|i| *i / 10);
1400 /// assert_eq!(vec, [10, 20, 30, 20]);
1402 #[stable(feature = "dedup_by", since = "1.16.0")]
1404 pub fn dedup_by_key<F, K>(&mut self, mut key: F)
1406 F: FnMut(&mut T) -> K,
1409 self.dedup_by(|a, b| key(a) == key(b))
1412 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
1415 /// The `same_bucket` function is passed references to two elements from the vector and
1416 /// must determine if the elements compare equal. The elements are passed in opposite order
1417 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
1419 /// If the vector is sorted, this removes all duplicates.
1424 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
1426 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
1428 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
1430 #[stable(feature = "dedup_by", since = "1.16.0")]
1431 pub fn dedup_by<F>(&mut self, same_bucket: F)
1433 F: FnMut(&mut T, &mut T) -> bool,
1436 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1442 /// Appends an element to the back of a collection.
1446 /// Panics if the new capacity exceeds `isize::MAX` bytes.
1451 /// let mut vec = vec![1, 2];
1453 /// assert_eq!(vec, [1, 2, 3]);
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 pub fn push(&mut self, value: T) {
1458 // This will panic or abort if we would allocate > isize::MAX bytes
1459 // or if the length increment would overflow for zero-sized types.
1460 if self.len == self.buf.capacity() {
1464 let end = self.as_mut_ptr().add(self.len);
1465 ptr::write(end, value);
1470 /// Removes the last element from a vector and returns it, or [`None`] if it
1476 /// let mut vec = vec![1, 2, 3];
1477 /// assert_eq!(vec.pop(), Some(3));
1478 /// assert_eq!(vec, [1, 2]);
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 pub fn pop(&mut self) -> Option<T> {
1488 Some(ptr::read(self.as_ptr().add(self.len())))
1493 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1497 /// Panics if the number of elements in the vector overflows a `usize`.
1502 /// let mut vec = vec![1, 2, 3];
1503 /// let mut vec2 = vec![4, 5, 6];
1504 /// vec.append(&mut vec2);
1505 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1506 /// assert_eq!(vec2, []);
1509 #[stable(feature = "append", since = "1.4.0")]
1510 pub fn append(&mut self, other: &mut Self) {
1512 self.append_elements(other.as_slice() as _);
1517 /// Appends elements to `Self` from other buffer.
1519 unsafe fn append_elements(&mut self, other: *const [T]) {
1520 let count = unsafe { (*other).len() };
1521 self.reserve(count);
1522 let len = self.len();
1523 unsafe { ptr::copy_nonoverlapping(other as *const T, self.as_mut_ptr().add(len), count) };
1527 /// Creates a draining iterator that removes the specified range in the vector
1528 /// and yields the removed items.
1530 /// When the iterator **is** dropped, all elements in the range are removed
1531 /// from the vector, even if the iterator was not fully consumed. If the
1532 /// iterator **is not** dropped (with [`mem::forget`] for example), it is
1533 /// unspecified how many elements are removed.
1537 /// Panics if the starting point is greater than the end point or if
1538 /// the end point is greater than the length of the vector.
1543 /// let mut v = vec![1, 2, 3];
1544 /// let u: Vec<_> = v.drain(1..).collect();
1545 /// assert_eq!(v, &[1]);
1546 /// assert_eq!(u, &[2, 3]);
1548 /// // A full range clears the vector
1550 /// assert_eq!(v, &[]);
1552 #[stable(feature = "drain", since = "1.6.0")]
1553 pub fn drain<R>(&mut self, range: R) -> Drain<'_, T, A>
1555 R: RangeBounds<usize>,
1559 // When the Drain is first created, it shortens the length of
1560 // the source vector to make sure no uninitialized or moved-from elements
1561 // are accessible at all if the Drain's destructor never gets to run.
1563 // Drain will ptr::read out the values to remove.
1564 // When finished, remaining tail of the vec is copied back to cover
1565 // the hole, and the vector length is restored to the new length.
1567 let len = self.len();
1568 let Range { start, end } = range.assert_len(len);
1571 // set self.vec length's to start, to be safe in case Drain is leaked
1572 self.set_len(start);
1573 // Use the borrow in the IterMut to indicate borrowing behavior of the
1574 // whole Drain iterator (like &mut T).
1575 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start), end - start);
1578 tail_len: len - end,
1579 iter: range_slice.iter(),
1580 vec: NonNull::from(self),
1585 /// Clears the vector, removing all values.
1587 /// Note that this method has no effect on the allocated capacity
1593 /// let mut v = vec![1, 2, 3];
1597 /// assert!(v.is_empty());
1600 #[stable(feature = "rust1", since = "1.0.0")]
1601 pub fn clear(&mut self) {
1605 /// Returns the number of elements in the vector, also referred to
1606 /// as its 'length'.
1611 /// let a = vec![1, 2, 3];
1612 /// assert_eq!(a.len(), 3);
1614 #[doc(alias = "length")]
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 pub fn len(&self) -> usize {
1621 /// Returns `true` if the vector contains no elements.
1626 /// let mut v = Vec::new();
1627 /// assert!(v.is_empty());
1630 /// assert!(!v.is_empty());
1632 #[stable(feature = "rust1", since = "1.0.0")]
1633 pub fn is_empty(&self) -> bool {
1637 /// Splits the collection into two at the given index.
1639 /// Returns a newly allocated vector containing the elements in the range
1640 /// `[at, len)`. After the call, the original vector will be left containing
1641 /// the elements `[0, at)` with its previous capacity unchanged.
1645 /// Panics if `at > len`.
1650 /// let mut vec = vec![1, 2, 3];
1651 /// let vec2 = vec.split_off(1);
1652 /// assert_eq!(vec, [1]);
1653 /// assert_eq!(vec2, [2, 3]);
1656 #[must_use = "use `.truncate()` if you don't need the other half"]
1657 #[stable(feature = "split_off", since = "1.4.0")]
1658 pub fn split_off(&mut self, at: usize) -> Self
1664 fn assert_failed(at: usize, len: usize) -> ! {
1665 panic!("`at` split index (is {}) should be <= len (is {})", at, len);
1668 if at > self.len() {
1669 assert_failed(at, self.len());
1673 // the new vector can take over the original buffer and avoid the copy
1674 return mem::replace(
1676 Vec::with_capacity_in(self.capacity(), self.allocator().clone()),
1680 let other_len = self.len - at;
1681 let mut other = Vec::with_capacity_in(other_len, self.allocator().clone());
1683 // Unsafely `set_len` and copy items to `other`.
1686 other.set_len(other_len);
1688 ptr::copy_nonoverlapping(self.as_ptr().add(at), other.as_mut_ptr(), other.len());
1693 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1695 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1696 /// difference, with each additional slot filled with the result of
1697 /// calling the closure `f`. The return values from `f` will end up
1698 /// in the `Vec` in the order they have been generated.
1700 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1702 /// This method uses a closure to create new values on every push. If
1703 /// you'd rather [`Clone`] a given value, use [`Vec::resize`]. If you
1704 /// want to use the [`Default`] trait to generate values, you can
1705 /// pass [`Default::default`] as the second argument.
1710 /// let mut vec = vec![1, 2, 3];
1711 /// vec.resize_with(5, Default::default);
1712 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1714 /// let mut vec = vec![];
1716 /// vec.resize_with(4, || { p *= 2; p });
1717 /// assert_eq!(vec, [2, 4, 8, 16]);
1719 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1720 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1724 let len = self.len();
1726 self.extend_with(new_len - len, ExtendFunc(f));
1728 self.truncate(new_len);
1732 /// Consumes and leaks the `Vec`, returning a mutable reference to the contents,
1733 /// `&'a mut [T]`. Note that the type `T` must outlive the chosen lifetime
1734 /// `'a`. If the type has only static references, or none at all, then this
1735 /// may be chosen to be `'static`.
1737 /// This function is similar to the [`leak`][Box::leak] function on [`Box`]
1738 /// except that there is no way to recover the leaked memory.
1740 /// This function is mainly useful for data that lives for the remainder of
1741 /// the program's life. Dropping the returned reference will cause a memory
1749 /// let x = vec![1, 2, 3];
1750 /// let static_ref: &'static mut [usize] = x.leak();
1751 /// static_ref[0] += 1;
1752 /// assert_eq!(static_ref, &[2, 2, 3]);
1754 #[stable(feature = "vec_leak", since = "1.47.0")]
1756 pub fn leak<'a>(self) -> &'a mut [T]
1760 Box::leak(self.into_boxed_slice())
1763 /// Returns the remaining spare capacity of the vector as a slice of
1764 /// `MaybeUninit<T>`.
1766 /// The returned slice can be used to fill the vector with data (e.g. by
1767 /// reading from a file) before marking the data as initialized using the
1768 /// [`set_len`] method.
1770 /// [`set_len`]: Vec::set_len
1775 /// #![feature(vec_spare_capacity, maybe_uninit_extra)]
1777 /// // Allocate vector big enough for 10 elements.
1778 /// let mut v = Vec::with_capacity(10);
1780 /// // Fill in the first 3 elements.
1781 /// let uninit = v.spare_capacity_mut();
1782 /// uninit[0].write(0);
1783 /// uninit[1].write(1);
1784 /// uninit[2].write(2);
1786 /// // Mark the first 3 elements of the vector as being initialized.
1791 /// assert_eq!(&v, &[0, 1, 2]);
1793 #[unstable(feature = "vec_spare_capacity", issue = "75017")]
1795 pub fn spare_capacity_mut(&mut self) -> &mut [MaybeUninit<T>] {
1797 slice::from_raw_parts_mut(
1798 self.as_mut_ptr().add(self.len) as *mut MaybeUninit<T>,
1799 self.buf.capacity() - self.len,
1805 impl<T: Clone, A: Allocator> Vec<T, A> {
1806 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1808 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1809 /// difference, with each additional slot filled with `value`.
1810 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1812 /// This method requires `T` to implement [`Clone`],
1813 /// in order to be able to clone the passed value.
1814 /// If you need more flexibility (or want to rely on [`Default`] instead of
1815 /// [`Clone`]), use [`Vec::resize_with`].
1820 /// let mut vec = vec!["hello"];
1821 /// vec.resize(3, "world");
1822 /// assert_eq!(vec, ["hello", "world", "world"]);
1824 /// let mut vec = vec![1, 2, 3, 4];
1825 /// vec.resize(2, 0);
1826 /// assert_eq!(vec, [1, 2]);
1828 #[stable(feature = "vec_resize", since = "1.5.0")]
1829 pub fn resize(&mut self, new_len: usize, value: T) {
1830 let len = self.len();
1833 self.extend_with(new_len - len, ExtendElement(value))
1835 self.truncate(new_len);
1839 /// Clones and appends all elements in a slice to the `Vec`.
1841 /// Iterates over the slice `other`, clones each element, and then appends
1842 /// it to this `Vec`. The `other` vector is traversed in-order.
1844 /// Note that this function is same as [`extend`] except that it is
1845 /// specialized to work with slices instead. If and when Rust gets
1846 /// specialization this function will likely be deprecated (but still
1852 /// let mut vec = vec![1];
1853 /// vec.extend_from_slice(&[2, 3, 4]);
1854 /// assert_eq!(vec, [1, 2, 3, 4]);
1857 /// [`extend`]: Vec::extend
1858 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1859 pub fn extend_from_slice(&mut self, other: &[T]) {
1860 self.spec_extend(other.iter())
1864 // This code generalizes `extend_with_{element,default}`.
1865 trait ExtendWith<T> {
1866 fn next(&mut self) -> T;
1870 struct ExtendElement<T>(T);
1871 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1872 fn next(&mut self) -> T {
1875 fn last(self) -> T {
1880 struct ExtendDefault;
1881 impl<T: Default> ExtendWith<T> for ExtendDefault {
1882 fn next(&mut self) -> T {
1885 fn last(self) -> T {
1890 struct ExtendFunc<F>(F);
1891 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1892 fn next(&mut self) -> T {
1895 fn last(mut self) -> T {
1900 impl<T, A: Allocator> Vec<T, A> {
1901 /// Extend the vector by `n` values, using the given generator.
1902 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1906 let mut ptr = self.as_mut_ptr().add(self.len());
1907 // Use SetLenOnDrop to work around bug where compiler
1908 // may not realize the store through `ptr` through self.set_len()
1910 let mut local_len = SetLenOnDrop::new(&mut self.len);
1912 // Write all elements except the last one
1914 ptr::write(ptr, value.next());
1915 ptr = ptr.offset(1);
1916 // Increment the length in every step in case next() panics
1917 local_len.increment_len(1);
1921 // We can write the last element directly without cloning needlessly
1922 ptr::write(ptr, value.last());
1923 local_len.increment_len(1);
1926 // len set by scope guard
1931 impl<T: PartialEq, A: Allocator> Vec<T, A> {
1932 /// Removes consecutive repeated elements in the vector according to the
1933 /// [`PartialEq`] trait implementation.
1935 /// If the vector is sorted, this removes all duplicates.
1940 /// let mut vec = vec![1, 2, 2, 3, 2];
1944 /// assert_eq!(vec, [1, 2, 3, 2]);
1946 #[stable(feature = "rust1", since = "1.0.0")]
1948 pub fn dedup(&mut self) {
1949 self.dedup_by(|a, b| a == b)
1953 ////////////////////////////////////////////////////////////////////////////////
1954 // Internal methods and functions
1955 ////////////////////////////////////////////////////////////////////////////////
1958 #[stable(feature = "rust1", since = "1.0.0")]
1959 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1960 <T as SpecFromElem>::from_elem(elem, n, Global)
1964 #[unstable(feature = "allocator_api", issue = "32838")]
1965 pub fn from_elem_in<T: Clone, A: Allocator>(elem: T, n: usize, alloc: A) -> Vec<T, A> {
1966 <T as SpecFromElem>::from_elem(elem, n, alloc)
1969 ////////////////////////////////////////////////////////////////////////////////
1970 // Common trait implementations for Vec
1971 ////////////////////////////////////////////////////////////////////////////////
1973 #[stable(feature = "rust1", since = "1.0.0")]
1974 impl<T, A: Allocator> ops::Deref for Vec<T, A> {
1977 fn deref(&self) -> &[T] {
1978 unsafe { slice::from_raw_parts(self.as_ptr(), self.len) }
1982 #[stable(feature = "rust1", since = "1.0.0")]
1983 impl<T, A: Allocator> ops::DerefMut for Vec<T, A> {
1984 fn deref_mut(&mut self) -> &mut [T] {
1985 unsafe { slice::from_raw_parts_mut(self.as_mut_ptr(), self.len) }
1989 #[stable(feature = "rust1", since = "1.0.0")]
1990 impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
1992 fn clone(&self) -> Self {
1993 let alloc = self.allocator().clone();
1994 <[T]>::to_vec_in(&**self, alloc)
1997 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1998 // required for this method definition, is not available. Instead use the
1999 // `slice::to_vec` function which is only available with cfg(test)
2000 // NB see the slice::hack module in slice.rs for more information
2002 fn clone(&self) -> Self {
2003 let alloc = self.allocator().clone();
2004 crate::slice::to_vec(&**self, alloc)
2007 fn clone_from(&mut self, other: &Self) {
2008 // drop anything that will not be overwritten
2009 self.truncate(other.len());
2011 // self.len <= other.len due to the truncate above, so the
2012 // slices here are always in-bounds.
2013 let (init, tail) = other.split_at(self.len());
2015 // reuse the contained values' allocations/resources.
2016 self.clone_from_slice(init);
2017 self.extend_from_slice(tail);
2021 #[stable(feature = "rust1", since = "1.0.0")]
2022 impl<T: Hash, A: Allocator> Hash for Vec<T, A> {
2024 fn hash<H: Hasher>(&self, state: &mut H) {
2025 Hash::hash(&**self, state)
2029 #[stable(feature = "rust1", since = "1.0.0")]
2030 #[rustc_on_unimplemented(
2031 message = "vector indices are of type `usize` or ranges of `usize`",
2032 label = "vector indices are of type `usize` or ranges of `usize`"
2034 impl<T, I: SliceIndex<[T]>, A: Allocator> Index<I> for Vec<T, A> {
2035 type Output = I::Output;
2038 fn index(&self, index: I) -> &Self::Output {
2039 Index::index(&**self, index)
2043 #[stable(feature = "rust1", since = "1.0.0")]
2044 #[rustc_on_unimplemented(
2045 message = "vector indices are of type `usize` or ranges of `usize`",
2046 label = "vector indices are of type `usize` or ranges of `usize`"
2048 impl<T, I: SliceIndex<[T]>, A: Allocator> IndexMut<I> for Vec<T, A> {
2050 fn index_mut(&mut self, index: I) -> &mut Self::Output {
2051 IndexMut::index_mut(&mut **self, index)
2055 #[stable(feature = "rust1", since = "1.0.0")]
2056 impl<T> FromIterator<T> for Vec<T> {
2058 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
2059 <Self as SpecFromIter<T, I::IntoIter>>::from_iter(iter.into_iter())
2063 #[stable(feature = "rust1", since = "1.0.0")]
2064 impl<T, A: Allocator> IntoIterator for Vec<T, A> {
2066 type IntoIter = IntoIter<T, A>;
2068 /// Creates a consuming iterator, that is, one that moves each value out of
2069 /// the vector (from start to end). The vector cannot be used after calling
2075 /// let v = vec!["a".to_string(), "b".to_string()];
2076 /// for s in v.into_iter() {
2077 /// // s has type String, not &String
2078 /// println!("{}", s);
2082 fn into_iter(self) -> IntoIter<T, A> {
2084 let mut me = ManuallyDrop::new(self);
2085 let alloc = ptr::read(me.allocator());
2086 let begin = me.as_mut_ptr();
2087 let end = if mem::size_of::<T>() == 0 {
2088 arith_offset(begin as *const i8, me.len() as isize) as *const T
2090 begin.add(me.len()) as *const T
2092 let cap = me.buf.capacity();
2094 buf: NonNull::new_unchecked(begin),
2095 phantom: PhantomData,
2105 #[stable(feature = "rust1", since = "1.0.0")]
2106 impl<'a, T, A: Allocator> IntoIterator for &'a Vec<T, A> {
2108 type IntoIter = slice::Iter<'a, T>;
2110 fn into_iter(self) -> slice::Iter<'a, T> {
2115 #[stable(feature = "rust1", since = "1.0.0")]
2116 impl<'a, T, A: Allocator> IntoIterator for &'a mut Vec<T, A> {
2117 type Item = &'a mut T;
2118 type IntoIter = slice::IterMut<'a, T>;
2120 fn into_iter(self) -> slice::IterMut<'a, T> {
2125 #[stable(feature = "rust1", since = "1.0.0")]
2126 impl<T, A: Allocator> Extend<T> for Vec<T, A> {
2128 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
2129 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
2133 fn extend_one(&mut self, item: T) {
2138 fn extend_reserve(&mut self, additional: usize) {
2139 self.reserve(additional);
2143 impl<T, A: Allocator> Vec<T, A> {
2144 // leaf method to which various SpecFrom/SpecExtend implementations delegate when
2145 // they have no further optimizations to apply
2146 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
2147 // This is the case for a general iterator.
2149 // This function should be the moral equivalent of:
2151 // for item in iterator {
2154 while let Some(element) = iterator.next() {
2155 let len = self.len();
2156 if len == self.capacity() {
2157 let (lower, _) = iterator.size_hint();
2158 self.reserve(lower.saturating_add(1));
2161 ptr::write(self.as_mut_ptr().add(len), element);
2162 // NB can't overflow since we would have had to alloc the address space
2163 self.set_len(len + 1);
2168 /// Creates a splicing iterator that replaces the specified range in the vector
2169 /// with the given `replace_with` iterator and yields the removed items.
2170 /// `replace_with` does not need to be the same length as `range`.
2172 /// `range` is removed even if the iterator is not consumed until the end.
2174 /// It is unspecified how many elements are removed from the vector
2175 /// if the `Splice` value is leaked.
2177 /// The input iterator `replace_with` is only consumed when the `Splice` value is dropped.
2179 /// This is optimal if:
2181 /// * The tail (elements in the vector after `range`) is empty,
2182 /// * or `replace_with` yields fewer elements than `range`’s length
2183 /// * or the lower bound of its `size_hint()` is exact.
2185 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
2189 /// Panics if the starting point is greater than the end point or if
2190 /// the end point is greater than the length of the vector.
2195 /// let mut v = vec![1, 2, 3];
2196 /// let new = [7, 8];
2197 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
2198 /// assert_eq!(v, &[7, 8, 3]);
2199 /// assert_eq!(u, &[1, 2]);
2202 #[stable(feature = "vec_splice", since = "1.21.0")]
2203 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<'_, I::IntoIter, A>
2205 R: RangeBounds<usize>,
2206 I: IntoIterator<Item = T>,
2208 Splice { drain: self.drain(range), replace_with: replace_with.into_iter() }
2211 /// Creates an iterator which uses a closure to determine if an element should be removed.
2213 /// If the closure returns true, then the element is removed and yielded.
2214 /// If the closure returns false, the element will remain in the vector and will not be yielded
2215 /// by the iterator.
2217 /// Using this method is equivalent to the following code:
2220 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2221 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2223 /// while i != vec.len() {
2224 /// if some_predicate(&mut vec[i]) {
2225 /// let val = vec.remove(i);
2226 /// // your code here
2232 /// # assert_eq!(vec, vec![1, 4, 5]);
2235 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2236 /// because it can backshift the elements of the array in bulk.
2238 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2239 /// regardless of whether you choose to keep or remove it.
2243 /// Splitting an array into evens and odds, reusing the original allocation:
2246 /// #![feature(drain_filter)]
2247 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2249 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2250 /// let odds = numbers;
2252 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2253 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2255 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2256 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<'_, T, F, A>
2258 F: FnMut(&mut T) -> bool,
2260 let old_len = self.len();
2262 // Guard against us getting leaked (leak amplification)
2267 DrainFilter { vec: self, idx: 0, del: 0, old_len, pred: filter, panic_flag: false }
2271 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2273 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2274 /// append the entire slice at once.
2276 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2277 #[stable(feature = "extend_ref", since = "1.2.0")]
2278 impl<'a, T: Copy + 'a, A: Allocator + 'a> Extend<&'a T> for Vec<T, A> {
2279 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2280 self.spec_extend(iter.into_iter())
2284 fn extend_one(&mut self, &item: &'a T) {
2289 fn extend_reserve(&mut self, additional: usize) {
2290 self.reserve(additional);
2294 /// Implements comparison of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2295 #[stable(feature = "rust1", since = "1.0.0")]
2296 impl<T: PartialOrd, A: Allocator> PartialOrd for Vec<T, A> {
2298 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
2299 PartialOrd::partial_cmp(&**self, &**other)
2303 #[stable(feature = "rust1", since = "1.0.0")]
2304 impl<T: Eq, A: Allocator> Eq for Vec<T, A> {}
2306 /// Implements ordering of vectors, [lexicographically](core::cmp::Ord#lexicographical-comparison).
2307 #[stable(feature = "rust1", since = "1.0.0")]
2308 impl<T: Ord, A: Allocator> Ord for Vec<T, A> {
2310 fn cmp(&self, other: &Self) -> Ordering {
2311 Ord::cmp(&**self, &**other)
2315 #[stable(feature = "rust1", since = "1.0.0")]
2316 unsafe impl<#[may_dangle] T, A: Allocator> Drop for Vec<T, A> {
2317 fn drop(&mut self) {
2320 // use a raw slice to refer to the elements of the vector as weakest necessary type;
2321 // could avoid questions of validity in certain cases
2322 ptr::drop_in_place(ptr::slice_from_raw_parts_mut(self.as_mut_ptr(), self.len))
2324 // RawVec handles deallocation
2328 #[stable(feature = "rust1", since = "1.0.0")]
2329 impl<T> Default for Vec<T> {
2330 /// Creates an empty `Vec<T>`.
2331 fn default() -> Vec<T> {
2336 #[stable(feature = "rust1", since = "1.0.0")]
2337 impl<T: fmt::Debug, A: Allocator> fmt::Debug for Vec<T, A> {
2338 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2339 fmt::Debug::fmt(&**self, f)
2343 #[stable(feature = "rust1", since = "1.0.0")]
2344 impl<T, A: Allocator> AsRef<Vec<T, A>> for Vec<T, A> {
2345 fn as_ref(&self) -> &Vec<T, A> {
2350 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2351 impl<T, A: Allocator> AsMut<Vec<T, A>> for Vec<T, A> {
2352 fn as_mut(&mut self) -> &mut Vec<T, A> {
2357 #[stable(feature = "rust1", since = "1.0.0")]
2358 impl<T, A: Allocator> AsRef<[T]> for Vec<T, A> {
2359 fn as_ref(&self) -> &[T] {
2364 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2365 impl<T, A: Allocator> AsMut<[T]> for Vec<T, A> {
2366 fn as_mut(&mut self) -> &mut [T] {
2371 #[stable(feature = "rust1", since = "1.0.0")]
2372 impl<T: Clone> From<&[T]> for Vec<T> {
2374 fn from(s: &[T]) -> Vec<T> {
2378 fn from(s: &[T]) -> Vec<T> {
2379 crate::slice::to_vec(s, Global)
2383 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2384 impl<T: Clone> From<&mut [T]> for Vec<T> {
2386 fn from(s: &mut [T]) -> Vec<T> {
2390 fn from(s: &mut [T]) -> Vec<T> {
2391 crate::slice::to_vec(s, Global)
2395 #[stable(feature = "vec_from_array", since = "1.44.0")]
2396 impl<T, const N: usize> From<[T; N]> for Vec<T> {
2398 fn from(s: [T; N]) -> Vec<T> {
2399 <[T]>::into_vec(box s)
2402 fn from(s: [T; N]) -> Vec<T> {
2403 crate::slice::into_vec(box s)
2407 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2408 impl<'a, T> From<Cow<'a, [T]>> for Vec<T>
2410 [T]: ToOwned<Owned = Vec<T>>,
2412 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2417 // note: test pulls in libstd, which causes errors here
2419 #[stable(feature = "vec_from_box", since = "1.18.0")]
2420 impl<T, A: Allocator> From<Box<[T], A>> for Vec<T, A> {
2421 fn from(s: Box<[T], A>) -> Self {
2423 Self { buf: RawVec::from_box(s), len }
2427 // note: test pulls in libstd, which causes errors here
2429 #[stable(feature = "box_from_vec", since = "1.20.0")]
2430 impl<T, A: Allocator> From<Vec<T, A>> for Box<[T], A> {
2431 fn from(v: Vec<T, A>) -> Self {
2432 v.into_boxed_slice()
2436 #[stable(feature = "rust1", since = "1.0.0")]
2437 impl From<&str> for Vec<u8> {
2438 fn from(s: &str) -> Vec<u8> {
2439 From::from(s.as_bytes())
2443 #[stable(feature = "array_try_from_vec", since = "1.48.0")]
2444 impl<T, A: Allocator, const N: usize> TryFrom<Vec<T, A>> for [T; N] {
2445 type Error = Vec<T, A>;
2447 /// Gets the entire contents of the `Vec<T>` as an array,
2448 /// if its size exactly matches that of the requested array.
2453 /// use std::convert::TryInto;
2454 /// assert_eq!(vec![1, 2, 3].try_into(), Ok([1, 2, 3]));
2455 /// assert_eq!(<Vec<i32>>::new().try_into(), Ok([]));
2458 /// If the length doesn't match, the input comes back in `Err`:
2460 /// use std::convert::TryInto;
2461 /// let r: Result<[i32; 4], _> = (0..10).collect::<Vec<_>>().try_into();
2462 /// assert_eq!(r, Err(vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9]));
2465 /// If you're fine with just getting a prefix of the `Vec<T>`,
2466 /// you can call [`.truncate(N)`](Vec::truncate) first.
2468 /// use std::convert::TryInto;
2469 /// let mut v = String::from("hello world").into_bytes();
2472 /// let [a, b]: [_; 2] = v.try_into().unwrap();
2473 /// assert_eq!(a, b' ');
2474 /// assert_eq!(b, b'd');
2476 fn try_from(mut vec: Vec<T, A>) -> Result<[T; N], Vec<T, A>> {
2481 // SAFETY: `.set_len(0)` is always sound.
2482 unsafe { vec.set_len(0) };
2484 // SAFETY: A `Vec`'s pointer is always aligned properly, and
2485 // the alignment the array needs is the same as the items.
2486 // We checked earlier that we have sufficient items.
2487 // The items will not double-drop as the `set_len`
2488 // tells the `Vec` not to also drop them.
2489 let array = unsafe { ptr::read(vec.as_ptr() as *const [T; N]) };