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