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