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