]> git.lizzy.rs Git - rust.git/blob - src/libstd/vec.rs
auto merge of #10977 : brson/rust/androidtest, r=brson
[rust.git] / src / libstd / vec.rs
1 // Copyright 2012-2013 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 /*!
12
13 Vector manipulation
14
15 The `vec` module contains useful code to help work with vector values.
16 Vectors are Rust's list type. Vectors contain zero or more values of
17 homogeneous types:
18
19 ```rust
20 let int_vector = [1,2,3];
21 let str_vector = ["one", "two", "three"];
22  ```
23
24 This is a big module, but for a high-level overview:
25
26 ## Structs
27
28 Several structs that are useful for vectors, such as `VecIterator`, which
29 represents iteration over a vector.
30
31 ## Traits
32
33 A number of traits add methods that allow you to accomplish tasks with vectors.
34
35 Traits defined for the `&[T]` type (a vector slice), have methods that can be
36 called on either owned vectors, denoted `~[T]`, or on vector slices themselves.
37 These traits include `ImmutableVector`, and `MutableVector` for the `&mut [T]`
38 case.
39
40 An example is the method `.slice(a, b)` that returns an immutable "view" into
41 a vector or a vector slice from the index interval `[a, b)`:
42
43 ```rust
44 let numbers = [0, 1, 2];
45 let last_numbers = numbers.slice(1, 3);
46 // last_numbers is now &[1, 2]
47  ```
48
49 Traits defined for the `~[T]` type, like `OwnedVector`, can only be called
50 on such vectors. These methods deal with adding elements or otherwise changing
51 the allocation of the vector.
52
53 An example is the method `.push(element)` that will add an element at the end
54 of the vector:
55
56 ```rust
57 let mut numbers = ~[0, 1, 2];
58 numbers.push(7);
59 // numbers is now ~[0, 1, 2, 7];
60  ```
61
62 ## Implementations of other traits
63
64 Vectors are a very useful type, and so there's several implementations of
65 traits from other modules. Some notable examples:
66
67 * `Clone`
68 * `Eq`, `Ord`, `TotalEq`, `TotalOrd` -- vectors can be compared,
69   if the element type defines the corresponding trait.
70
71 ## Iteration
72
73 The method `iter()` returns an iteration value for a vector or a vector slice.
74 The iterator yields borrowed pointers to the vector's elements, so if the element
75 type of the vector is `int`, the element type of the iterator is `&int`.
76
77 ```rust
78 let numbers = [0, 1, 2];
79 for &x in numbers.iter() {
80     println!("{} is a number!", x);
81 }
82  ```
83
84 * `.rev_iter()` returns an iterator with the same values as `.iter()`,
85   but going in the reverse order, starting with the back element.
86 * `.mut_iter()` returns an iterator that allows modifying each value.
87 * `.move_iter()` converts an owned vector into an iterator that
88   moves out a value from the vector each iteration.
89 * Further iterators exist that split, chunk or permute the vector.
90
91 ## Function definitions
92
93 There are a number of free functions that create or take vectors, for example:
94
95 * Creating a vector, like `from_elem` and `from_fn`
96 * Creating a vector with a given size: `with_capacity`
97 * Modifying a vector and returning it, like `append`
98 * Operations on paired elements, like `unzip`.
99
100 */
101
102 #[warn(non_camel_case_types)];
103
104 use cast;
105 use ops::Drop;
106 use clone::{Clone, DeepClone};
107 use container::{Container, Mutable};
108 use cmp::{Eq, TotalOrd, Ordering, Less, Equal, Greater};
109 use cmp;
110 use default::Default;
111 use iter::*;
112 use libc::{c_char, c_void};
113 use num::{Integer, CheckedAdd, Saturating};
114 use option::{None, Option, Some};
115 use ptr::to_unsafe_ptr;
116 use ptr;
117 use ptr::RawPtr;
118 use rt::global_heap::{malloc_raw, realloc_raw, exchange_free};
119 use rt::local_heap::local_free;
120 use mem;
121 use mem::size_of;
122 use uint;
123 use unstable::finally::Finally;
124 use unstable::intrinsics;
125 use unstable::intrinsics::{get_tydesc, owns_managed};
126 use unstable::raw::{Box, Repr, Slice, Vec};
127 use util;
128
129 /**
130  * Creates and initializes an owned vector.
131  *
132  * Creates an owned vector of size `n_elts` and initializes the elements
133  * to the value returned by the function `op`.
134  */
135 pub fn from_fn<T>(n_elts: uint, op: |uint| -> T) -> ~[T] {
136     unsafe {
137         let mut v = with_capacity(n_elts);
138         let p = v.as_mut_ptr();
139         let mut i: uint = 0u;
140         (|| {
141             while i < n_elts {
142                 intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), op(i));
143                 i += 1u;
144             }
145         }).finally(|| {
146             v.set_len(i);
147         });
148         v
149     }
150 }
151
152 /**
153  * Creates and initializes an owned vector.
154  *
155  * Creates an owned vector of size `n_elts` and initializes the elements
156  * to the value `t`.
157  */
158 pub fn from_elem<T:Clone>(n_elts: uint, t: T) -> ~[T] {
159     // FIXME (#7136): manually inline from_fn for 2x plus speedup (sadly very
160     // important, from_elem is a bottleneck in borrowck!). Unfortunately it
161     // still is substantially slower than using the unsafe
162     // vec::with_capacity/ptr::set_memory for primitive types.
163     unsafe {
164         let mut v = with_capacity(n_elts);
165         let p = v.as_mut_ptr();
166         let mut i = 0u;
167         (|| {
168             while i < n_elts {
169                 intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), t.clone());
170                 i += 1u;
171             }
172         }).finally(|| {
173             v.set_len(i);
174         });
175         v
176     }
177 }
178
179 /// Creates a new vector with a capacity of `capacity`
180 #[inline]
181 pub fn with_capacity<T>(capacity: uint) -> ~[T] {
182     unsafe {
183         if owns_managed::<T>() {
184             let mut vec = ~[];
185             vec.reserve(capacity);
186             vec
187         } else {
188             let alloc = capacity * mem::nonzero_size_of::<T>();
189             let size = alloc + mem::size_of::<Vec<()>>();
190             if alloc / mem::nonzero_size_of::<T>() != capacity || size < alloc {
191                 fail!("vector size is too large: {}", capacity);
192             }
193             let ptr = malloc_raw(size) as *mut Vec<()>;
194             (*ptr).alloc = alloc;
195             (*ptr).fill = 0;
196             cast::transmute(ptr)
197         }
198     }
199 }
200
201 /**
202  * Builds a vector by calling a provided function with an argument
203  * function that pushes an element to the back of a vector.
204  * The initial capacity for the vector may optionally be specified.
205  *
206  * # Arguments
207  *
208  * * size - An option, maybe containing initial size of the vector to reserve
209  * * builder - A function that will construct the vector. It receives
210  *             as an argument a function that will push an element
211  *             onto the vector being constructed.
212  */
213 #[inline]
214 pub fn build<A>(size: Option<uint>, builder: |push: |v: A||) -> ~[A] {
215     let mut vec = with_capacity(size.unwrap_or(4));
216     builder(|x| vec.push(x));
217     vec
218 }
219
220 /// An iterator over the slices of a vector separated by elements that
221 /// match a predicate function.
222 pub struct SplitIterator<'a, T> {
223     priv v: &'a [T],
224     priv n: uint,
225     priv pred: 'a |t: &T| -> bool,
226     priv finished: bool
227 }
228
229 impl<'a, T> Iterator<&'a [T]> for SplitIterator<'a, T> {
230     #[inline]
231     fn next(&mut self) -> Option<&'a [T]> {
232         if self.finished { return None; }
233
234         if self.n == 0 {
235             self.finished = true;
236             return Some(self.v);
237         }
238
239         match self.v.iter().position(|x| (self.pred)(x)) {
240             None => {
241                 self.finished = true;
242                 Some(self.v)
243             }
244             Some(idx) => {
245                 let ret = Some(self.v.slice(0, idx));
246                 self.v = self.v.slice(idx + 1, self.v.len());
247                 self.n -= 1;
248                 ret
249             }
250         }
251     }
252
253     #[inline]
254     fn size_hint(&self) -> (uint, Option<uint>) {
255         if self.finished {
256             return (0, Some(0))
257         }
258         // if the predicate doesn't match anything, we yield one slice
259         // if it matches every element, we yield N+1 empty slices where
260         // N is either the number of elements or the number of splits.
261         match (self.v.len(), self.n) {
262             (0,_) => (1, Some(1)),
263             (_,0) => (1, Some(1)),
264             (l,n) => (1, cmp::min(l,n).checked_add(&1u))
265         }
266     }
267 }
268
269 /// An iterator over the slices of a vector separated by elements that
270 /// match a predicate function, from back to front.
271 pub struct RSplitIterator<'a, T> {
272     priv v: &'a [T],
273     priv n: uint,
274     priv pred: 'a |t: &T| -> bool,
275     priv finished: bool
276 }
277
278 impl<'a, T> Iterator<&'a [T]> for RSplitIterator<'a, T> {
279     #[inline]
280     fn next(&mut self) -> Option<&'a [T]> {
281         if self.finished { return None; }
282
283         if self.n == 0 {
284             self.finished = true;
285             return Some(self.v);
286         }
287
288         match self.v.iter().rposition(|x| (self.pred)(x)) {
289             None => {
290                 self.finished = true;
291                 Some(self.v)
292             }
293             Some(idx) => {
294                 let ret = Some(self.v.slice(idx + 1, self.v.len()));
295                 self.v = self.v.slice(0, idx);
296                 self.n -= 1;
297                 ret
298             }
299         }
300     }
301
302     #[inline]
303     fn size_hint(&self) -> (uint, Option<uint>) {
304         if self.finished {
305             return (0, Some(0))
306         }
307         match (self.v.len(), self.n) {
308             (0,_) => (1, Some(1)),
309             (_,0) => (1, Some(1)),
310             (l,n) => (1, cmp::min(l,n).checked_add(&1u))
311         }
312     }
313 }
314
315 // Appending
316
317 /// Iterates over the `rhs` vector, copying each element and appending it to the
318 /// `lhs`. Afterwards, the `lhs` is then returned for use again.
319 #[inline]
320 pub fn append<T:Clone>(lhs: ~[T], rhs: &[T]) -> ~[T] {
321     let mut v = lhs;
322     v.push_all(rhs);
323     v
324 }
325
326 /// Appends one element to the vector provided. The vector itself is then
327 /// returned for use again.
328 #[inline]
329 pub fn append_one<T>(lhs: ~[T], x: T) -> ~[T] {
330     let mut v = lhs;
331     v.push(x);
332     v
333 }
334
335 // Functional utilities
336
337 /**
338  * Apply a function to each element of a vector and return a concatenation
339  * of each result vector
340  */
341 pub fn flat_map<T, U>(v: &[T], f: |t: &T| -> ~[U]) -> ~[U] {
342     let mut result = ~[];
343     for elem in v.iter() { result.push_all_move(f(elem)); }
344     result
345 }
346
347 #[allow(missing_doc)]
348 pub trait VectorVector<T> {
349     // FIXME #5898: calling these .concat and .connect conflicts with
350     // StrVector::con{cat,nect}, since they have generic contents.
351     /// Flattens a vector of vectors of T into a single vector of T.
352     fn concat_vec(&self) -> ~[T];
353
354     /// Concatenate a vector of vectors, placing a given separator between each.
355     fn connect_vec(&self, sep: &T) -> ~[T];
356 }
357
358 impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
359     fn concat_vec(&self) -> ~[T] {
360         let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
361         let mut result = with_capacity(size);
362         for v in self.iter() {
363             result.push_all(v.as_slice())
364         }
365         result
366     }
367
368     fn connect_vec(&self, sep: &T) -> ~[T] {
369         let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
370         let mut result = with_capacity(size + self.len());
371         let mut first = true;
372         for v in self.iter() {
373             if first { first = false } else { result.push(sep.clone()) }
374             result.push_all(v.as_slice())
375         }
376         result
377     }
378 }
379
380 /**
381  * Convert an iterator of pairs into a pair of vectors.
382  *
383  * Returns a tuple containing two vectors where the i-th element of the first
384  * vector contains the first element of the i-th tuple of the input iterator,
385  * and the i-th element of the second vector contains the second element
386  * of the i-th tuple of the input iterator.
387  */
388 pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
389     let (lo, _) = iter.size_hint();
390     let mut ts = with_capacity(lo);
391     let mut us = with_capacity(lo);
392     for (t, u) in iter {
393         ts.push(t);
394         us.push(u);
395     }
396     (ts, us)
397 }
398
399 /// An Iterator that yields the element swaps needed to produce
400 /// a sequence of all possible permutations for an indexed sequence of
401 /// elements. Each permutation is only a single swap apart.
402 ///
403 /// The Steinhaus–Johnson–Trotter algorithm is used.
404 ///
405 /// Generates even and odd permutations alternately.
406 ///
407 /// The last generated swap is always (0, 1), and it returns the
408 /// sequence to its initial order.
409 pub struct ElementSwaps {
410     priv sdir: ~[SizeDirection],
411     /// If true, emit the last swap that returns the sequence to initial state
412     priv emit_reset: bool,
413 }
414
415 impl ElementSwaps {
416     /// Create an `ElementSwaps` iterator for a sequence of `length` elements
417     pub fn new(length: uint) -> ElementSwaps {
418         // Initialize `sdir` with a direction that position should move in
419         // (all negative at the beginning) and the `size` of the
420         // element (equal to the original index).
421         ElementSwaps{
422             emit_reset: true,
423             sdir: range(0, length)
424                     .map(|i| SizeDirection{ size: i, dir: Neg })
425                     .to_owned_vec()
426         }
427     }
428 }
429
430 enum Direction { Pos, Neg }
431
432 /// An Index and Direction together
433 struct SizeDirection {
434     size: uint,
435     dir: Direction,
436 }
437
438 impl Iterator<(uint, uint)> for ElementSwaps {
439     #[inline]
440     fn next(&mut self) -> Option<(uint, uint)> {
441         fn new_pos(i: uint, s: Direction) -> uint {
442             i + match s { Pos => 1, Neg => -1 }
443         }
444
445         // Find the index of the largest mobile element:
446         // The direction should point into the vector, and the
447         // swap should be with a smaller `size` element.
448         let max = self.sdir.iter().map(|&x| x).enumerate()
449                            .filter(|&(i, sd)|
450                                 new_pos(i, sd.dir) < self.sdir.len() &&
451                                 self.sdir[new_pos(i, sd.dir)].size < sd.size)
452                            .max_by(|&(_, sd)| sd.size);
453         match max {
454             Some((i, sd)) => {
455                 let j = new_pos(i, sd.dir);
456                 self.sdir.swap(i, j);
457
458                 // Swap the direction of each larger SizeDirection
459                 for x in self.sdir.mut_iter() {
460                     if x.size > sd.size {
461                         x.dir = match x.dir { Pos => Neg, Neg => Pos };
462                     }
463                 }
464                 Some((i, j))
465             },
466             None => if self.emit_reset && self.sdir.len() > 1 {
467                 self.emit_reset = false;
468                 Some((0, 1))
469             } else {
470                 None
471             }
472         }
473     }
474 }
475
476 /// An Iterator that uses `ElementSwaps` to iterate through
477 /// all possible permutations of a vector.
478 ///
479 /// The first iteration yields a clone of the vector as it is,
480 /// then each successive element is the vector with one
481 /// swap applied.
482 ///
483 /// Generates even and odd permutations alternately.
484 pub struct Permutations<T> {
485     priv swaps: ElementSwaps,
486     priv v: ~[T],
487 }
488
489 impl<T: Clone> Iterator<~[T]> for Permutations<T> {
490     #[inline]
491     fn next(&mut self) -> Option<~[T]> {
492         match self.swaps.next() {
493             None => None,
494             Some((a, b)) => {
495                 let elt = self.v.clone();
496                 self.v.swap(a, b);
497                 Some(elt)
498             }
499         }
500     }
501 }
502
503 /// An iterator over the (overlapping) slices of length `size` within
504 /// a vector.
505 #[deriving(Clone)]
506 pub struct WindowIter<'a, T> {
507     priv v: &'a [T],
508     priv size: uint
509 }
510
511 impl<'a, T> Iterator<&'a [T]> for WindowIter<'a, T> {
512     #[inline]
513     fn next(&mut self) -> Option<&'a [T]> {
514         if self.size > self.v.len() {
515             None
516         } else {
517             let ret = Some(self.v.slice(0, self.size));
518             self.v = self.v.slice(1, self.v.len());
519             ret
520         }
521     }
522
523     #[inline]
524     fn size_hint(&self) -> (uint, Option<uint>) {
525         if self.size > self.v.len() {
526             (0, Some(0))
527         } else {
528             let x = self.v.len() - self.size;
529             (x.saturating_add(1), x.checked_add(&1u))
530         }
531     }
532 }
533
534 /// An iterator over a vector in (non-overlapping) chunks (`size`
535 /// elements at a time).
536 ///
537 /// When the vector len is not evenly divided by the chunk size,
538 /// the last slice of the iteration will be the remainder.
539 #[deriving(Clone)]
540 pub struct ChunkIter<'a, T> {
541     priv v: &'a [T],
542     priv size: uint
543 }
544
545 impl<'a, T> Iterator<&'a [T]> for ChunkIter<'a, T> {
546     #[inline]
547     fn next(&mut self) -> Option<&'a [T]> {
548         if self.v.len() == 0 {
549             None
550         } else {
551             let chunksz = cmp::min(self.v.len(), self.size);
552             let (fst, snd) = (self.v.slice_to(chunksz),
553                               self.v.slice_from(chunksz));
554             self.v = snd;
555             Some(fst)
556         }
557     }
558
559     #[inline]
560     fn size_hint(&self) -> (uint, Option<uint>) {
561         if self.v.len() == 0 {
562             (0, Some(0))
563         } else {
564             let (n, rem) = self.v.len().div_rem(&self.size);
565             let n = if rem > 0 { n+1 } else { n };
566             (n, Some(n))
567         }
568     }
569 }
570
571 impl<'a, T> DoubleEndedIterator<&'a [T]> for ChunkIter<'a, T> {
572     #[inline]
573     fn next_back(&mut self) -> Option<&'a [T]> {
574         if self.v.len() == 0 {
575             None
576         } else {
577             let remainder = self.v.len() % self.size;
578             let chunksz = if remainder != 0 { remainder } else { self.size };
579             let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
580                               self.v.slice_from(self.v.len() - chunksz));
581             self.v = fst;
582             Some(snd)
583         }
584     }
585 }
586
587 impl<'a, T> RandomAccessIterator<&'a [T]> for ChunkIter<'a, T> {
588     #[inline]
589     fn indexable(&self) -> uint {
590         self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
591     }
592
593     #[inline]
594     fn idx(&self, index: uint) -> Option<&'a [T]> {
595         if index < self.indexable() {
596             let lo = index * self.size;
597             let mut hi = lo + self.size;
598             if hi < lo || hi > self.v.len() { hi = self.v.len(); }
599
600             Some(self.v.slice(lo, hi))
601         } else {
602             None
603         }
604     }
605 }
606
607 // Equality
608
609 #[cfg(not(test))]
610 #[allow(missing_doc)]
611 pub mod traits {
612     use super::*;
613
614     use clone::Clone;
615     use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Equiv};
616     use iter::order;
617     use ops::Add;
618
619     impl<'a,T:Eq> Eq for &'a [T] {
620         fn eq(&self, other: & &'a [T]) -> bool {
621             self.len() == other.len() &&
622                 order::eq(self.iter(), other.iter())
623         }
624         fn ne(&self, other: & &'a [T]) -> bool {
625             self.len() != other.len() ||
626                 order::ne(self.iter(), other.iter())
627         }
628     }
629
630     impl<T:Eq> Eq for ~[T] {
631         #[inline]
632         fn eq(&self, other: &~[T]) -> bool { self.as_slice() == *other }
633         #[inline]
634         fn ne(&self, other: &~[T]) -> bool { !self.eq(other) }
635     }
636
637     impl<T:Eq> Eq for @[T] {
638         #[inline]
639         fn eq(&self, other: &@[T]) -> bool { self.as_slice() == *other }
640         #[inline]
641         fn ne(&self, other: &@[T]) -> bool { !self.eq(other) }
642     }
643
644     impl<'a,T:TotalEq> TotalEq for &'a [T] {
645         fn equals(&self, other: & &'a [T]) -> bool {
646             self.len() == other.len() &&
647                 order::equals(self.iter(), other.iter())
648         }
649     }
650
651     impl<T:TotalEq> TotalEq for ~[T] {
652         #[inline]
653         fn equals(&self, other: &~[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
654     }
655
656     impl<T:TotalEq> TotalEq for @[T] {
657         #[inline]
658         fn equals(&self, other: &@[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
659     }
660
661     impl<'a,T:Eq, V: Vector<T>> Equiv<V> for &'a [T] {
662         #[inline]
663         fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
664     }
665
666     impl<'a,T:Eq, V: Vector<T>> Equiv<V> for ~[T] {
667         #[inline]
668         fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
669     }
670
671     impl<'a,T:Eq, V: Vector<T>> Equiv<V> for @[T] {
672         #[inline]
673         fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
674     }
675
676     impl<'a,T:TotalOrd> TotalOrd for &'a [T] {
677         fn cmp(&self, other: & &'a [T]) -> Ordering {
678             order::cmp(self.iter(), other.iter())
679         }
680     }
681
682     impl<T: TotalOrd> TotalOrd for ~[T] {
683         #[inline]
684         fn cmp(&self, other: &~[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
685     }
686
687     impl<T: TotalOrd> TotalOrd for @[T] {
688         #[inline]
689         fn cmp(&self, other: &@[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
690     }
691
692     impl<'a, T: Eq + Ord> Ord for &'a [T] {
693         fn lt(&self, other: & &'a [T]) -> bool {
694             order::lt(self.iter(), other.iter())
695         }
696         #[inline]
697         fn le(&self, other: & &'a [T]) -> bool {
698             order::le(self.iter(), other.iter())
699         }
700         #[inline]
701         fn ge(&self, other: & &'a [T]) -> bool {
702             order::ge(self.iter(), other.iter())
703         }
704         #[inline]
705         fn gt(&self, other: & &'a [T]) -> bool {
706             order::gt(self.iter(), other.iter())
707         }
708     }
709
710     impl<T: Eq + Ord> Ord for ~[T] {
711         #[inline]
712         fn lt(&self, other: &~[T]) -> bool { self.as_slice() < other.as_slice() }
713         #[inline]
714         fn le(&self, other: &~[T]) -> bool { self.as_slice() <= other.as_slice() }
715         #[inline]
716         fn ge(&self, other: &~[T]) -> bool { self.as_slice() >= other.as_slice() }
717         #[inline]
718         fn gt(&self, other: &~[T]) -> bool { self.as_slice() > other.as_slice() }
719     }
720
721     impl<T: Eq + Ord> Ord for @[T] {
722         #[inline]
723         fn lt(&self, other: &@[T]) -> bool { self.as_slice() < other.as_slice() }
724         #[inline]
725         fn le(&self, other: &@[T]) -> bool { self.as_slice() <= other.as_slice() }
726         #[inline]
727         fn ge(&self, other: &@[T]) -> bool { self.as_slice() >= other.as_slice() }
728         #[inline]
729         fn gt(&self, other: &@[T]) -> bool { self.as_slice() > other.as_slice() }
730     }
731
732     impl<'a,T:Clone, V: Vector<T>> Add<V, ~[T]> for &'a [T] {
733         #[inline]
734         fn add(&self, rhs: &V) -> ~[T] {
735             let mut res = with_capacity(self.len() + rhs.as_slice().len());
736             res.push_all(*self);
737             res.push_all(rhs.as_slice());
738             res
739         }
740     }
741
742     impl<T:Clone, V: Vector<T>> Add<V, ~[T]> for ~[T] {
743         #[inline]
744         fn add(&self, rhs: &V) -> ~[T] {
745             self.as_slice() + rhs.as_slice()
746         }
747     }
748 }
749
750 #[cfg(test)]
751 pub mod traits {}
752
753 /// Any vector that can be represented as a slice.
754 pub trait Vector<T> {
755     /// Work with `self` as a slice.
756     fn as_slice<'a>(&'a self) -> &'a [T];
757 }
758
759 impl<'a,T> Vector<T> for &'a [T] {
760     #[inline(always)]
761     fn as_slice<'a>(&'a self) -> &'a [T] { *self }
762 }
763
764 impl<T> Vector<T> for ~[T] {
765     #[inline(always)]
766     fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
767 }
768
769 impl<T> Vector<T> for @[T] {
770     #[inline(always)]
771     fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
772 }
773
774 impl<'a, T> Container for &'a [T] {
775     /// Returns the length of a vector
776     #[inline]
777     fn len(&self) -> uint {
778         self.repr().len
779     }
780 }
781
782 impl<T> Container for ~[T] {
783     /// Returns the length of a vector
784     #[inline]
785     fn len(&self) -> uint {
786         self.repr().len
787     }
788 }
789
790 /// Extension methods for vector slices with copyable elements
791 pub trait CopyableVector<T> {
792     /// Copy `self` into a new owned vector
793     fn to_owned(&self) -> ~[T];
794
795     /// Convert `self` into a owned vector, not making a copy if possible.
796     fn into_owned(self) -> ~[T];
797 }
798
799 /// Extension methods for vector slices
800 impl<'a, T: Clone> CopyableVector<T> for &'a [T] {
801     /// Returns a copy of `v`.
802     #[inline]
803     fn to_owned(&self) -> ~[T] {
804         let mut result = with_capacity(self.len());
805         for e in self.iter() {
806             result.push((*e).clone());
807         }
808         result
809     }
810
811     #[inline(always)]
812     fn into_owned(self) -> ~[T] { self.to_owned() }
813 }
814
815 /// Extension methods for owned vectors
816 impl<T: Clone> CopyableVector<T> for ~[T] {
817     #[inline]
818     fn to_owned(&self) -> ~[T] { self.clone() }
819
820     #[inline(always)]
821     fn into_owned(self) -> ~[T] { self }
822 }
823
824 /// Extension methods for managed vectors
825 impl<T: Clone> CopyableVector<T> for @[T] {
826     #[inline]
827     fn to_owned(&self) -> ~[T] { self.as_slice().to_owned() }
828
829     #[inline(always)]
830     fn into_owned(self) -> ~[T] { self.to_owned() }
831 }
832
833 /// Extension methods for vectors
834 pub trait ImmutableVector<'a, T> {
835     /**
836      * Returns a slice of self between `start` and `end`.
837      *
838      * Fails when `start` or `end` point outside the bounds of self,
839      * or when `start` > `end`.
840      */
841     fn slice(&self, start: uint, end: uint) -> &'a [T];
842
843     /**
844      * Returns a slice of self from `start` to the end of the vec.
845      *
846      * Fails when `start` points outside the bounds of self.
847      */
848     fn slice_from(&self, start: uint) -> &'a [T];
849
850     /**
851      * Returns a slice of self from the start of the vec to `end`.
852      *
853      * Fails when `end` points outside the bounds of self.
854      */
855     fn slice_to(&self, end: uint) -> &'a [T];
856     /// Returns an iterator over the vector
857     fn iter(self) -> VecIterator<'a, T>;
858     /// Returns a reversed iterator over a vector
859     fn rev_iter(self) -> RevIterator<'a, T>;
860     /// Returns an iterator over the subslices of the vector which are
861     /// separated by elements that match `pred`.  The matched element
862     /// is not contained in the subslices.
863     fn split(self, pred: 'a |&T| -> bool) -> SplitIterator<'a, T>;
864     /// Returns an iterator over the subslices of the vector which are
865     /// separated by elements that match `pred`, limited to splitting
866     /// at most `n` times.  The matched element is not contained in
867     /// the subslices.
868     fn splitn(self, n: uint, pred: 'a |&T| -> bool) -> SplitIterator<'a, T>;
869     /// Returns an iterator over the subslices of the vector which are
870     /// separated by elements that match `pred`. This starts at the
871     /// end of the vector and works backwards.  The matched element is
872     /// not contained in the subslices.
873     fn rsplit(self, pred: 'a |&T| -> bool) -> RSplitIterator<'a, T>;
874     /// Returns an iterator over the subslices of the vector which are
875     /// separated by elements that match `pred` limited to splitting
876     /// at most `n` times. This starts at the end of the vector and
877     /// works backwards.  The matched element is not contained in the
878     /// subslices.
879     fn rsplitn(self,  n: uint, pred: 'a |&T| -> bool) -> RSplitIterator<'a, T>;
880
881     /**
882      * Returns an iterator over all contiguous windows of length
883      * `size`. The windows overlap. If the vector is shorter than
884      * `size`, the iterator returns no values.
885      *
886      * # Failure
887      *
888      * Fails if `size` is 0.
889      *
890      * # Example
891      *
892      * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
893      * `[3,4]`):
894      *
895      * ```rust
896      * let v = &[1,2,3,4];
897      * for win in v.windows(2) {
898      *     println!("{:?}", win);
899      * }
900      * ```
901      *
902      */
903     fn windows(self, size: uint) -> WindowIter<'a, T>;
904     /**
905      *
906      * Returns an iterator over `size` elements of the vector at a
907      * time. The chunks do not overlap. If `size` does not divide the
908      * length of the vector, then the last chunk will not have length
909      * `size`.
910      *
911      * # Failure
912      *
913      * Fails if `size` is 0.
914      *
915      * # Example
916      *
917      * Print the vector two elements at a time (i.e. `[1,2]`,
918      * `[3,4]`, `[5]`):
919      *
920      * ```rust
921      * let v = &[1,2,3,4,5];
922      * for win in v.chunks(2) {
923      *     println!("{:?}", win);
924      * }
925      * ```
926      *
927      */
928     fn chunks(self, size: uint) -> ChunkIter<'a, T>;
929
930     /// Returns the element of a vector at the given index, or `None` if the
931     /// index is out of bounds
932     fn get_opt(&self, index: uint) -> Option<&'a T>;
933     /// Returns the first element of a vector, failing if the vector is empty.
934     fn head(&self) -> &'a T;
935     /// Returns the first element of a vector, or `None` if it is empty
936     fn head_opt(&self) -> Option<&'a T>;
937     /// Returns all but the first element of a vector
938     fn tail(&self) -> &'a [T];
939     /// Returns all but the first `n' elements of a vector
940     fn tailn(&self, n: uint) -> &'a [T];
941     /// Returns all but the last element of a vector
942     fn init(&self) -> &'a [T];
943     /// Returns all but the last `n' elements of a vector
944     fn initn(&self, n: uint) -> &'a [T];
945     /// Returns the last element of a vector, failing if the vector is empty.
946     fn last(&self) -> &'a T;
947     /// Returns the last element of a vector, or `None` if it is empty.
948     fn last_opt(&self) -> Option<&'a T>;
949     /**
950      * Apply a function to each element of a vector and return a concatenation
951      * of each result vector
952      */
953     fn flat_map<U>(&self, f: |t: &T| -> ~[U]) -> ~[U];
954     /// Returns a pointer to the element at the given index, without doing
955     /// bounds checking.
956     unsafe fn unsafe_ref(&self, index: uint) -> *T;
957
958     /**
959      * Returns an unsafe pointer to the vector's buffer
960      *
961      * The caller must ensure that the vector outlives the pointer this
962      * function returns, or else it will end up pointing to garbage.
963      *
964      * Modifying the vector may cause its buffer to be reallocated, which
965      * would also make any pointers to it invalid.
966      */
967     fn as_ptr(&self) -> *T;
968
969     /**
970      * Binary search a sorted vector with a comparator function.
971      *
972      * The comparator function should implement an order consistent
973      * with the sort order of the underlying vector, returning an
974      * order code that indicates whether its argument is `Less`,
975      * `Equal` or `Greater` the desired target.
976      *
977      * Returns the index where the comparator returned `Equal`, or `None` if
978      * not found.
979      */
980     fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
981
982     /// Deprecated, use iterators where possible
983     /// (`self.iter().map(f)`). Apply a function to each element
984     /// of a vector and return the results.
985     fn map<U>(&self, |t: &T| -> U) -> ~[U];
986
987     /**
988      * Returns a mutable reference to the first element in this slice
989      * and adjusts the slice in place so that it no longer contains
990      * that element. O(1).
991      *
992      * Equivalent to:
993      *
994      * ```
995      *     let head = &self[0];
996      *     *self = self.slice_from(1);
997      *     head
998      * ```
999      *
1000      * Fails if slice is empty.
1001      */
1002     fn shift_ref(&mut self) -> &'a T;
1003
1004     /**
1005      * Returns a mutable reference to the last element in this slice
1006      * and adjusts the slice in place so that it no longer contains
1007      * that element. O(1).
1008      *
1009      * Equivalent to:
1010      *
1011      * ```
1012      *     let tail = &self[self.len() - 1];
1013      *     *self = self.slice_to(self.len() - 1);
1014      *     tail
1015      * ```
1016      *
1017      * Fails if slice is empty.
1018      */
1019     fn pop_ref(&mut self) -> &'a T;
1020 }
1021
1022 impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
1023     #[inline]
1024     fn slice(&self, start: uint, end: uint) -> &'a [T] {
1025         assert!(start <= end);
1026         assert!(end <= self.len());
1027         unsafe {
1028             cast::transmute(Slice {
1029                     data: self.as_ptr().offset(start as int),
1030                     len: (end - start)
1031                 })
1032         }
1033     }
1034
1035     #[inline]
1036     fn slice_from(&self, start: uint) -> &'a [T] {
1037         self.slice(start, self.len())
1038     }
1039
1040     #[inline]
1041     fn slice_to(&self, end: uint) -> &'a [T] {
1042         self.slice(0, end)
1043     }
1044
1045     #[inline]
1046     fn iter(self) -> VecIterator<'a, T> {
1047         unsafe {
1048             let p = self.as_ptr();
1049             if mem::size_of::<T>() == 0 {
1050                 VecIterator{ptr: p,
1051                             end: (p as uint + self.len()) as *T,
1052                             lifetime: None}
1053             } else {
1054                 VecIterator{ptr: p,
1055                             end: p.offset(self.len() as int),
1056                             lifetime: None}
1057             }
1058         }
1059     }
1060
1061     #[inline]
1062     fn rev_iter(self) -> RevIterator<'a, T> {
1063         self.iter().invert()
1064     }
1065
1066     #[inline]
1067     fn split(self, pred: 'a |&T| -> bool) -> SplitIterator<'a, T> {
1068         self.splitn(uint::max_value, pred)
1069     }
1070
1071     #[inline]
1072     fn splitn(self, n: uint, pred: 'a |&T| -> bool) -> SplitIterator<'a, T> {
1073         SplitIterator {
1074             v: self,
1075             n: n,
1076             pred: pred,
1077             finished: false
1078         }
1079     }
1080
1081     #[inline]
1082     fn rsplit(self, pred: 'a |&T| -> bool) -> RSplitIterator<'a, T> {
1083         self.rsplitn(uint::max_value, pred)
1084     }
1085
1086     #[inline]
1087     fn rsplitn(self, n: uint, pred: 'a |&T| -> bool) -> RSplitIterator<'a, T> {
1088         RSplitIterator {
1089             v: self,
1090             n: n,
1091             pred: pred,
1092             finished: false
1093         }
1094     }
1095
1096     #[inline]
1097     fn windows(self, size: uint) -> WindowIter<'a, T> {
1098         assert!(size != 0);
1099         WindowIter { v: self, size: size }
1100     }
1101
1102     #[inline]
1103     fn chunks(self, size: uint) -> ChunkIter<'a, T> {
1104         assert!(size != 0);
1105         ChunkIter { v: self, size: size }
1106     }
1107
1108     #[inline]
1109     fn get_opt(&self, index: uint) -> Option<&'a T> {
1110         if index < self.len() { Some(&self[index]) } else { None }
1111     }
1112
1113     #[inline]
1114     fn head(&self) -> &'a T {
1115         if self.len() == 0 { fail!("head: empty vector") }
1116         &self[0]
1117     }
1118
1119     #[inline]
1120     fn head_opt(&self) -> Option<&'a T> {
1121         if self.len() == 0 { None } else { Some(&self[0]) }
1122     }
1123
1124     #[inline]
1125     fn tail(&self) -> &'a [T] { self.slice(1, self.len()) }
1126
1127     #[inline]
1128     fn tailn(&self, n: uint) -> &'a [T] { self.slice(n, self.len()) }
1129
1130     #[inline]
1131     fn init(&self) -> &'a [T] {
1132         self.slice(0, self.len() - 1)
1133     }
1134
1135     #[inline]
1136     fn initn(&self, n: uint) -> &'a [T] {
1137         self.slice(0, self.len() - n)
1138     }
1139
1140     #[inline]
1141     fn last(&self) -> &'a T {
1142         if self.len() == 0 { fail!("last: empty vector") }
1143         &self[self.len() - 1]
1144     }
1145
1146     #[inline]
1147     fn last_opt(&self) -> Option<&'a T> {
1148             if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
1149     }
1150
1151     #[inline]
1152     fn flat_map<U>(&self, f: |t: &T| -> ~[U]) -> ~[U] {
1153         flat_map(*self, f)
1154     }
1155
1156     #[inline]
1157     unsafe fn unsafe_ref(&self, index: uint) -> *T {
1158         self.repr().data.offset(index as int)
1159     }
1160
1161     #[inline]
1162     fn as_ptr(&self) -> *T {
1163         self.repr().data
1164     }
1165
1166
1167     fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint> {
1168         let mut base : uint = 0;
1169         let mut lim : uint = self.len();
1170
1171         while lim != 0 {
1172             let ix = base + (lim >> 1);
1173             match f(&self[ix]) {
1174                 Equal => return Some(ix),
1175                 Less => {
1176                     base = ix + 1;
1177                     lim -= 1;
1178                 }
1179                 Greater => ()
1180             }
1181             lim >>= 1;
1182         }
1183         return None;
1184     }
1185
1186     fn map<U>(&self, f: |t: &T| -> U) -> ~[U] {
1187         self.iter().map(f).collect()
1188     }
1189
1190     fn shift_ref(&mut self) -> &'a T {
1191         unsafe {
1192             let s: &mut Slice<T> = cast::transmute(self);
1193             &*raw::shift_ptr(s)
1194         }
1195     }
1196
1197     fn pop_ref(&mut self) -> &'a T {
1198         unsafe {
1199             let s: &mut Slice<T> = cast::transmute(self);
1200             &*raw::pop_ptr(s)
1201         }
1202     }
1203 }
1204
1205 /// Extension methods for vectors contain `Eq` elements.
1206 pub trait ImmutableEqVector<T:Eq> {
1207     /// Find the first index containing a matching value
1208     fn position_elem(&self, t: &T) -> Option<uint>;
1209
1210     /// Find the last index containing a matching value
1211     fn rposition_elem(&self, t: &T) -> Option<uint>;
1212
1213     /// Return true if a vector contains an element with the given value
1214     fn contains(&self, x: &T) -> bool;
1215
1216     /// Returns true if `needle` is a prefix of the vector.
1217     fn starts_with(&self, needle: &[T]) -> bool;
1218
1219     /// Returns true if `needle` is a suffix of the vector.
1220     fn ends_with(&self, needle: &[T]) -> bool;
1221 }
1222
1223 impl<'a,T:Eq> ImmutableEqVector<T> for &'a [T] {
1224     #[inline]
1225     fn position_elem(&self, x: &T) -> Option<uint> {
1226         self.iter().position(|y| *x == *y)
1227     }
1228
1229     #[inline]
1230     fn rposition_elem(&self, t: &T) -> Option<uint> {
1231         self.iter().rposition(|x| *x == *t)
1232     }
1233
1234     #[inline]
1235     fn contains(&self, x: &T) -> bool {
1236         self.iter().any(|elt| *x == *elt)
1237     }
1238
1239     #[inline]
1240     fn starts_with(&self, needle: &[T]) -> bool {
1241         let n = needle.len();
1242         self.len() >= n && needle == self.slice_to(n)
1243     }
1244
1245     #[inline]
1246     fn ends_with(&self, needle: &[T]) -> bool {
1247         let (m, n) = (self.len(), needle.len());
1248         m >= n && needle == self.slice_from(m - n)
1249     }
1250 }
1251
1252 /// Extension methods for vectors containing `TotalOrd` elements.
1253 pub trait ImmutableTotalOrdVector<T: TotalOrd> {
1254     /**
1255      * Binary search a sorted vector for a given element.
1256      *
1257      * Returns the index of the element or None if not found.
1258      */
1259     fn bsearch_elem(&self, x: &T) -> Option<uint>;
1260 }
1261
1262 impl<'a, T: TotalOrd> ImmutableTotalOrdVector<T> for &'a [T] {
1263     fn bsearch_elem(&self, x: &T) -> Option<uint> {
1264         self.bsearch(|p| p.cmp(x))
1265     }
1266 }
1267
1268 /// Extension methods for vectors containing `Clone` elements.
1269 pub trait ImmutableCopyableVector<T> {
1270     /**
1271      * Partitions the vector into those that satisfies the predicate, and
1272      * those that do not.
1273      */
1274     fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]);
1275
1276     /// Create an iterator that yields every possible permutation of the
1277     /// vector in succession.
1278     fn permutations(self) -> Permutations<T>;
1279 }
1280
1281 impl<'a,T:Clone> ImmutableCopyableVector<T> for &'a [T] {
1282     #[inline]
1283     fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]) {
1284         let mut lefts  = ~[];
1285         let mut rights = ~[];
1286
1287         for elt in self.iter() {
1288             if f(elt) {
1289                 lefts.push((*elt).clone());
1290             } else {
1291                 rights.push((*elt).clone());
1292             }
1293         }
1294
1295         (lefts, rights)
1296     }
1297
1298     fn permutations(self) -> Permutations<T> {
1299         Permutations{
1300             swaps: ElementSwaps::new(self.len()),
1301             v: self.to_owned(),
1302         }
1303     }
1304
1305 }
1306
1307 /// Extension methods for owned vectors.
1308 pub trait OwnedVector<T> {
1309     /// Creates a consuming iterator, that is, one that moves each
1310     /// value out of the vector (from start to end). The vector cannot
1311     /// be used after calling this.
1312     ///
1313     /// # Examples
1314     ///
1315     /// ```rust
1316     /// let v = ~[~"a", ~"b"];
1317     /// for s in v.move_iter() {
1318     ///   // s has type ~str, not &~str
1319     ///   println(s);
1320     /// }
1321     /// ```
1322     fn move_iter(self) -> MoveIterator<T>;
1323     /// Creates a consuming iterator that moves out of the vector in
1324     /// reverse order.
1325     fn move_rev_iter(self) -> MoveRevIterator<T>;
1326
1327     /**
1328      * Reserves capacity for exactly `n` elements in the given vector.
1329      *
1330      * If the capacity for `self` is already equal to or greater than the requested
1331      * capacity, then no action is taken.
1332      *
1333      * # Arguments
1334      *
1335      * * n - The number of elements to reserve space for
1336      *
1337      * # Failure
1338      *
1339      * This method always succeeds in reserving space for `n` elements, or it does
1340      * not return.
1341      */
1342     fn reserve(&mut self, n: uint);
1343     /**
1344      * Reserves capacity for at least `n` elements in the given vector.
1345      *
1346      * This function will over-allocate in order to amortize the allocation costs
1347      * in scenarios where the caller may need to repeatedly reserve additional
1348      * space.
1349      *
1350      * If the capacity for `self` is already equal to or greater than the requested
1351      * capacity, then no action is taken.
1352      *
1353      * # Arguments
1354      *
1355      * * n - The number of elements to reserve space for
1356      */
1357     fn reserve_at_least(&mut self, n: uint);
1358     /**
1359      * Reserves capacity for at least `n` additional elements in the given vector.
1360      *
1361      * # Failure
1362      *
1363      * Fails if the new required capacity overflows uint.
1364      *
1365      * May also fail if `reserve` fails.
1366      */
1367     fn reserve_additional(&mut self, n: uint);
1368     /// Returns the number of elements the vector can hold without reallocating.
1369     fn capacity(&self) -> uint;
1370     /// Shrink the capacity of the vector to match the length
1371     fn shrink_to_fit(&mut self);
1372
1373     /// Append an element to a vector
1374     fn push(&mut self, t: T);
1375     /// Takes ownership of the vector `rhs`, moving all elements into
1376     /// the current vector. This does not copy any elements, and it is
1377     /// illegal to use the `rhs` vector after calling this method
1378     /// (because it is moved here).
1379     ///
1380     /// # Example
1381     ///
1382     /// ```rust
1383     /// let mut a = ~[~1];
1384     /// a.push_all_move(~[~2, ~3, ~4]);
1385     /// assert!(a == ~[~1, ~2, ~3, ~4]);
1386     /// ```
1387     fn push_all_move(&mut self, rhs: ~[T]);
1388     /// Remove the last element from a vector and return it, failing if it is empty
1389     fn pop(&mut self) -> T;
1390     /// Remove the last element from a vector and return it, or `None` if it is empty
1391     fn pop_opt(&mut self) -> Option<T>;
1392     /// Removes the first element from a vector and return it
1393     fn shift(&mut self) -> T;
1394     /// Removes the first element from a vector and return it, or `None` if it is empty
1395     fn shift_opt(&mut self) -> Option<T>;
1396     /// Prepend an element to the vector
1397     fn unshift(&mut self, x: T);
1398
1399     /// Insert an element at position i within v, shifting all
1400     /// elements after position i one position to the right.
1401     fn insert(&mut self, i: uint, x:T);
1402
1403     /// Remove and return the element at position i within v, shifting
1404     /// all elements after position i one position to the left.
1405     fn remove(&mut self, i: uint) -> T;
1406
1407     /**
1408      * Remove an element from anywhere in the vector and return it, replacing it
1409      * with the last element. This does not preserve ordering, but is O(1).
1410      *
1411      * Fails if index >= length.
1412      */
1413     fn swap_remove(&mut self, index: uint) -> T;
1414
1415     /// Shorten a vector, dropping excess elements.
1416     fn truncate(&mut self, newlen: uint);
1417
1418     /**
1419      * Like `filter()`, but in place.  Preserves order of `v`.  Linear time.
1420      */
1421     fn retain(&mut self, f: |t: &T| -> bool);
1422     /**
1423      * Partitions the vector into those that satisfies the predicate, and
1424      * those that do not.
1425      */
1426     fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]);
1427
1428     /**
1429      * Expands a vector in place, initializing the new elements to the result of
1430      * a function.
1431      *
1432      * Function `init_op` is called `n` times with the values [0..`n`)
1433      *
1434      * # Arguments
1435      *
1436      * * n - The number of elements to add
1437      * * init_op - A function to call to retrieve each appended element's
1438      *             value
1439      */
1440     fn grow_fn(&mut self, n: uint, op: |uint| -> T);
1441
1442     /**
1443      * Sets the length of a vector
1444      *
1445      * This will explicitly set the size of the vector, without actually
1446      * modifying its buffers, so it is up to the caller to ensure that
1447      * the vector is actually the specified size.
1448      */
1449     unsafe fn set_len(&mut self, new_len: uint);
1450 }
1451
1452 impl<T> OwnedVector<T> for ~[T] {
1453     #[inline]
1454     fn move_iter(self) -> MoveIterator<T> {
1455         unsafe {
1456             let iter = cast::transmute(self.iter());
1457             let ptr = cast::transmute(self);
1458             MoveIterator { allocation: ptr, iter: iter }
1459         }
1460     }
1461
1462     #[inline]
1463     fn move_rev_iter(self) -> MoveRevIterator<T> {
1464         self.move_iter().invert()
1465     }
1466
1467     fn reserve(&mut self, n: uint) {
1468         // Only make the (slow) call into the runtime if we have to
1469         if self.capacity() < n {
1470             unsafe {
1471                 let td = get_tydesc::<T>();
1472                 if owns_managed::<T>() {
1473                     let ptr: *mut *mut Box<Vec<()>> = cast::transmute(self);
1474                     ::at_vec::raw::reserve_raw(td, ptr, n);
1475                 } else {
1476                     let ptr: *mut *mut Vec<()> = cast::transmute(self);
1477                     let alloc = n * mem::nonzero_size_of::<T>();
1478                     let size = alloc + mem::size_of::<Vec<()>>();
1479                     if alloc / mem::nonzero_size_of::<T>() != n || size < alloc {
1480                         fail!("vector size is too large: {}", n);
1481                     }
1482                     *ptr = realloc_raw(*ptr as *mut c_void, size)
1483                            as *mut Vec<()>;
1484                     (**ptr).alloc = alloc;
1485                 }
1486             }
1487         }
1488     }
1489
1490     #[inline]
1491     fn reserve_at_least(&mut self, n: uint) {
1492         self.reserve(uint::next_power_of_two_opt(n).unwrap_or(n));
1493     }
1494
1495     #[inline]
1496     fn reserve_additional(&mut self, n: uint) {
1497         if self.capacity() - self.len() < n {
1498             match self.len().checked_add(&n) {
1499                 None => fail!("vec::reserve_additional: `uint` overflow"),
1500                 Some(new_cap) => self.reserve_at_least(new_cap)
1501             }
1502         }
1503     }
1504
1505     #[inline]
1506     fn capacity(&self) -> uint {
1507         unsafe {
1508             if owns_managed::<T>() {
1509                 let repr: **Box<Vec<()>> = cast::transmute(self);
1510                 (**repr).data.alloc / mem::nonzero_size_of::<T>()
1511             } else {
1512                 let repr: **Vec<()> = cast::transmute(self);
1513                 (**repr).alloc / mem::nonzero_size_of::<T>()
1514             }
1515         }
1516     }
1517
1518     fn shrink_to_fit(&mut self) {
1519         unsafe {
1520             let ptr: *mut *mut Vec<()> = cast::transmute(self);
1521             let alloc = (**ptr).fill;
1522             let size = alloc + mem::size_of::<Vec<()>>();
1523             *ptr = realloc_raw(*ptr as *mut c_void, size) as *mut Vec<()>;
1524             (**ptr).alloc = alloc;
1525         }
1526     }
1527
1528     #[inline]
1529     fn push(&mut self, t: T) {
1530         unsafe {
1531             if owns_managed::<T>() {
1532                 let repr: **Box<Vec<()>> = cast::transmute(&mut *self);
1533                 let fill = (**repr).data.fill;
1534                 if (**repr).data.alloc <= fill {
1535                     self.reserve_additional(1);
1536                 }
1537
1538                 push_fast(self, t);
1539             } else {
1540                 let repr: **Vec<()> = cast::transmute(&mut *self);
1541                 let fill = (**repr).fill;
1542                 if (**repr).alloc <= fill {
1543                     self.reserve_additional(1);
1544                 }
1545
1546                 push_fast(self, t);
1547             }
1548         }
1549
1550         // This doesn't bother to make sure we have space.
1551         #[inline] // really pretty please
1552         unsafe fn push_fast<T>(this: &mut ~[T], t: T) {
1553             if owns_managed::<T>() {
1554                 let repr: **mut Box<Vec<u8>> = cast::transmute(this);
1555                 let fill = (**repr).data.fill;
1556                 (**repr).data.fill += mem::nonzero_size_of::<T>();
1557                 let p = to_unsafe_ptr(&((**repr).data.data));
1558                 let p = ptr::offset(p, fill as int) as *mut T;
1559                 intrinsics::move_val_init(&mut(*p), t);
1560             } else {
1561                 let repr: **mut Vec<u8> = cast::transmute(this);
1562                 let fill = (**repr).fill;
1563                 (**repr).fill += mem::nonzero_size_of::<T>();
1564                 let p = to_unsafe_ptr(&((**repr).data));
1565                 let p = ptr::offset(p, fill as int) as *mut T;
1566                 intrinsics::move_val_init(&mut(*p), t);
1567             }
1568         }
1569
1570     }
1571
1572     #[inline]
1573     fn push_all_move(&mut self, mut rhs: ~[T]) {
1574         let self_len = self.len();
1575         let rhs_len = rhs.len();
1576         let new_len = self_len + rhs_len;
1577         self.reserve_additional(rhs.len());
1578         unsafe { // Note: infallible.
1579             let self_p = self.as_mut_ptr();
1580             let rhs_p = rhs.as_ptr();
1581             ptr::copy_memory(ptr::mut_offset(self_p, self_len as int), rhs_p, rhs_len);
1582             self.set_len(new_len);
1583             rhs.set_len(0);
1584         }
1585     }
1586
1587     fn pop_opt(&mut self) -> Option<T> {
1588         match self.len() {
1589             0  => None,
1590             ln => {
1591                 let valptr = ptr::to_mut_unsafe_ptr(&mut self[ln - 1u]);
1592                 unsafe {
1593                     self.set_len(ln - 1u);
1594                     Some(ptr::read_ptr(&*valptr))
1595                 }
1596             }
1597         }
1598     }
1599
1600
1601     #[inline]
1602     fn pop(&mut self) -> T {
1603         self.pop_opt().expect("pop: empty vector")
1604     }
1605
1606     #[inline]
1607     fn shift(&mut self) -> T {
1608         self.shift_opt().expect("shift: empty vector")
1609     }
1610
1611     fn shift_opt(&mut self) -> Option<T> {
1612         match self.len() {
1613             0 => None,
1614             1 => self.pop_opt(),
1615             2 => {
1616                 let last = self.pop();
1617                 let first = self.pop_opt();
1618                 self.push(last);
1619                 first
1620             }
1621             len => {
1622                 unsafe {
1623                     let next_len = len - 1;
1624
1625                     let ptr = self.as_ptr();
1626
1627                     // copy out the head element, for the moment it exists
1628                     // unsafely on the stack and as the first element of the
1629                     // vector.
1630                     let head = ptr::read_ptr(ptr);
1631
1632                     // Memcpy everything to the left one element (leaving the
1633                     // last element unsafely in two consecutive memory
1634                     // locations)
1635                     ptr::copy_memory(self.as_mut_ptr(), ptr.offset(1), next_len);
1636
1637                     // set the new length, which means the second instance of
1638                     // the last element is forgotten.
1639                     self.set_len(next_len);
1640
1641                     Some(head)
1642                 }
1643             }
1644         }
1645     }
1646
1647     fn unshift(&mut self, x: T) {
1648         let v = util::replace(self, ~[x]);
1649         self.push_all_move(v);
1650     }
1651     fn insert(&mut self, i: uint, x:T) {
1652         let len = self.len();
1653         assert!(i <= len);
1654
1655         self.push(x);
1656         let mut j = len;
1657         while j > i {
1658             self.swap(j, j - 1);
1659             j -= 1;
1660         }
1661     }
1662     fn remove(&mut self, i: uint) -> T {
1663         let len = self.len();
1664         assert!(i < len);
1665
1666         let mut j = i;
1667         while j < len - 1 {
1668             self.swap(j, j + 1);
1669             j += 1;
1670         }
1671         self.pop()
1672     }
1673     fn swap_remove(&mut self, index: uint) -> T {
1674         let ln = self.len();
1675         if index >= ln {
1676             fail!("vec::swap_remove - index {} >= length {}", index, ln);
1677         }
1678         if index < ln - 1 {
1679             self.swap(index, ln - 1);
1680         }
1681         self.pop()
1682     }
1683     fn truncate(&mut self, newlen: uint) {
1684         let oldlen = self.len();
1685         assert!(newlen <= oldlen);
1686
1687         unsafe {
1688             let p = self.as_mut_ptr();
1689             // This loop is optimized out for non-drop types.
1690             for i in range(newlen, oldlen) {
1691                 ptr::read_and_zero_ptr(p.offset(i as int));
1692             }
1693         }
1694         unsafe { self.set_len(newlen); }
1695     }
1696
1697     fn retain(&mut self, f: |t: &T| -> bool) {
1698         let len = self.len();
1699         let mut deleted: uint = 0;
1700
1701         for i in range(0u, len) {
1702             if !f(&self[i]) {
1703                 deleted += 1;
1704             } else if deleted > 0 {
1705                 self.swap(i - deleted, i);
1706             }
1707         }
1708
1709         if deleted > 0 {
1710             self.truncate(len - deleted);
1711         }
1712     }
1713
1714     #[inline]
1715     fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]) {
1716         let mut lefts  = ~[];
1717         let mut rights = ~[];
1718
1719         for elt in self.move_iter() {
1720             if f(&elt) {
1721                 lefts.push(elt);
1722             } else {
1723                 rights.push(elt);
1724             }
1725         }
1726
1727         (lefts, rights)
1728     }
1729     fn grow_fn(&mut self, n: uint, op: |uint| -> T) {
1730         let new_len = self.len() + n;
1731         self.reserve_at_least(new_len);
1732         let mut i: uint = 0u;
1733         while i < n {
1734             self.push(op(i));
1735             i += 1u;
1736         }
1737     }
1738     #[inline]
1739     unsafe fn set_len(&mut self, new_len: uint) {
1740         if owns_managed::<T>() {
1741             let repr: **mut Box<Vec<()>> = cast::transmute(self);
1742             (**repr).data.fill = new_len * mem::nonzero_size_of::<T>();
1743         } else {
1744             let repr: **mut Vec<()> = cast::transmute(self);
1745             (**repr).fill = new_len * mem::nonzero_size_of::<T>();
1746         }
1747     }
1748 }
1749
1750 impl<T> Mutable for ~[T] {
1751     /// Clear the vector, removing all values.
1752     fn clear(&mut self) { self.truncate(0) }
1753 }
1754
1755 /// Extension methods for owned vectors containing `Clone` elements.
1756 pub trait OwnedCopyableVector<T:Clone> {
1757     /// Iterates over the slice `rhs`, copies each element, and then appends it to
1758     /// the vector provided `v`. The `rhs` vector is traversed in-order.
1759     ///
1760     /// # Example
1761     ///
1762     /// ```rust
1763     /// let mut a = ~[1];
1764     /// a.push_all([2, 3, 4]);
1765     /// assert!(a == ~[1, 2, 3, 4]);
1766     /// ```
1767     fn push_all(&mut self, rhs: &[T]);
1768
1769     /**
1770      * Expands a vector in place, initializing the new elements to a given value
1771      *
1772      * # Arguments
1773      *
1774      * * n - The number of elements to add
1775      * * initval - The value for the new elements
1776      */
1777     fn grow(&mut self, n: uint, initval: &T);
1778
1779     /**
1780      * Sets the value of a vector element at a given index, growing the vector as
1781      * needed
1782      *
1783      * Sets the element at position `index` to `val`. If `index` is past the end
1784      * of the vector, expands the vector by replicating `initval` to fill the
1785      * intervening space.
1786      */
1787     fn grow_set(&mut self, index: uint, initval: &T, val: T);
1788 }
1789
1790 impl<T:Clone> OwnedCopyableVector<T> for ~[T] {
1791     #[inline]
1792     fn push_all(&mut self, rhs: &[T]) {
1793         let new_len = self.len() + rhs.len();
1794         self.reserve(new_len);
1795
1796         for elt in rhs.iter() {
1797             self.push((*elt).clone())
1798         }
1799     }
1800     fn grow(&mut self, n: uint, initval: &T) {
1801         let new_len = self.len() + n;
1802         self.reserve_at_least(new_len);
1803         let mut i: uint = 0u;
1804
1805         while i < n {
1806             self.push((*initval).clone());
1807             i += 1u;
1808         }
1809     }
1810     fn grow_set(&mut self, index: uint, initval: &T, val: T) {
1811         let l = self.len();
1812         if index >= l { self.grow(index - l + 1u, initval); }
1813         self[index] = val;
1814     }
1815 }
1816
1817 /// Extension methods for owned vectors containing `Eq` elements.
1818 pub trait OwnedEqVector<T:Eq> {
1819     /**
1820     * Remove consecutive repeated elements from a vector; if the vector is
1821     * sorted, this removes all duplicates.
1822     */
1823     fn dedup(&mut self);
1824 }
1825
1826 impl<T:Eq> OwnedEqVector<T> for ~[T] {
1827     fn dedup(&mut self) {
1828         unsafe {
1829             // Although we have a mutable reference to `self`, we cannot make
1830             // *arbitrary* changes. There exists the possibility that this
1831             // vector is contained with an `@mut` box and hence is still
1832             // readable by the outside world during the `Eq` comparisons.
1833             // Moreover, those comparisons could fail, so we must ensure
1834             // that the vector is in a valid state at all time.
1835             //
1836             // The way that we handle this is by using swaps; we iterate
1837             // over all the elements, swapping as we go so that at the end
1838             // the elements we wish to keep are in the front, and those we
1839             // wish to reject are at the back. We can then truncate the
1840             // vector. This operation is still O(n).
1841             //
1842             // Example: We start in this state, where `r` represents "next
1843             // read" and `w` represents "next_write`.
1844             //
1845             //           r
1846             //     +---+---+---+---+---+---+
1847             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1848             //     +---+---+---+---+---+---+
1849             //           w
1850             //
1851             // Comparing self[r] against self[w-1], tis is not a duplicate, so
1852             // we swap self[r] and self[w] (no effect as r==w) and then increment both
1853             // r and w, leaving us with:
1854             //
1855             //               r
1856             //     +---+---+---+---+---+---+
1857             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1858             //     +---+---+---+---+---+---+
1859             //               w
1860             //
1861             // Comparing self[r] against self[w-1], this value is a duplicate,
1862             // so we increment `r` but leave everything else unchanged:
1863             //
1864             //                   r
1865             //     +---+---+---+---+---+---+
1866             //     | 0 | 1 | 1 | 2 | 3 | 3 |
1867             //     +---+---+---+---+---+---+
1868             //               w
1869             //
1870             // Comparing self[r] against self[w-1], this is not a duplicate,
1871             // so swap self[r] and self[w] and advance r and w:
1872             //
1873             //                       r
1874             //     +---+---+---+---+---+---+
1875             //     | 0 | 1 | 2 | 1 | 3 | 3 |
1876             //     +---+---+---+---+---+---+
1877             //                   w
1878             //
1879             // Not a duplicate, repeat:
1880             //
1881             //                           r
1882             //     +---+---+---+---+---+---+
1883             //     | 0 | 1 | 2 | 3 | 1 | 3 |
1884             //     +---+---+---+---+---+---+
1885             //                       w
1886             //
1887             // Duplicate, advance r. End of vec. Truncate to w.
1888
1889             let ln = self.len();
1890             if ln < 1 { return; }
1891
1892             // Avoid bounds checks by using unsafe pointers.
1893             let p = self.as_mut_ptr();
1894             let mut r = 1;
1895             let mut w = 1;
1896
1897             while r < ln {
1898                 let p_r = ptr::mut_offset(p, r as int);
1899                 let p_wm1 = ptr::mut_offset(p, (w - 1) as int);
1900                 if *p_r != *p_wm1 {
1901                     if r != w {
1902                         let p_w = ptr::mut_offset(p_wm1, 1);
1903                         util::swap(&mut *p_r, &mut *p_w);
1904                     }
1905                     w += 1;
1906                 }
1907                 r += 1;
1908             }
1909
1910             self.truncate(w);
1911         }
1912     }
1913 }
1914
1915 /// Extension methods for vectors such that their elements are
1916 /// mutable.
1917 pub trait MutableVector<'a, T> {
1918     /// Return a slice that points into another slice.
1919     fn mut_slice(self, start: uint, end: uint) -> &'a mut [T];
1920
1921     /**
1922      * Returns a slice of self from `start` to the end of the vec.
1923      *
1924      * Fails when `start` points outside the bounds of self.
1925      */
1926     fn mut_slice_from(self, start: uint) -> &'a mut [T];
1927
1928     /**
1929      * Returns a slice of self from the start of the vec to `end`.
1930      *
1931      * Fails when `end` points outside the bounds of self.
1932      */
1933     fn mut_slice_to(self, end: uint) -> &'a mut [T];
1934
1935     /// Returns an iterator that allows modifying each value
1936     fn mut_iter(self) -> VecMutIterator<'a, T>;
1937
1938     /// Returns a reversed iterator that allows modifying each value
1939     fn mut_rev_iter(self) -> MutRevIterator<'a, T>;
1940
1941     /// Returns an iterator over the mutable subslices of the vector
1942     /// which are separated by elements that match `pred`.  The
1943     /// matched element is not contained in the subslices.
1944     fn mut_split(self, pred: 'a |&T| -> bool) -> MutSplitIterator<'a, T>;
1945
1946     /**
1947      * Returns an iterator over `size` elements of the vector at a time.
1948      * The chunks are mutable and do not overlap. If `size` does not divide the
1949      * length of the vector, then the last chunk will not have length
1950      * `size`.
1951      *
1952      * # Failure
1953      *
1954      * Fails if `size` is 0.
1955      */
1956     fn mut_chunks(self, chunk_size: uint) -> MutChunkIter<'a, T>;
1957
1958     /**
1959      * Returns a mutable reference to the first element in this slice
1960      * and adjusts the slice in place so that it no longer contains
1961      * that element. O(1).
1962      *
1963      * Equivalent to:
1964      *
1965      * ```
1966      *     let head = &mut self[0];
1967      *     *self = self.mut_slice_from(1);
1968      *     head
1969      * ```
1970      *
1971      * Fails if slice is empty.
1972      */
1973     fn mut_shift_ref(&mut self) -> &'a mut T;
1974
1975     /**
1976      * Returns a mutable reference to the last element in this slice
1977      * and adjusts the slice in place so that it no longer contains
1978      * that element. O(1).
1979      *
1980      * Equivalent to:
1981      *
1982      * ```
1983      *     let tail = &mut self[self.len() - 1];
1984      *     *self = self.mut_slice_to(self.len() - 1);
1985      *     tail
1986      * ```
1987      *
1988      * Fails if slice is empty.
1989      */
1990     fn mut_pop_ref(&mut self) -> &'a mut T;
1991
1992     /**
1993      * Swaps two elements in a vector
1994      *
1995      * # Arguments
1996      *
1997      * * a - The index of the first element
1998      * * b - The index of the second element
1999      */
2000     fn swap(self, a: uint, b: uint);
2001
2002     /**
2003      * Divides one `&mut` into two. The first will
2004      * contain all indices from `0..mid` (excluding the index `mid`
2005      * itself) and the second will contain all indices from
2006      * `mid..len` (excluding the index `len` itself).
2007      */
2008     fn mut_split_at(self, mid: uint) -> (&'a mut [T],
2009                                       &'a mut [T]);
2010
2011     /// Reverse the order of elements in a vector, in place
2012     fn reverse(self);
2013
2014     /**
2015      * Consumes `src` and moves as many elements as it can into `self`
2016      * from the range [start,end).
2017      *
2018      * Returns the number of elements copied (the shorter of self.len()
2019      * and end - start).
2020      *
2021      * # Arguments
2022      *
2023      * * src - A mutable vector of `T`
2024      * * start - The index into `src` to start copying from
2025      * * end - The index into `str` to stop copying from
2026      */
2027     fn move_from(self, src: ~[T], start: uint, end: uint) -> uint;
2028
2029     /// Returns an unsafe mutable pointer to the element in index
2030     unsafe fn unsafe_mut_ref(self, index: uint) -> *mut T;
2031
2032     /// Return an unsafe mutable pointer to the vector's buffer.
2033     ///
2034     /// The caller must ensure that the vector outlives the pointer this
2035     /// function returns, or else it will end up pointing to garbage.
2036     ///
2037     /// Modifying the vector may cause its buffer to be reallocated, which
2038     /// would also make any pointers to it invalid.
2039     #[inline]
2040     fn as_mut_ptr(self) -> *mut T;
2041
2042     /// Unsafely sets the element in index to the value
2043     unsafe fn unsafe_set(self, index: uint, val: T);
2044
2045     /**
2046      * Unchecked vector index assignment.  Does not drop the
2047      * old value and hence is only suitable when the vector
2048      * is newly allocated.
2049      */
2050     unsafe fn init_elem(self, i: uint, val: T);
2051
2052     /// Copies data from `src` to `self`.
2053     ///
2054     /// `self` and `src` must not overlap. Fails if `self` is
2055     /// shorter than `src`.
2056     unsafe fn copy_memory(self, src: &[T]);
2057 }
2058
2059 impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
2060     #[inline]
2061     fn mut_slice(self, start: uint, end: uint) -> &'a mut [T] {
2062         assert!(start <= end);
2063         assert!(end <= self.len());
2064         unsafe {
2065             cast::transmute(Slice {
2066                     data: self.as_mut_ptr().offset(start as int) as *T,
2067                     len: (end - start)
2068                 })
2069         }
2070     }
2071
2072     #[inline]
2073     fn mut_slice_from(self, start: uint) -> &'a mut [T] {
2074         let len = self.len();
2075         self.mut_slice(start, len)
2076     }
2077
2078     #[inline]
2079     fn mut_slice_to(self, end: uint) -> &'a mut [T] {
2080         self.mut_slice(0, end)
2081     }
2082
2083     #[inline]
2084     fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
2085         unsafe {
2086             let len = self.len();
2087             let self2: &'a mut [T] = cast::transmute_copy(&self);
2088             (self.mut_slice(0, mid), self2.mut_slice(mid, len))
2089         }
2090     }
2091
2092     #[inline]
2093     fn mut_iter(self) -> VecMutIterator<'a, T> {
2094         unsafe {
2095             let p = self.as_mut_ptr();
2096             if mem::size_of::<T>() == 0 {
2097                 VecMutIterator{ptr: p,
2098                                end: (p as uint + self.len()) as *mut T,
2099                                lifetime: None}
2100             } else {
2101                 VecMutIterator{ptr: p,
2102                                end: p.offset(self.len() as int),
2103                                lifetime: None}
2104             }
2105         }
2106     }
2107
2108     #[inline]
2109     fn mut_rev_iter(self) -> MutRevIterator<'a, T> {
2110         self.mut_iter().invert()
2111     }
2112
2113     #[inline]
2114     fn mut_split(self, pred: 'a |&T| -> bool) -> MutSplitIterator<'a, T> {
2115         MutSplitIterator { v: self, pred: pred, finished: false }
2116     }
2117
2118     #[inline]
2119     fn mut_chunks(self, chunk_size: uint) -> MutChunkIter<'a, T> {
2120         assert!(chunk_size > 0);
2121         let len = self.len();
2122         MutChunkIter { v: self, chunk_size: chunk_size, remaining: len }
2123     }
2124
2125     fn mut_shift_ref(&mut self) -> &'a mut T {
2126         unsafe {
2127             let s: &mut Slice<T> = cast::transmute(self);
2128             cast::transmute_mut(&*raw::shift_ptr(s))
2129         }
2130     }
2131
2132     fn mut_pop_ref(&mut self) -> &'a mut T {
2133         unsafe {
2134             let s: &mut Slice<T> = cast::transmute(self);
2135             cast::transmute_mut(&*raw::pop_ptr(s))
2136         }
2137     }
2138
2139     fn swap(self, a: uint, b: uint) {
2140         unsafe {
2141             // Can't take two mutable loans from one vector, so instead just cast
2142             // them to their raw pointers to do the swap
2143             let pa: *mut T = &mut self[a];
2144             let pb: *mut T = &mut self[b];
2145             ptr::swap_ptr(pa, pb);
2146         }
2147     }
2148
2149     fn reverse(self) {
2150         let mut i: uint = 0;
2151         let ln = self.len();
2152         while i < ln / 2 {
2153             self.swap(i, ln - i - 1);
2154             i += 1;
2155         }
2156     }
2157
2158     #[inline]
2159     fn move_from(self, mut src: ~[T], start: uint, end: uint) -> uint {
2160         for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
2161             util::swap(a, b);
2162         }
2163         cmp::min(self.len(), end-start)
2164     }
2165
2166     #[inline]
2167     unsafe fn unsafe_mut_ref(self, index: uint) -> *mut T {
2168         ptr::mut_offset(self.repr().data as *mut T, index as int)
2169     }
2170
2171     #[inline]
2172     fn as_mut_ptr(self) -> *mut T {
2173         self.repr().data as *mut T
2174     }
2175
2176     #[inline]
2177     unsafe fn unsafe_set(self, index: uint, val: T) {
2178         *self.unsafe_mut_ref(index) = val;
2179     }
2180
2181     #[inline]
2182     unsafe fn init_elem(self, i: uint, val: T) {
2183         intrinsics::move_val_init(&mut (*self.as_mut_ptr().offset(i as int)), val);
2184     }
2185
2186     #[inline]
2187     unsafe fn copy_memory(self, src: &[T]) {
2188         let len_src = src.len();
2189         assert!(self.len() >= len_src);
2190         ptr::copy_nonoverlapping_memory(self.as_mut_ptr(), src.as_ptr(), len_src)
2191     }
2192 }
2193
2194 /// Trait for &[T] where T is Cloneable
2195 pub trait MutableCloneableVector<T> {
2196     /// Copies as many elements from `src` as it can into `self`
2197     /// (the shorter of self.len() and src.len()). Returns the number of elements copied.
2198     fn copy_from(self, &[T]) -> uint;
2199 }
2200
2201 impl<'a, T:Clone> MutableCloneableVector<T> for &'a mut [T] {
2202     #[inline]
2203     fn copy_from(self, src: &[T]) -> uint {
2204         for (a, b) in self.mut_iter().zip(src.iter()) {
2205             a.clone_from(b);
2206         }
2207         cmp::min(self.len(), src.len())
2208     }
2209 }
2210
2211 /**
2212 * Constructs a vector from an unsafe pointer to a buffer
2213 *
2214 * # Arguments
2215 *
2216 * * ptr - An unsafe pointer to a buffer of `T`
2217 * * elts - The number of elements in the buffer
2218 */
2219 // Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
2220 pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
2221     raw::from_buf_raw(ptr, elts)
2222 }
2223
2224 /// Unsafe operations
2225 pub mod raw {
2226     use cast;
2227     use ptr;
2228     use vec::{with_capacity, MutableVector};
2229     use unstable::raw::Slice;
2230
2231     /**
2232      * Form a slice from a pointer and length (as a number of units,
2233      * not bytes).
2234      */
2235     #[inline]
2236     pub unsafe fn buf_as_slice<T,U>(p: *T, len: uint, f: |v: &[T]| -> U)
2237                                -> U {
2238         f(cast::transmute(Slice {
2239             data: p,
2240             len: len
2241         }))
2242     }
2243
2244     /**
2245      * Form a slice from a pointer and length (as a number of units,
2246      * not bytes).
2247      */
2248     #[inline]
2249     pub unsafe fn mut_buf_as_slice<T,
2250                                    U>(
2251                                    p: *mut T,
2252                                    len: uint,
2253                                    f: |v: &mut [T]| -> U)
2254                                    -> U {
2255         f(cast::transmute(Slice {
2256             data: p as *T,
2257             len: len
2258         }))
2259     }
2260
2261     /**
2262     * Constructs a vector from an unsafe pointer to a buffer
2263     *
2264     * # Arguments
2265     *
2266     * * ptr - An unsafe pointer to a buffer of `T`
2267     * * elts - The number of elements in the buffer
2268     */
2269     // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
2270     #[inline]
2271     pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
2272         let mut dst = with_capacity(elts);
2273         dst.set_len(elts);
2274         ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
2275         dst
2276     }
2277
2278     /**
2279      * Returns a pointer to first element in slice and adjusts
2280      * slice so it no longer contains that element. Fails if
2281      * slice is empty. O(1).
2282      */
2283     pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> *T {
2284         if slice.len == 0 { fail!("shift on empty slice"); }
2285         let head: *T = slice.data;
2286         slice.data = ptr::offset(slice.data, 1);
2287         slice.len -= 1;
2288         head
2289     }
2290
2291     /**
2292      * Returns a pointer to last element in slice and adjusts
2293      * slice so it no longer contains that element. Fails if
2294      * slice is empty. O(1).
2295      */
2296     pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> *T {
2297         if slice.len == 0 { fail!("pop on empty slice"); }
2298         let tail: *T = ptr::offset(slice.data, (slice.len - 1) as int);
2299         slice.len -= 1;
2300         tail
2301     }
2302 }
2303
2304 /// Operations on `[u8]`.
2305 pub mod bytes {
2306     use container::Container;
2307     use vec::MutableVector;
2308     use ptr;
2309
2310     /// A trait for operations on mutable `[u8]`s.
2311     pub trait MutableByteVector {
2312         /// Sets all bytes of the receiver to the given value.
2313         fn set_memory(self, value: u8);
2314     }
2315
2316     impl<'a> MutableByteVector for &'a mut [u8] {
2317         #[inline]
2318         fn set_memory(self, value: u8) {
2319             unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
2320         }
2321     }
2322
2323     /// Copies data from `src` to `dst`
2324     ///
2325     /// `src` and `dst` must not overlap. Fails if the length of `dst`
2326     /// is less than the length of `src`.
2327     #[inline]
2328     pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
2329         // Bound checks are done at .copy_memory.
2330         unsafe { dst.copy_memory(src) }
2331     }
2332
2333     /**
2334      * Allocate space in `dst` and append the data to `src`.
2335      */
2336     #[inline]
2337     pub fn push_bytes(dst: &mut ~[u8], src: &[u8]) {
2338         let old_len = dst.len();
2339         dst.reserve_additional(src.len());
2340         unsafe {
2341             ptr::copy_memory(dst.as_mut_ptr().offset(old_len as int), src.as_ptr(), src.len());
2342             dst.set_len(old_len + src.len());
2343         }
2344     }
2345 }
2346
2347 impl<A: Clone> Clone for ~[A] {
2348     #[inline]
2349     fn clone(&self) -> ~[A] {
2350         self.iter().map(|item| item.clone()).collect()
2351     }
2352
2353     fn clone_from(&mut self, source: &~[A]) {
2354         if self.len() < source.len() {
2355             *self = source.clone()
2356         } else {
2357             self.truncate(source.len());
2358             for (x, y) in self.mut_iter().zip(source.iter()) {
2359                 x.clone_from(y);
2360             }
2361         }
2362     }
2363 }
2364
2365 impl<A: DeepClone> DeepClone for ~[A] {
2366     #[inline]
2367     fn deep_clone(&self) -> ~[A] {
2368         self.iter().map(|item| item.deep_clone()).collect()
2369     }
2370
2371     fn deep_clone_from(&mut self, source: &~[A]) {
2372         if self.len() < source.len() {
2373             *self = source.deep_clone()
2374         } else {
2375             self.truncate(source.len());
2376             for (x, y) in self.mut_iter().zip(source.iter()) {
2377                 x.deep_clone_from(y);
2378             }
2379         }
2380     }
2381 }
2382
2383 // This works because every lifetime is a sub-lifetime of 'static
2384 impl<'a, A> Default for &'a [A] {
2385     fn default() -> &'a [A] { &'a [] }
2386 }
2387
2388 impl<A> Default for ~[A] {
2389     fn default() -> ~[A] { ~[] }
2390 }
2391
2392 impl<A> Default for @[A] {
2393     fn default() -> @[A] { @[] }
2394 }
2395
2396 macro_rules! iterator {
2397     (struct $name:ident -> $ptr:ty, $elem:ty) => {
2398         /// An iterator for iterating over a vector.
2399         pub struct $name<'a, T> {
2400             priv ptr: $ptr,
2401             priv end: $ptr,
2402             priv lifetime: Option<$elem> // FIXME: #5922
2403         }
2404
2405         impl<'a, T> Iterator<$elem> for $name<'a, T> {
2406             #[inline]
2407             fn next(&mut self) -> Option<$elem> {
2408                 // could be implemented with slices, but this avoids bounds checks
2409                 unsafe {
2410                     if self.ptr == self.end {
2411                         None
2412                     } else {
2413                         let old = self.ptr;
2414                         self.ptr = if mem::size_of::<T>() == 0 {
2415                             // purposefully don't use 'ptr.offset' because for
2416                             // vectors with 0-size elements this would return the
2417                             // same pointer.
2418                             cast::transmute(self.ptr as uint + 1)
2419                         } else {
2420                             self.ptr.offset(1)
2421                         };
2422
2423                         Some(cast::transmute(old))
2424                     }
2425                 }
2426             }
2427
2428             #[inline]
2429             fn size_hint(&self) -> (uint, Option<uint>) {
2430                 let diff = (self.end as uint) - (self.ptr as uint);
2431                 let exact = diff / mem::nonzero_size_of::<T>();
2432                 (exact, Some(exact))
2433             }
2434         }
2435
2436         impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
2437             #[inline]
2438             fn next_back(&mut self) -> Option<$elem> {
2439                 // could be implemented with slices, but this avoids bounds checks
2440                 unsafe {
2441                     if self.end == self.ptr {
2442                         None
2443                     } else {
2444                         self.end = if mem::size_of::<T>() == 0 {
2445                             // See above for why 'ptr.offset' isn't used
2446                             cast::transmute(self.end as uint - 1)
2447                         } else {
2448                             self.end.offset(-1)
2449                         };
2450                         Some(cast::transmute(self.end))
2451                     }
2452                 }
2453             }
2454         }
2455     }
2456 }
2457
2458 impl<'a, T> RandomAccessIterator<&'a T> for VecIterator<'a, T> {
2459     #[inline]
2460     fn indexable(&self) -> uint {
2461         let (exact, _) = self.size_hint();
2462         exact
2463     }
2464
2465     #[inline]
2466     fn idx(&self, index: uint) -> Option<&'a T> {
2467         unsafe {
2468             if index < self.indexable() {
2469                 cast::transmute(self.ptr.offset(index as int))
2470             } else {
2471                 None
2472             }
2473         }
2474     }
2475 }
2476
2477 iterator!{struct VecIterator -> *T, &'a T}
2478 pub type RevIterator<'a, T> = Invert<VecIterator<'a, T>>;
2479
2480 impl<'a, T> ExactSize<&'a T> for VecIterator<'a, T> {}
2481 impl<'a, T> ExactSize<&'a mut T> for VecMutIterator<'a, T> {}
2482
2483 impl<'a, T> Clone for VecIterator<'a, T> {
2484     fn clone(&self) -> VecIterator<'a, T> { *self }
2485 }
2486
2487 iterator!{struct VecMutIterator -> *mut T, &'a mut T}
2488 pub type MutRevIterator<'a, T> = Invert<VecMutIterator<'a, T>>;
2489
2490 /// An iterator over the subslices of the vector which are separated
2491 /// by elements that match `pred`.
2492 pub struct MutSplitIterator<'a, T> {
2493     priv v: &'a mut [T],
2494     priv pred: 'a |t: &T| -> bool,
2495     priv finished: bool
2496 }
2497
2498 impl<'a, T> Iterator<&'a mut [T]> for MutSplitIterator<'a, T> {
2499     #[inline]
2500     fn next(&mut self) -> Option<&'a mut [T]> {
2501         if self.finished { return None; }
2502
2503         match self.v.iter().position(|x| (self.pred)(x)) {
2504             None => {
2505                 self.finished = true;
2506                 let tmp = util::replace(&mut self.v, &mut []);
2507                 let len = tmp.len();
2508                 let (head, tail) = tmp.mut_split_at(len);
2509                 self.v = tail;
2510                 Some(head)
2511             }
2512             Some(idx) => {
2513                 let tmp = util::replace(&mut self.v, &mut []);
2514                 let (head, tail) = tmp.mut_split_at(idx);
2515                 self.v = tail.mut_slice_from(1);
2516                 Some(head)
2517             }
2518         }
2519     }
2520
2521     #[inline]
2522     fn size_hint(&self) -> (uint, Option<uint>) {
2523         if self.finished { return (0, Some(0)) }
2524
2525         // if the predicate doesn't match anything, we yield one slice
2526         // if it matches every element, we yield len+1 empty slices.
2527         // FIXME #9629
2528         //(1, Some(self.v.len() + 1))
2529         (1, None)
2530     }
2531 }
2532
2533 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplitIterator<'a, T> {
2534     #[inline]
2535     fn next_back(&mut self) -> Option<&'a mut [T]> {
2536         if self.finished { return None; }
2537
2538         match self.v.iter().rposition(|x| (self.pred)(x)) {
2539             None => {
2540                 self.finished = true;
2541                 let tmp = util::replace(&mut self.v, &mut []);
2542                 let len = tmp.len();
2543                 let (head, tail) = tmp.mut_split_at(len);
2544                 self.v = tail;
2545                 Some(head)
2546             }
2547             Some(idx) => {
2548                 let tmp = util::replace(&mut self.v, &mut []);
2549                 let (head, tail) = tmp.mut_split_at(idx);
2550                 self.v = head;
2551                 Some(tail.mut_slice_from(1))
2552             }
2553         }
2554     }
2555 }
2556
2557 /// An iterator over a vector in (non-overlapping) mutable chunks (`size`  elements at a time). When
2558 /// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be
2559 /// the remainder.
2560 pub struct MutChunkIter<'a, T> {
2561     priv v: &'a mut [T],
2562     priv chunk_size: uint,
2563     priv remaining: uint
2564 }
2565
2566 impl<'a, T> Iterator<&'a mut [T]> for MutChunkIter<'a, T> {
2567     #[inline]
2568     fn next(&mut self) -> Option<&'a mut [T]> {
2569         if self.remaining == 0 {
2570             None
2571         } else {
2572             let sz = cmp::min(self.remaining, self.chunk_size);
2573             let tmp = util::replace(&mut self.v, &mut []);
2574             let (head, tail) = tmp.mut_split_at(sz);
2575             self.v = tail;
2576             self.remaining -= sz;
2577             Some(head)
2578         }
2579     }
2580
2581     #[inline]
2582     fn size_hint(&self) -> (uint, Option<uint>) {
2583         if self.remaining == 0 {
2584             (0, Some(0))
2585         } else {
2586             let (n, rem) = self.remaining.div_rem(&self.chunk_size);
2587             let n = if rem > 0 { n + 1 } else { n };
2588             (n, Some(n))
2589         }
2590     }
2591 }
2592
2593 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunkIter<'a, T> {
2594     #[inline]
2595     fn next_back(&mut self) -> Option<&'a mut [T]> {
2596         if self.remaining == 0 {
2597             None
2598         } else {
2599             let remainder = self.remaining % self.chunk_size;
2600             let sz = if remainder != 0 { remainder } else { self.chunk_size };
2601             let tmp = util::replace(&mut self.v, &mut []);
2602             let (head, tail) = tmp.mut_split_at(self.remaining - sz);
2603             self.v = head;
2604             self.remaining -= sz;
2605             Some(tail)
2606         }
2607     }
2608 }
2609
2610 /// An iterator that moves out of a vector.
2611 pub struct MoveIterator<T> {
2612     priv allocation: *mut u8, // the block of memory allocated for the vector
2613     priv iter: VecIterator<'static, T>
2614 }
2615
2616 impl<T> Iterator<T> for MoveIterator<T> {
2617     #[inline]
2618     fn next(&mut self) -> Option<T> {
2619         unsafe {
2620             self.iter.next().map(|x| ptr::read_ptr(x))
2621         }
2622     }
2623
2624     #[inline]
2625     fn size_hint(&self) -> (uint, Option<uint>) {
2626         self.iter.size_hint()
2627     }
2628 }
2629
2630 impl<T> DoubleEndedIterator<T> for MoveIterator<T> {
2631     #[inline]
2632     fn next_back(&mut self) -> Option<T> {
2633         unsafe {
2634             self.iter.next_back().map(|x| ptr::read_ptr(x))
2635         }
2636     }
2637 }
2638
2639 #[unsafe_destructor]
2640 impl<T> Drop for MoveIterator<T> {
2641     fn drop(&mut self) {
2642         // destroy the remaining elements
2643         for _x in *self {}
2644         unsafe {
2645             if owns_managed::<T>() {
2646                 local_free(self.allocation as *u8 as *c_char)
2647             } else {
2648                 exchange_free(self.allocation as *u8 as *c_char)
2649             }
2650         }
2651     }
2652 }
2653
2654 /// An iterator that moves out of a vector in reverse order.
2655 pub type MoveRevIterator<T> = Invert<MoveIterator<T>>;
2656
2657 impl<A> FromIterator<A> for ~[A] {
2658     fn from_iterator<T: Iterator<A>>(iterator: &mut T) -> ~[A] {
2659         let (lower, _) = iterator.size_hint();
2660         let mut xs = with_capacity(lower);
2661         for x in *iterator {
2662             xs.push(x);
2663         }
2664         xs
2665     }
2666 }
2667
2668 impl<A> Extendable<A> for ~[A] {
2669     fn extend<T: Iterator<A>>(&mut self, iterator: &mut T) {
2670         let (lower, _) = iterator.size_hint();
2671         let len = self.len();
2672         self.reserve(len + lower);
2673         for x in *iterator {
2674             self.push(x);
2675         }
2676     }
2677 }
2678
2679 #[cfg(test)]
2680 mod tests {
2681     use option::{None, Option, Some};
2682     use mem;
2683     use vec::*;
2684     use cmp::*;
2685     use prelude::*;
2686
2687     fn square(n: uint) -> uint { n * n }
2688
2689     fn square_ref(n: &uint) -> uint { square(*n) }
2690
2691     fn is_three(n: &uint) -> bool { *n == 3u }
2692
2693     fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
2694
2695     fn is_equal(x: &uint, y:&uint) -> bool { *x == *y }
2696
2697     fn square_if_odd_r(n: &uint) -> Option<uint> {
2698         if *n % 2u == 1u { Some(*n * *n) } else { None }
2699     }
2700
2701     fn square_if_odd_v(n: uint) -> Option<uint> {
2702         if n % 2u == 1u { Some(n * n) } else { None }
2703     }
2704
2705     fn add(x: uint, y: &uint) -> uint { x + *y }
2706
2707     #[test]
2708     fn test_unsafe_ptrs() {
2709         unsafe {
2710             // Test on-stack copy-from-buf.
2711             let a = ~[1, 2, 3];
2712             let mut ptr = a.as_ptr();
2713             let b = from_buf(ptr, 3u);
2714             assert_eq!(b.len(), 3u);
2715             assert_eq!(b[0], 1);
2716             assert_eq!(b[1], 2);
2717             assert_eq!(b[2], 3);
2718
2719             // Test on-heap copy-from-buf.
2720             let c = ~[1, 2, 3, 4, 5];
2721             ptr = c.as_ptr();
2722             let d = from_buf(ptr, 5u);
2723             assert_eq!(d.len(), 5u);
2724             assert_eq!(d[0], 1);
2725             assert_eq!(d[1], 2);
2726             assert_eq!(d[2], 3);
2727             assert_eq!(d[3], 4);
2728             assert_eq!(d[4], 5);
2729         }
2730     }
2731
2732     #[test]
2733     fn test_from_fn() {
2734         // Test on-stack from_fn.
2735         let mut v = from_fn(3u, square);
2736         assert_eq!(v.len(), 3u);
2737         assert_eq!(v[0], 0u);
2738         assert_eq!(v[1], 1u);
2739         assert_eq!(v[2], 4u);
2740
2741         // Test on-heap from_fn.
2742         v = from_fn(5u, square);
2743         assert_eq!(v.len(), 5u);
2744         assert_eq!(v[0], 0u);
2745         assert_eq!(v[1], 1u);
2746         assert_eq!(v[2], 4u);
2747         assert_eq!(v[3], 9u);
2748         assert_eq!(v[4], 16u);
2749     }
2750
2751     #[test]
2752     fn test_from_elem() {
2753         // Test on-stack from_elem.
2754         let mut v = from_elem(2u, 10u);
2755         assert_eq!(v.len(), 2u);
2756         assert_eq!(v[0], 10u);
2757         assert_eq!(v[1], 10u);
2758
2759         // Test on-heap from_elem.
2760         v = from_elem(6u, 20u);
2761         assert_eq!(v[0], 20u);
2762         assert_eq!(v[1], 20u);
2763         assert_eq!(v[2], 20u);
2764         assert_eq!(v[3], 20u);
2765         assert_eq!(v[4], 20u);
2766         assert_eq!(v[5], 20u);
2767     }
2768
2769     #[test]
2770     fn test_is_empty() {
2771         let xs: [int, ..0] = [];
2772         assert!(xs.is_empty());
2773         assert!(![0].is_empty());
2774     }
2775
2776     #[test]
2777     fn test_len_divzero() {
2778         type Z = [i8, ..0];
2779         let v0 : &[Z] = &[];
2780         let v1 : &[Z] = &[[]];
2781         let v2 : &[Z] = &[[], []];
2782         assert_eq!(mem::size_of::<Z>(), 0);
2783         assert_eq!(v0.len(), 0);
2784         assert_eq!(v1.len(), 1);
2785         assert_eq!(v2.len(), 2);
2786     }
2787
2788     #[test]
2789     fn test_get_opt() {
2790         let mut a = ~[11];
2791         assert_eq!(a.get_opt(1), None);
2792         a = ~[11, 12];
2793         assert_eq!(a.get_opt(1).unwrap(), &12);
2794         a = ~[11, 12, 13];
2795         assert_eq!(a.get_opt(1).unwrap(), &12);
2796     }
2797
2798     #[test]
2799     fn test_head() {
2800         let mut a = ~[11];
2801         assert_eq!(a.head(), &11);
2802         a = ~[11, 12];
2803         assert_eq!(a.head(), &11);
2804     }
2805
2806     #[test]
2807     #[should_fail]
2808     fn test_head_empty() {
2809         let a: ~[int] = ~[];
2810         a.head();
2811     }
2812
2813     #[test]
2814     fn test_head_opt() {
2815         let mut a = ~[];
2816         assert_eq!(a.head_opt(), None);
2817         a = ~[11];
2818         assert_eq!(a.head_opt().unwrap(), &11);
2819         a = ~[11, 12];
2820         assert_eq!(a.head_opt().unwrap(), &11);
2821     }
2822
2823     #[test]
2824     fn test_tail() {
2825         let mut a = ~[11];
2826         assert_eq!(a.tail(), &[]);
2827         a = ~[11, 12];
2828         assert_eq!(a.tail(), &[12]);
2829     }
2830
2831     #[test]
2832     #[should_fail]
2833     fn test_tail_empty() {
2834         let a: ~[int] = ~[];
2835         a.tail();
2836     }
2837
2838     #[test]
2839     fn test_tailn() {
2840         let mut a = ~[11, 12, 13];
2841         assert_eq!(a.tailn(0), &[11, 12, 13]);
2842         a = ~[11, 12, 13];
2843         assert_eq!(a.tailn(2), &[13]);
2844     }
2845
2846     #[test]
2847     #[should_fail]
2848     fn test_tailn_empty() {
2849         let a: ~[int] = ~[];
2850         a.tailn(2);
2851     }
2852
2853     #[test]
2854     fn test_init() {
2855         let mut a = ~[11];
2856         assert_eq!(a.init(), &[]);
2857         a = ~[11, 12];
2858         assert_eq!(a.init(), &[11]);
2859     }
2860
2861     #[test]
2862     #[should_fail]
2863     fn test_init_empty() {
2864         let a: ~[int] = ~[];
2865         a.init();
2866     }
2867
2868     #[test]
2869     fn test_initn() {
2870         let mut a = ~[11, 12, 13];
2871         assert_eq!(a.initn(0), &[11, 12, 13]);
2872         a = ~[11, 12, 13];
2873         assert_eq!(a.initn(2), &[11]);
2874     }
2875
2876     #[test]
2877     #[should_fail]
2878     fn test_initn_empty() {
2879         let a: ~[int] = ~[];
2880         a.initn(2);
2881     }
2882
2883     #[test]
2884     fn test_last() {
2885         let mut a = ~[11];
2886         assert_eq!(a.last(), &11);
2887         a = ~[11, 12];
2888         assert_eq!(a.last(), &12);
2889     }
2890
2891     #[test]
2892     #[should_fail]
2893     fn test_last_empty() {
2894         let a: ~[int] = ~[];
2895         a.last();
2896     }
2897
2898     #[test]
2899     fn test_last_opt() {
2900         let mut a = ~[];
2901         assert_eq!(a.last_opt(), None);
2902         a = ~[11];
2903         assert_eq!(a.last_opt().unwrap(), &11);
2904         a = ~[11, 12];
2905         assert_eq!(a.last_opt().unwrap(), &12);
2906     }
2907
2908     #[test]
2909     fn test_slice() {
2910         // Test fixed length vector.
2911         let vec_fixed = [1, 2, 3, 4];
2912         let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
2913         assert_eq!(v_a.len(), 3u);
2914         assert_eq!(v_a[0], 2);
2915         assert_eq!(v_a[1], 3);
2916         assert_eq!(v_a[2], 4);
2917
2918         // Test on stack.
2919         let vec_stack = &[1, 2, 3];
2920         let v_b = vec_stack.slice(1u, 3u).to_owned();
2921         assert_eq!(v_b.len(), 2u);
2922         assert_eq!(v_b[0], 2);
2923         assert_eq!(v_b[1], 3);
2924
2925         // Test on managed heap.
2926         let vec_managed = @[1, 2, 3, 4, 5];
2927         let v_c = vec_managed.slice(0u, 3u).to_owned();
2928         assert_eq!(v_c.len(), 3u);
2929         assert_eq!(v_c[0], 1);
2930         assert_eq!(v_c[1], 2);
2931         assert_eq!(v_c[2], 3);
2932
2933         // Test on exchange heap.
2934         let vec_unique = ~[1, 2, 3, 4, 5, 6];
2935         let v_d = vec_unique.slice(1u, 6u).to_owned();
2936         assert_eq!(v_d.len(), 5u);
2937         assert_eq!(v_d[0], 2);
2938         assert_eq!(v_d[1], 3);
2939         assert_eq!(v_d[2], 4);
2940         assert_eq!(v_d[3], 5);
2941         assert_eq!(v_d[4], 6);
2942     }
2943
2944     #[test]
2945     fn test_slice_from() {
2946         let vec = &[1, 2, 3, 4];
2947         assert_eq!(vec.slice_from(0), vec);
2948         assert_eq!(vec.slice_from(2), &[3, 4]);
2949         assert_eq!(vec.slice_from(4), &[]);
2950     }
2951
2952     #[test]
2953     fn test_slice_to() {
2954         let vec = &[1, 2, 3, 4];
2955         assert_eq!(vec.slice_to(4), vec);
2956         assert_eq!(vec.slice_to(2), &[1, 2]);
2957         assert_eq!(vec.slice_to(0), &[]);
2958     }
2959
2960     #[test]
2961     fn test_pop() {
2962         // Test on-heap pop.
2963         let mut v = ~[1, 2, 3, 4, 5];
2964         let e = v.pop();
2965         assert_eq!(v.len(), 4u);
2966         assert_eq!(v[0], 1);
2967         assert_eq!(v[1], 2);
2968         assert_eq!(v[2], 3);
2969         assert_eq!(v[3], 4);
2970         assert_eq!(e, 5);
2971     }
2972
2973     #[test]
2974     fn test_pop_opt() {
2975         let mut v = ~[5];
2976         let e = v.pop_opt();
2977         assert_eq!(v.len(), 0);
2978         assert_eq!(e, Some(5));
2979         let f = v.pop_opt();
2980         assert_eq!(f, None);
2981         let g = v.pop_opt();
2982         assert_eq!(g, None);
2983     }
2984
2985     fn test_swap_remove() {
2986         let mut v = ~[1, 2, 3, 4, 5];
2987         let mut e = v.swap_remove(0);
2988         assert_eq!(v.len(), 4);
2989         assert_eq!(e, 1);
2990         assert_eq!(v[0], 5);
2991         e = v.swap_remove(3);
2992         assert_eq!(v.len(), 3);
2993         assert_eq!(e, 4);
2994         assert_eq!(v[0], 5);
2995         assert_eq!(v[1], 2);
2996         assert_eq!(v[2], 3);
2997     }
2998
2999     #[test]
3000     fn test_swap_remove_noncopyable() {
3001         // Tests that we don't accidentally run destructors twice.
3002         let mut v = ~[::unstable::sync::Exclusive::new(()),
3003                       ::unstable::sync::Exclusive::new(()),
3004                       ::unstable::sync::Exclusive::new(())];
3005         let mut _e = v.swap_remove(0);
3006         assert_eq!(v.len(), 2);
3007         _e = v.swap_remove(1);
3008         assert_eq!(v.len(), 1);
3009         _e = v.swap_remove(0);
3010         assert_eq!(v.len(), 0);
3011     }
3012
3013     #[test]
3014     fn test_push() {
3015         // Test on-stack push().
3016         let mut v = ~[];
3017         v.push(1);
3018         assert_eq!(v.len(), 1u);
3019         assert_eq!(v[0], 1);
3020
3021         // Test on-heap push().
3022         v.push(2);
3023         assert_eq!(v.len(), 2u);
3024         assert_eq!(v[0], 1);
3025         assert_eq!(v[1], 2);
3026     }
3027
3028     #[test]
3029     fn test_grow() {
3030         // Test on-stack grow().
3031         let mut v = ~[];
3032         v.grow(2u, &1);
3033         assert_eq!(v.len(), 2u);
3034         assert_eq!(v[0], 1);
3035         assert_eq!(v[1], 1);
3036
3037         // Test on-heap grow().
3038         v.grow(3u, &2);
3039         assert_eq!(v.len(), 5u);
3040         assert_eq!(v[0], 1);
3041         assert_eq!(v[1], 1);
3042         assert_eq!(v[2], 2);
3043         assert_eq!(v[3], 2);
3044         assert_eq!(v[4], 2);
3045     }
3046
3047     #[test]
3048     fn test_grow_fn() {
3049         let mut v = ~[];
3050         v.grow_fn(3u, square);
3051         assert_eq!(v.len(), 3u);
3052         assert_eq!(v[0], 0u);
3053         assert_eq!(v[1], 1u);
3054         assert_eq!(v[2], 4u);
3055     }
3056
3057     #[test]
3058     fn test_grow_set() {
3059         let mut v = ~[1, 2, 3];
3060         v.grow_set(4u, &4, 5);
3061         assert_eq!(v.len(), 5u);
3062         assert_eq!(v[0], 1);
3063         assert_eq!(v[1], 2);
3064         assert_eq!(v[2], 3);
3065         assert_eq!(v[3], 4);
3066         assert_eq!(v[4], 5);
3067     }
3068
3069     #[test]
3070     fn test_truncate() {
3071         let mut v = ~[@6,@5,@4];
3072         v.truncate(1);
3073         assert_eq!(v.len(), 1);
3074         assert_eq!(*(v[0]), 6);
3075         // If the unsafe block didn't drop things properly, we blow up here.
3076     }
3077
3078     #[test]
3079     fn test_clear() {
3080         let mut v = ~[@6,@5,@4];
3081         v.clear();
3082         assert_eq!(v.len(), 0);
3083         // If the unsafe block didn't drop things properly, we blow up here.
3084     }
3085
3086     #[test]
3087     fn test_dedup() {
3088         fn case(a: ~[uint], b: ~[uint]) {
3089             let mut v = a;
3090             v.dedup();
3091             assert_eq!(v, b);
3092         }
3093         case(~[], ~[]);
3094         case(~[1], ~[1]);
3095         case(~[1,1], ~[1]);
3096         case(~[1,2,3], ~[1,2,3]);
3097         case(~[1,1,2,3], ~[1,2,3]);
3098         case(~[1,2,2,3], ~[1,2,3]);
3099         case(~[1,2,3,3], ~[1,2,3]);
3100         case(~[1,1,2,2,2,3,3], ~[1,2,3]);
3101     }
3102
3103     #[test]
3104     fn test_dedup_unique() {
3105         let mut v0 = ~[~1, ~1, ~2, ~3];
3106         v0.dedup();
3107         let mut v1 = ~[~1, ~2, ~2, ~3];
3108         v1.dedup();
3109         let mut v2 = ~[~1, ~2, ~3, ~3];
3110         v2.dedup();
3111         /*
3112          * If the ~pointers were leaked or otherwise misused, valgrind and/or
3113          * rustrt should raise errors.
3114          */
3115     }
3116
3117     #[test]
3118     fn test_dedup_shared() {
3119         let mut v0 = ~[@1, @1, @2, @3];
3120         v0.dedup();
3121         let mut v1 = ~[@1, @2, @2, @3];
3122         v1.dedup();
3123         let mut v2 = ~[@1, @2, @3, @3];
3124         v2.dedup();
3125         /*
3126          * If the @pointers were leaked or otherwise misused, valgrind and/or
3127          * rustrt should raise errors.
3128          */
3129     }
3130
3131     #[test]
3132     fn test_map() {
3133         // Test on-stack map.
3134         let v = &[1u, 2u, 3u];
3135         let mut w = v.map(square_ref);
3136         assert_eq!(w.len(), 3u);
3137         assert_eq!(w[0], 1u);
3138         assert_eq!(w[1], 4u);
3139         assert_eq!(w[2], 9u);
3140
3141         // Test on-heap map.
3142         let v = ~[1u, 2u, 3u, 4u, 5u];
3143         w = v.map(square_ref);
3144         assert_eq!(w.len(), 5u);
3145         assert_eq!(w[0], 1u);
3146         assert_eq!(w[1], 4u);
3147         assert_eq!(w[2], 9u);
3148         assert_eq!(w[3], 16u);
3149         assert_eq!(w[4], 25u);
3150     }
3151
3152     #[test]
3153     fn test_retain() {
3154         let mut v = ~[1, 2, 3, 4, 5];
3155         v.retain(is_odd);
3156         assert_eq!(v, ~[1, 3, 5]);
3157     }
3158
3159     #[test]
3160     fn test_zip_unzip() {
3161         let z1 = ~[(1, 4), (2, 5), (3, 6)];
3162
3163         let (left, right) = unzip(z1.iter().map(|&x| x));
3164
3165         assert_eq!((1, 4), (left[0], right[0]));
3166         assert_eq!((2, 5), (left[1], right[1]));
3167         assert_eq!((3, 6), (left[2], right[2]));
3168     }
3169
3170     #[test]
3171     fn test_element_swaps() {
3172         let mut v = [1, 2, 3];
3173         for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
3174             v.swap(a, b);
3175             match i {
3176                 0 => assert_eq!(v, [1, 3, 2]),
3177                 1 => assert_eq!(v, [3, 1, 2]),
3178                 2 => assert_eq!(v, [3, 2, 1]),
3179                 3 => assert_eq!(v, [2, 3, 1]),
3180                 4 => assert_eq!(v, [2, 1, 3]),
3181                 5 => assert_eq!(v, [1, 2, 3]),
3182                 _ => fail!(),
3183             }
3184         }
3185     }
3186
3187     #[test]
3188     fn test_permutations() {
3189         use hashmap;
3190         {
3191             let v: [int, ..0] = [];
3192             let mut it = v.permutations();
3193             assert_eq!(it.next(), None);
3194         }
3195         {
3196             let v = [~"Hello"];
3197             let mut it = v.permutations();
3198             assert_eq!(it.next(), None);
3199         }
3200         {
3201             let v = [1, 2, 3];
3202             let mut it = v.permutations();
3203             assert_eq!(it.next(), Some(~[1,2,3]));
3204             assert_eq!(it.next(), Some(~[1,3,2]));
3205             assert_eq!(it.next(), Some(~[3,1,2]));
3206             assert_eq!(it.next(), Some(~[3,2,1]));
3207             assert_eq!(it.next(), Some(~[2,3,1]));
3208             assert_eq!(it.next(), Some(~[2,1,3]));
3209             assert_eq!(it.next(), None);
3210         }
3211         {
3212             // check that we have N! unique permutations
3213             let mut set = hashmap::HashSet::new();
3214             let v = ['A', 'B', 'C', 'D', 'E', 'F'];
3215             for perm in v.permutations() {
3216                 set.insert(perm);
3217             }
3218             assert_eq!(set.len(), 2 * 3 * 4 * 5 * 6);
3219         }
3220     }
3221
3222     #[test]
3223     fn test_position_elem() {
3224         assert!([].position_elem(&1).is_none());
3225
3226         let v1 = ~[1, 2, 3, 3, 2, 5];
3227         assert_eq!(v1.position_elem(&1), Some(0u));
3228         assert_eq!(v1.position_elem(&2), Some(1u));
3229         assert_eq!(v1.position_elem(&5), Some(5u));
3230         assert!(v1.position_elem(&4).is_none());
3231     }
3232
3233     #[test]
3234     fn test_bsearch_elem() {
3235         assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
3236         assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
3237         assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
3238         assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
3239         assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
3240
3241         assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
3242         assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
3243         assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
3244         assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
3245
3246         assert_eq!([2,4,6,8].bsearch_elem(&1), None);
3247         assert_eq!([2,4,6,8].bsearch_elem(&5), None);
3248         assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
3249         assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
3250
3251         assert_eq!([2,4,6].bsearch_elem(&1), None);
3252         assert_eq!([2,4,6].bsearch_elem(&5), None);
3253         assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
3254         assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
3255
3256         assert_eq!([2,4].bsearch_elem(&1), None);
3257         assert_eq!([2,4].bsearch_elem(&5), None);
3258         assert_eq!([2,4].bsearch_elem(&2), Some(0));
3259         assert_eq!([2,4].bsearch_elem(&4), Some(1));
3260
3261         assert_eq!([2].bsearch_elem(&1), None);
3262         assert_eq!([2].bsearch_elem(&5), None);
3263         assert_eq!([2].bsearch_elem(&2), Some(0));
3264
3265         assert_eq!([].bsearch_elem(&1), None);
3266         assert_eq!([].bsearch_elem(&5), None);
3267
3268         assert!([1,1,1,1,1].bsearch_elem(&1) != None);
3269         assert!([1,1,1,1,2].bsearch_elem(&1) != None);
3270         assert!([1,1,1,2,2].bsearch_elem(&1) != None);
3271         assert!([1,1,2,2,2].bsearch_elem(&1) != None);
3272         assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
3273
3274         assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
3275         assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
3276     }
3277
3278     #[test]
3279     fn test_reverse() {
3280         let mut v: ~[int] = ~[10, 20];
3281         assert_eq!(v[0], 10);
3282         assert_eq!(v[1], 20);
3283         v.reverse();
3284         assert_eq!(v[0], 20);
3285         assert_eq!(v[1], 10);
3286
3287         let mut v3: ~[int] = ~[];
3288         v3.reverse();
3289         assert!(v3.is_empty());
3290     }
3291
3292     #[test]
3293     fn test_partition() {
3294         assert_eq!((~[]).partition(|x: &int| *x < 3), (~[], ~[]));
3295         assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
3296         assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 2), (~[1], ~[2, 3]));
3297         assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
3298     }
3299
3300     #[test]
3301     fn test_partitioned() {
3302         assert_eq!(([]).partitioned(|x: &int| *x < 3), (~[], ~[]))
3303         assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
3304         assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (~[1], ~[2, 3]));
3305         assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
3306     }
3307
3308     #[test]
3309     fn test_concat() {
3310         let v: [~[int], ..0] = [];
3311         assert_eq!(v.concat_vec(), ~[]);
3312         assert_eq!([~[1], ~[2,3]].concat_vec(), ~[1, 2, 3]);
3313
3314         assert_eq!([&[1], &[2,3]].concat_vec(), ~[1, 2, 3]);
3315     }
3316
3317     #[test]
3318     fn test_connect() {
3319         let v: [~[int], ..0] = [];
3320         assert_eq!(v.connect_vec(&0), ~[]);
3321         assert_eq!([~[1], ~[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
3322         assert_eq!([~[1], ~[2], ~[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
3323
3324         assert_eq!(v.connect_vec(&0), ~[]);
3325         assert_eq!([&[1], &[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
3326         assert_eq!([&[1], &[2], &[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
3327     }
3328
3329     #[test]
3330     fn test_shift() {
3331         let mut x = ~[1, 2, 3];
3332         assert_eq!(x.shift(), 1);
3333         assert_eq!(&x, &~[2, 3]);
3334         assert_eq!(x.shift(), 2);
3335         assert_eq!(x.shift(), 3);
3336         assert_eq!(x.len(), 0);
3337     }
3338
3339     #[test]
3340     fn test_shift_opt() {
3341         let mut x = ~[1, 2, 3];
3342         assert_eq!(x.shift_opt(), Some(1));
3343         assert_eq!(&x, &~[2, 3]);
3344         assert_eq!(x.shift_opt(), Some(2));
3345         assert_eq!(x.shift_opt(), Some(3));
3346         assert_eq!(x.shift_opt(), None);
3347         assert_eq!(x.len(), 0);
3348     }
3349
3350     #[test]
3351     fn test_unshift() {
3352         let mut x = ~[1, 2, 3];
3353         x.unshift(0);
3354         assert_eq!(x, ~[0, 1, 2, 3]);
3355     }
3356
3357     #[test]
3358     fn test_insert() {
3359         let mut a = ~[1, 2, 4];
3360         a.insert(2, 3);
3361         assert_eq!(a, ~[1, 2, 3, 4]);
3362
3363         let mut a = ~[1, 2, 3];
3364         a.insert(0, 0);
3365         assert_eq!(a, ~[0, 1, 2, 3]);
3366
3367         let mut a = ~[1, 2, 3];
3368         a.insert(3, 4);
3369         assert_eq!(a, ~[1, 2, 3, 4]);
3370
3371         let mut a = ~[];
3372         a.insert(0, 1);
3373         assert_eq!(a, ~[1]);
3374     }
3375
3376     #[test]
3377     #[should_fail]
3378     fn test_insert_oob() {
3379         let mut a = ~[1, 2, 3];
3380         a.insert(4, 5);
3381     }
3382
3383     #[test]
3384     fn test_remove() {
3385         let mut a = ~[1, 2, 3, 4];
3386         a.remove(2);
3387         assert_eq!(a, ~[1, 2, 4]);
3388
3389         let mut a = ~[1, 2, 3];
3390         a.remove(0);
3391         assert_eq!(a, ~[2, 3]);
3392
3393         let mut a = ~[1];
3394         a.remove(0);
3395         assert_eq!(a, ~[]);
3396     }
3397
3398     #[test]
3399     #[should_fail]
3400     fn test_remove_oob() {
3401         let mut a = ~[1, 2, 3];
3402         a.remove(3);
3403     }
3404
3405     #[test]
3406     fn test_capacity() {
3407         let mut v = ~[0u64];
3408         v.reserve(10u);
3409         assert_eq!(v.capacity(), 10u);
3410         let mut v = ~[0u32];
3411         v.reserve(10u);
3412         assert_eq!(v.capacity(), 10u);
3413     }
3414
3415     #[test]
3416     fn test_slice_2() {
3417         let v = ~[1, 2, 3, 4, 5];
3418         let v = v.slice(1u, 3u);
3419         assert_eq!(v.len(), 2u);
3420         assert_eq!(v[0], 2);
3421         assert_eq!(v[1], 3);
3422     }
3423
3424
3425     #[test]
3426     #[should_fail]
3427     fn test_from_fn_fail() {
3428         from_fn(100, |v| {
3429             if v == 50 { fail!() }
3430             (~0, @0)
3431         });
3432     }
3433
3434     #[test]
3435     #[should_fail]
3436     fn test_from_elem_fail() {
3437         use cast;
3438
3439         struct S {
3440             f: int,
3441             boxes: (~int, @int)
3442         }
3443
3444         impl Clone for S {
3445             fn clone(&self) -> S {
3446                 let s = unsafe { cast::transmute_mut(self) };
3447                 s.f += 1;
3448                 if s.f == 10 { fail!() }
3449                 S { f: s.f, boxes: s.boxes.clone() }
3450             }
3451         }
3452
3453         let s = S { f: 0, boxes: (~0, @0) };
3454         let _ = from_elem(100, s);
3455     }
3456
3457     #[test]
3458     #[should_fail]
3459     fn test_build_fail() {
3460         build(None, |push| {
3461             push((~0, @0));
3462             push((~0, @0));
3463             push((~0, @0));
3464             push((~0, @0));
3465             fail!();
3466         });
3467     }
3468
3469     #[test]
3470     #[should_fail]
3471     fn test_grow_fn_fail() {
3472         let mut v = ~[];
3473         v.grow_fn(100, |i| {
3474             if i == 50 {
3475                 fail!()
3476             }
3477             (~0, @0)
3478         })
3479     }
3480
3481     #[test]
3482     #[should_fail]
3483     fn test_map_fail() {
3484         let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3485         let mut i = 0;
3486         v.map(|_elt| {
3487             if i == 2 {
3488                 fail!()
3489             }
3490             i += 1;
3491             ~[(~0, @0)]
3492         });
3493     }
3494
3495     #[test]
3496     #[should_fail]
3497     fn test_flat_map_fail() {
3498         let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3499         let mut i = 0;
3500         flat_map(v, |_elt| {
3501             if i == 2 {
3502                 fail!()
3503             }
3504             i += 1;
3505             ~[(~0, @0)]
3506         });
3507     }
3508
3509     #[test]
3510     #[should_fail]
3511     fn test_permute_fail() {
3512         let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3513         let mut i = 0;
3514         for _ in v.permutations() {
3515             if i == 2 {
3516                 fail!()
3517             }
3518             i += 1;
3519         }
3520     }
3521
3522     #[test]
3523     #[should_fail]
3524     fn test_copy_memory_oob() {
3525         unsafe {
3526             let mut a = [1, 2, 3, 4];
3527             let b = [1, 2, 3, 4, 5];
3528             a.copy_memory(b);
3529         }
3530     }
3531
3532     #[test]
3533     fn test_total_ord() {
3534         [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
3535         [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
3536         [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
3537         [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
3538         [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
3539     }
3540
3541     #[test]
3542     fn test_iterator() {
3543         use iter::*;
3544         let xs = [1, 2, 5, 10, 11];
3545         let mut it = xs.iter();
3546         assert_eq!(it.size_hint(), (5, Some(5)));
3547         assert_eq!(it.next().unwrap(), &1);
3548         assert_eq!(it.size_hint(), (4, Some(4)));
3549         assert_eq!(it.next().unwrap(), &2);
3550         assert_eq!(it.size_hint(), (3, Some(3)));
3551         assert_eq!(it.next().unwrap(), &5);
3552         assert_eq!(it.size_hint(), (2, Some(2)));
3553         assert_eq!(it.next().unwrap(), &10);
3554         assert_eq!(it.size_hint(), (1, Some(1)));
3555         assert_eq!(it.next().unwrap(), &11);
3556         assert_eq!(it.size_hint(), (0, Some(0)));
3557         assert!(it.next().is_none());
3558     }
3559
3560     #[test]
3561     fn test_random_access_iterator() {
3562         use iter::*;
3563         let xs = [1, 2, 5, 10, 11];
3564         let mut it = xs.iter();
3565
3566         assert_eq!(it.indexable(), 5);
3567         assert_eq!(it.idx(0).unwrap(), &1);
3568         assert_eq!(it.idx(2).unwrap(), &5);
3569         assert_eq!(it.idx(4).unwrap(), &11);
3570         assert!(it.idx(5).is_none());
3571
3572         assert_eq!(it.next().unwrap(), &1);
3573         assert_eq!(it.indexable(), 4);
3574         assert_eq!(it.idx(0).unwrap(), &2);
3575         assert_eq!(it.idx(3).unwrap(), &11);
3576         assert!(it.idx(4).is_none());
3577
3578         assert_eq!(it.next().unwrap(), &2);
3579         assert_eq!(it.indexable(), 3);
3580         assert_eq!(it.idx(1).unwrap(), &10);
3581         assert!(it.idx(3).is_none());
3582
3583         assert_eq!(it.next().unwrap(), &5);
3584         assert_eq!(it.indexable(), 2);
3585         assert_eq!(it.idx(1).unwrap(), &11);
3586
3587         assert_eq!(it.next().unwrap(), &10);
3588         assert_eq!(it.indexable(), 1);
3589         assert_eq!(it.idx(0).unwrap(), &11);
3590         assert!(it.idx(1).is_none());
3591
3592         assert_eq!(it.next().unwrap(), &11);
3593         assert_eq!(it.indexable(), 0);
3594         assert!(it.idx(0).is_none());
3595
3596         assert!(it.next().is_none());
3597     }
3598
3599     #[test]
3600     fn test_iter_size_hints() {
3601         use iter::*;
3602         let mut xs = [1, 2, 5, 10, 11];
3603         assert_eq!(xs.iter().size_hint(), (5, Some(5)));
3604         assert_eq!(xs.rev_iter().size_hint(), (5, Some(5)));
3605         assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
3606         assert_eq!(xs.mut_rev_iter().size_hint(), (5, Some(5)));
3607     }
3608
3609     #[test]
3610     fn test_iter_clone() {
3611         let xs = [1, 2, 5];
3612         let mut it = xs.iter();
3613         it.next();
3614         let mut jt = it.clone();
3615         assert_eq!(it.next(), jt.next());
3616         assert_eq!(it.next(), jt.next());
3617         assert_eq!(it.next(), jt.next());
3618     }
3619
3620     #[test]
3621     fn test_mut_iterator() {
3622         use iter::*;
3623         let mut xs = [1, 2, 3, 4, 5];
3624         for x in xs.mut_iter() {
3625             *x += 1;
3626         }
3627         assert_eq!(xs, [2, 3, 4, 5, 6])
3628     }
3629
3630     #[test]
3631     fn test_rev_iterator() {
3632         use iter::*;
3633
3634         let xs = [1, 2, 5, 10, 11];
3635         let ys = [11, 10, 5, 2, 1];
3636         let mut i = 0;
3637         for &x in xs.rev_iter() {
3638             assert_eq!(x, ys[i]);
3639             i += 1;
3640         }
3641         assert_eq!(i, 5);
3642     }
3643
3644     #[test]
3645     fn test_mut_rev_iterator() {
3646         use iter::*;
3647         let mut xs = [1u, 2, 3, 4, 5];
3648         for (i,x) in xs.mut_rev_iter().enumerate() {
3649             *x += i;
3650         }
3651         assert_eq!(xs, [5, 5, 5, 5, 5])
3652     }
3653
3654     #[test]
3655     fn test_move_iterator() {
3656         use iter::*;
3657         let xs = ~[1u,2,3,4,5];
3658         assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
3659     }
3660
3661     #[test]
3662     fn test_move_rev_iterator() {
3663         use iter::*;
3664         let xs = ~[1u,2,3,4,5];
3665         assert_eq!(xs.move_rev_iter().fold(0, |a: uint, b: uint| 10*a + b), 54321);
3666     }
3667
3668     #[test]
3669     fn test_splitator() {
3670         let xs = &[1i,2,3,4,5];
3671
3672         assert_eq!(xs.split(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3673                    ~[&[1], &[3], &[5]]);
3674         assert_eq!(xs.split(|x| *x == 1).collect::<~[&[int]]>(),
3675                    ~[&[], &[2,3,4,5]]);
3676         assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(),
3677                    ~[&[1,2,3,4], &[]]);
3678         assert_eq!(xs.split(|x| *x == 10).collect::<~[&[int]]>(),
3679                    ~[&[1,2,3,4,5]]);
3680         assert_eq!(xs.split(|_| true).collect::<~[&[int]]>(),
3681                    ~[&[], &[], &[], &[], &[], &[]]);
3682
3683         let xs: &[int] = &[];
3684         assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3685     }
3686
3687     #[test]
3688     fn test_splitnator() {
3689         let xs = &[1i,2,3,4,5];
3690
3691         assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3692                    ~[&[1,2,3,4,5]]);
3693         assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3694                    ~[&[1], &[3,4,5]]);
3695         assert_eq!(xs.splitn(3, |_| true).collect::<~[&[int]]>(),
3696                    ~[&[], &[], &[], &[4,5]]);
3697
3698         let xs: &[int] = &[];
3699         assert_eq!(xs.splitn(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3700     }
3701
3702     #[test]
3703     fn test_rsplitator() {
3704         let xs = &[1i,2,3,4,5];
3705
3706         assert_eq!(xs.rsplit(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3707                    ~[&[5], &[3], &[1]]);
3708         assert_eq!(xs.rsplit(|x| *x == 1).collect::<~[&[int]]>(),
3709                    ~[&[2,3,4,5], &[]]);
3710         assert_eq!(xs.rsplit(|x| *x == 5).collect::<~[&[int]]>(),
3711                    ~[&[], &[1,2,3,4]]);
3712         assert_eq!(xs.rsplit(|x| *x == 10).collect::<~[&[int]]>(),
3713                    ~[&[1,2,3,4,5]]);
3714
3715         let xs: &[int] = &[];
3716         assert_eq!(xs.rsplit(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3717     }
3718
3719     #[test]
3720     fn test_rsplitnator() {
3721         let xs = &[1,2,3,4,5];
3722
3723         assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3724                    ~[&[1,2,3,4,5]]);
3725         assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3726                    ~[&[5], &[1,2,3]]);
3727         assert_eq!(xs.rsplitn(3, |_| true).collect::<~[&[int]]>(),
3728                    ~[&[], &[], &[], &[1,2]]);
3729
3730         let xs: &[int] = &[];
3731         assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3732     }
3733
3734     #[test]
3735     fn test_windowsator() {
3736         let v = &[1i,2,3,4];
3737
3738         assert_eq!(v.windows(2).collect::<~[&[int]]>(), ~[&[1,2], &[2,3], &[3,4]]);
3739         assert_eq!(v.windows(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[2,3,4]]);
3740         assert!(v.windows(6).next().is_none());
3741     }
3742
3743     #[test]
3744     #[should_fail]
3745     fn test_windowsator_0() {
3746         let v = &[1i,2,3,4];
3747         let _it = v.windows(0);
3748     }
3749
3750     #[test]
3751     fn test_chunksator() {
3752         let v = &[1i,2,3,4,5];
3753
3754         assert_eq!(v.chunks(2).collect::<~[&[int]]>(), ~[&[1i,2], &[3,4], &[5]]);
3755         assert_eq!(v.chunks(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[4,5]]);
3756         assert_eq!(v.chunks(6).collect::<~[&[int]]>(), ~[&[1i,2,3,4,5]]);
3757
3758         assert_eq!(v.chunks(2).invert().collect::<~[&[int]]>(), ~[&[5i], &[3,4], &[1,2]]);
3759         let it = v.chunks(2);
3760         assert_eq!(it.indexable(), 3);
3761         assert_eq!(it.idx(0).unwrap(), &[1,2]);
3762         assert_eq!(it.idx(1).unwrap(), &[3,4]);
3763         assert_eq!(it.idx(2).unwrap(), &[5]);
3764         assert_eq!(it.idx(3), None);
3765     }
3766
3767     #[test]
3768     #[should_fail]
3769     fn test_chunksator_0() {
3770         let v = &[1i,2,3,4];
3771         let _it = v.chunks(0);
3772     }
3773
3774     #[test]
3775     fn test_move_from() {
3776         let mut a = [1,2,3,4,5];
3777         let b = ~[6,7,8];
3778         assert_eq!(a.move_from(b, 0, 3), 3);
3779         assert_eq!(a, [6,7,8,4,5]);
3780         let mut a = [7,2,8,1];
3781         let b = ~[3,1,4,1,5,9];
3782         assert_eq!(a.move_from(b, 0, 6), 4);
3783         assert_eq!(a, [3,1,4,1]);
3784         let mut a = [1,2,3,4];
3785         let b = ~[5,6,7,8,9,0];
3786         assert_eq!(a.move_from(b, 2, 3), 1);
3787         assert_eq!(a, [7,2,3,4]);
3788         let mut a = [1,2,3,4,5];
3789         let b = ~[5,6,7,8,9,0];
3790         assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
3791         assert_eq!(a, [1,2,6,7,5]);
3792     }
3793
3794     #[test]
3795     fn test_copy_from() {
3796         let mut a = [1,2,3,4,5];
3797         let b = [6,7,8];
3798         assert_eq!(a.copy_from(b), 3);
3799         assert_eq!(a, [6,7,8,4,5]);
3800         let mut c = [7,2,8,1];
3801         let d = [3,1,4,1,5,9];
3802         assert_eq!(c.copy_from(d), 4);
3803         assert_eq!(c, [3,1,4,1]);
3804     }
3805
3806     #[test]
3807     fn test_reverse_part() {
3808         let mut values = [1,2,3,4,5];
3809         values.mut_slice(1, 4).reverse();
3810         assert_eq!(values, [1,4,3,2,5]);
3811     }
3812
3813     #[test]
3814     fn test_vec_default() {
3815         use default::Default;
3816         macro_rules! t (
3817             ($ty:ty) => {{
3818                 let v: $ty = Default::default();
3819                 assert!(v.is_empty());
3820             }}
3821         );
3822
3823         t!(&[int]);
3824         t!(@[int]);
3825         t!(~[int]);
3826     }
3827
3828     #[test]
3829     fn test_bytes_set_memory() {
3830         use vec::bytes::MutableByteVector;
3831         let mut values = [1u8,2,3,4,5];
3832         values.mut_slice(0,5).set_memory(0xAB);
3833         assert_eq!(values, [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
3834         values.mut_slice(2,4).set_memory(0xFF);
3835         assert_eq!(values, [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
3836     }
3837
3838     #[test]
3839     #[should_fail]
3840     fn test_overflow_does_not_cause_segfault() {
3841         let mut v = ~[];
3842         v.reserve(-1);
3843         v.push(1);
3844         v.push(2);
3845     }
3846
3847     #[test]
3848     #[should_fail]
3849     fn test_overflow_does_not_cause_segfault_managed() {
3850         let mut v = ~[@1];
3851         v.reserve(-1);
3852         v.push(@2);
3853     }
3854
3855     #[test]
3856     fn test_mut_split_at() {
3857         let mut values = [1u8,2,3,4,5];
3858         {
3859             let (left, right) = values.mut_split_at(2);
3860             assert_eq!(left.slice(0, left.len()), [1, 2]);
3861             for p in left.mut_iter() {
3862                 *p += 1;
3863             }
3864
3865             assert_eq!(right.slice(0, right.len()), [3, 4, 5]);
3866             for p in right.mut_iter() {
3867                 *p += 2;
3868             }
3869         }
3870
3871         assert_eq!(values, [2, 3, 5, 6, 7]);
3872     }
3873
3874     #[deriving(Clone, Eq)]
3875     struct Foo;
3876
3877     #[test]
3878     fn test_iter_zero_sized() {
3879         let mut v = ~[Foo, Foo, Foo];
3880         assert_eq!(v.len(), 3);
3881         let mut cnt = 0;
3882
3883         for f in v.iter() {
3884             assert!(*f == Foo);
3885             cnt += 1;
3886         }
3887         assert_eq!(cnt, 3);
3888
3889         for f in v.slice(1, 3).iter() {
3890             assert!(*f == Foo);
3891             cnt += 1;
3892         }
3893         assert_eq!(cnt, 5);
3894
3895         for f in v.mut_iter() {
3896             assert!(*f == Foo);
3897             cnt += 1;
3898         }
3899         assert_eq!(cnt, 8);
3900
3901         for f in v.move_iter() {
3902             assert!(f == Foo);
3903             cnt += 1;
3904         }
3905         assert_eq!(cnt, 11);
3906
3907         let xs = ~[Foo, Foo, Foo];
3908         assert_eq!(format!("{:?}", xs.slice(0, 2).to_owned()),
3909                    ~"~[vec::tests::Foo, vec::tests::Foo]");
3910
3911         let xs: [Foo, ..3] = [Foo, Foo, Foo];
3912         assert_eq!(format!("{:?}", xs.slice(0, 2).to_owned()),
3913                    ~"~[vec::tests::Foo, vec::tests::Foo]");
3914         cnt = 0;
3915         for f in xs.iter() {
3916             assert!(*f == Foo);
3917             cnt += 1;
3918         }
3919         assert!(cnt == 3);
3920     }
3921
3922     #[test]
3923     fn test_shrink_to_fit() {
3924         let mut xs = ~[0, 1, 2, 3];
3925         for i in range(4, 100) {
3926             xs.push(i)
3927         }
3928         assert_eq!(xs.capacity(), 128);
3929         xs.shrink_to_fit();
3930         assert_eq!(xs.capacity(), 100);
3931         assert_eq!(xs, range(0, 100).to_owned_vec());
3932     }
3933
3934     #[test]
3935     fn test_starts_with() {
3936         assert!(bytes!("foobar").starts_with(bytes!("foo")));
3937         assert!(!bytes!("foobar").starts_with(bytes!("oob")));
3938         assert!(!bytes!("foobar").starts_with(bytes!("bar")));
3939         assert!(!bytes!("foo").starts_with(bytes!("foobar")));
3940         assert!(!bytes!("bar").starts_with(bytes!("foobar")));
3941         assert!(bytes!("foobar").starts_with(bytes!("foobar")));
3942         let empty: &[u8] = [];
3943         assert!(empty.starts_with(empty));
3944         assert!(!empty.starts_with(bytes!("foo")));
3945         assert!(bytes!("foobar").starts_with(empty));
3946     }
3947
3948     #[test]
3949     fn test_ends_with() {
3950         assert!(bytes!("foobar").ends_with(bytes!("bar")));
3951         assert!(!bytes!("foobar").ends_with(bytes!("oba")));
3952         assert!(!bytes!("foobar").ends_with(bytes!("foo")));
3953         assert!(!bytes!("foo").ends_with(bytes!("foobar")));
3954         assert!(!bytes!("bar").ends_with(bytes!("foobar")));
3955         assert!(bytes!("foobar").ends_with(bytes!("foobar")));
3956         let empty: &[u8] = [];
3957         assert!(empty.ends_with(empty));
3958         assert!(!empty.ends_with(bytes!("foo")));
3959         assert!(bytes!("foobar").ends_with(empty));
3960     }
3961
3962     #[test]
3963     fn test_shift_ref() {
3964         let mut x: &[int] = [1, 2, 3, 4, 5];
3965         let h = x.shift_ref();
3966         assert_eq!(*h, 1);
3967         assert_eq!(x.len(), 4);
3968         assert_eq!(x[0], 2);
3969         assert_eq!(x[3], 5);
3970     }
3971
3972     #[test]
3973     #[should_fail]
3974     fn test_shift_ref_empty() {
3975         let mut x: &[int] = [];
3976         x.shift_ref();
3977     }
3978
3979     #[test]
3980     fn test_pop_ref() {
3981         let mut x: &[int] = [1, 2, 3, 4, 5];
3982         let h = x.pop_ref();
3983         assert_eq!(*h, 5);
3984         assert_eq!(x.len(), 4);
3985         assert_eq!(x[0], 1);
3986         assert_eq!(x[3], 4);
3987     }
3988
3989     #[test]
3990     #[should_fail]
3991     fn test_pop_ref_empty() {
3992         let mut x: &[int] = [];
3993         x.pop_ref();
3994     }
3995
3996     #[test]
3997     fn test_mut_splitator() {
3998         let mut xs = [0,1,0,2,3,0,0,4,5,0];
3999         assert_eq!(xs.mut_split(|x| *x == 0).len(), 6);
4000         for slice in xs.mut_split(|x| *x == 0) {
4001             slice.reverse();
4002         }
4003         assert_eq!(xs, [0,1,0,3,2,0,0,5,4,0]);
4004
4005         let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
4006         for slice in xs.mut_split(|x| *x == 0).take(5) {
4007             slice.reverse();
4008         }
4009         assert_eq!(xs, [0,1,0,3,2,0,0,5,4,0,6,7]);
4010     }
4011
4012     #[test]
4013     fn test_mut_splitator_invert() {
4014         let mut xs = [1,2,0,3,4,0,0,5,6,0];
4015         for slice in xs.mut_split(|x| *x == 0).invert().take(4) {
4016             slice.reverse();
4017         }
4018         assert_eq!(xs, [1,2,0,4,3,0,0,6,5,0]);
4019     }
4020
4021     #[test]
4022     fn test_mut_chunks() {
4023         let mut v = [0u8, 1, 2, 3, 4, 5, 6];
4024         for (i, chunk) in v.mut_chunks(3).enumerate() {
4025             for x in chunk.mut_iter() {
4026                 *x = i as u8;
4027             }
4028         }
4029         let result = [0u8, 0, 0, 1, 1, 1, 2];
4030         assert_eq!(v, result);
4031     }
4032
4033     #[test]
4034     fn test_mut_chunks_invert() {
4035         let mut v = [0u8, 1, 2, 3, 4, 5, 6];
4036         for (i, chunk) in v.mut_chunks(3).invert().enumerate() {
4037             for x in chunk.mut_iter() {
4038                 *x = i as u8;
4039             }
4040         }
4041         let result = [2u8, 2, 2, 1, 1, 1, 0];
4042         assert_eq!(v, result);
4043     }
4044
4045     #[test]
4046     #[should_fail]
4047     fn test_mut_chunks_0() {
4048         let mut v = [1, 2, 3, 4];
4049         let _it = v.mut_chunks(0);
4050     }
4051
4052     #[test]
4053     fn test_mut_shift_ref() {
4054         let mut x: &mut [int] = [1, 2, 3, 4, 5];
4055         let h = x.mut_shift_ref();
4056         assert_eq!(*h, 1);
4057         assert_eq!(x.len(), 4);
4058         assert_eq!(x[0], 2);
4059         assert_eq!(x[3], 5);
4060     }
4061
4062     #[test]
4063     #[should_fail]
4064     fn test_mut_shift_ref_empty() {
4065         let mut x: &mut [int] = [];
4066         x.mut_shift_ref();
4067     }
4068
4069     #[test]
4070     fn test_mut_pop_ref() {
4071         let mut x: &mut [int] = [1, 2, 3, 4, 5];
4072         let h = x.mut_pop_ref();
4073         assert_eq!(*h, 5);
4074         assert_eq!(x.len(), 4);
4075         assert_eq!(x[0], 1);
4076         assert_eq!(x[3], 4);
4077     }
4078
4079     #[test]
4080     #[should_fail]
4081     fn test_mut_pop_ref_empty() {
4082         let mut x: &mut [int] = [];
4083         x.mut_pop_ref();
4084     }
4085 }
4086
4087 #[cfg(test)]
4088 mod bench {
4089     use extra::test::BenchHarness;
4090     use iter::range;
4091     use vec;
4092     use vec::VectorVector;
4093     use option::*;
4094     use ptr;
4095
4096     #[bench]
4097     fn iterator(bh: &mut BenchHarness) {
4098         // peculiar numbers to stop LLVM from optimising the summation
4099         // out.
4100         let v = vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
4101
4102         bh.iter(|| {
4103             let mut sum = 0;
4104             for x in v.iter() {
4105                 sum += *x;
4106             }
4107             // sum == 11806, to stop dead code elimination.
4108             if sum == 0 {fail!()}
4109         })
4110     }
4111
4112     #[bench]
4113     fn mut_iterator(bh: &mut BenchHarness) {
4114         let mut v = vec::from_elem(100, 0);
4115
4116         bh.iter(|| {
4117             let mut i = 0;
4118             for x in v.mut_iter() {
4119                 *x = i;
4120                 i += 1;
4121             }
4122         })
4123     }
4124
4125     #[bench]
4126     fn add(bh: &mut BenchHarness) {
4127         let xs: &[int] = [5, ..10];
4128         let ys: &[int] = [5, ..10];
4129         bh.iter(|| {
4130             xs + ys;
4131         });
4132     }
4133
4134     #[bench]
4135     fn concat(bh: &mut BenchHarness) {
4136         let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect());
4137         bh.iter(|| {
4138             let _ = xss.concat_vec();
4139         });
4140     }
4141
4142     #[bench]
4143     fn connect(bh: &mut BenchHarness) {
4144         let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect());
4145         bh.iter(|| {
4146             let _ = xss.connect_vec(&0);
4147         });
4148     }
4149
4150     #[bench]
4151     fn push(bh: &mut BenchHarness) {
4152         let mut vec: ~[uint] = ~[0u];
4153         bh.iter(|| {
4154             vec.push(0);
4155         })
4156     }
4157
4158     #[bench]
4159     fn starts_with_same_vector(bh: &mut BenchHarness) {
4160         let vec: ~[uint] = vec::from_fn(100, |i| i);
4161         bh.iter(|| {
4162             vec.starts_with(vec);
4163         })
4164     }
4165
4166     #[bench]
4167     fn starts_with_single_element(bh: &mut BenchHarness) {
4168         let vec: ~[uint] = ~[0u];
4169         bh.iter(|| {
4170             vec.starts_with(vec);
4171         })
4172     }
4173
4174     #[bench]
4175     fn starts_with_diff_one_element_at_end(bh: &mut BenchHarness) {
4176         let vec: ~[uint] = vec::from_fn(100, |i| i);
4177         let mut match_vec: ~[uint] = vec::from_fn(99, |i| i);
4178         match_vec.push(0);
4179         bh.iter(|| {
4180             vec.starts_with(match_vec);
4181         })
4182     }
4183
4184     #[bench]
4185     fn ends_with_same_vector(bh: &mut BenchHarness) {
4186         let vec: ~[uint] = vec::from_fn(100, |i| i);
4187         bh.iter(|| {
4188             vec.ends_with(vec);
4189         })
4190     }
4191
4192     #[bench]
4193     fn ends_with_single_element(bh: &mut BenchHarness) {
4194         let vec: ~[uint] = ~[0u];
4195         bh.iter(|| {
4196             vec.ends_with(vec);
4197         })
4198     }
4199
4200     #[bench]
4201     fn ends_with_diff_one_element_at_beginning(bh: &mut BenchHarness) {
4202         let vec: ~[uint] = vec::from_fn(100, |i| i);
4203         let mut match_vec: ~[uint] = vec::from_fn(100, |i| i);
4204         match_vec[0] = 200;
4205         bh.iter(|| {
4206             vec.starts_with(match_vec);
4207         })
4208     }
4209
4210     #[bench]
4211     fn contains_last_element(bh: &mut BenchHarness) {
4212         let vec: ~[uint] = vec::from_fn(100, |i| i);
4213         bh.iter(|| {
4214                 vec.contains(&99u);
4215         })
4216     }
4217
4218     #[bench]
4219     fn zero_1kb_from_elem(bh: &mut BenchHarness) {
4220         bh.iter(|| {
4221             let _v: ~[u8] = vec::from_elem(1024, 0u8);
4222         });
4223     }
4224
4225     #[bench]
4226     fn zero_1kb_set_memory(bh: &mut BenchHarness) {
4227         bh.iter(|| {
4228             let mut v: ~[u8] = vec::with_capacity(1024);
4229             unsafe {
4230                 let vp = v.as_mut_ptr();
4231                 ptr::set_memory(vp, 0, 1024);
4232                 v.set_len(1024);
4233             }
4234         });
4235     }
4236
4237     #[bench]
4238     fn zero_1kb_fixed_repeat(bh: &mut BenchHarness) {
4239         bh.iter(|| {
4240             let _v: ~[u8] = ~[0u8, ..1024];
4241         });
4242     }
4243
4244     #[bench]
4245     fn zero_1kb_loop_set(bh: &mut BenchHarness) {
4246         // Slower because the { len, cap, [0 x T] }* repr allows a pointer to the length
4247         // field to be aliased (in theory) and prevents LLVM from optimizing loads away.
4248         bh.iter(|| {
4249             let mut v: ~[u8] = vec::with_capacity(1024);
4250             unsafe {
4251                 v.set_len(1024);
4252             }
4253             for i in range(0, 1024) {
4254                 v[i] = 0;
4255             }
4256         });
4257     }
4258
4259     #[bench]
4260     fn zero_1kb_mut_iter(bh: &mut BenchHarness) {
4261         bh.iter(|| {
4262             let mut v: ~[u8] = vec::with_capacity(1024);
4263             unsafe {
4264                 v.set_len(1024);
4265             }
4266             for x in v.mut_iter() {
4267                 *x = 0;
4268             }
4269         });
4270     }
4271 }