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.
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.
13 The `vec` module contains useful code to help work with vector values. Vectors are Rust's list
14 type. Vectors contain zero or more values of homogeneous types:
17 let int_vector = [1,2,3];
18 let str_vector = ["one", "two", "three"];
21 This is a big module, but for a high-level overview:
25 Several structs that are useful for vectors, such as `VecIterator`, which
26 represents iteration over a vector.
30 A number of traits that allow you to accomplish tasks with vectors, like the
31 `MutableVector` and `ImmutableVector` traits.
33 ## Implementations of other traits
35 Vectors are a very useful type, and so there's tons of implementations of
36 traits found elsewhere. Some notable examples:
42 ## Function definitions
44 There are a number of different functions that take vectors, here are some
47 * Modifying a vector, like `append` and `grow`.
48 * Searching in a vector, like `bsearch`.
49 * Iterating over vectors, like `each_permutation`.
50 * Functional transformations on vectors, like `map` and `partition`.
51 * Stack/queue operations, like `push`/`pop` and `shift`/`unshift`.
52 * Cons-y operations, like `head` and `tail`.
53 * Zipper operations, like `zip` and `unzip`.
59 #[warn(non_camel_case_types)];
63 use container::{Container, Mutable};
64 use cmp::{Eq, TotalOrd, Ordering, Less, Equal, Greater};
69 use option::{None, Option, Some};
70 use ptr::to_unsafe_ptr;
73 use rt::global_heap::malloc_raw;
74 use rt::global_heap::realloc_raw;
78 use unstable::intrinsics;
79 use unstable::intrinsics::{get_tydesc, contains_managed};
80 use unstable::raw::{Box, Repr, Slice, Vec};
84 /// Returns true if two vectors have the same length
85 pub fn same_length<T, U>(xs: &[T], ys: &[U]) -> bool {
90 * Creates and initializes an owned vector.
92 * Creates an owned vector of size `n_elts` and initializes the elements
93 * to the value returned by the function `op`.
95 pub fn from_fn<T>(n_elts: uint, op: &fn(uint) -> T) -> ~[T] {
97 let mut v = with_capacity(n_elts);
98 let p = raw::to_mut_ptr(v);
101 intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), op(i));
104 raw::set_len(&mut v, n_elts);
110 * Creates and initializes an owned vector.
112 * Creates an owned vector of size `n_elts` and initializes the elements
115 pub fn from_elem<T:Clone>(n_elts: uint, t: T) -> ~[T] {
116 // FIXME (#7136): manually inline from_fn for 2x plus speedup (sadly very
117 // important, from_elem is a bottleneck in borrowck!). Unfortunately it
118 // still is substantially slower than using the unsafe
119 // vec::with_capacity/ptr::set_memory for primitive types.
121 let mut v = with_capacity(n_elts);
122 let p = raw::to_mut_ptr(v);
125 intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), t.clone());
128 raw::set_len(&mut v, n_elts);
133 /// Creates a new vector with a capacity of `capacity`
135 pub fn with_capacity<T>(capacity: uint) -> ~[T] {
137 if contains_managed::<T>() {
139 vec.reserve(capacity);
142 let alloc = capacity * sys::nonzero_size_of::<T>();
143 let ptr = malloc_raw(alloc + sys::size_of::<Vec<()>>()) as *mut Vec<()>;
144 (*ptr).alloc = alloc;
152 * Builds a vector by calling a provided function with an argument
153 * function that pushes an element to the back of a vector.
154 * This version takes an initial capacity for the vector.
158 * * size - An initial size of the vector to reserve
159 * * builder - A function that will construct the vector. It receives
160 * as an argument a function that will push an element
161 * onto the vector being constructed.
164 pub fn build_sized<A>(size: uint, builder: &fn(push: &fn(v: A))) -> ~[A] {
165 let mut vec = with_capacity(size);
166 builder(|x| vec.push(x));
171 * Builds a vector by calling a provided function with an argument
172 * function that pushes an element to the back of a vector.
176 * * builder - A function that will construct the vector. It receives
177 * as an argument a function that will push an element
178 * onto the vector being constructed.
181 pub fn build<A>(builder: &fn(push: &fn(v: A))) -> ~[A] {
182 build_sized(4, builder)
186 * Builds a vector by calling a provided function with an argument
187 * function that pushes an element to the back of a vector.
188 * This version takes an initial size for the vector.
192 * * size - An option, maybe containing initial size of the vector to reserve
193 * * builder - A function that will construct the vector. It receives
194 * as an argument a function that will push an element
195 * onto the vector being constructed.
198 pub fn build_sized_opt<A>(size: Option<uint>, builder: &fn(push: &fn(v: A))) -> ~[A] {
199 build_sized(size.unwrap_or_default(4), builder)
202 /// An iterator over the slices of a vector separated by elements that
203 /// match a predicate function.
204 pub struct SplitIterator<'self, T> {
207 priv pred: &'self fn(t: &T) -> bool,
211 impl<'self, T> Iterator<&'self [T]> for SplitIterator<'self, T> {
212 fn next(&mut self) -> Option<&'self [T]> {
213 if self.finished { return None; }
216 self.finished = true;
220 match self.v.iter().position(|x| (self.pred)(x)) {
222 self.finished = true;
226 let ret = Some(self.v.slice(0, idx));
227 self.v = self.v.slice(idx + 1, self.v.len());
235 /// An iterator over the slices of a vector separated by elements that
236 /// match a predicate function, from back to front.
237 pub struct RSplitIterator<'self, T> {
240 priv pred: &'self fn(t: &T) -> bool,
244 impl<'self, T> Iterator<&'self [T]> for RSplitIterator<'self, T> {
245 fn next(&mut self) -> Option<&'self [T]> {
246 if self.finished { return None; }
249 self.finished = true;
253 match self.v.rposition(|x| (self.pred)(x)) {
255 self.finished = true;
259 let ret = Some(self.v.slice(idx + 1, self.v.len()));
260 self.v = self.v.slice(0, idx);
270 /// Iterates over the `rhs` vector, copying each element and appending it to the
271 /// `lhs`. Afterwards, the `lhs` is then returned for use again.
273 pub fn append<T:Clone>(lhs: ~[T], rhs: &[T]) -> ~[T] {
279 /// Appends one element to the vector provided. The vector itself is then
280 /// returned for use again.
282 pub fn append_one<T>(lhs: ~[T], x: T) -> ~[T] {
288 // Functional utilities
291 * Apply a function to each element of a vector and return a concatenation
292 * of each result vector
294 pub fn flat_map<T, U>(v: &[T], f: &fn(t: &T) -> ~[U]) -> ~[U] {
295 let mut result = ~[];
296 for elem in v.iter() { result.push_all_move(f(elem)); }
300 /// Flattens a vector of vectors of T into a single vector of T.
301 pub fn concat<T:Clone>(v: &[~[T]]) -> ~[T] { v.concat_vec() }
303 /// Concatenate a vector of vectors, placing a given separator between each
304 pub fn connect<T:Clone>(v: &[~[T]], sep: &T) -> ~[T] { v.connect_vec(sep) }
306 /// Flattens a vector of vectors of T into a single vector of T.
307 pub fn concat_slices<T:Clone>(v: &[&[T]]) -> ~[T] { v.concat_vec() }
309 /// Concatenate a vector of vectors, placing a given separator between each
310 pub fn connect_slices<T:Clone>(v: &[&[T]], sep: &T) -> ~[T] { v.connect_vec(sep) }
312 #[allow(missing_doc)]
313 pub trait VectorVector<T> {
314 // FIXME #5898: calling these .concat and .connect conflicts with
315 // StrVector::con{cat,nect}, since they have generic contents.
316 pub fn concat_vec(&self) -> ~[T];
317 pub fn connect_vec(&self, sep: &T) -> ~[T];
320 impl<'self, T:Clone> VectorVector<T> for &'self [~[T]] {
321 /// Flattens a vector of slices of T into a single vector of T.
322 pub fn concat_vec(&self) -> ~[T] {
323 self.flat_map(|inner| (*inner).clone())
326 /// Concatenate a vector of vectors, placing a given separator between each.
327 pub fn connect_vec(&self, sep: &T) -> ~[T] {
329 let mut first = true;
330 for inner in self.iter() {
331 if first { first = false; } else { r.push((*sep).clone()); }
332 r.push_all((*inner).clone());
338 impl<'self,T:Clone> VectorVector<T> for &'self [&'self [T]] {
339 /// Flattens a vector of slices of T into a single vector of T.
340 pub fn concat_vec(&self) -> ~[T] {
341 self.flat_map(|&inner| inner.to_owned())
344 /// Concatenate a vector of slices, placing a given separator between each.
345 pub fn connect_vec(&self, sep: &T) -> ~[T] {
347 let mut first = true;
348 for &inner in self.iter() {
349 if first { first = false; } else { r.push((*sep).clone()); }
356 // FIXME: if issue #586 gets implemented, could have a postcondition
357 // saying the two result lists have the same length -- or, could
358 // return a nominal record with a constraint saying that, instead of
359 // returning a tuple (contingent on issue #869)
361 * Convert a vector of pairs into a pair of vectors, by reference. As unzip().
363 pub fn unzip_slice<T:Clone,U:Clone>(v: &[(T, U)]) -> (~[T], ~[U]) {
367 let (t, u) = (*p).clone();
375 * Convert a vector of pairs into a pair of vectors.
377 * Returns a tuple containing two vectors where the i-th element of the first
378 * vector contains the first element of the i-th tuple of the input vector,
379 * and the i-th element of the second vector contains the second element
380 * of the i-th tuple of the input vector.
382 pub fn unzip<T,U>(v: ~[(T, U)]) -> (~[T], ~[U]) {
385 for p in v.consume_iter() {
394 * Convert two vectors to a vector of pairs, by reference. As zip().
396 pub fn zip_slice<T:Clone,U:Clone>(v: &[T], u: &[U]) -> ~[(T, U)] {
397 let mut zipped = ~[];
400 assert_eq!(sz, u.len());
402 zipped.push((v[i].clone(), u[i].clone()));
409 * Convert two vectors to a vector of pairs.
411 * Returns a vector of tuples, where the i-th tuple contains the
412 * i-th elements from each of the input vectors.
414 pub fn zip<T, U>(mut v: ~[T], mut u: ~[U]) -> ~[(T, U)] {
416 assert_eq!(i, u.len());
417 let mut w = with_capacity(i);
419 w.push((v.pop(),u.pop()));
427 * Iterate over all permutations of vector `v`.
429 * Permutations are produced in lexicographic order with respect to the order
430 * of elements in `v` (so if `v` is sorted then the permutations are
431 * lexicographically sorted).
433 * The total number of permutations produced is `v.len()!`. If `v` contains
434 * repeated elements, then some permutations are repeated.
436 * See [Algorithms to generate
437 * permutations](http://en.wikipedia.org/wiki/Permutation).
441 * * `values` - A vector of values from which the permutations are
444 * * `fun` - The function to iterate over the combinations
446 pub fn each_permutation<T:Clone>(values: &[T], fun: &fn(perm : &[T]) -> bool) -> bool {
447 let length = values.len();
448 let mut permutation = vec::from_fn(length, |i| values[i].clone());
453 let mut indices = vec::from_fn(length, |i| i);
455 if !fun(permutation) { return true; }
456 // find largest k such that indices[k] < indices[k+1]
457 // if no such k exists, all permutations have been generated
458 let mut k = length - 2;
459 while k > 0 && indices[k] >= indices[k+1] {
462 if k == 0 && indices[0] > indices[1] { return true; }
463 // find largest l such that indices[k] < indices[l]
464 // k+1 is guaranteed to be such
465 let mut l = length - 1;
466 while indices[k] >= indices[l] {
469 // swap indices[k] and indices[l]; sort indices[k+1..]
470 // (they're just reversed)
472 indices.mut_slice(k+1, length).reverse();
473 // fixup permutation based on indices
474 for i in range(k, length) {
475 permutation[i] = values[indices[i]].clone();
480 /// An iterator over the (overlapping) slices of length `size` within
483 pub struct WindowIter<'self, T> {
488 impl<'self, T> Iterator<&'self [T]> for WindowIter<'self, T> {
489 fn next(&mut self) -> Option<&'self [T]> {
490 if self.size > self.v.len() {
493 let ret = Some(self.v.slice(0, self.size));
494 self.v = self.v.slice(1, self.v.len());
500 /// An iterator over a vector in (non-overlapping) chunks (`size`
501 /// elements at a time).
503 /// When the vector len is not evenly divided by the chunk size,
504 /// the last slice of the iteration will be the remainer.
506 pub struct ChunkIter<'self, T> {
511 impl<'self, T> Iterator<&'self [T]> for ChunkIter<'self, T> {
512 fn next(&mut self) -> Option<&'self [T]> {
513 if self.v.len() == 0 {
516 let chunksz = cmp::min(self.v.len(), self.size);
517 let (fst, snd) = (self.v.slice_to(chunksz),
518 self.v.slice_from(chunksz));
525 impl<'self, T> DoubleEndedIterator<&'self [T]> for ChunkIter<'self, T> {
526 fn next_back(&mut self) -> Option<&'self [T]> {
527 if self.v.len() == 0 {
530 let remainder = self.v.len() % self.size;
531 let chunksz = if remainder != 0 { remainder } else { self.size };
532 let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
533 self.v.slice_from(self.v.len() - chunksz));
540 impl<'self, T> RandomAccessIterator<&'self [T]> for ChunkIter<'self, T> {
542 fn indexable(&self) -> uint {
543 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
547 fn idx(&self, index: uint) -> Option<&'self [T]> {
548 if index < self.indexable() {
549 let lo = index * self.size;
550 let mut hi = lo + self.size;
551 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
553 Some(self.v.slice(lo, hi))
567 use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Equal, Equiv};
569 use option::{Some, None};
571 impl<'self,T:Eq> Eq for &'self [T] {
572 fn eq(&self, other: & &'self [T]) -> bool {
573 self.len() == other.len() &&
574 self.iter().zip(other.iter()).all(|(s,o)| *s == *o)
577 fn ne(&self, other: & &'self [T]) -> bool { !self.eq(other) }
580 impl<T:Eq> Eq for ~[T] {
582 fn eq(&self, other: &~[T]) -> bool { self.as_slice() == *other }
584 fn ne(&self, other: &~[T]) -> bool { !self.eq(other) }
587 impl<T:Eq> Eq for @[T] {
589 fn eq(&self, other: &@[T]) -> bool { self.as_slice() == *other }
591 fn ne(&self, other: &@[T]) -> bool { !self.eq(other) }
594 impl<'self,T:TotalEq> TotalEq for &'self [T] {
595 fn equals(&self, other: & &'self [T]) -> bool {
596 self.len() == other.len() &&
597 self.iter().zip(other.iter()).all(|(s,o)| s.equals(o))
601 impl<T:TotalEq> TotalEq for ~[T] {
603 fn equals(&self, other: &~[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
606 impl<T:TotalEq> TotalEq for @[T] {
608 fn equals(&self, other: &@[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
611 impl<'self,T:Eq, V: Vector<T>> Equiv<V> for &'self [T] {
613 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
616 impl<'self,T:Eq, V: Vector<T>> Equiv<V> for ~[T] {
618 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
621 impl<'self,T:Eq, V: Vector<T>> Equiv<V> for @[T] {
623 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
626 impl<'self,T:TotalOrd> TotalOrd for &'self [T] {
627 fn cmp(&self, other: & &'self [T]) -> Ordering {
628 for (s,o) in self.iter().zip(other.iter()) {
631 non_eq => { return non_eq; }
634 self.len().cmp(&other.len())
638 impl<T: TotalOrd> TotalOrd for ~[T] {
640 fn cmp(&self, other: &~[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
643 impl<T: TotalOrd> TotalOrd for @[T] {
645 fn cmp(&self, other: &@[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
648 impl<'self,T:Ord> Ord for &'self [T] {
649 fn lt(&self, other: & &'self [T]) -> bool {
650 for (s,o) in self.iter().zip(other.iter()) {
651 if *s < *o { return true; }
652 if *s > *o { return false; }
654 self.len() < other.len()
657 fn le(&self, other: & &'self [T]) -> bool { !(*other < *self) }
659 fn ge(&self, other: & &'self [T]) -> bool { !(*self < *other) }
661 fn gt(&self, other: & &'self [T]) -> bool { *other < *self }
664 impl<T:Ord> Ord for ~[T] {
666 fn lt(&self, other: &~[T]) -> bool { self.as_slice() < other.as_slice() }
668 fn le(&self, other: &~[T]) -> bool { self.as_slice() <= other.as_slice() }
670 fn ge(&self, other: &~[T]) -> bool { self.as_slice() >= other.as_slice() }
672 fn gt(&self, other: &~[T]) -> bool { self.as_slice() > other.as_slice() }
675 impl<T:Ord> Ord for @[T] {
677 fn lt(&self, other: &@[T]) -> bool { self.as_slice() < other.as_slice() }
679 fn le(&self, other: &@[T]) -> bool { self.as_slice() <= other.as_slice() }
681 fn ge(&self, other: &@[T]) -> bool { self.as_slice() >= other.as_slice() }
683 fn gt(&self, other: &@[T]) -> bool { self.as_slice() > other.as_slice() }
686 impl<'self,T:Clone, V: Vector<T>> Add<V, ~[T]> for &'self [T] {
688 fn add(&self, rhs: &V) -> ~[T] {
689 let mut res = self.to_owned();
690 res.push_all(rhs.as_slice());
694 impl<T:Clone, V: Vector<T>> Add<V, ~[T]> for ~[T] {
696 fn add(&self, rhs: &V) -> ~[T] {
697 let mut res = self.to_owned();
698 res.push_all(rhs.as_slice());
707 /// Any vector that can be represented as a slice.
708 pub trait Vector<T> {
709 /// Work with `self` as a slice.
710 fn as_slice<'a>(&'a self) -> &'a [T];
712 impl<'self,T> Vector<T> for &'self [T] {
714 fn as_slice<'a>(&'a self) -> &'a [T] { *self }
716 impl<T> Vector<T> for ~[T] {
718 fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
720 impl<T> Vector<T> for @[T] {
722 fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
725 impl<'self, T> Container for &'self [T] {
726 /// Returns true if a vector contains no elements
728 fn is_empty(&self) -> bool {
729 self.as_imm_buf(|_p, len| len == 0u)
732 /// Returns the length of a vector
734 fn len(&self) -> uint {
735 self.as_imm_buf(|_p, len| len)
739 impl<T> Container for ~[T] {
740 /// Returns true if a vector contains no elements
742 fn is_empty(&self) -> bool {
743 self.as_imm_buf(|_p, len| len == 0u)
746 /// Returns the length of a vector
748 fn len(&self) -> uint {
749 self.as_imm_buf(|_p, len| len)
753 #[allow(missing_doc)]
754 pub trait CopyableVector<T> {
755 fn to_owned(&self) -> ~[T];
758 /// Extension methods for vectors
759 impl<'self,T:Clone> CopyableVector<T> for &'self [T] {
760 /// Returns a copy of `v`.
762 fn to_owned(&self) -> ~[T] {
763 let mut result = with_capacity(self.len());
764 for e in self.iter() {
765 result.push((*e).clone());
771 #[allow(missing_doc)]
772 pub trait ImmutableVector<'self, T> {
773 fn slice(&self, start: uint, end: uint) -> &'self [T];
774 fn slice_from(&self, start: uint) -> &'self [T];
775 fn slice_to(&self, end: uint) -> &'self [T];
776 fn iter(self) -> VecIterator<'self, T>;
777 fn rev_iter(self) -> RevIterator<'self, T>;
778 fn split_iter(self, pred: &'self fn(&T) -> bool) -> SplitIterator<'self, T>;
779 fn splitn_iter(self, n: uint, pred: &'self fn(&T) -> bool) -> SplitIterator<'self, T>;
780 fn rsplit_iter(self, pred: &'self fn(&T) -> bool) -> RSplitIterator<'self, T>;
781 fn rsplitn_iter(self, n: uint, pred: &'self fn(&T) -> bool) -> RSplitIterator<'self, T>;
783 fn window_iter(self, size: uint) -> WindowIter<'self, T>;
784 fn chunk_iter(self, size: uint) -> ChunkIter<'self, T>;
786 fn head(&self) -> &'self T;
787 fn head_opt(&self) -> Option<&'self T>;
788 fn tail(&self) -> &'self [T];
789 fn tailn(&self, n: uint) -> &'self [T];
790 fn init(&self) -> &'self [T];
791 fn initn(&self, n: uint) -> &'self [T];
792 fn last(&self) -> &'self T;
793 fn last_opt(&self) -> Option<&'self T>;
794 fn rposition(&self, f: &fn(t: &T) -> bool) -> Option<uint>;
795 fn flat_map<U>(&self, f: &fn(t: &T) -> ~[U]) -> ~[U];
796 unsafe fn unsafe_ref(&self, index: uint) -> *T;
798 fn bsearch(&self, f: &fn(&T) -> Ordering) -> Option<uint>;
800 fn map<U>(&self, &fn(t: &T) -> U) -> ~[U];
802 fn as_imm_buf<U>(&self, f: &fn(*T, uint) -> U) -> U;
805 /// Extension methods for vectors
806 impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
809 * Returns a slice of self between `start` and `end`.
811 * Fails when `start` or `end` point outside the bounds of self,
812 * or when `start` > `end`.
815 fn slice(&self, start: uint, end: uint) -> &'self [T] {
816 assert!(start <= end);
817 assert!(end <= self.len());
818 do self.as_imm_buf |p, _len| {
820 cast::transmute(Slice {
821 data: ptr::offset(p, start as int),
822 len: (end - start) * sys::nonzero_size_of::<T>(),
829 * Returns a slice of self from `start` to the end of the vec.
831 * Fails when `start` points outside the bounds of self.
834 fn slice_from(&self, start: uint) -> &'self [T] {
835 self.slice(start, self.len())
839 * Returns a slice of self from the start of the vec to `end`.
841 * Fails when `end` points outside the bounds of self.
844 fn slice_to(&self, end: uint) -> &'self [T] {
849 fn iter(self) -> VecIterator<'self, T> {
851 let p = vec::raw::to_ptr(self);
852 if sys::size_of::<T>() == 0 {
854 end: (p as uint + self.len()) as *T,
855 lifetime: cast::transmute(p)}
858 end: p.offset_inbounds(self.len() as int),
859 lifetime: cast::transmute(p)}
865 fn rev_iter(self) -> RevIterator<'self, T> {
869 /// Returns an iterator over the subslices of the vector which are
870 /// separated by elements that match `pred`.
872 fn split_iter(self, pred: &'self fn(&T) -> bool) -> SplitIterator<'self, T> {
873 self.splitn_iter(uint::max_value, pred)
875 /// Returns an iterator over the subslices of the vector which are
876 /// separated by elements that match `pred`, limited to splitting
877 /// at most `n` times.
879 fn splitn_iter(self, n: uint, pred: &'self fn(&T) -> bool) -> SplitIterator<'self, T> {
887 /// Returns an iterator over the subslices of the vector which are
888 /// separated by elements that match `pred`. This starts at the
889 /// end of the vector and works backwards.
891 fn rsplit_iter(self, pred: &'self fn(&T) -> bool) -> RSplitIterator<'self, T> {
892 self.rsplitn_iter(uint::max_value, pred)
894 /// Returns an iterator over the subslices of the vector which are
895 /// separated by elements that match `pred` limited to splitting
896 /// at most `n` times. This starts at the end of the vector and
899 fn rsplitn_iter(self, n: uint, pred: &'self fn(&T) -> bool) -> RSplitIterator<'self, T> {
909 * Returns an iterator over all contiguous windows of length
910 * `size`. The windows overlap. If the vector is shorter than
911 * `size`, the iterator returns no values.
915 * Fails if `size` is 0.
919 * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
923 * let v = &[1,2,3,4];
924 * for win in v.window_iter() {
930 fn window_iter(self, size: uint) -> WindowIter<'self, T> {
932 WindowIter { v: self, size: size }
937 * Returns an iterator over `size` elements of the vector at a
938 * time. The chunks do not overlap. If `size` does not divide the
939 * length of the vector, then the last chunk will not have length
944 * Fails if `size` is 0.
948 * Print the vector two elements at a time (i.e. `[1,2]`,
952 * let v = &[1,2,3,4,5];
953 * for win in v.chunk_iter() {
959 fn chunk_iter(self, size: uint) -> ChunkIter<'self, T> {
961 ChunkIter { v: self, size: size }
964 /// Returns the first element of a vector, failing if the vector is empty.
966 fn head(&self) -> &'self T {
967 if self.len() == 0 { fail!("head: empty vector") }
971 /// Returns the first element of a vector, or `None` if it is empty
973 fn head_opt(&self) -> Option<&'self T> {
974 if self.len() == 0 { None } else { Some(&self[0]) }
977 /// Returns all but the first element of a vector
979 fn tail(&self) -> &'self [T] { self.slice(1, self.len()) }
981 /// Returns all but the first `n' elements of a vector
983 fn tailn(&self, n: uint) -> &'self [T] { self.slice(n, self.len()) }
985 /// Returns all but the last element of a vector
987 fn init(&self) -> &'self [T] {
988 self.slice(0, self.len() - 1)
991 /// Returns all but the last `n' elemnts of a vector
993 fn initn(&self, n: uint) -> &'self [T] {
994 self.slice(0, self.len() - n)
997 /// Returns the last element of a vector, failing if the vector is empty.
999 fn last(&self) -> &'self T {
1000 if self.len() == 0 { fail!("last: empty vector") }
1001 &self[self.len() - 1]
1004 /// Returns the last element of a vector, or `None` if it is empty.
1006 fn last_opt(&self) -> Option<&'self T> {
1007 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
1011 * Find the last index matching some predicate
1013 * Apply function `f` to each element of `v` in reverse order. When
1014 * function `f` returns true then an option containing the index is
1015 * returned. If `f` matches no elements then None is returned.
1018 fn rposition(&self, f: &fn(t: &T) -> bool) -> Option<uint> {
1019 for (i, t) in self.rev_iter().enumerate() {
1020 if f(t) { return Some(self.len() - i - 1); }
1026 * Apply a function to each element of a vector and return a concatenation
1027 * of each result vector
1030 fn flat_map<U>(&self, f: &fn(t: &T) -> ~[U]) -> ~[U] {
1034 /// Returns a pointer to the element at the given index, without doing
1035 /// bounds checking.
1037 unsafe fn unsafe_ref(&self, index: uint) -> *T {
1038 self.repr().data.offset(index as int)
1042 * Binary search a sorted vector with a comparator function.
1044 * The comparator should implement an order consistent with the sort
1045 * order of the underlying vector, returning an order code that indicates
1046 * whether its argument is `Less`, `Equal` or `Greater` the desired target.
1048 * Returns the index where the comparator returned `Equal`, or `None` if
1051 fn bsearch(&self, f: &fn(&T) -> Ordering) -> Option<uint> {
1052 let mut base : uint = 0;
1053 let mut lim : uint = self.len();
1056 let ix = base + (lim >> 1);
1057 match f(&self[ix]) {
1058 Equal => return Some(ix),
1070 /// Deprecated, use iterators where possible
1071 /// (`self.iter().transform(f)`). Apply a function to each element
1072 /// of a vector and return the results.
1073 fn map<U>(&self, f: &fn(t: &T) -> U) -> ~[U] {
1074 self.iter().transform(f).collect()
1078 * Work with the buffer of a vector.
1080 * Allows for unsafe manipulation of vector contents, which is useful for
1084 fn as_imm_buf<U>(&self,
1085 /* NB---this CANNOT be const, see below */
1086 f: &fn(*T, uint) -> U) -> U {
1087 // NB---Do not change the type of s to `&const [T]`. This is
1088 // unsound. The reason is that we are going to create immutable pointers
1089 // into `s` and pass them to `f()`, but in fact they are potentially
1090 // pointing at *mutable memory*. Use `as_mut_buf` instead!
1092 let s = self.repr();
1093 f(s.data, s.len / sys::nonzero_size_of::<T>())
1097 #[allow(missing_doc)]
1098 pub trait ImmutableEqVector<T:Eq> {
1099 fn position_elem(&self, t: &T) -> Option<uint>;
1100 fn rposition_elem(&self, t: &T) -> Option<uint>;
1101 fn contains(&self, x: &T) -> bool;
1104 impl<'self,T:Eq> ImmutableEqVector<T> for &'self [T] {
1105 /// Find the first index containing a matching value
1107 fn position_elem(&self, x: &T) -> Option<uint> {
1108 self.iter().position(|y| *x == *y)
1111 /// Find the last index containing a matching value
1113 fn rposition_elem(&self, t: &T) -> Option<uint> {
1114 self.rposition(|x| *x == *t)
1117 /// Return true if a vector contains an element with the given value
1118 fn contains(&self, x: &T) -> bool {
1119 for elt in self.iter() { if *x == *elt { return true; } }
1124 #[allow(missing_doc)]
1125 pub trait ImmutableTotalOrdVector<T: TotalOrd> {
1126 fn bsearch_elem(&self, x: &T) -> Option<uint>;
1129 impl<'self, T: TotalOrd> ImmutableTotalOrdVector<T> for &'self [T] {
1131 * Binary search a sorted vector for a given element.
1133 * Returns the index of the element or None if not found.
1135 fn bsearch_elem(&self, x: &T) -> Option<uint> {
1136 self.bsearch(|p| p.cmp(x))
1140 #[allow(missing_doc)]
1141 pub trait ImmutableCopyableVector<T> {
1142 fn partitioned(&self, f: &fn(&T) -> bool) -> (~[T], ~[T]);
1143 unsafe fn unsafe_get(&self, elem: uint) -> T;
1146 /// Extension methods for vectors
1147 impl<'self,T:Clone> ImmutableCopyableVector<T> for &'self [T] {
1149 * Partitions the vector into those that satisfies the predicate, and
1150 * those that do not.
1153 fn partitioned(&self, f: &fn(&T) -> bool) -> (~[T], ~[T]) {
1154 let mut lefts = ~[];
1155 let mut rights = ~[];
1157 for elt in self.iter() {
1159 lefts.push((*elt).clone());
1161 rights.push((*elt).clone());
1168 /// Returns the element at the given index, without doing bounds checking.
1170 unsafe fn unsafe_get(&self, index: uint) -> T {
1171 (*self.unsafe_ref(index)).clone()
1175 #[allow(missing_doc)]
1176 pub trait OwnedVector<T> {
1177 fn consume_iter(self) -> ConsumeIterator<T>;
1178 fn consume_rev_iter(self) -> ConsumeRevIterator<T>;
1180 fn reserve(&mut self, n: uint);
1181 fn reserve_at_least(&mut self, n: uint);
1182 fn capacity(&self) -> uint;
1184 fn push(&mut self, t: T);
1185 unsafe fn push_fast(&mut self, t: T);
1187 fn push_all_move(&mut self, rhs: ~[T]);
1188 fn pop(&mut self) -> T;
1189 fn pop_opt(&mut self) -> Option<T>;
1190 fn shift(&mut self) -> T;
1191 fn shift_opt(&mut self) -> Option<T>;
1192 fn unshift(&mut self, x: T);
1193 fn insert(&mut self, i: uint, x:T);
1194 fn remove(&mut self, i: uint) -> T;
1195 fn swap_remove(&mut self, index: uint) -> T;
1196 fn truncate(&mut self, newlen: uint);
1197 fn retain(&mut self, f: &fn(t: &T) -> bool);
1198 fn partition(self, f: &fn(&T) -> bool) -> (~[T], ~[T]);
1199 fn grow_fn(&mut self, n: uint, op: &fn(uint) -> T);
1202 impl<T> OwnedVector<T> for ~[T] {
1203 /// Creates a consuming iterator, that is, one that moves each
1204 /// value out of the vector (from start to end). The vector cannot
1205 /// be used after calling this.
1207 /// Note that this performs O(n) swaps, and so `consume_rev_iter`
1208 /// (which just calls `pop` repeatedly) is more efficient.
1213 /// let v = ~[~"a", ~"b"];
1214 /// for s in v.consume_iter() {
1215 /// // s has type ~str, not &~str
1219 fn consume_iter(self) -> ConsumeIterator<T> {
1220 ConsumeIterator { v: self, idx: 0 }
1222 /// Creates a consuming iterator that moves out of the vector in
1223 /// reverse order. Also see `consume_iter`, however note that this
1224 /// is more efficient.
1225 fn consume_rev_iter(self) -> ConsumeRevIterator<T> {
1226 ConsumeRevIterator { v: self }
1230 * Reserves capacity for exactly `n` elements in the given vector.
1232 * If the capacity for `self` is already equal to or greater than the requested
1233 * capacity, then no action is taken.
1237 * * n - The number of elements to reserve space for
1239 fn reserve(&mut self, n: uint) {
1240 // Only make the (slow) call into the runtime if we have to
1241 if self.capacity() < n {
1243 let td = get_tydesc::<T>();
1244 if contains_managed::<T>() {
1245 let ptr: *mut *mut Box<Vec<()>> = cast::transmute(self);
1246 ::at_vec::raw::reserve_raw(td, ptr, n);
1248 let ptr: *mut *mut Vec<()> = cast::transmute(self);
1249 let alloc = n * sys::nonzero_size_of::<T>();
1250 let size = alloc + sys::size_of::<Vec<()>>();
1251 if alloc / sys::nonzero_size_of::<T>() != n || size < alloc {
1252 fail!("vector size is too large: %u", n);
1254 *ptr = realloc_raw(*ptr as *mut c_void, size)
1256 (**ptr).alloc = alloc;
1263 * Reserves capacity for at least `n` elements in the given vector.
1265 * This function will over-allocate in order to amortize the allocation costs
1266 * in scenarios where the caller may need to repeatedly reserve additional
1269 * If the capacity for `self` is already equal to or greater than the requested
1270 * capacity, then no action is taken.
1274 * * n - The number of elements to reserve space for
1276 fn reserve_at_least(&mut self, n: uint) {
1277 self.reserve(uint::next_power_of_two(n));
1280 /// Returns the number of elements the vector can hold without reallocating.
1282 fn capacity(&self) -> uint {
1284 if contains_managed::<T>() {
1285 let repr: **Box<Vec<()>> = cast::transmute(self);
1286 (**repr).data.alloc / sys::nonzero_size_of::<T>()
1288 let repr: **Vec<()> = cast::transmute(self);
1289 (**repr).alloc / sys::nonzero_size_of::<T>()
1294 /// Append an element to a vector
1296 fn push(&mut self, t: T) {
1298 if contains_managed::<T>() {
1299 let repr: **Box<Vec<()>> = cast::transmute(&mut *self);
1300 let fill = (**repr).data.fill;
1301 if (**repr).data.alloc <= fill {
1302 let new_len = self.len() + 1;
1303 self.reserve_at_least(new_len);
1308 let repr: **Vec<()> = cast::transmute(&mut *self);
1309 let fill = (**repr).fill;
1310 if (**repr).alloc <= fill {
1311 let new_len = self.len() + 1;
1312 self.reserve_at_least(new_len);
1320 // This doesn't bother to make sure we have space.
1321 #[inline] // really pretty please
1322 unsafe fn push_fast(&mut self, t: T) {
1323 if contains_managed::<T>() {
1324 let repr: **mut Box<Vec<u8>> = cast::transmute(self);
1325 let fill = (**repr).data.fill;
1326 (**repr).data.fill += sys::nonzero_size_of::<T>();
1327 let p = to_unsafe_ptr(&((**repr).data.data));
1328 let p = ptr::offset(p, fill as int) as *mut T;
1329 intrinsics::move_val_init(&mut(*p), t);
1331 let repr: **mut Vec<u8> = cast::transmute(self);
1332 let fill = (**repr).fill;
1333 (**repr).fill += sys::nonzero_size_of::<T>();
1334 let p = to_unsafe_ptr(&((**repr).data));
1335 let p = ptr::offset(p, fill as int) as *mut T;
1336 intrinsics::move_val_init(&mut(*p), t);
1340 /// Takes ownership of the vector `rhs`, moving all elements into
1341 /// the current vector. This does not copy any elements, and it is
1342 /// illegal to use the `rhs` vector after calling this method
1343 /// (because it is moved here).
1348 /// let mut a = ~[~1];
1349 /// a.push_all_move(~[~2, ~3, ~4]);
1350 /// assert!(a == ~[~1, ~2, ~3, ~4]);
1353 fn push_all_move(&mut self, mut rhs: ~[T]) {
1354 let self_len = self.len();
1355 let rhs_len = rhs.len();
1356 let new_len = self_len + rhs_len;
1357 self.reserve(new_len);
1358 unsafe { // Note: infallible.
1359 let self_p = vec::raw::to_mut_ptr(*self);
1360 let rhs_p = vec::raw::to_ptr(rhs);
1361 ptr::copy_memory(ptr::mut_offset(self_p, self_len as int), rhs_p, rhs_len);
1362 raw::set_len(self, new_len);
1363 raw::set_len(&mut rhs, 0);
1367 /// Remove the last element from a vector and return it, or `None` if it is empty
1368 fn pop_opt(&mut self) -> Option<T> {
1372 let valptr = ptr::to_mut_unsafe_ptr(&mut self[ln - 1u]);
1374 raw::set_len(self, ln - 1u);
1375 Some(ptr::read_ptr(valptr))
1382 /// Remove the last element from a vector and return it, failing if it is empty
1384 fn pop(&mut self) -> T {
1385 self.pop_opt().expect("pop: empty vector")
1388 /// Removes the first element from a vector and return it
1390 fn shift(&mut self) -> T {
1391 self.shift_opt().expect("shift: empty vector")
1394 /// Removes the first element from a vector and return it, or `None` if it is empty
1395 fn shift_opt(&mut self) -> Option<T> {
1397 let ln = match self.len() {
1399 1 => return self.pop_opt(),
1401 let last = self.pop();
1402 let first = self.pop_opt();
1409 let next_ln = self.len() - 1;
1411 // Save the last element. We're going to overwrite its position
1412 let work_elt = self.pop();
1413 // We still should have room to work where what last element was
1414 assert!(self.capacity() >= ln);
1415 // Pretend like we have the original length so we can use
1416 // the vector copy_memory to overwrite the hole we just made
1417 raw::set_len(self, ln);
1419 // Memcopy the head element (the one we want) to the location we just
1420 // popped. For the moment it unsafely exists at both the head and last
1423 let first_slice = self.slice(0, 1);
1424 let last_slice = self.slice(next_ln, ln);
1425 raw::copy_memory(cast::transmute(last_slice), first_slice, 1);
1428 // Memcopy everything to the left one element
1430 let init_slice = self.slice(0, next_ln);
1431 let tail_slice = self.slice(1, ln);
1432 raw::copy_memory(cast::transmute(init_slice),
1437 // Set the new length. Now the vector is back to normal
1438 raw::set_len(self, next_ln);
1440 // Swap out the element we want from the end
1441 let vp = raw::to_mut_ptr(*self);
1442 let vp = ptr::mut_offset(vp, (next_ln - 1) as int);
1444 Some(ptr::replace_ptr(vp, work_elt))
1448 /// Prepend an element to the vector
1449 fn unshift(&mut self, x: T) {
1450 let v = util::replace(self, ~[x]);
1451 self.push_all_move(v);
1454 /// Insert an element at position i within v, shifting all
1455 /// elements after position i one position to the right.
1456 fn insert(&mut self, i: uint, x:T) {
1457 let len = self.len();
1463 self.swap(j, j - 1);
1468 /// Remove and return the element at position i within v, shifting
1469 /// all elements after position i one position to the left.
1470 fn remove(&mut self, i: uint) -> T {
1471 let len = self.len();
1476 self.swap(j, j + 1);
1483 * Remove an element from anywhere in the vector and return it, replacing it
1484 * with the last element. This does not preserve ordering, but is O(1).
1486 * Fails if index >= length.
1488 fn swap_remove(&mut self, index: uint) -> T {
1489 let ln = self.len();
1491 fail!("vec::swap_remove - index %u >= length %u", index, ln);
1494 self.swap(index, ln - 1);
1499 /// Shorten a vector, dropping excess elements.
1500 fn truncate(&mut self, newlen: uint) {
1501 do self.as_mut_buf |p, oldlen| {
1502 assert!(newlen <= oldlen);
1504 // This loop is optimized out for non-drop types.
1505 for i in range(newlen, oldlen) {
1506 ptr::read_and_zero_ptr(ptr::mut_offset(p, i as int));
1510 unsafe { raw::set_len(self, newlen); }
1515 * Like `filter()`, but in place. Preserves order of `v`. Linear time.
1517 fn retain(&mut self, f: &fn(t: &T) -> bool) {
1518 let len = self.len();
1519 let mut deleted: uint = 0;
1521 for i in range(0u, len) {
1524 } else if deleted > 0 {
1525 self.swap(i - deleted, i);
1530 self.truncate(len - deleted);
1535 * Partitions the vector into those that satisfies the predicate, and
1536 * those that do not.
1539 fn partition(self, f: &fn(&T) -> bool) -> (~[T], ~[T]) {
1540 let mut lefts = ~[];
1541 let mut rights = ~[];
1543 for elt in self.consume_iter() {
1555 * Expands a vector in place, initializing the new elements to the result of
1558 * Function `init_op` is called `n` times with the values [0..`n`)
1562 * * n - The number of elements to add
1563 * * init_op - A function to call to retreive each appended element's
1566 fn grow_fn(&mut self, n: uint, op: &fn(uint) -> T) {
1567 let new_len = self.len() + n;
1568 self.reserve_at_least(new_len);
1569 let mut i: uint = 0u;
1577 impl<T> Mutable for ~[T] {
1578 /// Clear the vector, removing all values.
1579 fn clear(&mut self) { self.truncate(0) }
1582 #[allow(missing_doc)]
1583 pub trait OwnedCopyableVector<T:Clone> {
1584 fn push_all(&mut self, rhs: &[T]);
1585 fn grow(&mut self, n: uint, initval: &T);
1586 fn grow_set(&mut self, index: uint, initval: &T, val: T);
1589 impl<T:Clone> OwnedCopyableVector<T> for ~[T] {
1590 /// Iterates over the slice `rhs`, copies each element, and then appends it to
1591 /// the vector provided `v`. The `rhs` vector is traversed in-order.
1596 /// let mut a = ~[1];
1597 /// a.push_all([2, 3, 4]);
1598 /// assert!(a == ~[1, 2, 3, 4]);
1601 fn push_all(&mut self, rhs: &[T]) {
1602 let new_len = self.len() + rhs.len();
1603 self.reserve(new_len);
1605 for i in range(0u, rhs.len()) {
1606 self.push(unsafe { raw::get(rhs, i) })
1611 * Expands a vector in place, initializing the new elements to a given value
1615 * * n - The number of elements to add
1616 * * initval - The value for the new elements
1618 fn grow(&mut self, n: uint, initval: &T) {
1619 let new_len = self.len() + n;
1620 self.reserve_at_least(new_len);
1621 let mut i: uint = 0u;
1624 self.push((*initval).clone());
1630 * Sets the value of a vector element at a given index, growing the vector as
1633 * Sets the element at position `index` to `val`. If `index` is past the end
1634 * of the vector, expands the vector by replicating `initval` to fill the
1635 * intervening space.
1637 fn grow_set(&mut self, index: uint, initval: &T, val: T) {
1639 if index >= l { self.grow(index - l + 1u, initval); }
1644 #[allow(missing_doc)]
1645 pub trait OwnedEqVector<T:Eq> {
1646 fn dedup(&mut self);
1649 impl<T:Eq> OwnedEqVector<T> for ~[T] {
1651 * Remove consecutive repeated elements from a vector; if the vector is
1652 * sorted, this removes all duplicates.
1654 pub fn dedup(&mut self) {
1656 // Although we have a mutable reference to `self`, we cannot make
1657 // *arbitrary* changes. There exists the possibility that this
1658 // vector is contained with an `@mut` box and hence is still
1659 // readable by the outside world during the `Eq` comparisons.
1660 // Moreover, those comparisons could fail, so we must ensure
1661 // that the vector is in a valid state at all time.
1663 // The way that we handle this is by using swaps; we iterate
1664 // over all the elements, swapping as we go so that at the end
1665 // the elements we wish to keep are in the front, and those we
1666 // wish to reject are at the back. We can then truncate the
1667 // vector. This operation is still O(n).
1669 // Example: We start in this state, where `r` represents "next
1670 // read" and `w` represents "next_write`.
1673 // +---+---+---+---+---+---+
1674 // | 0 | 1 | 1 | 2 | 3 | 3 |
1675 // +---+---+---+---+---+---+
1678 // Comparing self[r] against self[w-1], tis is not a duplicate, so
1679 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1680 // r and w, leaving us with:
1683 // +---+---+---+---+---+---+
1684 // | 0 | 1 | 1 | 2 | 3 | 3 |
1685 // +---+---+---+---+---+---+
1688 // Comparing self[r] against self[w-1], this value is a duplicate,
1689 // so we increment `r` but leave everything else unchanged:
1692 // +---+---+---+---+---+---+
1693 // | 0 | 1 | 1 | 2 | 3 | 3 |
1694 // +---+---+---+---+---+---+
1697 // Comparing self[r] against self[w-1], this is not a duplicate,
1698 // so swap self[r] and self[w] and advance r and w:
1701 // +---+---+---+---+---+---+
1702 // | 0 | 1 | 2 | 1 | 3 | 3 |
1703 // +---+---+---+---+---+---+
1706 // Not a duplicate, repeat:
1709 // +---+---+---+---+---+---+
1710 // | 0 | 1 | 2 | 3 | 1 | 3 |
1711 // +---+---+---+---+---+---+
1714 // Duplicate, advance r. End of vec. Truncate to w.
1716 let ln = self.len();
1717 if ln < 1 { return; }
1719 // Avoid bounds checks by using unsafe pointers.
1720 let p = vec::raw::to_mut_ptr(*self);
1725 let p_r = ptr::mut_offset(p, r as int);
1726 let p_wm1 = ptr::mut_offset(p, (w - 1) as int);
1729 let p_w = ptr::mut_offset(p_wm1, 1);
1730 util::swap(&mut *p_r, &mut *p_w);
1742 #[allow(missing_doc)]
1743 pub trait MutableVector<'self, T> {
1744 fn mut_slice(self, start: uint, end: uint) -> &'self mut [T];
1745 fn mut_slice_from(self, start: uint) -> &'self mut [T];
1746 fn mut_slice_to(self, end: uint) -> &'self mut [T];
1747 fn mut_iter(self) -> VecMutIterator<'self, T>;
1748 fn mut_rev_iter(self) -> MutRevIterator<'self, T>;
1750 fn swap(self, a: uint, b: uint);
1753 * Divides one `&mut` into two. The first will
1754 * contain all indices from `0..mid` (excluding the index `mid`
1755 * itself) and the second will contain all indices from
1756 * `mid..len` (excluding the index `len` itself).
1758 fn mut_split(self, mid: uint) -> (&'self mut [T],
1764 * Consumes `src` and moves as many elements as it can into `self`
1765 * from the range [start,end).
1767 * Returns the number of elements copied (the shorter of self.len()
1772 * * src - A mutable vector of `T`
1773 * * start - The index into `src` to start copying from
1774 * * end - The index into `str` to stop copying from
1776 fn move_from(self, src: ~[T], start: uint, end: uint) -> uint;
1778 unsafe fn unsafe_mut_ref(self, index: uint) -> *mut T;
1779 unsafe fn unsafe_set(self, index: uint, val: T);
1781 fn as_mut_buf<U>(self, f: &fn(*mut T, uint) -> U) -> U;
1784 impl<'self,T> MutableVector<'self, T> for &'self mut [T] {
1785 /// Return a slice that points into another slice.
1787 fn mut_slice(self, start: uint, end: uint) -> &'self mut [T] {
1788 assert!(start <= end);
1789 assert!(end <= self.len());
1790 do self.as_mut_buf |p, _len| {
1792 cast::transmute(Slice {
1793 data: ptr::mut_offset(p, start as int) as *T,
1794 len: (end - start) * sys::nonzero_size_of::<T>()
1801 * Returns a slice of self from `start` to the end of the vec.
1803 * Fails when `start` points outside the bounds of self.
1806 fn mut_slice_from(self, start: uint) -> &'self mut [T] {
1807 let len = self.len();
1808 self.mut_slice(start, len)
1812 * Returns a slice of self from the start of the vec to `end`.
1814 * Fails when `end` points outside the bounds of self.
1817 fn mut_slice_to(self, end: uint) -> &'self mut [T] {
1818 self.mut_slice(0, end)
1822 fn mut_split(self, mid: uint) -> (&'self mut [T], &'self mut [T]) {
1824 let len = self.len();
1825 let self2: &'self mut [T] = cast::transmute_copy(&self);
1826 (self.mut_slice(0, mid), self2.mut_slice(mid, len))
1831 fn mut_iter(self) -> VecMutIterator<'self, T> {
1833 let p = vec::raw::to_mut_ptr(self);
1834 if sys::size_of::<T>() == 0 {
1835 VecMutIterator{ptr: p,
1836 end: (p as uint + self.len()) as *mut T,
1837 lifetime: cast::transmute(p)}
1839 VecMutIterator{ptr: p,
1840 end: p.offset_inbounds(self.len() as int),
1841 lifetime: cast::transmute(p)}
1847 fn mut_rev_iter(self) -> MutRevIterator<'self, T> {
1848 self.mut_iter().invert()
1852 * Swaps two elements in a vector
1856 * * a - The index of the first element
1857 * * b - The index of the second element
1859 fn swap(self, a: uint, b: uint) {
1861 // Can't take two mutable loans from one vector, so instead just cast
1862 // them to their raw pointers to do the swap
1863 let pa: *mut T = &mut self[a];
1864 let pb: *mut T = &mut self[b];
1865 ptr::swap_ptr(pa, pb);
1869 /// Reverse the order of elements in a vector, in place
1871 let mut i: uint = 0;
1872 let ln = self.len();
1874 self.swap(i, ln - i - 1);
1880 fn move_from(self, mut src: ~[T], start: uint, end: uint) -> uint {
1881 for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
1884 cmp::min(self.len(), end-start)
1888 unsafe fn unsafe_mut_ref(self, index: uint) -> *mut T {
1889 ptr::mut_offset(self.repr().data as *mut T, index as int)
1893 unsafe fn unsafe_set(self, index: uint, val: T) {
1894 *self.unsafe_mut_ref(index) = val;
1897 /// Similar to `as_imm_buf` but passing a `*mut T`
1899 fn as_mut_buf<U>(self, f: &fn(*mut T, uint) -> U) -> U {
1900 let Slice{ data, len } = self.repr();
1901 f(data as *mut T, len / sys::nonzero_size_of::<T>())
1906 /// Trait for &[T] where T is Cloneable
1907 pub trait MutableCloneableVector<T> {
1908 /// Copies as many elements from `src` as it can into `self`
1909 /// (the shorter of self.len() and src.len()). Returns the number of elements copied.
1910 fn copy_from(self, &[T]) -> uint;
1913 impl<'self, T:Clone> MutableCloneableVector<T> for &'self mut [T] {
1915 fn copy_from(self, src: &[T]) -> uint {
1916 for (a, b) in self.mut_iter().zip(src.iter()) {
1919 cmp::min(self.len(), src.len())
1924 * Constructs a vector from an unsafe pointer to a buffer
1928 * * ptr - An unsafe pointer to a buffer of `T`
1929 * * elts - The number of elements in the buffer
1931 // Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
1932 pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
1933 raw::from_buf_raw(ptr, elts)
1936 /// Unsafe operations
1943 use unstable::intrinsics;
1944 use vec::{with_capacity, ImmutableVector, MutableVector};
1945 use unstable::intrinsics::contains_managed;
1946 use unstable::raw::{Box, Vec, Slice};
1949 * Sets the length of a vector
1951 * This will explicitly set the size of the vector, without actually
1952 * modifing its buffers, so it is up to the caller to ensure that
1953 * the vector is actually the specified size.
1956 pub unsafe fn set_len<T>(v: &mut ~[T], new_len: uint) {
1957 if contains_managed::<T>() {
1958 let repr: **mut Box<Vec<()>> = cast::transmute(v);
1959 (**repr).data.fill = new_len * sys::nonzero_size_of::<T>();
1961 let repr: **mut Vec<()> = cast::transmute(v);
1962 (**repr).fill = new_len * sys::nonzero_size_of::<T>();
1967 * Returns an unsafe pointer to the vector's buffer
1969 * The caller must ensure that the vector outlives the pointer this
1970 * function returns, or else it will end up pointing to garbage.
1972 * Modifying the vector may cause its buffer to be reallocated, which
1973 * would also make any pointers to it invalid.
1976 pub fn to_ptr<T>(v: &[T]) -> *T {
1980 /** see `to_ptr()` */
1982 pub fn to_mut_ptr<T>(v: &mut [T]) -> *mut T {
1983 v.repr().data as *mut T
1987 * Form a slice from a pointer and length (as a number of units,
1991 pub unsafe fn buf_as_slice<T,U>(p: *T,
1993 f: &fn(v: &[T]) -> U) -> U {
1994 f(cast::transmute(Slice {
1996 len: len * sys::nonzero_size_of::<T>()
2001 * Form a slice from a pointer and length (as a number of units,
2005 pub unsafe fn mut_buf_as_slice<T,U>(p: *mut T,
2007 f: &fn(v: &mut [T]) -> U) -> U {
2008 f(cast::transmute(Slice {
2010 len: len * sys::nonzero_size_of::<T>()
2015 * Unchecked vector indexing.
2018 pub unsafe fn get<T:Clone>(v: &[T], i: uint) -> T {
2019 v.as_imm_buf(|p, _len| (*ptr::offset(p, i as int)).clone())
2023 * Unchecked vector index assignment. Does not drop the
2024 * old value and hence is only suitable when the vector
2025 * is newly allocated.
2028 pub unsafe fn init_elem<T>(v: &mut [T], i: uint, val: T) {
2029 let mut box = Some(val);
2030 do v.as_mut_buf |p, _len| {
2031 intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)),
2037 * Constructs a vector from an unsafe pointer to a buffer
2041 * * ptr - An unsafe pointer to a buffer of `T`
2042 * * elts - The number of elements in the buffer
2044 // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
2046 pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
2047 let mut dst = with_capacity(elts);
2048 set_len(&mut dst, elts);
2049 dst.as_mut_buf(|p_dst, _len_dst| ptr::copy_memory(p_dst, ptr, elts));
2054 * Copies data from one vector to another.
2056 * Copies `count` bytes from `src` to `dst`. The source and destination
2060 pub unsafe fn copy_memory<T>(dst: &mut [T], src: &[T],
2062 assert!(dst.len() >= count);
2063 assert!(src.len() >= count);
2065 do dst.as_mut_buf |p_dst, _len_dst| {
2066 do src.as_imm_buf |p_src, _len_src| {
2067 ptr::copy_memory(p_dst, p_src, count)
2073 /// Operations on `[u8]`
2081 /// A trait for operations on mutable operations on `[u8]`
2082 pub trait MutableByteVector {
2083 /// Sets all bytes of the receiver to the given value.
2084 pub fn set_memory(self, value: u8);
2087 impl<'self> MutableByteVector for &'self mut [u8] {
2089 fn set_memory(self, value: u8) {
2090 do self.as_mut_buf |p, len| {
2091 unsafe { ptr::set_memory(p, value, len) };
2096 /// Bytewise string comparison
2097 pub fn memcmp(a: &~[u8], b: &~[u8]) -> int {
2098 let a_len = a.len();
2099 let b_len = b.len();
2100 let n = num::min(a_len, b_len) as libc::size_t;
2102 libc::memcmp(raw::to_ptr(*a) as *libc::c_void,
2103 raw::to_ptr(*b) as *libc::c_void, n) as int
2106 if r != 0 { r } else {
2109 } else if a_len < b_len {
2117 /// Bytewise less than or equal
2118 pub fn lt(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) < 0 }
2120 /// Bytewise less than or equal
2121 pub fn le(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) <= 0 }
2123 /// Bytewise equality
2124 pub fn eq(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) == 0 }
2126 /// Bytewise inequality
2127 pub fn ne(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) != 0 }
2129 /// Bytewise greater than or equal
2130 pub fn ge(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) >= 0 }
2132 /// Bytewise greater than
2133 pub fn gt(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) > 0 }
2136 * Copies data from one vector to another.
2138 * Copies `count` bytes from `src` to `dst`. The source and destination
2142 pub fn copy_memory(dst: &mut [u8], src: &[u8], count: uint) {
2143 // Bound checks are done at vec::raw::copy_memory.
2144 unsafe { vec::raw::copy_memory(dst, src, count) }
2148 impl<A:Clone> Clone for ~[A] {
2150 fn clone(&self) -> ~[A] {
2151 self.iter().transform(|item| item.clone()).collect()
2155 // This works because every lifetime is a sub-lifetime of 'static
2156 impl<'self, A> Zero for &'self [A] {
2157 fn zero() -> &'self [A] { &'self [] }
2158 fn is_zero(&self) -> bool { self.is_empty() }
2161 impl<A> Zero for ~[A] {
2162 fn zero() -> ~[A] { ~[] }
2163 fn is_zero(&self) -> bool { self.len() == 0 }
2166 impl<A> Zero for @[A] {
2167 fn zero() -> @[A] { @[] }
2168 fn is_zero(&self) -> bool { self.len() == 0 }
2171 macro_rules! iterator {
2172 /* FIXME: #4375 Cannot attach documentation/attributes to a macro generated struct.
2173 (struct $name:ident -> $ptr:ty, $elem:ty) => {
2174 pub struct $name<'self, T> {
2177 priv lifetime: $elem // FIXME: #5922
2180 (impl $name:ident -> $elem:ty) => {
2181 impl<'self, T> Iterator<$elem> for $name<'self, T> {
2183 fn next(&mut self) -> Option<$elem> {
2184 // could be implemented with slices, but this avoids bounds checks
2186 if self.ptr == self.end {
2190 self.ptr = if sys::size_of::<T>() == 0 {
2191 // purposefully don't use 'ptr.offset' because for
2192 // vectors with 0-size elements this would return the
2194 cast::transmute(self.ptr as uint + 1)
2196 self.ptr.offset_inbounds(1)
2199 Some(cast::transmute(old))
2205 fn size_hint(&self) -> (uint, Option<uint>) {
2206 let diff = (self.end as uint) - (self.ptr as uint);
2207 let exact = diff / sys::nonzero_size_of::<T>();
2208 (exact, Some(exact))
2214 macro_rules! double_ended_iterator {
2215 (impl $name:ident -> $elem:ty) => {
2216 impl<'self, T> DoubleEndedIterator<$elem> for $name<'self, T> {
2218 fn next_back(&mut self) -> Option<$elem> {
2219 // could be implemented with slices, but this avoids bounds checks
2221 if self.end == self.ptr {
2224 self.end = if sys::size_of::<T>() == 0 {
2225 // See above for why 'ptr.offset' isn't used
2226 cast::transmute(self.end as uint - 1)
2228 self.end.offset_inbounds(-1)
2230 Some(cast::transmute(self.end))
2238 impl<'self, T> RandomAccessIterator<&'self T> for VecIterator<'self, T> {
2240 fn indexable(&self) -> uint {
2241 let (exact, _) = self.size_hint();
2245 fn idx(&self, index: uint) -> Option<&'self T> {
2247 if index < self.indexable() {
2248 cast::transmute(self.ptr.offset(index as int))
2256 //iterator!{struct VecIterator -> *T, &'self T}
2257 /// An iterator for iterating over a vector.
2258 pub struct VecIterator<'self, T> {
2261 priv lifetime: &'self T // FIXME: #5922
2263 iterator!{impl VecIterator -> &'self T}
2264 double_ended_iterator!{impl VecIterator -> &'self T}
2265 pub type RevIterator<'self, T> = Invert<VecIterator<'self, T>>;
2267 impl<'self, T> Clone for VecIterator<'self, T> {
2268 fn clone(&self) -> VecIterator<'self, T> { *self }
2271 //iterator!{struct VecMutIterator -> *mut T, &'self mut T}
2272 /// An iterator for mutating the elements of a vector.
2273 pub struct VecMutIterator<'self, T> {
2276 priv lifetime: &'self mut T // FIXME: #5922
2278 iterator!{impl VecMutIterator -> &'self mut T}
2279 double_ended_iterator!{impl VecMutIterator -> &'self mut T}
2280 pub type MutRevIterator<'self, T> = Invert<VecMutIterator<'self, T>>;
2282 /// An iterator that moves out of a vector.
2284 pub struct ConsumeIterator<T> {
2289 impl<T> Iterator<T> for ConsumeIterator<T> {
2290 fn next(&mut self) -> Option<T> {
2291 // this is peculiar, but is required for safety with respect
2292 // to dtors. It traverses the first half of the vec, and
2293 // removes them by swapping them with the last element (and
2294 // popping), which results in the second half in reverse
2295 // order, and so these can just be pop'd off. That is,
2297 // [1,2,3,4,5] => 1, [5,2,3,4] => 2, [5,4,3] => 3, [5,4] => 4,
2299 let l = self.v.len();
2301 self.v.swap(self.idx, l - 1);
2309 /// An iterator that moves out of a vector in reverse order.
2311 pub struct ConsumeRevIterator<T> {
2315 impl<T> Iterator<T> for ConsumeRevIterator<T> {
2316 fn next(&mut self) -> Option<T> {
2321 impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] {
2322 fn from_iterator(iterator: &mut T) -> ~[A] {
2323 let (lower, _) = iterator.size_hint();
2324 let mut xs = with_capacity(lower);
2325 for x in *iterator {
2332 impl<A, T: Iterator<A>> Extendable<A, T> for ~[A] {
2333 fn extend(&mut self, iterator: &mut T) {
2334 let (lower, _) = iterator.size_hint();
2335 let len = self.len();
2336 self.reserve(len + lower);
2337 for x in *iterator {
2345 use option::{None, Option, Some};
2350 fn square(n: uint) -> uint { n * n }
2352 fn square_ref(n: &uint) -> uint { square(*n) }
2354 fn is_three(n: &uint) -> bool { *n == 3u }
2356 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
2358 fn is_equal(x: &uint, y:&uint) -> bool { *x == *y }
2360 fn square_if_odd_r(n: &uint) -> Option<uint> {
2361 if *n % 2u == 1u { Some(*n * *n) } else { None }
2364 fn square_if_odd_v(n: uint) -> Option<uint> {
2365 if n % 2u == 1u { Some(n * n) } else { None }
2368 fn add(x: uint, y: &uint) -> uint { x + *y }
2371 fn test_unsafe_ptrs() {
2373 // Test on-stack copy-from-buf.
2375 let mut ptr = raw::to_ptr(a);
2376 let b = from_buf(ptr, 3u);
2377 assert_eq!(b.len(), 3u);
2378 assert_eq!(b[0], 1);
2379 assert_eq!(b[1], 2);
2380 assert_eq!(b[2], 3);
2382 // Test on-heap copy-from-buf.
2383 let c = ~[1, 2, 3, 4, 5];
2384 ptr = raw::to_ptr(c);
2385 let d = from_buf(ptr, 5u);
2386 assert_eq!(d.len(), 5u);
2387 assert_eq!(d[0], 1);
2388 assert_eq!(d[1], 2);
2389 assert_eq!(d[2], 3);
2390 assert_eq!(d[3], 4);
2391 assert_eq!(d[4], 5);
2397 // Test on-stack from_fn.
2398 let mut v = from_fn(3u, square);
2399 assert_eq!(v.len(), 3u);
2400 assert_eq!(v[0], 0u);
2401 assert_eq!(v[1], 1u);
2402 assert_eq!(v[2], 4u);
2404 // Test on-heap from_fn.
2405 v = from_fn(5u, square);
2406 assert_eq!(v.len(), 5u);
2407 assert_eq!(v[0], 0u);
2408 assert_eq!(v[1], 1u);
2409 assert_eq!(v[2], 4u);
2410 assert_eq!(v[3], 9u);
2411 assert_eq!(v[4], 16u);
2415 fn test_from_elem() {
2416 // Test on-stack from_elem.
2417 let mut v = from_elem(2u, 10u);
2418 assert_eq!(v.len(), 2u);
2419 assert_eq!(v[0], 10u);
2420 assert_eq!(v[1], 10u);
2422 // Test on-heap from_elem.
2423 v = from_elem(6u, 20u);
2424 assert_eq!(v[0], 20u);
2425 assert_eq!(v[1], 20u);
2426 assert_eq!(v[2], 20u);
2427 assert_eq!(v[3], 20u);
2428 assert_eq!(v[4], 20u);
2429 assert_eq!(v[5], 20u);
2433 fn test_is_empty() {
2434 let xs: [int, ..0] = [];
2435 assert!(xs.is_empty());
2436 assert!(![0].is_empty());
2440 fn test_len_divzero() {
2442 let v0 : &[Z] = &[];
2443 let v1 : &[Z] = &[[]];
2444 let v2 : &[Z] = &[[], []];
2445 assert_eq!(sys::size_of::<Z>(), 0);
2446 assert_eq!(v0.len(), 0);
2447 assert_eq!(v1.len(), 1);
2448 assert_eq!(v2.len(), 2);
2454 assert_eq!(a.head(), &11);
2456 assert_eq!(a.head(), &11);
2461 #[ignore(cfg(windows))]
2462 fn test_head_empty() {
2463 let a: ~[int] = ~[];
2468 fn test_head_opt() {
2470 assert_eq!(a.head_opt(), None);
2472 assert_eq!(a.head_opt().unwrap(), &11);
2474 assert_eq!(a.head_opt().unwrap(), &11);
2480 assert_eq!(a.tail(), &[]);
2482 assert_eq!(a.tail(), &[12]);
2487 #[ignore(cfg(windows))]
2488 fn test_tail_empty() {
2489 let a: ~[int] = ~[];
2495 let mut a = ~[11, 12, 13];
2496 assert_eq!(a.tailn(0), &[11, 12, 13]);
2498 assert_eq!(a.tailn(2), &[13]);
2503 #[ignore(cfg(windows))]
2504 fn test_tailn_empty() {
2505 let a: ~[int] = ~[];
2512 assert_eq!(a.init(), &[]);
2514 assert_eq!(a.init(), &[11]);
2519 #[ignore(cfg(windows))]
2520 fn test_init_empty() {
2521 let a: ~[int] = ~[];
2527 let mut a = ~[11, 12, 13];
2528 assert_eq!(a.initn(0), &[11, 12, 13]);
2530 assert_eq!(a.initn(2), &[11]);
2535 #[ignore(cfg(windows))]
2536 fn test_initn_empty() {
2537 let a: ~[int] = ~[];
2544 assert_eq!(a.last(), &11);
2546 assert_eq!(a.last(), &12);
2551 #[ignore(cfg(windows))]
2552 fn test_last_empty() {
2553 let a: ~[int] = ~[];
2558 fn test_last_opt() {
2560 assert_eq!(a.last_opt(), None);
2562 assert_eq!(a.last_opt().unwrap(), &11);
2564 assert_eq!(a.last_opt().unwrap(), &12);
2569 // Test fixed length vector.
2570 let vec_fixed = [1, 2, 3, 4];
2571 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
2572 assert_eq!(v_a.len(), 3u);
2573 assert_eq!(v_a[0], 2);
2574 assert_eq!(v_a[1], 3);
2575 assert_eq!(v_a[2], 4);
2578 let vec_stack = &[1, 2, 3];
2579 let v_b = vec_stack.slice(1u, 3u).to_owned();
2580 assert_eq!(v_b.len(), 2u);
2581 assert_eq!(v_b[0], 2);
2582 assert_eq!(v_b[1], 3);
2584 // Test on managed heap.
2585 let vec_managed = @[1, 2, 3, 4, 5];
2586 let v_c = vec_managed.slice(0u, 3u).to_owned();
2587 assert_eq!(v_c.len(), 3u);
2588 assert_eq!(v_c[0], 1);
2589 assert_eq!(v_c[1], 2);
2590 assert_eq!(v_c[2], 3);
2592 // Test on exchange heap.
2593 let vec_unique = ~[1, 2, 3, 4, 5, 6];
2594 let v_d = vec_unique.slice(1u, 6u).to_owned();
2595 assert_eq!(v_d.len(), 5u);
2596 assert_eq!(v_d[0], 2);
2597 assert_eq!(v_d[1], 3);
2598 assert_eq!(v_d[2], 4);
2599 assert_eq!(v_d[3], 5);
2600 assert_eq!(v_d[4], 6);
2604 fn test_slice_from() {
2605 let vec = &[1, 2, 3, 4];
2606 assert_eq!(vec.slice_from(0), vec);
2607 assert_eq!(vec.slice_from(2), &[3, 4]);
2608 assert_eq!(vec.slice_from(4), &[]);
2612 fn test_slice_to() {
2613 let vec = &[1, 2, 3, 4];
2614 assert_eq!(vec.slice_to(4), vec);
2615 assert_eq!(vec.slice_to(2), &[1, 2]);
2616 assert_eq!(vec.slice_to(0), &[]);
2621 // Test on-heap pop.
2622 let mut v = ~[1, 2, 3, 4, 5];
2624 assert_eq!(v.len(), 4u);
2625 assert_eq!(v[0], 1);
2626 assert_eq!(v[1], 2);
2627 assert_eq!(v[2], 3);
2628 assert_eq!(v[3], 4);
2635 let e = v.pop_opt();
2636 assert_eq!(v.len(), 0);
2637 assert_eq!(e, Some(5));
2638 let f = v.pop_opt();
2639 assert_eq!(f, None);
2640 let g = v.pop_opt();
2641 assert_eq!(g, None);
2644 fn test_swap_remove() {
2645 let mut v = ~[1, 2, 3, 4, 5];
2646 let mut e = v.swap_remove(0);
2647 assert_eq!(v.len(), 4);
2649 assert_eq!(v[0], 5);
2650 e = v.swap_remove(3);
2651 assert_eq!(v.len(), 3);
2653 assert_eq!(v[0], 5);
2654 assert_eq!(v[1], 2);
2655 assert_eq!(v[2], 3);
2659 fn test_swap_remove_noncopyable() {
2660 // Tests that we don't accidentally run destructors twice.
2661 let mut v = ~[::unstable::sync::Exclusive::new(()),
2662 ::unstable::sync::Exclusive::new(()),
2663 ::unstable::sync::Exclusive::new(())];
2664 let mut _e = v.swap_remove(0);
2665 assert_eq!(v.len(), 2);
2666 _e = v.swap_remove(1);
2667 assert_eq!(v.len(), 1);
2668 _e = v.swap_remove(0);
2669 assert_eq!(v.len(), 0);
2674 // Test on-stack push().
2677 assert_eq!(v.len(), 1u);
2678 assert_eq!(v[0], 1);
2680 // Test on-heap push().
2682 assert_eq!(v.len(), 2u);
2683 assert_eq!(v[0], 1);
2684 assert_eq!(v[1], 2);
2689 // Test on-stack grow().
2692 assert_eq!(v.len(), 2u);
2693 assert_eq!(v[0], 1);
2694 assert_eq!(v[1], 1);
2696 // Test on-heap grow().
2698 assert_eq!(v.len(), 5u);
2699 assert_eq!(v[0], 1);
2700 assert_eq!(v[1], 1);
2701 assert_eq!(v[2], 2);
2702 assert_eq!(v[3], 2);
2703 assert_eq!(v[4], 2);
2709 v.grow_fn(3u, square);
2710 assert_eq!(v.len(), 3u);
2711 assert_eq!(v[0], 0u);
2712 assert_eq!(v[1], 1u);
2713 assert_eq!(v[2], 4u);
2717 fn test_grow_set() {
2718 let mut v = ~[1, 2, 3];
2719 v.grow_set(4u, &4, 5);
2720 assert_eq!(v.len(), 5u);
2721 assert_eq!(v[0], 1);
2722 assert_eq!(v[1], 2);
2723 assert_eq!(v[2], 3);
2724 assert_eq!(v[3], 4);
2725 assert_eq!(v[4], 5);
2729 fn test_truncate() {
2730 let mut v = ~[@6,@5,@4];
2732 assert_eq!(v.len(), 1);
2733 assert_eq!(*(v[0]), 6);
2734 // If the unsafe block didn't drop things properly, we blow up here.
2739 let mut v = ~[@6,@5,@4];
2741 assert_eq!(v.len(), 0);
2742 // If the unsafe block didn't drop things properly, we blow up here.
2747 fn case(a: ~[uint], b: ~[uint]) {
2755 case(~[1,2,3], ~[1,2,3]);
2756 case(~[1,1,2,3], ~[1,2,3]);
2757 case(~[1,2,2,3], ~[1,2,3]);
2758 case(~[1,2,3,3], ~[1,2,3]);
2759 case(~[1,1,2,2,2,3,3], ~[1,2,3]);
2763 fn test_dedup_unique() {
2764 let mut v0 = ~[~1, ~1, ~2, ~3];
2766 let mut v1 = ~[~1, ~2, ~2, ~3];
2768 let mut v2 = ~[~1, ~2, ~3, ~3];
2771 * If the ~pointers were leaked or otherwise misused, valgrind and/or
2772 * rustrt should raise errors.
2777 fn test_dedup_shared() {
2778 let mut v0 = ~[@1, @1, @2, @3];
2780 let mut v1 = ~[@1, @2, @2, @3];
2782 let mut v2 = ~[@1, @2, @3, @3];
2785 * If the @pointers were leaked or otherwise misused, valgrind and/or
2786 * rustrt should raise errors.
2792 // Test on-stack map.
2793 let v = &[1u, 2u, 3u];
2794 let mut w = v.map(square_ref);
2795 assert_eq!(w.len(), 3u);
2796 assert_eq!(w[0], 1u);
2797 assert_eq!(w[1], 4u);
2798 assert_eq!(w[2], 9u);
2800 // Test on-heap map.
2801 let v = ~[1u, 2u, 3u, 4u, 5u];
2802 w = v.map(square_ref);
2803 assert_eq!(w.len(), 5u);
2804 assert_eq!(w[0], 1u);
2805 assert_eq!(w[1], 4u);
2806 assert_eq!(w[2], 9u);
2807 assert_eq!(w[3], 16u);
2808 assert_eq!(w[4], 25u);
2813 let mut v = ~[1, 2, 3, 4, 5];
2815 assert_eq!(v, ~[1, 3, 5]);
2819 fn test_each_permutation() {
2820 let mut results: ~[~[int]];
2823 do each_permutation([]) |v| { results.push(v.to_owned()); true };
2824 assert_eq!(results, ~[~[]]);
2827 do each_permutation([7]) |v| { results.push(v.to_owned()); true };
2828 assert_eq!(results, ~[~[7]]);
2831 do each_permutation([1,1]) |v| { results.push(v.to_owned()); true };
2832 assert_eq!(results, ~[~[1,1],~[1,1]]);
2835 do each_permutation([5,2,0]) |v| { results.push(v.to_owned()); true };
2837 ~[~[5,2,0],~[5,0,2],~[2,5,0],~[2,0,5],~[0,5,2],~[0,2,5]]);
2841 fn test_zip_unzip() {
2842 let v1 = ~[1, 2, 3];
2843 let v2 = ~[4, 5, 6];
2845 let z1 = zip(v1, v2);
2847 assert_eq!((1, 4), z1[0]);
2848 assert_eq!((2, 5), z1[1]);
2849 assert_eq!((3, 6), z1[2]);
2851 let (left, right) = unzip(z1);
2853 assert_eq!((1, 4), (left[0], right[0]));
2854 assert_eq!((2, 5), (left[1], right[1]));
2855 assert_eq!((3, 6), (left[2], right[2]));
2859 fn test_position_elem() {
2860 assert!([].position_elem(&1).is_none());
2862 let v1 = ~[1, 2, 3, 3, 2, 5];
2863 assert_eq!(v1.position_elem(&1), Some(0u));
2864 assert_eq!(v1.position_elem(&2), Some(1u));
2865 assert_eq!(v1.position_elem(&5), Some(5u));
2866 assert!(v1.position_elem(&4).is_none());
2870 fn test_rposition() {
2871 fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
2872 fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
2873 let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
2875 assert_eq!(v.rposition(f), Some(3u));
2876 assert!(v.rposition(g).is_none());
2880 fn test_bsearch_elem() {
2881 assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
2882 assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
2883 assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
2884 assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
2885 assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
2887 assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
2888 assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
2889 assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
2890 assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
2892 assert_eq!([2,4,6,8].bsearch_elem(&1), None);
2893 assert_eq!([2,4,6,8].bsearch_elem(&5), None);
2894 assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
2895 assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
2897 assert_eq!([2,4,6].bsearch_elem(&1), None);
2898 assert_eq!([2,4,6].bsearch_elem(&5), None);
2899 assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
2900 assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
2902 assert_eq!([2,4].bsearch_elem(&1), None);
2903 assert_eq!([2,4].bsearch_elem(&5), None);
2904 assert_eq!([2,4].bsearch_elem(&2), Some(0));
2905 assert_eq!([2,4].bsearch_elem(&4), Some(1));
2907 assert_eq!([2].bsearch_elem(&1), None);
2908 assert_eq!([2].bsearch_elem(&5), None);
2909 assert_eq!([2].bsearch_elem(&2), Some(0));
2911 assert_eq!([].bsearch_elem(&1), None);
2912 assert_eq!([].bsearch_elem(&5), None);
2914 assert!([1,1,1,1,1].bsearch_elem(&1) != None);
2915 assert!([1,1,1,1,2].bsearch_elem(&1) != None);
2916 assert!([1,1,1,2,2].bsearch_elem(&1) != None);
2917 assert!([1,1,2,2,2].bsearch_elem(&1) != None);
2918 assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
2920 assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
2921 assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
2926 let mut v: ~[int] = ~[10, 20];
2927 assert_eq!(v[0], 10);
2928 assert_eq!(v[1], 20);
2930 assert_eq!(v[0], 20);
2931 assert_eq!(v[1], 10);
2933 let mut v3: ~[int] = ~[];
2935 assert!(v3.is_empty());
2939 fn test_partition() {
2940 assert_eq!((~[]).partition(|x: &int| *x < 3), (~[], ~[]));
2941 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
2942 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 2), (~[1], ~[2, 3]));
2943 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
2947 fn test_partitioned() {
2948 assert_eq!(([]).partitioned(|x: &int| *x < 3), (~[], ~[]))
2949 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
2950 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (~[1], ~[2, 3]));
2951 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
2956 assert_eq!(concat([~[1], ~[2,3]]), ~[1, 2, 3]);
2957 assert_eq!([~[1], ~[2,3]].concat_vec(), ~[1, 2, 3]);
2959 assert_eq!(concat_slices([&[1], &[2,3]]), ~[1, 2, 3]);
2960 assert_eq!([&[1], &[2,3]].concat_vec(), ~[1, 2, 3]);
2965 assert_eq!(connect([], &0), ~[]);
2966 assert_eq!(connect([~[1], ~[2, 3]], &0), ~[1, 0, 2, 3]);
2967 assert_eq!(connect([~[1], ~[2], ~[3]], &0), ~[1, 0, 2, 0, 3]);
2968 assert_eq!([~[1], ~[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
2969 assert_eq!([~[1], ~[2], ~[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
2971 assert_eq!(connect_slices([], &0), ~[]);
2972 assert_eq!(connect_slices([&[1], &[2, 3]], &0), ~[1, 0, 2, 3]);
2973 assert_eq!(connect_slices([&[1], &[2], &[3]], &0), ~[1, 0, 2, 0, 3]);
2974 assert_eq!([&[1], &[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
2975 assert_eq!([&[1], &[2], &[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
2980 let mut x = ~[1, 2, 3];
2981 assert_eq!(x.shift(), 1);
2982 assert_eq!(&x, &~[2, 3]);
2983 assert_eq!(x.shift(), 2);
2984 assert_eq!(x.shift(), 3);
2985 assert_eq!(x.len(), 0);
2989 fn test_shift_opt() {
2990 let mut x = ~[1, 2, 3];
2991 assert_eq!(x.shift_opt(), Some(1));
2992 assert_eq!(&x, &~[2, 3]);
2993 assert_eq!(x.shift_opt(), Some(2));
2994 assert_eq!(x.shift_opt(), Some(3));
2995 assert_eq!(x.shift_opt(), None);
2996 assert_eq!(x.len(), 0);
3001 let mut x = ~[1, 2, 3];
3003 assert_eq!(x, ~[0, 1, 2, 3]);
3008 let mut a = ~[1, 2, 4];
3010 assert_eq!(a, ~[1, 2, 3, 4]);
3012 let mut a = ~[1, 2, 3];
3014 assert_eq!(a, ~[0, 1, 2, 3]);
3016 let mut a = ~[1, 2, 3];
3018 assert_eq!(a, ~[1, 2, 3, 4]);
3022 assert_eq!(a, ~[1]);
3026 #[ignore(cfg(windows))]
3028 fn test_insert_oob() {
3029 let mut a = ~[1, 2, 3];
3035 let mut a = ~[1, 2, 3, 4];
3037 assert_eq!(a, ~[1, 2, 4]);
3039 let mut a = ~[1, 2, 3];
3041 assert_eq!(a, ~[2, 3]);
3049 #[ignore(cfg(windows))]
3051 fn test_remove_oob() {
3052 let mut a = ~[1, 2, 3];
3057 fn test_capacity() {
3058 let mut v = ~[0u64];
3060 assert_eq!(v.capacity(), 10u);
3061 let mut v = ~[0u32];
3063 assert_eq!(v.capacity(), 10u);
3068 let v = ~[1, 2, 3, 4, 5];
3069 let v = v.slice(1u, 3u);
3070 assert_eq!(v.len(), 2u);
3071 assert_eq!(v[0], 2);
3072 assert_eq!(v[1], 3);
3079 fn test_from_fn_fail() {
3080 do from_fn(100) |v| {
3081 if v == 50 { fail!() }
3089 fn test_build_fail() {
3102 fn test_grow_fn_fail() {
3104 do v.grow_fn(100) |i| {
3115 fn test_map_fail() {
3116 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3130 fn test_flat_map_fail() {
3131 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3133 do flat_map(v) |_elt| {
3145 fn test_rposition_fail() {
3146 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3148 do v.rposition |_elt| {
3160 fn test_permute_fail() {
3161 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3163 do each_permutation(v) |_elt| {
3175 fn test_as_imm_buf_fail() {
3176 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3177 do v.as_imm_buf |_buf, _i| {
3183 #[ignore(cfg(windows))]
3185 fn test_as_mut_buf_fail() {
3186 let mut v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3187 do v.as_mut_buf |_buf, _i| {
3194 #[ignore(cfg(windows))]
3195 fn test_copy_memory_oob() {
3197 let mut a = [1, 2, 3, 4];
3198 let b = [1, 2, 3, 4, 5];
3199 raw::copy_memory(a, b, 5);
3204 fn test_total_ord() {
3205 [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
3206 [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
3207 [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
3208 [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
3209 [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
3213 fn test_iterator() {
3215 let xs = [1, 2, 5, 10, 11];
3216 let mut it = xs.iter();
3217 assert_eq!(it.size_hint(), (5, Some(5)));
3218 assert_eq!(it.next().unwrap(), &1);
3219 assert_eq!(it.size_hint(), (4, Some(4)));
3220 assert_eq!(it.next().unwrap(), &2);
3221 assert_eq!(it.size_hint(), (3, Some(3)));
3222 assert_eq!(it.next().unwrap(), &5);
3223 assert_eq!(it.size_hint(), (2, Some(2)));
3224 assert_eq!(it.next().unwrap(), &10);
3225 assert_eq!(it.size_hint(), (1, Some(1)));
3226 assert_eq!(it.next().unwrap(), &11);
3227 assert_eq!(it.size_hint(), (0, Some(0)));
3228 assert!(it.next().is_none());
3232 fn test_random_access_iterator() {
3234 let xs = [1, 2, 5, 10, 11];
3235 let mut it = xs.iter();
3237 assert_eq!(it.indexable(), 5);
3238 assert_eq!(it.idx(0).unwrap(), &1);
3239 assert_eq!(it.idx(2).unwrap(), &5);
3240 assert_eq!(it.idx(4).unwrap(), &11);
3241 assert!(it.idx(5).is_none());
3243 assert_eq!(it.next().unwrap(), &1);
3244 assert_eq!(it.indexable(), 4);
3245 assert_eq!(it.idx(0).unwrap(), &2);
3246 assert_eq!(it.idx(3).unwrap(), &11);
3247 assert!(it.idx(4).is_none());
3249 assert_eq!(it.next().unwrap(), &2);
3250 assert_eq!(it.indexable(), 3);
3251 assert_eq!(it.idx(1).unwrap(), &10);
3252 assert!(it.idx(3).is_none());
3254 assert_eq!(it.next().unwrap(), &5);
3255 assert_eq!(it.indexable(), 2);
3256 assert_eq!(it.idx(1).unwrap(), &11);
3258 assert_eq!(it.next().unwrap(), &10);
3259 assert_eq!(it.indexable(), 1);
3260 assert_eq!(it.idx(0).unwrap(), &11);
3261 assert!(it.idx(1).is_none());
3263 assert_eq!(it.next().unwrap(), &11);
3264 assert_eq!(it.indexable(), 0);
3265 assert!(it.idx(0).is_none());
3267 assert!(it.next().is_none());
3271 fn test_iter_size_hints() {
3273 let mut xs = [1, 2, 5, 10, 11];
3274 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
3275 assert_eq!(xs.rev_iter().size_hint(), (5, Some(5)));
3276 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
3277 assert_eq!(xs.mut_rev_iter().size_hint(), (5, Some(5)));
3281 fn test_iter_clone() {
3283 let mut it = xs.iter();
3285 let mut jt = it.clone();
3286 assert_eq!(it.next(), jt.next());
3287 assert_eq!(it.next(), jt.next());
3288 assert_eq!(it.next(), jt.next());
3292 fn test_mut_iterator() {
3294 let mut xs = [1, 2, 3, 4, 5];
3295 for x in xs.mut_iter() {
3298 assert_eq!(xs, [2, 3, 4, 5, 6])
3302 fn test_rev_iterator() {
3305 let xs = [1, 2, 5, 10, 11];
3306 let ys = [11, 10, 5, 2, 1];
3308 for &x in xs.rev_iter() {
3309 assert_eq!(x, ys[i]);
3316 fn test_mut_rev_iterator() {
3318 let mut xs = [1u, 2, 3, 4, 5];
3319 for (i,x) in xs.mut_rev_iter().enumerate() {
3322 assert_eq!(xs, [5, 5, 5, 5, 5])
3326 fn test_consume_iterator() {
3328 let xs = ~[1u,2,3,4,5];
3329 assert_eq!(xs.consume_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
3333 fn test_consume_rev_iterator() {
3335 let xs = ~[1u,2,3,4,5];
3336 assert_eq!(xs.consume_rev_iter().fold(0, |a: uint, b: uint| 10*a + b), 54321);
3340 fn test_split_iterator() {
3341 let xs = &[1i,2,3,4,5];
3343 assert_eq!(xs.split_iter(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3344 ~[&[1], &[3], &[5]]);
3345 assert_eq!(xs.split_iter(|x| *x == 1).collect::<~[&[int]]>(),
3346 ~[&[], &[2,3,4,5]]);
3347 assert_eq!(xs.split_iter(|x| *x == 5).collect::<~[&[int]]>(),
3348 ~[&[1,2,3,4], &[]]);
3349 assert_eq!(xs.split_iter(|x| *x == 10).collect::<~[&[int]]>(),
3351 assert_eq!(xs.split_iter(|_| true).collect::<~[&[int]]>(),
3352 ~[&[], &[], &[], &[], &[], &[]]);
3354 let xs: &[int] = &[];
3355 assert_eq!(xs.split_iter(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3359 fn test_splitn_iterator() {
3360 let xs = &[1i,2,3,4,5];
3362 assert_eq!(xs.splitn_iter(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3364 assert_eq!(xs.splitn_iter(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3366 assert_eq!(xs.splitn_iter(3, |_| true).collect::<~[&[int]]>(),
3367 ~[&[], &[], &[], &[4,5]]);
3369 let xs: &[int] = &[];
3370 assert_eq!(xs.splitn_iter(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3374 fn test_rsplit_iterator() {
3375 let xs = &[1i,2,3,4,5];
3377 assert_eq!(xs.rsplit_iter(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3378 ~[&[5], &[3], &[1]]);
3379 assert_eq!(xs.rsplit_iter(|x| *x == 1).collect::<~[&[int]]>(),
3380 ~[&[2,3,4,5], &[]]);
3381 assert_eq!(xs.rsplit_iter(|x| *x == 5).collect::<~[&[int]]>(),
3382 ~[&[], &[1,2,3,4]]);
3383 assert_eq!(xs.rsplit_iter(|x| *x == 10).collect::<~[&[int]]>(),
3386 let xs: &[int] = &[];
3387 assert_eq!(xs.rsplit_iter(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3391 fn test_rsplitn_iterator() {
3392 let xs = &[1,2,3,4,5];
3394 assert_eq!(xs.rsplitn_iter(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3396 assert_eq!(xs.rsplitn_iter(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3398 assert_eq!(xs.rsplitn_iter(3, |_| true).collect::<~[&[int]]>(),
3399 ~[&[], &[], &[], &[1,2]]);
3401 let xs: &[int] = &[];
3402 assert_eq!(xs.rsplitn_iter(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3406 fn test_window_iterator() {
3407 let v = &[1i,2,3,4];
3409 assert_eq!(v.window_iter(2).collect::<~[&[int]]>(), ~[&[1,2], &[2,3], &[3,4]]);
3410 assert_eq!(v.window_iter(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[2,3,4]]);
3411 assert!(v.window_iter(6).next().is_none());
3416 #[ignore(cfg(windows))]
3417 fn test_window_iterator_0() {
3418 let v = &[1i,2,3,4];
3419 let _it = v.window_iter(0);
3423 fn test_chunk_iterator() {
3424 let v = &[1i,2,3,4,5];
3426 assert_eq!(v.chunk_iter(2).collect::<~[&[int]]>(), ~[&[1i,2], &[3,4], &[5]]);
3427 assert_eq!(v.chunk_iter(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[4,5]]);
3428 assert_eq!(v.chunk_iter(6).collect::<~[&[int]]>(), ~[&[1i,2,3,4,5]]);
3430 assert_eq!(v.chunk_iter(2).invert().collect::<~[&[int]]>(), ~[&[5i], &[3,4], &[1,2]]);
3431 let it = v.chunk_iter(2);
3432 assert_eq!(it.indexable(), 3);
3433 assert_eq!(it.idx(0).unwrap(), &[1,2]);
3434 assert_eq!(it.idx(1).unwrap(), &[3,4]);
3435 assert_eq!(it.idx(2).unwrap(), &[5]);
3436 assert_eq!(it.idx(3), None);
3441 #[ignore(cfg(windows))]
3442 fn test_chunk_iterator_0() {
3443 let v = &[1i,2,3,4];
3444 let _it = v.chunk_iter(0);
3448 fn test_move_from() {
3449 let mut a = [1,2,3,4,5];
3451 assert_eq!(a.move_from(b, 0, 3), 3);
3452 assert_eq!(a, [6,7,8,4,5]);
3453 let mut a = [7,2,8,1];
3454 let b = ~[3,1,4,1,5,9];
3455 assert_eq!(a.move_from(b, 0, 6), 4);
3456 assert_eq!(a, [3,1,4,1]);
3457 let mut a = [1,2,3,4];
3458 let b = ~[5,6,7,8,9,0];
3459 assert_eq!(a.move_from(b, 2, 3), 1);
3460 assert_eq!(a, [7,2,3,4]);
3461 let mut a = [1,2,3,4,5];
3462 let b = ~[5,6,7,8,9,0];
3463 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
3464 assert_eq!(a, [1,2,6,7,5]);
3468 fn test_copy_from() {
3469 let mut a = [1,2,3,4,5];
3471 assert_eq!(a.copy_from(b), 3);
3472 assert_eq!(a, [6,7,8,4,5]);
3473 let mut c = [7,2,8,1];
3474 let d = [3,1,4,1,5,9];
3475 assert_eq!(c.copy_from(d), 4);
3476 assert_eq!(c, [3,1,4,1]);
3480 fn test_reverse_part() {
3481 let mut values = [1,2,3,4,5];
3482 values.mut_slice(1, 4).reverse();
3483 assert_eq!(values, [1,4,3,2,5]);
3487 fn test_permutations0() {
3489 let mut v : ~[~[int]] = ~[];
3490 do each_permutation(values) |p| {
3491 v.push(p.to_owned());
3494 assert_eq!(v, ~[~[]]);
3498 fn test_permutations1() {
3500 let mut v : ~[~[int]] = ~[];
3501 do each_permutation(values) |p| {
3502 v.push(p.to_owned());
3505 assert_eq!(v, ~[~[1]]);
3509 fn test_permutations2() {
3511 let mut v : ~[~[int]] = ~[];
3512 do each_permutation(values) |p| {
3513 v.push(p.to_owned());
3516 assert_eq!(v, ~[~[1,2],~[2,1]]);
3520 fn test_permutations3() {
3521 let values = [1,2,3];
3522 let mut v : ~[~[int]] = ~[];
3523 do each_permutation(values) |p| {
3524 v.push(p.to_owned());
3527 assert_eq!(v, ~[~[1,2,3],~[1,3,2],~[2,1,3],~[2,3,1],~[3,1,2],~[3,2,1]]);
3531 fn test_vec_zero() {
3535 let v: $ty = Zero::zero();
3536 assert!(v.is_empty());
3537 assert!(v.is_zero());
3547 fn test_bytes_set_memory() {
3548 use vec::bytes::MutableByteVector;
3549 let mut values = [1u8,2,3,4,5];
3550 values.mut_slice(0,5).set_memory(0xAB);
3551 assert_eq!(values, [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
3552 values.mut_slice(2,4).set_memory(0xFF);
3553 assert_eq!(values, [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
3558 fn test_overflow_does_not_cause_segfault() {
3566 fn test_mut_split() {
3567 let mut values = [1u8,2,3,4,5];
3569 let (left, right) = values.mut_split(2);
3570 assert_eq!(left.slice(0, left.len()), [1, 2]);
3571 for p in left.mut_iter() {
3575 assert_eq!(right.slice(0, right.len()), [3, 4, 5]);
3576 for p in right.mut_iter() {
3581 assert_eq!(values, [2, 3, 5, 6, 7]);
3584 #[deriving(Clone, Eq)]
3588 fn test_iter_zero_sized() {
3589 let mut v = ~[Foo, Foo, Foo];
3590 assert_eq!(v.len(), 3);
3599 for f in v.slice(1, 3).iter() {
3605 for f in v.mut_iter() {
3611 for f in v.consume_iter() {
3615 assert_eq!(cnt, 11);
3617 let xs = ~[Foo, Foo, Foo];
3618 assert_eq!(fmt!("%?", xs.slice(0, 2).to_owned()), ~"~[{}, {}]");
3620 let xs: [Foo, ..3] = [Foo, Foo, Foo];
3621 assert_eq!(fmt!("%?", xs.slice(0, 2).to_owned()), ~"~[{}, {}]");
3623 for f in xs.iter() {
3633 use extra::test::BenchHarness;
3638 fn iterator(bh: &mut BenchHarness) {
3639 // peculiar numbers to stop LLVM from optimising the summation
3641 let v = vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
3648 // sum == 11806, to stop dead code elimination.
3649 if sum == 0 {fail!()}
3654 fn mut_iterator(bh: &mut BenchHarness) {
3655 let mut v = vec::from_elem(100, 0);
3659 for x in v.mut_iter() {