1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A contiguous growable array type with heap-allocated contents, written
12 //! `Vec<T>` but pronounced 'vector.'
14 //! Vectors have `O(1)` indexing, amortized `O(1)` push (to the end) and
15 //! `O(1)` pop (from the end).
19 //! You can explicitly create a [`Vec<T>`] with [`new`]:
22 //! let v: Vec<i32> = Vec::new();
25 //! ...or by using the [`vec!`] macro:
28 //! let v: Vec<i32> = vec![];
30 //! let v = vec![1, 2, 3, 4, 5];
32 //! let v = vec![0; 10]; // ten zeroes
35 //! You can [`push`] values onto the end of a vector (which will grow the vector
39 //! let mut v = vec![1, 2];
44 //! Popping values works in much the same way:
47 //! let mut v = vec![1, 2];
49 //! let two = v.pop();
52 //! Vectors also support indexing (through the [`Index`] and [`IndexMut`] traits):
55 //! let mut v = vec![1, 2, 3];
60 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
61 //! [`new`]: ../../std/vec/struct.Vec.html#method.new
62 //! [`push`]: ../../std/vec/struct.Vec.html#method.push
63 //! [`Index`]: ../../std/ops/trait.Index.html
64 //! [`IndexMut`]: ../../std/ops/trait.IndexMut.html
65 //! [`vec!`]: ../../std/macro.vec.html
67 #![stable(feature = "rust1", since = "1.0.0")]
69 use alloc::boxed::Box;
70 use alloc::heap::EMPTY;
71 use alloc::raw_vec::RawVec;
74 use core::cmp::Ordering;
76 use core::hash::{self, Hash};
77 use core::intrinsics::{arith_offset, assume};
78 use core::iter::{FromIterator, FusedIterator, TrustedLen};
82 use core::ops::{InPlace, Index, IndexMut, Place, Placer};
85 use core::ptr::Shared;
88 use super::range::RangeArgument;
89 use Bound::{Excluded, Included, Unbounded};
91 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector'.
96 /// let mut vec = Vec::new();
100 /// assert_eq!(vec.len(), 2);
101 /// assert_eq!(vec[0], 1);
103 /// assert_eq!(vec.pop(), Some(2));
104 /// assert_eq!(vec.len(), 1);
107 /// assert_eq!(vec[0], 7);
109 /// vec.extend([1, 2, 3].iter().cloned());
112 /// println!("{}", x);
114 /// assert_eq!(vec, [7, 1, 2, 3]);
117 /// The [`vec!`] macro is provided to make initialization more convenient:
120 /// let mut vec = vec![1, 2, 3];
122 /// assert_eq!(vec, [1, 2, 3, 4]);
125 /// It can also initialize each element of a `Vec<T>` with a given value:
128 /// let vec = vec![0; 5];
129 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
132 /// Use a `Vec<T>` as an efficient stack:
135 /// let mut stack = Vec::new();
141 /// while let Some(top) = stack.pop() {
142 /// // Prints 3, 2, 1
143 /// println!("{}", top);
149 /// The `Vec` type allows to access values by index, because it implements the
150 /// [`Index`] trait. An example will be more explicit:
153 /// let v = vec![0, 2, 4, 6];
154 /// println!("{}", v[1]); // it will display '2'
157 /// However be careful: if you try to access an index which isn't in the `Vec`,
158 /// your software will panic! You cannot do this:
161 /// let v = vec![0, 2, 4, 6];
162 /// println!("{}", v[6]); // it will panic!
165 /// In conclusion: always check if the index you want to get really exists
170 /// A `Vec` can be mutable. Slices, on the other hand, are read-only objects.
171 /// To get a slice, use `&`. Example:
174 /// fn read_slice(slice: &[usize]) {
178 /// let v = vec![0, 1];
181 /// // ... and that's all!
182 /// // you can also do it like this:
183 /// let x : &[usize] = &v;
186 /// In Rust, it's more common to pass slices as arguments rather than vectors
187 /// when you just want to provide a read access. The same goes for [`String`] and
190 /// # Capacity and reallocation
192 /// The capacity of a vector is the amount of space allocated for any future
193 /// elements that will be added onto the vector. This is not to be confused with
194 /// the *length* of a vector, which specifies the number of actual elements
195 /// within the vector. If a vector's length exceeds its capacity, its capacity
196 /// will automatically be increased, but its elements will have to be
199 /// For example, a vector with capacity 10 and length 0 would be an empty vector
200 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
201 /// vector will not change its capacity or cause reallocation to occur. However,
202 /// if the vector's length is increased to 11, it will have to reallocate, which
203 /// can be slow. For this reason, it is recommended to use [`Vec::with_capacity`]
204 /// whenever possible to specify how big the vector is expected to get.
208 /// Due to its incredibly fundamental nature, `Vec` makes a lot of guarantees
209 /// about its design. This ensures that it's as low-overhead as possible in
210 /// the general case, and can be correctly manipulated in primitive ways
211 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
212 /// If additional type parameters are added (e.g. to support custom allocators),
213 /// overriding their defaults may change the behavior.
215 /// Most fundamentally, `Vec` is and always will be a (pointer, capacity, length)
216 /// triplet. No more, no less. The order of these fields is completely
217 /// unspecified, and you should use the appropriate methods to modify these.
218 /// The pointer will never be null, so this type is null-pointer-optimized.
220 /// However, the pointer may not actually point to allocated memory. In particular,
221 /// if you construct a `Vec` with capacity 0 via [`Vec::new`], [`vec![]`][`vec!`],
222 /// [`Vec::with_capacity(0)`][`Vec::with_capacity`], or by calling [`shrink_to_fit`]
223 /// on an empty Vec, it will not allocate memory. Similarly, if you store zero-sized
224 /// types inside a `Vec`, it will not allocate space for them. *Note that in this case
225 /// the `Vec` may not report a [`capacity`] of 0*. `Vec` will allocate if and only
226 /// if [`mem::size_of::<T>`]` * capacity() > 0`. In general, `Vec`'s allocation
227 /// details are subtle enough that it is strongly recommended that you only
228 /// free memory allocated by a `Vec` by creating a new `Vec` and dropping it.
230 /// If a `Vec` *has* allocated memory, then the memory it points to is on the heap
231 /// (as defined by the allocator Rust is configured to use by default), and its
232 /// pointer points to [`len`] initialized elements in order (what you would see
233 /// if you coerced it to a slice), followed by [`capacity`]` - `[`len`]
234 /// logically uninitialized elements.
236 /// `Vec` will never perform a "small optimization" where elements are actually
237 /// stored on the stack for two reasons:
239 /// * It would make it more difficult for unsafe code to correctly manipulate
240 /// a `Vec`. The contents of a `Vec` wouldn't have a stable address if it were
241 /// only moved, and it would be more difficult to determine if a `Vec` had
242 /// actually allocated memory.
244 /// * It would penalize the general case, incurring an additional branch
247 /// `Vec` will never automatically shrink itself, even if completely empty. This
248 /// ensures no unnecessary allocations or deallocations occur. Emptying a `Vec`
249 /// and then filling it back up to the same [`len`] should incur no calls to
250 /// the allocator. If you wish to free up unused memory, use
251 /// [`shrink_to_fit`][`shrink_to_fit`].
253 /// [`push`] and [`insert`] will never (re)allocate if the reported capacity is
254 /// sufficient. [`push`] and [`insert`] *will* (re)allocate if
255 /// [`len`]` == `[`capacity`]. That is, the reported capacity is completely
256 /// accurate, and can be relied on. It can even be used to manually free the memory
257 /// allocated by a `Vec` if desired. Bulk insertion methods *may* reallocate, even
258 /// when not necessary.
260 /// `Vec` does not guarantee any particular growth strategy when reallocating
261 /// when full, nor when [`reserve`] is called. The current strategy is basic
262 /// and it may prove desirable to use a non-constant growth factor. Whatever
263 /// strategy is used will of course guarantee `O(1)` amortized [`push`].
265 /// `vec![x; n]`, `vec![a, b, c, d]`, and
266 /// [`Vec::with_capacity(n)`][`Vec::with_capacity`], will all produce a `Vec`
267 /// with exactly the requested capacity. If [`len`]` == `[`capacity`],
268 /// (as is the case for the [`vec!`] macro), then a `Vec<T>` can be converted to
269 /// and from a [`Box<[T]>`][owned slice] without reallocating or moving the elements.
271 /// `Vec` will not specifically overwrite any data that is removed from it,
272 /// but also won't specifically preserve it. Its uninitialized memory is
273 /// scratch space that it may use however it wants. It will generally just do
274 /// whatever is most efficient or otherwise easy to implement. Do not rely on
275 /// removed data to be erased for security purposes. Even if you drop a `Vec`, its
276 /// buffer may simply be reused by another `Vec`. Even if you zero a `Vec`'s memory
277 /// first, that may not actually happen because the optimizer does not consider
278 /// this a side-effect that must be preserved. There is one case which we will
279 /// not break, however: using `unsafe` code to write to the excess capacity,
280 /// and then increasing the length to match, is always valid.
282 /// `Vec` does not currently guarantee the order in which elements are dropped
283 /// (the order has changed in the past, and may change again).
285 /// [`vec!`]: ../../std/macro.vec.html
286 /// [`Index`]: ../../std/ops/trait.Index.html
287 /// [`String`]: ../../std/string/struct.String.html
288 /// [`&str`]: ../../std/primitive.str.html
289 /// [`Vec::with_capacity`]: ../../std/vec/struct.Vec.html#method.with_capacity
290 /// [`Vec::new`]: ../../std/vec/struct.Vec.html#method.new
291 /// [`shrink_to_fit`]: ../../std/vec/struct.Vec.html#method.shrink_to_fit
292 /// [`capacity`]: ../../std/vec/struct.Vec.html#method.capacity
293 /// [`mem::size_of::<T>`]: ../../std/mem/fn.size_of.html
294 /// [`len`]: ../../std/vec/struct.Vec.html#method.len
295 /// [`push`]: ../../std/vec/struct.Vec.html#method.push
296 /// [`insert`]: ../../std/vec/struct.Vec.html#method.insert
297 /// [`reserve`]: ../../std/vec/struct.Vec.html#method.reserve
298 /// [owned slice]: ../../std/boxed/struct.Box.html
299 #[stable(feature = "rust1", since = "1.0.0")]
305 ////////////////////////////////////////////////////////////////////////////////
307 ////////////////////////////////////////////////////////////////////////////////
310 /// Constructs a new, empty `Vec<T>`.
312 /// The vector will not allocate until elements are pushed onto it.
317 /// # #![allow(unused_mut)]
318 /// let mut vec: Vec<i32> = Vec::new();
321 #[stable(feature = "rust1", since = "1.0.0")]
322 pub fn new() -> Vec<T> {
329 /// Constructs a new, empty `Vec<T>` with the specified capacity.
331 /// The vector will be able to hold exactly `capacity` elements without
332 /// reallocating. If `capacity` is 0, the vector will not allocate.
334 /// It is important to note that this function does not specify the *length*
335 /// of the returned vector, but only the *capacity*. For an explanation of
336 /// the difference between length and capacity, see *[Capacity and reallocation]*.
338 /// [Capacity and reallocation]: #capacity-and-reallocation
343 /// let mut vec = Vec::with_capacity(10);
345 /// // The vector contains no items, even though it has capacity for more
346 /// assert_eq!(vec.len(), 0);
348 /// // These are all done without reallocating...
353 /// // ...but this may make the vector reallocate
357 #[stable(feature = "rust1", since = "1.0.0")]
358 pub fn with_capacity(capacity: usize) -> Vec<T> {
360 buf: RawVec::with_capacity(capacity),
365 /// Creates a `Vec<T>` directly from the raw components of another vector.
369 /// This is highly unsafe, due to the number of invariants that aren't
372 /// * `ptr` needs to have been previously allocated via [`String`]/`Vec<T>`
373 /// (at least, it's highly likely to be incorrect if it wasn't).
374 /// * `length` needs to be less than or equal to `capacity`.
375 /// * `capacity` needs to be the capacity that the pointer was allocated with.
377 /// Violating these may cause problems like corrupting the allocator's
378 /// internal datastructures. For example it is **not** safe
379 /// to build a `Vec<u8>` from a pointer to a C `char` array and a `size_t`.
381 /// The ownership of `ptr` is effectively transferred to the
382 /// `Vec<T>` which may then deallocate, reallocate or change the
383 /// contents of memory pointed to by the pointer at will. Ensure
384 /// that nothing else uses the pointer after calling this
387 /// [`String`]: ../../std/string/struct.String.html
396 /// let mut v = vec![1, 2, 3];
398 /// // Pull out the various important pieces of information about `v`
399 /// let p = v.as_mut_ptr();
400 /// let len = v.len();
401 /// let cap = v.capacity();
404 /// // Cast `v` into the void: no destructor run, so we are in
405 /// // complete control of the allocation to which `p` points.
408 /// // Overwrite memory with 4, 5, 6
409 /// for i in 0..len as isize {
410 /// ptr::write(p.offset(i), 4 + i);
413 /// // Put everything back together into a Vec
414 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
415 /// assert_eq!(rebuilt, [4, 5, 6]);
419 #[stable(feature = "rust1", since = "1.0.0")]
420 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
422 buf: RawVec::from_raw_parts(ptr, capacity),
427 /// Returns the number of elements the vector can hold without
433 /// let vec: Vec<i32> = Vec::with_capacity(10);
434 /// assert_eq!(vec.capacity(), 10);
437 #[stable(feature = "rust1", since = "1.0.0")]
438 pub fn capacity(&self) -> usize {
442 /// Reserves capacity for at least `additional` more elements to be inserted
443 /// in the given `Vec<T>`. The collection may reserve more space to avoid
444 /// frequent reallocations. After calling `reserve`, capacity will be
445 /// greater than or equal to `self.len() + additional`. Does nothing if
446 /// capacity is already sufficient.
450 /// Panics if the new capacity overflows `usize`.
455 /// let mut vec = vec![1];
457 /// assert!(vec.capacity() >= 11);
459 #[stable(feature = "rust1", since = "1.0.0")]
460 pub fn reserve(&mut self, additional: usize) {
461 self.buf.reserve(self.len, additional);
464 /// Reserves the minimum capacity for exactly `additional` more elements to
465 /// be inserted in the given `Vec<T>`. After calling `reserve_exact`,
466 /// capacity will be greater than or equal to `self.len() + additional`.
467 /// Does nothing if the capacity is already sufficient.
469 /// Note that the allocator may give the collection more space than it
470 /// requests. Therefore capacity can not be relied upon to be precisely
471 /// minimal. Prefer `reserve` if future insertions are expected.
475 /// Panics if the new capacity overflows `usize`.
480 /// let mut vec = vec![1];
481 /// vec.reserve_exact(10);
482 /// assert!(vec.capacity() >= 11);
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub fn reserve_exact(&mut self, additional: usize) {
486 self.buf.reserve_exact(self.len, additional);
489 /// Shrinks the capacity of the vector as much as possible.
491 /// It will drop down as close as possible to the length but the allocator
492 /// may still inform the vector that there is space for a few more elements.
497 /// let mut vec = Vec::with_capacity(10);
498 /// vec.extend([1, 2, 3].iter().cloned());
499 /// assert_eq!(vec.capacity(), 10);
500 /// vec.shrink_to_fit();
501 /// assert!(vec.capacity() >= 3);
503 #[stable(feature = "rust1", since = "1.0.0")]
504 pub fn shrink_to_fit(&mut self) {
505 self.buf.shrink_to_fit(self.len);
508 /// Converts the vector into [`Box<[T]>`][owned slice].
510 /// Note that this will drop any excess capacity. Calling this and
511 /// converting back to a vector with [`into_vec`] is equivalent to calling
512 /// [`shrink_to_fit`].
514 /// [owned slice]: ../../std/boxed/struct.Box.html
515 /// [`into_vec`]: ../../std/primitive.slice.html#method.into_vec
516 /// [`shrink_to_fit`]: #method.shrink_to_fit
521 /// let v = vec![1, 2, 3];
523 /// let slice = v.into_boxed_slice();
526 /// Any excess capacity is removed:
529 /// let mut vec = Vec::with_capacity(10);
530 /// vec.extend([1, 2, 3].iter().cloned());
532 /// assert_eq!(vec.capacity(), 10);
533 /// let slice = vec.into_boxed_slice();
534 /// assert_eq!(slice.into_vec().capacity(), 3);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn into_boxed_slice(mut self) -> Box<[T]> {
539 self.shrink_to_fit();
540 let buf = ptr::read(&self.buf);
546 /// Shortens the vector, keeping the first `len` elements and dropping
549 /// If `len` is greater than the vector's current length, this has no
552 /// The [`drain`] method can emulate `truncate`, but causes the excess
553 /// elements to be returned instead of dropped.
555 /// Note that this method has no effect on the allocated capacity
560 /// Truncating a five element vector to two elements:
563 /// let mut vec = vec![1, 2, 3, 4, 5];
565 /// assert_eq!(vec, [1, 2]);
568 /// No truncation occurs when `len` is greater than the vector's current
572 /// let mut vec = vec![1, 2, 3];
574 /// assert_eq!(vec, [1, 2, 3]);
577 /// Truncating when `len == 0` is equivalent to calling the [`clear`]
581 /// let mut vec = vec![1, 2, 3];
583 /// assert_eq!(vec, []);
586 /// [`clear`]: #method.clear
587 /// [`drain`]: #method.drain
588 #[stable(feature = "rust1", since = "1.0.0")]
589 pub fn truncate(&mut self, len: usize) {
591 // drop any extra elements
592 while len < self.len {
593 // decrement len before the drop_in_place(), so a panic on Drop
594 // doesn't re-drop the just-failed value.
597 ptr::drop_in_place(self.get_unchecked_mut(len));
602 /// Extracts a slice containing the entire vector.
604 /// Equivalent to `&s[..]`.
609 /// use std::io::{self, Write};
610 /// let buffer = vec![1, 2, 3, 5, 8];
611 /// io::sink().write(buffer.as_slice()).unwrap();
614 #[stable(feature = "vec_as_slice", since = "1.7.0")]
615 pub fn as_slice(&self) -> &[T] {
619 /// Extracts a mutable slice of the entire vector.
621 /// Equivalent to `&mut s[..]`.
626 /// use std::io::{self, Read};
627 /// let mut buffer = vec![0; 3];
628 /// io::repeat(0b101).read_exact(buffer.as_mut_slice()).unwrap();
631 #[stable(feature = "vec_as_slice", since = "1.7.0")]
632 pub fn as_mut_slice(&mut self) -> &mut [T] {
636 /// Sets the length of a vector.
638 /// This will explicitly set the size of the vector, without actually
639 /// modifying its buffers, so it is up to the caller to ensure that the
640 /// vector is actually the specified size.
647 /// let mut vec = vec!['r', 'u', 's', 't'];
650 /// ptr::drop_in_place(&mut vec[3]);
653 /// assert_eq!(vec, ['r', 'u', 's']);
656 /// In this example, there is a memory leak since the memory locations
657 /// owned by the inner vectors were not freed prior to the `set_len` call:
660 /// let mut vec = vec![vec![1, 0, 0],
668 /// In this example, the vector gets expanded from zero to four items
669 /// without any memory allocations occurring, resulting in vector
670 /// values of unallocated memory:
673 /// let mut vec: Vec<char> = Vec::new();
680 #[stable(feature = "rust1", since = "1.0.0")]
681 pub unsafe fn set_len(&mut self, len: usize) {
685 /// Removes an element from the vector and returns it.
687 /// The removed element is replaced by the last element of the vector.
689 /// This does not preserve ordering, but is O(1).
693 /// Panics if `index` is out of bounds.
698 /// let mut v = vec!["foo", "bar", "baz", "qux"];
700 /// assert_eq!(v.swap_remove(1), "bar");
701 /// assert_eq!(v, ["foo", "qux", "baz"]);
703 /// assert_eq!(v.swap_remove(0), "foo");
704 /// assert_eq!(v, ["baz", "qux"]);
707 #[stable(feature = "rust1", since = "1.0.0")]
708 pub fn swap_remove(&mut self, index: usize) -> T {
709 let length = self.len();
710 self.swap(index, length - 1);
714 /// Inserts an element at position `index` within the vector, shifting all
715 /// elements after it to the right.
719 /// Panics if `index` is out of bounds.
724 /// let mut vec = vec![1, 2, 3];
725 /// vec.insert(1, 4);
726 /// assert_eq!(vec, [1, 4, 2, 3]);
727 /// vec.insert(4, 5);
728 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
730 #[stable(feature = "rust1", since = "1.0.0")]
731 pub fn insert(&mut self, index: usize, element: T) {
732 let len = self.len();
733 assert!(index <= len);
735 // space for the new element
736 if len == self.buf.cap() {
742 // The spot to put the new value
744 let p = self.as_mut_ptr().offset(index as isize);
745 // Shift everything over to make space. (Duplicating the
746 // `index`th element into two consecutive places.)
747 ptr::copy(p, p.offset(1), len - index);
748 // Write it in, overwriting the first copy of the `index`th
750 ptr::write(p, element);
752 self.set_len(len + 1);
756 /// Removes and returns the element at position `index` within the vector,
757 /// shifting all elements after it to the left.
761 /// Panics if `index` is out of bounds.
766 /// let mut v = vec![1, 2, 3];
767 /// assert_eq!(v.remove(1), 2);
768 /// assert_eq!(v, [1, 3]);
770 #[stable(feature = "rust1", since = "1.0.0")]
771 pub fn remove(&mut self, index: usize) -> T {
772 let len = self.len();
773 assert!(index < len);
778 // the place we are taking from.
779 let ptr = self.as_mut_ptr().offset(index as isize);
780 // copy it out, unsafely having a copy of the value on
781 // the stack and in the vector at the same time.
782 ret = ptr::read(ptr);
784 // Shift everything down to fill in that spot.
785 ptr::copy(ptr.offset(1), ptr, len - index - 1);
787 self.set_len(len - 1);
792 /// Retains only the elements specified by the predicate.
794 /// In other words, remove all elements `e` such that `f(&e)` returns `false`.
795 /// This method operates in place and preserves the order of the retained
801 /// let mut vec = vec![1, 2, 3, 4];
802 /// vec.retain(|&x| x%2 == 0);
803 /// assert_eq!(vec, [2, 4]);
805 #[stable(feature = "rust1", since = "1.0.0")]
806 pub fn retain<F>(&mut self, mut f: F)
807 where F: FnMut(&T) -> bool
809 let len = self.len();
823 self.truncate(len - del);
827 /// Removes consecutive elements in the vector that resolve to the same key.
829 /// If the vector is sorted, this removes all duplicates.
834 /// let mut vec = vec![10, 20, 21, 30, 20];
836 /// vec.dedup_by_key(|i| *i / 10);
838 /// assert_eq!(vec, [10, 20, 30, 20]);
840 #[stable(feature = "dedup_by", since = "1.16.0")]
842 pub fn dedup_by_key<F, K>(&mut self, mut key: F) where F: FnMut(&mut T) -> K, K: PartialEq {
843 self.dedup_by(|a, b| key(a) == key(b))
846 /// Removes consecutive elements in the vector according to a predicate.
848 /// The `same_bucket` function is passed references to two elements from the vector, and
849 /// returns `true` if the elements compare equal, or `false` if they do not. Only the first
850 /// of adjacent equal items is kept.
852 /// If the vector is sorted, this removes all duplicates.
857 /// use std::ascii::AsciiExt;
859 /// let mut vec = vec!["foo", "bar", "Bar", "baz", "bar"];
861 /// vec.dedup_by(|a, b| a.eq_ignore_ascii_case(b));
863 /// assert_eq!(vec, ["foo", "bar", "baz", "bar"]);
865 #[stable(feature = "dedup_by", since = "1.16.0")]
866 pub fn dedup_by<F>(&mut self, mut same_bucket: F) where F: FnMut(&mut T, &mut T) -> bool {
868 // Although we have a mutable reference to `self`, we cannot make
869 // *arbitrary* changes. The `same_bucket` calls could panic, so we
870 // must ensure that the vector is in a valid state at all time.
872 // The way that we handle this is by using swaps; we iterate
873 // over all the elements, swapping as we go so that at the end
874 // the elements we wish to keep are in the front, and those we
875 // wish to reject are at the back. We can then truncate the
876 // vector. This operation is still O(n).
878 // Example: We start in this state, where `r` represents "next
879 // read" and `w` represents "next_write`.
882 // +---+---+---+---+---+---+
883 // | 0 | 1 | 1 | 2 | 3 | 3 |
884 // +---+---+---+---+---+---+
887 // Comparing self[r] against self[w-1], this is not a duplicate, so
888 // we swap self[r] and self[w] (no effect as r==w) and then increment both
889 // r and w, leaving us with:
892 // +---+---+---+---+---+---+
893 // | 0 | 1 | 1 | 2 | 3 | 3 |
894 // +---+---+---+---+---+---+
897 // Comparing self[r] against self[w-1], this value is a duplicate,
898 // so we increment `r` but leave everything else unchanged:
901 // +---+---+---+---+---+---+
902 // | 0 | 1 | 1 | 2 | 3 | 3 |
903 // +---+---+---+---+---+---+
906 // Comparing self[r] against self[w-1], this is not a duplicate,
907 // so swap self[r] and self[w] and advance r and w:
910 // +---+---+---+---+---+---+
911 // | 0 | 1 | 2 | 1 | 3 | 3 |
912 // +---+---+---+---+---+---+
915 // Not a duplicate, repeat:
918 // +---+---+---+---+---+---+
919 // | 0 | 1 | 2 | 3 | 1 | 3 |
920 // +---+---+---+---+---+---+
923 // Duplicate, advance r. End of vec. Truncate to w.
930 // Avoid bounds checks by using raw pointers.
931 let p = self.as_mut_ptr();
932 let mut r: usize = 1;
933 let mut w: usize = 1;
936 let p_r = p.offset(r as isize);
937 let p_wm1 = p.offset((w - 1) as isize);
938 if !same_bucket(&mut *p_r, &mut *p_wm1) {
940 let p_w = p_wm1.offset(1);
941 mem::swap(&mut *p_r, &mut *p_w);
952 /// Appends an element to the back of a collection.
956 /// Panics if the number of elements in the vector overflows a `usize`.
961 /// let mut vec = vec![1, 2];
963 /// assert_eq!(vec, [1, 2, 3]);
966 #[stable(feature = "rust1", since = "1.0.0")]
967 pub fn push(&mut self, value: T) {
968 // This will panic or abort if we would allocate > isize::MAX bytes
969 // or if the length increment would overflow for zero-sized types.
970 if self.len == self.buf.cap() {
974 let end = self.as_mut_ptr().offset(self.len as isize);
975 ptr::write(end, value);
980 /// Returns a place for insertion at the back of the `Vec`.
982 /// Using this method with placement syntax is equivalent to [`push`](#method.push),
983 /// but may be more efficient.
988 /// #![feature(collection_placement)]
989 /// #![feature(placement_in_syntax)]
991 /// let mut vec = vec![1, 2];
992 /// vec.place_back() <- 3;
993 /// vec.place_back() <- 4;
994 /// assert_eq!(&vec, &[1, 2, 3, 4]);
996 #[unstable(feature = "collection_placement",
997 reason = "placement protocol is subject to change",
999 pub fn place_back(&mut self) -> PlaceBack<T> {
1000 PlaceBack { vec: self }
1003 /// Removes the last element from a vector and returns it, or [`None`] if it
1006 /// [`None`]: ../../std/option/enum.Option.html#variant.None
1011 /// let mut vec = vec![1, 2, 3];
1012 /// assert_eq!(vec.pop(), Some(3));
1013 /// assert_eq!(vec, [1, 2]);
1016 #[stable(feature = "rust1", since = "1.0.0")]
1017 pub fn pop(&mut self) -> Option<T> {
1023 Some(ptr::read(self.get_unchecked(self.len())))
1028 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
1032 /// Panics if the number of elements in the vector overflows a `usize`.
1037 /// let mut vec = vec![1, 2, 3];
1038 /// let mut vec2 = vec![4, 5, 6];
1039 /// vec.append(&mut vec2);
1040 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
1041 /// assert_eq!(vec2, []);
1044 #[stable(feature = "append", since = "1.4.0")]
1045 pub fn append(&mut self, other: &mut Self) {
1047 self.append_elements(other.as_slice() as _);
1052 /// Appends elements to `Self` from other buffer.
1054 unsafe fn append_elements(&mut self, other: *const [T]) {
1055 let count = (*other).len();
1056 self.reserve(count);
1057 let len = self.len();
1058 ptr::copy_nonoverlapping(other as *const T, self.get_unchecked_mut(len), count);
1062 /// Creates a draining iterator that removes the specified range in the vector
1063 /// and yields the removed items.
1065 /// Note 1: The element range is removed even if the iterator is only
1066 /// partially consumed or not consumed at all.
1068 /// Note 2: It is unspecified how many elements are removed from the vector
1069 /// if the `Drain` value is leaked.
1073 /// Panics if the starting point is greater than the end point or if
1074 /// the end point is greater than the length of the vector.
1079 /// let mut v = vec![1, 2, 3];
1080 /// let u: Vec<_> = v.drain(1..).collect();
1081 /// assert_eq!(v, &[1]);
1082 /// assert_eq!(u, &[2, 3]);
1084 /// // A full range clears the vector
1086 /// assert_eq!(v, &[]);
1088 #[stable(feature = "drain", since = "1.6.0")]
1089 pub fn drain<R>(&mut self, range: R) -> Drain<T>
1090 where R: RangeArgument<usize>
1094 // When the Drain is first created, it shortens the length of
1095 // the source vector to make sure no uninitalized or moved-from elements
1096 // are accessible at all if the Drain's destructor never gets to run.
1098 // Drain will ptr::read out the values to remove.
1099 // When finished, remaining tail of the vec is copied back to cover
1100 // the hole, and the vector length is restored to the new length.
1102 let len = self.len();
1103 let start = match range.start() {
1105 Excluded(&n) => n + 1,
1108 let end = match range.end() {
1109 Included(&n) => n + 1,
1113 assert!(start <= end);
1114 assert!(end <= len);
1117 // set self.vec length's to start, to be safe in case Drain is leaked
1118 self.set_len(start);
1119 // Use the borrow in the IterMut to indicate borrowing behavior of the
1120 // whole Drain iterator (like &mut T).
1121 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
1125 tail_len: len - end,
1126 iter: range_slice.iter(),
1127 vec: Shared::new(self as *mut _),
1132 /// Clears the vector, removing all values.
1134 /// Note that this method has no effect on the allocated capacity
1140 /// let mut v = vec![1, 2, 3];
1144 /// assert!(v.is_empty());
1147 #[stable(feature = "rust1", since = "1.0.0")]
1148 pub fn clear(&mut self) {
1152 /// Returns the number of elements in the vector, also referred to
1153 /// as its 'length'.
1158 /// let a = vec![1, 2, 3];
1159 /// assert_eq!(a.len(), 3);
1162 #[stable(feature = "rust1", since = "1.0.0")]
1163 pub fn len(&self) -> usize {
1167 /// Returns `true` if the vector contains no elements.
1172 /// let mut v = Vec::new();
1173 /// assert!(v.is_empty());
1176 /// assert!(!v.is_empty());
1178 #[stable(feature = "rust1", since = "1.0.0")]
1179 pub fn is_empty(&self) -> bool {
1183 /// Splits the collection into two at the given index.
1185 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1186 /// and the returned `Self` contains elements `[at, len)`.
1188 /// Note that the capacity of `self` does not change.
1192 /// Panics if `at > len`.
1197 /// let mut vec = vec![1,2,3];
1198 /// let vec2 = vec.split_off(1);
1199 /// assert_eq!(vec, [1]);
1200 /// assert_eq!(vec2, [2, 3]);
1203 #[stable(feature = "split_off", since = "1.4.0")]
1204 pub fn split_off(&mut self, at: usize) -> Self {
1205 assert!(at <= self.len(), "`at` out of bounds");
1207 let other_len = self.len - at;
1208 let mut other = Vec::with_capacity(other_len);
1210 // Unsafely `set_len` and copy items to `other`.
1213 other.set_len(other_len);
1215 ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
1223 impl<T: Clone> Vec<T> {
1224 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1226 /// If `new_len` is greater than `len()`, the `Vec` is extended by the
1227 /// difference, with each additional slot filled with `value`.
1228 /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
1233 /// let mut vec = vec!["hello"];
1234 /// vec.resize(3, "world");
1235 /// assert_eq!(vec, ["hello", "world", "world"]);
1237 /// let mut vec = vec![1, 2, 3, 4];
1238 /// vec.resize(2, 0);
1239 /// assert_eq!(vec, [1, 2]);
1241 #[stable(feature = "vec_resize", since = "1.5.0")]
1242 pub fn resize(&mut self, new_len: usize, value: T) {
1243 let len = self.len();
1246 self.extend_with_element(new_len - len, value);
1248 self.truncate(new_len);
1252 /// Extend the vector by `n` additional clones of `value`.
1253 fn extend_with_element(&mut self, n: usize, value: T) {
1257 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1258 // Use SetLenOnDrop to work around bug where compiler
1259 // may not realize the store through `ptr` through self.set_len()
1261 let mut local_len = SetLenOnDrop::new(&mut self.len);
1263 // Write all elements except the last one
1265 ptr::write(ptr, value.clone());
1266 ptr = ptr.offset(1);
1267 // Increment the length in every step in case clone() panics
1268 local_len.increment_len(1);
1272 // We can write the last element directly without cloning needlessly
1273 ptr::write(ptr, value);
1274 local_len.increment_len(1);
1277 // len set by scope guard
1281 /// Clones and appends all elements in a slice to the `Vec`.
1283 /// Iterates over the slice `other`, clones each element, and then appends
1284 /// it to this `Vec`. The `other` vector is traversed in-order.
1286 /// Note that this function is same as `extend` except that it is
1287 /// specialized to work with slices instead. If and when Rust gets
1288 /// specialization this function will likely be deprecated (but still
1294 /// let mut vec = vec![1];
1295 /// vec.extend_from_slice(&[2, 3, 4]);
1296 /// assert_eq!(vec, [1, 2, 3, 4]);
1298 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
1299 pub fn extend_from_slice(&mut self, other: &[T]) {
1300 self.spec_extend(other.iter())
1304 // Set the length of the vec when the `SetLenOnDrop` value goes out of scope.
1306 // The idea is: The length field in SetLenOnDrop is a local variable
1307 // that the optimizer will see does not alias with any stores through the Vec's data
1308 // pointer. This is a workaround for alias analysis issue #32155
1309 struct SetLenOnDrop<'a> {
1314 impl<'a> SetLenOnDrop<'a> {
1316 fn new(len: &'a mut usize) -> Self {
1317 SetLenOnDrop { local_len: *len, len: len }
1321 fn increment_len(&mut self, increment: usize) {
1322 self.local_len += increment;
1326 impl<'a> Drop for SetLenOnDrop<'a> {
1328 fn drop(&mut self) {
1329 *self.len = self.local_len;
1333 impl<T: PartialEq> Vec<T> {
1334 /// Removes consecutive repeated elements in the vector.
1336 /// If the vector is sorted, this removes all duplicates.
1341 /// let mut vec = vec![1, 2, 2, 3, 2];
1345 /// assert_eq!(vec, [1, 2, 3, 2]);
1347 #[stable(feature = "rust1", since = "1.0.0")]
1349 pub fn dedup(&mut self) {
1350 self.dedup_by(|a, b| a == b)
1353 /// Removes the first instance of `item` from the vector if the item exists.
1358 /// # #![feature(vec_remove_item)]
1359 /// let mut vec = vec![1, 2, 3, 1];
1361 /// vec.remove_item(&1);
1363 /// assert_eq!(vec, vec![2, 3, 1]);
1365 #[unstable(feature = "vec_remove_item", reason = "recently added", issue = "40062")]
1366 pub fn remove_item(&mut self, item: &T) -> Option<T> {
1367 let pos = match self.iter().position(|x| *x == *item) {
1369 None => return None,
1371 Some(self.remove(pos))
1375 ////////////////////////////////////////////////////////////////////////////////
1376 // Internal methods and functions
1377 ////////////////////////////////////////////////////////////////////////////////
1380 #[stable(feature = "rust1", since = "1.0.0")]
1381 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1382 <T as SpecFromElem>::from_elem(elem, n)
1385 // Specialization trait used for Vec::from_elem
1386 trait SpecFromElem: Sized {
1387 fn from_elem(elem: Self, n: usize) -> Vec<Self>;
1390 impl<T: Clone> SpecFromElem for T {
1391 default fn from_elem(elem: Self, n: usize) -> Vec<Self> {
1392 let mut v = Vec::with_capacity(n);
1393 v.extend_with_element(n, elem);
1398 impl SpecFromElem for u8 {
1400 fn from_elem(elem: u8, n: usize) -> Vec<u8> {
1403 buf: RawVec::with_capacity_zeroed(n),
1408 let mut v = Vec::with_capacity(n);
1409 ptr::write_bytes(v.as_mut_ptr(), elem, n);
1416 macro_rules! impl_spec_from_elem {
1417 ($t: ty, $is_zero: expr) => {
1418 impl SpecFromElem for $t {
1420 fn from_elem(elem: $t, n: usize) -> Vec<$t> {
1423 buf: RawVec::with_capacity_zeroed(n),
1427 let mut v = Vec::with_capacity(n);
1428 v.extend_with_element(n, elem);
1435 impl_spec_from_elem!(i8, |x| x == 0);
1436 impl_spec_from_elem!(i16, |x| x == 0);
1437 impl_spec_from_elem!(i32, |x| x == 0);
1438 impl_spec_from_elem!(i64, |x| x == 0);
1439 impl_spec_from_elem!(i128, |x| x == 0);
1440 impl_spec_from_elem!(isize, |x| x == 0);
1442 impl_spec_from_elem!(u16, |x| x == 0);
1443 impl_spec_from_elem!(u32, |x| x == 0);
1444 impl_spec_from_elem!(u64, |x| x == 0);
1445 impl_spec_from_elem!(u128, |x| x == 0);
1446 impl_spec_from_elem!(usize, |x| x == 0);
1448 impl_spec_from_elem!(f32, |x: f32| x == 0. && x.is_sign_positive());
1449 impl_spec_from_elem!(f64, |x: f64| x == 0. && x.is_sign_positive());
1451 ////////////////////////////////////////////////////////////////////////////////
1452 // Common trait implementations for Vec
1453 ////////////////////////////////////////////////////////////////////////////////
1455 #[stable(feature = "rust1", since = "1.0.0")]
1456 impl<T: Clone> Clone for Vec<T> {
1458 fn clone(&self) -> Vec<T> {
1459 <[T]>::to_vec(&**self)
1462 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1463 // required for this method definition, is not available. Instead use the
1464 // `slice::to_vec` function which is only available with cfg(test)
1465 // NB see the slice::hack module in slice.rs for more information
1467 fn clone(&self) -> Vec<T> {
1468 ::slice::to_vec(&**self)
1471 fn clone_from(&mut self, other: &Vec<T>) {
1472 other.as_slice().clone_into(self);
1476 #[stable(feature = "rust1", since = "1.0.0")]
1477 impl<T: Hash> Hash for Vec<T> {
1479 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1480 Hash::hash(&**self, state)
1484 #[stable(feature = "rust1", since = "1.0.0")]
1485 impl<T> Index<usize> for Vec<T> {
1489 fn index(&self, index: usize) -> &T {
1490 // NB built-in indexing via `&[T]`
1495 #[stable(feature = "rust1", since = "1.0.0")]
1496 impl<T> IndexMut<usize> for Vec<T> {
1498 fn index_mut(&mut self, index: usize) -> &mut T {
1499 // NB built-in indexing via `&mut [T]`
1500 &mut (**self)[index]
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1510 fn index(&self, index: ops::Range<usize>) -> &[T] {
1511 Index::index(&**self, index)
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1519 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1520 Index::index(&**self, index)
1523 #[stable(feature = "rust1", since = "1.0.0")]
1524 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1528 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1529 Index::index(&**self, index)
1532 #[stable(feature = "rust1", since = "1.0.0")]
1533 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1537 fn index(&self, _index: ops::RangeFull) -> &[T] {
1541 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1542 impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> {
1546 fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
1547 Index::index(&**self, index)
1550 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1551 impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> {
1555 fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
1556 Index::index(&**self, index)
1560 #[stable(feature = "rust1", since = "1.0.0")]
1561 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1563 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1564 IndexMut::index_mut(&mut **self, index)
1567 #[stable(feature = "rust1", since = "1.0.0")]
1568 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1570 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1571 IndexMut::index_mut(&mut **self, index)
1574 #[stable(feature = "rust1", since = "1.0.0")]
1575 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1577 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1578 IndexMut::index_mut(&mut **self, index)
1581 #[stable(feature = "rust1", since = "1.0.0")]
1582 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1584 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1588 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1589 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> {
1591 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
1592 IndexMut::index_mut(&mut **self, index)
1595 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1596 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> {
1598 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
1599 IndexMut::index_mut(&mut **self, index)
1603 #[stable(feature = "rust1", since = "1.0.0")]
1604 impl<T> ops::Deref for Vec<T> {
1607 fn deref(&self) -> &[T] {
1609 let p = self.buf.ptr();
1610 assume(!p.is_null());
1611 slice::from_raw_parts(p, self.len)
1616 #[stable(feature = "rust1", since = "1.0.0")]
1617 impl<T> ops::DerefMut for Vec<T> {
1618 fn deref_mut(&mut self) -> &mut [T] {
1620 let ptr = self.buf.ptr();
1621 assume(!ptr.is_null());
1622 slice::from_raw_parts_mut(ptr, self.len)
1627 #[stable(feature = "rust1", since = "1.0.0")]
1628 impl<T> FromIterator<T> for Vec<T> {
1630 fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Vec<T> {
1631 <Self as SpecExtend<T, I::IntoIter>>::from_iter(iter.into_iter())
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 impl<T> IntoIterator for Vec<T> {
1638 type IntoIter = IntoIter<T>;
1640 /// Creates a consuming iterator, that is, one that moves each value out of
1641 /// the vector (from start to end). The vector cannot be used after calling
1647 /// let v = vec!["a".to_string(), "b".to_string()];
1648 /// for s in v.into_iter() {
1649 /// // s has type String, not &String
1650 /// println!("{}", s);
1654 fn into_iter(mut self) -> IntoIter<T> {
1656 let begin = self.as_mut_ptr();
1657 assume(!begin.is_null());
1658 let end = if mem::size_of::<T>() == 0 {
1659 arith_offset(begin as *const i8, self.len() as isize) as *const T
1661 begin.offset(self.len() as isize) as *const T
1663 let cap = self.buf.cap();
1666 buf: Shared::new(begin),
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 impl<'a, T> IntoIterator for &'a Vec<T> {
1678 type IntoIter = slice::Iter<'a, T>;
1680 fn into_iter(self) -> slice::Iter<'a, T> {
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1687 type Item = &'a mut T;
1688 type IntoIter = slice::IterMut<'a, T>;
1690 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<T> Extend<T> for Vec<T> {
1698 fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
1699 <Self as SpecExtend<T, I::IntoIter>>::spec_extend(self, iter.into_iter())
1703 // Specialization trait used for Vec::from_iter and Vec::extend
1704 trait SpecExtend<T, I> {
1705 fn from_iter(iter: I) -> Self;
1706 fn spec_extend(&mut self, iter: I);
1709 impl<T, I> SpecExtend<T, I> for Vec<T>
1710 where I: Iterator<Item=T>,
1712 default fn from_iter(mut iterator: I) -> Self {
1713 // Unroll the first iteration, as the vector is going to be
1714 // expanded on this iteration in every case when the iterable is not
1715 // empty, but the loop in extend_desugared() is not going to see the
1716 // vector being full in the few subsequent loop iterations.
1717 // So we get better branch prediction.
1718 let mut vector = match iterator.next() {
1719 None => return Vec::new(),
1721 let (lower, _) = iterator.size_hint();
1722 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1724 ptr::write(vector.get_unchecked_mut(0), element);
1730 <Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1734 default fn spec_extend(&mut self, iter: I) {
1735 self.extend_desugared(iter)
1739 impl<T, I> SpecExtend<T, I> for Vec<T>
1740 where I: TrustedLen<Item=T>,
1742 default fn from_iter(iterator: I) -> Self {
1743 let mut vector = Vec::new();
1744 vector.spec_extend(iterator);
1748 default fn spec_extend(&mut self, iterator: I) {
1749 // This is the case for a TrustedLen iterator.
1750 let (low, high) = iterator.size_hint();
1751 if let Some(high_value) = high {
1752 debug_assert_eq!(low, high_value,
1753 "TrustedLen iterator's size hint is not exact: {:?}",
1756 if let Some(additional) = high {
1757 self.reserve(additional);
1759 let mut ptr = self.as_mut_ptr().offset(self.len() as isize);
1760 let mut local_len = SetLenOnDrop::new(&mut self.len);
1761 for element in iterator {
1762 ptr::write(ptr, element);
1763 ptr = ptr.offset(1);
1764 // NB can't overflow since we would have had to alloc the address space
1765 local_len.increment_len(1);
1769 self.extend_desugared(iterator)
1774 impl<T> SpecExtend<T, IntoIter<T>> for Vec<T> {
1775 fn from_iter(iterator: IntoIter<T>) -> Self {
1776 // A common case is passing a vector into a function which immediately
1777 // re-collects into a vector. We can short circuit this if the IntoIter
1778 // has not been advanced at all.
1779 if *iterator.buf == iterator.ptr as *mut T {
1781 let vec = Vec::from_raw_parts(*iterator.buf as *mut T,
1784 mem::forget(iterator);
1788 let mut vector = Vec::new();
1789 vector.spec_extend(iterator);
1794 fn spec_extend(&mut self, mut iterator: IntoIter<T>) {
1796 self.append_elements(iterator.as_slice() as _);
1798 iterator.ptr = iterator.end;
1802 impl<'a, T: 'a, I> SpecExtend<&'a T, I> for Vec<T>
1803 where I: Iterator<Item=&'a T>,
1806 default fn from_iter(iterator: I) -> Self {
1807 SpecExtend::from_iter(iterator.cloned())
1810 default fn spec_extend(&mut self, iterator: I) {
1811 self.spec_extend(iterator.cloned())
1815 impl<'a, T: 'a> SpecExtend<&'a T, slice::Iter<'a, T>> for Vec<T>
1818 fn spec_extend(&mut self, iterator: slice::Iter<'a, T>) {
1819 let slice = iterator.as_slice();
1820 self.reserve(slice.len());
1822 let len = self.len();
1823 self.set_len(len + slice.len());
1824 self.get_unchecked_mut(len..).copy_from_slice(slice);
1830 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1831 // This is the case for a general iterator.
1833 // This function should be the moral equivalent of:
1835 // for item in iterator {
1838 while let Some(element) = iterator.next() {
1839 let len = self.len();
1840 if len == self.capacity() {
1841 let (lower, _) = iterator.size_hint();
1842 self.reserve(lower.saturating_add(1));
1845 ptr::write(self.get_unchecked_mut(len), element);
1846 // NB can't overflow since we would have had to alloc the address space
1847 self.set_len(len + 1);
1852 /// Creates a splicing iterator that replaces the specified range in the vector
1853 /// with the given `replace_with` iterator and yields the removed items.
1854 /// `replace_with` does not need to be the same length as `range`.
1856 /// Note 1: The element range is removed even if the iterator is not
1857 /// consumed until the end.
1859 /// Note 2: It is unspecified how many elements are removed from the vector,
1860 /// if the `Splice` value is leaked.
1862 /// Note 3: The input iterator `replace_with` is only consumed
1863 /// when the `Splice` value is dropped.
1865 /// Note 4: This is optimal if:
1867 /// * The tail (elements in the vector after `range`) is empty,
1868 /// * or `replace_with` yields fewer elements than `range`’s length
1869 /// * or the lower bound of its `size_hint()` is exact.
1871 /// Otherwise, a temporary vector is allocated and the tail is moved twice.
1875 /// Panics if the starting point is greater than the end point or if
1876 /// the end point is greater than the length of the vector.
1881 /// #![feature(splice)]
1882 /// let mut v = vec![1, 2, 3];
1883 /// let new = [7, 8];
1884 /// let u: Vec<_> = v.splice(..2, new.iter().cloned()).collect();
1885 /// assert_eq!(v, &[7, 8, 3]);
1886 /// assert_eq!(u, &[1, 2]);
1889 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
1890 pub fn splice<R, I>(&mut self, range: R, replace_with: I) -> Splice<I::IntoIter>
1891 where R: RangeArgument<usize>, I: IntoIterator<Item=T>
1894 drain: self.drain(range),
1895 replace_with: replace_with.into_iter(),
1901 #[stable(feature = "extend_ref", since = "1.2.0")]
1902 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1903 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1904 self.spec_extend(iter.into_iter())
1908 macro_rules! __impl_slice_eq1 {
1909 ($Lhs: ty, $Rhs: ty) => {
1910 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1912 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
1916 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
1918 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
1923 __impl_slice_eq1! { Vec<A>, Vec<B> }
1924 __impl_slice_eq1! { Vec<A>, &'b [B] }
1925 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1926 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1927 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1928 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1930 macro_rules! array_impls {
1933 // NOTE: some less important impls are omitted to reduce code bloat
1934 __impl_slice_eq1! { Vec<A>, [B; $N] }
1935 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1936 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1937 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1938 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1939 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1946 10 11 12 13 14 15 16 17 18 19
1947 20 21 22 23 24 25 26 27 28 29
1951 /// Implements comparison of vectors, lexicographically.
1952 #[stable(feature = "rust1", since = "1.0.0")]
1953 impl<T: PartialOrd> PartialOrd for Vec<T> {
1955 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1956 PartialOrd::partial_cmp(&**self, &**other)
1960 #[stable(feature = "rust1", since = "1.0.0")]
1961 impl<T: Eq> Eq for Vec<T> {}
1963 /// Implements ordering of vectors, lexicographically.
1964 #[stable(feature = "rust1", since = "1.0.0")]
1965 impl<T: Ord> Ord for Vec<T> {
1967 fn cmp(&self, other: &Vec<T>) -> Ordering {
1968 Ord::cmp(&**self, &**other)
1972 #[stable(feature = "rust1", since = "1.0.0")]
1973 unsafe impl<#[may_dangle] T> Drop for Vec<T> {
1974 fn drop(&mut self) {
1977 ptr::drop_in_place(&mut self[..]);
1979 // RawVec handles deallocation
1983 #[stable(feature = "rust1", since = "1.0.0")]
1984 impl<T> Default for Vec<T> {
1985 /// Creates an empty `Vec<T>`.
1986 fn default() -> Vec<T> {
1991 #[stable(feature = "rust1", since = "1.0.0")]
1992 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1993 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1994 fmt::Debug::fmt(&**self, f)
1998 #[stable(feature = "rust1", since = "1.0.0")]
1999 impl<T> AsRef<Vec<T>> for Vec<T> {
2000 fn as_ref(&self) -> &Vec<T> {
2005 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2006 impl<T> AsMut<Vec<T>> for Vec<T> {
2007 fn as_mut(&mut self) -> &mut Vec<T> {
2012 #[stable(feature = "rust1", since = "1.0.0")]
2013 impl<T> AsRef<[T]> for Vec<T> {
2014 fn as_ref(&self) -> &[T] {
2019 #[stable(feature = "vec_as_mut", since = "1.5.0")]
2020 impl<T> AsMut<[T]> for Vec<T> {
2021 fn as_mut(&mut self) -> &mut [T] {
2026 #[stable(feature = "rust1", since = "1.0.0")]
2027 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
2029 fn from(s: &'a [T]) -> Vec<T> {
2033 fn from(s: &'a [T]) -> Vec<T> {
2038 #[stable(feature = "vec_from_mut", since = "1.21.0")]
2039 impl<'a, T: Clone> From<&'a mut [T]> for Vec<T> {
2041 fn from(s: &'a mut [T]) -> Vec<T> {
2045 fn from(s: &'a mut [T]) -> Vec<T> {
2050 #[stable(feature = "vec_from_cow_slice", since = "1.14.0")]
2051 impl<'a, T> From<Cow<'a, [T]>> for Vec<T> where [T]: ToOwned<Owned=Vec<T>> {
2052 fn from(s: Cow<'a, [T]>) -> Vec<T> {
2057 // note: test pulls in libstd, which causes errors here
2059 #[stable(feature = "vec_from_box", since = "1.17.0")]
2060 impl<T> From<Box<[T]>> for Vec<T> {
2061 fn from(s: Box<[T]>) -> Vec<T> {
2066 #[stable(feature = "box_from_vec", since = "1.17.0")]
2067 impl<T> Into<Box<[T]>> for Vec<T> {
2068 fn into(self) -> Box<[T]> {
2069 self.into_boxed_slice()
2073 #[stable(feature = "rust1", since = "1.0.0")]
2074 impl<'a> From<&'a str> for Vec<u8> {
2075 fn from(s: &'a str) -> Vec<u8> {
2076 From::from(s.as_bytes())
2080 ////////////////////////////////////////////////////////////////////////////////
2082 ////////////////////////////////////////////////////////////////////////////////
2084 #[stable(feature = "cow_from_vec", since = "1.7.0")]
2085 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
2086 fn from(s: &'a [T]) -> Cow<'a, [T]> {
2091 #[stable(feature = "cow_from_vec", since = "1.7.0")]
2092 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
2093 fn from(v: Vec<T>) -> Cow<'a, [T]> {
2098 #[stable(feature = "rust1", since = "1.0.0")]
2099 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
2100 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
2101 Cow::Owned(FromIterator::from_iter(it))
2105 ////////////////////////////////////////////////////////////////////////////////
2107 ////////////////////////////////////////////////////////////////////////////////
2109 /// An iterator that moves out of a vector.
2111 /// This `struct` is created by the `into_iter` method on [`Vec`][`Vec`] (provided
2112 /// by the [`IntoIterator`] trait).
2114 /// [`Vec`]: struct.Vec.html
2115 /// [`IntoIterator`]: ../../std/iter/trait.IntoIterator.html
2116 #[stable(feature = "rust1", since = "1.0.0")]
2117 pub struct IntoIter<T> {
2124 #[stable(feature = "vec_intoiter_debug", since = "1.13.0")]
2125 impl<T: fmt::Debug> fmt::Debug for IntoIter<T> {
2126 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2127 f.debug_tuple("IntoIter")
2128 .field(&self.as_slice())
2133 impl<T> IntoIter<T> {
2134 /// Returns the remaining items of this iterator as a slice.
2139 /// let vec = vec!['a', 'b', 'c'];
2140 /// let mut into_iter = vec.into_iter();
2141 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2142 /// let _ = into_iter.next().unwrap();
2143 /// assert_eq!(into_iter.as_slice(), &['b', 'c']);
2145 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2146 pub fn as_slice(&self) -> &[T] {
2148 slice::from_raw_parts(self.ptr, self.len())
2152 /// Returns the remaining items of this iterator as a mutable slice.
2157 /// let vec = vec!['a', 'b', 'c'];
2158 /// let mut into_iter = vec.into_iter();
2159 /// assert_eq!(into_iter.as_slice(), &['a', 'b', 'c']);
2160 /// into_iter.as_mut_slice()[2] = 'z';
2161 /// assert_eq!(into_iter.next().unwrap(), 'a');
2162 /// assert_eq!(into_iter.next().unwrap(), 'b');
2163 /// assert_eq!(into_iter.next().unwrap(), 'z');
2165 #[stable(feature = "vec_into_iter_as_slice", since = "1.15.0")]
2166 pub fn as_mut_slice(&mut self) -> &mut [T] {
2168 slice::from_raw_parts_mut(self.ptr as *mut T, self.len())
2173 #[stable(feature = "rust1", since = "1.0.0")]
2174 unsafe impl<T: Send> Send for IntoIter<T> {}
2175 #[stable(feature = "rust1", since = "1.0.0")]
2176 unsafe impl<T: Sync> Sync for IntoIter<T> {}
2178 #[stable(feature = "rust1", since = "1.0.0")]
2179 impl<T> Iterator for IntoIter<T> {
2183 fn next(&mut self) -> Option<T> {
2185 if self.ptr as *const _ == self.end {
2188 if mem::size_of::<T>() == 0 {
2189 // purposefully don't use 'ptr.offset' because for
2190 // vectors with 0-size elements this would return the
2192 self.ptr = arith_offset(self.ptr as *const i8, 1) as *mut T;
2194 // Use a non-null pointer value
2195 Some(ptr::read(EMPTY as *mut T))
2198 self.ptr = self.ptr.offset(1);
2200 Some(ptr::read(old))
2207 fn size_hint(&self) -> (usize, Option<usize>) {
2208 let exact = match self.ptr.offset_to(self.end) {
2209 Some(x) => x as usize,
2210 None => (self.end as usize).wrapping_sub(self.ptr as usize),
2212 (exact, Some(exact))
2216 fn count(self) -> usize {
2221 #[stable(feature = "rust1", since = "1.0.0")]
2222 impl<T> DoubleEndedIterator for IntoIter<T> {
2224 fn next_back(&mut self) -> Option<T> {
2226 if self.end == self.ptr {
2229 if mem::size_of::<T>() == 0 {
2230 // See above for why 'ptr.offset' isn't used
2231 self.end = arith_offset(self.end as *const i8, -1) as *mut T;
2233 // Use a non-null pointer value
2234 Some(ptr::read(EMPTY as *mut T))
2236 self.end = self.end.offset(-1);
2238 Some(ptr::read(self.end))
2245 #[stable(feature = "rust1", since = "1.0.0")]
2246 impl<T> ExactSizeIterator for IntoIter<T> {
2247 fn is_empty(&self) -> bool {
2248 self.ptr == self.end
2252 #[unstable(feature = "fused", issue = "35602")]
2253 impl<T> FusedIterator for IntoIter<T> {}
2255 #[unstable(feature = "trusted_len", issue = "37572")]
2256 unsafe impl<T> TrustedLen for IntoIter<T> {}
2258 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
2259 impl<T: Clone> Clone for IntoIter<T> {
2260 fn clone(&self) -> IntoIter<T> {
2261 self.as_slice().to_owned().into_iter()
2265 #[stable(feature = "rust1", since = "1.0.0")]
2266 unsafe impl<#[may_dangle] T> Drop for IntoIter<T> {
2267 fn drop(&mut self) {
2268 // destroy the remaining elements
2269 for _x in self.by_ref() {}
2271 // RawVec handles deallocation
2272 let _ = unsafe { RawVec::from_raw_parts(self.buf.as_mut_ptr(), self.cap) };
2276 /// A draining iterator for `Vec<T>`.
2278 /// This `struct` is created by the [`drain`] method on [`Vec`].
2280 /// [`drain`]: struct.Vec.html#method.drain
2281 /// [`Vec`]: struct.Vec.html
2282 #[stable(feature = "drain", since = "1.6.0")]
2283 pub struct Drain<'a, T: 'a> {
2284 /// Index of tail to preserve
2288 /// Current remaining range to remove
2289 iter: slice::Iter<'a, T>,
2290 vec: Shared<Vec<T>>,
2293 #[stable(feature = "collection_debug", since = "1.17.0")]
2294 impl<'a, T: 'a + fmt::Debug> fmt::Debug for Drain<'a, T> {
2295 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2296 f.debug_tuple("Drain")
2297 .field(&self.iter.as_slice())
2302 #[stable(feature = "drain", since = "1.6.0")]
2303 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
2304 #[stable(feature = "drain", since = "1.6.0")]
2305 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
2307 #[stable(feature = "drain", since = "1.6.0")]
2308 impl<'a, T> Iterator for Drain<'a, T> {
2312 fn next(&mut self) -> Option<T> {
2313 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
2316 fn size_hint(&self) -> (usize, Option<usize>) {
2317 self.iter.size_hint()
2321 #[stable(feature = "drain", since = "1.6.0")]
2322 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
2324 fn next_back(&mut self) -> Option<T> {
2325 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
2329 #[stable(feature = "drain", since = "1.6.0")]
2330 impl<'a, T> Drop for Drain<'a, T> {
2331 fn drop(&mut self) {
2332 // exhaust self first
2333 while let Some(_) = self.next() {}
2335 if self.tail_len > 0 {
2337 let source_vec = &mut *self.vec.as_mut_ptr();
2338 // memmove back untouched tail, update to new length
2339 let start = source_vec.len();
2340 let tail = self.tail_start;
2341 let src = source_vec.as_ptr().offset(tail as isize);
2342 let dst = source_vec.as_mut_ptr().offset(start as isize);
2343 ptr::copy(src, dst, self.tail_len);
2344 source_vec.set_len(start + self.tail_len);
2351 #[stable(feature = "drain", since = "1.6.0")]
2352 impl<'a, T> ExactSizeIterator for Drain<'a, T> {
2353 fn is_empty(&self) -> bool {
2354 self.iter.is_empty()
2358 #[unstable(feature = "fused", issue = "35602")]
2359 impl<'a, T> FusedIterator for Drain<'a, T> {}
2361 /// A place for insertion at the back of a `Vec`.
2363 /// See [`Vec::place_back`](struct.Vec.html#method.place_back) for details.
2364 #[must_use = "places do nothing unless written to with `<-` syntax"]
2365 #[unstable(feature = "collection_placement",
2366 reason = "struct name and placement protocol are subject to change",
2369 pub struct PlaceBack<'a, T: 'a> {
2370 vec: &'a mut Vec<T>,
2373 #[unstable(feature = "collection_placement",
2374 reason = "placement protocol is subject to change",
2376 impl<'a, T> Placer<T> for PlaceBack<'a, T> {
2377 type Place = PlaceBack<'a, T>;
2379 fn make_place(self) -> Self {
2380 // This will panic or abort if we would allocate > isize::MAX bytes
2381 // or if the length increment would overflow for zero-sized types.
2382 if self.vec.len == self.vec.buf.cap() {
2383 self.vec.buf.double();
2389 #[unstable(feature = "collection_placement",
2390 reason = "placement protocol is subject to change",
2392 impl<'a, T> Place<T> for PlaceBack<'a, T> {
2393 fn pointer(&mut self) -> *mut T {
2394 unsafe { self.vec.as_mut_ptr().offset(self.vec.len as isize) }
2398 #[unstable(feature = "collection_placement",
2399 reason = "placement protocol is subject to change",
2401 impl<'a, T> InPlace<T> for PlaceBack<'a, T> {
2402 type Owner = &'a mut T;
2404 unsafe fn finalize(mut self) -> &'a mut T {
2405 let ptr = self.pointer();
2412 /// A splicing iterator for `Vec`.
2414 /// This struct is created by the [`splice()`] method on [`Vec`]. See its
2415 /// documentation for more.
2417 /// [`splice()`]: struct.Vec.html#method.splice
2418 /// [`Vec`]: struct.Vec.html
2420 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2421 pub struct Splice<'a, I: Iterator + 'a> {
2422 drain: Drain<'a, I::Item>,
2426 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2427 impl<'a, I: Iterator> Iterator for Splice<'a, I> {
2428 type Item = I::Item;
2430 fn next(&mut self) -> Option<Self::Item> {
2434 fn size_hint(&self) -> (usize, Option<usize>) {
2435 self.drain.size_hint()
2439 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2440 impl<'a, I: Iterator> DoubleEndedIterator for Splice<'a, I> {
2441 fn next_back(&mut self) -> Option<Self::Item> {
2442 self.drain.next_back()
2446 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2447 impl<'a, I: Iterator> ExactSizeIterator for Splice<'a, I> {}
2450 #[unstable(feature = "splice", reason = "recently added", issue = "32310")]
2451 impl<'a, I: Iterator> Drop for Splice<'a, I> {
2452 fn drop(&mut self) {
2453 // exhaust drain first
2454 while let Some(_) = self.drain.next() {}
2458 if self.drain.tail_len == 0 {
2459 let vec = &mut *self.drain.vec.as_mut_ptr();
2460 vec.extend(self.replace_with.by_ref());
2464 // First fill the range left by drain().
2465 if !self.drain.fill(&mut self.replace_with) {
2469 // There may be more elements. Use the lower bound as an estimate.
2470 // FIXME: Is the upper bound a better guess? Or something else?
2471 let (lower_bound, _upper_bound) = self.replace_with.size_hint();
2472 if lower_bound > 0 {
2473 self.drain.move_tail(lower_bound);
2474 if !self.drain.fill(&mut self.replace_with) {
2479 // Collect any remaining elements.
2480 // This is a zero-length vector which does not allocate if `lower_bound` was exact.
2481 let mut collected = self.replace_with.by_ref().collect::<Vec<I::Item>>().into_iter();
2482 // Now we have an exact count.
2483 if collected.len() > 0 {
2484 self.drain.move_tail(collected.len());
2485 let filled = self.drain.fill(&mut collected);
2486 debug_assert!(filled);
2487 debug_assert_eq!(collected.len(), 0);
2490 // Let `Drain::drop` move the tail back if necessary and restore `vec.len`.
2494 /// Private helper methods for `Splice::drop`
2495 impl<'a, T> Drain<'a, T> {
2496 /// The range from `self.vec.len` to `self.tail_start` contains elements
2497 /// that have been moved out.
2498 /// Fill that range as much as possible with new elements from the `replace_with` iterator.
2499 /// Return whether we filled the entire range. (`replace_with.next()` didn’t return `None`.)
2500 unsafe fn fill<I: Iterator<Item=T>>(&mut self, replace_with: &mut I) -> bool {
2501 let vec = &mut *self.vec.as_mut_ptr();
2502 let range_start = vec.len;
2503 let range_end = self.tail_start;
2504 let range_slice = slice::from_raw_parts_mut(
2505 vec.as_mut_ptr().offset(range_start as isize),
2506 range_end - range_start);
2508 for place in range_slice {
2509 if let Some(new_item) = replace_with.next() {
2510 ptr::write(place, new_item);
2519 /// Make room for inserting more elements before the tail.
2520 unsafe fn move_tail(&mut self, extra_capacity: usize) {
2521 let vec = &mut *self.vec.as_mut_ptr();
2522 let used_capacity = self.tail_start + self.tail_len;
2523 vec.buf.reserve(used_capacity, extra_capacity);
2525 let new_tail_start = self.tail_start + extra_capacity;
2526 let src = vec.as_ptr().offset(self.tail_start as isize);
2527 let dst = vec.as_mut_ptr().offset(new_tail_start as isize);
2528 ptr::copy(src, dst, self.tail_len);
2529 self.tail_start = new_tail_start;