]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec.rs
Auto merge of #21604 - nikomatsakis:closure-move-indiv-vars, r=eddyb
[rust.git] / src / libcollections / vec.rs
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.
4 //
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.
10
11 //! A growable list type with heap-allocated contents, written `Vec<T>` but pronounced 'vector.'
12 //!
13 //! Vectors have `O(1)` indexing, push (to the end) and pop (from the end).
14 //!
15 //! # Examples
16 //!
17 //! Explicitly creating a `Vec<T>` with `new()`:
18 //!
19 //! ```
20 //! let xs: Vec<i32> = Vec::new();
21 //! ```
22 //!
23 //! Using the `vec!` macro:
24 //!
25 //! ```
26 //! let ys: Vec<i32> = vec![];
27 //!
28 //! let zs = vec![1i32, 2, 3, 4, 5];
29 //! ```
30 //!
31 //! Push:
32 //!
33 //! ```
34 //! let mut xs = vec![1i32, 2];
35 //!
36 //! xs.push(3);
37 //! ```
38 //!
39 //! And pop:
40 //!
41 //! ```
42 //! let mut xs = vec![1i32, 2];
43 //!
44 //! let two = xs.pop();
45 //! ```
46
47 #![stable(feature = "rust1", since = "1.0.0")]
48
49 use core::prelude::*;
50
51 use alloc::boxed::Box;
52 use alloc::heap::{EMPTY, allocate, reallocate, deallocate};
53 use core::borrow::{Cow, IntoCow};
54 use core::cmp::max;
55 use core::cmp::{Ordering};
56 use core::default::Default;
57 use core::fmt;
58 use core::hash::{self, Hash};
59 use core::iter::{repeat, FromIterator};
60 use core::marker::{ContravariantLifetime, InvariantType};
61 use core::mem;
62 use core::nonzero::NonZero;
63 use core::num::{Int, UnsignedInt};
64 use core::ops::{Index, IndexMut, Deref, Add};
65 use core::ops;
66 use core::ptr;
67 use core::raw::Slice as RawSlice;
68 use core::uint;
69
70 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
71 ///
72 /// # Examples
73 ///
74 /// ```
75 /// let mut vec = Vec::new();
76 /// vec.push(1i);
77 /// vec.push(2i);
78 ///
79 /// assert_eq!(vec.len(), 2);
80 /// assert_eq!(vec[0], 1);
81 ///
82 /// assert_eq!(vec.pop(), Some(2));
83 /// assert_eq!(vec.len(), 1);
84 ///
85 /// vec[0] = 7i;
86 /// assert_eq!(vec[0], 7);
87 ///
88 /// vec.push_all(&[1, 2, 3]);
89 ///
90 /// for x in vec.iter() {
91 ///     println!("{}", x);
92 /// }
93 /// assert_eq!(vec, vec![7i, 1, 2, 3]);
94 /// ```
95 ///
96 /// The `vec!` macro is provided to make initialization more convenient:
97 ///
98 /// ```
99 /// let mut vec = vec![1i, 2i, 3i];
100 /// vec.push(4);
101 /// assert_eq!(vec, vec![1, 2, 3, 4]);
102 /// ```
103 ///
104 /// Use a `Vec<T>` as an efficient stack:
105 ///
106 /// ```
107 /// let mut stack = Vec::new();
108 ///
109 /// stack.push(1i);
110 /// stack.push(2i);
111 /// stack.push(3i);
112 ///
113 /// loop {
114 ///     let top = match stack.pop() {
115 ///         None => break, // empty
116 ///         Some(x) => x,
117 ///     };
118 ///     // Prints 3, 2, 1
119 ///     println!("{}", top);
120 /// }
121 /// ```
122 ///
123 /// # Capacity and reallocation
124 ///
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
129 /// reallocated.
130 ///
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")]
138 pub struct Vec<T> {
139     ptr: NonZero<*mut T>,
140     len: uint,
141     cap: uint,
142 }
143
144 unsafe impl<T: Send> Send for Vec<T> { }
145 unsafe impl<T: Sync> Sync for Vec<T> { }
146
147 ////////////////////////////////////////////////////////////////////////////////
148 // Inherent methods
149 ////////////////////////////////////////////////////////////////////////////////
150
151 impl<T> Vec<T> {
152     /// Constructs a new, empty `Vec<T>`.
153     ///
154     /// The vector will not allocate until elements are pushed onto it.
155     ///
156     /// # Examples
157     ///
158     /// ```
159     /// let mut vec: Vec<int> = Vec::new();
160     /// ```
161     #[inline]
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 }
169     }
170
171     /// Constructs a new, empty `Vec<T>` with the specified capacity.
172     ///
173     /// The vector will be able to hold exactly `capacity` elements without reallocating. If
174     /// `capacity` is 0, the vector will not allocate.
175     ///
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'.)
179     ///
180     /// # Examples
181     ///
182     /// ```
183     /// let mut vec: Vec<int> = Vec::with_capacity(10);
184     ///
185     /// // The vector contains no items, even though it has capacity for more
186     /// assert_eq!(vec.len(), 0);
187     ///
188     /// // These are all done without reallocating...
189     /// for i in 0i..10 {
190     ///     vec.push(i);
191     /// }
192     ///
193     /// // ...but this may make the vector reallocate
194     /// vec.push(11);
195     /// ```
196     #[inline]
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 {
202             Vec::new()
203         } else {
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 }
209         }
210     }
211
212     /// Creates a `Vec<T>` directly from the raw components of another vector.
213     ///
214     /// This is highly unsafe, due to the number of invariants that aren't checked.
215     ///
216     /// # Examples
217     ///
218     /// ```
219     /// use std::ptr;
220     /// use std::mem;
221     ///
222     /// fn main() {
223     ///     let mut v = vec![1i, 2, 3];
224     ///
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();
229     ///
230     ///     unsafe {
231     ///         // Cast `v` into the void: no destructor run, so we are in
232     ///         // complete control of the allocation to which `p` points.
233     ///         mem::forget(v);
234     ///
235     ///         // Overwrite memory with 4, 5, 6
236     ///         for i in 0..len as int {
237     ///             ptr::write(p.offset(i), 4 + i);
238     ///         }
239     ///
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]);
243     ///     }
244     /// }
245     /// ```
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 }
250     }
251
252     /// Creates a vector by copying the elements from a raw pointer.
253     ///
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.
257     #[inline]
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);
262         dst.set_len(elts);
263         ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
264         dst
265     }
266
267     /// Returns the number of elements the vector can hold without
268     /// reallocating.
269     ///
270     /// # Examples
271     ///
272     /// ```
273     /// let vec: Vec<int> = Vec::with_capacity(10);
274     /// assert_eq!(vec.capacity(), 10);
275     /// ```
276     #[inline]
277     #[stable(feature = "rust1", since = "1.0.0")]
278     pub fn capacity(&self) -> uint {
279         self.cap
280     }
281
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.
284     ///
285     /// # Panics
286     ///
287     /// Panics if the new capacity overflows `uint`.
288     ///
289     /// # Examples
290     ///
291     /// ```
292     /// let mut vec: Vec<int> = vec![1];
293     /// vec.reserve(10);
294     /// assert!(vec.capacity() >= 11);
295     /// ```
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);
303         }
304     }
305
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
308     /// sufficient.
309     ///
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.
313     ///
314     /// # Panics
315     ///
316     /// Panics if the new capacity overflows `uint`.
317     ///
318     /// # Examples
319     ///
320     /// ```
321     /// let mut vec: Vec<int> = vec![1];
322     /// vec.reserve_exact(10);
323     /// assert!(vec.capacity() >= 11);
324     /// ```
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)
331             }
332         }
333     }
334
335     /// Shrinks the capacity of the vector as much as possible.
336     ///
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.
339     ///
340     /// # Examples
341     ///
342     /// ```
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);
348     /// ```
349     #[stable(feature = "rust1", since = "1.0.0")]
350     pub fn shrink_to_fit(&mut self) {
351         if mem::size_of::<T>() == 0 { return }
352
353         if self.len == 0 {
354             if self.cap != 0 {
355                 unsafe {
356                     dealloc(*self.ptr, self.cap)
357                 }
358                 self.cap = 0;
359             }
360         } else if self.cap != self.len {
361             unsafe {
362                 // Overflow check is unnecessary as the vector is already at
363                 // least this large.
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);
370             }
371             self.cap = self.len;
372         }
373     }
374
375     /// Convert the vector into Box<[T]>.
376     ///
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();
383         unsafe {
384             let xs: Box<[T]> = mem::transmute(self.as_mut_slice());
385             mem::forget(self);
386             xs
387         }
388     }
389
390     /// Shorten a vector, dropping excess elements.
391     ///
392     /// If `len` is greater than the vector's current length, this has no
393     /// effect.
394     ///
395     /// # Examples
396     ///
397     /// ```
398     /// let mut vec = vec![1i, 2, 3, 4];
399     /// vec.truncate(2);
400     /// assert_eq!(vec, vec![1, 2]);
401     /// ```
402     #[stable(feature = "rust1", since = "1.0.0")]
403     pub fn truncate(&mut self, len: uint) {
404         unsafe {
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.
409                 self.len -= 1;
410                 ptr::read(self.get_unchecked(self.len));
411             }
412         }
413     }
414
415     /// Returns a mutable slice of the elements of `self`.
416     ///
417     /// # Examples
418     ///
419     /// ```
420     /// fn foo(slice: &mut [int]) {}
421     ///
422     /// let mut vec = vec![1i, 2];
423     /// foo(vec.as_mut_slice());
424     /// ```
425     #[inline]
426     #[stable(feature = "rust1", since = "1.0.0")]
427     pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
428         unsafe {
429             mem::transmute(RawSlice {
430                 data: *self.ptr,
431                 len: self.len,
432             })
433         }
434     }
435
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
438     /// this.
439     ///
440     /// # Examples
441     ///
442     /// ```
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);
447     /// }
448     /// ```
449     #[inline]
450     #[stable(feature = "rust1", since = "1.0.0")]
451     pub fn into_iter(self) -> IntoIter<T> {
452         unsafe {
453             let ptr = *self.ptr;
454             let cap = self.cap;
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
458             } else {
459                 ptr.offset(self.len() as int) as *const T
460             };
461             mem::forget(self);
462             IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end }
463         }
464     }
465
466     /// Sets the length of a vector.
467     ///
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.
471     ///
472     /// # Examples
473     ///
474     /// ```
475     /// let mut v = vec![1u, 2, 3, 4];
476     /// unsafe {
477     ///     v.set_len(1);
478     /// }
479     /// ```
480     #[inline]
481     #[stable(feature = "rust1", since = "1.0.0")]
482     pub unsafe fn set_len(&mut self, len: uint) {
483         self.len = len;
484     }
485
486     /// Removes an element from anywhere in the vector and return it, replacing
487     /// it with the last element.
488     ///
489     /// This does not preserve ordering, but is O(1).
490     ///
491     /// # Panics
492     ///
493     /// Panics if `index` is out of bounds.
494     ///
495     /// # Examples
496     ///
497     /// ```
498     /// let mut v = vec!["foo", "bar", "baz", "qux"];
499     ///
500     /// assert_eq!(v.swap_remove(1), "bar");
501     /// assert_eq!(v, vec!["foo", "qux", "baz"]);
502     ///
503     /// assert_eq!(v.swap_remove(0), "foo");
504     /// assert_eq!(v, vec!["baz", "qux"]);
505     /// ```
506     #[inline]
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);
511         self.pop().unwrap()
512     }
513
514     /// Inserts an element at position `index` within the vector, shifting all
515     /// elements after position `i` one position to the right.
516     ///
517     /// # Panics
518     ///
519     /// Panics if `index` is not between `0` and the vector's length (both
520     /// bounds inclusive).
521     ///
522     /// # Examples
523     ///
524     /// ```
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]);
530     /// ```
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
536         self.reserve(1);
537
538         unsafe { // infallible
539             // The spot to put the new value
540             {
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
546                 // element.
547                 ptr::write(&mut *p, element);
548             }
549             self.set_len(len + 1);
550         }
551     }
552
553     /// Removes and returns the element at position `index` within the vector,
554     /// shifting all elements after position `index` one position to the left.
555     ///
556     /// # Panics
557     ///
558     /// Panics if `i` is out of bounds.
559     ///
560     /// # Examples
561     ///
562     /// ```
563     /// let mut v = vec![1i, 2, 3];
564     /// assert_eq!(v.remove(1), 2);
565     /// assert_eq!(v, vec![1, 3]);
566     /// ```
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
572             let ret;
573             {
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);
579
580                 // Shift everything down to fill in that spot.
581                 ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
582             }
583             self.set_len(len - 1);
584             ret
585         }
586     }
587
588     /// Retains only the elements specified by the predicate.
589     ///
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
592     /// elements.
593     ///
594     /// # Examples
595     ///
596     /// ```
597     /// let mut vec = vec![1i, 2, 3, 4];
598     /// vec.retain(|&x| x%2 == 0);
599     /// assert_eq!(vec, vec![2, 4]);
600     /// ```
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();
604         let mut del = 0u;
605         {
606             let v = self.as_mut_slice();
607
608             for i in 0u..len {
609                 if !f(&v[i]) {
610                     del += 1;
611                 } else if del > 0 {
612                     v.swap(i-del, i);
613                 }
614             }
615         }
616         if del > 0 {
617             self.truncate(len - del);
618         }
619     }
620
621     /// Appends an element to the back of a collection.
622     ///
623     /// # Panics
624     ///
625     /// Panics if the number of elements in the vector overflows a `uint`.
626     ///
627     /// # Examples
628     ///
629     /// ```rust
630     /// let mut vec = vec!(1i, 2);
631     /// vec.push(3);
632     /// assert_eq!(vec, vec!(1, 2, 3));
633     /// ```
634     #[inline]
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); }
642             return
643         }
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") }
648             unsafe {
649                 let ptr = alloc_or_realloc(*self.ptr, old_size, size);
650                 if ptr.is_null() { ::alloc::oom() }
651                 self.ptr = NonZero::new(ptr);
652             }
653             self.cap = max(self.cap, 2) * 2;
654         }
655
656         unsafe {
657             let end = (*self.ptr).offset(self.len as int);
658             ptr::write(&mut *end, value);
659             self.len += 1;
660         }
661     }
662
663     /// Removes the last element from a vector and returns it, or `None` if it is empty.
664     ///
665     /// # Examples
666     ///
667     /// ```rust
668     /// let mut vec = vec![1i, 2, 3];
669     /// assert_eq!(vec.pop(), Some(3));
670     /// assert_eq!(vec, vec![1, 2]);
671     /// ```
672     #[inline]
673     #[stable(feature = "rust1", since = "1.0.0")]
674     pub fn pop(&mut self) -> Option<T> {
675         if self.len == 0 {
676             None
677         } else {
678             unsafe {
679                 self.len -= 1;
680                 Some(ptr::read(self.get_unchecked(self.len())))
681             }
682         }
683     }
684
685     /// Moves all the elements of `other` into `Self`, leaving `other` empty.
686     ///
687     /// # Panics
688     ///
689     /// Panics if the number of elements in the vector overflows a `uint`.
690     ///
691     /// # Examples
692     /// ```rust
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![]);
698     /// ```
699     #[inline]
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) }
708             return;
709         }
710         self.reserve(other.len());
711         let len = self.len();
712         unsafe {
713             ptr::copy_nonoverlapping_memory(
714                 self.get_unchecked_mut(len),
715                 other.as_ptr(),
716                 other.len());
717         }
718
719         self.len += other.len();
720         unsafe { other.set_len(0); }
721     }
722
723     /// Creates a draining iterator that clears the `Vec` and iterates over
724     /// the removed items from start to end.
725     ///
726     /// # Examples
727     ///
728     /// ```
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);
733     /// }
734     /// assert!(v.is_empty());
735     /// ```
736     #[inline]
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> {
740         unsafe {
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
744             } else {
745                 (*self.ptr).offset(self.len() as int) as *const T
746             };
747             self.set_len(0);
748             Drain {
749                 ptr: begin,
750                 end: end,
751                 marker: ContravariantLifetime,
752             }
753         }
754     }
755
756     /// Clears the vector, removing all values.
757     ///
758     /// # Examples
759     ///
760     /// ```
761     /// let mut v = vec![1i, 2, 3];
762     ///
763     /// v.clear();
764     ///
765     /// assert!(v.is_empty());
766     /// ```
767     #[inline]
768     #[stable(feature = "rust1", since = "1.0.0")]
769     pub fn clear(&mut self) {
770         self.truncate(0)
771     }
772
773     /// Returns the number of elements in the vector.
774     ///
775     /// # Examples
776     ///
777     /// ```
778     /// let a = vec![1i, 2, 3];
779     /// assert_eq!(a.len(), 3);
780     /// ```
781     #[inline]
782     #[stable(feature = "rust1", since = "1.0.0")]
783     pub fn len(&self) -> uint { self.len }
784
785     /// Returns `true` if the vector contains no elements.
786     ///
787     /// # Examples
788     ///
789     /// ```
790     /// let mut v = Vec::new();
791     /// assert!(v.is_empty());
792     ///
793     /// v.push(1i);
794     /// assert!(!v.is_empty());
795     /// ```
796     #[stable(feature = "rust1", since = "1.0.0")]
797     pub fn is_empty(&self) -> bool { self.len() == 0 }
798
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.
801     ///
802     /// # Panics
803     ///
804     /// Panics if `T` and `U` have differing sizes or are not zero-sized and
805     /// have differing minimal alignments.
806     ///
807     /// # Examples
808     ///
809     /// ```
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());
813     ///
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());
819     /// ```
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
824         // size.
825         assert!(mem::size_of::<T>() == mem::size_of::<U>());
826
827         let mut vec = self;
828
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.
832
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>());
836
837             // This `as int` cast is safe, because the size of the elements of the
838             // vector is not 0, and:
839             //
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.
843             //
844             //    Example:
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)
851             //
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();
856
857             let mut pv = PartialVecNonZeroSized {
858                 vec: vec,
859
860                 start_t: start,
861                 // This points inside the vector, as the vector has length
862                 // `offset`.
863                 end_t: unsafe { start.offset(offset) },
864                 start_u: start as *mut U,
865                 end_u: start as *mut U,
866             };
867             //  start_t
868             //  start_u
869             //  |
870             // +-+-+-+-+-+-+
871             // |T|T|T|...|T|
872             // +-+-+-+-+-+-+
873             //  |           |
874             //  end_u       end_t
875
876             while pv.end_u as *mut T != pv.end_t {
877                 unsafe {
878                     //  start_u start_t
879                     //  |       |
880                     // +-+-+-+-+-+-+-+-+-+
881                     // |U|...|U|T|T|...|T|
882                     // +-+-+-+-+-+-+-+-+-+
883                     //          |         |
884                     //          end_u     end_t
885
886                     let t = ptr::read(pv.start_t);
887                     //  start_u start_t
888                     //  |       |
889                     // +-+-+-+-+-+-+-+-+-+
890                     // |U|...|U|X|T|...|T|
891                     // +-+-+-+-+-+-+-+-+-+
892                     //          |         |
893                     //          end_u     end_t
894                     // We must not panic here, one cell is marked as `T`
895                     // although it is not `T`.
896
897                     pv.start_t = pv.start_t.offset(1);
898                     //  start_u   start_t
899                     //  |         |
900                     // +-+-+-+-+-+-+-+-+-+
901                     // |U|...|U|X|T|...|T|
902                     // +-+-+-+-+-+-+-+-+-+
903                     //          |         |
904                     //          end_u     end_t
905                     // We may panic again.
906
907                     // The function given by the user might panic.
908                     let u = f(t);
909
910                     ptr::write(pv.end_u, u);
911                     //  start_u   start_t
912                     //  |         |
913                     // +-+-+-+-+-+-+-+-+-+
914                     // |U|...|U|U|T|...|T|
915                     // +-+-+-+-+-+-+-+-+-+
916                     //          |         |
917                     //          end_u     end_t
918                     // We should not panic here, because that would leak the `U`
919                     // pointed to by `end_u`.
920
921                     pv.end_u = pv.end_u.offset(1);
922                     //  start_u   start_t
923                     //  |         |
924                     // +-+-+-+-+-+-+-+-+-+
925                     // |U|...|U|U|T|...|T|
926                     // +-+-+-+-+-+-+-+-+-+
927                     //            |       |
928                     //            end_u   end_t
929                     // We may panic again.
930                 }
931             }
932
933             //  start_u     start_t
934             //  |           |
935             // +-+-+-+-+-+-+
936             // |U|...|U|U|U|
937             // +-+-+-+-+-+-+
938             //              |
939             //              end_t
940             //              end_u
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
946             // this can panic.
947             unsafe {
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;
951                 mem::forget(pv);
952                 Vec::from_raw_parts(vec_ptr, vec_len, vec_cap)
953             }
954         } else {
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> {
960                 num_t: vec.len(),
961                 num_u: 0,
962                 marker_t: InvariantType,
963                 marker_u: InvariantType,
964             };
965             unsafe { mem::forget(vec); }
966
967             while pv.num_t != 0 {
968                 unsafe {
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();
973                     pv.num_t -= 1;
974
975                     // The function given by the user might panic.
976                     let u = f(t);
977
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.
982                     mem::forget(u);
983                     pv.num_u += 1;
984                 }
985             }
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();
989             unsafe {
990                 result.set_len(pv.num_u);
991                 mem::forget(pv);
992             }
993             result
994         }
995     }
996
997     /// Splits the collection into two at the given index.
998     ///
999     /// Returns a newly allocated `Self`. `self` contains elements `[0, at)`,
1000     /// and the returned `Self` contains elements `[at, len)`.
1001     ///
1002     /// Note that the capacity of `self` does not change.
1003     ///
1004     /// # Examples
1005     /// ```rust
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]);
1010     /// ```
1011     #[inline]
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");
1016
1017         let other_len = self.len - at;
1018         let mut other = Vec::with_capacity(other_len);
1019
1020         // Unsafely `set_len` and copy items to `other`.
1021         unsafe {
1022             self.set_len(at);
1023             other.set_len(other_len);
1024
1025             ptr::copy_nonoverlapping_memory(
1026                 other.as_mut_ptr(),
1027                 self.as_ptr().offset(at as isize),
1028                 other.len());
1029         }
1030         other
1031     }
1032
1033 }
1034
1035 impl<T: Clone> Vec<T> {
1036     /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
1037     ///
1038     /// Calls either `extend()` or `truncate()` depending on whether `new_len`
1039     /// is larger than the current value of `len()` or not.
1040     ///
1041     /// # Examples
1042     ///
1043     /// ```
1044     /// let mut vec = vec!["hello"];
1045     /// vec.resize(3, "world");
1046     /// assert_eq!(vec, vec!["hello", "world", "world"]);
1047     ///
1048     /// let mut vec = vec![1i, 2, 3, 4];
1049     /// vec.resize(2, 0);
1050     /// assert_eq!(vec, vec![1, 2]);
1051     /// ```
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();
1056
1057         if new_len > len {
1058             self.extend(repeat(value).take(new_len - len));
1059         } else {
1060             self.truncate(new_len);
1061         }
1062     }
1063
1064     /// Appends all elements in a slice to the `Vec`.
1065     ///
1066     /// Iterates over the slice `other`, clones each element, and then appends
1067     /// it to this `Vec`. The `other` vector is traversed in-order.
1068     ///
1069     /// # Examples
1070     ///
1071     /// ```
1072     /// let mut vec = vec![1i];
1073     /// vec.push_all(&[2i, 3, 4]);
1074     /// assert_eq!(vec, vec![1, 2, 3, 4]);
1075     /// ```
1076     #[inline]
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());
1081
1082         for i in 0..other.len() {
1083             let len = self.len();
1084
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.
1088             unsafe {
1089                 ptr::write(
1090                     self.get_unchecked_mut(len),
1091                     other.get_unchecked(i).clone());
1092                 self.set_len(len + 1);
1093             }
1094         }
1095     }
1096 }
1097
1098 impl<T: PartialEq> Vec<T> {
1099     /// Removes consecutive repeated elements in the vector.
1100     ///
1101     /// If the vector is sorted, this removes all duplicates.
1102     ///
1103     /// # Examples
1104     ///
1105     /// ```
1106     /// let mut vec = vec![1i, 2, 2, 3, 2];
1107     ///
1108     /// vec.dedup();
1109     ///
1110     /// assert_eq!(vec, vec![1i, 2, 3, 2]);
1111     /// ```
1112     #[stable(feature = "rust1", since = "1.0.0")]
1113     pub fn dedup(&mut self) {
1114         unsafe {
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.
1118             //
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).
1124             //
1125             // Example: We start in this state, where `r` represents "next
1126             // read" and `w` represents "next_write`.
1127             //
1128             //           r
1129             //     +---+---+---+---+---+---+
1130             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1131             //     +---+---+---+---+---+---+
1132             //           w
1133             //
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:
1137             //
1138             //               r
1139             //     +---+---+---+---+---+---+
1140             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1141             //     +---+---+---+---+---+---+
1142             //               w
1143             //
1144             // Comparing self[r] against self[w-1], this value is a duplicate,
1145             // so we increment `r` but leave everything else unchanged:
1146             //
1147             //                   r
1148             //     +---+---+---+---+---+---+
1149             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1150             //     +---+---+---+---+---+---+
1151             //               w
1152             //
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:
1155             //
1156             //                       r
1157             //     +---+---+---+---+---+---+
1158             //     | 0 | 1 | 2 | 1 | 3 | 3 |
1159             //     +---+---+---+---+---+---+
1160             //                   w
1161             //
1162             // Not a duplicate, repeat:
1163             //
1164             //                           r
1165             //     +---+---+---+---+---+---+
1166             //     | 0 | 1 | 2 | 3 | 1 | 3 |
1167             //     +---+---+---+---+---+---+
1168             //                       w
1169             //
1170             // Duplicate, advance r. End of vec. Truncate to w.
1171
1172             let ln = self.len();
1173             if ln < 1 { return; }
1174
1175             // Avoid bounds checks by using unsafe pointers.
1176             let p = self.as_mut_ptr();
1177             let mut r = 1;
1178             let mut w = 1;
1179
1180             while r < ln {
1181                 let p_r = p.offset(r as int);
1182                 let p_wm1 = p.offset((w - 1) as int);
1183                 if *p_r != *p_wm1 {
1184                     if r != w {
1185                         let p_w = p_wm1.offset(1);
1186                         mem::swap(&mut *p_r, &mut *p_w);
1187                     }
1188                     w += 1;
1189                 }
1190                 r += 1;
1191             }
1192
1193             self.truncate(w);
1194         }
1195     }
1196 }
1197
1198 ////////////////////////////////////////////////////////////////////////////////
1199 // Internal methods and functions
1200 ////////////////////////////////////////////////////////////////////////////////
1201
1202 impl<T> Vec<T> {
1203     /// Reserves capacity for exactly `capacity` elements in the given vector.
1204     ///
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 }
1209
1210         if capacity > self.cap {
1211             let size = capacity.checked_mul(mem::size_of::<T>())
1212                                .expect("capacity overflow");
1213             unsafe {
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);
1217             }
1218             self.cap = capacity;
1219         }
1220     }
1221 }
1222
1223 // FIXME: #13996: need a way to mark the return value as `noalias`
1224 #[inline(never)]
1225 unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: uint, size: uint) -> *mut T {
1226     if old_size == 0 {
1227         allocate(size, mem::min_align_of::<T>()) as *mut T
1228     } else {
1229         reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T
1230     }
1231 }
1232
1233 #[inline]
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>())
1239     }
1240 }
1241
1242 ////////////////////////////////////////////////////////////////////////////////
1243 // Common trait implementations for Vec
1244 ////////////////////////////////////////////////////////////////////////////////
1245
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()) }
1249
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())
1254         }
1255
1256         // reuse the contained values' allocations/resources.
1257         for (place, thing) in self.iter_mut().zip(other.iter()) {
1258             place.clone_from(thing)
1259         }
1260
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);
1265     }
1266 }
1267
1268 impl<S: hash::Writer + hash::Hasher, T: Hash<S>> Hash<S> for Vec<T> {
1269     #[inline]
1270     fn hash(&self, state: &mut S) {
1271         self.as_slice().hash(state);
1272     }
1273 }
1274
1275 #[stable(feature = "rust1", since = "1.0.0")]
1276 impl<T> Index<uint> for Vec<T> {
1277     type Output = T;
1278
1279     #[inline]
1280     fn index<'a>(&'a self, index: &uint) -> &'a T {
1281         &self.as_slice()[*index]
1282     }
1283 }
1284
1285 #[stable(feature = "rust1", since = "1.0.0")]
1286 impl<T> IndexMut<uint> for Vec<T> {
1287     type Output = T;
1288
1289     #[inline]
1290     fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
1291         &mut self.as_mut_slice()[*index]
1292     }
1293 }
1294
1295
1296 #[stable(feature = "rust1", since = "1.0.0")]
1297 impl<T> ops::Index<ops::Range<uint>> for Vec<T> {
1298     type Output = [T];
1299     #[inline]
1300     fn index(&self, index: &ops::Range<uint>) -> &[T] {
1301         self.as_slice().index(index)
1302     }
1303 }
1304 #[stable(feature = "rust1", since = "1.0.0")]
1305 impl<T> ops::Index<ops::RangeTo<uint>> for Vec<T> {
1306     type Output = [T];
1307     #[inline]
1308     fn index(&self, index: &ops::RangeTo<uint>) -> &[T] {
1309         self.as_slice().index(index)
1310     }
1311 }
1312 #[stable(feature = "rust1", since = "1.0.0")]
1313 impl<T> ops::Index<ops::RangeFrom<uint>> for Vec<T> {
1314     type Output = [T];
1315     #[inline]
1316     fn index(&self, index: &ops::RangeFrom<uint>) -> &[T] {
1317         self.as_slice().index(index)
1318     }
1319 }
1320 #[cfg(stage0)]
1321 #[stable(feature = "rust1", since = "1.0.0")]
1322 impl<T> ops::Index<ops::FullRange> for Vec<T> {
1323     type Output = [T];
1324     #[inline]
1325     fn index(&self, _index: &ops::FullRange) -> &[T] {
1326         self.as_slice()
1327     }
1328 }
1329 #[cfg(not(stage0))]
1330 #[stable(feature = "rust1", since = "1.0.0")]
1331 impl<T> ops::Index<ops::RangeFull> for Vec<T> {
1332     type Output = [T];
1333     #[inline]
1334     fn index(&self, _index: &ops::RangeFull) -> &[T] {
1335         self.as_slice()
1336     }
1337 }
1338
1339 #[stable(feature = "rust1", since = "1.0.0")]
1340 impl<T> ops::IndexMut<ops::Range<uint>> for Vec<T> {
1341     type Output = [T];
1342     #[inline]
1343     fn index_mut(&mut self, index: &ops::Range<uint>) -> &mut [T] {
1344         self.as_mut_slice().index_mut(index)
1345     }
1346 }
1347 #[stable(feature = "rust1", since = "1.0.0")]
1348 impl<T> ops::IndexMut<ops::RangeTo<uint>> for Vec<T> {
1349     type Output = [T];
1350     #[inline]
1351     fn index_mut(&mut self, index: &ops::RangeTo<uint>) -> &mut [T] {
1352         self.as_mut_slice().index_mut(index)
1353     }
1354 }
1355 #[stable(feature = "rust1", since = "1.0.0")]
1356 impl<T> ops::IndexMut<ops::RangeFrom<uint>> for Vec<T> {
1357     type Output = [T];
1358     #[inline]
1359     fn index_mut(&mut self, index: &ops::RangeFrom<uint>) -> &mut [T] {
1360         self.as_mut_slice().index_mut(index)
1361     }
1362 }
1363 #[cfg(stage0)]
1364 #[stable(feature = "rust1", since = "1.0.0")]
1365 impl<T> ops::IndexMut<ops::FullRange> for Vec<T> {
1366     type Output = [T];
1367     #[inline]
1368     fn index_mut(&mut self, _index: &ops::FullRange) -> &mut [T] {
1369         self.as_mut_slice()
1370     }
1371 }
1372 #[cfg(not(stage0))]
1373 #[stable(feature = "rust1", since = "1.0.0")]
1374 impl<T> ops::IndexMut<ops::RangeFull> for Vec<T> {
1375     type Output = [T];
1376     #[inline]
1377     fn index_mut(&mut self, _index: &ops::RangeFull) -> &mut [T] {
1378         self.as_mut_slice()
1379     }
1380 }
1381
1382 #[stable(feature = "rust1", since = "1.0.0")]
1383 impl<T> ops::Deref for Vec<T> {
1384     type Target = [T];
1385
1386     fn deref<'a>(&'a self) -> &'a [T] { self.as_slice() }
1387 }
1388
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() }
1392 }
1393
1394 #[stable(feature = "rust1", since = "1.0.0")]
1395 impl<T> FromIterator<T> for Vec<T> {
1396     #[inline]
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)
1402         }
1403         vector
1404     }
1405 }
1406
1407 #[unstable(feature = "collections", reason = "waiting on Extend stability")]
1408 impl<T> Extend<T> for Vec<T> {
1409     #[inline]
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 {
1414             self.push(element)
1415         }
1416     }
1417 }
1418
1419 impl<A, B> PartialEq<Vec<B>> for Vec<A> where A: PartialEq<B> {
1420     #[inline]
1421     fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1422     #[inline]
1423     fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1424 }
1425
1426 macro_rules! impl_eq {
1427     ($lhs:ty, $rhs:ty) => {
1428         impl<'b, A, B> PartialEq<$rhs> for $lhs where A: PartialEq<B> {
1429             #[inline]
1430             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1431             #[inline]
1432             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1433         }
1434
1435         impl<'b, A, B> PartialEq<$lhs> for $rhs where B: PartialEq<A> {
1436             #[inline]
1437             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
1438             #[inline]
1439             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
1440         }
1441     }
1442 }
1443
1444 impl_eq! { Vec<A>, &'b [B] }
1445 impl_eq! { Vec<A>, &'b mut [B] }
1446
1447 impl<'a, A, B> PartialEq<Vec<B>> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1448     #[inline]
1449     fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1450     #[inline]
1451     fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1452 }
1453
1454 impl<'a, A, B> PartialEq<CowVec<'a, A>> for Vec<B> where A: Clone, B: PartialEq<A> {
1455     #[inline]
1456     fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1457     #[inline]
1458     fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1459 }
1460
1461 macro_rules! impl_eq_for_cowvec {
1462     ($rhs:ty) => {
1463         impl<'a, 'b, A, B> PartialEq<$rhs> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1464             #[inline]
1465             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1466             #[inline]
1467             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1468         }
1469
1470         impl<'a, 'b, A, B> PartialEq<CowVec<'a, A>> for $rhs where A: Clone, B: PartialEq<A> {
1471             #[inline]
1472             fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1473             #[inline]
1474             fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1475         }
1476     }
1477 }
1478
1479 impl_eq_for_cowvec! { &'b [B] }
1480 impl_eq_for_cowvec! { &'b mut [B] }
1481
1482 #[unstable(feature = "collections",
1483            reason = "waiting on PartialOrd stability")]
1484 impl<T: PartialOrd> PartialOrd for Vec<T> {
1485     #[inline]
1486     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1487         self.as_slice().partial_cmp(other.as_slice())
1488     }
1489 }
1490
1491 #[unstable(feature = "collections", reason = "waiting on Eq stability")]
1492 impl<T: Eq> Eq for Vec<T> {}
1493
1494 #[unstable(feature = "collections", reason = "waiting on Ord stability")]
1495 impl<T: Ord> Ord for Vec<T> {
1496     #[inline]
1497     fn cmp(&self, other: &Vec<T>) -> Ordering {
1498         self.as_slice().cmp(other.as_slice())
1499     }
1500 }
1501
1502 impl<T> AsSlice<T> for Vec<T> {
1503     /// Returns a slice into `self`.
1504     ///
1505     /// # Examples
1506     ///
1507     /// ```
1508     /// fn foo(slice: &[int]) {}
1509     ///
1510     /// let vec = vec![1i, 2];
1511     /// foo(vec.as_slice());
1512     /// ```
1513     #[inline]
1514     #[stable(feature = "rust1", since = "1.0.0")]
1515     fn as_slice<'a>(&'a self) -> &'a [T] {
1516         unsafe {
1517             mem::transmute(RawSlice {
1518                 data: *self.ptr,
1519                 len: self.len
1520             })
1521         }
1522     }
1523 }
1524
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>;
1529
1530     #[inline]
1531     fn add(mut self, rhs: &[T]) -> Vec<T> {
1532         self.push_all(rhs);
1533         self
1534     }
1535 }
1536
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]).
1543         if self.cap != 0 {
1544             unsafe {
1545                 for x in self.iter() {
1546                     ptr::read(x);
1547                 }
1548                 dealloc(*self.ptr, self.cap)
1549             }
1550         }
1551     }
1552 }
1553
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> {
1558         Vec::new()
1559     }
1560 }
1561
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)
1566     }
1567 }
1568
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());
1572         Ok(())
1573     }
1574 }
1575
1576 ////////////////////////////////////////////////////////////////////////////////
1577 // Clone-on-write
1578 ////////////////////////////////////////////////////////////////////////////////
1579
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]>;
1584
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))
1589     }
1590 }
1591
1592 impl<'a, T: 'a> IntoCow<'a, Vec<T>, [T]> for Vec<T> where T: Clone {
1593     fn into_cow(self) -> CowVec<'a, T> {
1594         Cow::Owned(self)
1595     }
1596 }
1597
1598 impl<'a, T> IntoCow<'a, Vec<T>, [T]> for &'a [T] where T: Clone {
1599     fn into_cow(self) -> CowVec<'a, T> {
1600         Cow::Borrowed(self)
1601     }
1602 }
1603
1604 ////////////////////////////////////////////////////////////////////////////////
1605 // Iterators
1606 ////////////////////////////////////////////////////////////////////////////////
1607
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
1613     ptr: *const T,
1614     end: *const T
1615 }
1616
1617 unsafe impl<T: Send> Send for IntoIter<T> { }
1618 unsafe impl<T: Sync> Sync for IntoIter<T> { }
1619
1620 impl<T> IntoIter<T> {
1621     #[inline]
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> {
1625         unsafe {
1626             for _x in self { }
1627             let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
1628             mem::forget(self);
1629             Vec { ptr: NonZero::new(allocation), cap: cap, len: 0 }
1630         }
1631     }
1632 }
1633
1634 #[stable(feature = "rust1", since = "1.0.0")]
1635 impl<T> Iterator for IntoIter<T> {
1636     type Item = T;
1637
1638     #[inline]
1639     fn next<'a>(&'a mut self) -> Option<T> {
1640         unsafe {
1641             if self.ptr == self.end {
1642                 None
1643             } else {
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
1647                     // same pointer.
1648                     self.ptr = mem::transmute(self.ptr as uint + 1);
1649
1650                     // Use a non-null pointer value
1651                     Some(ptr::read(mem::transmute(1u)))
1652                 } else {
1653                     let old = self.ptr;
1654                     self.ptr = self.ptr.offset(1);
1655
1656                     Some(ptr::read(old))
1657                 }
1658             }
1659         }
1660     }
1661
1662     #[inline]
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))
1668     }
1669 }
1670
1671 #[stable(feature = "rust1", since = "1.0.0")]
1672 impl<T> DoubleEndedIterator for IntoIter<T> {
1673     #[inline]
1674     fn next_back<'a>(&'a mut self) -> Option<T> {
1675         unsafe {
1676             if self.end == self.ptr {
1677                 None
1678             } else {
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);
1682
1683                     // Use a non-null pointer value
1684                     Some(ptr::read(mem::transmute(1u)))
1685                 } else {
1686                     self.end = self.end.offset(-1);
1687
1688                     Some(ptr::read(mem::transmute(self.end)))
1689                 }
1690             }
1691         }
1692     }
1693 }
1694
1695 #[stable(feature = "rust1", since = "1.0.0")]
1696 impl<T> ExactSizeIterator for IntoIter<T> {}
1697
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
1703         if self.cap != 0 {
1704             for _x in *self {}
1705             unsafe {
1706                 dealloc(self.allocation, self.cap);
1707             }
1708         }
1709     }
1710 }
1711
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> {
1717     ptr: *const T,
1718     end: *const T,
1719     marker: ContravariantLifetime<'a>,
1720 }
1721
1722 #[stable(feature = "rust1", since = "1.0.0")]
1723 impl<'a, T> Iterator for Drain<'a, T> {
1724     type Item = T;
1725
1726     #[inline]
1727     fn next(&mut self) -> Option<T> {
1728         unsafe {
1729             if self.ptr == self.end {
1730                 None
1731             } else {
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
1735                     // same pointer.
1736                     self.ptr = mem::transmute(self.ptr as uint + 1);
1737
1738                     // Use a non-null pointer value
1739                     Some(ptr::read(mem::transmute(1u)))
1740                 } else {
1741                     let old = self.ptr;
1742                     self.ptr = self.ptr.offset(1);
1743
1744                     Some(ptr::read(old))
1745                 }
1746             }
1747         }
1748     }
1749
1750     #[inline]
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))
1756     }
1757 }
1758
1759 #[stable(feature = "rust1", since = "1.0.0")]
1760 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1761     #[inline]
1762     fn next_back(&mut self) -> Option<T> {
1763         unsafe {
1764             if self.end == self.ptr {
1765                 None
1766             } else {
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);
1770
1771                     // Use a non-null pointer value
1772                     Some(ptr::read(mem::transmute(1u)))
1773                 } else {
1774                     self.end = self.end.offset(-1);
1775
1776                     Some(ptr::read(self.end))
1777                 }
1778             }
1779         }
1780     }
1781 }
1782
1783 #[stable(feature = "rust1", since = "1.0.0")]
1784 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1785
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].
1792
1793         // destroy the remaining elements
1794         for _x in *self {}
1795     }
1796 }
1797
1798 ////////////////////////////////////////////////////////////////////////////////
1799 // Conversion from &[T] to &Vec<T>
1800 ////////////////////////////////////////////////////////////////////////////////
1801
1802 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1803 #[unstable(feature = "collections")]
1804 pub struct DerefVec<'a, T> {
1805     x: Vec<T>,
1806     l: ContravariantLifetime<'a>
1807 }
1808
1809 #[unstable(feature = "collections")]
1810 impl<'a, T> Deref for DerefVec<'a, T> {
1811     type Target = Vec<T>;
1812
1813     fn deref<'b>(&'b self) -> &'b Vec<T> {
1814         &self.x
1815     }
1816 }
1817
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) {
1823         self.x.len = 0;
1824         self.x.cap = 0;
1825     }
1826 }
1827
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> {
1831     unsafe {
1832         DerefVec {
1833             x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1834             l: ContravariantLifetime::<'a>
1835         }
1836     }
1837 }
1838
1839 ////////////////////////////////////////////////////////////////////////////////
1840 // Partial vec, used for map_in_place
1841 ////////////////////////////////////////////////////////////////////////////////
1842
1843 /// An owned, partially type-converted vector of elements with non-zero size.
1844 ///
1845 /// `T` and `U` must have the same, non-zero size. They must also have the same
1846 /// alignment.
1847 ///
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> {
1852     vec: Vec<T>,
1853
1854     start_u: *mut U,
1855     end_u: *mut U,
1856     start_t: *mut T,
1857     end_t: *mut T,
1858 }
1859
1860 /// An owned, partially type-converted vector of zero-sized elements.
1861 ///
1862 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1863 /// are destructed.
1864 struct PartialVecZeroSized<T,U> {
1865     num_t: uint,
1866     num_u: uint,
1867     marker_t: InvariantType<T>,
1868     marker_u: InvariantType<U>,
1869 }
1870
1871 #[unsafe_destructor]
1872 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1873     fn drop(&mut self) {
1874         unsafe {
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);
1881
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);
1886             }
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);
1890             }
1891             // After this destructor ran, the destructor of `vec` will run,
1892             // deallocating the underlying memory.
1893         }
1894     }
1895 }
1896
1897 #[unsafe_destructor]
1898 impl<T,U> Drop for PartialVecZeroSized<T,U> {
1899     fn drop(&mut self) {
1900         unsafe {
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.
1904                 self.num_t -= 1;
1905             }
1906             while self.num_u != 0 {
1907                 let _: U = mem::uninitialized(); // Run a `U` destructor.
1908                 self.num_u -= 1;
1909             }
1910         }
1911     }
1912 }
1913
1914 #[cfg(test)]
1915 mod tests {
1916     use prelude::*;
1917     use core::mem::size_of;
1918     use core::iter::repeat;
1919     #[cfg(stage0)]
1920     use core::ops::FullRange;
1921     use test::Bencher;
1922     use super::as_vec;
1923
1924     struct DropCounter<'a> {
1925         count: &'a mut int
1926     }
1927
1928     #[unsafe_destructor]
1929     impl<'a> Drop for DropCounter<'a> {
1930         fn drop(&mut self) {
1931             *self.count += 1;
1932         }
1933     }
1934
1935     #[test]
1936     fn test_as_vec() {
1937         let xs = [1u8, 2u8, 3u8];
1938         assert_eq!(as_vec(&xs).as_slice(), xs);
1939     }
1940
1941     #[test]
1942     fn test_as_vec_dtor() {
1943         let (mut count_x, mut count_y) = (0, 0);
1944         {
1945             let xs = &[DropCounter { count: &mut count_x }, DropCounter { count: &mut count_y }];
1946             assert_eq!(as_vec(xs).len(), 2);
1947         }
1948         assert_eq!(count_x, 1);
1949         assert_eq!(count_y, 1);
1950     }
1951
1952     #[test]
1953     fn test_small_vec_struct() {
1954         assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1955     }
1956
1957     #[test]
1958     fn test_double_drop() {
1959         struct TwoVec<T> {
1960             x: Vec<T>,
1961             y: Vec<T>
1962         }
1963
1964         let (mut count_x, mut count_y) = (0, 0);
1965         {
1966             let mut tv = TwoVec {
1967                 x: Vec::new(),
1968                 y: Vec::new()
1969             };
1970             tv.x.push(DropCounter {count: &mut count_x});
1971             tv.y.push(DropCounter {count: &mut count_y});
1972
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.
1976             drop(tv.x);
1977
1978             // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1979         }
1980
1981         assert_eq!(count_x, 1);
1982         assert_eq!(count_y, 1);
1983     }
1984
1985     #[test]
1986     fn test_reserve() {
1987         let mut v = Vec::new();
1988         assert_eq!(v.capacity(), 0);
1989
1990         v.reserve(2);
1991         assert!(v.capacity() >= 2);
1992
1993         for i in 0i..16 {
1994             v.push(i);
1995         }
1996
1997         assert!(v.capacity() >= 16);
1998         v.reserve(16);
1999         assert!(v.capacity() >= 32);
2000
2001         v.push(16);
2002
2003         v.reserve(16);
2004         assert!(v.capacity() >= 33)
2005     }
2006
2007     #[test]
2008     fn test_extend() {
2009         let mut v = Vec::new();
2010         let mut w = Vec::new();
2011
2012         v.extend(0i..3);
2013         for i in 0i..3 { w.push(i) }
2014
2015         assert_eq!(v, w);
2016
2017         v.extend(3i..10);
2018         for i in 3i..10 { w.push(i) }
2019
2020         assert_eq!(v, w);
2021     }
2022
2023     #[test]
2024     fn test_slice_from_mut() {
2025         let mut values = vec![1u8,2,3,4,5];
2026         {
2027             let slice = &mut values[2 ..];
2028             assert!(slice == [3, 4, 5]);
2029             for p in slice.iter_mut() {
2030                 *p += 2;
2031             }
2032         }
2033
2034         assert!(values == [1, 2, 5, 6, 7]);
2035     }
2036
2037     #[test]
2038     fn test_slice_to_mut() {
2039         let mut values = vec![1u8,2,3,4,5];
2040         {
2041             let slice = &mut values[.. 2];
2042             assert!(slice == [1, 2]);
2043             for p in slice.iter_mut() {
2044                 *p += 1;
2045             }
2046         }
2047
2048         assert!(values == [2, 3, 3, 4, 5]);
2049     }
2050
2051     #[test]
2052     fn test_split_at_mut() {
2053         let mut values = vec![1u8,2,3,4,5];
2054         {
2055             let (left, right) = values.split_at_mut(2);
2056             {
2057                 let left: &[_] = left;
2058                 assert!(&left[..left.len()] == &[1, 2][]);
2059             }
2060             for p in left.iter_mut() {
2061                 *p += 1;
2062             }
2063
2064             {
2065                 let right: &[_] = right;
2066                 assert!(&right[..right.len()] == &[3, 4, 5][]);
2067             }
2068             for p in right.iter_mut() {
2069                 *p += 2;
2070             }
2071         }
2072
2073         assert!(values == vec![2u8, 3, 5, 6, 7]);
2074     }
2075
2076     #[test]
2077     fn test_clone() {
2078         let v: Vec<int> = vec!();
2079         let w = vec!(1i, 2, 3);
2080
2081         assert_eq!(v, v.clone());
2082
2083         let z = w.clone();
2084         assert_eq!(w, z);
2085         // they should be disjoint in memory.
2086         assert!(w.as_ptr() != z.as_ptr())
2087     }
2088
2089     #[test]
2090     fn test_clone_from() {
2091         let mut v = vec!();
2092         let three = vec!(box 1i, box 2, box 3);
2093         let two = vec!(box 4i, box 5);
2094         // zero, long
2095         v.clone_from(&three);
2096         assert_eq!(v, three);
2097
2098         // equal
2099         v.clone_from(&three);
2100         assert_eq!(v, three);
2101
2102         // long, short
2103         v.clone_from(&two);
2104         assert_eq!(v, two);
2105
2106         // short, long
2107         v.clone_from(&three);
2108         assert_eq!(v, three)
2109     }
2110
2111     #[test]
2112     fn test_retain() {
2113         let mut vec = vec![1u, 2, 3, 4];
2114         vec.retain(|&x| x % 2 == 0);
2115         assert!(vec == vec![2u, 4]);
2116     }
2117
2118     #[test]
2119     fn zero_sized_values() {
2120         let mut v = Vec::new();
2121         assert_eq!(v.len(), 0);
2122         v.push(());
2123         assert_eq!(v.len(), 1);
2124         v.push(());
2125         assert_eq!(v.len(), 2);
2126         assert_eq!(v.pop(), Some(()));
2127         assert_eq!(v.pop(), Some(()));
2128         assert_eq!(v.pop(), None);
2129
2130         assert_eq!(v.iter().count(), 0);
2131         v.push(());
2132         assert_eq!(v.iter().count(), 1);
2133         v.push(());
2134         assert_eq!(v.iter().count(), 2);
2135
2136         for &() in v.iter() {}
2137
2138         assert_eq!(v.iter_mut().count(), 2);
2139         v.push(());
2140         assert_eq!(v.iter_mut().count(), 3);
2141         v.push(());
2142         assert_eq!(v.iter_mut().count(), 4);
2143
2144         for &mut () in v.iter_mut() {}
2145         unsafe { v.set_len(0); }
2146         assert_eq!(v.iter_mut().count(), 0);
2147     }
2148
2149     #[test]
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]));
2155     }
2156
2157     #[test]
2158     fn test_zip_unzip() {
2159         let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
2160
2161         let (left, right): (Vec<_>, Vec<_>) = z1.iter().map(|&x| x).unzip();
2162
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]));
2166     }
2167
2168     #[test]
2169     fn test_unsafe_ptrs() {
2170         unsafe {
2171             // Test on-stack copy-from-buf.
2172             let a = [1i, 2, 3];
2173             let ptr = a.as_ptr();
2174             let b = Vec::from_raw_buf(ptr, 3u);
2175             assert_eq!(b, vec![1, 2, 3]);
2176
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]);
2182         }
2183     }
2184
2185     #[test]
2186     fn test_vec_truncate_drop() {
2187         static mut drops: uint = 0;
2188         struct Elem(int);
2189         impl Drop for Elem {
2190             fn drop(&mut self) {
2191                 unsafe { drops += 1; }
2192             }
2193         }
2194
2195         let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
2196         assert_eq!(unsafe { drops }, 0);
2197         v.truncate(3);
2198         assert_eq!(unsafe { drops }, 2);
2199         v.truncate(0);
2200         assert_eq!(unsafe { drops }, 5);
2201     }
2202
2203     #[test]
2204     #[should_fail]
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")
2212                 }
2213             }
2214         }
2215
2216         let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
2217         v.truncate(0);
2218     }
2219
2220     #[test]
2221     fn test_index() {
2222         let vec = vec!(1i, 2, 3);
2223         assert!(vec[1] == 2);
2224     }
2225
2226     #[test]
2227     #[should_fail]
2228     fn test_index_out_of_bounds() {
2229         let vec = vec!(1i, 2, 3);
2230         let _ = vec[3];
2231     }
2232
2233     #[test]
2234     #[should_fail]
2235     fn test_slice_out_of_bounds_1() {
2236         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2237         &x[-1..];
2238     }
2239
2240     #[test]
2241     #[should_fail]
2242     fn test_slice_out_of_bounds_2() {
2243         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2244         &x[..6];
2245     }
2246
2247     #[test]
2248     #[should_fail]
2249     fn test_slice_out_of_bounds_3() {
2250         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2251         &x[-1..4];
2252     }
2253
2254     #[test]
2255     #[should_fail]
2256     fn test_slice_out_of_bounds_4() {
2257         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2258         &x[1..6];
2259     }
2260
2261     #[test]
2262     #[should_fail]
2263     fn test_slice_out_of_bounds_5() {
2264         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2265         &x[3..2];
2266     }
2267
2268     #[test]
2269     #[should_fail]
2270     fn test_swap_remove_empty() {
2271         let mut vec: Vec<uint> = vec!();
2272         vec.swap_remove(0);
2273     }
2274
2275     #[test]
2276     fn test_move_iter_unwrap() {
2277         let mut vec: Vec<uint> = Vec::with_capacity(7);
2278         vec.push(1);
2279         vec.push(2);
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);
2285     }
2286
2287     #[test]
2288     #[should_fail]
2289     fn test_map_in_place_incompatible_types_fail() {
2290         let v = vec![0u, 1, 2];
2291         v.map_in_place(|_| ());
2292     }
2293
2294     #[test]
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]);
2298     }
2299
2300     #[test]
2301     fn test_map_in_place_zero_sized() {
2302         let v = vec![(), ()];
2303         #[derive(PartialEq, Debug)]
2304         struct ZeroSized;
2305         assert_eq!(v.map_in_place(|_| ZeroSized), [ZeroSized, ZeroSized]);
2306     }
2307
2308     #[test]
2309     fn test_map_in_place_zero_drop_count() {
2310         use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT};
2311
2312         #[derive(Clone, PartialEq, Debug)]
2313         struct Nothing;
2314         impl Drop for Nothing { fn drop(&mut self) { } }
2315
2316         #[derive(Clone, PartialEq, Debug)]
2317         struct ZeroSized;
2318         impl Drop for ZeroSized {
2319             fn drop(&mut self) {
2320                 DROP_COUNTER.fetch_add(1, Ordering::Relaxed);
2321             }
2322         }
2323         const NUM_ELEMENTS: uint = 2;
2324         static DROP_COUNTER: AtomicUsize = ATOMIC_USIZE_INIT;
2325
2326         let v = repeat(Nothing).take(NUM_ELEMENTS).collect::<Vec<_>>();
2327
2328         DROP_COUNTER.store(0, Ordering::Relaxed);
2329
2330         let v = v.map_in_place(|_| ZeroSized);
2331         assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), 0);
2332         drop(v);
2333         assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), NUM_ELEMENTS);
2334     }
2335
2336     #[test]
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() {
2341             vec2.push(i);
2342         }
2343         assert!(vec2 == vec![1, 2, 3]);
2344     }
2345
2346     #[test]
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() {
2351             vec2.push(i);
2352         }
2353         assert!(vec2 == vec![3, 2, 1]);
2354     }
2355
2356     #[test]
2357     fn test_move_items_zero_sized() {
2358         let vec = vec![(), (), ()];
2359         let mut vec2 : Vec<()> = vec![];
2360         for i in vec.into_iter() {
2361             vec2.push(i);
2362         }
2363         assert!(vec2 == vec![(), (), ()]);
2364     }
2365
2366     #[test]
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() {
2371             vec2.push(i);
2372         }
2373         assert_eq!(vec, []);
2374         assert_eq!(vec2, [ 1, 2, 3 ]);
2375     }
2376
2377     #[test]
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() {
2382             vec2.push(i);
2383         }
2384         assert_eq!(vec, []);
2385         assert_eq!(vec2, [ 3, 2, 1 ]);
2386     }
2387
2388     #[test]
2389     fn test_drain_items_zero_sized() {
2390         let mut vec = vec![(), (), ()];
2391         let mut vec2: Vec<()> = vec![];
2392         for i in vec.drain() {
2393             vec2.push(i);
2394         }
2395         assert_eq!(vec, []);
2396         assert_eq!(vec2, [(), (), ()]);
2397     }
2398
2399     #[test]
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]);
2404     }
2405
2406     #[test]
2407     fn test_append() {
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![]);
2413     }
2414
2415     #[test]
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]);
2421     }
2422
2423     #[bench]
2424     fn bench_new(b: &mut Bencher) {
2425         b.iter(|| {
2426             let v: Vec<uint> = Vec::new();
2427             assert_eq!(v.len(), 0);
2428             assert_eq!(v.capacity(), 0);
2429         })
2430     }
2431
2432     fn do_bench_with_capacity(b: &mut Bencher, src_len: uint) {
2433         b.bytes = src_len as u64;
2434
2435         b.iter(|| {
2436             let v: Vec<uint> = Vec::with_capacity(src_len);
2437             assert_eq!(v.len(), 0);
2438             assert_eq!(v.capacity(), src_len);
2439         })
2440     }
2441
2442     #[bench]
2443     fn bench_with_capacity_0000(b: &mut Bencher) {
2444         do_bench_with_capacity(b, 0)
2445     }
2446
2447     #[bench]
2448     fn bench_with_capacity_0010(b: &mut Bencher) {
2449         do_bench_with_capacity(b, 10)
2450     }
2451
2452     #[bench]
2453     fn bench_with_capacity_0100(b: &mut Bencher) {
2454         do_bench_with_capacity(b, 100)
2455     }
2456
2457     #[bench]
2458     fn bench_with_capacity_1000(b: &mut Bencher) {
2459         do_bench_with_capacity(b, 1000)
2460     }
2461
2462     fn do_bench_from_fn(b: &mut Bencher, src_len: uint) {
2463         b.bytes = src_len as u64;
2464
2465         b.iter(|| {
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));
2469         })
2470     }
2471
2472     #[bench]
2473     fn bench_from_fn_0000(b: &mut Bencher) {
2474         do_bench_from_fn(b, 0)
2475     }
2476
2477     #[bench]
2478     fn bench_from_fn_0010(b: &mut Bencher) {
2479         do_bench_from_fn(b, 10)
2480     }
2481
2482     #[bench]
2483     fn bench_from_fn_0100(b: &mut Bencher) {
2484         do_bench_from_fn(b, 100)
2485     }
2486
2487     #[bench]
2488     fn bench_from_fn_1000(b: &mut Bencher) {
2489         do_bench_from_fn(b, 1000)
2490     }
2491
2492     fn do_bench_from_elem(b: &mut Bencher, src_len: uint) {
2493         b.bytes = src_len as u64;
2494
2495         b.iter(|| {
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));
2499         })
2500     }
2501
2502     #[bench]
2503     fn bench_from_elem_0000(b: &mut Bencher) {
2504         do_bench_from_elem(b, 0)
2505     }
2506
2507     #[bench]
2508     fn bench_from_elem_0010(b: &mut Bencher) {
2509         do_bench_from_elem(b, 10)
2510     }
2511
2512     #[bench]
2513     fn bench_from_elem_0100(b: &mut Bencher) {
2514         do_bench_from_elem(b, 100)
2515     }
2516
2517     #[bench]
2518     fn bench_from_elem_1000(b: &mut Bencher) {
2519         do_bench_from_elem(b, 1000)
2520     }
2521
2522     fn do_bench_from_slice(b: &mut Bencher, src_len: uint) {
2523         let src: Vec<uint> = FromIterator::from_iter(0..src_len);
2524
2525         b.bytes = src_len as u64;
2526
2527         b.iter(|| {
2528             let dst = src.clone()[].to_vec();
2529             assert_eq!(dst.len(), src_len);
2530             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2531         });
2532     }
2533
2534     #[bench]
2535     fn bench_from_slice_0000(b: &mut Bencher) {
2536         do_bench_from_slice(b, 0)
2537     }
2538
2539     #[bench]
2540     fn bench_from_slice_0010(b: &mut Bencher) {
2541         do_bench_from_slice(b, 10)
2542     }
2543
2544     #[bench]
2545     fn bench_from_slice_0100(b: &mut Bencher) {
2546         do_bench_from_slice(b, 100)
2547     }
2548
2549     #[bench]
2550     fn bench_from_slice_1000(b: &mut Bencher) {
2551         do_bench_from_slice(b, 1000)
2552     }
2553
2554     fn do_bench_from_iter(b: &mut Bencher, src_len: uint) {
2555         let src: Vec<uint> = FromIterator::from_iter(0..src_len);
2556
2557         b.bytes = src_len as u64;
2558
2559         b.iter(|| {
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));
2563         });
2564     }
2565
2566     #[bench]
2567     fn bench_from_iter_0000(b: &mut Bencher) {
2568         do_bench_from_iter(b, 0)
2569     }
2570
2571     #[bench]
2572     fn bench_from_iter_0010(b: &mut Bencher) {
2573         do_bench_from_iter(b, 10)
2574     }
2575
2576     #[bench]
2577     fn bench_from_iter_0100(b: &mut Bencher) {
2578         do_bench_from_iter(b, 100)
2579     }
2580
2581     #[bench]
2582     fn bench_from_iter_1000(b: &mut Bencher) {
2583         do_bench_from_iter(b, 1000)
2584     }
2585
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);
2589
2590         b.bytes = src_len as u64;
2591
2592         b.iter(|| {
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));
2597         });
2598     }
2599
2600     #[bench]
2601     fn bench_extend_0000_0000(b: &mut Bencher) {
2602         do_bench_extend(b, 0, 0)
2603     }
2604
2605     #[bench]
2606     fn bench_extend_0000_0010(b: &mut Bencher) {
2607         do_bench_extend(b, 0, 10)
2608     }
2609
2610     #[bench]
2611     fn bench_extend_0000_0100(b: &mut Bencher) {
2612         do_bench_extend(b, 0, 100)
2613     }
2614
2615     #[bench]
2616     fn bench_extend_0000_1000(b: &mut Bencher) {
2617         do_bench_extend(b, 0, 1000)
2618     }
2619
2620     #[bench]
2621     fn bench_extend_0010_0010(b: &mut Bencher) {
2622         do_bench_extend(b, 10, 10)
2623     }
2624
2625     #[bench]
2626     fn bench_extend_0100_0100(b: &mut Bencher) {
2627         do_bench_extend(b, 100, 100)
2628     }
2629
2630     #[bench]
2631     fn bench_extend_1000_1000(b: &mut Bencher) {
2632         do_bench_extend(b, 1000, 1000)
2633     }
2634
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);
2638
2639         b.bytes = src_len as u64;
2640
2641         b.iter(|| {
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));
2646         });
2647     }
2648
2649     #[bench]
2650     fn bench_push_all_0000_0000(b: &mut Bencher) {
2651         do_bench_push_all(b, 0, 0)
2652     }
2653
2654     #[bench]
2655     fn bench_push_all_0000_0010(b: &mut Bencher) {
2656         do_bench_push_all(b, 0, 10)
2657     }
2658
2659     #[bench]
2660     fn bench_push_all_0000_0100(b: &mut Bencher) {
2661         do_bench_push_all(b, 0, 100)
2662     }
2663
2664     #[bench]
2665     fn bench_push_all_0000_1000(b: &mut Bencher) {
2666         do_bench_push_all(b, 0, 1000)
2667     }
2668
2669     #[bench]
2670     fn bench_push_all_0010_0010(b: &mut Bencher) {
2671         do_bench_push_all(b, 10, 10)
2672     }
2673
2674     #[bench]
2675     fn bench_push_all_0100_0100(b: &mut Bencher) {
2676         do_bench_push_all(b, 100, 100)
2677     }
2678
2679     #[bench]
2680     fn bench_push_all_1000_1000(b: &mut Bencher) {
2681         do_bench_push_all(b, 1000, 1000)
2682     }
2683
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);
2687
2688         b.bytes = src_len as u64;
2689
2690         b.iter(|| {
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));
2695         });
2696     }
2697
2698     #[bench]
2699     fn bench_push_all_move_0000_0000(b: &mut Bencher) {
2700         do_bench_push_all_move(b, 0, 0)
2701     }
2702
2703     #[bench]
2704     fn bench_push_all_move_0000_0010(b: &mut Bencher) {
2705         do_bench_push_all_move(b, 0, 10)
2706     }
2707
2708     #[bench]
2709     fn bench_push_all_move_0000_0100(b: &mut Bencher) {
2710         do_bench_push_all_move(b, 0, 100)
2711     }
2712
2713     #[bench]
2714     fn bench_push_all_move_0000_1000(b: &mut Bencher) {
2715         do_bench_push_all_move(b, 0, 1000)
2716     }
2717
2718     #[bench]
2719     fn bench_push_all_move_0010_0010(b: &mut Bencher) {
2720         do_bench_push_all_move(b, 10, 10)
2721     }
2722
2723     #[bench]
2724     fn bench_push_all_move_0100_0100(b: &mut Bencher) {
2725         do_bench_push_all_move(b, 100, 100)
2726     }
2727
2728     #[bench]
2729     fn bench_push_all_move_1000_1000(b: &mut Bencher) {
2730         do_bench_push_all_move(b, 1000, 1000)
2731     }
2732
2733     fn do_bench_clone(b: &mut Bencher, src_len: uint) {
2734         let src: Vec<uint> = FromIterator::from_iter(0..src_len);
2735
2736         b.bytes = src_len as u64;
2737
2738         b.iter(|| {
2739             let dst = src.clone();
2740             assert_eq!(dst.len(), src_len);
2741             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2742         });
2743     }
2744
2745     #[bench]
2746     fn bench_clone_0000(b: &mut Bencher) {
2747         do_bench_clone(b, 0)
2748     }
2749
2750     #[bench]
2751     fn bench_clone_0010(b: &mut Bencher) {
2752         do_bench_clone(b, 10)
2753     }
2754
2755     #[bench]
2756     fn bench_clone_0100(b: &mut Bencher) {
2757         do_bench_clone(b, 100)
2758     }
2759
2760     #[bench]
2761     fn bench_clone_1000(b: &mut Bencher) {
2762         do_bench_clone(b, 1000)
2763     }
2764
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);
2768
2769         b.bytes = (times * src_len) as u64;
2770
2771         b.iter(|| {
2772             let mut dst = dst.clone();
2773
2774             for _ in 0..times {
2775                 dst.clone_from(&src);
2776
2777                 assert_eq!(dst.len(), src_len);
2778                 assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x));
2779             }
2780         });
2781     }
2782
2783     #[bench]
2784     fn bench_clone_from_01_0000_0000(b: &mut Bencher) {
2785         do_bench_clone_from(b, 1, 0, 0)
2786     }
2787
2788     #[bench]
2789     fn bench_clone_from_01_0000_0010(b: &mut Bencher) {
2790         do_bench_clone_from(b, 1, 0, 10)
2791     }
2792
2793     #[bench]
2794     fn bench_clone_from_01_0000_0100(b: &mut Bencher) {
2795         do_bench_clone_from(b, 1, 0, 100)
2796     }
2797
2798     #[bench]
2799     fn bench_clone_from_01_0000_1000(b: &mut Bencher) {
2800         do_bench_clone_from(b, 1, 0, 1000)
2801     }
2802
2803     #[bench]
2804     fn bench_clone_from_01_0010_0010(b: &mut Bencher) {
2805         do_bench_clone_from(b, 1, 10, 10)
2806     }
2807
2808     #[bench]
2809     fn bench_clone_from_01_0100_0100(b: &mut Bencher) {
2810         do_bench_clone_from(b, 1, 100, 100)
2811     }
2812
2813     #[bench]
2814     fn bench_clone_from_01_1000_1000(b: &mut Bencher) {
2815         do_bench_clone_from(b, 1, 1000, 1000)
2816     }
2817
2818     #[bench]
2819     fn bench_clone_from_01_0010_0100(b: &mut Bencher) {
2820         do_bench_clone_from(b, 1, 10, 100)
2821     }
2822
2823     #[bench]
2824     fn bench_clone_from_01_0100_1000(b: &mut Bencher) {
2825         do_bench_clone_from(b, 1, 100, 1000)
2826     }
2827
2828     #[bench]
2829     fn bench_clone_from_01_0010_0000(b: &mut Bencher) {
2830         do_bench_clone_from(b, 1, 10, 0)
2831     }
2832
2833     #[bench]
2834     fn bench_clone_from_01_0100_0010(b: &mut Bencher) {
2835         do_bench_clone_from(b, 1, 100, 10)
2836     }
2837
2838     #[bench]
2839     fn bench_clone_from_01_1000_0100(b: &mut Bencher) {
2840         do_bench_clone_from(b, 1, 1000, 100)
2841     }
2842
2843     #[bench]
2844     fn bench_clone_from_10_0000_0000(b: &mut Bencher) {
2845         do_bench_clone_from(b, 10, 0, 0)
2846     }
2847
2848     #[bench]
2849     fn bench_clone_from_10_0000_0010(b: &mut Bencher) {
2850         do_bench_clone_from(b, 10, 0, 10)
2851     }
2852
2853     #[bench]
2854     fn bench_clone_from_10_0000_0100(b: &mut Bencher) {
2855         do_bench_clone_from(b, 10, 0, 100)
2856     }
2857
2858     #[bench]
2859     fn bench_clone_from_10_0000_1000(b: &mut Bencher) {
2860         do_bench_clone_from(b, 10, 0, 1000)
2861     }
2862
2863     #[bench]
2864     fn bench_clone_from_10_0010_0010(b: &mut Bencher) {
2865         do_bench_clone_from(b, 10, 10, 10)
2866     }
2867
2868     #[bench]
2869     fn bench_clone_from_10_0100_0100(b: &mut Bencher) {
2870         do_bench_clone_from(b, 10, 100, 100)
2871     }
2872
2873     #[bench]
2874     fn bench_clone_from_10_1000_1000(b: &mut Bencher) {
2875         do_bench_clone_from(b, 10, 1000, 1000)
2876     }
2877
2878     #[bench]
2879     fn bench_clone_from_10_0010_0100(b: &mut Bencher) {
2880         do_bench_clone_from(b, 10, 10, 100)
2881     }
2882
2883     #[bench]
2884     fn bench_clone_from_10_0100_1000(b: &mut Bencher) {
2885         do_bench_clone_from(b, 10, 100, 1000)
2886     }
2887
2888     #[bench]
2889     fn bench_clone_from_10_0010_0000(b: &mut Bencher) {
2890         do_bench_clone_from(b, 10, 10, 0)
2891     }
2892
2893     #[bench]
2894     fn bench_clone_from_10_0100_0010(b: &mut Bencher) {
2895         do_bench_clone_from(b, 10, 100, 10)
2896     }
2897
2898     #[bench]
2899     fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
2900         do_bench_clone_from(b, 10, 1000, 100)
2901     }
2902 }