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