]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec.rs
Fix misspelled comments.
[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 #[experimental = "waiting on Index stability"]
1194 impl<T> Index<uint> for Vec<T> {
1195     type Output = T;
1196
1197     #[inline]
1198     fn index<'a>(&'a self, index: &uint) -> &'a T {
1199         &self.as_slice()[*index]
1200     }
1201 }
1202
1203 impl<T> IndexMut<uint> for Vec<T> {
1204     type Output = T;
1205
1206     #[inline]
1207     fn index_mut<'a>(&'a mut self, index: &uint) -> &'a mut T {
1208         &mut self.as_mut_slice()[*index]
1209     }
1210 }
1211
1212 impl<T> ops::Slice<uint, [T]> for Vec<T> {
1213     #[inline]
1214     fn as_slice_<'a>(&'a self) -> &'a [T] {
1215         self.as_slice()
1216     }
1217
1218     #[inline]
1219     fn slice_from_or_fail<'a>(&'a self, start: &uint) -> &'a [T] {
1220         self.as_slice().slice_from_or_fail(start)
1221     }
1222
1223     #[inline]
1224     fn slice_to_or_fail<'a>(&'a self, end: &uint) -> &'a [T] {
1225         self.as_slice().slice_to_or_fail(end)
1226     }
1227     #[inline]
1228     fn slice_or_fail<'a>(&'a self, start: &uint, end: &uint) -> &'a [T] {
1229         self.as_slice().slice_or_fail(start, end)
1230     }
1231 }
1232
1233 impl<T> ops::SliceMut<uint, [T]> for Vec<T> {
1234     #[inline]
1235     fn as_mut_slice_<'a>(&'a mut self) -> &'a mut [T] {
1236         self.as_mut_slice()
1237     }
1238
1239     #[inline]
1240     fn slice_from_or_fail_mut<'a>(&'a mut self, start: &uint) -> &'a mut [T] {
1241         self.as_mut_slice().slice_from_or_fail_mut(start)
1242     }
1243
1244     #[inline]
1245     fn slice_to_or_fail_mut<'a>(&'a mut self, end: &uint) -> &'a mut [T] {
1246         self.as_mut_slice().slice_to_or_fail_mut(end)
1247     }
1248     #[inline]
1249     fn slice_or_fail_mut<'a>(&'a mut self, start: &uint, end: &uint) -> &'a mut [T] {
1250         self.as_mut_slice().slice_or_fail_mut(start, end)
1251     }
1252 }
1253
1254 #[stable]
1255 impl<T> ops::Deref for Vec<T> {
1256     type Target = [T];
1257
1258     fn deref<'a>(&'a self) -> &'a [T] { self.as_slice() }
1259 }
1260
1261 #[stable]
1262 impl<T> ops::DerefMut for Vec<T> {
1263     fn deref_mut<'a>(&'a mut self) -> &'a mut [T] { self.as_mut_slice() }
1264 }
1265
1266 #[stable]
1267 impl<T> FromIterator<T> for Vec<T> {
1268     #[inline]
1269     fn from_iter<I:Iterator<Item=T>>(mut iterator: I) -> Vec<T> {
1270         let (lower, _) = iterator.size_hint();
1271         let mut vector = Vec::with_capacity(lower);
1272         for element in iterator {
1273             vector.push(element)
1274         }
1275         vector
1276     }
1277 }
1278
1279 #[experimental = "waiting on Extend stability"]
1280 impl<T> Extend<T> for Vec<T> {
1281     #[inline]
1282     fn extend<I: Iterator<Item=T>>(&mut self, mut iterator: I) {
1283         let (lower, _) = iterator.size_hint();
1284         self.reserve(lower);
1285         for element in iterator {
1286             self.push(element)
1287         }
1288     }
1289 }
1290
1291 impl<A, B> PartialEq<Vec<B>> for Vec<A> where A: PartialEq<B> {
1292     #[inline]
1293     fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1294     #[inline]
1295     fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1296 }
1297
1298 macro_rules! impl_eq {
1299     ($lhs:ty, $rhs:ty) => {
1300         impl<'b, A, B> PartialEq<$rhs> for $lhs where A: PartialEq<B> {
1301             #[inline]
1302             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1303             #[inline]
1304             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1305         }
1306
1307         impl<'b, A, B> PartialEq<$lhs> for $rhs where B: PartialEq<A> {
1308             #[inline]
1309             fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) }
1310             #[inline]
1311             fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) }
1312         }
1313     }
1314 }
1315
1316 impl_eq! { Vec<A>, &'b [B] }
1317 impl_eq! { Vec<A>, &'b mut [B] }
1318
1319 impl<'a, A, B> PartialEq<Vec<B>> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1320     #[inline]
1321     fn eq(&self, other: &Vec<B>) -> bool { PartialEq::eq(&**self, &**other) }
1322     #[inline]
1323     fn ne(&self, other: &Vec<B>) -> bool { PartialEq::ne(&**self, &**other) }
1324 }
1325
1326 impl<'a, A, B> PartialEq<CowVec<'a, A>> for Vec<B> where A: Clone, B: PartialEq<A> {
1327     #[inline]
1328     fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1329     #[inline]
1330     fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1331 }
1332
1333 macro_rules! impl_eq_for_cowvec {
1334     ($rhs:ty) => {
1335         impl<'a, 'b, A, B> PartialEq<$rhs> for CowVec<'a, A> where A: PartialEq<B> + Clone {
1336             #[inline]
1337             fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) }
1338             #[inline]
1339             fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) }
1340         }
1341
1342         impl<'a, 'b, A, B> PartialEq<CowVec<'a, A>> for $rhs where A: Clone, B: PartialEq<A> {
1343             #[inline]
1344             fn eq(&self, other: &CowVec<'a, A>) -> bool { PartialEq::eq(&**self, &**other) }
1345             #[inline]
1346             fn ne(&self, other: &CowVec<'a, A>) -> bool { PartialEq::ne(&**self, &**other) }
1347         }
1348     }
1349 }
1350
1351 impl_eq_for_cowvec! { &'b [B] }
1352 impl_eq_for_cowvec! { &'b mut [B] }
1353
1354 #[unstable = "waiting on PartialOrd stability"]
1355 impl<T: PartialOrd> PartialOrd for Vec<T> {
1356     #[inline]
1357     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
1358         self.as_slice().partial_cmp(other.as_slice())
1359     }
1360 }
1361
1362 #[unstable = "waiting on Eq stability"]
1363 impl<T: Eq> Eq for Vec<T> {}
1364
1365 #[unstable = "waiting on Ord stability"]
1366 impl<T: Ord> Ord for Vec<T> {
1367     #[inline]
1368     fn cmp(&self, other: &Vec<T>) -> Ordering {
1369         self.as_slice().cmp(other.as_slice())
1370     }
1371 }
1372
1373 impl<T> AsSlice<T> for Vec<T> {
1374     /// Returns a slice into `self`.
1375     ///
1376     /// # Examples
1377     ///
1378     /// ```
1379     /// fn foo(slice: &[int]) {}
1380     ///
1381     /// let vec = vec![1i, 2];
1382     /// foo(vec.as_slice());
1383     /// ```
1384     #[inline]
1385     #[stable]
1386     fn as_slice<'a>(&'a self) -> &'a [T] {
1387         unsafe {
1388             mem::transmute(RawSlice {
1389                 data: *self.ptr as *const T,
1390                 len: self.len
1391             })
1392         }
1393     }
1394 }
1395
1396 #[unstable = "recent addition, needs more experience"]
1397 impl<'a, T: Clone> Add<&'a [T]> for Vec<T> {
1398     type Output = Vec<T>;
1399
1400     #[inline]
1401     fn add(mut self, rhs: &[T]) -> Vec<T> {
1402         self.push_all(rhs);
1403         self
1404     }
1405 }
1406
1407 #[unsafe_destructor]
1408 #[stable]
1409 impl<T> Drop for Vec<T> {
1410     fn drop(&mut self) {
1411         // This is (and should always remain) a no-op if the fields are
1412         // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1413         if self.cap != 0 {
1414             unsafe {
1415                 for x in self.iter() {
1416                     ptr::read(x);
1417                 }
1418                 dealloc(*self.ptr, self.cap)
1419             }
1420         }
1421     }
1422 }
1423
1424 #[stable]
1425 impl<T> Default for Vec<T> {
1426     #[stable]
1427     fn default() -> Vec<T> {
1428         Vec::new()
1429     }
1430 }
1431
1432 #[experimental = "waiting on Show stability"]
1433 impl<T:fmt::Show> fmt::Show for Vec<T> {
1434     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1435         self.as_slice().fmt(f)
1436     }
1437 }
1438
1439 impl<'a> fmt::Writer for Vec<u8> {
1440     fn write_str(&mut self, s: &str) -> fmt::Result {
1441         self.push_all(s.as_bytes());
1442         Ok(())
1443     }
1444 }
1445
1446 ////////////////////////////////////////////////////////////////////////////////
1447 // Clone-on-write
1448 ////////////////////////////////////////////////////////////////////////////////
1449
1450 #[experimental = "unclear how valuable this alias is"]
1451 /// A clone-on-write vector
1452 pub type CowVec<'a, T> = Cow<'a, Vec<T>, [T]>;
1453
1454 #[unstable]
1455 impl<'a, T> FromIterator<T> for CowVec<'a, T> where T: Clone {
1456     fn from_iter<I: Iterator<Item=T>>(it: I) -> CowVec<'a, T> {
1457         Cow::Owned(FromIterator::from_iter(it))
1458     }
1459 }
1460
1461 impl<'a, T: 'a> IntoCow<'a, Vec<T>, [T]> for Vec<T> where T: Clone {
1462     fn into_cow(self) -> CowVec<'a, T> {
1463         Cow::Owned(self)
1464     }
1465 }
1466
1467 impl<'a, T> IntoCow<'a, Vec<T>, [T]> for &'a [T] where T: Clone {
1468     fn into_cow(self) -> CowVec<'a, T> {
1469         Cow::Borrowed(self)
1470     }
1471 }
1472
1473 ////////////////////////////////////////////////////////////////////////////////
1474 // Iterators
1475 ////////////////////////////////////////////////////////////////////////////////
1476
1477 /// An iterator that moves out of a vector.
1478 #[stable]
1479 pub struct IntoIter<T> {
1480     allocation: *mut T, // the block of memory allocated for the vector
1481     cap: uint, // the capacity of the vector
1482     ptr: *const T,
1483     end: *const T
1484 }
1485
1486 impl<T> IntoIter<T> {
1487     #[inline]
1488     /// Drops all items that have not yet been moved and returns the empty vector.
1489     #[unstable]
1490     pub fn into_inner(mut self) -> Vec<T> {
1491         unsafe {
1492             for _x in self { }
1493             let IntoIter { allocation, cap, ptr: _ptr, end: _end } = self;
1494             mem::forget(self);
1495             Vec { ptr: NonZero::new(allocation), cap: cap, len: 0 }
1496         }
1497     }
1498 }
1499
1500 #[stable]
1501 impl<T> Iterator for IntoIter<T> {
1502     type Item = T;
1503
1504     #[inline]
1505     fn next<'a>(&'a mut self) -> Option<T> {
1506         unsafe {
1507             if self.ptr == self.end {
1508                 None
1509             } else {
1510                 if mem::size_of::<T>() == 0 {
1511                     // purposefully don't use 'ptr.offset' because for
1512                     // vectors with 0-size elements this would return the
1513                     // same pointer.
1514                     self.ptr = mem::transmute(self.ptr as uint + 1);
1515
1516                     // Use a non-null pointer value
1517                     Some(ptr::read(mem::transmute(1u)))
1518                 } else {
1519                     let old = self.ptr;
1520                     self.ptr = self.ptr.offset(1);
1521
1522                     Some(ptr::read(old))
1523                 }
1524             }
1525         }
1526     }
1527
1528     #[inline]
1529     fn size_hint(&self) -> (uint, Option<uint>) {
1530         let diff = (self.end as uint) - (self.ptr as uint);
1531         let size = mem::size_of::<T>();
1532         let exact = diff / (if size == 0 {1} else {size});
1533         (exact, Some(exact))
1534     }
1535 }
1536
1537 #[stable]
1538 impl<T> DoubleEndedIterator for IntoIter<T> {
1539     #[inline]
1540     fn next_back<'a>(&'a mut self) -> Option<T> {
1541         unsafe {
1542             if self.end == self.ptr {
1543                 None
1544             } else {
1545                 if mem::size_of::<T>() == 0 {
1546                     // See above for why 'ptr.offset' isn't used
1547                     self.end = mem::transmute(self.end as uint - 1);
1548
1549                     // Use a non-null pointer value
1550                     Some(ptr::read(mem::transmute(1u)))
1551                 } else {
1552                     self.end = self.end.offset(-1);
1553
1554                     Some(ptr::read(mem::transmute(self.end)))
1555                 }
1556             }
1557         }
1558     }
1559 }
1560
1561 #[stable]
1562 impl<T> ExactSizeIterator for IntoIter<T> {}
1563
1564 #[unsafe_destructor]
1565 #[stable]
1566 impl<T> Drop for IntoIter<T> {
1567     fn drop(&mut self) {
1568         // destroy the remaining elements
1569         if self.cap != 0 {
1570             for _x in *self {}
1571             unsafe {
1572                 dealloc(self.allocation, self.cap);
1573             }
1574         }
1575     }
1576 }
1577
1578 /// An iterator that drains a vector.
1579 #[unsafe_no_drop_flag]
1580 #[unstable = "recently added as part of collections reform 2"]
1581 pub struct Drain<'a, T> {
1582     ptr: *const T,
1583     end: *const T,
1584     marker: ContravariantLifetime<'a>,
1585 }
1586
1587 #[stable]
1588 impl<'a, T> Iterator for Drain<'a, T> {
1589     type Item = T;
1590
1591     #[inline]
1592     fn next(&mut self) -> Option<T> {
1593         unsafe {
1594             if self.ptr == self.end {
1595                 None
1596             } else {
1597                 if mem::size_of::<T>() == 0 {
1598                     // purposefully don't use 'ptr.offset' because for
1599                     // vectors with 0-size elements this would return the
1600                     // same pointer.
1601                     self.ptr = mem::transmute(self.ptr as uint + 1);
1602
1603                     // Use a non-null pointer value
1604                     Some(ptr::read(mem::transmute(1u)))
1605                 } else {
1606                     let old = self.ptr;
1607                     self.ptr = self.ptr.offset(1);
1608
1609                     Some(ptr::read(old))
1610                 }
1611             }
1612         }
1613     }
1614
1615     #[inline]
1616     fn size_hint(&self) -> (uint, Option<uint>) {
1617         let diff = (self.end as uint) - (self.ptr as uint);
1618         let size = mem::size_of::<T>();
1619         let exact = diff / (if size == 0 {1} else {size});
1620         (exact, Some(exact))
1621     }
1622 }
1623
1624 #[stable]
1625 impl<'a, T> DoubleEndedIterator for Drain<'a, T> {
1626     #[inline]
1627     fn next_back(&mut self) -> Option<T> {
1628         unsafe {
1629             if self.end == self.ptr {
1630                 None
1631             } else {
1632                 if mem::size_of::<T>() == 0 {
1633                     // See above for why 'ptr.offset' isn't used
1634                     self.end = mem::transmute(self.end as uint - 1);
1635
1636                     // Use a non-null pointer value
1637                     Some(ptr::read(mem::transmute(1u)))
1638                 } else {
1639                     self.end = self.end.offset(-1);
1640
1641                     Some(ptr::read(self.end))
1642                 }
1643             }
1644         }
1645     }
1646 }
1647
1648 #[stable]
1649 impl<'a, T> ExactSizeIterator for Drain<'a, T> {}
1650
1651 #[unsafe_destructor]
1652 #[stable]
1653 impl<'a, T> Drop for Drain<'a, T> {
1654     fn drop(&mut self) {
1655         // self.ptr == self.end == null if drop has already been called,
1656         // so we can use #[unsafe_no_drop_flag].
1657
1658         // destroy the remaining elements
1659         for _x in *self {}
1660     }
1661 }
1662
1663 ////////////////////////////////////////////////////////////////////////////////
1664 // Conversion from &[T] to &Vec<T>
1665 ////////////////////////////////////////////////////////////////////////////////
1666
1667 /// Wrapper type providing a `&Vec<T>` reference via `Deref`.
1668 #[experimental]
1669 pub struct DerefVec<'a, T> {
1670     x: Vec<T>,
1671     l: ContravariantLifetime<'a>
1672 }
1673
1674 #[experimental]
1675 impl<'a, T> Deref for DerefVec<'a, T> {
1676     type Target = Vec<T>;
1677
1678     fn deref<'b>(&'b self) -> &'b Vec<T> {
1679         &self.x
1680     }
1681 }
1682
1683 // Prevent the inner `Vec<T>` from attempting to deallocate memory.
1684 #[unsafe_destructor]
1685 #[stable]
1686 impl<'a, T> Drop for DerefVec<'a, T> {
1687     fn drop(&mut self) {
1688         self.x.len = 0;
1689         self.x.cap = 0;
1690     }
1691 }
1692
1693 /// Convert a slice to a wrapper type providing a `&Vec<T>` reference.
1694 #[experimental]
1695 pub fn as_vec<'a, T>(x: &'a [T]) -> DerefVec<'a, T> {
1696     unsafe {
1697         DerefVec {
1698             x: Vec::from_raw_parts(x.as_ptr() as *mut T, x.len(), x.len()),
1699             l: ContravariantLifetime::<'a>
1700         }
1701     }
1702 }
1703
1704 ////////////////////////////////////////////////////////////////////////////////
1705 // Partial vec, used for map_in_place
1706 ////////////////////////////////////////////////////////////////////////////////
1707
1708 /// An owned, partially type-converted vector of elements with non-zero size.
1709 ///
1710 /// `T` and `U` must have the same, non-zero size. They must also have the same
1711 /// alignment.
1712 ///
1713 /// When the destructor of this struct runs, all `U`s from `start_u` (incl.) to
1714 /// `end_u` (excl.) and all `T`s from `start_t` (incl.) to `end_t` (excl.) are
1715 /// destructed. Additionally the underlying storage of `vec` will be freed.
1716 struct PartialVecNonZeroSized<T,U> {
1717     vec: Vec<T>,
1718
1719     start_u: *mut U,
1720     end_u: *mut U,
1721     start_t: *mut T,
1722     end_t: *mut T,
1723 }
1724
1725 /// An owned, partially type-converted vector of zero-sized elements.
1726 ///
1727 /// When the destructor of this struct runs, all `num_t` `T`s and `num_u` `U`s
1728 /// are destructed.
1729 struct PartialVecZeroSized<T,U> {
1730     num_t: uint,
1731     num_u: uint,
1732     marker_t: InvariantType<T>,
1733     marker_u: InvariantType<U>,
1734 }
1735
1736 #[unsafe_destructor]
1737 impl<T,U> Drop for PartialVecNonZeroSized<T,U> {
1738     fn drop(&mut self) {
1739         unsafe {
1740             // `vec` hasn't been modified until now. As it has a length
1741             // currently, this would run destructors of `T`s which might not be
1742             // there. So at first, set `vec`s length to `0`. This must be done
1743             // at first to remain memory-safe as the destructors of `U` or `T`
1744             // might cause unwinding where `vec`s destructor would be executed.
1745             self.vec.set_len(0);
1746
1747             // We have instances of `U`s and `T`s in `vec`. Destruct them.
1748             while self.start_u != self.end_u {
1749                 let _ = ptr::read(self.start_u as *const U); // Run a `U` destructor.
1750                 self.start_u = self.start_u.offset(1);
1751             }
1752             while self.start_t != self.end_t {
1753                 let _ = ptr::read(self.start_t as *const T); // Run a `T` destructor.
1754                 self.start_t = self.start_t.offset(1);
1755             }
1756             // After this destructor ran, the destructor of `vec` will run,
1757             // deallocating the underlying memory.
1758         }
1759     }
1760 }
1761
1762 #[unsafe_destructor]
1763 impl<T,U> Drop for PartialVecZeroSized<T,U> {
1764     fn drop(&mut self) {
1765         unsafe {
1766             // Destruct the instances of `T` and `U` this struct owns.
1767             while self.num_t != 0 {
1768                 let _: T = mem::uninitialized(); // Run a `T` destructor.
1769                 self.num_t -= 1;
1770             }
1771             while self.num_u != 0 {
1772                 let _: U = mem::uninitialized(); // Run a `U` destructor.
1773                 self.num_u -= 1;
1774             }
1775         }
1776     }
1777 }
1778
1779 #[cfg(test)]
1780 mod tests {
1781     use prelude::*;
1782     use core::mem::size_of;
1783     use core::iter::repeat;
1784     use test::Bencher;
1785     use super::as_vec;
1786
1787     struct DropCounter<'a> {
1788         count: &'a mut int
1789     }
1790
1791     #[unsafe_destructor]
1792     impl<'a> Drop for DropCounter<'a> {
1793         fn drop(&mut self) {
1794             *self.count += 1;
1795         }
1796     }
1797
1798     #[test]
1799     fn test_as_vec() {
1800         let xs = [1u8, 2u8, 3u8];
1801         assert_eq!(as_vec(&xs).as_slice(), xs);
1802     }
1803
1804     #[test]
1805     fn test_as_vec_dtor() {
1806         let (mut count_x, mut count_y) = (0, 0);
1807         {
1808             let xs = &[DropCounter { count: &mut count_x }, DropCounter { count: &mut count_y }];
1809             assert_eq!(as_vec(xs).len(), 2);
1810         }
1811         assert_eq!(count_x, 1);
1812         assert_eq!(count_y, 1);
1813     }
1814
1815     #[test]
1816     fn test_small_vec_struct() {
1817         assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1818     }
1819
1820     #[test]
1821     fn test_double_drop() {
1822         struct TwoVec<T> {
1823             x: Vec<T>,
1824             y: Vec<T>
1825         }
1826
1827         let (mut count_x, mut count_y) = (0, 0);
1828         {
1829             let mut tv = TwoVec {
1830                 x: Vec::new(),
1831                 y: Vec::new()
1832             };
1833             tv.x.push(DropCounter {count: &mut count_x});
1834             tv.y.push(DropCounter {count: &mut count_y});
1835
1836             // If Vec had a drop flag, here is where it would be zeroed.
1837             // Instead, it should rely on its internal state to prevent
1838             // doing anything significant when dropped multiple times.
1839             drop(tv.x);
1840
1841             // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1842         }
1843
1844         assert_eq!(count_x, 1);
1845         assert_eq!(count_y, 1);
1846     }
1847
1848     #[test]
1849     fn test_reserve() {
1850         let mut v = Vec::new();
1851         assert_eq!(v.capacity(), 0);
1852
1853         v.reserve(2);
1854         assert!(v.capacity() >= 2);
1855
1856         for i in range(0i, 16) {
1857             v.push(i);
1858         }
1859
1860         assert!(v.capacity() >= 16);
1861         v.reserve(16);
1862         assert!(v.capacity() >= 32);
1863
1864         v.push(16);
1865
1866         v.reserve(16);
1867         assert!(v.capacity() >= 33)
1868     }
1869
1870     #[test]
1871     fn test_extend() {
1872         let mut v = Vec::new();
1873         let mut w = Vec::new();
1874
1875         v.extend(range(0i, 3));
1876         for i in range(0i, 3) { w.push(i) }
1877
1878         assert_eq!(v, w);
1879
1880         v.extend(range(3i, 10));
1881         for i in range(3i, 10) { w.push(i) }
1882
1883         assert_eq!(v, w);
1884     }
1885
1886     #[test]
1887     fn test_slice_from_mut() {
1888         let mut values = vec![1u8,2,3,4,5];
1889         {
1890             let slice = values.slice_from_mut(2);
1891             assert!(slice == [3, 4, 5]);
1892             for p in slice.iter_mut() {
1893                 *p += 2;
1894             }
1895         }
1896
1897         assert!(values == [1, 2, 5, 6, 7]);
1898     }
1899
1900     #[test]
1901     fn test_slice_to_mut() {
1902         let mut values = vec![1u8,2,3,4,5];
1903         {
1904             let slice = values.slice_to_mut(2);
1905             assert!(slice == [1, 2]);
1906             for p in slice.iter_mut() {
1907                 *p += 1;
1908             }
1909         }
1910
1911         assert!(values == [2, 3, 3, 4, 5]);
1912     }
1913
1914     #[test]
1915     fn test_split_at_mut() {
1916         let mut values = vec![1u8,2,3,4,5];
1917         {
1918             let (left, right) = values.split_at_mut(2);
1919             {
1920                 let left: &[_] = left;
1921                 assert!(left[0..left.len()] == [1, 2][]);
1922             }
1923             for p in left.iter_mut() {
1924                 *p += 1;
1925             }
1926
1927             {
1928                 let right: &[_] = right;
1929                 assert!(right[0..right.len()] == [3, 4, 5][]);
1930             }
1931             for p in right.iter_mut() {
1932                 *p += 2;
1933             }
1934         }
1935
1936         assert!(values == vec![2u8, 3, 5, 6, 7]);
1937     }
1938
1939     #[test]
1940     fn test_clone() {
1941         let v: Vec<int> = vec!();
1942         let w = vec!(1i, 2, 3);
1943
1944         assert_eq!(v, v.clone());
1945
1946         let z = w.clone();
1947         assert_eq!(w, z);
1948         // they should be disjoint in memory.
1949         assert!(w.as_ptr() != z.as_ptr())
1950     }
1951
1952     #[test]
1953     fn test_clone_from() {
1954         let mut v = vec!();
1955         let three = vec!(box 1i, box 2, box 3);
1956         let two = vec!(box 4i, box 5);
1957         // zero, long
1958         v.clone_from(&three);
1959         assert_eq!(v, three);
1960
1961         // equal
1962         v.clone_from(&three);
1963         assert_eq!(v, three);
1964
1965         // long, short
1966         v.clone_from(&two);
1967         assert_eq!(v, two);
1968
1969         // short, long
1970         v.clone_from(&three);
1971         assert_eq!(v, three)
1972     }
1973
1974     #[test]
1975     fn test_retain() {
1976         let mut vec = vec![1u, 2, 3, 4];
1977         vec.retain(|&x| x % 2 == 0);
1978         assert!(vec == vec![2u, 4]);
1979     }
1980
1981     #[test]
1982     fn zero_sized_values() {
1983         let mut v = Vec::new();
1984         assert_eq!(v.len(), 0);
1985         v.push(());
1986         assert_eq!(v.len(), 1);
1987         v.push(());
1988         assert_eq!(v.len(), 2);
1989         assert_eq!(v.pop(), Some(()));
1990         assert_eq!(v.pop(), Some(()));
1991         assert_eq!(v.pop(), None);
1992
1993         assert_eq!(v.iter().count(), 0);
1994         v.push(());
1995         assert_eq!(v.iter().count(), 1);
1996         v.push(());
1997         assert_eq!(v.iter().count(), 2);
1998
1999         for &() in v.iter() {}
2000
2001         assert_eq!(v.iter_mut().count(), 2);
2002         v.push(());
2003         assert_eq!(v.iter_mut().count(), 3);
2004         v.push(());
2005         assert_eq!(v.iter_mut().count(), 4);
2006
2007         for &() in v.iter_mut() {}
2008         unsafe { v.set_len(0); }
2009         assert_eq!(v.iter_mut().count(), 0);
2010     }
2011
2012     #[test]
2013     fn test_partition() {
2014         assert_eq!(vec![].into_iter().partition(|x: &int| *x < 3), (vec![], vec![]));
2015         assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
2016         assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
2017         assert_eq!(vec![1i, 2, 3].into_iter().partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
2018     }
2019
2020     #[test]
2021     fn test_zip_unzip() {
2022         let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
2023
2024         let (left, right): (Vec<_>, Vec<_>) = z1.iter().map(|&x| x).unzip();
2025
2026         assert_eq!((1, 4), (left[0], right[0]));
2027         assert_eq!((2, 5), (left[1], right[1]));
2028         assert_eq!((3, 6), (left[2], right[2]));
2029     }
2030
2031     #[test]
2032     fn test_unsafe_ptrs() {
2033         unsafe {
2034             // Test on-stack copy-from-buf.
2035             let a = [1i, 2, 3];
2036             let ptr = a.as_ptr();
2037             let b = Vec::from_raw_buf(ptr, 3u);
2038             assert_eq!(b, vec![1, 2, 3]);
2039
2040             // Test on-heap copy-from-buf.
2041             let c = vec![1i, 2, 3, 4, 5];
2042             let ptr = c.as_ptr();
2043             let d = Vec::from_raw_buf(ptr, 5u);
2044             assert_eq!(d, vec![1, 2, 3, 4, 5]);
2045         }
2046     }
2047
2048     #[test]
2049     fn test_vec_truncate_drop() {
2050         static mut drops: uint = 0;
2051         struct Elem(int);
2052         impl Drop for Elem {
2053             fn drop(&mut self) {
2054                 unsafe { drops += 1; }
2055             }
2056         }
2057
2058         let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
2059         assert_eq!(unsafe { drops }, 0);
2060         v.truncate(3);
2061         assert_eq!(unsafe { drops }, 2);
2062         v.truncate(0);
2063         assert_eq!(unsafe { drops }, 5);
2064     }
2065
2066     #[test]
2067     #[should_fail]
2068     fn test_vec_truncate_fail() {
2069         struct BadElem(int);
2070         impl Drop for BadElem {
2071             fn drop(&mut self) {
2072                 let BadElem(ref mut x) = *self;
2073                 if *x == 0xbadbeef {
2074                     panic!("BadElem panic: 0xbadbeef")
2075                 }
2076             }
2077         }
2078
2079         let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
2080         v.truncate(0);
2081     }
2082
2083     #[test]
2084     fn test_index() {
2085         let vec = vec!(1i, 2, 3);
2086         assert!(vec[1] == 2);
2087     }
2088
2089     #[test]
2090     #[should_fail]
2091     fn test_index_out_of_bounds() {
2092         let vec = vec!(1i, 2, 3);
2093         let _ = vec[3];
2094     }
2095
2096     #[test]
2097     #[should_fail]
2098     fn test_slice_out_of_bounds_1() {
2099         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2100         x[-1..];
2101     }
2102
2103     #[test]
2104     #[should_fail]
2105     fn test_slice_out_of_bounds_2() {
2106         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2107         x[..6];
2108     }
2109
2110     #[test]
2111     #[should_fail]
2112     fn test_slice_out_of_bounds_3() {
2113         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2114         x[-1..4];
2115     }
2116
2117     #[test]
2118     #[should_fail]
2119     fn test_slice_out_of_bounds_4() {
2120         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2121         x[1..6];
2122     }
2123
2124     #[test]
2125     #[should_fail]
2126     fn test_slice_out_of_bounds_5() {
2127         let x: Vec<int> = vec![1, 2, 3, 4, 5];
2128         x[3..2];
2129     }
2130
2131     #[test]
2132     #[should_fail]
2133     fn test_swap_remove_empty() {
2134         let mut vec: Vec<uint> = vec!();
2135         vec.swap_remove(0);
2136     }
2137
2138     #[test]
2139     fn test_move_iter_unwrap() {
2140         let mut vec: Vec<uint> = Vec::with_capacity(7);
2141         vec.push(1);
2142         vec.push(2);
2143         let ptr = vec.as_ptr();
2144         vec = vec.into_iter().into_inner();
2145         assert_eq!(vec.as_ptr(), ptr);
2146         assert_eq!(vec.capacity(), 7);
2147         assert_eq!(vec.len(), 0);
2148     }
2149
2150     #[test]
2151     #[should_fail]
2152     fn test_map_in_place_incompatible_types_fail() {
2153         let v = vec![0u, 1, 2];
2154         v.map_in_place(|_| ());
2155     }
2156
2157     #[test]
2158     fn test_map_in_place() {
2159         let v = vec![0u, 1, 2];
2160         assert_eq!(v.map_in_place(|i: uint| i as int - 1), [-1i, 0, 1]);
2161     }
2162
2163     #[test]
2164     fn test_map_in_place_zero_sized() {
2165         let v = vec![(), ()];
2166         #[derive(PartialEq, Show)]
2167         struct ZeroSized;
2168         assert_eq!(v.map_in_place(|_| ZeroSized), [ZeroSized, ZeroSized]);
2169     }
2170
2171     #[test]
2172     fn test_map_in_place_zero_drop_count() {
2173         use std::sync::atomic::{AtomicUint, Ordering, ATOMIC_UINT_INIT};
2174
2175         #[derive(Clone, PartialEq, Show)]
2176         struct Nothing;
2177         impl Drop for Nothing { fn drop(&mut self) { } }
2178
2179         #[derive(Clone, PartialEq, Show)]
2180         struct ZeroSized;
2181         impl Drop for ZeroSized {
2182             fn drop(&mut self) {
2183                 DROP_COUNTER.fetch_add(1, Ordering::Relaxed);
2184             }
2185         }
2186         const NUM_ELEMENTS: uint = 2;
2187         static DROP_COUNTER: AtomicUint = ATOMIC_UINT_INIT;
2188
2189         let v = repeat(Nothing).take(NUM_ELEMENTS).collect::<Vec<_>>();
2190
2191         DROP_COUNTER.store(0, Ordering::Relaxed);
2192
2193         let v = v.map_in_place(|_| ZeroSized);
2194         assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), 0);
2195         drop(v);
2196         assert_eq!(DROP_COUNTER.load(Ordering::Relaxed), NUM_ELEMENTS);
2197     }
2198
2199     #[test]
2200     fn test_move_items() {
2201         let vec = vec![1, 2, 3];
2202         let mut vec2 : Vec<i32> = vec![];
2203         for i in vec.into_iter() {
2204             vec2.push(i);
2205         }
2206         assert!(vec2 == vec![1, 2, 3]);
2207     }
2208
2209     #[test]
2210     fn test_move_items_reverse() {
2211         let vec = vec![1, 2, 3];
2212         let mut vec2 : Vec<i32> = vec![];
2213         for i in vec.into_iter().rev() {
2214             vec2.push(i);
2215         }
2216         assert!(vec2 == vec![3, 2, 1]);
2217     }
2218
2219     #[test]
2220     fn test_move_items_zero_sized() {
2221         let vec = vec![(), (), ()];
2222         let mut vec2 : Vec<()> = vec![];
2223         for i in vec.into_iter() {
2224             vec2.push(i);
2225         }
2226         assert!(vec2 == vec![(), (), ()]);
2227     }
2228
2229     #[test]
2230     fn test_drain_items() {
2231         let mut vec = vec![1, 2, 3];
2232         let mut vec2: Vec<i32> = vec![];
2233         for i in vec.drain() {
2234             vec2.push(i);
2235         }
2236         assert_eq!(vec, []);
2237         assert_eq!(vec2, [ 1, 2, 3 ]);
2238     }
2239
2240     #[test]
2241     fn test_drain_items_reverse() {
2242         let mut vec = vec![1, 2, 3];
2243         let mut vec2: Vec<i32> = vec![];
2244         for i in vec.drain().rev() {
2245             vec2.push(i);
2246         }
2247         assert_eq!(vec, []);
2248         assert_eq!(vec2, [ 3, 2, 1 ]);
2249     }
2250
2251     #[test]
2252     fn test_drain_items_zero_sized() {
2253         let mut vec = vec![(), (), ()];
2254         let mut vec2: Vec<()> = vec![];
2255         for i in vec.drain() {
2256             vec2.push(i);
2257         }
2258         assert_eq!(vec, []);
2259         assert_eq!(vec2, [(), (), ()]);
2260     }
2261
2262     #[test]
2263     fn test_into_boxed_slice() {
2264         let xs = vec![1u, 2, 3];
2265         let ys = xs.into_boxed_slice();
2266         assert_eq!(ys.as_slice(), [1u, 2, 3]);
2267     }
2268
2269     #[bench]
2270     fn bench_new(b: &mut Bencher) {
2271         b.iter(|| {
2272             let v: Vec<uint> = Vec::new();
2273             assert_eq!(v.len(), 0);
2274             assert_eq!(v.capacity(), 0);
2275         })
2276     }
2277
2278     fn do_bench_with_capacity(b: &mut Bencher, src_len: uint) {
2279         b.bytes = src_len as u64;
2280
2281         b.iter(|| {
2282             let v: Vec<uint> = Vec::with_capacity(src_len);
2283             assert_eq!(v.len(), 0);
2284             assert_eq!(v.capacity(), src_len);
2285         })
2286     }
2287
2288     #[bench]
2289     fn bench_with_capacity_0000(b: &mut Bencher) {
2290         do_bench_with_capacity(b, 0)
2291     }
2292
2293     #[bench]
2294     fn bench_with_capacity_0010(b: &mut Bencher) {
2295         do_bench_with_capacity(b, 10)
2296     }
2297
2298     #[bench]
2299     fn bench_with_capacity_0100(b: &mut Bencher) {
2300         do_bench_with_capacity(b, 100)
2301     }
2302
2303     #[bench]
2304     fn bench_with_capacity_1000(b: &mut Bencher) {
2305         do_bench_with_capacity(b, 1000)
2306     }
2307
2308     fn do_bench_from_fn(b: &mut Bencher, src_len: uint) {
2309         b.bytes = src_len as u64;
2310
2311         b.iter(|| {
2312             let dst = range(0, src_len).collect::<Vec<_>>();
2313             assert_eq!(dst.len(), src_len);
2314             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2315         })
2316     }
2317
2318     #[bench]
2319     fn bench_from_fn_0000(b: &mut Bencher) {
2320         do_bench_from_fn(b, 0)
2321     }
2322
2323     #[bench]
2324     fn bench_from_fn_0010(b: &mut Bencher) {
2325         do_bench_from_fn(b, 10)
2326     }
2327
2328     #[bench]
2329     fn bench_from_fn_0100(b: &mut Bencher) {
2330         do_bench_from_fn(b, 100)
2331     }
2332
2333     #[bench]
2334     fn bench_from_fn_1000(b: &mut Bencher) {
2335         do_bench_from_fn(b, 1000)
2336     }
2337
2338     fn do_bench_from_elem(b: &mut Bencher, src_len: uint) {
2339         b.bytes = src_len as u64;
2340
2341         b.iter(|| {
2342             let dst: Vec<uint> = repeat(5).take(src_len).collect();
2343             assert_eq!(dst.len(), src_len);
2344             assert!(dst.iter().all(|x| *x == 5));
2345         })
2346     }
2347
2348     #[bench]
2349     fn bench_from_elem_0000(b: &mut Bencher) {
2350         do_bench_from_elem(b, 0)
2351     }
2352
2353     #[bench]
2354     fn bench_from_elem_0010(b: &mut Bencher) {
2355         do_bench_from_elem(b, 10)
2356     }
2357
2358     #[bench]
2359     fn bench_from_elem_0100(b: &mut Bencher) {
2360         do_bench_from_elem(b, 100)
2361     }
2362
2363     #[bench]
2364     fn bench_from_elem_1000(b: &mut Bencher) {
2365         do_bench_from_elem(b, 1000)
2366     }
2367
2368     fn do_bench_from_slice(b: &mut Bencher, src_len: uint) {
2369         let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2370
2371         b.bytes = src_len as u64;
2372
2373         b.iter(|| {
2374             let dst = src.clone().as_slice().to_vec();
2375             assert_eq!(dst.len(), src_len);
2376             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2377         });
2378     }
2379
2380     #[bench]
2381     fn bench_from_slice_0000(b: &mut Bencher) {
2382         do_bench_from_slice(b, 0)
2383     }
2384
2385     #[bench]
2386     fn bench_from_slice_0010(b: &mut Bencher) {
2387         do_bench_from_slice(b, 10)
2388     }
2389
2390     #[bench]
2391     fn bench_from_slice_0100(b: &mut Bencher) {
2392         do_bench_from_slice(b, 100)
2393     }
2394
2395     #[bench]
2396     fn bench_from_slice_1000(b: &mut Bencher) {
2397         do_bench_from_slice(b, 1000)
2398     }
2399
2400     fn do_bench_from_iter(b: &mut Bencher, src_len: uint) {
2401         let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2402
2403         b.bytes = src_len as u64;
2404
2405         b.iter(|| {
2406             let dst: Vec<uint> = FromIterator::from_iter(src.clone().into_iter());
2407             assert_eq!(dst.len(), src_len);
2408             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2409         });
2410     }
2411
2412     #[bench]
2413     fn bench_from_iter_0000(b: &mut Bencher) {
2414         do_bench_from_iter(b, 0)
2415     }
2416
2417     #[bench]
2418     fn bench_from_iter_0010(b: &mut Bencher) {
2419         do_bench_from_iter(b, 10)
2420     }
2421
2422     #[bench]
2423     fn bench_from_iter_0100(b: &mut Bencher) {
2424         do_bench_from_iter(b, 100)
2425     }
2426
2427     #[bench]
2428     fn bench_from_iter_1000(b: &mut Bencher) {
2429         do_bench_from_iter(b, 1000)
2430     }
2431
2432     fn do_bench_extend(b: &mut Bencher, dst_len: uint, src_len: uint) {
2433         let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2434         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2435
2436         b.bytes = src_len as u64;
2437
2438         b.iter(|| {
2439             let mut dst = dst.clone();
2440             dst.extend(src.clone().into_iter());
2441             assert_eq!(dst.len(), dst_len + src_len);
2442             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2443         });
2444     }
2445
2446     #[bench]
2447     fn bench_extend_0000_0000(b: &mut Bencher) {
2448         do_bench_extend(b, 0, 0)
2449     }
2450
2451     #[bench]
2452     fn bench_extend_0000_0010(b: &mut Bencher) {
2453         do_bench_extend(b, 0, 10)
2454     }
2455
2456     #[bench]
2457     fn bench_extend_0000_0100(b: &mut Bencher) {
2458         do_bench_extend(b, 0, 100)
2459     }
2460
2461     #[bench]
2462     fn bench_extend_0000_1000(b: &mut Bencher) {
2463         do_bench_extend(b, 0, 1000)
2464     }
2465
2466     #[bench]
2467     fn bench_extend_0010_0010(b: &mut Bencher) {
2468         do_bench_extend(b, 10, 10)
2469     }
2470
2471     #[bench]
2472     fn bench_extend_0100_0100(b: &mut Bencher) {
2473         do_bench_extend(b, 100, 100)
2474     }
2475
2476     #[bench]
2477     fn bench_extend_1000_1000(b: &mut Bencher) {
2478         do_bench_extend(b, 1000, 1000)
2479     }
2480
2481     fn do_bench_push_all(b: &mut Bencher, dst_len: uint, src_len: uint) {
2482         let dst: Vec<uint> = FromIterator::from_iter(range(0, dst_len));
2483         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2484
2485         b.bytes = src_len as u64;
2486
2487         b.iter(|| {
2488             let mut dst = dst.clone();
2489             dst.push_all(src.as_slice());
2490             assert_eq!(dst.len(), dst_len + src_len);
2491             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2492         });
2493     }
2494
2495     #[bench]
2496     fn bench_push_all_0000_0000(b: &mut Bencher) {
2497         do_bench_push_all(b, 0, 0)
2498     }
2499
2500     #[bench]
2501     fn bench_push_all_0000_0010(b: &mut Bencher) {
2502         do_bench_push_all(b, 0, 10)
2503     }
2504
2505     #[bench]
2506     fn bench_push_all_0000_0100(b: &mut Bencher) {
2507         do_bench_push_all(b, 0, 100)
2508     }
2509
2510     #[bench]
2511     fn bench_push_all_0000_1000(b: &mut Bencher) {
2512         do_bench_push_all(b, 0, 1000)
2513     }
2514
2515     #[bench]
2516     fn bench_push_all_0010_0010(b: &mut Bencher) {
2517         do_bench_push_all(b, 10, 10)
2518     }
2519
2520     #[bench]
2521     fn bench_push_all_0100_0100(b: &mut Bencher) {
2522         do_bench_push_all(b, 100, 100)
2523     }
2524
2525     #[bench]
2526     fn bench_push_all_1000_1000(b: &mut Bencher) {
2527         do_bench_push_all(b, 1000, 1000)
2528     }
2529
2530     fn do_bench_push_all_move(b: &mut Bencher, dst_len: uint, src_len: uint) {
2531         let dst: Vec<uint> = FromIterator::from_iter(range(0u, dst_len));
2532         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2533
2534         b.bytes = src_len as u64;
2535
2536         b.iter(|| {
2537             let mut dst = dst.clone();
2538             dst.extend(src.clone().into_iter());
2539             assert_eq!(dst.len(), dst_len + src_len);
2540             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2541         });
2542     }
2543
2544     #[bench]
2545     fn bench_push_all_move_0000_0000(b: &mut Bencher) {
2546         do_bench_push_all_move(b, 0, 0)
2547     }
2548
2549     #[bench]
2550     fn bench_push_all_move_0000_0010(b: &mut Bencher) {
2551         do_bench_push_all_move(b, 0, 10)
2552     }
2553
2554     #[bench]
2555     fn bench_push_all_move_0000_0100(b: &mut Bencher) {
2556         do_bench_push_all_move(b, 0, 100)
2557     }
2558
2559     #[bench]
2560     fn bench_push_all_move_0000_1000(b: &mut Bencher) {
2561         do_bench_push_all_move(b, 0, 1000)
2562     }
2563
2564     #[bench]
2565     fn bench_push_all_move_0010_0010(b: &mut Bencher) {
2566         do_bench_push_all_move(b, 10, 10)
2567     }
2568
2569     #[bench]
2570     fn bench_push_all_move_0100_0100(b: &mut Bencher) {
2571         do_bench_push_all_move(b, 100, 100)
2572     }
2573
2574     #[bench]
2575     fn bench_push_all_move_1000_1000(b: &mut Bencher) {
2576         do_bench_push_all_move(b, 1000, 1000)
2577     }
2578
2579     fn do_bench_clone(b: &mut Bencher, src_len: uint) {
2580         let src: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2581
2582         b.bytes = src_len as u64;
2583
2584         b.iter(|| {
2585             let dst = src.clone();
2586             assert_eq!(dst.len(), src_len);
2587             assert!(dst.iter().enumerate().all(|(i, x)| i == *x));
2588         });
2589     }
2590
2591     #[bench]
2592     fn bench_clone_0000(b: &mut Bencher) {
2593         do_bench_clone(b, 0)
2594     }
2595
2596     #[bench]
2597     fn bench_clone_0010(b: &mut Bencher) {
2598         do_bench_clone(b, 10)
2599     }
2600
2601     #[bench]
2602     fn bench_clone_0100(b: &mut Bencher) {
2603         do_bench_clone(b, 100)
2604     }
2605
2606     #[bench]
2607     fn bench_clone_1000(b: &mut Bencher) {
2608         do_bench_clone(b, 1000)
2609     }
2610
2611     fn do_bench_clone_from(b: &mut Bencher, times: uint, dst_len: uint, src_len: uint) {
2612         let dst: Vec<uint> = FromIterator::from_iter(range(0, src_len));
2613         let src: Vec<uint> = FromIterator::from_iter(range(dst_len, dst_len + src_len));
2614
2615         b.bytes = (times * src_len) as u64;
2616
2617         b.iter(|| {
2618             let mut dst = dst.clone();
2619
2620             for _ in range(0, times) {
2621                 dst.clone_from(&src);
2622
2623                 assert_eq!(dst.len(), src_len);
2624                 assert!(dst.iter().enumerate().all(|(i, x)| dst_len + i == *x));
2625             }
2626         });
2627     }
2628
2629     #[bench]
2630     fn bench_clone_from_01_0000_0000(b: &mut Bencher) {
2631         do_bench_clone_from(b, 1, 0, 0)
2632     }
2633
2634     #[bench]
2635     fn bench_clone_from_01_0000_0010(b: &mut Bencher) {
2636         do_bench_clone_from(b, 1, 0, 10)
2637     }
2638
2639     #[bench]
2640     fn bench_clone_from_01_0000_0100(b: &mut Bencher) {
2641         do_bench_clone_from(b, 1, 0, 100)
2642     }
2643
2644     #[bench]
2645     fn bench_clone_from_01_0000_1000(b: &mut Bencher) {
2646         do_bench_clone_from(b, 1, 0, 1000)
2647     }
2648
2649     #[bench]
2650     fn bench_clone_from_01_0010_0010(b: &mut Bencher) {
2651         do_bench_clone_from(b, 1, 10, 10)
2652     }
2653
2654     #[bench]
2655     fn bench_clone_from_01_0100_0100(b: &mut Bencher) {
2656         do_bench_clone_from(b, 1, 100, 100)
2657     }
2658
2659     #[bench]
2660     fn bench_clone_from_01_1000_1000(b: &mut Bencher) {
2661         do_bench_clone_from(b, 1, 1000, 1000)
2662     }
2663
2664     #[bench]
2665     fn bench_clone_from_01_0010_0100(b: &mut Bencher) {
2666         do_bench_clone_from(b, 1, 10, 100)
2667     }
2668
2669     #[bench]
2670     fn bench_clone_from_01_0100_1000(b: &mut Bencher) {
2671         do_bench_clone_from(b, 1, 100, 1000)
2672     }
2673
2674     #[bench]
2675     fn bench_clone_from_01_0010_0000(b: &mut Bencher) {
2676         do_bench_clone_from(b, 1, 10, 0)
2677     }
2678
2679     #[bench]
2680     fn bench_clone_from_01_0100_0010(b: &mut Bencher) {
2681         do_bench_clone_from(b, 1, 100, 10)
2682     }
2683
2684     #[bench]
2685     fn bench_clone_from_01_1000_0100(b: &mut Bencher) {
2686         do_bench_clone_from(b, 1, 1000, 100)
2687     }
2688
2689     #[bench]
2690     fn bench_clone_from_10_0000_0000(b: &mut Bencher) {
2691         do_bench_clone_from(b, 10, 0, 0)
2692     }
2693
2694     #[bench]
2695     fn bench_clone_from_10_0000_0010(b: &mut Bencher) {
2696         do_bench_clone_from(b, 10, 0, 10)
2697     }
2698
2699     #[bench]
2700     fn bench_clone_from_10_0000_0100(b: &mut Bencher) {
2701         do_bench_clone_from(b, 10, 0, 100)
2702     }
2703
2704     #[bench]
2705     fn bench_clone_from_10_0000_1000(b: &mut Bencher) {
2706         do_bench_clone_from(b, 10, 0, 1000)
2707     }
2708
2709     #[bench]
2710     fn bench_clone_from_10_0010_0010(b: &mut Bencher) {
2711         do_bench_clone_from(b, 10, 10, 10)
2712     }
2713
2714     #[bench]
2715     fn bench_clone_from_10_0100_0100(b: &mut Bencher) {
2716         do_bench_clone_from(b, 10, 100, 100)
2717     }
2718
2719     #[bench]
2720     fn bench_clone_from_10_1000_1000(b: &mut Bencher) {
2721         do_bench_clone_from(b, 10, 1000, 1000)
2722     }
2723
2724     #[bench]
2725     fn bench_clone_from_10_0010_0100(b: &mut Bencher) {
2726         do_bench_clone_from(b, 10, 10, 100)
2727     }
2728
2729     #[bench]
2730     fn bench_clone_from_10_0100_1000(b: &mut Bencher) {
2731         do_bench_clone_from(b, 10, 100, 1000)
2732     }
2733
2734     #[bench]
2735     fn bench_clone_from_10_0010_0000(b: &mut Bencher) {
2736         do_bench_clone_from(b, 10, 10, 0)
2737     }
2738
2739     #[bench]
2740     fn bench_clone_from_10_0100_0010(b: &mut Bencher) {
2741         do_bench_clone_from(b, 10, 100, 10)
2742     }
2743
2744     #[bench]
2745     fn bench_clone_from_10_1000_0100(b: &mut Bencher) {
2746         do_bench_clone_from(b, 10, 1000, 100)
2747     }
2748 }