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