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