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