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 #![stable(feature = "rust1", since = "1.0.0")]
62 use alloc::boxed::Box;
63 use alloc::heap::EMPTY;
64 use alloc::raw_vec::RawVec;
66 use core::cmp::Ordering;
68 use core::hash::{self, Hash};
69 use core::intrinsics::{arith_offset, assume, needs_drop};
70 use core::iter::FromIterator;
72 use core::ops::{Index, IndexMut};
78 use borrow::{Cow, IntoCow};
80 use super::range::RangeArgument;
82 /// A contiguous growable array type, written `Vec<T>` but pronounced 'vector.'
87 /// let mut vec = Vec::new();
91 /// assert_eq!(vec.len(), 2);
92 /// assert_eq!(vec[0], 1);
94 /// assert_eq!(vec.pop(), Some(2));
95 /// assert_eq!(vec.len(), 1);
98 /// assert_eq!(vec[0], 7);
100 /// vec.extend([1, 2, 3].iter().cloned());
103 /// println!("{}", x);
105 /// assert_eq!(vec, [7, 1, 2, 3]);
108 /// The `vec!` macro is provided to make initialization more convenient:
111 /// let mut vec = vec![1, 2, 3];
113 /// assert_eq!(vec, [1, 2, 3, 4]);
116 /// It can also initialize each element of a `Vec<T>` with a given value:
119 /// let vec = vec![0; 5];
120 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
123 /// Use a `Vec<T>` as an efficient stack:
126 /// let mut stack = Vec::new();
132 /// while let Some(top) = stack.pop() {
133 /// // Prints 3, 2, 1
134 /// println!("{}", top);
140 /// The Vec type allows to access values by index, because it implements the
141 /// `Index` trait. An example will be more explicit:
144 /// let v = vec!(0, 2, 4, 6);
145 /// println!("{}", v[1]); // it will display '2'
148 /// However be careful: if you try to access an index which isn't in the Vec,
149 /// your software will panic! You cannot do this:
152 /// let v = vec!(0, 2, 4, 6);
153 /// println!("{}", v[6]); // it will panic!
156 /// In conclusion: always check if the index you want to get really exists
161 /// A Vec can be mutable. Slices, on the other hand, are read-only objects.
162 /// To get a slice, use "&". Example:
165 /// fn read_slice(slice: &[usize]) {
169 /// let v = vec!(0, 1);
172 /// // ... and that's all!
173 /// // you can also do it like this:
174 /// let x : &[usize] = &v;
177 /// In Rust, it's more common to pass slices as arguments rather than vectors
178 /// when you just want to provide a read access. The same goes for String and
181 /// # Capacity and reallocation
183 /// The capacity of a vector is the amount of space allocated for any future
184 /// elements that will be added onto the vector. This is not to be confused with
185 /// the *length* of a vector, which specifies the number of actual elements
186 /// within the vector. If a vector's length exceeds its capacity, its capacity
187 /// will automatically be increased, but its elements will have to be
190 /// For example, a vector with capacity 10 and length 0 would be an empty vector
191 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
192 /// vector will not change its capacity or cause reallocation to occur. However,
193 /// if the vector's length is increased to 11, it will have to reallocate, which
194 /// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
195 /// whenever possible to specify how big the vector is expected to get.
199 /// Due to its incredibly fundamental nature, Vec makes a lot of guarantees
200 /// about its design. This ensures that it's as low-overhead as possible in
201 /// the general case, and can be correctly manipulated in primitive ways
202 /// by unsafe code. Note that these guarantees refer to an unqualified `Vec<T>`.
203 /// If additional type parameters are added (e.g. to support custom allocators),
204 /// overriding their defaults may change the behavior.
206 /// Most fundamentally, Vec is and always will be a (pointer, capacity, length)
207 /// triplet. No more, no less. The order of these fields is completely
208 /// unspecified, and you should use the appropriate methods to modify these.
209 /// The pointer will never be null, so this type is null-pointer-optimized.
211 /// However, the pointer may not actually point to allocated memory. In particular,
212 /// if you construct a Vec with capacity 0 via `Vec::new()`, `vec![]`,
213 /// `Vec::with_capacity(0)`, or by calling `shrink_to_fit()` on an empty Vec, it
214 /// will not allocate memory. Similarly, if you store zero-sized types inside
215 /// a Vec, it will not allocate space for them. *Note that in this case the
216 /// Vec may not report a `capacity()` of 0*. Vec will allocate if and only
217 /// if `mem::size_of::<T>() * capacity() > 0`. In general, Vec's allocation
218 /// details are subtle enough that it is strongly recommended that you only
219 /// free memory allocated by a Vec by creating a new Vec and dropping it.
221 /// If a Vec *has* allocated memory, then the memory it points to is on the heap
222 /// (as defined by the allocator Rust is configured to use by default), and its
223 /// pointer points to `len()` initialized elements in order (what you would see
224 /// if you coerced it to a slice), followed by `capacity() - len()` logically
225 /// uninitialized elements.
227 /// Vec will never perform a "small optimization" where elements are actually
228 /// stored on the stack for two reasons:
230 /// * It would make it more difficult for unsafe code to correctly manipulate
231 /// a Vec. The contents of a Vec wouldn't have a stable address if it were
232 /// only moved, and it would be more difficult to determine if a Vec had
233 /// actually allocated memory.
235 /// * It would penalize the general case, incurring an additional branch
238 /// Vec will never automatically shrink itself, even if completely empty. This
239 /// ensures no unnecessary allocations or deallocations occur. Emptying a Vec
240 /// and then filling it back up to the same `len()` should incur no calls to
241 /// the allocator. If you wish to free up unused memory, use `shrink_to_fit`.
243 /// `push` and `insert` will never (re)allocate if the reported capacity is
244 /// sufficient. `push` and `insert` *will* (re)allocate if `len() == capacity()`.
245 /// That is, the reported capacity is completely accurate, and can be relied on.
246 /// It can even be used to manually free the memory allocated by a Vec if
247 /// desired. Bulk insertion methods *may* reallocate, even when not necessary.
249 /// Vec does not guarantee any particular growth strategy when reallocating
250 /// when full, nor when `reserve` is called. The current strategy is basic
251 /// and it may prove desirable to use a non-constant growth factor. Whatever
252 /// strategy is used will of course guarantee `O(1)` amortized `push`.
254 /// `vec![x; n]`, `vec![a, b, c, d]`, and `Vec::with_capacity(n)`, will all
255 /// produce a Vec with exactly the requested capacity. If `len() == capacity()`,
256 /// (as is the case for the `vec!` macro), then a `Vec<T>` can be converted
257 /// to and from a `Box<[T]>` without reallocating or moving the elements.
259 /// Vec will not specifically overwrite any data that is removed from it,
260 /// but also won't specifically preserve it. Its uninitialized memory is
261 /// scratch space that it may use however it wants. It will generally just do
262 /// whatever is most efficient or otherwise easy to implement. Do not rely on
263 /// removed data to be erased for security purposes. Even if you drop a Vec, its
264 /// buffer may simply be reused by another Vec. Even if you zero a Vec's memory
265 /// first, that may not actually happen because the optimizer does not consider
266 /// this a side-effect that must be preserved.
268 /// Vec does not currently guarantee the order in which elements are dropped
269 /// (the order has changed in the past, and may change again).
271 #[unsafe_no_drop_flag]
272 #[stable(feature = "rust1", since = "1.0.0")]
278 ////////////////////////////////////////////////////////////////////////////////
280 ////////////////////////////////////////////////////////////////////////////////
283 /// Constructs a new, empty `Vec<T>`.
285 /// The vector will not allocate until elements are pushed onto it.
290 /// # #![allow(unused_mut)]
291 /// let mut vec: Vec<i32> = Vec::new();
294 #[stable(feature = "rust1", since = "1.0.0")]
295 pub fn new() -> Vec<T> {
302 /// Constructs a new, empty `Vec<T>` with the specified capacity.
304 /// The vector will be able to hold exactly `capacity` elements without
305 /// reallocating. If `capacity` is 0, the vector will not allocate.
307 /// It is important to note that this function does not specify the *length*
308 /// of the returned vector, but only the *capacity*. (For an explanation of
309 /// the difference between length and capacity, see the main `Vec<T>` docs
310 /// above, 'Capacity and reallocation'.)
315 /// let mut vec = Vec::with_capacity(10);
317 /// // The vector contains no items, even though it has capacity for more
318 /// assert_eq!(vec.len(), 0);
320 /// // These are all done without reallocating...
325 /// // ...but this may make the vector reallocate
329 #[stable(feature = "rust1", since = "1.0.0")]
330 pub fn with_capacity(capacity: usize) -> Vec<T> {
332 buf: RawVec::with_capacity(capacity),
337 /// Creates a `Vec<T>` directly from the raw components of another vector.
341 /// This is highly unsafe, due to the number of invariants that aren't
344 /// * `ptr` needs to have been previously allocated via `String`/`Vec<T>`
345 /// (at least, it's highly likely to be incorrect if it wasn't).
346 /// * `length` needs to be the length that less than or equal to `capacity`.
347 /// * `capacity` needs to be the capacity that the pointer was allocated with.
349 /// Violating these may cause problems like corrupting the allocator's
350 /// internal datastructures.
359 /// let mut v = vec![1, 2, 3];
361 /// // Pull out the various important pieces of information about `v`
362 /// let p = v.as_mut_ptr();
363 /// let len = v.len();
364 /// let cap = v.capacity();
367 /// // Cast `v` into the void: no destructor run, so we are in
368 /// // complete control of the allocation to which `p` points.
371 /// // Overwrite memory with 4, 5, 6
372 /// for i in 0..len as isize {
373 /// ptr::write(p.offset(i), 4 + i);
376 /// // Put everything back together into a Vec
377 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
378 /// assert_eq!(rebuilt, [4, 5, 6]);
382 #[stable(feature = "rust1", since = "1.0.0")]
383 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec<T> {
385 buf: RawVec::from_raw_parts(ptr, capacity),
390 /// Returns the number of elements the vector can hold without
396 /// let vec: Vec<i32> = Vec::with_capacity(10);
397 /// assert_eq!(vec.capacity(), 10);
400 #[stable(feature = "rust1", since = "1.0.0")]
401 pub fn capacity(&self) -> usize {
405 /// Reserves capacity for at least `additional` more elements to be inserted
406 /// in the given `Vec<T>`. The collection may reserve more space to avoid
407 /// frequent reallocations.
411 /// Panics if the new capacity overflows `usize`.
416 /// let mut vec = vec![1];
418 /// assert!(vec.capacity() >= 11);
420 #[stable(feature = "rust1", since = "1.0.0")]
421 pub fn reserve(&mut self, additional: usize) {
422 self.buf.reserve(self.len, additional);
425 /// Reserves the minimum capacity for exactly `additional` more elements to
426 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
429 /// Note that the allocator may give the collection more space than it
430 /// requests. Therefore capacity can not be relied upon to be precisely
431 /// minimal. Prefer `reserve` if future insertions are expected.
435 /// Panics if the new capacity overflows `usize`.
440 /// let mut vec = vec![1];
441 /// vec.reserve_exact(10);
442 /// assert!(vec.capacity() >= 11);
444 #[stable(feature = "rust1", since = "1.0.0")]
445 pub fn reserve_exact(&mut self, additional: usize) {
446 self.buf.reserve_exact(self.len, additional);
449 /// Shrinks the capacity of the vector as much as possible.
451 /// It will drop down as close as possible to the length but the allocator
452 /// may still inform the vector that there is space for a few more elements.
457 /// let mut vec = Vec::with_capacity(10);
458 /// vec.extend([1, 2, 3].iter().cloned());
459 /// assert_eq!(vec.capacity(), 10);
460 /// vec.shrink_to_fit();
461 /// assert!(vec.capacity() >= 3);
463 #[stable(feature = "rust1", since = "1.0.0")]
464 pub fn shrink_to_fit(&mut self) {
465 self.buf.shrink_to_fit(self.len);
468 /// Converts the vector into Box<[T]>.
470 /// Note that this will drop any excess capacity. Calling this and
471 /// converting back to a vector with `into_vec()` is equivalent to calling
472 /// `shrink_to_fit()`.
473 #[stable(feature = "rust1", since = "1.0.0")]
474 pub fn into_boxed_slice(mut self) -> Box<[T]> {
476 self.shrink_to_fit();
477 let buf = ptr::read(&self.buf);
483 /// Shorten a vector to be `len` elements long, dropping excess elements.
485 /// If `len` is greater than the vector's current length, this has no
491 /// let mut vec = vec![1, 2, 3, 4, 5];
493 /// assert_eq!(vec, [1, 2]);
495 #[stable(feature = "rust1", since = "1.0.0")]
496 pub fn truncate(&mut self, len: usize) {
498 // drop any extra elements
499 while len < self.len {
500 // decrement len before the read(), so a panic on Drop doesn't
501 // re-drop the just-failed value.
503 ptr::read(self.get_unchecked(self.len));
508 /// Extracts a slice containing the entire vector.
510 /// Equivalent to `&s[..]`.
512 #[stable(feature = "vec_as_slice", since = "1.7.0")]
513 pub fn as_slice(&self) -> &[T] {
517 /// Extracts a mutable slice of the entire vector.
519 /// Equivalent to `&mut s[..]`.
521 #[stable(feature = "vec_as_slice", since = "1.7.0")]
522 pub fn as_mut_slice(&mut self) -> &mut [T] {
526 /// Sets the length of a vector.
528 /// This will explicitly set the size of the vector, without actually
529 /// modifying its buffers, so it is up to the caller to ensure that the
530 /// vector is actually the specified size.
535 /// let mut v = vec![1, 2, 3, 4];
541 #[stable(feature = "rust1", since = "1.0.0")]
542 pub unsafe fn set_len(&mut self, len: usize) {
546 /// Removes an element from anywhere in the vector and return it, replacing
547 /// it with the last element.
549 /// This does not preserve ordering, but is O(1).
553 /// Panics if `index` is out of bounds.
558 /// let mut v = vec!["foo", "bar", "baz", "qux"];
560 /// assert_eq!(v.swap_remove(1), "bar");
561 /// assert_eq!(v, ["foo", "qux", "baz"]);
563 /// assert_eq!(v.swap_remove(0), "foo");
564 /// assert_eq!(v, ["baz", "qux"]);
567 #[stable(feature = "rust1", since = "1.0.0")]
568 pub fn swap_remove(&mut self, index: usize) -> T {
569 let length = self.len();
570 self.swap(index, length - 1);
574 /// Inserts an element at position `index` within the vector, shifting all
575 /// elements after it to the right.
579 /// Panics if `index` is greater than the vector's length.
584 /// let mut vec = vec![1, 2, 3];
585 /// vec.insert(1, 4);
586 /// assert_eq!(vec, [1, 4, 2, 3]);
587 /// vec.insert(4, 5);
588 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
590 #[stable(feature = "rust1", since = "1.0.0")]
591 pub fn insert(&mut self, index: usize, element: T) {
592 let len = self.len();
593 assert!(index <= len);
595 // space for the new element
596 if len == self.buf.cap() {
602 // The spot to put the new value
604 let p = self.as_mut_ptr().offset(index as isize);
605 // Shift everything over to make space. (Duplicating the
606 // `index`th element into two consecutive places.)
607 ptr::copy(p, p.offset(1), len - index);
608 // Write it in, overwriting the first copy of the `index`th
610 ptr::write(p, element);
612 self.set_len(len + 1);
616 /// Removes and returns the element at position `index` within the vector,
617 /// shifting all elements after it to the left.
621 /// Panics if `index` is out of bounds.
626 /// let mut v = vec![1, 2, 3];
627 /// assert_eq!(v.remove(1), 2);
628 /// assert_eq!(v, [1, 3]);
630 #[stable(feature = "rust1", since = "1.0.0")]
631 pub fn remove(&mut self, index: usize) -> T {
632 let len = self.len();
633 assert!(index < len);
638 // the place we are taking from.
639 let ptr = self.as_mut_ptr().offset(index as isize);
640 // copy it out, unsafely having a copy of the value on
641 // the stack and in the vector at the same time.
642 ret = ptr::read(ptr);
644 // Shift everything down to fill in that spot.
645 ptr::copy(ptr.offset(1), ptr, len - index - 1);
647 self.set_len(len - 1);
652 /// Retains only the elements specified by the predicate.
654 /// In other words, remove all elements `e` such that `f(&e)` returns false.
655 /// This method operates in place and preserves the order of the retained
661 /// let mut vec = vec![1, 2, 3, 4];
662 /// vec.retain(|&x| x%2 == 0);
663 /// assert_eq!(vec, [2, 4]);
665 #[stable(feature = "rust1", since = "1.0.0")]
666 pub fn retain<F>(&mut self, mut f: F)
667 where F: FnMut(&T) -> bool
669 let len = self.len();
683 self.truncate(len - del);
687 /// Appends an element to the back of a collection.
691 /// Panics if the number of elements in the vector overflows a `usize`.
696 /// let mut vec = vec![1, 2];
698 /// assert_eq!(vec, [1, 2, 3]);
701 #[stable(feature = "rust1", since = "1.0.0")]
702 pub fn push(&mut self, value: T) {
703 // This will panic or abort if we would allocate > isize::MAX bytes
704 // or if the length increment would overflow for zero-sized types.
705 if self.len == self.buf.cap() {
709 let end = self.as_mut_ptr().offset(self.len as isize);
710 ptr::write(end, value);
715 /// Removes the last element from a vector and returns it, or `None` if it
721 /// let mut vec = vec![1, 2, 3];
722 /// assert_eq!(vec.pop(), Some(3));
723 /// assert_eq!(vec, [1, 2]);
726 #[stable(feature = "rust1", since = "1.0.0")]
727 pub fn pop(&mut self) -> Option<T> {
733 Some(ptr::read(self.get_unchecked(self.len())))
738 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
742 /// Panics if the number of elements in the vector overflows a `usize`.
747 /// let mut vec = vec![1, 2, 3];
748 /// let mut vec2 = vec![4, 5, 6];
749 /// vec.append(&mut vec2);
750 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
751 /// assert_eq!(vec2, []);
754 #[stable(feature = "append", since = "1.4.0")]
755 pub fn append(&mut self, other: &mut Self) {
756 self.reserve(other.len());
757 let len = self.len();
759 ptr::copy_nonoverlapping(other.as_ptr(), self.get_unchecked_mut(len), other.len());
762 self.len += other.len();
768 /// Create a draining iterator that removes the specified range in the vector
769 /// and yields the removed items.
771 /// Note 1: The element range is removed even if the iterator is not
772 /// consumed until the end.
774 /// Note 2: It is unspecified how many elements are removed from the vector,
775 /// if the `Drain` value is leaked.
779 /// Panics if the starting point is greater than the end point or if
780 /// the end point is greater than the length of the vector.
785 /// let mut v = vec![1, 2, 3];
786 /// let u: Vec<_> = v.drain(1..).collect();
787 /// assert_eq!(v, &[1]);
788 /// assert_eq!(u, &[2, 3]);
790 /// // A full range clears the vector
792 /// assert_eq!(v, &[]);
794 #[stable(feature = "drain", since = "1.6.0")]
795 pub fn drain<R>(&mut self, range: R) -> Drain<T>
796 where R: RangeArgument<usize>
800 // When the Drain is first created, it shortens the length of
801 // the source vector to make sure no uninitalized or moved-from elements
802 // are accessible at all if the Drain's destructor never gets to run.
804 // Drain will ptr::read out the values to remove.
805 // When finished, remaining tail of the vec is copied back to cover
806 // the hole, and the vector length is restored to the new length.
808 let len = self.len();
809 let start = *range.start().unwrap_or(&0);
810 let end = *range.end().unwrap_or(&len);
811 assert!(start <= end);
815 // set self.vec length's to start, to be safe in case Drain is leaked
817 // Use the borrow in the IterMut to indicate borrowing behavior of the
818 // whole Drain iterator (like &mut T).
819 let range_slice = slice::from_raw_parts_mut(self.as_mut_ptr().offset(start as isize),
824 iter: range_slice.iter_mut(),
830 /// Clears the vector, removing all values.
835 /// let mut v = vec![1, 2, 3];
839 /// assert!(v.is_empty());
842 #[stable(feature = "rust1", since = "1.0.0")]
843 pub fn clear(&mut self) {
847 /// Returns the number of elements in the vector.
852 /// let a = vec![1, 2, 3];
853 /// assert_eq!(a.len(), 3);
856 #[stable(feature = "rust1", since = "1.0.0")]
857 pub fn len(&self) -> usize {
861 /// Returns `true` if the vector contains no elements.
866 /// let mut v = Vec::new();
867 /// assert!(v.is_empty());
870 /// assert!(!v.is_empty());
872 #[stable(feature = "rust1", since = "1.0.0")]
873 pub fn is_empty(&self) -> bool {
877 /// Splits the collection into two at the given index.
879 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
880 /// and the returned `Self` contains elements `[at, len)`.
882 /// Note that the capacity of `self` does not change.
886 /// Panics if `at > len`.
891 /// let mut vec = vec![1,2,3];
892 /// let vec2 = vec.split_off(1);
893 /// assert_eq!(vec, [1]);
894 /// assert_eq!(vec2, [2, 3]);
897 #[stable(feature = "split_off", since = "1.4.0")]
898 pub fn split_off(&mut self, at: usize) -> Self {
899 assert!(at <= self.len(), "`at` out of bounds");
901 let other_len = self.len - at;
902 let mut other = Vec::with_capacity(other_len);
904 // Unsafely `set_len` and copy items to `other`.
907 other.set_len(other_len);
909 ptr::copy_nonoverlapping(self.as_ptr().offset(at as isize),
917 impl<T: Clone> Vec<T> {
918 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
920 /// If `new_len` is greater than `len()`, the `Vec` is extended by the
921 /// difference, with each additional slot filled with `value`.
922 /// If `new_len` is less than `len()`, the `Vec` is simply truncated.
927 /// let mut vec = vec!["hello"];
928 /// vec.resize(3, "world");
929 /// assert_eq!(vec, ["hello", "world", "world"]);
931 /// let mut vec = vec![1, 2, 3, 4];
932 /// vec.resize(2, 0);
933 /// assert_eq!(vec, [1, 2]);
935 #[stable(feature = "vec_resize", since = "1.5.0")]
936 pub fn resize(&mut self, new_len: usize, value: T) {
937 let len = self.len();
940 self.extend_with_element(new_len - len, value);
942 self.truncate(new_len);
946 /// Extend the vector by `n` additional clones of `value`.
947 fn extend_with_element(&mut self, n: usize, value: T) {
951 let len = self.len();
952 let mut ptr = self.as_mut_ptr().offset(len as isize);
953 // Write all elements except the last one
955 ptr::write(ptr, value.clone());
957 // Increment the length in every step in case clone() panics
958 self.set_len(len + i);
962 // We can write the last element directly without cloning needlessly
963 ptr::write(ptr, value);
964 self.set_len(len + n);
969 #[allow(missing_docs)]
971 #[unstable(feature = "vec_push_all",
972 reason = "likely to be replaced by a more optimized extend",
974 #[rustc_deprecated(reason = "renamed to extend_from_slice",
976 pub fn push_all(&mut self, other: &[T]) {
977 self.extend_from_slice(other)
980 /// Appends all elements in a slice to the `Vec`.
982 /// Iterates over the slice `other`, clones each element, and then appends
983 /// it to this `Vec`. The `other` vector is traversed in-order.
985 /// Note that this function is same as `extend` except that it is
986 /// specialized to work with slices instead. If and when Rust gets
987 /// specialization this function will likely be deprecated (but still
993 /// let mut vec = vec![1];
994 /// vec.extend_from_slice(&[2, 3, 4]);
995 /// assert_eq!(vec, [1, 2, 3, 4]);
997 #[stable(feature = "vec_extend_from_slice", since = "1.6.0")]
998 pub fn extend_from_slice(&mut self, other: &[T]) {
999 self.reserve(other.len());
1001 for i in 0..other.len() {
1002 let len = self.len();
1004 // Unsafe code so this can be optimised to a memcpy (or something
1005 // similarly fast) when T is Copy. LLVM is easily confused, so any
1006 // extra operations during the loop can prevent this optimisation.
1008 ptr::write(self.get_unchecked_mut(len), other.get_unchecked(i).clone());
1009 self.set_len(len + 1);
1015 impl<T: PartialEq> Vec<T> {
1016 /// Removes consecutive repeated elements in the vector.
1018 /// If the vector is sorted, this removes all duplicates.
1023 /// let mut vec = vec![1, 2, 2, 3, 2];
1027 /// assert_eq!(vec, [1, 2, 3, 2]);
1029 #[stable(feature = "rust1", since = "1.0.0")]
1030 pub fn dedup(&mut self) {
1032 // Although we have a mutable reference to `self`, we cannot make
1033 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1034 // must ensure that the vector is in a valid state at all time.
1036 // The way that we handle this is by using swaps; we iterate
1037 // over all the elements, swapping as we go so that at the end
1038 // the elements we wish to keep are in the front, and those we
1039 // wish to reject are at the back. We can then truncate the
1040 // vector. This operation is still O(n).
1042 // Example: We start in this state, where `r` represents "next
1043 // read" and `w` represents "next_write`.
1046 // +---+---+---+---+---+---+
1047 // | 0 | 1 | 1 | 2 | 3 | 3 |
1048 // +---+---+---+---+---+---+
1051 // Comparing self[r] against self[w-1], this is not a duplicate, so
1052 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1053 // r and w, leaving us with:
1056 // +---+---+---+---+---+---+
1057 // | 0 | 1 | 1 | 2 | 3 | 3 |
1058 // +---+---+---+---+---+---+
1061 // Comparing self[r] against self[w-1], this value is a duplicate,
1062 // so we increment `r` but leave everything else unchanged:
1065 // +---+---+---+---+---+---+
1066 // | 0 | 1 | 1 | 2 | 3 | 3 |
1067 // +---+---+---+---+---+---+
1070 // Comparing self[r] against self[w-1], this is not a duplicate,
1071 // so swap self[r] and self[w] and advance r and w:
1074 // +---+---+---+---+---+---+
1075 // | 0 | 1 | 2 | 1 | 3 | 3 |
1076 // +---+---+---+---+---+---+
1079 // Not a duplicate, repeat:
1082 // +---+---+---+---+---+---+
1083 // | 0 | 1 | 2 | 3 | 1 | 3 |
1084 // +---+---+---+---+---+---+
1087 // Duplicate, advance r. End of vec. Truncate to w.
1089 let ln = self.len();
1094 // Avoid bounds checks by using raw pointers.
1095 let p = self.as_mut_ptr();
1096 let mut r: usize = 1;
1097 let mut w: usize = 1;
1100 let p_r = p.offset(r as isize);
1101 let p_wm1 = p.offset((w - 1) as isize);
1104 let p_w = p_wm1.offset(1);
1105 mem::swap(&mut *p_r, &mut *p_w);
1117 ////////////////////////////////////////////////////////////////////////////////
1118 // Internal methods and functions
1119 ////////////////////////////////////////////////////////////////////////////////
1122 #[stable(feature = "rust1", since = "1.0.0")]
1123 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1124 let mut v = Vec::with_capacity(n);
1125 v.extend_with_element(n, elem);
1129 ////////////////////////////////////////////////////////////////////////////////
1130 // Common trait implementations for Vec
1131 ////////////////////////////////////////////////////////////////////////////////
1133 #[stable(feature = "rust1", since = "1.0.0")]
1134 impl<T: Clone> Clone for Vec<T> {
1136 fn clone(&self) -> Vec<T> {
1137 <[T]>::to_vec(&**self)
1140 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1141 // required for this method definition, is not available. Instead use the
1142 // `slice::to_vec` function which is only available with cfg(test)
1143 // NB see the slice::hack module in slice.rs for more information
1145 fn clone(&self) -> Vec<T> {
1146 ::slice::to_vec(&**self)
1149 fn clone_from(&mut self, other: &Vec<T>) {
1150 // drop anything in self that will not be overwritten
1151 self.truncate(other.len());
1152 let len = self.len();
1154 // reuse the contained values' allocations/resources.
1155 self.clone_from_slice(&other[..len]);
1157 // self.len <= other.len due to the truncate above, so the
1158 // slice here is always in-bounds.
1159 self.extend_from_slice(&other[len..]);
1163 #[stable(feature = "rust1", since = "1.0.0")]
1164 impl<T: Hash> Hash for Vec<T> {
1166 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1167 Hash::hash(&**self, state)
1171 #[stable(feature = "rust1", since = "1.0.0")]
1172 impl<T> Index<usize> for Vec<T> {
1176 fn index(&self, index: usize) -> &T {
1177 // NB built-in indexing via `&[T]`
1182 #[stable(feature = "rust1", since = "1.0.0")]
1183 impl<T> IndexMut<usize> for Vec<T> {
1185 fn index_mut(&mut self, index: usize) -> &mut T {
1186 // NB built-in indexing via `&mut [T]`
1187 &mut (**self)[index]
1192 #[stable(feature = "rust1", since = "1.0.0")]
1193 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1197 fn index(&self, index: ops::Range<usize>) -> &[T] {
1198 Index::index(&**self, index)
1201 #[stable(feature = "rust1", since = "1.0.0")]
1202 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1206 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1207 Index::index(&**self, index)
1210 #[stable(feature = "rust1", since = "1.0.0")]
1211 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1215 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1216 Index::index(&**self, index)
1219 #[stable(feature = "rust1", since = "1.0.0")]
1220 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1224 fn index(&self, _index: ops::RangeFull) -> &[T] {
1228 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1229 impl<T> ops::Index<ops::RangeInclusive<usize>> for Vec<T> {
1233 fn index(&self, index: ops::RangeInclusive<usize>) -> &[T] {
1234 Index::index(&**self, index)
1237 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1238 impl<T> ops::Index<ops::RangeToInclusive<usize>> for Vec<T> {
1242 fn index(&self, index: ops::RangeToInclusive<usize>) -> &[T] {
1243 Index::index(&**self, index)
1247 #[stable(feature = "rust1", since = "1.0.0")]
1248 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1250 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1251 IndexMut::index_mut(&mut **self, index)
1254 #[stable(feature = "rust1", since = "1.0.0")]
1255 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1257 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1258 IndexMut::index_mut(&mut **self, index)
1261 #[stable(feature = "rust1", since = "1.0.0")]
1262 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1264 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1265 IndexMut::index_mut(&mut **self, index)
1268 #[stable(feature = "rust1", since = "1.0.0")]
1269 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1271 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1275 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1276 impl<T> ops::IndexMut<ops::RangeInclusive<usize>> for Vec<T> {
1278 fn index_mut(&mut self, index: ops::RangeInclusive<usize>) -> &mut [T] {
1279 IndexMut::index_mut(&mut **self, index)
1282 #[unstable(feature = "inclusive_range", reason = "recently added, follows RFC", issue = "28237")]
1283 impl<T> ops::IndexMut<ops::RangeToInclusive<usize>> for Vec<T> {
1285 fn index_mut(&mut self, index: ops::RangeToInclusive<usize>) -> &mut [T] {
1286 IndexMut::index_mut(&mut **self, index)
1290 #[stable(feature = "rust1", since = "1.0.0")]
1291 impl<T> ops::Deref for Vec<T> {
1294 fn deref(&self) -> &[T] {
1296 let p = self.buf.ptr();
1297 assume(!p.is_null());
1298 slice::from_raw_parts(p, self.len)
1303 #[stable(feature = "rust1", since = "1.0.0")]
1304 impl<T> ops::DerefMut for Vec<T> {
1305 fn deref_mut(&mut self) -> &mut [T] {
1307 let ptr = self.buf.ptr();
1308 assume(!ptr.is_null());
1309 slice::from_raw_parts_mut(ptr, self.len)
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 impl<T> FromIterator<T> for Vec<T> {
1317 fn from_iter<I: IntoIterator<Item = T>>(iterable: I) -> Vec<T> {
1318 // Unroll the first iteration, as the vector is going to be
1319 // expanded on this iteration in every case when the iterable is not
1320 // empty, but the loop in extend_desugared() is not going to see the
1321 // vector being full in the few subsequent loop iterations.
1322 // So we get better branch prediction.
1323 let mut iterator = iterable.into_iter();
1324 let mut vector = match iterator.next() {
1325 None => return Vec::new(),
1327 let (lower, _) = iterator.size_hint();
1328 let mut vector = Vec::with_capacity(lower.saturating_add(1));
1330 ptr::write(vector.get_unchecked_mut(0), element);
1336 vector.extend_desugared(iterator);
1341 #[stable(feature = "rust1", since = "1.0.0")]
1342 impl<T> IntoIterator for Vec<T> {
1344 type IntoIter = IntoIter<T>;
1346 /// Creates a consuming iterator, that is, one that moves each value out of
1347 /// the vector (from start to end). The vector cannot be used after calling
1353 /// let v = vec!["a".to_string(), "b".to_string()];
1354 /// for s in v.into_iter() {
1355 /// // s has type String, not &String
1356 /// println!("{}", s);
1360 fn into_iter(mut self) -> IntoIter<T> {
1362 let ptr = self.as_mut_ptr();
1363 assume(!ptr.is_null());
1364 let begin = ptr as *const T;
1365 let end = if mem::size_of::<T>() == 0 {
1366 arith_offset(ptr as *const i8, self.len() as isize) as *const T
1368 ptr.offset(self.len() as isize) as *const T
1370 let buf = ptr::read(&self.buf);
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 impl<'a, T> IntoIterator for &'a Vec<T> {
1384 type IntoIter = slice::Iter<'a, T>;
1386 fn into_iter(self) -> slice::Iter<'a, T> {
1391 #[stable(feature = "rust1", since = "1.0.0")]
1392 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1393 type Item = &'a mut T;
1394 type IntoIter = slice::IterMut<'a, T>;
1396 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<T> Extend<T> for Vec<T> {
1404 fn extend<I: IntoIterator<Item = T>>(&mut self, iterable: I) {
1405 self.extend_desugared(iterable.into_iter())
1410 fn extend_desugared<I: Iterator<Item = T>>(&mut self, mut iterator: I) {
1411 // This function should be the moral equivalent of:
1413 // for item in iterator {
1416 while let Some(element) = iterator.next() {
1417 let len = self.len();
1418 if len == self.capacity() {
1419 let (lower, _) = iterator.size_hint();
1420 self.reserve(lower.saturating_add(1));
1423 ptr::write(self.get_unchecked_mut(len), element);
1424 // NB can't overflow since we would have had to alloc the address space
1425 self.set_len(len + 1);
1431 #[stable(feature = "extend_ref", since = "1.2.0")]
1432 impl<'a, T: 'a + Copy> Extend<&'a T> for Vec<T> {
1433 fn extend<I: IntoIterator<Item = &'a T>>(&mut self, iter: I) {
1434 self.extend(iter.into_iter().cloned());
1438 macro_rules! __impl_slice_eq1 {
1439 ($Lhs: ty, $Rhs: ty) => {
1440 __impl_slice_eq1! { $Lhs, $Rhs, Sized }
1442 ($Lhs: ty, $Rhs: ty, $Bound: ident) => {
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<'a, 'b, A: $Bound, B> PartialEq<$Rhs> for $Lhs where A: PartialEq<B> {
1446 fn eq(&self, other: &$Rhs) -> bool { self[..] == other[..] }
1448 fn ne(&self, other: &$Rhs) -> bool { self[..] != other[..] }
1453 __impl_slice_eq1! { Vec<A>, Vec<B> }
1454 __impl_slice_eq1! { Vec<A>, &'b [B] }
1455 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1456 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1457 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1458 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1460 macro_rules! array_impls {
1463 // NOTE: some less important impls are omitted to reduce code bloat
1464 __impl_slice_eq1! { Vec<A>, [B; $N] }
1465 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1466 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1467 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1468 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1469 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1476 10 11 12 13 14 15 16 17 18 19
1477 20 21 22 23 24 25 26 27 28 29
1481 #[stable(feature = "rust1", since = "1.0.0")]
1482 impl<T: PartialOrd> PartialOrd for Vec<T> {
1484 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1485 PartialOrd::partial_cmp(&**self, &**other)
1489 #[stable(feature = "rust1", since = "1.0.0")]
1490 impl<T: Eq> Eq for Vec<T> {}
1492 #[stable(feature = "rust1", since = "1.0.0")]
1493 impl<T: Ord> Ord for Vec<T> {
1495 fn cmp(&self, other: &Vec<T>) -> Ordering {
1496 Ord::cmp(&**self, &**other)
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 impl<T> Drop for Vec<T> {
1502 #[unsafe_destructor_blind_to_params]
1503 fn drop(&mut self) {
1504 if self.buf.unsafe_no_drop_flag_needs_drop() {
1506 // The branch on needs_drop() is an -O1 performance optimization.
1507 // Without the branch, dropping Vec<u8> takes linear time.
1508 if needs_drop::<T>() {
1509 for x in self.iter_mut() {
1510 ptr::drop_in_place(x);
1515 // RawVec handles deallocation
1519 #[stable(feature = "rust1", since = "1.0.0")]
1520 impl<T> Default for Vec<T> {
1521 fn default() -> Vec<T> {
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1528 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1529 fmt::Debug::fmt(&**self, f)
1533 #[stable(feature = "rust1", since = "1.0.0")]
1534 impl<T> AsRef<Vec<T>> for Vec<T> {
1535 fn as_ref(&self) -> &Vec<T> {
1540 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1541 impl<T> AsMut<Vec<T>> for Vec<T> {
1542 fn as_mut(&mut self) -> &mut Vec<T> {
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 impl<T> AsRef<[T]> for Vec<T> {
1549 fn as_ref(&self) -> &[T] {
1554 #[stable(feature = "vec_as_mut", since = "1.5.0")]
1555 impl<T> AsMut<[T]> for Vec<T> {
1556 fn as_mut(&mut self) -> &mut [T] {
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1564 fn from(s: &'a [T]) -> Vec<T> {
1568 fn from(s: &'a [T]) -> Vec<T> {
1573 #[stable(feature = "rust1", since = "1.0.0")]
1574 impl<'a> From<&'a str> for Vec<u8> {
1575 fn from(s: &'a str) -> Vec<u8> {
1576 From::from(s.as_bytes())
1580 ////////////////////////////////////////////////////////////////////////////////
1582 ////////////////////////////////////////////////////////////////////////////////
1584 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1585 impl<'a, T: Clone> From<&'a [T]> for Cow<'a, [T]> {
1586 fn from(s: &'a [T]) -> Cow<'a, [T]> {
1591 #[stable(feature = "cow_from_vec", since = "1.7.0")]
1592 impl<'a, T: Clone> From<Vec<T>> for Cow<'a, [T]> {
1593 fn from(v: Vec<T>) -> Cow<'a, [T]> {
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1600 fn from_iter<I: IntoIterator<Item = T>>(it: I) -> Cow<'a, [T]> {
1601 Cow::Owned(FromIterator::from_iter(it))
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 #[allow(deprecated)]
1607 impl<'a, T: 'a> IntoCow<'a, [T]> for Vec<T> where T: Clone {
1608 fn into_cow(self) -> Cow<'a, [T]> {
1613 #[stable(feature = "rust1", since = "1.0.0")]
1614 #[allow(deprecated)]
1615 impl<'a, T> IntoCow<'a, [T]> for &'a [T] where T: Clone {
1616 fn into_cow(self) -> Cow<'a, [T]> {
1621 ////////////////////////////////////////////////////////////////////////////////
1623 ////////////////////////////////////////////////////////////////////////////////
1625 /// An iterator that moves out of a vector.
1626 #[stable(feature = "rust1", since = "1.0.0")]
1627 pub struct IntoIter<T> {
1633 #[stable(feature = "rust1", since = "1.0.0")]
1634 unsafe impl<T: Send> Send for IntoIter<T> {}
1635 #[stable(feature = "rust1", since = "1.0.0")]
1636 unsafe impl<T: Sync> Sync for IntoIter<T> {}
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl<T> Iterator for IntoIter<T> {
1643 fn next(&mut self) -> Option<T> {
1645 if self.ptr == self.end {
1648 if mem::size_of::<T>() == 0 {
1649 // purposefully don't use 'ptr.offset' because for
1650 // vectors with 0-size elements this would return the
1652 self.ptr = arith_offset(self.ptr as *const i8, 1) as *const T;
1654 // Use a non-null pointer value
1655 Some(ptr::read(EMPTY as *mut T))
1658 self.ptr = self.ptr.offset(1);
1660 Some(ptr::read(old))
1667 fn size_hint(&self) -> (usize, Option<usize>) {
1668 let diff = (self.end as usize) - (self.ptr as usize);
1669 let size = mem::size_of::<T>();
1676 (exact, Some(exact))
1680 fn count(self) -> usize {
1685 #[stable(feature = "rust1", since = "1.0.0")]
1686 impl<T> DoubleEndedIterator for IntoIter<T> {
1688 fn next_back(&mut self) -> Option<T> {
1690 if self.end == self.ptr {
1693 if mem::size_of::<T>() == 0 {
1694 // See above for why 'ptr.offset' isn't used
1695 self.end = arith_offset(self.end as *const i8, -1) as *const T;
1697 // Use a non-null pointer value
1698 Some(ptr::read(EMPTY as *mut T))
1700 self.end = self.end.offset(-1);
1702 Some(ptr::read(self.end))
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 impl<T> ExactSizeIterator for IntoIter<T> {}
1712 #[stable(feature = "vec_into_iter_clone", since = "1.8.0")]
1713 impl<T: Clone> Clone for IntoIter<T> {
1714 fn clone(&self) -> IntoIter<T> {
1716 slice::from_raw_parts(self.ptr, self.len()).to_owned().into_iter()
1721 #[stable(feature = "rust1", since = "1.0.0")]
1722 impl<T> Drop for IntoIter<T> {
1723 #[unsafe_destructor_blind_to_params]
1724 fn drop(&mut self) {
1725 // destroy the remaining elements
1728 // RawVec handles deallocation
1732 /// A draining iterator for `Vec<T>`.
1733 #[stable(feature = "drain", since = "1.6.0")]
1734 pub struct Drain<'a, T: 'a> {
1735 /// Index of tail to preserve
1739 /// Current remaining range to remove
1740 iter: slice::IterMut<'a, T>,
1744 #[stable(feature = "drain", since = "1.6.0")]
1745 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1746 #[stable(feature = "drain", since = "1.6.0")]
1747 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1749 #[stable(feature = "rust1", since = "1.0.0")]
1750 impl<'a, T> Iterator for Drain<'a, T> {
1754 fn next(&mut self) -> Option<T> {
1755 self.iter.next().map(|elt| unsafe { ptr::read(elt as *const _) })
1758 fn size_hint(&self) -> (usize, Option<usize>) {
1759 self.iter.size_hint()
1763 #[stable(feature = "rust1", since = "1.0.0")]
1764 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1766 fn next_back(&mut self) -> Option<T> {
1767 self.iter.next_back().map(|elt| unsafe { ptr::read(elt as *const _) })
1771 #[stable(feature = "rust1", since = "1.0.0")]
1772 impl<'a, T> Drop for Drain<'a, T> {
1773 fn drop(&mut self) {
1774 // exhaust self first
1775 while let Some(_) = self.next() {}
1777 if self.tail_len > 0 {
1779 let source_vec = &mut *self.vec;
1780 // memmove back untouched tail, update to new length
1781 let start = source_vec.len();
1782 let tail = self.tail_start;
1783 let src = source_vec.as_ptr().offset(tail as isize);
1784 let dst = source_vec.as_mut_ptr().offset(start as isize);
1785 ptr::copy(src, dst, self.tail_len);
1786 source_vec.set_len(start + self.tail_len);
1793 #[stable(feature = "rust1", since = "1.0.0")]
1794 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}