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