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 pronounced 'vector.'
13 //! Vectors have `O(1)` indexing, push (to the end) and pop (from the end).
17 //! Explicitly creating a `Vec<T>` with `new()`:
20 //! let xs: Vec<i32> = Vec::new();
23 //! Using the `vec!` macro:
26 //! let ys: Vec<i32> = vec![];
28 //! let zs = vec![1i32, 2, 3, 4, 5];
34 //! let mut xs = vec![1i32, 2];
42 //! let mut xs = vec![1i32, 2];
44 //! let two = xs.pop();
47 #![stable(feature = "rust1", since = "1.0.0")]
51 use alloc::boxed::Box;
52 use alloc::heap::{EMPTY, allocate, reallocate, deallocate};
54 use core::cmp::{Ordering};
55 use core::default::Default;
57 use core::hash::{self, Hash};
58 use core::intrinsics::assume;
59 use core::iter::{repeat, FromIterator, IntoIterator};
60 use core::marker::PhantomData;
62 use core::ops::{Index, IndexMut, Deref, Add};
65 use core::ptr::Unique;
69 use borrow::{Cow, IntoCow};
71 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
76 /// let mut vec = Vec::new();
80 /// assert_eq!(vec.len(), 2);
81 /// assert_eq!(vec[0], 1);
83 /// assert_eq!(vec.pop(), Some(2));
84 /// assert_eq!(vec.len(), 1);
87 /// assert_eq!(vec[0], 7);
89 /// vec.push_all(&[1, 2, 3]);
91 /// for x in vec.iter() {
92 /// println!("{}", x);
94 /// assert_eq!(vec, [7, 1, 2, 3]);
97 /// The `vec!` macro is provided to make initialization more convenient:
100 /// let mut vec = vec![1, 2, 3];
102 /// assert_eq!(vec, [1, 2, 3, 4]);
105 /// Use a `Vec<T>` as an efficient stack:
108 /// let mut stack = Vec::new();
115 /// let top = match stack.pop() {
116 /// None => break, // empty
119 /// // Prints 3, 2, 1
120 /// println!("{}", top);
124 /// # Capacity and reallocation
126 /// The capacity of a vector is the amount of space allocated for any future elements that will be
127 /// added onto the vector. This is not to be confused with the *length* of a vector, which
128 /// specifies the number of actual elements within the vector. If a vector's length exceeds its
129 /// capacity, its capacity will automatically be increased, but its elements will have to be
132 /// For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10
133 /// more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or
134 /// cause reallocation to occur. However, if the vector's length is increased to 11, it will have
135 /// to reallocate, which can be slow. For this reason, it is recommended to use
136 /// `Vec::with_capacity` whenever possible to specify how big the vector is expected to get.
137 #[unsafe_no_drop_flag]
138 #[stable(feature = "rust1", since = "1.0.0")]
145 unsafe impl<T: Send> Send for Vec<T> { }
146 unsafe impl<T: Sync> Sync for Vec<T> { }
148 ////////////////////////////////////////////////////////////////////////////////
150 ////////////////////////////////////////////////////////////////////////////////
153 /// Constructs a new, empty `Vec<T>`.
155 /// The vector will not allocate until elements are pushed onto it.
160 /// let mut vec: Vec<i32> = Vec::new();
163 #[stable(feature = "rust1", since = "1.0.0")]
164 pub fn new() -> Vec<T> {
165 // We want ptr to never be NULL so instead we set it to some arbitrary
166 // non-null value which is fine since we never call deallocate on the ptr
167 // if cap is 0. The reason for this is because the pointer of a slice
168 // being NULL would break the null pointer optimization for enums.
169 unsafe { Vec::from_raw_parts(EMPTY as *mut T, 0, 0) }
172 /// Constructs a new, empty `Vec<T>` with the specified capacity.
174 /// The vector will be able to hold exactly `capacity` elements without reallocating. If
175 /// `capacity` is 0, the vector will not allocate.
177 /// It is important to note that this function does not specify the *length* of the returned
178 /// vector, but only the *capacity*. (For an explanation of the difference between length and
179 /// capacity, see the main `Vec<T>` docs above, 'Capacity and reallocation'.)
184 /// let mut vec: Vec<_> = Vec::with_capacity(10);
186 /// // The vector contains no items, even though it has capacity for more
187 /// assert_eq!(vec.len(), 0);
189 /// // These are all done without reallocating...
194 /// // ...but this may make the vector reallocate
198 #[stable(feature = "rust1", since = "1.0.0")]
199 pub fn with_capacity(capacity: usize) -> Vec<T> {
200 if mem::size_of::<T>() == 0 {
201 unsafe { Vec::from_raw_parts(EMPTY as *mut T, 0, usize::MAX) }
202 } else if capacity == 0 {
205 let size = capacity.checked_mul(mem::size_of::<T>())
206 .expect("capacity overflow");
207 let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
208 if ptr.is_null() { ::alloc::oom() }
209 unsafe { Vec::from_raw_parts(ptr as *mut T, 0, capacity) }
213 /// Creates a `Vec<T>` directly from the raw components of another vector.
215 /// This is highly unsafe, due to the number of invariants that aren't checked.
224 /// let mut v = vec![1, 2, 3];
226 /// // Pull out the various important pieces of information about `v`
227 /// let p = v.as_mut_ptr();
228 /// let len = v.len();
229 /// let cap = v.capacity();
232 /// // Cast `v` into the void: no destructor run, so we are in
233 /// // complete control of the allocation to which `p` points.
236 /// // Overwrite memory with 4, 5, 6
237 /// for i in 0..len as isize {
238 /// ptr::write(p.offset(i), 4 + i);
241 /// // Put everything back together into a Vec
242 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
243 /// assert_eq!(rebuilt, [4, 5, 6]);
247 #[stable(feature = "rust1", since = "1.0.0")]
248 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize,
249 capacity: usize) -> Vec<T> {
251 ptr: Unique::new(ptr),
257 /// Creates a vector by copying the elements from a raw pointer.
259 /// This function will copy `elts` contiguous elements starting at `ptr` into a new allocation
260 /// owned by the returned `Vec<T>`. The elements of the buffer are copied into the vector
261 /// without cloning, as if `ptr::read()` were called on them.
263 #[unstable(feature = "collections",
264 reason = "may be better expressed via composition")]
265 pub unsafe fn from_raw_buf(ptr: *const T, elts: usize) -> Vec<T> {
266 let mut dst = Vec::with_capacity(elts);
268 ptr::copy_nonoverlapping(dst.as_mut_ptr(), ptr, elts);
272 /// Returns the number of elements the vector can hold without
278 /// let vec: Vec<i32> = Vec::with_capacity(10);
279 /// assert_eq!(vec.capacity(), 10);
282 #[stable(feature = "rust1", since = "1.0.0")]
283 pub fn capacity(&self) -> usize {
287 /// Reserves capacity for at least `additional` more elements to be inserted in the given
288 /// `Vec<T>`. The collection may reserve more space to avoid frequent reallocations.
292 /// Panics if the new capacity overflows `usize`.
297 /// let mut vec = vec![1];
299 /// assert!(vec.capacity() >= 11);
301 #[stable(feature = "rust1", since = "1.0.0")]
302 pub fn reserve(&mut self, additional: usize) {
303 if self.cap - self.len < additional {
304 let err_msg = "Vec::reserve: `usize` overflow";
305 let new_cap = self.len.checked_add(additional).expect(err_msg)
306 .checked_next_power_of_two().expect(err_msg);
307 self.grow_capacity(new_cap);
311 /// Reserves the minimum capacity for exactly `additional` more elements to
312 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
315 /// Note that the allocator may give the collection more space than it
316 /// requests. Therefore capacity can not be relied upon to be precisely
317 /// minimal. Prefer `reserve` if future insertions are expected.
321 /// Panics if the new capacity overflows `usize`.
326 /// let mut vec = vec![1];
327 /// vec.reserve_exact(10);
328 /// assert!(vec.capacity() >= 11);
330 #[stable(feature = "rust1", since = "1.0.0")]
331 pub fn reserve_exact(&mut self, additional: usize) {
332 if self.cap - self.len < additional {
333 match self.len.checked_add(additional) {
334 None => panic!("Vec::reserve: `usize` overflow"),
335 Some(new_cap) => self.grow_capacity(new_cap)
340 /// Shrinks the capacity of the vector as much as possible.
342 /// It will drop down as close as possible to the length but the allocator
343 /// may still inform the vector that there is space for a few more elements.
348 /// let mut vec = Vec::with_capacity(10);
349 /// vec.push_all(&[1, 2, 3]);
350 /// assert_eq!(vec.capacity(), 10);
351 /// vec.shrink_to_fit();
352 /// assert!(vec.capacity() >= 3);
354 #[stable(feature = "rust1", since = "1.0.0")]
355 pub fn shrink_to_fit(&mut self) {
356 if mem::size_of::<T>() == 0 { return }
361 dealloc(*self.ptr, self.cap)
365 } else if self.cap != self.len {
367 // Overflow check is unnecessary as the vector is already at
369 let ptr = reallocate(*self.ptr as *mut u8,
370 self.cap * mem::size_of::<T>(),
371 self.len * mem::size_of::<T>(),
372 mem::min_align_of::<T>()) as *mut T;
373 if ptr.is_null() { ::alloc::oom() }
374 self.ptr = Unique::new(ptr);
380 /// Convert the vector into Box<[T]>.
382 /// Note that this will drop any excess capacity. Calling this and
383 /// converting back to a vector with `into_vec()` is equivalent to calling
384 /// `shrink_to_fit()`.
385 #[unstable(feature = "collections")]
386 pub fn into_boxed_slice(mut self) -> Box<[T]> {
387 self.shrink_to_fit();
389 let xs: Box<[T]> = Box::from_raw(&mut *self);
395 /// Shorten a vector, dropping excess elements.
397 /// If `len` is greater than the vector's current length, this has no
403 /// let mut vec = vec![1, 2, 3, 4];
405 /// assert_eq!(vec, [1, 2]);
407 #[stable(feature = "rust1", since = "1.0.0")]
408 pub fn truncate(&mut self, len: usize) {
410 // drop any extra elements
411 while len < self.len {
412 // decrement len before the read(), so a panic on Drop doesn't
413 // re-drop the just-failed value.
415 ptr::read(self.get_unchecked(self.len));
420 /// Returns a mutable slice of the elements of `self`.
425 /// fn foo(slice: &mut [i32]) {}
427 /// let mut vec = vec![1, 2];
428 /// foo(vec.as_mut_slice());
431 #[stable(feature = "rust1", since = "1.0.0")]
432 pub fn as_mut_slice(&mut self) -> &mut [T] {
435 assume(!ptr.is_null());
436 slice::from_raw_parts_mut(ptr, self.len)
440 /// Creates a consuming iterator, that is, one that moves each value out of
441 /// the vector (from start to end). The vector cannot be used after calling
447 /// let v = vec!["a".to_string(), "b".to_string()];
448 /// for s in v.into_iter() {
449 /// // s has type String, not &String
450 /// println!("{}", s);
454 #[stable(feature = "rust1", since = "1.0.0")]
455 pub fn into_iter(self) -> IntoIter<T> {
458 assume(!ptr.is_null());
460 let begin = ptr as *const T;
461 let end = if mem::size_of::<T>() == 0 {
462 (ptr as usize + self.len()) as *const T
464 ptr.offset(self.len() as isize) as *const T
467 IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end }
471 /// Sets the length of a vector.
473 /// This will explicitly set the size of the vector, without actually
474 /// modifying its buffers, so it is up to the caller to ensure that the
475 /// vector is actually the specified size.
480 /// let mut v = vec![1, 2, 3, 4];
486 #[stable(feature = "rust1", since = "1.0.0")]
487 pub unsafe fn set_len(&mut self, len: usize) {
491 /// Removes an element from anywhere in the vector and return it, replacing
492 /// it with the last element.
494 /// This does not preserve ordering, but is O(1).
498 /// Panics if `index` is out of bounds.
503 /// let mut v = vec!["foo", "bar", "baz", "qux"];
505 /// assert_eq!(v.swap_remove(1), "bar");
506 /// assert_eq!(v, ["foo", "qux", "baz"]);
508 /// assert_eq!(v.swap_remove(0), "foo");
509 /// assert_eq!(v, ["baz", "qux"]);
512 #[stable(feature = "rust1", since = "1.0.0")]
513 pub fn swap_remove(&mut self, index: usize) -> T {
514 let length = self.len();
515 self.swap(index, length - 1);
519 /// Inserts an element at position `index` within the vector, shifting all
520 /// elements after position `i` one position to the right.
524 /// Panics if `index` is not between `0` and the vector's length (both
525 /// bounds inclusive).
530 /// let mut vec = vec![1, 2, 3];
531 /// vec.insert(1, 4);
532 /// assert_eq!(vec, [1, 4, 2, 3]);
533 /// vec.insert(4, 5);
534 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
536 #[stable(feature = "rust1", since = "1.0.0")]
537 pub fn insert(&mut self, index: usize, element: T) {
538 let len = self.len();
539 assert!(index <= len);
540 // space for the new element
543 unsafe { // infallible
544 // The spot to put the new value
546 let p = self.as_mut_ptr().offset(index as isize);
547 // Shift everything over to make space. (Duplicating the
548 // `index`th element into two consecutive places.)
549 ptr::copy(p.offset(1), &*p, len - index);
550 // Write it in, overwriting the first copy of the `index`th
552 ptr::write(&mut *p, element);
554 self.set_len(len + 1);
558 /// Removes and returns the element at position `index` within the vector,
559 /// shifting all elements after position `index` one position to the left.
563 /// Panics if `i` is out of bounds.
568 /// let mut v = vec![1, 2, 3];
569 /// assert_eq!(v.remove(1), 2);
570 /// assert_eq!(v, [1, 3]);
572 #[stable(feature = "rust1", since = "1.0.0")]
573 pub fn remove(&mut self, index: usize) -> T {
574 let len = self.len();
575 assert!(index < len);
576 unsafe { // infallible
579 // the place we are taking from.
580 let ptr = self.as_mut_ptr().offset(index as isize);
581 // copy it out, unsafely having a copy of the value on
582 // the stack and in the vector at the same time.
583 ret = ptr::read(ptr);
585 // Shift everything down to fill in that spot.
586 ptr::copy(ptr, &*ptr.offset(1), len - index - 1);
588 self.set_len(len - 1);
593 /// Retains only the elements specified by the predicate.
595 /// In other words, remove all elements `e` such that `f(&e)` returns false.
596 /// This method operates in place and preserves the order of the retained
602 /// let mut vec = vec![1, 2, 3, 4];
603 /// vec.retain(|&x| x%2 == 0);
604 /// assert_eq!(vec, [2, 4]);
606 #[stable(feature = "rust1", since = "1.0.0")]
607 pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
608 let len = self.len();
622 self.truncate(len - del);
626 /// Appends an element to the back of a collection.
630 /// Panics if the number of elements in the vector overflows a `usize`.
635 /// let mut vec = vec!(1, 2);
637 /// assert_eq!(vec, [1, 2, 3]);
640 #[stable(feature = "rust1", since = "1.0.0")]
641 pub fn push(&mut self, value: T) {
642 if mem::size_of::<T>() == 0 {
643 // zero-size types consume no memory, so we can't rely on the
644 // address space running out
645 self.len = self.len.checked_add(1).expect("length overflow");
646 unsafe { mem::forget(value); }
649 if self.len == self.cap {
650 let old_size = self.cap * mem::size_of::<T>();
651 let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
652 if old_size > size { panic!("capacity overflow") }
654 let ptr = alloc_or_realloc(*self.ptr, old_size, size);
655 if ptr.is_null() { ::alloc::oom() }
656 self.ptr = Unique::new(ptr);
658 self.cap = max(self.cap, 2) * 2;
662 let end = (*self.ptr).offset(self.len as isize);
663 ptr::write(&mut *end, value);
668 /// Removes the last element from a vector and returns it, or `None` if it is empty.
673 /// let mut vec = vec![1, 2, 3];
674 /// assert_eq!(vec.pop(), Some(3));
675 /// assert_eq!(vec, [1, 2]);
678 #[stable(feature = "rust1", since = "1.0.0")]
679 pub fn pop(&mut self) -> Option<T> {
685 Some(ptr::read(self.get_unchecked(self.len())))
690 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
694 /// Panics if the number of elements in the vector overflows a `usize`.
699 /// let mut vec = vec![1, 2, 3];
700 /// let mut vec2 = vec![4, 5, 6];
701 /// vec.append(&mut vec2);
702 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
703 /// assert_eq!(vec2, []);
706 #[unstable(feature = "collections",
707 reason = "new API, waiting for dust to settle")]
708 pub fn append(&mut self, other: &mut Self) {
709 if mem::size_of::<T>() == 0 {
710 // zero-size types consume no memory, so we can't rely on the
711 // address space running out
712 self.len = self.len.checked_add(other.len()).expect("length overflow");
713 unsafe { other.set_len(0) }
716 self.reserve(other.len());
717 let len = self.len();
719 ptr::copy_nonoverlapping(
720 self.get_unchecked_mut(len),
725 self.len += other.len();
726 unsafe { other.set_len(0); }
729 /// Creates a draining iterator that clears the `Vec` and iterates over
730 /// the removed items from start to end.
735 /// let mut v = vec!["a".to_string(), "b".to_string()];
736 /// for s in v.drain() {
737 /// // s has type String, not &String
738 /// println!("{}", s);
740 /// assert!(v.is_empty());
743 #[unstable(feature = "collections",
744 reason = "matches collection reform specification, waiting for dust to settle")]
745 pub fn drain(&mut self) -> Drain<T> {
747 let begin = *self.ptr as *const T;
748 let end = if mem::size_of::<T>() == 0 {
749 (*self.ptr as usize + self.len()) as *const T
751 (*self.ptr).offset(self.len() as isize) as *const T
762 /// Clears the vector, removing all values.
767 /// let mut v = vec![1, 2, 3];
771 /// assert!(v.is_empty());
774 #[stable(feature = "rust1", since = "1.0.0")]
775 pub fn clear(&mut self) {
779 /// Returns the number of elements in the vector.
784 /// let a = vec![1, 2, 3];
785 /// assert_eq!(a.len(), 3);
788 #[stable(feature = "rust1", since = "1.0.0")]
789 pub fn len(&self) -> usize { self.len }
791 /// Returns `true` if the vector contains no elements.
796 /// let mut v = Vec::new();
797 /// assert!(v.is_empty());
800 /// assert!(!v.is_empty());
802 #[stable(feature = "rust1", since = "1.0.0")]
803 pub fn is_empty(&self) -> bool { self.len() == 0 }
805 /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same
806 /// size and in case they are not zero-sized the same minimal alignment.
810 /// Panics if `T` and `U` have differing sizes or are not zero-sized and
811 /// have differing minimal alignments.
816 /// let v = vec![0, 1, 2];
817 /// let w = v.map_in_place(|i| i + 3);
818 /// assert_eq!(w.as_slice(), [3, 4, 5].as_slice());
820 /// #[derive(PartialEq, Debug)]
821 /// struct Newtype(u8);
822 /// let bytes = vec![0x11, 0x22];
823 /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x));
824 /// assert_eq!(newtyped_bytes.as_slice(), [Newtype(0x11), Newtype(0x22)].as_slice());
826 #[unstable(feature = "collections",
827 reason = "API may change to provide stronger guarantees")]
828 pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
829 // FIXME: Assert statically that the types `T` and `U` have the same
831 assert!(mem::size_of::<T>() == mem::size_of::<U>());
835 if mem::size_of::<T>() != 0 {
836 // FIXME: Assert statically that the types `T` and `U` have the
837 // same minimal alignment in case they are not zero-sized.
839 // These asserts are necessary because the `min_align_of` of the
840 // types are passed to the allocator by `Vec`.
841 assert!(mem::min_align_of::<T>() == mem::min_align_of::<U>());
843 // This `as isize` cast is safe, because the size of the elements of the
844 // vector is not 0, and:
846 // 1) If the size of the elements in the vector is 1, the `isize` may
847 // overflow, but it has the correct bit pattern so that the
848 // `.offset()` function will work.
851 // Address space 0x0-0xF.
852 // `u8` array at: 0x1.
853 // Size of `u8` array: 0x8.
854 // Calculated `offset`: -0x8.
855 // After `array.offset(offset)`: 0x9.
856 // (0x1 + 0x8 = 0x1 - 0x8)
858 // 2) If the size of the elements in the vector is >1, the `usize` ->
859 // `isize` conversion can't overflow.
860 let offset = vec.len() as isize;
861 let start = vec.as_mut_ptr();
863 let mut pv = PartialVecNonZeroSized {
867 // This points inside the vector, as the vector has length
869 end_t: unsafe { start.offset(offset) },
870 start_u: start as *mut U,
871 end_u: start as *mut U,
873 _marker: PhantomData,
884 while pv.end_u as *mut T != pv.end_t {
888 // +-+-+-+-+-+-+-+-+-+
889 // |U|...|U|T|T|...|T|
890 // +-+-+-+-+-+-+-+-+-+
894 let t = ptr::read(pv.start_t);
897 // +-+-+-+-+-+-+-+-+-+
898 // |U|...|U|X|T|...|T|
899 // +-+-+-+-+-+-+-+-+-+
902 // We must not panic here, one cell is marked as `T`
903 // although it is not `T`.
905 pv.start_t = pv.start_t.offset(1);
908 // +-+-+-+-+-+-+-+-+-+
909 // |U|...|U|X|T|...|T|
910 // +-+-+-+-+-+-+-+-+-+
913 // We may panic again.
915 // The function given by the user might panic.
918 ptr::write(pv.end_u, u);
921 // +-+-+-+-+-+-+-+-+-+
922 // |U|...|U|U|T|...|T|
923 // +-+-+-+-+-+-+-+-+-+
926 // We should not panic here, because that would leak the `U`
927 // pointed to by `end_u`.
929 pv.end_u = pv.end_u.offset(1);
932 // +-+-+-+-+-+-+-+-+-+
933 // |U|...|U|U|T|...|T|
934 // +-+-+-+-+-+-+-+-+-+
937 // We may panic again.
949 // Extract `vec` and prevent the destructor of
950 // `PartialVecNonZeroSized` from running. Note that none of the
951 // function calls can panic, thus no resources can be leaked (as the
952 // `vec` member of `PartialVec` is the only one which holds
953 // allocations -- and it is returned from this function. None of
956 let vec_len = pv.vec.len();
957 let vec_cap = pv.vec.capacity();
958 let vec_ptr = pv.vec.as_mut_ptr() as *mut U;
960 Vec::from_raw_parts(vec_ptr, vec_len, vec_cap)
963 // Put the `Vec` into the `PartialVecZeroSized` structure and
964 // prevent the destructor of the `Vec` from running. Since the
965 // `Vec` contained zero-sized objects, it did not allocate, so we
966 // are not leaking memory here.
967 let mut pv = PartialVecZeroSized::<T,U> {
972 unsafe { mem::forget(vec); }
974 while pv.num_t != 0 {
976 // Create a `T` out of thin air and decrement `num_t`. This
977 // must not panic between these steps, as otherwise a
978 // destructor of `T` which doesn't exist runs.
979 let t = mem::uninitialized();
982 // The function given by the user might panic.
985 // Forget the `U` and increment `num_u`. This increment
986 // cannot overflow the `usize` as we only do this for a
987 // number of times that fits into a `usize` (and start with
988 // `0`). Again, we should not panic between these steps.
993 // Create a `Vec` from our `PartialVecZeroSized` and make sure the
994 // destructor of the latter will not run. None of this can panic.
995 let mut result = Vec::new();
997 result.set_len(pv.num_u);
1004 /// Splits the collection into two at the given index.
1006 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1007 /// and the returned `Self` contains elements `[at, len)`.
1009 /// Note that the capacity of `self` does not change.
1013 /// Panics if `at > len`.
1018 /// let mut vec = vec![1,2,3];
1019 /// let vec2 = vec.split_off(1);
1020 /// assert_eq!(vec, [1]);
1021 /// assert_eq!(vec2, [2, 3]);
1024 #[unstable(feature = "collections",
1025 reason = "new API, waiting for dust to settle")]
1026 pub fn split_off(&mut self, at: usize) -> Self {
1027 assert!(at <= self.len(), "`at` out of bounds");
1029 let other_len = self.len - at;
1030 let mut other = Vec::with_capacity(other_len);
1032 // Unsafely `set_len` and copy items to `other`.
1035 other.set_len(other_len);
1037 ptr::copy_nonoverlapping(
1039 self.as_ptr().offset(at as isize),
1047 impl<T: Clone> Vec<T> {
1048 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1050 /// Calls either `extend()` or `truncate()` depending on whether `new_len`
1051 /// is larger than the current value of `len()` or not.
1056 /// let mut vec = vec!["hello"];
1057 /// vec.resize(3, "world");
1058 /// assert_eq!(vec, ["hello", "world", "world"]);
1060 /// let mut vec = vec![1, 2, 3, 4];
1061 /// vec.resize(2, 0);
1062 /// assert_eq!(vec, [1, 2]);
1064 #[unstable(feature = "collections",
1065 reason = "matches collection reform specification; waiting for dust to settle")]
1066 pub fn resize(&mut self, new_len: usize, value: T) {
1067 let len = self.len();
1070 self.extend(repeat(value).take(new_len - len));
1072 self.truncate(new_len);
1076 /// Appends all elements in a slice to the `Vec`.
1078 /// Iterates over the slice `other`, clones each element, and then appends
1079 /// it to this `Vec`. The `other` vector is traversed in-order.
1084 /// let mut vec = vec![1];
1085 /// vec.push_all(&[2, 3, 4]);
1086 /// assert_eq!(vec, [1, 2, 3, 4]);
1089 #[unstable(feature = "collections",
1090 reason = "likely to be replaced by a more optimized extend")]
1091 pub fn push_all(&mut self, other: &[T]) {
1092 self.reserve(other.len());
1094 for i in 0..other.len() {
1095 let len = self.len();
1097 // Unsafe code so this can be optimised to a memcpy (or something similarly
1098 // fast) when T is Copy. LLVM is easily confused, so any extra operations
1099 // during the loop can prevent this optimisation.
1102 self.get_unchecked_mut(len),
1103 other.get_unchecked(i).clone());
1104 self.set_len(len + 1);
1110 impl<T: PartialEq> Vec<T> {
1111 /// Removes consecutive repeated elements in the vector.
1113 /// If the vector is sorted, this removes all duplicates.
1118 /// let mut vec = vec![1, 2, 2, 3, 2];
1122 /// assert_eq!(vec, [1, 2, 3, 2]);
1124 #[stable(feature = "rust1", since = "1.0.0")]
1125 pub fn dedup(&mut self) {
1127 // Although we have a mutable reference to `self`, we cannot make
1128 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1129 // must ensure that the vector is in a valid state at all time.
1131 // The way that we handle this is by using swaps; we iterate
1132 // over all the elements, swapping as we go so that at the end
1133 // the elements we wish to keep are in the front, and those we
1134 // wish to reject are at the back. We can then truncate the
1135 // vector. This operation is still O(n).
1137 // Example: We start in this state, where `r` represents "next
1138 // read" and `w` represents "next_write`.
1141 // +---+---+---+---+---+---+
1142 // | 0 | 1 | 1 | 2 | 3 | 3 |
1143 // +---+---+---+---+---+---+
1146 // Comparing self[r] against self[w-1], this is not a duplicate, so
1147 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1148 // r and w, leaving us with:
1151 // +---+---+---+---+---+---+
1152 // | 0 | 1 | 1 | 2 | 3 | 3 |
1153 // +---+---+---+---+---+---+
1156 // Comparing self[r] against self[w-1], this value is a duplicate,
1157 // so we increment `r` but leave everything else unchanged:
1160 // +---+---+---+---+---+---+
1161 // | 0 | 1 | 1 | 2 | 3 | 3 |
1162 // +---+---+---+---+---+---+
1165 // Comparing self[r] against self[w-1], this is not a duplicate,
1166 // so swap self[r] and self[w] and advance r and w:
1169 // +---+---+---+---+---+---+
1170 // | 0 | 1 | 2 | 1 | 3 | 3 |
1171 // +---+---+---+---+---+---+
1174 // Not a duplicate, repeat:
1177 // +---+---+---+---+---+---+
1178 // | 0 | 1 | 2 | 3 | 1 | 3 |
1179 // +---+---+---+---+---+---+
1182 // Duplicate, advance r. End of vec. Truncate to w.
1184 let ln = self.len();
1185 if ln < 1 { return; }
1187 // Avoid bounds checks by using unsafe pointers.
1188 let p = self.as_mut_ptr();
1193 let p_r = p.offset(r as isize);
1194 let p_wm1 = p.offset((w - 1) as isize);
1197 let p_w = p_wm1.offset(1);
1198 mem::swap(&mut *p_r, &mut *p_w);
1210 ////////////////////////////////////////////////////////////////////////////////
1211 // Internal methods and functions
1212 ////////////////////////////////////////////////////////////////////////////////
1215 /// Reserves capacity for exactly `capacity` elements in the given vector.
1217 /// If the capacity for `self` is already equal to or greater than the
1218 /// requested capacity, then no action is taken.
1219 fn grow_capacity(&mut self, capacity: usize) {
1220 if mem::size_of::<T>() == 0 { return }
1222 if capacity > self.cap {
1223 let size = capacity.checked_mul(mem::size_of::<T>())
1224 .expect("capacity overflow");
1226 let ptr = alloc_or_realloc(*self.ptr, self.cap * mem::size_of::<T>(), size);
1227 if ptr.is_null() { ::alloc::oom() }
1228 self.ptr = Unique::new(ptr);
1230 self.cap = capacity;
1235 // FIXME: #13996: need a way to mark the return value as `noalias`
1237 unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: usize, size: usize) -> *mut T {
1239 allocate(size, mem::min_align_of::<T>()) as *mut T
1241 reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T
1246 unsafe fn dealloc<T>(ptr: *mut T, len: usize) {
1247 if mem::size_of::<T>() != 0 {
1248 deallocate(ptr as *mut u8,
1249 len * mem::size_of::<T>(),
1250 mem::min_align_of::<T>())
1255 #[stable(feature = "rust1", since = "1.0.0")]
1256 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1258 let mut v = Vec::with_capacity(n);
1259 let mut ptr = v.as_mut_ptr();
1261 // Write all elements except the last one
1263 ptr::write(ptr, Clone::clone(&elem));
1264 ptr = ptr.offset(1);
1265 v.set_len(i); // Increment the length in every step in case Clone::clone() panics
1269 // We can write the last element directly without cloning needlessly
1270 ptr::write(ptr, elem);
1278 ////////////////////////////////////////////////////////////////////////////////
1279 // Common trait implementations for Vec
1280 ////////////////////////////////////////////////////////////////////////////////
1282 #[unstable(feature = "collections")]
1283 impl<T:Clone> Clone for Vec<T> {
1285 fn clone(&self) -> Vec<T> { <[T]>::to_vec(&**self) }
1287 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1288 // required for this method definition, is not available. Instead use the
1289 // `slice::to_vec` function which is only available with cfg(test)
1290 // NB see the slice::hack module in slice.rs for more information
1292 fn clone(&self) -> Vec<T> {
1293 ::slice::to_vec(&**self)
1296 fn clone_from(&mut self, other: &Vec<T>) {
1297 // drop anything in self that will not be overwritten
1298 if self.len() > other.len() {
1299 self.truncate(other.len())
1302 // reuse the contained values' allocations/resources.
1303 for (place, thing) in self.iter_mut().zip(other.iter()) {
1304 place.clone_from(thing)
1307 // self.len <= other.len due to the truncate above, so the
1308 // slice here is always in-bounds.
1309 let slice = &other[self.len()..];
1310 self.push_all(slice);
1314 #[stable(feature = "rust1", since = "1.0.0")]
1315 impl<T: Hash> Hash for Vec<T> {
1317 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1318 Hash::hash(&**self, state)
1322 #[stable(feature = "rust1", since = "1.0.0")]
1323 impl<T> Index<usize> for Vec<T> {
1329 fn index(&self, index: &usize) -> &T {
1330 // NB built-in indexing via `&[T]`
1336 fn index(&self, index: usize) -> &T {
1337 // NB built-in indexing via `&[T]`
1342 #[stable(feature = "rust1", since = "1.0.0")]
1343 impl<T> IndexMut<usize> for Vec<T> {
1347 fn index_mut(&mut self, index: &usize) -> &mut T {
1348 // NB built-in indexing via `&mut [T]`
1349 &mut (**self)[*index]
1354 fn index_mut(&mut self, index: usize) -> &mut T {
1355 // NB built-in indexing via `&mut [T]`
1356 &mut (**self)[index]
1361 #[stable(feature = "rust1", since = "1.0.0")]
1362 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1367 fn index(&self, index: &ops::Range<usize>) -> &[T] {
1368 Index::index(&**self, index)
1373 fn index(&self, index: ops::Range<usize>) -> &[T] {
1374 Index::index(&**self, index)
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1383 fn index(&self, index: &ops::RangeTo<usize>) -> &[T] {
1384 Index::index(&**self, index)
1389 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1390 Index::index(&**self, index)
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1399 fn index(&self, index: &ops::RangeFrom<usize>) -> &[T] {
1400 Index::index(&**self, index)
1405 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1406 Index::index(&**self, index)
1409 #[stable(feature = "rust1", since = "1.0.0")]
1410 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1415 fn index(&self, _index: &ops::RangeFull) -> &[T] {
1421 fn index(&self, _index: ops::RangeFull) -> &[T] {
1426 #[stable(feature = "rust1", since = "1.0.0")]
1427 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1431 fn index_mut(&mut self, index: &ops::Range<usize>) -> &mut [T] {
1432 IndexMut::index_mut(&mut **self, index)
1437 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1438 IndexMut::index_mut(&mut **self, index)
1441 #[stable(feature = "rust1", since = "1.0.0")]
1442 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1446 fn index_mut(&mut self, index: &ops::RangeTo<usize>) -> &mut [T] {
1447 IndexMut::index_mut(&mut **self, index)
1452 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1453 IndexMut::index_mut(&mut **self, index)
1456 #[stable(feature = "rust1", since = "1.0.0")]
1457 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1461 fn index_mut(&mut self, index: &ops::RangeFrom<usize>) -> &mut [T] {
1462 IndexMut::index_mut(&mut **self, index)
1467 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1468 IndexMut::index_mut(&mut **self, index)
1471 #[stable(feature = "rust1", since = "1.0.0")]
1472 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1476 fn index_mut(&mut self, _index: &ops::RangeFull) -> &mut [T] {
1482 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1487 #[stable(feature = "rust1", since = "1.0.0")]
1488 impl<T> ops::Deref for Vec<T> {
1491 fn deref(&self) -> &[T] {
1494 assume(p != 0 as *mut T);
1495 slice::from_raw_parts(p, self.len)
1500 #[stable(feature = "rust1", since = "1.0.0")]
1501 impl<T> ops::DerefMut for Vec<T> {
1502 fn deref_mut(&mut self) -> &mut [T] { self.as_mut_slice() }
1505 #[stable(feature = "rust1", since = "1.0.0")]
1506 impl<T> FromIterator<T> for Vec<T> {
1508 fn from_iter<I: IntoIterator<Item=T>>(iterable: I) -> Vec<T> {
1509 let mut iterator = iterable.into_iter();
1510 let (lower, _) = iterator.size_hint();
1511 let mut vector = Vec::with_capacity(lower);
1513 // This function should be the moral equivalent of:
1515 // for item in iterator {
1516 // vector.push(item);
1519 // This equivalent crucially runs the iterator precisely once. Below we
1520 // actually in theory run the iterator twice (one without bounds checks
1521 // and one with). To achieve the "moral equivalent", we use the `if`
1522 // statement below to break out early.
1524 // If the first loop has terminated, then we have one of two conditions.
1526 // 1. The underlying iterator returned `None`. In this case we are
1527 // guaranteed that less than `vector.capacity()` elements have been
1528 // returned, so we break out early.
1529 // 2. The underlying iterator yielded `vector.capacity()` elements and
1530 // has not yielded `None` yet. In this case we run the iterator to
1532 for element in iterator.by_ref().take(vector.capacity()) {
1533 let len = vector.len();
1535 ptr::write(vector.get_unchecked_mut(len), element);
1536 vector.set_len(len + 1);
1540 if vector.len() == vector.capacity() {
1541 for element in iterator {
1542 vector.push(element);
1549 #[stable(feature = "rust1", since = "1.0.0")]
1550 impl<T> IntoIterator for Vec<T> {
1552 type IntoIter = IntoIter<T>;
1554 fn into_iter(self) -> IntoIter<T> {
1559 #[stable(feature = "rust1", since = "1.0.0")]
1560 impl<'a, T> IntoIterator for &'a Vec<T> {
1562 type IntoIter = slice::Iter<'a, T>;
1564 fn into_iter(self) -> slice::Iter<'a, T> {
1569 #[stable(feature = "rust1", since = "1.0.0")]
1570 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1571 type Item = &'a mut T;
1572 type IntoIter = slice::IterMut<'a, T>;
1574 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1579 #[unstable(feature = "collections", reason = "waiting on Extend stability")]
1580 impl<T> Extend<T> for Vec<T> {
1582 fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
1583 let iterator = iterable.into_iter();
1584 let (lower, _) = iterator.size_hint();
1585 self.reserve(lower);
1586 for element in iterator {
1592 __impl_slice_eq1! { Vec<A>, Vec<B> }
1593 __impl_slice_eq2! { Vec<A>, &'b [B] }
1594 __impl_slice_eq2! { Vec<A>, &'b mut [B] }
1595 __impl_slice_eq2! { Cow<'a, [A]>, &'b [B], Clone }
1596 __impl_slice_eq2! { Cow<'a, [A]>, &'b mut [B], Clone }
1597 __impl_slice_eq2! { Cow<'a, [A]>, Vec<B>, Clone }
1599 macro_rules! array_impls {
1602 // NOTE: some less important impls are omitted to reduce code bloat
1603 __impl_slice_eq2! { Vec<A>, [B; $N] }
1604 __impl_slice_eq2! { Vec<A>, &'b [B; $N] }
1605 // __impl_slice_eq2! { Vec<A>, &'b mut [B; $N] }
1606 // __impl_slice_eq2! { Cow<'a, [A]>, [B; $N], Clone }
1607 // __impl_slice_eq2! { Cow<'a, [A]>, &'b [B; $N], Clone }
1608 // __impl_slice_eq2! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1615 10 11 12 13 14 15 16 17 18 19
1616 20 21 22 23 24 25 26 27 28 29
1620 #[stable(feature = "rust1", since = "1.0.0")]
1621 impl<T: PartialOrd> PartialOrd for Vec<T> {
1623 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1624 PartialOrd::partial_cmp(&**self, &**other)
1628 #[stable(feature = "rust1", since = "1.0.0")]
1629 impl<T: Eq> Eq for Vec<T> {}
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 impl<T: Ord> Ord for Vec<T> {
1634 fn cmp(&self, other: &Vec<T>) -> Ordering {
1635 Ord::cmp(&**self, &**other)
1639 #[allow(deprecated)]
1640 impl<T> AsSlice<T> for Vec<T> {
1641 /// Returns a slice into `self`.
1646 /// fn foo(slice: &[i32]) {}
1648 /// let vec = vec![1, 2];
1649 /// foo(vec.as_slice());
1652 #[stable(feature = "rust1", since = "1.0.0")]
1653 fn as_slice(&self) -> &[T] {
1658 #[unstable(feature = "collections",
1659 reason = "recent addition, needs more experience")]
1660 impl<'a, T: Clone> Add<&'a [T]> for Vec<T> {
1661 type Output = Vec<T>;
1664 fn add(mut self, rhs: &[T]) -> Vec<T> {
1670 #[unsafe_destructor]
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<T> Drop for Vec<T> {
1673 fn drop(&mut self) {
1674 // This is (and should always remain) a no-op if the fields are
1675 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1681 dealloc(*self.ptr, self.cap)
1687 #[stable(feature = "rust1", since = "1.0.0")]
1688 impl<T> Default for Vec<T> {
1689 #[stable(feature = "rust1", since = "1.0.0")]
1690 fn default() -> Vec<T> {
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1697 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1698 fmt::Debug::fmt(&**self, f)
1702 #[stable(feature = "rust1", since = "1.0.0")]
1703 impl<T> AsRef<Vec<T>> for Vec<T> {
1704 fn as_ref(&self) -> &Vec<T> {
1709 #[stable(feature = "rust1", since = "1.0.0")]
1710 impl<T> Into<Vec<T>> for Vec<T> {
1711 fn into(self) -> Vec<T> {
1716 #[stable(feature = "rust1", since = "1.0.0")]
1717 impl<T> AsRef<[T]> for Vec<T> {
1718 fn as_ref(&self) -> &[T] {
1723 #[stable(feature = "rust1", since = "1.0.0")]
1724 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1725 fn from(s: &'a [T]) -> Vec<T> {
1730 #[stable(feature = "rust1", since = "1.0.0")]
1731 impl<'a> From<&'a str> for Vec<u8> {
1732 fn from(s: &'a str) -> Vec<u8> {
1733 s.as_bytes().to_vec()
1737 ////////////////////////////////////////////////////////////////////////////////
1739 ////////////////////////////////////////////////////////////////////////////////
1741 /// A clone-on-write vector
1742 #[deprecated(since = "1.0.0", reason = "use Cow<'a, [T]> instead")]
1743 #[unstable(feature = "collections")]
1744 pub type CowVec<'a, T> = Cow<'a, [T]>;
1746 #[unstable(feature = "collections")]
1747 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1748 fn from_iter<I: IntoIterator<Item=T>>(it: I) -> Cow<'a, [T]> {
1749 Cow::Owned(FromIterator::from_iter(it))
1753 impl<'a, T: 'a> IntoCow<'a, [T]> for Vec<T> where T: Clone {
1754 fn into_cow(self) -> Cow<'a, [T]> {
1759 impl<'a, T> IntoCow<'a, [T]> for &'a [T] where T: Clone {
1760 fn into_cow(self) -> Cow<'a, [T]> {
1765 ////////////////////////////////////////////////////////////////////////////////
1767 ////////////////////////////////////////////////////////////////////////////////
1769 /// An iterator that moves out of a vector.
1770 #[stable(feature = "rust1", since = "1.0.0")]
1771 pub struct IntoIter<T> {
1772 allocation: *mut T, // the block of memory allocated for the vector
1773 cap: usize, // the capacity of the vector
1778 unsafe impl<T: Send> Send for IntoIter<T> { }
1779 unsafe impl<T: Sync> Sync for IntoIter<T> { }
1781 impl<T> IntoIter<T> {
1783 /// Drops all items that have not yet been moved and returns the empty vector.
1784 #[unstable(feature = "collections")]
1785 pub fn into_inner(mut self) -> Vec<T> {
1787 for _x in self.by_ref() { }
1788 let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
1790 Vec::from_raw_parts(allocation, 0, cap)
1795 #[stable(feature = "rust1", since = "1.0.0")]
1796 impl<T> Iterator for IntoIter<T> {
1800 fn next(&mut self) -> Option<T> {
1802 if self.ptr == self.end {
1805 if mem::size_of::<T>() == 0 {
1806 // purposefully don't use 'ptr.offset' because for
1807 // vectors with 0-size elements this would return the
1809 self.ptr = mem::transmute(self.ptr as usize + 1);
1811 // Use a non-null pointer value
1812 Some(ptr::read(EMPTY as *mut T))
1815 self.ptr = self.ptr.offset(1);
1817 Some(ptr::read(old))
1824 fn size_hint(&self) -> (usize, Option<usize>) {
1825 let diff = (self.end as usize) - (self.ptr as usize);
1826 let size = mem::size_of::<T>();
1827 let exact = diff / (if size == 0 {1} else {size});
1828 (exact, Some(exact))
1832 #[stable(feature = "rust1", since = "1.0.0")]
1833 impl<T> DoubleEndedIterator for IntoIter<T> {
1835 fn next_back(&mut self) -> Option<T> {
1837 if self.end == self.ptr {
1840 if mem::size_of::<T>() == 0 {
1841 // See above for why 'ptr.offset' isn't used
1842 self.end = mem::transmute(self.end as usize - 1);
1844 // Use a non-null pointer value
1845 Some(ptr::read(EMPTY as *mut T))
1847 self.end = self.end.offset(-1);
1849 Some(ptr::read(mem::transmute(self.end)))
1856 #[stable(feature = "rust1", since = "1.0.0")]
1857 impl<T> ExactSizeIterator for IntoIter<T> {}
1859 #[unsafe_destructor]
1860 #[stable(feature = "rust1", since = "1.0.0")]
1861 impl<T> Drop for IntoIter<T> {
1862 fn drop(&mut self) {
1863 // destroy the remaining elements
1865 for _x in self.by_ref() {}
1867 dealloc(self.allocation, self.cap);
1873 /// An iterator that drains a vector.
1874 #[unsafe_no_drop_flag]
1875 #[unstable(feature = "collections",
1876 reason = "recently added as part of collections reform 2")]
1877 pub struct Drain<'a, T:'a> {
1880 marker: PhantomData<&'a T>,
1883 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1884 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1886 #[stable(feature = "rust1", since = "1.0.0")]
1887 impl<'a, T> Iterator for Drain<'a, T> {
1891 fn next(&mut self) -> Option<T> {
1893 if self.ptr == self.end {
1896 if mem::size_of::<T>() == 0 {
1897 // purposefully don't use 'ptr.offset' because for
1898 // vectors with 0-size elements this would return the
1900 self.ptr = mem::transmute(self.ptr as usize + 1);
1902 // Use a non-null pointer value
1903 Some(ptr::read(EMPTY as *mut T))
1906 self.ptr = self.ptr.offset(1);
1908 Some(ptr::read(old))
1915 fn size_hint(&self) -> (usize, Option<usize>) {
1916 let diff = (self.end as usize) - (self.ptr as usize);
1917 let size = mem::size_of::<T>();
1918 let exact = diff / (if size == 0 {1} else {size});
1919 (exact, Some(exact))
1923 #[stable(feature = "rust1", since = "1.0.0")]
1924 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1926 fn next_back(&mut self) -> Option<T> {
1928 if self.end == self.ptr {
1931 if mem::size_of::<T>() == 0 {
1932 // See above for why 'ptr.offset' isn't used
1933 self.end = mem::transmute(self.end as usize - 1);
1935 // Use a non-null pointer value
1936 Some(ptr::read(EMPTY as *mut T))
1938 self.end = self.end.offset(-1);
1940 Some(ptr::read(self.end))
1947 #[stable(feature = "rust1", since = "1.0.0")]
1948 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1950 #[unsafe_destructor]
1951 #[stable(feature = "rust1", since = "1.0.0")]
1952 impl<'a, T> Drop for Drain<'a, T> {
1953 fn drop(&mut self) {
1954 // self.ptr == self.end == null if drop has already been called,
1955 // so we can use #[unsafe_no_drop_flag].
1957 // destroy the remaining elements
1958 for _x in self.by_ref() {}
1962 ////////////////////////////////////////////////////////////////////////////////
1963 // Conversion from &[T] to &Vec<T>
1964 ////////////////////////////////////////////////////////////////////////////////
1966 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1967 #[unstable(feature = "collections")]
1968 pub struct DerefVec<'a, T:'a> {
1970 l: PhantomData<&'a T>,
1973 #[unstable(feature = "collections")]
1974 impl<'a, T> Deref for DerefVec<'a, T> {
1975 type Target = Vec<T>;
1977 fn deref<'b>(&'b self) -> &'b Vec<T> {
1982 // Prevent the inner `Vec<T>` from attempting to deallocate memory.
1983 #[unsafe_destructor]
1984 #[stable(feature = "rust1", since = "1.0.0")]
1985 impl<'a, T> Drop for DerefVec<'a, T> {
1986 fn drop(&mut self) {
1992 /// Convert a slice to a wrapper type providing a `&Vec<T>` reference.
1993 #[unstable(feature = "collections")]
1994 pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
1997 x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
2003 ////////////////////////////////////////////////////////////////////////////////
2004 // Partial vec, used for map_in_place
2005 ////////////////////////////////////////////////////////////////////////////////
2007 /// An owned, partially type-converted vector of elements with non-zero size.
2009 /// `T` and `U` must have the same, non-zero size. They must also have the same
2012 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
2013 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
2014 /// destructed. Additionally the underlying storage of `vec` will be freed.
2015 struct PartialVecNonZeroSized<T,U> {
2023 _marker: PhantomData<U>,
2026 /// An owned, partially type-converted vector of zero-sized elements.
2028 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
2030 struct PartialVecZeroSized<T,U> {
2033 marker: PhantomData<::core::cell::Cell<(T,U)>>,
2036 #[unsafe_destructor]
2037 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
2038 fn drop(&mut self) {
2040 // `vec` hasn't been modified until now. As it has a length
2041 // currently, this would run destructors of `T`s which might not be
2042 // there. So at first, set `vec`s length to `0`. This must be done
2043 // at first to remain memory-safe as the destructors of `U` or `T`
2044 // might cause unwinding where `vec`s destructor would be executed.
2045 self.vec.set_len(0);
2047 // We have instances of `U`s and `T`s in `vec`. Destruct them.
2048 while self.start_u != self.end_u {
2049 let _ = ptr::read(self.start_u); // Run a `U` destructor.
2050 self.start_u = self.start_u.offset(1);
2052 while self.start_t != self.end_t {
2053 let _ = ptr::read(self.start_t); // Run a `T` destructor.
2054 self.start_t = self.start_t.offset(1);
2056 // After this destructor ran, the destructor of `vec` will run,
2057 // deallocating the underlying memory.
2062 #[unsafe_destructor]
2063 impl<T,U> Drop for PartialVecZeroSized<T,U> {
2064 fn drop(&mut self) {
2066 // Destruct the instances of `T` and `U` this struct owns.
2067 while self.num_t != 0 {
2068 let _: T = mem::uninitialized(); // Run a `T` destructor.
2071 while self.num_u != 0 {
2072 let _: U = mem::uninitialized(); // Run a `U` destructor.