1 // Copyright 2012-2014 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 Utilities for vector manipulation
15 The `vec` module contains useful code to help work with vector values.
16 Vectors are Rust's list type. Vectors contain zero or more values of
20 let int_vector = [1,2,3];
21 let str_vector = ["one", "two", "three"];
24 This is a big module, but for a high-level overview:
28 Several structs that are useful for vectors, such as `Items`, which
29 represents iteration over a vector.
33 A number of traits add methods that allow you to accomplish tasks with vectors.
35 Traits defined for the `&[T]` type (a vector slice), have methods that can be
36 called on either owned vectors, denoted `~[T]`, or on vector slices themselves.
37 These traits include `ImmutableVector`, and `MutableVector` for the `&mut [T]`
40 An example is the method `.slice(a, b)` that returns an immutable "view" into
41 a vector or a vector slice from the index interval `[a, b)`:
44 let numbers = [0, 1, 2];
45 let last_numbers = numbers.slice(1, 3);
46 // last_numbers is now &[1, 2]
49 Traits defined for the `~[T]` type, like `OwnedVector`, can only be called
50 on such vectors. These methods deal with adding elements or otherwise changing
51 the allocation of the vector.
53 An example is the method `.push(element)` that will add an element at the end
57 let mut numbers = ~[0, 1, 2];
59 // numbers is now ~[0, 1, 2, 7];
62 ## Implementations of other traits
64 Vectors are a very useful type, and so there's several implementations of
65 traits from other modules. Some notable examples:
68 * `Eq`, `Ord`, `TotalEq`, `TotalOrd` -- vectors can be compared,
69 if the element type defines the corresponding trait.
73 The method `iter()` returns an iteration value for a vector or a vector slice.
74 The iterator yields references to the vector's elements, so if the element
75 type of the vector is `int`, the element type of the iterator is `&int`.
78 let numbers = [0, 1, 2];
79 for &x in numbers.iter() {
80 println!("{} is a number!", x);
84 * `.rev_iter()` returns an iterator with the same values as `.iter()`,
85 but going in the reverse order, starting with the back element.
86 * `.mut_iter()` returns an iterator that allows modifying each value.
87 * `.move_iter()` converts an owned vector into an iterator that
88 moves out a value from the vector each iteration.
89 * Further iterators exist that split, chunk or permute the vector.
91 ## Function definitions
93 There are a number of free functions that create or take vectors, for example:
95 * Creating a vector, like `from_elem` and `from_fn`
96 * Creating a vector with a given size: `with_capacity`
97 * Modifying a vector and returning it, like `append`
98 * Operations on paired elements, like `unzip`.
102 #[warn(non_camel_case_types)];
106 use clone::{Clone, DeepClone};
107 use container::{Container, Mutable};
108 use cmp::{Eq, TotalOrd, Ordering, Less, Equal, Greater};
110 use default::Default;
112 use num::{Integer, CheckedAdd, Saturating, checked_next_power_of_two};
113 use option::{None, Option, Some};
114 use ptr::to_unsafe_ptr;
117 use rt::global_heap::{malloc_raw, realloc_raw, exchange_free};
122 use unstable::finally::Finally;
123 use unstable::intrinsics;
124 use unstable::raw::{Repr, Slice, Vec};
128 * Creates and initializes an owned vector.
130 * Creates an owned vector of size `n_elts` and initializes the elements
131 * to the value returned by the function `op`.
133 pub fn from_fn<T>(n_elts: uint, op: |uint| -> T) -> ~[T] {
135 let mut v = with_capacity(n_elts);
136 let p = v.as_mut_ptr();
137 let mut i: uint = 0u;
140 intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), op(i));
151 * Creates and initializes an owned vector.
153 * Creates an owned vector of size `n_elts` and initializes the elements
156 pub fn from_elem<T:Clone>(n_elts: uint, t: T) -> ~[T] {
157 // FIXME (#7136): manually inline from_fn for 2x plus speedup (sadly very
158 // important, from_elem is a bottleneck in borrowck!). Unfortunately it
159 // still is substantially slower than using the unsafe
160 // vec::with_capacity/ptr::set_memory for primitive types.
162 let mut v = with_capacity(n_elts);
163 let p = v.as_mut_ptr();
167 intrinsics::move_val_init(&mut(*ptr::mut_offset(p, i as int)), t.clone());
177 /// Creates a new vector with a capacity of `capacity`
179 pub fn with_capacity<T>(capacity: uint) -> ~[T] {
181 let alloc = capacity * mem::nonzero_size_of::<T>();
182 let size = alloc + mem::size_of::<Vec<()>>();
183 if alloc / mem::nonzero_size_of::<T>() != capacity || size < alloc {
184 fail!("vector size is too large: {}", capacity);
186 let ptr = malloc_raw(size) as *mut Vec<()>;
187 (*ptr).alloc = alloc;
194 * Builds a vector by calling a provided function with an argument
195 * function that pushes an element to the back of a vector.
196 * The initial capacity for the vector may optionally be specified.
200 * * size - An option, maybe containing initial size of the vector to reserve
201 * * builder - A function that will construct the vector. It receives
202 * as an argument a function that will push an element
203 * onto the vector being constructed.
206 pub fn build<A>(size: Option<uint>, builder: |push: |v: A||) -> ~[A] {
207 let mut vec = with_capacity(size.unwrap_or(4));
208 builder(|x| vec.push(x));
213 * Converts a pointer to A into a slice of length 1 (without copying).
215 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
217 cast::transmute(Slice { data: s, len: 1 })
222 * Converts a pointer to A into a slice of length 1 (without copying).
224 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
226 let ptr: *A = cast::transmute(s);
227 cast::transmute(Slice { data: ptr, len: 1 })
231 /// An iterator over the slices of a vector separated by elements that
232 /// match a predicate function.
233 pub struct Splits<'a, T> {
236 priv pred: 'a |t: &T| -> bool,
240 impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
242 fn next(&mut self) -> Option<&'a [T]> {
243 if self.finished { return None; }
246 self.finished = true;
250 match self.v.iter().position(|x| (self.pred)(x)) {
252 self.finished = true;
256 let ret = Some(self.v.slice(0, idx));
257 self.v = self.v.slice(idx + 1, self.v.len());
265 fn size_hint(&self) -> (uint, Option<uint>) {
269 // if the predicate doesn't match anything, we yield one slice
270 // if it matches every element, we yield N+1 empty slices where
271 // N is either the number of elements or the number of splits.
272 match (self.v.len(), self.n) {
273 (0,_) => (1, Some(1)),
274 (_,0) => (1, Some(1)),
275 (l,n) => (1, cmp::min(l,n).checked_add(&1u))
280 /// An iterator over the slices of a vector separated by elements that
281 /// match a predicate function, from back to front.
282 pub struct RevSplits<'a, T> {
285 priv pred: 'a |t: &T| -> bool,
289 impl<'a, T> Iterator<&'a [T]> for RevSplits<'a, T> {
291 fn next(&mut self) -> Option<&'a [T]> {
292 if self.finished { return None; }
295 self.finished = true;
299 match self.v.iter().rposition(|x| (self.pred)(x)) {
301 self.finished = true;
305 let ret = Some(self.v.slice(idx + 1, self.v.len()));
306 self.v = self.v.slice(0, idx);
314 fn size_hint(&self) -> (uint, Option<uint>) {
318 match (self.v.len(), self.n) {
319 (0,_) => (1, Some(1)),
320 (_,0) => (1, Some(1)),
321 (l,n) => (1, cmp::min(l,n).checked_add(&1u))
328 /// Iterates over the `rhs` vector, copying each element and appending it to the
329 /// `lhs`. Afterwards, the `lhs` is then returned for use again.
331 pub fn append<T:Clone>(lhs: ~[T], rhs: &[T]) -> ~[T] {
337 /// Appends one element to the vector provided. The vector itself is then
338 /// returned for use again.
340 pub fn append_one<T>(lhs: ~[T], x: T) -> ~[T] {
346 // Functional utilities
349 * Apply a function to each element of a vector and return a concatenation
350 * of each result vector
352 pub fn flat_map<T, U>(v: &[T], f: |t: &T| -> ~[U]) -> ~[U] {
353 let mut result = ~[];
354 for elem in v.iter() { result.push_all_move(f(elem)); }
358 #[allow(missing_doc)]
359 pub trait VectorVector<T> {
360 // FIXME #5898: calling these .concat and .connect conflicts with
361 // StrVector::con{cat,nect}, since they have generic contents.
362 /// Flattens a vector of vectors of T into a single vector of T.
363 fn concat_vec(&self) -> ~[T];
365 /// Concatenate a vector of vectors, placing a given separator between each.
366 fn connect_vec(&self, sep: &T) -> ~[T];
369 impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
370 fn concat_vec(&self) -> ~[T] {
371 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
372 let mut result = with_capacity(size);
373 for v in self.iter() {
374 result.push_all(v.as_slice())
379 fn connect_vec(&self, sep: &T) -> ~[T] {
380 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
381 let mut result = with_capacity(size + self.len());
382 let mut first = true;
383 for v in self.iter() {
384 if first { first = false } else { result.push(sep.clone()) }
385 result.push_all(v.as_slice())
392 * Convert an iterator of pairs into a pair of vectors.
394 * Returns a tuple containing two vectors where the i-th element of the first
395 * vector contains the first element of the i-th tuple of the input iterator,
396 * and the i-th element of the second vector contains the second element
397 * of the i-th tuple of the input iterator.
399 pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
400 let (lo, _) = iter.size_hint();
401 let mut ts = with_capacity(lo);
402 let mut us = with_capacity(lo);
410 /// An Iterator that yields the element swaps needed to produce
411 /// a sequence of all possible permutations for an indexed sequence of
412 /// elements. Each permutation is only a single swap apart.
414 /// The Steinhaus–Johnson–Trotter algorithm is used.
416 /// Generates even and odd permutations alternately.
418 /// The last generated swap is always (0, 1), and it returns the
419 /// sequence to its initial order.
420 pub struct ElementSwaps {
421 priv sdir: ~[SizeDirection],
422 /// If true, emit the last swap that returns the sequence to initial state
423 priv emit_reset: bool,
427 /// Create an `ElementSwaps` iterator for a sequence of `length` elements
428 pub fn new(length: uint) -> ElementSwaps {
429 // Initialize `sdir` with a direction that position should move in
430 // (all negative at the beginning) and the `size` of the
431 // element (equal to the original index).
434 sdir: range(0, length)
435 .map(|i| SizeDirection{ size: i, dir: Neg })
441 enum Direction { Pos, Neg }
443 /// An Index and Direction together
444 struct SizeDirection {
449 impl Iterator<(uint, uint)> for ElementSwaps {
451 fn next(&mut self) -> Option<(uint, uint)> {
452 fn new_pos(i: uint, s: Direction) -> uint {
453 i + match s { Pos => 1, Neg => -1 }
456 // Find the index of the largest mobile element:
457 // The direction should point into the vector, and the
458 // swap should be with a smaller `size` element.
459 let max = self.sdir.iter().map(|&x| x).enumerate()
461 new_pos(i, sd.dir) < self.sdir.len() &&
462 self.sdir[new_pos(i, sd.dir)].size < sd.size)
463 .max_by(|&(_, sd)| sd.size);
466 let j = new_pos(i, sd.dir);
467 self.sdir.swap(i, j);
469 // Swap the direction of each larger SizeDirection
470 for x in self.sdir.mut_iter() {
471 if x.size > sd.size {
472 x.dir = match x.dir { Pos => Neg, Neg => Pos };
477 None => if self.emit_reset && self.sdir.len() > 1 {
478 self.emit_reset = false;
487 /// An Iterator that uses `ElementSwaps` to iterate through
488 /// all possible permutations of a vector.
490 /// The first iteration yields a clone of the vector as it is,
491 /// then each successive element is the vector with one
494 /// Generates even and odd permutations alternately.
495 pub struct Permutations<T> {
496 priv swaps: ElementSwaps,
500 impl<T: Clone> Iterator<~[T]> for Permutations<T> {
502 fn next(&mut self) -> Option<~[T]> {
503 match self.swaps.next() {
506 let elt = self.v.clone();
514 /// An iterator over the (overlapping) slices of length `size` within
517 pub struct Windows<'a, T> {
522 impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
524 fn next(&mut self) -> Option<&'a [T]> {
525 if self.size > self.v.len() {
528 let ret = Some(self.v.slice(0, self.size));
529 self.v = self.v.slice(1, self.v.len());
535 fn size_hint(&self) -> (uint, Option<uint>) {
536 if self.size > self.v.len() {
539 let x = self.v.len() - self.size;
540 (x.saturating_add(1), x.checked_add(&1u))
545 /// An iterator over a vector in (non-overlapping) chunks (`size`
546 /// elements at a time).
548 /// When the vector len is not evenly divided by the chunk size,
549 /// the last slice of the iteration will be the remainder.
551 pub struct Chunks<'a, T> {
556 impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
558 fn next(&mut self) -> Option<&'a [T]> {
559 if self.v.len() == 0 {
562 let chunksz = cmp::min(self.v.len(), self.size);
563 let (fst, snd) = (self.v.slice_to(chunksz),
564 self.v.slice_from(chunksz));
571 fn size_hint(&self) -> (uint, Option<uint>) {
572 if self.v.len() == 0 {
575 let (n, rem) = self.v.len().div_rem(&self.size);
576 let n = if rem > 0 { n+1 } else { n };
582 impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
584 fn next_back(&mut self) -> Option<&'a [T]> {
585 if self.v.len() == 0 {
588 let remainder = self.v.len() % self.size;
589 let chunksz = if remainder != 0 { remainder } else { self.size };
590 let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
591 self.v.slice_from(self.v.len() - chunksz));
598 impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
600 fn indexable(&self) -> uint {
601 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
605 fn idx(&self, index: uint) -> Option<&'a [T]> {
606 if index < self.indexable() {
607 let lo = index * self.size;
608 let mut hi = lo + self.size;
609 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
611 Some(self.v.slice(lo, hi))
621 #[allow(missing_doc)]
625 use container::Container;
627 use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Equiv};
631 impl<'a,T:Eq> Eq for &'a [T] {
632 fn eq(&self, other: & &'a [T]) -> bool {
633 self.len() == other.len() &&
634 order::eq(self.iter(), other.iter())
636 fn ne(&self, other: & &'a [T]) -> bool {
637 self.len() != other.len() ||
638 order::ne(self.iter(), other.iter())
642 impl<T:Eq> Eq for ~[T] {
644 fn eq(&self, other: &~[T]) -> bool { self.as_slice() == *other }
646 fn ne(&self, other: &~[T]) -> bool { !self.eq(other) }
649 impl<T:Eq> Eq for @[T] {
651 fn eq(&self, other: &@[T]) -> bool { self.as_slice() == *other }
653 fn ne(&self, other: &@[T]) -> bool { !self.eq(other) }
656 impl<'a,T:TotalEq> TotalEq for &'a [T] {
657 fn equals(&self, other: & &'a [T]) -> bool {
658 self.len() == other.len() &&
659 order::equals(self.iter(), other.iter())
663 impl<T:TotalEq> TotalEq for ~[T] {
665 fn equals(&self, other: &~[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
668 impl<T:TotalEq> TotalEq for @[T] {
670 fn equals(&self, other: &@[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
673 impl<'a,T:Eq, V: Vector<T>> Equiv<V> for &'a [T] {
675 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
678 impl<'a,T:Eq, V: Vector<T>> Equiv<V> for ~[T] {
680 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
683 impl<'a,T:Eq, V: Vector<T>> Equiv<V> for @[T] {
685 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
688 impl<'a,T:TotalOrd> TotalOrd for &'a [T] {
689 fn cmp(&self, other: & &'a [T]) -> Ordering {
690 order::cmp(self.iter(), other.iter())
694 impl<T: TotalOrd> TotalOrd for ~[T] {
696 fn cmp(&self, other: &~[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
699 impl<T: TotalOrd> TotalOrd for @[T] {
701 fn cmp(&self, other: &@[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
704 impl<'a, T: Eq + Ord> Ord for &'a [T] {
705 fn lt(&self, other: & &'a [T]) -> bool {
706 order::lt(self.iter(), other.iter())
709 fn le(&self, other: & &'a [T]) -> bool {
710 order::le(self.iter(), other.iter())
713 fn ge(&self, other: & &'a [T]) -> bool {
714 order::ge(self.iter(), other.iter())
717 fn gt(&self, other: & &'a [T]) -> bool {
718 order::gt(self.iter(), other.iter())
722 impl<T: Eq + Ord> Ord for ~[T] {
724 fn lt(&self, other: &~[T]) -> bool { self.as_slice() < other.as_slice() }
726 fn le(&self, other: &~[T]) -> bool { self.as_slice() <= other.as_slice() }
728 fn ge(&self, other: &~[T]) -> bool { self.as_slice() >= other.as_slice() }
730 fn gt(&self, other: &~[T]) -> bool { self.as_slice() > other.as_slice() }
733 impl<T: Eq + Ord> Ord for @[T] {
735 fn lt(&self, other: &@[T]) -> bool { self.as_slice() < other.as_slice() }
737 fn le(&self, other: &@[T]) -> bool { self.as_slice() <= other.as_slice() }
739 fn ge(&self, other: &@[T]) -> bool { self.as_slice() >= other.as_slice() }
741 fn gt(&self, other: &@[T]) -> bool { self.as_slice() > other.as_slice() }
744 impl<'a,T:Clone, V: Vector<T>> Add<V, ~[T]> for &'a [T] {
746 fn add(&self, rhs: &V) -> ~[T] {
747 let mut res = with_capacity(self.len() + rhs.as_slice().len());
749 res.push_all(rhs.as_slice());
754 impl<T:Clone, V: Vector<T>> Add<V, ~[T]> for ~[T] {
756 fn add(&self, rhs: &V) -> ~[T] {
757 self.as_slice() + rhs.as_slice()
765 /// Any vector that can be represented as a slice.
766 pub trait Vector<T> {
767 /// Work with `self` as a slice.
768 fn as_slice<'a>(&'a self) -> &'a [T];
771 impl<'a,T> Vector<T> for &'a [T] {
773 fn as_slice<'a>(&'a self) -> &'a [T] { *self }
776 impl<T> Vector<T> for ~[T] {
778 fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
781 impl<T> Vector<T> for @[T] {
783 fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
786 impl<'a, T> Container for &'a [T] {
787 /// Returns the length of a vector
789 fn len(&self) -> uint {
794 impl<T> Container for ~[T] {
795 /// Returns the length of a vector
797 fn len(&self) -> uint {
798 self.as_slice().len()
802 /// Extension methods for vector slices with cloneable elements
803 pub trait CloneableVector<T> {
804 /// Copy `self` into a new owned vector
805 fn to_owned(&self) -> ~[T];
807 /// Convert `self` into an owned vector, not making a copy if possible.
808 fn into_owned(self) -> ~[T];
811 /// Extension methods for vector slices
812 impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
813 /// Returns a copy of `v`.
815 fn to_owned(&self) -> ~[T] {
816 let mut result = with_capacity(self.len());
817 for e in self.iter() {
818 result.push((*e).clone());
824 fn into_owned(self) -> ~[T] { self.to_owned() }
827 /// Extension methods for owned vectors
828 impl<T: Clone> CloneableVector<T> for ~[T] {
830 fn to_owned(&self) -> ~[T] { self.clone() }
833 fn into_owned(self) -> ~[T] { self }
836 /// Extension methods for managed vectors
837 impl<T: Clone> CloneableVector<T> for @[T] {
839 fn to_owned(&self) -> ~[T] { self.as_slice().to_owned() }
842 fn into_owned(self) -> ~[T] { self.to_owned() }
845 /// Extension methods for vectors
846 pub trait ImmutableVector<'a, T> {
848 * Returns a slice of self between `start` and `end`.
850 * Fails when `start` or `end` point outside the bounds of self,
851 * or when `start` > `end`.
853 fn slice(&self, start: uint, end: uint) -> &'a [T];
856 * Returns a slice of self from `start` to the end of the vec.
858 * Fails when `start` points outside the bounds of self.
860 fn slice_from(&self, start: uint) -> &'a [T];
863 * Returns a slice of self from the start of the vec to `end`.
865 * Fails when `end` points outside the bounds of self.
867 fn slice_to(&self, end: uint) -> &'a [T];
868 /// Returns an iterator over the vector
869 fn iter(self) -> Items<'a, T>;
870 /// Returns a reversed iterator over a vector
871 fn rev_iter(self) -> RevItems<'a, T>;
872 /// Returns an iterator over the subslices of the vector which are
873 /// separated by elements that match `pred`. The matched element
874 /// is not contained in the subslices.
875 fn split(self, pred: 'a |&T| -> bool) -> Splits<'a, T>;
876 /// Returns an iterator over the subslices of the vector which are
877 /// separated by elements that match `pred`, limited to splitting
878 /// at most `n` times. The matched element is not contained in
880 fn splitn(self, n: uint, pred: 'a |&T| -> bool) -> Splits<'a, T>;
881 /// Returns an iterator over the subslices of the vector which are
882 /// separated by elements that match `pred`. This starts at the
883 /// end of the vector and works backwards. The matched element is
884 /// not contained in the subslices.
885 fn rsplit(self, pred: 'a |&T| -> bool) -> RevSplits<'a, T>;
886 /// Returns an iterator over the subslices of the vector which are
887 /// separated by elements that match `pred` limited to splitting
888 /// at most `n` times. This starts at the end of the vector and
889 /// works backwards. The matched element is not contained in the
891 fn rsplitn(self, n: uint, pred: 'a |&T| -> bool) -> RevSplits<'a, T>;
894 * Returns an iterator over all contiguous windows of length
895 * `size`. The windows overlap. If the vector is shorter than
896 * `size`, the iterator returns no values.
900 * Fails if `size` is 0.
904 * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
908 * let v = &[1,2,3,4];
909 * for win in v.windows(2) {
910 * println!("{:?}", win);
915 fn windows(self, size: uint) -> Windows<'a, T>;
918 * Returns an iterator over `size` elements of the vector at a
919 * time. The chunks do not overlap. If `size` does not divide the
920 * length of the vector, then the last chunk will not have length
925 * Fails if `size` is 0.
929 * Print the vector two elements at a time (i.e. `[1,2]`,
933 * let v = &[1,2,3,4,5];
934 * for win in v.chunks(2) {
935 * println!("{:?}", win);
940 fn chunks(self, size: uint) -> Chunks<'a, T>;
942 /// Returns the element of a vector at the given index, or `None` if the
943 /// index is out of bounds
944 fn get(&self, index: uint) -> Option<&'a T>;
945 /// Returns the first element of a vector, or `None` if it is empty
946 fn head(&self) -> Option<&'a T>;
947 /// Returns all but the first element of a vector
948 fn tail(&self) -> &'a [T];
949 /// Returns all but the first `n' elements of a vector
950 fn tailn(&self, n: uint) -> &'a [T];
951 /// Returns all but the last element of a vector
952 fn init(&self) -> &'a [T];
953 /// Returns all but the last `n' elements of a vector
954 fn initn(&self, n: uint) -> &'a [T];
955 /// Returns the last element of a vector, or `None` if it is empty.
956 fn last(&self) -> Option<&'a T>;
958 * Apply a function to each element of a vector and return a concatenation
959 * of each result vector
961 fn flat_map<U>(&self, f: |t: &T| -> ~[U]) -> ~[U];
962 /// Returns a pointer to the element at the given index, without doing
964 unsafe fn unsafe_ref(self, index: uint) -> &'a T;
967 * Returns an unsafe pointer to the vector's buffer
969 * The caller must ensure that the vector outlives the pointer this
970 * function returns, or else it will end up pointing to garbage.
972 * Modifying the vector may cause its buffer to be reallocated, which
973 * would also make any pointers to it invalid.
975 fn as_ptr(&self) -> *T;
978 * Binary search a sorted vector with a comparator function.
980 * The comparator function should implement an order consistent
981 * with the sort order of the underlying vector, returning an
982 * order code that indicates whether its argument is `Less`,
983 * `Equal` or `Greater` the desired target.
985 * Returns the index where the comparator returned `Equal`, or `None` if
988 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
990 /// Deprecated, use iterators where possible
991 /// (`self.iter().map(f)`). Apply a function to each element
992 /// of a vector and return the results.
993 fn map<U>(&self, |t: &T| -> U) -> ~[U];
996 * Returns a mutable reference to the first element in this slice
997 * and adjusts the slice in place so that it no longer contains
998 * that element. O(1).
1003 * let head = &self[0];
1004 * *self = self.slice_from(1);
1008 * Fails if slice is empty.
1010 fn shift_ref(&mut self) -> &'a T;
1013 * Returns a mutable reference to the last element in this slice
1014 * and adjusts the slice in place so that it no longer contains
1015 * that element. O(1).
1020 * let tail = &self[self.len() - 1];
1021 * *self = self.slice_to(self.len() - 1);
1025 * Fails if slice is empty.
1027 fn pop_ref(&mut self) -> &'a T;
1030 impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
1032 fn slice(&self, start: uint, end: uint) -> &'a [T] {
1033 assert!(start <= end);
1034 assert!(end <= self.len());
1036 cast::transmute(Slice {
1037 data: self.as_ptr().offset(start as int),
1044 fn slice_from(&self, start: uint) -> &'a [T] {
1045 self.slice(start, self.len())
1049 fn slice_to(&self, end: uint) -> &'a [T] {
1054 fn iter(self) -> Items<'a, T> {
1056 let p = self.as_ptr();
1057 if mem::size_of::<T>() == 0 {
1059 end: (p as uint + self.len()) as *T,
1060 marker: marker::ContravariantLifetime::<'a>}
1063 end: p.offset(self.len() as int),
1064 marker: marker::ContravariantLifetime::<'a>}
1070 fn rev_iter(self) -> RevItems<'a, T> {
1075 fn split(self, pred: 'a |&T| -> bool) -> Splits<'a, T> {
1076 self.splitn(uint::MAX, pred)
1080 fn splitn(self, n: uint, pred: 'a |&T| -> bool) -> Splits<'a, T> {
1090 fn rsplit(self, pred: 'a |&T| -> bool) -> RevSplits<'a, T> {
1091 self.rsplitn(uint::MAX, pred)
1095 fn rsplitn(self, n: uint, pred: 'a |&T| -> bool) -> RevSplits<'a, T> {
1105 fn windows(self, size: uint) -> Windows<'a, T> {
1107 Windows { v: self, size: size }
1111 fn chunks(self, size: uint) -> Chunks<'a, T> {
1113 Chunks { v: self, size: size }
1117 fn get(&self, index: uint) -> Option<&'a T> {
1118 if index < self.len() { Some(&self[index]) } else { None }
1122 fn head(&self) -> Option<&'a T> {
1123 if self.len() == 0 { None } else { Some(&self[0]) }
1127 fn tail(&self) -> &'a [T] { self.slice(1, self.len()) }
1130 fn tailn(&self, n: uint) -> &'a [T] { self.slice(n, self.len()) }
1133 fn init(&self) -> &'a [T] {
1134 self.slice(0, self.len() - 1)
1138 fn initn(&self, n: uint) -> &'a [T] {
1139 self.slice(0, self.len() - n)
1143 fn last(&self) -> Option<&'a T> {
1144 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
1148 fn flat_map<U>(&self, f: |t: &T| -> ~[U]) -> ~[U] {
1153 unsafe fn unsafe_ref(self, index: uint) -> &'a T {
1154 cast::transmute(self.repr().data.offset(index as int))
1158 fn as_ptr(&self) -> *T {
1163 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint> {
1164 let mut base : uint = 0;
1165 let mut lim : uint = self.len();
1168 let ix = base + (lim >> 1);
1169 match f(&self[ix]) {
1170 Equal => return Some(ix),
1182 fn map<U>(&self, f: |t: &T| -> U) -> ~[U] {
1183 self.iter().map(f).collect()
1186 fn shift_ref(&mut self) -> &'a T {
1188 let s: &mut Slice<T> = cast::transmute(self);
1193 fn pop_ref(&mut self) -> &'a T {
1195 let s: &mut Slice<T> = cast::transmute(self);
1201 /// Extension methods for vectors contain `Eq` elements.
1202 pub trait ImmutableEqVector<T:Eq> {
1203 /// Find the first index containing a matching value
1204 fn position_elem(&self, t: &T) -> Option<uint>;
1206 /// Find the last index containing a matching value
1207 fn rposition_elem(&self, t: &T) -> Option<uint>;
1209 /// Return true if a vector contains an element with the given value
1210 fn contains(&self, x: &T) -> bool;
1212 /// Returns true if `needle` is a prefix of the vector.
1213 fn starts_with(&self, needle: &[T]) -> bool;
1215 /// Returns true if `needle` is a suffix of the vector.
1216 fn ends_with(&self, needle: &[T]) -> bool;
1219 impl<'a,T:Eq> ImmutableEqVector<T> for &'a [T] {
1221 fn position_elem(&self, x: &T) -> Option<uint> {
1222 self.iter().position(|y| *x == *y)
1226 fn rposition_elem(&self, t: &T) -> Option<uint> {
1227 self.iter().rposition(|x| *x == *t)
1231 fn contains(&self, x: &T) -> bool {
1232 self.iter().any(|elt| *x == *elt)
1236 fn starts_with(&self, needle: &[T]) -> bool {
1237 let n = needle.len();
1238 self.len() >= n && needle == self.slice_to(n)
1242 fn ends_with(&self, needle: &[T]) -> bool {
1243 let (m, n) = (self.len(), needle.len());
1244 m >= n && needle == self.slice_from(m - n)
1248 /// Extension methods for vectors containing `TotalOrd` elements.
1249 pub trait ImmutableTotalOrdVector<T: TotalOrd> {
1251 * Binary search a sorted vector for a given element.
1253 * Returns the index of the element or None if not found.
1255 fn bsearch_elem(&self, x: &T) -> Option<uint>;
1258 impl<'a, T: TotalOrd> ImmutableTotalOrdVector<T> for &'a [T] {
1259 fn bsearch_elem(&self, x: &T) -> Option<uint> {
1260 self.bsearch(|p| p.cmp(x))
1264 /// Extension methods for vectors containing `Clone` elements.
1265 pub trait ImmutableCloneableVector<T> {
1267 * Partitions the vector into those that satisfies the predicate, and
1268 * those that do not.
1270 fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]);
1272 /// Create an iterator that yields every possible permutation of the
1273 /// vector in succession.
1274 fn permutations(self) -> Permutations<T>;
1277 impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
1279 fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]) {
1280 let mut lefts = ~[];
1281 let mut rights = ~[];
1283 for elt in self.iter() {
1285 lefts.push((*elt).clone());
1287 rights.push((*elt).clone());
1294 fn permutations(self) -> Permutations<T> {
1296 swaps: ElementSwaps::new(self.len()),
1303 /// Extension methods for owned vectors.
1304 pub trait OwnedVector<T> {
1305 /// Creates a consuming iterator, that is, one that moves each
1306 /// value out of the vector (from start to end). The vector cannot
1307 /// be used after calling this.
1312 /// let v = ~[~"a", ~"b"];
1313 /// for s in v.move_iter() {
1314 /// // s has type ~str, not &~str
1315 /// println!("{}", s);
1318 fn move_iter(self) -> MoveItems<T>;
1319 /// Creates a consuming iterator that moves out of the vector in
1321 fn move_rev_iter(self) -> RevMoveItems<T>;
1324 * Reserves capacity for exactly `n` elements in the given vector.
1326 * If the capacity for `self` is already equal to or greater than the requested
1327 * capacity, then no action is taken.
1331 * * n - The number of elements to reserve space for
1335 * This method always succeeds in reserving space for `n` elements, or it does
1338 fn reserve(&mut self, n: uint);
1340 * Reserves capacity for at least `n` elements in the given vector.
1342 * This function will over-allocate in order to amortize the allocation costs
1343 * in scenarios where the caller may need to repeatedly reserve additional
1346 * If the capacity for `self` is already equal to or greater than the requested
1347 * capacity, then no action is taken.
1351 * * n - The number of elements to reserve space for
1353 fn reserve_at_least(&mut self, n: uint);
1355 * Reserves capacity for at least `n` additional elements in the given vector.
1359 * Fails if the new required capacity overflows uint.
1361 * May also fail if `reserve` fails.
1363 fn reserve_additional(&mut self, n: uint);
1364 /// Returns the number of elements the vector can hold without reallocating.
1365 fn capacity(&self) -> uint;
1366 /// Shrink the capacity of the vector to match the length
1367 fn shrink_to_fit(&mut self);
1369 /// Append an element to a vector
1370 fn push(&mut self, t: T);
1371 /// Takes ownership of the vector `rhs`, moving all elements into
1372 /// the current vector. This does not copy any elements, and it is
1373 /// illegal to use the `rhs` vector after calling this method
1374 /// (because it is moved here).
1379 /// let mut a = ~[~1];
1380 /// a.push_all_move(~[~2, ~3, ~4]);
1381 /// assert!(a == ~[~1, ~2, ~3, ~4]);
1383 fn push_all_move(&mut self, rhs: ~[T]);
1384 /// Remove the last element from a vector and return it, or `None` if it is empty
1385 fn pop(&mut self) -> Option<T>;
1386 /// Removes the first element from a vector and return it, or `None` if it is empty
1387 fn shift(&mut self) -> Option<T>;
1388 /// Prepend an element to the vector
1389 fn unshift(&mut self, x: T);
1391 /// Insert an element at position i within v, shifting all
1392 /// elements after position i one position to the right.
1393 fn insert(&mut self, i: uint, x:T);
1395 /// Remove and return the element at position `i` within `v`,
1396 /// shifting all elements after position `i` one position to the
1397 /// left. Returns `None` if `i` is out of bounds.
1401 /// let mut v = ~[1, 2, 3];
1402 /// assert_eq!(v.remove(1), Some(2));
1403 /// assert_eq!(v, ~[1, 3]);
1405 /// assert_eq!(v.remove(4), None);
1406 /// // v is unchanged:
1407 /// assert_eq!(v, ~[1, 3]);
1409 fn remove(&mut self, i: uint) -> Option<T>;
1412 * Remove an element from anywhere in the vector and return it, replacing it
1413 * with the last element. This does not preserve ordering, but is O(1).
1415 * Fails if index >= length.
1417 fn swap_remove(&mut self, index: uint) -> T;
1419 /// Shorten a vector, dropping excess elements.
1420 fn truncate(&mut self, newlen: uint);
1423 * Like `filter()`, but in place. Preserves order of `v`. Linear time.
1425 fn retain(&mut self, f: |t: &T| -> bool);
1427 * Partitions the vector into those that satisfies the predicate, and
1428 * those that do not.
1430 fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]);
1433 * Expands a vector in place, initializing the new elements to the result of
1436 * Function `init_op` is called `n` times with the values [0..`n`)
1440 * * n - The number of elements to add
1441 * * init_op - A function to call to retrieve each appended element's
1444 fn grow_fn(&mut self, n: uint, op: |uint| -> T);
1447 * Sets the length of a vector
1449 * This will explicitly set the size of the vector, without actually
1450 * modifying its buffers, so it is up to the caller to ensure that
1451 * the vector is actually the specified size.
1453 unsafe fn set_len(&mut self, new_len: uint);
1456 impl<T> OwnedVector<T> for ~[T] {
1458 fn move_iter(self) -> MoveItems<T> {
1460 let iter = cast::transmute(self.iter());
1461 let ptr = cast::transmute(self);
1462 MoveItems { allocation: ptr, iter: iter }
1467 fn move_rev_iter(self) -> RevMoveItems<T> {
1468 self.move_iter().rev()
1471 fn reserve(&mut self, n: uint) {
1472 // Only make the (slow) call into the runtime if we have to
1473 if self.capacity() < n {
1475 let ptr: *mut *mut Vec<()> = cast::transmute(self);
1476 let alloc = n * mem::nonzero_size_of::<T>();
1477 let size = alloc + mem::size_of::<Vec<()>>();
1478 if alloc / mem::nonzero_size_of::<T>() != n || size < alloc {
1479 fail!("vector size is too large: {}", n);
1481 *ptr = realloc_raw(*ptr as *mut u8, size)
1483 (**ptr).alloc = alloc;
1489 fn reserve_at_least(&mut self, n: uint) {
1490 self.reserve(checked_next_power_of_two(n).unwrap_or(n));
1494 fn reserve_additional(&mut self, n: uint) {
1495 if self.capacity() - self.len() < n {
1496 match self.len().checked_add(&n) {
1497 None => fail!("vec::reserve_additional: `uint` overflow"),
1498 Some(new_cap) => self.reserve_at_least(new_cap)
1504 fn capacity(&self) -> uint {
1506 let repr: **Vec<()> = cast::transmute(self);
1507 (**repr).alloc / mem::nonzero_size_of::<T>()
1511 fn shrink_to_fit(&mut self) {
1513 let ptr: *mut *mut Vec<()> = cast::transmute(self);
1514 let alloc = (**ptr).fill;
1515 let size = alloc + mem::size_of::<Vec<()>>();
1516 *ptr = realloc_raw(*ptr as *mut u8, size) as *mut Vec<()>;
1517 (**ptr).alloc = alloc;
1522 fn push(&mut self, t: T) {
1524 let repr: **Vec<()> = cast::transmute(&mut *self);
1525 let fill = (**repr).fill;
1526 if (**repr).alloc <= fill {
1527 self.reserve_additional(1);
1533 // This doesn't bother to make sure we have space.
1534 #[inline] // really pretty please
1535 unsafe fn push_fast<T>(this: &mut ~[T], t: T) {
1536 let repr: **mut Vec<u8> = cast::transmute(this);
1537 let fill = (**repr).fill;
1538 (**repr).fill += mem::nonzero_size_of::<T>();
1539 let p = to_unsafe_ptr(&((**repr).data));
1540 let p = ptr::offset(p, fill as int) as *mut T;
1541 intrinsics::move_val_init(&mut(*p), t);
1546 fn push_all_move(&mut self, mut rhs: ~[T]) {
1547 let self_len = self.len();
1548 let rhs_len = rhs.len();
1549 let new_len = self_len + rhs_len;
1550 self.reserve_additional(rhs.len());
1551 unsafe { // Note: infallible.
1552 let self_p = self.as_mut_ptr();
1553 let rhs_p = rhs.as_ptr();
1554 ptr::copy_memory(ptr::mut_offset(self_p, self_len as int), rhs_p, rhs_len);
1555 self.set_len(new_len);
1560 fn pop(&mut self) -> Option<T> {
1564 let valptr = ptr::to_mut_unsafe_ptr(&mut self[ln - 1u]);
1566 self.set_len(ln - 1u);
1567 Some(ptr::read_ptr(&*valptr))
1575 fn shift(&mut self) -> Option<T> {
1580 fn unshift(&mut self, x: T) {
1584 fn insert(&mut self, i: uint, x: T) {
1585 let len = self.len();
1587 // space for the new element
1588 self.reserve_additional(1);
1590 unsafe { // infallible
1591 // The spot to put the new value
1592 let p = self.as_mut_ptr().offset(i as int);
1593 // Shift everything over to make space. (Duplicating the
1594 // `i`th element into two consecutive places.)
1595 ptr::copy_memory(p.offset(1), p, len - i);
1596 // Write it in, overwriting the first copy of the `i`th
1598 intrinsics::move_val_init(&mut *p, x);
1599 self.set_len(len + 1);
1603 fn remove(&mut self, i: uint) -> Option<T> {
1604 let len = self.len();
1606 unsafe { // infallible
1607 // the place we are taking from.
1608 let ptr = self.as_mut_ptr().offset(i as int);
1609 // copy it out, unsafely having a copy of the value on
1610 // the stack and in the vector at the same time.
1611 let ret = Some(ptr::read_ptr(ptr as *T));
1613 // Shift everything down to fill in that spot.
1614 ptr::copy_memory(ptr, ptr.offset(1), len - i - 1);
1615 self.set_len(len - 1);
1623 fn swap_remove(&mut self, index: uint) -> T {
1624 let ln = self.len();
1626 fail!("vec::swap_remove - index {} >= length {}", index, ln);
1629 self.swap(index, ln - 1);
1633 fn truncate(&mut self, newlen: uint) {
1634 let oldlen = self.len();
1635 assert!(newlen <= oldlen);
1638 let p = self.as_mut_ptr();
1639 // This loop is optimized out for non-drop types.
1640 for i in range(newlen, oldlen) {
1641 ptr::read_and_zero_ptr(p.offset(i as int));
1644 unsafe { self.set_len(newlen); }
1647 fn retain(&mut self, f: |t: &T| -> bool) {
1648 let len = self.len();
1649 let mut deleted: uint = 0;
1651 for i in range(0u, len) {
1654 } else if deleted > 0 {
1655 self.swap(i - deleted, i);
1660 self.truncate(len - deleted);
1665 fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]) {
1666 let mut lefts = ~[];
1667 let mut rights = ~[];
1669 for elt in self.move_iter() {
1679 fn grow_fn(&mut self, n: uint, op: |uint| -> T) {
1680 let new_len = self.len() + n;
1681 self.reserve_at_least(new_len);
1682 let mut i: uint = 0u;
1690 unsafe fn set_len(&mut self, new_len: uint) {
1691 let repr: **mut Vec<()> = cast::transmute(self);
1692 (**repr).fill = new_len * mem::nonzero_size_of::<T>();
1696 impl<T> Mutable for ~[T] {
1697 /// Clear the vector, removing all values.
1698 fn clear(&mut self) { self.truncate(0) }
1701 /// Extension methods for owned vectors containing `Clone` elements.
1702 pub trait OwnedCloneableVector<T:Clone> {
1703 /// Iterates over the slice `rhs`, copies each element, and then appends it to
1704 /// the vector provided `v`. The `rhs` vector is traversed in-order.
1709 /// let mut a = ~[1];
1710 /// a.push_all([2, 3, 4]);
1711 /// assert!(a == ~[1, 2, 3, 4]);
1713 fn push_all(&mut self, rhs: &[T]);
1716 * Expands a vector in place, initializing the new elements to a given value
1720 * * n - The number of elements to add
1721 * * initval - The value for the new elements
1723 fn grow(&mut self, n: uint, initval: &T);
1726 * Sets the value of a vector element at a given index, growing the vector as
1729 * Sets the element at position `index` to `val`. If `index` is past the end
1730 * of the vector, expands the vector by replicating `initval` to fill the
1731 * intervening space.
1733 fn grow_set(&mut self, index: uint, initval: &T, val: T);
1736 impl<T:Clone> OwnedCloneableVector<T> for ~[T] {
1738 fn push_all(&mut self, rhs: &[T]) {
1739 let new_len = self.len() + rhs.len();
1740 self.reserve(new_len);
1742 for elt in rhs.iter() {
1743 self.push((*elt).clone())
1746 fn grow(&mut self, n: uint, initval: &T) {
1747 let new_len = self.len() + n;
1748 self.reserve_at_least(new_len);
1749 let mut i: uint = 0u;
1752 self.push((*initval).clone());
1756 fn grow_set(&mut self, index: uint, initval: &T, val: T) {
1758 if index >= l { self.grow(index - l + 1u, initval); }
1763 /// Extension methods for owned vectors containing `Eq` elements.
1764 pub trait OwnedEqVector<T:Eq> {
1766 * Remove consecutive repeated elements from a vector; if the vector is
1767 * sorted, this removes all duplicates.
1769 fn dedup(&mut self);
1772 impl<T:Eq> OwnedEqVector<T> for ~[T] {
1773 fn dedup(&mut self) {
1775 // Although we have a mutable reference to `self`, we cannot make
1776 // *arbitrary* changes. The `Eq` comparisons could fail, so we
1777 // must ensure that the vector is in a valid state at all time.
1779 // The way that we handle this is by using swaps; we iterate
1780 // over all the elements, swapping as we go so that at the end
1781 // the elements we wish to keep are in the front, and those we
1782 // wish to reject are at the back. We can then truncate the
1783 // vector. This operation is still O(n).
1785 // Example: We start in this state, where `r` represents "next
1786 // read" and `w` represents "next_write`.
1789 // +---+---+---+---+---+---+
1790 // | 0 | 1 | 1 | 2 | 3 | 3 |
1791 // +---+---+---+---+---+---+
1794 // Comparing self[r] against self[w-1], tis is not a duplicate, so
1795 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1796 // r and w, leaving us with:
1799 // +---+---+---+---+---+---+
1800 // | 0 | 1 | 1 | 2 | 3 | 3 |
1801 // +---+---+---+---+---+---+
1804 // Comparing self[r] against self[w-1], this value is a duplicate,
1805 // so we increment `r` but leave everything else unchanged:
1808 // +---+---+---+---+---+---+
1809 // | 0 | 1 | 1 | 2 | 3 | 3 |
1810 // +---+---+---+---+---+---+
1813 // Comparing self[r] against self[w-1], this is not a duplicate,
1814 // so swap self[r] and self[w] and advance r and w:
1817 // +---+---+---+---+---+---+
1818 // | 0 | 1 | 2 | 1 | 3 | 3 |
1819 // +---+---+---+---+---+---+
1822 // Not a duplicate, repeat:
1825 // +---+---+---+---+---+---+
1826 // | 0 | 1 | 2 | 3 | 1 | 3 |
1827 // +---+---+---+---+---+---+
1830 // Duplicate, advance r. End of vec. Truncate to w.
1832 let ln = self.len();
1833 if ln < 1 { return; }
1835 // Avoid bounds checks by using unsafe pointers.
1836 let p = self.as_mut_ptr();
1841 let p_r = ptr::mut_offset(p, r as int);
1842 let p_wm1 = ptr::mut_offset(p, (w - 1) as int);
1845 let p_w = ptr::mut_offset(p_wm1, 1);
1846 util::swap(&mut *p_r, &mut *p_w);
1858 fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
1859 // warning: this wildly uses unsafe.
1860 static INSERTION: uint = 8;
1864 // allocate some memory to use as scratch memory, we keep the
1865 // length 0 so we can keep shallow copies of the contents of `v`
1866 // without risking the dtors running on an object twice if
1868 let mut working_space = with_capacity(2 * len);
1869 // these both are buffers of length `len`.
1870 let mut buf_dat = working_space.as_mut_ptr();
1871 let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
1874 let buf_v = v.as_ptr();
1876 // step 1. sort short runs with insertion sort. This takes the
1877 // values from `v` and sorts them into `buf_dat`, leaving that
1878 // with sorted runs of length INSERTION.
1880 // We could hardcode the sorting comparisons here, and we could
1881 // manipulate/step the pointers themselves, rather than repeatedly
1883 for start in range_step(0, len, INSERTION) {
1884 // start <= i <= len;
1885 for i in range(start, cmp::min(start + INSERTION, len)) {
1886 // j satisfies: start <= j <= i;
1887 let mut j = i as int;
1889 // `i` is in bounds.
1890 let read_ptr = buf_v.offset(i as int);
1892 // find where to insert, we need to do strict <,
1893 // rather than <=, to maintain stability.
1895 // start <= j - 1 < len, so .offset(j - 1) is in
1897 while j > start as int &&
1898 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1902 // shift everything to the right, to make space to
1903 // insert this value.
1905 // j + 1 could be `len` (for the last `i`), but in
1906 // that case, `i == j` so we don't copy. The
1907 // `.offset(j)` is always in bounds.
1908 ptr::copy_memory(buf_dat.offset(j + 1),
1911 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
1916 // step 2. merge the sorted runs.
1917 let mut width = INSERTION;
1919 // merge the sorted runs of length `width` in `buf_dat` two at
1920 // a time, placing the result in `buf_tmp`.
1922 // 0 <= start <= len.
1923 for start in range_step(0, len, 2 * width) {
1924 // manipulate pointers directly for speed (rather than
1925 // using a `for` loop with `range` and `.offset` inside
1928 // the end of the first run & start of the
1929 // second. Offset of `len` is defined, since this is
1930 // precisely one byte past the end of the object.
1931 let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
1932 // end of the second. Similar reasoning to the above re safety.
1933 let right_end_idx = cmp::min(start + 2 * width, len);
1934 let right_end = buf_dat.offset(right_end_idx as int);
1936 // the pointers to the elements under consideration
1937 // from the two runs.
1939 // both of these are in bounds.
1940 let mut left = buf_dat.offset(start as int);
1941 let mut right = right_start;
1943 // where we're putting the results, it is a run of
1944 // length `2*width`, so we step it once for each step
1945 // of either `left` or `right`. `buf_tmp` has length
1946 // `len`, so these are in bounds.
1947 let mut out = buf_tmp.offset(start as int);
1948 let out_end = buf_tmp.offset(right_end_idx as int);
1950 while out < out_end {
1951 // Either the left or the right run are exhausted,
1952 // so just copy the remainder from the other run
1953 // and move on; this gives a huge speed-up (order
1954 // of 25%) for mostly sorted vectors (the best
1956 if left == right_start {
1957 // the number remaining in this run.
1958 let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
1959 ptr::copy_nonoverlapping_memory(out, right, elems);
1961 } else if right == right_end {
1962 let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
1963 ptr::copy_nonoverlapping_memory(out, left, elems);
1967 // check which side is smaller, and that's the
1968 // next element for the new run.
1970 // `left < right_start` and `right < right_end`,
1971 // so these are valid.
1972 let to_copy = if compare(&*left, &*right) == Greater {
1977 ptr::copy_nonoverlapping_memory(out, to_copy, 1);
1983 util::swap(&mut buf_dat, &mut buf_tmp);
1988 // write the result to `v` in one go, so that there are never two copies
1989 // of the same object in `v`.
1991 ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), buf_dat, len);
1994 // increment the pointer, returning the old pointer.
1996 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1998 *ptr = ptr.offset(1);
2003 /// Extension methods for vectors such that their elements are
2005 pub trait MutableVector<'a, T> {
2006 /// Work with `self` as a mut slice.
2007 /// Primarily intended for getting a &mut [T] from a [T, ..N].
2008 fn as_mut_slice(self) -> &'a mut [T];
2010 /// Return a slice that points into another slice.
2011 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T];
2014 * Returns a slice of self from `start` to the end of the vec.
2016 * Fails when `start` points outside the bounds of self.
2018 fn mut_slice_from(self, start: uint) -> &'a mut [T];
2021 * Returns a slice of self from the start of the vec to `end`.
2023 * Fails when `end` points outside the bounds of self.
2025 fn mut_slice_to(self, end: uint) -> &'a mut [T];
2027 /// Returns an iterator that allows modifying each value
2028 fn mut_iter(self) -> MutItems<'a, T>;
2030 /// Returns a mutable pointer to the last item in the vector.
2031 fn mut_last(self) -> &'a mut T;
2033 /// Returns a reversed iterator that allows modifying each value
2034 fn mut_rev_iter(self) -> RevMutItems<'a, T>;
2036 /// Returns an iterator over the mutable subslices of the vector
2037 /// which are separated by elements that match `pred`. The
2038 /// matched element is not contained in the subslices.
2039 fn mut_split(self, pred: 'a |&T| -> bool) -> MutSplits<'a, T>;
2042 * Returns an iterator over `size` elements of the vector at a time.
2043 * The chunks are mutable and do not overlap. If `size` does not divide the
2044 * length of the vector, then the last chunk will not have length
2049 * Fails if `size` is 0.
2051 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T>;
2054 * Returns a mutable reference to the first element in this slice
2055 * and adjusts the slice in place so that it no longer contains
2056 * that element. O(1).
2061 * let head = &mut self[0];
2062 * *self = self.mut_slice_from(1);
2066 * Fails if slice is empty.
2068 fn mut_shift_ref(&mut self) -> &'a mut T;
2071 * Returns a mutable reference to the last element in this slice
2072 * and adjusts the slice in place so that it no longer contains
2073 * that element. O(1).
2078 * let tail = &mut self[self.len() - 1];
2079 * *self = self.mut_slice_to(self.len() - 1);
2083 * Fails if slice is empty.
2085 fn mut_pop_ref(&mut self) -> &'a mut T;
2087 /// Swaps two elements in a vector.
2089 /// Fails if `a` or `b` are out of bounds.
2093 /// * a - The index of the first element
2094 /// * b - The index of the second element
2099 /// let mut v = ["a", "b", "c", "d"];
2101 /// assert_eq!(v, ["a", "d", "c", "b"]);
2103 fn swap(self, a: uint, b: uint);
2106 /// Divides one `&mut` into two at an index.
2108 /// The first will contain all indices from `[0, mid)` (excluding
2109 /// the index `mid` itself) and the second will contain all
2110 /// indices from `[mid, len)` (excluding the index `len` itself).
2112 /// Fails if `mid > len`.
2117 /// let mut v = [1, 2, 3, 4, 5, 6];
2119 /// // scoped to restrict the lifetime of the borrows
2121 /// let (left, right) = v.mut_split_at(0);
2122 /// assert_eq!(left, &mut []);
2123 /// assert_eq!(right, &mut [1, 2, 3, 4, 5, 6]);
2127 /// let (left, right) = v.mut_split_at(2);
2128 /// assert_eq!(left, &mut [1, 2]);
2129 /// assert_eq!(right, &mut [3, 4, 5, 6]);
2133 /// let (left, right) = v.mut_split_at(6);
2134 /// assert_eq!(left, &mut [1, 2, 3, 4, 5, 6]);
2135 /// assert_eq!(right, &mut []);
2138 fn mut_split_at(self, mid: uint) -> (&'a mut [T],
2141 /// Reverse the order of elements in a vector, in place.
2146 /// let mut v = [1, 2, 3];
2148 /// assert_eq!(v, [3, 2, 1]);
2152 /// Sort the vector, in place, using `compare` to compare
2155 /// This sort is `O(n log n)` worst-case and stable, but allocates
2156 /// approximately `2 * n`, where `n` is the length of `self`.
2161 /// let mut v = [5i, 4, 1, 3, 2];
2162 /// v.sort_by(|a, b| a.cmp(b));
2163 /// assert_eq!(v, [1, 2, 3, 4, 5]);
2165 /// // reverse sorting
2166 /// v.sort_by(|a, b| b.cmp(a));
2167 /// assert_eq!(v, [5, 4, 3, 2, 1]);
2169 fn sort_by(self, compare: |&T, &T| -> Ordering);
2172 * Consumes `src` and moves as many elements as it can into `self`
2173 * from the range [start,end).
2175 * Returns the number of elements copied (the shorter of self.len()
2180 * * src - A mutable vector of `T`
2181 * * start - The index into `src` to start copying from
2182 * * end - The index into `str` to stop copying from
2184 fn move_from(self, src: ~[T], start: uint, end: uint) -> uint;
2186 /// Returns an unsafe mutable pointer to the element in index
2187 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T;
2189 /// Return an unsafe mutable pointer to the vector's buffer.
2191 /// The caller must ensure that the vector outlives the pointer this
2192 /// function returns, or else it will end up pointing to garbage.
2194 /// Modifying the vector may cause its buffer to be reallocated, which
2195 /// would also make any pointers to it invalid.
2197 fn as_mut_ptr(self) -> *mut T;
2199 /// Unsafely sets the element in index to the value.
2201 /// This performs no bounds checks, and it is undefined behaviour
2202 /// if `index` is larger than the length of `self`. However, it
2203 /// does run the destructor at `index`. It is equivalent to
2204 /// `self[index] = val`.
2209 /// let mut v = ~[~"foo", ~"bar", ~"baz"];
2212 /// // `~"baz"` is deallocated.
2213 /// v.unsafe_set(2, ~"qux");
2215 /// // Out of bounds: could cause a crash, or overwriting
2216 /// // other data, or something else.
2217 /// // v.unsafe_set(10, ~"oops");
2220 unsafe fn unsafe_set(self, index: uint, val: T);
2222 /// Unchecked vector index assignment. Does not drop the
2223 /// old value and hence is only suitable when the vector
2224 /// is newly allocated.
2229 /// let mut v = [~"foo", ~"bar"];
2231 /// // memory leak! `~"bar"` is not deallocated.
2232 /// unsafe { v.init_elem(1, ~"baz"); }
2234 unsafe fn init_elem(self, i: uint, val: T);
2236 /// Copies raw bytes from `src` to `self`.
2238 /// This does not run destructors on the overwritten elements, and
2239 /// ignores move semantics. `self` and `src` must not
2240 /// overlap. Fails if `self` is shorter than `src`.
2241 unsafe fn copy_memory(self, src: &[T]);
2244 impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
2246 fn as_mut_slice(self) -> &'a mut [T] { self }
2248 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T] {
2249 assert!(start <= end);
2250 assert!(end <= self.len());
2252 cast::transmute(Slice {
2253 data: self.as_mut_ptr().offset(start as int) as *T,
2260 fn mut_slice_from(self, start: uint) -> &'a mut [T] {
2261 let len = self.len();
2262 self.mut_slice(start, len)
2266 fn mut_slice_to(self, end: uint) -> &'a mut [T] {
2267 self.mut_slice(0, end)
2271 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
2273 let len = self.len();
2274 let self2: &'a mut [T] = cast::transmute_copy(&self);
2275 (self.mut_slice(0, mid), self2.mut_slice(mid, len))
2280 fn mut_iter(self) -> MutItems<'a, T> {
2282 let p = self.as_mut_ptr();
2283 if mem::size_of::<T>() == 0 {
2285 end: (p as uint + self.len()) as *mut T,
2286 marker: marker::ContravariantLifetime::<'a>}
2289 end: p.offset(self.len() as int),
2290 marker: marker::ContravariantLifetime::<'a>}
2296 fn mut_last(self) -> &'a mut T {
2297 let len = self.len();
2298 if len == 0 { fail!("mut_last: empty vector") }
2303 fn mut_rev_iter(self) -> RevMutItems<'a, T> {
2304 self.mut_iter().rev()
2308 fn mut_split(self, pred: 'a |&T| -> bool) -> MutSplits<'a, T> {
2309 MutSplits { v: self, pred: pred, finished: false }
2313 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T> {
2314 assert!(chunk_size > 0);
2315 MutChunks { v: self, chunk_size: chunk_size }
2318 fn mut_shift_ref(&mut self) -> &'a mut T {
2320 let s: &mut Slice<T> = cast::transmute(self);
2321 cast::transmute_mut(&*raw::shift_ptr(s))
2325 fn mut_pop_ref(&mut self) -> &'a mut T {
2327 let s: &mut Slice<T> = cast::transmute(self);
2328 cast::transmute_mut(&*raw::pop_ptr(s))
2332 fn swap(self, a: uint, b: uint) {
2334 // Can't take two mutable loans from one vector, so instead just cast
2335 // them to their raw pointers to do the swap
2336 let pa: *mut T = &mut self[a];
2337 let pb: *mut T = &mut self[b];
2338 ptr::swap_ptr(pa, pb);
2343 let mut i: uint = 0;
2344 let ln = self.len();
2346 self.swap(i, ln - i - 1);
2352 fn sort_by(self, compare: |&T, &T| -> Ordering) {
2353 merge_sort(self, compare)
2357 fn move_from(self, mut src: ~[T], start: uint, end: uint) -> uint {
2358 for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
2361 cmp::min(self.len(), end-start)
2365 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T {
2366 cast::transmute(ptr::mut_offset(self.repr().data as *mut T, index as int))
2370 fn as_mut_ptr(self) -> *mut T {
2371 self.repr().data as *mut T
2375 unsafe fn unsafe_set(self, index: uint, val: T) {
2376 *self.unsafe_mut_ref(index) = val;
2380 unsafe fn init_elem(self, i: uint, val: T) {
2381 intrinsics::move_val_init(&mut (*self.as_mut_ptr().offset(i as int)), val);
2385 unsafe fn copy_memory(self, src: &[T]) {
2386 let len_src = src.len();
2387 assert!(self.len() >= len_src);
2388 ptr::copy_nonoverlapping_memory(self.as_mut_ptr(), src.as_ptr(), len_src)
2392 /// Trait for &[T] where T is Cloneable
2393 pub trait MutableCloneableVector<T> {
2394 /// Copies as many elements from `src` as it can into `self` (the
2395 /// shorter of `self.len()` and `src.len()`). Returns the number
2396 /// of elements copied.
2401 /// use std::vec::MutableCloneableVector;
2403 /// let mut dst = [0, 0, 0];
2404 /// let src = [1, 2];
2406 /// assert_eq!(dst.copy_from(src), 2);
2407 /// assert_eq!(dst, [1, 2, 0]);
2409 /// let src2 = [3, 4, 5, 6];
2410 /// assert_eq!(dst.copy_from(src2), 3);
2411 /// assert_eq!(dst, [3, 4, 5]);
2413 fn copy_from(self, &[T]) -> uint;
2416 impl<'a, T:Clone> MutableCloneableVector<T> for &'a mut [T] {
2418 fn copy_from(self, src: &[T]) -> uint {
2419 for (a, b) in self.mut_iter().zip(src.iter()) {
2422 cmp::min(self.len(), src.len())
2426 /// Methods for mutable vectors with orderable elements, such as
2427 /// in-place sorting.
2428 pub trait MutableTotalOrdVector<T> {
2429 /// Sort the vector, in place.
2431 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
2436 /// let mut v = [-5, 4, 1, -3, 2];
2439 /// assert_eq!(v, [-5, -3, 1, 2, 4]);
2443 impl<'a, T: TotalOrd> MutableTotalOrdVector<T> for &'a mut [T] {
2446 self.sort_by(|a,b| a.cmp(b))
2451 * Constructs a vector from an unsafe pointer to a buffer
2455 * * ptr - An unsafe pointer to a buffer of `T`
2456 * * elts - The number of elements in the buffer
2458 // Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
2459 pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
2460 raw::from_buf_raw(ptr, elts)
2463 /// Unsafe operations
2467 use vec::{with_capacity, MutableVector, OwnedVector};
2468 use unstable::raw::Slice;
2471 * Form a slice from a pointer and length (as a number of units,
2475 pub unsafe fn buf_as_slice<T,U>(p: *T, len: uint, f: |v: &[T]| -> U)
2477 f(cast::transmute(Slice {
2484 * Form a slice from a pointer and length (as a number of units,
2488 pub unsafe fn mut_buf_as_slice<T,
2492 f: |v: &mut [T]| -> U)
2494 f(cast::transmute(Slice {
2501 * Constructs a vector from an unsafe pointer to a buffer
2505 * * ptr - An unsafe pointer to a buffer of `T`
2506 * * elts - The number of elements in the buffer
2508 // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
2510 pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
2511 let mut dst = with_capacity(elts);
2513 ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
2518 * Returns a pointer to first element in slice and adjusts
2519 * slice so it no longer contains that element. Fails if
2520 * slice is empty. O(1).
2522 pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> *T {
2523 if slice.len == 0 { fail!("shift on empty slice"); }
2524 let head: *T = slice.data;
2525 slice.data = ptr::offset(slice.data, 1);
2531 * Returns a pointer to last element in slice and adjusts
2532 * slice so it no longer contains that element. Fails if
2533 * slice is empty. O(1).
2535 pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> *T {
2536 if slice.len == 0 { fail!("pop on empty slice"); }
2537 let tail: *T = ptr::offset(slice.data, (slice.len - 1) as int);
2543 /// Operations on `[u8]`.
2545 use container::Container;
2546 use vec::{MutableVector, OwnedVector, ImmutableVector};
2550 /// A trait for operations on mutable `[u8]`s.
2551 pub trait MutableByteVector {
2552 /// Sets all bytes of the receiver to the given value.
2553 fn set_memory(self, value: u8);
2556 impl<'a> MutableByteVector for &'a mut [u8] {
2558 fn set_memory(self, value: u8) {
2559 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
2563 /// Copies data from `src` to `dst`
2565 /// `src` and `dst` must not overlap. Fails if the length of `dst`
2566 /// is less than the length of `src`.
2568 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
2569 // Bound checks are done at .copy_memory.
2570 unsafe { dst.copy_memory(src) }
2574 * Allocate space in `dst` and append the data to `src`.
2577 pub fn push_bytes(dst: &mut ~[u8], src: &[u8]) {
2578 let old_len = dst.len();
2579 dst.reserve_additional(src.len());
2581 ptr::copy_memory(dst.as_mut_ptr().offset(old_len as int), src.as_ptr(), src.len());
2582 dst.set_len(old_len + src.len());
2587 impl<A: Clone> Clone for ~[A] {
2589 fn clone(&self) -> ~[A] {
2590 self.iter().map(|item| item.clone()).collect()
2593 fn clone_from(&mut self, source: &~[A]) {
2594 if self.len() < source.len() {
2595 *self = source.clone()
2597 self.truncate(source.len());
2598 for (x, y) in self.mut_iter().zip(source.iter()) {
2605 impl<A: DeepClone> DeepClone for ~[A] {
2607 fn deep_clone(&self) -> ~[A] {
2608 self.iter().map(|item| item.deep_clone()).collect()
2611 fn deep_clone_from(&mut self, source: &~[A]) {
2612 if self.len() < source.len() {
2613 *self = source.deep_clone()
2615 self.truncate(source.len());
2616 for (x, y) in self.mut_iter().zip(source.iter()) {
2617 x.deep_clone_from(y);
2623 // This works because every lifetime is a sub-lifetime of 'static
2624 impl<'a, A> Default for &'a [A] {
2625 fn default() -> &'a [A] { &'a [] }
2628 impl<A> Default for ~[A] {
2629 fn default() -> ~[A] { ~[] }
2632 impl<A> Default for @[A] {
2633 fn default() -> @[A] { @[] }
2636 macro_rules! iterator {
2637 (struct $name:ident -> $ptr:ty, $elem:ty) => {
2638 /// An iterator for iterating over a vector.
2639 pub struct $name<'a, T> {
2642 priv marker: marker::ContravariantLifetime<'a>,
2645 impl<'a, T> Iterator<$elem> for $name<'a, T> {
2647 fn next(&mut self) -> Option<$elem> {
2648 // could be implemented with slices, but this avoids bounds checks
2650 if self.ptr == self.end {
2654 self.ptr = if mem::size_of::<T>() == 0 {
2655 // purposefully don't use 'ptr.offset' because for
2656 // vectors with 0-size elements this would return the
2658 cast::transmute(self.ptr as uint + 1)
2663 Some(cast::transmute(old))
2669 fn size_hint(&self) -> (uint, Option<uint>) {
2670 let diff = (self.end as uint) - (self.ptr as uint);
2671 let exact = diff / mem::nonzero_size_of::<T>();
2672 (exact, Some(exact))
2676 impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
2678 fn next_back(&mut self) -> Option<$elem> {
2679 // could be implemented with slices, but this avoids bounds checks
2681 if self.end == self.ptr {
2684 self.end = if mem::size_of::<T>() == 0 {
2685 // See above for why 'ptr.offset' isn't used
2686 cast::transmute(self.end as uint - 1)
2690 Some(cast::transmute(self.end))
2698 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
2700 fn indexable(&self) -> uint {
2701 let (exact, _) = self.size_hint();
2706 fn idx(&self, index: uint) -> Option<&'a T> {
2708 if index < self.indexable() {
2709 cast::transmute(self.ptr.offset(index as int))
2717 iterator!{struct Items -> *T, &'a T}
2718 pub type RevItems<'a, T> = Rev<Items<'a, T>>;
2720 impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
2721 impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
2723 impl<'a, T> Clone for Items<'a, T> {
2724 fn clone(&self) -> Items<'a, T> { *self }
2727 iterator!{struct MutItems -> *mut T, &'a mut T}
2728 pub type RevMutItems<'a, T> = Rev<MutItems<'a, T>>;
2730 /// An iterator over the subslices of the vector which are separated
2731 /// by elements that match `pred`.
2732 pub struct MutSplits<'a, T> {
2733 priv v: &'a mut [T],
2734 priv pred: 'a |t: &T| -> bool,
2738 impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
2740 fn next(&mut self) -> Option<&'a mut [T]> {
2741 if self.finished { return None; }
2743 match self.v.iter().position(|x| (self.pred)(x)) {
2745 self.finished = true;
2746 let tmp = util::replace(&mut self.v, &mut []);
2747 let len = tmp.len();
2748 let (head, tail) = tmp.mut_split_at(len);
2753 let tmp = util::replace(&mut self.v, &mut []);
2754 let (head, tail) = tmp.mut_split_at(idx);
2755 self.v = tail.mut_slice_from(1);
2762 fn size_hint(&self) -> (uint, Option<uint>) {
2766 // if the predicate doesn't match anything, we yield one slice
2767 // if it matches every element, we yield len+1 empty slices.
2768 (1, Some(self.v.len() + 1))
2773 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
2775 fn next_back(&mut self) -> Option<&'a mut [T]> {
2776 if self.finished { return None; }
2778 match self.v.iter().rposition(|x| (self.pred)(x)) {
2780 self.finished = true;
2781 let tmp = util::replace(&mut self.v, &mut []);
2785 let tmp = util::replace(&mut self.v, &mut []);
2786 let (head, tail) = tmp.mut_split_at(idx);
2788 Some(tail.mut_slice_from(1))
2794 /// An iterator over a vector in (non-overlapping) mutable chunks (`size` elements at a time). When
2795 /// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be
2797 pub struct MutChunks<'a, T> {
2798 priv v: &'a mut [T],
2799 priv chunk_size: uint
2802 impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
2804 fn next(&mut self) -> Option<&'a mut [T]> {
2805 if self.v.len() == 0 {
2808 let sz = cmp::min(self.v.len(), self.chunk_size);
2809 let tmp = util::replace(&mut self.v, &mut []);
2810 let (head, tail) = tmp.mut_split_at(sz);
2817 fn size_hint(&self) -> (uint, Option<uint>) {
2818 if self.v.len() == 0 {
2821 let (n, rem) = self.v.len().div_rem(&self.chunk_size);
2822 let n = if rem > 0 { n + 1 } else { n };
2828 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
2830 fn next_back(&mut self) -> Option<&'a mut [T]> {
2831 if self.v.len() == 0 {
2834 let remainder = self.v.len() % self.chunk_size;
2835 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2836 let tmp = util::replace(&mut self.v, &mut []);
2837 let tmp_len = tmp.len();
2838 let (head, tail) = tmp.mut_split_at(tmp_len - sz);
2845 /// An iterator that moves out of a vector.
2846 pub struct MoveItems<T> {
2847 priv allocation: *mut u8, // the block of memory allocated for the vector
2848 priv iter: Items<'static, T>
2851 impl<T> Iterator<T> for MoveItems<T> {
2853 fn next(&mut self) -> Option<T> {
2855 self.iter.next().map(|x| ptr::read_ptr(x))
2860 fn size_hint(&self) -> (uint, Option<uint>) {
2861 self.iter.size_hint()
2865 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
2867 fn next_back(&mut self) -> Option<T> {
2869 self.iter.next_back().map(|x| ptr::read_ptr(x))
2874 #[unsafe_destructor]
2875 impl<T> Drop for MoveItems<T> {
2876 fn drop(&mut self) {
2877 // destroy the remaining elements
2880 exchange_free(self.allocation as *u8)
2885 /// An iterator that moves out of a vector in reverse order.
2886 pub type RevMoveItems<T> = Rev<MoveItems<T>>;
2888 impl<A> FromIterator<A> for ~[A] {
2889 fn from_iterator<T: Iterator<A>>(iterator: &mut T) -> ~[A] {
2890 let (lower, _) = iterator.size_hint();
2891 let mut xs = with_capacity(lower);
2892 for x in *iterator {
2899 impl<A> Extendable<A> for ~[A] {
2900 fn extend<T: Iterator<A>>(&mut self, iterator: &mut T) {
2901 let (lower, _) = iterator.size_hint();
2902 let len = self.len();
2903 self.reserve(len + lower);
2904 for x in *iterator {
2916 use rand::{Rng, task_rng};
2918 fn square(n: uint) -> uint { n * n }
2920 fn square_ref(n: &uint) -> uint { square(*n) }
2922 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
2925 fn test_unsafe_ptrs() {
2927 // Test on-stack copy-from-buf.
2929 let mut ptr = a.as_ptr();
2930 let b = from_buf(ptr, 3u);
2931 assert_eq!(b.len(), 3u);
2932 assert_eq!(b[0], 1);
2933 assert_eq!(b[1], 2);
2934 assert_eq!(b[2], 3);
2936 // Test on-heap copy-from-buf.
2937 let c = ~[1, 2, 3, 4, 5];
2939 let d = from_buf(ptr, 5u);
2940 assert_eq!(d.len(), 5u);
2941 assert_eq!(d[0], 1);
2942 assert_eq!(d[1], 2);
2943 assert_eq!(d[2], 3);
2944 assert_eq!(d[3], 4);
2945 assert_eq!(d[4], 5);
2951 // Test on-stack from_fn.
2952 let mut v = from_fn(3u, square);
2953 assert_eq!(v.len(), 3u);
2954 assert_eq!(v[0], 0u);
2955 assert_eq!(v[1], 1u);
2956 assert_eq!(v[2], 4u);
2958 // Test on-heap from_fn.
2959 v = from_fn(5u, square);
2960 assert_eq!(v.len(), 5u);
2961 assert_eq!(v[0], 0u);
2962 assert_eq!(v[1], 1u);
2963 assert_eq!(v[2], 4u);
2964 assert_eq!(v[3], 9u);
2965 assert_eq!(v[4], 16u);
2969 fn test_from_elem() {
2970 // Test on-stack from_elem.
2971 let mut v = from_elem(2u, 10u);
2972 assert_eq!(v.len(), 2u);
2973 assert_eq!(v[0], 10u);
2974 assert_eq!(v[1], 10u);
2976 // Test on-heap from_elem.
2977 v = from_elem(6u, 20u);
2978 assert_eq!(v[0], 20u);
2979 assert_eq!(v[1], 20u);
2980 assert_eq!(v[2], 20u);
2981 assert_eq!(v[3], 20u);
2982 assert_eq!(v[4], 20u);
2983 assert_eq!(v[5], 20u);
2987 fn test_is_empty() {
2988 let xs: [int, ..0] = [];
2989 assert!(xs.is_empty());
2990 assert!(![0].is_empty());
2994 fn test_len_divzero() {
2996 let v0 : &[Z] = &[];
2997 let v1 : &[Z] = &[[]];
2998 let v2 : &[Z] = &[[], []];
2999 assert_eq!(mem::size_of::<Z>(), 0);
3000 assert_eq!(v0.len(), 0);
3001 assert_eq!(v1.len(), 1);
3002 assert_eq!(v2.len(), 2);
3008 assert_eq!(a.get(1), None);
3010 assert_eq!(a.get(1).unwrap(), &12);
3012 assert_eq!(a.get(1).unwrap(), &12);
3018 assert_eq!(a.head(), None);
3020 assert_eq!(a.head().unwrap(), &11);
3022 assert_eq!(a.head().unwrap(), &11);
3028 assert_eq!(a.tail(), &[]);
3030 assert_eq!(a.tail(), &[12]);
3035 fn test_tail_empty() {
3036 let a: ~[int] = ~[];
3042 let mut a = ~[11, 12, 13];
3043 assert_eq!(a.tailn(0), &[11, 12, 13]);
3045 assert_eq!(a.tailn(2), &[13]);
3050 fn test_tailn_empty() {
3051 let a: ~[int] = ~[];
3058 assert_eq!(a.init(), &[]);
3060 assert_eq!(a.init(), &[11]);
3065 fn test_init_empty() {
3066 let a: ~[int] = ~[];
3072 let mut a = ~[11, 12, 13];
3073 assert_eq!(a.initn(0), &[11, 12, 13]);
3075 assert_eq!(a.initn(2), &[11]);
3080 fn test_initn_empty() {
3081 let a: ~[int] = ~[];
3088 assert_eq!(a.last(), None);
3090 assert_eq!(a.last().unwrap(), &11);
3092 assert_eq!(a.last().unwrap(), &12);
3097 // Test fixed length vector.
3098 let vec_fixed = [1, 2, 3, 4];
3099 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
3100 assert_eq!(v_a.len(), 3u);
3101 assert_eq!(v_a[0], 2);
3102 assert_eq!(v_a[1], 3);
3103 assert_eq!(v_a[2], 4);
3106 let vec_stack = &[1, 2, 3];
3107 let v_b = vec_stack.slice(1u, 3u).to_owned();
3108 assert_eq!(v_b.len(), 2u);
3109 assert_eq!(v_b[0], 2);
3110 assert_eq!(v_b[1], 3);
3112 // Test on managed heap.
3113 let vec_managed = @[1, 2, 3, 4, 5];
3114 let v_c = vec_managed.slice(0u, 3u).to_owned();
3115 assert_eq!(v_c.len(), 3u);
3116 assert_eq!(v_c[0], 1);
3117 assert_eq!(v_c[1], 2);
3118 assert_eq!(v_c[2], 3);
3120 // Test on exchange heap.
3121 let vec_unique = ~[1, 2, 3, 4, 5, 6];
3122 let v_d = vec_unique.slice(1u, 6u).to_owned();
3123 assert_eq!(v_d.len(), 5u);
3124 assert_eq!(v_d[0], 2);
3125 assert_eq!(v_d[1], 3);
3126 assert_eq!(v_d[2], 4);
3127 assert_eq!(v_d[3], 5);
3128 assert_eq!(v_d[4], 6);
3132 fn test_slice_from() {
3133 let vec = &[1, 2, 3, 4];
3134 assert_eq!(vec.slice_from(0), vec);
3135 assert_eq!(vec.slice_from(2), &[3, 4]);
3136 assert_eq!(vec.slice_from(4), &[]);
3140 fn test_slice_to() {
3141 let vec = &[1, 2, 3, 4];
3142 assert_eq!(vec.slice_to(4), vec);
3143 assert_eq!(vec.slice_to(2), &[1, 2]);
3144 assert_eq!(vec.slice_to(0), &[]);
3152 assert_eq!(v.len(), 0);
3153 assert_eq!(e, Some(5));
3155 assert_eq!(f, None);
3157 assert_eq!(g, None);
3161 fn test_swap_remove() {
3162 let mut v = ~[1, 2, 3, 4, 5];
3163 let mut e = v.swap_remove(0);
3164 assert_eq!(v.len(), 4);
3166 assert_eq!(v[0], 5);
3167 e = v.swap_remove(3);
3168 assert_eq!(v.len(), 3);
3170 assert_eq!(v[0], 5);
3171 assert_eq!(v[1], 2);
3172 assert_eq!(v[2], 3);
3176 fn test_swap_remove_noncopyable() {
3177 // Tests that we don't accidentally run destructors twice.
3178 let mut v = ~[::unstable::sync::Exclusive::new(()),
3179 ::unstable::sync::Exclusive::new(()),
3180 ::unstable::sync::Exclusive::new(())];
3181 let mut _e = v.swap_remove(0);
3182 assert_eq!(v.len(), 2);
3183 _e = v.swap_remove(1);
3184 assert_eq!(v.len(), 1);
3185 _e = v.swap_remove(0);
3186 assert_eq!(v.len(), 0);
3191 // Test on-stack push().
3194 assert_eq!(v.len(), 1u);
3195 assert_eq!(v[0], 1);
3197 // Test on-heap push().
3199 assert_eq!(v.len(), 2u);
3200 assert_eq!(v[0], 1);
3201 assert_eq!(v[1], 2);
3206 // Test on-stack grow().
3209 assert_eq!(v.len(), 2u);
3210 assert_eq!(v[0], 1);
3211 assert_eq!(v[1], 1);
3213 // Test on-heap grow().
3215 assert_eq!(v.len(), 5u);
3216 assert_eq!(v[0], 1);
3217 assert_eq!(v[1], 1);
3218 assert_eq!(v[2], 2);
3219 assert_eq!(v[3], 2);
3220 assert_eq!(v[4], 2);
3226 v.grow_fn(3u, square);
3227 assert_eq!(v.len(), 3u);
3228 assert_eq!(v[0], 0u);
3229 assert_eq!(v[1], 1u);
3230 assert_eq!(v[2], 4u);
3234 fn test_grow_set() {
3235 let mut v = ~[1, 2, 3];
3236 v.grow_set(4u, &4, 5);
3237 assert_eq!(v.len(), 5u);
3238 assert_eq!(v[0], 1);
3239 assert_eq!(v[1], 2);
3240 assert_eq!(v[2], 3);
3241 assert_eq!(v[3], 4);
3242 assert_eq!(v[4], 5);
3246 fn test_truncate() {
3247 let mut v = ~[~6,~5,~4];
3249 assert_eq!(v.len(), 1);
3250 assert_eq!(*(v[0]), 6);
3251 // If the unsafe block didn't drop things properly, we blow up here.
3256 let mut v = ~[~6,~5,~4];
3258 assert_eq!(v.len(), 0);
3259 // If the unsafe block didn't drop things properly, we blow up here.
3264 fn case(a: ~[uint], b: ~[uint]) {
3272 case(~[1,2,3], ~[1,2,3]);
3273 case(~[1,1,2,3], ~[1,2,3]);
3274 case(~[1,2,2,3], ~[1,2,3]);
3275 case(~[1,2,3,3], ~[1,2,3]);
3276 case(~[1,1,2,2,2,3,3], ~[1,2,3]);
3280 fn test_dedup_unique() {
3281 let mut v0 = ~[~1, ~1, ~2, ~3];
3283 let mut v1 = ~[~1, ~2, ~2, ~3];
3285 let mut v2 = ~[~1, ~2, ~3, ~3];
3288 * If the ~pointers were leaked or otherwise misused, valgrind and/or
3289 * rustrt should raise errors.
3294 fn test_dedup_shared() {
3295 let mut v0 = ~[~1, ~1, ~2, ~3];
3297 let mut v1 = ~[~1, ~2, ~2, ~3];
3299 let mut v2 = ~[~1, ~2, ~3, ~3];
3302 * If the pointers were leaked or otherwise misused, valgrind and/or
3303 * rustrt should raise errors.
3309 // Test on-stack map.
3310 let v = &[1u, 2u, 3u];
3311 let mut w = v.map(square_ref);
3312 assert_eq!(w.len(), 3u);
3313 assert_eq!(w[0], 1u);
3314 assert_eq!(w[1], 4u);
3315 assert_eq!(w[2], 9u);
3317 // Test on-heap map.
3318 let v = ~[1u, 2u, 3u, 4u, 5u];
3319 w = v.map(square_ref);
3320 assert_eq!(w.len(), 5u);
3321 assert_eq!(w[0], 1u);
3322 assert_eq!(w[1], 4u);
3323 assert_eq!(w[2], 9u);
3324 assert_eq!(w[3], 16u);
3325 assert_eq!(w[4], 25u);
3330 let mut v = ~[1, 2, 3, 4, 5];
3332 assert_eq!(v, ~[1, 3, 5]);
3336 fn test_zip_unzip() {
3337 let z1 = ~[(1, 4), (2, 5), (3, 6)];
3339 let (left, right) = unzip(z1.iter().map(|&x| x));
3341 assert_eq!((1, 4), (left[0], right[0]));
3342 assert_eq!((2, 5), (left[1], right[1]));
3343 assert_eq!((3, 6), (left[2], right[2]));
3347 fn test_element_swaps() {
3348 let mut v = [1, 2, 3];
3349 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
3352 0 => assert_eq!(v, [1, 3, 2]),
3353 1 => assert_eq!(v, [3, 1, 2]),
3354 2 => assert_eq!(v, [3, 2, 1]),
3355 3 => assert_eq!(v, [2, 3, 1]),
3356 4 => assert_eq!(v, [2, 1, 3]),
3357 5 => assert_eq!(v, [1, 2, 3]),
3364 fn test_permutations() {
3367 let v: [int, ..0] = [];
3368 let mut it = v.permutations();
3369 assert_eq!(it.next(), None);
3373 let mut it = v.permutations();
3374 assert_eq!(it.next(), None);
3378 let mut it = v.permutations();
3379 assert_eq!(it.next(), Some(~[1,2,3]));
3380 assert_eq!(it.next(), Some(~[1,3,2]));
3381 assert_eq!(it.next(), Some(~[3,1,2]));
3382 assert_eq!(it.next(), Some(~[3,2,1]));
3383 assert_eq!(it.next(), Some(~[2,3,1]));
3384 assert_eq!(it.next(), Some(~[2,1,3]));
3385 assert_eq!(it.next(), None);
3388 // check that we have N! unique permutations
3389 let mut set = hashmap::HashSet::new();
3390 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
3391 for perm in v.permutations() {
3394 assert_eq!(set.len(), 2 * 3 * 4 * 5 * 6);
3399 fn test_position_elem() {
3400 assert!([].position_elem(&1).is_none());
3402 let v1 = ~[1, 2, 3, 3, 2, 5];
3403 assert_eq!(v1.position_elem(&1), Some(0u));
3404 assert_eq!(v1.position_elem(&2), Some(1u));
3405 assert_eq!(v1.position_elem(&5), Some(5u));
3406 assert!(v1.position_elem(&4).is_none());
3410 fn test_bsearch_elem() {
3411 assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
3412 assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
3413 assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
3414 assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
3415 assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
3417 assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
3418 assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
3419 assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
3420 assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
3422 assert_eq!([2,4,6,8].bsearch_elem(&1), None);
3423 assert_eq!([2,4,6,8].bsearch_elem(&5), None);
3424 assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
3425 assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
3427 assert_eq!([2,4,6].bsearch_elem(&1), None);
3428 assert_eq!([2,4,6].bsearch_elem(&5), None);
3429 assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
3430 assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
3432 assert_eq!([2,4].bsearch_elem(&1), None);
3433 assert_eq!([2,4].bsearch_elem(&5), None);
3434 assert_eq!([2,4].bsearch_elem(&2), Some(0));
3435 assert_eq!([2,4].bsearch_elem(&4), Some(1));
3437 assert_eq!([2].bsearch_elem(&1), None);
3438 assert_eq!([2].bsearch_elem(&5), None);
3439 assert_eq!([2].bsearch_elem(&2), Some(0));
3441 assert_eq!([].bsearch_elem(&1), None);
3442 assert_eq!([].bsearch_elem(&5), None);
3444 assert!([1,1,1,1,1].bsearch_elem(&1) != None);
3445 assert!([1,1,1,1,2].bsearch_elem(&1) != None);
3446 assert!([1,1,1,2,2].bsearch_elem(&1) != None);
3447 assert!([1,1,2,2,2].bsearch_elem(&1) != None);
3448 assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
3450 assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
3451 assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
3456 let mut v: ~[int] = ~[10, 20];
3457 assert_eq!(v[0], 10);
3458 assert_eq!(v[1], 20);
3460 assert_eq!(v[0], 20);
3461 assert_eq!(v[1], 10);
3463 let mut v3: ~[int] = ~[];
3465 assert!(v3.is_empty());
3470 for len in range(4u, 25) {
3471 for _ in range(0, 100) {
3472 let mut v = task_rng().gen_vec::<uint>(len);
3473 let mut v1 = v.clone();
3476 assert!(v.windows(2).all(|w| w[0] <= w[1]));
3478 v1.sort_by(|a, b| a.cmp(b));
3479 assert!(v1.windows(2).all(|w| w[0] <= w[1]));
3481 v1.sort_by(|a, b| b.cmp(a));
3482 assert!(v1.windows(2).all(|w| w[0] >= w[1]));
3486 // shouldn't fail/crash
3487 let mut v: [uint, .. 0] = [];
3490 let mut v = [0xDEADBEEF];
3492 assert_eq!(v, [0xDEADBEEF]);
3496 fn test_sort_stability() {
3497 for len in range(4, 25) {
3498 for _ in range(0 , 10) {
3499 let mut counts = [0, .. 10];
3501 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
3502 // where the first item of each tuple is random, but
3503 // the second item represents which occurrence of that
3504 // number this element is, i.e. the second elements
3505 // will occur in sorted order.
3506 let mut v = range(0, len).map(|_| {
3507 let n = task_rng().gen::<uint>() % 10;
3512 // only sort on the first element, so an unstable sort
3513 // may mix up the counts.
3514 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
3516 // this comparison includes the count (the second item
3517 // of the tuple), so elements with equal first items
3518 // will need to be ordered with increasing
3519 // counts... i.e. exactly asserting that this sort is
3521 assert!(v.windows(2).all(|w| w[0] <= w[1]));
3527 fn test_partition() {
3528 assert_eq!((~[]).partition(|x: &int| *x < 3), (~[], ~[]));
3529 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
3530 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 2), (~[1], ~[2, 3]));
3531 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
3535 fn test_partitioned() {
3536 assert_eq!(([]).partitioned(|x: &int| *x < 3), (~[], ~[]))
3537 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
3538 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (~[1], ~[2, 3]));
3539 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
3544 let v: [~[int], ..0] = [];
3545 assert_eq!(v.concat_vec(), ~[]);
3546 assert_eq!([~[1], ~[2,3]].concat_vec(), ~[1, 2, 3]);
3548 assert_eq!([&[1], &[2,3]].concat_vec(), ~[1, 2, 3]);
3553 let v: [~[int], ..0] = [];
3554 assert_eq!(v.connect_vec(&0), ~[]);
3555 assert_eq!([~[1], ~[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
3556 assert_eq!([~[1], ~[2], ~[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
3558 assert_eq!(v.connect_vec(&0), ~[]);
3559 assert_eq!([&[1], &[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
3560 assert_eq!([&[1], &[2], &[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
3565 let mut x = ~[1, 2, 3];
3566 assert_eq!(x.shift(), Some(1));
3567 assert_eq!(&x, &~[2, 3]);
3568 assert_eq!(x.shift(), Some(2));
3569 assert_eq!(x.shift(), Some(3));
3570 assert_eq!(x.shift(), None);
3571 assert_eq!(x.len(), 0);
3576 let mut x = ~[1, 2, 3];
3578 assert_eq!(x, ~[0, 1, 2, 3]);
3583 let mut a = ~[1, 2, 4];
3585 assert_eq!(a, ~[1, 2, 3, 4]);
3587 let mut a = ~[1, 2, 3];
3589 assert_eq!(a, ~[0, 1, 2, 3]);
3591 let mut a = ~[1, 2, 3];
3593 assert_eq!(a, ~[1, 2, 3, 4]);
3597 assert_eq!(a, ~[1]);
3602 fn test_insert_oob() {
3603 let mut a = ~[1, 2, 3];
3609 let mut a = ~[1,2,3,4];
3611 assert_eq!(a.remove(2), Some(3));
3612 assert_eq!(a, ~[1,2,4]);
3614 assert_eq!(a.remove(2), Some(4));
3615 assert_eq!(a, ~[1,2]);
3617 assert_eq!(a.remove(2), None);
3618 assert_eq!(a, ~[1,2]);
3620 assert_eq!(a.remove(0), Some(1));
3621 assert_eq!(a, ~[2]);
3623 assert_eq!(a.remove(0), Some(2));
3626 assert_eq!(a.remove(0), None);
3627 assert_eq!(a.remove(10), None);
3631 fn test_capacity() {
3632 let mut v = ~[0u64];
3634 assert_eq!(v.capacity(), 10u);
3635 let mut v = ~[0u32];
3637 assert_eq!(v.capacity(), 10u);
3642 let v = ~[1, 2, 3, 4, 5];
3643 let v = v.slice(1u, 3u);
3644 assert_eq!(v.len(), 2u);
3645 assert_eq!(v[0], 2);
3646 assert_eq!(v[1], 3);
3652 fn test_from_fn_fail() {
3654 if v == 50 { fail!() }
3661 fn test_from_elem_fail() {
3667 boxes: (~int, Rc<int>)
3671 fn clone(&self) -> S {
3672 let s = unsafe { cast::transmute_mut(self) };
3674 if s.f == 10 { fail!() }
3675 S { f: s.f, boxes: s.boxes.clone() }
3679 let s = S { f: 0, boxes: (~0, Rc::new(0)) };
3680 let _ = from_elem(100, s);
3685 fn test_build_fail() {
3687 build(None, |push| {
3688 push((~0, Rc::new(0)));
3689 push((~0, Rc::new(0)));
3690 push((~0, Rc::new(0)));
3691 push((~0, Rc::new(0)));
3698 fn test_grow_fn_fail() {
3701 v.grow_fn(100, |i| {
3711 fn test_map_fail() {
3713 let v = [(~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0))];
3726 fn test_flat_map_fail() {
3728 let v = [(~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0))];
3730 flat_map(v, |_elt| {
3741 fn test_permute_fail() {
3743 let v = [(~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0))];
3745 for _ in v.permutations() {
3755 fn test_copy_memory_oob() {
3757 let mut a = [1, 2, 3, 4];
3758 let b = [1, 2, 3, 4, 5];
3764 fn test_total_ord() {
3765 [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
3766 [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
3767 [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
3768 [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
3769 [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
3773 fn test_iterator() {
3775 let xs = [1, 2, 5, 10, 11];
3776 let mut it = xs.iter();
3777 assert_eq!(it.size_hint(), (5, Some(5)));
3778 assert_eq!(it.next().unwrap(), &1);
3779 assert_eq!(it.size_hint(), (4, Some(4)));
3780 assert_eq!(it.next().unwrap(), &2);
3781 assert_eq!(it.size_hint(), (3, Some(3)));
3782 assert_eq!(it.next().unwrap(), &5);
3783 assert_eq!(it.size_hint(), (2, Some(2)));
3784 assert_eq!(it.next().unwrap(), &10);
3785 assert_eq!(it.size_hint(), (1, Some(1)));
3786 assert_eq!(it.next().unwrap(), &11);
3787 assert_eq!(it.size_hint(), (0, Some(0)));
3788 assert!(it.next().is_none());
3792 fn test_random_access_iterator() {
3794 let xs = [1, 2, 5, 10, 11];
3795 let mut it = xs.iter();
3797 assert_eq!(it.indexable(), 5);
3798 assert_eq!(it.idx(0).unwrap(), &1);
3799 assert_eq!(it.idx(2).unwrap(), &5);
3800 assert_eq!(it.idx(4).unwrap(), &11);
3801 assert!(it.idx(5).is_none());
3803 assert_eq!(it.next().unwrap(), &1);
3804 assert_eq!(it.indexable(), 4);
3805 assert_eq!(it.idx(0).unwrap(), &2);
3806 assert_eq!(it.idx(3).unwrap(), &11);
3807 assert!(it.idx(4).is_none());
3809 assert_eq!(it.next().unwrap(), &2);
3810 assert_eq!(it.indexable(), 3);
3811 assert_eq!(it.idx(1).unwrap(), &10);
3812 assert!(it.idx(3).is_none());
3814 assert_eq!(it.next().unwrap(), &5);
3815 assert_eq!(it.indexable(), 2);
3816 assert_eq!(it.idx(1).unwrap(), &11);
3818 assert_eq!(it.next().unwrap(), &10);
3819 assert_eq!(it.indexable(), 1);
3820 assert_eq!(it.idx(0).unwrap(), &11);
3821 assert!(it.idx(1).is_none());
3823 assert_eq!(it.next().unwrap(), &11);
3824 assert_eq!(it.indexable(), 0);
3825 assert!(it.idx(0).is_none());
3827 assert!(it.next().is_none());
3831 fn test_iter_size_hints() {
3833 let mut xs = [1, 2, 5, 10, 11];
3834 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
3835 assert_eq!(xs.rev_iter().size_hint(), (5, Some(5)));
3836 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
3837 assert_eq!(xs.mut_rev_iter().size_hint(), (5, Some(5)));
3841 fn test_iter_clone() {
3843 let mut it = xs.iter();
3845 let mut jt = it.clone();
3846 assert_eq!(it.next(), jt.next());
3847 assert_eq!(it.next(), jt.next());
3848 assert_eq!(it.next(), jt.next());
3852 fn test_mut_iterator() {
3854 let mut xs = [1, 2, 3, 4, 5];
3855 for x in xs.mut_iter() {
3858 assert_eq!(xs, [2, 3, 4, 5, 6])
3862 fn test_rev_iterator() {
3865 let xs = [1, 2, 5, 10, 11];
3866 let ys = [11, 10, 5, 2, 1];
3868 for &x in xs.rev_iter() {
3869 assert_eq!(x, ys[i]);
3876 fn test_mut_rev_iterator() {
3878 let mut xs = [1u, 2, 3, 4, 5];
3879 for (i,x) in xs.mut_rev_iter().enumerate() {
3882 assert_eq!(xs, [5, 5, 5, 5, 5])
3886 fn test_move_iterator() {
3888 let xs = ~[1u,2,3,4,5];
3889 assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
3893 fn test_move_rev_iterator() {
3895 let xs = ~[1u,2,3,4,5];
3896 assert_eq!(xs.move_rev_iter().fold(0, |a: uint, b: uint| 10*a + b), 54321);
3900 fn test_splitator() {
3901 let xs = &[1i,2,3,4,5];
3903 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3904 ~[&[1], &[3], &[5]]);
3905 assert_eq!(xs.split(|x| *x == 1).collect::<~[&[int]]>(),
3906 ~[&[], &[2,3,4,5]]);
3907 assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(),
3908 ~[&[1,2,3,4], &[]]);
3909 assert_eq!(xs.split(|x| *x == 10).collect::<~[&[int]]>(),
3911 assert_eq!(xs.split(|_| true).collect::<~[&[int]]>(),
3912 ~[&[], &[], &[], &[], &[], &[]]);
3914 let xs: &[int] = &[];
3915 assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3919 fn test_splitnator() {
3920 let xs = &[1i,2,3,4,5];
3922 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3924 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3926 assert_eq!(xs.splitn(3, |_| true).collect::<~[&[int]]>(),
3927 ~[&[], &[], &[], &[4,5]]);
3929 let xs: &[int] = &[];
3930 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3934 fn test_rsplitator() {
3935 let xs = &[1i,2,3,4,5];
3937 assert_eq!(xs.rsplit(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3938 ~[&[5], &[3], &[1]]);
3939 assert_eq!(xs.rsplit(|x| *x == 1).collect::<~[&[int]]>(),
3940 ~[&[2,3,4,5], &[]]);
3941 assert_eq!(xs.rsplit(|x| *x == 5).collect::<~[&[int]]>(),
3942 ~[&[], &[1,2,3,4]]);
3943 assert_eq!(xs.rsplit(|x| *x == 10).collect::<~[&[int]]>(),
3946 let xs: &[int] = &[];
3947 assert_eq!(xs.rsplit(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3951 fn test_rsplitnator() {
3952 let xs = &[1,2,3,4,5];
3954 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3956 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3958 assert_eq!(xs.rsplitn(3, |_| true).collect::<~[&[int]]>(),
3959 ~[&[], &[], &[], &[1,2]]);
3961 let xs: &[int] = &[];
3962 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3966 fn test_windowsator() {
3967 let v = &[1i,2,3,4];
3969 assert_eq!(v.windows(2).collect::<~[&[int]]>(), ~[&[1,2], &[2,3], &[3,4]]);
3970 assert_eq!(v.windows(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[2,3,4]]);
3971 assert!(v.windows(6).next().is_none());
3976 fn test_windowsator_0() {
3977 let v = &[1i,2,3,4];
3978 let _it = v.windows(0);
3982 fn test_chunksator() {
3983 let v = &[1i,2,3,4,5];
3985 assert_eq!(v.chunks(2).collect::<~[&[int]]>(), ~[&[1i,2], &[3,4], &[5]]);
3986 assert_eq!(v.chunks(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[4,5]]);
3987 assert_eq!(v.chunks(6).collect::<~[&[int]]>(), ~[&[1i,2,3,4,5]]);
3989 assert_eq!(v.chunks(2).rev().collect::<~[&[int]]>(), ~[&[5i], &[3,4], &[1,2]]);
3990 let it = v.chunks(2);
3991 assert_eq!(it.indexable(), 3);
3992 assert_eq!(it.idx(0).unwrap(), &[1,2]);
3993 assert_eq!(it.idx(1).unwrap(), &[3,4]);
3994 assert_eq!(it.idx(2).unwrap(), &[5]);
3995 assert_eq!(it.idx(3), None);
4000 fn test_chunksator_0() {
4001 let v = &[1i,2,3,4];
4002 let _it = v.chunks(0);
4006 fn test_move_from() {
4007 let mut a = [1,2,3,4,5];
4009 assert_eq!(a.move_from(b, 0, 3), 3);
4010 assert_eq!(a, [6,7,8,4,5]);
4011 let mut a = [7,2,8,1];
4012 let b = ~[3,1,4,1,5,9];
4013 assert_eq!(a.move_from(b, 0, 6), 4);
4014 assert_eq!(a, [3,1,4,1]);
4015 let mut a = [1,2,3,4];
4016 let b = ~[5,6,7,8,9,0];
4017 assert_eq!(a.move_from(b, 2, 3), 1);
4018 assert_eq!(a, [7,2,3,4]);
4019 let mut a = [1,2,3,4,5];
4020 let b = ~[5,6,7,8,9,0];
4021 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
4022 assert_eq!(a, [1,2,6,7,5]);
4026 fn test_copy_from() {
4027 let mut a = [1,2,3,4,5];
4029 assert_eq!(a.copy_from(b), 3);
4030 assert_eq!(a, [6,7,8,4,5]);
4031 let mut c = [7,2,8,1];
4032 let d = [3,1,4,1,5,9];
4033 assert_eq!(c.copy_from(d), 4);
4034 assert_eq!(c, [3,1,4,1]);
4038 fn test_reverse_part() {
4039 let mut values = [1,2,3,4,5];
4040 values.mut_slice(1, 4).reverse();
4041 assert_eq!(values, [1,4,3,2,5]);
4045 fn test_vec_default() {
4046 use default::Default;
4049 let v: $ty = Default::default();
4050 assert!(v.is_empty());
4060 fn test_bytes_set_memory() {
4061 use vec::bytes::MutableByteVector;
4062 let mut values = [1u8,2,3,4,5];
4063 values.mut_slice(0,5).set_memory(0xAB);
4064 assert_eq!(values, [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
4065 values.mut_slice(2,4).set_memory(0xFF);
4066 assert_eq!(values, [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
4071 fn test_overflow_does_not_cause_segfault() {
4080 fn test_overflow_does_not_cause_segfault_managed() {
4082 let mut v = ~[Rc::new(1)];
4088 fn test_mut_split_at() {
4089 let mut values = [1u8,2,3,4,5];
4091 let (left, right) = values.mut_split_at(2);
4092 assert_eq!(left.slice(0, left.len()), [1, 2]);
4093 for p in left.mut_iter() {
4097 assert_eq!(right.slice(0, right.len()), [3, 4, 5]);
4098 for p in right.mut_iter() {
4103 assert_eq!(values, [2, 3, 5, 6, 7]);
4106 #[deriving(Clone, Eq)]
4110 fn test_iter_zero_sized() {
4111 let mut v = ~[Foo, Foo, Foo];
4112 assert_eq!(v.len(), 3);
4121 for f in v.slice(1, 3).iter() {
4127 for f in v.mut_iter() {
4133 for f in v.move_iter() {
4137 assert_eq!(cnt, 11);
4139 let xs = ~[Foo, Foo, Foo];
4140 assert_eq!(format!("{:?}", xs.slice(0, 2).to_owned()),
4141 ~"~[vec::tests::Foo, vec::tests::Foo]");
4143 let xs: [Foo, ..3] = [Foo, Foo, Foo];
4144 assert_eq!(format!("{:?}", xs.slice(0, 2).to_owned()),
4145 ~"~[vec::tests::Foo, vec::tests::Foo]");
4147 for f in xs.iter() {
4155 fn test_shrink_to_fit() {
4156 let mut xs = ~[0, 1, 2, 3];
4157 for i in range(4, 100) {
4160 assert_eq!(xs.capacity(), 128);
4162 assert_eq!(xs.capacity(), 100);
4163 assert_eq!(xs, range(0, 100).to_owned_vec());
4167 fn test_starts_with() {
4168 assert!(bytes!("foobar").starts_with(bytes!("foo")));
4169 assert!(!bytes!("foobar").starts_with(bytes!("oob")));
4170 assert!(!bytes!("foobar").starts_with(bytes!("bar")));
4171 assert!(!bytes!("foo").starts_with(bytes!("foobar")));
4172 assert!(!bytes!("bar").starts_with(bytes!("foobar")));
4173 assert!(bytes!("foobar").starts_with(bytes!("foobar")));
4174 let empty: &[u8] = [];
4175 assert!(empty.starts_with(empty));
4176 assert!(!empty.starts_with(bytes!("foo")));
4177 assert!(bytes!("foobar").starts_with(empty));
4181 fn test_ends_with() {
4182 assert!(bytes!("foobar").ends_with(bytes!("bar")));
4183 assert!(!bytes!("foobar").ends_with(bytes!("oba")));
4184 assert!(!bytes!("foobar").ends_with(bytes!("foo")));
4185 assert!(!bytes!("foo").ends_with(bytes!("foobar")));
4186 assert!(!bytes!("bar").ends_with(bytes!("foobar")));
4187 assert!(bytes!("foobar").ends_with(bytes!("foobar")));
4188 let empty: &[u8] = [];
4189 assert!(empty.ends_with(empty));
4190 assert!(!empty.ends_with(bytes!("foo")));
4191 assert!(bytes!("foobar").ends_with(empty));
4195 fn test_shift_ref() {
4196 let mut x: &[int] = [1, 2, 3, 4, 5];
4197 let h = x.shift_ref();
4199 assert_eq!(x.len(), 4);
4200 assert_eq!(x[0], 2);
4201 assert_eq!(x[3], 5);
4206 fn test_shift_ref_empty() {
4207 let mut x: &[int] = [];
4213 let mut x: &[int] = [1, 2, 3, 4, 5];
4214 let h = x.pop_ref();
4216 assert_eq!(x.len(), 4);
4217 assert_eq!(x[0], 1);
4218 assert_eq!(x[3], 4);
4223 fn test_pop_ref_empty() {
4224 let mut x: &[int] = [];
4229 fn test_mut_splitator() {
4230 let mut xs = [0,1,0,2,3,0,0,4,5,0];
4231 assert_eq!(xs.mut_split(|x| *x == 0).len(), 6);
4232 for slice in xs.mut_split(|x| *x == 0) {
4235 assert_eq!(xs, [0,1,0,3,2,0,0,5,4,0]);
4237 let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
4238 for slice in xs.mut_split(|x| *x == 0).take(5) {
4241 assert_eq!(xs, [0,1,0,3,2,0,0,5,4,0,6,7]);
4245 fn test_mut_splitator_rev() {
4246 let mut xs = [1,2,0,3,4,0,0,5,6,0];
4247 for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
4250 assert_eq!(xs, [1,2,0,4,3,0,0,6,5,0]);
4254 fn test_mut_chunks() {
4255 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
4256 for (i, chunk) in v.mut_chunks(3).enumerate() {
4257 for x in chunk.mut_iter() {
4261 let result = [0u8, 0, 0, 1, 1, 1, 2];
4262 assert_eq!(v, result);
4266 fn test_mut_chunks_rev() {
4267 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
4268 for (i, chunk) in v.mut_chunks(3).rev().enumerate() {
4269 for x in chunk.mut_iter() {
4273 let result = [2u8, 2, 2, 1, 1, 1, 0];
4274 assert_eq!(v, result);
4279 fn test_mut_chunks_0() {
4280 let mut v = [1, 2, 3, 4];
4281 let _it = v.mut_chunks(0);
4285 fn test_mut_shift_ref() {
4286 let mut x: &mut [int] = [1, 2, 3, 4, 5];
4287 let h = x.mut_shift_ref();
4289 assert_eq!(x.len(), 4);
4290 assert_eq!(x[0], 2);
4291 assert_eq!(x[3], 5);
4296 fn test_mut_shift_ref_empty() {
4297 let mut x: &mut [int] = [];
4302 fn test_mut_pop_ref() {
4303 let mut x: &mut [int] = [1, 2, 3, 4, 5];
4304 let h = x.mut_pop_ref();
4306 assert_eq!(x.len(), 4);
4307 assert_eq!(x[0], 1);
4308 assert_eq!(x[3], 4);
4313 fn test_mut_pop_ref_empty() {
4314 let mut x: &mut [int] = [];
4321 use extra::test::BenchHarness;
4325 use rand::{weak_rng, Rng};
4329 fn iterator(bh: &mut BenchHarness) {
4330 // peculiar numbers to stop LLVM from optimising the summation
4332 let v = vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
4339 // sum == 11806, to stop dead code elimination.
4340 if sum == 0 {fail!()}
4345 fn mut_iterator(bh: &mut BenchHarness) {
4346 let mut v = vec::from_elem(100, 0);
4350 for x in v.mut_iter() {
4358 fn add(bh: &mut BenchHarness) {
4359 let xs: &[int] = [5, ..10];
4360 let ys: &[int] = [5, ..10];
4367 fn concat(bh: &mut BenchHarness) {
4368 let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect());
4370 let _ = xss.concat_vec();
4375 fn connect(bh: &mut BenchHarness) {
4376 let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect());
4378 let _ = xss.connect_vec(&0);
4383 fn push(bh: &mut BenchHarness) {
4384 let mut vec: ~[uint] = ~[0u];
4391 fn starts_with_same_vector(bh: &mut BenchHarness) {
4392 let vec: ~[uint] = vec::from_fn(100, |i| i);
4394 vec.starts_with(vec);
4399 fn starts_with_single_element(bh: &mut BenchHarness) {
4400 let vec: ~[uint] = ~[0u];
4402 vec.starts_with(vec);
4407 fn starts_with_diff_one_element_at_end(bh: &mut BenchHarness) {
4408 let vec: ~[uint] = vec::from_fn(100, |i| i);
4409 let mut match_vec: ~[uint] = vec::from_fn(99, |i| i);
4412 vec.starts_with(match_vec);
4417 fn ends_with_same_vector(bh: &mut BenchHarness) {
4418 let vec: ~[uint] = vec::from_fn(100, |i| i);
4425 fn ends_with_single_element(bh: &mut BenchHarness) {
4426 let vec: ~[uint] = ~[0u];
4433 fn ends_with_diff_one_element_at_beginning(bh: &mut BenchHarness) {
4434 let vec: ~[uint] = vec::from_fn(100, |i| i);
4435 let mut match_vec: ~[uint] = vec::from_fn(100, |i| i);
4438 vec.starts_with(match_vec);
4443 fn contains_last_element(bh: &mut BenchHarness) {
4444 let vec: ~[uint] = vec::from_fn(100, |i| i);
4451 fn zero_1kb_from_elem(bh: &mut BenchHarness) {
4453 let _v: ~[u8] = vec::from_elem(1024, 0u8);
4458 fn zero_1kb_set_memory(bh: &mut BenchHarness) {
4460 let mut v: ~[u8] = vec::with_capacity(1024);
4462 let vp = v.as_mut_ptr();
4463 ptr::set_memory(vp, 0, 1024);
4470 fn zero_1kb_fixed_repeat(bh: &mut BenchHarness) {
4472 let _v: ~[u8] = ~[0u8, ..1024];
4477 fn zero_1kb_loop_set(bh: &mut BenchHarness) {
4478 // Slower because the { len, cap, [0 x T] }* repr allows a pointer to the length
4479 // field to be aliased (in theory) and prevents LLVM from optimizing loads away.
4481 let mut v: ~[u8] = vec::with_capacity(1024);
4485 for i in range(0, 1024) {
4492 fn zero_1kb_mut_iter(bh: &mut BenchHarness) {
4494 let mut v: ~[u8] = vec::with_capacity(1024);
4498 for x in v.mut_iter() {
4505 fn random_inserts(bh: &mut BenchHarness) {
4506 let mut rng = weak_rng();
4508 let mut v = vec::from_elem(30, (0u, 0u));
4509 for _ in range(0, 100) {
4511 v.insert(rng.gen::<uint>() % (l + 1),
4517 fn random_removes(bh: &mut BenchHarness) {
4518 let mut rng = weak_rng();
4520 let mut v = vec::from_elem(130, (0u, 0u));
4521 for _ in range(0, 100) {
4523 v.remove(rng.gen::<uint>() % l);
4529 fn sort_random_small(bh: &mut BenchHarness) {
4530 let mut rng = weak_rng();
4532 let mut v: ~[u64] = rng.gen_vec(5);
4535 bh.bytes = 5 * mem::size_of::<u64>() as u64;
4539 fn sort_random_medium(bh: &mut BenchHarness) {
4540 let mut rng = weak_rng();
4542 let mut v: ~[u64] = rng.gen_vec(100);
4545 bh.bytes = 100 * mem::size_of::<u64>() as u64;
4549 fn sort_random_large(bh: &mut BenchHarness) {
4550 let mut rng = weak_rng();
4552 let mut v: ~[u64] = rng.gen_vec(10000);
4555 bh.bytes = 10000 * mem::size_of::<u64>() as u64;
4559 fn sort_sorted(bh: &mut BenchHarness) {
4560 let mut v = vec::from_fn(10000, |i| i);
4564 bh.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;