]> git.lizzy.rs Git - rust.git/blob - src/libcollections/vec.rs
2ffc168f82c0eef4b4d77244a873ed3cd327d1a6
[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 //! An owned, growable vector.
12
13 use core::prelude::*;
14
15 use alloc::heap::{allocate, reallocate, deallocate};
16 use core::raw::Slice;
17 use core::cmp::max;
18 use core::default::Default;
19 use core::fmt;
20 use core::mem;
21 use core::num::{CheckedMul, CheckedAdd};
22 use core::num;
23 use core::ptr;
24 use core::uint;
25
26 use {Collection, Mutable};
27 use slice::{MutableOrdVector, MutableVectorAllocating, CloneableVector};
28 use slice::{Items, MutItems};
29
30 /// An owned, growable vector.
31 ///
32 /// # Examples
33 ///
34 /// ```rust
35 /// # use std::vec::Vec;
36 /// let mut vec = Vec::new();
37 /// vec.push(1i);
38 /// vec.push(2i);
39 ///
40 /// assert_eq!(vec.len(), 2);
41 /// assert_eq!(vec.get(0), &1);
42 ///
43 /// assert_eq!(vec.pop(), Some(2));
44 /// assert_eq!(vec.len(), 1);
45 /// ```
46 ///
47 /// The `vec!` macro is provided to make initialization more convenient:
48 ///
49 /// ```rust
50 /// let mut vec = vec!(1i, 2i, 3i);
51 /// vec.push(4);
52 /// assert_eq!(vec, vec!(1, 2, 3, 4));
53 /// ```
54 #[unsafe_no_drop_flag]
55 pub struct Vec<T> {
56     len: uint,
57     cap: uint,
58     ptr: *mut T
59 }
60
61 impl<T> Vec<T> {
62     /// Constructs a new, empty `Vec`.
63     ///
64     /// The vector will not allocate until elements are pushed onto it.
65     ///
66     /// # Example
67     ///
68     /// ```rust
69     /// # use std::vec::Vec;
70     /// let mut vec: Vec<int> = Vec::new();
71     /// ```
72     #[inline]
73     pub fn new() -> Vec<T> {
74         Vec { len: 0, cap: 0, ptr: 0 as *mut T }
75     }
76
77     /// Constructs a new, empty `Vec` with the specified capacity.
78     ///
79     /// The vector will be able to hold exactly `capacity` elements without
80     /// reallocating. If `capacity` is 0, the vector will not allocate.
81     ///
82     /// # Example
83     ///
84     /// ```rust
85     /// # use std::vec::Vec;
86     /// let vec: Vec<int> = Vec::with_capacity(10);
87     /// ```
88     #[inline]
89     pub fn with_capacity(capacity: uint) -> Vec<T> {
90         if mem::size_of::<T>() == 0 {
91             Vec { len: 0, cap: uint::MAX, ptr: 0 as *mut T }
92         } else if capacity == 0 {
93             Vec::new()
94         } else {
95             let size = capacity.checked_mul(&mem::size_of::<T>())
96                                .expect("capacity overflow");
97             let ptr = unsafe { allocate(size, mem::min_align_of::<T>()) };
98             Vec { len: 0, cap: capacity, ptr: ptr as *mut T }
99         }
100     }
101
102     /// Creates and initializes a `Vec`.
103     ///
104     /// Creates a `Vec` of size `length` and initializes the elements to the
105     /// value returned by the closure `op`.
106     ///
107     /// # Example
108     ///
109     /// ```rust
110     /// # use std::vec::Vec;
111     /// let vec = Vec::from_fn(3, |idx| idx * 2);
112     /// assert_eq!(vec, vec!(0, 2, 4));
113     /// ```
114     #[inline]
115     pub fn from_fn(length: uint, op: |uint| -> T) -> Vec<T> {
116         unsafe {
117             let mut xs = Vec::with_capacity(length);
118             while xs.len < length {
119                 let len = xs.len;
120                 ptr::write(xs.as_mut_slice().unsafe_mut_ref(len), op(len));
121                 xs.len += 1;
122             }
123             xs
124         }
125     }
126
127     /// Create a `Vec<T>` directly from the raw constituents.
128     ///
129     /// This is highly unsafe:
130     ///
131     /// - if `ptr` is null, then `length` and `capacity` should be 0
132     /// - `ptr` must point to an allocation of size `capacity`
133     /// - there must be `length` valid instances of type `T` at the
134     ///   beginning of that allocation
135     /// - `ptr` must be allocated by the default `Vec` allocator
136     pub unsafe fn from_raw_parts(length: uint, capacity: uint,
137                                  ptr: *mut T) -> Vec<T> {
138         Vec { len: length, cap: capacity, ptr: ptr }
139     }
140
141     /// Consumes the `Vec`, partitioning it based on a predicate.
142     ///
143     /// Partitions the `Vec` into two `Vec`s `(A,B)`, where all elements of `A`
144     /// satisfy `f` and all elements of `B` do not. The order of elements is
145     /// preserved.
146     ///
147     /// # Example
148     ///
149     /// ```rust
150     /// let vec = vec!(1i, 2i, 3i, 4i);
151     /// let (even, odd) = vec.partition(|&n| n % 2 == 0);
152     /// assert_eq!(even, vec!(2, 4));
153     /// assert_eq!(odd, vec!(1, 3));
154     /// ```
155     #[inline]
156     pub fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
157         let mut lefts  = Vec::new();
158         let mut rights = Vec::new();
159
160         for elt in self.move_iter() {
161             if f(&elt) {
162                 lefts.push(elt);
163             } else {
164                 rights.push(elt);
165             }
166         }
167
168         (lefts, rights)
169     }
170 }
171
172 impl<T: Clone> Vec<T> {
173     /// Iterates over the `second` vector, copying each element and appending it to
174     /// the `first`. Afterwards, the `first` is then returned for use again.
175     ///
176     /// # Example
177     ///
178     /// ```rust
179     /// let vec = vec!(1i, 2i);
180     /// let vec = vec.append([3i, 4i]);
181     /// assert_eq!(vec, vec!(1, 2, 3, 4));
182     /// ```
183     #[inline]
184     pub fn append(mut self, second: &[T]) -> Vec<T> {
185         self.push_all(second);
186         self
187     }
188
189     /// Constructs a `Vec` by cloning elements of a slice.
190     ///
191     /// # Example
192     ///
193     /// ```rust
194     /// # use std::vec::Vec;
195     /// let slice = [1i, 2, 3];
196     /// let vec = Vec::from_slice(slice);
197     /// ```
198     #[inline]
199     pub fn from_slice(values: &[T]) -> Vec<T> {
200         values.iter().map(|x| x.clone()).collect()
201     }
202
203     /// Constructs a `Vec` with copies of a value.
204     ///
205     /// Creates a `Vec` with `length` copies of `value`.
206     ///
207     /// # Example
208     /// ```rust
209     /// # use std::vec::Vec;
210     /// let vec = Vec::from_elem(3, "hi");
211     /// println!("{}", vec); // prints [hi, hi, hi]
212     /// ```
213     #[inline]
214     pub fn from_elem(length: uint, value: T) -> Vec<T> {
215         unsafe {
216             let mut xs = Vec::with_capacity(length);
217             while xs.len < length {
218                 let len = xs.len;
219                 ptr::write(xs.as_mut_slice().unsafe_mut_ref(len),
220                            value.clone());
221                 xs.len += 1;
222             }
223             xs
224         }
225     }
226
227     /// Appends all elements in a slice to the `Vec`.
228     ///
229     /// Iterates over the slice `other`, clones each element, and then appends
230     /// it to this `Vec`. The `other` vector is traversed in-order.
231     ///
232     /// # Example
233     ///
234     /// ```rust
235     /// let mut vec = vec!(1i);
236     /// vec.push_all([2i, 3, 4]);
237     /// assert_eq!(vec, vec!(1, 2, 3, 4));
238     /// ```
239     #[inline]
240     pub fn push_all(&mut self, other: &[T]) {
241         self.extend(other.iter().map(|e| e.clone()));
242     }
243
244     /// Grows the `Vec` in-place.
245     ///
246     /// Adds `n` copies of `value` to the `Vec`.
247     ///
248     /// # Example
249     ///
250     /// ```rust
251     /// let mut vec = vec!("hello");
252     /// vec.grow(2, &("world"));
253     /// assert_eq!(vec, vec!("hello", "world", "world"));
254     /// ```
255     pub fn grow(&mut self, n: uint, value: &T) {
256         let new_len = self.len() + n;
257         self.reserve(new_len);
258         let mut i: uint = 0u;
259
260         while i < n {
261             self.push((*value).clone());
262             i += 1u;
263         }
264     }
265
266     /// Sets the value of a vector element at a given index, growing the vector
267     /// as needed.
268     ///
269     /// Sets the element at position `index` to `value`. If `index` is past the
270     /// end of the vector, expands the vector by replicating `initval` to fill
271     /// the intervening space.
272     ///
273     /// # Example
274     ///
275     /// ```rust
276     /// let mut vec = vec!("a", "b", "c");
277     /// vec.grow_set(1, &("fill"), "d");
278     /// vec.grow_set(4, &("fill"), "e");
279     /// assert_eq!(vec, vec!("a", "d", "c", "fill", "e"));
280     /// ```
281     pub fn grow_set(&mut self, index: uint, initval: &T, value: T) {
282         let l = self.len();
283         if index >= l {
284             self.grow(index - l + 1u, initval);
285         }
286         *self.get_mut(index) = value;
287     }
288
289     /// Partitions a vector based on a predicate.
290     ///
291     /// Clones the elements of the vector, partitioning them into two `Vec`s
292     /// `(A,B)`, where all elements of `A` satisfy `f` and all elements of `B`
293     /// do not. The order of elements is preserved.
294     ///
295     /// # Example
296     ///
297     /// ```rust
298     /// let vec = vec!(1i, 2, 3, 4);
299     /// let (even, odd) = vec.partitioned(|&n| n % 2 == 0);
300     /// assert_eq!(even, vec!(2i, 4));
301     /// assert_eq!(odd, vec!(1i, 3));
302     /// ```
303     pub fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
304         let mut lefts = Vec::new();
305         let mut rights = Vec::new();
306
307         for elt in self.iter() {
308             if f(elt) {
309                 lefts.push(elt.clone());
310             } else {
311                 rights.push(elt.clone());
312             }
313         }
314
315         (lefts, rights)
316     }
317 }
318
319 #[unstable]
320 impl<T:Clone> Clone for Vec<T> {
321     fn clone(&self) -> Vec<T> {
322         let len = self.len;
323         let mut vector = Vec::with_capacity(len);
324         // Unsafe code so this can be optimised to a memcpy (or something
325         // similarly fast) when T is Copy. LLVM is easily confused, so any
326         // extra operations during the loop can prevent this optimisation
327         {
328             let this_slice = self.as_slice();
329             while vector.len < len {
330                 unsafe {
331                     let len = vector.len;
332                     ptr::write(
333                         vector.as_mut_slice().unsafe_mut_ref(len),
334                         this_slice.unsafe_ref(len).clone());
335                 }
336                 vector.len += 1;
337             }
338         }
339         vector
340     }
341
342     fn clone_from(&mut self, other: &Vec<T>) {
343         // drop anything in self that will not be overwritten
344         if self.len() > other.len() {
345             self.truncate(other.len())
346         }
347
348         // reuse the contained values' allocations/resources.
349         for (place, thing) in self.mut_iter().zip(other.iter()) {
350             place.clone_from(thing)
351         }
352
353         // self.len <= other.len due to the truncate above, so the
354         // slice here is always in-bounds.
355         let len = self.len();
356         self.extend(other.slice_from(len).iter().map(|x| x.clone()));
357     }
358 }
359
360 impl<T> FromIterator<T> for Vec<T> {
361     #[inline]
362     fn from_iter<I:Iterator<T>>(mut iterator: I) -> Vec<T> {
363         let (lower, _) = iterator.size_hint();
364         let mut vector = Vec::with_capacity(lower);
365         for element in iterator {
366             vector.push(element)
367         }
368         vector
369     }
370 }
371
372 impl<T> Extendable<T> for Vec<T> {
373     #[inline]
374     fn extend<I: Iterator<T>>(&mut self, mut iterator: I) {
375         let (lower, _) = iterator.size_hint();
376         self.reserve_additional(lower);
377         for element in iterator {
378             self.push(element)
379         }
380     }
381 }
382
383 impl<T: PartialEq> PartialEq for Vec<T> {
384     #[inline]
385     fn eq(&self, other: &Vec<T>) -> bool {
386         self.as_slice() == other.as_slice()
387     }
388 }
389
390 impl<T: PartialOrd> PartialOrd for Vec<T> {
391     #[inline]
392     fn partial_cmp(&self, other: &Vec<T>) -> Option<Ordering> {
393         self.as_slice().partial_cmp(&other.as_slice())
394     }
395 }
396
397 impl<T: Eq> Eq for Vec<T> {}
398
399 impl<T: PartialEq, V: Vector<T>> Equiv<V> for Vec<T> {
400     #[inline]
401     fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
402 }
403
404 impl<T: Ord> Ord for Vec<T> {
405     #[inline]
406     fn cmp(&self, other: &Vec<T>) -> Ordering {
407         self.as_slice().cmp(&other.as_slice())
408     }
409 }
410
411 impl<T> Collection for Vec<T> {
412     #[inline]
413     fn len(&self) -> uint {
414         self.len
415     }
416 }
417
418 impl<T: Clone> CloneableVector<T> for Vec<T> {
419     fn to_owned(&self) -> Vec<T> { self.clone() }
420     fn into_owned(self) -> Vec<T> { self }
421 }
422
423 // FIXME: #13996: need a way to mark the return value as `noalias`
424 #[inline(never)]
425 unsafe fn alloc_or_realloc<T>(ptr: *mut T, size: uint, old_size: uint) -> *mut T {
426     if old_size == 0 {
427         allocate(size, mem::min_align_of::<T>()) as *mut T
428     } else {
429         reallocate(ptr as *mut u8, size,
430                    mem::min_align_of::<T>(), old_size) as *mut T
431     }
432 }
433
434 #[inline]
435 unsafe fn dealloc<T>(ptr: *mut T, len: uint) {
436     if mem::size_of::<T>() != 0 {
437         deallocate(ptr as *mut u8,
438                    len * mem::size_of::<T>(),
439                    mem::min_align_of::<T>())
440     }
441 }
442
443 impl<T> Vec<T> {
444     /// Returns the number of elements the vector can hold without
445     /// reallocating.
446     ///
447     /// # Example
448     ///
449     /// ```rust
450     /// # use std::vec::Vec;
451     /// let vec: Vec<int> = Vec::with_capacity(10);
452     /// assert_eq!(vec.capacity(), 10);
453     /// ```
454     #[inline]
455     pub fn capacity(&self) -> uint {
456         self.cap
457     }
458
459      /// Reserves capacity for at least `n` additional elements in the given
460      /// vector.
461      ///
462      /// # Failure
463      ///
464      /// Fails if the new capacity overflows `uint`.
465      ///
466      /// # Example
467      ///
468      /// ```rust
469      /// # use std::vec::Vec;
470      /// let mut vec: Vec<int> = vec!(1i);
471      /// vec.reserve_additional(10);
472      /// assert!(vec.capacity() >= 11);
473      /// ```
474     pub fn reserve_additional(&mut self, extra: uint) {
475         if self.cap - self.len < extra {
476             match self.len.checked_add(&extra) {
477                 None => fail!("Vec::reserve_additional: `uint` overflow"),
478                 Some(new_cap) => self.reserve(new_cap)
479             }
480         }
481     }
482
483     /// Reserves capacity for at least `n` elements in the given vector.
484     ///
485     /// This function will over-allocate in order to amortize the allocation
486     /// costs in scenarios where the caller may need to repeatedly reserve
487     /// additional space.
488     ///
489     /// If the capacity for `self` is already equal to or greater than the
490     /// requested capacity, then no action is taken.
491     ///
492     /// # Example
493     ///
494     /// ```rust
495     /// let mut vec = vec!(1i, 2, 3);
496     /// vec.reserve(10);
497     /// assert!(vec.capacity() >= 10);
498     /// ```
499     pub fn reserve(&mut self, capacity: uint) {
500         if capacity >= self.len {
501             self.reserve_exact(num::next_power_of_two(capacity))
502         }
503     }
504
505     /// Reserves capacity for exactly `capacity` elements in the given vector.
506     ///
507     /// If the capacity for `self` is already equal to or greater than the
508     /// requested capacity, then no action is taken.
509     ///
510     /// # Example
511     ///
512     /// ```rust
513     /// # use std::vec::Vec;
514     /// let mut vec: Vec<int> = Vec::with_capacity(10);
515     /// vec.reserve_exact(11);
516     /// assert_eq!(vec.capacity(), 11);
517     /// ```
518     pub fn reserve_exact(&mut self, capacity: uint) {
519         if mem::size_of::<T>() == 0 { return }
520
521         if capacity > self.cap {
522             let size = capacity.checked_mul(&mem::size_of::<T>())
523                                .expect("capacity overflow");
524             unsafe {
525                 self.ptr = alloc_or_realloc(self.ptr, size,
526                                             self.cap * mem::size_of::<T>());
527             }
528             self.cap = capacity;
529         }
530     }
531
532     /// Shrink the capacity of the vector as much as possible
533     ///
534     /// # Example
535     ///
536     /// ```rust
537     /// let mut vec = vec!(1i, 2, 3);
538     /// vec.shrink_to_fit();
539     /// ```
540     pub fn shrink_to_fit(&mut self) {
541         if mem::size_of::<T>() == 0 { return }
542
543         if self.len == 0 {
544             if self.cap != 0 {
545                 unsafe {
546                     dealloc(self.ptr, self.cap)
547                 }
548                 self.cap = 0;
549             }
550         } else {
551             unsafe {
552                 // Overflow check is unnecessary as the vector is already at
553                 // least this large.
554                 self.ptr = reallocate(self.ptr as *mut u8,
555                                       self.len * mem::size_of::<T>(),
556                                       mem::min_align_of::<T>(),
557                                       self.cap * mem::size_of::<T>()) as *mut T;
558             }
559             self.cap = self.len;
560         }
561     }
562
563     /// Remove the last element from a vector and return it, or `None` if it is
564     /// empty.
565     ///
566     /// # Example
567     ///
568     /// ```rust
569     /// let mut vec = vec!(1i, 2, 3);
570     /// assert_eq!(vec.pop(), Some(3));
571     /// assert_eq!(vec, vec!(1, 2));
572     /// ```
573     #[inline]
574     pub fn pop(&mut self) -> Option<T> {
575         if self.len == 0 {
576             None
577         } else {
578             unsafe {
579                 self.len -= 1;
580                 Some(ptr::read(self.as_slice().unsafe_ref(self.len())))
581             }
582         }
583     }
584
585     /// Append an element to a vector.
586     ///
587     /// # Failure
588     ///
589     /// Fails if the number of elements in the vector overflows a `uint`.
590     ///
591     /// # Example
592     ///
593     /// ```rust
594     /// let mut vec = vec!(1i, 2);
595     /// vec.push(3);
596     /// assert_eq!(vec, vec!(1, 2, 3));
597     /// ```
598     #[inline]
599     pub fn push(&mut self, value: T) {
600         if mem::size_of::<T>() == 0 {
601             // zero-size types consume no memory, so we can't rely on the address space running out
602             self.len = self.len.checked_add(&1).expect("length overflow");
603             unsafe { mem::forget(value); }
604             return
605         }
606         if self.len == self.cap {
607             let old_size = self.cap * mem::size_of::<T>();
608             let size = max(old_size, 2 * mem::size_of::<T>()) * 2;
609             if old_size > size { fail!("capacity overflow") }
610             unsafe {
611                 self.ptr = alloc_or_realloc(self.ptr, size,
612                                             self.cap * mem::size_of::<T>());
613             }
614             self.cap = max(self.cap, 2) * 2;
615         }
616
617         unsafe {
618             let end = (self.ptr as *const T).offset(self.len as int) as *mut T;
619             ptr::write(&mut *end, value);
620             self.len += 1;
621         }
622     }
623
624     /// Appends one element to the vector provided. The vector itself is then
625     /// returned for use again.
626     ///
627     /// # Example
628     ///
629     /// ```rust
630     /// let vec = vec!(1i, 2);
631     /// let vec = vec.append_one(3);
632     /// assert_eq!(vec, vec!(1, 2, 3));
633     /// ```
634     #[inline]
635     pub fn append_one(mut self, x: T) -> Vec<T> {
636         self.push(x);
637         self
638     }
639
640     /// Shorten a vector, dropping excess elements.
641     ///
642     /// If `len` is greater than the vector's current length, this has no
643     /// effect.
644     ///
645     /// # Example
646     ///
647     /// ```rust
648     /// let mut vec = vec!(1i, 2, 3, 4);
649     /// vec.truncate(2);
650     /// assert_eq!(vec, vec!(1, 2));
651     /// ```
652     pub fn truncate(&mut self, len: uint) {
653         unsafe {
654             // drop any extra elements
655             while len < self.len {
656                 // decrement len before the read(), so a failure on Drop doesn't
657                 // re-drop the just-failed value.
658                 self.len -= 1;
659                 ptr::read(self.as_slice().unsafe_ref(self.len));
660             }
661         }
662     }
663
664     /// Work with `self` as a mutable slice.
665     ///
666     /// # Example
667     ///
668     /// ```rust
669     /// fn foo(slice: &mut [int]) {}
670     ///
671     /// let mut vec = vec!(1i, 2);
672     /// foo(vec.as_mut_slice());
673     /// ```
674     #[inline]
675     pub fn as_mut_slice<'a>(&'a mut self) -> &'a mut [T] {
676         unsafe {
677             mem::transmute(Slice {
678                 data: self.as_mut_ptr() as *const T,
679                 len: self.len,
680             })
681         }
682     }
683
684     /// Creates a consuming iterator, that is, one that moves each
685     /// value out of the vector (from start to end). The vector cannot
686     /// be used after calling this.
687     ///
688     /// # Example
689     ///
690     /// ```rust
691     /// let v = vec!("a".to_string(), "b".to_string());
692     /// for s in v.move_iter() {
693     ///     // s has type String, not &String
694     ///     println!("{}", s);
695     /// }
696     /// ```
697     #[inline]
698     pub fn move_iter(self) -> MoveItems<T> {
699         unsafe {
700             let iter = mem::transmute(self.as_slice().iter());
701             let ptr = self.ptr;
702             let cap = self.cap;
703             mem::forget(self);
704             MoveItems { allocation: ptr, cap: cap, iter: iter }
705         }
706     }
707
708
709     /// Sets the length of a vector.
710     ///
711     /// This will explicitly set the size of the vector, without actually
712     /// modifying its buffers, so it is up to the caller to ensure that the
713     /// vector is actually the specified size.
714     #[inline]
715     pub unsafe fn set_len(&mut self, len: uint) {
716         self.len = len;
717     }
718
719     /// Returns a reference to the value at index `index`.
720     ///
721     /// # Failure
722     ///
723     /// Fails if `index` is out of bounds
724     ///
725     /// # Example
726     ///
727     /// ```rust
728     /// let vec = vec!(1i, 2, 3);
729     /// assert!(vec.get(1) == &2);
730     /// ```
731     #[inline]
732     pub fn get<'a>(&'a self, index: uint) -> &'a T {
733         &self.as_slice()[index]
734     }
735
736     /// Returns a mutable reference to the value at index `index`.
737     ///
738     /// # Failure
739     ///
740     /// Fails if `index` is out of bounds
741     ///
742     /// # Example
743     ///
744     /// ```rust
745     /// let mut vec = vec!(1i, 2, 3);
746     /// *vec.get_mut(1) = 4;
747     /// assert_eq!(vec, vec!(1i, 4, 3));
748     /// ```
749     #[inline]
750     pub fn get_mut<'a>(&'a mut self, index: uint) -> &'a mut T {
751         &mut self.as_mut_slice()[index]
752     }
753
754     /// Returns an iterator over references to the elements of the vector in
755     /// order.
756     ///
757     /// # Example
758     ///
759     /// ```rust
760     /// let vec = vec!(1i, 2, 3);
761     /// for num in vec.iter() {
762     ///     println!("{}", *num);
763     /// }
764     /// ```
765     #[inline]
766     pub fn iter<'a>(&'a self) -> Items<'a,T> {
767         self.as_slice().iter()
768     }
769
770
771     /// Returns an iterator over mutable references to the elements of the
772     /// vector in order.
773     ///
774     /// # Example
775     ///
776     /// ```rust
777     /// let mut vec = vec!(1i, 2, 3);
778     /// for num in vec.mut_iter() {
779     ///     *num = 0;
780     /// }
781     /// ```
782     #[inline]
783     pub fn mut_iter<'a>(&'a mut self) -> MutItems<'a,T> {
784         self.as_mut_slice().mut_iter()
785     }
786
787     /// Sort the vector, in place, using `compare` to compare elements.
788     ///
789     /// This sort is `O(n log n)` worst-case and stable, but allocates
790     /// approximately `2 * n`, where `n` is the length of `self`.
791     ///
792     /// # Example
793     ///
794     /// ```rust
795     /// let mut v = vec!(5i, 4, 1, 3, 2);
796     /// v.sort_by(|a, b| a.cmp(b));
797     /// assert_eq!(v, vec!(1i, 2, 3, 4, 5));
798     ///
799     /// // reverse sorting
800     /// v.sort_by(|a, b| b.cmp(a));
801     /// assert_eq!(v, vec!(5i, 4, 3, 2, 1));
802     /// ```
803     #[inline]
804     pub fn sort_by(&mut self, compare: |&T, &T| -> Ordering) {
805         self.as_mut_slice().sort_by(compare)
806     }
807
808     /// Returns a slice of self spanning the interval [`start`, `end`).
809     ///
810     /// # Failure
811     ///
812     /// Fails when the slice (or part of it) is outside the bounds of self, or when
813     /// `start` > `end`.
814     ///
815     /// # Example
816     ///
817     /// ```rust
818     /// let vec = vec!(1i, 2, 3, 4);
819     /// assert!(vec.slice(0, 2) == [1, 2]);
820     /// ```
821     #[inline]
822     pub fn slice<'a>(&'a self, start: uint, end: uint) -> &'a [T] {
823         self.as_slice().slice(start, end)
824     }
825
826     /// Returns a slice containing all but the first element of the vector.
827     ///
828     /// # Failure
829     ///
830     /// Fails when the vector is empty.
831     ///
832     /// # Example
833     ///
834     /// ```rust
835     /// let vec = vec!(1i, 2, 3);
836     /// assert!(vec.tail() == [2, 3]);
837     /// ```
838     #[inline]
839     pub fn tail<'a>(&'a self) -> &'a [T] {
840         self.as_slice().tail()
841     }
842
843     /// Returns all but the first `n' elements of a vector.
844     ///
845     /// # Failure
846     ///
847     /// Fails when there are fewer than `n` elements in the vector.
848     ///
849     /// # Example
850     ///
851     /// ```rust
852     /// let vec = vec!(1i, 2, 3, 4);
853     /// assert!(vec.tailn(2) == [3, 4]);
854     /// ```
855     #[inline]
856     pub fn tailn<'a>(&'a self, n: uint) -> &'a [T] {
857         self.as_slice().tailn(n)
858     }
859
860     /// Returns a reference to the last element of a vector, or `None` if it is
861     /// empty.
862     ///
863     /// # Example
864     ///
865     /// ```rust
866     /// let vec = vec!(1i, 2, 3);
867     /// assert!(vec.last() == Some(&3));
868     /// ```
869     #[inline]
870     pub fn last<'a>(&'a self) -> Option<&'a T> {
871         self.as_slice().last()
872     }
873
874     /// Returns a mutable reference to the last element of a vector, or `None`
875     /// if it is empty.
876     ///
877     /// # Example
878     ///
879     /// ```rust
880     /// let mut vec = vec!(1i, 2, 3);
881     /// *vec.mut_last().unwrap() = 4;
882     /// assert_eq!(vec, vec!(1i, 2, 4));
883     /// ```
884     #[inline]
885     pub fn mut_last<'a>(&'a mut self) -> Option<&'a mut T> {
886         self.as_mut_slice().mut_last()
887     }
888
889     /// Remove an element from anywhere in the vector and return it, replacing
890     /// it with the last element. This does not preserve ordering, but is O(1).
891     ///
892     /// Returns `None` if `index` is out of bounds.
893     ///
894     /// # Example
895     /// ```rust
896     /// let mut v = vec!("foo".to_string(), "bar".to_string(),
897     ///                  "baz".to_string(), "qux".to_string());
898     ///
899     /// assert_eq!(v.swap_remove(1), Some("bar".to_string()));
900     /// assert_eq!(v, vec!("foo".to_string(), "qux".to_string(), "baz".to_string()));
901     ///
902     /// assert_eq!(v.swap_remove(0), Some("foo".to_string()));
903     /// assert_eq!(v, vec!("baz".to_string(), "qux".to_string()));
904     ///
905     /// assert_eq!(v.swap_remove(2), None);
906     /// ```
907     #[inline]
908     pub fn swap_remove(&mut self, index: uint) -> Option<T> {
909         let length = self.len();
910         if index < length - 1 {
911             self.as_mut_slice().swap(index, length - 1);
912         } else if index >= length {
913             return None
914         }
915         self.pop()
916     }
917
918     /// Prepend an element to the vector.
919     ///
920     /// # Warning
921     ///
922     /// This is an O(n) operation as it requires copying every element in the
923     /// vector.
924     ///
925     /// # Example
926     ///
927     /// ```rust
928     /// let mut vec = vec!(1i, 2, 3);
929     /// vec.unshift(4);
930     /// assert_eq!(vec, vec!(4, 1, 2, 3));
931     /// ```
932     #[inline]
933     pub fn unshift(&mut self, element: T) {
934         self.insert(0, element)
935     }
936
937     /// Removes the first element from a vector and returns it, or `None` if
938     /// the vector is empty.
939     ///
940     /// # Warning
941     ///
942     /// This is an O(n) operation as it requires copying every element in the
943     /// vector.
944     ///
945     /// # Example
946     ///
947     /// ```rust
948     /// let mut vec = vec!(1i, 2, 3);
949     /// assert!(vec.shift() == Some(1));
950     /// assert_eq!(vec, vec!(2, 3));
951     /// ```
952     #[inline]
953     pub fn shift(&mut self) -> Option<T> {
954         self.remove(0)
955     }
956
957     /// Insert an element at position `index` within the vector, shifting all
958     /// elements after position i one position to the right.
959     ///
960     /// # Failure
961     ///
962     /// Fails if `index` is not between `0` and the vector's length (both
963     /// bounds inclusive).
964     ///
965     /// # Example
966     ///
967     /// ```rust
968     /// let mut vec = vec!(1i, 2, 3);
969     /// vec.insert(1, 4);
970     /// assert_eq!(vec, vec!(1, 4, 2, 3));
971     /// vec.insert(4, 5);
972     /// assert_eq!(vec, vec!(1, 4, 2, 3, 5));
973     /// ```
974     pub fn insert(&mut self, index: uint, element: T) {
975         let len = self.len();
976         assert!(index <= len);
977         // space for the new element
978         self.reserve(len + 1);
979
980         unsafe { // infallible
981             // The spot to put the new value
982             {
983                 let p = self.as_mut_ptr().offset(index as int);
984                 // Shift everything over to make space. (Duplicating the
985                 // `index`th element into two consecutive places.)
986                 ptr::copy_memory(p.offset(1), &*p, len - index);
987                 // Write it in, overwriting the first copy of the `index`th
988                 // element.
989                 ptr::write(&mut *p, element);
990             }
991             self.set_len(len + 1);
992         }
993     }
994
995     /// Remove and return the element at position `index` within the vector,
996     /// shifting all elements after position `index` one position to the left.
997     /// Returns `None` if `i` is out of bounds.
998     ///
999     /// # Example
1000     ///
1001     /// ```rust
1002     /// let mut v = vec!(1i, 2, 3);
1003     /// assert_eq!(v.remove(1), Some(2));
1004     /// assert_eq!(v, vec!(1, 3));
1005     ///
1006     /// assert_eq!(v.remove(4), None);
1007     /// // v is unchanged:
1008     /// assert_eq!(v, vec!(1, 3));
1009     /// ```
1010     pub fn remove(&mut self, index: uint) -> Option<T> {
1011         let len = self.len();
1012         if index < len {
1013             unsafe { // infallible
1014                 let ret;
1015                 {
1016                     // the place we are taking from.
1017                     let ptr = self.as_mut_ptr().offset(index as int);
1018                     // copy it out, unsafely having a copy of the value on
1019                     // the stack and in the vector at the same time.
1020                     ret = Some(ptr::read(ptr as *const T));
1021
1022                     // Shift everything down to fill in that spot.
1023                     ptr::copy_memory(ptr, &*ptr.offset(1), len - index - 1);
1024                 }
1025                 self.set_len(len - 1);
1026                 ret
1027             }
1028         } else {
1029             None
1030         }
1031     }
1032
1033     /// Takes ownership of the vector `other`, moving all elements into
1034     /// the current vector. This does not copy any elements, and it is
1035     /// illegal to use the `other` vector after calling this method
1036     /// (because it is moved here).
1037     ///
1038     /// # Example
1039     ///
1040     /// ```rust
1041     /// let mut vec = vec!(box 1i);
1042     /// vec.push_all_move(vec!(box 2, box 3, box 4));
1043     /// assert_eq!(vec, vec!(box 1, box 2, box 3, box 4));
1044     /// ```
1045     #[inline]
1046     pub fn push_all_move(&mut self, other: Vec<T>) {
1047         self.extend(other.move_iter());
1048     }
1049
1050     /// Returns a mutable slice of `self` between `start` and `end`.
1051     ///
1052     /// # Failure
1053     ///
1054     /// Fails when `start` or `end` point outside the bounds of `self`, or when
1055     /// `start` > `end`.
1056     ///
1057     /// # Example
1058     ///
1059     /// ```rust
1060     /// let mut vec = vec!(1i, 2, 3, 4);
1061     /// assert!(vec.mut_slice(0, 2) == [1, 2]);
1062     /// ```
1063     #[inline]
1064     pub fn mut_slice<'a>(&'a mut self, start: uint, end: uint)
1065                          -> &'a mut [T] {
1066         self.as_mut_slice().mut_slice(start, end)
1067     }
1068
1069     /// Returns a mutable slice of self from `start` to the end of the vec.
1070     ///
1071     /// # Failure
1072     ///
1073     /// Fails when `start` points outside the bounds of self.
1074     ///
1075     /// # Example
1076     ///
1077     /// ```rust
1078     /// let mut vec = vec!(1i, 2, 3, 4);
1079     /// assert!(vec.mut_slice_from(2) == [3, 4]);
1080     /// ```
1081     #[inline]
1082     pub fn mut_slice_from<'a>(&'a mut self, start: uint) -> &'a mut [T] {
1083         self.as_mut_slice().mut_slice_from(start)
1084     }
1085
1086     /// Returns a mutable slice of self from the start of the vec to `end`.
1087     ///
1088     /// # Failure
1089     ///
1090     /// Fails when `end` points outside the bounds of self.
1091     ///
1092     /// # Example
1093     ///
1094     /// ```rust
1095     /// let mut vec = vec!(1i, 2, 3, 4);
1096     /// assert!(vec.mut_slice_to(2) == [1, 2]);
1097     /// ```
1098     #[inline]
1099     pub fn mut_slice_to<'a>(&'a mut self, end: uint) -> &'a mut [T] {
1100         self.as_mut_slice().mut_slice_to(end)
1101     }
1102
1103     /// Returns a pair of mutable slices that divides the vec at an index.
1104     ///
1105     /// The first will contain all indices from `[0, mid)` (excluding
1106     /// the index `mid` itself) and the second will contain all
1107     /// indices from `[mid, len)` (excluding the index `len` itself).
1108     ///
1109     /// # Failure
1110     ///
1111     /// Fails if `mid > len`.
1112     ///
1113     /// # Example
1114     ///
1115     /// ```rust
1116     /// let mut vec = vec!(1i, 2, 3, 4, 5, 6);
1117     ///
1118     /// // scoped to restrict the lifetime of the borrows
1119     /// {
1120     ///    let (left, right) = vec.mut_split_at(0);
1121     ///    assert!(left == &mut []);
1122     ///    assert!(right == &mut [1, 2, 3, 4, 5, 6]);
1123     /// }
1124     ///
1125     /// {
1126     ///     let (left, right) = vec.mut_split_at(2);
1127     ///     assert!(left == &mut [1, 2]);
1128     ///     assert!(right == &mut [3, 4, 5, 6]);
1129     /// }
1130     ///
1131     /// {
1132     ///     let (left, right) = vec.mut_split_at(6);
1133     ///     assert!(left == &mut [1, 2, 3, 4, 5, 6]);
1134     ///     assert!(right == &mut []);
1135     /// }
1136     /// ```
1137     #[inline]
1138     pub fn mut_split_at<'a>(&'a mut self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
1139         self.as_mut_slice().mut_split_at(mid)
1140     }
1141
1142     /// Reverse the order of elements in a vector, in place.
1143     ///
1144     /// # Example
1145     ///
1146     /// ```rust
1147     /// let mut v = vec!(1i, 2, 3);
1148     /// v.reverse();
1149     /// assert_eq!(v, vec!(3i, 2, 1));
1150     /// ```
1151     #[inline]
1152     pub fn reverse(&mut self) {
1153         self.as_mut_slice().reverse()
1154     }
1155
1156     /// Returns a slice of `self` from `start` to the end of the vec.
1157     ///
1158     /// # Failure
1159     ///
1160     /// Fails when `start` points outside the bounds of self.
1161     ///
1162     /// # Example
1163     ///
1164     /// ```rust
1165     /// let vec = vec!(1i, 2, 3);
1166     /// assert!(vec.slice_from(1) == [2, 3]);
1167     /// ```
1168     #[inline]
1169     pub fn slice_from<'a>(&'a self, start: uint) -> &'a [T] {
1170         self.as_slice().slice_from(start)
1171     }
1172
1173     /// Returns a slice of self from the start of the vec to `end`.
1174     ///
1175     /// # Failure
1176     ///
1177     /// Fails when `end` points outside the bounds of self.
1178     ///
1179     /// # Example
1180     ///
1181     /// ```rust
1182     /// let vec = vec!(1i, 2, 3);
1183     /// assert!(vec.slice_to(2) == [1, 2]);
1184     /// ```
1185     #[inline]
1186     pub fn slice_to<'a>(&'a self, end: uint) -> &'a [T] {
1187         self.as_slice().slice_to(end)
1188     }
1189
1190     /// Returns a slice containing all but the last element of the vector.
1191     ///
1192     /// # Failure
1193     ///
1194     /// Fails if the vector is empty
1195     #[inline]
1196     pub fn init<'a>(&'a self) -> &'a [T] {
1197         self.slice(0, self.len() - 1)
1198     }
1199
1200
1201     /// Returns an unsafe pointer to the vector's buffer.
1202     ///
1203     /// The caller must ensure that the vector outlives the pointer this
1204     /// function returns, or else it will end up pointing to garbage.
1205     ///
1206     /// Modifying the vector may cause its buffer to be reallocated, which
1207     /// would also make any pointers to it invalid.
1208     #[inline]
1209     pub fn as_ptr(&self) -> *const T {
1210         // If we have a 0-sized vector, then the base pointer should not be NULL
1211         // because an iterator over the slice will attempt to yield the base
1212         // pointer as the first element in the vector, but this will end up
1213         // being Some(NULL) which is optimized to None.
1214         if mem::size_of::<T>() == 0 {
1215             1 as *const T
1216         } else {
1217             self.ptr as *const T
1218         }
1219     }
1220
1221     /// Returns a mutable unsafe pointer to the vector's buffer.
1222     ///
1223     /// The caller must ensure that the vector outlives the pointer this
1224     /// function returns, or else it will end up pointing to garbage.
1225     ///
1226     /// Modifying the vector may cause its buffer to be reallocated, which
1227     /// would also make any pointers to it invalid.
1228     #[inline]
1229     pub fn as_mut_ptr(&mut self) -> *mut T {
1230         // see above for the 0-size check
1231         if mem::size_of::<T>() == 0 {
1232             1 as *mut T
1233         } else {
1234             self.ptr
1235         }
1236     }
1237
1238     /// Retains only the elements specified by the predicate.
1239     ///
1240     /// In other words, remove all elements `e` such that `f(&e)` returns false.
1241     /// This method operates in place and preserves the order the retained elements.
1242     ///
1243     /// # Example
1244     ///
1245     /// ```rust
1246     /// let mut vec = vec!(1i, 2, 3, 4);
1247     /// vec.retain(|x| x%2 == 0);
1248     /// assert_eq!(vec, vec!(2, 4));
1249     /// ```
1250     pub fn retain(&mut self, f: |&T| -> bool) {
1251         let len = self.len();
1252         let mut del = 0u;
1253         {
1254             let v = self.as_mut_slice();
1255
1256             for i in range(0u, len) {
1257                 if !f(&v[i]) {
1258                     del += 1;
1259                 } else if del > 0 {
1260                     v.swap(i-del, i);
1261                 }
1262             }
1263         }
1264         if del > 0 {
1265             self.truncate(len - del);
1266         }
1267     }
1268
1269     /// Expands a vector in place, initializing the new elements to the result of a function.
1270     ///
1271     /// The vector is grown by `n` elements. The i-th new element are initialized to the value
1272     /// returned by `f(i)` where `i` is in the range [0, n).
1273     ///
1274     /// # Example
1275     ///
1276     /// ```rust
1277     /// let mut vec = vec!(0u, 1);
1278     /// vec.grow_fn(3, |i| i);
1279     /// assert_eq!(vec, vec!(0, 1, 0, 1, 2));
1280     /// ```
1281     pub fn grow_fn(&mut self, n: uint, f: |uint| -> T) {
1282         self.reserve_additional(n);
1283         for i in range(0u, n) {
1284             self.push(f(i));
1285         }
1286     }
1287 }
1288
1289 impl<T:Ord> Vec<T> {
1290     /// Sorts the vector in place.
1291     ///
1292     /// This sort is `O(n log n)` worst-case and stable, but allocates
1293     /// approximately `2 * n`, where `n` is the length of `self`.
1294     ///
1295     /// # Example
1296     ///
1297     /// ```rust
1298     /// let mut vec = vec!(3i, 1, 2);
1299     /// vec.sort();
1300     /// assert_eq!(vec, vec!(1, 2, 3));
1301     /// ```
1302     pub fn sort(&mut self) {
1303         self.as_mut_slice().sort()
1304     }
1305 }
1306
1307 impl<T> Mutable for Vec<T> {
1308     #[inline]
1309     fn clear(&mut self) {
1310         self.truncate(0)
1311     }
1312 }
1313
1314 impl<T:PartialEq> Vec<T> {
1315     /// Return true if a vector contains an element with the given value
1316     ///
1317     /// # Example
1318     ///
1319     /// ```rust
1320     /// let vec = vec!(1i, 2, 3);
1321     /// assert!(vec.contains(&1));
1322     /// ```
1323     #[inline]
1324     pub fn contains(&self, x: &T) -> bool {
1325         self.as_slice().contains(x)
1326     }
1327
1328     /// Remove consecutive repeated elements in the vector.
1329     ///
1330     /// If the vector is sorted, this removes all duplicates.
1331     ///
1332     /// # Example
1333     ///
1334     /// ```rust
1335     /// let mut vec = vec!(1i, 2, 2, 3, 2);
1336     /// vec.dedup();
1337     /// assert_eq!(vec, vec!(1i, 2, 3, 2));
1338     /// ```
1339     pub fn dedup(&mut self) {
1340         unsafe {
1341             // Although we have a mutable reference to `self`, we cannot make
1342             // *arbitrary* changes. The `PartialEq` comparisons could fail, so we
1343             // must ensure that the vector is in a valid state at all time.
1344             //
1345             // The way that we handle this is by using swaps; we iterate
1346             // over all the elements, swapping as we go so that at the end
1347             // the elements we wish to keep are in the front, and those we
1348             // wish to reject are at the back. We can then truncate the
1349             // vector. This operation is still O(n).
1350             //
1351             // Example: We start in this state, where `r` represents "next
1352             // read" and `w` represents "next_write`.
1353             //
1354             //           r
1355             //     +---+---+---+---+---+---+
1356             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1357             //     +---+---+---+---+---+---+
1358             //           w
1359             //
1360             // Comparing self[r] against self[w-1], this is not a duplicate, so
1361             // we swap self[r] and self[w] (no effect as r==w) and then increment both
1362             // r and w, leaving us with:
1363             //
1364             //               r
1365             //     +---+---+---+---+---+---+
1366             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1367             //     +---+---+---+---+---+---+
1368             //               w
1369             //
1370             // Comparing self[r] against self[w-1], this value is a duplicate,
1371             // so we increment `r` but leave everything else unchanged:
1372             //
1373             //                   r
1374             //     +---+---+---+---+---+---+
1375             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1376             //     +---+---+---+---+---+---+
1377             //               w
1378             //
1379             // Comparing self[r] against self[w-1], this is not a duplicate,
1380             // so swap self[r] and self[w] and advance r and w:
1381             //
1382             //                       r
1383             //     +---+---+---+---+---+---+
1384             //     | 0 | 1 | 2 | 1 | 3 | 3 |
1385             //     +---+---+---+---+---+---+
1386             //                   w
1387             //
1388             // Not a duplicate, repeat:
1389             //
1390             //                           r
1391             //     +---+---+---+---+---+---+
1392             //     | 0 | 1 | 2 | 3 | 1 | 3 |
1393             //     +---+---+---+---+---+---+
1394             //                       w
1395             //
1396             // Duplicate, advance r. End of vec. Truncate to w.
1397
1398             let ln = self.len();
1399             if ln < 1 { return; }
1400
1401             // Avoid bounds checks by using unsafe pointers.
1402             let p = self.as_mut_slice().as_mut_ptr();
1403             let mut r = 1;
1404             let mut w = 1;
1405
1406             while r < ln {
1407                 let p_r = p.offset(r as int);
1408                 let p_wm1 = p.offset((w - 1) as int);
1409                 if *p_r != *p_wm1 {
1410                     if r != w {
1411                         let p_w = p_wm1.offset(1);
1412                         mem::swap(&mut *p_r, &mut *p_w);
1413                     }
1414                     w += 1;
1415                 }
1416                 r += 1;
1417             }
1418
1419             self.truncate(w);
1420         }
1421     }
1422 }
1423
1424 impl<T> Vector<T> for Vec<T> {
1425     /// Work with `self` as a slice.
1426     ///
1427     /// # Example
1428     ///
1429     /// ```rust
1430     /// fn foo(slice: &[int]) {}
1431     ///
1432     /// let vec = vec!(1i, 2);
1433     /// foo(vec.as_slice());
1434     /// ```
1435     #[inline]
1436     fn as_slice<'a>(&'a self) -> &'a [T] {
1437         unsafe { mem::transmute(Slice { data: self.as_ptr(), len: self.len }) }
1438     }
1439 }
1440
1441 impl<T: Clone, V: Vector<T>> Add<V, Vec<T>> for Vec<T> {
1442     #[inline]
1443     fn add(&self, rhs: &V) -> Vec<T> {
1444         let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len());
1445         res.push_all(self.as_slice());
1446         res.push_all(rhs.as_slice());
1447         res
1448     }
1449 }
1450
1451 #[unsafe_destructor]
1452 impl<T> Drop for Vec<T> {
1453     fn drop(&mut self) {
1454         // This is (and should always remain) a no-op if the fields are
1455         // zeroed (when moving out, because of #[unsafe_no_drop_flag]).
1456         if self.cap != 0 {
1457             unsafe {
1458                 for x in self.as_mut_slice().iter() {
1459                     ptr::read(x);
1460                 }
1461                 dealloc(self.ptr, self.cap)
1462             }
1463         }
1464     }
1465 }
1466
1467 impl<T> Default for Vec<T> {
1468     fn default() -> Vec<T> {
1469         Vec::new()
1470     }
1471 }
1472
1473 impl<T:fmt::Show> fmt::Show for Vec<T> {
1474     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1475         self.as_slice().fmt(f)
1476     }
1477 }
1478
1479 /// An iterator that moves out of a vector.
1480 pub struct MoveItems<T> {
1481     allocation: *mut T, // the block of memory allocated for the vector
1482     cap: uint, // the capacity of the vector
1483     iter: Items<'static, T>
1484 }
1485
1486 impl<T> Iterator<T> for MoveItems<T> {
1487     #[inline]
1488     fn next(&mut self) -> Option<T> {
1489         unsafe {
1490             self.iter.next().map(|x| ptr::read(x))
1491         }
1492     }
1493
1494     #[inline]
1495     fn size_hint(&self) -> (uint, Option<uint>) {
1496         self.iter.size_hint()
1497     }
1498 }
1499
1500 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
1501     #[inline]
1502     fn next_back(&mut self) -> Option<T> {
1503         unsafe {
1504             self.iter.next_back().map(|x| ptr::read(x))
1505         }
1506     }
1507 }
1508
1509 #[unsafe_destructor]
1510 impl<T> Drop for MoveItems<T> {
1511     fn drop(&mut self) {
1512         // destroy the remaining elements
1513         if self.cap != 0 {
1514             for _x in *self {}
1515             unsafe {
1516                 dealloc(self.allocation, self.cap);
1517             }
1518         }
1519     }
1520 }
1521
1522 /**
1523  * Convert an iterator of pairs into a pair of vectors.
1524  *
1525  * Returns a tuple containing two vectors where the i-th element of the first
1526  * vector contains the first element of the i-th tuple of the input iterator,
1527  * and the i-th element of the second vector contains the second element
1528  * of the i-th tuple of the input iterator.
1529  */
1530 pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (Vec<T>, Vec<U>) {
1531     let (lo, _) = iter.size_hint();
1532     let mut ts = Vec::with_capacity(lo);
1533     let mut us = Vec::with_capacity(lo);
1534     for (t, u) in iter {
1535         ts.push(t);
1536         us.push(u);
1537     }
1538     (ts, us)
1539 }
1540
1541 /// Unsafe operations
1542 pub mod raw {
1543     use super::Vec;
1544     use core::ptr;
1545
1546     /// Constructs a vector from an unsafe pointer to a buffer.
1547     ///
1548     /// The elements of the buffer are copied into the vector without cloning,
1549     /// as if `ptr::read()` were called on them.
1550     #[inline]
1551     pub unsafe fn from_buf<T>(ptr: *const T, elts: uint) -> Vec<T> {
1552         let mut dst = Vec::with_capacity(elts);
1553         dst.set_len(elts);
1554         ptr::copy_nonoverlapping_memory(dst.as_mut_ptr(), ptr, elts);
1555         dst
1556     }
1557 }
1558
1559
1560 #[cfg(test)]
1561 mod tests {
1562     extern crate test;
1563
1564     use std::prelude::*;
1565     use std::mem::size_of;
1566     use test::Bencher;
1567     use super::{unzip, raw, Vec};
1568
1569     #[test]
1570     fn test_small_vec_struct() {
1571         assert!(size_of::<Vec<u8>>() == size_of::<uint>() * 3);
1572     }
1573
1574     #[test]
1575     fn test_double_drop() {
1576         struct TwoVec<T> {
1577             x: Vec<T>,
1578             y: Vec<T>
1579         }
1580
1581         struct DropCounter<'a> {
1582             count: &'a mut int
1583         }
1584
1585         #[unsafe_destructor]
1586         impl<'a> Drop for DropCounter<'a> {
1587             fn drop(&mut self) {
1588                 *self.count += 1;
1589             }
1590         }
1591
1592         let mut count_x @ mut count_y = 0;
1593         {
1594             let mut tv = TwoVec {
1595                 x: Vec::new(),
1596                 y: Vec::new()
1597             };
1598             tv.x.push(DropCounter {count: &mut count_x});
1599             tv.y.push(DropCounter {count: &mut count_y});
1600
1601             // If Vec had a drop flag, here is where it would be zeroed.
1602             // Instead, it should rely on its internal state to prevent
1603             // doing anything significant when dropped multiple times.
1604             drop(tv.x);
1605
1606             // Here tv goes out of scope, tv.y should be dropped, but not tv.x.
1607         }
1608
1609         assert_eq!(count_x, 1);
1610         assert_eq!(count_y, 1);
1611     }
1612
1613     #[test]
1614     fn test_reserve_additional() {
1615         let mut v = Vec::new();
1616         assert_eq!(v.capacity(), 0);
1617
1618         v.reserve_additional(2);
1619         assert!(v.capacity() >= 2);
1620
1621         for i in range(0i, 16) {
1622             v.push(i);
1623         }
1624
1625         assert!(v.capacity() >= 16);
1626         v.reserve_additional(16);
1627         assert!(v.capacity() >= 32);
1628
1629         v.push(16);
1630
1631         v.reserve_additional(16);
1632         assert!(v.capacity() >= 33)
1633     }
1634
1635     #[test]
1636     fn test_extend() {
1637         let mut v = Vec::new();
1638         let mut w = Vec::new();
1639
1640         v.extend(range(0i, 3));
1641         for i in range(0i, 3) { w.push(i) }
1642
1643         assert_eq!(v, w);
1644
1645         v.extend(range(3i, 10));
1646         for i in range(3i, 10) { w.push(i) }
1647
1648         assert_eq!(v, w);
1649     }
1650
1651     #[test]
1652     fn test_mut_slice_from() {
1653         let mut values = Vec::from_slice([1u8,2,3,4,5]);
1654         {
1655             let slice = values.mut_slice_from(2);
1656             assert!(slice == [3, 4, 5]);
1657             for p in slice.mut_iter() {
1658                 *p += 2;
1659             }
1660         }
1661
1662         assert!(values.as_slice() == [1, 2, 5, 6, 7]);
1663     }
1664
1665     #[test]
1666     fn test_mut_slice_to() {
1667         let mut values = Vec::from_slice([1u8,2,3,4,5]);
1668         {
1669             let slice = values.mut_slice_to(2);
1670             assert!(slice == [1, 2]);
1671             for p in slice.mut_iter() {
1672                 *p += 1;
1673             }
1674         }
1675
1676         assert!(values.as_slice() == [2, 3, 3, 4, 5]);
1677     }
1678
1679     #[test]
1680     fn test_mut_split_at() {
1681         let mut values = Vec::from_slice([1u8,2,3,4,5]);
1682         {
1683             let (left, right) = values.mut_split_at(2);
1684             assert!(left.slice(0, left.len()) == [1, 2]);
1685             for p in left.mut_iter() {
1686                 *p += 1;
1687             }
1688
1689             assert!(right.slice(0, right.len()) == [3, 4, 5]);
1690             for p in right.mut_iter() {
1691                 *p += 2;
1692             }
1693         }
1694
1695         assert!(values == Vec::from_slice([2u8, 3, 5, 6, 7]));
1696     }
1697
1698     #[test]
1699     fn test_clone() {
1700         let v: Vec<int> = vec!();
1701         let w = vec!(1i, 2, 3);
1702
1703         assert_eq!(v, v.clone());
1704
1705         let z = w.clone();
1706         assert_eq!(w, z);
1707         // they should be disjoint in memory.
1708         assert!(w.as_ptr() != z.as_ptr())
1709     }
1710
1711     #[test]
1712     fn test_clone_from() {
1713         let mut v = vec!();
1714         let three = vec!(box 1i, box 2, box 3);
1715         let two = vec!(box 4i, box 5);
1716         // zero, long
1717         v.clone_from(&three);
1718         assert_eq!(v, three);
1719
1720         // equal
1721         v.clone_from(&three);
1722         assert_eq!(v, three);
1723
1724         // long, short
1725         v.clone_from(&two);
1726         assert_eq!(v, two);
1727
1728         // short, long
1729         v.clone_from(&three);
1730         assert_eq!(v, three)
1731     }
1732
1733     #[test]
1734     fn test_grow_fn() {
1735         let mut v = Vec::from_slice([0u, 1]);
1736         v.grow_fn(3, |i| i);
1737         assert!(v == Vec::from_slice([0u, 1, 0, 1, 2]));
1738     }
1739
1740     #[test]
1741     fn test_retain() {
1742         let mut vec = Vec::from_slice([1u, 2, 3, 4]);
1743         vec.retain(|x| x%2 == 0);
1744         assert!(vec == Vec::from_slice([2u, 4]));
1745     }
1746
1747     #[test]
1748     fn zero_sized_values() {
1749         let mut v = Vec::new();
1750         assert_eq!(v.len(), 0);
1751         v.push(());
1752         assert_eq!(v.len(), 1);
1753         v.push(());
1754         assert_eq!(v.len(), 2);
1755         assert_eq!(v.pop(), Some(()));
1756         assert_eq!(v.pop(), Some(()));
1757         assert_eq!(v.pop(), None);
1758
1759         assert_eq!(v.iter().count(), 0);
1760         v.push(());
1761         assert_eq!(v.iter().count(), 1);
1762         v.push(());
1763         assert_eq!(v.iter().count(), 2);
1764
1765         for &() in v.iter() {}
1766
1767         assert_eq!(v.mut_iter().count(), 2);
1768         v.push(());
1769         assert_eq!(v.mut_iter().count(), 3);
1770         v.push(());
1771         assert_eq!(v.mut_iter().count(), 4);
1772
1773         for &() in v.mut_iter() {}
1774         unsafe { v.set_len(0); }
1775         assert_eq!(v.mut_iter().count(), 0);
1776     }
1777
1778     #[test]
1779     fn test_partition() {
1780         assert_eq!(vec![].partition(|x: &int| *x < 3), (vec![], vec![]));
1781         assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1782         assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1783         assert_eq!(vec![1i, 2, 3].partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1784     }
1785
1786     #[test]
1787     fn test_partitioned() {
1788         assert_eq!(vec![].partitioned(|x: &int| *x < 3), (vec![], vec![]))
1789         assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1790         assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1791         assert_eq!(vec![1i, 2, 3].partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1792     }
1793
1794     #[test]
1795     fn test_zip_unzip() {
1796         let z1 = vec![(1i, 4i), (2, 5), (3, 6)];
1797
1798         let (left, right) = unzip(z1.iter().map(|&x| x));
1799
1800         let (left, right) = (left.as_slice(), right.as_slice());
1801         assert_eq!((1, 4), (left[0], right[0]));
1802         assert_eq!((2, 5), (left[1], right[1]));
1803         assert_eq!((3, 6), (left[2], right[2]));
1804     }
1805
1806     #[test]
1807     fn test_unsafe_ptrs() {
1808         unsafe {
1809             // Test on-stack copy-from-buf.
1810             let a = [1i, 2, 3];
1811             let ptr = a.as_ptr();
1812             let b = raw::from_buf(ptr, 3u);
1813             assert_eq!(b, vec![1, 2, 3]);
1814
1815             // Test on-heap copy-from-buf.
1816             let c = vec![1i, 2, 3, 4, 5];
1817             let ptr = c.as_ptr();
1818             let d = raw::from_buf(ptr, 5u);
1819             assert_eq!(d, vec![1, 2, 3, 4, 5]);
1820         }
1821     }
1822
1823     #[test]
1824     fn test_vec_truncate_drop() {
1825         static mut drops: uint = 0;
1826         struct Elem(int);
1827         impl Drop for Elem {
1828             fn drop(&mut self) {
1829                 unsafe { drops += 1; }
1830             }
1831         }
1832
1833         let mut v = vec![Elem(1), Elem(2), Elem(3), Elem(4), Elem(5)];
1834         assert_eq!(unsafe { drops }, 0);
1835         v.truncate(3);
1836         assert_eq!(unsafe { drops }, 2);
1837         v.truncate(0);
1838         assert_eq!(unsafe { drops }, 5);
1839     }
1840
1841     #[test]
1842     #[should_fail]
1843     fn test_vec_truncate_fail() {
1844         struct BadElem(int);
1845         impl Drop for BadElem {
1846             fn drop(&mut self) {
1847                 let BadElem(ref mut x) = *self;
1848                 if *x == 0xbadbeef {
1849                     fail!("BadElem failure: 0xbadbeef")
1850                 }
1851             }
1852         }
1853
1854         let mut v = vec![BadElem(1), BadElem(2), BadElem(0xbadbeef), BadElem(4)];
1855         v.truncate(0);
1856     }
1857
1858     #[bench]
1859     fn bench_new(b: &mut Bencher) {
1860         b.iter(|| {
1861             let v: Vec<int> = Vec::new();
1862             assert_eq!(v.capacity(), 0);
1863             assert!(v.as_slice() == []);
1864         })
1865     }
1866
1867     #[bench]
1868     fn bench_with_capacity_0(b: &mut Bencher) {
1869         b.iter(|| {
1870             let v: Vec<int> = Vec::with_capacity(0);
1871             assert_eq!(v.capacity(), 0);
1872             assert!(v.as_slice() == []);
1873         })
1874     }
1875
1876
1877     #[bench]
1878     fn bench_with_capacity_5(b: &mut Bencher) {
1879         b.iter(|| {
1880             let v: Vec<int> = Vec::with_capacity(5);
1881             assert_eq!(v.capacity(), 5);
1882             assert!(v.as_slice() == []);
1883         })
1884     }
1885
1886     #[bench]
1887     fn bench_with_capacity_100(b: &mut Bencher) {
1888         b.iter(|| {
1889             let v: Vec<int> = Vec::with_capacity(100);
1890             assert_eq!(v.capacity(), 100);
1891             assert!(v.as_slice() == []);
1892         })
1893     }
1894
1895     #[bench]
1896     fn bench_from_fn_0(b: &mut Bencher) {
1897         b.iter(|| {
1898             let v: Vec<int> = Vec::from_fn(0, |_| 5);
1899             assert!(v.as_slice() == []);
1900         })
1901     }
1902
1903     #[bench]
1904     fn bench_from_fn_5(b: &mut Bencher) {
1905         b.iter(|| {
1906             let v: Vec<int> = Vec::from_fn(5, |_| 5);
1907             assert!(v.as_slice() == [5, 5, 5, 5, 5]);
1908         })
1909     }
1910
1911     #[bench]
1912     fn bench_from_slice_0(b: &mut Bencher) {
1913         b.iter(|| {
1914             let v: Vec<int> = Vec::from_slice([]);
1915             assert!(v.as_slice() == []);
1916         })
1917     }
1918
1919     #[bench]
1920     fn bench_from_slice_5(b: &mut Bencher) {
1921         b.iter(|| {
1922             let v: Vec<int> = Vec::from_slice([1i, 2, 3, 4, 5]);
1923             assert!(v.as_slice() == [1, 2, 3, 4, 5]);
1924         })
1925     }
1926
1927     #[bench]
1928     fn bench_from_iter_0(b: &mut Bencher) {
1929         b.iter(|| {
1930             let v0: Vec<int> = vec!();
1931             let v1: Vec<int> = FromIterator::from_iter(v0.move_iter());
1932             assert!(v1.as_slice() == []);
1933         })
1934     }
1935
1936     #[bench]
1937     fn bench_from_iter_5(b: &mut Bencher) {
1938         b.iter(|| {
1939             let v0: Vec<int> = vec!(1, 2, 3, 4, 5);
1940             let v1: Vec<int> = FromIterator::from_iter(v0.move_iter());
1941             assert!(v1.as_slice() == [1, 2, 3, 4, 5]);
1942         })
1943     }
1944
1945     #[bench]
1946     fn bench_extend_0(b: &mut Bencher) {
1947         b.iter(|| {
1948             let v0: Vec<int> = vec!();
1949             let mut v1: Vec<int> = vec!(1, 2, 3, 4, 5);
1950             v1.extend(v0.move_iter());
1951             assert!(v1.as_slice() == [1, 2, 3, 4, 5]);
1952         })
1953     }
1954
1955     #[bench]
1956     fn bench_extend_5(b: &mut Bencher) {
1957         b.iter(|| {
1958             let v0: Vec<int> = vec!(1, 2, 3, 4, 5);
1959             let mut v1: Vec<int> = vec!(1, 2, 3, 4, 5);
1960             v1.extend(v0.move_iter());
1961             assert!(v1.as_slice() == [1, 2, 3, 4, 5, 1, 2, 3, 4, 5]);
1962         })
1963     }
1964 }