]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec.rs
doc: remove incomplete sentence
[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, 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 use core::prelude::*;
48
49 use alloc::boxed::Box;
50 use alloc::heap::{EMPTY, allocate, reallocate, deallocate};
51 use core::borrow::{Cow, IntoCow};
52 use core::cmp::max;
53 use core::cmp::{Equiv, Ordering};
54 use core::default::Default;
55 use core::fmt;
56 use core::hash::{mod, Hash};
57 use core::iter::{repeat, FromIterator};
58 use core::kinds::marker::{ContravariantLifetime, InvariantType};
59 use core::mem;
60 use core::nonzero::NonZero;
61 use core::num::{Int, UnsignedInt};
62 use core::ops::{Index, IndexMut, Deref, Add};
63 use core::ops;
64 use core::ptr;
65 use core::raw::Slice as RawSlice;
66 use core::uint;
67
68 /// A growable list type, written `Vec<T>` but pronounced 'vector.'
69 ///
70 /// # Examples
71 ///
72 /// ```
73 /// let mut vec = Vec::new();
74 /// vec.push(1i);
75 /// vec.push(2i);
76 ///
77 /// assert_eq!(vec.len(), 2);
78 /// assert_eq!(vec[0], 1);
79 ///
80 /// assert_eq!(vec.pop(), Some(2));
81 /// assert_eq!(vec.len(), 1);
82 ///
83 /// vec[0] = 7i;
84 /// assert_eq!(vec[0], 7);
85 ///
86 /// vec.push_all(&[1, 2, 3]);
87 ///
88 /// for x in vec.iter() {
89 ///     println!("{}", x);
90 /// }
91 /// assert_eq!(vec, vec![7i, 1, 2, 3]);
92 /// ```
93 ///
94 /// The `vec!` macro is provided to make initialization more convenient:
95 ///
96 /// ```
97 /// let mut vec = vec![1i, 2i, 3i];
98 /// vec.push(4);
99 /// assert_eq!(vec, vec![1, 2, 3, 4]);
100 /// ```
101 ///
102 /// Use a `Vec<T>` as an efficient stack:
103 ///
104 /// ```
105 /// let mut stack = Vec::new();
106 ///
107 /// stack.push(1i);
108 /// stack.push(2i);
109 /// stack.push(3i);
110 ///
111 /// loop {
112 ///     let top = match stack.pop() {
113 ///         None => break, // empty
114 ///         Some(x) => x,
115 ///     };
116 ///     // Prints 3, 2, 1
117 ///     println!("{}", top);
118 /// }
119 /// ```
120 ///
121 /// # Capacity and reallocation
122 ///
123 /// The capacity of a vector is the amount of space allocated for any future elements that will be
124 /// added onto the vector. This is not to be confused with the *length* of a vector, which
125 /// specifies the number of actual elements within the vector. If a vector's length exceeds its
126 /// capacity, its capacity will automatically be increased, but its elements will have to be
127 /// reallocated.
128 ///
129 /// For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10
130 /// more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or
131 /// cause reallocation to occur. However, if the vector's length is increased to 11, it will have
132 /// to reallocate, which can be slow. For this reason, it is recommended to use
133 /// `Vec::with_capacity` whenever possible to specify how big the vector is expected to get.
134 #[unsafe_no_drop_flag]
135 #[stable]
136 pub struct Vec<T> {
137     ptr: NonZero<*mut T>,
138     len: uint,
139     cap: uint,
140 }
141
142 unsafe impl<T: Send> Send for Vec<T> { }
143 unsafe impl<T: Sync> Sync for Vec<T> { }
144
145 ////////////////////////////////////////////////////////////////////////////////
146 // Inherent methods
147 ////////////////////////////////////////////////////////////////////////////////
148
149 impl<T> Vec<T> {
150     /// Constructs a new, empty `Vec<T>`.
151     ///
152     /// The vector will not allocate until elements are pushed onto it.
153     ///
154     /// # Examples
155     ///
156     /// ```
157     /// let mut vec: Vec<int> = Vec::new();
158     /// ```
159     #[inline]
160     #[stable]
161     pub fn new() -> Vec<T> {
162         // We want ptr to never be NULL so instead we set it to some arbitrary
163         // non-null value which is fine since we never call deallocate on the ptr
164         // if cap is 0. The reason for this is because the pointer of a slice
165         // being NULL would break the null pointer optimization for enums.
166         Vec { ptr: unsafe { NonZero::new(EMPTY as *mut T) }, len: 0, cap: 0 }
167     }
168
169     /// Constructs a new, empty `Vec<T>` with the specified capacity.
170     ///
171     /// The vector will be able to hold exactly `capacity` elements without reallocating. If
172     /// `capacity` is 0, the vector will not allocate.
173     ///
174     /// It is important to note that this function does not specify the *length* of the returned
175     /// vector, but only the *capacity*. (For an explanation of the difference between length and
176     /// capacity, see the main `Vec<T>` docs above, 'Capacity and reallocation'.)
177     ///
178     /// # Examples
179     ///
180     /// ```
181     /// let mut vec: Vec<int> = Vec::with_capacity(10);
182     ///
183     /// // The vector contains no items, even though it has capacity for more
184     /// assert_eq!(vec.len(), 0);
185     ///
186     /// // These are all done without reallocating...
187     /// for i in range(0i, 10) {
188     ///     vec.push(i);
189     /// }
190     ///
191     /// // ...but this may make the vector reallocate
192     /// vec.push(11);
193     /// ```
194     #[inline]
195     #[stable]
196     pub fn with_capacity(capacity: uint) -> Vec<T> {
197         if mem::size_of::<T>() == 0 {
198             Vec { ptr: unsafe { NonZero::new(EMPTY as *mut T) }, len: 0, cap: uint::MAX }
199         } else if capacity == 0 {
200             Vec::new()
201         } else {
202             let size = capacity.checked_mul(mem::size_of::<T>())
203                                .expect("capacity overflow");
204             let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
205             if ptr.is_null() { ::alloc::oom() }
206             Vec { ptr: unsafe { NonZero::new(ptr as *mut T) }, len: 0, cap: capacity }
207         }
208     }
209
210     /// Deprecated: use `iter::range(0, length).map(op).collect()` instead
211     #[inline]
212     #[deprecated = "use iter::range(0, length).map(op).collect() instead"]
213     pub fn from_fn<F>(length: uint, op: F) -> Vec<T> where F: FnMut(uint) -> T {
214         range(0, length).map(op).collect()
215     }
216
217     /// Creates a `Vec<T>` directly from the raw components of another vector.
218     ///
219     /// This is highly unsafe, due to the number of invariants that aren't checked.
220     ///
221     /// # Examples
222     ///
223     /// ```
224     /// use std::ptr;
225     /// use std::mem;
226     ///
227     /// fn main() {
228     ///     let mut v = vec![1i, 2, 3];
229     ///
230     ///     // Pull out the various important pieces of information about `v`
231     ///     let p = v.as_mut_ptr();
232     ///     let len = v.len();
233     ///     let cap = v.capacity();
234     ///
235     ///     unsafe {
236     ///         // Cast `v` into the void: no destructor run, so we are in
237     ///         // complete control of the allocation to which `p` points.
238     ///         mem::forget(v);
239     ///
240     ///         // Overwrite memory with 4, 5, 6
241     ///         for i in range(0, len as int) {
242     ///             ptr::write(p.offset(i), 4 + i);
243     ///         }
244     ///
245     ///         // Put everything back together into a Vec
246     ///         let rebuilt = Vec::from_raw_parts(p, len, cap);
247     ///         assert_eq!(rebuilt, vec![4i, 5i, 6i]);
248     ///     }
249     /// }
250     /// ```
251     #[stable]
252     pub unsafe fn from_raw_parts(ptr: *mut T, length: uint,
253                                  capacity: uint) -> Vec<T> {
254         Vec { ptr: NonZero::new(ptr), len: length, cap: capacity }
255     }
256
257     /// Creates a vector by copying the elements from a raw pointer.
258     ///
259     /// This function will copy `elts` contiguous elements starting at `ptr` into a new allocation
260     /// owned by the returned `Vec<T>`. The elements of the buffer are copied into the vector
261     /// without cloning, as if `ptr::read()` were called on them.
262     #[inline]
263     #[unstable = "may be better expressed via composition"]
264     pub unsafe fn from_raw_buf(ptr: *const T, elts: uint) -> Vec<T> {
265         let mut dst = Vec::with_capacity(elts);
266         dst.set_len(elts);
267         ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
268         dst
269     }
270
271     /// Deprecated: use `into_iter().partition(f)` instead.
272     #[inline]
273     #[deprecated = "use into_iter().partition(f) instead"]
274     pub fn partition<F>(self, f: F) -> (Vec<T>, Vec<T>) where F: FnMut(&T) -> bool {
275         self.into_iter().partition(f)
276     }
277
278     /// Returns the number of elements the vector can hold without
279     /// reallocating.
280     ///
281     /// # Examples
282     ///
283     /// ```
284     /// let vec: Vec<int> = Vec::with_capacity(10);
285     /// assert_eq!(vec.capacity(), 10);
286     /// ```
287     #[inline]
288     #[stable]
289     pub fn capacity(&self) -> uint {
290         self.cap
291     }
292
293     /// Deprecated: Renamed to `reserve`.
294     #[deprecated = "Renamed to `reserve`"]
295     pub fn reserve_additional(&mut self, extra: uint) {
296         self.reserve(extra)
297     }
298
299     /// Reserves capacity for at least `additional` more elements to be inserted in the given
300     /// `Vec<T>`. The collection may reserve more space to avoid frequent reallocations.
301     ///
302     /// # Panics
303     ///
304     /// Panics if the new capacity overflows `uint`.
305     ///
306     /// # Examples
307     ///
308     /// ```
309     /// let mut vec: Vec<int> = vec![1];
310     /// vec.reserve(10);
311     /// assert!(vec.capacity() >= 11);
312     /// ```
313     #[stable]
314     pub fn reserve(&mut self, additional: uint) {
315         if self.cap - self.len < additional {
316             let err_msg = "Vec::reserve: `uint` overflow";
317             let new_cap = self.len.checked_add(additional).expect(err_msg)
318                 .checked_next_power_of_two().expect(err_msg);
319             self.grow_capacity(new_cap);
320         }
321     }
322
323     /// Reserves the minimum capacity for exactly `additional` more elements to
324     /// be inserted in the given `Vec<T>`. Does nothing if the capacity is already
325     /// sufficient.
326     ///
327     /// Note that the allocator may give the collection more space than it
328     /// requests. Therefore capacity can not be relied upon to be precisely
329     /// minimal. Prefer `reserve` if future insertions are expected.
330     ///
331     /// # Panics
332     ///
333     /// Panics if the new capacity overflows `uint`.
334     ///
335     /// # Examples
336     ///
337     /// ```
338     /// let mut vec: Vec<int> = vec![1];
339     /// vec.reserve_exact(10);
340     /// assert!(vec.capacity() >= 11);
341     /// ```
342     #[stable]
343     pub fn reserve_exact(&mut self, additional: uint) {
344         if self.cap - self.len < additional {
345             match self.len.checked_add(additional) {
346                 None => panic!("Vec::reserve: `uint` overflow"),
347                 Some(new_cap) => self.grow_capacity(new_cap)
348             }
349         }
350     }
351
352     /// Shrinks the capacity of the vector as much as possible.
353     ///
354     /// It will drop down as close as possible to the length but the allocator
355     /// may still inform the vector that there is space for a few more elements.
356     ///
357     /// # Examples
358     ///
359     /// ```
360     /// let mut vec: Vec<int> = Vec::with_capacity(10);
361     /// vec.push_all(&[1, 2, 3]);
362     /// assert_eq!(vec.capacity(), 10);
363     /// vec.shrink_to_fit();
364     /// assert!(vec.capacity() >= 3);
365     /// ```
366     #[stable]
367     pub fn shrink_to_fit(&mut self) {
368         if mem::size_of::<T>() == 0 { return }
369
370         if self.len == 0 {
371             if self.cap != 0 {
372                 unsafe {
373                     dealloc(*self.ptr, self.cap)
374                 }
375                 self.cap = 0;
376             }
377         } else {
378             unsafe {
379                 // Overflow check is unnecessary as the vector is already at
380                 // least this large.
381                 let ptr = reallocate(*self.ptr as *mut u8,
382                                      self.cap * mem::size_of::<T>(),
383                                      self.len * mem::size_of::<T>(),
384                                      mem::min_align_of::<T>()) as *mut T;
385                 if ptr.is_null() { ::alloc::oom() }
386                 self.ptr = NonZero::new(ptr);
387             }
388             self.cap = self.len;
389         }
390     }
391
392     /// Convert the vector into Box<[T]>.
393     ///
394     /// Note that this will drop any excess capacity. Calling this and
395     /// converting back to a vector with `into_vec()` is equivalent to calling
396     /// `shrink_to_fit()`.
397     #[experimental]
398     pub fn into_boxed_slice(mut self) -> Box<[T]> {
399         self.shrink_to_fit();
400         unsafe {
401             let xs: Box<[T]> = mem::transmute(self.as_mut_slice());
402             mem::forget(self);
403             xs
404         }
405     }
406
407     /// Shorten a vector, dropping excess elements.
408     ///
409     /// If `len` is greater than the vector's current length, this has no
410     /// effect.
411     ///
412     /// # Examples
413     ///
414     /// ```
415     /// let mut vec = vec![1i, 2, 3, 4];
416     /// vec.truncate(2);
417     /// assert_eq!(vec, vec![1, 2]);
418     /// ```
419     #[stable]
420     pub fn truncate(&mut self, len: uint) {
421         unsafe {
422             // drop any extra elements
423             while len < self.len {
424                 // decrement len before the read(), so a panic on Drop doesn't
425                 // re-drop the just-failed value.
426                 self.len -= 1;
427                 ptr::read(self.get_unchecked(self.len));
428             }
429         }
430     }
431
432     /// Returns a mutable slice of the elements of `self`.
433     ///
434     /// # Examples
435     ///
436     /// ```
437     /// fn foo(slice: &mut [int]) {}
438     ///
439     /// let mut vec = vec![1i, 2];
440     /// foo(vec.as_mut_slice());
441     /// ```
442     #[inline]
443     #[stable]
444     pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
445         unsafe {
446             mem::transmute(RawSlice {
447                 data: *self.ptr as *const T,
448                 len: self.len,
449             })
450         }
451     }
452
453     /// Creates a consuming iterator, that is, one that moves each value out of
454     /// the vector (from start to end). The vector cannot be used after calling
455     /// this.
456     ///
457     /// # Examples
458     ///
459     /// ```
460     /// let v = vec!["a".to_string(), "b".to_string()];
461     /// for s in v.into_iter() {
462     ///     // s has type String, not &String
463     ///     println!("{}", s);
464     /// }
465     /// ```
466     #[inline]
467     #[stable]
468     pub fn into_iter(self) -> IntoIter<T> {
469         unsafe {
470             let ptr = *self.ptr;
471             let cap = self.cap;
472             let begin = ptr as *const T;
473             let end = if mem::size_of::<T>() == 0 {
474                 (ptr as uint + self.len()) as *const T
475             } else {
476                 ptr.offset(self.len() as int) as *const T
477             };
478             mem::forget(self);
479             IntoIter { allocation: ptr, cap: cap, ptr: begin, end: end }
480         }
481     }
482
483     /// Sets the length of a vector.
484     ///
485     /// This will explicitly set the size of the vector, without actually
486     /// modifying its buffers, so it is up to the caller to ensure that the
487     /// vector is actually the specified size.
488     ///
489     /// # Examples
490     ///
491     /// ```
492     /// let mut v = vec![1u, 2, 3, 4];
493     /// unsafe {
494     ///     v.set_len(1);
495     /// }
496     /// ```
497     #[inline]
498     #[stable]
499     pub unsafe fn set_len(&mut self, len: uint) {
500         self.len = len;
501     }
502
503     /// Removes an element from anywhere in the vector and return it, replacing
504     /// it with the last element.
505     ///
506     /// This does not preserve ordering, but is O(1).
507     ///
508     /// # Panics
509     ///
510     /// Panics if `index` is out of bounds.
511     ///
512     /// # Examples
513     ///
514     /// ```
515     /// let mut v = vec!["foo", "bar", "baz", "qux"];
516     ///
517     /// assert_eq!(v.swap_remove(1), "bar");
518     /// assert_eq!(v, vec!["foo", "qux", "baz"]);
519     ///
520     /// assert_eq!(v.swap_remove(0), "foo");
521     /// assert_eq!(v, vec!["baz", "qux"]);
522     /// ```
523     #[inline]
524     #[stable]
525     pub fn swap_remove(&mut self, index: uint) -> T {
526         let length = self.len();
527         self.swap(index, length - 1);
528         self.pop().unwrap()
529     }
530
531     /// Inserts an element at position `index` within the vector, shifting all
532     /// elements after position `i` one position to the right.
533     ///
534     /// # Panics
535     ///
536     /// Panics if `index` is not between `0` and the vector's length (both
537     /// bounds inclusive).
538     ///
539     /// # Examples
540     ///
541     /// ```
542     /// let mut vec = vec![1i, 2, 3];
543     /// vec.insert(1, 4);
544     /// assert_eq!(vec, vec![1, 4, 2, 3]);
545     /// vec.insert(4, 5);
546     /// assert_eq!(vec, vec![1, 4, 2, 3, 5]);
547     /// ```
548     #[stable]
549     pub fn insert(&mut self, index: uint, element: T) {
550         let len = self.len();
551         assert!(index <= len);
552         // space for the new element
553         self.reserve(1);
554
555         unsafe { // infallible
556             // The spot to put the new value
557             {
558                 let p = self.as_mut_ptr().offset(index as int);
559                 // Shift everything over to make space. (Duplicating the
560                 // `index`th element into two consecutive places.)
561                 ptr::copy_memory(p.offset(1), &*p, len - index);
562                 // Write it in, overwriting the first copy of the `index`th
563                 // element.
564                 ptr::write(&mut *p, element);
565             }
566             self.set_len(len + 1);
567         }
568     }
569
570     /// Removes and returns the element at position `index` within the vector,
571     /// shifting all elements after position `index` one position to the left.
572     ///
573     /// # Panics
574     ///
575     /// Panics if `i` is out of bounds.
576     ///
577     /// # Examples
578     ///
579     /// ```
580     /// let mut v = vec![1i, 2, 3];
581     /// assert_eq!(v.remove(1), 2);
582     /// assert_eq!(v, vec![1, 3]);
583     /// ```
584     #[stable]
585     pub fn remove(&mut self, index: uint) -> T {
586         let len = self.len();
587         assert!(index < len);
588         unsafe { // infallible
589             let ret;
590             {
591                 // the place we are taking from.
592                 let ptr = self.as_mut_ptr().offset(index as int);
593                 // copy it out, unsafely having a copy of the value on
594                 // the stack and in the vector at the same time.
595                 ret = ptr::read(ptr as *const T);
596
597                 // Shift everything down to fill in that spot.
598                 ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
599             }
600             self.set_len(len - 1);
601             ret
602         }
603     }
604
605     /// Retains only the elements specified by the predicate.
606     ///
607     /// In other words, remove all elements `e` such that `f(&e)` returns false.
608     /// This method operates in place and preserves the order of the retained
609     /// elements.
610     ///
611     /// # Examples
612     ///
613     /// ```
614     /// let mut vec = vec![1i, 2, 3, 4];
615     /// vec.retain(|&x| x%2 == 0);
616     /// assert_eq!(vec, vec![2, 4]);
617     /// ```
618     #[stable]
619     pub fn retain<F>(&mut self, mut f: F) where F: FnMut(&T) -> bool {
620         let len = self.len();
621         let mut del = 0u;
622         {
623             let v = self.as_mut_slice();
624
625             for i in range(0u, len) {
626                 if !f(&v[i]) {
627                     del += 1;
628                 } else if del > 0 {
629                     v.swap(i-del, i);
630                 }
631             }
632         }
633         if del > 0 {
634             self.truncate(len - del);
635         }
636     }
637
638     /// Deprecated: use `extend(range(0, n).map(f))` instead.
639     #[deprecated = "use extend(range(0, n).map(f)) instead"]
640     pub fn grow_fn<F>(&mut self, n: uint, f: F) where F: FnMut(uint) -> T {
641         self.extend(range(0, n).map(f));
642     }
643
644     /// Appends an element to the back of a collection.
645     ///
646     /// # Panics
647     ///
648     /// Panics if the number of elements in the vector overflows a `uint`.
649     ///
650     /// # Examples
651     ///
652     /// ```rust
653     /// let mut vec = vec!(1i, 2);
654     /// vec.push(3);
655     /// assert_eq!(vec, vec!(1, 2, 3));
656     /// ```
657     #[inline]
658     #[stable]
659     pub fn push(&mut self, value: T) {
660         if mem::size_of::<T>() == 0 {
661             // zero-size types consume no memory, so we can't rely on the
662             // address space running out
663             self.len = self.len.checked_add(1).expect("length overflow");
664             unsafe { mem::forget(value); }
665             return
666         }
667         if self.len == self.cap {
668             let old_size = self.cap * mem::size_of::<T>();
669             let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
670             if old_size > size { panic!("capacity overflow") }
671             unsafe {
672                 let ptr = alloc_or_realloc(*self.ptr, old_size, size);
673                 if ptr.is_null() { ::alloc::oom() }
674                 self.ptr = NonZero::new(ptr);
675             }
676             self.cap = max(self.cap, 2) * 2;
677         }
678
679         unsafe {
680             let end = (*self.ptr).offset(self.len as int);
681             ptr::write(&mut *end, value);
682             self.len += 1;
683         }
684     }
685
686     /// Removes the last element from a vector and returns it, or `None` if it is empty.
687     ///
688     /// # Examples
689     ///
690     /// ```rust
691     /// let mut vec = vec![1i, 2, 3];
692     /// assert_eq!(vec.pop(), Some(3));
693     /// assert_eq!(vec, vec![1, 2]);
694     /// ```
695     #[inline]
696     #[stable]
697     pub fn pop(&mut self) -> Option<T> {
698         if self.len == 0 {
699             None
700         } else {
701             unsafe {
702                 self.len -= 1;
703                 Some(ptr::read(self.get_unchecked(self.len())))
704             }
705         }
706     }
707
708     /// Creates a draining iterator that clears the `Vec` and iterates over
709     /// the removed items from start to end.
710     ///
711     /// # Examples
712     ///
713     /// ```
714     /// let mut v = vec!["a".to_string(), "b".to_string()];
715     /// for s in v.drain() {
716     ///     // s has type String, not &String
717     ///     println!("{}", s);
718     /// }
719     /// assert!(v.is_empty());
720     /// ```
721     #[inline]
722     #[unstable = "matches collection reform specification, waiting for dust to settle"]
723     pub fn drain<'a>(&'a mut self) -> Drain<'a, T> {
724         unsafe {
725             let begin = *self.ptr as *const T;
726             let end = if mem::size_of::<T>() == 0 {
727                 (*self.ptr as uint + self.len()) as *const T
728             } else {
729                 (*self.ptr).offset(self.len() as int) as *const T
730             };
731             self.set_len(0);
732             Drain {
733                 ptr: begin,
734                 end: end,
735                 marker: ContravariantLifetime,
736             }
737         }
738     }
739
740     /// Clears the vector, removing all values.
741     ///
742     /// # Examples
743     ///
744     /// ```
745     /// let mut v = vec![1i, 2, 3];
746     ///
747     /// v.clear();
748     ///
749     /// assert!(v.is_empty());
750     /// ```
751     #[inline]
752     #[stable]
753     pub fn clear(&mut self) {
754         self.truncate(0)
755     }
756
757     /// Returns the number of elements in the vector.
758     ///
759     /// # Examples
760     ///
761     /// ```
762     /// let a = vec![1i, 2, 3];
763     /// assert_eq!(a.len(), 3);
764     /// ```
765     #[inline]
766     #[stable]
767     pub fn len(&self) -> uint { self.len }
768
769     /// Returns `true` if the vector contains no elements.
770     ///
771     /// # Examples
772     ///
773     /// ```
774     /// let mut v = Vec::new();
775     /// assert!(v.is_empty());
776     ///
777     /// v.push(1i);
778     /// assert!(!v.is_empty());
779     /// ```
780     #[stable]
781     pub fn is_empty(&self) -> bool { self.len() == 0 }
782
783     /// Converts a `Vec<T>` to a `Vec<U>` where `T` and `U` have the same
784     /// size and in case they are not zero-sized the same minimal alignment.
785     ///
786     /// # Panics
787     ///
788     /// Panics if `T` and `U` have differing sizes or are not zero-sized and
789     /// have differing minimal alignments.
790     ///
791     /// # Examples
792     ///
793     /// ```
794     /// let v = vec![0u, 1, 2];
795     /// let w = v.map_in_place(|i| i + 3);
796     /// assert_eq!(w.as_slice(), [3, 4, 5].as_slice());
797     ///
798     /// #[deriving(PartialEq, Show)]
799     /// struct Newtype(u8);
800     /// let bytes = vec![0x11, 0x22];
801     /// let newtyped_bytes = bytes.map_in_place(|x| Newtype(x));
802     /// assert_eq!(newtyped_bytes.as_slice(), [Newtype(0x11), Newtype(0x22)].as_slice());
803     /// ```
804     #[experimental = "API may change to provide stronger guarantees"]
805     pub fn map_in_place<U, F>(self, mut f: F) -> Vec<U> where F: FnMut(T) -> U {
806         // FIXME: Assert statically that the types `T` and `U` have the same
807         // size.
808         assert!(mem::size_of::<T>() == mem::size_of::<U>());
809
810         let mut vec = self;
811
812         if mem::size_of::<T>() != 0 {
813             // FIXME: Assert statically that the types `T` and `U` have the
814             // same minimal alignment in case they are not zero-sized.
815
816             // These asserts are necessary because the `min_align_of` of the
817             // types are passed to the allocator by `Vec`.
818             assert!(mem::min_align_of::<T>() == mem::min_align_of::<U>());
819
820             // This `as int` cast is safe, because the size of the elements of the
821             // vector is not 0, and:
822             //
823             // 1) If the size of the elements in the vector is 1, the `int` may
824             //    overflow, but it has the correct bit pattern so that the
825             //    `.offset()` function will work.
826             //
827             //    Example:
828             //        Address space 0x0-0xF.
829             //        `u8` array at: 0x1.
830             //        Size of `u8` array: 0x8.
831             //        Calculated `offset`: -0x8.
832             //        After `array.offset(offset)`: 0x9.
833             //        (0x1 + 0x8 = 0x1 - 0x8)
834             //
835             // 2) If the size of the elements in the vector is >1, the `uint` ->
836             //    `int` conversion can't overflow.
837             let offset = vec.len() as int;
838             let start = vec.as_mut_ptr();
839
840             let mut pv = PartialVecNonZeroSized {
841                 vec: vec,
842
843                 start_t: start,
844                 // This points inside the vector, as the vector has length
845                 // `offset`.
846                 end_t: unsafe { start.offset(offset) },
847                 start_u: start as *mut U,
848                 end_u: start as *mut U,
849             };
850             //  start_t
851             //  start_u
852             //  |
853             // +-+-+-+-+-+-+
854             // |T|T|T|...|T|
855             // +-+-+-+-+-+-+
856             //  |           |
857             //  end_u       end_t
858
859             while pv.end_u as *mut T != pv.end_t {
860                 unsafe {
861                     //  start_u start_t
862                     //  |       |
863                     // +-+-+-+-+-+-+-+-+-+
864                     // |U|...|U|T|T|...|T|
865                     // +-+-+-+-+-+-+-+-+-+
866                     //          |         |
867                     //          end_u     end_t
868
869                     let t = ptr::read(pv.start_t as *const T);
870                     //  start_u start_t
871                     //  |       |
872                     // +-+-+-+-+-+-+-+-+-+
873                     // |U|...|U|X|T|...|T|
874                     // +-+-+-+-+-+-+-+-+-+
875                     //          |         |
876                     //          end_u     end_t
877                     // We must not panic here, one cell is marked as `T`
878                     // although it is not `T`.
879
880                     pv.start_t = pv.start_t.offset(1);
881                     //  start_u   start_t
882                     //  |         |
883                     // +-+-+-+-+-+-+-+-+-+
884                     // |U|...|U|X|T|...|T|
885                     // +-+-+-+-+-+-+-+-+-+
886                     //          |         |
887                     //          end_u     end_t
888                     // We may panic again.
889
890                     // The function given by the user might panic.
891                     let u = f(t);
892
893                     ptr::write(pv.end_u, u);
894                     //  start_u   start_t
895                     //  |         |
896                     // +-+-+-+-+-+-+-+-+-+
897                     // |U|...|U|U|T|...|T|
898                     // +-+-+-+-+-+-+-+-+-+
899                     //          |         |
900                     //          end_u     end_t
901                     // We should not panic here, because that would leak the `U`
902                     // pointed to by `end_u`.
903
904                     pv.end_u = pv.end_u.offset(1);
905                     //  start_u   start_t
906                     //  |         |
907                     // +-+-+-+-+-+-+-+-+-+
908                     // |U|...|U|U|T|...|T|
909                     // +-+-+-+-+-+-+-+-+-+
910                     //            |       |
911                     //            end_u   end_t
912                     // We may panic again.
913                 }
914             }
915
916             //  start_u     start_t
917             //  |           |
918             // +-+-+-+-+-+-+
919             // |U|...|U|U|U|
920             // +-+-+-+-+-+-+
921             //              |
922             //              end_t
923             //              end_u
924             // Extract `vec` and prevent the destructor of
925             // `PartialVecNonZeroSized` from running. Note that none of the
926             // function calls can panic, thus no resources can be leaked (as the
927             // `vec` member of `PartialVec` is the only one which holds
928             // allocations -- and it is returned from this function. None of
929             // this can panic.
930             unsafe {
931                 let vec_len = pv.vec.len();
932                 let vec_cap = pv.vec.capacity();
933                 let vec_ptr = pv.vec.as_mut_ptr() as *mut U;
934                 mem::forget(pv);
935                 Vec::from_raw_parts(vec_ptr, vec_len, vec_cap)
936             }
937         } else {
938             // Put the `Vec` into the `PartialVecZeroSized` structure and
939             // prevent the destructor of the `Vec` from running. Since the
940             // `Vec` contained zero-sized objects, it did not allocate, so we
941             // are not leaking memory here.
942             let mut pv = PartialVecZeroSized::<T,U> {
943                 num_t: vec.len(),
944                 num_u: 0,
945                 marker_t: InvariantType,
946                 marker_u: InvariantType,
947             };
948             unsafe { mem::forget(vec); }
949
950             while pv.num_t != 0 {
951                 unsafe {
952                     // Create a `T` out of thin air and decrement `num_t`. This
953                     // must not panic between these steps, as otherwise a
954                     // destructor of `T` which doesn't exist runs.
955                     let t = mem::uninitialized();
956                     pv.num_t -= 1;
957
958                     // The function given by the user might panic.
959                     let u = f(t);
960
961                     // Forget the `U` and increment `num_u`. This increment
962                     // cannot overflow the `uint` as we only do this for a
963                     // number of times that fits into a `uint` (and start with
964                     // `0`). Again, we should not panic between these steps.
965                     mem::forget(u);
966                     pv.num_u += 1;
967                 }
968             }
969             // Create a `Vec` from our `PartialVecZeroSized` and make sure the
970             // destructor of the latter will not run. None of this can panic.
971             let mut result = Vec::new();
972             unsafe {
973                 result.set_len(pv.num_u);
974                 mem::forget(pv);
975             }
976             result
977         }
978     }
979 }
980
981 impl<T: Clone> Vec<T> {
982     /// Deprecated: use `repeat(value).take(length).collect()` instead.
983     #[inline]
984     #[deprecated = "use repeat(value).take(length).collect() instead"]
985     pub fn from_elem(length: uint, value: T) -> Vec<T> {
986         repeat(value).take(length).collect()
987     }
988
989     /// Resizes the `Vec` in-place so that `len()` is equal to `new_len`.
990     ///
991     /// Calls either `extend()` or `truncate()` depending on whether `new_len`
992     /// is larger than the current value of `len()` or not.
993     ///
994     /// # Examples
995     ///
996     /// ```
997     /// let mut vec = vec!["hello"];
998     /// vec.resize(3, "world");
999     /// assert_eq!(vec, vec!["hello", "world", "world"]);
1000     ///
1001     /// let mut vec = vec![1i, 2, 3, 4];
1002     /// vec.resize(2, 0);
1003     /// assert_eq!(vec, vec![1, 2]);
1004     /// ```
1005     #[unstable = "matches collection reform specification; waiting for dust to settle"]
1006     pub fn resize(&mut self, new_len: uint, value: T) {
1007         let len = self.len();
1008
1009         if new_len > len {
1010             self.extend(repeat(value).take(new_len - len));
1011         } else {
1012             self.truncate(new_len);
1013         }
1014     }
1015
1016     /// Appends all elements in a slice to the `Vec`.
1017     ///
1018     /// Iterates over the slice `other`, clones each element, and then appends
1019     /// it to this `Vec`. The `other` vector is traversed in-order.
1020     ///
1021     /// # Examples
1022     ///
1023     /// ```
1024     /// let mut vec = vec![1i];
1025     /// vec.push_all(&[2i, 3, 4]);
1026     /// assert_eq!(vec, vec![1, 2, 3, 4]);
1027     /// ```
1028     #[inline]
1029     #[experimental = "likely to be replaced by a more optimized extend"]
1030     pub fn push_all(&mut self, other: &[T]) {
1031         self.reserve(other.len());
1032
1033         for i in range(0, other.len()) {
1034             let len = self.len();
1035
1036             // Unsafe code so this can be optimised to a memcpy (or something similarly
1037             // fast) when T is Copy. LLVM is easily confused, so any extra operations
1038             // during the loop can prevent this optimisation.
1039             unsafe {
1040                 ptr::write(
1041                     self.get_unchecked_mut(len),
1042                     other.get_unchecked(i).clone());
1043                 self.set_len(len + 1);
1044             }
1045         }
1046     }
1047
1048     /// Deprecated: use `extend(repeat(value).take(n))` instead
1049     #[deprecated = "use extend(repeat(value).take(n)) instead"]
1050     pub fn grow(&mut self, n: uint, value: T) {
1051         self.extend(repeat(value).take(n))
1052     }
1053
1054     /// Deprecated: use `iter().cloned().partition(f)` instead.
1055     #[deprecated = "use iter().cloned().partition(f) instead"]
1056     pub fn partitioned<F>(&self, f: F) -> (Vec<T>, Vec<T>) where F: FnMut(&T) -> bool {
1057         self.iter().cloned().partition(f)
1058     }
1059 }
1060
1061 impl<T: PartialEq> Vec<T> {
1062     /// Removes consecutive repeated elements in the vector.
1063     ///
1064     /// If the vector is sorted, this removes all duplicates.
1065     ///
1066     /// # Examples
1067     ///
1068     /// ```
1069     /// let mut vec = vec![1i, 2, 2, 3, 2];
1070     ///
1071     /// vec.dedup();
1072     ///
1073     /// assert_eq!(vec, vec![1i, 2, 3, 2]);
1074     /// ```
1075     #[stable]
1076     pub fn dedup(&mut self) {
1077         unsafe {
1078             // Although we have a mutable reference to `self`, we cannot make
1079             // *arbitrary* changes. The `PartialEq` comparisons could panic, so we
1080             // must ensure that the vector is in a valid state at all time.
1081             //
1082             // The way that we handle this is by using swaps; we iterate
1083             // over all the elements, swapping as we go so that at the end
1084             // the elements we wish to keep are in the front, and those we
1085             // wish to reject are at the back. We can then truncate the
1086             // vector. This operation is still O(n).
1087             //
1088             // Example: We start in this state, where `r` represents "next
1089             // read" and `w` represents "next_write`.
1090             //
1091             //           r
1092             //     +---+---+---+---+---+---+
1093             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1094             //     +---+---+---+---+---+---+
1095             //           w
1096             //
1097             // Comparing self[r] against self[w-1], this is not a duplicate, so
1098             // we swap self[r] and self[w] (no effect as r==w) and then increment both
1099             // r and w, leaving us with:
1100             //
1101             //               r
1102             //     +---+---+---+---+---+---+
1103             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1104             //     +---+---+---+---+---+---+
1105             //               w
1106             //
1107             // Comparing self[r] against self[w-1], this value is a duplicate,
1108             // so we increment `r` but leave everything else unchanged:
1109             //
1110             //                   r
1111             //     +---+---+---+---+---+---+
1112             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1113             //     +---+---+---+---+---+---+
1114             //               w
1115             //
1116             // Comparing self[r] against self[w-1], this is not a duplicate,
1117             // so swap self[r] and self[w] and advance r and w:
1118             //
1119             //                       r
1120             //     +---+---+---+---+---+---+
1121             //     | 0 | 1 | 2 | 1 | 3 | 3 |
1122             //     +---+---+---+---+---+---+
1123             //                   w
1124             //
1125             // Not a duplicate, repeat:
1126             //
1127             //                           r
1128             //     +---+---+---+---+---+---+
1129             //     | 0 | 1 | 2 | 3 | 1 | 3 |
1130             //     +---+---+---+---+---+---+
1131             //                       w
1132             //
1133             // Duplicate, advance r. End of vec. Truncate to w.
1134
1135             let ln = self.len();
1136             if ln < 1 { return; }
1137
1138             // Avoid bounds checks by using unsafe pointers.
1139             let p = self.as_mut_ptr();
1140             let mut r = 1;
1141             let mut w = 1;
1142
1143             while r < ln {
1144                 let p_r = p.offset(r as int);
1145                 let p_wm1 = p.offset((w - 1) as int);
1146                 if *p_r != *p_wm1 {
1147                     if r != w {
1148                         let p_w = p_wm1.offset(1);
1149                         mem::swap(&mut *p_r, &mut *p_w);
1150                     }
1151                     w += 1;
1152                 }
1153                 r += 1;
1154             }
1155
1156             self.truncate(w);
1157         }
1158     }
1159 }
1160
1161 ////////////////////////////////////////////////////////////////////////////////
1162 // Public free fns
1163 ////////////////////////////////////////////////////////////////////////////////
1164
1165 /// Deprecated: use `unzip` directly on the iterator instead.
1166 #[deprecated = "use unzip directly on the iterator instead"]
1167 pub fn unzip<T, U, V: Iterator<Item=(T, U)>>(iter: V) -> (Vec<T>, Vec<U>) {
1168     iter.unzip()
1169 }
1170
1171 ////////////////////////////////////////////////////////////////////////////////
1172 // Internal methods and functions
1173 ////////////////////////////////////////////////////////////////////////////////
1174
1175 impl<T> Vec<T> {
1176     /// Reserves capacity for exactly `capacity` elements in the given vector.
1177     ///
1178     /// If the capacity for `self` is already equal to or greater than the
1179     /// requested capacity, then no action is taken.
1180     fn grow_capacity(&mut self, capacity: uint) {
1181         if mem::size_of::<T>() == 0 { return }
1182
1183         if capacity > self.cap {
1184             let size = capacity.checked_mul(mem::size_of::<T>())
1185                                .expect("capacity overflow");
1186             unsafe {
1187                 let ptr = alloc_or_realloc(*self.ptr, self.cap * mem::size_of::<T>(), size);
1188                 if ptr.is_null() { ::alloc::oom() }
1189                 self.ptr = NonZero::new(ptr);
1190             }
1191             self.cap = capacity;
1192         }
1193     }
1194 }
1195
1196 // FIXME: #13996: need a way to mark the return value as `noalias`
1197 #[inline(never)]
1198 unsafe fn alloc_or_realloc<T>(ptr: *mut T, old_size: uint, size: uint) -> *mut T {
1199     if old_size == 0 {
1200         allocate(size, mem::min_align_of::<T>()) as *mut T
1201     } else {
1202         reallocate(ptr as *mut u8, old_size, size, mem::min_align_of::<T>()) as *mut T
1203     }
1204 }
1205
1206 #[inline]
1207 unsafe fn dealloc<T>(ptr: *mut T, len: uint) {
1208     if mem::size_of::<T>() != 0 {
1209         deallocate(ptr as *mut u8,
1210                    len * mem::size_of::<T>(),
1211                    mem::min_align_of::<T>())
1212     }
1213 }
1214
1215 ////////////////////////////////////////////////////////////////////////////////
1216 // Common trait implementations for Vec
1217 ////////////////////////////////////////////////////////////////////////////////
1218
1219 #[unstable]
1220 impl<T:Clone> Clone for Vec<T> {
1221     fn clone(&self) -> Vec<T> { ::slice::SliceExt::to_vec(self.as_slice()) }
1222
1223     fn clone_from(&mut self, other: &Vec<T>) {
1224         // drop anything in self that will not be overwritten
1225         if self.len() > other.len() {
1226             self.truncate(other.len())
1227         }
1228
1229         // reuse the contained values' allocations/resources.
1230         for (place, thing) in self.iter_mut().zip(other.iter()) {
1231             place.clone_from(thing)
1232         }
1233
1234         // self.len <= other.len due to the truncate above, so the
1235         // slice here is always in-bounds.
1236         let slice = other[self.len()..];
1237         self.push_all(slice);
1238     }
1239 }
1240
1241 impl<S: hash::Writer, T: Hash<S>> Hash<S> for Vec<T> {
1242     #[inline]
1243     fn hash(&self, state: &mut S) {
1244         self.as_slice().hash(state);
1245     }
1246 }
1247
1248 // NOTE(stage0): remove impl after a snapshot
1249 #[cfg(stage0)]
1250 #[experimental = "waiting on Index stability"]
1251 impl<T> Index<uint,T> for Vec<T> {
1252     #[inline]
1253     fn index<'a>(&'a self, index: &uint) -> &'a T {
1254         &self.as_slice()[*index]
1255     }
1256 }
1257
1258 #[cfg(not(stage0))]  // NOTE(stage0): remove cfg after a snapshot
1259 #[experimental = "waiting on Index stability"]
1260 impl<T> Index<uint> for Vec<T> {
1261     type Output = T;
1262
1263     #[inline]
1264     fn index<'a>(&'a self, index: &uint) -> &'a T {
1265         &self.as_slice()[*index]
1266     }
1267 }
1268
1269 // NOTE(stage0): remove impl after a snapshot
1270 #[cfg(stage0)]
1271 impl<T> IndexMut<uint,T> for Vec<T> {
1272     #[inline]
1273     fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
1274         &mut self.as_mut_slice()[*index]
1275     }
1276 }
1277
1278 #[cfg(not(stage0))]  // NOTE(stage0): remove cfg after a snapshot
1279 impl<T> IndexMut<uint> for Vec<T> {
1280     type Output = T;
1281
1282     #[inline]
1283     fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
1284         &mut self.as_mut_slice()[*index]
1285     }
1286 }
1287
1288 impl<T> ops::Slice<uint, [T]> for Vec<T> {
1289     #[inline]
1290     fn as_slice_<'a>(&'a self) -> &'a [T] {
1291         self.as_slice()
1292     }
1293
1294     #[inline]
1295     fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [T] {
1296         self.as_slice().slice_from_or_fail(start)
1297     }
1298
1299     #[inline]
1300     fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [T] {
1301         self.as_slice().slice_to_or_fail(end)
1302     }
1303     #[inline]
1304     fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] {
1305         self.as_slice().slice_or_fail(start, end)
1306     }
1307 }
1308
1309 impl<T> ops::SliceMut<uint, [T]> for Vec<T> {
1310     #[inline]
1311     fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
1312         self.as_mut_slice()
1313     }
1314
1315     #[inline]
1316     fn slice_from_or_fail_mut<'a>(&'a mut self, start: &uint) -> &'a mut [T] {
1317         self.as_mut_slice().slice_from_or_fail_mut(start)
1318     }
1319
1320     #[inline]
1321     fn slice_to_or_fail_mut<'a>(&'a mut self, end: &uint) -> &'a mut [T] {
1322         self.as_mut_slice().slice_to_or_fail_mut(end)
1323     }
1324     #[inline]
1325     fn slice_or_fail_mut<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] {
1326         self.as_mut_slice().slice_or_fail_mut(start, end)
1327     }
1328 }
1329
1330 #[experimental = "waiting on Deref stability"]
1331 impl<T> ops::Deref for Vec<T> {
1332     type Target = [T];
1333
1334     fn deref<'a>(&'a self) -> &'a [T] { self.as_slice() }
1335 }
1336
1337 #[experimental = "waiting on DerefMut stability"]
1338 impl<T> ops::DerefMut for Vec<T> {
1339     fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.as_mut_slice() }
1340 }
1341
1342 #[experimental = "waiting on FromIterator stability"]
1343 impl<T> FromIterator<T> for Vec<T> {
1344     #[inline]
1345     fn from_iter<I:Iterator<Item=T>>(mut iterator: I) -> Vec<T> {
1346         let (lower, _) = iterator.size_hint();
1347         let mut vector = Vec::with_capacity(lower);
1348         for element in iterator {
1349             vector.push(element)
1350         }
1351         vector
1352     }
1353 }
1354
1355 #[experimental = "waiting on Extend stability"]
1356 impl<T> Extend<T> for Vec<T> {
1357     #[inline]
1358     fn extend<I: Iterator<Item=T>>(&mut self, mut iterator: I) {
1359         let (lower, _) = iterator.size_hint();
1360         self.reserve(lower);
1361         for element in iterator {
1362             self.push(element)
1363         }
1364     }
1365 }
1366
1367 impl<A, B> PartialEq<Vec<B>> for Vec<A> where A: PartialEq<B> {
1368     #[inline]
1369     fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1370     #[inline]
1371     fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1372 }
1373
1374 macro_rules! impl_eq {
1375     ($lhs:ty, $rhs:ty) => {
1376         impl<'b, A, B> PartialEq<$rhs> for $lhs where A: PartialEq<B> {
1377             #[inline]
1378             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1379             #[inline]
1380             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1381         }
1382
1383         impl<'b, A, B> PartialEq<$lhs> for $rhs where B: PartialEq<A> {
1384             #[inline]
1385             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
1386             #[inline]
1387             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
1388         }
1389     }
1390 }
1391
1392 impl_eq! { Vec<A>, &'b [B] }
1393 impl_eq! { Vec<A>, &'b mut [B] }
1394
1395 impl<'a, A, B> PartialEq<Vec<B>> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1396     #[inline]
1397     fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1398     #[inline]
1399     fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1400 }
1401
1402 impl<'a, A, B> PartialEq<CowVec<'a, A>> for Vec<B> where A: Clone, B: PartialEq<A> {
1403     #[inline]
1404     fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1405     #[inline]
1406     fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1407 }
1408
1409 macro_rules! impl_eq_for_cowvec {
1410     ($rhs:ty) => {
1411         impl<'a, 'b, A, B> PartialEq<$rhs> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1412             #[inline]
1413             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1414             #[inline]
1415             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1416         }
1417
1418         impl<'a, 'b, A, B> PartialEq<CowVec<'a, A>> for $rhs where A: Clone, B: PartialEq<A> {
1419             #[inline]
1420             fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1421             #[inline]
1422             fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1423         }
1424     }
1425 }
1426
1427 impl_eq_for_cowvec! { &'b [B] }
1428 impl_eq_for_cowvec! { &'b mut [B] }
1429
1430 #[unstable = "waiting on PartialOrd stability"]
1431 impl<T: PartialOrd> PartialOrd for Vec<T> {
1432     #[inline]
1433     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1434         self.as_slice().partial_cmp(other.as_slice())
1435     }
1436 }
1437
1438 #[unstable = "waiting on Eq stability"]
1439 impl<T: Eq> Eq for Vec<T> {}
1440
1441 #[allow(deprecated)]
1442 #[deprecated = "Use overloaded `core::cmp::PartialEq`"]
1443 impl<T: PartialEq, Sized? V: AsSlice<T>> Equiv<V> for Vec<T> {
1444     #[inline]
1445     fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
1446 }
1447
1448 #[unstable = "waiting on Ord stability"]
1449 impl<T: Ord> Ord for Vec<T> {
1450     #[inline]
1451     fn cmp(&self, other: &Vec<T>) -> Ordering {
1452         self.as_slice().cmp(other.as_slice())
1453     }
1454 }
1455
1456 impl<T> AsSlice<T> for Vec<T> {
1457     /// Returns a slice into `self`.
1458     ///
1459     /// # Examples
1460     ///
1461     /// ```
1462     /// fn foo(slice: &[int]) {}
1463     ///
1464     /// let vec = vec![1i, 2];
1465     /// foo(vec.as_slice());
1466     /// ```
1467     #[inline]
1468     #[stable]
1469     fn as_slice<'a>(&'a self) -> &'a [T] {
1470         unsafe {
1471             mem::transmute(RawSlice {
1472                 data: *self.ptr as *const T,
1473                 len: self.len
1474             })
1475         }
1476     }
1477 }
1478
1479 impl<'a, T: Clone> Add<&'a [T]> for Vec<T> {
1480     type Output = Vec<T>;
1481
1482     #[inline]
1483     fn add(mut self, rhs: &[T]) -> Vec<T> {
1484         self.push_all(rhs);
1485         self
1486     }
1487 }
1488
1489 #[unsafe_destructor]
1490 impl<T> Drop for Vec<T> {
1491     fn drop(&mut self) {
1492         // This is (and should always remain) a no-op if the fields are
1493         // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1494         if self.cap != 0 {
1495             unsafe {
1496                 for x in self.iter() {
1497                     ptr::read(x);
1498                 }
1499                 dealloc(*self.ptr, self.cap)
1500             }
1501         }
1502     }
1503 }
1504
1505 #[stable]
1506 impl<T> Default for Vec<T> {
1507     #[stable]
1508     fn default() -> Vec<T> {
1509         Vec::new()
1510     }
1511 }
1512
1513 #[experimental = "waiting on Show stability"]
1514 impl<T:fmt::Show> fmt::Show for Vec<T> {
1515     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1516         self.as_slice().fmt(f)
1517     }
1518 }
1519
1520 impl<'a> fmt::Writer for Vec<u8> {
1521     fn write_str(&mut self, s: &str) -> fmt::Result {
1522         self.push_all(s.as_bytes());
1523         Ok(())
1524     }
1525 }
1526
1527 ////////////////////////////////////////////////////////////////////////////////
1528 // Clone-on-write
1529 ////////////////////////////////////////////////////////////////////////////////
1530
1531 #[experimental = "unclear how valuable this alias is"]
1532 /// A clone-on-write vector
1533 pub type CowVec<'a, T> = Cow<'a, Vec<T>, [T]>;
1534
1535 impl<'a, T> FromIterator<T> for CowVec<'a, T> where T: Clone {
1536     fn from_iter<I: Iterator<Item=T>>(it: I) -> CowVec<'a, T> {
1537         Cow::Owned(FromIterator::from_iter(it))
1538     }
1539 }
1540
1541 impl<'a, T: 'a> IntoCow<'a, Vec<T>, [T]> for Vec<T> where T: Clone {
1542     fn into_cow(self) -> CowVec<'a, T> {
1543         Cow::Owned(self)
1544     }
1545 }
1546
1547 impl<'a, T> IntoCow<'a, Vec<T>, [T]> for &'a [T] where T: Clone {
1548     fn into_cow(self) -> CowVec<'a, T> {
1549         Cow::Borrowed(self)
1550     }
1551 }
1552
1553 ////////////////////////////////////////////////////////////////////////////////
1554 // Iterators
1555 ////////////////////////////////////////////////////////////////////////////////
1556
1557 /// An iterator that moves out of a vector.
1558 #[stable]
1559 pub struct IntoIter<T> {
1560     allocation: *mut T, // the block of memory allocated for the vector
1561     cap: uint, // the capacity of the vector
1562     ptr: *const T,
1563     end: *const T
1564 }
1565
1566 #[deprecated = "use IntoIter instead"]
1567 pub type MoveItems<T> = IntoIter<T>;
1568
1569 impl<T> IntoIter<T> {
1570     #[inline]
1571     /// Drops all items that have not yet been moved and returns the empty vector.
1572     #[unstable]
1573     pub fn into_inner(mut self) -> Vec<T> {
1574         unsafe {
1575             for _x in self { }
1576             let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
1577             mem::forget(self);
1578             Vec { ptr: NonZero::new(allocation), cap: cap, len: 0 }
1579         }
1580     }
1581
1582     /// Deprecated, use .into_inner() instead
1583     #[deprecated = "use .into_inner() instead"]
1584     pub fn unwrap(self) -> Vec<T> { self.into_inner() }
1585 }
1586
1587 impl<T> Iterator for IntoIter<T> {
1588     type Item = T;
1589
1590     #[inline]
1591     fn next<'a>(&'a mut self) -> Option<T> {
1592         unsafe {
1593             if self.ptr == self.end {
1594                 None
1595             } else {
1596                 if mem::size_of::<T>() == 0 {
1597                     // purposefully don't use 'ptr.offset' because for
1598                     // vectors with 0-size elements this would return the
1599                     // same pointer.
1600                     self.ptr = mem::transmute(self.ptr as uint + 1);
1601
1602                     // Use a non-null pointer value
1603                     Some(ptr::read(mem::transmute(1u)))
1604                 } else {
1605                     let old = self.ptr;
1606                     self.ptr = self.ptr.offset(1);
1607
1608                     Some(ptr::read(old))
1609                 }
1610             }
1611         }
1612     }
1613
1614     #[inline]
1615     fn size_hint(&self) -> (uint, Option<uint>) {
1616         let diff = (self.end as uint) - (self.ptr as uint);
1617         let size = mem::size_of::<T>();
1618         let exact = diff / (if size == 0 {1} else {size});
1619         (exact, Some(exact))
1620     }
1621 }
1622
1623 impl<T> DoubleEndedIterator for IntoIter<T> {
1624     #[inline]
1625     fn next_back<'a>(&'a mut self) -> Option<T> {
1626         unsafe {
1627             if self.end == self.ptr {
1628                 None
1629             } else {
1630                 if mem::size_of::<T>() == 0 {
1631                     // See above for why 'ptr.offset' isn't used
1632                     self.end = mem::transmute(self.end as uint - 1);
1633
1634                     // Use a non-null pointer value
1635                     Some(ptr::read(mem::transmute(1u)))
1636                 } else {
1637                     self.end = self.end.offset(-1);
1638
1639                     Some(ptr::read(mem::transmute(self.end)))
1640                 }
1641             }
1642         }
1643     }
1644 }
1645
1646 impl<T> ExactSizeIterator for IntoIter<T> {}
1647
1648 #[unsafe_destructor]
1649 impl<T> Drop for IntoIter<T> {
1650     fn drop(&mut self) {
1651         // destroy the remaining elements
1652         if self.cap != 0 {
1653             for _x in *self {}
1654             unsafe {
1655                 dealloc(self.allocation, self.cap);
1656             }
1657         }
1658     }
1659 }
1660
1661 /// An iterator that drains a vector.
1662 #[unsafe_no_drop_flag]
1663 #[unstable = "recently added as part of collections reform 2"]
1664 pub struct Drain<'a, T> {
1665     ptr: *const T,
1666     end: *const T,
1667     marker: ContravariantLifetime<'a>,
1668 }
1669
1670 impl<'a, T> Iterator for Drain<'a, T> {
1671     type Item = T;
1672
1673     #[inline]
1674     fn next(&mut self) -> Option<T> {
1675         unsafe {
1676             if self.ptr == self.end {
1677                 None
1678             } else {
1679                 if mem::size_of::<T>() == 0 {
1680                     // purposefully don't use 'ptr.offset' because for
1681                     // vectors with 0-size elements this would return the
1682                     // same pointer.
1683                     self.ptr = mem::transmute(self.ptr as uint + 1);
1684
1685                     // Use a non-null pointer value
1686                     Some(ptr::read(mem::transmute(1u)))
1687                 } else {
1688                     let old = self.ptr;
1689                     self.ptr = self.ptr.offset(1);
1690
1691                     Some(ptr::read(old))
1692                 }
1693             }
1694         }
1695     }
1696
1697     #[inline]
1698     fn size_hint(&self) -> (uint, Option<uint>) {
1699         let diff = (self.end as uint) - (self.ptr as uint);
1700         let size = mem::size_of::<T>();
1701         let exact = diff / (if size == 0 {1} else {size});
1702         (exact, Some(exact))
1703     }
1704 }
1705
1706 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1707     #[inline]
1708     fn next_back(&mut self) -> Option<T> {
1709         unsafe {
1710             if self.end == self.ptr {
1711                 None
1712             } else {
1713                 if mem::size_of::<T>() == 0 {
1714                     // See above for why 'ptr.offset' isn't used
1715                     self.end = mem::transmute(self.end as uint - 1);
1716
1717                     // Use a non-null pointer value
1718                     Some(ptr::read(mem::transmute(1u)))
1719                 } else {
1720                     self.end = self.end.offset(-1);
1721
1722                     Some(ptr::read(self.end))
1723                 }
1724             }
1725         }
1726     }
1727 }
1728
1729 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1730
1731 #[unsafe_destructor]
1732 impl<'a, T> Drop for Drain<'a, T> {
1733     fn drop(&mut self) {
1734         // self.ptr == self.end == null if drop has already been called,
1735         // so we can use #[unsafe_no_drop_flag].
1736
1737         // destroy the remaining elements
1738         for _x in *self {}
1739     }
1740 }
1741
1742 ////////////////////////////////////////////////////////////////////////////////
1743 // Conversion from &[T] to &Vec<T>
1744 ////////////////////////////////////////////////////////////////////////////////
1745
1746 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1747 #[experimental]
1748 pub struct DerefVec<'a, T> {
1749     x: Vec<T>,
1750     l: ContravariantLifetime<'a>
1751 }
1752
1753 #[experimental]
1754 impl<'a, T> Deref for DerefVec<'a, T> {
1755     type Target = Vec<T>;
1756
1757     fn deref<'b>(&'b self) -> &'b Vec<T> {
1758         &self.x
1759     }
1760 }
1761
1762 // Prevent the inner `Vec<T>` from attempting to deallocate memory.
1763 #[unsafe_destructor]
1764 #[experimental]
1765 impl<'a, T> Drop for DerefVec<'a, T> {
1766     fn drop(&mut self) {
1767         self.x.len = 0;
1768         self.x.cap = 0;
1769     }
1770 }
1771
1772 /// Convert a slice to a wrapper type providing a `&Vec<T>` reference.
1773 #[experimental]
1774 pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
1775     unsafe {
1776         DerefVec {
1777             x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1778             l: ContravariantLifetime::<'a>
1779         }
1780     }
1781 }
1782
1783 ////////////////////////////////////////////////////////////////////////////////
1784 // Raw module (deprecated)
1785 ////////////////////////////////////////////////////////////////////////////////
1786
1787 /// Unsafe vector operations.
1788 #[deprecated]
1789 pub mod raw {
1790     use super::Vec;
1791
1792     /// Constructs a vector from an unsafe pointer to a buffer.
1793     ///
1794     /// The elements of the buffer are copied into the vector without cloning,
1795     /// as if `ptr::read()` were called on them.
1796     #[inline]
1797     #[deprecated = "renamed to Vec::from_raw_buf"]
1798     pub unsafe fn from_buf<T>(ptr: *const T, elts: uint) -> Vec<T> {
1799         Vec::from_raw_buf(ptr, elts)
1800     }
1801 }
1802
1803 ////////////////////////////////////////////////////////////////////////////////
1804 // Partial vec, used for map_in_place
1805 ////////////////////////////////////////////////////////////////////////////////
1806
1807 /// An owned, partially type-converted vector of elements with non-zero size.
1808 ///
1809 /// `T` and `U` must have the same, non-zero size. They must also have the same
1810 /// alignment.
1811 ///
1812 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
1813 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
1814 /// destructed. Additionally the underlying storage of `vec` will be freed.
1815 struct PartialVecNonZeroSized<T,U> {
1816     vec: Vec<T>,
1817
1818     start_u: *mut U,
1819     end_u: *mut U,
1820     start_t: *mut T,
1821     end_t: *mut T,
1822 }
1823
1824 /// An owned, partially type-converted vector of zero-sized elements.
1825 ///
1826 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1827 /// are destructed.
1828 struct PartialVecZeroSized<T,U> {
1829     num_t: uint,
1830     num_u: uint,
1831     marker_t: InvariantType<T>,
1832     marker_u: InvariantType<U>,
1833 }
1834
1835 #[unsafe_destructor]
1836 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1837     fn drop(&mut self) {
1838         unsafe {
1839             // `vec` hasn't been modified until now. As it has a length
1840             // currently, this would run destructors of `T`s which might not be
1841             // there. So at first, set `vec`s length to `0`. This must be done
1842             // at first to remain memory-safe as the destructors of `U` or `T`
1843             // might cause unwinding where `vec`s destructor would be executed.
1844             self.vec.set_len(0);
1845
1846             // We have instances of `U`s and `T`s in `vec`. Destruct them.
1847             while self.start_u != self.end_u {
1848                 let _ = ptr::read(self.start_u as *const U); // Run a `U` destructor.
1849                 self.start_u = self.start_u.offset(1);
1850             }
1851             while self.start_t != self.end_t {
1852                 let _ = ptr::read(self.start_t as *const T); // Run a `T` destructor.
1853                 self.start_t = self.start_t.offset(1);
1854             }
1855             // After this destructor ran, the destructor of `vec` will run,
1856             // deallocating the underlying memory.
1857         }
1858     }
1859 }
1860
1861 #[unsafe_destructor]
1862 impl<T,U> Drop for PartialVecZeroSized<T,U> {
1863     fn drop(&mut self) {
1864         unsafe {
1865             // Destruct the instances of `T` and `U` this struct owns.
1866             while self.num_t != 0 {
1867                 let _: T = mem::uninitialized(); // Run a `T` destructor.
1868                 self.num_t -= 1;
1869             }
1870             while self.num_u != 0 {
1871                 let _: U = mem::uninitialized(); // Run a `U` destructor.
1872                 self.num_u -= 1;
1873             }
1874         }
1875     }
1876 }
1877
1878 #[cfg(test)]
1879 mod tests {
1880     use prelude::*;
1881     use core::mem::size_of;
1882     use test::Bencher;
1883     use super::{as_vec, unzip, raw};
1884
1885     struct DropCounter<'a> {
1886         count: &'a mut int
1887     }
1888
1889     #[unsafe_destructor]
1890     impl<'a> Drop for DropCounter<'a> {
1891         fn drop(&mut self) {
1892             *self.count += 1;
1893         }
1894     }
1895
1896     #[test]
1897     fn test_as_vec() {
1898         let xs = [1u8, 2u8, 3u8];
1899         assert_eq!(as_vec(&xs).as_slice(), xs);
1900     }
1901
1902     #[test]
1903     fn test_as_vec_dtor() {
1904         let (mut count_x, mut count_y) = (0, 0);
1905         {
1906             let xs = &[DropCounter { count: &mut count_x }, DropCounter { count: &mut count_y }];
1907             assert_eq!(as_vec(xs).len(), 2);
1908         }
1909         assert_eq!(count_x, 1);
1910         assert_eq!(count_y, 1);
1911     }
1912
1913     #[test]
1914     fn test_small_vec_struct() {
1915         assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1916     }
1917
1918     #[test]
1919     fn test_double_drop() {
1920         struct TwoVec<T> {
1921             x: Vec<T>,
1922             y: Vec<T>
1923         }
1924
1925         let (mut count_x, mut count_y) = (0, 0);
1926         {
1927             let mut tv = TwoVec {
1928                 x: Vec::new(),
1929                 y: Vec::new()
1930             };
1931             tv.x.push(DropCounter {count: &mut count_x});
1932             tv.y.push(DropCounter {count: &mut count_y});
1933
1934             // If Vec had a drop flag, here is where it would be zeroed.
1935             // Instead, it should rely on its internal state to prevent
1936             // doing anything significant when dropped multiple times.
1937             drop(tv.x);
1938
1939             // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1940         }
1941
1942         assert_eq!(count_x, 1);
1943         assert_eq!(count_y, 1);
1944     }
1945
1946     #[test]
1947     fn test_reserve() {
1948         let mut v = Vec::new();
1949         assert_eq!(v.capacity(), 0);
1950
1951         v.reserve(2);
1952         assert!(v.capacity() >= 2);
1953
1954         for i in range(0i, 16) {
1955             v.push(i);
1956         }
1957
1958         assert!(v.capacity() >= 16);
1959         v.reserve(16);
1960         assert!(v.capacity() >= 32);
1961
1962         v.push(16);
1963
1964         v.reserve(16);
1965         assert!(v.capacity() >= 33)
1966     }
1967
1968     #[test]
1969     fn test_extend() {
1970         let mut v = Vec::new();
1971         let mut w = Vec::new();
1972
1973         v.extend(range(0i, 3));
1974         for i in range(0i, 3) { w.push(i) }
1975
1976         assert_eq!(v, w);
1977
1978         v.extend(range(3i, 10));
1979         for i in range(3i, 10) { w.push(i) }
1980
1981         assert_eq!(v, w);
1982     }
1983
1984     #[test]
1985     fn test_slice_from_mut() {
1986         let mut values = vec![1u8,2,3,4,5];
1987         {
1988             let slice = values.slice_from_mut(2);
1989             assert!(slice == [3, 4, 5]);
1990             for p in slice.iter_mut() {
1991                 *p += 2;
1992             }
1993         }
1994
1995         assert!(values == [1, 2, 5, 6, 7]);
1996     }
1997
1998     #[test]
1999     fn test_slice_to_mut() {
2000         let mut values = vec![1u8,2,3,4,5];
2001         {
2002             let slice = values.slice_to_mut(2);
2003             assert!(slice == [1, 2]);
2004             for p in slice.iter_mut() {
2005                 *p += 1;
2006             }
2007         }
2008
2009         assert!(values == [2, 3, 3, 4, 5]);
2010     }
2011
2012     #[test]
2013     fn test_split_at_mut() {
2014         let mut values = vec![1u8,2,3,4,5];
2015         {
2016             let (left, right) = values.split_at_mut(2);
2017             {
2018                 let left: &[_] = left;
2019                 assert!(left[0..left.len()] == [1, 2][]);
2020             }
2021             for p in left.iter_mut() {
2022                 *p += 1;
2023             }
2024
2025             {
2026                 let right: &[_] = right;
2027                 assert!(right[0..right.len()] == [3, 4, 5][]);
2028             }
2029             for p in right.iter_mut() {
2030                 *p += 2;
2031             }
2032         }
2033
2034         assert!(values == vec![2u8, 3, 5, 6, 7]);
2035     }
2036
2037     #[test]
2038     fn test_clone() {
2039         let v: Vec<int> = vec!();
2040         let w = vec!(1i, 2, 3);
2041
2042         assert_eq!(v, v.clone());
2043
2044         let z = w.clone();
2045         assert_eq!(w, z);
2046         // they should be disjoint in memory.
2047         assert!(w.as_ptr() != z.as_ptr())
2048     }
2049
2050     #[test]
2051     fn test_clone_from() {
2052         let mut v = vec!();
2053         let three = vec!(box 1i, box 2, box 3);
2054         let two = vec!(box 4i, box 5);
2055         // zero, long
2056         v.clone_from(&three);
2057         assert_eq!(v, three);
2058
2059         // equal
2060         v.clone_from(&three);
2061         assert_eq!(v, three);
2062
2063         // long, short
2064         v.clone_from(&two);
2065         assert_eq!(v, two);
2066
2067         // short, long
2068         v.clone_from(&three);
2069         assert_eq!(v, three)
2070     }
2071
2072     #[test]
2073     fn test_grow_fn() {
2074         let mut v = vec![0u, 1];
2075         v.grow_fn(3, |i| i);
2076         assert!(v == vec![0u, 1, 0, 1, 2]);
2077     }
2078
2079     #[test]
2080     fn test_retain() {
2081         let mut vec = vec![1u, 2, 3, 4];
2082         vec.retain(|&x| x % 2 == 0);
2083         assert!(vec == vec![2u, 4]);
2084     }
2085
2086     #[test]
2087     fn zero_sized_values() {
2088         let mut v = Vec::new();
2089         assert_eq!(v.len(), 0);
2090         v.push(());
2091         assert_eq!(v.len(), 1);
2092         v.push(());
2093         assert_eq!(v.len(), 2);
2094         assert_eq!(v.pop(), Some(()));
2095         assert_eq!(v.pop(), Some(()));
2096         assert_eq!(v.pop(), None);
2097
2098         assert_eq!(v.iter().count(), 0);
2099         v.push(());
2100         assert_eq!(v.iter().count(), 1);
2101         v.push(());
2102         assert_eq!(v.iter().count(), 2);
2103
2104         for &() in v.iter() {}
2105
2106         assert_eq!(v.iter_mut().count(), 2);
2107         v.push(());
2108         assert_eq!(v.iter_mut().count(), 3);
2109         v.push(());
2110         assert_eq!(v.iter_mut().count(), 4);
2111
2112         for &() in v.iter_mut() {}
2113         unsafe { v.set_len(0); }
2114         assert_eq!(v.iter_mut().count(), 0);
2115     }
2116
2117     #[test]
2118     fn test_partition() {
2119         assert_eq!(vec![].partition(|x: &int| *x < 3), (vec![], vec![]));
2120         assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2121         assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2122         assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2123     }
2124
2125     #[test]
2126     fn test_partitioned() {
2127         assert_eq!(vec![].partitioned(|x: &int| *x < 3), (vec![], vec![]));
2128         assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2129         assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2130         assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2131     }
2132
2133     #[test]
2134     fn test_zip_unzip() {
2135         let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
2136
2137         let (left, right) = unzip(z1.iter().map(|&x| x));
2138
2139         assert_eq!((1, 4), (left[0], right[0]));
2140         assert_eq!((2, 5), (left[1], right[1]));
2141         assert_eq!((3, 6), (left[2], right[2]));
2142     }
2143
2144     #[test]
2145     fn test_unsafe_ptrs() {
2146         unsafe {
2147             // Test on-stack copy-from-buf.
2148             let a = [1i, 2, 3];
2149             let ptr = a.as_ptr();
2150             let b = raw::from_buf(ptr, 3u);
2151             assert_eq!(b, vec![1, 2, 3]);
2152
2153             // Test on-heap copy-from-buf.
2154             let c = vec![1i, 2, 3, 4, 5];
2155             let ptr = c.as_ptr();
2156             let d = raw::from_buf(ptr, 5u);
2157             assert_eq!(d, vec![1, 2, 3, 4, 5]);
2158         }
2159     }
2160
2161     #[test]
2162     fn test_vec_truncate_drop() {
2163         static mut drops: uint = 0;
2164         struct Elem(int);
2165         impl Drop for Elem {
2166             fn drop(&mut self) {
2167                 unsafe { drops += 1; }
2168             }
2169         }
2170
2171         let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
2172         assert_eq!(unsafe { drops }, 0);
2173         v.truncate(3);
2174         assert_eq!(unsafe { drops }, 2);
2175         v.truncate(0);
2176         assert_eq!(unsafe { drops }, 5);
2177     }
2178
2179     #[test]
2180     #[should_fail]
2181     fn test_vec_truncate_fail() {
2182         struct BadElem(int);
2183         impl Drop for BadElem {
2184             fn drop(&mut self) {
2185                 let BadElem(ref mut x) = *self;
2186                 if *x == 0xbadbeef {
2187                     panic!("BadElem panic: 0xbadbeef")
2188                 }
2189             }
2190         }
2191
2192         let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
2193         v.truncate(0);
2194     }
2195
2196     #[test]
2197     fn test_index() {
2198         let vec = vec!(1i, 2, 3);
2199         assert!(vec[1] == 2);
2200     }
2201
2202     #[test]
2203     #[should_fail]
2204     fn test_index_out_of_bounds() {
2205         let vec = vec!(1i, 2, 3);
2206         let _ = vec[3];
2207     }
2208
2209     #[test]
2210     #[should_fail]
2211     fn test_slice_out_of_bounds_1() {
2212         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2213         x[-1..];
2214     }
2215
2216     #[test]
2217     #[should_fail]
2218     fn test_slice_out_of_bounds_2() {
2219         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2220         x[..6];
2221     }
2222
2223     #[test]
2224     #[should_fail]
2225     fn test_slice_out_of_bounds_3() {
2226         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2227         x[-1..4];
2228     }
2229
2230     #[test]
2231     #[should_fail]
2232     fn test_slice_out_of_bounds_4() {
2233         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2234         x[1..6];
2235     }
2236
2237     #[test]
2238     #[should_fail]
2239     fn test_slice_out_of_bounds_5() {
2240         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2241         x[3..2];
2242     }
2243
2244     #[test]
2245     #[should_fail]
2246     fn test_swap_remove_empty() {
2247         let mut vec: Vec<uint> = vec!();
2248         vec.swap_remove(0);
2249     }
2250
2251     #[test]
2252     fn test_move_iter_unwrap() {
2253         let mut vec: Vec<uint> = Vec::with_capacity(7);
2254         vec.push(1);
2255         vec.push(2);
2256         let ptr = vec.as_ptr();
2257         vec = vec.into_iter().unwrap();
2258         assert_eq!(vec.as_ptr(), ptr);
2259         assert_eq!(vec.capacity(), 7);
2260         assert_eq!(vec.len(), 0);
2261     }
2262
2263     #[test]
2264     #[should_fail]
2265     fn test_map_in_place_incompatible_types_fail() {
2266         let v = vec![0u, 1, 2];
2267         v.map_in_place(|_| ());
2268     }
2269
2270     #[test]
2271     fn test_map_in_place() {
2272         let v = vec![0u, 1, 2];
2273         assert_eq!(v.map_in_place(|i: uint| i as int - 1), [-1i, 0, 1]);
2274     }
2275
2276     #[test]
2277     fn test_map_in_place_zero_sized() {
2278         let v = vec![(), ()];
2279         #[deriving(PartialEq, Show)]
2280         struct ZeroSized;
2281         assert_eq!(v.map_in_place(|_| ZeroSized), [ZeroSized, ZeroSized]);
2282     }
2283
2284     #[test]
2285     fn test_map_in_place_zero_drop_count() {
2286         use std::sync::atomic;
2287         use std::sync::atomic::AtomicUint;
2288
2289         #[deriving(Clone, PartialEq, Show)]
2290         struct Nothing;
2291         impl Drop for Nothing { fn drop(&mut self) { } }
2292
2293         #[deriving(Clone, PartialEq, Show)]
2294         struct ZeroSized;
2295         impl Drop for ZeroSized {
2296             fn drop(&mut self) {
2297                 DROP_COUNTER.fetch_add(1, atomic::Relaxed);
2298             }
2299         }
2300         const NUM_ELEMENTS: uint = 2;
2301         static DROP_COUNTER: AtomicUint = atomic::ATOMIC_UINT_INIT;
2302
2303         let v = Vec::from_elem(NUM_ELEMENTS, Nothing);
2304
2305         DROP_COUNTER.store(0, atomic::Relaxed);
2306
2307         let v = v.map_in_place(|_| ZeroSized);
2308         assert_eq!(DROP_COUNTER.load(atomic::Relaxed), 0);
2309         drop(v);
2310         assert_eq!(DROP_COUNTER.load(atomic::Relaxed), NUM_ELEMENTS);
2311     }
2312
2313     #[test]
2314     fn test_move_items() {
2315         let vec = vec![1, 2, 3];
2316         let mut vec2 : Vec<i32> = vec![];
2317         for i in vec.into_iter() {
2318             vec2.push(i);
2319         }
2320         assert!(vec2 == vec![1, 2, 3]);
2321     }
2322
2323     #[test]
2324     fn test_move_items_reverse() {
2325         let vec = vec![1, 2, 3];
2326         let mut vec2 : Vec<i32> = vec![];
2327         for i in vec.into_iter().rev() {
2328             vec2.push(i);
2329         }
2330         assert!(vec2 == vec![3, 2, 1]);
2331     }
2332
2333     #[test]
2334     fn test_move_items_zero_sized() {
2335         let vec = vec![(), (), ()];
2336         let mut vec2 : Vec<()> = vec![];
2337         for i in vec.into_iter() {
2338             vec2.push(i);
2339         }
2340         assert!(vec2 == vec![(), (), ()]);
2341     }
2342
2343     #[test]
2344     fn test_drain_items() {
2345         let mut vec = vec![1, 2, 3];
2346         let mut vec2: Vec<i32> = vec![];
2347         for i in vec.drain() {
2348             vec2.push(i);
2349         }
2350         assert_eq!(vec, []);
2351         assert_eq!(vec2, [ 1, 2, 3 ]);
2352     }
2353
2354     #[test]
2355     fn test_drain_items_reverse() {
2356         let mut vec = vec![1, 2, 3];
2357         let mut vec2: Vec<i32> = vec![];
2358         for i in vec.drain().rev() {
2359             vec2.push(i);
2360         }
2361         assert_eq!(vec, []);
2362         assert_eq!(vec2, [ 3, 2, 1 ]);
2363     }
2364
2365     #[test]
2366     fn test_drain_items_zero_sized() {
2367         let mut vec = vec![(), (), ()];
2368         let mut vec2: Vec<()> = vec![];
2369         for i in vec.drain() {
2370             vec2.push(i);
2371         }
2372         assert_eq!(vec, []);
2373         assert_eq!(vec2, [(), (), ()]);
2374     }
2375
2376     #[test]
2377     fn test_into_boxed_slice() {
2378         let xs = vec![1u, 2, 3];
2379         let ys = xs.into_boxed_slice();
2380         assert_eq!(ys.as_slice(), [1u, 2, 3]);
2381     }
2382
2383     #[bench]
2384     fn bench_new(b: &mut Bencher) {
2385         b.iter(|| {
2386             let v: Vec<uint> = Vec::new();
2387             assert_eq!(v.len(), 0);
2388             assert_eq!(v.capacity(), 0);
2389         })
2390     }
2391
2392     fn do_bench_with_capacity(b: &mut Bencher, src_len: uint) {
2393         b.bytes = src_len as u64;
2394
2395         b.iter(|| {
2396             let v: Vec<uint> = Vec::with_capacity(src_len);
2397             assert_eq!(v.len(), 0);
2398             assert_eq!(v.capacity(), src_len);
2399         })
2400     }
2401
2402     #[bench]
2403     fn bench_with_capacity_0000(b: &mut Bencher) {
2404         do_bench_with_capacity(b, 0)
2405     }
2406
2407     #[bench]
2408     fn bench_with_capacity_0010(b: &mut Bencher) {
2409         do_bench_with_capacity(b, 10)
2410     }
2411
2412     #[bench]
2413     fn bench_with_capacity_0100(b: &mut Bencher) {
2414         do_bench_with_capacity(b, 100)
2415     }
2416
2417     #[bench]
2418     fn bench_with_capacity_1000(b: &mut Bencher) {
2419         do_bench_with_capacity(b, 1000)
2420     }
2421
2422     fn do_bench_from_fn(b: &mut Bencher, src_len: uint) {
2423         b.bytes = src_len as u64;
2424
2425         b.iter(|| {
2426             let dst = Vec::from_fn(src_len, |i| i);
2427             assert_eq!(dst.len(), src_len);
2428             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2429         })
2430     }
2431
2432     #[bench]
2433     fn bench_from_fn_0000(b: &mut Bencher) {
2434         do_bench_from_fn(b, 0)
2435     }
2436
2437     #[bench]
2438     fn bench_from_fn_0010(b: &mut Bencher) {
2439         do_bench_from_fn(b, 10)
2440     }
2441
2442     #[bench]
2443     fn bench_from_fn_0100(b: &mut Bencher) {
2444         do_bench_from_fn(b, 100)
2445     }
2446
2447     #[bench]
2448     fn bench_from_fn_1000(b: &mut Bencher) {
2449         do_bench_from_fn(b, 1000)
2450     }
2451
2452     fn do_bench_from_elem(b: &mut Bencher, src_len: uint) {
2453         b.bytes = src_len as u64;
2454
2455         b.iter(|| {
2456             let dst: Vec<uint> = Vec::from_elem(src_len, 5);
2457             assert_eq!(dst.len(), src_len);
2458             assert!(dst.iter().all(|x| *x == 5));
2459         })
2460     }
2461
2462     #[bench]
2463     fn bench_from_elem_0000(b: &mut Bencher) {
2464         do_bench_from_elem(b, 0)
2465     }
2466
2467     #[bench]
2468     fn bench_from_elem_0010(b: &mut Bencher) {
2469         do_bench_from_elem(b, 10)
2470     }
2471
2472     #[bench]
2473     fn bench_from_elem_0100(b: &mut Bencher) {
2474         do_bench_from_elem(b, 100)
2475     }
2476
2477     #[bench]
2478     fn bench_from_elem_1000(b: &mut Bencher) {
2479         do_bench_from_elem(b, 1000)
2480     }
2481
2482     fn do_bench_from_slice(b: &mut Bencher, src_len: uint) {
2483         let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2484
2485         b.bytes = src_len as u64;
2486
2487         b.iter(|| {
2488             let dst = src.clone().as_slice().to_vec();
2489             assert_eq!(dst.len(), src_len);
2490             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2491         });
2492     }
2493
2494     #[bench]
2495     fn bench_from_slice_0000(b: &mut Bencher) {
2496         do_bench_from_slice(b, 0)
2497     }
2498
2499     #[bench]
2500     fn bench_from_slice_0010(b: &mut Bencher) {
2501         do_bench_from_slice(b, 10)
2502     }
2503
2504     #[bench]
2505     fn bench_from_slice_0100(b: &mut Bencher) {
2506         do_bench_from_slice(b, 100)
2507     }
2508
2509     #[bench]
2510     fn bench_from_slice_1000(b: &mut Bencher) {
2511         do_bench_from_slice(b, 1000)
2512     }
2513
2514     fn do_bench_from_iter(b: &mut Bencher, src_len: uint) {
2515         let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2516
2517         b.bytes = src_len as u64;
2518
2519         b.iter(|| {
2520             let dst: Vec<uint> = FromIterator::from_iter(src.clone().into_iter());
2521             assert_eq!(dst.len(), src_len);
2522             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2523         });
2524     }
2525
2526     #[bench]
2527     fn bench_from_iter_0000(b: &mut Bencher) {
2528         do_bench_from_iter(b, 0)
2529     }
2530
2531     #[bench]
2532     fn bench_from_iter_0010(b: &mut Bencher) {
2533         do_bench_from_iter(b, 10)
2534     }
2535
2536     #[bench]
2537     fn bench_from_iter_0100(b: &mut Bencher) {
2538         do_bench_from_iter(b, 100)
2539     }
2540
2541     #[bench]
2542     fn bench_from_iter_1000(b: &mut Bencher) {
2543         do_bench_from_iter(b, 1000)
2544     }
2545
2546     fn do_bench_extend(b: &mut Bencher, dst_len: uint, src_len: uint) {
2547         let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2548         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2549
2550         b.bytes = src_len as u64;
2551
2552         b.iter(|| {
2553             let mut dst = dst.clone();
2554             dst.extend(src.clone().into_iter());
2555             assert_eq!(dst.len(), dst_len + src_len);
2556             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2557         });
2558     }
2559
2560     #[bench]
2561     fn bench_extend_0000_0000(b: &mut Bencher) {
2562         do_bench_extend(b, 0, 0)
2563     }
2564
2565     #[bench]
2566     fn bench_extend_0000_0010(b: &mut Bencher) {
2567         do_bench_extend(b, 0, 10)
2568     }
2569
2570     #[bench]
2571     fn bench_extend_0000_0100(b: &mut Bencher) {
2572         do_bench_extend(b, 0, 100)
2573     }
2574
2575     #[bench]
2576     fn bench_extend_0000_1000(b: &mut Bencher) {
2577         do_bench_extend(b, 0, 1000)
2578     }
2579
2580     #[bench]
2581     fn bench_extend_0010_0010(b: &mut Bencher) {
2582         do_bench_extend(b, 10, 10)
2583     }
2584
2585     #[bench]
2586     fn bench_extend_0100_0100(b: &mut Bencher) {
2587         do_bench_extend(b, 100, 100)
2588     }
2589
2590     #[bench]
2591     fn bench_extend_1000_1000(b: &mut Bencher) {
2592         do_bench_extend(b, 1000, 1000)
2593     }
2594
2595     fn do_bench_push_all(b: &mut Bencher, dst_len: uint, src_len: uint) {
2596         let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2597         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2598
2599         b.bytes = src_len as u64;
2600
2601         b.iter(|| {
2602             let mut dst = dst.clone();
2603             dst.push_all(src.as_slice());
2604             assert_eq!(dst.len(), dst_len + src_len);
2605             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2606         });
2607     }
2608
2609     #[bench]
2610     fn bench_push_all_0000_0000(b: &mut Bencher) {
2611         do_bench_push_all(b, 0, 0)
2612     }
2613
2614     #[bench]
2615     fn bench_push_all_0000_0010(b: &mut Bencher) {
2616         do_bench_push_all(b, 0, 10)
2617     }
2618
2619     #[bench]
2620     fn bench_push_all_0000_0100(b: &mut Bencher) {
2621         do_bench_push_all(b, 0, 100)
2622     }
2623
2624     #[bench]
2625     fn bench_push_all_0000_1000(b: &mut Bencher) {
2626         do_bench_push_all(b, 0, 1000)
2627     }
2628
2629     #[bench]
2630     fn bench_push_all_0010_0010(b: &mut Bencher) {
2631         do_bench_push_all(b, 10, 10)
2632     }
2633
2634     #[bench]
2635     fn bench_push_all_0100_0100(b: &mut Bencher) {
2636         do_bench_push_all(b, 100, 100)
2637     }
2638
2639     #[bench]
2640     fn bench_push_all_1000_1000(b: &mut Bencher) {
2641         do_bench_push_all(b, 1000, 1000)
2642     }
2643
2644     fn do_bench_push_all_move(b: &mut Bencher, dst_len: uint, src_len: uint) {
2645         let dst: Vec<uint> = FromIterator::from_iter(range(0u, dst_len));
2646         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2647
2648         b.bytes = src_len as u64;
2649
2650         b.iter(|| {
2651             let mut dst = dst.clone();
2652             dst.extend(src.clone().into_iter());
2653             assert_eq!(dst.len(), dst_len + src_len);
2654             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2655         });
2656     }
2657
2658     #[bench]
2659     fn bench_push_all_move_0000_0000(b: &mut Bencher) {
2660         do_bench_push_all_move(b, 0, 0)
2661     }
2662
2663     #[bench]
2664     fn bench_push_all_move_0000_0010(b: &mut Bencher) {
2665         do_bench_push_all_move(b, 0, 10)
2666     }
2667
2668     #[bench]
2669     fn bench_push_all_move_0000_0100(b: &mut Bencher) {
2670         do_bench_push_all_move(b, 0, 100)
2671     }
2672
2673     #[bench]
2674     fn bench_push_all_move_0000_1000(b: &mut Bencher) {
2675         do_bench_push_all_move(b, 0, 1000)
2676     }
2677
2678     #[bench]
2679     fn bench_push_all_move_0010_0010(b: &mut Bencher) {
2680         do_bench_push_all_move(b, 10, 10)
2681     }
2682
2683     #[bench]
2684     fn bench_push_all_move_0100_0100(b: &mut Bencher) {
2685         do_bench_push_all_move(b, 100, 100)
2686     }
2687
2688     #[bench]
2689     fn bench_push_all_move_1000_1000(b: &mut Bencher) {
2690         do_bench_push_all_move(b, 1000, 1000)
2691     }
2692
2693     fn do_bench_clone(b: &mut Bencher, src_len: uint) {
2694         let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2695
2696         b.bytes = src_len as u64;
2697
2698         b.iter(|| {
2699             let dst = src.clone();
2700             assert_eq!(dst.len(), src_len);
2701             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2702         });
2703     }
2704
2705     #[bench]
2706     fn bench_clone_0000(b: &mut Bencher) {
2707         do_bench_clone(b, 0)
2708     }
2709
2710     #[bench]
2711     fn bench_clone_0010(b: &mut Bencher) {
2712         do_bench_clone(b, 10)
2713     }
2714
2715     #[bench]
2716     fn bench_clone_0100(b: &mut Bencher) {
2717         do_bench_clone(b, 100)
2718     }
2719
2720     #[bench]
2721     fn bench_clone_1000(b: &mut Bencher) {
2722         do_bench_clone(b, 1000)
2723     }
2724
2725     fn do_bench_clone_from(b: &mut Bencher, times: uint, dst_len: uint, src_len: uint) {
2726         let dst: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2727         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2728
2729         b.bytes = (times * src_len) as u64;
2730
2731         b.iter(|| {
2732             let mut dst = dst.clone();
2733
2734             for _ in range(0, times) {
2735                 dst.clone_from(&src);
2736
2737                 assert_eq!(dst.len(), src_len);
2738                 assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x));
2739             }
2740         });
2741     }
2742
2743     #[bench]
2744     fn bench_clone_from_01_0000_0000(b: &mut Bencher) {
2745         do_bench_clone_from(b, 1, 0, 0)
2746     }
2747
2748     #[bench]
2749     fn bench_clone_from_01_0000_0010(b: &mut Bencher) {
2750         do_bench_clone_from(b, 1, 0, 10)
2751     }
2752
2753     #[bench]
2754     fn bench_clone_from_01_0000_0100(b: &mut Bencher) {
2755         do_bench_clone_from(b, 1, 0, 100)
2756     }
2757
2758     #[bench]
2759     fn bench_clone_from_01_0000_1000(b: &mut Bencher) {
2760         do_bench_clone_from(b, 1, 0, 1000)
2761     }
2762
2763     #[bench]
2764     fn bench_clone_from_01_0010_0010(b: &mut Bencher) {
2765         do_bench_clone_from(b, 1, 10, 10)
2766     }
2767
2768     #[bench]
2769     fn bench_clone_from_01_0100_0100(b: &mut Bencher) {
2770         do_bench_clone_from(b, 1, 100, 100)
2771     }
2772
2773     #[bench]
2774     fn bench_clone_from_01_1000_1000(b: &mut Bencher) {
2775         do_bench_clone_from(b, 1, 1000, 1000)
2776     }
2777
2778     #[bench]
2779     fn bench_clone_from_01_0010_0100(b: &mut Bencher) {
2780         do_bench_clone_from(b, 1, 10, 100)
2781     }
2782
2783     #[bench]
2784     fn bench_clone_from_01_0100_1000(b: &mut Bencher) {
2785         do_bench_clone_from(b, 1, 100, 1000)
2786     }
2787
2788     #[bench]
2789     fn bench_clone_from_01_0010_0000(b: &mut Bencher) {
2790         do_bench_clone_from(b, 1, 10, 0)
2791     }
2792
2793     #[bench]
2794     fn bench_clone_from_01_0100_0010(b: &mut Bencher) {
2795         do_bench_clone_from(b, 1, 100, 10)
2796     }
2797
2798     #[bench]
2799     fn bench_clone_from_01_1000_0100(b: &mut Bencher) {
2800         do_bench_clone_from(b, 1, 1000, 100)
2801     }
2802
2803     #[bench]
2804     fn bench_clone_from_10_0000_0000(b: &mut Bencher) {
2805         do_bench_clone_from(b, 10, 0, 0)
2806     }
2807
2808     #[bench]
2809     fn bench_clone_from_10_0000_0010(b: &mut Bencher) {
2810         do_bench_clone_from(b, 10, 0, 10)
2811     }
2812
2813     #[bench]
2814     fn bench_clone_from_10_0000_0100(b: &mut Bencher) {
2815         do_bench_clone_from(b, 10, 0, 100)
2816     }
2817
2818     #[bench]
2819     fn bench_clone_from_10_0000_1000(b: &mut Bencher) {
2820         do_bench_clone_from(b, 10, 0, 1000)
2821     }
2822
2823     #[bench]
2824     fn bench_clone_from_10_0010_0010(b: &mut Bencher) {
2825         do_bench_clone_from(b, 10, 10, 10)
2826     }
2827
2828     #[bench]
2829     fn bench_clone_from_10_0100_0100(b: &mut Bencher) {
2830         do_bench_clone_from(b, 10, 100, 100)
2831     }
2832
2833     #[bench]
2834     fn bench_clone_from_10_1000_1000(b: &mut Bencher) {
2835         do_bench_clone_from(b, 10, 1000, 1000)
2836     }
2837
2838     #[bench]
2839     fn bench_clone_from_10_0010_0100(b: &mut Bencher) {
2840         do_bench_clone_from(b, 10, 10, 100)
2841     }
2842
2843     #[bench]
2844     fn bench_clone_from_10_0100_1000(b: &mut Bencher) {
2845         do_bench_clone_from(b, 10, 100, 1000)
2846     }
2847
2848     #[bench]
2849     fn bench_clone_from_10_0010_0000(b: &mut Bencher) {
2850         do_bench_clone_from(b, 10, 10, 0)
2851     }
2852
2853     #[bench]
2854     fn bench_clone_from_10_0100_0010(b: &mut Bencher) {
2855         do_bench_clone_from(b, 10, 100, 10)
2856     }
2857
2858     #[bench]
2859     fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
2860         do_bench_clone_from(b, 10, 1000, 100)
2861     }
2862 }