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