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};
53 use core::borrow::{Cow, IntoCow};
55 use core::cmp::{Ordering};
56 use core::default::Default;
58 use core::hash::{self, Hash};
59 use core::iter::{repeat, FromIterator};
60 use core::marker::{ContravariantLifetime, InvariantType};
62 use core::nonzero::NonZero;
63 use core::num::{Int, UnsignedInt};
64 use core::ops::{Index, IndexMut, Deref, Add};
67 use core::raw::Slice as RawSlice;
70 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
75 /// let mut vec = Vec::new();
79 /// assert_eq!(vec.len(), 2);
80 /// assert_eq!(vec[0], 1);
82 /// assert_eq!(vec.pop(), Some(2));
83 /// assert_eq!(vec.len(), 1);
86 /// assert_eq!(vec[0], 7);
88 /// vec.push_all(&[1, 2, 3]);
90 /// for x in vec.iter() {
91 /// println!("{}", x);
93 /// assert_eq!(vec, vec![7i, 1, 2, 3]);
96 /// The `vec!` macro is provided to make initialization more convenient:
99 /// let mut vec = vec![1i, 2i, 3i];
101 /// assert_eq!(vec, vec![1, 2, 3, 4]);
104 /// Use a `Vec<T>` as an efficient stack:
107 /// let mut stack = Vec::new();
114 /// let top = match stack.pop() {
115 /// None => break, // empty
118 /// // Prints 3, 2, 1
119 /// println!("{}", top);
123 /// # Capacity and reallocation
125 /// The capacity of a vector is the amount of space allocated for any future elements that will be
126 /// added onto the vector. This is not to be confused with the *length* of a vector, which
127 /// specifies the number of actual elements within the vector. If a vector's length exceeds its
128 /// capacity, its capacity will automatically be increased, but its elements will have to be
131 /// For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10
132 /// more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or
133 /// cause reallocation to occur. However, if the vector's length is increased to 11, it will have
134 /// to reallocate, which can be slow. For this reason, it is recommended to use
135 /// `Vec::with_capacity` whenever possible to specify how big the vector is expected to get.
136 #[unsafe_no_drop_flag]
137 #[stable(feature = "rust1", since = "1.0.0")]
139 ptr: NonZero<*mut T>,
144 unsafe impl<T: Send> Send for Vec<T> { }
145 unsafe impl<T: Sync> Sync for Vec<T> { }
147 ////////////////////////////////////////////////////////////////////////////////
149 ////////////////////////////////////////////////////////////////////////////////
152 /// Constructs a new, empty `Vec<T>`.
154 /// The vector will not allocate until elements are pushed onto it.
159 /// let mut vec: Vec<int> = Vec::new();
162 #[stable(feature = "rust1", since = "1.0.0")]
163 pub fn new() -> Vec<T> {
164 // We want ptr to never be NULL so instead we set it to some arbitrary
165 // non-null value which is fine since we never call deallocate on the ptr
166 // if cap is 0. The reason for this is because the pointer of a slice
167 // being NULL would break the null pointer optimization for enums.
168 Vec { ptr: unsafe { NonZero::new(EMPTY as *mut T) }, len: 0, cap: 0 }
171 /// Constructs a new, empty `Vec<T>` with the specified capacity.
173 /// The vector will be able to hold exactly `capacity` elements without reallocating. If
174 /// `capacity` is 0, the vector will not allocate.
176 /// It is important to note that this function does not specify the *length* of the returned
177 /// vector, but only the *capacity*. (For an explanation of the difference between length and
178 /// capacity, see the main `Vec<T>` docs above, 'Capacity and reallocation'.)
183 /// let mut vec: Vec<int> = Vec::with_capacity(10);
185 /// // The vector contains no items, even though it has capacity for more
186 /// assert_eq!(vec.len(), 0);
188 /// // These are all done without reallocating...
189 /// for i in 0i..10 {
193 /// // ...but this may make the vector reallocate
197 #[stable(feature = "rust1", since = "1.0.0")]
198 pub fn with_capacity(capacity: uint) -> Vec<T> {
199 if mem::size_of::<T>() == 0 {
200 Vec { ptr: unsafe { NonZero::new(EMPTY as *mut T) }, len: 0, cap: uint::MAX }
201 } else if capacity == 0 {
204 let size = capacity.checked_mul(mem::size_of::<T>())
205 .expect("capacity overflow");
206 let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
207 if ptr.is_null() { ::alloc::oom() }
208 Vec { ptr: unsafe { NonZero::new(ptr as *mut T) }, len: 0, cap: capacity }
212 /// Creates a `Vec<T>` directly from the raw components of another vector.
214 /// This is highly unsafe, due to the number of invariants that aren't checked.
223 /// let mut v = vec![1i, 2, 3];
225 /// // Pull out the various important pieces of information about `v`
226 /// let p = v.as_mut_ptr();
227 /// let len = v.len();
228 /// let cap = v.capacity();
231 /// // Cast `v` into the void: no destructor run, so we are in
232 /// // complete control of the allocation to which `p` points.
235 /// // Overwrite memory with 4, 5, 6
236 /// for i in 0..len as int {
237 /// ptr::write(p.offset(i), 4 + i);
240 /// // Put everything back together into a Vec
241 /// let rebuilt = Vec::from_raw_parts(p, len, cap);
242 /// assert_eq!(rebuilt, vec![4i, 5i, 6i]);
246 #[stable(feature = "rust1", since = "1.0.0")]
247 pub unsafe fn from_raw_parts(ptr: *mut T, length: uint,
248 capacity: uint) -> Vec<T> {
249 Vec { ptr: NonZero::new(ptr), len: length, cap: capacity }
252 /// Creates a vector by copying the elements from a raw pointer.
254 /// This function will copy `elts` contiguous elements starting at `ptr` into a new allocation
255 /// owned by the returned `Vec<T>`. The elements of the buffer are copied into the vector
256 /// without cloning, as if `ptr::read()` were called on them.
258 #[unstable(feature = "collections",
259 reason = "may be better expressed via composition")]
260 pub unsafe fn from_raw_buf(ptr: *const T, elts: uint) -> Vec<T> {
261 let mut dst = Vec::with_capacity(elts);
263 ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
267 /// Returns the number of elements the vector can hold without
273 /// let vec: Vec<int> = Vec::with_capacity(10);
274 /// assert_eq!(vec.capacity(), 10);
277 #[stable(feature = "rust1", since = "1.0.0")]
278 pub fn capacity(&self) -> uint {
282 /// Reserves capacity for at least `additional` more elements to be inserted in the given
283 /// `Vec<T>`. The collection may reserve more space to avoid frequent reallocations.
287 /// Panics if the new capacity overflows `uint`.
292 /// let mut vec: Vec<int> = vec![1];
294 /// assert!(vec.capacity() >= 11);
296 #[stable(feature = "rust1", since = "1.0.0")]
297 pub fn reserve(&mut self, additional: uint) {
298 if self.cap - self.len < additional {
299 let err_msg = "Vec::reserve: `uint` overflow";
300 let new_cap = self.len.checked_add(additional).expect(err_msg)
301 .checked_next_power_of_two().expect(err_msg);
302 self.grow_capacity(new_cap);
306 /// Reserves the minimum capacity for exactly `additional` more elements to
307 /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
310 /// Note that the allocator may give the collection more space than it
311 /// requests. Therefore capacity can not be relied upon to be precisely
312 /// minimal. Prefer `reserve` if future insertions are expected.
316 /// Panics if the new capacity overflows `uint`.
321 /// let mut vec: Vec<int> = vec![1];
322 /// vec.reserve_exact(10);
323 /// assert!(vec.capacity() >= 11);
325 #[stable(feature = "rust1", since = "1.0.0")]
326 pub fn reserve_exact(&mut self, additional: uint) {
327 if self.cap - self.len < additional {
328 match self.len.checked_add(additional) {
329 None => panic!("Vec::reserve: `uint` overflow"),
330 Some(new_cap) => self.grow_capacity(new_cap)
335 /// Shrinks the capacity of the vector as much as possible.
337 /// It will drop down as close as possible to the length but the allocator
338 /// may still inform the vector that there is space for a few more elements.
343 /// let mut vec: Vec<int> = Vec::with_capacity(10);
344 /// vec.push_all(&[1, 2, 3]);
345 /// assert_eq!(vec.capacity(), 10);
346 /// vec.shrink_to_fit();
347 /// assert!(vec.capacity() >= 3);
349 #[stable(feature = "rust1", since = "1.0.0")]
350 pub fn shrink_to_fit(&mut self) {
351 if mem::size_of::<T>() == 0 { return }
356 dealloc(*self.ptr, self.cap)
360 } else if self.cap != self.len {
362 // Overflow check is unnecessary as the vector is already at
364 let ptr = reallocate(*self.ptr as *mut u8,
365 self.cap * mem::size_of::<T>(),
366 self.len * mem::size_of::<T>(),
367 mem::min_align_of::<T>()) as *mut T;
368 if ptr.is_null() { ::alloc::oom() }
369 self.ptr = NonZero::new(ptr);
375 /// Convert the vector into Box<[T]>.
377 /// Note that this will drop any excess capacity. Calling this and
378 /// converting back to a vector with `into_vec()` is equivalent to calling
379 /// `shrink_to_fit()`.
380 #[unstable(feature = "collections")]
381 pub fn into_boxed_slice(mut self) -> Box<[T]> {
382 self.shrink_to_fit();
384 let xs: Box<[T]> = mem::transmute(self.as_mut_slice());
390 /// Shorten a vector, dropping excess elements.
392 /// If `len` is greater than the vector's current length, this has no
398 /// let mut vec = vec![1i, 2, 3, 4];
400 /// assert_eq!(vec, vec![1, 2]);
402 #[stable(feature = "rust1", since = "1.0.0")]
403 pub fn truncate(&mut self, len: uint) {
405 // drop any extra elements
406 while len < self.len {
407 // decrement len before the read(), so a panic on Drop doesn't
408 // re-drop the just-failed value.
410 ptr::read(self.get_unchecked(self.len));
415 /// Returns a mutable slice of the elements of `self`.
420 /// fn foo(slice: &mut [int]) {}
422 /// let mut vec = vec![1i, 2];
423 /// foo(vec.as_mut_slice());
426 #[stable(feature = "rust1", since = "1.0.0")]
427 pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
429 mem::transmute(RawSlice {
436 /// Creates a consuming iterator, that is, one that moves each value out of
437 /// the vector (from start to end). The vector cannot be used after calling
443 /// let v = vec!["a".to_string(), "b".to_string()];
444 /// for s in v.into_iter() {
445 /// // s has type String, not &String
446 /// println!("{}", s);
450 #[stable(feature = "rust1", since = "1.0.0")]
451 pub fn into_iter(self) -> IntoIter<T> {
455 let begin = ptr as *const T;
456 let end = if mem::size_of::<T>() == 0 {
457 (ptr as uint + self.len()) as *const T
459 ptr.offset(self.len() as int) as *const T
462 IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end }
466 /// Sets the length of a vector.
468 /// This will explicitly set the size of the vector, without actually
469 /// modifying its buffers, so it is up to the caller to ensure that the
470 /// vector is actually the specified size.
475 /// let mut v = vec![1u, 2, 3, 4];
481 #[stable(feature = "rust1", since = "1.0.0")]
482 pub unsafe fn set_len(&mut self, len: uint) {
486 /// Removes an element from anywhere in the vector and return it, replacing
487 /// it with the last element.
489 /// This does not preserve ordering, but is O(1).
493 /// Panics if `index` is out of bounds.
498 /// let mut v = vec!["foo", "bar", "baz", "qux"];
500 /// assert_eq!(v.swap_remove(1), "bar");
501 /// assert_eq!(v, vec!["foo", "qux", "baz"]);
503 /// assert_eq!(v.swap_remove(0), "foo");
504 /// assert_eq!(v, vec!["baz", "qux"]);
507 #[stable(feature = "rust1", since = "1.0.0")]
508 pub fn swap_remove(&mut self, index: uint) -> T {
509 let length = self.len();
510 self.swap(index, length - 1);
514 /// Inserts an element at position `index` within the vector, shifting all
515 /// elements after position `i` one position to the right.
519 /// Panics if `index` is not between `0` and the vector's length (both
520 /// bounds inclusive).
525 /// let mut vec = vec![1i, 2, 3];
526 /// vec.insert(1, 4);
527 /// assert_eq!(vec, vec![1, 4, 2, 3]);
528 /// vec.insert(4, 5);
529 /// assert_eq!(vec, vec![1, 4, 2, 3, 5]);
531 #[stable(feature = "rust1", since = "1.0.0")]
532 pub fn insert(&mut self, index: uint, element: T) {
533 let len = self.len();
534 assert!(index <= len);
535 // space for the new element
538 unsafe { // infallible
539 // The spot to put the new value
541 let p = self.as_mut_ptr().offset(index as int);
542 // Shift everything over to make space. (Duplicating the
543 // `index`th element into two consecutive places.)
544 ptr::copy_memory(p.offset(1), &*p, len - index);
545 // Write it in, overwriting the first copy of the `index`th
547 ptr::write(&mut *p, element);
549 self.set_len(len + 1);
553 /// Removes and returns the element at position `index` within the vector,
554 /// shifting all elements after position `index` one position to the left.
558 /// Panics if `i` is out of bounds.
563 /// let mut v = vec![1i, 2, 3];
564 /// assert_eq!(v.remove(1), 2);
565 /// assert_eq!(v, vec![1, 3]);
567 #[stable(feature = "rust1", since = "1.0.0")]
568 pub fn remove(&mut self, index: uint) -> T {
569 let len = self.len();
570 assert!(index < len);
571 unsafe { // infallible
574 // the place we are taking from.
575 let ptr = self.as_mut_ptr().offset(index as int);
576 // copy it out, unsafely having a copy of the value on
577 // the stack and in the vector at the same time.
578 ret = ptr::read(ptr);
580 // Shift everything down to fill in that spot.
581 ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
583 self.set_len(len - 1);
588 /// Retains only the elements specified by the predicate.
590 /// In other words, remove all elements `e` such that `f(&e)` returns false.
591 /// This method operates in place and preserves the order of the retained
597 /// let mut vec = vec![1i, 2, 3, 4];
598 /// vec.retain(|&x| x%2 == 0);
599 /// assert_eq!(vec, vec![2, 4]);
601 #[stable(feature = "rust1", since = "1.0.0")]
602 pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
603 let len = self.len();
606 let v = self.as_mut_slice();
617 self.truncate(len - del);
621 /// Appends an element to the back of a collection.
625 /// Panics if the number of elements in the vector overflows a `uint`.
630 /// let mut vec = vec!(1i, 2);
632 /// assert_eq!(vec, vec!(1, 2, 3));
635 #[stable(feature = "rust1", since = "1.0.0")]
636 pub fn push(&mut self, value: T) {
637 if mem::size_of::<T>() == 0 {
638 // zero-size types consume no memory, so we can't rely on the
639 // address space running out
640 self.len = self.len.checked_add(1).expect("length overflow");
641 unsafe { mem::forget(value); }
644 if self.len == self.cap {
645 let old_size = self.cap * mem::size_of::<T>();
646 let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
647 if old_size > size { panic!("capacity overflow") }
649 let ptr = alloc_or_realloc(*self.ptr, old_size, size);
650 if ptr.is_null() { ::alloc::oom() }
651 self.ptr = NonZero::new(ptr);
653 self.cap = max(self.cap, 2) * 2;
657 let end = (*self.ptr).offset(self.len as int);
658 ptr::write(&mut *end, value);
663 /// Removes the last element from a vector and returns it, or `None` if it is empty.
668 /// let mut vec = vec![1i, 2, 3];
669 /// assert_eq!(vec.pop(), Some(3));
670 /// assert_eq!(vec, vec![1, 2]);
673 #[stable(feature = "rust1", since = "1.0.0")]
674 pub fn pop(&mut self) -> Option<T> {
680 Some(ptr::read(self.get_unchecked(self.len())))
685 /// Moves all the elements of `other` into `Self`, leaving `other` empty.
689 /// Panics if the number of elements in the vector overflows a `uint`.
693 /// let mut vec = vec![1, 2, 3];
694 /// let mut vec2 = vec![4, 5, 6];
695 /// vec.append(&mut vec2);
696 /// assert_eq!(vec, vec![1, 2, 3, 4, 5, 6]);
697 /// assert_eq!(vec2, vec![]);
700 #[unstable(feature = "collections",
701 reason = "new API, waiting for dust to settle")]
702 pub fn append(&mut self, other: &mut Self) {
703 if mem::size_of::<T>() == 0 {
704 // zero-size types consume no memory, so we can't rely on the
705 // address space running out
706 self.len = self.len.checked_add(other.len()).expect("length overflow");
707 unsafe { other.set_len(0) }
710 self.reserve(other.len());
711 let len = self.len();
713 ptr::copy_nonoverlapping_memory(
714 self.get_unchecked_mut(len),
719 self.len += other.len();
720 unsafe { other.set_len(0); }
723 /// Creates a draining iterator that clears the `Vec` and iterates over
724 /// the removed items from start to end.
729 /// let mut v = vec!["a".to_string(), "b".to_string()];
730 /// for s in v.drain() {
731 /// // s has type String, not &String
732 /// println!("{}", s);
734 /// assert!(v.is_empty());
737 #[unstable(feature = "collections",
738 reason = "matches collection reform specification, waiting for dust to settle")]
739 pub fn drain<'a>(&'a mut self) -> Drain<'a, T> {
741 let begin = *self.ptr as *const T;
742 let end = if mem::size_of::<T>() == 0 {
743 (*self.ptr as uint + self.len()) as *const T
745 (*self.ptr).offset(self.len() as int) as *const T
751 marker: ContravariantLifetime,
756 /// Clears the vector, removing all values.
761 /// let mut v = vec![1i, 2, 3];
765 /// assert!(v.is_empty());
768 #[stable(feature = "rust1", since = "1.0.0")]
769 pub fn clear(&mut self) {
773 /// Returns the number of elements in the vector.
778 /// let a = vec![1i, 2, 3];
779 /// assert_eq!(a.len(), 3);
782 #[stable(feature = "rust1", since = "1.0.0")]
783 pub fn len(&self) -> uint { self.len }
785 /// Returns `true` if the vector contains no elements.
790 /// let mut v = Vec::new();
791 /// assert!(v.is_empty());
794 /// assert!(!v.is_empty());
796 #[stable(feature = "rust1", since = "1.0.0")]
797 pub fn is_empty(&self) -> bool { self.len() == 0 }
799 /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same
800 /// size and in case they are not zero-sized the same minimal alignment.
804 /// Panics if `T` and `U` have differing sizes or are not zero-sized and
805 /// have differing minimal alignments.
810 /// let v = vec![0u, 1, 2];
811 /// let w = v.map_in_place(|i| i + 3);
812 /// assert_eq!(w.as_slice(), [3, 4, 5].as_slice());
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.as_slice(), [Newtype(0x11), Newtype(0x22)].as_slice());
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 int` 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 `int` 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 `uint` ->
853 // `int` conversion can't overflow.
854 let offset = vec.len() as int;
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,
876 while pv.end_u as *mut T != pv.end_t {
880 // +-+-+-+-+-+-+-+-+-+
881 // |U|...|U|T|T|...|T|
882 // +-+-+-+-+-+-+-+-+-+
886 let t = ptr::read(pv.start_t);
889 // +-+-+-+-+-+-+-+-+-+
890 // |U|...|U|X|T|...|T|
891 // +-+-+-+-+-+-+-+-+-+
894 // We must not panic here, one cell is marked as `T`
895 // although it is not `T`.
897 pv.start_t = pv.start_t.offset(1);
900 // +-+-+-+-+-+-+-+-+-+
901 // |U|...|U|X|T|...|T|
902 // +-+-+-+-+-+-+-+-+-+
905 // We may panic again.
907 // The function given by the user might panic.
910 ptr::write(pv.end_u, u);
913 // +-+-+-+-+-+-+-+-+-+
914 // |U|...|U|U|T|...|T|
915 // +-+-+-+-+-+-+-+-+-+
918 // We should not panic here, because that would leak the `U`
919 // pointed to by `end_u`.
921 pv.end_u = pv.end_u.offset(1);
924 // +-+-+-+-+-+-+-+-+-+
925 // |U|...|U|U|T|...|T|
926 // +-+-+-+-+-+-+-+-+-+
929 // We may panic again.
941 // Extract `vec` and prevent the destructor of
942 // `PartialVecNonZeroSized` from running. Note that none of the
943 // function calls can panic, thus no resources can be leaked (as the
944 // `vec` member of `PartialVec` is the only one which holds
945 // allocations -- and it is returned from this function. None of
948 let vec_len = pv.vec.len();
949 let vec_cap = pv.vec.capacity();
950 let vec_ptr = pv.vec.as_mut_ptr() as *mut U;
952 Vec::from_raw_parts(vec_ptr, vec_len, vec_cap)
955 // Put the `Vec` into the `PartialVecZeroSized` structure and
956 // prevent the destructor of the `Vec` from running. Since the
957 // `Vec` contained zero-sized objects, it did not allocate, so we
958 // are not leaking memory here.
959 let mut pv = PartialVecZeroSized::<T,U> {
962 marker_t: InvariantType,
963 marker_u: InvariantType,
965 unsafe { mem::forget(vec); }
967 while pv.num_t != 0 {
969 // Create a `T` out of thin air and decrement `num_t`. This
970 // must not panic between these steps, as otherwise a
971 // destructor of `T` which doesn't exist runs.
972 let t = mem::uninitialized();
975 // The function given by the user might panic.
978 // Forget the `U` and increment `num_u`. This increment
979 // cannot overflow the `uint` as we only do this for a
980 // number of times that fits into a `uint` (and start with
981 // `0`). Again, we should not panic between these steps.
986 // Create a `Vec` from our `PartialVecZeroSized` and make sure the
987 // destructor of the latter will not run. None of this can panic.
988 let mut result = Vec::new();
990 result.set_len(pv.num_u);
997 /// Splits the collection into two at the given index.
999 /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1000 /// and the returned `Self` contains elements `[at, len)`.
1002 /// Note that the capacity of `self` does not change.
1006 /// let mut vec = vec![1,2,3];
1007 /// let vec2 = vec.split_off(1);
1008 /// assert_eq!(vec, vec![1]);
1009 /// assert_eq!(vec2, vec![2, 3]);
1012 #[unstable(feature = "collections",
1013 reason = "new API, waiting for dust to settle")]
1014 pub fn split_off(&mut self, at: usize) -> Self {
1015 assert!(at < self.len(), "`at` out of bounds");
1017 let other_len = self.len - at;
1018 let mut other = Vec::with_capacity(other_len);
1020 // Unsafely `set_len` and copy items to `other`.
1023 other.set_len(other_len);
1025 ptr::copy_nonoverlapping_memory(
1027 self.as_ptr().offset(at as isize),
1035 impl<T: Clone> Vec<T> {
1036 /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1038 /// Calls either `extend()` or `truncate()` depending on whether `new_len`
1039 /// is larger than the current value of `len()` or not.
1044 /// let mut vec = vec!["hello"];
1045 /// vec.resize(3, "world");
1046 /// assert_eq!(vec, vec!["hello", "world", "world"]);
1048 /// let mut vec = vec![1i, 2, 3, 4];
1049 /// vec.resize(2, 0);
1050 /// assert_eq!(vec, vec![1, 2]);
1052 #[unstable(feature = "collections",
1053 reason = "matches collection reform specification; waiting for dust to settle")]
1054 pub fn resize(&mut self, new_len: uint, value: T) {
1055 let len = self.len();
1058 self.extend(repeat(value).take(new_len - len));
1060 self.truncate(new_len);
1064 /// Appends all elements in a slice to the `Vec`.
1066 /// Iterates over the slice `other`, clones each element, and then appends
1067 /// it to this `Vec`. The `other` vector is traversed in-order.
1072 /// let mut vec = vec![1i];
1073 /// vec.push_all(&[2i, 3, 4]);
1074 /// assert_eq!(vec, vec![1, 2, 3, 4]);
1077 #[unstable(feature = "collections",
1078 reason = "likely to be replaced by a more optimized extend")]
1079 pub fn push_all(&mut self, other: &[T]) {
1080 self.reserve(other.len());
1082 for i in 0..other.len() {
1083 let len = self.len();
1085 // Unsafe code so this can be optimised to a memcpy (or something similarly
1086 // fast) when T is Copy. LLVM is easily confused, so any extra operations
1087 // during the loop can prevent this optimisation.
1090 self.get_unchecked_mut(len),
1091 other.get_unchecked(i).clone());
1092 self.set_len(len + 1);
1098 impl<T: PartialEq> Vec<T> {
1099 /// Removes consecutive repeated elements in the vector.
1101 /// If the vector is sorted, this removes all duplicates.
1106 /// let mut vec = vec![1i, 2, 2, 3, 2];
1110 /// assert_eq!(vec, vec![1i, 2, 3, 2]);
1112 #[stable(feature = "rust1", since = "1.0.0")]
1113 pub fn dedup(&mut self) {
1115 // Although we have a mutable reference to `self`, we cannot make
1116 // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1117 // must ensure that the vector is in a valid state at all time.
1119 // The way that we handle this is by using swaps; we iterate
1120 // over all the elements, swapping as we go so that at the end
1121 // the elements we wish to keep are in the front, and those we
1122 // wish to reject are at the back. We can then truncate the
1123 // vector. This operation is still O(n).
1125 // Example: We start in this state, where `r` represents "next
1126 // read" and `w` represents "next_write`.
1129 // +---+---+---+---+---+---+
1130 // | 0 | 1 | 1 | 2 | 3 | 3 |
1131 // +---+---+---+---+---+---+
1134 // Comparing self[r] against self[w-1], this is not a duplicate, so
1135 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1136 // r and w, leaving us with:
1139 // +---+---+---+---+---+---+
1140 // | 0 | 1 | 1 | 2 | 3 | 3 |
1141 // +---+---+---+---+---+---+
1144 // Comparing self[r] against self[w-1], this value is a duplicate,
1145 // so we increment `r` but leave everything else unchanged:
1148 // +---+---+---+---+---+---+
1149 // | 0 | 1 | 1 | 2 | 3 | 3 |
1150 // +---+---+---+---+---+---+
1153 // Comparing self[r] against self[w-1], this is not a duplicate,
1154 // so swap self[r] and self[w] and advance r and w:
1157 // +---+---+---+---+---+---+
1158 // | 0 | 1 | 2 | 1 | 3 | 3 |
1159 // +---+---+---+---+---+---+
1162 // Not a duplicate, repeat:
1165 // +---+---+---+---+---+---+
1166 // | 0 | 1 | 2 | 3 | 1 | 3 |
1167 // +---+---+---+---+---+---+
1170 // Duplicate, advance r. End of vec. Truncate to w.
1172 let ln = self.len();
1173 if ln < 1 { return; }
1175 // Avoid bounds checks by using unsafe pointers.
1176 let p = self.as_mut_ptr();
1181 let p_r = p.offset(r as int);
1182 let p_wm1 = p.offset((w - 1) as int);
1185 let p_w = p_wm1.offset(1);
1186 mem::swap(&mut *p_r, &mut *p_w);
1198 ////////////////////////////////////////////////////////////////////////////////
1199 // Internal methods and functions
1200 ////////////////////////////////////////////////////////////////////////////////
1203 /// Reserves capacity for exactly `capacity` elements in the given vector.
1205 /// If the capacity for `self` is already equal to or greater than the
1206 /// requested capacity, then no action is taken.
1207 fn grow_capacity(&mut self, capacity: uint) {
1208 if mem::size_of::<T>() == 0 { return }
1210 if capacity > self.cap {
1211 let size = capacity.checked_mul(mem::size_of::<T>())
1212 .expect("capacity overflow");
1214 let ptr = alloc_or_realloc(*self.ptr, self.cap * mem::size_of::<T>(), size);
1215 if ptr.is_null() { ::alloc::oom() }
1216 self.ptr = NonZero::new(ptr);
1218 self.cap = capacity;
1223 // FIXME: #13996: need a way to mark the return value as `noalias`
1225 unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: uint, size: uint) -> *mut T {
1227 allocate(size, mem::min_align_of::<T>()) as *mut T
1229 reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T
1234 unsafe fn dealloc<T>(ptr: *mut T, len: uint) {
1235 if mem::size_of::<T>() != 0 {
1236 deallocate(ptr as *mut u8,
1237 len * mem::size_of::<T>(),
1238 mem::min_align_of::<T>())
1242 ////////////////////////////////////////////////////////////////////////////////
1243 // Common trait implementations for Vec
1244 ////////////////////////////////////////////////////////////////////////////////
1246 #[unstable(feature = "collections")]
1247 impl<T:Clone> Clone for Vec<T> {
1248 fn clone(&self) -> Vec<T> { ::slice::SliceExt::to_vec(self.as_slice()) }
1250 fn clone_from(&mut self, other: &Vec<T>) {
1251 // drop anything in self that will not be overwritten
1252 if self.len() > other.len() {
1253 self.truncate(other.len())
1256 // reuse the contained values' allocations/resources.
1257 for (place, thing) in self.iter_mut().zip(other.iter()) {
1258 place.clone_from(thing)
1261 // self.len <= other.len due to the truncate above, so the
1262 // slice here is always in-bounds.
1263 let slice = &other[self.len()..];
1264 self.push_all(slice);
1268 impl<S: hash::Writer + hash::Hasher, T: Hash<S>> Hash<S> for Vec<T> {
1270 fn hash(&self, state: &mut S) {
1271 self.as_slice().hash(state);
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 impl<T> Index<uint> for Vec<T> {
1280 fn index<'a>(&'a self, index: &uint) -> &'a T {
1281 &self.as_slice()[*index]
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl<T> IndexMut<uint> for Vec<T> {
1290 fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
1291 &mut self.as_mut_slice()[*index]
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 impl<T> ops::Index<ops::Range<uint>> for Vec<T> {
1300 fn index(&self, index: &ops::Range<uint>) -> &[T] {
1301 self.as_slice().index(index)
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<T> ops::Index<ops::RangeTo<uint>> for Vec<T> {
1308 fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
1309 self.as_slice().index(index)
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<T> ops::Index<ops::RangeFrom<uint>> for Vec<T> {
1316 fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
1317 self.as_slice().index(index)
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<T> ops::Index<ops::FullRange> for Vec<T> {
1325 fn index(&self, _index: &ops::FullRange) -> &[T] {
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1334 fn index(&self, _index: &ops::RangeFull) -> &[T] {
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl<T> ops::IndexMut<ops::Range<uint>> for Vec<T> {
1343 fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
1344 self.as_mut_slice().index_mut(index)
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 impl<T> ops::IndexMut<ops::RangeTo<uint>> for Vec<T> {
1351 fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
1352 self.as_mut_slice().index_mut(index)
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 impl<T> ops::IndexMut<ops::RangeFrom<uint>> for Vec<T> {
1359 fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
1360 self.as_mut_slice().index_mut(index)
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 impl<T> ops::IndexMut<ops::FullRange> for Vec<T> {
1368 fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1377 fn index_mut(&mut self, _index: &ops::RangeFull) -> &mut [T] {
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 impl<T> ops::Deref for Vec<T> {
1386 fn deref<'a>(&'a self) -> &'a [T] { self.as_slice() }
1389 #[stable(feature = "rust1", since = "1.0.0")]
1390 impl<T> ops::DerefMut for Vec<T> {
1391 fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.as_mut_slice() }
1394 #[stable(feature = "rust1", since = "1.0.0")]
1395 impl<T> FromIterator<T> for Vec<T> {
1397 fn from_iter<I:Iterator<Item=T>>(mut iterator: I) -> Vec<T> {
1398 let (lower, _) = iterator.size_hint();
1399 let mut vector = Vec::with_capacity(lower);
1400 for element in iterator {
1401 vector.push(element)
1407 #[unstable(feature = "collections", reason = "waiting on Extend stability")]
1408 impl<T> Extend<T> for Vec<T> {
1410 fn extend<I: Iterator<Item=T>>(&mut self, mut iterator: I) {
1411 let (lower, _) = iterator.size_hint();
1412 self.reserve(lower);
1413 for element in iterator {
1419 impl<A, B> PartialEq<Vec<B>> for Vec<A> where A: PartialEq<B> {
1421 fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1423 fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1426 macro_rules! impl_eq {
1427 ($lhs:ty, $rhs:ty) => {
1428 impl<'b, A, B> PartialEq<$rhs> for $lhs where A: PartialEq<B> {
1430 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1432 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1435 impl<'b, A, B> PartialEq<$lhs> for $rhs where B: PartialEq<A> {
1437 fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
1439 fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
1444 impl_eq! { Vec<A>, &'b [B] }
1445 impl_eq! { Vec<A>, &'b mut [B] }
1447 impl<'a, A, B> PartialEq<Vec<B>> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1449 fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1451 fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1454 impl<'a, A, B> PartialEq<CowVec<'a, A>> for Vec<B> where A: Clone, B: PartialEq<A> {
1456 fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1458 fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1461 macro_rules! impl_eq_for_cowvec {
1463 impl<'a, 'b, A, B> PartialEq<$rhs> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1465 fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1467 fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1470 impl<'a, 'b, A, B> PartialEq<CowVec<'a, A>> for $rhs where A: Clone, B: PartialEq<A> {
1472 fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1474 fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1479 impl_eq_for_cowvec! { &'b [B] }
1480 impl_eq_for_cowvec! { &'b mut [B] }
1482 #[unstable(feature = "collections",
1483 reason = "waiting on PartialOrd stability")]
1484 impl<T: PartialOrd> PartialOrd for Vec<T> {
1486 fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1487 self.as_slice().partial_cmp(other.as_slice())
1491 #[unstable(feature = "collections", reason = "waiting on Eq stability")]
1492 impl<T: Eq> Eq for Vec<T> {}
1494 #[unstable(feature = "collections", reason = "waiting on Ord stability")]
1495 impl<T: Ord> Ord for Vec<T> {
1497 fn cmp(&self, other: &Vec<T>) -> Ordering {
1498 self.as_slice().cmp(other.as_slice())
1502 impl<T> AsSlice<T> for Vec<T> {
1503 /// Returns a slice into `self`.
1508 /// fn foo(slice: &[int]) {}
1510 /// let vec = vec![1i, 2];
1511 /// foo(vec.as_slice());
1514 #[stable(feature = "rust1", since = "1.0.0")]
1515 fn as_slice<'a>(&'a self) -> &'a [T] {
1517 mem::transmute(RawSlice {
1525 #[unstable(feature = "collections",
1526 reason = "recent addition, needs more experience")]
1527 impl<'a, T: Clone> Add<&'a [T]> for Vec<T> {
1528 type Output = Vec<T>;
1531 fn add(mut self, rhs: &[T]) -> Vec<T> {
1537 #[unsafe_destructor]
1538 #[stable(feature = "rust1", since = "1.0.0")]
1539 impl<T> Drop for Vec<T> {
1540 fn drop(&mut self) {
1541 // This is (and should always remain) a no-op if the fields are
1542 // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1545 for x in self.iter() {
1548 dealloc(*self.ptr, self.cap)
1554 #[stable(feature = "rust1", since = "1.0.0")]
1555 impl<T> Default for Vec<T> {
1556 #[stable(feature = "rust1", since = "1.0.0")]
1557 fn default() -> Vec<T> {
1562 #[stable(feature = "rust1", since = "1.0.0")]
1563 impl<T: fmt::Debug> fmt::Debug for Vec<T> {
1564 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1565 fmt::Debug::fmt(self.as_slice(), f)
1569 impl<'a> fmt::Writer for Vec<u8> {
1570 fn write_str(&mut self, s: &str) -> fmt::Result {
1571 self.push_all(s.as_bytes());
1576 ////////////////////////////////////////////////////////////////////////////////
1578 ////////////////////////////////////////////////////////////////////////////////
1580 #[unstable(feature = "collections",
1581 reason = "unclear how valuable this alias is")]
1582 /// A clone-on-write vector
1583 pub type CowVec<'a, T> = Cow<'a, Vec<T>, [T]>;
1585 #[unstable(feature = "collections")]
1586 impl<'a, T> FromIterator<T> for CowVec<'a, T> where T: Clone {
1587 fn from_iter<I: Iterator<Item=T>>(it: I) -> CowVec<'a, T> {
1588 Cow::Owned(FromIterator::from_iter(it))
1592 impl<'a, T: 'a> IntoCow<'a, Vec<T>, [T]> for Vec<T> where T: Clone {
1593 fn into_cow(self) -> CowVec<'a, T> {
1598 impl<'a, T> IntoCow<'a, Vec<T>, [T]> for &'a [T] where T: Clone {
1599 fn into_cow(self) -> CowVec<'a, T> {
1604 ////////////////////////////////////////////////////////////////////////////////
1606 ////////////////////////////////////////////////////////////////////////////////
1608 /// An iterator that moves out of a vector.
1609 #[stable(feature = "rust1", since = "1.0.0")]
1610 pub struct IntoIter<T> {
1611 allocation: *mut T, // the block of memory allocated for the vector
1612 cap: uint, // the capacity of the vector
1617 unsafe impl<T: Send> Send for IntoIter<T> { }
1618 unsafe impl<T: Sync> Sync for IntoIter<T> { }
1620 impl<T> IntoIter<T> {
1622 /// Drops all items that have not yet been moved and returns the empty vector.
1623 #[unstable(feature = "collections")]
1624 pub fn into_inner(mut self) -> Vec<T> {
1627 let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
1629 Vec { ptr: NonZero::new(allocation), cap: cap, len: 0 }
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 impl<T> Iterator for IntoIter<T> {
1639 fn next<'a>(&'a mut self) -> Option<T> {
1641 if self.ptr == self.end {
1644 if mem::size_of::<T>() == 0 {
1645 // purposefully don't use 'ptr.offset' because for
1646 // vectors with 0-size elements this would return the
1648 self.ptr = mem::transmute(self.ptr as uint + 1);
1650 // Use a non-null pointer value
1651 Some(ptr::read(mem::transmute(1u)))
1654 self.ptr = self.ptr.offset(1);
1656 Some(ptr::read(old))
1663 fn size_hint(&self) -> (uint, Option<uint>) {
1664 let diff = (self.end as uint) - (self.ptr as uint);
1665 let size = mem::size_of::<T>();
1666 let exact = diff / (if size == 0 {1} else {size});
1667 (exact, Some(exact))
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<T> DoubleEndedIterator for IntoIter<T> {
1674 fn next_back<'a>(&'a mut self) -> Option<T> {
1676 if self.end == self.ptr {
1679 if mem::size_of::<T>() == 0 {
1680 // See above for why 'ptr.offset' isn't used
1681 self.end = mem::transmute(self.end as uint - 1);
1683 // Use a non-null pointer value
1684 Some(ptr::read(mem::transmute(1u)))
1686 self.end = self.end.offset(-1);
1688 Some(ptr::read(mem::transmute(self.end)))
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<T> ExactSizeIterator for IntoIter<T> {}
1698 #[unsafe_destructor]
1699 #[stable(feature = "rust1", since = "1.0.0")]
1700 impl<T> Drop for IntoIter<T> {
1701 fn drop(&mut self) {
1702 // destroy the remaining elements
1706 dealloc(self.allocation, self.cap);
1712 /// An iterator that drains a vector.
1713 #[unsafe_no_drop_flag]
1714 #[unstable(feature = "collections",
1715 reason = "recently added as part of collections reform 2")]
1716 pub struct Drain<'a, T> {
1719 marker: ContravariantLifetime<'a>,
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl<'a, T> Iterator for Drain<'a, T> {
1727 fn next(&mut self) -> Option<T> {
1729 if self.ptr == self.end {
1732 if mem::size_of::<T>() == 0 {
1733 // purposefully don't use 'ptr.offset' because for
1734 // vectors with 0-size elements this would return the
1736 self.ptr = mem::transmute(self.ptr as uint + 1);
1738 // Use a non-null pointer value
1739 Some(ptr::read(mem::transmute(1u)))
1742 self.ptr = self.ptr.offset(1);
1744 Some(ptr::read(old))
1751 fn size_hint(&self) -> (uint, Option<uint>) {
1752 let diff = (self.end as uint) - (self.ptr as uint);
1753 let size = mem::size_of::<T>();
1754 let exact = diff / (if size == 0 {1} else {size});
1755 (exact, Some(exact))
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1762 fn next_back(&mut self) -> Option<T> {
1764 if self.end == self.ptr {
1767 if mem::size_of::<T>() == 0 {
1768 // See above for why 'ptr.offset' isn't used
1769 self.end = mem::transmute(self.end as uint - 1);
1771 // Use a non-null pointer value
1772 Some(ptr::read(mem::transmute(1u)))
1774 self.end = self.end.offset(-1);
1776 Some(ptr::read(self.end))
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1786 #[unsafe_destructor]
1787 #[stable(feature = "rust1", since = "1.0.0")]
1788 impl<'a, T> Drop for Drain<'a, T> {
1789 fn drop(&mut self) {
1790 // self.ptr == self.end == null if drop has already been called,
1791 // so we can use #[unsafe_no_drop_flag].
1793 // destroy the remaining elements
1798 ////////////////////////////////////////////////////////////////////////////////
1799 // Conversion from &[T] to &Vec<T>
1800 ////////////////////////////////////////////////////////////////////////////////
1802 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1803 #[unstable(feature = "collections")]
1804 pub struct DerefVec<'a, T> {
1806 l: ContravariantLifetime<'a>
1809 #[unstable(feature = "collections")]
1810 impl<'a, T> Deref for DerefVec<'a, T> {
1811 type Target = Vec<T>;
1813 fn deref<'b>(&'b self) -> &'b Vec<T> {
1818 // Prevent the inner `Vec<T>` from attempting to deallocate memory.
1819 #[unsafe_destructor]
1820 #[stable(feature = "rust1", since = "1.0.0")]
1821 impl<'a, T> Drop for DerefVec<'a, T> {
1822 fn drop(&mut self) {
1828 /// Convert a slice to a wrapper type providing a `&Vec<T>` reference.
1829 #[unstable(feature = "collections")]
1830 pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
1833 x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1834 l: ContravariantLifetime::<'a>
1839 ////////////////////////////////////////////////////////////////////////////////
1840 // Partial vec, used for map_in_place
1841 ////////////////////////////////////////////////////////////////////////////////
1843 /// An owned, partially type-converted vector of elements with non-zero size.
1845 /// `T` and `U` must have the same, non-zero size. They must also have the same
1848 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
1849 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
1850 /// destructed. Additionally the underlying storage of `vec` will be freed.
1851 struct PartialVecNonZeroSized<T,U> {
1860 /// An owned, partially type-converted vector of zero-sized elements.
1862 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1864 struct PartialVecZeroSized<T,U> {
1867 marker_t: InvariantType<T>,
1868 marker_u: InvariantType<U>,
1871 #[unsafe_destructor]
1872 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1873 fn drop(&mut self) {
1875 // `vec` hasn't been modified until now. As it has a length
1876 // currently, this would run destructors of `T`s which might not be
1877 // there. So at first, set `vec`s length to `0`. This must be done
1878 // at first to remain memory-safe as the destructors of `U` or `T`
1879 // might cause unwinding where `vec`s destructor would be executed.
1880 self.vec.set_len(0);
1882 // We have instances of `U`s and `T`s in `vec`. Destruct them.
1883 while self.start_u != self.end_u {
1884 let _ = ptr::read(self.start_u); // Run a `U` destructor.
1885 self.start_u = self.start_u.offset(1);
1887 while self.start_t != self.end_t {
1888 let _ = ptr::read(self.start_t); // Run a `T` destructor.
1889 self.start_t = self.start_t.offset(1);
1891 // After this destructor ran, the destructor of `vec` will run,
1892 // deallocating the underlying memory.
1897 #[unsafe_destructor]
1898 impl<T,U> Drop for PartialVecZeroSized<T,U> {
1899 fn drop(&mut self) {
1901 // Destruct the instances of `T` and `U` this struct owns.
1902 while self.num_t != 0 {
1903 let _: T = mem::uninitialized(); // Run a `T` destructor.
1906 while self.num_u != 0 {
1907 let _: U = mem::uninitialized(); // Run a `U` destructor.
1917 use core::mem::size_of;
1918 use core::iter::repeat;
1920 use core::ops::FullRange;
1924 struct DropCounter<'a> {
1928 #[unsafe_destructor]
1929 impl<'a> Drop for DropCounter<'a> {
1930 fn drop(&mut self) {
1937 let xs = [1u8, 2u8, 3u8];
1938 assert_eq!(as_vec(&xs).as_slice(), xs);
1942 fn test_as_vec_dtor() {
1943 let (mut count_x, mut count_y) = (0, 0);
1945 let xs = &[DropCounter { count: &mut count_x }, DropCounter { count: &mut count_y }];
1946 assert_eq!(as_vec(xs).len(), 2);
1948 assert_eq!(count_x, 1);
1949 assert_eq!(count_y, 1);
1953 fn test_small_vec_struct() {
1954 assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1958 fn test_double_drop() {
1964 let (mut count_x, mut count_y) = (0, 0);
1966 let mut tv = TwoVec {
1970 tv.x.push(DropCounter {count: &mut count_x});
1971 tv.y.push(DropCounter {count: &mut count_y});
1973 // If Vec had a drop flag, here is where it would be zeroed.
1974 // Instead, it should rely on its internal state to prevent
1975 // doing anything significant when dropped multiple times.
1978 // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1981 assert_eq!(count_x, 1);
1982 assert_eq!(count_y, 1);
1987 let mut v = Vec::new();
1988 assert_eq!(v.capacity(), 0);
1991 assert!(v.capacity() >= 2);
1997 assert!(v.capacity() >= 16);
1999 assert!(v.capacity() >= 32);
2004 assert!(v.capacity() >= 33)
2009 let mut v = Vec::new();
2010 let mut w = Vec::new();
2013 for i in 0i..3 { w.push(i) }
2018 for i in 3i..10 { w.push(i) }
2024 fn test_slice_from_mut() {
2025 let mut values = vec![1u8,2,3,4,5];
2027 let slice = &mut values[2 ..];
2028 assert!(slice == [3, 4, 5]);
2029 for p in slice.iter_mut() {
2034 assert!(values == [1, 2, 5, 6, 7]);
2038 fn test_slice_to_mut() {
2039 let mut values = vec![1u8,2,3,4,5];
2041 let slice = &mut values[.. 2];
2042 assert!(slice == [1, 2]);
2043 for p in slice.iter_mut() {
2048 assert!(values == [2, 3, 3, 4, 5]);
2052 fn test_split_at_mut() {
2053 let mut values = vec![1u8,2,3,4,5];
2055 let (left, right) = values.split_at_mut(2);
2057 let left: &[_] = left;
2058 assert!(&left[..left.len()] == &[1, 2][]);
2060 for p in left.iter_mut() {
2065 let right: &[_] = right;
2066 assert!(&right[..right.len()] == &[3, 4, 5][]);
2068 for p in right.iter_mut() {
2073 assert!(values == vec![2u8, 3, 5, 6, 7]);
2078 let v: Vec<int> = vec!();
2079 let w = vec!(1i, 2, 3);
2081 assert_eq!(v, v.clone());
2085 // they should be disjoint in memory.
2086 assert!(w.as_ptr() != z.as_ptr())
2090 fn test_clone_from() {
2092 let three = vec!(box 1i, box 2, box 3);
2093 let two = vec!(box 4i, box 5);
2095 v.clone_from(&three);
2096 assert_eq!(v, three);
2099 v.clone_from(&three);
2100 assert_eq!(v, three);
2107 v.clone_from(&three);
2108 assert_eq!(v, three)
2113 let mut vec = vec![1u, 2, 3, 4];
2114 vec.retain(|&x| x % 2 == 0);
2115 assert!(vec == vec![2u, 4]);
2119 fn zero_sized_values() {
2120 let mut v = Vec::new();
2121 assert_eq!(v.len(), 0);
2123 assert_eq!(v.len(), 1);
2125 assert_eq!(v.len(), 2);
2126 assert_eq!(v.pop(), Some(()));
2127 assert_eq!(v.pop(), Some(()));
2128 assert_eq!(v.pop(), None);
2130 assert_eq!(v.iter().count(), 0);
2132 assert_eq!(v.iter().count(), 1);
2134 assert_eq!(v.iter().count(), 2);
2136 for &() in v.iter() {}
2138 assert_eq!(v.iter_mut().count(), 2);
2140 assert_eq!(v.iter_mut().count(), 3);
2142 assert_eq!(v.iter_mut().count(), 4);
2144 for &mut () in v.iter_mut() {}
2145 unsafe { v.set_len(0); }
2146 assert_eq!(v.iter_mut().count(), 0);
2150 fn test_partition() {
2151 assert_eq!(vec![].into_iter().partition(|x: &int| *x < 3), (vec![], vec![]));
2152 assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2153 assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2154 assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2158 fn test_zip_unzip() {
2159 let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
2161 let (left, right): (Vec<_>, Vec<_>) = z1.iter().map(|&x| x).unzip();
2163 assert_eq!((1, 4), (left[0], right[0]));
2164 assert_eq!((2, 5), (left[1], right[1]));
2165 assert_eq!((3, 6), (left[2], right[2]));
2169 fn test_unsafe_ptrs() {
2171 // Test on-stack copy-from-buf.
2173 let ptr = a.as_ptr();
2174 let b = Vec::from_raw_buf(ptr, 3u);
2175 assert_eq!(b, vec![1, 2, 3]);
2177 // Test on-heap copy-from-buf.
2178 let c = vec![1i, 2, 3, 4, 5];
2179 let ptr = c.as_ptr();
2180 let d = Vec::from_raw_buf(ptr, 5u);
2181 assert_eq!(d, vec![1, 2, 3, 4, 5]);
2186 fn test_vec_truncate_drop() {
2187 static mut drops: uint = 0;
2189 impl Drop for Elem {
2190 fn drop(&mut self) {
2191 unsafe { drops += 1; }
2195 let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
2196 assert_eq!(unsafe { drops }, 0);
2198 assert_eq!(unsafe { drops }, 2);
2200 assert_eq!(unsafe { drops }, 5);
2205 fn test_vec_truncate_fail() {
2206 struct BadElem(int);
2207 impl Drop for BadElem {
2208 fn drop(&mut self) {
2209 let BadElem(ref mut x) = *self;
2210 if *x == 0xbadbeef {
2211 panic!("BadElem panic: 0xbadbeef")
2216 let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
2222 let vec = vec!(1i, 2, 3);
2223 assert!(vec[1] == 2);
2228 fn test_index_out_of_bounds() {
2229 let vec = vec!(1i, 2, 3);
2235 fn test_slice_out_of_bounds_1() {
2236 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2242 fn test_slice_out_of_bounds_2() {
2243 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2249 fn test_slice_out_of_bounds_3() {
2250 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2256 fn test_slice_out_of_bounds_4() {
2257 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2263 fn test_slice_out_of_bounds_5() {
2264 let x: Vec<int> = vec![1, 2, 3, 4, 5];
2270 fn test_swap_remove_empty() {
2271 let mut vec: Vec<uint> = vec!();
2276 fn test_move_iter_unwrap() {
2277 let mut vec: Vec<uint> = Vec::with_capacity(7);
2280 let ptr = vec.as_ptr();
2281 vec = vec.into_iter().into_inner();
2282 assert_eq!(vec.as_ptr(), ptr);
2283 assert_eq!(vec.capacity(), 7);
2284 assert_eq!(vec.len(), 0);
2289 fn test_map_in_place_incompatible_types_fail() {
2290 let v = vec![0u, 1, 2];
2291 v.map_in_place(|_| ());
2295 fn test_map_in_place() {
2296 let v = vec![0u, 1, 2];
2297 assert_eq!(v.map_in_place(|i: uint| i as int - 1), [-1i, 0, 1]);
2301 fn test_map_in_place_zero_sized() {
2302 let v = vec![(), ()];
2303 #[derive(PartialEq, Debug)]
2305 assert_eq!(v.map_in_place(|_| ZeroSized), [ZeroSized, ZeroSized]);
2309 fn test_map_in_place_zero_drop_count() {
2310 use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
2312 #[derive(Clone, PartialEq, Debug)]
2314 impl Drop for Nothing { fn drop(&mut self) { } }
2316 #[derive(Clone, PartialEq, Debug)]
2318 impl Drop for ZeroSized {
2319 fn drop(&mut self) {
2320 DROP_COUNTER.fetch_add(1, Ordering::Relaxed);
2323 const NUM_ELEMENTS: uint = 2;
2324 static DROP_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
2326 let v = repeat(Nothing).take(NUM_ELEMENTS).collect::<Vec<_>>();
2328 DROP_COUNTER.store(0, Ordering::Relaxed);
2330 let v = v.map_in_place(|_| ZeroSized);
2331 assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), 0);
2333 assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), NUM_ELEMENTS);
2337 fn test_move_items() {
2338 let vec = vec![1, 2, 3];
2339 let mut vec2 : Vec<i32> = vec![];
2340 for i in vec.into_iter() {
2343 assert!(vec2 == vec![1, 2, 3]);
2347 fn test_move_items_reverse() {
2348 let vec = vec![1, 2, 3];
2349 let mut vec2 : Vec<i32> = vec![];
2350 for i in vec.into_iter().rev() {
2353 assert!(vec2 == vec![3, 2, 1]);
2357 fn test_move_items_zero_sized() {
2358 let vec = vec![(), (), ()];
2359 let mut vec2 : Vec<()> = vec![];
2360 for i in vec.into_iter() {
2363 assert!(vec2 == vec![(), (), ()]);
2367 fn test_drain_items() {
2368 let mut vec = vec![1, 2, 3];
2369 let mut vec2: Vec<i32> = vec![];
2370 for i in vec.drain() {
2373 assert_eq!(vec, []);
2374 assert_eq!(vec2, [ 1, 2, 3 ]);
2378 fn test_drain_items_reverse() {
2379 let mut vec = vec![1, 2, 3];
2380 let mut vec2: Vec<i32> = vec![];
2381 for i in vec.drain().rev() {
2384 assert_eq!(vec, []);
2385 assert_eq!(vec2, [ 3, 2, 1 ]);
2389 fn test_drain_items_zero_sized() {
2390 let mut vec = vec![(), (), ()];
2391 let mut vec2: Vec<()> = vec![];
2392 for i in vec.drain() {
2395 assert_eq!(vec, []);
2396 assert_eq!(vec2, [(), (), ()]);
2400 fn test_into_boxed_slice() {
2401 let xs = vec![1u, 2, 3];
2402 let ys = xs.into_boxed_slice();
2403 assert_eq!(ys.as_slice(), [1u, 2, 3]);
2408 let mut vec = vec![1, 2, 3];
2409 let mut vec2 = vec![4, 5, 6];
2410 vec.append(&mut vec2);
2411 assert_eq!(vec, vec![1, 2, 3, 4, 5, 6]);
2412 assert_eq!(vec2, vec![]);
2416 fn test_split_off() {
2417 let mut vec = vec![1, 2, 3, 4, 5, 6];
2418 let vec2 = vec.split_off(4);
2419 assert_eq!(vec, vec![1, 2, 3, 4]);
2420 assert_eq!(vec2, vec![5, 6]);
2424 fn bench_new(b: &mut Bencher) {
2426 let v: Vec<uint> = Vec::new();
2427 assert_eq!(v.len(), 0);
2428 assert_eq!(v.capacity(), 0);
2432 fn do_bench_with_capacity(b: &mut Bencher, src_len: uint) {
2433 b.bytes = src_len as u64;
2436 let v: Vec<uint> = Vec::with_capacity(src_len);
2437 assert_eq!(v.len(), 0);
2438 assert_eq!(v.capacity(), src_len);
2443 fn bench_with_capacity_0000(b: &mut Bencher) {
2444 do_bench_with_capacity(b, 0)
2448 fn bench_with_capacity_0010(b: &mut Bencher) {
2449 do_bench_with_capacity(b, 10)
2453 fn bench_with_capacity_0100(b: &mut Bencher) {
2454 do_bench_with_capacity(b, 100)
2458 fn bench_with_capacity_1000(b: &mut Bencher) {
2459 do_bench_with_capacity(b, 1000)
2462 fn do_bench_from_fn(b: &mut Bencher, src_len: uint) {
2463 b.bytes = src_len as u64;
2466 let dst = (0..src_len).collect::<Vec<_>>();
2467 assert_eq!(dst.len(), src_len);
2468 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2473 fn bench_from_fn_0000(b: &mut Bencher) {
2474 do_bench_from_fn(b, 0)
2478 fn bench_from_fn_0010(b: &mut Bencher) {
2479 do_bench_from_fn(b, 10)
2483 fn bench_from_fn_0100(b: &mut Bencher) {
2484 do_bench_from_fn(b, 100)
2488 fn bench_from_fn_1000(b: &mut Bencher) {
2489 do_bench_from_fn(b, 1000)
2492 fn do_bench_from_elem(b: &mut Bencher, src_len: uint) {
2493 b.bytes = src_len as u64;
2496 let dst: Vec<uint> = repeat(5).take(src_len).collect();
2497 assert_eq!(dst.len(), src_len);
2498 assert!(dst.iter().all(|x| *x == 5));
2503 fn bench_from_elem_0000(b: &mut Bencher) {
2504 do_bench_from_elem(b, 0)
2508 fn bench_from_elem_0010(b: &mut Bencher) {
2509 do_bench_from_elem(b, 10)
2513 fn bench_from_elem_0100(b: &mut Bencher) {
2514 do_bench_from_elem(b, 100)
2518 fn bench_from_elem_1000(b: &mut Bencher) {
2519 do_bench_from_elem(b, 1000)
2522 fn do_bench_from_slice(b: &mut Bencher, src_len: uint) {
2523 let src: Vec<uint> = FromIterator::from_iter(0..src_len);
2525 b.bytes = src_len as u64;
2528 let dst = src.clone()[].to_vec();
2529 assert_eq!(dst.len(), src_len);
2530 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2535 fn bench_from_slice_0000(b: &mut Bencher) {
2536 do_bench_from_slice(b, 0)
2540 fn bench_from_slice_0010(b: &mut Bencher) {
2541 do_bench_from_slice(b, 10)
2545 fn bench_from_slice_0100(b: &mut Bencher) {
2546 do_bench_from_slice(b, 100)
2550 fn bench_from_slice_1000(b: &mut Bencher) {
2551 do_bench_from_slice(b, 1000)
2554 fn do_bench_from_iter(b: &mut Bencher, src_len: uint) {
2555 let src: Vec<uint> = FromIterator::from_iter(0..src_len);
2557 b.bytes = src_len as u64;
2560 let dst: Vec<uint> = FromIterator::from_iter(src.clone().into_iter());
2561 assert_eq!(dst.len(), src_len);
2562 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2567 fn bench_from_iter_0000(b: &mut Bencher) {
2568 do_bench_from_iter(b, 0)
2572 fn bench_from_iter_0010(b: &mut Bencher) {
2573 do_bench_from_iter(b, 10)
2577 fn bench_from_iter_0100(b: &mut Bencher) {
2578 do_bench_from_iter(b, 100)
2582 fn bench_from_iter_1000(b: &mut Bencher) {
2583 do_bench_from_iter(b, 1000)
2586 fn do_bench_extend(b: &mut Bencher, dst_len: uint, src_len: uint) {
2587 let dst: Vec<uint> = FromIterator::from_iter(0..dst_len);
2588 let src: Vec<uint> = FromIterator::from_iter(dst_len..dst_len + src_len);
2590 b.bytes = src_len as u64;
2593 let mut dst = dst.clone();
2594 dst.extend(src.clone().into_iter());
2595 assert_eq!(dst.len(), dst_len + src_len);
2596 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2601 fn bench_extend_0000_0000(b: &mut Bencher) {
2602 do_bench_extend(b, 0, 0)
2606 fn bench_extend_0000_0010(b: &mut Bencher) {
2607 do_bench_extend(b, 0, 10)
2611 fn bench_extend_0000_0100(b: &mut Bencher) {
2612 do_bench_extend(b, 0, 100)
2616 fn bench_extend_0000_1000(b: &mut Bencher) {
2617 do_bench_extend(b, 0, 1000)
2621 fn bench_extend_0010_0010(b: &mut Bencher) {
2622 do_bench_extend(b, 10, 10)
2626 fn bench_extend_0100_0100(b: &mut Bencher) {
2627 do_bench_extend(b, 100, 100)
2631 fn bench_extend_1000_1000(b: &mut Bencher) {
2632 do_bench_extend(b, 1000, 1000)
2635 fn do_bench_push_all(b: &mut Bencher, dst_len: uint, src_len: uint) {
2636 let dst: Vec<uint> = FromIterator::from_iter(0..dst_len);
2637 let src: Vec<uint> = FromIterator::from_iter(dst_len..dst_len + src_len);
2639 b.bytes = src_len as u64;
2642 let mut dst = dst.clone();
2643 dst.push_all(src.as_slice());
2644 assert_eq!(dst.len(), dst_len + src_len);
2645 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2650 fn bench_push_all_0000_0000(b: &mut Bencher) {
2651 do_bench_push_all(b, 0, 0)
2655 fn bench_push_all_0000_0010(b: &mut Bencher) {
2656 do_bench_push_all(b, 0, 10)
2660 fn bench_push_all_0000_0100(b: &mut Bencher) {
2661 do_bench_push_all(b, 0, 100)
2665 fn bench_push_all_0000_1000(b: &mut Bencher) {
2666 do_bench_push_all(b, 0, 1000)
2670 fn bench_push_all_0010_0010(b: &mut Bencher) {
2671 do_bench_push_all(b, 10, 10)
2675 fn bench_push_all_0100_0100(b: &mut Bencher) {
2676 do_bench_push_all(b, 100, 100)
2680 fn bench_push_all_1000_1000(b: &mut Bencher) {
2681 do_bench_push_all(b, 1000, 1000)
2684 fn do_bench_push_all_move(b: &mut Bencher, dst_len: uint, src_len: uint) {
2685 let dst: Vec<uint> = FromIterator::from_iter(0u..dst_len);
2686 let src: Vec<uint> = FromIterator::from_iter(dst_len..dst_len + src_len);
2688 b.bytes = src_len as u64;
2691 let mut dst = dst.clone();
2692 dst.extend(src.clone().into_iter());
2693 assert_eq!(dst.len(), dst_len + src_len);
2694 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2699 fn bench_push_all_move_0000_0000(b: &mut Bencher) {
2700 do_bench_push_all_move(b, 0, 0)
2704 fn bench_push_all_move_0000_0010(b: &mut Bencher) {
2705 do_bench_push_all_move(b, 0, 10)
2709 fn bench_push_all_move_0000_0100(b: &mut Bencher) {
2710 do_bench_push_all_move(b, 0, 100)
2714 fn bench_push_all_move_0000_1000(b: &mut Bencher) {
2715 do_bench_push_all_move(b, 0, 1000)
2719 fn bench_push_all_move_0010_0010(b: &mut Bencher) {
2720 do_bench_push_all_move(b, 10, 10)
2724 fn bench_push_all_move_0100_0100(b: &mut Bencher) {
2725 do_bench_push_all_move(b, 100, 100)
2729 fn bench_push_all_move_1000_1000(b: &mut Bencher) {
2730 do_bench_push_all_move(b, 1000, 1000)
2733 fn do_bench_clone(b: &mut Bencher, src_len: uint) {
2734 let src: Vec<uint> = FromIterator::from_iter(0..src_len);
2736 b.bytes = src_len as u64;
2739 let dst = src.clone();
2740 assert_eq!(dst.len(), src_len);
2741 assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2746 fn bench_clone_0000(b: &mut Bencher) {
2747 do_bench_clone(b, 0)
2751 fn bench_clone_0010(b: &mut Bencher) {
2752 do_bench_clone(b, 10)
2756 fn bench_clone_0100(b: &mut Bencher) {
2757 do_bench_clone(b, 100)
2761 fn bench_clone_1000(b: &mut Bencher) {
2762 do_bench_clone(b, 1000)
2765 fn do_bench_clone_from(b: &mut Bencher, times: uint, dst_len: uint, src_len: uint) {
2766 let dst: Vec<uint> = FromIterator::from_iter(0..src_len);
2767 let src: Vec<uint> = FromIterator::from_iter(dst_len..dst_len + src_len);
2769 b.bytes = (times * src_len) as u64;
2772 let mut dst = dst.clone();
2775 dst.clone_from(&src);
2777 assert_eq!(dst.len(), src_len);
2778 assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x));
2784 fn bench_clone_from_01_0000_0000(b: &mut Bencher) {
2785 do_bench_clone_from(b, 1, 0, 0)
2789 fn bench_clone_from_01_0000_0010(b: &mut Bencher) {
2790 do_bench_clone_from(b, 1, 0, 10)
2794 fn bench_clone_from_01_0000_0100(b: &mut Bencher) {
2795 do_bench_clone_from(b, 1, 0, 100)
2799 fn bench_clone_from_01_0000_1000(b: &mut Bencher) {
2800 do_bench_clone_from(b, 1, 0, 1000)
2804 fn bench_clone_from_01_0010_0010(b: &mut Bencher) {
2805 do_bench_clone_from(b, 1, 10, 10)
2809 fn bench_clone_from_01_0100_0100(b: &mut Bencher) {
2810 do_bench_clone_from(b, 1, 100, 100)
2814 fn bench_clone_from_01_1000_1000(b: &mut Bencher) {
2815 do_bench_clone_from(b, 1, 1000, 1000)
2819 fn bench_clone_from_01_0010_0100(b: &mut Bencher) {
2820 do_bench_clone_from(b, 1, 10, 100)
2824 fn bench_clone_from_01_0100_1000(b: &mut Bencher) {
2825 do_bench_clone_from(b, 1, 100, 1000)
2829 fn bench_clone_from_01_0010_0000(b: &mut Bencher) {
2830 do_bench_clone_from(b, 1, 10, 0)
2834 fn bench_clone_from_01_0100_0010(b: &mut Bencher) {
2835 do_bench_clone_from(b, 1, 100, 10)
2839 fn bench_clone_from_01_1000_0100(b: &mut Bencher) {
2840 do_bench_clone_from(b, 1, 1000, 100)
2844 fn bench_clone_from_10_0000_0000(b: &mut Bencher) {
2845 do_bench_clone_from(b, 10, 0, 0)
2849 fn bench_clone_from_10_0000_0010(b: &mut Bencher) {
2850 do_bench_clone_from(b, 10, 0, 10)
2854 fn bench_clone_from_10_0000_0100(b: &mut Bencher) {
2855 do_bench_clone_from(b, 10, 0, 100)
2859 fn bench_clone_from_10_0000_1000(b: &mut Bencher) {
2860 do_bench_clone_from(b, 10, 0, 1000)
2864 fn bench_clone_from_10_0010_0010(b: &mut Bencher) {
2865 do_bench_clone_from(b, 10, 10, 10)
2869 fn bench_clone_from_10_0100_0100(b: &mut Bencher) {
2870 do_bench_clone_from(b, 10, 100, 100)
2874 fn bench_clone_from_10_1000_1000(b: &mut Bencher) {
2875 do_bench_clone_from(b, 10, 1000, 1000)
2879 fn bench_clone_from_10_0010_0100(b: &mut Bencher) {
2880 do_bench_clone_from(b, 10, 10, 100)
2884 fn bench_clone_from_10_0100_1000(b: &mut Bencher) {
2885 do_bench_clone_from(b, 10, 100, 1000)
2889 fn bench_clone_from_10_0010_0000(b: &mut Bencher) {
2890 do_bench_clone_from(b, 10, 10, 0)
2894 fn bench_clone_from_10_0100_0010(b: &mut Bencher) {
2895 do_bench_clone_from(b, 10, 100, 10)
2899 fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
2900 do_bench_clone_from(b, 10, 1000, 100)