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