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