]> git.lizzy.rs Git - rust.git/blob - src/libstd/vec.rs
std: simplify str::as_imm_buf and vec::as_{imm,mut}_buf
[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         let (buf, len): (*mut T, uint) = unsafe { transmute(self) };
1788         f(buf, len / sys::nonzero_size_of::<T>())
1789     }
1790
1791 }
1792
1793 /// Trait for &[T] where T is Cloneable
1794 pub trait MutableCloneableVector<T> {
1795     /// Copies as many elements from `src` as it can into `self`
1796     /// (the shorter of self.len() and src.len()). Returns the number of elements copied.
1797     fn copy_from(self, &[T]) -> uint;
1798 }
1799
1800 impl<'self, T:Clone> MutableCloneableVector<T> for &'self mut [T] {
1801     #[inline]
1802     fn copy_from(self, src: &[T]) -> uint {
1803         for self.mut_iter().zip(src.iter()).advance |(a, b)| {
1804             *a = b.clone();
1805         }
1806         cmp::min(self.len(), src.len())
1807     }
1808 }
1809
1810 /**
1811 * Constructs a vector from an unsafe pointer to a buffer
1812 *
1813 * # Arguments
1814 *
1815 * * ptr - An unsafe pointer to a buffer of `T`
1816 * * elts - The number of elements in the buffer
1817 */
1818 // Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
1819 pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
1820     raw::from_buf_raw(ptr, elts)
1821 }
1822
1823 /// The internal 'unboxed' representation of a vector
1824 #[allow(missing_doc)]
1825 pub struct UnboxedVecRepr {
1826     fill: uint,
1827     alloc: uint,
1828     data: u8
1829 }
1830
1831 /// Unsafe operations
1832 pub mod raw {
1833     use cast::transmute;
1834     use clone::Clone;
1835     use managed;
1836     use option::Some;
1837     use ptr;
1838     use sys;
1839     use unstable::intrinsics;
1840     use vec::{UnboxedVecRepr, with_capacity, ImmutableVector, MutableVector};
1841     use unstable::intrinsics::contains_managed;
1842
1843     /// The internal representation of a (boxed) vector
1844     #[allow(missing_doc)]
1845     pub struct VecRepr {
1846         box_header: managed::raw::BoxHeaderRepr,
1847         unboxed: UnboxedVecRepr
1848     }
1849
1850     /// The internal representation of a slice
1851     pub struct SliceRepr {
1852         /// Pointer to the base of this slice
1853         data: *u8,
1854         /// The length of the slice
1855         len: uint
1856     }
1857
1858     /**
1859      * Sets the length of a vector
1860      *
1861      * This will explicitly set the size of the vector, without actually
1862      * modifing its buffers, so it is up to the caller to ensure that
1863      * the vector is actually the specified size.
1864      */
1865     #[inline]
1866     pub unsafe fn set_len<T>(v: &mut ~[T], new_len: uint) {
1867         if contains_managed::<T>() {
1868             let repr: **mut VecRepr = transmute(v);
1869             (**repr).unboxed.fill = new_len * sys::nonzero_size_of::<T>();
1870         } else {
1871             let repr: **mut UnboxedVecRepr = transmute(v);
1872             (**repr).fill = new_len * sys::nonzero_size_of::<T>();
1873         }
1874     }
1875
1876     /**
1877      * Returns an unsafe pointer to the vector's buffer
1878      *
1879      * The caller must ensure that the vector outlives the pointer this
1880      * function returns, or else it will end up pointing to garbage.
1881      *
1882      * Modifying the vector may cause its buffer to be reallocated, which
1883      * would also make any pointers to it invalid.
1884      */
1885     #[inline]
1886     pub fn to_ptr<T>(v: &[T]) -> *T {
1887         unsafe {
1888             let repr: **SliceRepr = transmute(&v);
1889             transmute(&((**repr).data))
1890         }
1891     }
1892
1893     /** see `to_ptr()` */
1894     #[inline]
1895     pub fn to_mut_ptr<T>(v: &mut [T]) -> *mut T {
1896         unsafe {
1897             let repr: **SliceRepr = transmute(&v);
1898             transmute(&((**repr).data))
1899         }
1900     }
1901
1902     /**
1903      * Form a slice from a pointer and length (as a number of units,
1904      * not bytes).
1905      */
1906     #[inline]
1907     pub unsafe fn buf_as_slice<T,U>(p: *T,
1908                                     len: uint,
1909                                     f: &fn(v: &[T]) -> U) -> U {
1910         let pair = (p, len * sys::nonzero_size_of::<T>());
1911         let v : *(&'blk [T]) = transmute(&pair);
1912         f(*v)
1913     }
1914
1915     /**
1916      * Form a slice from a pointer and length (as a number of units,
1917      * not bytes).
1918      */
1919     #[inline]
1920     pub unsafe fn mut_buf_as_slice<T,U>(p: *mut T,
1921                                         len: uint,
1922                                         f: &fn(v: &mut [T]) -> U) -> U {
1923         let pair = (p, len * sys::nonzero_size_of::<T>());
1924         let v : *(&'blk mut [T]) = transmute(&pair);
1925         f(*v)
1926     }
1927
1928     /**
1929      * Unchecked vector indexing.
1930      */
1931     #[inline]
1932     pub unsafe fn get<T:Clone>(v: &[T], i: uint) -> T {
1933         v.as_imm_buf(|p, _len| (*ptr::offset(p, i)).clone())
1934     }
1935
1936     /**
1937      * Unchecked vector index assignment.  Does not drop the
1938      * old value and hence is only suitable when the vector
1939      * is newly allocated.
1940      */
1941     #[inline]
1942     pub unsafe fn init_elem<T>(v: &mut [T], i: uint, val: T) {
1943         let mut box = Some(val);
1944         do v.as_mut_buf |p, _len| {
1945             intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i)),
1946                                       box.take_unwrap());
1947         }
1948     }
1949
1950     /**
1951     * Constructs a vector from an unsafe pointer to a buffer
1952     *
1953     * # Arguments
1954     *
1955     * * ptr - An unsafe pointer to a buffer of `T`
1956     * * elts - The number of elements in the buffer
1957     */
1958     // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
1959     #[inline]
1960     pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
1961         let mut dst = with_capacity(elts);
1962         set_len(&mut dst, elts);
1963         dst.as_mut_buf(|p_dst, _len_dst| ptr::copy_memory(p_dst, ptr, elts));
1964         dst
1965     }
1966
1967     /**
1968       * Copies data from one vector to another.
1969       *
1970       * Copies `count` bytes from `src` to `dst`. The source and destination
1971       * may overlap.
1972       */
1973     #[inline]
1974     pub unsafe fn copy_memory<T>(dst: &mut [T], src: &[T],
1975                                  count: uint) {
1976         assert!(dst.len() >= count);
1977         assert!(src.len() >= count);
1978
1979         do dst.as_mut_buf |p_dst, _len_dst| {
1980             do src.as_imm_buf |p_src, _len_src| {
1981                 ptr::copy_memory(p_dst, p_src, count)
1982             }
1983         }
1984     }
1985 }
1986
1987 /// Operations on `[u8]`
1988 pub mod bytes {
1989     use libc;
1990     use num;
1991     use vec::raw;
1992     use vec;
1993     use ptr;
1994
1995     /// A trait for operations on mutable operations on `[u8]`
1996     pub trait MutableByteVector {
1997         /// Sets all bytes of the receiver to the given value.
1998         pub fn set_memory(self, value: u8);
1999     }
2000
2001     impl<'self> MutableByteVector for &'self mut [u8] {
2002         #[inline]
2003         fn set_memory(self, value: u8) {
2004             do self.as_mut_buf |p, len| {
2005                 unsafe { ptr::set_memory(p, value, len) };
2006             }
2007         }
2008     }
2009
2010     /// Bytewise string comparison
2011     pub fn memcmp(a: &~[u8], b: &~[u8]) -> int {
2012         let a_len = a.len();
2013         let b_len = b.len();
2014         let n = num::min(a_len, b_len) as libc::size_t;
2015         let r = unsafe {
2016             libc::memcmp(raw::to_ptr(*a) as *libc::c_void,
2017                          raw::to_ptr(*b) as *libc::c_void, n) as int
2018         };
2019
2020         if r != 0 { r } else {
2021             if a_len == b_len {
2022                 0
2023             } else if a_len < b_len {
2024                 -1
2025             } else {
2026                 1
2027             }
2028         }
2029     }
2030
2031     /// Bytewise less than or equal
2032     pub fn lt(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) < 0 }
2033
2034     /// Bytewise less than or equal
2035     pub fn le(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) <= 0 }
2036
2037     /// Bytewise equality
2038     pub fn eq(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) == 0 }
2039
2040     /// Bytewise inequality
2041     pub fn ne(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) != 0 }
2042
2043     /// Bytewise greater than or equal
2044     pub fn ge(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) >= 0 }
2045
2046     /// Bytewise greater than
2047     pub fn gt(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) > 0 }
2048
2049     /**
2050       * Copies data from one vector to another.
2051       *
2052       * Copies `count` bytes from `src` to `dst`. The source and destination
2053       * may overlap.
2054       */
2055     #[inline]
2056     pub fn copy_memory(dst: &mut [u8], src: &[u8], count: uint) {
2057         // Bound checks are done at vec::raw::copy_memory.
2058         unsafe { vec::raw::copy_memory(dst, src, count) }
2059     }
2060 }
2061
2062 impl<A:Clone> Clone for ~[A] {
2063     #[inline]
2064     fn clone(&self) -> ~[A] {
2065         self.iter().transform(|item| item.clone()).collect()
2066     }
2067 }
2068
2069 // This works because every lifetime is a sub-lifetime of 'static
2070 impl<'self, A> Zero for &'self [A] {
2071     fn zero() -> &'self [A] { &'self [] }
2072     fn is_zero(&self) -> bool { self.is_empty() }
2073 }
2074
2075 impl<A> Zero for ~[A] {
2076     fn zero() -> ~[A] { ~[] }
2077     fn is_zero(&self) -> bool { self.len() == 0 }
2078 }
2079
2080 impl<A> Zero for @[A] {
2081     fn zero() -> @[A] { @[] }
2082     fn is_zero(&self) -> bool { self.len() == 0 }
2083 }
2084
2085 macro_rules! iterator {
2086     /* FIXME: #4375 Cannot attach documentation/attributes to a macro generated struct.
2087     (struct $name:ident -> $ptr:ty, $elem:ty) => {
2088         pub struct $name<'self, T> {
2089             priv ptr: $ptr,
2090             priv end: $ptr,
2091             priv lifetime: $elem // FIXME: #5922
2092         }
2093     };*/
2094     (impl $name:ident -> $elem:ty) => {
2095         impl<'self, T> Iterator<$elem> for $name<'self, T> {
2096             #[inline]
2097             fn next(&mut self) -> Option<$elem> {
2098                 // could be implemented with slices, but this avoids bounds checks
2099                 unsafe {
2100                     if self.ptr == self.end {
2101                         None
2102                     } else {
2103                         let old = self.ptr;
2104                         // purposefully don't use 'ptr.offset' because for
2105                         // vectors with 0-size elements this would return the
2106                         // same pointer.
2107                         self.ptr = cast::transmute(self.ptr as uint +
2108                                                    sys::nonzero_size_of::<T>());
2109                         Some(cast::transmute(old))
2110                     }
2111                 }
2112             }
2113
2114             #[inline]
2115             fn size_hint(&self) -> (uint, Option<uint>) {
2116                 let diff = (self.end as uint) - (self.ptr as uint);
2117                 let exact = diff / sys::nonzero_size_of::<$elem>();
2118                 (exact, Some(exact))
2119             }
2120         }
2121     }
2122 }
2123
2124 macro_rules! double_ended_iterator {
2125     (impl $name:ident -> $elem:ty) => {
2126         impl<'self, T> DoubleEndedIterator<$elem> for $name<'self, T> {
2127             #[inline]
2128             fn next_back(&mut self) -> Option<$elem> {
2129                 // could be implemented with slices, but this avoids bounds checks
2130                 unsafe {
2131                     if self.end == self.ptr {
2132                         None
2133                     } else {
2134                         // See above for why 'ptr.offset' isn't used
2135                         self.end = cast::transmute(self.end as uint -
2136                                                    sys::nonzero_size_of::<T>());
2137                         Some(cast::transmute(self.end))
2138                     }
2139                 }
2140             }
2141         }
2142     }
2143 }
2144
2145 //iterator!{struct VecIterator -> *T, &'self T}
2146 /// An iterator for iterating over a vector.
2147 pub struct VecIterator<'self, T> {
2148     priv ptr: *T,
2149     priv end: *T,
2150     priv lifetime: &'self T // FIXME: #5922
2151 }
2152 iterator!{impl VecIterator -> &'self T}
2153 double_ended_iterator!{impl VecIterator -> &'self T}
2154 pub type VecRevIterator<'self, T> = InvertIterator<&'self T, VecIterator<'self, T>>;
2155
2156 impl<'self, T> Clone for VecIterator<'self, T> {
2157     fn clone(&self) -> VecIterator<'self, T> { *self }
2158 }
2159
2160 //iterator!{struct VecMutIterator -> *mut T, &'self mut T}
2161 /// An iterator for mutating the elements of a vector.
2162 pub struct VecMutIterator<'self, T> {
2163     priv ptr: *mut T,
2164     priv end: *mut T,
2165     priv lifetime: &'self mut T // FIXME: #5922
2166 }
2167 iterator!{impl VecMutIterator -> &'self mut T}
2168 double_ended_iterator!{impl VecMutIterator -> &'self mut T}
2169 pub type VecMutRevIterator<'self, T> = InvertIterator<&'self mut T, VecMutIterator<'self, T>>;
2170
2171 /// An iterator that moves out of a vector.
2172 #[deriving(Clone)]
2173 pub struct VecConsumeIterator<T> {
2174     priv v: ~[T],
2175     priv idx: uint,
2176 }
2177
2178 impl<T> Iterator<T> for VecConsumeIterator<T> {
2179     fn next(&mut self) -> Option<T> {
2180         // this is peculiar, but is required for safety with respect
2181         // to dtors. It traverses the first half of the vec, and
2182         // removes them by swapping them with the last element (and
2183         // popping), which results in the second half in reverse
2184         // order, and so these can just be pop'd off. That is,
2185         //
2186         // [1,2,3,4,5] => 1, [5,2,3,4] => 2, [5,4,3] => 3, [5,4] => 4,
2187         // [5] -> 5, []
2188         let l = self.v.len();
2189         if self.idx < l {
2190             self.v.swap(self.idx, l - 1);
2191             self.idx += 1;
2192         }
2193
2194         self.v.pop_opt()
2195     }
2196 }
2197
2198 /// An iterator that moves out of a vector in reverse order.
2199 #[deriving(Clone)]
2200 pub struct VecConsumeRevIterator<T> {
2201     priv v: ~[T]
2202 }
2203
2204 impl<T> Iterator<T> for VecConsumeRevIterator<T> {
2205     fn next(&mut self) -> Option<T> {
2206         self.v.pop_opt()
2207     }
2208 }
2209
2210 impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] {
2211     pub fn from_iterator(iterator: &mut T) -> ~[A] {
2212         let (lower, _) = iterator.size_hint();
2213         let mut xs = with_capacity(lower);
2214         for iterator.advance |x| {
2215             xs.push(x);
2216         }
2217         xs
2218     }
2219 }
2220
2221 #[cfg(test)]
2222 mod tests {
2223     use option::{None, Option, Some};
2224     use sys;
2225     use vec::*;
2226     use cmp::*;
2227
2228     fn square(n: uint) -> uint { n * n }
2229
2230     fn square_ref(n: &uint) -> uint { square(*n) }
2231
2232     fn is_three(n: &uint) -> bool { *n == 3u }
2233
2234     fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
2235
2236     fn is_equal(x: &uint, y:&uint) -> bool { *x == *y }
2237
2238     fn square_if_odd_r(n: &uint) -> Option<uint> {
2239         if *n % 2u == 1u { Some(*n * *n) } else { None }
2240     }
2241
2242     fn square_if_odd_v(n: uint) -> Option<uint> {
2243         if n % 2u == 1u { Some(n * n) } else { None }
2244     }
2245
2246     fn add(x: uint, y: &uint) -> uint { x + *y }
2247
2248     #[test]
2249     fn test_unsafe_ptrs() {
2250         unsafe {
2251             // Test on-stack copy-from-buf.
2252             let a = ~[1, 2, 3];
2253             let mut ptr = raw::to_ptr(a);
2254             let b = from_buf(ptr, 3u);
2255             assert_eq!(b.len(), 3u);
2256             assert_eq!(b[0], 1);
2257             assert_eq!(b[1], 2);
2258             assert_eq!(b[2], 3);
2259
2260             // Test on-heap copy-from-buf.
2261             let c = ~[1, 2, 3, 4, 5];
2262             ptr = raw::to_ptr(c);
2263             let d = from_buf(ptr, 5u);
2264             assert_eq!(d.len(), 5u);
2265             assert_eq!(d[0], 1);
2266             assert_eq!(d[1], 2);
2267             assert_eq!(d[2], 3);
2268             assert_eq!(d[3], 4);
2269             assert_eq!(d[4], 5);
2270         }
2271     }
2272
2273     #[test]
2274     fn test_from_fn() {
2275         // Test on-stack from_fn.
2276         let mut v = from_fn(3u, square);
2277         assert_eq!(v.len(), 3u);
2278         assert_eq!(v[0], 0u);
2279         assert_eq!(v[1], 1u);
2280         assert_eq!(v[2], 4u);
2281
2282         // Test on-heap from_fn.
2283         v = from_fn(5u, square);
2284         assert_eq!(v.len(), 5u);
2285         assert_eq!(v[0], 0u);
2286         assert_eq!(v[1], 1u);
2287         assert_eq!(v[2], 4u);
2288         assert_eq!(v[3], 9u);
2289         assert_eq!(v[4], 16u);
2290     }
2291
2292     #[test]
2293     fn test_from_elem() {
2294         // Test on-stack from_elem.
2295         let mut v = from_elem(2u, 10u);
2296         assert_eq!(v.len(), 2u);
2297         assert_eq!(v[0], 10u);
2298         assert_eq!(v[1], 10u);
2299
2300         // Test on-heap from_elem.
2301         v = from_elem(6u, 20u);
2302         assert_eq!(v[0], 20u);
2303         assert_eq!(v[1], 20u);
2304         assert_eq!(v[2], 20u);
2305         assert_eq!(v[3], 20u);
2306         assert_eq!(v[4], 20u);
2307         assert_eq!(v[5], 20u);
2308     }
2309
2310     #[test]
2311     fn test_is_empty() {
2312         let xs: [int, ..0] = [];
2313         assert!(xs.is_empty());
2314         assert!(![0].is_empty());
2315     }
2316
2317     #[test]
2318     fn test_len_divzero() {
2319         type Z = [i8, ..0];
2320         let v0 : &[Z] = &[];
2321         let v1 : &[Z] = &[[]];
2322         let v2 : &[Z] = &[[], []];
2323         assert_eq!(sys::size_of::<Z>(), 0);
2324         assert_eq!(v0.len(), 0);
2325         assert_eq!(v1.len(), 1);
2326         assert_eq!(v2.len(), 2);
2327     }
2328
2329     #[test]
2330     fn test_head() {
2331         let mut a = ~[11];
2332         assert_eq!(a.head(), &11);
2333         a = ~[11, 12];
2334         assert_eq!(a.head(), &11);
2335     }
2336
2337     #[test]
2338     #[should_fail]
2339     #[ignore(cfg(windows))]
2340     fn test_head_empty() {
2341         let a: ~[int] = ~[];
2342         a.head();
2343     }
2344
2345     #[test]
2346     fn test_head_opt() {
2347         let mut a = ~[];
2348         assert_eq!(a.head_opt(), None);
2349         a = ~[11];
2350         assert_eq!(a.head_opt().unwrap(), &11);
2351         a = ~[11, 12];
2352         assert_eq!(a.head_opt().unwrap(), &11);
2353     }
2354
2355     #[test]
2356     fn test_tail() {
2357         let mut a = ~[11];
2358         assert_eq!(a.tail(), &[]);
2359         a = ~[11, 12];
2360         assert_eq!(a.tail(), &[12]);
2361     }
2362
2363     #[test]
2364     #[should_fail]
2365     #[ignore(cfg(windows))]
2366     fn test_tail_empty() {
2367         let a: ~[int] = ~[];
2368         a.tail();
2369     }
2370
2371     #[test]
2372     fn test_tailn() {
2373         let mut a = ~[11, 12, 13];
2374         assert_eq!(a.tailn(0), &[11, 12, 13]);
2375         a = ~[11, 12, 13];
2376         assert_eq!(a.tailn(2), &[13]);
2377     }
2378
2379     #[test]
2380     #[should_fail]
2381     #[ignore(cfg(windows))]
2382     fn test_tailn_empty() {
2383         let a: ~[int] = ~[];
2384         a.tailn(2);
2385     }
2386
2387     #[test]
2388     fn test_init() {
2389         let mut a = ~[11];
2390         assert_eq!(a.init(), &[]);
2391         a = ~[11, 12];
2392         assert_eq!(a.init(), &[11]);
2393     }
2394
2395     #[init]
2396     #[should_fail]
2397     #[ignore(cfg(windows))]
2398     fn test_init_empty() {
2399         let a: ~[int] = ~[];
2400         a.init();
2401     }
2402
2403     #[test]
2404     fn test_initn() {
2405         let mut a = ~[11, 12, 13];
2406         assert_eq!(a.initn(0), &[11, 12, 13]);
2407         a = ~[11, 12, 13];
2408         assert_eq!(a.initn(2), &[11]);
2409     }
2410
2411     #[init]
2412     #[should_fail]
2413     #[ignore(cfg(windows))]
2414     fn test_initn_empty() {
2415         let a: ~[int] = ~[];
2416         a.initn(2);
2417     }
2418
2419     #[test]
2420     fn test_last() {
2421         let mut a = ~[11];
2422         assert_eq!(a.last(), &11);
2423         a = ~[11, 12];
2424         assert_eq!(a.last(), &12);
2425     }
2426
2427     #[test]
2428     #[should_fail]
2429     #[ignore(cfg(windows))]
2430     fn test_last_empty() {
2431         let a: ~[int] = ~[];
2432         a.last();
2433     }
2434
2435     #[test]
2436     fn test_last_opt() {
2437         let mut a = ~[];
2438         assert_eq!(a.last_opt(), None);
2439         a = ~[11];
2440         assert_eq!(a.last_opt().unwrap(), &11);
2441         a = ~[11, 12];
2442         assert_eq!(a.last_opt().unwrap(), &12);
2443     }
2444
2445     #[test]
2446     fn test_slice() {
2447         // Test fixed length vector.
2448         let vec_fixed = [1, 2, 3, 4];
2449         let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
2450         assert_eq!(v_a.len(), 3u);
2451         assert_eq!(v_a[0], 2);
2452         assert_eq!(v_a[1], 3);
2453         assert_eq!(v_a[2], 4);
2454
2455         // Test on stack.
2456         let vec_stack = &[1, 2, 3];
2457         let v_b = vec_stack.slice(1u, 3u).to_owned();
2458         assert_eq!(v_b.len(), 2u);
2459         assert_eq!(v_b[0], 2);
2460         assert_eq!(v_b[1], 3);
2461
2462         // Test on managed heap.
2463         let vec_managed = @[1, 2, 3, 4, 5];
2464         let v_c = vec_managed.slice(0u, 3u).to_owned();
2465         assert_eq!(v_c.len(), 3u);
2466         assert_eq!(v_c[0], 1);
2467         assert_eq!(v_c[1], 2);
2468         assert_eq!(v_c[2], 3);
2469
2470         // Test on exchange heap.
2471         let vec_unique = ~[1, 2, 3, 4, 5, 6];
2472         let v_d = vec_unique.slice(1u, 6u).to_owned();
2473         assert_eq!(v_d.len(), 5u);
2474         assert_eq!(v_d[0], 2);
2475         assert_eq!(v_d[1], 3);
2476         assert_eq!(v_d[2], 4);
2477         assert_eq!(v_d[3], 5);
2478         assert_eq!(v_d[4], 6);
2479     }
2480
2481     #[test]
2482     fn test_slice_from() {
2483         let vec = &[1, 2, 3, 4];
2484         assert_eq!(vec.slice_from(0), vec);
2485         assert_eq!(vec.slice_from(2), &[3, 4]);
2486         assert_eq!(vec.slice_from(4), &[]);
2487     }
2488
2489     #[test]
2490     fn test_slice_to() {
2491         let vec = &[1, 2, 3, 4];
2492         assert_eq!(vec.slice_to(4), vec);
2493         assert_eq!(vec.slice_to(2), &[1, 2]);
2494         assert_eq!(vec.slice_to(0), &[]);
2495     }
2496
2497     #[test]
2498     fn test_pop() {
2499         // Test on-heap pop.
2500         let mut v = ~[1, 2, 3, 4, 5];
2501         let e = v.pop();
2502         assert_eq!(v.len(), 4u);
2503         assert_eq!(v[0], 1);
2504         assert_eq!(v[1], 2);
2505         assert_eq!(v[2], 3);
2506         assert_eq!(v[3], 4);
2507         assert_eq!(e, 5);
2508     }
2509
2510     #[test]
2511     fn test_pop_opt() {
2512         let mut v = ~[5];
2513         let e = v.pop_opt();
2514         assert_eq!(v.len(), 0);
2515         assert_eq!(e, Some(5));
2516         let f = v.pop_opt();
2517         assert_eq!(f, None);
2518         let g = v.pop_opt();
2519         assert_eq!(g, None);
2520     }
2521
2522     fn test_swap_remove() {
2523         let mut v = ~[1, 2, 3, 4, 5];
2524         let mut e = v.swap_remove(0);
2525         assert_eq!(v.len(), 4);
2526         assert_eq!(e, 1);
2527         assert_eq!(v[0], 5);
2528         e = v.swap_remove(3);
2529         assert_eq!(v.len(), 3);
2530         assert_eq!(e, 4);
2531         assert_eq!(v[0], 5);
2532         assert_eq!(v[1], 2);
2533         assert_eq!(v[2], 3);
2534     }
2535
2536     #[test]
2537     fn test_swap_remove_noncopyable() {
2538         // Tests that we don't accidentally run destructors twice.
2539         let mut v = ~[::unstable::sync::exclusive(()),
2540                       ::unstable::sync::exclusive(()),
2541                       ::unstable::sync::exclusive(())];
2542         let mut _e = v.swap_remove(0);
2543         assert_eq!(v.len(), 2);
2544         _e = v.swap_remove(1);
2545         assert_eq!(v.len(), 1);
2546         _e = v.swap_remove(0);
2547         assert_eq!(v.len(), 0);
2548     }
2549
2550     #[test]
2551     fn test_push() {
2552         // Test on-stack push().
2553         let mut v = ~[];
2554         v.push(1);
2555         assert_eq!(v.len(), 1u);
2556         assert_eq!(v[0], 1);
2557
2558         // Test on-heap push().
2559         v.push(2);
2560         assert_eq!(v.len(), 2u);
2561         assert_eq!(v[0], 1);
2562         assert_eq!(v[1], 2);
2563     }
2564
2565     #[test]
2566     fn test_grow() {
2567         // Test on-stack grow().
2568         let mut v = ~[];
2569         v.grow(2u, &1);
2570         assert_eq!(v.len(), 2u);
2571         assert_eq!(v[0], 1);
2572         assert_eq!(v[1], 1);
2573
2574         // Test on-heap grow().
2575         v.grow(3u, &2);
2576         assert_eq!(v.len(), 5u);
2577         assert_eq!(v[0], 1);
2578         assert_eq!(v[1], 1);
2579         assert_eq!(v[2], 2);
2580         assert_eq!(v[3], 2);
2581         assert_eq!(v[4], 2);
2582     }
2583
2584     #[test]
2585     fn test_grow_fn() {
2586         let mut v = ~[];
2587         v.grow_fn(3u, square);
2588         assert_eq!(v.len(), 3u);
2589         assert_eq!(v[0], 0u);
2590         assert_eq!(v[1], 1u);
2591         assert_eq!(v[2], 4u);
2592     }
2593
2594     #[test]
2595     fn test_grow_set() {
2596         let mut v = ~[1, 2, 3];
2597         v.grow_set(4u, &4, 5);
2598         assert_eq!(v.len(), 5u);
2599         assert_eq!(v[0], 1);
2600         assert_eq!(v[1], 2);
2601         assert_eq!(v[2], 3);
2602         assert_eq!(v[3], 4);
2603         assert_eq!(v[4], 5);
2604     }
2605
2606     #[test]
2607     fn test_truncate() {
2608         let mut v = ~[@6,@5,@4];
2609         v.truncate(1);
2610         assert_eq!(v.len(), 1);
2611         assert_eq!(*(v[0]), 6);
2612         // If the unsafe block didn't drop things properly, we blow up here.
2613     }
2614
2615     #[test]
2616     fn test_clear() {
2617         let mut v = ~[@6,@5,@4];
2618         v.clear();
2619         assert_eq!(v.len(), 0);
2620         // If the unsafe block didn't drop things properly, we blow up here.
2621     }
2622
2623     #[test]
2624     fn test_dedup() {
2625         fn case(a: ~[uint], b: ~[uint]) {
2626             let mut v = a;
2627             v.dedup();
2628             assert_eq!(v, b);
2629         }
2630         case(~[], ~[]);
2631         case(~[1], ~[1]);
2632         case(~[1,1], ~[1]);
2633         case(~[1,2,3], ~[1,2,3]);
2634         case(~[1,1,2,3], ~[1,2,3]);
2635         case(~[1,2,2,3], ~[1,2,3]);
2636         case(~[1,2,3,3], ~[1,2,3]);
2637         case(~[1,1,2,2,2,3,3], ~[1,2,3]);
2638     }
2639
2640     #[test]
2641     fn test_dedup_unique() {
2642         let mut v0 = ~[~1, ~1, ~2, ~3];
2643         v0.dedup();
2644         let mut v1 = ~[~1, ~2, ~2, ~3];
2645         v1.dedup();
2646         let mut v2 = ~[~1, ~2, ~3, ~3];
2647         v2.dedup();
2648         /*
2649          * If the ~pointers were leaked or otherwise misused, valgrind and/or
2650          * rustrt should raise errors.
2651          */
2652     }
2653
2654     #[test]
2655     fn test_dedup_shared() {
2656         let mut v0 = ~[@1, @1, @2, @3];
2657         v0.dedup();
2658         let mut v1 = ~[@1, @2, @2, @3];
2659         v1.dedup();
2660         let mut v2 = ~[@1, @2, @3, @3];
2661         v2.dedup();
2662         /*
2663          * If the @pointers were leaked or otherwise misused, valgrind and/or
2664          * rustrt should raise errors.
2665          */
2666     }
2667
2668     #[test]
2669     fn test_map() {
2670         // Test on-stack map.
2671         let v = &[1u, 2u, 3u];
2672         let mut w = v.map(square_ref);
2673         assert_eq!(w.len(), 3u);
2674         assert_eq!(w[0], 1u);
2675         assert_eq!(w[1], 4u);
2676         assert_eq!(w[2], 9u);
2677
2678         // Test on-heap map.
2679         let v = ~[1u, 2u, 3u, 4u, 5u];
2680         w = v.map(square_ref);
2681         assert_eq!(w.len(), 5u);
2682         assert_eq!(w[0], 1u);
2683         assert_eq!(w[1], 4u);
2684         assert_eq!(w[2], 9u);
2685         assert_eq!(w[3], 16u);
2686         assert_eq!(w[4], 25u);
2687     }
2688
2689     #[test]
2690     fn test_retain() {
2691         let mut v = ~[1, 2, 3, 4, 5];
2692         v.retain(is_odd);
2693         assert_eq!(v, ~[1, 3, 5]);
2694     }
2695
2696     #[test]
2697     fn test_each_permutation() {
2698         let mut results: ~[~[int]];
2699
2700         results = ~[];
2701         for each_permutation([]) |v| { results.push(v.to_owned()); }
2702         assert_eq!(results, ~[~[]]);
2703
2704         results = ~[];
2705         for each_permutation([7]) |v| { results.push(v.to_owned()); }
2706         assert_eq!(results, ~[~[7]]);
2707
2708         results = ~[];
2709         for each_permutation([1,1]) |v| { results.push(v.to_owned()); }
2710         assert_eq!(results, ~[~[1,1],~[1,1]]);
2711
2712         results = ~[];
2713         for each_permutation([5,2,0]) |v| { results.push(v.to_owned()); }
2714         assert!(results ==
2715             ~[~[5,2,0],~[5,0,2],~[2,5,0],~[2,0,5],~[0,5,2],~[0,2,5]]);
2716     }
2717
2718     #[test]
2719     fn test_zip_unzip() {
2720         let v1 = ~[1, 2, 3];
2721         let v2 = ~[4, 5, 6];
2722
2723         let z1 = zip(v1, v2);
2724
2725         assert_eq!((1, 4), z1[0]);
2726         assert_eq!((2, 5), z1[1]);
2727         assert_eq!((3, 6), z1[2]);
2728
2729         let (left, right) = unzip(z1);
2730
2731         assert_eq!((1, 4), (left[0], right[0]));
2732         assert_eq!((2, 5), (left[1], right[1]));
2733         assert_eq!((3, 6), (left[2], right[2]));
2734     }
2735
2736     #[test]
2737     fn test_position_elem() {
2738         assert!([].position_elem(&1).is_none());
2739
2740         let v1 = ~[1, 2, 3, 3, 2, 5];
2741         assert_eq!(v1.position_elem(&1), Some(0u));
2742         assert_eq!(v1.position_elem(&2), Some(1u));
2743         assert_eq!(v1.position_elem(&5), Some(5u));
2744         assert!(v1.position_elem(&4).is_none());
2745     }
2746
2747     #[test]
2748     fn test_rposition() {
2749         fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
2750         fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
2751         let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
2752
2753         assert_eq!(v.rposition(f), Some(3u));
2754         assert!(v.rposition(g).is_none());
2755     }
2756
2757     #[test]
2758     fn test_bsearch_elem() {
2759         assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
2760         assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
2761         assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
2762         assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
2763         assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
2764
2765         assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
2766         assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
2767         assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
2768         assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
2769
2770         assert_eq!([2,4,6,8].bsearch_elem(&1), None);
2771         assert_eq!([2,4,6,8].bsearch_elem(&5), None);
2772         assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
2773         assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
2774
2775         assert_eq!([2,4,6].bsearch_elem(&1), None);
2776         assert_eq!([2,4,6].bsearch_elem(&5), None);
2777         assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
2778         assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
2779
2780         assert_eq!([2,4].bsearch_elem(&1), None);
2781         assert_eq!([2,4].bsearch_elem(&5), None);
2782         assert_eq!([2,4].bsearch_elem(&2), Some(0));
2783         assert_eq!([2,4].bsearch_elem(&4), Some(1));
2784
2785         assert_eq!([2].bsearch_elem(&1), None);
2786         assert_eq!([2].bsearch_elem(&5), None);
2787         assert_eq!([2].bsearch_elem(&2), Some(0));
2788
2789         assert_eq!([].bsearch_elem(&1), None);
2790         assert_eq!([].bsearch_elem(&5), None);
2791
2792         assert!([1,1,1,1,1].bsearch_elem(&1) != None);
2793         assert!([1,1,1,1,2].bsearch_elem(&1) != None);
2794         assert!([1,1,1,2,2].bsearch_elem(&1) != None);
2795         assert!([1,1,2,2,2].bsearch_elem(&1) != None);
2796         assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
2797
2798         assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
2799         assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
2800     }
2801
2802     #[test]
2803     fn test_reverse() {
2804         let mut v: ~[int] = ~[10, 20];
2805         assert_eq!(v[0], 10);
2806         assert_eq!(v[1], 20);
2807         v.reverse();
2808         assert_eq!(v[0], 20);
2809         assert_eq!(v[1], 10);
2810
2811         let mut v3: ~[int] = ~[];
2812         v3.reverse();
2813         assert!(v3.is_empty());
2814     }
2815
2816     #[test]
2817     fn test_partition() {
2818         assert_eq!((~[]).partition(|x: &int| *x < 3), (~[], ~[]));
2819         assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
2820         assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 2), (~[1], ~[2, 3]));
2821         assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
2822     }
2823
2824     #[test]
2825     fn test_partitioned() {
2826         assert_eq!(([]).partitioned(|x: &int| *x < 3), (~[], ~[]))
2827         assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
2828         assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (~[1], ~[2, 3]));
2829         assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
2830     }
2831
2832     #[test]
2833     fn test_concat() {
2834         assert_eq!(concat([~[1], ~[2,3]]), ~[1, 2, 3]);
2835         assert_eq!([~[1], ~[2,3]].concat_vec(), ~[1, 2, 3]);
2836
2837         assert_eq!(concat_slices([&[1], &[2,3]]), ~[1, 2, 3]);
2838         assert_eq!([&[1], &[2,3]].concat_vec(), ~[1, 2, 3]);
2839     }
2840
2841     #[test]
2842     fn test_connect() {
2843         assert_eq!(connect([], &0), ~[]);
2844         assert_eq!(connect([~[1], ~[2, 3]], &0), ~[1, 0, 2, 3]);
2845         assert_eq!(connect([~[1], ~[2], ~[3]], &0), ~[1, 0, 2, 0, 3]);
2846         assert_eq!([~[1], ~[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
2847         assert_eq!([~[1], ~[2], ~[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
2848
2849         assert_eq!(connect_slices([], &0), ~[]);
2850         assert_eq!(connect_slices([&[1], &[2, 3]], &0), ~[1, 0, 2, 3]);
2851         assert_eq!(connect_slices([&[1], &[2], &[3]], &0), ~[1, 0, 2, 0, 3]);
2852         assert_eq!([&[1], &[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
2853         assert_eq!([&[1], &[2], &[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
2854     }
2855
2856     #[test]
2857     fn test_shift() {
2858         let mut x = ~[1, 2, 3];
2859         assert_eq!(x.shift(), 1);
2860         assert_eq!(&x, &~[2, 3]);
2861         assert_eq!(x.shift(), 2);
2862         assert_eq!(x.shift(), 3);
2863         assert_eq!(x.len(), 0);
2864     }
2865
2866     #[test]
2867     fn test_shift_opt() {
2868         let mut x = ~[1, 2, 3];
2869         assert_eq!(x.shift_opt(), Some(1));
2870         assert_eq!(&x, &~[2, 3]);
2871         assert_eq!(x.shift_opt(), Some(2));
2872         assert_eq!(x.shift_opt(), Some(3));
2873         assert_eq!(x.shift_opt(), None);
2874         assert_eq!(x.len(), 0);
2875     }
2876
2877     #[test]
2878     fn test_unshift() {
2879         let mut x = ~[1, 2, 3];
2880         x.unshift(0);
2881         assert_eq!(x, ~[0, 1, 2, 3]);
2882     }
2883
2884     #[test]
2885     fn test_insert() {
2886         let mut a = ~[1, 2, 4];
2887         a.insert(2, 3);
2888         assert_eq!(a, ~[1, 2, 3, 4]);
2889
2890         let mut a = ~[1, 2, 3];
2891         a.insert(0, 0);
2892         assert_eq!(a, ~[0, 1, 2, 3]);
2893
2894         let mut a = ~[1, 2, 3];
2895         a.insert(3, 4);
2896         assert_eq!(a, ~[1, 2, 3, 4]);
2897
2898         let mut a = ~[];
2899         a.insert(0, 1);
2900         assert_eq!(a, ~[1]);
2901     }
2902
2903     #[test]
2904     #[ignore(cfg(windows))]
2905     #[should_fail]
2906     fn test_insert_oob() {
2907         let mut a = ~[1, 2, 3];
2908         a.insert(4, 5);
2909     }
2910
2911     #[test]
2912     fn test_remove() {
2913         let mut a = ~[1, 2, 3, 4];
2914         a.remove(2);
2915         assert_eq!(a, ~[1, 2, 4]);
2916
2917         let mut a = ~[1, 2, 3];
2918         a.remove(0);
2919         assert_eq!(a, ~[2, 3]);
2920
2921         let mut a = ~[1];
2922         a.remove(0);
2923         assert_eq!(a, ~[]);
2924     }
2925
2926     #[test]
2927     #[ignore(cfg(windows))]
2928     #[should_fail]
2929     fn test_remove_oob() {
2930         let mut a = ~[1, 2, 3];
2931         a.remove(3);
2932     }
2933
2934     #[test]
2935     fn test_capacity() {
2936         let mut v = ~[0u64];
2937         v.reserve(10u);
2938         assert_eq!(v.capacity(), 10u);
2939         let mut v = ~[0u32];
2940         v.reserve(10u);
2941         assert_eq!(v.capacity(), 10u);
2942     }
2943
2944     #[test]
2945     fn test_slice_2() {
2946         let v = ~[1, 2, 3, 4, 5];
2947         let v = v.slice(1u, 3u);
2948         assert_eq!(v.len(), 2u);
2949         assert_eq!(v[0], 2);
2950         assert_eq!(v[1], 3);
2951     }
2952
2953
2954     #[test]
2955     #[ignore(windows)]
2956     #[should_fail]
2957     fn test_from_fn_fail() {
2958         do from_fn(100) |v| {
2959             if v == 50 { fail!() }
2960             (~0, @0)
2961         };
2962     }
2963
2964     #[test]
2965     #[ignore(windows)]
2966     #[should_fail]
2967     fn test_build_fail() {
2968         do build |push| {
2969             push((~0, @0));
2970             push((~0, @0));
2971             push((~0, @0));
2972             push((~0, @0));
2973             fail!();
2974         };
2975     }
2976
2977     #[test]
2978     #[ignore(windows)]
2979     #[should_fail]
2980     fn test_grow_fn_fail() {
2981         let mut v = ~[];
2982         do v.grow_fn(100) |i| {
2983             if i == 50 {
2984                 fail!()
2985             }
2986             (~0, @0)
2987         }
2988     }
2989
2990     #[test]
2991     #[ignore(windows)]
2992     #[should_fail]
2993     fn test_map_fail() {
2994         let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
2995         let mut i = 0;
2996         do v.map |_elt| {
2997             if i == 2 {
2998                 fail!()
2999             }
3000             i += 0;
3001             ~[(~0, @0)]
3002         };
3003     }
3004
3005     #[test]
3006     #[ignore(windows)]
3007     #[should_fail]
3008     fn test_flat_map_fail() {
3009         let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3010         let mut i = 0;
3011         do flat_map(v) |_elt| {
3012             if i == 2 {
3013                 fail!()
3014             }
3015             i += 0;
3016             ~[(~0, @0)]
3017         };
3018     }
3019
3020     #[test]
3021     #[ignore(windows)]
3022     #[should_fail]
3023     fn test_rposition_fail() {
3024         let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3025         let mut i = 0;
3026         do v.rposition |_elt| {
3027             if i == 2 {
3028                 fail!()
3029             }
3030             i += 0;
3031             false
3032         };
3033     }
3034
3035     #[test]
3036     #[ignore(windows)]
3037     #[should_fail]
3038     fn test_permute_fail() {
3039         let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3040         let mut i = 0;
3041         for each_permutation(v) |_elt| {
3042             if i == 2 {
3043                 fail!()
3044             }
3045             i += 0;
3046         }
3047     }
3048
3049     #[test]
3050     #[ignore(windows)]
3051     #[should_fail]
3052     fn test_as_imm_buf_fail() {
3053         let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3054         do v.as_imm_buf |_buf, _i| {
3055             fail!()
3056         }
3057     }
3058
3059     #[test]
3060     #[ignore(cfg(windows))]
3061     #[should_fail]
3062     fn test_as_mut_buf_fail() {
3063         let mut v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3064         do v.as_mut_buf |_buf, _i| {
3065             fail!()
3066         }
3067     }
3068
3069     #[test]
3070     #[should_fail]
3071     #[ignore(cfg(windows))]
3072     fn test_copy_memory_oob() {
3073         unsafe {
3074             let mut a = [1, 2, 3, 4];
3075             let b = [1, 2, 3, 4, 5];
3076             raw::copy_memory(a, b, 5);
3077         }
3078     }
3079
3080     #[test]
3081     fn test_total_ord() {
3082         [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
3083         [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
3084         [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
3085         [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
3086         [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
3087     }
3088
3089     #[test]
3090     fn test_iterator() {
3091         use iterator::*;
3092         let xs = [1, 2, 5, 10, 11];
3093         let mut it = xs.iter();
3094         assert_eq!(it.size_hint(), (5, Some(5)));
3095         assert_eq!(it.next().unwrap(), &1);
3096         assert_eq!(it.size_hint(), (4, Some(4)));
3097         assert_eq!(it.next().unwrap(), &2);
3098         assert_eq!(it.size_hint(), (3, Some(3)));
3099         assert_eq!(it.next().unwrap(), &5);
3100         assert_eq!(it.size_hint(), (2, Some(2)));
3101         assert_eq!(it.next().unwrap(), &10);
3102         assert_eq!(it.size_hint(), (1, Some(1)));
3103         assert_eq!(it.next().unwrap(), &11);
3104         assert_eq!(it.size_hint(), (0, Some(0)));
3105         assert!(it.next().is_none());
3106     }
3107
3108     #[test]
3109     fn test_iter_size_hints() {
3110         use iterator::*;
3111         let mut xs = [1, 2, 5, 10, 11];
3112         assert_eq!(xs.iter().size_hint(), (5, Some(5)));
3113         assert_eq!(xs.rev_iter().size_hint(), (5, Some(5)));
3114         assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
3115         assert_eq!(xs.mut_rev_iter().size_hint(), (5, Some(5)));
3116     }
3117
3118     #[test]
3119     fn test_iter_clone() {
3120         let xs = [1, 2, 5];
3121         let mut it = xs.iter();
3122         it.next();
3123         let mut jt = it.clone();
3124         assert_eq!(it.next(), jt.next());
3125         assert_eq!(it.next(), jt.next());
3126         assert_eq!(it.next(), jt.next());
3127     }
3128
3129     #[test]
3130     fn test_mut_iterator() {
3131         use iterator::*;
3132         let mut xs = [1, 2, 3, 4, 5];
3133         for xs.mut_iter().advance |x| {
3134             *x += 1;
3135         }
3136         assert_eq!(xs, [2, 3, 4, 5, 6])
3137     }
3138
3139     #[test]
3140     fn test_rev_iterator() {
3141         use iterator::*;
3142
3143         let xs = [1, 2, 5, 10, 11];
3144         let ys = [11, 10, 5, 2, 1];
3145         let mut i = 0;
3146         for xs.rev_iter().advance |&x| {
3147             assert_eq!(x, ys[i]);
3148             i += 1;
3149         }
3150         assert_eq!(i, 5);
3151     }
3152
3153     #[test]
3154     fn test_mut_rev_iterator() {
3155         use iterator::*;
3156         let mut xs = [1u, 2, 3, 4, 5];
3157         for xs.mut_rev_iter().enumerate().advance |(i,x)| {
3158             *x += i;
3159         }
3160         assert_eq!(xs, [5, 5, 5, 5, 5])
3161     }
3162
3163     #[test]
3164     fn test_consume_iterator() {
3165         use iterator::*;
3166         let xs = ~[1u,2,3,4,5];
3167         assert_eq!(xs.consume_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
3168     }
3169
3170     #[test]
3171     fn test_consume_rev_iterator() {
3172         use iterator::*;
3173         let xs = ~[1u,2,3,4,5];
3174         assert_eq!(xs.consume_rev_iter().fold(0, |a: uint, b: uint| 10*a + b), 54321);
3175     }
3176
3177     #[test]
3178     fn test_split_iterator() {
3179         let xs = &[1i,2,3,4,5];
3180
3181         assert_eq!(xs.split_iter(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3182                    ~[&[1], &[3], &[5]]);
3183         assert_eq!(xs.split_iter(|x| *x == 1).collect::<~[&[int]]>(),
3184                    ~[&[], &[2,3,4,5]]);
3185         assert_eq!(xs.split_iter(|x| *x == 5).collect::<~[&[int]]>(),
3186                    ~[&[1,2,3,4], &[]]);
3187         assert_eq!(xs.split_iter(|x| *x == 10).collect::<~[&[int]]>(),
3188                    ~[&[1,2,3,4,5]]);
3189         assert_eq!(xs.split_iter(|_| true).collect::<~[&[int]]>(),
3190                    ~[&[], &[], &[], &[], &[], &[]]);
3191
3192         let xs: &[int] = &[];
3193         assert_eq!(xs.split_iter(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3194     }
3195
3196     #[test]
3197     fn test_splitn_iterator() {
3198         let xs = &[1i,2,3,4,5];
3199
3200         assert_eq!(xs.splitn_iter(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3201                    ~[&[1,2,3,4,5]]);
3202         assert_eq!(xs.splitn_iter(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3203                    ~[&[1], &[3,4,5]]);
3204         assert_eq!(xs.splitn_iter(3, |_| true).collect::<~[&[int]]>(),
3205                    ~[&[], &[], &[], &[4,5]]);
3206
3207         let xs: &[int] = &[];
3208         assert_eq!(xs.splitn_iter(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3209     }
3210
3211     #[test]
3212     fn test_rsplit_iterator() {
3213         let xs = &[1i,2,3,4,5];
3214
3215         assert_eq!(xs.rsplit_iter(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3216                    ~[&[5], &[3], &[1]]);
3217         assert_eq!(xs.rsplit_iter(|x| *x == 1).collect::<~[&[int]]>(),
3218                    ~[&[2,3,4,5], &[]]);
3219         assert_eq!(xs.rsplit_iter(|x| *x == 5).collect::<~[&[int]]>(),
3220                    ~[&[], &[1,2,3,4]]);
3221         assert_eq!(xs.rsplit_iter(|x| *x == 10).collect::<~[&[int]]>(),
3222                    ~[&[1,2,3,4,5]]);
3223
3224         let xs: &[int] = &[];
3225         assert_eq!(xs.rsplit_iter(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3226     }
3227
3228     #[test]
3229     fn test_rsplitn_iterator() {
3230         let xs = &[1,2,3,4,5];
3231
3232         assert_eq!(xs.rsplitn_iter(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3233                    ~[&[1,2,3,4,5]]);
3234         assert_eq!(xs.rsplitn_iter(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3235                    ~[&[5], &[1,2,3]]);
3236         assert_eq!(xs.rsplitn_iter(3, |_| true).collect::<~[&[int]]>(),
3237                    ~[&[], &[], &[], &[1,2]]);
3238
3239         let xs: &[int] = &[];
3240         assert_eq!(xs.rsplitn_iter(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3241     }
3242
3243     #[test]
3244     fn test_window_iterator() {
3245         let v = &[1i,2,3,4];
3246
3247         assert_eq!(v.window_iter(2).collect::<~[&[int]]>(), ~[&[1,2], &[2,3], &[3,4]]);
3248         assert_eq!(v.window_iter(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[2,3,4]]);
3249         assert!(v.window_iter(6).next().is_none());
3250     }
3251
3252     #[test]
3253     #[should_fail]
3254     #[ignore(cfg(windows))]
3255     fn test_window_iterator_0() {
3256         let v = &[1i,2,3,4];
3257         let _it = v.window_iter(0);
3258     }
3259
3260     #[test]
3261     fn test_chunk_iterator() {
3262         let v = &[1i,2,3,4,5];
3263
3264         assert_eq!(v.chunk_iter(2).collect::<~[&[int]]>(), ~[&[1i,2], &[3,4], &[5]]);
3265         assert_eq!(v.chunk_iter(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[4,5]]);
3266         assert_eq!(v.chunk_iter(6).collect::<~[&[int]]>(), ~[&[1i,2,3,4,5]]);
3267     }
3268
3269     #[test]
3270     #[should_fail]
3271     #[ignore(cfg(windows))]
3272     fn test_chunk_iterator_0() {
3273         let v = &[1i,2,3,4];
3274         let _it = v.chunk_iter(0);
3275     }
3276
3277     #[test]
3278     fn test_move_from() {
3279         let mut a = [1,2,3,4,5];
3280         let b = ~[6,7,8];
3281         assert_eq!(a.move_from(b, 0, 3), 3);
3282         assert_eq!(a, [6,7,8,4,5]);
3283         let mut a = [7,2,8,1];
3284         let b = ~[3,1,4,1,5,9];
3285         assert_eq!(a.move_from(b, 0, 6), 4);
3286         assert_eq!(a, [3,1,4,1]);
3287         let mut a = [1,2,3,4];
3288         let b = ~[5,6,7,8,9,0];
3289         assert_eq!(a.move_from(b, 2, 3), 1);
3290         assert_eq!(a, [7,2,3,4]);
3291         let mut a = [1,2,3,4,5];
3292         let b = ~[5,6,7,8,9,0];
3293         assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
3294         assert_eq!(a, [1,2,6,7,5]);
3295     }
3296
3297     #[test]
3298     fn test_copy_from() {
3299         let mut a = [1,2,3,4,5];
3300         let b = [6,7,8];
3301         assert_eq!(a.copy_from(b), 3);
3302         assert_eq!(a, [6,7,8,4,5]);
3303         let mut c = [7,2,8,1];
3304         let d = [3,1,4,1,5,9];
3305         assert_eq!(c.copy_from(d), 4);
3306         assert_eq!(c, [3,1,4,1]);
3307     }
3308
3309     #[test]
3310     fn test_reverse_part() {
3311         let mut values = [1,2,3,4,5];
3312         values.mut_slice(1, 4).reverse();
3313         assert_eq!(values, [1,4,3,2,5]);
3314     }
3315
3316     #[test]
3317     fn test_permutations0() {
3318         let values = [];
3319         let mut v : ~[~[int]] = ~[];
3320         for each_permutation(values) |p| {
3321             v.push(p.to_owned());
3322         }
3323         assert_eq!(v, ~[~[]]);
3324     }
3325
3326     #[test]
3327     fn test_permutations1() {
3328         let values = [1];
3329         let mut v : ~[~[int]] = ~[];
3330         for each_permutation(values) |p| {
3331             v.push(p.to_owned());
3332         }
3333         assert_eq!(v, ~[~[1]]);
3334     }
3335
3336     #[test]
3337     fn test_permutations2() {
3338         let values = [1,2];
3339         let mut v : ~[~[int]] = ~[];
3340         for each_permutation(values) |p| {
3341             v.push(p.to_owned());
3342         }
3343         assert_eq!(v, ~[~[1,2],~[2,1]]);
3344     }
3345
3346     #[test]
3347     fn test_permutations3() {
3348         let values = [1,2,3];
3349         let mut v : ~[~[int]] = ~[];
3350         for each_permutation(values) |p| {
3351             v.push(p.to_owned());
3352         }
3353         assert_eq!(v, ~[~[1,2,3],~[1,3,2],~[2,1,3],~[2,3,1],~[3,1,2],~[3,2,1]]);
3354     }
3355
3356     #[test]
3357     fn test_vec_zero() {
3358         use num::Zero;
3359         macro_rules! t (
3360             ($ty:ty) => {{
3361                 let v: $ty = Zero::zero();
3362                 assert!(v.is_empty());
3363                 assert!(v.is_zero());
3364             }}
3365         );
3366
3367         t!(&[int]);
3368         t!(@[int]);
3369         t!(~[int]);
3370     }
3371
3372     #[test]
3373     fn test_bytes_set_memory() {
3374         use vec::bytes::MutableByteVector;
3375         let mut values = [1u8,2,3,4,5];
3376         values.mut_slice(0,5).set_memory(0xAB);
3377         assert_eq!(values, [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
3378         values.mut_slice(2,4).set_memory(0xFF);
3379         assert_eq!(values, [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
3380     }
3381
3382     #[test]
3383     #[should_fail]
3384     fn test_overflow_does_not_cause_segfault() {
3385         let mut v = ~[];
3386         v.reserve(-1);
3387         v.push(1);
3388         v.push(2);
3389     }
3390
3391     #[test]
3392     fn test_mut_split() {
3393         let mut values = [1u8,2,3,4,5];
3394         {
3395             let (left, right) = values.mut_split(2);
3396             assert_eq!(left.slice(0, left.len()), [1, 2]);
3397             for left.mut_iter().advance |p| {
3398                 *p += 1;
3399             }
3400
3401             assert_eq!(right.slice(0, right.len()), [3, 4, 5]);
3402             for right.mut_iter().advance |p| {
3403                 *p += 2;
3404             }
3405         }
3406
3407         assert_eq!(values, [2, 3, 5, 6, 7]);
3408     }
3409
3410     #[deriving(Clone, Eq)]
3411     struct Foo;
3412
3413     #[test]
3414     fn test_iter_zero_sized() {
3415         let mut v = ~[Foo, Foo, Foo];
3416         assert_eq!(v.len(), 3);
3417         let mut cnt = 0;
3418
3419         for v.iter().advance |f| {
3420             assert!(*f == Foo);
3421             cnt += 1;
3422         }
3423         assert_eq!(cnt, 3);
3424
3425         for v.slice(1, 3).iter().advance |f| {
3426             assert!(*f == Foo);
3427             cnt += 1;
3428         }
3429         assert_eq!(cnt, 5);
3430
3431         for v.mut_iter().advance |f| {
3432             assert!(*f == Foo);
3433             cnt += 1;
3434         }
3435         assert_eq!(cnt, 8);
3436
3437         for v.consume_iter().advance |f| {
3438             assert!(f == Foo);
3439             cnt += 1;
3440         }
3441         assert_eq!(cnt, 11);
3442
3443         let xs = ~[Foo, Foo, Foo];
3444         assert_eq!(fmt!("%?", xs.slice(0, 2).to_owned()), ~"~[{}, {}]");
3445
3446         let xs: [Foo, ..3] = [Foo, Foo, Foo];
3447         assert_eq!(fmt!("%?", xs.slice(0, 2).to_owned()), ~"~[{}, {}]");
3448         cnt = 0;
3449         for xs.iter().advance |f| {
3450             assert!(*f == Foo);
3451             cnt += 1;
3452         }
3453         assert!(cnt == 3);
3454     }
3455 }