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 growable list type with heap-allocated contents, written `Vec<T>` but
12 //! 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 as needed):
38 //! let mut v = vec![1, 2];
43 //! Popping values works in much the same way:
46 //! let mut v = vec![1, 2];
48 //! let two = v.pop();
51 //! Vectors also support indexing (through the `Index` and `IndexMut` traits):
54 //! let mut v = vec![1, 2, 3];
59 #![stable(feature = "rust1", since = "1.0.0")]
62 use alloc
::raw_vec
::RawVec
;
63 use alloc
::boxed
::Box
;
64 use alloc
::heap
::EMPTY
;
65 use core
::cmp
::Ordering
;
67 use core
::hash
::{self, Hash}
;
68 use core
::intrinsics
::{arith_offset, assume, drop_in_place}
;
69 use core
::iter
::FromIterator
;
70 use core
::marker
::PhantomData
;
72 use core
::ops
::{Index, IndexMut, Deref}
;
77 use borrow
::{Cow, IntoCow}
;
79 use super::range
::RangeArgument
;
81 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
86 /// let mut vec = Vec::new();
90 /// assert_eq!(vec.len(), 2);
91 /// assert_eq!(vec[0], 1);
93 /// assert_eq!(vec.pop(), Some(2));
94 /// assert_eq!(vec.len(), 1);
97 /// assert_eq!(vec[0], 7);
99 /// vec.extend([1, 2, 3].iter().cloned());
102 /// println!("{}", x);
104 /// assert_eq!(vec, [7, 1, 2, 3]);
107 /// The `vec!` macro is provided to make initialization more convenient:
110 /// let mut vec = vec![1, 2, 3];
112 /// assert_eq!(vec, [1, 2, 3, 4]);
115 /// It can also initialize each element of a `Vec<T>` with a given value:
118 /// let vec = vec![0; 5];
119 /// assert_eq!(vec, [0, 0, 0, 0, 0]);
122 /// Use a `Vec<T>` as an efficient stack:
125 /// let mut stack = Vec::new();
131 /// while let Some(top) = stack.pop() {
132 /// // Prints 3, 2, 1
133 /// println!("{}", top);
137 /// # Capacity and reallocation
139 /// The capacity of a vector is the amount of space allocated for any future
140 /// elements that will be added onto the vector. This is not to be confused with
141 /// the *length* of a vector, which specifies the number of actual elements
142 /// within the vector. If a vector's length exceeds its capacity, its capacity
143 /// will automatically be increased, but its elements will have to be
146 /// For example, a vector with capacity 10 and length 0 would be an empty vector
147 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
148 /// vector will not change its capacity or cause reallocation to occur. However,
149 /// if the vector's length is increased to 11, it will have to reallocate, which
150 /// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
151 /// whenever possible to specify how big the vector is expected to get.
152 #[unsafe_no_drop_flag]
153 #[stable(feature = "rust1", since = "1.0.0")]
159 ////////////////////////////////////////////////////////////////////////////////
161 ////////////////////////////////////////////////////////////////////////////////
164 /// Constructs a new, empty `Vec<T>`.
166 /// The vector will not allocate until elements are pushed onto it.
171 /// let mut vec: Vec<i32> = Vec::new();
174 #[stable(feature = "rust1", since = "1.0.0")]
175 pub fn new() -> Vec
<T
> {
176 Vec { buf: RawVec::new(), len: 0 }
179 /// Constructs a new, empty `Vec<T>` with the specified capacity.
181 /// The vector will be able to hold exactly `capacity` elements without reallocating. If
182 /// `capacity` is 0, the vector will not allocate.
184 /// It is important to note that this function does not specify the *length* of the returned
185 /// vector, but only the *capacity*. (For an explanation of the difference between length and
186 /// capacity, see the main `Vec<T>` docs above, 'Capacity and reallocation'.)
191 /// let mut vec = Vec::with_capacity(10);
193 /// // The vector contains no items, even though it has capacity for more
194 /// assert_eq!(vec.len(), 0);
196 /// // These are all done without reallocating...
201 /// // ...but this may make the vector reallocate
205 #[stable(feature = "rust1", since = "1.0.0")]
206 pub fn with_capacity(capacity
: usize) -> Vec
<T
> {
207 Vec { buf: RawVec::with_capacity(capacity), len: 0 }
210 /// Creates a `Vec<T>` directly from the raw components of another vector.
214 /// This is highly unsafe, due to the number of invariants that aren't
217 /// * `ptr` needs to have been previously allocated via `String`/`Vec<T>`
218 /// (at least, it's highly likely to be incorrect if it wasn't).
219 /// * `length` needs to be the length that less than or equal to `capacity`.
220 /// * `capacity` needs to be the capacity that the pointer was allocated with.
222 /// Violating these may cause problems like corrupting the allocator's
223 /// internal datastructures.
232 /// let mut v = vec![1, 2, 3];
234 /// // Pull out the various important pieces of information about `v`
235 /// let p = v.as_mut_ptr();
236 /// let len = v.len();
237 /// let cap = v.capacity();
240 /// // Cast `v` into the void: no destructor run, so we are in
241 /// // complete control of the allocation to which `p` points.
244 /// // Overwrite memory with 4, 5, 6
245 /// for i in 0..len as isize {
246 /// ptr::write(p.offset(i), 4 + i);
249 /// // Put everything back together into a Vec
250 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
251 /// assert_eq!(rebuilt, [4, 5, 6]);
255 #[stable(feature = "rust1", since = "1.0.0")]
256 pub unsafe fn from_raw_parts(ptr
: *mut T
, length
: usize,
257 capacity
: usize) -> Vec
<T
> {
259 buf
: RawVec
::from_raw_parts(ptr
, capacity
),
264 /// Creates a vector by copying the elements from a raw pointer.
266 /// This function will copy `elts` contiguous elements starting at `ptr`
267 /// into a new allocation owned by the returned `Vec<T>`. The elements of
268 /// the buffer are copied into the vector without cloning, as if
269 /// `ptr::read()` were called on them.
271 #[unstable(feature = "vec_from_raw_buf",
272 reason
= "may be better expressed via composition")]
273 #[deprecated(since = "1.2.0",
274 reason
= "use slice::from_raw_parts + .to_vec() instead")]
275 pub unsafe fn from_raw_buf(ptr
: *const T
, elts
: usize) -> Vec
<T
> {
276 let mut dst
= Vec
::with_capacity(elts
);
278 ptr
::copy_nonoverlapping(ptr
, dst
.as_mut_ptr(), elts
);
282 /// Returns the number of elements the vector can hold without
288 /// let vec: Vec<i32> = Vec::with_capacity(10);
289 /// assert_eq!(vec.capacity(), 10);
292 #[stable(feature = "rust1", since = "1.0.0")]
293 pub fn capacity(&self) -> usize {
297 /// Reserves capacity for at least `additional` more elements to be inserted
298 /// in the given `Vec<T>`. The collection may reserve more space to avoid
299 /// frequent reallocations.
303 /// Panics if the new capacity overflows `usize`.
308 /// let mut vec = vec![1];
310 /// assert!(vec.capacity() >= 11);
312 #[stable(feature = "rust1", since = "1.0.0")]
313 pub fn reserve(&mut self, additional
: usize) {
314 self.buf
.reserve(self.len
, additional
);
317 /// Reserves the minimum capacity for exactly `additional` more elements to
318 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
321 /// Note that the allocator may give the collection more space than it
322 /// requests. Therefore capacity can not be relied upon to be precisely
323 /// minimal. Prefer `reserve` if future insertions are expected.
327 /// Panics if the new capacity overflows `usize`.
332 /// let mut vec = vec![1];
333 /// vec.reserve_exact(10);
334 /// assert!(vec.capacity() >= 11);
336 #[stable(feature = "rust1", since = "1.0.0")]
337 pub fn reserve_exact(&mut self, additional
: usize) {
338 self.buf
.reserve_exact(self.len
, additional
);
341 /// Shrinks the capacity of the vector as much as possible.
343 /// It will drop down as close as possible to the length but the allocator
344 /// may still inform the vector that there is space for a few more elements.
349 /// let mut vec = Vec::with_capacity(10);
350 /// vec.extend([1, 2, 3].iter().cloned());
351 /// assert_eq!(vec.capacity(), 10);
352 /// vec.shrink_to_fit();
353 /// assert!(vec.capacity() >= 3);
355 #[stable(feature = "rust1", since = "1.0.0")]
356 pub fn shrink_to_fit(&mut self) {
357 self.buf
.shrink_to_fit(self.len
);
360 /// Converts the vector into Box<[T]>.
362 /// Note that this will drop any excess capacity. Calling this and
363 /// converting back to a vector with `into_vec()` is equivalent to calling
364 /// `shrink_to_fit()`.
365 #[stable(feature = "rust1", since = "1.0.0")]
366 pub fn into_boxed_slice(mut self) -> Box
<[T
]> {
368 self.shrink_to_fit();
369 let buf
= ptr
::read(&self.buf
);
375 /// Shorten a vector, dropping excess elements.
377 /// If `len` is greater than the vector's current length, this has no
383 /// let mut vec = vec![1, 2, 3, 4];
385 /// assert_eq!(vec, [1, 2]);
387 #[stable(feature = "rust1", since = "1.0.0")]
388 pub fn truncate(&mut self, len
: usize) {
390 // drop any extra elements
391 while len
< self.len
{
392 // decrement len before the read(), so a panic on Drop doesn't
393 // re-drop the just-failed value.
395 ptr
::read(self.get_unchecked(self.len
));
400 /// Extracts a slice containing the entire vector.
402 /// Equivalent to `&s[..]`.
404 #[unstable(feature = "convert",
405 reason
= "waiting on RFC revision")]
406 pub fn as_slice(&self) -> &[T
] {
410 /// Extracts a mutable slice of the entire vector.
412 /// Equivalent to `&mut s[..]`.
414 #[unstable(feature = "convert",
415 reason
= "waiting on RFC revision")]
416 pub fn as_mut_slice(&mut self) -> &mut [T
] {
420 /// Sets the length of a vector.
422 /// This will explicitly set the size of the vector, without actually
423 /// modifying its buffers, so it is up to the caller to ensure that the
424 /// vector is actually the specified size.
429 /// let mut v = vec![1, 2, 3, 4];
435 #[stable(feature = "rust1", since = "1.0.0")]
436 pub unsafe fn set_len(&mut self, len
: usize) {
440 /// Removes an element from anywhere in the vector and return it, replacing
441 /// it with the last element.
443 /// This does not preserve ordering, but is O(1).
447 /// Panics if `index` is out of bounds.
452 /// let mut v = vec!["foo", "bar", "baz", "qux"];
454 /// assert_eq!(v.swap_remove(1), "bar");
455 /// assert_eq!(v, ["foo", "qux", "baz"]);
457 /// assert_eq!(v.swap_remove(0), "foo");
458 /// assert_eq!(v, ["baz", "qux"]);
461 #[stable(feature = "rust1", since = "1.0.0")]
462 pub fn swap_remove(&mut self, index
: usize) -> T
{
463 let length
= self.len();
464 self.swap(index
, length
- 1);
468 /// Inserts an element at position `index` within the vector, shifting all
469 /// elements after position `i` one position to the right.
473 /// Panics if `index` is greater than the vector's length.
478 /// let mut vec = vec![1, 2, 3];
479 /// vec.insert(1, 4);
480 /// assert_eq!(vec, [1, 4, 2, 3]);
481 /// vec.insert(4, 5);
482 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
484 #[stable(feature = "rust1", since = "1.0.0")]
485 pub fn insert(&mut self, index
: usize, element
: T
) {
486 let len
= self.len();
487 assert
!(index
<= len
);
489 // space for the new element
490 if len
== self.buf
.cap() { self.buf.double(); }
492 unsafe { // infallible
493 // The spot to put the new value
495 let p
= self.as_mut_ptr().offset(index
as isize);
496 // Shift everything over to make space. (Duplicating the
497 // `index`th element into two consecutive places.)
498 ptr
::copy(p
, p
.offset(1), len
- index
);
499 // Write it in, overwriting the first copy of the `index`th
501 ptr
::write(p
, element
);
503 self.set_len(len
+ 1);
507 /// Removes and returns the element at position `index` within the vector,
508 /// shifting all elements after position `index` one position to the left.
512 /// Panics if `index` is out of bounds.
517 /// let mut v = vec![1, 2, 3];
518 /// assert_eq!(v.remove(1), 2);
519 /// assert_eq!(v, [1, 3]);
521 #[stable(feature = "rust1", since = "1.0.0")]
522 pub fn remove(&mut self, index
: usize) -> T
{
523 let len
= self.len();
524 assert
!(index
< len
);
525 unsafe { // infallible
528 // the place we are taking from.
529 let ptr
= self.as_mut_ptr().offset(index
as isize);
530 // copy it out, unsafely having a copy of the value on
531 // the stack and in the vector at the same time.
532 ret
= ptr
::read(ptr
);
534 // Shift everything down to fill in that spot.
535 ptr
::copy(ptr
.offset(1), ptr
, len
- index
- 1);
537 self.set_len(len
- 1);
542 /// Retains only the elements specified by the predicate.
544 /// In other words, remove all elements `e` such that `f(&e)` returns false.
545 /// This method operates in place and preserves the order of the retained
551 /// let mut vec = vec![1, 2, 3, 4];
552 /// vec.retain(|&x| x%2 == 0);
553 /// assert_eq!(vec, [2, 4]);
555 #[stable(feature = "rust1", since = "1.0.0")]
556 pub fn retain
<F
>(&mut self, mut f
: F
) where F
: FnMut(&T
) -> bool
{
557 let len
= self.len();
571 self.truncate(len
- del
);
575 /// Appends an element to the back of a collection.
579 /// Panics if the number of elements in the vector overflows a `usize`.
584 /// let mut vec = vec![1, 2];
586 /// assert_eq!(vec, [1, 2, 3]);
589 #[stable(feature = "rust1", since = "1.0.0")]
590 pub fn push(&mut self, value
: T
) {
591 // This will panic or abort if we would allocate > isize::MAX bytes
592 // or if the length increment would overflow for zero-sized types.
593 if self.len
== self.buf
.cap() { self.buf.double(); }
595 let end
= self.as_mut_ptr().offset(self.len
as isize);
596 ptr
::write(end
, value
);
601 /// Removes the last element from a vector and returns it, or `None` if it is empty.
606 /// let mut vec = vec![1, 2, 3];
607 /// assert_eq!(vec.pop(), Some(3));
608 /// assert_eq!(vec, [1, 2]);
611 #[stable(feature = "rust1", since = "1.0.0")]
612 pub fn pop(&mut self) -> Option
<T
> {
618 Some(ptr
::read(self.get_unchecked(self.len())))
623 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
627 /// Panics if the number of elements in the vector overflows a `usize`.
632 /// #![feature(append)]
634 /// let mut vec = vec![1, 2, 3];
635 /// let mut vec2 = vec![4, 5, 6];
636 /// vec.append(&mut vec2);
637 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
638 /// assert_eq!(vec2, []);
641 #[unstable(feature = "append",
642 reason
= "new API, waiting for dust to settle")]
643 pub fn append(&mut self, other
: &mut Self) {
644 self.reserve(other
.len());
645 let len
= self.len();
647 ptr
::copy_nonoverlapping(
649 self.get_unchecked_mut(len
),
653 self.len
+= other
.len();
654 unsafe { other.set_len(0); }
657 /// Create a draining iterator that removes the specified range in the vector
658 /// and yields the removed items from start to end. The element range is
659 /// removed even if the iterator is not consumed until the end.
661 /// Note: It is unspecified how many elements are removed from the vector,
662 /// if the `Drain` value is leaked.
666 /// Panics if the starting point is greater than the end point or if
667 /// the end point is greater than the length of the vector.
672 /// #![feature(drain)]
674 /// // Draining using `..` clears the whole vector.
675 /// let mut v = vec![1, 2, 3];
676 /// let u: Vec<_> = v.drain(..).collect();
677 /// assert_eq!(v, &[]);
678 /// assert_eq!(u, &[1, 2, 3]);
680 #[unstable(feature = "drain",
681 reason
= "recently added, matches RFC")]
682 pub fn drain
<R
>(&mut self, range
: R
) -> Drain
<T
> where R
: RangeArgument
<usize> {
685 // When the Drain is first created, it shortens the length of
686 // the source vector to make sure no uninitalized or moved-from elements
687 // are accessible at all if the Drain's destructor never gets to run.
689 // Drain will ptr::read out the values to remove.
690 // When finished, remaining tail of the vec is copied back to cover
691 // the hole, and the vector length is restored to the new length.
693 let len
= self.len();
694 let start
= *range
.start().unwrap_or(&0);
695 let end
= *range
.end().unwrap_or(&len
);
696 assert
!(start
<= end
);
700 // set self.vec length's to start, to be safe in case Drain is leaked
702 // Use the borrow in the IterMut to indicate borrowing behavior of the
703 // whole Drain iterator (like &mut T).
704 let range_slice
= slice
::from_raw_parts_mut(
705 self.as_mut_ptr().offset(start
as isize),
710 iter
: range_slice
.iter_mut(),
716 /// Clears the vector, removing all values.
721 /// let mut v = vec![1, 2, 3];
725 /// assert!(v.is_empty());
728 #[stable(feature = "rust1", since = "1.0.0")]
729 pub fn clear(&mut self) {
733 /// Returns the number of elements in the vector.
738 /// let a = vec![1, 2, 3];
739 /// assert_eq!(a.len(), 3);
742 #[stable(feature = "rust1", since = "1.0.0")]
743 pub fn len(&self) -> usize { self.len }
745 /// Returns `true` if the vector contains no elements.
750 /// let mut v = Vec::new();
751 /// assert!(v.is_empty());
754 /// assert!(!v.is_empty());
756 #[stable(feature = "rust1", since = "1.0.0")]
757 pub fn is_empty(&self) -> bool { self.len() == 0 }
759 /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same
760 /// size and in case they are not zero-sized the same minimal alignment.
764 /// Panics if `T` and `U` have differing sizes or are not zero-sized and
765 /// have differing minimal alignments.
770 /// #![feature(map_in_place)]
772 /// let v = vec![0, 1, 2];
773 /// let w = v.map_in_place(|i| i + 3);
774 /// assert_eq!(&w[..], &[3, 4, 5]);
776 /// #[derive(PartialEq, Debug)]
777 /// struct Newtype(u8);
778 /// let bytes = vec![0x11, 0x22];
779 /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x));
780 /// assert_eq!(&newtyped_bytes[..], &[Newtype(0x11), Newtype(0x22)]);
782 #[unstable(feature = "map_in_place",
783 reason
= "API may change to provide stronger guarantees")]
784 #[deprecated(since = "1.3.0",
785 reason
= "unclear that the API is strong enough and did \
787 pub fn map_in_place
<U
, F
>(self, mut f
: F
) -> Vec
<U
> where F
: FnMut(T
) -> U
{
788 // FIXME: Assert statically that the types `T` and `U` have the same
790 assert
!(mem
::size_of
::<T
>() == mem
::size_of
::<U
>());
794 if mem
::size_of
::<T
>() != 0 {
795 // FIXME: Assert statically that the types `T` and `U` have the
796 // same minimal alignment in case they are not zero-sized.
798 // These asserts are necessary because the `align_of` of the
799 // types are passed to the allocator by `Vec`.
800 assert
!(mem
::align_of
::<T
>() == mem
::align_of
::<U
>());
802 // This `as isize` cast is safe, because the size of the elements of the
803 // vector is not 0, and:
805 // 1) If the size of the elements in the vector is 1, the `isize` may
806 // overflow, but it has the correct bit pattern so that the
807 // `.offset()` function will work.
810 // Address space 0x0-0xF.
811 // `u8` array at: 0x1.
812 // Size of `u8` array: 0x8.
813 // Calculated `offset`: -0x8.
814 // After `array.offset(offset)`: 0x9.
815 // (0x1 + 0x8 = 0x1 - 0x8)
817 // 2) If the size of the elements in the vector is >1, the `usize` ->
818 // `isize` conversion can't overflow.
819 let offset
= vec
.len() as isize;
820 let start
= vec
.as_mut_ptr();
822 let mut pv
= PartialVecNonZeroSized
{
826 // This points inside the vector, as the vector has length
828 end_t
: unsafe { start.offset(offset) }
,
829 start_u
: start
as *mut U
,
830 end_u
: start
as *mut U
,
832 _marker
: PhantomData
,
843 while pv
.end_u
as *mut T
!= pv
.end_t
{
847 // +-+-+-+-+-+-+-+-+-+
848 // |U|...|U|T|T|...|T|
849 // +-+-+-+-+-+-+-+-+-+
853 let t
= ptr
::read(pv
.start_t
);
856 // +-+-+-+-+-+-+-+-+-+
857 // |U|...|U|X|T|...|T|
858 // +-+-+-+-+-+-+-+-+-+
861 // We must not panic here, one cell is marked as `T`
862 // although it is not `T`.
864 pv
.start_t
= pv
.start_t
.offset(1);
867 // +-+-+-+-+-+-+-+-+-+
868 // |U|...|U|X|T|...|T|
869 // +-+-+-+-+-+-+-+-+-+
872 // We may panic again.
874 // The function given by the user might panic.
877 ptr
::write(pv
.end_u
, u
);
880 // +-+-+-+-+-+-+-+-+-+
881 // |U|...|U|U|T|...|T|
882 // +-+-+-+-+-+-+-+-+-+
885 // We should not panic here, because that would leak the `U`
886 // pointed to by `end_u`.
888 pv
.end_u
= pv
.end_u
.offset(1);
891 // +-+-+-+-+-+-+-+-+-+
892 // |U|...|U|U|T|...|T|
893 // +-+-+-+-+-+-+-+-+-+
896 // We may panic again.
908 // Extract `vec` and prevent the destructor of
909 // `PartialVecNonZeroSized` from running. Note that none of the
910 // function calls can panic, thus no resources can be leaked (as the
911 // `vec` member of `PartialVec` is the only one which holds
912 // allocations -- and it is returned from this function. None of
915 let vec_len
= pv
.vec
.len();
916 let vec_cap
= pv
.vec
.capacity();
917 let vec_ptr
= pv
.vec
.as_mut_ptr() as *mut U
;
919 Vec
::from_raw_parts(vec_ptr
, vec_len
, vec_cap
)
922 // Put the `Vec` into the `PartialVecZeroSized` structure and
923 // prevent the destructor of the `Vec` from running. Since the
924 // `Vec` contained zero-sized objects, it did not allocate, so we
925 // are not leaking memory here.
926 let mut pv
= PartialVecZeroSized
::<T
,U
> {
933 while pv
.num_t
!= 0 {
935 // Create a `T` out of thin air and decrement `num_t`. This
936 // must not panic between these steps, as otherwise a
937 // destructor of `T` which doesn't exist runs.
938 let t
= mem
::uninitialized();
941 // The function given by the user might panic.
944 // Forget the `U` and increment `num_u`. This increment
945 // cannot overflow the `usize` as we only do this for a
946 // number of times that fits into a `usize` (and start with
947 // `0`). Again, we should not panic between these steps.
952 // Create a `Vec` from our `PartialVecZeroSized` and make sure the
953 // destructor of the latter will not run. None of this can panic.
954 let mut result
= Vec
::new();
956 result
.set_len(pv
.num_u
);
963 /// Splits the collection into two at the given index.
965 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
966 /// and the returned `Self` contains elements `[at, len)`.
968 /// Note that the capacity of `self` does not change.
972 /// Panics if `at > len`.
977 /// #![feature(split_off)]
979 /// let mut vec = vec![1,2,3];
980 /// let vec2 = vec.split_off(1);
981 /// assert_eq!(vec, [1]);
982 /// assert_eq!(vec2, [2, 3]);
985 #[unstable(feature = "split_off",
986 reason
= "new API, waiting for dust to settle")]
987 pub fn split_off(&mut self, at
: usize) -> Self {
988 assert
!(at
<= self.len(), "`at` out of bounds");
990 let other_len
= self.len
- at
;
991 let mut other
= Vec
::with_capacity(other_len
);
993 // Unsafely `set_len` and copy items to `other`.
996 other
.set_len(other_len
);
998 ptr
::copy_nonoverlapping(
999 self.as_ptr().offset(at
as isize),
1008 impl<T
: Clone
> Vec
<T
> {
1009 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1011 /// Calls either `extend()` or `truncate()` depending on whether `new_len`
1012 /// is larger than the current value of `len()` or not.
1017 /// #![feature(vec_resize)]
1019 /// let mut vec = vec!["hello"];
1020 /// vec.resize(3, "world");
1021 /// assert_eq!(vec, ["hello", "world", "world"]);
1023 /// let mut vec = vec![1, 2, 3, 4];
1024 /// vec.resize(2, 0);
1025 /// assert_eq!(vec, [1, 2]);
1027 #[unstable(feature = "vec_resize",
1028 reason
= "matches collection reform specification; waiting for dust to settle")]
1029 pub fn resize(&mut self, new_len
: usize, value
: T
) {
1030 let len
= self.len();
1033 self.extend_with_element(new_len
- len
, value
);
1035 self.truncate(new_len
);
1039 /// Extend the vector by `n` additional clones of `value`.
1040 fn extend_with_element(&mut self, n
: usize, value
: T
) {
1044 let len
= self.len();
1045 let mut ptr
= self.as_mut_ptr().offset(len
as isize);
1046 // Write all elements except the last one
1048 ptr
::write(ptr
, value
.clone());
1049 ptr
= ptr
.offset(1);
1050 // Increment the length in every step in case clone() panics
1051 self.set_len(len
+ i
);
1055 // We can write the last element directly without cloning needlessly
1056 ptr
::write(ptr
, value
);
1057 self.set_len(len
+ n
);
1062 /// Appends all elements in a slice to the `Vec`.
1064 /// Iterates over the slice `other`, clones each element, and then appends
1065 /// it to this `Vec`. The `other` vector is traversed in-order.
1070 /// #![feature(vec_push_all)]
1072 /// let mut vec = vec![1];
1073 /// vec.push_all(&[2, 3, 4]);
1074 /// assert_eq!(vec, [1, 2, 3, 4]);
1077 #[unstable(feature = "vec_push_all",
1078 reason
= "likely to be replaced by a more optimized extend")]
1079 pub fn push_all(&mut self, other
: &[T
]) {
1080 self.reserve(other
.len());
1082 for i
in 0..other
.len() {
1083 let len
= self.len();
1085 // Unsafe code so this can be optimised to a memcpy (or something similarly
1086 // fast) when T is Copy. LLVM is easily confused, so any extra operations
1087 // during the loop can prevent this optimisation.
1090 self.get_unchecked_mut(len
),
1091 other
.get_unchecked(i
).clone());
1092 self.set_len(len
+ 1);
1098 impl<T
: PartialEq
> Vec
<T
> {
1099 /// Removes consecutive repeated elements in the vector.
1101 /// If the vector is sorted, this removes all duplicates.
1106 /// let mut vec = vec![1, 2, 2, 3, 2];
1110 /// assert_eq!(vec, [1, 2, 3, 2]);
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn dedup(&mut self) {
1115 // Although we have a mutable reference to `self`, we cannot make
1116 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1117 // must ensure that the vector is in a valid state at all time.
1119 // The way that we handle this is by using swaps; we iterate
1120 // over all the elements, swapping as we go so that at the end
1121 // the elements we wish to keep are in the front, and those we
1122 // wish to reject are at the back. We can then truncate the
1123 // vector. This operation is still O(n).
1125 // Example: We start in this state, where `r` represents "next
1126 // read" and `w` represents "next_write`.
1129 // +---+---+---+---+---+---+
1130 // | 0 | 1 | 1 | 2 | 3 | 3 |
1131 // +---+---+---+---+---+---+
1134 // Comparing self[r] against self[w-1], this is not a duplicate, so
1135 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1136 // r and w, leaving us with:
1139 // +---+---+---+---+---+---+
1140 // | 0 | 1 | 1 | 2 | 3 | 3 |
1141 // +---+---+---+---+---+---+
1144 // Comparing self[r] against self[w-1], this value is a duplicate,
1145 // so we increment `r` but leave everything else unchanged:
1148 // +---+---+---+---+---+---+
1149 // | 0 | 1 | 1 | 2 | 3 | 3 |
1150 // +---+---+---+---+---+---+
1153 // Comparing self[r] against self[w-1], this is not a duplicate,
1154 // so swap self[r] and self[w] and advance r and w:
1157 // +---+---+---+---+---+---+
1158 // | 0 | 1 | 2 | 1 | 3 | 3 |
1159 // +---+---+---+---+---+---+
1162 // Not a duplicate, repeat:
1165 // +---+---+---+---+---+---+
1166 // | 0 | 1 | 2 | 3 | 1 | 3 |
1167 // +---+---+---+---+---+---+
1170 // Duplicate, advance r. End of vec. Truncate to w.
1172 let ln
= self.len();
1173 if ln
<= 1 { return; }
1175 // Avoid bounds checks by using raw pointers.
1176 let p
= self.as_mut_ptr();
1177 let mut r
: usize = 1;
1178 let mut w
: usize = 1;
1181 let p_r
= p
.offset(r
as isize);
1182 let p_wm1
= p
.offset((w
- 1) as isize);
1185 let p_w
= p_wm1
.offset(1);
1186 mem
::swap(&mut *p_r
, &mut *p_w
);
1198 ////////////////////////////////////////////////////////////////////////////////
1199 // Internal methods and functions
1200 ////////////////////////////////////////////////////////////////////////////////
1203 #[stable(feature = "rust1", since = "1.0.0")]
1204 pub fn from_elem
<T
: Clone
>(elem
: T
, n
: usize) -> Vec
<T
> {
1205 let mut v
= Vec
::with_capacity(n
);
1206 v
.extend_with_element(n
, elem
);
1210 ////////////////////////////////////////////////////////////////////////////////
1211 // Common trait implementations for Vec
1212 ////////////////////////////////////////////////////////////////////////////////
1214 #[stable(feature = "rust1", since = "1.0.0")]
1215 impl<T
:Clone
> Clone
for Vec
<T
> {
1217 fn clone(&self) -> Vec
<T
> { <[T]>::to_vec(&**self) }
1219 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1220 // required for this method definition, is not available. Instead use the
1221 // `slice::to_vec` function which is only available with cfg(test)
1222 // NB see the slice::hack module in slice.rs for more information
1224 fn clone(&self) -> Vec
<T
> {
1225 ::slice
::to_vec(&**self)
1228 fn clone_from(&mut self, other
: &Vec
<T
>) {
1229 // drop anything in self that will not be overwritten
1230 if self.len() > other
.len() {
1231 self.truncate(other
.len())
1234 // reuse the contained values' allocations/resources.
1235 for (place
, thing
) in self.iter_mut().zip(other
) {
1236 place
.clone_from(thing
)
1239 // self.len <= other.len due to the truncate above, so the
1240 // slice here is always in-bounds.
1241 let slice
= &other
[self.len()..];
1242 self.push_all(slice
);
1246 #[stable(feature = "rust1", since = "1.0.0")]
1247 impl<T
: Hash
> Hash
for Vec
<T
> {
1249 fn hash
<H
: hash
::Hasher
>(&self, state
: &mut H
) {
1250 Hash
::hash(&**self, state
)
1254 #[stable(feature = "rust1", since = "1.0.0")]
1255 impl<T
> Index
<usize> for Vec
<T
> {
1259 fn index(&self, index
: usize) -> &T
{
1260 // NB built-in indexing via `&[T]`
1265 #[stable(feature = "rust1", since = "1.0.0")]
1266 impl<T
> IndexMut
<usize> for Vec
<T
> {
1268 fn index_mut(&mut self, index
: usize) -> &mut T
{
1269 // NB built-in indexing via `&mut [T]`
1270 &mut (**self)[index
]
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 impl<T
> ops
::Index
<ops
::Range
<usize>> for Vec
<T
> {
1280 fn index(&self, index
: ops
::Range
<usize>) -> &[T
] {
1281 Index
::index(&**self, index
)
1284 #[stable(feature = "rust1", since = "1.0.0")]
1285 impl<T
> ops
::Index
<ops
::RangeTo
<usize>> for Vec
<T
> {
1289 fn index(&self, index
: ops
::RangeTo
<usize>) -> &[T
] {
1290 Index
::index(&**self, index
)
1293 #[stable(feature = "rust1", since = "1.0.0")]
1294 impl<T
> ops
::Index
<ops
::RangeFrom
<usize>> for Vec
<T
> {
1298 fn index(&self, index
: ops
::RangeFrom
<usize>) -> &[T
] {
1299 Index
::index(&**self, index
)
1302 #[stable(feature = "rust1", since = "1.0.0")]
1303 impl<T
> ops
::Index
<ops
::RangeFull
> for Vec
<T
> {
1307 fn index(&self, _index
: ops
::RangeFull
) -> &[T
] {
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<T
> ops
::IndexMut
<ops
::Range
<usize>> for Vec
<T
> {
1316 fn index_mut(&mut self, index
: ops
::Range
<usize>) -> &mut [T
] {
1317 IndexMut
::index_mut(&mut **self, index
)
1320 #[stable(feature = "rust1", since = "1.0.0")]
1321 impl<T
> ops
::IndexMut
<ops
::RangeTo
<usize>> for Vec
<T
> {
1324 fn index_mut(&mut self, index
: ops
::RangeTo
<usize>) -> &mut [T
] {
1325 IndexMut
::index_mut(&mut **self, index
)
1328 #[stable(feature = "rust1", since = "1.0.0")]
1329 impl<T
> ops
::IndexMut
<ops
::RangeFrom
<usize>> for Vec
<T
> {
1332 fn index_mut(&mut self, index
: ops
::RangeFrom
<usize>) -> &mut [T
] {
1333 IndexMut
::index_mut(&mut **self, index
)
1336 #[stable(feature = "rust1", since = "1.0.0")]
1337 impl<T
> ops
::IndexMut
<ops
::RangeFull
> for Vec
<T
> {
1340 fn index_mut(&mut self, _index
: ops
::RangeFull
) -> &mut [T
] {
1345 #[stable(feature = "rust1", since = "1.0.0")]
1346 impl<T
> ops
::Deref
for Vec
<T
> {
1349 fn deref(&self) -> &[T
] {
1351 let p
= self.buf
.ptr();
1352 assume(p
!= 0 as *mut T
);
1353 slice
::from_raw_parts(p
, self.len
)
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl<T
> ops
::DerefMut
for Vec
<T
> {
1360 fn deref_mut(&mut self) -> &mut [T
] {
1362 let ptr
= self.buf
.ptr();
1363 assume(!ptr
.is_null());
1364 slice
::from_raw_parts_mut(ptr
, self.len
)
1369 #[stable(feature = "rust1", since = "1.0.0")]
1370 impl<T
> FromIterator
<T
> for Vec
<T
> {
1372 fn from_iter
<I
: IntoIterator
<Item
=T
>>(iterable
: I
) -> Vec
<T
> {
1373 // Unroll the first iteration, as the vector is going to be
1374 // expanded on this iteration in every case when the iterable is not
1375 // empty, but the loop in extend_desugared() is not going to see the
1376 // vector being full in the few subsequent loop iterations.
1377 // So we get better branch prediction and the possibility to
1378 // construct the vector with initial estimated capacity.
1379 let mut iterator
= iterable
.into_iter();
1380 let mut vector
= match iterator
.next() {
1381 None
=> return Vec
::new(),
1383 let (lower
, _
) = iterator
.size_hint();
1384 let mut vector
= Vec
::with_capacity(lower
.saturating_add(1));
1386 ptr
::write(vector
.get_unchecked_mut(0), element
);
1392 vector
.extend_desugared(iterator
);
1397 #[stable(feature = "rust1", since = "1.0.0")]
1398 impl<T
> IntoIterator
for Vec
<T
> {
1400 type IntoIter
= IntoIter
<T
>;
1402 /// Creates a consuming iterator, that is, one that moves each value out of
1403 /// the vector (from start to end). The vector cannot be used after calling
1409 /// let v = vec!["a".to_string(), "b".to_string()];
1410 /// for s in v.into_iter() {
1411 /// // s has type String, not &String
1412 /// println!("{}", s);
1416 fn into_iter(mut self) -> IntoIter
<T
> {
1418 let ptr
= self.as_mut_ptr();
1419 assume(!ptr
.is_null());
1420 let begin
= ptr
as *const T
;
1421 let end
= if mem
::size_of
::<T
>() == 0 {
1422 arith_offset(ptr
as *const i8, self.len() as isize) as *const T
1424 ptr
.offset(self.len() as isize) as *const T
1426 let buf
= ptr
::read(&self.buf
);
1428 IntoIter { buf: buf, ptr: begin, end: end }
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<'a
, T
> IntoIterator
for &'a Vec
<T
> {
1436 type IntoIter
= slice
::Iter
<'a
, T
>;
1438 fn into_iter(self) -> slice
::Iter
<'a
, T
> {
1443 #[stable(feature = "rust1", since = "1.0.0")]
1444 impl<'a
, T
> IntoIterator
for &'a
mut Vec
<T
> {
1445 type Item
= &'a
mut T
;
1446 type IntoIter
= slice
::IterMut
<'a
, T
>;
1448 fn into_iter(mut self) -> slice
::IterMut
<'a
, T
> {
1453 #[stable(feature = "rust1", since = "1.0.0")]
1454 impl<T
> Extend
<T
> for Vec
<T
> {
1456 fn extend
<I
: IntoIterator
<Item
=T
>>(&mut self, iterable
: I
) {
1457 self.extend_desugared(iterable
.into_iter())
1462 fn extend_desugared
<I
: Iterator
<Item
=T
>>(&mut self, mut iterator
: I
) {
1463 // This function should be the moral equivalent of:
1465 // for item in iterator {
1468 while let Some(element
) = iterator
.next() {
1469 let len
= self.len();
1470 if len
== self.capacity() {
1471 let (lower
, _
) = iterator
.size_hint();
1472 self.reserve(lower
.saturating_add(1));
1475 ptr
::write(self.get_unchecked_mut(len
), element
);
1476 // NB can't overflow since we would have had to alloc the address space
1477 self.set_len(len
+ 1);
1483 #[stable(feature = "extend_ref", since = "1.2.0")]
1484 impl<'a
, T
: 'a
+ Copy
> Extend
<&'a T
> for Vec
<T
> {
1485 fn extend
<I
: IntoIterator
<Item
=&'a T
>>(&mut self, iter
: I
) {
1486 self.extend(iter
.into_iter().cloned());
1490 __impl_slice_eq1
! { Vec<A>, Vec<B> }
1491 __impl_slice_eq1
! { Vec<A>, &'b [B] }
1492 __impl_slice_eq1
! { Vec<A>, &'b mut [B] }
1493 __impl_slice_eq1
! { Cow<'a, [A]>, &'b [B], Clone }
1494 __impl_slice_eq1
! { Cow<'a, [A]>, &'b mut [B], Clone }
1495 __impl_slice_eq1
! { Cow<'a, [A]>, Vec<B>, Clone }
1497 macro_rules
! array_impls
{
1500 // NOTE: some less important impls are omitted to reduce code bloat
1501 __impl_slice_eq1
! { Vec<A>, [B; $N] }
1502 __impl_slice_eq1
! { Vec<A>, &'b [B; $N] }
1503 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1504 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1505 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1506 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1513 10 11 12 13 14 15 16 17 18 19
1514 20 21 22 23 24 25 26 27 28 29
1518 #[stable(feature = "rust1", since = "1.0.0")]
1519 impl<T
: PartialOrd
> PartialOrd
for Vec
<T
> {
1521 fn partial_cmp(&self, other
: &Vec
<T
>) -> Option
<Ordering
> {
1522 PartialOrd
::partial_cmp(&**self, &**other
)
1526 #[stable(feature = "rust1", since = "1.0.0")]
1527 impl<T
: Eq
> Eq
for Vec
<T
> {}
1529 #[stable(feature = "rust1", since = "1.0.0")]
1530 impl<T
: Ord
> Ord
for Vec
<T
> {
1532 fn cmp(&self, other
: &Vec
<T
>) -> Ordering
{
1533 Ord
::cmp(&**self, &**other
)
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl<T
> Drop
for Vec
<T
> {
1539 fn drop(&mut self) {
1540 // NOTE: this is currently abusing the fact that ZSTs can't impl Drop.
1541 // Or rather, that impl'ing Drop makes them not zero-sized. This is
1542 // OK because exactly when this stops being a valid assumption, we
1543 // don't need unsafe_no_drop_flag shenanigans anymore.
1544 if self.buf
.unsafe_no_drop_flag_needs_drop() {
1545 for x
in self.iter_mut() {
1546 unsafe { drop_in_place(x); }
1549 // RawVec handles deallocation
1553 #[stable(feature = "rust1", since = "1.0.0")]
1554 impl<T
> Default
for Vec
<T
> {
1555 #[stable(feature = "rust1", since = "1.0.0")]
1556 fn default() -> Vec
<T
> {
1561 #[stable(feature = "rust1", since = "1.0.0")]
1562 impl<T
: fmt
::Debug
> fmt
::Debug
for Vec
<T
> {
1563 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
1564 fmt
::Debug
::fmt(&**self, f
)
1568 #[stable(feature = "rust1", since = "1.0.0")]
1569 impl<T
> AsRef
<Vec
<T
>> for Vec
<T
> {
1570 fn as_ref(&self) -> &Vec
<T
> {
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl<T
> AsRef
<[T
]> for Vec
<T
> {
1577 fn as_ref(&self) -> &[T
] {
1582 #[stable(feature = "rust1", since = "1.0.0")]
1583 impl<'a
, T
: Clone
> From
<&'a
[T
]> for Vec
<T
> {
1585 fn from(s
: &'a
[T
]) -> Vec
<T
> {
1589 fn from(s
: &'a
[T
]) -> Vec
<T
> {
1594 #[stable(feature = "rust1", since = "1.0.0")]
1595 impl<'a
> From
<&'a
str> for Vec
<u8> {
1596 fn from(s
: &'a
str) -> Vec
<u8> {
1597 From
::from(s
.as_bytes())
1601 ////////////////////////////////////////////////////////////////////////////////
1603 ////////////////////////////////////////////////////////////////////////////////
1605 #[stable(feature = "rust1", since = "1.0.0")]
1606 impl<'a
, T
> FromIterator
<T
> for Cow
<'a
, [T
]> where T
: Clone
{
1607 fn from_iter
<I
: IntoIterator
<Item
=T
>>(it
: I
) -> Cow
<'a
, [T
]> {
1608 Cow
::Owned(FromIterator
::from_iter(it
))
1612 #[allow(deprecated)]
1613 impl<'a
, T
: 'a
> IntoCow
<'a
, [T
]> for Vec
<T
> where T
: Clone
{
1614 fn into_cow(self) -> Cow
<'a
, [T
]> {
1619 #[allow(deprecated)]
1620 impl<'a
, T
> IntoCow
<'a
, [T
]> for &'a
[T
] where T
: Clone
{
1621 fn into_cow(self) -> Cow
<'a
, [T
]> {
1626 ////////////////////////////////////////////////////////////////////////////////
1628 ////////////////////////////////////////////////////////////////////////////////
1630 /// An iterator that moves out of a vector.
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 pub struct IntoIter
<T
> {
1638 unsafe impl<T
: Send
> Send
for IntoIter
<T
> { }
1639 unsafe impl<T
: Sync
> Sync
for IntoIter
<T
> { }
1641 impl<T
> IntoIter
<T
> {
1643 /// Drops all items that have not yet been moved and returns the empty vector.
1644 #[unstable(feature = "iter_to_vec")]
1645 #[deprecated(since = "1.3.0", reason = "replaced by drain()")]
1646 pub fn into_inner(mut self) -> Vec
<T
> {
1648 for _x
in self.by_ref() { }
1649 let buf
= ptr
::read(&self.buf
);
1651 Vec { buf: buf, len: 0 }
1656 #[stable(feature = "rust1", since = "1.0.0")]
1657 impl<T
> Iterator
for IntoIter
<T
> {
1661 fn next(&mut self) -> Option
<T
> {
1663 if self.ptr
== self.end
{
1666 if mem
::size_of
::<T
>() == 0 {
1667 // purposefully don't use 'ptr.offset' because for
1668 // vectors with 0-size elements this would return the
1670 self.ptr
= arith_offset(self.ptr
as *const i8, 1) as *const T
;
1672 // Use a non-null pointer value
1673 Some(ptr
::read(EMPTY
as *mut T
))
1676 self.ptr
= self.ptr
.offset(1);
1678 Some(ptr
::read(old
))
1685 fn size_hint(&self) -> (usize, Option
<usize>) {
1686 let diff
= (self.end
as usize) - (self.ptr
as usize);
1687 let size
= mem
::size_of
::<T
>();
1688 let exact
= diff
/ (if size
== 0 {1}
else {size}
);
1689 (exact
, Some(exact
))
1693 fn count(self) -> usize {
1698 #[stable(feature = "rust1", since = "1.0.0")]
1699 impl<T
> DoubleEndedIterator
for IntoIter
<T
> {
1701 fn next_back(&mut self) -> Option
<T
> {
1703 if self.end
== self.ptr
{
1706 if mem
::size_of
::<T
>() == 0 {
1707 // See above for why 'ptr.offset' isn't used
1708 self.end
= arith_offset(self.end
as *const i8, -1) as *const T
;
1710 // Use a non-null pointer value
1711 Some(ptr
::read(EMPTY
as *mut T
))
1713 self.end
= self.end
.offset(-1);
1715 Some(ptr
::read(mem
::transmute(self.end
)))
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl<T
> ExactSizeIterator
for IntoIter
<T
> {}
1725 #[stable(feature = "rust1", since = "1.0.0")]
1726 impl<T
> Drop
for IntoIter
<T
> {
1727 fn drop(&mut self) {
1728 // destroy the remaining elements
1729 for _x
in self.by_ref() {}
1731 // RawVec handles deallocation
1735 /// A draining iterator for `Vec<T>`.
1736 #[unstable(feature = "drain", reason = "recently added")]
1737 pub struct Drain
<'a
, T
: 'a
> {
1738 /// Index of tail to preserve
1742 /// Current remaining range to remove
1743 iter
: slice
::IterMut
<'a
, T
>,
1747 unsafe impl<'a
, T
: Sync
> Sync
for Drain
<'a
, T
> {}
1748 unsafe impl<'a
, T
: Send
> Send
for Drain
<'a
, T
> {}
1750 #[stable(feature = "rust1", since = "1.0.0")]
1751 impl<'a
, T
> Iterator
for Drain
<'a
, T
> {
1755 fn next(&mut self) -> Option
<T
> {
1756 self.iter
.next().map(|elt
|
1758 ptr
::read(elt
as *const _
)
1763 fn size_hint(&self) -> (usize, Option
<usize>) {
1764 self.iter
.size_hint()
1768 #[stable(feature = "rust1", since = "1.0.0")]
1769 impl<'a
, T
> DoubleEndedIterator
for Drain
<'a
, T
> {
1771 fn next_back(&mut self) -> Option
<T
> {
1772 self.iter
.next_back().map(|elt
|
1774 ptr
::read(elt
as *const _
)
1780 #[stable(feature = "rust1", since = "1.0.0")]
1781 impl<'a
, T
> Drop
for Drain
<'a
, T
> {
1782 fn drop(&mut self) {
1783 // exhaust self first
1784 while let Some(_
) = self.next() { }
1786 if self.tail_len
> 0 {
1788 let source_vec
= &mut *self.vec
;
1789 // memmove back untouched tail, update to new length
1790 let start
= source_vec
.len();
1791 let tail
= self.tail_start
;
1792 let src
= source_vec
.as_ptr().offset(tail
as isize);
1793 let dst
= source_vec
.as_mut_ptr().offset(start
as isize);
1794 ptr
::copy(src
, dst
, self.tail_len
);
1795 source_vec
.set_len(start
+ self.tail_len
);
1802 #[stable(feature = "rust1", since = "1.0.0")]
1803 impl<'a
, T
> ExactSizeIterator
for Drain
<'a
, T
> {}
1805 ////////////////////////////////////////////////////////////////////////////////
1806 // Partial vec, used for map_in_place
1807 ////////////////////////////////////////////////////////////////////////////////
1809 /// An owned, partially type-converted vector of elements with non-zero size.
1811 /// `T` and `U` must have the same, non-zero size. They must also have the same
1814 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
1815 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
1816 /// destructed. Additionally the underlying storage of `vec` will be freed.
1817 struct PartialVecNonZeroSized
<T
,U
> {
1825 _marker
: PhantomData
<U
>,
1828 /// An owned, partially type-converted vector of zero-sized elements.
1830 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1832 struct PartialVecZeroSized
<T
,U
> {
1835 marker
: PhantomData
<::core
::cell
::Cell
<(T
,U
)>>,
1838 impl<T
,U
> Drop
for PartialVecNonZeroSized
<T
,U
> {
1839 fn drop(&mut self) {
1841 // `vec` hasn't been modified until now. As it has a length
1842 // currently, this would run destructors of `T`s which might not be
1843 // there. So at first, set `vec`s length to `0`. This must be done
1844 // at first to remain memory-safe as the destructors of `U` or `T`
1845 // might cause unwinding where `vec`s destructor would be executed.
1846 self.vec
.set_len(0);
1848 // We have instances of `U`s and `T`s in `vec`. Destruct them.
1849 while self.start_u
!= self.end_u
{
1850 let _
= ptr
::read(self.start_u
); // Run a `U` destructor.
1851 self.start_u
= self.start_u
.offset(1);
1853 while self.start_t
!= self.end_t
{
1854 let _
= ptr
::read(self.start_t
); // Run a `T` destructor.
1855 self.start_t
= self.start_t
.offset(1);
1857 // After this destructor ran, the destructor of `vec` will run,
1858 // deallocating the underlying memory.
1863 impl<T
,U
> Drop
for PartialVecZeroSized
<T
,U
> {
1864 fn drop(&mut self) {
1866 // Destruct the instances of `T` and `U` this struct owns.
1867 while self.num_t
!= 0 {
1868 let _
: T
= mem
::uninitialized(); // Run a `T` destructor.
1871 while self.num_u
!= 0 {
1872 let _
: U
= mem
::uninitialized(); // Run a `U` destructor.