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 // FIXME- fix places which assume the max vector allowed has memory usize::MAX.
73 static MAX_MEMORY_SIZE: usize = isize::MAX as usize;
75 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
80 /// # #![feature(collections)]
81 /// let mut vec = Vec::new();
85 /// assert_eq!(vec.len(), 2);
86 /// assert_eq!(vec[0], 1);
88 /// assert_eq!(vec.pop(), Some(2));
89 /// assert_eq!(vec.len(), 1);
92 /// assert_eq!(vec[0], 7);
94 /// vec.push_all(&[1, 2, 3]);
96 /// for x in vec.iter() {
97 /// println!("{}", x);
99 /// assert_eq!(vec, [7, 1, 2, 3]);
102 /// The `vec!` macro is provided to make initialization more convenient:
105 /// let mut vec = vec![1, 2, 3];
107 /// assert_eq!(vec, [1, 2, 3, 4]);
110 /// Use a `Vec<T>` as an efficient stack:
113 /// let mut stack = Vec::new();
120 /// let top = match stack.pop() {
121 /// None => break, // empty
124 /// // Prints 3, 2, 1
125 /// println!("{}", top);
129 /// # Capacity and reallocation
131 /// The capacity of a vector is the amount of space allocated for any future
132 /// elements that will be added onto the vector. This is not to be confused with
133 /// the *length* of a vector, which specifies the number of actual elements
134 /// within the vector. If a vector's length exceeds its capacity, its capacity
135 /// will automatically be increased, but its elements will have to be
138 /// For example, a vector with capacity 10 and length 0 would be an empty vector
139 /// with space for 10 more elements. Pushing 10 or fewer elements onto the
140 /// vector will not change its capacity or cause reallocation to occur. However,
141 /// if the vector's length is increased to 11, it will have to reallocate, which
142 /// can be slow. For this reason, it is recommended to use `Vec::with_capacity`
143 /// whenever possible to specify how big the vector is expected to get.
144 #[unsafe_no_drop_flag]
145 #[stable(feature = "rust1", since = "1.0.0")]
152 unsafe impl<T: Send> Send for Vec<T> { }
153 unsafe impl<T: Sync> Sync for Vec<T> { }
155 ////////////////////////////////////////////////////////////////////////////////
157 ////////////////////////////////////////////////////////////////////////////////
160 /// Constructs a new, empty `Vec<T>`.
162 /// The vector will not allocate until elements are pushed onto it.
167 /// let mut vec: Vec<i32> = Vec::new();
170 #[stable(feature = "rust1", since = "1.0.0")]
171 pub fn new() -> Vec<T> {
172 // We want ptr to never be NULL so instead we set it to some arbitrary
173 // non-null value which is fine since we never call deallocate on the ptr
174 // if cap is 0. The reason for this is because the pointer of a slice
175 // being NULL would break the null pointer optimization for enums.
176 unsafe { Vec::from_raw_parts(EMPTY as *mut T, 0, 0) }
179 /// Constructs a new, empty `Vec<T>` with the specified capacity.
181 /// The vector will be able to hold exactly `capacity` elements without reallocating. If
182 /// `capacity` is 0, the vector will not allocate.
184 /// It is important to note that this function does not specify the *length* of the returned
185 /// vector, but only the *capacity*. (For an explanation of the difference between length and
186 /// capacity, see the main `Vec<T>` docs above, 'Capacity and reallocation'.)
191 /// let mut vec = Vec::with_capacity(10);
193 /// // The vector contains no items, even though it has capacity for more
194 /// assert_eq!(vec.len(), 0);
196 /// // These are all done without reallocating...
201 /// // ...but this may make the vector reallocate
205 #[stable(feature = "rust1", since = "1.0.0")]
206 pub fn with_capacity(capacity: usize) -> Vec<T> {
207 if mem::size_of::<T>() == 0 {
208 unsafe { Vec::from_raw_parts(EMPTY as *mut T, 0, usize::MAX) }
209 } else if capacity == 0 {
212 let size = capacity.checked_mul(mem::size_of::<T>())
213 .expect("capacity overflow");
214 let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
215 if ptr.is_null() { ::alloc::oom() }
216 unsafe { Vec::from_raw_parts(ptr as *mut T, 0, capacity) }
220 /// Creates a `Vec<T>` directly from the raw components of another vector.
222 /// This is highly unsafe, due to the number of invariants that aren't checked.
231 /// let mut v = vec![1, 2, 3];
233 /// // Pull out the various important pieces of information about `v`
234 /// let p = v.as_mut_ptr();
235 /// let len = v.len();
236 /// let cap = v.capacity();
239 /// // Cast `v` into the void: no destructor run, so we are in
240 /// // complete control of the allocation to which `p` points.
243 /// // Overwrite memory with 4, 5, 6
244 /// for i in 0..len as isize {
245 /// ptr::write(p.offset(i), 4 + i);
248 /// // Put everything back together into a Vec
249 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
250 /// assert_eq!(rebuilt, [4, 5, 6]);
254 #[stable(feature = "rust1", since = "1.0.0")]
255 pub unsafe fn from_raw_parts(ptr: *mut T, length: usize,
256 capacity: usize) -> Vec<T> {
258 ptr: Unique::new(ptr),
264 /// Creates a vector by copying the elements from a raw pointer.
266 /// This function will copy `elts` contiguous elements starting at `ptr`
267 /// into a new allocation owned by the returned `Vec<T>`. The elements of
268 /// the buffer are copied into the vector without cloning, as if
269 /// `ptr::read()` were called on them.
271 #[unstable(feature = "collections",
272 reason = "may be better expressed via composition")]
273 pub unsafe fn from_raw_buf(ptr: *const T, elts: usize) -> Vec<T> {
274 let mut dst = Vec::with_capacity(elts);
276 ptr::copy_nonoverlapping(ptr, dst.as_mut_ptr(), elts);
280 /// Returns the number of elements the vector can hold without
286 /// let vec: Vec<i32> = Vec::with_capacity(10);
287 /// assert_eq!(vec.capacity(), 10);
290 #[stable(feature = "rust1", since = "1.0.0")]
291 pub fn capacity(&self) -> usize {
295 /// Reserves capacity for at least `additional` more elements to be inserted
296 /// in the given `Vec<T>`. The collection may reserve more space to avoid
297 /// frequent reallocations.
301 /// Panics if the new capacity overflows `usize`.
306 /// let mut vec = vec![1];
308 /// assert!(vec.capacity() >= 11);
310 #[stable(feature = "rust1", since = "1.0.0")]
311 pub fn reserve(&mut self, additional: usize) {
312 if self.cap - self.len < additional {
313 const ERR_MSG: &'static str = "Vec::reserve: `isize` overflow";
315 let new_min_cap = self.len.checked_add(additional).expect(ERR_MSG);
316 if new_min_cap > MAX_MEMORY_SIZE { panic!(ERR_MSG) }
317 self.grow_capacity(match new_min_cap.checked_next_power_of_two() {
318 Some(x) if x > MAX_MEMORY_SIZE => MAX_MEMORY_SIZE,
319 None => MAX_MEMORY_SIZE,
325 /// Reserves the minimum capacity for exactly `additional` more elements to
326 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
329 /// Note that the allocator may give the collection more space than it
330 /// requests. Therefore capacity can not be relied upon to be precisely
331 /// minimal. Prefer `reserve` if future insertions are expected.
335 /// Panics if the new capacity overflows `usize`.
340 /// let mut vec = vec![1];
341 /// vec.reserve_exact(10);
342 /// assert!(vec.capacity() >= 11);
344 #[stable(feature = "rust1", since = "1.0.0")]
345 pub fn reserve_exact(&mut self, additional: usize) {
346 if self.cap - self.len < additional {
347 match self.len.checked_add(additional) {
348 None => panic!("Vec::reserve: `usize` overflow"),
349 Some(new_cap) => self.grow_capacity(new_cap)
354 /// Shrinks the capacity of the vector as much as possible.
356 /// It will drop down as close as possible to the length but the allocator
357 /// may still inform the vector that there is space for a few more elements.
362 /// # #![feature(collections)]
363 /// let mut vec = Vec::with_capacity(10);
364 /// vec.push_all(&[1, 2, 3]);
365 /// assert_eq!(vec.capacity(), 10);
366 /// vec.shrink_to_fit();
367 /// assert!(vec.capacity() >= 3);
369 #[stable(feature = "rust1", since = "1.0.0")]
370 pub fn shrink_to_fit(&mut self) {
371 if mem::size_of::<T>() == 0 { return }
376 dealloc(*self.ptr, self.cap)
380 } else if self.cap != self.len {
382 // Overflow check is unnecessary as the vector is already at
384 let ptr = reallocate(*self.ptr as *mut u8,
385 self.cap * mem::size_of::<T>(),
386 self.len * mem::size_of::<T>(),
387 mem::min_align_of::<T>()) as *mut T;
388 if ptr.is_null() { ::alloc::oom() }
389 self.ptr = Unique::new(ptr);
395 /// Converts the vector into Box<[T]>.
397 /// Note that this will drop any excess capacity. Calling this and
398 /// converting back to a vector with `into_vec()` is equivalent to calling
399 /// `shrink_to_fit()`.
400 #[stable(feature = "rust1", since = "1.0.0")]
401 pub fn into_boxed_slice(mut self) -> Box<[T]> {
402 self.shrink_to_fit();
404 let xs: Box<[T]> = Box::from_raw(&mut *self);
410 /// Shorten a vector, dropping excess elements.
412 /// If `len` is greater than the vector's current length, this has no
418 /// # #![feature(collections)]
419 /// let mut vec = vec![1, 2, 3, 4];
421 /// assert_eq!(vec, [1, 2]);
423 #[stable(feature = "rust1", since = "1.0.0")]
424 pub fn truncate(&mut self, len: usize) {
426 // drop any extra elements
427 while len < self.len {
428 // decrement len before the read(), so a panic on Drop doesn't
429 // re-drop the just-failed value.
431 ptr::read(self.get_unchecked(self.len));
436 /// Extracts a slice containing the entire vector.
438 #[unstable(feature = "convert",
439 reason = "waiting on RFC revision")]
440 pub fn as_slice(&self) -> &[T] {
444 /// Deprecated: use `&mut s[..]` instead.
446 #[unstable(feature = "convert",
447 reason = "waiting on RFC revision")]
448 pub fn as_mut_slice(&mut self) -> &mut [T] {
452 /// Sets the length of a vector.
454 /// This will explicitly set the size of the vector, without actually
455 /// modifying its buffers, so it is up to the caller to ensure that the
456 /// vector is actually the specified size.
461 /// let mut v = vec![1, 2, 3, 4];
467 #[stable(feature = "rust1", since = "1.0.0")]
468 pub unsafe fn set_len(&mut self, len: usize) {
472 /// Removes an element from anywhere in the vector and return it, replacing
473 /// it with the last element.
475 /// This does not preserve ordering, but is O(1).
479 /// Panics if `index` is out of bounds.
484 /// let mut v = vec!["foo", "bar", "baz", "qux"];
486 /// assert_eq!(v.swap_remove(1), "bar");
487 /// assert_eq!(v, ["foo", "qux", "baz"]);
489 /// assert_eq!(v.swap_remove(0), "foo");
490 /// assert_eq!(v, ["baz", "qux"]);
493 #[stable(feature = "rust1", since = "1.0.0")]
494 pub fn swap_remove(&mut self, index: usize) -> T {
495 let length = self.len();
496 self.swap(index, length - 1);
500 /// Inserts an element at position `index` within the vector, shifting all
501 /// elements after position `i` one position to the right.
505 /// Panics if `index` is greater than the vector's length.
510 /// let mut vec = vec![1, 2, 3];
511 /// vec.insert(1, 4);
512 /// assert_eq!(vec, [1, 4, 2, 3]);
513 /// vec.insert(4, 5);
514 /// assert_eq!(vec, [1, 4, 2, 3, 5]);
516 #[stable(feature = "rust1", since = "1.0.0")]
517 pub fn insert(&mut self, index: usize, element: T) {
518 let len = self.len();
519 assert!(index <= len);
520 // space for the new element
523 unsafe { // infallible
524 // The spot to put the new value
526 let p = self.as_mut_ptr().offset(index as isize);
527 // Shift everything over to make space. (Duplicating the
528 // `index`th element into two consecutive places.)
529 ptr::copy(&*p, p.offset(1), len - index);
530 // Write it in, overwriting the first copy of the `index`th
532 ptr::write(&mut *p, element);
534 self.set_len(len + 1);
538 /// Removes and returns the element at position `index` within the vector,
539 /// shifting all elements after position `index` one position to the left.
543 /// Panics if `i` is out of bounds.
548 /// # #![feature(collections)]
549 /// let mut v = vec![1, 2, 3];
550 /// assert_eq!(v.remove(1), 2);
551 /// assert_eq!(v, [1, 3]);
553 #[stable(feature = "rust1", since = "1.0.0")]
554 pub fn remove(&mut self, index: usize) -> T {
555 let len = self.len();
556 assert!(index < len);
557 unsafe { // infallible
560 // the place we are taking from.
561 let ptr = self.as_mut_ptr().offset(index as isize);
562 // copy it out, unsafely having a copy of the value on
563 // the stack and in the vector at the same time.
564 ret = ptr::read(ptr);
566 // Shift everything down to fill in that spot.
567 ptr::copy(&*ptr.offset(1), ptr, len - index - 1);
569 self.set_len(len - 1);
574 /// Retains only the elements specified by the predicate.
576 /// In other words, remove all elements `e` such that `f(&e)` returns false.
577 /// This method operates in place and preserves the order of the retained
583 /// let mut vec = vec![1, 2, 3, 4];
584 /// vec.retain(|&x| x%2 == 0);
585 /// assert_eq!(vec, [2, 4]);
587 #[stable(feature = "rust1", since = "1.0.0")]
588 pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
589 let len = self.len();
603 self.truncate(len - del);
607 /// Appends an element to the back of a collection.
611 /// Panics if the number of elements in the vector overflows a `usize`.
616 /// let mut vec = vec!(1, 2);
618 /// assert_eq!(vec, [1, 2, 3]);
621 #[stable(feature = "rust1", since = "1.0.0")]
622 pub fn push(&mut self, value: T) {
625 fn resize<T>(vec: &mut Vec<T>) {
626 let old_size = vec.cap * mem::size_of::<T>();
627 if old_size >= MAX_MEMORY_SIZE { panic!("capacity overflow") }
628 let mut size = max(old_size, 2 * mem::size_of::<T>()) * 2;
629 if old_size > size || size > MAX_MEMORY_SIZE {
630 size = MAX_MEMORY_SIZE;
633 let ptr = alloc_or_realloc(*vec.ptr, old_size, size);
634 if ptr.is_null() { ::alloc::oom() }
635 vec.ptr = Unique::new(ptr);
637 vec.cap = max(vec.cap, 2) * 2;
640 if mem::size_of::<T>() == 0 {
641 // zero-size types consume no memory, so we can't rely on the
642 // address space running out
643 self.len = self.len.checked_add(1).expect("length overflow");
644 unsafe { mem::forget(value); }
648 if self.len == self.cap {
653 let end = (*self.ptr).offset(self.len as isize);
654 ptr::write(&mut *end, value);
659 /// Removes the last element from a vector and returns it, or `None` if it is empty.
664 /// let mut vec = vec![1, 2, 3];
665 /// assert_eq!(vec.pop(), Some(3));
666 /// assert_eq!(vec, [1, 2]);
669 #[stable(feature = "rust1", since = "1.0.0")]
670 pub fn pop(&mut self) -> Option<T> {
676 Some(ptr::read(self.get_unchecked(self.len())))
681 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
685 /// Panics if the number of elements in the vector overflows a `usize`.
690 /// # #![feature(collections)]
691 /// let mut vec = vec![1, 2, 3];
692 /// let mut vec2 = vec![4, 5, 6];
693 /// vec.append(&mut vec2);
694 /// assert_eq!(vec, [1, 2, 3, 4, 5, 6]);
695 /// assert_eq!(vec2, []);
698 #[unstable(feature = "collections",
699 reason = "new API, waiting for dust to settle")]
700 pub fn append(&mut self, other: &mut Self) {
701 if mem::size_of::<T>() == 0 {
702 // zero-size types consume no memory, so we can't rely on the
703 // address space running out
704 self.len = self.len.checked_add(other.len()).expect("length overflow");
705 unsafe { other.set_len(0) }
708 self.reserve(other.len());
709 let len = self.len();
711 ptr::copy_nonoverlapping(
713 self.get_unchecked_mut(len),
717 self.len += other.len();
718 unsafe { other.set_len(0); }
721 /// Creates a draining iterator that clears the `Vec` and iterates over
722 /// the removed items from start to end.
727 /// # #![feature(collections)]
728 /// let mut v = vec!["a".to_string(), "b".to_string()];
729 /// for s in v.drain() {
730 /// // s has type String, not &String
731 /// println!("{}", s);
733 /// assert!(v.is_empty());
736 #[unstable(feature = "collections",
737 reason = "matches collection reform specification, waiting for dust to settle")]
738 pub fn drain(&mut self) -> Drain<T> {
740 let begin = *self.ptr as *const T;
741 let end = if mem::size_of::<T>() == 0 {
742 (*self.ptr as usize + self.len()) as *const T
744 (*self.ptr).offset(self.len() as isize) as *const T
755 /// Clears the vector, removing all values.
760 /// let mut v = vec![1, 2, 3];
764 /// assert!(v.is_empty());
767 #[stable(feature = "rust1", since = "1.0.0")]
768 pub fn clear(&mut self) {
772 /// Returns the number of elements in the vector.
777 /// let a = vec![1, 2, 3];
778 /// assert_eq!(a.len(), 3);
781 #[stable(feature = "rust1", since = "1.0.0")]
782 pub fn len(&self) -> usize { self.len }
784 /// Returns `true` if the vector contains no elements.
789 /// let mut v = Vec::new();
790 /// assert!(v.is_empty());
793 /// assert!(!v.is_empty());
795 #[stable(feature = "rust1", since = "1.0.0")]
796 pub fn is_empty(&self) -> bool { self.len() == 0 }
798 /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same
799 /// size and in case they are not zero-sized the same minimal alignment.
803 /// Panics if `T` and `U` have differing sizes or are not zero-sized and
804 /// have differing minimal alignments.
809 /// # #![feature(collections, core)]
810 /// let v = vec![0, 1, 2];
811 /// let w = v.map_in_place(|i| i + 3);
812 /// assert_eq!(&w[..], &[3, 4, 5]);
814 /// #[derive(PartialEq, Debug)]
815 /// struct Newtype(u8);
816 /// let bytes = vec![0x11, 0x22];
817 /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x));
818 /// assert_eq!(&newtyped_bytes[..], &[Newtype(0x11), Newtype(0x22)]);
820 #[unstable(feature = "collections",
821 reason = "API may change to provide stronger guarantees")]
822 pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
823 // FIXME: Assert statically that the types `T` and `U` have the same
825 assert!(mem::size_of::<T>() == mem::size_of::<U>());
829 if mem::size_of::<T>() != 0 {
830 // FIXME: Assert statically that the types `T` and `U` have the
831 // same minimal alignment in case they are not zero-sized.
833 // These asserts are necessary because the `min_align_of` of the
834 // types are passed to the allocator by `Vec`.
835 assert!(mem::min_align_of::<T>() == mem::min_align_of::<U>());
837 // This `as isize` cast is safe, because the size of the elements of the
838 // vector is not 0, and:
840 // 1) If the size of the elements in the vector is 1, the `isize` may
841 // overflow, but it has the correct bit pattern so that the
842 // `.offset()` function will work.
845 // Address space 0x0-0xF.
846 // `u8` array at: 0x1.
847 // Size of `u8` array: 0x8.
848 // Calculated `offset`: -0x8.
849 // After `array.offset(offset)`: 0x9.
850 // (0x1 + 0x8 = 0x1 - 0x8)
852 // 2) If the size of the elements in the vector is >1, the `usize` ->
853 // `isize` conversion can't overflow.
854 let offset = vec.len() as isize;
855 let start = vec.as_mut_ptr();
857 let mut pv = PartialVecNonZeroSized {
861 // This points inside the vector, as the vector has length
863 end_t: unsafe { start.offset(offset) },
864 start_u: start as *mut U,
865 end_u: start as *mut U,
867 _marker: PhantomData,
878 while pv.end_u as *mut T != pv.end_t {
882 // +-+-+-+-+-+-+-+-+-+
883 // |U|...|U|T|T|...|T|
884 // +-+-+-+-+-+-+-+-+-+
888 let t = ptr::read(pv.start_t);
891 // +-+-+-+-+-+-+-+-+-+
892 // |U|...|U|X|T|...|T|
893 // +-+-+-+-+-+-+-+-+-+
896 // We must not panic here, one cell is marked as `T`
897 // although it is not `T`.
899 pv.start_t = pv.start_t.offset(1);
902 // +-+-+-+-+-+-+-+-+-+
903 // |U|...|U|X|T|...|T|
904 // +-+-+-+-+-+-+-+-+-+
907 // We may panic again.
909 // The function given by the user might panic.
912 ptr::write(pv.end_u, u);
915 // +-+-+-+-+-+-+-+-+-+
916 // |U|...|U|U|T|...|T|
917 // +-+-+-+-+-+-+-+-+-+
920 // We should not panic here, because that would leak the `U`
921 // pointed to by `end_u`.
923 pv.end_u = pv.end_u.offset(1);
926 // +-+-+-+-+-+-+-+-+-+
927 // |U|...|U|U|T|...|T|
928 // +-+-+-+-+-+-+-+-+-+
931 // We may panic again.
943 // Extract `vec` and prevent the destructor of
944 // `PartialVecNonZeroSized` from running. Note that none of the
945 // function calls can panic, thus no resources can be leaked (as the
946 // `vec` member of `PartialVec` is the only one which holds
947 // allocations -- and it is returned from this function. None of
950 let vec_len = pv.vec.len();
951 let vec_cap = pv.vec.capacity();
952 let vec_ptr = pv.vec.as_mut_ptr() as *mut U;
954 Vec::from_raw_parts(vec_ptr, vec_len, vec_cap)
957 // Put the `Vec` into the `PartialVecZeroSized` structure and
958 // prevent the destructor of the `Vec` from running. Since the
959 // `Vec` contained zero-sized objects, it did not allocate, so we
960 // are not leaking memory here.
961 let mut pv = PartialVecZeroSized::<T,U> {
966 unsafe { mem::forget(vec); }
968 while pv.num_t != 0 {
970 // Create a `T` out of thin air and decrement `num_t`. This
971 // must not panic between these steps, as otherwise a
972 // destructor of `T` which doesn't exist runs.
973 let t = mem::uninitialized();
976 // The function given by the user might panic.
979 // Forget the `U` and increment `num_u`. This increment
980 // cannot overflow the `usize` as we only do this for a
981 // number of times that fits into a `usize` (and start with
982 // `0`). Again, we should not panic between these steps.
987 // Create a `Vec` from our `PartialVecZeroSized` and make sure the
988 // destructor of the latter will not run. None of this can panic.
989 let mut result = Vec::new();
991 result.set_len(pv.num_u);
998 /// Splits the collection into two at the given index.
1000 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1001 /// and the returned `Self` contains elements `[at, len)`.
1003 /// Note that the capacity of `self` does not change.
1007 /// Panics if `at > len`.
1012 /// # #![feature(collections)]
1013 /// let mut vec = vec![1,2,3];
1014 /// let vec2 = vec.split_off(1);
1015 /// assert_eq!(vec, [1]);
1016 /// assert_eq!(vec2, [2, 3]);
1019 #[unstable(feature = "collections",
1020 reason = "new API, waiting for dust to settle")]
1021 pub fn split_off(&mut self, at: usize) -> Self {
1022 assert!(at <= self.len(), "`at` out of bounds");
1024 let other_len = self.len - at;
1025 let mut other = Vec::with_capacity(other_len);
1027 // Unsafely `set_len` and copy items to `other`.
1030 other.set_len(other_len);
1032 ptr::copy_nonoverlapping(
1033 self.as_ptr().offset(at as isize),
1042 impl<T: Clone> Vec<T> {
1043 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1045 /// Calls either `extend()` or `truncate()` depending on whether `new_len`
1046 /// is larger than the current value of `len()` or not.
1051 /// # #![feature(collections)]
1052 /// let mut vec = vec!["hello"];
1053 /// vec.resize(3, "world");
1054 /// assert_eq!(vec, ["hello", "world", "world"]);
1056 /// let mut vec = vec![1, 2, 3, 4];
1057 /// vec.resize(2, 0);
1058 /// assert_eq!(vec, [1, 2]);
1060 #[unstable(feature = "collections",
1061 reason = "matches collection reform specification; waiting for dust to settle")]
1062 pub fn resize(&mut self, new_len: usize, value: T) {
1063 let len = self.len();
1066 self.extend(repeat(value).take(new_len - len));
1068 self.truncate(new_len);
1072 /// Appends all elements in a slice to the `Vec`.
1074 /// Iterates over the slice `other`, clones each element, and then appends
1075 /// it to this `Vec`. The `other` vector is traversed in-order.
1080 /// # #![feature(collections)]
1081 /// let mut vec = vec![1];
1082 /// vec.push_all(&[2, 3, 4]);
1083 /// assert_eq!(vec, [1, 2, 3, 4]);
1086 #[unstable(feature = "collections",
1087 reason = "likely to be replaced by a more optimized extend")]
1088 pub fn push_all(&mut self, other: &[T]) {
1089 self.reserve(other.len());
1091 for i in 0..other.len() {
1092 let len = self.len();
1094 // Unsafe code so this can be optimised to a memcpy (or something similarly
1095 // fast) when T is Copy. LLVM is easily confused, so any extra operations
1096 // during the loop can prevent this optimisation.
1099 self.get_unchecked_mut(len),
1100 other.get_unchecked(i).clone());
1101 self.set_len(len + 1);
1107 impl<T: PartialEq> Vec<T> {
1108 /// Removes consecutive repeated elements in the vector.
1110 /// If the vector is sorted, this removes all duplicates.
1115 /// let mut vec = vec![1, 2, 2, 3, 2];
1119 /// assert_eq!(vec, [1, 2, 3, 2]);
1121 #[stable(feature = "rust1", since = "1.0.0")]
1122 pub fn dedup(&mut self) {
1124 // Although we have a mutable reference to `self`, we cannot make
1125 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1126 // must ensure that the vector is in a valid state at all time.
1128 // The way that we handle this is by using swaps; we iterate
1129 // over all the elements, swapping as we go so that at the end
1130 // the elements we wish to keep are in the front, and those we
1131 // wish to reject are at the back. We can then truncate the
1132 // vector. This operation is still O(n).
1134 // Example: We start in this state, where `r` represents "next
1135 // read" and `w` represents "next_write`.
1138 // +---+---+---+---+---+---+
1139 // | 0 | 1 | 1 | 2 | 3 | 3 |
1140 // +---+---+---+---+---+---+
1143 // Comparing self[r] against self[w-1], this is not a duplicate, so
1144 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1145 // r and w, leaving us with:
1148 // +---+---+---+---+---+---+
1149 // | 0 | 1 | 1 | 2 | 3 | 3 |
1150 // +---+---+---+---+---+---+
1153 // Comparing self[r] against self[w-1], this value is a duplicate,
1154 // so we increment `r` but leave everything else unchanged:
1157 // +---+---+---+---+---+---+
1158 // | 0 | 1 | 1 | 2 | 3 | 3 |
1159 // +---+---+---+---+---+---+
1162 // Comparing self[r] against self[w-1], this is not a duplicate,
1163 // so swap self[r] and self[w] and advance r and w:
1166 // +---+---+---+---+---+---+
1167 // | 0 | 1 | 2 | 1 | 3 | 3 |
1168 // +---+---+---+---+---+---+
1171 // Not a duplicate, repeat:
1174 // +---+---+---+---+---+---+
1175 // | 0 | 1 | 2 | 3 | 1 | 3 |
1176 // +---+---+---+---+---+---+
1179 // Duplicate, advance r. End of vec. Truncate to w.
1181 let ln = self.len();
1182 if ln < 1 { return; }
1184 // Avoid bounds checks by using unsafe pointers.
1185 let p = self.as_mut_ptr();
1186 let mut r: usize = 1;
1187 let mut w: usize = 1;
1190 let p_r = p.offset(r as isize);
1191 let p_wm1 = p.offset((w - 1) as isize);
1194 let p_w = p_wm1.offset(1);
1195 mem::swap(&mut *p_r, &mut *p_w);
1207 ////////////////////////////////////////////////////////////////////////////////
1208 // Internal methods and functions
1209 ////////////////////////////////////////////////////////////////////////////////
1212 /// Reserves capacity for exactly `capacity` elements in the given vector.
1214 /// If the capacity for `self` is already equal to or greater than the
1215 /// requested capacity, then no action is taken.
1216 fn grow_capacity(&mut self, capacity: usize) {
1217 if mem::size_of::<T>() == 0 { return }
1219 if capacity > self.cap {
1220 let size = capacity.checked_mul(mem::size_of::<T>())
1221 .expect("capacity overflow");
1223 let ptr = alloc_or_realloc(*self.ptr, self.cap * mem::size_of::<T>(), size);
1224 if ptr.is_null() { ::alloc::oom() }
1225 self.ptr = Unique::new(ptr);
1227 self.cap = capacity;
1232 // FIXME: #13996: need a way to mark the return value as `noalias`
1234 unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: usize, size: usize) -> *mut T {
1236 allocate(size, mem::min_align_of::<T>()) as *mut T
1238 reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T
1243 unsafe fn dealloc<T>(ptr: *mut T, len: usize) {
1244 if mem::size_of::<T>() != 0 {
1245 deallocate(ptr as *mut u8,
1246 len * mem::size_of::<T>(),
1247 mem::min_align_of::<T>())
1252 #[stable(feature = "rust1", since = "1.0.0")]
1253 pub fn from_elem<T: Clone>(elem: T, n: usize) -> Vec<T> {
1255 let mut v = Vec::with_capacity(n);
1256 let mut ptr = v.as_mut_ptr();
1258 // Write all elements except the last one
1260 ptr::write(ptr, Clone::clone(&elem));
1261 ptr = ptr.offset(1);
1262 v.set_len(i); // Increment the length in every step in case Clone::clone() panics
1266 // We can write the last element directly without cloning needlessly
1267 ptr::write(ptr, elem);
1275 ////////////////////////////////////////////////////////////////////////////////
1276 // Common trait implementations for Vec
1277 ////////////////////////////////////////////////////////////////////////////////
1279 #[unstable(feature = "collections")]
1280 impl<T:Clone> Clone for Vec<T> {
1282 fn clone(&self) -> Vec<T> { <[T]>::to_vec(&**self) }
1284 // HACK(japaric): with cfg(test) the inherent `[T]::to_vec` method, which is
1285 // required for this method definition, is not available. Instead use the
1286 // `slice::to_vec` function which is only available with cfg(test)
1287 // NB see the slice::hack module in slice.rs for more information
1289 fn clone(&self) -> Vec<T> {
1290 ::slice::to_vec(&**self)
1293 fn clone_from(&mut self, other: &Vec<T>) {
1294 // drop anything in self that will not be overwritten
1295 if self.len() > other.len() {
1296 self.truncate(other.len())
1299 // reuse the contained values' allocations/resources.
1300 for (place, thing) in self.iter_mut().zip(other.iter()) {
1301 place.clone_from(thing)
1304 // self.len <= other.len due to the truncate above, so the
1305 // slice here is always in-bounds.
1306 let slice = &other[self.len()..];
1307 self.push_all(slice);
1311 #[stable(feature = "rust1", since = "1.0.0")]
1312 impl<T: Hash> Hash for Vec<T> {
1314 fn hash<H: hash::Hasher>(&self, state: &mut H) {
1315 Hash::hash(&**self, state)
1319 #[stable(feature = "rust1", since = "1.0.0")]
1320 impl<T> Index<usize> for Vec<T> {
1324 fn index(&self, index: usize) -> &T {
1325 // NB built-in indexing via `&[T]`
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<T> IndexMut<usize> for Vec<T> {
1333 fn index_mut(&mut self, index: usize) -> &mut T {
1334 // NB built-in indexing via `&mut [T]`
1335 &mut (**self)[index]
1340 #[stable(feature = "rust1", since = "1.0.0")]
1341 impl<T> ops::Index<ops::Range<usize>> for Vec<T> {
1345 fn index(&self, index: ops::Range<usize>) -> &[T] {
1346 Index::index(&**self, index)
1349 #[stable(feature = "rust1", since = "1.0.0")]
1350 impl<T> ops::Index<ops::RangeTo<usize>> for Vec<T> {
1354 fn index(&self, index: ops::RangeTo<usize>) -> &[T] {
1355 Index::index(&**self, index)
1358 #[stable(feature = "rust1", since = "1.0.0")]
1359 impl<T> ops::Index<ops::RangeFrom<usize>> for Vec<T> {
1363 fn index(&self, index: ops::RangeFrom<usize>) -> &[T] {
1364 Index::index(&**self, index)
1367 #[stable(feature = "rust1", since = "1.0.0")]
1368 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1372 fn index(&self, _index: ops::RangeFull) -> &[T] {
1377 #[stable(feature = "rust1", since = "1.0.0")]
1378 impl<T> ops::IndexMut<ops::Range<usize>> for Vec<T> {
1381 fn index_mut(&mut self, index: ops::Range<usize>) -> &mut [T] {
1382 IndexMut::index_mut(&mut **self, index)
1385 #[stable(feature = "rust1", since = "1.0.0")]
1386 impl<T> ops::IndexMut<ops::RangeTo<usize>> for Vec<T> {
1389 fn index_mut(&mut self, index: ops::RangeTo<usize>) -> &mut [T] {
1390 IndexMut::index_mut(&mut **self, index)
1393 #[stable(feature = "rust1", since = "1.0.0")]
1394 impl<T> ops::IndexMut<ops::RangeFrom<usize>> for Vec<T> {
1397 fn index_mut(&mut self, index: ops::RangeFrom<usize>) -> &mut [T] {
1398 IndexMut::index_mut(&mut **self, index)
1401 #[stable(feature = "rust1", since = "1.0.0")]
1402 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1405 fn index_mut(&mut self, _index: ops::RangeFull) -> &mut [T] {
1410 #[stable(feature = "rust1", since = "1.0.0")]
1411 impl<T> ops::Deref for Vec<T> {
1414 fn deref(&self) -> &[T] {
1417 assume(p != 0 as *mut T);
1418 slice::from_raw_parts(p, self.len)
1423 #[stable(feature = "rust1", since = "1.0.0")]
1424 impl<T> ops::DerefMut for Vec<T> {
1425 fn deref_mut(&mut self) -> &mut [T] {
1427 let ptr = *self.ptr;
1428 assume(!ptr.is_null());
1429 slice::from_raw_parts_mut(ptr, self.len)
1434 #[stable(feature = "rust1", since = "1.0.0")]
1435 impl<T> FromIterator<T> for Vec<T> {
1437 fn from_iter<I: IntoIterator<Item=T>>(iterable: I) -> Vec<T> {
1438 let mut iterator = iterable.into_iter();
1439 let (lower, _) = iterator.size_hint();
1440 let mut vector = Vec::with_capacity(lower);
1442 // This function should be the moral equivalent of:
1444 // for item in iterator {
1445 // vector.push(item);
1448 // This equivalent crucially runs the iterator precisely once. Below we
1449 // actually in theory run the iterator twice (one without bounds checks
1450 // and one with). To achieve the "moral equivalent", we use the `if`
1451 // statement below to break out early.
1453 // If the first loop has terminated, then we have one of two conditions.
1455 // 1. The underlying iterator returned `None`. In this case we are
1456 // guaranteed that less than `vector.capacity()` elements have been
1457 // returned, so we break out early.
1458 // 2. The underlying iterator yielded `vector.capacity()` elements and
1459 // has not yielded `None` yet. In this case we run the iterator to
1461 for element in iterator.by_ref().take(vector.capacity()) {
1462 let len = vector.len();
1464 ptr::write(vector.get_unchecked_mut(len), element);
1465 vector.set_len(len + 1);
1469 if vector.len() == vector.capacity() {
1470 for element in iterator {
1471 vector.push(element);
1478 #[stable(feature = "rust1", since = "1.0.0")]
1479 impl<T> IntoIterator for Vec<T> {
1481 type IntoIter = IntoIter<T>;
1483 /// Creates a consuming iterator, that is, one that moves each value out of
1484 /// the vector (from start to end). The vector cannot be used after calling
1490 /// let v = vec!["a".to_string(), "b".to_string()];
1491 /// for s in v.into_iter() {
1492 /// // s has type String, not &String
1493 /// println!("{}", s);
1497 fn into_iter(self) -> IntoIter<T> {
1499 let ptr = *self.ptr;
1500 assume(!ptr.is_null());
1502 let begin = ptr as *const T;
1503 let end = if mem::size_of::<T>() == 0 {
1504 (ptr as usize + self.len()) as *const T
1506 ptr.offset(self.len() as isize) as *const T
1509 IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end }
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 impl<'a, T> IntoIterator for &'a Vec<T> {
1517 type IntoIter = slice::Iter<'a, T>;
1519 fn into_iter(self) -> slice::Iter<'a, T> {
1524 #[stable(feature = "rust1", since = "1.0.0")]
1525 impl<'a, T> IntoIterator for &'a mut Vec<T> {
1526 type Item = &'a mut T;
1527 type IntoIter = slice::IterMut<'a, T>;
1529 fn into_iter(mut self) -> slice::IterMut<'a, T> {
1534 #[unstable(feature = "collections", reason = "waiting on Extend stability")]
1535 impl<T> Extend<T> for Vec<T> {
1537 fn extend<I: IntoIterator<Item=T>>(&mut self, iterable: I) {
1538 let iterator = iterable.into_iter();
1539 let (lower, _) = iterator.size_hint();
1540 self.reserve(lower);
1541 for element in iterator {
1547 __impl_slice_eq1! { Vec<A>, Vec<B> }
1548 __impl_slice_eq1! { Vec<A>, &'b [B] }
1549 __impl_slice_eq1! { Vec<A>, &'b mut [B] }
1550 __impl_slice_eq1! { Cow<'a, [A]>, &'b [B], Clone }
1551 __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B], Clone }
1552 __impl_slice_eq1! { Cow<'a, [A]>, Vec<B>, Clone }
1554 macro_rules! array_impls {
1557 // NOTE: some less important impls are omitted to reduce code bloat
1558 __impl_slice_eq1! { Vec<A>, [B; $N] }
1559 __impl_slice_eq1! { Vec<A>, &'b [B; $N] }
1560 // __impl_slice_eq1! { Vec<A>, &'b mut [B; $N] }
1561 // __impl_slice_eq1! { Cow<'a, [A]>, [B; $N], Clone }
1562 // __impl_slice_eq1! { Cow<'a, [A]>, &'b [B; $N], Clone }
1563 // __impl_slice_eq1! { Cow<'a, [A]>, &'b mut [B; $N], Clone }
1570 10 11 12 13 14 15 16 17 18 19
1571 20 21 22 23 24 25 26 27 28 29
1575 #[stable(feature = "rust1", since = "1.0.0")]
1576 impl<T: PartialOrd> PartialOrd for Vec<T> {
1578 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1579 PartialOrd::partial_cmp(&**self, &**other)
1583 #[stable(feature = "rust1", since = "1.0.0")]
1584 impl<T: Eq> Eq for Vec<T> {}
1586 #[stable(feature = "rust1", since = "1.0.0")]
1587 impl<T: Ord> Ord for Vec<T> {
1589 fn cmp(&self, other: &Vec<T>) -> Ordering {
1590 Ord::cmp(&**self, &**other)
1594 #[unstable(feature = "collections",
1595 reason = "recent addition, needs more experience")]
1596 impl<'a, T: Clone> Add<&'a [T]> for Vec<T> {
1597 type Output = Vec<T>;
1600 fn add(mut self, rhs: &[T]) -> Vec<T> {
1606 #[unsafe_destructor]
1607 #[stable(feature = "rust1", since = "1.0.0")]
1608 impl<T> Drop for Vec<T> {
1609 fn drop(&mut self) {
1610 // This is (and should always remain) a no-op if the fields are
1611 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1612 if self.cap != 0 && self.cap != mem::POST_DROP_USIZE {
1617 dealloc(*self.ptr, self.cap)
1623 #[stable(feature = "rust1", since = "1.0.0")]
1624 impl<T> Default for Vec<T> {
1625 #[stable(feature = "rust1", since = "1.0.0")]
1626 fn default() -> Vec<T> {
1631 #[stable(feature = "rust1", since = "1.0.0")]
1632 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1633 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1634 fmt::Debug::fmt(&**self, f)
1638 #[stable(feature = "rust1", since = "1.0.0")]
1639 impl<T> AsRef<Vec<T>> for Vec<T> {
1640 fn as_ref(&self) -> &Vec<T> {
1645 #[stable(feature = "rust1", since = "1.0.0")]
1646 impl<T> AsRef<[T]> for Vec<T> {
1647 fn as_ref(&self) -> &[T] {
1652 #[stable(feature = "rust1", since = "1.0.0")]
1653 impl<'a, T: Clone> From<&'a [T]> for Vec<T> {
1655 fn from(s: &'a [T]) -> Vec<T> {
1659 fn from(s: &'a [T]) -> Vec<T> {
1664 #[stable(feature = "rust1", since = "1.0.0")]
1665 impl<'a> From<&'a str> for Vec<u8> {
1666 fn from(s: &'a str) -> Vec<u8> {
1667 From::from(s.as_bytes())
1671 ////////////////////////////////////////////////////////////////////////////////
1673 ////////////////////////////////////////////////////////////////////////////////
1675 #[unstable(feature = "collections")]
1676 impl<'a, T> FromIterator<T> for Cow<'a, [T]> where T: Clone {
1677 fn from_iter<I: IntoIterator<Item=T>>(it: I) -> Cow<'a, [T]> {
1678 Cow::Owned(FromIterator::from_iter(it))
1682 impl<'a, T: 'a> IntoCow<'a, [T]> for Vec<T> where T: Clone {
1683 fn into_cow(self) -> Cow<'a, [T]> {
1688 impl<'a, T> IntoCow<'a, [T]> for &'a [T] where T: Clone {
1689 fn into_cow(self) -> Cow<'a, [T]> {
1694 ////////////////////////////////////////////////////////////////////////////////
1696 ////////////////////////////////////////////////////////////////////////////////
1698 /// An iterator that moves out of a vector.
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 pub struct IntoIter<T> {
1701 allocation: *mut T, // the block of memory allocated for the vector
1702 cap: usize, // the capacity of the vector
1707 unsafe impl<T: Send> Send for IntoIter<T> { }
1708 unsafe impl<T: Sync> Sync for IntoIter<T> { }
1710 impl<T> IntoIter<T> {
1712 /// Drops all items that have not yet been moved and returns the empty vector.
1713 #[unstable(feature = "collections")]
1714 pub fn into_inner(mut self) -> Vec<T> {
1716 for _x in self.by_ref() { }
1717 let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
1719 Vec::from_raw_parts(allocation, 0, cap)
1724 #[stable(feature = "rust1", since = "1.0.0")]
1725 impl<T> Iterator for IntoIter<T> {
1729 fn next(&mut self) -> Option<T> {
1731 if self.ptr == self.end {
1734 if mem::size_of::<T>() == 0 {
1735 // purposefully don't use 'ptr.offset' because for
1736 // vectors with 0-size elements this would return the
1738 self.ptr = mem::transmute(self.ptr as usize + 1);
1740 // Use a non-null pointer value
1741 Some(ptr::read(EMPTY as *mut T))
1744 self.ptr = self.ptr.offset(1);
1746 Some(ptr::read(old))
1753 fn size_hint(&self) -> (usize, Option<usize>) {
1754 let diff = (self.end as usize) - (self.ptr as usize);
1755 let size = mem::size_of::<T>();
1756 let exact = diff / (if size == 0 {1} else {size});
1757 (exact, Some(exact))
1761 #[stable(feature = "rust1", since = "1.0.0")]
1762 impl<T> DoubleEndedIterator for IntoIter<T> {
1764 fn next_back(&mut self) -> Option<T> {
1766 if self.end == self.ptr {
1769 if mem::size_of::<T>() == 0 {
1770 // See above for why 'ptr.offset' isn't used
1771 self.end = mem::transmute(self.end as usize - 1);
1773 // Use a non-null pointer value
1774 Some(ptr::read(EMPTY as *mut T))
1776 self.end = self.end.offset(-1);
1778 Some(ptr::read(mem::transmute(self.end)))
1785 #[stable(feature = "rust1", since = "1.0.0")]
1786 impl<T> ExactSizeIterator for IntoIter<T> {}
1788 #[unsafe_destructor]
1789 #[stable(feature = "rust1", since = "1.0.0")]
1790 impl<T> Drop for IntoIter<T> {
1791 fn drop(&mut self) {
1792 // destroy the remaining elements
1794 for _x in self.by_ref() {}
1796 dealloc(self.allocation, self.cap);
1802 /// An iterator that drains a vector.
1803 #[unsafe_no_drop_flag]
1804 #[unstable(feature = "collections",
1805 reason = "recently added as part of collections reform 2")]
1806 pub struct Drain<'a, T:'a> {
1809 marker: PhantomData<&'a T>,
1812 unsafe impl<'a, T: Sync> Sync for Drain<'a, T> {}
1813 unsafe impl<'a, T: Send> Send for Drain<'a, T> {}
1815 #[stable(feature = "rust1", since = "1.0.0")]
1816 impl<'a, T> Iterator for Drain<'a, T> {
1820 fn next(&mut self) -> Option<T> {
1822 if self.ptr == self.end {
1825 if mem::size_of::<T>() == 0 {
1826 // purposefully don't use 'ptr.offset' because for
1827 // vectors with 0-size elements this would return the
1829 self.ptr = mem::transmute(self.ptr as usize + 1);
1831 // Use a non-null pointer value
1832 Some(ptr::read(EMPTY as *mut T))
1835 self.ptr = self.ptr.offset(1);
1837 Some(ptr::read(old))
1844 fn size_hint(&self) -> (usize, Option<usize>) {
1845 let diff = (self.end as usize) - (self.ptr as usize);
1846 let size = mem::size_of::<T>();
1847 let exact = diff / (if size == 0 {1} else {size});
1848 (exact, Some(exact))
1852 #[stable(feature = "rust1", since = "1.0.0")]
1853 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1855 fn next_back(&mut self) -> Option<T> {
1857 if self.end == self.ptr {
1860 if mem::size_of::<T>() == 0 {
1861 // See above for why 'ptr.offset' isn't used
1862 self.end = mem::transmute(self.end as usize - 1);
1864 // Use a non-null pointer value
1865 Some(ptr::read(EMPTY as *mut T))
1867 self.end = self.end.offset(-1);
1869 Some(ptr::read(self.end))
1876 #[stable(feature = "rust1", since = "1.0.0")]
1877 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1879 #[unsafe_destructor]
1880 #[stable(feature = "rust1", since = "1.0.0")]
1881 impl<'a, T> Drop for Drain<'a, T> {
1882 fn drop(&mut self) {
1883 // self.ptr == self.end == mem::POST_DROP_USIZE if drop has already been called,
1884 // so we can use #[unsafe_no_drop_flag].
1886 // destroy the remaining elements
1887 for _x in self.by_ref() {}
1891 ////////////////////////////////////////////////////////////////////////////////
1892 // Conversion from &[T] to &Vec<T>
1893 ////////////////////////////////////////////////////////////////////////////////
1895 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1896 #[unstable(feature = "collections")]
1897 pub struct DerefVec<'a, T:'a> {
1899 l: PhantomData<&'a T>,
1902 #[unstable(feature = "collections")]
1903 impl<'a, T> Deref for DerefVec<'a, T> {
1904 type Target = Vec<T>;
1906 fn deref<'b>(&'b self) -> &'b Vec<T> {
1911 // Prevent the inner `Vec<T>` from attempting to deallocate memory.
1912 #[unsafe_destructor]
1913 #[stable(feature = "rust1", since = "1.0.0")]
1914 impl<'a, T> Drop for DerefVec<'a, T> {
1915 fn drop(&mut self) {
1921 /// Converts a slice to a wrapper type providing a `&Vec<T>` reference.
1922 #[unstable(feature = "collections")]
1923 pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
1926 x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1932 ////////////////////////////////////////////////////////////////////////////////
1933 // Partial vec, used for map_in_place
1934 ////////////////////////////////////////////////////////////////////////////////
1936 /// An owned, partially type-converted vector of elements with non-zero size.
1938 /// `T` and `U` must have the same, non-zero size. They must also have the same
1941 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
1942 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
1943 /// destructed. Additionally the underlying storage of `vec` will be freed.
1944 struct PartialVecNonZeroSized<T,U> {
1952 _marker: PhantomData<U>,
1955 /// An owned, partially type-converted vector of zero-sized elements.
1957 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1959 struct PartialVecZeroSized<T,U> {
1962 marker: PhantomData<::core::cell::Cell<(T,U)>>,
1965 #[unsafe_destructor]
1966 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1967 fn drop(&mut self) {
1969 // `vec` hasn't been modified until now. As it has a length
1970 // currently, this would run destructors of `T`s which might not be
1971 // there. So at first, set `vec`s length to `0`. This must be done
1972 // at first to remain memory-safe as the destructors of `U` or `T`
1973 // might cause unwinding where `vec`s destructor would be executed.
1974 self.vec.set_len(0);
1976 // We have instances of `U`s and `T`s in `vec`. Destruct them.
1977 while self.start_u != self.end_u {
1978 let _ = ptr::read(self.start_u); // Run a `U` destructor.
1979 self.start_u = self.start_u.offset(1);
1981 while self.start_t != self.end_t {
1982 let _ = ptr::read(self.start_t); // Run a `T` destructor.
1983 self.start_t = self.start_t.offset(1);
1985 // After this destructor ran, the destructor of `vec` will run,
1986 // deallocating the underlying memory.
1991 #[unsafe_destructor]
1992 impl<T,U> Drop for PartialVecZeroSized<T,U> {
1993 fn drop(&mut self) {
1995 // Destruct the instances of `T` and `U` this struct owns.
1996 while self.num_t != 0 {
1997 let _: T = mem::uninitialized(); // Run a `T` destructor.
2000 while self.num_u != 0 {
2001 let _: U = mem::uninitialized(); // Run a `U` destructor.