1 //! A contiguous growable array type with heap-allocated contents, written
4 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
5 //! `O(1)` pop (from the end).
9 //! You can explicitly create a [`Vec<T>`] with [`new`]:
12 //! let v: Vec<i32> = Vec::new();
15 //! ...or by using the [`vec!`] macro:
18 //! let v: Vec<i32> = vec![];
20 //! let v = vec![1, 2, 3, 4, 5];
22 //! let v = vec![0; 10]; // ten zeroes
25 //! You can [`push`] values onto the end of a vector (which will grow the vector
29 //! let mut v = vec![1, 2];
34 //! Popping values works in much the same way:
37 //! let mut v = vec![1, 2];
39 //! let two = v.pop();
42 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
45 //! let mut v = vec![1, 2, 3];
50 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
51 //! [`new`]: ../../std/vec/struct.Vec.html#method.new
52 //! [`push`]: ../../std/vec/struct.Vec.html#method.push
53 //! [`Index`]: ../../std/ops/trait.Index.html
54 //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
55 //! [`vec!`]: ../../std/macro.vec.html
57 #![stable(feature = "rust1", since = "1.0.0")]
59 use core::cmp::{self, Ordering};
61 use core::hash::{self, Hash};
62 use core::intrinsics::{arith_offset, assume};
63 use core::iter::{FromIterator, FusedIterator, TrustedLen};
64 use core::marker::PhantomData;
66 use core::ops::Bound::{Excluded, Included, Unbounded};
67 use core::ops::{Index, IndexMut, RangeBounds};
70 use core::ptr::NonNull;
73 use collections::CollectionAllocErr;
79 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
84 /// let mut vec = Vec::new();
88 /// assert_eq!(vec.len(), 2);
89 /// assert_eq!(vec[0], 1);
91 /// assert_eq!(vec.pop(), Some(2));
92 /// assert_eq!(vec.len(), 1);
95 /// assert_eq!(vec[0], 7);
97 /// vec.extend([1, 2, 3].iter().cloned());
100 /// println!("{}", x);
102 /// assert_eq!(vec, [7, 1, 2, 3]);
105 /// The [`vec!`] macro is provided to make initialization more convenient:
108 /// let mut vec = vec![1, 2, 3];
110 /// assert_eq!(vec, [1, 2, 3, 4]);
113 /// It can also initialize each element of a `Vec<T>` with a given value.
114 /// This may be more efficient than performing allocation and initialization
115 /// in separate steps, especially when initializing a vector of zeros:
118 /// let vec = vec![0; 5];
119 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
121 /// // The following is equivalent, but potentially slower:
122 /// let mut vec1 = Vec::with_capacity(5);
123 /// vec1.resize(5, 0);
126 /// Use a `Vec<T>` as an efficient stack:
129 /// let mut stack = Vec::new();
135 /// while let Some(top) = stack.pop() {
136 /// // Prints 3, 2, 1
137 /// println!("{}", top);
143 /// The `Vec` type allows to access values by index, because it implements the
144 /// [`Index`] trait. An example will be more explicit:
147 /// let v = vec![0, 2, 4, 6];
148 /// println!("{}", v[1]); // it will display '2'
151 /// However be careful: if you try to access an index which isn't in the `Vec`,
152 /// your software will panic! You cannot do this:
155 /// let v = vec![0, 2, 4, 6];
156 /// println!("{}", v[6]); // it will panic!
159 /// In conclusion: always check if the index you want to get really exists
164 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
165 /// To get a slice, use `&`. Example:
168 /// fn read_slice(slice: &[usize]) {
172 /// let v = vec![0, 1];
175 /// // ... and that's all!
176 /// // you can also do it like this:
177 /// let x : &[usize] = &v;
180 /// In Rust, it's more common to pass slices as arguments rather than vectors
181 /// when you just want to provide a read access. The same goes for [`String`] and
184 /// # Capacity and reallocation
186 /// The capacity of a vector is the amount of space allocated for any future
187 /// elements that will be added onto the vector. This is not to be confused with
188 /// the *length* of a vector, which specifies the number of actual elements
189 /// within the vector. If a vector's length exceeds its capacity, its capacity
190 /// will automatically be increased, but its elements will have to be
193 /// For example, a vector with capacity 10 and length 0 would be an empty vector
194 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
195 /// vector will not change its capacity or cause reallocation to occur. However,
196 /// if the vector's length is increased to 11, it will have to reallocate, which
197 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
198 /// whenever possible to specify how big the vector is expected to get.
202 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
203 /// about its design. This ensures that it's as low-overhead as possible in
204 /// the general case, and can be correctly manipulated in primitive ways
205 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
206 /// If additional type parameters are added (e.g., to support custom allocators),
207 /// overriding their defaults may change the behavior.
209 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
210 /// triplet. No more, no less. The order of these fields is completely
211 /// unspecified, and you should use the appropriate methods to modify these.
212 /// The pointer will never be null, so this type is null-pointer-optimized.
214 /// However, the pointer may not actually point to allocated memory. In particular,
215 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
216 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
217 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
218 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
219 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
220 /// if [`mem::size_of::<T>`]`() * capacity() > 0`. In general, `Vec`'s allocation
221 /// details are very subtle — if you intend to allocate memory using a `Vec`
222 /// and use it for something else (either to pass to unsafe code, or to build your
223 /// own memory-backed collection), be sure to deallocate this memory by using
224 /// `from_raw_parts` to recover the `Vec` and then dropping it.
226 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
227 /// (as defined by the allocator Rust is configured to use by default), and its
228 /// pointer points to [`len`] initialized, contiguous elements in order (what
229 /// you would see if you coerced it to a slice), followed by [`capacity`]` -
230 /// `[`len`] logically uninitialized, contiguous elements.
232 /// `Vec` will never perform a "small optimization" where elements are actually
233 /// stored on the stack for two reasons:
235 /// * It would make it more difficult for unsafe code to correctly manipulate
236 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
237 /// only moved, and it would be more difficult to determine if a `Vec` had
238 /// actually allocated memory.
240 /// * It would penalize the general case, incurring an additional branch
243 /// `Vec` will never automatically shrink itself, even if completely empty. This
244 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
245 /// and then filling it back up to the same [`len`] should incur no calls to
246 /// the allocator. If you wish to free up unused memory, use
247 /// [`shrink_to_fit`][`shrink_to_fit`].
249 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
250 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
251 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
252 /// accurate, and can be relied on. It can even be used to manually free the memory
253 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
254 /// when not necessary.
256 /// `Vec` does not guarantee any particular growth strategy when reallocating
257 /// when full, nor when [`reserve`] is called. The current strategy is basic
258 /// and it may prove desirable to use a non-constant growth factor. Whatever
259 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
261 /// `vec![x; n]`, `vec![a, b, c, d]`, and
262 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
263 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
264 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
265 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
267 /// `Vec` will not specifically overwrite any data that is removed from it,
268 /// but also won't specifically preserve it. Its uninitialized memory is
269 /// scratch space that it may use however it wants. It will generally just do
270 /// whatever is most efficient or otherwise easy to implement. Do not rely on
271 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
272 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
273 /// first, that may not actually happen because the optimizer does not consider
274 /// this a side-effect that must be preserved. There is one case which we will
275 /// not break, however: using `unsafe` code to write to the excess capacity,
276 /// and then increasing the length to match, is always valid.
278 /// `Vec` does not currently guarantee the order in which elements are dropped.
279 /// The order has changed in the past and may change again.
281 /// [`vec!`]: ../../std/macro.vec.html
282 /// [`Index`]: ../../std/ops/trait.Index.html
283 /// [`String`]: ../../std/string/struct.String.html
284 /// [`&str`]: ../../std/primitive.str.html
285 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
286 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
287 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
288 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
289 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
290 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
291 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
292 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
293 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
294 /// [owned slice]: ../../std/boxed/struct.Box.html
295 #[stable(feature = "rust1", since = "1.0.0")]
301 ////////////////////////////////////////////////////////////////////////////////
303 ////////////////////////////////////////////////////////////////////////////////
306 /// Constructs a new, empty `Vec<T>`.
308 /// The vector will not allocate until elements are pushed onto it.
313 /// # #![allow(unused_mut)]
314 /// let mut vec: Vec<i32> = Vec::new();
317 #[stable(feature = "rust1", since = "1.0.0")]
318 #[rustc_const_unstable(feature = "const_vec_new")]
319 pub const fn new() -> Vec<T> {
326 /// Constructs a new, empty `Vec<T>` with the specified capacity.
328 /// The vector will be able to hold exactly `capacity` elements without
329 /// reallocating. If `capacity` is 0, the vector will not allocate.
331 /// It is important to note that although the returned vector has the
332 /// *capacity* specified, the vector will have a zero *length*. For an
333 /// explanation of the difference between length and capacity, see
334 /// *[Capacity and reallocation]*.
336 /// [Capacity and reallocation]: #capacity-and-reallocation
341 /// let mut vec = Vec::with_capacity(10);
343 /// // The vector contains no items, even though it has capacity for more
344 /// assert_eq!(vec.len(), 0);
346 /// // These are all done without reallocating...
351 /// // ...but this may make the vector reallocate
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn with_capacity(capacity: usize) -> Vec<T> {
358 buf: RawVec::with_capacity(capacity),
363 /// Creates a `Vec<T>` directly from the raw components of another vector.
367 /// This is highly unsafe, due to the number of invariants that aren't
370 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
371 /// (at least, it's highly likely to be incorrect if it wasn't).
372 /// * `ptr`'s `T` needs to have the same size and alignment as it was allocated with.
373 /// * `length` needs to be less than or equal to `capacity`.
374 /// * `capacity` needs to be the capacity that the pointer was allocated with.
376 /// Violating these may cause problems like corrupting the allocator's
377 /// internal data structures. For example it is **not** safe
378 /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`.
380 /// The ownership of `ptr` is effectively transferred to the
381 /// `Vec<T>` which may then deallocate, reallocate or change the
382 /// contents of memory pointed to by the pointer at will. Ensure
383 /// that nothing else uses the pointer after calling this
386 /// [`String`]: ../../std/string/struct.String.html
395 /// let mut v = vec![1, 2, 3];
397 /// // Pull out the various important pieces of information about `v`
398 /// let p = v.as_mut_ptr();
399 /// let len = v.len();
400 /// let cap = v.capacity();
403 /// // Cast `v` into the void: no destructor run, so we are in
404 /// // complete control of the allocation to which `p` points.
407 /// // Overwrite memory with 4, 5, 6
408 /// for i in 0..len as isize {
409 /// ptr::write(p.offset(i), 4 + i);
412 /// // Put everything back together into a Vec
413 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
414 /// assert_eq!(rebuilt, [4, 5, 6]);
418 #[stable(feature = "rust1", since = "1.0.0")]
419 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
421 buf: RawVec::from_raw_parts(ptr, capacity),
426 /// Returns the number of elements the vector can hold without
432 /// let vec: Vec<i32> = Vec::with_capacity(10);
433 /// assert_eq!(vec.capacity(), 10);
436 #[stable(feature = "rust1", since = "1.0.0")]
437 pub fn capacity(&self) -> usize {
441 /// Reserves capacity for at least `additional` more elements to be inserted
442 /// in the given `Vec<T>`. The collection may reserve more space to avoid
443 /// frequent reallocations. After calling `reserve`, capacity will be
444 /// greater than or equal to `self.len() + additional`. Does nothing if
445 /// capacity is already sufficient.
449 /// Panics if the new capacity overflows `usize`.
454 /// let mut vec = vec![1];
456 /// assert!(vec.capacity() >= 11);
458 #[stable(feature = "rust1", since = "1.0.0")]
459 pub fn reserve(&mut self, additional: usize) {
460 self.buf.reserve(self.len, additional);
463 /// Reserves the minimum capacity for exactly `additional` more elements to
464 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
465 /// capacity will be greater than or equal to `self.len() + additional`.
466 /// Does nothing if the capacity is already sufficient.
468 /// Note that the allocator may give the collection more space than it
469 /// requests. Therefore capacity can not be relied upon to be precisely
470 /// minimal. Prefer `reserve` if future insertions are expected.
474 /// Panics if the new capacity overflows `usize`.
479 /// let mut vec = vec![1];
480 /// vec.reserve_exact(10);
481 /// assert!(vec.capacity() >= 11);
483 #[stable(feature = "rust1", since = "1.0.0")]
484 pub fn reserve_exact(&mut self, additional: usize) {
485 self.buf.reserve_exact(self.len, additional);
488 /// Tries to reserve capacity for at least `additional` more elements to be inserted
489 /// in the given `Vec<T>`. The collection may reserve more space to avoid
490 /// frequent reallocations. After calling `reserve`, capacity will be
491 /// greater than or equal to `self.len() + additional`. Does nothing if
492 /// capacity is already sufficient.
496 /// If the capacity overflows, or the allocator reports a failure, then an error
502 /// #![feature(try_reserve)]
503 /// use std::collections::CollectionAllocErr;
505 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> {
506 /// let mut output = Vec::new();
508 /// // Pre-reserve the memory, exiting if we can't
509 /// output.try_reserve(data.len())?;
511 /// // Now we know this can't OOM in the middle of our complex work
512 /// output.extend(data.iter().map(|&val| {
513 /// val * 2 + 5 // very complicated
518 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
520 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
521 pub fn try_reserve(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
522 self.buf.try_reserve(self.len, additional)
525 /// Tries to reserves the minimum capacity for exactly `additional` more elements to
526 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
527 /// capacity will be greater than or equal to `self.len() + additional`.
528 /// Does nothing if the capacity is already sufficient.
530 /// Note that the allocator may give the collection more space than it
531 /// requests. Therefore capacity can not be relied upon to be precisely
532 /// minimal. Prefer `reserve` if future insertions are expected.
536 /// If the capacity overflows, or the allocator reports a failure, then an error
542 /// #![feature(try_reserve)]
543 /// use std::collections::CollectionAllocErr;
545 /// fn process_data(data: &[u32]) -> Result<Vec<u32>, CollectionAllocErr> {
546 /// let mut output = Vec::new();
548 /// // Pre-reserve the memory, exiting if we can't
549 /// output.try_reserve(data.len())?;
551 /// // Now we know this can't OOM in the middle of our complex work
552 /// output.extend(data.iter().map(|&val| {
553 /// val * 2 + 5 // very complicated
558 /// # process_data(&[1, 2, 3]).expect("why is the test harness OOMing on 12 bytes?");
560 #[unstable(feature = "try_reserve", reason = "new API", issue="48043")]
561 pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), CollectionAllocErr> {
562 self.buf.try_reserve_exact(self.len, additional)
565 /// Shrinks the capacity of the vector as much as possible.
567 /// It will drop down as close as possible to the length but the allocator
568 /// may still inform the vector that there is space for a few more elements.
573 /// let mut vec = Vec::with_capacity(10);
574 /// vec.extend([1, 2, 3].iter().cloned());
575 /// assert_eq!(vec.capacity(), 10);
576 /// vec.shrink_to_fit();
577 /// assert!(vec.capacity() >= 3);
579 #[stable(feature = "rust1", since = "1.0.0")]
580 pub fn shrink_to_fit(&mut self) {
581 if self.capacity() != self.len {
582 self.buf.shrink_to_fit(self.len);
586 /// Shrinks the capacity of the vector with a lower bound.
588 /// The capacity will remain at least as large as both the length
589 /// and the supplied value.
591 /// Panics if the current capacity is smaller than the supplied
592 /// minimum capacity.
597 /// #![feature(shrink_to)]
598 /// let mut vec = Vec::with_capacity(10);
599 /// vec.extend([1, 2, 3].iter().cloned());
600 /// assert_eq!(vec.capacity(), 10);
601 /// vec.shrink_to(4);
602 /// assert!(vec.capacity() >= 4);
603 /// vec.shrink_to(0);
604 /// assert!(vec.capacity() >= 3);
606 #[unstable(feature = "shrink_to", reason = "new API", issue="56431")]
607 pub fn shrink_to(&mut self, min_capacity: usize) {
608 self.buf.shrink_to_fit(cmp::max(self.len, min_capacity));
611 /// Converts the vector into [`Box<[T]>`][owned slice].
613 /// Note that this will drop any excess capacity.
615 /// [owned slice]: ../../std/boxed/struct.Box.html
620 /// let v = vec![1, 2, 3];
622 /// let slice = v.into_boxed_slice();
625 /// Any excess capacity is removed:
628 /// let mut vec = Vec::with_capacity(10);
629 /// vec.extend([1, 2, 3].iter().cloned());
631 /// assert_eq!(vec.capacity(), 10);
632 /// let slice = vec.into_boxed_slice();
633 /// assert_eq!(slice.into_vec().capacity(), 3);
635 #[stable(feature = "rust1", since = "1.0.0")]
636 pub fn into_boxed_slice(mut self) -> Box<[T]> {
638 self.shrink_to_fit();
639 let buf = ptr::read(&self.buf);
645 /// Shortens the vector, keeping the first `len` elements and dropping
648 /// If `len` is greater than the vector's current length, this has no
651 /// The [`drain`] method can emulate `truncate`, but causes the excess
652 /// elements to be returned instead of dropped.
654 /// Note that this method has no effect on the allocated capacity
659 /// Truncating a five element vector to two elements:
662 /// let mut vec = vec![1, 2, 3, 4, 5];
664 /// assert_eq!(vec, [1, 2]);
667 /// No truncation occurs when `len` is greater than the vector's current
671 /// let mut vec = vec![1, 2, 3];
673 /// assert_eq!(vec, [1, 2, 3]);
676 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
680 /// let mut vec = vec![1, 2, 3];
682 /// assert_eq!(vec, []);
685 /// [`clear`]: #method.clear
686 /// [`drain`]: #method.drain
687 #[stable(feature = "rust1", since = "1.0.0")]
688 pub fn truncate(&mut self, len: usize) {
689 let current_len = self.len;
691 let mut ptr = self.as_mut_ptr().add(self.len);
692 // Set the final length at the end, keeping in mind that
693 // dropping an element might panic. Works around a missed
694 // optimization, as seen in the following issue:
695 // https://github.com/rust-lang/rust/issues/51802
696 let mut local_len = SetLenOnDrop::new(&mut self.len);
698 // drop any extra elements
699 for _ in len..current_len {
700 local_len.decrement_len(1);
701 ptr = ptr.offset(-1);
702 ptr::drop_in_place(ptr);
707 /// Extracts a slice containing the entire vector.
709 /// Equivalent to `&s[..]`.
714 /// use std::io::{self, Write};
715 /// let buffer = vec![1, 2, 3, 5, 8];
716 /// io::sink().write(buffer.as_slice()).unwrap();
719 #[stable(feature = "vec_as_slice", since = "1.7.0")]
720 pub fn as_slice(&self) -> &[T] {
724 /// Extracts a mutable slice of the entire vector.
726 /// Equivalent to `&mut s[..]`.
731 /// use std::io::{self, Read};
732 /// let mut buffer = vec![0; 3];
733 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
736 #[stable(feature = "vec_as_slice", since = "1.7.0")]
737 pub fn as_mut_slice(&mut self) -> &mut [T] {
741 /// Forces the length of the vector to `new_len`.
743 /// This is a low-level operation that maintains none of the normal
744 /// invariants of the type. Normally changing the length of a vector
745 /// is done using one of the safe operations instead, such as
746 /// [`truncate`], [`resize`], [`extend`], or [`clear`].
748 /// [`truncate`]: #method.truncate
749 /// [`resize`]: #method.resize
750 /// [`extend`]: #method.extend-1
751 /// [`clear`]: #method.clear
755 /// - `new_len` must be less than or equal to [`capacity()`].
756 /// - The elements at `old_len..new_len` must be initialized.
758 /// [`capacity()`]: #method.capacity
762 /// This method can be useful for situations in which the vector
763 /// is serving as a buffer for other code, particularly over FFI:
766 /// # #![allow(dead_code)]
767 /// # // This is just a minimal skeleton for the doc example;
768 /// # // don't use this as a starting point for a real library.
769 /// # pub struct StreamWrapper { strm: *mut std::ffi::c_void }
770 /// # const Z_OK: i32 = 0;
772 /// # fn deflateGetDictionary(
773 /// # strm: *mut std::ffi::c_void,
774 /// # dictionary: *mut u8,
775 /// # dictLength: *mut usize,
778 /// # impl StreamWrapper {
779 /// pub fn get_dictionary(&self) -> Option<Vec<u8>> {
780 /// // Per the FFI method's docs, "32768 bytes is always enough".
781 /// let mut dict = Vec::with_capacity(32_768);
782 /// let mut dict_length = 0;
783 /// // SAFETY: When `deflateGetDictionary` returns `Z_OK`, it holds that:
784 /// // 1. `dict_length` elements were initialized.
785 /// // 2. `dict_length` <= the capacity (32_768)
786 /// // which makes `set_len` safe to call.
788 /// // Make the FFI call...
789 /// let r = deflateGetDictionary(self.strm, dict.as_mut_ptr(), &mut dict_length);
791 /// // ...and update the length to what was initialized.
792 /// dict.set_len(dict_length);
802 /// While the following example is sound, there is a memory leak since
803 /// the inner vectors were not freed prior to the `set_len` call:
806 /// let mut vec = vec![vec![1, 0, 0],
810 /// // 1. `old_len..0` is empty so no elements need to be initialized.
811 /// // 2. `0 <= capacity` always holds whatever `capacity` is.
817 /// Normally, here, one would use [`clear`] instead to correctly drop
818 /// the contents and thus not leak memory.
820 #[stable(feature = "rust1", since = "1.0.0")]
821 pub unsafe fn set_len(&mut self, new_len: usize) {
822 debug_assert!(new_len <= self.capacity());
827 /// Removes an element from the vector and returns it.
829 /// The removed element is replaced by the last element of the vector.
831 /// This does not preserve ordering, but is O(1).
835 /// Panics if `index` is out of bounds.
840 /// let mut v = vec!["foo", "bar", "baz", "qux"];
842 /// assert_eq!(v.swap_remove(1), "bar");
843 /// assert_eq!(v, ["foo", "qux", "baz"]);
845 /// assert_eq!(v.swap_remove(0), "foo");
846 /// assert_eq!(v, ["baz", "qux"]);
849 #[stable(feature = "rust1", since = "1.0.0")]
850 pub fn swap_remove(&mut self, index: usize) -> T {
852 // We replace self[index] with the last element. Note that if the
853 // bounds check on hole succeeds there must be a last element (which
854 // can be self[index] itself).
855 let hole: *mut T = &mut self[index];
856 let last = ptr::read(self.get_unchecked(self.len - 1));
858 ptr::replace(hole, last)
862 /// Inserts an element at position `index` within the vector, shifting all
863 /// elements after it to the right.
867 /// Panics if `index > len`.
872 /// let mut vec = vec![1, 2, 3];
873 /// vec.insert(1, 4);
874 /// assert_eq!(vec, [1, 4, 2, 3]);
875 /// vec.insert(4, 5);
876 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
878 #[stable(feature = "rust1", since = "1.0.0")]
879 pub fn insert(&mut self, index: usize, element: T) {
880 let len = self.len();
881 assert!(index <= len);
883 // space for the new element
884 if len == self.buf.cap() {
890 // The spot to put the new value
892 let p = self.as_mut_ptr().add(index);
893 // Shift everything over to make space. (Duplicating the
894 // `index`th element into two consecutive places.)
895 ptr::copy(p, p.offset(1), len - index);
896 // Write it in, overwriting the first copy of the `index`th
898 ptr::write(p, element);
900 self.set_len(len + 1);
904 /// Removes and returns the element at position `index` within the vector,
905 /// shifting all elements after it to the left.
909 /// Panics if `index` is out of bounds.
914 /// let mut v = vec![1, 2, 3];
915 /// assert_eq!(v.remove(1), 2);
916 /// assert_eq!(v, [1, 3]);
918 #[stable(feature = "rust1", since = "1.0.0")]
919 pub fn remove(&mut self, index: usize) -> T {
920 let len = self.len();
921 assert!(index < len);
926 // the place we are taking from.
927 let ptr = self.as_mut_ptr().add(index);
928 // copy it out, unsafely having a copy of the value on
929 // the stack and in the vector at the same time.
930 ret = ptr::read(ptr);
932 // Shift everything down to fill in that spot.
933 ptr::copy(ptr.offset(1), ptr, len - index - 1);
935 self.set_len(len - 1);
940 /// Retains only the elements specified by the predicate.
942 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
943 /// This method operates in place and preserves the order of the retained
949 /// let mut vec = vec![1, 2, 3, 4];
950 /// vec.retain(|&x| x%2 == 0);
951 /// assert_eq!(vec, [2, 4]);
953 #[stable(feature = "rust1", since = "1.0.0")]
954 pub fn retain<F>(&mut self, mut f: F)
955 where F: FnMut(&T) -> bool
957 self.drain_filter(|x| !f(x));
960 /// Removes all but the first of consecutive elements in the vector that resolve to the same
963 /// If the vector is sorted, this removes all duplicates.
968 /// let mut vec = vec![10, 20, 21, 30, 20];
970 /// vec.dedup_by_key(|i| *i / 10);
972 /// assert_eq!(vec, [10, 20, 30, 20]);
974 #[stable(feature = "dedup_by", since = "1.16.0")]
976 pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
977 self.dedup_by(|a, b| key(a) == key(b))
980 /// Removes all but the first of consecutive elements in the vector satisfying a given equality
983 /// The `same_bucket` function is passed references to two elements from the vector and
984 /// must determine if the elements compare equal. The elements are passed in opposite order
985 /// from their order in the slice, so if `same_bucket(a, b)` returns `true`, `a` is removed.
987 /// If the vector is sorted, this removes all duplicates.
992 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
994 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
996 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
998 #[stable(feature = "dedup_by", since = "1.16.0")]
999 pub fn dedup_by<F>(&mut self, same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
1001 let (dedup, _) = self.as_mut_slice().partition_dedup_by(same_bucket);
1007 /// Appends an element to the back of a collection.
1011 /// Panics if the number of elements in the vector overflows a `usize`.
1016 /// let mut vec = vec![1, 2];
1018 /// assert_eq!(vec, [1, 2, 3]);
1021 #[stable(feature = "rust1", since = "1.0.0")]
1022 pub fn push(&mut self, value: T) {
1023 // This will panic or abort if we would allocate > isize::MAX bytes
1024 // or if the length increment would overflow for zero-sized types.
1025 if self.len == self.buf.cap() {
1029 let end = self.as_mut_ptr().add(self.len);
1030 ptr::write(end, value);
1035 /// Removes the last element from a vector and returns it, or [`None`] if it
1038 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1043 /// let mut vec = vec![1, 2, 3];
1044 /// assert_eq!(vec.pop(), Some(3));
1045 /// assert_eq!(vec, [1, 2]);
1048 #[stable(feature = "rust1", since = "1.0.0")]
1049 pub fn pop(&mut self) -> Option<T> {
1055 Some(ptr::read(self.get_unchecked(self.len())))
1060 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1064 /// Panics if the number of elements in the vector overflows a `usize`.
1069 /// let mut vec = vec![1, 2, 3];
1070 /// let mut vec2 = vec![4, 5, 6];
1071 /// vec.append(&mut vec2);
1072 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1073 /// assert_eq!(vec2, []);
1076 #[stable(feature = "append", since = "1.4.0")]
1077 pub fn append(&mut self, other: &mut Self) {
1079 self.append_elements(other.as_slice() as _);
1084 /// Appends elements to `Self` from other buffer.
1086 unsafe fn append_elements(&mut self, other: *const [T]) {
1087 let count = (*other).len();
1088 self.reserve(count);
1089 let len = self.len();
1090 ptr::copy_nonoverlapping(other as *const T, self.get_unchecked_mut(len), count);
1094 /// Creates a draining iterator that removes the specified range in the vector
1095 /// and yields the removed items.
1097 /// Note 1: The element range is removed even if the iterator is only
1098 /// partially consumed or not consumed at all.
1100 /// Note 2: It is unspecified how many elements are removed from the vector
1101 /// if the `Drain` value is leaked.
1105 /// Panics if the starting point is greater than the end point or if
1106 /// the end point is greater than the length of the vector.
1111 /// let mut v = vec![1, 2, 3];
1112 /// let u: Vec<_> = v.drain(1..).collect();
1113 /// assert_eq!(v, &[1]);
1114 /// assert_eq!(u, &[2, 3]);
1116 /// // A full range clears the vector
1118 /// assert_eq!(v, &[]);
1120 #[stable(feature = "drain", since = "1.6.0")]
1121 pub fn drain<R>(&mut self, range: R) -> Drain<T>
1122 where R: RangeBounds<usize>
1126 // When the Drain is first created, it shortens the length of
1127 // the source vector to make sure no uninitialized or moved-from elements
1128 // are accessible at all if the Drain's destructor never gets to run.
1130 // Drain will ptr::read out the values to remove.
1131 // When finished, remaining tail of the vec is copied back to cover
1132 // the hole, and the vector length is restored to the new length.
1134 let len = self.len();
1135 let start = match range.start_bound() {
1137 Excluded(&n) => n + 1,
1140 let end = match range.end_bound() {
1141 Included(&n) => n + 1,
1145 assert!(start <= end);
1146 assert!(end <= len);
1149 // set self.vec length's to start, to be safe in case Drain is leaked
1150 self.set_len(start);
1151 // Use the borrow in the IterMut to indicate borrowing behavior of the
1152 // whole Drain iterator (like &mut T).
1153 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().add(start),
1157 tail_len: len - end,
1158 iter: range_slice.iter(),
1159 vec: NonNull::from(self),
1164 /// Clears the vector, removing all values.
1166 /// Note that this method has no effect on the allocated capacity
1172 /// let mut v = vec![1, 2, 3];
1176 /// assert!(v.is_empty());
1179 #[stable(feature = "rust1", since = "1.0.0")]
1180 pub fn clear(&mut self) {
1184 /// Returns the number of elements in the vector, also referred to
1185 /// as its 'length'.
1190 /// let a = vec![1, 2, 3];
1191 /// assert_eq!(a.len(), 3);
1194 #[stable(feature = "rust1", since = "1.0.0")]
1195 pub fn len(&self) -> usize {
1199 /// Returns `true` if the vector contains no elements.
1204 /// let mut v = Vec::new();
1205 /// assert!(v.is_empty());
1208 /// assert!(!v.is_empty());
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 pub fn is_empty(&self) -> bool {
1215 /// Splits the collection into two at the given index.
1217 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1218 /// and the returned `Self` contains elements `[at, len)`.
1220 /// Note that the capacity of `self` does not change.
1224 /// Panics if `at > len`.
1229 /// let mut vec = vec![1,2,3];
1230 /// let vec2 = vec.split_off(1);
1231 /// assert_eq!(vec, [1]);
1232 /// assert_eq!(vec2, [2, 3]);
1235 #[stable(feature = "split_off", since = "1.4.0")]
1236 pub fn split_off(&mut self, at: usize) -> Self {
1237 assert!(at <= self.len(), "`at` out of bounds");
1239 let other_len = self.len - at;
1240 let mut other = Vec::with_capacity(other_len);
1242 // Unsafely `set_len` and copy items to `other`.
1245 other.set_len(other_len);
1247 ptr::copy_nonoverlapping(self.as_ptr().add(at),
1254 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1256 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1257 /// difference, with each additional slot filled with the result of
1258 /// calling the closure `f`. The return values from `f` will end up
1259 /// in the `Vec` in the order they have been generated.
1261 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1263 /// This method uses a closure to create new values on every push. If
1264 /// you'd rather [`Clone`] a given value, use [`resize`]. If you want
1265 /// to use the [`Default`] trait to generate values, you can pass
1266 /// [`Default::default()`] as the second argument..
1271 /// let mut vec = vec![1, 2, 3];
1272 /// vec.resize_with(5, Default::default);
1273 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1275 /// let mut vec = vec![];
1277 /// vec.resize_with(4, || { p *= 2; p });
1278 /// assert_eq!(vec, [2, 4, 8, 16]);
1281 /// [`resize`]: #method.resize
1282 /// [`Clone`]: ../../std/clone/trait.Clone.html
1283 #[stable(feature = "vec_resize_with", since = "1.33.0")]
1284 pub fn resize_with<F>(&mut self, new_len: usize, f: F)
1285 where F: FnMut() -> T
1287 let len = self.len();
1289 self.extend_with(new_len - len, ExtendFunc(f));
1291 self.truncate(new_len);
1296 impl<T: Clone> Vec<T> {
1297 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1299 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1300 /// difference, with each additional slot filled with `value`.
1301 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1303 /// This method requires [`Clone`] to be able clone the passed value. If
1304 /// you need more flexibility (or want to rely on [`Default`] instead of
1305 /// [`Clone`]), use [`resize_with`].
1310 /// let mut vec = vec!["hello"];
1311 /// vec.resize(3, "world");
1312 /// assert_eq!(vec, ["hello", "world", "world"]);
1314 /// let mut vec = vec![1, 2, 3, 4];
1315 /// vec.resize(2, 0);
1316 /// assert_eq!(vec, [1, 2]);
1319 /// [`Clone`]: ../../std/clone/trait.Clone.html
1320 /// [`Default`]: ../../std/default/trait.Default.html
1321 /// [`resize_with`]: #method.resize_with
1322 #[stable(feature = "vec_resize", since = "1.5.0")]
1323 pub fn resize(&mut self, new_len: usize, value: T) {
1324 let len = self.len();
1327 self.extend_with(new_len - len, ExtendElement(value))
1329 self.truncate(new_len);
1333 /// Clones and appends all elements in a slice to the `Vec`.
1335 /// Iterates over the slice `other`, clones each element, and then appends
1336 /// it to this `Vec`. The `other` vector is traversed in-order.
1338 /// Note that this function is same as [`extend`] except that it is
1339 /// specialized to work with slices instead. If and when Rust gets
1340 /// specialization this function will likely be deprecated (but still
1346 /// let mut vec = vec![1];
1347 /// vec.extend_from_slice(&[2, 3, 4]);
1348 /// assert_eq!(vec, [1, 2, 3, 4]);
1351 /// [`extend`]: #method.extend
1352 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1353 pub fn extend_from_slice(&mut self, other: &[T]) {
1354 self.spec_extend(other.iter())
1358 impl<T: Default> Vec<T> {
1359 /// Resizes the `Vec` in-place so that `len` is equal to `new_len`.
1361 /// If `new_len` is greater than `len`, the `Vec` is extended by the
1362 /// difference, with each additional slot filled with [`Default::default()`].
1363 /// If `new_len` is less than `len`, the `Vec` is simply truncated.
1365 /// This method uses [`Default`] to create new values on every push. If
1366 /// you'd rather [`Clone`] a given value, use [`resize`].
1371 /// #![feature(vec_resize_default)]
1373 /// let mut vec = vec![1, 2, 3];
1374 /// vec.resize_default(5);
1375 /// assert_eq!(vec, [1, 2, 3, 0, 0]);
1377 /// let mut vec = vec![1, 2, 3, 4];
1378 /// vec.resize_default(2);
1379 /// assert_eq!(vec, [1, 2]);
1382 /// [`resize`]: #method.resize
1383 /// [`Default::default()`]: ../../std/default/trait.Default.html#tymethod.default
1384 /// [`Default`]: ../../std/default/trait.Default.html
1385 /// [`Clone`]: ../../std/clone/trait.Clone.html
1386 #[unstable(feature = "vec_resize_default", issue = "41758")]
1387 pub fn resize_default(&mut self, new_len: usize) {
1388 let len = self.len();
1391 self.extend_with(new_len - len, ExtendDefault);
1393 self.truncate(new_len);
1398 // This code generalises `extend_with_{element,default}`.
1399 trait ExtendWith<T> {
1400 fn next(&mut self) -> T;
1404 struct ExtendElement<T>(T);
1405 impl<T: Clone> ExtendWith<T> for ExtendElement<T> {
1406 fn next(&mut self) -> T { self.0.clone() }
1407 fn last(self) -> T { self.0 }
1410 struct ExtendDefault;
1411 impl<T: Default> ExtendWith<T> for ExtendDefault {
1412 fn next(&mut self) -> T { Default::default() }
1413 fn last(self) -> T { Default::default() }
1416 struct ExtendFunc<F>(F);
1417 impl<T, F: FnMut() -> T> ExtendWith<T> for ExtendFunc<F> {
1418 fn next(&mut self) -> T { (self.0)() }
1419 fn last(mut self) -> T { (self.0)() }
1423 /// Extend the vector by `n` values, using the given generator.
1424 fn extend_with<E: ExtendWith<T>>(&mut self, n: usize, mut value: E) {
1428 let mut ptr = self.as_mut_ptr().add(self.len());
1429 // Use SetLenOnDrop to work around bug where compiler
1430 // may not realize the store through `ptr` through self.set_len()
1432 let mut local_len = SetLenOnDrop::new(&mut self.len);
1434 // Write all elements except the last one
1436 ptr::write(ptr, value.next());
1437 ptr = ptr.offset(1);
1438 // Increment the length in every step in case next() panics
1439 local_len.increment_len(1);
1443 // We can write the last element directly without cloning needlessly
1444 ptr::write(ptr, value.last());
1445 local_len.increment_len(1);
1448 // len set by scope guard
1453 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1455 // The idea is: The length field in SetLenOnDrop is a local variable
1456 // that the optimizer will see does not alias with any stores through the Vec's data
1457 // pointer. This is a workaround for alias analysis issue #32155
1458 struct SetLenOnDrop<'a> {
1463 impl<'a> SetLenOnDrop<'a> {
1465 fn new(len: &'a mut usize) -> Self {
1466 SetLenOnDrop { local_len: *len, len: len }
1470 fn increment_len(&mut self, increment: usize) {
1471 self.local_len += increment;
1475 fn decrement_len(&mut self, decrement: usize) {
1476 self.local_len -= decrement;
1480 impl<'a> Drop for SetLenOnDrop<'a> {
1482 fn drop(&mut self) {
1483 *self.len = self.local_len;
1487 impl<T: PartialEq> Vec<T> {
1488 /// Removes consecutive repeated elements in the vector according to the
1489 /// [`PartialEq`] trait implementation.
1491 /// If the vector is sorted, this removes all duplicates.
1496 /// let mut vec = vec![1, 2, 2, 3, 2];
1500 /// assert_eq!(vec, [1, 2, 3, 2]);
1502 #[stable(feature = "rust1", since = "1.0.0")]
1504 pub fn dedup(&mut self) {
1505 self.dedup_by(|a, b| a == b)
1508 /// Removes the first instance of `item` from the vector if the item exists.
1513 /// # #![feature(vec_remove_item)]
1514 /// let mut vec = vec![1, 2, 3, 1];
1516 /// vec.remove_item(&1);
1518 /// assert_eq!(vec, vec![2, 3, 1]);
1520 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1521 pub fn remove_item(&mut self, item: &T) -> Option<T> {
1522 let pos = self.iter().position(|x| *x == *item)?;
1523 Some(self.remove(pos))
1527 ////////////////////////////////////////////////////////////////////////////////
1528 // Internal methods and functions
1529 ////////////////////////////////////////////////////////////////////////////////
1532 #[stable(feature = "rust1", since = "1.0.0")]
1533 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1534 <T as SpecFromElem>::from_elem(elem, n)
1537 // Specialization trait used for Vec::from_elem
1538 trait SpecFromElem: Sized {
1539 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1542 impl<T: Clone> SpecFromElem for T {
1543 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1544 let mut v = Vec::with_capacity(n);
1545 v.extend_with(n, ExtendElement(elem));
1550 impl SpecFromElem for u8 {
1552 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1555 buf: RawVec::with_capacity_zeroed(n),
1560 let mut v = Vec::with_capacity(n);
1561 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1568 impl<T: Clone + IsZero> SpecFromElem for T {
1570 fn from_elem(elem: T, n: usize) -> Vec<T> {
1573 buf: RawVec::with_capacity_zeroed(n),
1577 let mut v = Vec::with_capacity(n);
1578 v.extend_with(n, ExtendElement(elem));
1583 unsafe trait IsZero {
1584 /// Whether this value is zero
1585 fn is_zero(&self) -> bool;
1588 macro_rules! impl_is_zero {
1589 ($t: ty, $is_zero: expr) => {
1590 unsafe impl IsZero for $t {
1592 fn is_zero(&self) -> bool {
1599 impl_is_zero!(i8, |x| x == 0);
1600 impl_is_zero!(i16, |x| x == 0);
1601 impl_is_zero!(i32, |x| x == 0);
1602 impl_is_zero!(i64, |x| x == 0);
1603 impl_is_zero!(i128, |x| x == 0);
1604 impl_is_zero!(isize, |x| x == 0);
1606 impl_is_zero!(u16, |x| x == 0);
1607 impl_is_zero!(u32, |x| x == 0);
1608 impl_is_zero!(u64, |x| x == 0);
1609 impl_is_zero!(u128, |x| x == 0);
1610 impl_is_zero!(usize, |x| x == 0);
1612 impl_is_zero!(char, |x| x == '\0');
1614 impl_is_zero!(f32, |x: f32| x.to_bits() == 0);
1615 impl_is_zero!(f64, |x: f64| x.to_bits() == 0);
1617 unsafe impl<T: ?Sized> IsZero for *const T {
1619 fn is_zero(&self) -> bool {
1624 unsafe impl<T: ?Sized> IsZero for *mut T {
1626 fn is_zero(&self) -> bool {
1632 ////////////////////////////////////////////////////////////////////////////////
1633 // Common trait implementations for Vec
1634 ////////////////////////////////////////////////////////////////////////////////
1636 #[stable(feature = "rust1", since = "1.0.0")]
1637 impl<T: Clone> Clone for Vec<T> {
1639 fn clone(&self) -> Vec<T> {
1640 <[T]>::to_vec(&**self)
1643 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1644 // required for this method definition, is not available. Instead use the
1645 // `slice::to_vec` function which is only available with cfg(test)
1646 // NB see the slice::hack module in slice.rs for more information
1648 fn clone(&self) -> Vec<T> {
1649 ::slice::to_vec(&**self)
1652 fn clone_from(&mut self, other: &Vec<T>) {
1653 other.as_slice().clone_into(self);
1657 #[stable(feature = "rust1", since = "1.0.0")]
1658 impl<T: Hash> Hash for Vec<T> {
1660 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1661 Hash::hash(&**self, state)
1665 #[stable(feature = "rust1", since = "1.0.0")]
1666 #[rustc_on_unimplemented(
1667 message="vector indices are of type `usize` or ranges of `usize`",
1668 label="vector indices are of type `usize` or ranges of `usize`",
1670 impl<T, I> Index<I> for Vec<T>
1672 I: ::core::slice::SliceIndex<[T]>,
1674 type Output = I::Output;
1677 fn index(&self, index: I) -> &Self::Output {
1678 Index::index(&**self, index)
1682 #[stable(feature = "rust1", since = "1.0.0")]
1683 #[rustc_on_unimplemented(
1684 message="vector indices are of type `usize` or ranges of `usize`",
1685 label="vector indices are of type `usize` or ranges of `usize`",
1687 impl<T, I> IndexMut<I> for Vec<T>
1689 I: ::core::slice::SliceIndex<[T]>,
1692 fn index_mut(&mut self, index: I) -> &mut Self::Output {
1693 IndexMut::index_mut(&mut **self, index)
1697 #[stable(feature = "rust1", since = "1.0.0")]
1698 impl<T> ops::Deref for Vec<T> {
1701 fn deref(&self) -> &[T] {
1703 let p = self.buf.ptr();
1704 assume(!p.is_null());
1705 slice::from_raw_parts(p, self.len)
1710 #[stable(feature = "rust1", since = "1.0.0")]
1711 impl<T> ops::DerefMut for Vec<T> {
1712 fn deref_mut(&mut self) -> &mut [T] {
1714 let ptr = self.buf.ptr();
1715 assume(!ptr.is_null());
1716 slice::from_raw_parts_mut(ptr, self.len)
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 impl<T> FromIterator<T> for Vec<T> {
1724 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1725 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1729 #[stable(feature = "rust1", since = "1.0.0")]
1730 impl<T> IntoIterator for Vec<T> {
1732 type IntoIter = IntoIter<T>;
1734 /// Creates a consuming iterator, that is, one that moves each value out of
1735 /// the vector (from start to end). The vector cannot be used after calling
1741 /// let v = vec!["a".to_string(), "b".to_string()];
1742 /// for s in v.into_iter() {
1743 /// // s has type String, not &String
1744 /// println!("{}", s);
1748 fn into_iter(mut self) -> IntoIter<T> {
1750 let begin = self.as_mut_ptr();
1751 assume(!begin.is_null());
1752 let end = if mem::size_of::<T>() == 0 {
1753 arith_offset(begin as *const i8, self.len() as isize) as *const T
1755 begin.add(self.len()) as *const T
1757 let cap = self.buf.cap();
1760 buf: NonNull::new_unchecked(begin),
1761 phantom: PhantomData,
1770 #[stable(feature = "rust1", since = "1.0.0")]
1771 impl<'a, T> IntoIterator for &'a Vec<T> {
1773 type IntoIter = slice::Iter<'a, T>;
1775 fn into_iter(self) -> slice::Iter<'a, T> {
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1782 type Item = &'a mut T;
1783 type IntoIter = slice::IterMut<'a, T>;
1785 fn into_iter(self) -> slice::IterMut<'a, T> {
1790 #[stable(feature = "rust1", since = "1.0.0")]
1791 impl<T> Extend<T> for Vec<T> {
1793 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1794 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1798 // Specialization trait used for Vec::from_iter and Vec::extend
1799 trait SpecExtend<T, I> {
1800 fn from_iter(iter: I) -> Self;
1801 fn spec_extend(&mut self, iter: I);
1804 impl<T, I> SpecExtend<T, I> for Vec<T>
1805 where I: Iterator<Item=T>,
1807 default fn from_iter(mut iterator: I) -> Self {
1808 // Unroll the first iteration, as the vector is going to be
1809 // expanded on this iteration in every case when the iterable is not
1810 // empty, but the loop in extend_desugared() is not going to see the
1811 // vector being full in the few subsequent loop iterations.
1812 // So we get better branch prediction.
1813 let mut vector = match iterator.next() {
1814 None => return Vec::new(),
1816 let (lower, _) = iterator.size_hint();
1817 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1819 ptr::write(vector.get_unchecked_mut(0), element);
1825 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1829 default fn spec_extend(&mut self, iter: I) {
1830 self.extend_desugared(iter)
1834 impl<T, I> SpecExtend<T, I> for Vec<T>
1835 where I: TrustedLen<Item=T>,
1837 default fn from_iter(iterator: I) -> Self {
1838 let mut vector = Vec::new();
1839 vector.spec_extend(iterator);
1843 default fn spec_extend(&mut self, iterator: I) {
1844 // This is the case for a TrustedLen iterator.
1845 let (low, high) = iterator.size_hint();
1846 if let Some(high_value) = high {
1847 debug_assert_eq!(low, high_value,
1848 "TrustedLen iterator's size hint is not exact: {:?}",
1851 if let Some(additional) = high {
1852 self.reserve(additional);
1854 let mut ptr = self.as_mut_ptr().add(self.len());
1855 let mut local_len = SetLenOnDrop::new(&mut self.len);
1856 iterator.for_each(move |element| {
1857 ptr::write(ptr, element);
1858 ptr = ptr.offset(1);
1859 // NB can't overflow since we would have had to alloc the address space
1860 local_len.increment_len(1);
1864 self.extend_desugared(iterator)
1869 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
1870 fn from_iter(iterator: IntoIter<T>) -> Self {
1871 // A common case is passing a vector into a function which immediately
1872 // re-collects into a vector. We can short circuit this if the IntoIter
1873 // has not been advanced at all.
1874 if iterator.buf.as_ptr() as *const _ == iterator.ptr {
1876 let vec = Vec::from_raw_parts(iterator.buf.as_ptr(),
1879 mem::forget(iterator);
1883 let mut vector = Vec::new();
1884 vector.spec_extend(iterator);
1889 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
1891 self.append_elements(iterator.as_slice() as _);
1893 iterator.ptr = iterator.end;
1897 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
1898 where I: Iterator<Item=&'a T>,
1901 default fn from_iter(iterator: I) -> Self {
1902 SpecExtend::from_iter(iterator.cloned())
1905 default fn spec_extend(&mut self, iterator: I) {
1906 self.spec_extend(iterator.cloned())
1910 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
1913 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
1914 let slice = iterator.as_slice();
1915 self.reserve(slice.len());
1917 let len = self.len();
1918 self.set_len(len + slice.len());
1919 self.get_unchecked_mut(len..).copy_from_slice(slice);
1925 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1926 // This is the case for a general iterator.
1928 // This function should be the moral equivalent of:
1930 // for item in iterator {
1933 while let Some(element) = iterator.next() {
1934 let len = self.len();
1935 if len == self.capacity() {
1936 let (lower, _) = iterator.size_hint();
1937 self.reserve(lower.saturating_add(1));
1940 ptr::write(self.get_unchecked_mut(len), element);
1941 // NB can't overflow since we would have had to alloc the address space
1942 self.set_len(len + 1);
1947 /// Creates a splicing iterator that replaces the specified range in the vector
1948 /// with the given `replace_with` iterator and yields the removed items.
1949 /// `replace_with` does not need to be the same length as `range`.
1951 /// Note 1: The element range is removed even if the iterator is not
1952 /// consumed until the end.
1954 /// Note 2: It is unspecified how many elements are removed from the vector,
1955 /// if the `Splice` value is leaked.
1957 /// Note 3: The input iterator `replace_with` is only consumed
1958 /// when the `Splice` value is dropped.
1960 /// Note 4: This is optimal if:
1962 /// * The tail (elements in the vector after `range`) is empty,
1963 /// * or `replace_with` yields fewer elements than `range`’s length
1964 /// * or the lower bound of its `size_hint()` is exact.
1966 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
1970 /// Panics if the starting point is greater than the end point or if
1971 /// the end point is greater than the length of the vector.
1976 /// let mut v = vec![1, 2, 3];
1977 /// let new = [7, 8];
1978 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
1979 /// assert_eq!(v, &[7, 8, 3]);
1980 /// assert_eq!(u, &[1, 2]);
1983 #[stable(feature = "vec_splice", since = "1.21.0")]
1984 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<I::IntoIter>
1985 where R: RangeBounds<usize>, I: IntoIterator<Item=T>
1988 drain: self.drain(range),
1989 replace_with: replace_with.into_iter(),
1993 /// Creates an iterator which uses a closure to determine if an element should be removed.
1995 /// If the closure returns true, then the element is removed and yielded.
1996 /// If the closure returns false, the element will remain in the vector and will not be yielded
1997 /// by the iterator.
1999 /// Using this method is equivalent to the following code:
2002 /// # let some_predicate = |x: &mut i32| { *x == 2 || *x == 3 || *x == 6 };
2003 /// # let mut vec = vec![1, 2, 3, 4, 5, 6];
2005 /// while i != vec.len() {
2006 /// if some_predicate(&mut vec[i]) {
2007 /// let val = vec.remove(i);
2008 /// // your code here
2014 /// # assert_eq!(vec, vec![1, 4, 5]);
2017 /// But `drain_filter` is easier to use. `drain_filter` is also more efficient,
2018 /// because it can backshift the elements of the array in bulk.
2020 /// Note that `drain_filter` also lets you mutate every element in the filter closure,
2021 /// regardless of whether you choose to keep or remove it.
2026 /// Splitting an array into evens and odds, reusing the original allocation:
2029 /// #![feature(drain_filter)]
2030 /// let mut numbers = vec![1, 2, 3, 4, 5, 6, 8, 9, 11, 13, 14, 15];
2032 /// let evens = numbers.drain_filter(|x| *x % 2 == 0).collect::<Vec<_>>();
2033 /// let odds = numbers;
2035 /// assert_eq!(evens, vec![2, 4, 6, 8, 14]);
2036 /// assert_eq!(odds, vec![1, 3, 5, 9, 11, 13, 15]);
2038 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2039 pub fn drain_filter<F>(&mut self, filter: F) -> DrainFilter<T, F>
2040 where F: FnMut(&mut T) -> bool,
2042 let old_len = self.len();
2044 // Guard against us getting leaked (leak amplification)
2045 unsafe { self.set_len(0); }
2057 /// Extend implementation that copies elements out of references before pushing them onto the Vec.
2059 /// This implementation is specialized for slice iterators, where it uses [`copy_from_slice`] to
2060 /// append the entire slice at once.
2062 /// [`copy_from_slice`]: ../../std/primitive.slice.html#method.copy_from_slice
2063 #[stable(feature = "extend_ref", since = "1.2.0")]
2064 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
2065 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
2066 self.spec_extend(iter.into_iter())
2070 macro_rules! __impl_slice_eq1 {
2071 ($Lhs: ty, $Rhs: ty) => {
2072 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
2074 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
2075 #[stable(feature = "rust1", since = "1.0.0")]
2076 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
2078 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
2080 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
2085 __impl_slice_eq1! { Vec<A>, Vec<B> }
2086 __impl_slice_eq1! { Vec<A>, &'b [B] }
2087 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
2088 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
2089 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
2090 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
2092 macro_rules! array_impls {
2095 // NOTE: some less important impls are omitted to reduce code bloat
2096 __impl_slice_eq1! { Vec<A>, [B; $N] }
2097 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
2098 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
2099 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
2100 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
2101 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
2108 10 11 12 13 14 15 16 17 18 19
2109 20 21 22 23 24 25 26 27 28 29
2113 /// Implements comparison of vectors, lexicographically.
2114 #[stable(feature = "rust1", since = "1.0.0")]
2115 impl<T: PartialOrd> PartialOrd for Vec<T> {
2117 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
2118 PartialOrd::partial_cmp(&**self, &**other)
2122 #[stable(feature = "rust1", since = "1.0.0")]
2123 impl<T: Eq> Eq for Vec<T> {}
2125 /// Implements ordering of vectors, lexicographically.
2126 #[stable(feature = "rust1", since = "1.0.0")]
2127 impl<T: Ord> Ord for Vec<T> {
2129 fn cmp(&self, other: &Vec<T>) -> Ordering {
2130 Ord::cmp(&**self, &**other)
2134 #[stable(feature = "rust1", since = "1.0.0")]
2135 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
2136 fn drop(&mut self) {
2139 ptr::drop_in_place(&mut self[..]);
2141 // RawVec handles deallocation
2145 #[stable(feature = "rust1", since = "1.0.0")]
2146 impl<T> Default for Vec<T> {
2147 /// Creates an empty `Vec<T>`.
2148 fn default() -> Vec<T> {
2153 #[stable(feature = "rust1", since = "1.0.0")]
2154 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
2155 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2156 fmt::Debug::fmt(&**self, f)
2160 #[stable(feature = "rust1", since = "1.0.0")]
2161 impl<T> AsRef<Vec<T>> for Vec<T> {
2162 fn as_ref(&self) -> &Vec<T> {
2167 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2168 impl<T> AsMut<Vec<T>> for Vec<T> {
2169 fn as_mut(&mut self) -> &mut Vec<T> {
2174 #[stable(feature = "rust1", since = "1.0.0")]
2175 impl<T> AsRef<[T]> for Vec<T> {
2176 fn as_ref(&self) -> &[T] {
2181 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2182 impl<T> AsMut<[T]> for Vec<T> {
2183 fn as_mut(&mut self) -> &mut [T] {
2188 #[stable(feature = "rust1", since = "1.0.0")]
2189 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
2191 fn from(s: &'a [T]) -> Vec<T> {
2195 fn from(s: &'a [T]) -> Vec<T> {
2200 #[stable(feature = "vec_from_mut", since = "1.19.0")]
2201 impl<'a, T: Clone> From<&'a mut [T]> for Vec<T> {
2203 fn from(s: &'a mut [T]) -> Vec<T> {
2207 fn from(s: &'a mut [T]) -> Vec<T> {
2212 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2213 impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> {
2214 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2219 // note: test pulls in libstd, which causes errors here
2221 #[stable(feature = "vec_from_box", since = "1.18.0")]
2222 impl<T> From<Box<[T]>> for Vec<T> {
2223 fn from(s: Box<[T]>) -> Vec<T> {
2228 // note: test pulls in libstd, which causes errors here
2230 #[stable(feature = "box_from_vec", since = "1.20.0")]
2231 impl<T> From<Vec<T>> for Box<[T]> {
2232 fn from(v: Vec<T>) -> Box<[T]> {
2233 v.into_boxed_slice()
2237 #[stable(feature = "rust1", since = "1.0.0")]
2238 impl<'a> From<&'a str> for Vec<u8> {
2239 fn from(s: &'a str) -> Vec<u8> {
2240 From::from(s.as_bytes())
2244 ////////////////////////////////////////////////////////////////////////////////
2246 ////////////////////////////////////////////////////////////////////////////////
2248 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2249 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2250 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2255 #[stable(feature = "cow_from_vec", since = "1.8.0")]
2256 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2257 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2262 #[stable(feature = "cow_from_vec_ref", since = "1.28.0")]
2263 impl<'a, T: Clone> From<&'a Vec<T>> for Cow<'a, [T]> {
2264 fn from(v: &'a Vec<T>) -> Cow<'a, [T]> {
2265 Cow::Borrowed(v.as_slice())
2269 #[stable(feature = "rust1", since = "1.0.0")]
2270 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
2271 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2272 Cow::Owned(FromIterator::from_iter(it))
2276 ////////////////////////////////////////////////////////////////////////////////
2278 ////////////////////////////////////////////////////////////////////////////////
2280 /// An iterator that moves out of a vector.
2282 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2283 /// by the [`IntoIterator`] trait).
2285 /// [`Vec`]: struct.Vec.html
2286 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2287 #[stable(feature = "rust1", since = "1.0.0")]
2288 pub struct IntoIter<T> {
2290 phantom: PhantomData<T>,
2296 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2297 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2298 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2299 f.debug_tuple("IntoIter")
2300 .field(&self.as_slice())
2305 impl<T> IntoIter<T> {
2306 /// Returns the remaining items of this iterator as a slice.
2311 /// let vec = vec!['a', 'b', 'c'];
2312 /// let mut into_iter = vec.into_iter();
2313 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2314 /// let _ = into_iter.next().unwrap();
2315 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2317 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2318 pub fn as_slice(&self) -> &[T] {
2320 slice::from_raw_parts(self.ptr, self.len())
2324 /// Returns the remaining items of this iterator as a mutable slice.
2329 /// let vec = vec!['a', 'b', 'c'];
2330 /// let mut into_iter = vec.into_iter();
2331 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2332 /// into_iter.as_mut_slice()[2] = 'z';
2333 /// assert_eq!(into_iter.next().unwrap(), 'a');
2334 /// assert_eq!(into_iter.next().unwrap(), 'b');
2335 /// assert_eq!(into_iter.next().unwrap(), 'z');
2337 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2338 pub fn as_mut_slice(&mut self) -> &mut [T] {
2340 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
2345 #[stable(feature = "rust1", since = "1.0.0")]
2346 unsafe impl<T: Send> Send for IntoIter<T> {}
2347 #[stable(feature = "rust1", since = "1.0.0")]
2348 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2350 #[stable(feature = "rust1", since = "1.0.0")]
2351 impl<T> Iterator for IntoIter<T> {
2355 fn next(&mut self) -> Option<T> {
2357 if self.ptr as *const _ == self.end {
2360 if mem::size_of::<T>() == 0 {
2361 // purposefully don't use 'ptr.offset' because for
2362 // vectors with 0-size elements this would return the
2364 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2366 // Make up a value of this ZST.
2370 self.ptr = self.ptr.offset(1);
2372 Some(ptr::read(old))
2379 fn size_hint(&self) -> (usize, Option<usize>) {
2380 let exact = if mem::size_of::<T>() == 0 {
2381 (self.end as usize).wrapping_sub(self.ptr as usize)
2383 unsafe { self.end.offset_from(self.ptr) as usize }
2385 (exact, Some(exact))
2389 fn count(self) -> usize {
2394 #[stable(feature = "rust1", since = "1.0.0")]
2395 impl<T> DoubleEndedIterator for IntoIter<T> {
2397 fn next_back(&mut self) -> Option<T> {
2399 if self.end == self.ptr {
2402 if mem::size_of::<T>() == 0 {
2403 // See above for why 'ptr.offset' isn't used
2404 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2406 // Make up a value of this ZST.
2409 self.end = self.end.offset(-1);
2411 Some(ptr::read(self.end))
2418 #[stable(feature = "rust1", since = "1.0.0")]
2419 impl<T> ExactSizeIterator for IntoIter<T> {
2420 fn is_empty(&self) -> bool {
2421 self.ptr == self.end
2425 #[stable(feature = "fused", since = "1.26.0")]
2426 impl<T> FusedIterator for IntoIter<T> {}
2428 #[unstable(feature = "trusted_len", issue = "37572")]
2429 unsafe impl<T> TrustedLen for IntoIter<T> {}
2431 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2432 impl<T: Clone> Clone for IntoIter<T> {
2433 fn clone(&self) -> IntoIter<T> {
2434 self.as_slice().to_owned().into_iter()
2438 #[stable(feature = "rust1", since = "1.0.0")]
2439 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2440 fn drop(&mut self) {
2441 // destroy the remaining elements
2442 for _x in self.by_ref() {}
2444 // RawVec handles deallocation
2445 let _ = unsafe { RawVec::from_raw_parts(self.buf.as_ptr(), self.cap) };
2449 /// A draining iterator for `Vec<T>`.
2451 /// This `struct` is created by the [`drain`] method on [`Vec`].
2453 /// [`drain`]: struct.Vec.html#method.drain
2454 /// [`Vec`]: struct.Vec.html
2455 #[stable(feature = "drain", since = "1.6.0")]
2456 pub struct Drain<'a, T: 'a> {
2457 /// Index of tail to preserve
2461 /// Current remaining range to remove
2462 iter: slice::Iter<'a, T>,
2463 vec: NonNull<Vec<T>>,
2466 #[stable(feature = "collection_debug", since = "1.17.0")]
2467 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2468 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2469 f.debug_tuple("Drain")
2470 .field(&self.iter.as_slice())
2475 #[stable(feature = "drain", since = "1.6.0")]
2476 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2477 #[stable(feature = "drain", since = "1.6.0")]
2478 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2480 #[stable(feature = "drain", since = "1.6.0")]
2481 impl<'a, T> Iterator for Drain<'a, T> {
2485 fn next(&mut self) -> Option<T> {
2486 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2489 fn size_hint(&self) -> (usize, Option<usize>) {
2490 self.iter.size_hint()
2494 #[stable(feature = "drain", since = "1.6.0")]
2495 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
2497 fn next_back(&mut self) -> Option<T> {
2498 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2502 #[stable(feature = "drain", since = "1.6.0")]
2503 impl<'a, T> Drop for Drain<'a, T> {
2504 fn drop(&mut self) {
2505 // exhaust self first
2506 self.for_each(drop);
2508 if self.tail_len > 0 {
2510 let source_vec = self.vec.as_mut();
2511 // memmove back untouched tail, update to new length
2512 let start = source_vec.len();
2513 let tail = self.tail_start;
2515 let src = source_vec.as_ptr().add(tail);
2516 let dst = source_vec.as_mut_ptr().add(start);
2517 ptr::copy(src, dst, self.tail_len);
2519 source_vec.set_len(start + self.tail_len);
2526 #[stable(feature = "drain", since = "1.6.0")]
2527 impl<'a, T> ExactSizeIterator for Drain<'a, T> {
2528 fn is_empty(&self) -> bool {
2529 self.iter.is_empty()
2533 #[stable(feature = "fused", since = "1.26.0")]
2534 impl<'a, T> FusedIterator for Drain<'a, T> {}
2536 /// A splicing iterator for `Vec`.
2538 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2539 /// documentation for more.
2541 /// [`splice()`]: struct.Vec.html#method.splice
2542 /// [`Vec`]: struct.Vec.html
2544 #[stable(feature = "vec_splice", since = "1.21.0")]
2545 pub struct Splice<'a, I: Iterator + 'a> {
2546 drain: Drain<'a, I::Item>,
2550 #[stable(feature = "vec_splice", since = "1.21.0")]
2551 impl<'a, I: Iterator> Iterator for Splice<'a, I> {
2552 type Item = I::Item;
2554 fn next(&mut self) -> Option<Self::Item> {
2558 fn size_hint(&self) -> (usize, Option<usize>) {
2559 self.drain.size_hint()
2563 #[stable(feature = "vec_splice", since = "1.21.0")]
2564 impl<'a, I: Iterator> DoubleEndedIterator for Splice<'a, I> {
2565 fn next_back(&mut self) -> Option<Self::Item> {
2566 self.drain.next_back()
2570 #[stable(feature = "vec_splice", since = "1.21.0")]
2571 impl<'a, I: Iterator> ExactSizeIterator for Splice<'a, I> {}
2574 #[stable(feature = "vec_splice", since = "1.21.0")]
2575 impl<'a, I: Iterator> Drop for Splice<'a, I> {
2576 fn drop(&mut self) {
2577 self.drain.by_ref().for_each(drop);
2580 if self.drain.tail_len == 0 {
2581 self.drain.vec.as_mut().extend(self.replace_with.by_ref());
2585 // First fill the range left by drain().
2586 if !self.drain.fill(&mut self.replace_with) {
2590 // There may be more elements. Use the lower bound as an estimate.
2591 // FIXME: Is the upper bound a better guess? Or something else?
2592 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2593 if lower_bound > 0 {
2594 self.drain.move_tail(lower_bound);
2595 if !self.drain.fill(&mut self.replace_with) {
2600 // Collect any remaining elements.
2601 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2602 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2603 // Now we have an exact count.
2604 if collected.len() > 0 {
2605 self.drain.move_tail(collected.len());
2606 let filled = self.drain.fill(&mut collected);
2607 debug_assert!(filled);
2608 debug_assert_eq!(collected.len(), 0);
2611 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2615 /// Private helper methods for `Splice::drop`
2616 impl<'a, T> Drain<'a, T> {
2617 /// The range from `self.vec.len` to `self.tail_start` contains elements
2618 /// that have been moved out.
2619 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2620 /// Return whether we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2621 unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
2622 let vec = self.vec.as_mut();
2623 let range_start = vec.len;
2624 let range_end = self.tail_start;
2625 let range_slice = slice::from_raw_parts_mut(
2626 vec.as_mut_ptr().add(range_start),
2627 range_end - range_start);
2629 for place in range_slice {
2630 if let Some(new_item) = replace_with.next() {
2631 ptr::write(place, new_item);
2640 /// Make room for inserting more elements before the tail.
2641 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2642 let vec = self.vec.as_mut();
2643 let used_capacity = self.tail_start + self.tail_len;
2644 vec.buf.reserve(used_capacity, extra_capacity);
2646 let new_tail_start = self.tail_start + extra_capacity;
2647 let src = vec.as_ptr().add(self.tail_start);
2648 let dst = vec.as_mut_ptr().add(new_tail_start);
2649 ptr::copy(src, dst, self.tail_len);
2650 self.tail_start = new_tail_start;
2654 /// An iterator produced by calling `drain_filter` on Vec.
2655 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2657 pub struct DrainFilter<'a, T: 'a, F>
2658 where F: FnMut(&mut T) -> bool,
2660 vec: &'a mut Vec<T>,
2667 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2668 impl<'a, T, F> Iterator for DrainFilter<'a, T, F>
2669 where F: FnMut(&mut T) -> bool,
2673 fn next(&mut self) -> Option<T> {
2675 while self.idx != self.old_len {
2678 let v = slice::from_raw_parts_mut(self.vec.as_mut_ptr(), self.old_len);
2679 if (self.pred)(&mut v[i]) {
2681 return Some(ptr::read(&v[i]));
2682 } else if self.del > 0 {
2684 let src: *const T = &v[i];
2685 let dst: *mut T = &mut v[i - del];
2686 // This is safe because self.vec has length 0
2687 // thus its elements will not have Drop::drop
2688 // called on them in the event of a panic.
2689 ptr::copy_nonoverlapping(src, dst, 1);
2696 fn size_hint(&self) -> (usize, Option<usize>) {
2697 (0, Some(self.old_len - self.idx))
2701 #[unstable(feature = "drain_filter", reason = "recently added", issue = "43244")]
2702 impl<'a, T, F> Drop for DrainFilter<'a, T, F>
2703 where F: FnMut(&mut T) -> bool,
2705 fn drop(&mut self) {
2706 self.for_each(drop);
2708 self.vec.set_len(self.old_len - self.del);