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, push (to the end) and pop (from the end).
18 //! Explicitly creating a `Vec<T>` with `new()`:
21 //! let xs: Vec<i32> = Vec::new();
24 //! Using the `vec!` macro:
27 //! let ys: Vec<i32> = vec![];
29 //! let zs = vec![1i32, 2, 3, 4, 5];
35 //! let mut xs = vec![1i32, 2];
43 //! let mut xs = vec![1i32, 2];
45 //! let two = xs.pop();
48 #![stable(feature = "rust1", since = "1.0.0")]
52 use alloc::boxed::Box;
53 use alloc::heap::{EMPTY, allocate, reallocate, deallocate};
55 use core::cmp::Ordering;
57 use core::hash::{self, Hash};
58 use core::intrinsics::assume;
59 use core::iter::{repeat, FromIterator};
60 use core::marker::PhantomData;
62 use core::ops::{Index, IndexMut, Deref, Add};
65 use core::ptr::Unique;
70 use borrow::{Cow, IntoCow};
72 use super::range::RangeArgument;
74 // FIXME- fix places which assume the max vector allowed has memory usize::MAX.
75 static MAX_MEMORY_SIZE: usize = isize::MAX as usize;
77 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
82 /// # #![feature(collections)]
83 /// let mut vec = Vec::new();
87 /// assert_eq!(vec.len(), 2);
88 /// assert_eq!(vec[0], 1);
90 /// assert_eq!(vec.pop(), Some(2));
91 /// assert_eq!(vec.len(), 1);
94 /// assert_eq!(vec[0], 7);
96 /// vec.push_all(&[1, 2, 3]);
98 /// for x in vec.iter() {
99 /// println!("{}", x);
101 /// assert_eq!(vec, [7, 1, 2, 3]);
104 /// The `vec!` macro is provided to make initialization more convenient:
107 /// let mut vec = vec![1, 2, 3];
109 /// assert_eq!(vec, [1, 2, 3, 4]);
112 /// Use a `Vec<T>` as an efficient stack:
115 /// let mut stack = Vec::new();
121 /// while let Some(top) = stack.pop() {
122 /// // Prints 3, 2, 1
123 /// println!("{}", top);
127 /// # Capacity and reallocation
129 /// The capacity of a vector is the amount of space allocated for any future
130 /// elements that will be added onto the vector. This is not to be confused with
131 /// the *length* of a vector, which specifies the number of actual elements
132 /// within the vector. If a vector's length exceeds its capacity, its capacity
133 /// will automatically be increased, but its elements will have to be
136 /// For example, a vector with capacity 10 and length 0 would be an empty vector
137 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
138 /// vector will not change its capacity or cause reallocation to occur. However,
139 /// if the vector's length is increased to 11, it will have to reallocate, which
140 /// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
141 /// whenever possible to specify how big the vector is expected to get.
142 #[unsafe_no_drop_flag]
143 #[stable(feature = "rust1", since = "1.0.0")]
150 unsafe impl<T: Send> Send for Vec<T> { }
151 unsafe impl<T: Sync> Sync for Vec<T> { }
153 ////////////////////////////////////////////////////////////////////////////////
155 ////////////////////////////////////////////////////////////////////////////////
158 /// Constructs a new, empty `Vec<T>`.
160 /// The vector will not allocate until elements are pushed onto it.
165 /// let mut vec: Vec<i32> = Vec::new();
168 #[stable(feature = "rust1", since = "1.0.0")]
169 pub fn new() -> Vec<T> {
170 // We want ptr to never be NULL so instead we set it to some arbitrary
171 // non-null value which is fine since we never call deallocate on the ptr
172 // if cap is 0. The reason for this is because the pointer of a slice
173 // being NULL would break the null pointer optimization for enums.
174 unsafe { Vec::from_raw_parts(EMPTY as *mut T, 0, 0) }
177 /// Constructs a new, empty `Vec<T>` with the specified capacity.
179 /// The vector will be able to hold exactly `capacity` elements without reallocating. If
180 /// `capacity` is 0, the vector will not allocate.
182 /// It is important to note that this function does not specify the *length* of the returned
183 /// vector, but only the *capacity*. (For an explanation of the difference between length and
184 /// capacity, see the main `Vec<T>` docs above, 'Capacity and reallocation'.)
189 /// let mut vec = Vec::with_capacity(10);
191 /// // The vector contains no items, even though it has capacity for more
192 /// assert_eq!(vec.len(), 0);
194 /// // These are all done without reallocating...
199 /// // ...but this may make the vector reallocate
203 #[stable(feature = "rust1", since = "1.0.0")]
204 pub fn with_capacity(capacity: usize) -> Vec<T> {
205 if mem::size_of::<T>() == 0 {
206 unsafe { Vec::from_raw_parts(EMPTY as *mut T, 0, usize::MAX) }
207 } else if capacity == 0 {
210 let size = capacity.checked_mul(mem::size_of::<T>())
211 .expect("capacity overflow");
212 let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
213 if ptr.is_null() { ::alloc::oom() }
214 unsafe { Vec::from_raw_parts(ptr as *mut T, 0, capacity) }
218 /// Creates a `Vec<T>` directly from the raw components of another vector.
220 /// This is highly unsafe, due to the number of invariants that aren't checked.
229 /// let mut v = vec![1, 2, 3];
231 /// // Pull out the various important pieces of information about `v`
232 /// let p = v.as_mut_ptr();
233 /// let len = v.len();
234 /// let cap = v.capacity();
237 /// // Cast `v` into the void: no destructor run, so we are in
238 /// // complete control of the allocation to which `p` points.
241 /// // Overwrite memory with 4, 5, 6
242 /// for i in 0..len as isize {
243 /// ptr::write(p.offset(i), 4 + i);
246 /// // Put everything back together into a Vec
247 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
248 /// assert_eq!(rebuilt, [4, 5, 6]);
252 #[stable(feature = "rust1", since = "1.0.0")]
253 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize,
254 capacity: usize) -> Vec<T> {
256 ptr: Unique::new(ptr),
262 /// Creates a vector by copying the elements from a raw pointer.
264 /// This function will copy `elts` contiguous elements starting at `ptr`
265 /// into a new allocation owned by the returned `Vec<T>`. The elements of
266 /// the buffer are copied into the vector without cloning, as if
267 /// `ptr::read()` were called on them.
269 #[unstable(feature = "collections",
270 reason = "may be better expressed via composition")]
271 pub unsafe fn from_raw_buf(ptr: *const T, elts: usize) -> Vec<T> {
272 let mut dst = Vec::with_capacity(elts);
274 ptr::copy_nonoverlapping(ptr, dst.as_mut_ptr(), elts);
278 /// Returns the number of elements the vector can hold without
284 /// let vec: Vec<i32> = Vec::with_capacity(10);
285 /// assert_eq!(vec.capacity(), 10);
288 #[stable(feature = "rust1", since = "1.0.0")]
289 pub fn capacity(&self) -> usize {
293 /// Reserves capacity for at least `additional` more elements to be inserted
294 /// in the given `Vec<T>`. The collection may reserve more space to avoid
295 /// frequent reallocations.
299 /// Panics if the new capacity overflows `usize`.
304 /// let mut vec = vec![1];
306 /// assert!(vec.capacity() >= 11);
308 #[stable(feature = "rust1", since = "1.0.0")]
309 pub fn reserve(&mut self, additional: usize) {
310 if self.cap - self.len < additional {
311 const ERR_MSG: &'static str = "Vec::reserve: `isize` overflow";
313 let new_min_cap = self.len.checked_add(additional).expect(ERR_MSG);
314 if new_min_cap > MAX_MEMORY_SIZE { panic!(ERR_MSG) }
315 self.grow_capacity(match new_min_cap.checked_next_power_of_two() {
316 Some(x) if x > MAX_MEMORY_SIZE => MAX_MEMORY_SIZE,
317 None => MAX_MEMORY_SIZE,
323 /// Reserves the minimum capacity for exactly `additional` more elements to
324 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
327 /// Note that the allocator may give the collection more space than it
328 /// requests. Therefore capacity can not be relied upon to be precisely
329 /// minimal. Prefer `reserve` if future insertions are expected.
333 /// Panics if the new capacity overflows `usize`.
338 /// let mut vec = vec![1];
339 /// vec.reserve_exact(10);
340 /// assert!(vec.capacity() >= 11);
342 #[stable(feature = "rust1", since = "1.0.0")]
343 pub fn reserve_exact(&mut self, additional: usize) {
344 if self.cap - self.len < additional {
345 match self.len.checked_add(additional) {
346 None => panic!("Vec::reserve: `usize` overflow"),
347 Some(new_cap) => self.grow_capacity(new_cap)
352 /// Shrinks the capacity of the vector as much as possible.
354 /// It will drop down as close as possible to the length but the allocator
355 /// may still inform the vector that there is space for a few more elements.
360 /// # #![feature(collections)]
361 /// let mut vec = Vec::with_capacity(10);
362 /// vec.push_all(&[1, 2, 3]);
363 /// assert_eq!(vec.capacity(), 10);
364 /// vec.shrink_to_fit();
365 /// assert!(vec.capacity() >= 3);
367 #[stable(feature = "rust1", since = "1.0.0")]
368 pub fn shrink_to_fit(&mut self) {
369 if mem::size_of::<T>() == 0 { return }
374 dealloc(*self.ptr, self.cap)
378 } else if self.cap != self.len {
380 // Overflow check is unnecessary as the vector is already at
382 let ptr = reallocate(*self.ptr as *mut u8,
383 self.cap * mem::size_of::<T>(),
384 self.len * mem::size_of::<T>(),
385 mem::min_align_of::<T>()) as *mut T;
386 if ptr.is_null() { ::alloc::oom() }
387 self.ptr = Unique::new(ptr);
393 /// Converts the vector into Box<[T]>.
395 /// Note that this will drop any excess capacity. Calling this and
396 /// converting back to a vector with `into_vec()` is equivalent to calling
397 /// `shrink_to_fit()`.
398 #[stable(feature = "rust1", since = "1.0.0")]
399 pub fn into_boxed_slice(mut self) -> Box<[T]> {
400 self.shrink_to_fit();
402 let xs: Box<[T]> = Box::from_raw(&mut *self);
408 /// Shorten a vector, dropping excess elements.
410 /// If `len` is greater than the vector's current length, this has no
416 /// # #![feature(collections)]
417 /// let mut vec = vec![1, 2, 3, 4];
419 /// assert_eq!(vec, [1, 2]);
421 #[stable(feature = "rust1", since = "1.0.0")]
422 pub fn truncate(&mut self, len: usize) {
424 // drop any extra elements
425 while len < self.len {
426 // decrement len before the read(), so a panic on Drop doesn't
427 // re-drop the just-failed value.
429 ptr::read(self.get_unchecked(self.len));
434 /// Extracts a slice containing the entire vector.
436 #[unstable(feature = "convert",
437 reason = "waiting on RFC revision")]
438 pub fn as_slice(&self) -> &[T] {
442 /// Deprecated: use `&mut s[..]` instead.
444 #[unstable(feature = "convert",
445 reason = "waiting on RFC revision")]
446 pub fn as_mut_slice(&mut self) -> &mut [T] {
450 /// Sets the length of a vector.
452 /// This will explicitly set the size of the vector, without actually
453 /// modifying its buffers, so it is up to the caller to ensure that the
454 /// vector is actually the specified size.
459 /// let mut v = vec![1, 2, 3, 4];
465 #[stable(feature = "rust1", since = "1.0.0")]
466 pub unsafe fn set_len(&mut self, len: usize) {
470 /// Removes an element from anywhere in the vector and return it, replacing
471 /// it with the last element.
473 /// This does not preserve ordering, but is O(1).
477 /// Panics if `index` is out of bounds.
482 /// let mut v = vec!["foo", "bar", "baz", "qux"];
484 /// assert_eq!(v.swap_remove(1), "bar");
485 /// assert_eq!(v, ["foo", "qux", "baz"]);
487 /// assert_eq!(v.swap_remove(0), "foo");
488 /// assert_eq!(v, ["baz", "qux"]);
491 #[stable(feature = "rust1", since = "1.0.0")]
492 pub fn swap_remove(&mut self, index: usize) -> T {
493 let length = self.len();
494 self.swap(index, length - 1);
498 /// Inserts an element at position `index` within the vector, shifting all
499 /// elements after position `i` one position to the right.
503 /// Panics if `index` is greater than the vector's length.
508 /// let mut vec = vec![1, 2, 3];
509 /// vec.insert(1, 4);
510 /// assert_eq!(vec, [1, 4, 2, 3]);
511 /// vec.insert(4, 5);
512 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
514 #[stable(feature = "rust1", since = "1.0.0")]
515 pub fn insert(&mut self, index: usize, element: T) {
516 let len = self.len();
517 assert!(index <= len);
518 // space for the new element
521 unsafe { // infallible
522 // The spot to put the new value
524 let p = self.as_mut_ptr().offset(index as isize);
525 // Shift everything over to make space. (Duplicating the
526 // `index`th element into two consecutive places.)
527 ptr::copy(&*p, p.offset(1), len - index);
528 // Write it in, overwriting the first copy of the `index`th
530 ptr::write(&mut *p, element);
532 self.set_len(len + 1);
536 /// Removes and returns the element at position `index` within the vector,
537 /// shifting all elements after position `index` one position to the left.
541 /// Panics if `index` is out of bounds.
546 /// # #![feature(collections)]
547 /// let mut v = vec![1, 2, 3];
548 /// assert_eq!(v.remove(1), 2);
549 /// assert_eq!(v, [1, 3]);
551 #[stable(feature = "rust1", since = "1.0.0")]
552 pub fn remove(&mut self, index: usize) -> T {
553 let len = self.len();
554 assert!(index < len);
555 unsafe { // infallible
558 // the place we are taking from.
559 let ptr = self.as_mut_ptr().offset(index as isize);
560 // copy it out, unsafely having a copy of the value on
561 // the stack and in the vector at the same time.
562 ret = ptr::read(ptr);
564 // Shift everything down to fill in that spot.
565 ptr::copy(&*ptr.offset(1), ptr, len - index - 1);
567 self.set_len(len - 1);
572 /// Retains only the elements specified by the predicate.
574 /// In other words, remove all elements `e` such that `f(&e)` returns false.
575 /// This method operates in place and preserves the order of the retained
581 /// let mut vec = vec![1, 2, 3, 4];
582 /// vec.retain(|&x| x%2 == 0);
583 /// assert_eq!(vec, [2, 4]);
585 #[stable(feature = "rust1", since = "1.0.0")]
586 pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
587 let len = self.len();
601 self.truncate(len - del);
605 /// Appends an element to the back of a collection.
609 /// Panics if the number of elements in the vector overflows a `usize`.
614 /// let mut vec = vec!(1, 2);
616 /// assert_eq!(vec, [1, 2, 3]);
619 #[stable(feature = "rust1", since = "1.0.0")]
620 pub fn push(&mut self, value: T) {
623 fn resize<T>(vec: &mut Vec<T>) {
624 let old_size = vec.cap * mem::size_of::<T>();
625 if old_size >= MAX_MEMORY_SIZE { panic!("capacity overflow") }
626 let mut size = max(old_size, 2 * mem::size_of::<T>()) * 2;
627 if old_size > size || size > MAX_MEMORY_SIZE {
628 size = MAX_MEMORY_SIZE;
631 let ptr = alloc_or_realloc(*vec.ptr, old_size, size);
632 if ptr.is_null() { ::alloc::oom() }
633 vec.ptr = Unique::new(ptr);
635 vec.cap = max(vec.cap, 2) * 2;
638 if mem::size_of::<T>() == 0 {
639 // zero-size types consume no memory, so we can't rely on the
640 // address space running out
641 self.len = self.len.checked_add(1).expect("length overflow");
642 unsafe { mem::forget(value); }
646 if self.len == self.cap {
651 let end = (*self.ptr).offset(self.len as isize);
652 ptr::write(&mut *end, value);
657 /// Removes the last element from a vector and returns it, or `None` if it is empty.
662 /// let mut vec = vec![1, 2, 3];
663 /// assert_eq!(vec.pop(), Some(3));
664 /// assert_eq!(vec, [1, 2]);
667 #[stable(feature = "rust1", since = "1.0.0")]
668 pub fn pop(&mut self) -> Option<T> {
674 Some(ptr::read(self.get_unchecked(self.len())))
679 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
683 /// Panics if the number of elements in the vector overflows a `usize`.
688 /// # #![feature(collections)]
689 /// let mut vec = vec![1, 2, 3];
690 /// let mut vec2 = vec![4, 5, 6];
691 /// vec.append(&mut vec2);
692 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
693 /// assert_eq!(vec2, []);
696 #[unstable(feature = "collections",
697 reason = "new API, waiting for dust to settle")]
698 pub fn append(&mut self, other: &mut Self) {
699 if mem::size_of::<T>() == 0 {
700 // zero-size types consume no memory, so we can't rely on the
701 // address space running out
702 self.len = self.len.checked_add(other.len()).expect("length overflow");
703 unsafe { other.set_len(0) }
706 self.reserve(other.len());
707 let len = self.len();
709 ptr::copy_nonoverlapping(
711 self.get_unchecked_mut(len),
715 self.len += other.len();
716 unsafe { other.set_len(0); }
719 /// Create a draining iterator that removes the specified range in the vector
720 /// and yields the removed items from start to end. The element range is
721 /// removed even if the iterator is not consumed until the end.
723 /// Note: It is unspecified how many elements are removed from the vector,
724 /// if the `Drain` value is leaked.
728 /// Panics if the starting point is greater than the end point or if
729 /// the end point is greater than the length of the vector.
734 /// # #![feature(collections_drain, collections_range)]
736 /// // Draining using `..` clears the whole vector.
737 /// let mut v = vec![1, 2, 3];
738 /// let u: Vec<_> = v.drain(..).collect();
739 /// assert_eq!(v, &[]);
740 /// assert_eq!(u, &[1, 2, 3]);
742 #[unstable(feature = "collections_drain",
743 reason = "recently added, matches RFC")]
744 pub fn drain<R>(&mut self, range: R) -> Drain<T> where R: RangeArgument<usize> {
747 // When the Drain is first created, it shortens the length of
748 // the source vector to make sure no uninitalized or moved-from elements
749 // are accessible at all if the Drain's destructor never gets to run.
751 // Drain will ptr::read out the values to remove.
752 // When finished, remaining tail of the vec is copied back to cover
753 // the hole, and the vector length is restored to the new length.
755 let len = self.len();
756 let start = *range.start().unwrap_or(&0);
757 let end = *range.end().unwrap_or(&len);
758 assert!(start <= end);
762 // set self.vec length's to start, to be safe in case Drain is leaked
764 // Use the borrow in the IterMut to indicate borrowing behavior of the
765 // whole Drain iterator (like &mut T).
766 let range_slice = slice::from_raw_parts_mut(
767 self.as_mut_ptr().offset(start as isize),
772 iter: range_slice.iter_mut(),
778 /// Clears the vector, removing all values.
783 /// let mut v = vec![1, 2, 3];
787 /// assert!(v.is_empty());
790 #[stable(feature = "rust1", since = "1.0.0")]
791 pub fn clear(&mut self) {
795 /// Returns the number of elements in the vector.
800 /// let a = vec![1, 2, 3];
801 /// assert_eq!(a.len(), 3);
804 #[stable(feature = "rust1", since = "1.0.0")]
805 pub fn len(&self) -> usize { self.len }
807 /// Returns `true` if the vector contains no elements.
812 /// let mut v = Vec::new();
813 /// assert!(v.is_empty());
816 /// assert!(!v.is_empty());
818 #[stable(feature = "rust1", since = "1.0.0")]
819 pub fn is_empty(&self) -> bool { self.len() == 0 }
821 /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same
822 /// size and in case they are not zero-sized the same minimal alignment.
826 /// Panics if `T` and `U` have differing sizes or are not zero-sized and
827 /// have differing minimal alignments.
832 /// # #![feature(collections, core)]
833 /// let v = vec![0, 1, 2];
834 /// let w = v.map_in_place(|i| i + 3);
835 /// assert_eq!(&w[..], &[3, 4, 5]);
837 /// #[derive(PartialEq, Debug)]
838 /// struct Newtype(u8);
839 /// let bytes = vec![0x11, 0x22];
840 /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x));
841 /// assert_eq!(&newtyped_bytes[..], &[Newtype(0x11), Newtype(0x22)]);
843 #[unstable(feature = "collections",
844 reason = "API may change to provide stronger guarantees")]
845 pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
846 // FIXME: Assert statically that the types `T` and `U` have the same
848 assert!(mem::size_of::<T>() == mem::size_of::<U>());
852 if mem::size_of::<T>() != 0 {
853 // FIXME: Assert statically that the types `T` and `U` have the
854 // same minimal alignment in case they are not zero-sized.
856 // These asserts are necessary because the `min_align_of` of the
857 // types are passed to the allocator by `Vec`.
858 assert!(mem::min_align_of::<T>() == mem::min_align_of::<U>());
860 // This `as isize` cast is safe, because the size of the elements of the
861 // vector is not 0, and:
863 // 1) If the size of the elements in the vector is 1, the `isize` may
864 // overflow, but it has the correct bit pattern so that the
865 // `.offset()` function will work.
868 // Address space 0x0-0xF.
869 // `u8` array at: 0x1.
870 // Size of `u8` array: 0x8.
871 // Calculated `offset`: -0x8.
872 // After `array.offset(offset)`: 0x9.
873 // (0x1 + 0x8 = 0x1 - 0x8)
875 // 2) If the size of the elements in the vector is >1, the `usize` ->
876 // `isize` conversion can't overflow.
877 let offset = vec.len() as isize;
878 let start = vec.as_mut_ptr();
880 let mut pv = PartialVecNonZeroSized {
884 // This points inside the vector, as the vector has length
886 end_t: unsafe { start.offset(offset) },
887 start_u: start as *mut U,
888 end_u: start as *mut U,
890 _marker: PhantomData,
901 while pv.end_u as *mut T != pv.end_t {
905 // +-+-+-+-+-+-+-+-+-+
906 // |U|...|U|T|T|...|T|
907 // +-+-+-+-+-+-+-+-+-+
911 let t = ptr::read(pv.start_t);
914 // +-+-+-+-+-+-+-+-+-+
915 // |U|...|U|X|T|...|T|
916 // +-+-+-+-+-+-+-+-+-+
919 // We must not panic here, one cell is marked as `T`
920 // although it is not `T`.
922 pv.start_t = pv.start_t.offset(1);
925 // +-+-+-+-+-+-+-+-+-+
926 // |U|...|U|X|T|...|T|
927 // +-+-+-+-+-+-+-+-+-+
930 // We may panic again.
932 // The function given by the user might panic.
935 ptr::write(pv.end_u, u);
938 // +-+-+-+-+-+-+-+-+-+
939 // |U|...|U|U|T|...|T|
940 // +-+-+-+-+-+-+-+-+-+
943 // We should not panic here, because that would leak the `U`
944 // pointed to by `end_u`.
946 pv.end_u = pv.end_u.offset(1);
949 // +-+-+-+-+-+-+-+-+-+
950 // |U|...|U|U|T|...|T|
951 // +-+-+-+-+-+-+-+-+-+
954 // We may panic again.
966 // Extract `vec` and prevent the destructor of
967 // `PartialVecNonZeroSized` from running. Note that none of the
968 // function calls can panic, thus no resources can be leaked (as the
969 // `vec` member of `PartialVec` is the only one which holds
970 // allocations -- and it is returned from this function. None of
973 let vec_len = pv.vec.len();
974 let vec_cap = pv.vec.capacity();
975 let vec_ptr = pv.vec.as_mut_ptr() as *mut U;
977 Vec::from_raw_parts(vec_ptr, vec_len, vec_cap)
980 // Put the `Vec` into the `PartialVecZeroSized` structure and
981 // prevent the destructor of the `Vec` from running. Since the
982 // `Vec` contained zero-sized objects, it did not allocate, so we
983 // are not leaking memory here.
984 let mut pv = PartialVecZeroSized::<T,U> {
989 unsafe { mem::forget(vec); }
991 while pv.num_t != 0 {
993 // Create a `T` out of thin air and decrement `num_t`. This
994 // must not panic between these steps, as otherwise a
995 // destructor of `T` which doesn't exist runs.
996 let t = mem::uninitialized();
999 // The function given by the user might panic.
1002 // Forget the `U` and increment `num_u`. This increment
1003 // cannot overflow the `usize` as we only do this for a
1004 // number of times that fits into a `usize` (and start with
1005 // `0`). Again, we should not panic between these steps.
1010 // Create a `Vec` from our `PartialVecZeroSized` and make sure the
1011 // destructor of the latter will not run. None of this can panic.
1012 let mut result = Vec::new();
1014 result.set_len(pv.num_u);
1021 /// Splits the collection into two at the given index.
1023 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1024 /// and the returned `Self` contains elements `[at, len)`.
1026 /// Note that the capacity of `self` does not change.
1030 /// Panics if `at > len`.
1035 /// # #![feature(collections)]
1036 /// let mut vec = vec![1,2,3];
1037 /// let vec2 = vec.split_off(1);
1038 /// assert_eq!(vec, [1]);
1039 /// assert_eq!(vec2, [2, 3]);
1042 #[unstable(feature = "collections",
1043 reason = "new API, waiting for dust to settle")]
1044 pub fn split_off(&mut self, at: usize) -> Self {
1045 assert!(at <= self.len(), "`at` out of bounds");
1047 let other_len = self.len - at;
1048 let mut other = Vec::with_capacity(other_len);
1050 // Unsafely `set_len` and copy items to `other`.
1053 other.set_len(other_len);
1055 ptr::copy_nonoverlapping(
1056 self.as_ptr().offset(at as isize),
1065 impl<T: Clone> Vec<T> {
1066 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1068 /// Calls either `extend()` or `truncate()` depending on whether `new_len`
1069 /// is larger than the current value of `len()` or not.
1074 /// # #![feature(collections)]
1075 /// let mut vec = vec!["hello"];
1076 /// vec.resize(3, "world");
1077 /// assert_eq!(vec, ["hello", "world", "world"]);
1079 /// let mut vec = vec![1, 2, 3, 4];
1080 /// vec.resize(2, 0);
1081 /// assert_eq!(vec, [1, 2]);
1083 #[unstable(feature = "collections",
1084 reason = "matches collection reform specification; waiting for dust to settle")]
1085 pub fn resize(&mut self, new_len: usize, value: T) {
1086 let len = self.len();
1089 self.extend(repeat(value).take(new_len - len));
1091 self.truncate(new_len);
1095 /// Appends all elements in a slice to the `Vec`.
1097 /// Iterates over the slice `other`, clones each element, and then appends
1098 /// it to this `Vec`. The `other` vector is traversed in-order.
1103 /// # #![feature(collections)]
1104 /// let mut vec = vec![1];
1105 /// vec.push_all(&[2, 3, 4]);
1106 /// assert_eq!(vec, [1, 2, 3, 4]);
1109 #[unstable(feature = "collections",
1110 reason = "likely to be replaced by a more optimized extend")]
1111 pub fn push_all(&mut self, other: &[T]) {
1112 self.reserve(other.len());
1114 for i in 0..other.len() {
1115 let len = self.len();
1117 // Unsafe code so this can be optimised to a memcpy (or something similarly
1118 // fast) when T is Copy. LLVM is easily confused, so any extra operations
1119 // during the loop can prevent this optimisation.
1122 self.get_unchecked_mut(len),
1123 other.get_unchecked(i).clone());
1124 self.set_len(len + 1);
1130 impl<T: PartialEq> Vec<T> {
1131 /// Removes consecutive repeated elements in the vector.
1133 /// If the vector is sorted, this removes all duplicates.
1138 /// let mut vec = vec![1, 2, 2, 3, 2];
1142 /// assert_eq!(vec, [1, 2, 3, 2]);
1144 #[stable(feature = "rust1", since = "1.0.0")]
1145 pub fn dedup(&mut self) {
1147 // Although we have a mutable reference to `self`, we cannot make
1148 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1149 // must ensure that the vector is in a valid state at all time.
1151 // The way that we handle this is by using swaps; we iterate
1152 // over all the elements, swapping as we go so that at the end
1153 // the elements we wish to keep are in the front, and those we
1154 // wish to reject are at the back. We can then truncate the
1155 // vector. This operation is still O(n).
1157 // Example: We start in this state, where `r` represents "next
1158 // read" and `w` represents "next_write`.
1161 // +---+---+---+---+---+---+
1162 // | 0 | 1 | 1 | 2 | 3 | 3 |
1163 // +---+---+---+---+---+---+
1166 // Comparing self[r] against self[w-1], this is not a duplicate, so
1167 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1168 // r and w, leaving us with:
1171 // +---+---+---+---+---+---+
1172 // | 0 | 1 | 1 | 2 | 3 | 3 |
1173 // +---+---+---+---+---+---+
1176 // Comparing self[r] against self[w-1], this value is a duplicate,
1177 // so we increment `r` but leave everything else unchanged:
1180 // +---+---+---+---+---+---+
1181 // | 0 | 1 | 1 | 2 | 3 | 3 |
1182 // +---+---+---+---+---+---+
1185 // Comparing self[r] against self[w-1], this is not a duplicate,
1186 // so swap self[r] and self[w] and advance r and w:
1189 // +---+---+---+---+---+---+
1190 // | 0 | 1 | 2 | 1 | 3 | 3 |
1191 // +---+---+---+---+---+---+
1194 // Not a duplicate, repeat:
1197 // +---+---+---+---+---+---+
1198 // | 0 | 1 | 2 | 3 | 1 | 3 |
1199 // +---+---+---+---+---+---+
1202 // Duplicate, advance r. End of vec. Truncate to w.
1204 let ln = self.len();
1205 if ln < 1 { return; }
1207 // Avoid bounds checks by using unsafe pointers.
1208 let p = self.as_mut_ptr();
1209 let mut r: usize = 1;
1210 let mut w: usize = 1;
1213 let p_r = p.offset(r as isize);
1214 let p_wm1 = p.offset((w - 1) as isize);
1217 let p_w = p_wm1.offset(1);
1218 mem::swap(&mut *p_r, &mut *p_w);
1230 ////////////////////////////////////////////////////////////////////////////////
1231 // Internal methods and functions
1232 ////////////////////////////////////////////////////////////////////////////////
1235 /// Reserves capacity for exactly `capacity` elements in the given vector.
1237 /// If the capacity for `self` is already equal to or greater than the
1238 /// requested capacity, then no action is taken.
1239 fn grow_capacity(&mut self, capacity: usize) {
1240 if mem::size_of::<T>() == 0 { return }
1242 if capacity > self.cap {
1243 let size = capacity.checked_mul(mem::size_of::<T>())
1244 .expect("capacity overflow");
1246 let ptr = alloc_or_realloc(*self.ptr, self.cap * mem::size_of::<T>(), size);
1247 if ptr.is_null() { ::alloc::oom() }
1248 self.ptr = Unique::new(ptr);
1250 self.cap = capacity;
1255 // FIXME: #13996: need a way to mark the return value as `noalias`
1257 unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: usize, size: usize) -> *mut T {
1259 allocate(size, mem::min_align_of::<T>()) as *mut T
1261 reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T
1266 unsafe fn dealloc<T>(ptr: *mut T, len: usize) {
1267 if mem::size_of::<T>() != 0 {
1268 deallocate(ptr as *mut u8,
1269 len * mem::size_of::<T>(),
1270 mem::min_align_of::<T>())
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1278 let mut v = Vec::with_capacity(n);
1279 let mut ptr = v.as_mut_ptr();
1281 // Write all elements except the last one
1283 ptr::write(ptr, Clone::clone(&elem));
1284 ptr = ptr.offset(1);
1285 v.set_len(i); // Increment the length in every step in case Clone::clone() panics
1289 // We can write the last element directly without cloning needlessly
1290 ptr::write(ptr, elem);
1298 ////////////////////////////////////////////////////////////////////////////////
1299 // Common trait implementations for Vec
1300 ////////////////////////////////////////////////////////////////////////////////
1302 #[unstable(feature = "collections")]
1303 impl<T:Clone> Clone for Vec<T> {
1305 fn clone(&self) -> Vec<T> { <[T]>::to_vec(&**self) }
1307 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1308 // required for this method definition, is not available. Instead use the
1309 // `slice::to_vec` function which is only available with cfg(test)
1310 // NB see the slice::hack module in slice.rs for more information
1312 fn clone(&self) -> Vec<T> {
1313 ::slice::to_vec(&**self)
1316 fn clone_from(&mut self, other: &Vec<T>) {
1317 // drop anything in self that will not be overwritten
1318 if self.len() > other.len() {
1319 self.truncate(other.len())
1322 // reuse the contained values' allocations/resources.
1323 for (place, thing) in self.iter_mut().zip(other.iter()) {
1324 place.clone_from(thing)
1327 // self.len <= other.len due to the truncate above, so the
1328 // slice here is always in-bounds.
1329 let slice = &other[self.len()..];
1330 self.push_all(slice);
1334 #[stable(feature = "rust1", since = "1.0.0")]
1335 impl<T: Hash> Hash for Vec<T> {
1337 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1338 Hash::hash(&**self, state)
1342 #[stable(feature = "rust1", since = "1.0.0")]
1343 impl<T> Index<usize> for Vec<T> {
1347 fn index(&self, index: usize) -> &T {
1348 // NB built-in indexing via `&[T]`
1353 #[stable(feature = "rust1", since = "1.0.0")]
1354 impl<T> IndexMut<usize> for Vec<T> {
1356 fn index_mut(&mut self, index: usize) -> &mut T {
1357 // NB built-in indexing via `&mut [T]`
1358 &mut (**self)[index]
1363 #[stable(feature = "rust1", since = "1.0.0")]
1364 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1368 fn index(&self, index: ops::Range<usize>) -> &[T] {
1369 Index::index(&**self, index)
1372 #[stable(feature = "rust1", since = "1.0.0")]
1373 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1377 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1378 Index::index(&**self, index)
1381 #[stable(feature = "rust1", since = "1.0.0")]
1382 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1386 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1387 Index::index(&**self, index)
1390 #[stable(feature = "rust1", since = "1.0.0")]
1391 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1395 fn index(&self, _index: ops::RangeFull) -> &[T] {
1400 #[stable(feature = "rust1", since = "1.0.0")]
1401 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1404 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1405 IndexMut::index_mut(&mut **self, index)
1408 #[stable(feature = "rust1", since = "1.0.0")]
1409 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1412 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1413 IndexMut::index_mut(&mut **self, index)
1416 #[stable(feature = "rust1", since = "1.0.0")]
1417 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1420 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1421 IndexMut::index_mut(&mut **self, index)
1424 #[stable(feature = "rust1", since = "1.0.0")]
1425 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1428 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1433 #[stable(feature = "rust1", since = "1.0.0")]
1434 impl<T> ops::Deref for Vec<T> {
1437 fn deref(&self) -> &[T] {
1440 assume(p != 0 as *mut T);
1441 slice::from_raw_parts(p, self.len)
1446 #[stable(feature = "rust1", since = "1.0.0")]
1447 impl<T> ops::DerefMut for Vec<T> {
1448 fn deref_mut(&mut self) -> &mut [T] {
1450 let ptr = *self.ptr;
1451 assume(!ptr.is_null());
1452 slice::from_raw_parts_mut(ptr, self.len)
1457 #[stable(feature = "rust1", since = "1.0.0")]
1458 impl<T> FromIterator<T> for Vec<T> {
1460 fn from_iter<I: IntoIterator<Item=T>>(iterable: I) -> Vec<T> {
1461 let mut iterator = iterable.into_iter();
1462 let (lower, _) = iterator.size_hint();
1463 let mut vector = Vec::with_capacity(lower);
1465 // This function should be the moral equivalent of:
1467 // for item in iterator {
1468 // vector.push(item);
1471 // This equivalent crucially runs the iterator precisely once. Below we
1472 // actually in theory run the iterator twice (one without bounds checks
1473 // and one with). To achieve the "moral equivalent", we use the `if`
1474 // statement below to break out early.
1476 // If the first loop has terminated, then we have one of two conditions.
1478 // 1. The underlying iterator returned `None`. In this case we are
1479 // guaranteed that less than `vector.capacity()` elements have been
1480 // returned, so we break out early.
1481 // 2. The underlying iterator yielded `vector.capacity()` elements and
1482 // has not yielded `None` yet. In this case we run the iterator to
1484 for element in iterator.by_ref().take(vector.capacity()) {
1485 let len = vector.len();
1487 ptr::write(vector.get_unchecked_mut(len), element);
1488 vector.set_len(len + 1);
1492 if vector.len() == vector.capacity() {
1493 for element in iterator {
1494 vector.push(element);
1501 #[stable(feature = "rust1", since = "1.0.0")]
1502 impl<T> IntoIterator for Vec<T> {
1504 type IntoIter = IntoIter<T>;
1506 /// Creates a consuming iterator, that is, one that moves each value out of
1507 /// the vector (from start to end). The vector cannot be used after calling
1513 /// let v = vec!["a".to_string(), "b".to_string()];
1514 /// for s in v.into_iter() {
1515 /// // s has type String, not &String
1516 /// println!("{}", s);
1520 fn into_iter(self) -> IntoIter<T> {
1522 let ptr = *self.ptr;
1523 assume(!ptr.is_null());
1525 let begin = ptr as *const T;
1526 let end = if mem::size_of::<T>() == 0 {
1527 (ptr as usize + self.len()) as *const T
1529 ptr.offset(self.len() as isize) as *const T
1532 IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end }
1537 #[stable(feature = "rust1", since = "1.0.0")]
1538 impl<'a, T> IntoIterator for &'a Vec<T> {
1540 type IntoIter = slice::Iter<'a, T>;
1542 fn into_iter(self) -> slice::Iter<'a, T> {
1547 #[stable(feature = "rust1", since = "1.0.0")]
1548 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1549 type Item = &'a mut T;
1550 type IntoIter = slice::IterMut<'a, T>;
1552 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1557 #[unstable(feature = "collections", reason = "waiting on Extend stability")]
1558 impl<T> Extend<T> for Vec<T> {
1560 fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
1561 let iterator = iterable.into_iter();
1562 let (lower, _) = iterator.size_hint();
1563 self.reserve(lower);
1564 for element in iterator {
1570 __impl_slice_eq1! { Vec<A>, Vec<B> }
1571 __impl_slice_eq1! { Vec<A>, &'b [B] }
1572 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1573 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1574 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1575 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1577 macro_rules! array_impls {
1580 // NOTE: some less important impls are omitted to reduce code bloat
1581 __impl_slice_eq1! { Vec<A>, [B; $N] }
1582 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1583 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1584 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1585 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1586 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1593 10 11 12 13 14 15 16 17 18 19
1594 20 21 22 23 24 25 26 27 28 29
1598 #[stable(feature = "rust1", since = "1.0.0")]
1599 impl<T: PartialOrd> PartialOrd for Vec<T> {
1601 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1602 PartialOrd::partial_cmp(&**self, &**other)
1606 #[stable(feature = "rust1", since = "1.0.0")]
1607 impl<T: Eq> Eq for Vec<T> {}
1609 #[stable(feature = "rust1", since = "1.0.0")]
1610 impl<T: Ord> Ord for Vec<T> {
1612 fn cmp(&self, other: &Vec<T>) -> Ordering {
1613 Ord::cmp(&**self, &**other)
1617 #[unstable(feature = "collections",
1618 reason = "recent addition, needs more experience")]
1619 impl<'a, T: Clone> Add<&'a [T]> for Vec<T> {
1620 type Output = Vec<T>;
1623 fn add(mut self, rhs: &[T]) -> Vec<T> {
1629 #[unsafe_destructor]
1630 #[stable(feature = "rust1", since = "1.0.0")]
1631 impl<T> Drop for Vec<T> {
1632 fn drop(&mut self) {
1633 // This is (and should always remain) a no-op if the fields are
1634 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1635 if self.cap != 0 && self.cap != mem::POST_DROP_USIZE {
1640 dealloc(*self.ptr, self.cap)
1646 #[stable(feature = "rust1", since = "1.0.0")]
1647 impl<T> Default for Vec<T> {
1648 #[stable(feature = "rust1", since = "1.0.0")]
1649 fn default() -> Vec<T> {
1654 #[stable(feature = "rust1", since = "1.0.0")]
1655 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1656 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1657 fmt::Debug::fmt(&**self, f)
1661 #[stable(feature = "rust1", since = "1.0.0")]
1662 impl<T> AsRef<Vec<T>> for Vec<T> {
1663 fn as_ref(&self) -> &Vec<T> {
1668 #[stable(feature = "rust1", since = "1.0.0")]
1669 impl<T> AsRef<[T]> for Vec<T> {
1670 fn as_ref(&self) -> &[T] {
1675 #[stable(feature = "rust1", since = "1.0.0")]
1676 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1678 fn from(s: &'a [T]) -> Vec<T> {
1682 fn from(s: &'a [T]) -> Vec<T> {
1687 #[stable(feature = "rust1", since = "1.0.0")]
1688 impl<'a> From<&'a str> for Vec<u8> {
1689 fn from(s: &'a str) -> Vec<u8> {
1690 From::from(s.as_bytes())
1694 ////////////////////////////////////////////////////////////////////////////////
1696 ////////////////////////////////////////////////////////////////////////////////
1698 #[unstable(feature = "collections")]
1699 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1700 fn from_iter<I: IntoIterator<Item=T>>(it: I) -> Cow<'a, [T]> {
1701 Cow::Owned(FromIterator::from_iter(it))
1705 impl<'a, T: 'a> IntoCow<'a, [T]> for Vec<T> where T: Clone {
1706 fn into_cow(self) -> Cow<'a, [T]> {
1711 impl<'a, T> IntoCow<'a, [T]> for &'a [T] where T: Clone {
1712 fn into_cow(self) -> Cow<'a, [T]> {
1717 ////////////////////////////////////////////////////////////////////////////////
1719 ////////////////////////////////////////////////////////////////////////////////
1721 /// An iterator that moves out of a vector.
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 pub struct IntoIter<T> {
1724 allocation: *mut T, // the block of memory allocated for the vector
1725 cap: usize, // the capacity of the vector
1730 unsafe impl<T: Send> Send for IntoIter<T> { }
1731 unsafe impl<T: Sync> Sync for IntoIter<T> { }
1733 impl<T> IntoIter<T> {
1735 /// Drops all items that have not yet been moved and returns the empty vector.
1736 #[unstable(feature = "collections")]
1737 pub fn into_inner(mut self) -> Vec<T> {
1739 for _x in self.by_ref() { }
1740 let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
1742 Vec::from_raw_parts(allocation, 0, cap)
1747 #[stable(feature = "rust1", since = "1.0.0")]
1748 impl<T> Iterator for IntoIter<T> {
1752 fn next(&mut self) -> Option<T> {
1754 if self.ptr == self.end {
1757 if mem::size_of::<T>() == 0 {
1758 // purposefully don't use 'ptr.offset' because for
1759 // vectors with 0-size elements this would return the
1761 self.ptr = mem::transmute(self.ptr as usize + 1);
1763 // Use a non-null pointer value
1764 Some(ptr::read(EMPTY as *mut T))
1767 self.ptr = self.ptr.offset(1);
1769 Some(ptr::read(old))
1776 fn size_hint(&self) -> (usize, Option<usize>) {
1777 let diff = (self.end as usize) - (self.ptr as usize);
1778 let size = mem::size_of::<T>();
1779 let exact = diff / (if size == 0 {1} else {size});
1780 (exact, Some(exact))
1784 #[stable(feature = "rust1", since = "1.0.0")]
1785 impl<T> DoubleEndedIterator for IntoIter<T> {
1787 fn next_back(&mut self) -> Option<T> {
1789 if self.end == self.ptr {
1792 if mem::size_of::<T>() == 0 {
1793 // See above for why 'ptr.offset' isn't used
1794 self.end = mem::transmute(self.end as usize - 1);
1796 // Use a non-null pointer value
1797 Some(ptr::read(EMPTY as *mut T))
1799 self.end = self.end.offset(-1);
1801 Some(ptr::read(mem::transmute(self.end)))
1808 #[stable(feature = "rust1", since = "1.0.0")]
1809 impl<T> ExactSizeIterator for IntoIter<T> {}
1811 #[unsafe_destructor]
1812 #[stable(feature = "rust1", since = "1.0.0")]
1813 impl<T> Drop for IntoIter<T> {
1814 fn drop(&mut self) {
1815 // destroy the remaining elements
1817 for _x in self.by_ref() {}
1819 dealloc(self.allocation, self.cap);
1825 /// A draining iterator for `Vec<T>`.
1826 #[unstable(feature = "collections_drain", reason = "recently added")]
1827 pub struct Drain<'a, T: 'a> {
1828 /// Index of tail to preserve
1832 /// Current remaining range to remove
1833 iter: slice::IterMut<'a, T>,
1837 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1838 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1840 #[stable(feature = "rust1", since = "1.0.0")]
1841 impl<'a, T> Iterator for Drain<'a, T> {
1845 fn next(&mut self) -> Option<T> {
1846 self.iter.next().map(|elt|
1848 ptr::read(elt as *const _)
1853 fn size_hint(&self) -> (usize, Option<usize>) {
1854 self.iter.size_hint()
1858 #[stable(feature = "rust1", since = "1.0.0")]
1859 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1861 fn next_back(&mut self) -> Option<T> {
1862 self.iter.next_back().map(|elt|
1864 ptr::read(elt as *const _)
1870 #[unsafe_destructor]
1871 #[stable(feature = "rust1", since = "1.0.0")]
1872 impl<'a, T> Drop for Drain<'a, T> {
1873 fn drop(&mut self) {
1874 // exhaust self first
1875 while let Some(_) = self.next() { }
1877 if self.tail_len > 0 {
1879 let source_vec = &mut *self.vec;
1880 // memmove back untouched tail, update to new length
1881 let start = source_vec.len();
1882 let tail = self.tail_start;
1883 let src = source_vec.as_ptr().offset(tail as isize);
1884 let dst = source_vec.as_mut_ptr().offset(start as isize);
1885 ptr::copy(src, dst, self.tail_len);
1886 source_vec.set_len(start + self.tail_len);
1893 #[stable(feature = "rust1", since = "1.0.0")]
1894 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1896 ////////////////////////////////////////////////////////////////////////////////
1897 // Conversion from &[T] to &Vec<T>
1898 ////////////////////////////////////////////////////////////////////////////////
1900 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1901 #[unstable(feature = "collections")]
1902 pub struct DerefVec<'a, T:'a> {
1904 l: PhantomData<&'a T>,
1907 #[unstable(feature = "collections")]
1908 impl<'a, T> Deref for DerefVec<'a, T> {
1909 type Target = Vec<T>;
1911 fn deref<'b>(&'b self) -> &'b Vec<T> {
1916 // Prevent the inner `Vec<T>` from attempting to deallocate memory.
1917 #[unsafe_destructor]
1918 #[stable(feature = "rust1", since = "1.0.0")]
1919 impl<'a, T> Drop for DerefVec<'a, T> {
1920 fn drop(&mut self) {
1926 /// Converts a slice to a wrapper type providing a `&Vec<T>` reference.
1931 /// # #![feature(collections)]
1932 /// use std::vec::as_vec;
1934 /// // Let's pretend we have a function that requires `&Vec<i32>`
1935 /// fn vec_consumer(s: &Vec<i32>) {
1936 /// assert_eq!(s, &[1, 2, 3]);
1939 /// // Provide a `&Vec<i32>` from a `&[i32]` without allocating
1940 /// let values = [1, 2, 3];
1941 /// vec_consumer(&as_vec(&values));
1943 #[unstable(feature = "collections")]
1944 pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
1947 x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1953 ////////////////////////////////////////////////////////////////////////////////
1954 // Partial vec, used for map_in_place
1955 ////////////////////////////////////////////////////////////////////////////////
1957 /// An owned, partially type-converted vector of elements with non-zero size.
1959 /// `T` and `U` must have the same, non-zero size. They must also have the same
1962 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
1963 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
1964 /// destructed. Additionally the underlying storage of `vec` will be freed.
1965 struct PartialVecNonZeroSized<T,U> {
1973 _marker: PhantomData<U>,
1976 /// An owned, partially type-converted vector of zero-sized elements.
1978 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1980 struct PartialVecZeroSized<T,U> {
1983 marker: PhantomData<::core::cell::Cell<(T,U)>>,
1986 #[unsafe_destructor]
1987 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1988 fn drop(&mut self) {
1990 // `vec` hasn't been modified until now. As it has a length
1991 // currently, this would run destructors of `T`s which might not be
1992 // there. So at first, set `vec`s length to `0`. This must be done
1993 // at first to remain memory-safe as the destructors of `U` or `T`
1994 // might cause unwinding where `vec`s destructor would be executed.
1995 self.vec.set_len(0);
1997 // We have instances of `U`s and `T`s in `vec`. Destruct them.
1998 while self.start_u != self.end_u {
1999 let _ = ptr::read(self.start_u); // Run a `U` destructor.
2000 self.start_u = self.start_u.offset(1);
2002 while self.start_t != self.end_t {
2003 let _ = ptr::read(self.start_t); // Run a `T` destructor.
2004 self.start_t = self.start_t.offset(1);
2006 // After this destructor ran, the destructor of `vec` will run,
2007 // deallocating the underlying memory.
2012 #[unsafe_destructor]
2013 impl<T,U> Drop for PartialVecZeroSized<T,U> {
2014 fn drop(&mut self) {
2016 // Destruct the instances of `T` and `U` this struct owns.
2017 while self.num_t != 0 {
2018 let _: T = mem::uninitialized(); // Run a `T` destructor.
2021 while self.num_u != 0 {
2022 let _: U = mem::uninitialized(); // Run a `U` destructor.