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 #[warn(non_camel_case_types)];
18 use container::{Container, Mutable};
19 use cmp::{Eq, TotalOrd, Ordering, Less, Equal, Greater};
24 use option::{None, Option, Some};
25 use ptr::to_unsafe_ptr;
28 use rt::global_heap::malloc_raw;
29 use rt::global_heap::realloc_raw;
33 use unstable::intrinsics;
34 use unstable::intrinsics::{get_tydesc, contains_managed};
38 /// Returns true if two vectors have the same length
39 pub fn same_length<T, U>(xs: &[T], ys: &[U]) -> bool {
44 * Creates and initializes an owned vector.
46 * Creates an owned vector of size `n_elts` and initializes the elements
47 * to the value returned by the function `op`.
49 pub fn from_fn<T>(n_elts: uint, op: &fn(uint) -> T) -> ~[T] {
51 let mut v = with_capacity(n_elts);
52 do v.as_mut_buf |p, _len| {
55 intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i)), op(i));
59 raw::set_len(&mut v, n_elts);
65 * Creates and initializes an owned vector.
67 * Creates an owned vector of size `n_elts` and initializes the elements
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.
76 let mut v = with_capacity(n_elts);
77 do v.as_mut_buf |p, _len| {
80 intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i)), t.clone());
84 raw::set_len(&mut v, n_elts);
89 /// Creates a new vector with a capacity of `capacity`
90 pub fn with_capacity<T>(capacity: uint) -> ~[T] {
92 if contains_managed::<T>() {
94 vec.reserve(capacity);
97 let alloc = capacity * sys::nonzero_size_of::<T>();
98 let ptr = malloc_raw(alloc + sys::size_of::<UnboxedVecRepr>()) as *mut UnboxedVecRepr;
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.
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.
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));
126 * Builds a vector by calling a provided function with an argument
127 * function that pushes an element to the back of a vector.
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.
136 pub fn build<A>(builder: &fn(push: &fn(v: A))) -> ~[A] {
137 build_sized(4, builder)
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.
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.
153 pub fn build_sized_opt<A>(size: Option<uint>,
154 builder: &fn(push: &fn(v: A)))
156 build_sized(size.get_or_default(4), builder)
159 /// An iterator over the slices of a vector separated by elements that
160 /// match a predicate function.
161 pub struct VecSplitIterator<'self, T> {
164 priv pred: &'self fn(t: &T) -> bool,
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; }
173 self.finished = true;
177 match self.v.iter().position(|x| (self.pred)(x)) {
179 self.finished = true;
183 let ret = Some(self.v.slice(0, idx));
184 self.v = self.v.slice(idx + 1, self.v.len());
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> {
197 priv pred: &'self fn(t: &T) -> bool,
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; }
206 self.finished = true;
210 match self.v.rposition(|x| (self.pred)(x)) {
212 self.finished = true;
216 let ret = Some(self.v.slice(idx + 1, self.v.len()));
217 self.v = self.v.slice(0, idx);
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.
230 pub fn append<T:Clone>(lhs: ~[T], rhs: &[T]) -> ~[T] {
236 /// Appends one element to the vector provided. The vector itself is then
237 /// returned for use again.
239 pub fn append_one<T>(lhs: ~[T], x: T) -> ~[T] {
245 // Functional utilities
248 * Apply a function to each element of a vector and return a concatenation
249 * of each result vector
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)); }
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() }
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) }
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() }
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) }
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];
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())
283 /// Concatenate a vector of vectors, placing a given separator between each.
284 pub fn connect_vec(&self, sep: &T) -> ~[T] {
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());
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())
301 /// Concatenate a vector of slices, placing a given separator between each.
302 pub fn connect_vec(&self, sep: &T) -> ~[T] {
304 let mut first = true;
305 for self.iter().advance |&inner| {
306 if first { first = false; } else { r.push((*sep).clone()); }
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)
318 * Convert a vector of pairs into a pair of vectors, by reference. As unzip().
320 pub fn unzip_slice<T:Clone,U:Clone>(v: &[(T, U)]) -> (~[T], ~[U]) {
323 for v.iter().advance |p| {
324 let (t, u) = (*p).clone();
332 * Convert a vector of pairs into a pair of vectors.
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.
339 pub fn unzip<T,U>(v: ~[(T, U)]) -> (~[T], ~[U]) {
342 for v.consume_iter().advance |p| {
351 * Convert two vectors to a vector of pairs, by reference. As zip().
353 pub fn zip_slice<T:Clone,U:Clone>(v: &[T], u: &[U]) -> ~[(T, U)] {
354 let mut zipped = ~[];
357 assert_eq!(sz, u.len());
359 zipped.push((v[i].clone(), u[i].clone()));
366 * Convert two vectors to a vector of pairs.
368 * Returns a vector of tuples, where the i-th tuple contains the
369 * i-th elements from each of the input vectors.
371 pub fn zip<T, U>(mut v: ~[T], mut u: ~[U]) -> ~[(T, U)] {
373 assert_eq!(i, u.len());
374 let mut w = with_capacity(i);
376 w.push((v.pop(),u.pop()));
384 * Iterate over all permutations of vector `v`.
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).
390 * The total number of permutations produced is `v.len()!`. If `v` contains
391 * repeated elements, then some permutations are repeated.
393 * See [Algorithms to generate
394 * permutations](http://en.wikipedia.org/wiki/Permutation).
398 * * `values` - A vector of values from which the permutations are
401 * * `fun` - The function to iterate over the combinations
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());
410 let mut indices = vec::from_fn(length, |i| i);
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] {
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] {
426 // swap indices[k] and indices[l]; sort indices[k+1..]
427 // (they're just reversed)
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();
437 /// An iterator over the (overlapping) slices of length `size` within
439 pub struct VecWindowIter<'self, T> {
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() {
449 let ret = Some(self.v.slice(0, self.size));
450 self.v = self.v.slice(1, self.v.len());
456 /// An iterator over a vector in (non-overlapping) chunks (`size`
457 /// elements at a time).
458 pub struct VecChunkIter<'self, T> {
463 impl<'self, T> Iterator<&'self [T]> for VecChunkIter<'self, T> {
464 fn next(&mut self) -> Option<&'self [T]> {
467 } else if self.size >= self.v.len() {
472 let ret = Some(self.v.slice(0, self.size));
473 self.v = self.v.slice(self.size, self.v.len());
486 use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Equal, Equiv};
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)
495 fn ne(&self, other: & &'self [T]) -> bool { !self.eq(other) }
498 impl<T:Eq> Eq for ~[T] {
500 fn eq(&self, other: &~[T]) -> bool { self.as_slice() == *other }
502 fn ne(&self, other: &~[T]) -> bool { !self.eq(other) }
505 impl<T:Eq> Eq for @[T] {
507 fn eq(&self, other: &@[T]) -> bool { self.as_slice() == *other }
509 fn ne(&self, other: &@[T]) -> bool { !self.eq(other) }
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))
519 impl<T:TotalEq> TotalEq for ~[T] {
521 fn equals(&self, other: &~[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
524 impl<T:TotalEq> TotalEq for @[T] {
526 fn equals(&self, other: &@[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
529 impl<'self,T:Eq, V: Vector<T>> Equiv<V> for &'self [T] {
531 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
534 impl<'self,T:Eq, V: Vector<T>> Equiv<V> for ~[T] {
536 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
539 impl<'self,T:Eq, V: Vector<T>> Equiv<V> for @[T] {
541 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
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)| {
549 non_eq => { return non_eq; }
552 self.len().cmp(&other.len())
556 impl<T: TotalOrd> TotalOrd for ~[T] {
558 fn cmp(&self, other: &~[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
561 impl<T: TotalOrd> TotalOrd for @[T] {
563 fn cmp(&self, other: &@[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
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; }
572 self.len() < other.len()
575 fn le(&self, other: & &'self [T]) -> bool { !(*other < *self) }
577 fn ge(&self, other: & &'self [T]) -> bool { !(*self < *other) }
579 fn gt(&self, other: & &'self [T]) -> bool { *other < *self }
582 impl<T:Ord> Ord for ~[T] {
584 fn lt(&self, other: &~[T]) -> bool { self.as_slice() < other.as_slice() }
586 fn le(&self, other: &~[T]) -> bool { self.as_slice() <= other.as_slice() }
588 fn ge(&self, other: &~[T]) -> bool { self.as_slice() >= other.as_slice() }
590 fn gt(&self, other: &~[T]) -> bool { self.as_slice() > other.as_slice() }
593 impl<T:Ord> Ord for @[T] {
595 fn lt(&self, other: &@[T]) -> bool { self.as_slice() < other.as_slice() }
597 fn le(&self, other: &@[T]) -> bool { self.as_slice() <= other.as_slice() }
599 fn ge(&self, other: &@[T]) -> bool { self.as_slice() >= other.as_slice() }
601 fn gt(&self, other: &@[T]) -> bool { self.as_slice() > other.as_slice() }
604 impl<'self,T:Clone, V: Vector<T>> Add<V, ~[T]> for &'self [T] {
606 fn add(&self, rhs: &V) -> ~[T] {
607 let mut res = self.to_owned();
608 res.push_all(rhs.as_slice());
612 impl<T:Clone, V: Vector<T>> Add<V, ~[T]> for ~[T] {
614 fn add(&self, rhs: &V) -> ~[T] {
615 let mut res = self.to_owned();
616 res.push_all(rhs.as_slice());
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];
630 impl<'self,T> Vector<T> for &'self [T] {
632 fn as_slice<'a>(&'a self) -> &'a [T] { *self }
634 impl<T> Vector<T> for ~[T] {
636 fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
638 impl<T> Vector<T> for @[T] {
640 fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
643 impl<'self, T> Container for &'self [T] {
644 /// Returns true if a vector contains no elements
646 fn is_empty(&self) -> bool {
647 self.as_imm_buf(|_p, len| len == 0u)
650 /// Returns the length of a vector
652 fn len(&self) -> uint {
653 self.as_imm_buf(|_p, len| len)
657 impl<T> Container for ~[T] {
658 /// Returns true if a vector contains no elements
660 fn is_empty(&self) -> bool {
661 self.as_imm_buf(|_p, len| len == 0u)
664 /// Returns the length of a vector
666 fn len(&self) -> uint {
667 self.as_imm_buf(|_p, len| len)
671 #[allow(missing_doc)]
672 pub trait CopyableVector<T> {
673 fn to_owned(&self) -> ~[T];
676 /// Extension methods for vectors
677 impl<'self,T:Clone> CopyableVector<T> for &'self [T] {
678 /// Returns a copy of `v`.
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());
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>;
701 fn window_iter(self, size: uint) -> VecWindowIter<'self, T>;
702 fn chunk_iter(self, size: uint) -> VecChunkIter<'self, T>;
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;
716 fn bsearch(&self, f: &fn(&T) -> Ordering) -> Option<uint>;
718 fn map<U>(&self, &fn(t: &T) -> U) -> ~[U];
720 fn as_imm_buf<U>(&self, f: &fn(*T, uint) -> U) -> U;
723 /// Extension methods for vectors
724 impl<'self,T> ImmutableVector<'self, T> for &'self [T] {
727 * Returns a slice of self between `start` and `end`.
729 * Fails when `start` or `end` point outside the bounds of self,
730 * or when `start` > `end`.
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| {
738 transmute((ptr::offset(p, start),
739 (end - start) * sys::nonzero_size_of::<T>()))
745 * Returns a slice of self from `start` to the end of the vec.
747 * Fails when `start` points outside the bounds of self.
750 fn slice_from(&self, start: uint) -> &'self [T] {
751 self.slice(start, self.len())
755 * Returns a slice of self from the start of the vec to `end`.
757 * Fails when `end` points outside the bounds of self.
760 fn slice_to(&self, end: uint) -> &'self [T] {
765 fn iter(self) -> VecIterator<'self, T> {
767 let p = vec::raw::to_ptr(self);
769 end: cast::transmute(p as uint + self.len() *
770 sys::nonzero_size_of::<T>()),
771 lifetime: cast::transmute(p)}
776 fn rev_iter(self) -> VecRevIterator<'self, T> {
780 /// Returns an iterator over the subslices of the vector which are
781 /// separated by elements that match `pred`.
783 fn split_iter(self, pred: &'self fn(&T) -> bool) -> VecSplitIterator<'self, T> {
784 self.splitn_iter(uint::max_value, pred)
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.
790 fn splitn_iter(self, n: uint, pred: &'self fn(&T) -> bool) -> VecSplitIterator<'self, T> {
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.
802 fn rsplit_iter(self, pred: &'self fn(&T) -> bool) -> VecRSplitIterator<'self, T> {
803 self.rsplitn_iter(uint::max_value, pred)
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
810 fn rsplitn_iter(self, n: uint, pred: &'self fn(&T) -> bool) -> VecRSplitIterator<'self, T> {
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.
826 * Fails if `size` is 0.
830 * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
834 * let v = &[1,2,3,4];
835 * for v.window_iter().advance |win| {
836 * io::println(fmt!("%?", win));
841 fn window_iter(self, size: uint) -> VecWindowIter<'self, T> {
843 VecWindowIter { v: self, size: size }
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
855 * Fails if `size` is 0.
859 * Print the vector two elements at a time (i.e. `[1,2]`,
863 * let v = &[1,2,3,4,5];
864 * for v.chunk_iter().advance |win| {
865 * io::println(fmt!("%?", win));
870 fn chunk_iter(self, size: uint) -> VecChunkIter<'self, T> {
872 VecChunkIter { v: self, size: size }
875 /// Returns the first element of a vector, failing if the vector is empty.
877 fn head(&self) -> &'self T {
878 if self.len() == 0 { fail!("head: empty vector") }
882 /// Returns the first element of a vector, or `None` if it is empty
884 fn head_opt(&self) -> Option<&'self T> {
885 if self.len() == 0 { None } else { Some(&self[0]) }
888 /// Returns all but the first element of a vector
890 fn tail(&self) -> &'self [T] { self.slice(1, self.len()) }
892 /// Returns all but the first `n' elements of a vector
894 fn tailn(&self, n: uint) -> &'self [T] { self.slice(n, self.len()) }
896 /// Returns all but the last element of a vector
898 fn init(&self) -> &'self [T] {
899 self.slice(0, self.len() - 1)
902 /// Returns all but the last `n' elemnts of a vector
904 fn initn(&self, n: uint) -> &'self [T] {
905 self.slice(0, self.len() - n)
908 /// Returns the last element of a vector, failing if the vector is empty.
910 fn last(&self) -> &'self T {
911 if self.len() == 0 { fail!("last: empty vector") }
912 &self[self.len() - 1]
915 /// Returns the last element of a vector, or `None` if it is empty.
917 fn last_opt(&self) -> Option<&'self T> {
918 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
922 * Find the last index matching some predicate
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.
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); }
937 * Apply a function to each element of a vector and return a concatenation
938 * of each result vector
941 fn flat_map<U>(&self, f: &fn(t: &T) -> ~[U]) -> ~[U] {
945 /// Returns a pointer to the element at the given index, without doing
948 unsafe fn unsafe_ref(&self, index: uint) -> *T {
949 let (ptr, _): (*T, uint) = transmute(*self);
954 * Binary search a sorted vector with a comparator function.
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.
960 * Returns the index where the comparator returned `Equal`, or `None` if
963 fn bsearch(&self, f: &fn(&T) -> Ordering) -> Option<uint> {
964 let mut base : uint = 0;
965 let mut lim : uint = self.len();
968 let ix = base + (lim >> 1);
970 Equal => return Some(ix),
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()
990 * Work with the buffer of a vector.
992 * Allows for unsafe manipulation of vector contents, which is useful for
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!
1005 let v : *(*T,uint) = transmute(self);
1007 f(buf, len / sys::nonzero_size_of::<T>())
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;
1019 impl<'self,T:Eq> ImmutableEqVector<T> for &'self [T] {
1020 /// Find the first index containing a matching value
1022 fn position_elem(&self, x: &T) -> Option<uint> {
1023 self.iter().position(|y| *x == *y)
1026 /// Find the last index containing a matching value
1028 fn rposition_elem(&self, t: &T) -> Option<uint> {
1029 self.rposition(|x| *x == *t)
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; } }
1039 #[allow(missing_doc)]
1040 pub trait ImmutableTotalOrdVector<T: TotalOrd> {
1041 fn bsearch_elem(&self, x: &T) -> Option<uint>;
1044 impl<'self, T: TotalOrd> ImmutableTotalOrdVector<T> for &'self [T] {
1046 * Binary search a sorted vector for a given element.
1048 * Returns the index of the element or None if not found.
1050 fn bsearch_elem(&self, x: &T) -> Option<uint> {
1051 self.bsearch(|p| p.cmp(x))
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;
1061 /// Extension methods for vectors
1062 impl<'self,T:Clone> ImmutableCopyableVector<T> for &'self [T] {
1064 * Partitions the vector into those that satisfies the predicate, and
1065 * those that do not.
1068 fn partitioned(&self, f: &fn(&T) -> bool) -> (~[T], ~[T]) {
1069 let mut lefts = ~[];
1070 let mut rights = ~[];
1072 for self.iter().advance |elt| {
1074 lefts.push((*elt).clone());
1076 rights.push((*elt).clone());
1083 /// Returns the element at the given index, without doing bounds checking.
1085 unsafe fn unsafe_get(&self, index: uint) -> T {
1086 (*self.unsafe_ref(index)).clone()
1090 #[allow(missing_doc)]
1091 pub trait OwnedVector<T> {
1092 fn consume_iter(self) -> VecConsumeIterator<T>;
1093 fn consume_rev_iter(self) -> VecConsumeRevIterator<T>;
1095 fn reserve(&mut self, n: uint);
1096 fn reserve_at_least(&mut self, n: uint);
1097 fn capacity(&self) -> uint;
1099 fn push(&mut self, t: T);
1100 unsafe fn push_fast(&mut self, t: T);
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);
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.
1122 /// Note that this performs O(n) swaps, and so `consume_rev_iter`
1123 /// (which just calls `pop` repeatedly) is more efficient.
1128 /// let v = ~[~"a", ~"b"];
1129 /// for v.consume_iter().advance |s| {
1130 /// // s has type ~str, not &~str
1134 fn consume_iter(self) -> VecConsumeIterator<T> {
1135 VecConsumeIterator { v: self, idx: 0 }
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 }
1145 * Reserves capacity for exactly `n` elements in the given vector.
1147 * If the capacity for `self` is already equal to or greater than the requested
1148 * capacity, then no action is taken.
1152 * * n - The number of elements to reserve space for
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 {
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);
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);
1169 *ptr = realloc_raw(*ptr as *mut c_void, size)
1170 as *mut UnboxedVecRepr;
1171 (**ptr).alloc = alloc;
1178 * Reserves capacity for at least `n` elements in the given vector.
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
1184 * If the capacity for `self` is already equal to or greater than the requested
1185 * capacity, then no action is taken.
1189 * * n - The number of elements to reserve space for
1191 fn reserve_at_least(&mut self, n: uint) {
1192 self.reserve(uint::next_power_of_two(n));
1195 /// Returns the number of elements the vector can hold without reallocating.
1197 fn capacity(&self) -> uint {
1199 if contains_managed::<T>() {
1200 let repr: **raw::VecRepr = transmute(self);
1201 (**repr).unboxed.alloc / sys::nonzero_size_of::<T>()
1203 let repr: **UnboxedVecRepr = transmute(self);
1204 (**repr).alloc / sys::nonzero_size_of::<T>()
1209 /// Append an element to a vector
1211 fn push(&mut self, t: T) {
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);
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);
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);
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);
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).
1263 /// let mut a = ~[~1];
1264 /// a.push_all_move(~[~2, ~3, ~4]);
1265 /// assert!(a == ~[~1, ~2, ~3, ~4]);
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);
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> {
1287 let valptr = ptr::to_mut_unsafe_ptr(&mut self[ln - 1u]);
1289 raw::set_len(self, ln - 1u);
1290 Some(ptr::read_ptr(valptr))
1297 /// Remove the last element from a vector and return it, failing if it is empty
1299 fn pop(&mut self) -> T {
1300 self.pop_opt().expect("pop: empty vector")
1303 /// Removes the first element from a vector and return it
1305 fn shift(&mut self) -> T {
1306 self.shift_opt().expect("shift: empty vector")
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> {
1312 let ln = match self.len() {
1314 1 => return self.pop_opt(),
1316 let last = self.pop();
1317 let first = self.pop_opt();
1324 let next_ln = self.len() - 1;
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);
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
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);
1343 // Memcopy everything to the left one element
1345 let init_slice = self.slice(0, next_ln);
1346 let tail_slice = self.slice(1, ln);
1347 raw::copy_memory(transmute(init_slice),
1352 // Set the new length. Now the vector is back to normal
1353 raw::set_len(self, next_ln);
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);
1359 Some(ptr::replace_ptr(vp, work_elt))
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);
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();
1378 self.swap(j, j - 1);
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();
1391 self.swap(j, j + 1);
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).
1401 * Fails if index >= length.
1403 fn swap_remove(&mut self, index: uint) -> T {
1404 let ln = self.len();
1406 fail!("vec::swap_remove - index %u >= length %u", index, ln);
1409 self.swap(index, ln - 1);
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);
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));
1425 unsafe { raw::set_len(self, newlen); }
1430 * Like `filter()`, but in place. Preserves order of `v`. Linear time.
1432 fn retain(&mut self, f: &fn(t: &T) -> bool) {
1433 let len = self.len();
1434 let mut deleted: uint = 0;
1436 for uint::range(0, len) |i| {
1439 } else if deleted > 0 {
1440 self.swap(i - deleted, i);
1445 self.truncate(len - deleted);
1450 * Partitions the vector into those that satisfies the predicate, and
1451 * those that do not.
1454 fn partition(self, f: &fn(&T) -> bool) -> (~[T], ~[T]) {
1455 let mut lefts = ~[];
1456 let mut rights = ~[];
1458 for self.consume_iter().advance |elt| {
1470 * Expands a vector in place, initializing the new elements to the result of
1473 * Function `init_op` is called `n` times with the values [0..`n`)
1477 * * n - The number of elements to add
1478 * * init_op - A function to call to retreive each appended element's
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;
1492 impl<T> Mutable for ~[T] {
1493 /// Clear the vector, removing all values.
1494 fn clear(&mut self) { self.truncate(0) }
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);
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.
1511 /// let mut a = ~[1];
1512 /// a.push_all([2, 3, 4]);
1513 /// assert!(a == ~[1, 2, 3, 4]);
1516 fn push_all(&mut self, rhs: &[T]) {
1517 let new_len = self.len() + rhs.len();
1518 self.reserve(new_len);
1520 for uint::range(0u, rhs.len()) |i| {
1521 self.push(unsafe { raw::get(rhs, i) })
1526 * Expands a vector in place, initializing the new elements to a given value
1530 * * n - The number of elements to add
1531 * * initval - The value for the new elements
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;
1539 self.push((*initval).clone());
1545 * Sets the value of a vector element at a given index, growing the vector as
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.
1552 fn grow_set(&mut self, index: uint, initval: &T, val: T) {
1554 if index >= l { self.grow(index - l + 1u, initval); }
1559 #[allow(missing_doc)]
1560 pub trait OwnedEqVector<T:Eq> {
1561 fn dedup(&mut self);
1564 impl<T:Eq> OwnedEqVector<T> for ~[T] {
1566 * Remove consecutive repeated elements from a vector; if the vector is
1567 * sorted, this removes all duplicates.
1569 pub fn dedup(&mut self) {
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.
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).
1584 // Example: We start in this state, where `r` represents "next
1585 // read" and `w` represents "next_write`.
1588 // +---+---+---+---+---+---+
1589 // | 0 | 1 | 1 | 2 | 3 | 3 |
1590 // +---+---+---+---+---+---+
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:
1598 // +---+---+---+---+---+---+
1599 // | 0 | 1 | 1 | 2 | 3 | 3 |
1600 // +---+---+---+---+---+---+
1603 // Comparing self[r] against self[w-1], this value is a duplicate,
1604 // so we increment `r` but leave everything else unchanged:
1607 // +---+---+---+---+---+---+
1608 // | 0 | 1 | 1 | 2 | 3 | 3 |
1609 // +---+---+---+---+---+---+
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:
1616 // +---+---+---+---+---+---+
1617 // | 0 | 1 | 2 | 1 | 3 | 3 |
1618 // +---+---+---+---+---+---+
1621 // Not a duplicate, repeat:
1624 // +---+---+---+---+---+---+
1625 // | 0 | 1 | 2 | 3 | 1 | 3 |
1626 // +---+---+---+---+---+---+
1629 // Duplicate, advance r. End of vec. Truncate to w.
1631 let ln = self.len();
1632 if ln < 1 { return; }
1634 // Avoid bounds checks by using unsafe pointers.
1635 let p = vec::raw::to_mut_ptr(*self);
1640 let p_r = ptr::mut_offset(p, r);
1641 let p_wm1 = ptr::mut_offset(p, w - 1);
1644 let p_w = ptr::mut_offset(p_wm1, 1);
1645 util::swap(&mut *p_r, &mut *p_w);
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>;
1663 fn swap(self, a: uint, b: uint);
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).
1671 fn mut_split(self, mid: uint) -> (&'self mut [T],
1677 * Consumes `src` and moves as many elements as it can into `self`
1678 * from the range [start,end).
1680 * Returns the number of elements copied (the shorter of self.len()
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
1689 fn move_from(self, src: ~[T], start: uint, end: uint) -> uint;
1691 unsafe fn unsafe_mut_ref(&self, index: uint) -> *mut T;
1692 unsafe fn unsafe_set(&self, index: uint, val: T);
1694 fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U;
1697 impl<'self,T> MutableVector<'self, T> for &'self mut [T] {
1698 /// Return a slice that points into another slice.
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| {
1705 transmute((ptr::mut_offset(p, start),
1706 (end - start) * sys::nonzero_size_of::<T>()))
1712 fn mut_split(self, mid: uint) -> (&'self mut [T], &'self mut [T]) {
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))
1721 fn mut_iter(self) -> VecMutIterator<'self, T> {
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)}
1732 fn mut_rev_iter(self) -> VecMutRevIterator<'self, T> {
1733 self.mut_iter().invert()
1737 * Swaps two elements in a vector
1741 * * a - The index of the first element
1742 * * b - The index of the second element
1744 fn swap(self, a: uint, b: uint) {
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);
1754 /// Reverse the order of elements in a vector, in place
1756 let mut i: uint = 0;
1757 let ln = self.len();
1759 self.swap(i, ln - i - 1);
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)| {
1769 cmp::min(self.len(), end-start)
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;
1780 unsafe fn unsafe_set(&self, index: uint, val: T) {
1781 *self.unsafe_mut_ref(index) = val;
1784 /// Similar to `as_imm_buf` but passing a `*mut T`
1786 fn as_mut_buf<U>(&self, f: &fn(*mut T, uint) -> U) -> U {
1788 let v : *(*mut T,uint) = transmute(self);
1790 f(buf, len / sys::nonzero_size_of::<T>())
1796 /// Trait for &[T] where T is Cloneable
1797 pub trait MutableCloneableVector<T> {
1798 /// Copies as many elements from `src` as it can into `self`
1799 /// (the shorter of self.len() and src.len()). Returns the number of elements copied.
1800 fn copy_from(self, &[T]) -> uint;
1803 impl<'self, T:Clone> MutableCloneableVector<T> for &'self mut [T] {
1805 fn copy_from(self, src: &[T]) -> uint {
1806 for self.mut_iter().zip(src.iter()).advance |(a, b)| {
1809 cmp::min(self.len(), src.len())
1814 * Constructs a vector from an unsafe pointer to a buffer
1818 * * ptr - An unsafe pointer to a buffer of `T`
1819 * * elts - The number of elements in the buffer
1821 // Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
1822 pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
1823 raw::from_buf_raw(ptr, elts)
1826 /// The internal 'unboxed' representation of a vector
1827 #[allow(missing_doc)]
1828 pub struct UnboxedVecRepr {
1834 /// Unsafe operations
1836 use cast::transmute;
1842 use unstable::intrinsics;
1843 use vec::{UnboxedVecRepr, with_capacity, ImmutableVector, MutableVector};
1844 use unstable::intrinsics::contains_managed;
1846 /// The internal representation of a (boxed) vector
1847 #[allow(missing_doc)]
1848 pub struct VecRepr {
1849 box_header: managed::raw::BoxHeaderRepr,
1850 unboxed: UnboxedVecRepr
1853 /// The internal representation of a slice
1854 pub struct SliceRepr {
1855 /// Pointer to the base of this slice
1857 /// The length of the slice
1862 * Sets the length of a vector
1864 * This will explicitly set the size of the vector, without actually
1865 * modifing its buffers, so it is up to the caller to ensure that
1866 * the vector is actually the specified size.
1869 pub unsafe fn set_len<T>(v: &mut ~[T], new_len: uint) {
1870 if contains_managed::<T>() {
1871 let repr: **mut VecRepr = transmute(v);
1872 (**repr).unboxed.fill = new_len * sys::nonzero_size_of::<T>();
1874 let repr: **mut UnboxedVecRepr = transmute(v);
1875 (**repr).fill = new_len * sys::nonzero_size_of::<T>();
1880 * Returns an unsafe pointer to the vector's buffer
1882 * The caller must ensure that the vector outlives the pointer this
1883 * function returns, or else it will end up pointing to garbage.
1885 * Modifying the vector may cause its buffer to be reallocated, which
1886 * would also make any pointers to it invalid.
1889 pub fn to_ptr<T>(v: &[T]) -> *T {
1891 let repr: **SliceRepr = transmute(&v);
1892 transmute(&((**repr).data))
1896 /** see `to_ptr()` */
1898 pub fn to_mut_ptr<T>(v: &mut [T]) -> *mut T {
1900 let repr: **SliceRepr = transmute(&v);
1901 transmute(&((**repr).data))
1906 * Form a slice from a pointer and length (as a number of units,
1910 pub unsafe fn buf_as_slice<T,U>(p: *T,
1912 f: &fn(v: &[T]) -> U) -> U {
1913 let pair = (p, len * sys::nonzero_size_of::<T>());
1914 let v : *(&'blk [T]) = transmute(&pair);
1919 * Form a slice from a pointer and length (as a number of units,
1923 pub unsafe fn mut_buf_as_slice<T,U>(p: *mut T,
1925 f: &fn(v: &mut [T]) -> U) -> U {
1926 let pair = (p, len * sys::nonzero_size_of::<T>());
1927 let v : *(&'blk mut [T]) = transmute(&pair);
1932 * Unchecked vector indexing.
1935 pub unsafe fn get<T:Clone>(v: &[T], i: uint) -> T {
1936 v.as_imm_buf(|p, _len| (*ptr::offset(p, i)).clone())
1940 * Unchecked vector index assignment. Does not drop the
1941 * old value and hence is only suitable when the vector
1942 * is newly allocated.
1945 pub unsafe fn init_elem<T>(v: &mut [T], i: uint, val: T) {
1946 let mut box = Some(val);
1947 do v.as_mut_buf |p, _len| {
1948 intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i)),
1954 * Constructs a vector from an unsafe pointer to a buffer
1958 * * ptr - An unsafe pointer to a buffer of `T`
1959 * * elts - The number of elements in the buffer
1961 // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
1963 pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
1964 let mut dst = with_capacity(elts);
1965 set_len(&mut dst, elts);
1966 dst.as_mut_buf(|p_dst, _len_dst| ptr::copy_memory(p_dst, ptr, elts));
1971 * Copies data from one vector to another.
1973 * Copies `count` bytes from `src` to `dst`. The source and destination
1977 pub unsafe fn copy_memory<T>(dst: &mut [T], src: &[T],
1979 assert!(dst.len() >= count);
1980 assert!(src.len() >= count);
1982 do dst.as_mut_buf |p_dst, _len_dst| {
1983 do src.as_imm_buf |p_src, _len_src| {
1984 ptr::copy_memory(p_dst, p_src, count)
1990 /// Operations on `[u8]`
1998 /// A trait for operations on mutable operations on `[u8]`
1999 pub trait MutableByteVector {
2000 /// Sets all bytes of the receiver to the given value.
2001 pub fn set_memory(self, value: u8);
2004 impl<'self> MutableByteVector for &'self mut [u8] {
2006 fn set_memory(self, value: u8) {
2007 do self.as_mut_buf |p, len| {
2008 unsafe { ptr::set_memory(p, value, len) };
2013 /// Bytewise string comparison
2014 pub fn memcmp(a: &~[u8], b: &~[u8]) -> int {
2015 let a_len = a.len();
2016 let b_len = b.len();
2017 let n = num::min(a_len, b_len) as libc::size_t;
2019 libc::memcmp(raw::to_ptr(*a) as *libc::c_void,
2020 raw::to_ptr(*b) as *libc::c_void, n) as int
2023 if r != 0 { r } else {
2026 } else if a_len < b_len {
2034 /// Bytewise less than or equal
2035 pub fn lt(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) < 0 }
2037 /// Bytewise less than or equal
2038 pub fn le(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) <= 0 }
2040 /// Bytewise equality
2041 pub fn eq(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) == 0 }
2043 /// Bytewise inequality
2044 pub fn ne(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) != 0 }
2046 /// Bytewise greater than or equal
2047 pub fn ge(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) >= 0 }
2049 /// Bytewise greater than
2050 pub fn gt(a: &~[u8], b: &~[u8]) -> bool { memcmp(a, b) > 0 }
2053 * Copies data from one vector to another.
2055 * Copies `count` bytes from `src` to `dst`. The source and destination
2059 pub fn copy_memory(dst: &mut [u8], src: &[u8], count: uint) {
2060 // Bound checks are done at vec::raw::copy_memory.
2061 unsafe { vec::raw::copy_memory(dst, src, count) }
2065 impl<A:Clone> Clone for ~[A] {
2067 fn clone(&self) -> ~[A] {
2068 self.iter().transform(|item| item.clone()).collect()
2072 // This works because every lifetime is a sub-lifetime of 'static
2073 impl<'self, A> Zero for &'self [A] {
2074 fn zero() -> &'self [A] { &'self [] }
2075 fn is_zero(&self) -> bool { self.is_empty() }
2078 impl<A> Zero for ~[A] {
2079 fn zero() -> ~[A] { ~[] }
2080 fn is_zero(&self) -> bool { self.len() == 0 }
2083 impl<A> Zero for @[A] {
2084 fn zero() -> @[A] { @[] }
2085 fn is_zero(&self) -> bool { self.len() == 0 }
2088 macro_rules! iterator {
2089 /* FIXME: #4375 Cannot attach documentation/attributes to a macro generated struct.
2090 (struct $name:ident -> $ptr:ty, $elem:ty) => {
2091 pub struct $name<'self, T> {
2094 priv lifetime: $elem // FIXME: #5922
2097 (impl $name:ident -> $elem:ty) => {
2098 impl<'self, T> Iterator<$elem> for $name<'self, T> {
2100 fn next(&mut self) -> Option<$elem> {
2101 // could be implemented with slices, but this avoids bounds checks
2103 if self.ptr == self.end {
2107 // purposefully don't use 'ptr.offset' because for
2108 // vectors with 0-size elements this would return the
2110 self.ptr = cast::transmute(self.ptr as uint +
2111 sys::nonzero_size_of::<T>());
2112 Some(cast::transmute(old))
2118 fn size_hint(&self) -> (uint, Option<uint>) {
2119 let diff = (self.end as uint) - (self.ptr as uint);
2120 let exact = diff / sys::nonzero_size_of::<$elem>();
2121 (exact, Some(exact))
2127 macro_rules! double_ended_iterator {
2128 (impl $name:ident -> $elem:ty) => {
2129 impl<'self, T> DoubleEndedIterator<$elem> for $name<'self, T> {
2131 fn next_back(&mut self) -> Option<$elem> {
2132 // could be implemented with slices, but this avoids bounds checks
2134 if self.end == self.ptr {
2137 // See above for why 'ptr.offset' isn't used
2138 self.end = cast::transmute(self.end as uint -
2139 sys::nonzero_size_of::<T>());
2140 Some(cast::transmute(self.end))
2148 //iterator!{struct VecIterator -> *T, &'self T}
2149 /// An iterator for iterating over a vector.
2150 pub struct VecIterator<'self, T> {
2153 priv lifetime: &'self T // FIXME: #5922
2155 iterator!{impl VecIterator -> &'self T}
2156 double_ended_iterator!{impl VecIterator -> &'self T}
2157 pub type VecRevIterator<'self, T> = InvertIterator<&'self T, VecIterator<'self, T>>;
2159 impl<'self, T> Clone for VecIterator<'self, T> {
2160 fn clone(&self) -> VecIterator<'self, T> { *self }
2163 //iterator!{struct VecMutIterator -> *mut T, &'self mut T}
2164 /// An iterator for mutating the elements of a vector.
2165 pub struct VecMutIterator<'self, T> {
2168 priv lifetime: &'self mut T // FIXME: #5922
2170 iterator!{impl VecMutIterator -> &'self mut T}
2171 double_ended_iterator!{impl VecMutIterator -> &'self mut T}
2172 pub type VecMutRevIterator<'self, T> = InvertIterator<&'self mut T, VecMutIterator<'self, T>>;
2174 /// An iterator that moves out of a vector.
2176 pub struct VecConsumeIterator<T> {
2181 impl<T> Iterator<T> for VecConsumeIterator<T> {
2182 fn next(&mut self) -> Option<T> {
2183 // this is peculiar, but is required for safety with respect
2184 // to dtors. It traverses the first half of the vec, and
2185 // removes them by swapping them with the last element (and
2186 // popping), which results in the second half in reverse
2187 // order, and so these can just be pop'd off. That is,
2189 // [1,2,3,4,5] => 1, [5,2,3,4] => 2, [5,4,3] => 3, [5,4] => 4,
2191 let l = self.v.len();
2193 self.v.swap(self.idx, l - 1);
2201 /// An iterator that moves out of a vector in reverse order.
2203 pub struct VecConsumeRevIterator<T> {
2207 impl<T> Iterator<T> for VecConsumeRevIterator<T> {
2208 fn next(&mut self) -> Option<T> {
2213 impl<A, T: Iterator<A>> FromIterator<A, T> for ~[A] {
2214 pub fn from_iterator(iterator: &mut T) -> ~[A] {
2215 let (lower, _) = iterator.size_hint();
2216 let mut xs = with_capacity(lower);
2217 for iterator.advance |x| {
2226 use option::{None, Option, Some};
2231 fn square(n: uint) -> uint { n * n }
2233 fn square_ref(n: &uint) -> uint { square(*n) }
2235 fn is_three(n: &uint) -> bool { *n == 3u }
2237 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
2239 fn is_equal(x: &uint, y:&uint) -> bool { *x == *y }
2241 fn square_if_odd_r(n: &uint) -> Option<uint> {
2242 if *n % 2u == 1u { Some(*n * *n) } else { None }
2245 fn square_if_odd_v(n: uint) -> Option<uint> {
2246 if n % 2u == 1u { Some(n * n) } else { None }
2249 fn add(x: uint, y: &uint) -> uint { x + *y }
2252 fn test_unsafe_ptrs() {
2254 // Test on-stack copy-from-buf.
2256 let mut ptr = raw::to_ptr(a);
2257 let b = from_buf(ptr, 3u);
2258 assert_eq!(b.len(), 3u);
2259 assert_eq!(b[0], 1);
2260 assert_eq!(b[1], 2);
2261 assert_eq!(b[2], 3);
2263 // Test on-heap copy-from-buf.
2264 let c = ~[1, 2, 3, 4, 5];
2265 ptr = raw::to_ptr(c);
2266 let d = from_buf(ptr, 5u);
2267 assert_eq!(d.len(), 5u);
2268 assert_eq!(d[0], 1);
2269 assert_eq!(d[1], 2);
2270 assert_eq!(d[2], 3);
2271 assert_eq!(d[3], 4);
2272 assert_eq!(d[4], 5);
2278 // Test on-stack from_fn.
2279 let mut v = from_fn(3u, square);
2280 assert_eq!(v.len(), 3u);
2281 assert_eq!(v[0], 0u);
2282 assert_eq!(v[1], 1u);
2283 assert_eq!(v[2], 4u);
2285 // Test on-heap from_fn.
2286 v = from_fn(5u, square);
2287 assert_eq!(v.len(), 5u);
2288 assert_eq!(v[0], 0u);
2289 assert_eq!(v[1], 1u);
2290 assert_eq!(v[2], 4u);
2291 assert_eq!(v[3], 9u);
2292 assert_eq!(v[4], 16u);
2296 fn test_from_elem() {
2297 // Test on-stack from_elem.
2298 let mut v = from_elem(2u, 10u);
2299 assert_eq!(v.len(), 2u);
2300 assert_eq!(v[0], 10u);
2301 assert_eq!(v[1], 10u);
2303 // Test on-heap from_elem.
2304 v = from_elem(6u, 20u);
2305 assert_eq!(v[0], 20u);
2306 assert_eq!(v[1], 20u);
2307 assert_eq!(v[2], 20u);
2308 assert_eq!(v[3], 20u);
2309 assert_eq!(v[4], 20u);
2310 assert_eq!(v[5], 20u);
2314 fn test_is_empty() {
2315 let xs: [int, ..0] = [];
2316 assert!(xs.is_empty());
2317 assert!(![0].is_empty());
2321 fn test_len_divzero() {
2323 let v0 : &[Z] = &[];
2324 let v1 : &[Z] = &[[]];
2325 let v2 : &[Z] = &[[], []];
2326 assert_eq!(sys::size_of::<Z>(), 0);
2327 assert_eq!(v0.len(), 0);
2328 assert_eq!(v1.len(), 1);
2329 assert_eq!(v2.len(), 2);
2335 assert_eq!(a.head(), &11);
2337 assert_eq!(a.head(), &11);
2342 #[ignore(cfg(windows))]
2343 fn test_head_empty() {
2344 let a: ~[int] = ~[];
2349 fn test_head_opt() {
2351 assert_eq!(a.head_opt(), None);
2353 assert_eq!(a.head_opt().unwrap(), &11);
2355 assert_eq!(a.head_opt().unwrap(), &11);
2361 assert_eq!(a.tail(), &[]);
2363 assert_eq!(a.tail(), &[12]);
2368 #[ignore(cfg(windows))]
2369 fn test_tail_empty() {
2370 let a: ~[int] = ~[];
2376 let mut a = ~[11, 12, 13];
2377 assert_eq!(a.tailn(0), &[11, 12, 13]);
2379 assert_eq!(a.tailn(2), &[13]);
2384 #[ignore(cfg(windows))]
2385 fn test_tailn_empty() {
2386 let a: ~[int] = ~[];
2393 assert_eq!(a.init(), &[]);
2395 assert_eq!(a.init(), &[11]);
2400 #[ignore(cfg(windows))]
2401 fn test_init_empty() {
2402 let a: ~[int] = ~[];
2408 let mut a = ~[11, 12, 13];
2409 assert_eq!(a.initn(0), &[11, 12, 13]);
2411 assert_eq!(a.initn(2), &[11]);
2416 #[ignore(cfg(windows))]
2417 fn test_initn_empty() {
2418 let a: ~[int] = ~[];
2425 assert_eq!(a.last(), &11);
2427 assert_eq!(a.last(), &12);
2432 #[ignore(cfg(windows))]
2433 fn test_last_empty() {
2434 let a: ~[int] = ~[];
2439 fn test_last_opt() {
2441 assert_eq!(a.last_opt(), None);
2443 assert_eq!(a.last_opt().unwrap(), &11);
2445 assert_eq!(a.last_opt().unwrap(), &12);
2450 // Test fixed length vector.
2451 let vec_fixed = [1, 2, 3, 4];
2452 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
2453 assert_eq!(v_a.len(), 3u);
2454 assert_eq!(v_a[0], 2);
2455 assert_eq!(v_a[1], 3);
2456 assert_eq!(v_a[2], 4);
2459 let vec_stack = &[1, 2, 3];
2460 let v_b = vec_stack.slice(1u, 3u).to_owned();
2461 assert_eq!(v_b.len(), 2u);
2462 assert_eq!(v_b[0], 2);
2463 assert_eq!(v_b[1], 3);
2465 // Test on managed heap.
2466 let vec_managed = @[1, 2, 3, 4, 5];
2467 let v_c = vec_managed.slice(0u, 3u).to_owned();
2468 assert_eq!(v_c.len(), 3u);
2469 assert_eq!(v_c[0], 1);
2470 assert_eq!(v_c[1], 2);
2471 assert_eq!(v_c[2], 3);
2473 // Test on exchange heap.
2474 let vec_unique = ~[1, 2, 3, 4, 5, 6];
2475 let v_d = vec_unique.slice(1u, 6u).to_owned();
2476 assert_eq!(v_d.len(), 5u);
2477 assert_eq!(v_d[0], 2);
2478 assert_eq!(v_d[1], 3);
2479 assert_eq!(v_d[2], 4);
2480 assert_eq!(v_d[3], 5);
2481 assert_eq!(v_d[4], 6);
2485 fn test_slice_from() {
2486 let vec = &[1, 2, 3, 4];
2487 assert_eq!(vec.slice_from(0), vec);
2488 assert_eq!(vec.slice_from(2), &[3, 4]);
2489 assert_eq!(vec.slice_from(4), &[]);
2493 fn test_slice_to() {
2494 let vec = &[1, 2, 3, 4];
2495 assert_eq!(vec.slice_to(4), vec);
2496 assert_eq!(vec.slice_to(2), &[1, 2]);
2497 assert_eq!(vec.slice_to(0), &[]);
2502 // Test on-heap pop.
2503 let mut v = ~[1, 2, 3, 4, 5];
2505 assert_eq!(v.len(), 4u);
2506 assert_eq!(v[0], 1);
2507 assert_eq!(v[1], 2);
2508 assert_eq!(v[2], 3);
2509 assert_eq!(v[3], 4);
2516 let e = v.pop_opt();
2517 assert_eq!(v.len(), 0);
2518 assert_eq!(e, Some(5));
2519 let f = v.pop_opt();
2520 assert_eq!(f, None);
2521 let g = v.pop_opt();
2522 assert_eq!(g, None);
2525 fn test_swap_remove() {
2526 let mut v = ~[1, 2, 3, 4, 5];
2527 let mut e = v.swap_remove(0);
2528 assert_eq!(v.len(), 4);
2530 assert_eq!(v[0], 5);
2531 e = v.swap_remove(3);
2532 assert_eq!(v.len(), 3);
2534 assert_eq!(v[0], 5);
2535 assert_eq!(v[1], 2);
2536 assert_eq!(v[2], 3);
2540 fn test_swap_remove_noncopyable() {
2541 // Tests that we don't accidentally run destructors twice.
2542 let mut v = ~[::unstable::sync::exclusive(()),
2543 ::unstable::sync::exclusive(()),
2544 ::unstable::sync::exclusive(())];
2545 let mut _e = v.swap_remove(0);
2546 assert_eq!(v.len(), 2);
2547 _e = v.swap_remove(1);
2548 assert_eq!(v.len(), 1);
2549 _e = v.swap_remove(0);
2550 assert_eq!(v.len(), 0);
2555 // Test on-stack push().
2558 assert_eq!(v.len(), 1u);
2559 assert_eq!(v[0], 1);
2561 // Test on-heap push().
2563 assert_eq!(v.len(), 2u);
2564 assert_eq!(v[0], 1);
2565 assert_eq!(v[1], 2);
2570 // Test on-stack grow().
2573 assert_eq!(v.len(), 2u);
2574 assert_eq!(v[0], 1);
2575 assert_eq!(v[1], 1);
2577 // Test on-heap grow().
2579 assert_eq!(v.len(), 5u);
2580 assert_eq!(v[0], 1);
2581 assert_eq!(v[1], 1);
2582 assert_eq!(v[2], 2);
2583 assert_eq!(v[3], 2);
2584 assert_eq!(v[4], 2);
2590 v.grow_fn(3u, square);
2591 assert_eq!(v.len(), 3u);
2592 assert_eq!(v[0], 0u);
2593 assert_eq!(v[1], 1u);
2594 assert_eq!(v[2], 4u);
2598 fn test_grow_set() {
2599 let mut v = ~[1, 2, 3];
2600 v.grow_set(4u, &4, 5);
2601 assert_eq!(v.len(), 5u);
2602 assert_eq!(v[0], 1);
2603 assert_eq!(v[1], 2);
2604 assert_eq!(v[2], 3);
2605 assert_eq!(v[3], 4);
2606 assert_eq!(v[4], 5);
2610 fn test_truncate() {
2611 let mut v = ~[@6,@5,@4];
2613 assert_eq!(v.len(), 1);
2614 assert_eq!(*(v[0]), 6);
2615 // If the unsafe block didn't drop things properly, we blow up here.
2620 let mut v = ~[@6,@5,@4];
2622 assert_eq!(v.len(), 0);
2623 // If the unsafe block didn't drop things properly, we blow up here.
2628 fn case(a: ~[uint], b: ~[uint]) {
2636 case(~[1,2,3], ~[1,2,3]);
2637 case(~[1,1,2,3], ~[1,2,3]);
2638 case(~[1,2,2,3], ~[1,2,3]);
2639 case(~[1,2,3,3], ~[1,2,3]);
2640 case(~[1,1,2,2,2,3,3], ~[1,2,3]);
2644 fn test_dedup_unique() {
2645 let mut v0 = ~[~1, ~1, ~2, ~3];
2647 let mut v1 = ~[~1, ~2, ~2, ~3];
2649 let mut v2 = ~[~1, ~2, ~3, ~3];
2652 * If the ~pointers were leaked or otherwise misused, valgrind and/or
2653 * rustrt should raise errors.
2658 fn test_dedup_shared() {
2659 let mut v0 = ~[@1, @1, @2, @3];
2661 let mut v1 = ~[@1, @2, @2, @3];
2663 let mut v2 = ~[@1, @2, @3, @3];
2666 * If the @pointers were leaked or otherwise misused, valgrind and/or
2667 * rustrt should raise errors.
2673 // Test on-stack map.
2674 let v = &[1u, 2u, 3u];
2675 let mut w = v.map(square_ref);
2676 assert_eq!(w.len(), 3u);
2677 assert_eq!(w[0], 1u);
2678 assert_eq!(w[1], 4u);
2679 assert_eq!(w[2], 9u);
2681 // Test on-heap map.
2682 let v = ~[1u, 2u, 3u, 4u, 5u];
2683 w = v.map(square_ref);
2684 assert_eq!(w.len(), 5u);
2685 assert_eq!(w[0], 1u);
2686 assert_eq!(w[1], 4u);
2687 assert_eq!(w[2], 9u);
2688 assert_eq!(w[3], 16u);
2689 assert_eq!(w[4], 25u);
2694 let mut v = ~[1, 2, 3, 4, 5];
2696 assert_eq!(v, ~[1, 3, 5]);
2700 fn test_each_permutation() {
2701 let mut results: ~[~[int]];
2704 for each_permutation([]) |v| { results.push(v.to_owned()); }
2705 assert_eq!(results, ~[~[]]);
2708 for each_permutation([7]) |v| { results.push(v.to_owned()); }
2709 assert_eq!(results, ~[~[7]]);
2712 for each_permutation([1,1]) |v| { results.push(v.to_owned()); }
2713 assert_eq!(results, ~[~[1,1],~[1,1]]);
2716 for each_permutation([5,2,0]) |v| { results.push(v.to_owned()); }
2718 ~[~[5,2,0],~[5,0,2],~[2,5,0],~[2,0,5],~[0,5,2],~[0,2,5]]);
2722 fn test_zip_unzip() {
2723 let v1 = ~[1, 2, 3];
2724 let v2 = ~[4, 5, 6];
2726 let z1 = zip(v1, v2);
2728 assert_eq!((1, 4), z1[0]);
2729 assert_eq!((2, 5), z1[1]);
2730 assert_eq!((3, 6), z1[2]);
2732 let (left, right) = unzip(z1);
2734 assert_eq!((1, 4), (left[0], right[0]));
2735 assert_eq!((2, 5), (left[1], right[1]));
2736 assert_eq!((3, 6), (left[2], right[2]));
2740 fn test_position_elem() {
2741 assert!([].position_elem(&1).is_none());
2743 let v1 = ~[1, 2, 3, 3, 2, 5];
2744 assert_eq!(v1.position_elem(&1), Some(0u));
2745 assert_eq!(v1.position_elem(&2), Some(1u));
2746 assert_eq!(v1.position_elem(&5), Some(5u));
2747 assert!(v1.position_elem(&4).is_none());
2751 fn test_rposition() {
2752 fn f(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'b' }
2753 fn g(xy: &(int, char)) -> bool { let (_x, y) = *xy; y == 'd' }
2754 let v = ~[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'b')];
2756 assert_eq!(v.rposition(f), Some(3u));
2757 assert!(v.rposition(g).is_none());
2761 fn test_bsearch_elem() {
2762 assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
2763 assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
2764 assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
2765 assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
2766 assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
2768 assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
2769 assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
2770 assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
2771 assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
2773 assert_eq!([2,4,6,8].bsearch_elem(&1), None);
2774 assert_eq!([2,4,6,8].bsearch_elem(&5), None);
2775 assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
2776 assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
2778 assert_eq!([2,4,6].bsearch_elem(&1), None);
2779 assert_eq!([2,4,6].bsearch_elem(&5), None);
2780 assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
2781 assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
2783 assert_eq!([2,4].bsearch_elem(&1), None);
2784 assert_eq!([2,4].bsearch_elem(&5), None);
2785 assert_eq!([2,4].bsearch_elem(&2), Some(0));
2786 assert_eq!([2,4].bsearch_elem(&4), Some(1));
2788 assert_eq!([2].bsearch_elem(&1), None);
2789 assert_eq!([2].bsearch_elem(&5), None);
2790 assert_eq!([2].bsearch_elem(&2), Some(0));
2792 assert_eq!([].bsearch_elem(&1), None);
2793 assert_eq!([].bsearch_elem(&5), None);
2795 assert!([1,1,1,1,1].bsearch_elem(&1) != None);
2796 assert!([1,1,1,1,2].bsearch_elem(&1) != None);
2797 assert!([1,1,1,2,2].bsearch_elem(&1) != None);
2798 assert!([1,1,2,2,2].bsearch_elem(&1) != None);
2799 assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
2801 assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
2802 assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
2807 let mut v: ~[int] = ~[10, 20];
2808 assert_eq!(v[0], 10);
2809 assert_eq!(v[1], 20);
2811 assert_eq!(v[0], 20);
2812 assert_eq!(v[1], 10);
2814 let mut v3: ~[int] = ~[];
2816 assert!(v3.is_empty());
2820 fn test_partition() {
2821 assert_eq!((~[]).partition(|x: &int| *x < 3), (~[], ~[]));
2822 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
2823 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 2), (~[1], ~[2, 3]));
2824 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
2828 fn test_partitioned() {
2829 assert_eq!(([]).partitioned(|x: &int| *x < 3), (~[], ~[]))
2830 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
2831 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (~[1], ~[2, 3]));
2832 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
2837 assert_eq!(concat([~[1], ~[2,3]]), ~[1, 2, 3]);
2838 assert_eq!([~[1], ~[2,3]].concat_vec(), ~[1, 2, 3]);
2840 assert_eq!(concat_slices([&[1], &[2,3]]), ~[1, 2, 3]);
2841 assert_eq!([&[1], &[2,3]].concat_vec(), ~[1, 2, 3]);
2846 assert_eq!(connect([], &0), ~[]);
2847 assert_eq!(connect([~[1], ~[2, 3]], &0), ~[1, 0, 2, 3]);
2848 assert_eq!(connect([~[1], ~[2], ~[3]], &0), ~[1, 0, 2, 0, 3]);
2849 assert_eq!([~[1], ~[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
2850 assert_eq!([~[1], ~[2], ~[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
2852 assert_eq!(connect_slices([], &0), ~[]);
2853 assert_eq!(connect_slices([&[1], &[2, 3]], &0), ~[1, 0, 2, 3]);
2854 assert_eq!(connect_slices([&[1], &[2], &[3]], &0), ~[1, 0, 2, 0, 3]);
2855 assert_eq!([&[1], &[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
2856 assert_eq!([&[1], &[2], &[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
2861 let mut x = ~[1, 2, 3];
2862 assert_eq!(x.shift(), 1);
2863 assert_eq!(&x, &~[2, 3]);
2864 assert_eq!(x.shift(), 2);
2865 assert_eq!(x.shift(), 3);
2866 assert_eq!(x.len(), 0);
2870 fn test_shift_opt() {
2871 let mut x = ~[1, 2, 3];
2872 assert_eq!(x.shift_opt(), Some(1));
2873 assert_eq!(&x, &~[2, 3]);
2874 assert_eq!(x.shift_opt(), Some(2));
2875 assert_eq!(x.shift_opt(), Some(3));
2876 assert_eq!(x.shift_opt(), None);
2877 assert_eq!(x.len(), 0);
2882 let mut x = ~[1, 2, 3];
2884 assert_eq!(x, ~[0, 1, 2, 3]);
2889 let mut a = ~[1, 2, 4];
2891 assert_eq!(a, ~[1, 2, 3, 4]);
2893 let mut a = ~[1, 2, 3];
2895 assert_eq!(a, ~[0, 1, 2, 3]);
2897 let mut a = ~[1, 2, 3];
2899 assert_eq!(a, ~[1, 2, 3, 4]);
2903 assert_eq!(a, ~[1]);
2907 #[ignore(cfg(windows))]
2909 fn test_insert_oob() {
2910 let mut a = ~[1, 2, 3];
2916 let mut a = ~[1, 2, 3, 4];
2918 assert_eq!(a, ~[1, 2, 4]);
2920 let mut a = ~[1, 2, 3];
2922 assert_eq!(a, ~[2, 3]);
2930 #[ignore(cfg(windows))]
2932 fn test_remove_oob() {
2933 let mut a = ~[1, 2, 3];
2938 fn test_capacity() {
2939 let mut v = ~[0u64];
2941 assert_eq!(v.capacity(), 10u);
2942 let mut v = ~[0u32];
2944 assert_eq!(v.capacity(), 10u);
2949 let v = ~[1, 2, 3, 4, 5];
2950 let v = v.slice(1u, 3u);
2951 assert_eq!(v.len(), 2u);
2952 assert_eq!(v[0], 2);
2953 assert_eq!(v[1], 3);
2960 fn test_from_fn_fail() {
2961 do from_fn(100) |v| {
2962 if v == 50 { fail!() }
2970 fn test_build_fail() {
2983 fn test_grow_fn_fail() {
2985 do v.grow_fn(100) |i| {
2996 fn test_map_fail() {
2997 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3011 fn test_flat_map_fail() {
3012 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3014 do flat_map(v) |_elt| {
3026 fn test_rposition_fail() {
3027 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3029 do v.rposition |_elt| {
3041 fn test_permute_fail() {
3042 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3044 for each_permutation(v) |_elt| {
3055 fn test_as_imm_buf_fail() {
3056 let v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3057 do v.as_imm_buf |_buf, _i| {
3063 #[ignore(cfg(windows))]
3065 fn test_as_mut_buf_fail() {
3066 let mut v = [(~0, @0), (~0, @0), (~0, @0), (~0, @0)];
3067 do v.as_mut_buf |_buf, _i| {
3074 #[ignore(cfg(windows))]
3075 fn test_copy_memory_oob() {
3077 let mut a = [1, 2, 3, 4];
3078 let b = [1, 2, 3, 4, 5];
3079 raw::copy_memory(a, b, 5);
3084 fn test_total_ord() {
3085 [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
3086 [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
3087 [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
3088 [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
3089 [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
3093 fn test_iterator() {
3095 let xs = [1, 2, 5, 10, 11];
3096 let mut it = xs.iter();
3097 assert_eq!(it.size_hint(), (5, Some(5)));
3098 assert_eq!(it.next().unwrap(), &1);
3099 assert_eq!(it.size_hint(), (4, Some(4)));
3100 assert_eq!(it.next().unwrap(), &2);
3101 assert_eq!(it.size_hint(), (3, Some(3)));
3102 assert_eq!(it.next().unwrap(), &5);
3103 assert_eq!(it.size_hint(), (2, Some(2)));
3104 assert_eq!(it.next().unwrap(), &10);
3105 assert_eq!(it.size_hint(), (1, Some(1)));
3106 assert_eq!(it.next().unwrap(), &11);
3107 assert_eq!(it.size_hint(), (0, Some(0)));
3108 assert!(it.next().is_none());
3112 fn test_iter_size_hints() {
3114 let mut xs = [1, 2, 5, 10, 11];
3115 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
3116 assert_eq!(xs.rev_iter().size_hint(), (5, Some(5)));
3117 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
3118 assert_eq!(xs.mut_rev_iter().size_hint(), (5, Some(5)));
3122 fn test_iter_clone() {
3124 let mut it = xs.iter();
3126 let mut jt = it.clone();
3127 assert_eq!(it.next(), jt.next());
3128 assert_eq!(it.next(), jt.next());
3129 assert_eq!(it.next(), jt.next());
3133 fn test_mut_iterator() {
3135 let mut xs = [1, 2, 3, 4, 5];
3136 for xs.mut_iter().advance |x| {
3139 assert_eq!(xs, [2, 3, 4, 5, 6])
3143 fn test_rev_iterator() {
3146 let xs = [1, 2, 5, 10, 11];
3147 let ys = [11, 10, 5, 2, 1];
3149 for xs.rev_iter().advance |&x| {
3150 assert_eq!(x, ys[i]);
3157 fn test_mut_rev_iterator() {
3159 let mut xs = [1u, 2, 3, 4, 5];
3160 for xs.mut_rev_iter().enumerate().advance |(i,x)| {
3163 assert_eq!(xs, [5, 5, 5, 5, 5])
3167 fn test_consume_iterator() {
3169 let xs = ~[1u,2,3,4,5];
3170 assert_eq!(xs.consume_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
3174 fn test_consume_rev_iterator() {
3176 let xs = ~[1u,2,3,4,5];
3177 assert_eq!(xs.consume_rev_iter().fold(0, |a: uint, b: uint| 10*a + b), 54321);
3181 fn test_split_iterator() {
3182 let xs = &[1i,2,3,4,5];
3184 assert_eq!(xs.split_iter(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3185 ~[&[1], &[3], &[5]]);
3186 assert_eq!(xs.split_iter(|x| *x == 1).collect::<~[&[int]]>(),
3187 ~[&[], &[2,3,4,5]]);
3188 assert_eq!(xs.split_iter(|x| *x == 5).collect::<~[&[int]]>(),
3189 ~[&[1,2,3,4], &[]]);
3190 assert_eq!(xs.split_iter(|x| *x == 10).collect::<~[&[int]]>(),
3192 assert_eq!(xs.split_iter(|_| true).collect::<~[&[int]]>(),
3193 ~[&[], &[], &[], &[], &[], &[]]);
3195 let xs: &[int] = &[];
3196 assert_eq!(xs.split_iter(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3200 fn test_splitn_iterator() {
3201 let xs = &[1i,2,3,4,5];
3203 assert_eq!(xs.splitn_iter(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3205 assert_eq!(xs.splitn_iter(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3207 assert_eq!(xs.splitn_iter(3, |_| true).collect::<~[&[int]]>(),
3208 ~[&[], &[], &[], &[4,5]]);
3210 let xs: &[int] = &[];
3211 assert_eq!(xs.splitn_iter(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3215 fn test_rsplit_iterator() {
3216 let xs = &[1i,2,3,4,5];
3218 assert_eq!(xs.rsplit_iter(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3219 ~[&[5], &[3], &[1]]);
3220 assert_eq!(xs.rsplit_iter(|x| *x == 1).collect::<~[&[int]]>(),
3221 ~[&[2,3,4,5], &[]]);
3222 assert_eq!(xs.rsplit_iter(|x| *x == 5).collect::<~[&[int]]>(),
3223 ~[&[], &[1,2,3,4]]);
3224 assert_eq!(xs.rsplit_iter(|x| *x == 10).collect::<~[&[int]]>(),
3227 let xs: &[int] = &[];
3228 assert_eq!(xs.rsplit_iter(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3232 fn test_rsplitn_iterator() {
3233 let xs = &[1,2,3,4,5];
3235 assert_eq!(xs.rsplitn_iter(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3237 assert_eq!(xs.rsplitn_iter(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3239 assert_eq!(xs.rsplitn_iter(3, |_| true).collect::<~[&[int]]>(),
3240 ~[&[], &[], &[], &[1,2]]);
3242 let xs: &[int] = &[];
3243 assert_eq!(xs.rsplitn_iter(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3247 fn test_window_iterator() {
3248 let v = &[1i,2,3,4];
3250 assert_eq!(v.window_iter(2).collect::<~[&[int]]>(), ~[&[1,2], &[2,3], &[3,4]]);
3251 assert_eq!(v.window_iter(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[2,3,4]]);
3252 assert!(v.window_iter(6).next().is_none());
3257 #[ignore(cfg(windows))]
3258 fn test_window_iterator_0() {
3259 let v = &[1i,2,3,4];
3260 let _it = v.window_iter(0);
3264 fn test_chunk_iterator() {
3265 let v = &[1i,2,3,4,5];
3267 assert_eq!(v.chunk_iter(2).collect::<~[&[int]]>(), ~[&[1i,2], &[3,4], &[5]]);
3268 assert_eq!(v.chunk_iter(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[4,5]]);
3269 assert_eq!(v.chunk_iter(6).collect::<~[&[int]]>(), ~[&[1i,2,3,4,5]]);
3274 #[ignore(cfg(windows))]
3275 fn test_chunk_iterator_0() {
3276 let v = &[1i,2,3,4];
3277 let _it = v.chunk_iter(0);
3281 fn test_move_from() {
3282 let mut a = [1,2,3,4,5];
3284 assert_eq!(a.move_from(b, 0, 3), 3);
3285 assert_eq!(a, [6,7,8,4,5]);
3286 let mut a = [7,2,8,1];
3287 let b = ~[3,1,4,1,5,9];
3288 assert_eq!(a.move_from(b, 0, 6), 4);
3289 assert_eq!(a, [3,1,4,1]);
3290 let mut a = [1,2,3,4];
3291 let b = ~[5,6,7,8,9,0];
3292 assert_eq!(a.move_from(b, 2, 3), 1);
3293 assert_eq!(a, [7,2,3,4]);
3294 let mut a = [1,2,3,4,5];
3295 let b = ~[5,6,7,8,9,0];
3296 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
3297 assert_eq!(a, [1,2,6,7,5]);
3301 fn test_copy_from() {
3302 let mut a = [1,2,3,4,5];
3304 assert_eq!(a.copy_from(b), 3);
3305 assert_eq!(a, [6,7,8,4,5]);
3306 let mut c = [7,2,8,1];
3307 let d = [3,1,4,1,5,9];
3308 assert_eq!(c.copy_from(d), 4);
3309 assert_eq!(c, [3,1,4,1]);
3313 fn test_reverse_part() {
3314 let mut values = [1,2,3,4,5];
3315 values.mut_slice(1, 4).reverse();
3316 assert_eq!(values, [1,4,3,2,5]);
3320 fn test_permutations0() {
3322 let mut v : ~[~[int]] = ~[];
3323 for each_permutation(values) |p| {
3324 v.push(p.to_owned());
3326 assert_eq!(v, ~[~[]]);
3330 fn test_permutations1() {
3332 let mut v : ~[~[int]] = ~[];
3333 for each_permutation(values) |p| {
3334 v.push(p.to_owned());
3336 assert_eq!(v, ~[~[1]]);
3340 fn test_permutations2() {
3342 let mut v : ~[~[int]] = ~[];
3343 for each_permutation(values) |p| {
3344 v.push(p.to_owned());
3346 assert_eq!(v, ~[~[1,2],~[2,1]]);
3350 fn test_permutations3() {
3351 let values = [1,2,3];
3352 let mut v : ~[~[int]] = ~[];
3353 for each_permutation(values) |p| {
3354 v.push(p.to_owned());
3356 assert_eq!(v, ~[~[1,2,3],~[1,3,2],~[2,1,3],~[2,3,1],~[3,1,2],~[3,2,1]]);
3360 fn test_vec_zero() {
3364 let v: $ty = Zero::zero();
3365 assert!(v.is_empty());
3366 assert!(v.is_zero());
3376 fn test_bytes_set_memory() {
3377 use vec::bytes::MutableByteVector;
3378 let mut values = [1u8,2,3,4,5];
3379 values.mut_slice(0,5).set_memory(0xAB);
3380 assert_eq!(values, [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
3381 values.mut_slice(2,4).set_memory(0xFF);
3382 assert_eq!(values, [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
3387 fn test_overflow_does_not_cause_segfault() {
3395 fn test_mut_split() {
3396 let mut values = [1u8,2,3,4,5];
3398 let (left, right) = values.mut_split(2);
3399 assert_eq!(left.slice(0, left.len()), [1, 2]);
3400 for left.mut_iter().advance |p| {
3404 assert_eq!(right.slice(0, right.len()), [3, 4, 5]);
3405 for right.mut_iter().advance |p| {
3410 assert_eq!(values, [2, 3, 5, 6, 7]);
3413 #[deriving(Clone, Eq)]
3417 fn test_iter_zero_sized() {
3418 let mut v = ~[Foo, Foo, Foo];
3419 assert_eq!(v.len(), 3);
3422 for v.iter().advance |f| {
3428 for v.slice(1, 3).iter().advance |f| {
3434 for v.mut_iter().advance |f| {
3440 for v.consume_iter().advance |f| {
3444 assert_eq!(cnt, 11);
3446 let xs = ~[Foo, Foo, Foo];
3447 assert_eq!(fmt!("%?", xs.slice(0, 2).to_owned()), ~"~[{}, {}]");
3449 let xs: [Foo, ..3] = [Foo, Foo, Foo];
3450 assert_eq!(fmt!("%?", xs.slice(0, 2).to_owned()), ~"~[{}, {}]");
3452 for xs.iter().advance |f| {