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