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)];
107 use clone::{Clone, DeepClone};
108 use container::{Container, Mutable};
109 use cmp::{Eq, TotalOrd, Ordering, Less, Equal, Greater};
111 use default::Default;
114 use num::{CheckedAdd, Saturating, checked_next_power_of_two, div_rem};
115 use option::{None, Option, Some};
118 use rt::global_heap::{malloc_raw, realloc_raw, exchange_free};
119 use result::{Ok, Err};
124 use unstable::finally::try_finally;
125 use 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();
140 |i, ()| while *i < n_elts {
142 &mut(*p.offset(*i as int)),
152 * Creates and initializes an owned vector.
154 * Creates an owned vector of size `n_elts` and initializes the elements
157 pub fn from_elem<T:Clone>(n_elts: uint, t: T) -> ~[T] {
158 // FIXME (#7136): manually inline from_fn for 2x plus speedup (sadly very
159 // important, from_elem is a bottleneck in borrowck!). Unfortunately it
160 // still is substantially slower than using the unsafe
161 // vec::with_capacity/ptr::set_memory for primitive types.
163 let mut v = with_capacity(n_elts);
164 let p = v.as_mut_ptr();
168 |i, ()| while *i < n_elts {
170 &mut(*p.offset(*i as int)),
179 /// Creates a new vector with a capacity of `capacity`
181 pub fn with_capacity<T>(capacity: uint) -> ~[T] {
183 let alloc = capacity * mem::nonzero_size_of::<T>();
184 let size = alloc + mem::size_of::<Vec<()>>();
185 if alloc / mem::nonzero_size_of::<T>() != capacity || size < alloc {
186 fail!("vector size is too large: {}", capacity);
188 let ptr = malloc_raw(size) as *mut Vec<()>;
189 (*ptr).alloc = alloc;
196 * Builds a vector by calling a provided function with an argument
197 * function that pushes an element to the back of a vector.
198 * The initial capacity for the vector may optionally be specified.
202 * * size - An option, maybe containing initial size of the vector to reserve
203 * * builder - A function that will construct the vector. It receives
204 * as an argument a function that will push an element
205 * onto the vector being constructed.
208 pub fn build<A>(size: Option<uint>, builder: |push: |v: A||) -> ~[A] {
209 let mut vec = with_capacity(size.unwrap_or(4));
210 builder(|x| vec.push(x));
215 * Converts a pointer to A into a slice of length 1 (without copying).
217 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
219 transmute(Slice { data: s, len: 1 })
224 * Converts a pointer to A into a slice of length 1 (without copying).
226 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
228 let ptr: *A = transmute(s);
229 transmute(Slice { data: ptr, len: 1 })
233 /// An iterator over the slices of a vector separated by elements that
234 /// match a predicate function.
235 pub struct Splits<'a, T> {
238 priv pred: 'a |t: &T| -> bool,
242 impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
244 fn next(&mut self) -> Option<&'a [T]> {
245 if self.finished { return None; }
248 self.finished = true;
252 match self.v.iter().position(|x| (self.pred)(x)) {
254 self.finished = true;
258 let ret = Some(self.v.slice(0, idx));
259 self.v = self.v.slice(idx + 1, self.v.len());
267 fn size_hint(&self) -> (uint, Option<uint>) {
271 // if the predicate doesn't match anything, we yield one slice
272 // if it matches every element, we yield N+1 empty slices where
273 // N is either the number of elements or the number of splits.
274 match (self.v.len(), self.n) {
275 (0,_) => (1, Some(1)),
276 (_,0) => (1, Some(1)),
277 (l,n) => (1, cmp::min(l,n).checked_add(&1u))
282 /// An iterator over the slices of a vector separated by elements that
283 /// match a predicate function, from back to front.
284 pub struct RevSplits<'a, T> {
287 priv pred: 'a |t: &T| -> bool,
291 impl<'a, T> Iterator<&'a [T]> for RevSplits<'a, T> {
293 fn next(&mut self) -> Option<&'a [T]> {
294 if self.finished { return None; }
297 self.finished = true;
301 let pred = &mut self.pred;
302 match self.v.iter().rposition(|x| (*pred)(x)) {
304 self.finished = true;
308 let ret = Some(self.v.slice(idx + 1, self.v.len()));
309 self.v = self.v.slice(0, idx);
317 fn size_hint(&self) -> (uint, Option<uint>) {
321 match (self.v.len(), self.n) {
322 (0,_) => (1, Some(1)),
323 (_,0) => (1, Some(1)),
324 (l,n) => (1, cmp::min(l,n).checked_add(&1u))
331 /// Iterates over the `rhs` vector, copying each element and appending it to the
332 /// `lhs`. Afterwards, the `lhs` is then returned for use again.
334 pub fn append<T:Clone>(lhs: ~[T], rhs: &[T]) -> ~[T] {
340 /// Appends one element to the vector provided. The vector itself is then
341 /// returned for use again.
343 pub fn append_one<T>(lhs: ~[T], x: T) -> ~[T] {
349 // Functional utilities
352 * Apply a function to each element of a vector and return a concatenation
353 * of each result vector
355 pub fn flat_map<T, U>(v: &[T], f: |t: &T| -> ~[U]) -> ~[U] {
356 let mut result = ~[];
357 for elem in v.iter() { result.push_all_move(f(elem)); }
361 #[allow(missing_doc)]
362 pub trait VectorVector<T> {
363 // FIXME #5898: calling these .concat and .connect conflicts with
364 // StrVector::con{cat,nect}, since they have generic contents.
365 /// Flattens a vector of vectors of T into a single vector of T.
366 fn concat_vec(&self) -> ~[T];
368 /// Concatenate a vector of vectors, placing a given separator between each.
369 fn connect_vec(&self, sep: &T) -> ~[T];
372 impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
373 fn concat_vec(&self) -> ~[T] {
374 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
375 let mut result = with_capacity(size);
376 for v in self.iter() {
377 result.push_all(v.as_slice())
382 fn connect_vec(&self, sep: &T) -> ~[T] {
383 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
384 let mut result = with_capacity(size + self.len());
385 let mut first = true;
386 for v in self.iter() {
387 if first { first = false } else { result.push(sep.clone()) }
388 result.push_all(v.as_slice())
395 * Convert an iterator of pairs into a pair of vectors.
397 * Returns a tuple containing two vectors where the i-th element of the first
398 * vector contains the first element of the i-th tuple of the input iterator,
399 * and the i-th element of the second vector contains the second element
400 * of the i-th tuple of the input iterator.
402 pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
403 let (lo, _) = iter.size_hint();
404 let mut ts = with_capacity(lo);
405 let mut us = with_capacity(lo);
413 /// An Iterator that yields the element swaps needed to produce
414 /// a sequence of all possible permutations for an indexed sequence of
415 /// elements. Each permutation is only a single swap apart.
417 /// The Steinhaus–Johnson–Trotter algorithm is used.
419 /// Generates even and odd permutations alternately.
421 /// The last generated swap is always (0, 1), and it returns the
422 /// sequence to its initial order.
423 pub struct ElementSwaps {
424 priv sdir: ~[SizeDirection],
425 /// If true, emit the last swap that returns the sequence to initial state
426 priv emit_reset: bool,
430 /// Create an `ElementSwaps` iterator for a sequence of `length` elements
431 pub fn new(length: uint) -> ElementSwaps {
432 // Initialize `sdir` with a direction that position should move in
433 // (all negative at the beginning) and the `size` of the
434 // element (equal to the original index).
437 sdir: range(0, length)
438 .map(|i| SizeDirection{ size: i, dir: Neg })
444 enum Direction { Pos, Neg }
446 /// An Index and Direction together
447 struct SizeDirection {
452 impl Iterator<(uint, uint)> for ElementSwaps {
454 fn next(&mut self) -> Option<(uint, uint)> {
455 fn new_pos(i: uint, s: Direction) -> uint {
456 i + match s { Pos => 1, Neg => -1 }
459 // Find the index of the largest mobile element:
460 // The direction should point into the vector, and the
461 // swap should be with a smaller `size` element.
462 let max = self.sdir.iter().map(|&x| x).enumerate()
464 new_pos(i, sd.dir) < self.sdir.len() &&
465 self.sdir[new_pos(i, sd.dir)].size < sd.size)
466 .max_by(|&(_, sd)| sd.size);
469 let j = new_pos(i, sd.dir);
470 self.sdir.swap(i, j);
472 // Swap the direction of each larger SizeDirection
473 for x in self.sdir.mut_iter() {
474 if x.size > sd.size {
475 x.dir = match x.dir { Pos => Neg, Neg => Pos };
480 None => if self.emit_reset && self.sdir.len() > 1 {
481 self.emit_reset = false;
490 /// An Iterator that uses `ElementSwaps` to iterate through
491 /// all possible permutations of a vector.
493 /// The first iteration yields a clone of the vector as it is,
494 /// then each successive element is the vector with one
497 /// Generates even and odd permutations alternately.
498 pub struct Permutations<T> {
499 priv swaps: ElementSwaps,
503 impl<T: Clone> Iterator<~[T]> for Permutations<T> {
505 fn next(&mut self) -> Option<~[T]> {
506 match self.swaps.next() {
509 let elt = self.v.clone();
517 /// An iterator over the (overlapping) slices of length `size` within
520 pub struct Windows<'a, T> {
525 impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
527 fn next(&mut self) -> Option<&'a [T]> {
528 if self.size > self.v.len() {
531 let ret = Some(self.v.slice(0, self.size));
532 self.v = self.v.slice(1, self.v.len());
538 fn size_hint(&self) -> (uint, Option<uint>) {
539 if self.size > self.v.len() {
542 let x = self.v.len() - self.size;
543 (x.saturating_add(1), x.checked_add(&1u))
548 /// An iterator over a vector in (non-overlapping) chunks (`size`
549 /// elements at a time).
551 /// When the vector len is not evenly divided by the chunk size,
552 /// the last slice of the iteration will be the remainder.
554 pub struct Chunks<'a, T> {
559 impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
561 fn next(&mut self) -> Option<&'a [T]> {
562 if self.v.len() == 0 {
565 let chunksz = cmp::min(self.v.len(), self.size);
566 let (fst, snd) = (self.v.slice_to(chunksz),
567 self.v.slice_from(chunksz));
574 fn size_hint(&self) -> (uint, Option<uint>) {
575 if self.v.len() == 0 {
578 let (n, rem) = div_rem(self.v.len(), self.size);
579 let n = if rem > 0 { n+1 } else { n };
585 impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
587 fn next_back(&mut self) -> Option<&'a [T]> {
588 if self.v.len() == 0 {
591 let remainder = self.v.len() % self.size;
592 let chunksz = if remainder != 0 { remainder } else { self.size };
593 let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
594 self.v.slice_from(self.v.len() - chunksz));
601 impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
603 fn indexable(&self) -> uint {
604 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
608 fn idx(&self, index: uint) -> Option<&'a [T]> {
609 if index < self.indexable() {
610 let lo = index * self.size;
611 let mut hi = lo + self.size;
612 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
614 Some(self.v.slice(lo, hi))
624 #[allow(missing_doc)]
628 use container::Container;
630 use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Equiv};
634 impl<'a,T:Eq> Eq for &'a [T] {
635 fn eq(&self, other: & &'a [T]) -> bool {
636 self.len() == other.len() &&
637 order::eq(self.iter(), other.iter())
639 fn ne(&self, other: & &'a [T]) -> bool {
640 self.len() != other.len() ||
641 order::ne(self.iter(), other.iter())
645 impl<T:Eq> Eq for ~[T] {
647 fn eq(&self, other: &~[T]) -> bool { self.as_slice() == *other }
649 fn ne(&self, other: &~[T]) -> bool { !self.eq(other) }
652 impl<'a,T:TotalEq> TotalEq for &'a [T] {
653 fn equals(&self, other: & &'a [T]) -> bool {
654 self.len() == other.len() &&
655 order::equals(self.iter(), other.iter())
659 impl<T:TotalEq> TotalEq for ~[T] {
661 fn equals(&self, other: &~[T]) -> bool { self.as_slice().equals(&other.as_slice()) }
664 impl<'a,T:Eq, V: Vector<T>> Equiv<V> for &'a [T] {
666 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
669 impl<'a,T:Eq, V: Vector<T>> Equiv<V> for ~[T] {
671 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
674 impl<'a,T:TotalOrd> TotalOrd for &'a [T] {
675 fn cmp(&self, other: & &'a [T]) -> Ordering {
676 order::cmp(self.iter(), other.iter())
680 impl<T: TotalOrd> TotalOrd for ~[T] {
682 fn cmp(&self, other: &~[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
685 impl<'a, T: Eq + Ord> Ord for &'a [T] {
686 fn lt(&self, other: & &'a [T]) -> bool {
687 order::lt(self.iter(), other.iter())
690 fn le(&self, other: & &'a [T]) -> bool {
691 order::le(self.iter(), other.iter())
694 fn ge(&self, other: & &'a [T]) -> bool {
695 order::ge(self.iter(), other.iter())
698 fn gt(&self, other: & &'a [T]) -> bool {
699 order::gt(self.iter(), other.iter())
703 impl<T: Eq + Ord> Ord for ~[T] {
705 fn lt(&self, other: &~[T]) -> bool { self.as_slice() < other.as_slice() }
707 fn le(&self, other: &~[T]) -> bool { self.as_slice() <= other.as_slice() }
709 fn ge(&self, other: &~[T]) -> bool { self.as_slice() >= other.as_slice() }
711 fn gt(&self, other: &~[T]) -> bool { self.as_slice() > other.as_slice() }
714 impl<'a,T:Clone, V: Vector<T>> Add<V, ~[T]> for &'a [T] {
716 fn add(&self, rhs: &V) -> ~[T] {
717 let mut res = with_capacity(self.len() + rhs.as_slice().len());
719 res.push_all(rhs.as_slice());
724 impl<T:Clone, V: Vector<T>> Add<V, ~[T]> for ~[T] {
726 fn add(&self, rhs: &V) -> ~[T] {
727 self.as_slice() + rhs.as_slice()
735 /// Any vector that can be represented as a slice.
736 pub trait Vector<T> {
737 /// Work with `self` as a slice.
738 fn as_slice<'a>(&'a self) -> &'a [T];
741 impl<'a,T> Vector<T> for &'a [T] {
743 fn as_slice<'a>(&'a self) -> &'a [T] { *self }
746 impl<T> Vector<T> for ~[T] {
748 fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
751 impl<'a, T> Container for &'a [T] {
752 /// Returns the length of a vector
754 fn len(&self) -> uint {
759 impl<T> Container for ~[T] {
760 /// Returns the length of a vector
762 fn len(&self) -> uint {
763 self.as_slice().len()
767 /// Extension methods for vector slices with cloneable elements
768 pub trait CloneableVector<T> {
769 /// Copy `self` into a new owned vector
770 fn to_owned(&self) -> ~[T];
772 /// Convert `self` into an owned vector, not making a copy if possible.
773 fn into_owned(self) -> ~[T];
776 /// Extension methods for vector slices
777 impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
778 /// Returns a copy of `v`.
780 fn to_owned(&self) -> ~[T] {
781 let mut result = with_capacity(self.len());
782 for e in self.iter() {
783 result.push((*e).clone());
789 fn into_owned(self) -> ~[T] { self.to_owned() }
792 /// Extension methods for owned vectors
793 impl<T: Clone> CloneableVector<T> for ~[T] {
795 fn to_owned(&self) -> ~[T] { self.clone() }
798 fn into_owned(self) -> ~[T] { self }
801 /// Extension methods for vectors
802 pub trait ImmutableVector<'a, T> {
804 * Returns a slice of self between `start` and `end`.
806 * Fails when `start` or `end` point outside the bounds of self,
807 * or when `start` > `end`.
809 fn slice(&self, start: uint, end: uint) -> &'a [T];
812 * Returns a slice of self from `start` to the end of the vec.
814 * Fails when `start` points outside the bounds of self.
816 fn slice_from(&self, start: uint) -> &'a [T];
819 * Returns a slice of self from the start of the vec to `end`.
821 * Fails when `end` points outside the bounds of self.
823 fn slice_to(&self, end: uint) -> &'a [T];
824 /// Returns an iterator over the vector
825 fn iter(self) -> Items<'a, T>;
826 /// Returns a reversed iterator over a vector
827 fn rev_iter(self) -> RevItems<'a, T>;
828 /// Returns an iterator over the subslices of the vector which are
829 /// separated by elements that match `pred`. The matched element
830 /// is not contained in the subslices.
831 fn split(self, pred: 'a |&T| -> bool) -> Splits<'a, T>;
832 /// Returns an iterator over the subslices of the vector which are
833 /// separated by elements that match `pred`, limited to splitting
834 /// at most `n` times. The matched element is not contained in
836 fn splitn(self, n: uint, pred: 'a |&T| -> bool) -> Splits<'a, T>;
837 /// Returns an iterator over the subslices of the vector which are
838 /// separated by elements that match `pred`. This starts at the
839 /// end of the vector and works backwards. The matched element is
840 /// not contained in the subslices.
841 fn rsplit(self, pred: 'a |&T| -> bool) -> RevSplits<'a, T>;
842 /// Returns an iterator over the subslices of the vector which are
843 /// separated by elements that match `pred` limited to splitting
844 /// at most `n` times. This starts at the end of the vector and
845 /// works backwards. The matched element is not contained in the
847 fn rsplitn(self, n: uint, pred: 'a |&T| -> bool) -> RevSplits<'a, T>;
850 * Returns an iterator over all contiguous windows of length
851 * `size`. The windows overlap. If the vector is shorter than
852 * `size`, the iterator returns no values.
856 * Fails if `size` is 0.
860 * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
864 * let v = &[1,2,3,4];
865 * for win in v.windows(2) {
866 * println!("{:?}", win);
871 fn windows(self, size: uint) -> Windows<'a, T>;
874 * Returns an iterator over `size` elements of the vector at a
875 * time. The chunks do not overlap. If `size` does not divide the
876 * length of the vector, then the last chunk will not have length
881 * Fails if `size` is 0.
885 * Print the vector two elements at a time (i.e. `[1,2]`,
889 * let v = &[1,2,3,4,5];
890 * for win in v.chunks(2) {
891 * println!("{:?}", win);
896 fn chunks(self, size: uint) -> Chunks<'a, T>;
898 /// Returns the element of a vector at the given index, or `None` if the
899 /// index is out of bounds
900 fn get(&self, index: uint) -> Option<&'a T>;
901 /// Returns the first element of a vector, or `None` if it is empty
902 fn head(&self) -> Option<&'a T>;
903 /// Returns all but the first element of a vector
904 fn tail(&self) -> &'a [T];
905 /// Returns all but the first `n' elements of a vector
906 fn tailn(&self, n: uint) -> &'a [T];
907 /// Returns all but the last element of a vector
908 fn init(&self) -> &'a [T];
909 /// Returns all but the last `n' elements of a vector
910 fn initn(&self, n: uint) -> &'a [T];
911 /// Returns the last element of a vector, or `None` if it is empty.
912 fn last(&self) -> Option<&'a T>;
914 * Apply a function to each element of a vector and return a concatenation
915 * of each result vector
917 fn flat_map<U>(&self, f: |t: &T| -> ~[U]) -> ~[U];
918 /// Returns a pointer to the element at the given index, without doing
920 unsafe fn unsafe_ref(self, index: uint) -> &'a T;
923 * Returns an unsafe pointer to the vector's buffer
925 * The caller must ensure that the vector outlives the pointer this
926 * function returns, or else it will end up pointing to garbage.
928 * Modifying the vector may cause its buffer to be reallocated, which
929 * would also make any pointers to it invalid.
931 fn as_ptr(&self) -> *T;
934 * Binary search a sorted vector with a comparator function.
936 * The comparator function should implement an order consistent
937 * with the sort order of the underlying vector, returning an
938 * order code that indicates whether its argument is `Less`,
939 * `Equal` or `Greater` the desired target.
941 * Returns the index where the comparator returned `Equal`, or `None` if
944 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
946 /// Deprecated, use iterators where possible
947 /// (`self.iter().map(f)`). Apply a function to each element
948 /// of a vector and return the results.
949 fn map<U>(&self, |t: &T| -> U) -> ~[U];
952 * Returns a mutable reference to the first element in this slice
953 * and adjusts the slice in place so that it no longer contains
954 * that element. O(1).
959 * if self.len() == 0 { return None }
960 * let head = &self[0];
961 * *self = self.slice_from(1);
965 * Returns `None` if vector is empty
967 fn shift_ref(&mut self) -> Option<&'a T>;
970 * Returns a mutable reference to the last element in this slice
971 * and adjusts the slice in place so that it no longer contains
972 * that element. O(1).
977 * if self.len() == 0 { return None; }
978 * let tail = &self[self.len() - 1];
979 * *self = self.slice_to(self.len() - 1);
983 * Returns `None` if slice is empty.
985 fn pop_ref(&mut self) -> Option<&'a T>;
988 impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
990 fn slice(&self, start: uint, end: uint) -> &'a [T] {
991 assert!(start <= end);
992 assert!(end <= self.len());
995 data: self.as_ptr().offset(start as int),
1002 fn slice_from(&self, start: uint) -> &'a [T] {
1003 self.slice(start, self.len())
1007 fn slice_to(&self, end: uint) -> &'a [T] {
1012 fn iter(self) -> Items<'a, T> {
1014 let p = self.as_ptr();
1015 if mem::size_of::<T>() == 0 {
1017 end: (p as uint + self.len()) as *T,
1018 marker: marker::ContravariantLifetime::<'a>}
1021 end: p.offset(self.len() as int),
1022 marker: marker::ContravariantLifetime::<'a>}
1028 fn rev_iter(self) -> RevItems<'a, T> {
1033 fn split(self, pred: 'a |&T| -> bool) -> Splits<'a, T> {
1034 self.splitn(uint::MAX, pred)
1038 fn splitn(self, n: uint, pred: 'a |&T| -> bool) -> Splits<'a, T> {
1048 fn rsplit(self, pred: 'a |&T| -> bool) -> RevSplits<'a, T> {
1049 self.rsplitn(uint::MAX, pred)
1053 fn rsplitn(self, n: uint, pred: 'a |&T| -> bool) -> RevSplits<'a, T> {
1063 fn windows(self, size: uint) -> Windows<'a, T> {
1065 Windows { v: self, size: size }
1069 fn chunks(self, size: uint) -> Chunks<'a, T> {
1071 Chunks { v: self, size: size }
1075 fn get(&self, index: uint) -> Option<&'a T> {
1076 if index < self.len() { Some(&self[index]) } else { None }
1080 fn head(&self) -> Option<&'a T> {
1081 if self.len() == 0 { None } else { Some(&self[0]) }
1085 fn tail(&self) -> &'a [T] { self.slice(1, self.len()) }
1088 fn tailn(&self, n: uint) -> &'a [T] { self.slice(n, self.len()) }
1091 fn init(&self) -> &'a [T] {
1092 self.slice(0, self.len() - 1)
1096 fn initn(&self, n: uint) -> &'a [T] {
1097 self.slice(0, self.len() - n)
1101 fn last(&self) -> Option<&'a T> {
1102 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
1106 fn flat_map<U>(&self, f: |t: &T| -> ~[U]) -> ~[U] {
1111 unsafe fn unsafe_ref(self, index: uint) -> &'a T {
1112 transmute(self.repr().data.offset(index as int))
1116 fn as_ptr(&self) -> *T {
1121 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint> {
1122 let mut base : uint = 0;
1123 let mut lim : uint = self.len();
1126 let ix = base + (lim >> 1);
1127 match f(&self[ix]) {
1128 Equal => return Some(ix),
1140 fn map<U>(&self, f: |t: &T| -> U) -> ~[U] {
1141 self.iter().map(f).collect()
1144 fn shift_ref(&mut self) -> Option<&'a T> {
1145 if self.len() == 0 { return None; }
1147 let s: &mut Slice<T> = transmute(self);
1148 Some(&*raw::shift_ptr(s))
1152 fn pop_ref(&mut self) -> Option<&'a T> {
1153 if self.len() == 0 { return None; }
1155 let s: &mut Slice<T> = transmute(self);
1156 Some(&*raw::pop_ptr(s))
1161 /// Extension methods for vectors contain `Eq` elements.
1162 pub trait ImmutableEqVector<T:Eq> {
1163 /// Find the first index containing a matching value
1164 fn position_elem(&self, t: &T) -> Option<uint>;
1166 /// Find the last index containing a matching value
1167 fn rposition_elem(&self, t: &T) -> Option<uint>;
1169 /// Return true if a vector contains an element with the given value
1170 fn contains(&self, x: &T) -> bool;
1172 /// Returns true if `needle` is a prefix of the vector.
1173 fn starts_with(&self, needle: &[T]) -> bool;
1175 /// Returns true if `needle` is a suffix of the vector.
1176 fn ends_with(&self, needle: &[T]) -> bool;
1179 impl<'a,T:Eq> ImmutableEqVector<T> for &'a [T] {
1181 fn position_elem(&self, x: &T) -> Option<uint> {
1182 self.iter().position(|y| *x == *y)
1186 fn rposition_elem(&self, t: &T) -> Option<uint> {
1187 self.iter().rposition(|x| *x == *t)
1191 fn contains(&self, x: &T) -> bool {
1192 self.iter().any(|elt| *x == *elt)
1196 fn starts_with(&self, needle: &[T]) -> bool {
1197 let n = needle.len();
1198 self.len() >= n && needle == self.slice_to(n)
1202 fn ends_with(&self, needle: &[T]) -> bool {
1203 let (m, n) = (self.len(), needle.len());
1204 m >= n && needle == self.slice_from(m - n)
1208 /// Extension methods for vectors containing `TotalOrd` elements.
1209 pub trait ImmutableTotalOrdVector<T: TotalOrd> {
1211 * Binary search a sorted vector for a given element.
1213 * Returns the index of the element or None if not found.
1215 fn bsearch_elem(&self, x: &T) -> Option<uint>;
1218 impl<'a, T: TotalOrd> ImmutableTotalOrdVector<T> for &'a [T] {
1219 fn bsearch_elem(&self, x: &T) -> Option<uint> {
1220 self.bsearch(|p| p.cmp(x))
1224 /// Extension methods for vectors containing `Clone` elements.
1225 pub trait ImmutableCloneableVector<T> {
1226 /// Partitions the vector into two vectors `(A,B)`, where all
1227 /// elements of `A` satisfy `f` and all elements of `B` do not.
1228 fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]);
1230 /// Create an iterator that yields every possible permutation of the
1231 /// vector in succession.
1232 fn permutations(self) -> Permutations<T>;
1235 impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
1237 fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]) {
1238 let mut lefts = ~[];
1239 let mut rights = ~[];
1241 for elt in self.iter() {
1243 lefts.push((*elt).clone());
1245 rights.push((*elt).clone());
1252 fn permutations(self) -> Permutations<T> {
1254 swaps: ElementSwaps::new(self.len()),
1261 /// Extension methods for owned vectors.
1262 pub trait OwnedVector<T> {
1263 /// Creates a consuming iterator, that is, one that moves each
1264 /// value out of the vector (from start to end). The vector cannot
1265 /// be used after calling this.
1270 /// let v = ~[~"a", ~"b"];
1271 /// for s in v.move_iter() {
1272 /// // s has type ~str, not &~str
1273 /// println!("{}", s);
1276 fn move_iter(self) -> MoveItems<T>;
1277 /// Creates a consuming iterator that moves out of the vector in
1279 fn move_rev_iter(self) -> RevMoveItems<T>;
1282 * Reserves capacity for exactly `n` elements in the given vector.
1284 * If the capacity for `self` is already equal to or greater than the requested
1285 * capacity, then no action is taken.
1289 * * n - The number of elements to reserve space for
1293 * This method always succeeds in reserving space for `n` elements, or it does
1296 fn reserve_exact(&mut self, n: uint);
1298 * Reserves capacity for at least `n` elements in the given vector.
1300 * This function will over-allocate in order to amortize the allocation costs
1301 * in scenarios where the caller may need to repeatedly reserve additional
1304 * If the capacity for `self` is already equal to or greater than the requested
1305 * capacity, then no action is taken.
1309 * * n - The number of elements to reserve space for
1311 fn reserve(&mut self, n: uint);
1313 * Reserves capacity for at least `n` additional elements in the given vector.
1317 * Fails if the new required capacity overflows uint.
1319 * May also fail if `reserve` fails.
1321 fn reserve_additional(&mut self, n: uint);
1322 /// Returns the number of elements the vector can hold without reallocating.
1323 fn capacity(&self) -> uint;
1324 /// Shrink the capacity of the vector to match the length
1325 fn shrink_to_fit(&mut self);
1327 /// Append an element to a vector
1328 fn push(&mut self, t: T);
1329 /// Takes ownership of the vector `rhs`, moving all elements into
1330 /// the current vector. This does not copy any elements, and it is
1331 /// illegal to use the `rhs` vector after calling this method
1332 /// (because it is moved here).
1337 /// let mut a = ~[~1];
1338 /// a.push_all_move(~[~2, ~3, ~4]);
1339 /// assert!(a == ~[~1, ~2, ~3, ~4]);
1341 fn push_all_move(&mut self, rhs: ~[T]);
1342 /// Remove the last element from a vector and return it, or `None` if it is empty
1343 fn pop(&mut self) -> Option<T>;
1344 /// Removes the first element from a vector and return it, or `None` if it is empty
1345 fn shift(&mut self) -> Option<T>;
1346 /// Prepend an element to the vector
1347 fn unshift(&mut self, x: T);
1349 /// Insert an element at position i within v, shifting all
1350 /// elements after position i one position to the right.
1351 fn insert(&mut self, i: uint, x:T);
1353 /// Remove and return the element at position `i` within `v`,
1354 /// shifting all elements after position `i` one position to the
1355 /// left. Returns `None` if `i` is out of bounds.
1359 /// let mut v = ~[1, 2, 3];
1360 /// assert_eq!(v.remove(1), Some(2));
1361 /// assert_eq!(v, ~[1, 3]);
1363 /// assert_eq!(v.remove(4), None);
1364 /// // v is unchanged:
1365 /// assert_eq!(v, ~[1, 3]);
1367 fn remove(&mut self, i: uint) -> Option<T>;
1369 /// Remove an element from anywhere in the vector and return it, replacing it
1370 /// with the last element. This does not preserve ordering, but is O(1).
1372 /// Returns `None` if `index` is out of bounds.
1376 /// let mut v = ~[~"foo", ~"bar", ~"baz", ~"qux"];
1378 /// assert_eq!(v.swap_remove(1), Some(~"bar"));
1379 /// assert_eq!(v, ~[~"foo", ~"qux", ~"baz"]);
1381 /// assert_eq!(v.swap_remove(0), Some(~"foo"));
1382 /// assert_eq!(v, ~[~"baz", ~"qux"]);
1384 /// assert_eq!(v.swap_remove(2), None);
1386 fn swap_remove(&mut self, index: uint) -> Option<T>;
1388 /// Shorten a vector, dropping excess elements.
1389 fn truncate(&mut self, newlen: uint);
1392 * Like `filter()`, but in place. Preserves order of `v`. Linear time.
1394 fn retain(&mut self, f: |t: &T| -> bool);
1397 * Partitions the vector into two vectors `(A,B)`, where all
1398 * elements of `A` satisfy `f` and all elements of `B` do not.
1400 fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]);
1403 * Expands a vector in place, initializing the new elements to the result of
1406 * Function `init_op` is called `n` times with the values [0..`n`)
1410 * * n - The number of elements to add
1411 * * init_op - A function to call to retrieve each appended element's
1414 fn grow_fn(&mut self, n: uint, op: |uint| -> T);
1417 * Sets the length of a vector
1419 * This will explicitly set the size of the vector, without actually
1420 * modifying its buffers, so it is up to the caller to ensure that
1421 * the vector is actually the specified size.
1423 unsafe fn set_len(&mut self, new_len: uint);
1426 impl<T> OwnedVector<T> for ~[T] {
1428 fn move_iter(self) -> MoveItems<T> {
1430 let iter = transmute(self.iter());
1431 let ptr = transmute(self);
1432 MoveItems { allocation: ptr, iter: iter }
1437 fn move_rev_iter(self) -> RevMoveItems<T> {
1438 self.move_iter().rev()
1441 fn reserve_exact(&mut self, n: uint) {
1442 // Only make the (slow) call into the runtime if we have to
1443 if self.capacity() < n {
1445 let ptr: *mut *mut Vec<()> = transmute(self);
1446 let alloc = n * mem::nonzero_size_of::<T>();
1447 let size = alloc + mem::size_of::<Vec<()>>();
1448 if alloc / mem::nonzero_size_of::<T>() != n || size < alloc {
1449 fail!("vector size is too large: {}", n);
1451 *ptr = realloc_raw(*ptr as *mut u8, size)
1453 (**ptr).alloc = alloc;
1459 fn reserve(&mut self, n: uint) {
1460 self.reserve_exact(checked_next_power_of_two(n).unwrap_or(n));
1464 fn reserve_additional(&mut self, n: uint) {
1465 if self.capacity() - self.len() < n {
1466 match self.len().checked_add(&n) {
1467 None => fail!("vec::reserve_additional: `uint` overflow"),
1468 Some(new_cap) => self.reserve(new_cap)
1474 fn capacity(&self) -> uint {
1476 let repr: **Vec<()> = transmute(self);
1477 (**repr).alloc / mem::nonzero_size_of::<T>()
1481 fn shrink_to_fit(&mut self) {
1483 let ptr: *mut *mut Vec<()> = transmute(self);
1484 let alloc = (**ptr).fill;
1485 let size = alloc + mem::size_of::<Vec<()>>();
1486 *ptr = realloc_raw(*ptr as *mut u8, size) as *mut Vec<()>;
1487 (**ptr).alloc = alloc;
1492 fn push(&mut self, t: T) {
1494 let repr: **Vec<()> = transmute(&mut *self);
1495 let fill = (**repr).fill;
1496 if (**repr).alloc <= fill {
1497 self.reserve_additional(1);
1503 // This doesn't bother to make sure we have space.
1504 #[inline] // really pretty please
1505 unsafe fn push_fast<T>(this: &mut ~[T], t: T) {
1506 let repr: **mut Vec<u8> = transmute(this);
1507 let fill = (**repr).fill;
1508 (**repr).fill += mem::nonzero_size_of::<T>();
1509 let p = &((**repr).data) as *u8;
1510 let p = p.offset(fill as int) as *mut T;
1511 mem::move_val_init(&mut(*p), t);
1516 fn push_all_move(&mut self, mut rhs: ~[T]) {
1517 let self_len = self.len();
1518 let rhs_len = rhs.len();
1519 let new_len = self_len + rhs_len;
1520 self.reserve_additional(rhs.len());
1521 unsafe { // Note: infallible.
1522 let self_p = self.as_mut_ptr();
1523 let rhs_p = rhs.as_ptr();
1524 ptr::copy_memory(self_p.offset(self_len as int), rhs_p, rhs_len);
1525 self.set_len(new_len);
1530 fn pop(&mut self) -> Option<T> {
1534 let valptr = &mut self[ln - 1u] as *mut T;
1536 self.set_len(ln - 1u);
1537 Some(ptr::read(&*valptr))
1545 fn shift(&mut self) -> Option<T> {
1550 fn unshift(&mut self, x: T) {
1554 fn insert(&mut self, i: uint, x: T) {
1555 let len = self.len();
1557 // space for the new element
1558 self.reserve_additional(1);
1560 unsafe { // infallible
1561 // The spot to put the new value
1562 let p = self.as_mut_ptr().offset(i as int);
1563 // Shift everything over to make space. (Duplicating the
1564 // `i`th element into two consecutive places.)
1565 ptr::copy_memory(p.offset(1), &*p, len - i);
1566 // Write it in, overwriting the first copy of the `i`th
1568 mem::move_val_init(&mut *p, x);
1569 self.set_len(len + 1);
1573 fn remove(&mut self, i: uint) -> Option<T> {
1574 let len = self.len();
1576 unsafe { // infallible
1577 // the place we are taking from.
1578 let ptr = self.as_mut_ptr().offset(i as int);
1579 // copy it out, unsafely having a copy of the value on
1580 // the stack and in the vector at the same time.
1581 let ret = Some(ptr::read(ptr as *T));
1583 // Shift everything down to fill in that spot.
1584 ptr::copy_memory(ptr, &*ptr.offset(1), len - i - 1);
1585 self.set_len(len - 1);
1593 fn swap_remove(&mut self, index: uint) -> Option<T> {
1594 let ln = self.len();
1596 self.swap(index, ln - 1);
1597 } else if index >= ln {
1602 fn truncate(&mut self, newlen: uint) {
1603 let oldlen = self.len();
1604 assert!(newlen <= oldlen);
1607 let p = self.as_mut_ptr();
1608 // This loop is optimized out for non-drop types.
1609 for i in range(newlen, oldlen) {
1610 ptr::read_and_zero(p.offset(i as int));
1613 unsafe { self.set_len(newlen); }
1616 fn retain(&mut self, f: |t: &T| -> bool) {
1617 let len = self.len();
1618 let mut deleted: uint = 0;
1620 for i in range(0u, len) {
1623 } else if deleted > 0 {
1624 self.swap(i - deleted, i);
1629 self.truncate(len - deleted);
1634 fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]) {
1635 let mut lefts = ~[];
1636 let mut rights = ~[];
1638 for elt in self.move_iter() {
1648 fn grow_fn(&mut self, n: uint, op: |uint| -> T) {
1649 let new_len = self.len() + n;
1650 self.reserve(new_len);
1651 let mut i: uint = 0u;
1659 unsafe fn set_len(&mut self, new_len: uint) {
1660 let repr: **mut Vec<()> = transmute(self);
1661 (**repr).fill = new_len * mem::nonzero_size_of::<T>();
1665 impl<T> Mutable for ~[T] {
1666 /// Clear the vector, removing all values.
1667 fn clear(&mut self) { self.truncate(0) }
1670 /// Extension methods for owned vectors containing `Clone` elements.
1671 pub trait OwnedCloneableVector<T:Clone> {
1672 /// Iterates over the slice `rhs`, copies each element, and then appends it to
1673 /// the vector provided `v`. The `rhs` vector is traversed in-order.
1678 /// let mut a = ~[1];
1679 /// a.push_all([2, 3, 4]);
1680 /// assert!(a == ~[1, 2, 3, 4]);
1682 fn push_all(&mut self, rhs: &[T]);
1685 * Expands a vector in place, initializing the new elements to a given value
1689 * * n - The number of elements to add
1690 * * initval - The value for the new elements
1692 fn grow(&mut self, n: uint, initval: &T);
1695 * Sets the value of a vector element at a given index, growing the vector as
1698 * Sets the element at position `index` to `val`. If `index` is past the end
1699 * of the vector, expands the vector by replicating `initval` to fill the
1700 * intervening space.
1702 fn grow_set(&mut self, index: uint, initval: &T, val: T);
1705 impl<T:Clone> OwnedCloneableVector<T> for ~[T] {
1707 fn push_all(&mut self, rhs: &[T]) {
1708 let new_len = self.len() + rhs.len();
1709 self.reserve_exact(new_len);
1711 for elt in rhs.iter() {
1712 self.push((*elt).clone())
1715 fn grow(&mut self, n: uint, initval: &T) {
1716 let new_len = self.len() + n;
1717 self.reserve(new_len);
1718 let mut i: uint = 0u;
1721 self.push((*initval).clone());
1725 fn grow_set(&mut self, index: uint, initval: &T, val: T) {
1727 if index >= l { self.grow(index - l + 1u, initval); }
1732 /// Extension methods for owned vectors containing `Eq` elements.
1733 pub trait OwnedEqVector<T:Eq> {
1735 * Remove consecutive repeated elements from a vector; if the vector is
1736 * sorted, this removes all duplicates.
1738 fn dedup(&mut self);
1741 impl<T:Eq> OwnedEqVector<T> for ~[T] {
1742 fn dedup(&mut self) {
1744 // Although we have a mutable reference to `self`, we cannot make
1745 // *arbitrary* changes. The `Eq` comparisons could fail, so we
1746 // must ensure that the vector is in a valid state at all time.
1748 // The way that we handle this is by using swaps; we iterate
1749 // over all the elements, swapping as we go so that at the end
1750 // the elements we wish to keep are in the front, and those we
1751 // wish to reject are at the back. We can then truncate the
1752 // vector. This operation is still O(n).
1754 // Example: We start in this state, where `r` represents "next
1755 // read" and `w` represents "next_write`.
1758 // +---+---+---+---+---+---+
1759 // | 0 | 1 | 1 | 2 | 3 | 3 |
1760 // +---+---+---+---+---+---+
1763 // Comparing self[r] against self[w-1], tis is not a duplicate, so
1764 // we swap self[r] and self[w] (no effect as r==w) and then increment both
1765 // r and w, leaving us with:
1768 // +---+---+---+---+---+---+
1769 // | 0 | 1 | 1 | 2 | 3 | 3 |
1770 // +---+---+---+---+---+---+
1773 // Comparing self[r] against self[w-1], this value is a duplicate,
1774 // so we increment `r` but leave everything else unchanged:
1777 // +---+---+---+---+---+---+
1778 // | 0 | 1 | 1 | 2 | 3 | 3 |
1779 // +---+---+---+---+---+---+
1782 // Comparing self[r] against self[w-1], this is not a duplicate,
1783 // so swap self[r] and self[w] and advance r and w:
1786 // +---+---+---+---+---+---+
1787 // | 0 | 1 | 2 | 1 | 3 | 3 |
1788 // +---+---+---+---+---+---+
1791 // Not a duplicate, repeat:
1794 // +---+---+---+---+---+---+
1795 // | 0 | 1 | 2 | 3 | 1 | 3 |
1796 // +---+---+---+---+---+---+
1799 // Duplicate, advance r. End of vec. Truncate to w.
1801 let ln = self.len();
1802 if ln < 1 { return; }
1804 // Avoid bounds checks by using unsafe pointers.
1805 let p = self.as_mut_ptr();
1810 let p_r = p.offset(r as int);
1811 let p_wm1 = p.offset((w - 1) as int);
1814 let p_w = p_wm1.offset(1);
1815 mem::swap(&mut *p_r, &mut *p_w);
1827 fn insertion_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
1828 let len = v.len() as int;
1829 let buf_v = v.as_mut_ptr();
1832 for i in range(1, len) {
1833 // j satisfies: 0 <= j <= i;
1836 // `i` is in bounds.
1837 let read_ptr = buf_v.offset(i) as *T;
1839 // find where to insert, we need to do strict <,
1840 // rather than <=, to maintain stability.
1842 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1844 compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
1848 // shift everything to the right, to make space to
1849 // insert this value.
1851 // j + 1 could be `len` (for the last `i`), but in
1852 // that case, `i == j` so we don't copy. The
1853 // `.offset(j)` is always in bounds.
1856 let tmp = ptr::read(read_ptr);
1857 ptr::copy_memory(buf_v.offset(j + 1),
1860 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
1869 fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
1870 // warning: this wildly uses unsafe.
1871 static BASE_INSERTION: uint = 32;
1872 static LARGE_INSERTION: uint = 16;
1874 // FIXME #12092: smaller insertion runs seems to make sorting
1875 // vectors of large elements a little faster on some platforms,
1876 // but hasn't been tested/tuned extensively
1877 let insertion = if size_of::<T>() <= 16 {
1885 // short vectors get sorted in-place via insertion sort to avoid allocations
1886 if len <= insertion {
1887 insertion_sort(v, compare);
1891 // allocate some memory to use as scratch memory, we keep the
1892 // length 0 so we can keep shallow copies of the contents of `v`
1893 // without risking the dtors running on an object twice if
1895 let mut working_space = with_capacity(2 * len);
1896 // these both are buffers of length `len`.
1897 let mut buf_dat = working_space.as_mut_ptr();
1898 let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
1901 let buf_v = v.as_ptr();
1903 // step 1. sort short runs with insertion sort. This takes the
1904 // values from `v` and sorts them into `buf_dat`, leaving that
1905 // with sorted runs of length INSERTION.
1907 // We could hardcode the sorting comparisons here, and we could
1908 // manipulate/step the pointers themselves, rather than repeatedly
1910 for start in range_step(0, len, insertion) {
1911 // start <= i < len;
1912 for i in range(start, cmp::min(start + insertion, len)) {
1913 // j satisfies: start <= j <= i;
1914 let mut j = i as int;
1916 // `i` is in bounds.
1917 let read_ptr = buf_v.offset(i as int);
1919 // find where to insert, we need to do strict <,
1920 // rather than <=, to maintain stability.
1922 // start <= j - 1 < len, so .offset(j - 1) is in
1924 while j > start as int &&
1925 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1929 // shift everything to the right, to make space to
1930 // insert this value.
1932 // j + 1 could be `len` (for the last `i`), but in
1933 // that case, `i == j` so we don't copy. The
1934 // `.offset(j)` is always in bounds.
1935 ptr::copy_memory(buf_dat.offset(j + 1),
1936 &*buf_dat.offset(j),
1938 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
1943 // step 2. merge the sorted runs.
1944 let mut width = insertion;
1946 // merge the sorted runs of length `width` in `buf_dat` two at
1947 // a time, placing the result in `buf_tmp`.
1949 // 0 <= start <= len.
1950 for start in range_step(0, len, 2 * width) {
1951 // manipulate pointers directly for speed (rather than
1952 // using a `for` loop with `range` and `.offset` inside
1955 // the end of the first run & start of the
1956 // second. Offset of `len` is defined, since this is
1957 // precisely one byte past the end of the object.
1958 let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
1959 // end of the second. Similar reasoning to the above re safety.
1960 let right_end_idx = cmp::min(start + 2 * width, len);
1961 let right_end = buf_dat.offset(right_end_idx as int);
1963 // the pointers to the elements under consideration
1964 // from the two runs.
1966 // both of these are in bounds.
1967 let mut left = buf_dat.offset(start as int);
1968 let mut right = right_start;
1970 // where we're putting the results, it is a run of
1971 // length `2*width`, so we step it once for each step
1972 // of either `left` or `right`. `buf_tmp` has length
1973 // `len`, so these are in bounds.
1974 let mut out = buf_tmp.offset(start as int);
1975 let out_end = buf_tmp.offset(right_end_idx as int);
1977 while out < out_end {
1978 // Either the left or the right run are exhausted,
1979 // so just copy the remainder from the other run
1980 // and move on; this gives a huge speed-up (order
1981 // of 25%) for mostly sorted vectors (the best
1983 if left == right_start {
1984 // the number remaining in this run.
1985 let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
1986 ptr::copy_nonoverlapping_memory(out, &*right, elems);
1988 } else if right == right_end {
1989 let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
1990 ptr::copy_nonoverlapping_memory(out, &*left, elems);
1994 // check which side is smaller, and that's the
1995 // next element for the new run.
1997 // `left < right_start` and `right < right_end`,
1998 // so these are valid.
1999 let to_copy = if compare(&*left, &*right) == Greater {
2004 ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
2010 mem::swap(&mut buf_dat, &mut buf_tmp);
2015 // write the result to `v` in one go, so that there are never two copies
2016 // of the same object in `v`.
2018 ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
2021 // increment the pointer, returning the old pointer.
2023 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
2025 *ptr = ptr.offset(1);
2030 /// Extension methods for vectors such that their elements are
2032 pub trait MutableVector<'a, T> {
2033 /// Work with `self` as a mut slice.
2034 /// Primarily intended for getting a &mut [T] from a [T, ..N].
2035 fn as_mut_slice(self) -> &'a mut [T];
2037 /// Return a slice that points into another slice.
2038 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T];
2041 * Returns a slice of self from `start` to the end of the vec.
2043 * Fails when `start` points outside the bounds of self.
2045 fn mut_slice_from(self, start: uint) -> &'a mut [T];
2048 * Returns a slice of self from the start of the vec to `end`.
2050 * Fails when `end` points outside the bounds of self.
2052 fn mut_slice_to(self, end: uint) -> &'a mut [T];
2054 /// Returns an iterator that allows modifying each value
2055 fn mut_iter(self) -> MutItems<'a, T>;
2057 /// Returns a mutable pointer to the last item in the vector.
2058 fn mut_last(self) -> Option<&'a mut T>;
2060 /// Returns a reversed iterator that allows modifying each value
2061 fn mut_rev_iter(self) -> RevMutItems<'a, T>;
2063 /// Returns an iterator over the mutable subslices of the vector
2064 /// which are separated by elements that match `pred`. The
2065 /// matched element is not contained in the subslices.
2066 fn mut_split(self, pred: 'a |&T| -> bool) -> MutSplits<'a, T>;
2069 * Returns an iterator over `size` elements of the vector at a time.
2070 * The chunks are mutable and do not overlap. If `size` does not divide the
2071 * length of the vector, then the last chunk will not have length
2076 * Fails if `size` is 0.
2078 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T>;
2081 * Returns a mutable reference to the first element in this slice
2082 * and adjusts the slice in place so that it no longer contains
2083 * that element. O(1).
2088 * if self.len() == 0 { return None; }
2089 * let head = &mut self[0];
2090 * *self = self.mut_slice_from(1);
2094 * Returns `None` if slice is empty
2096 fn mut_shift_ref(&mut self) -> Option<&'a mut T>;
2099 * Returns a mutable reference to the last element in this slice
2100 * and adjusts the slice in place so that it no longer contains
2101 * that element. O(1).
2106 * if self.len() == 0 { return None; }
2107 * let tail = &mut self[self.len() - 1];
2108 * *self = self.mut_slice_to(self.len() - 1);
2112 * Returns `None` if slice is empty.
2114 fn mut_pop_ref(&mut self) -> Option<&'a mut T>;
2116 /// Swaps two elements in a vector.
2118 /// Fails if `a` or `b` are out of bounds.
2122 /// * a - The index of the first element
2123 /// * b - The index of the second element
2128 /// let mut v = ["a", "b", "c", "d"];
2130 /// assert!(v == ["a", "d", "c", "b"]);
2132 fn swap(self, a: uint, b: uint);
2135 /// Divides one `&mut` into two at an index.
2137 /// The first will contain all indices from `[0, mid)` (excluding
2138 /// the index `mid` itself) and the second will contain all
2139 /// indices from `[mid, len)` (excluding the index `len` itself).
2141 /// Fails if `mid > len`.
2146 /// let mut v = [1, 2, 3, 4, 5, 6];
2148 /// // scoped to restrict the lifetime of the borrows
2150 /// let (left, right) = v.mut_split_at(0);
2151 /// assert!(left == &mut []);
2152 /// assert!(right == &mut [1, 2, 3, 4, 5, 6]);
2156 /// let (left, right) = v.mut_split_at(2);
2157 /// assert!(left == &mut [1, 2]);
2158 /// assert!(right == &mut [3, 4, 5, 6]);
2162 /// let (left, right) = v.mut_split_at(6);
2163 /// assert!(left == &mut [1, 2, 3, 4, 5, 6]);
2164 /// assert!(right == &mut []);
2167 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]);
2169 /// Reverse the order of elements in a vector, in place.
2174 /// let mut v = [1, 2, 3];
2176 /// assert!(v == [3, 2, 1]);
2180 /// Sort the vector, in place, using `compare` to compare
2183 /// This sort is `O(n log n)` worst-case and stable, but allocates
2184 /// approximately `2 * n`, where `n` is the length of `self`.
2189 /// let mut v = [5i, 4, 1, 3, 2];
2190 /// v.sort_by(|a, b| a.cmp(b));
2191 /// assert!(v == [1, 2, 3, 4, 5]);
2193 /// // reverse sorting
2194 /// v.sort_by(|a, b| b.cmp(a));
2195 /// assert!(v == [5, 4, 3, 2, 1]);
2197 fn sort_by(self, compare: |&T, &T| -> Ordering);
2200 * Consumes `src` and moves as many elements as it can into `self`
2201 * from the range [start,end).
2203 * Returns the number of elements copied (the shorter of self.len()
2208 * * src - A mutable vector of `T`
2209 * * start - The index into `src` to start copying from
2210 * * end - The index into `str` to stop copying from
2212 fn move_from(self, src: ~[T], start: uint, end: uint) -> uint;
2214 /// Returns an unsafe mutable pointer to the element in index
2215 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T;
2217 /// Return an unsafe mutable pointer to the vector's buffer.
2219 /// The caller must ensure that the vector outlives the pointer this
2220 /// function returns, or else it will end up pointing to garbage.
2222 /// Modifying the vector may cause its buffer to be reallocated, which
2223 /// would also make any pointers to it invalid.
2225 fn as_mut_ptr(self) -> *mut T;
2227 /// Unsafely sets the element in index to the value.
2229 /// This performs no bounds checks, and it is undefined behaviour
2230 /// if `index` is larger than the length of `self`. However, it
2231 /// does run the destructor at `index`. It is equivalent to
2232 /// `self[index] = val`.
2237 /// let mut v = ~[~"foo", ~"bar", ~"baz"];
2240 /// // `~"baz"` is deallocated.
2241 /// v.unsafe_set(2, ~"qux");
2243 /// // Out of bounds: could cause a crash, or overwriting
2244 /// // other data, or something else.
2245 /// // v.unsafe_set(10, ~"oops");
2248 unsafe fn unsafe_set(self, index: uint, val: T);
2250 /// Unchecked vector index assignment. Does not drop the
2251 /// old value and hence is only suitable when the vector
2252 /// is newly allocated.
2257 /// let mut v = [~"foo", ~"bar"];
2259 /// // memory leak! `~"bar"` is not deallocated.
2260 /// unsafe { v.init_elem(1, ~"baz"); }
2262 unsafe fn init_elem(self, i: uint, val: T);
2264 /// Copies raw bytes from `src` to `self`.
2266 /// This does not run destructors on the overwritten elements, and
2267 /// ignores move semantics. `self` and `src` must not
2268 /// overlap. Fails if `self` is shorter than `src`.
2269 unsafe fn copy_memory(self, src: &[T]);
2272 impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
2274 fn as_mut_slice(self) -> &'a mut [T] { self }
2276 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T] {
2277 assert!(start <= end);
2278 assert!(end <= self.len());
2281 data: self.as_mut_ptr().offset(start as int) as *T,
2288 fn mut_slice_from(self, start: uint) -> &'a mut [T] {
2289 let len = self.len();
2290 self.mut_slice(start, len)
2294 fn mut_slice_to(self, end: uint) -> &'a mut [T] {
2295 self.mut_slice(0, end)
2299 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
2301 let len = self.len();
2302 let self2: &'a mut [T] = cast::transmute_copy(&self);
2303 (self.mut_slice(0, mid), self2.mut_slice(mid, len))
2308 fn mut_iter(self) -> MutItems<'a, T> {
2310 let p = self.as_mut_ptr();
2311 if mem::size_of::<T>() == 0 {
2313 end: (p as uint + self.len()) as *mut T,
2314 marker: marker::ContravariantLifetime::<'a>}
2317 end: p.offset(self.len() as int),
2318 marker: marker::ContravariantLifetime::<'a>}
2324 fn mut_last(self) -> Option<&'a mut T> {
2325 let len = self.len();
2326 if len == 0 { return None; }
2327 Some(&mut self[len - 1])
2331 fn mut_rev_iter(self) -> RevMutItems<'a, T> {
2332 self.mut_iter().rev()
2336 fn mut_split(self, pred: 'a |&T| -> bool) -> MutSplits<'a, T> {
2337 MutSplits { v: self, pred: pred, finished: false }
2341 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T> {
2342 assert!(chunk_size > 0);
2343 MutChunks { v: self, chunk_size: chunk_size }
2346 fn mut_shift_ref(&mut self) -> Option<&'a mut T> {
2347 if self.len() == 0 { return None; }
2349 let s: &mut Slice<T> = transmute(self);
2350 Some(cast::transmute_mut(&*raw::shift_ptr(s)))
2354 fn mut_pop_ref(&mut self) -> Option<&'a mut T> {
2355 if self.len() == 0 { return None; }
2357 let s: &mut Slice<T> = transmute(self);
2358 Some(cast::transmute_mut(&*raw::pop_ptr(s)))
2362 fn swap(self, a: uint, b: uint) {
2364 // Can't take two mutable loans from one vector, so instead just cast
2365 // them to their raw pointers to do the swap
2366 let pa: *mut T = &mut self[a];
2367 let pb: *mut T = &mut self[b];
2373 let mut i: uint = 0;
2374 let ln = self.len();
2376 self.swap(i, ln - i - 1);
2382 fn sort_by(self, compare: |&T, &T| -> Ordering) {
2383 merge_sort(self, compare)
2387 fn move_from(self, mut src: ~[T], start: uint, end: uint) -> uint {
2388 for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
2391 cmp::min(self.len(), end-start)
2395 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T {
2396 transmute((self.repr().data as *mut T).offset(index as int))
2400 fn as_mut_ptr(self) -> *mut T {
2401 self.repr().data as *mut T
2405 unsafe fn unsafe_set(self, index: uint, val: T) {
2406 *self.unsafe_mut_ref(index) = val;
2410 unsafe fn init_elem(self, i: uint, val: T) {
2411 mem::move_val_init(&mut (*self.as_mut_ptr().offset(i as int)), val);
2415 unsafe fn copy_memory(self, src: &[T]) {
2416 let len_src = src.len();
2417 assert!(self.len() >= len_src);
2418 ptr::copy_nonoverlapping_memory(self.as_mut_ptr(), src.as_ptr(), len_src)
2422 /// Trait for &[T] where T is Cloneable
2423 pub trait MutableCloneableVector<T> {
2424 /// Copies as many elements from `src` as it can into `self` (the
2425 /// shorter of `self.len()` and `src.len()`). Returns the number
2426 /// of elements copied.
2431 /// use std::vec::MutableCloneableVector;
2433 /// let mut dst = [0, 0, 0];
2434 /// let src = [1, 2];
2436 /// assert!(dst.copy_from(src) == 2);
2437 /// assert!(dst == [1, 2, 0]);
2439 /// let src2 = [3, 4, 5, 6];
2440 /// assert!(dst.copy_from(src2) == 3);
2441 /// assert!(dst == [3, 4, 5]);
2443 fn copy_from(self, &[T]) -> uint;
2446 impl<'a, T:Clone> MutableCloneableVector<T> for &'a mut [T] {
2448 fn copy_from(self, src: &[T]) -> uint {
2449 for (a, b) in self.mut_iter().zip(src.iter()) {
2452 cmp::min(self.len(), src.len())
2456 /// Methods for mutable vectors with orderable elements, such as
2457 /// in-place sorting.
2458 pub trait MutableTotalOrdVector<T> {
2459 /// Sort the vector, in place.
2461 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
2466 /// let mut v = [-5, 4, 1, -3, 2];
2469 /// assert!(v == [-5, -3, 1, 2, 4]);
2473 impl<'a, T: TotalOrd> MutableTotalOrdVector<T> for &'a mut [T] {
2476 self.sort_by(|a,b| a.cmp(b))
2481 * Constructs a vector from an unsafe pointer to a buffer
2485 * * ptr - An unsafe pointer to a buffer of `T`
2486 * * elts - The number of elements in the buffer
2488 // Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
2489 pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
2490 raw::from_buf_raw(ptr, elts)
2493 /// Unsafe operations
2495 use cast::transmute;
2498 use vec::{with_capacity, MutableVector, OwnedVector};
2502 * Form a slice from a pointer and length (as a number of units,
2506 pub unsafe fn buf_as_slice<T,U>(p: *T, len: uint, f: |v: &[T]| -> U)
2515 * Form a slice from a pointer and length (as a number of units,
2519 pub unsafe fn mut_buf_as_slice<T,
2523 f: |v: &mut [T]| -> U)
2532 * Constructs a vector from an unsafe pointer to a buffer
2536 * * ptr - An unsafe pointer to a buffer of `T`
2537 * * elts - The number of elements in the buffer
2539 // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
2541 pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
2542 let mut dst = with_capacity(elts);
2544 ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
2549 * Returns a pointer to first element in slice and adjusts
2550 * slice so it no longer contains that element. Fails if
2551 * slice is empty. O(1).
2553 pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> *T {
2554 if slice.len == 0 { fail!("shift on empty slice"); }
2555 let head: *T = slice.data;
2556 slice.data = slice.data.offset(1);
2562 * Returns a pointer to last element in slice and adjusts
2563 * slice so it no longer contains that element. Fails if
2564 * slice is empty. O(1).
2566 pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> *T {
2567 if slice.len == 0 { fail!("pop on empty slice"); }
2568 let tail: *T = slice.data.offset((slice.len - 1) as int);
2574 /// Operations on `[u8]`.
2576 use container::Container;
2577 use vec::{MutableVector, OwnedVector, ImmutableVector};
2581 /// A trait for operations on mutable `[u8]`s.
2582 pub trait MutableByteVector {
2583 /// Sets all bytes of the receiver to the given value.
2584 fn set_memory(self, value: u8);
2587 impl<'a> MutableByteVector for &'a mut [u8] {
2589 fn set_memory(self, value: u8) {
2590 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
2594 /// Copies data from `src` to `dst`
2596 /// `src` and `dst` must not overlap. Fails if the length of `dst`
2597 /// is less than the length of `src`.
2599 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
2600 // Bound checks are done at .copy_memory.
2601 unsafe { dst.copy_memory(src) }
2605 * Allocate space in `dst` and append the data to `src`.
2608 pub fn push_bytes(dst: &mut ~[u8], src: &[u8]) {
2609 let old_len = dst.len();
2610 dst.reserve_additional(src.len());
2612 ptr::copy_memory(dst.as_mut_ptr().offset(old_len as int), src.as_ptr(), src.len());
2613 dst.set_len(old_len + src.len());
2618 impl<A: Clone> Clone for ~[A] {
2620 fn clone(&self) -> ~[A] {
2621 self.iter().map(|item| item.clone()).collect()
2624 fn clone_from(&mut self, source: &~[A]) {
2625 if self.len() < source.len() {
2626 *self = source.clone()
2628 self.truncate(source.len());
2629 for (x, y) in self.mut_iter().zip(source.iter()) {
2636 impl<A: DeepClone> DeepClone for ~[A] {
2638 fn deep_clone(&self) -> ~[A] {
2639 self.iter().map(|item| item.deep_clone()).collect()
2642 fn deep_clone_from(&mut self, source: &~[A]) {
2643 if self.len() < source.len() {
2644 *self = source.deep_clone()
2646 self.truncate(source.len());
2647 for (x, y) in self.mut_iter().zip(source.iter()) {
2648 x.deep_clone_from(y);
2654 impl<'a, T: fmt::Show> fmt::Show for &'a [T] {
2655 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2656 try!(write!(f.buf, "["));
2657 let mut is_first = true;
2658 for x in self.iter() {
2662 try!(write!(f.buf, ", "));
2664 try!(write!(f.buf, "{}", *x))
2670 impl<T: fmt::Show> fmt::Show for ~[T] {
2671 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2672 self.as_slice().fmt(f)
2676 // This works because every lifetime is a sub-lifetime of 'static
2677 impl<'a, A> Default for &'a [A] {
2678 fn default() -> &'a [A] { &'a [] }
2681 impl<A> Default for ~[A] {
2682 fn default() -> ~[A] { ~[] }
2685 macro_rules! iterator {
2686 (struct $name:ident -> $ptr:ty, $elem:ty) => {
2687 /// An iterator for iterating over a vector.
2688 pub struct $name<'a, T> {
2691 priv marker: marker::ContravariantLifetime<'a>,
2694 impl<'a, T> Iterator<$elem> for $name<'a, T> {
2696 fn next(&mut self) -> Option<$elem> {
2697 // could be implemented with slices, but this avoids bounds checks
2699 if self.ptr == self.end {
2703 self.ptr = if mem::size_of::<T>() == 0 {
2704 // purposefully don't use 'ptr.offset' because for
2705 // vectors with 0-size elements this would return the
2707 transmute(self.ptr as uint + 1)
2712 Some(transmute(old))
2718 fn size_hint(&self) -> (uint, Option<uint>) {
2719 let diff = (self.end as uint) - (self.ptr as uint);
2720 let exact = diff / mem::nonzero_size_of::<T>();
2721 (exact, Some(exact))
2725 impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
2727 fn next_back(&mut self) -> Option<$elem> {
2728 // could be implemented with slices, but this avoids bounds checks
2730 if self.end == self.ptr {
2733 self.end = if mem::size_of::<T>() == 0 {
2734 // See above for why 'ptr.offset' isn't used
2735 transmute(self.end as uint - 1)
2739 Some(transmute(self.end))
2747 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
2749 fn indexable(&self) -> uint {
2750 let (exact, _) = self.size_hint();
2755 fn idx(&self, index: uint) -> Option<&'a T> {
2757 if index < self.indexable() {
2758 transmute(self.ptr.offset(index as int))
2766 iterator!{struct Items -> *T, &'a T}
2767 pub type RevItems<'a, T> = Rev<Items<'a, T>>;
2769 impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
2770 impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
2772 impl<'a, T> Clone for Items<'a, T> {
2773 fn clone(&self) -> Items<'a, T> { *self }
2776 iterator!{struct MutItems -> *mut T, &'a mut T}
2777 pub type RevMutItems<'a, T> = Rev<MutItems<'a, T>>;
2779 /// An iterator over the subslices of the vector which are separated
2780 /// by elements that match `pred`.
2781 pub struct MutSplits<'a, T> {
2782 priv v: &'a mut [T],
2783 priv pred: 'a |t: &T| -> bool,
2787 impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
2789 fn next(&mut self) -> Option<&'a mut [T]> {
2790 if self.finished { return None; }
2792 match self.v.iter().position(|x| (self.pred)(x)) {
2794 self.finished = true;
2795 let tmp = mem::replace(&mut self.v, &mut []);
2796 let len = tmp.len();
2797 let (head, tail) = tmp.mut_split_at(len);
2802 let tmp = mem::replace(&mut self.v, &mut []);
2803 let (head, tail) = tmp.mut_split_at(idx);
2804 self.v = tail.mut_slice_from(1);
2811 fn size_hint(&self) -> (uint, Option<uint>) {
2815 // if the predicate doesn't match anything, we yield one slice
2816 // if it matches every element, we yield len+1 empty slices.
2817 (1, Some(self.v.len() + 1))
2822 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
2824 fn next_back(&mut self) -> Option<&'a mut [T]> {
2825 if self.finished { return None; }
2827 match self.v.iter().rposition(|x| (self.pred)(x)) {
2829 self.finished = true;
2830 let tmp = mem::replace(&mut self.v, &mut []);
2834 let tmp = mem::replace(&mut self.v, &mut []);
2835 let (head, tail) = tmp.mut_split_at(idx);
2837 Some(tail.mut_slice_from(1))
2843 /// An iterator over a vector in (non-overlapping) mutable chunks (`size` elements at a time). When
2844 /// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be
2846 pub struct MutChunks<'a, T> {
2847 priv v: &'a mut [T],
2848 priv chunk_size: uint
2851 impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
2853 fn next(&mut self) -> Option<&'a mut [T]> {
2854 if self.v.len() == 0 {
2857 let sz = cmp::min(self.v.len(), self.chunk_size);
2858 let tmp = mem::replace(&mut self.v, &mut []);
2859 let (head, tail) = tmp.mut_split_at(sz);
2866 fn size_hint(&self) -> (uint, Option<uint>) {
2867 if self.v.len() == 0 {
2870 let (n, rem) = div_rem(self.v.len(), self.chunk_size);
2871 let n = if rem > 0 { n + 1 } else { n };
2877 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
2879 fn next_back(&mut self) -> Option<&'a mut [T]> {
2880 if self.v.len() == 0 {
2883 let remainder = self.v.len() % self.chunk_size;
2884 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2885 let tmp = mem::replace(&mut self.v, &mut []);
2886 let tmp_len = tmp.len();
2887 let (head, tail) = tmp.mut_split_at(tmp_len - sz);
2894 /// An iterator that moves out of a vector.
2895 pub struct MoveItems<T> {
2896 priv allocation: *mut u8, // the block of memory allocated for the vector
2897 priv iter: Items<'static, T>
2900 impl<T> Iterator<T> for MoveItems<T> {
2902 fn next(&mut self) -> Option<T> {
2904 self.iter.next().map(|x| ptr::read(x))
2909 fn size_hint(&self) -> (uint, Option<uint>) {
2910 self.iter.size_hint()
2914 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
2916 fn next_back(&mut self) -> Option<T> {
2918 self.iter.next_back().map(|x| ptr::read(x))
2923 #[unsafe_destructor]
2924 impl<T> Drop for MoveItems<T> {
2925 fn drop(&mut self) {
2926 // destroy the remaining elements
2929 exchange_free(self.allocation as *u8)
2934 /// An iterator that moves out of a vector in reverse order.
2935 pub type RevMoveItems<T> = Rev<MoveItems<T>>;
2937 impl<A> FromIterator<A> for ~[A] {
2938 fn from_iterator<T: Iterator<A>>(iterator: &mut T) -> ~[A] {
2939 let (lower, _) = iterator.size_hint();
2940 let mut xs = with_capacity(lower);
2941 for x in *iterator {
2948 impl<A> Extendable<A> for ~[A] {
2949 fn extend<T: Iterator<A>>(&mut self, iterator: &mut T) {
2950 let (lower, _) = iterator.size_hint();
2951 let len = self.len();
2952 self.reserve_exact(len + lower);
2953 for x in *iterator {
2965 use rand::{Rng, task_rng};
2967 fn square(n: uint) -> uint { n * n }
2969 fn square_ref(n: &uint) -> uint { square(*n) }
2971 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
2974 fn test_unsafe_ptrs() {
2976 // Test on-stack copy-from-buf.
2978 let mut ptr = a.as_ptr();
2979 let b = from_buf(ptr, 3u);
2980 assert_eq!(b.len(), 3u);
2981 assert_eq!(b[0], 1);
2982 assert_eq!(b[1], 2);
2983 assert_eq!(b[2], 3);
2985 // Test on-heap copy-from-buf.
2986 let c = ~[1, 2, 3, 4, 5];
2988 let d = from_buf(ptr, 5u);
2989 assert_eq!(d.len(), 5u);
2990 assert_eq!(d[0], 1);
2991 assert_eq!(d[1], 2);
2992 assert_eq!(d[2], 3);
2993 assert_eq!(d[3], 4);
2994 assert_eq!(d[4], 5);
3000 // Test on-stack from_fn.
3001 let mut v = from_fn(3u, square);
3002 assert_eq!(v.len(), 3u);
3003 assert_eq!(v[0], 0u);
3004 assert_eq!(v[1], 1u);
3005 assert_eq!(v[2], 4u);
3007 // Test on-heap from_fn.
3008 v = from_fn(5u, square);
3009 assert_eq!(v.len(), 5u);
3010 assert_eq!(v[0], 0u);
3011 assert_eq!(v[1], 1u);
3012 assert_eq!(v[2], 4u);
3013 assert_eq!(v[3], 9u);
3014 assert_eq!(v[4], 16u);
3018 fn test_from_elem() {
3019 // Test on-stack from_elem.
3020 let mut v = from_elem(2u, 10u);
3021 assert_eq!(v.len(), 2u);
3022 assert_eq!(v[0], 10u);
3023 assert_eq!(v[1], 10u);
3025 // Test on-heap from_elem.
3026 v = from_elem(6u, 20u);
3027 assert_eq!(v[0], 20u);
3028 assert_eq!(v[1], 20u);
3029 assert_eq!(v[2], 20u);
3030 assert_eq!(v[3], 20u);
3031 assert_eq!(v[4], 20u);
3032 assert_eq!(v[5], 20u);
3036 fn test_is_empty() {
3037 let xs: [int, ..0] = [];
3038 assert!(xs.is_empty());
3039 assert!(![0].is_empty());
3043 fn test_len_divzero() {
3045 let v0 : &[Z] = &[];
3046 let v1 : &[Z] = &[[]];
3047 let v2 : &[Z] = &[[], []];
3048 assert_eq!(mem::size_of::<Z>(), 0);
3049 assert_eq!(v0.len(), 0);
3050 assert_eq!(v1.len(), 1);
3051 assert_eq!(v2.len(), 2);
3057 assert_eq!(a.get(1), None);
3059 assert_eq!(a.get(1).unwrap(), &12);
3061 assert_eq!(a.get(1).unwrap(), &12);
3067 assert_eq!(a.head(), None);
3069 assert_eq!(a.head().unwrap(), &11);
3071 assert_eq!(a.head().unwrap(), &11);
3077 assert_eq!(a.tail(), &[]);
3079 assert_eq!(a.tail(), &[12]);
3084 fn test_tail_empty() {
3085 let a: ~[int] = ~[];
3091 let mut a = ~[11, 12, 13];
3092 assert_eq!(a.tailn(0), &[11, 12, 13]);
3094 assert_eq!(a.tailn(2), &[13]);
3099 fn test_tailn_empty() {
3100 let a: ~[int] = ~[];
3107 assert_eq!(a.init(), &[]);
3109 assert_eq!(a.init(), &[11]);
3114 fn test_init_empty() {
3115 let a: ~[int] = ~[];
3121 let mut a = ~[11, 12, 13];
3122 assert_eq!(a.initn(0), &[11, 12, 13]);
3124 assert_eq!(a.initn(2), &[11]);
3129 fn test_initn_empty() {
3130 let a: ~[int] = ~[];
3137 assert_eq!(a.last(), None);
3139 assert_eq!(a.last().unwrap(), &11);
3141 assert_eq!(a.last().unwrap(), &12);
3146 // Test fixed length vector.
3147 let vec_fixed = [1, 2, 3, 4];
3148 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
3149 assert_eq!(v_a.len(), 3u);
3150 assert_eq!(v_a[0], 2);
3151 assert_eq!(v_a[1], 3);
3152 assert_eq!(v_a[2], 4);
3155 let vec_stack = &[1, 2, 3];
3156 let v_b = vec_stack.slice(1u, 3u).to_owned();
3157 assert_eq!(v_b.len(), 2u);
3158 assert_eq!(v_b[0], 2);
3159 assert_eq!(v_b[1], 3);
3161 // Test on exchange heap.
3162 let vec_unique = ~[1, 2, 3, 4, 5, 6];
3163 let v_d = vec_unique.slice(1u, 6u).to_owned();
3164 assert_eq!(v_d.len(), 5u);
3165 assert_eq!(v_d[0], 2);
3166 assert_eq!(v_d[1], 3);
3167 assert_eq!(v_d[2], 4);
3168 assert_eq!(v_d[3], 5);
3169 assert_eq!(v_d[4], 6);
3173 fn test_slice_from() {
3174 let vec = &[1, 2, 3, 4];
3175 assert_eq!(vec.slice_from(0), vec);
3176 assert_eq!(vec.slice_from(2), &[3, 4]);
3177 assert_eq!(vec.slice_from(4), &[]);
3181 fn test_slice_to() {
3182 let vec = &[1, 2, 3, 4];
3183 assert_eq!(vec.slice_to(4), vec);
3184 assert_eq!(vec.slice_to(2), &[1, 2]);
3185 assert_eq!(vec.slice_to(0), &[]);
3193 assert_eq!(v.len(), 0);
3194 assert_eq!(e, Some(5));
3196 assert_eq!(f, None);
3198 assert_eq!(g, None);
3202 fn test_swap_remove() {
3203 let mut v = ~[1, 2, 3, 4, 5];
3204 let mut e = v.swap_remove(0);
3205 assert_eq!(e, Some(1));
3206 assert_eq!(v, ~[5, 2, 3, 4]);
3207 e = v.swap_remove(3);
3208 assert_eq!(e, Some(4));
3209 assert_eq!(v, ~[5, 2, 3]);
3211 e = v.swap_remove(3);
3212 assert_eq!(e, None);
3213 assert_eq!(v, ~[5, 2, 3]);
3217 fn test_swap_remove_noncopyable() {
3218 // Tests that we don't accidentally run destructors twice.
3219 let mut v = ~[::unstable::sync::Exclusive::new(()),
3220 ::unstable::sync::Exclusive::new(()),
3221 ::unstable::sync::Exclusive::new(())];
3222 let mut _e = v.swap_remove(0);
3223 assert_eq!(v.len(), 2);
3224 _e = v.swap_remove(1);
3225 assert_eq!(v.len(), 1);
3226 _e = v.swap_remove(0);
3227 assert_eq!(v.len(), 0);
3232 // Test on-stack push().
3235 assert_eq!(v.len(), 1u);
3236 assert_eq!(v[0], 1);
3238 // Test on-heap push().
3240 assert_eq!(v.len(), 2u);
3241 assert_eq!(v[0], 1);
3242 assert_eq!(v[1], 2);
3247 // Test on-stack grow().
3250 assert_eq!(v.len(), 2u);
3251 assert_eq!(v[0], 1);
3252 assert_eq!(v[1], 1);
3254 // Test on-heap grow().
3256 assert_eq!(v.len(), 5u);
3257 assert_eq!(v[0], 1);
3258 assert_eq!(v[1], 1);
3259 assert_eq!(v[2], 2);
3260 assert_eq!(v[3], 2);
3261 assert_eq!(v[4], 2);
3267 v.grow_fn(3u, square);
3268 assert_eq!(v.len(), 3u);
3269 assert_eq!(v[0], 0u);
3270 assert_eq!(v[1], 1u);
3271 assert_eq!(v[2], 4u);
3275 fn test_grow_set() {
3276 let mut v = ~[1, 2, 3];
3277 v.grow_set(4u, &4, 5);
3278 assert_eq!(v.len(), 5u);
3279 assert_eq!(v[0], 1);
3280 assert_eq!(v[1], 2);
3281 assert_eq!(v[2], 3);
3282 assert_eq!(v[3], 4);
3283 assert_eq!(v[4], 5);
3287 fn test_truncate() {
3288 let mut v = ~[~6,~5,~4];
3290 assert_eq!(v.len(), 1);
3291 assert_eq!(*(v[0]), 6);
3292 // If the unsafe block didn't drop things properly, we blow up here.
3297 let mut v = ~[~6,~5,~4];
3299 assert_eq!(v.len(), 0);
3300 // If the unsafe block didn't drop things properly, we blow up here.
3305 fn case(a: ~[uint], b: ~[uint]) {
3313 case(~[1,2,3], ~[1,2,3]);
3314 case(~[1,1,2,3], ~[1,2,3]);
3315 case(~[1,2,2,3], ~[1,2,3]);
3316 case(~[1,2,3,3], ~[1,2,3]);
3317 case(~[1,1,2,2,2,3,3], ~[1,2,3]);
3321 fn test_dedup_unique() {
3322 let mut v0 = ~[~1, ~1, ~2, ~3];
3324 let mut v1 = ~[~1, ~2, ~2, ~3];
3326 let mut v2 = ~[~1, ~2, ~3, ~3];
3329 * If the ~pointers were leaked or otherwise misused, valgrind and/or
3330 * rustrt should raise errors.
3335 fn test_dedup_shared() {
3336 let mut v0 = ~[~1, ~1, ~2, ~3];
3338 let mut v1 = ~[~1, ~2, ~2, ~3];
3340 let mut v2 = ~[~1, ~2, ~3, ~3];
3343 * If the pointers were leaked or otherwise misused, valgrind and/or
3344 * rustrt should raise errors.
3350 // Test on-stack map.
3351 let v = &[1u, 2u, 3u];
3352 let mut w = v.map(square_ref);
3353 assert_eq!(w.len(), 3u);
3354 assert_eq!(w[0], 1u);
3355 assert_eq!(w[1], 4u);
3356 assert_eq!(w[2], 9u);
3358 // Test on-heap map.
3359 let v = ~[1u, 2u, 3u, 4u, 5u];
3360 w = v.map(square_ref);
3361 assert_eq!(w.len(), 5u);
3362 assert_eq!(w[0], 1u);
3363 assert_eq!(w[1], 4u);
3364 assert_eq!(w[2], 9u);
3365 assert_eq!(w[3], 16u);
3366 assert_eq!(w[4], 25u);
3371 let mut v = ~[1, 2, 3, 4, 5];
3373 assert_eq!(v, ~[1, 3, 5]);
3377 fn test_zip_unzip() {
3378 let z1 = ~[(1, 4), (2, 5), (3, 6)];
3380 let (left, right) = unzip(z1.iter().map(|&x| x));
3382 assert_eq!((1, 4), (left[0], right[0]));
3383 assert_eq!((2, 5), (left[1], right[1]));
3384 assert_eq!((3, 6), (left[2], right[2]));
3388 fn test_element_swaps() {
3389 let mut v = [1, 2, 3];
3390 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
3393 0 => assert!(v == [1, 3, 2]),
3394 1 => assert!(v == [3, 1, 2]),
3395 2 => assert!(v == [3, 2, 1]),
3396 3 => assert!(v == [2, 3, 1]),
3397 4 => assert!(v == [2, 1, 3]),
3398 5 => assert!(v == [1, 2, 3]),
3405 fn test_permutations() {
3407 let v: [int, ..0] = [];
3408 let mut it = v.permutations();
3409 assert_eq!(it.next(), None);
3413 let mut it = v.permutations();
3414 assert_eq!(it.next(), None);
3418 let mut it = v.permutations();
3419 assert_eq!(it.next(), Some(~[1,2,3]));
3420 assert_eq!(it.next(), Some(~[1,3,2]));
3421 assert_eq!(it.next(), Some(~[3,1,2]));
3422 assert_eq!(it.next(), Some(~[3,2,1]));
3423 assert_eq!(it.next(), Some(~[2,3,1]));
3424 assert_eq!(it.next(), Some(~[2,1,3]));
3425 assert_eq!(it.next(), None);
3428 // check that we have N! permutations
3429 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
3431 for _perm in v.permutations() {
3434 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
3439 fn test_position_elem() {
3440 assert!([].position_elem(&1).is_none());
3442 let v1 = ~[1, 2, 3, 3, 2, 5];
3443 assert_eq!(v1.position_elem(&1), Some(0u));
3444 assert_eq!(v1.position_elem(&2), Some(1u));
3445 assert_eq!(v1.position_elem(&5), Some(5u));
3446 assert!(v1.position_elem(&4).is_none());
3450 fn test_bsearch_elem() {
3451 assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
3452 assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
3453 assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
3454 assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
3455 assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
3457 assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
3458 assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
3459 assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
3460 assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
3462 assert_eq!([2,4,6,8].bsearch_elem(&1), None);
3463 assert_eq!([2,4,6,8].bsearch_elem(&5), None);
3464 assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
3465 assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
3467 assert_eq!([2,4,6].bsearch_elem(&1), None);
3468 assert_eq!([2,4,6].bsearch_elem(&5), None);
3469 assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
3470 assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
3472 assert_eq!([2,4].bsearch_elem(&1), None);
3473 assert_eq!([2,4].bsearch_elem(&5), None);
3474 assert_eq!([2,4].bsearch_elem(&2), Some(0));
3475 assert_eq!([2,4].bsearch_elem(&4), Some(1));
3477 assert_eq!([2].bsearch_elem(&1), None);
3478 assert_eq!([2].bsearch_elem(&5), None);
3479 assert_eq!([2].bsearch_elem(&2), Some(0));
3481 assert_eq!([].bsearch_elem(&1), None);
3482 assert_eq!([].bsearch_elem(&5), None);
3484 assert!([1,1,1,1,1].bsearch_elem(&1) != None);
3485 assert!([1,1,1,1,2].bsearch_elem(&1) != None);
3486 assert!([1,1,1,2,2].bsearch_elem(&1) != None);
3487 assert!([1,1,2,2,2].bsearch_elem(&1) != None);
3488 assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
3490 assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
3491 assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
3496 let mut v: ~[int] = ~[10, 20];
3497 assert_eq!(v[0], 10);
3498 assert_eq!(v[1], 20);
3500 assert_eq!(v[0], 20);
3501 assert_eq!(v[1], 10);
3503 let mut v3: ~[int] = ~[];
3505 assert!(v3.is_empty());
3510 for len in range(4u, 25) {
3511 for _ in range(0, 100) {
3512 let mut v = task_rng().gen_vec::<uint>(len);
3513 let mut v1 = v.clone();
3516 assert!(v.windows(2).all(|w| w[0] <= w[1]));
3518 v1.sort_by(|a, b| a.cmp(b));
3519 assert!(v1.windows(2).all(|w| w[0] <= w[1]));
3521 v1.sort_by(|a, b| b.cmp(a));
3522 assert!(v1.windows(2).all(|w| w[0] >= w[1]));
3526 // shouldn't fail/crash
3527 let mut v: [uint, .. 0] = [];
3530 let mut v = [0xDEADBEEFu];
3532 assert!(v == [0xDEADBEEF]);
3536 fn test_sort_stability() {
3537 for len in range(4, 25) {
3538 for _ in range(0 , 10) {
3539 let mut counts = [0, .. 10];
3541 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
3542 // where the first item of each tuple is random, but
3543 // the second item represents which occurrence of that
3544 // number this element is, i.e. the second elements
3545 // will occur in sorted order.
3546 let mut v = range(0, len).map(|_| {
3547 let n = task_rng().gen::<uint>() % 10;
3552 // only sort on the first element, so an unstable sort
3553 // may mix up the counts.
3554 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
3556 // this comparison includes the count (the second item
3557 // of the tuple), so elements with equal first items
3558 // will need to be ordered with increasing
3559 // counts... i.e. exactly asserting that this sort is
3561 assert!(v.windows(2).all(|w| w[0] <= w[1]));
3567 fn test_partition() {
3568 assert_eq!((~[]).partition(|x: &int| *x < 3), (~[], ~[]));
3569 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
3570 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 2), (~[1], ~[2, 3]));
3571 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
3575 fn test_partitioned() {
3576 assert_eq!(([]).partitioned(|x: &int| *x < 3), (~[], ~[]))
3577 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
3578 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (~[1], ~[2, 3]));
3579 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
3584 let v: [~[int], ..0] = [];
3585 assert_eq!(v.concat_vec(), ~[]);
3586 assert_eq!([~[1], ~[2,3]].concat_vec(), ~[1, 2, 3]);
3588 assert_eq!([&[1], &[2,3]].concat_vec(), ~[1, 2, 3]);
3593 let v: [~[int], ..0] = [];
3594 assert_eq!(v.connect_vec(&0), ~[]);
3595 assert_eq!([~[1], ~[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
3596 assert_eq!([~[1], ~[2], ~[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
3598 assert_eq!(v.connect_vec(&0), ~[]);
3599 assert_eq!([&[1], &[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
3600 assert_eq!([&[1], &[2], &[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
3605 let mut x = ~[1, 2, 3];
3606 assert_eq!(x.shift(), Some(1));
3607 assert_eq!(&x, &~[2, 3]);
3608 assert_eq!(x.shift(), Some(2));
3609 assert_eq!(x.shift(), Some(3));
3610 assert_eq!(x.shift(), None);
3611 assert_eq!(x.len(), 0);
3616 let mut x = ~[1, 2, 3];
3618 assert_eq!(x, ~[0, 1, 2, 3]);
3623 let mut a = ~[1, 2, 4];
3625 assert_eq!(a, ~[1, 2, 3, 4]);
3627 let mut a = ~[1, 2, 3];
3629 assert_eq!(a, ~[0, 1, 2, 3]);
3631 let mut a = ~[1, 2, 3];
3633 assert_eq!(a, ~[1, 2, 3, 4]);
3637 assert_eq!(a, ~[1]);
3642 fn test_insert_oob() {
3643 let mut a = ~[1, 2, 3];
3649 let mut a = ~[1,2,3,4];
3651 assert_eq!(a.remove(2), Some(3));
3652 assert_eq!(a, ~[1,2,4]);
3654 assert_eq!(a.remove(2), Some(4));
3655 assert_eq!(a, ~[1,2]);
3657 assert_eq!(a.remove(2), None);
3658 assert_eq!(a, ~[1,2]);
3660 assert_eq!(a.remove(0), Some(1));
3661 assert_eq!(a, ~[2]);
3663 assert_eq!(a.remove(0), Some(2));
3666 assert_eq!(a.remove(0), None);
3667 assert_eq!(a.remove(10), None);
3671 fn test_capacity() {
3672 let mut v = ~[0u64];
3673 v.reserve_exact(10u);
3674 assert_eq!(v.capacity(), 10u);
3675 let mut v = ~[0u32];
3676 v.reserve_exact(10u);
3677 assert_eq!(v.capacity(), 10u);
3682 let v = ~[1, 2, 3, 4, 5];
3683 let v = v.slice(1u, 3u);
3684 assert_eq!(v.len(), 2u);
3685 assert_eq!(v[0], 2);
3686 assert_eq!(v[1], 3);
3692 fn test_from_fn_fail() {
3694 if v == 50 { fail!() }
3701 fn test_from_elem_fail() {
3707 boxes: (~int, Rc<int>)
3711 fn clone(&self) -> S {
3712 let s = unsafe { cast::transmute_mut(self) };
3714 if s.f == 10 { fail!() }
3715 S { f: s.f, boxes: s.boxes.clone() }
3719 let s = S { f: 0, boxes: (~0, Rc::new(0)) };
3720 let _ = from_elem(100, s);
3725 fn test_build_fail() {
3727 build(None, |push| {
3728 push((~0, Rc::new(0)));
3729 push((~0, Rc::new(0)));
3730 push((~0, Rc::new(0)));
3731 push((~0, Rc::new(0)));
3738 fn test_grow_fn_fail() {
3741 v.grow_fn(100, |i| {
3751 fn test_map_fail() {
3753 let v = [(~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0))];
3766 fn test_flat_map_fail() {
3768 let v = [(~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0))];
3770 flat_map(v, |_elt| {
3781 fn test_permute_fail() {
3783 let v = [(~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0))];
3785 for _ in v.permutations() {
3795 fn test_copy_memory_oob() {
3797 let mut a = [1, 2, 3, 4];
3798 let b = [1, 2, 3, 4, 5];
3804 fn test_total_ord() {
3805 [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
3806 [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
3807 [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
3808 [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
3809 [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
3813 fn test_iterator() {
3815 let xs = [1, 2, 5, 10, 11];
3816 let mut it = xs.iter();
3817 assert_eq!(it.size_hint(), (5, Some(5)));
3818 assert_eq!(it.next().unwrap(), &1);
3819 assert_eq!(it.size_hint(), (4, Some(4)));
3820 assert_eq!(it.next().unwrap(), &2);
3821 assert_eq!(it.size_hint(), (3, Some(3)));
3822 assert_eq!(it.next().unwrap(), &5);
3823 assert_eq!(it.size_hint(), (2, Some(2)));
3824 assert_eq!(it.next().unwrap(), &10);
3825 assert_eq!(it.size_hint(), (1, Some(1)));
3826 assert_eq!(it.next().unwrap(), &11);
3827 assert_eq!(it.size_hint(), (0, Some(0)));
3828 assert!(it.next().is_none());
3832 fn test_random_access_iterator() {
3834 let xs = [1, 2, 5, 10, 11];
3835 let mut it = xs.iter();
3837 assert_eq!(it.indexable(), 5);
3838 assert_eq!(it.idx(0).unwrap(), &1);
3839 assert_eq!(it.idx(2).unwrap(), &5);
3840 assert_eq!(it.idx(4).unwrap(), &11);
3841 assert!(it.idx(5).is_none());
3843 assert_eq!(it.next().unwrap(), &1);
3844 assert_eq!(it.indexable(), 4);
3845 assert_eq!(it.idx(0).unwrap(), &2);
3846 assert_eq!(it.idx(3).unwrap(), &11);
3847 assert!(it.idx(4).is_none());
3849 assert_eq!(it.next().unwrap(), &2);
3850 assert_eq!(it.indexable(), 3);
3851 assert_eq!(it.idx(1).unwrap(), &10);
3852 assert!(it.idx(3).is_none());
3854 assert_eq!(it.next().unwrap(), &5);
3855 assert_eq!(it.indexable(), 2);
3856 assert_eq!(it.idx(1).unwrap(), &11);
3858 assert_eq!(it.next().unwrap(), &10);
3859 assert_eq!(it.indexable(), 1);
3860 assert_eq!(it.idx(0).unwrap(), &11);
3861 assert!(it.idx(1).is_none());
3863 assert_eq!(it.next().unwrap(), &11);
3864 assert_eq!(it.indexable(), 0);
3865 assert!(it.idx(0).is_none());
3867 assert!(it.next().is_none());
3871 fn test_iter_size_hints() {
3873 let mut xs = [1, 2, 5, 10, 11];
3874 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
3875 assert_eq!(xs.rev_iter().size_hint(), (5, Some(5)));
3876 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
3877 assert_eq!(xs.mut_rev_iter().size_hint(), (5, Some(5)));
3881 fn test_iter_clone() {
3883 let mut it = xs.iter();
3885 let mut jt = it.clone();
3886 assert_eq!(it.next(), jt.next());
3887 assert_eq!(it.next(), jt.next());
3888 assert_eq!(it.next(), jt.next());
3892 fn test_mut_iterator() {
3894 let mut xs = [1, 2, 3, 4, 5];
3895 for x in xs.mut_iter() {
3898 assert!(xs == [2, 3, 4, 5, 6])
3902 fn test_rev_iterator() {
3905 let xs = [1, 2, 5, 10, 11];
3906 let ys = [11, 10, 5, 2, 1];
3908 for &x in xs.rev_iter() {
3909 assert_eq!(x, ys[i]);
3916 fn test_mut_rev_iterator() {
3918 let mut xs = [1u, 2, 3, 4, 5];
3919 for (i,x) in xs.mut_rev_iter().enumerate() {
3922 assert!(xs == [5, 5, 5, 5, 5])
3926 fn test_move_iterator() {
3928 let xs = ~[1u,2,3,4,5];
3929 assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
3933 fn test_move_rev_iterator() {
3935 let xs = ~[1u,2,3,4,5];
3936 assert_eq!(xs.move_rev_iter().fold(0, |a: uint, b: uint| 10*a + b), 54321);
3940 fn test_splitator() {
3941 let xs = &[1i,2,3,4,5];
3943 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3944 ~[&[1], &[3], &[5]]);
3945 assert_eq!(xs.split(|x| *x == 1).collect::<~[&[int]]>(),
3946 ~[&[], &[2,3,4,5]]);
3947 assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(),
3948 ~[&[1,2,3,4], &[]]);
3949 assert_eq!(xs.split(|x| *x == 10).collect::<~[&[int]]>(),
3951 assert_eq!(xs.split(|_| true).collect::<~[&[int]]>(),
3952 ~[&[], &[], &[], &[], &[], &[]]);
3954 let xs: &[int] = &[];
3955 assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3959 fn test_splitnator() {
3960 let xs = &[1i,2,3,4,5];
3962 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3964 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3966 assert_eq!(xs.splitn(3, |_| true).collect::<~[&[int]]>(),
3967 ~[&[], &[], &[], &[4,5]]);
3969 let xs: &[int] = &[];
3970 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3974 fn test_rsplitator() {
3975 let xs = &[1i,2,3,4,5];
3977 assert_eq!(xs.rsplit(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3978 ~[&[5], &[3], &[1]]);
3979 assert_eq!(xs.rsplit(|x| *x == 1).collect::<~[&[int]]>(),
3980 ~[&[2,3,4,5], &[]]);
3981 assert_eq!(xs.rsplit(|x| *x == 5).collect::<~[&[int]]>(),
3982 ~[&[], &[1,2,3,4]]);
3983 assert_eq!(xs.rsplit(|x| *x == 10).collect::<~[&[int]]>(),
3986 let xs: &[int] = &[];
3987 assert_eq!(xs.rsplit(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3991 fn test_rsplitnator() {
3992 let xs = &[1,2,3,4,5];
3994 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3996 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3998 assert_eq!(xs.rsplitn(3, |_| true).collect::<~[&[int]]>(),
3999 ~[&[], &[], &[], &[1,2]]);
4001 let xs: &[int] = &[];
4002 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
4006 fn test_windowsator() {
4007 let v = &[1i,2,3,4];
4009 assert_eq!(v.windows(2).collect::<~[&[int]]>(), ~[&[1,2], &[2,3], &[3,4]]);
4010 assert_eq!(v.windows(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[2,3,4]]);
4011 assert!(v.windows(6).next().is_none());
4016 fn test_windowsator_0() {
4017 let v = &[1i,2,3,4];
4018 let _it = v.windows(0);
4022 fn test_chunksator() {
4023 let v = &[1i,2,3,4,5];
4025 assert_eq!(v.chunks(2).collect::<~[&[int]]>(), ~[&[1i,2], &[3,4], &[5]]);
4026 assert_eq!(v.chunks(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[4,5]]);
4027 assert_eq!(v.chunks(6).collect::<~[&[int]]>(), ~[&[1i,2,3,4,5]]);
4029 assert_eq!(v.chunks(2).rev().collect::<~[&[int]]>(), ~[&[5i], &[3,4], &[1,2]]);
4030 let it = v.chunks(2);
4031 assert_eq!(it.indexable(), 3);
4032 assert_eq!(it.idx(0).unwrap(), &[1,2]);
4033 assert_eq!(it.idx(1).unwrap(), &[3,4]);
4034 assert_eq!(it.idx(2).unwrap(), &[5]);
4035 assert_eq!(it.idx(3), None);
4040 fn test_chunksator_0() {
4041 let v = &[1i,2,3,4];
4042 let _it = v.chunks(0);
4046 fn test_move_from() {
4047 let mut a = [1,2,3,4,5];
4049 assert_eq!(a.move_from(b, 0, 3), 3);
4050 assert!(a == [6,7,8,4,5]);
4051 let mut a = [7,2,8,1];
4052 let b = ~[3,1,4,1,5,9];
4053 assert_eq!(a.move_from(b, 0, 6), 4);
4054 assert!(a == [3,1,4,1]);
4055 let mut a = [1,2,3,4];
4056 let b = ~[5,6,7,8,9,0];
4057 assert_eq!(a.move_from(b, 2, 3), 1);
4058 assert!(a == [7,2,3,4]);
4059 let mut a = [1,2,3,4,5];
4060 let b = ~[5,6,7,8,9,0];
4061 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
4062 assert!(a == [1,2,6,7,5]);
4066 fn test_copy_from() {
4067 let mut a = [1,2,3,4,5];
4069 assert_eq!(a.copy_from(b), 3);
4070 assert!(a == [6,7,8,4,5]);
4071 let mut c = [7,2,8,1];
4072 let d = [3,1,4,1,5,9];
4073 assert_eq!(c.copy_from(d), 4);
4074 assert!(c == [3,1,4,1]);
4078 fn test_reverse_part() {
4079 let mut values = [1,2,3,4,5];
4080 values.mut_slice(1, 4).reverse();
4081 assert!(values == [1,4,3,2,5]);
4086 macro_rules! test_show_vec(
4087 ($x:expr, $x_str:expr) => ({
4088 let (x, x_str) = ($x, $x_str);
4089 assert_eq!(format!("{}", x), x_str);
4090 assert_eq!(format!("{}", x.as_slice()), x_str);
4093 let empty: ~[int] = ~[];
4094 test_show_vec!(empty, ~"[]");
4095 test_show_vec!(~[1], ~"[1]");
4096 test_show_vec!(~[1, 2, 3], ~"[1, 2, 3]");
4097 test_show_vec!(~[~[], ~[1u], ~[1u, 1u]], ~"[[], [1], [1, 1]]");
4101 fn test_vec_default() {
4102 use default::Default;
4105 let v: $ty = Default::default();
4106 assert!(v.is_empty());
4115 fn test_bytes_set_memory() {
4116 use vec::bytes::MutableByteVector;
4117 let mut values = [1u8,2,3,4,5];
4118 values.mut_slice(0,5).set_memory(0xAB);
4119 assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
4120 values.mut_slice(2,4).set_memory(0xFF);
4121 assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
4126 fn test_overflow_does_not_cause_segfault() {
4128 v.reserve_exact(-1);
4135 fn test_overflow_does_not_cause_segfault_managed() {
4137 let mut v = ~[Rc::new(1)];
4138 v.reserve_exact(-1);
4143 fn test_mut_split_at() {
4144 let mut values = [1u8,2,3,4,5];
4146 let (left, right) = values.mut_split_at(2);
4147 assert!(left.slice(0, left.len()) == [1, 2]);
4148 for p in left.mut_iter() {
4152 assert!(right.slice(0, right.len()) == [3, 4, 5]);
4153 for p in right.mut_iter() {
4158 assert!(values == [2, 3, 5, 6, 7]);
4161 #[deriving(Clone, Eq)]
4165 fn test_iter_zero_sized() {
4166 let mut v = ~[Foo, Foo, Foo];
4167 assert_eq!(v.len(), 3);
4176 for f in v.slice(1, 3).iter() {
4182 for f in v.mut_iter() {
4188 for f in v.move_iter() {
4192 assert_eq!(cnt, 11);
4194 let xs = ~[Foo, Foo, Foo];
4195 assert_eq!(format!("{:?}", xs.slice(0, 2).to_owned()),
4196 ~"~[vec::tests::Foo, vec::tests::Foo]");
4198 let xs: [Foo, ..3] = [Foo, Foo, Foo];
4199 assert_eq!(format!("{:?}", xs.slice(0, 2).to_owned()),
4200 ~"~[vec::tests::Foo, vec::tests::Foo]");
4202 for f in xs.iter() {
4210 fn test_shrink_to_fit() {
4211 let mut xs = ~[0, 1, 2, 3];
4212 for i in range(4, 100) {
4215 assert_eq!(xs.capacity(), 128);
4217 assert_eq!(xs.capacity(), 100);
4218 assert_eq!(xs, range(0, 100).to_owned_vec());
4222 fn test_starts_with() {
4223 assert!(bytes!("foobar").starts_with(bytes!("foo")));
4224 assert!(!bytes!("foobar").starts_with(bytes!("oob")));
4225 assert!(!bytes!("foobar").starts_with(bytes!("bar")));
4226 assert!(!bytes!("foo").starts_with(bytes!("foobar")));
4227 assert!(!bytes!("bar").starts_with(bytes!("foobar")));
4228 assert!(bytes!("foobar").starts_with(bytes!("foobar")));
4229 let empty: &[u8] = [];
4230 assert!(empty.starts_with(empty));
4231 assert!(!empty.starts_with(bytes!("foo")));
4232 assert!(bytes!("foobar").starts_with(empty));
4236 fn test_ends_with() {
4237 assert!(bytes!("foobar").ends_with(bytes!("bar")));
4238 assert!(!bytes!("foobar").ends_with(bytes!("oba")));
4239 assert!(!bytes!("foobar").ends_with(bytes!("foo")));
4240 assert!(!bytes!("foo").ends_with(bytes!("foobar")));
4241 assert!(!bytes!("bar").ends_with(bytes!("foobar")));
4242 assert!(bytes!("foobar").ends_with(bytes!("foobar")));
4243 let empty: &[u8] = [];
4244 assert!(empty.ends_with(empty));
4245 assert!(!empty.ends_with(bytes!("foo")));
4246 assert!(bytes!("foobar").ends_with(empty));
4250 fn test_shift_ref() {
4251 let mut x: &[int] = [1, 2, 3, 4, 5];
4252 let h = x.shift_ref();
4253 assert_eq!(*h.unwrap(), 1);
4254 assert_eq!(x.len(), 4);
4255 assert_eq!(x[0], 2);
4256 assert_eq!(x[3], 5);
4258 let mut y: &[int] = [];
4259 assert_eq!(y.shift_ref(), None);
4264 let mut x: &[int] = [1, 2, 3, 4, 5];
4265 let h = x.pop_ref();
4266 assert_eq!(*h.unwrap(), 5);
4267 assert_eq!(x.len(), 4);
4268 assert_eq!(x[0], 1);
4269 assert_eq!(x[3], 4);
4271 let mut y: &[int] = [];
4272 assert!(y.pop_ref().is_none());
4276 fn test_mut_splitator() {
4277 let mut xs = [0,1,0,2,3,0,0,4,5,0];
4278 assert_eq!(xs.mut_split(|x| *x == 0).len(), 6);
4279 for slice in xs.mut_split(|x| *x == 0) {
4282 assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
4284 let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
4285 for slice in xs.mut_split(|x| *x == 0).take(5) {
4288 assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
4292 fn test_mut_splitator_rev() {
4293 let mut xs = [1,2,0,3,4,0,0,5,6,0];
4294 for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
4297 assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
4301 fn test_mut_chunks() {
4302 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
4303 for (i, chunk) in v.mut_chunks(3).enumerate() {
4304 for x in chunk.mut_iter() {
4308 let result = [0u8, 0, 0, 1, 1, 1, 2];
4309 assert!(v == result);
4313 fn test_mut_chunks_rev() {
4314 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
4315 for (i, chunk) in v.mut_chunks(3).rev().enumerate() {
4316 for x in chunk.mut_iter() {
4320 let result = [2u8, 2, 2, 1, 1, 1, 0];
4321 assert!(v == result);
4326 fn test_mut_chunks_0() {
4327 let mut v = [1, 2, 3, 4];
4328 let _it = v.mut_chunks(0);
4332 fn test_mut_shift_ref() {
4333 let mut x: &mut [int] = [1, 2, 3, 4, 5];
4334 let h = x.mut_shift_ref();
4335 assert_eq!(*h.unwrap(), 1);
4336 assert_eq!(x.len(), 4);
4337 assert_eq!(x[0], 2);
4338 assert_eq!(x[3], 5);
4340 let mut y: &mut [int] = [];
4341 assert!(y.mut_shift_ref().is_none());
4345 fn test_mut_pop_ref() {
4346 let mut x: &mut [int] = [1, 2, 3, 4, 5];
4347 let h = x.mut_pop_ref();
4348 assert_eq!(*h.unwrap(), 5);
4349 assert_eq!(x.len(), 4);
4350 assert_eq!(x[0], 1);
4351 assert_eq!(x[3], 4);
4353 let mut y: &mut [int] = [];
4354 assert!(y.mut_pop_ref().is_none());
4358 fn test_mut_last() {
4359 let mut x = [1, 2, 3, 4, 5];
4360 let h = x.mut_last();
4361 assert_eq!(*h.unwrap(), 5);
4363 let y: &mut [int] = [];
4364 assert!(y.mut_last().is_none());
4371 use self::test::BenchHarness;
4375 use rand::{weak_rng, Rng};
4379 fn iterator(bh: &mut BenchHarness) {
4380 // peculiar numbers to stop LLVM from optimising the summation
4382 let v = vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
4389 // sum == 11806, to stop dead code elimination.
4390 if sum == 0 {fail!()}
4395 fn mut_iterator(bh: &mut BenchHarness) {
4396 let mut v = vec::from_elem(100, 0);
4400 for x in v.mut_iter() {
4408 fn add(bh: &mut BenchHarness) {
4409 let xs: &[int] = [5, ..10];
4410 let ys: &[int] = [5, ..10];
4417 fn concat(bh: &mut BenchHarness) {
4418 let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect());
4420 let _ = xss.concat_vec();
4425 fn connect(bh: &mut BenchHarness) {
4426 let xss: &[~[uint]] = vec::from_fn(100, |i| range(0, i).collect());
4428 let _ = xss.connect_vec(&0);
4433 fn push(bh: &mut BenchHarness) {
4434 let mut vec: ~[uint] = ~[0u];
4442 fn starts_with_same_vector(bh: &mut BenchHarness) {
4443 let vec: ~[uint] = vec::from_fn(100, |i| i);
4445 vec.starts_with(vec)
4450 fn starts_with_single_element(bh: &mut BenchHarness) {
4451 let vec: ~[uint] = ~[0u];
4453 vec.starts_with(vec)
4458 fn starts_with_diff_one_element_at_end(bh: &mut BenchHarness) {
4459 let vec: ~[uint] = vec::from_fn(100, |i| i);
4460 let mut match_vec: ~[uint] = vec::from_fn(99, |i| i);
4463 vec.starts_with(match_vec)
4468 fn ends_with_same_vector(bh: &mut BenchHarness) {
4469 let vec: ~[uint] = vec::from_fn(100, |i| i);
4476 fn ends_with_single_element(bh: &mut BenchHarness) {
4477 let vec: ~[uint] = ~[0u];
4484 fn ends_with_diff_one_element_at_beginning(bh: &mut BenchHarness) {
4485 let vec: ~[uint] = vec::from_fn(100, |i| i);
4486 let mut match_vec: ~[uint] = vec::from_fn(100, |i| i);
4489 vec.starts_with(match_vec)
4494 fn contains_last_element(bh: &mut BenchHarness) {
4495 let vec: ~[uint] = vec::from_fn(100, |i| i);
4502 fn zero_1kb_from_elem(bh: &mut BenchHarness) {
4504 let _v: ~[u8] = vec::from_elem(1024, 0u8);
4509 fn zero_1kb_set_memory(bh: &mut BenchHarness) {
4511 let mut v: ~[u8] = vec::with_capacity(1024);
4513 let vp = v.as_mut_ptr();
4514 ptr::set_memory(vp, 0, 1024);
4522 fn zero_1kb_fixed_repeat(bh: &mut BenchHarness) {
4529 fn zero_1kb_loop_set(bh: &mut BenchHarness) {
4530 // Slower because the { len, cap, [0 x T] }* repr allows a pointer to the length
4531 // field to be aliased (in theory) and prevents LLVM from optimizing loads away.
4533 let mut v: ~[u8] = vec::with_capacity(1024);
4537 for i in range(0, 1024) {
4544 fn zero_1kb_mut_iter(bh: &mut BenchHarness) {
4546 let mut v: ~[u8] = vec::with_capacity(1024);
4550 for x in v.mut_iter() {
4558 fn random_inserts(bh: &mut BenchHarness) {
4559 let mut rng = weak_rng();
4561 let mut v = vec::from_elem(30, (0u, 0u));
4562 for _ in range(0, 100) {
4564 v.insert(rng.gen::<uint>() % (l + 1),
4570 fn random_removes(bh: &mut BenchHarness) {
4571 let mut rng = weak_rng();
4573 let mut v = vec::from_elem(130, (0u, 0u));
4574 for _ in range(0, 100) {
4576 v.remove(rng.gen::<uint>() % l);
4582 fn sort_random_small(bh: &mut BenchHarness) {
4583 let mut rng = weak_rng();
4585 let mut v: ~[u64] = rng.gen_vec(5);
4588 bh.bytes = 5 * mem::size_of::<u64>() as u64;
4592 fn sort_random_medium(bh: &mut BenchHarness) {
4593 let mut rng = weak_rng();
4595 let mut v: ~[u64] = rng.gen_vec(100);
4598 bh.bytes = 100 * mem::size_of::<u64>() as u64;
4602 fn sort_random_large(bh: &mut BenchHarness) {
4603 let mut rng = weak_rng();
4605 let mut v: ~[u64] = rng.gen_vec(10000);
4608 bh.bytes = 10000 * mem::size_of::<u64>() as u64;
4612 fn sort_sorted(bh: &mut BenchHarness) {
4613 let mut v = vec::from_fn(10000, |i| i);
4617 bh.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;
4620 type BigSortable = (u64,u64,u64,u64);
4623 fn sort_big_random_small(bh: &mut BenchHarness) {
4624 let mut rng = weak_rng();
4626 let mut v: ~[BigSortable] = rng.gen_vec(5);
4629 bh.bytes = 5 * mem::size_of::<BigSortable>() as u64;
4633 fn sort_big_random_medium(bh: &mut BenchHarness) {
4634 let mut rng = weak_rng();
4636 let mut v: ~[BigSortable] = rng.gen_vec(100);
4639 bh.bytes = 100 * mem::size_of::<BigSortable>() as u64;
4643 fn sort_big_random_large(bh: &mut BenchHarness) {
4644 let mut rng = weak_rng();
4646 let mut v: ~[BigSortable] = rng.gen_vec(10000);
4649 bh.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
4653 fn sort_big_sorted(bh: &mut BenchHarness) {
4654 let mut v = vec::from_fn(10000u, |i| (i, i, i, i));
4658 bh.bytes = (v.len() * mem::size_of_val(&v[0])) as u64;