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 = vec![0, 1, 2];
59 // numbers is now vec![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`.
106 use container::Container;
107 use cmp::{Eq, TotalOrd, Ordering, Less, Equal, Greater};
109 use default::Default;
112 use num::{CheckedAdd, Saturating, div_rem};
114 use option::{None, Option, Some};
117 use rt::global_heap::{malloc_raw, exchange_free};
118 use result::{Ok, Err};
123 use unstable::finally::try_finally;
124 use raw::{Repr, Slice};
125 use RawVec = raw::Vec;
129 * Converts a pointer to A into a slice of length 1 (without copying).
131 pub fn ref_slice<'a, A>(s: &'a A) -> &'a [A] {
133 transmute(Slice { data: s, len: 1 })
138 * Converts a pointer to A into a slice of length 1 (without copying).
140 pub fn mut_ref_slice<'a, A>(s: &'a mut A) -> &'a mut [A] {
142 let ptr: *A = transmute(s);
143 transmute(Slice { data: ptr, len: 1 })
147 /// An iterator over the slices of a vector separated by elements that
148 /// match a predicate function.
149 pub struct Splits<'a, T> {
152 pred: |t: &T|: 'a -> bool,
156 impl<'a, T> Iterator<&'a [T]> for Splits<'a, T> {
158 fn next(&mut self) -> Option<&'a [T]> {
159 if self.finished { return None; }
162 self.finished = true;
166 match self.v.iter().position(|x| (self.pred)(x)) {
168 self.finished = true;
172 let ret = Some(self.v.slice(0, idx));
173 self.v = self.v.slice(idx + 1, self.v.len());
181 fn size_hint(&self) -> (uint, Option<uint>) {
185 // if the predicate doesn't match anything, we yield one slice
186 // if it matches every element, we yield N+1 empty slices where
187 // N is either the number of elements or the number of splits.
188 match (self.v.len(), self.n) {
189 (0,_) => (1, Some(1)),
190 (_,0) => (1, Some(1)),
191 (l,n) => (1, cmp::min(l,n).checked_add(&1u))
196 /// An iterator over the slices of a vector separated by elements that
197 /// match a predicate function, from back to front.
198 pub struct RevSplits<'a, T> {
201 pred: |t: &T|: 'a -> bool,
205 impl<'a, T> Iterator<&'a [T]> for RevSplits<'a, T> {
207 fn next(&mut self) -> Option<&'a [T]> {
208 if self.finished { return None; }
211 self.finished = true;
215 match self.v.iter().rposition(|x| (self.pred)(x)) {
217 self.finished = true;
221 let ret = Some(self.v.slice(idx + 1, self.v.len()));
222 self.v = self.v.slice(0, idx);
230 fn size_hint(&self) -> (uint, Option<uint>) {
234 match (self.v.len(), self.n) {
235 (0,_) => (1, Some(1)),
236 (_,0) => (1, Some(1)),
237 (l,n) => (1, cmp::min(l,n).checked_add(&1u))
242 // Functional utilities
244 #[allow(missing_doc)]
245 pub trait VectorVector<T> {
246 // FIXME #5898: calling these .concat and .connect conflicts with
247 // StrVector::con{cat,nect}, since they have generic contents.
248 /// Flattens a vector of vectors of T into a single vector of T.
249 fn concat_vec(&self) -> ~[T];
251 /// Concatenate a vector of vectors, placing a given separator between each.
252 fn connect_vec(&self, sep: &T) -> ~[T];
255 impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
256 fn concat_vec(&self) -> ~[T] {
257 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
258 let mut result = Vec::with_capacity(size);
259 for v in self.iter() {
260 result.push_all(v.as_slice())
262 result.move_iter().collect()
265 fn connect_vec(&self, sep: &T) -> ~[T] {
266 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
267 let mut result = Vec::with_capacity(size + self.len());
268 let mut first = true;
269 for v in self.iter() {
270 if first { first = false } else { result.push(sep.clone()) }
271 result.push_all(v.as_slice())
273 result.move_iter().collect()
278 * Convert an iterator of pairs into a pair of vectors.
280 * Returns a tuple containing two vectors where the i-th element of the first
281 * vector contains the first element of the i-th tuple of the input iterator,
282 * and the i-th element of the second vector contains the second element
283 * of the i-th tuple of the input iterator.
285 pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
286 let (lo, _) = iter.size_hint();
287 let mut ts = Vec::with_capacity(lo);
288 let mut us = Vec::with_capacity(lo);
293 (ts.move_iter().collect(), us.move_iter().collect())
296 /// An Iterator that yields the element swaps needed to produce
297 /// a sequence of all possible permutations for an indexed sequence of
298 /// elements. Each permutation is only a single swap apart.
300 /// The Steinhaus–Johnson–Trotter algorithm is used.
302 /// Generates even and odd permutations alternately.
304 /// The last generated swap is always (0, 1), and it returns the
305 /// sequence to its initial order.
306 pub struct ElementSwaps {
307 sdir: ~[SizeDirection],
308 /// If true, emit the last swap that returns the sequence to initial state
313 /// Create an `ElementSwaps` iterator for a sequence of `length` elements
314 pub fn new(length: uint) -> ElementSwaps {
315 // Initialize `sdir` with a direction that position should move in
316 // (all negative at the beginning) and the `size` of the
317 // element (equal to the original index).
320 sdir: range(0, length)
321 .map(|i| SizeDirection{ size: i, dir: Neg })
327 enum Direction { Pos, Neg }
329 /// An Index and Direction together
330 struct SizeDirection {
335 impl Iterator<(uint, uint)> for ElementSwaps {
337 fn next(&mut self) -> Option<(uint, uint)> {
338 fn new_pos(i: uint, s: Direction) -> uint {
339 i + match s { Pos => 1, Neg => -1 }
342 // Find the index of the largest mobile element:
343 // The direction should point into the vector, and the
344 // swap should be with a smaller `size` element.
345 let max = self.sdir.iter().map(|&x| x).enumerate()
347 new_pos(i, sd.dir) < self.sdir.len() &&
348 self.sdir[new_pos(i, sd.dir)].size < sd.size)
349 .max_by(|&(_, sd)| sd.size);
352 let j = new_pos(i, sd.dir);
353 self.sdir.swap(i, j);
355 // Swap the direction of each larger SizeDirection
356 for x in self.sdir.mut_iter() {
357 if x.size > sd.size {
358 x.dir = match x.dir { Pos => Neg, Neg => Pos };
363 None => if self.emit_reset && self.sdir.len() > 1 {
364 self.emit_reset = false;
373 /// An Iterator that uses `ElementSwaps` to iterate through
374 /// all possible permutations of a vector.
376 /// The first iteration yields a clone of the vector as it is,
377 /// then each successive element is the vector with one
380 /// Generates even and odd permutations alternately.
381 pub struct Permutations<T> {
386 impl<T: Clone> Iterator<~[T]> for Permutations<T> {
388 fn next(&mut self) -> Option<~[T]> {
389 match self.swaps.next() {
392 let elt = self.v.clone();
400 /// An iterator over the (overlapping) slices of length `size` within
403 pub struct Windows<'a, T> {
408 impl<'a, T> Iterator<&'a [T]> for Windows<'a, T> {
410 fn next(&mut self) -> Option<&'a [T]> {
411 if self.size > self.v.len() {
414 let ret = Some(self.v.slice(0, self.size));
415 self.v = self.v.slice(1, self.v.len());
421 fn size_hint(&self) -> (uint, Option<uint>) {
422 if self.size > self.v.len() {
425 let x = self.v.len() - self.size;
426 (x.saturating_add(1), x.checked_add(&1u))
431 /// An iterator over a vector in (non-overlapping) chunks (`size`
432 /// elements at a time).
434 /// When the vector len is not evenly divided by the chunk size,
435 /// the last slice of the iteration will be the remainder.
437 pub struct Chunks<'a, T> {
442 impl<'a, T> Iterator<&'a [T]> for Chunks<'a, T> {
444 fn next(&mut self) -> Option<&'a [T]> {
445 if self.v.len() == 0 {
448 let chunksz = cmp::min(self.v.len(), self.size);
449 let (fst, snd) = (self.v.slice_to(chunksz),
450 self.v.slice_from(chunksz));
457 fn size_hint(&self) -> (uint, Option<uint>) {
458 if self.v.len() == 0 {
461 let (n, rem) = div_rem(self.v.len(), self.size);
462 let n = if rem > 0 { n+1 } else { n };
468 impl<'a, T> DoubleEndedIterator<&'a [T]> for Chunks<'a, T> {
470 fn next_back(&mut self) -> Option<&'a [T]> {
471 if self.v.len() == 0 {
474 let remainder = self.v.len() % self.size;
475 let chunksz = if remainder != 0 { remainder } else { self.size };
476 let (fst, snd) = (self.v.slice_to(self.v.len() - chunksz),
477 self.v.slice_from(self.v.len() - chunksz));
484 impl<'a, T> RandomAccessIterator<&'a [T]> for Chunks<'a, T> {
486 fn indexable(&self) -> uint {
487 self.v.len()/self.size + if self.v.len() % self.size != 0 { 1 } else { 0 }
491 fn idx(&mut self, index: uint) -> Option<&'a [T]> {
492 if index < self.indexable() {
493 let lo = index * self.size;
494 let mut hi = lo + self.size;
495 if hi < lo || hi > self.v.len() { hi = self.v.len(); }
497 Some(self.v.slice(lo, hi))
507 #[allow(missing_doc)]
511 use container::Container;
513 use cmp::{Eq, Ord, TotalEq, TotalOrd, Ordering, Equiv};
514 use iter::{order, Iterator};
518 impl<'a,T:Eq> Eq for &'a [T] {
519 fn eq(&self, other: & &'a [T]) -> bool {
520 self.len() == other.len() &&
521 order::eq(self.iter(), other.iter())
523 fn ne(&self, other: & &'a [T]) -> bool {
524 self.len() != other.len() ||
525 order::ne(self.iter(), other.iter())
529 impl<T:Eq> Eq for ~[T] {
531 fn eq(&self, other: &~[T]) -> bool { self.as_slice() == *other }
533 fn ne(&self, other: &~[T]) -> bool { !self.eq(other) }
536 impl<'a,T:TotalEq> TotalEq for &'a [T] {}
538 impl<T:TotalEq> TotalEq for ~[T] {}
540 impl<'a,T:Eq, V: Vector<T>> Equiv<V> for &'a [T] {
542 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
545 impl<'a,T:Eq, V: Vector<T>> Equiv<V> for ~[T] {
547 fn equiv(&self, other: &V) -> bool { self.as_slice() == other.as_slice() }
550 impl<'a,T:TotalOrd> TotalOrd for &'a [T] {
551 fn cmp(&self, other: & &'a [T]) -> Ordering {
552 order::cmp(self.iter(), other.iter())
556 impl<T: TotalOrd> TotalOrd for ~[T] {
558 fn cmp(&self, other: &~[T]) -> Ordering { self.as_slice().cmp(&other.as_slice()) }
561 impl<'a, T: Ord> Ord for &'a [T] {
562 fn lt(&self, other: & &'a [T]) -> bool {
563 order::lt(self.iter(), other.iter())
566 fn le(&self, other: & &'a [T]) -> bool {
567 order::le(self.iter(), other.iter())
570 fn ge(&self, other: & &'a [T]) -> bool {
571 order::ge(self.iter(), other.iter())
574 fn gt(&self, other: & &'a [T]) -> bool {
575 order::gt(self.iter(), other.iter())
579 impl<T: Ord> Ord for ~[T] {
581 fn lt(&self, other: &~[T]) -> bool { self.as_slice() < other.as_slice() }
583 fn le(&self, other: &~[T]) -> bool { self.as_slice() <= other.as_slice() }
585 fn ge(&self, other: &~[T]) -> bool { self.as_slice() >= other.as_slice() }
587 fn gt(&self, other: &~[T]) -> bool { self.as_slice() > other.as_slice() }
590 impl<'a,T:Clone, V: Vector<T>> Add<V, ~[T]> for &'a [T] {
592 fn add(&self, rhs: &V) -> ~[T] {
593 let mut res = Vec::with_capacity(self.len() + rhs.as_slice().len());
595 res.push_all(rhs.as_slice());
596 res.move_iter().collect()
600 impl<T:Clone, V: Vector<T>> Add<V, ~[T]> for ~[T] {
602 fn add(&self, rhs: &V) -> ~[T] {
603 self.as_slice() + rhs.as_slice()
611 /// Any vector that can be represented as a slice.
612 pub trait Vector<T> {
613 /// Work with `self` as a slice.
614 fn as_slice<'a>(&'a self) -> &'a [T];
617 impl<'a,T> Vector<T> for &'a [T] {
619 fn as_slice<'a>(&'a self) -> &'a [T] { *self }
622 impl<T> Vector<T> for ~[T] {
624 fn as_slice<'a>(&'a self) -> &'a [T] { let v: &'a [T] = *self; v }
627 impl<'a, T> Container for &'a [T] {
628 /// Returns the length of a vector
630 fn len(&self) -> uint {
635 impl<T> Container for ~[T] {
636 /// Returns the length of a vector
638 fn len(&self) -> uint {
639 self.as_slice().len()
643 /// Extension methods for vector slices with cloneable elements
644 pub trait CloneableVector<T> {
645 /// Copy `self` into a new owned vector
646 fn to_owned(&self) -> ~[T];
648 /// Convert `self` into an owned vector, not making a copy if possible.
649 fn into_owned(self) -> ~[T];
652 /// Extension methods for vector slices
653 impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
654 /// Returns a copy of `v`.
656 fn to_owned(&self) -> ~[T] {
657 let len = self.len();
658 let mut result = Vec::with_capacity(len);
659 // Unsafe code so this can be optimised to a memcpy (or something
660 // similarly fast) when T is Copy. LLVM is easily confused, so any
661 // extra operations during the loop can prevent this optimisation
664 let p = result.as_mut_ptr();
665 // Use try_finally here otherwise the write to length
666 // inside the loop stops LLVM from optimising this.
669 |i, ()| while *i < len {
671 &mut(*p.offset(*i as int)),
672 self.unsafe_ref(*i).clone());
675 |i| result.set_len(*i));
677 result.move_iter().collect()
681 fn into_owned(self) -> ~[T] { self.to_owned() }
684 /// Extension methods for owned vectors
685 impl<T: Clone> CloneableVector<T> for ~[T] {
687 fn to_owned(&self) -> ~[T] { self.clone() }
690 fn into_owned(self) -> ~[T] { self }
693 /// Extension methods for vectors
694 pub trait ImmutableVector<'a, T> {
696 * Returns a slice of self between `start` and `end`.
698 * Fails when `start` or `end` point outside the bounds of self,
699 * or when `start` > `end`.
701 fn slice(&self, start: uint, end: uint) -> &'a [T];
704 * Returns a slice of self from `start` to the end of the vec.
706 * Fails when `start` points outside the bounds of self.
708 fn slice_from(&self, start: uint) -> &'a [T];
711 * Returns a slice of self from the start of the vec to `end`.
713 * Fails when `end` points outside the bounds of self.
715 fn slice_to(&self, end: uint) -> &'a [T];
716 /// Returns an iterator over the vector
717 fn iter(self) -> Items<'a, T>;
718 /// Returns a reversed iterator over a vector
719 fn rev_iter(self) -> RevItems<'a, T>;
720 /// Returns an iterator over the subslices of the vector which are
721 /// separated by elements that match `pred`. The matched element
722 /// is not contained in the subslices.
723 fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T>;
724 /// Returns an iterator over the subslices of the vector which are
725 /// separated by elements that match `pred`, limited to splitting
726 /// at most `n` times. The matched element is not contained in
728 fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> Splits<'a, T>;
729 /// Returns an iterator over the subslices of the vector which are
730 /// separated by elements that match `pred`. This starts at the
731 /// end of the vector and works backwards. The matched element is
732 /// not contained in the subslices.
733 fn rsplit(self, pred: |&T|: 'a -> bool) -> RevSplits<'a, T>;
734 /// Returns an iterator over the subslices of the vector which are
735 /// separated by elements that match `pred` limited to splitting
736 /// at most `n` times. This starts at the end of the vector and
737 /// works backwards. The matched element is not contained in the
739 fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> RevSplits<'a, T>;
742 * Returns an iterator over all contiguous windows of length
743 * `size`. The windows overlap. If the vector is shorter than
744 * `size`, the iterator returns no values.
748 * Fails if `size` is 0.
752 * Print the adjacent pairs of a vector (i.e. `[1,2]`, `[2,3]`,
756 * let v = &[1,2,3,4];
757 * for win in v.windows(2) {
758 * println!("{:?}", win);
763 fn windows(self, size: uint) -> Windows<'a, T>;
766 * Returns an iterator over `size` elements of the vector at a
767 * time. The chunks do not overlap. If `size` does not divide the
768 * length of the vector, then the last chunk will not have length
773 * Fails if `size` is 0.
777 * Print the vector two elements at a time (i.e. `[1,2]`,
781 * let v = &[1,2,3,4,5];
782 * for win in v.chunks(2) {
783 * println!("{:?}", win);
788 fn chunks(self, size: uint) -> Chunks<'a, T>;
790 /// Returns the element of a vector at the given index, or `None` if the
791 /// index is out of bounds
792 fn get(&self, index: uint) -> Option<&'a T>;
793 /// Returns the first element of a vector, or `None` if it is empty
794 fn head(&self) -> Option<&'a T>;
795 /// Returns all but the first element of a vector
796 fn tail(&self) -> &'a [T];
797 /// Returns all but the first `n' elements of a vector
798 fn tailn(&self, n: uint) -> &'a [T];
799 /// Returns all but the last element of a vector
800 fn init(&self) -> &'a [T];
801 /// Returns all but the last `n' elements of a vector
802 fn initn(&self, n: uint) -> &'a [T];
803 /// Returns the last element of a vector, or `None` if it is empty.
804 fn last(&self) -> Option<&'a T>;
806 /// Returns a pointer to the element at the given index, without doing
808 unsafe fn unsafe_ref(self, index: uint) -> &'a T;
811 * Returns an unsafe pointer to the vector's buffer
813 * The caller must ensure that the vector outlives the pointer this
814 * function returns, or else it will end up pointing to garbage.
816 * Modifying the vector may cause its buffer to be reallocated, which
817 * would also make any pointers to it invalid.
819 fn as_ptr(&self) -> *T;
822 * Binary search a sorted vector with a comparator function.
824 * The comparator function should implement an order consistent
825 * with the sort order of the underlying vector, returning an
826 * order code that indicates whether its argument is `Less`,
827 * `Equal` or `Greater` the desired target.
829 * Returns the index where the comparator returned `Equal`, or `None` if
832 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint>;
835 * Returns a mutable reference to the first element in this slice
836 * and adjusts the slice in place so that it no longer contains
837 * that element. O(1).
842 * if self.len() == 0 { return None }
843 * let head = &self[0];
844 * *self = self.slice_from(1);
848 * Returns `None` if vector is empty
850 fn shift_ref(&mut self) -> Option<&'a T>;
853 * Returns a mutable reference to the last element in this slice
854 * and adjusts the slice in place so that it no longer contains
855 * that element. O(1).
860 * if self.len() == 0 { return None; }
861 * let tail = &self[self.len() - 1];
862 * *self = self.slice_to(self.len() - 1);
866 * Returns `None` if slice is empty.
868 fn pop_ref(&mut self) -> Option<&'a T>;
871 impl<'a,T> ImmutableVector<'a, T> for &'a [T] {
873 fn slice(&self, start: uint, end: uint) -> &'a [T] {
874 assert!(start <= end);
875 assert!(end <= self.len());
878 data: self.as_ptr().offset(start as int),
885 fn slice_from(&self, start: uint) -> &'a [T] {
886 self.slice(start, self.len())
890 fn slice_to(&self, end: uint) -> &'a [T] {
895 fn iter(self) -> Items<'a, T> {
897 let p = self.as_ptr();
898 if mem::size_of::<T>() == 0 {
900 end: (p as uint + self.len()) as *T,
901 marker: marker::ContravariantLifetime::<'a>}
904 end: p.offset(self.len() as int),
905 marker: marker::ContravariantLifetime::<'a>}
911 fn rev_iter(self) -> RevItems<'a, T> {
916 fn split(self, pred: |&T|: 'a -> bool) -> Splits<'a, T> {
917 self.splitn(uint::MAX, pred)
921 fn splitn(self, n: uint, pred: |&T|: 'a -> bool) -> Splits<'a, T> {
931 fn rsplit(self, pred: |&T|: 'a -> bool) -> RevSplits<'a, T> {
932 self.rsplitn(uint::MAX, pred)
936 fn rsplitn(self, n: uint, pred: |&T|: 'a -> bool) -> RevSplits<'a, T> {
946 fn windows(self, size: uint) -> Windows<'a, T> {
948 Windows { v: self, size: size }
952 fn chunks(self, size: uint) -> Chunks<'a, T> {
954 Chunks { v: self, size: size }
958 fn get(&self, index: uint) -> Option<&'a T> {
959 if index < self.len() { Some(&self[index]) } else { None }
963 fn head(&self) -> Option<&'a T> {
964 if self.len() == 0 { None } else { Some(&self[0]) }
968 fn tail(&self) -> &'a [T] { self.slice(1, self.len()) }
971 fn tailn(&self, n: uint) -> &'a [T] { self.slice(n, self.len()) }
974 fn init(&self) -> &'a [T] {
975 self.slice(0, self.len() - 1)
979 fn initn(&self, n: uint) -> &'a [T] {
980 self.slice(0, self.len() - n)
984 fn last(&self) -> Option<&'a T> {
985 if self.len() == 0 { None } else { Some(&self[self.len() - 1]) }
989 unsafe fn unsafe_ref(self, index: uint) -> &'a T {
990 transmute(self.repr().data.offset(index as int))
994 fn as_ptr(&self) -> *T {
999 fn bsearch(&self, f: |&T| -> Ordering) -> Option<uint> {
1000 let mut base : uint = 0;
1001 let mut lim : uint = self.len();
1004 let ix = base + (lim >> 1);
1005 match f(&self[ix]) {
1006 Equal => return Some(ix),
1018 fn shift_ref(&mut self) -> Option<&'a T> {
1019 if self.len() == 0 { return None; }
1021 let s: &mut Slice<T> = transmute(self);
1022 Some(&*raw::shift_ptr(s))
1026 fn pop_ref(&mut self) -> Option<&'a T> {
1027 if self.len() == 0 { return None; }
1029 let s: &mut Slice<T> = transmute(self);
1030 Some(&*raw::pop_ptr(s))
1035 /// Extension methods for vectors contain `Eq` elements.
1036 pub trait ImmutableEqVector<T:Eq> {
1037 /// Find the first index containing a matching value
1038 fn position_elem(&self, t: &T) -> Option<uint>;
1040 /// Find the last index containing a matching value
1041 fn rposition_elem(&self, t: &T) -> Option<uint>;
1043 /// Return true if a vector contains an element with the given value
1044 fn contains(&self, x: &T) -> bool;
1046 /// Returns true if `needle` is a prefix of the vector.
1047 fn starts_with(&self, needle: &[T]) -> bool;
1049 /// Returns true if `needle` is a suffix of the vector.
1050 fn ends_with(&self, needle: &[T]) -> bool;
1053 impl<'a,T:Eq> ImmutableEqVector<T> for &'a [T] {
1055 fn position_elem(&self, x: &T) -> Option<uint> {
1056 self.iter().position(|y| *x == *y)
1060 fn rposition_elem(&self, t: &T) -> Option<uint> {
1061 self.iter().rposition(|x| *x == *t)
1065 fn contains(&self, x: &T) -> bool {
1066 self.iter().any(|elt| *x == *elt)
1070 fn starts_with(&self, needle: &[T]) -> bool {
1071 let n = needle.len();
1072 self.len() >= n && needle == self.slice_to(n)
1076 fn ends_with(&self, needle: &[T]) -> bool {
1077 let (m, n) = (self.len(), needle.len());
1078 m >= n && needle == self.slice_from(m - n)
1082 /// Extension methods for vectors containing `TotalOrd` elements.
1083 pub trait ImmutableTotalOrdVector<T: TotalOrd> {
1085 * Binary search a sorted vector for a given element.
1087 * Returns the index of the element or None if not found.
1089 fn bsearch_elem(&self, x: &T) -> Option<uint>;
1092 impl<'a, T: TotalOrd> ImmutableTotalOrdVector<T> for &'a [T] {
1093 fn bsearch_elem(&self, x: &T) -> Option<uint> {
1094 self.bsearch(|p| p.cmp(x))
1098 /// Extension methods for vectors containing `Clone` elements.
1099 pub trait ImmutableCloneableVector<T> {
1100 /// Partitions the vector into two vectors `(A,B)`, where all
1101 /// elements of `A` satisfy `f` and all elements of `B` do not.
1102 fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]);
1104 /// Create an iterator that yields every possible permutation of the
1105 /// vector in succession.
1106 fn permutations(self) -> Permutations<T>;
1109 impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
1111 fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]) {
1112 let mut lefts = Vec::new();
1113 let mut rights = Vec::new();
1115 for elt in self.iter() {
1117 lefts.push((*elt).clone());
1119 rights.push((*elt).clone());
1123 (lefts.move_iter().collect(), rights.move_iter().collect())
1126 fn permutations(self) -> Permutations<T> {
1128 swaps: ElementSwaps::new(self.len()),
1135 /// Extension methods for owned vectors.
1136 pub trait OwnedVector<T> {
1137 /// Creates a consuming iterator, that is, one that moves each
1138 /// value out of the vector (from start to end). The vector cannot
1139 /// be used after calling this.
1144 /// let v = ~["a".to_owned(), "b".to_owned()];
1145 /// for s in v.move_iter() {
1146 /// // s has type ~str, not &~str
1147 /// println!("{}", s);
1150 fn move_iter(self) -> MoveItems<T>;
1151 /// Creates a consuming iterator that moves out of the vector in
1153 fn move_rev_iter(self) -> RevMoveItems<T>;
1156 * Partitions the vector into two vectors `(A,B)`, where all
1157 * elements of `A` satisfy `f` and all elements of `B` do not.
1159 fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]);
1162 impl<T> OwnedVector<T> for ~[T] {
1164 fn move_iter(self) -> MoveItems<T> {
1166 let iter = transmute(self.iter());
1167 let ptr = transmute(self);
1168 MoveItems { allocation: ptr, iter: iter }
1173 fn move_rev_iter(self) -> RevMoveItems<T> {
1174 self.move_iter().rev()
1178 fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]) {
1179 let mut lefts = Vec::new();
1180 let mut rights = Vec::new();
1182 for elt in self.move_iter() {
1190 (lefts.move_iter().collect(), rights.move_iter().collect())
1194 fn insertion_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
1195 let len = v.len() as int;
1196 let buf_v = v.as_mut_ptr();
1199 for i in range(1, len) {
1200 // j satisfies: 0 <= j <= i;
1203 // `i` is in bounds.
1204 let read_ptr = buf_v.offset(i) as *T;
1206 // find where to insert, we need to do strict <,
1207 // rather than <=, to maintain stability.
1209 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
1211 compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
1215 // shift everything to the right, to make space to
1216 // insert this value.
1218 // j + 1 could be `len` (for the last `i`), but in
1219 // that case, `i == j` so we don't copy. The
1220 // `.offset(j)` is always in bounds.
1223 let tmp = ptr::read(read_ptr);
1224 ptr::copy_memory(buf_v.offset(j + 1),
1227 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
1236 fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
1237 // warning: this wildly uses unsafe.
1238 static BASE_INSERTION: uint = 32;
1239 static LARGE_INSERTION: uint = 16;
1241 // FIXME #12092: smaller insertion runs seems to make sorting
1242 // vectors of large elements a little faster on some platforms,
1243 // but hasn't been tested/tuned extensively
1244 let insertion = if size_of::<T>() <= 16 {
1252 // short vectors get sorted in-place via insertion sort to avoid allocations
1253 if len <= insertion {
1254 insertion_sort(v, compare);
1258 // allocate some memory to use as scratch memory, we keep the
1259 // length 0 so we can keep shallow copies of the contents of `v`
1260 // without risking the dtors running on an object twice if
1262 let mut working_space = Vec::with_capacity(2 * len);
1263 // these both are buffers of length `len`.
1264 let mut buf_dat = working_space.as_mut_ptr();
1265 let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
1268 let buf_v = v.as_ptr();
1270 // step 1. sort short runs with insertion sort. This takes the
1271 // values from `v` and sorts them into `buf_dat`, leaving that
1272 // with sorted runs of length INSERTION.
1274 // We could hardcode the sorting comparisons here, and we could
1275 // manipulate/step the pointers themselves, rather than repeatedly
1277 for start in range_step(0, len, insertion) {
1278 // start <= i < len;
1279 for i in range(start, cmp::min(start + insertion, len)) {
1280 // j satisfies: start <= j <= i;
1281 let mut j = i as int;
1283 // `i` is in bounds.
1284 let read_ptr = buf_v.offset(i as int);
1286 // find where to insert, we need to do strict <,
1287 // rather than <=, to maintain stability.
1289 // start <= j - 1 < len, so .offset(j - 1) is in
1291 while j > start as int &&
1292 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
1296 // shift everything to the right, to make space to
1297 // insert this value.
1299 // j + 1 could be `len` (for the last `i`), but in
1300 // that case, `i == j` so we don't copy. The
1301 // `.offset(j)` is always in bounds.
1302 ptr::copy_memory(buf_dat.offset(j + 1),
1303 &*buf_dat.offset(j),
1305 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
1310 // step 2. merge the sorted runs.
1311 let mut width = insertion;
1313 // merge the sorted runs of length `width` in `buf_dat` two at
1314 // a time, placing the result in `buf_tmp`.
1316 // 0 <= start <= len.
1317 for start in range_step(0, len, 2 * width) {
1318 // manipulate pointers directly for speed (rather than
1319 // using a `for` loop with `range` and `.offset` inside
1322 // the end of the first run & start of the
1323 // second. Offset of `len` is defined, since this is
1324 // precisely one byte past the end of the object.
1325 let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
1326 // end of the second. Similar reasoning to the above re safety.
1327 let right_end_idx = cmp::min(start + 2 * width, len);
1328 let right_end = buf_dat.offset(right_end_idx as int);
1330 // the pointers to the elements under consideration
1331 // from the two runs.
1333 // both of these are in bounds.
1334 let mut left = buf_dat.offset(start as int);
1335 let mut right = right_start;
1337 // where we're putting the results, it is a run of
1338 // length `2*width`, so we step it once for each step
1339 // of either `left` or `right`. `buf_tmp` has length
1340 // `len`, so these are in bounds.
1341 let mut out = buf_tmp.offset(start as int);
1342 let out_end = buf_tmp.offset(right_end_idx as int);
1344 while out < out_end {
1345 // Either the left or the right run are exhausted,
1346 // so just copy the remainder from the other run
1347 // and move on; this gives a huge speed-up (order
1348 // of 25%) for mostly sorted vectors (the best
1350 if left == right_start {
1351 // the number remaining in this run.
1352 let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
1353 ptr::copy_nonoverlapping_memory(out, &*right, elems);
1355 } else if right == right_end {
1356 let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
1357 ptr::copy_nonoverlapping_memory(out, &*left, elems);
1361 // check which side is smaller, and that's the
1362 // next element for the new run.
1364 // `left < right_start` and `right < right_end`,
1365 // so these are valid.
1366 let to_copy = if compare(&*left, &*right) == Greater {
1371 ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
1377 mem::swap(&mut buf_dat, &mut buf_tmp);
1382 // write the result to `v` in one go, so that there are never two copies
1383 // of the same object in `v`.
1385 ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
1388 // increment the pointer, returning the old pointer.
1390 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
1392 *ptr = ptr.offset(1);
1397 /// Extension methods for vectors such that their elements are
1399 pub trait MutableVector<'a, T> {
1400 /// Work with `self` as a mut slice.
1401 /// Primarily intended for getting a &mut [T] from a [T, ..N].
1402 fn as_mut_slice(self) -> &'a mut [T];
1404 /// Return a slice that points into another slice.
1405 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T];
1408 * Returns a slice of self from `start` to the end of the vec.
1410 * Fails when `start` points outside the bounds of self.
1412 fn mut_slice_from(self, start: uint) -> &'a mut [T];
1415 * Returns a slice of self from the start of the vec to `end`.
1417 * Fails when `end` points outside the bounds of self.
1419 fn mut_slice_to(self, end: uint) -> &'a mut [T];
1421 /// Returns an iterator that allows modifying each value
1422 fn mut_iter(self) -> MutItems<'a, T>;
1424 /// Returns a mutable pointer to the last item in the vector.
1425 fn mut_last(self) -> Option<&'a mut T>;
1427 /// Returns a reversed iterator that allows modifying each value
1428 fn mut_rev_iter(self) -> RevMutItems<'a, T>;
1430 /// Returns an iterator over the mutable subslices of the vector
1431 /// which are separated by elements that match `pred`. The
1432 /// matched element is not contained in the subslices.
1433 fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T>;
1436 * Returns an iterator over `size` elements of the vector at a time.
1437 * The chunks are mutable and do not overlap. If `size` does not divide the
1438 * length of the vector, then the last chunk will not have length
1443 * Fails if `size` is 0.
1445 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T>;
1448 * Returns a mutable reference to the first element in this slice
1449 * and adjusts the slice in place so that it no longer contains
1450 * that element. O(1).
1455 * if self.len() == 0 { return None; }
1456 * let head = &mut self[0];
1457 * *self = self.mut_slice_from(1);
1461 * Returns `None` if slice is empty
1463 fn mut_shift_ref(&mut self) -> Option<&'a mut T>;
1466 * Returns a mutable reference to the last element in this slice
1467 * and adjusts the slice in place so that it no longer contains
1468 * that element. O(1).
1473 * if self.len() == 0 { return None; }
1474 * let tail = &mut self[self.len() - 1];
1475 * *self = self.mut_slice_to(self.len() - 1);
1479 * Returns `None` if slice is empty.
1481 fn mut_pop_ref(&mut self) -> Option<&'a mut T>;
1483 /// Swaps two elements in a vector.
1485 /// Fails if `a` or `b` are out of bounds.
1489 /// * a - The index of the first element
1490 /// * b - The index of the second element
1495 /// let mut v = ["a", "b", "c", "d"];
1497 /// assert!(v == ["a", "d", "c", "b"]);
1499 fn swap(self, a: uint, b: uint);
1502 /// Divides one `&mut` into two at an index.
1504 /// The first will contain all indices from `[0, mid)` (excluding
1505 /// the index `mid` itself) and the second will contain all
1506 /// indices from `[mid, len)` (excluding the index `len` itself).
1508 /// Fails if `mid > len`.
1513 /// let mut v = [1, 2, 3, 4, 5, 6];
1515 /// // scoped to restrict the lifetime of the borrows
1517 /// let (left, right) = v.mut_split_at(0);
1518 /// assert!(left == &mut []);
1519 /// assert!(right == &mut [1, 2, 3, 4, 5, 6]);
1523 /// let (left, right) = v.mut_split_at(2);
1524 /// assert!(left == &mut [1, 2]);
1525 /// assert!(right == &mut [3, 4, 5, 6]);
1529 /// let (left, right) = v.mut_split_at(6);
1530 /// assert!(left == &mut [1, 2, 3, 4, 5, 6]);
1531 /// assert!(right == &mut []);
1534 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]);
1536 /// Reverse the order of elements in a vector, in place.
1541 /// let mut v = [1, 2, 3];
1543 /// assert!(v == [3, 2, 1]);
1547 /// Sort the vector, in place, using `compare` to compare
1550 /// This sort is `O(n log n)` worst-case and stable, but allocates
1551 /// approximately `2 * n`, where `n` is the length of `self`.
1556 /// let mut v = [5i, 4, 1, 3, 2];
1557 /// v.sort_by(|a, b| a.cmp(b));
1558 /// assert!(v == [1, 2, 3, 4, 5]);
1560 /// // reverse sorting
1561 /// v.sort_by(|a, b| b.cmp(a));
1562 /// assert!(v == [5, 4, 3, 2, 1]);
1564 fn sort_by(self, compare: |&T, &T| -> Ordering);
1567 * Consumes `src` and moves as many elements as it can into `self`
1568 * from the range [start,end).
1570 * Returns the number of elements copied (the shorter of self.len()
1575 * * src - A mutable vector of `T`
1576 * * start - The index into `src` to start copying from
1577 * * end - The index into `str` to stop copying from
1579 fn move_from(self, src: ~[T], start: uint, end: uint) -> uint;
1581 /// Returns an unsafe mutable pointer to the element in index
1582 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T;
1584 /// Return an unsafe mutable pointer to the vector's buffer.
1586 /// The caller must ensure that the vector outlives the pointer this
1587 /// function returns, or else it will end up pointing to garbage.
1589 /// Modifying the vector may cause its buffer to be reallocated, which
1590 /// would also make any pointers to it invalid.
1592 fn as_mut_ptr(self) -> *mut T;
1594 /// Unsafely sets the element in index to the value.
1596 /// This performs no bounds checks, and it is undefined behaviour
1597 /// if `index` is larger than the length of `self`. However, it
1598 /// does run the destructor at `index`. It is equivalent to
1599 /// `self[index] = val`.
1604 /// let mut v = ~["foo".to_owned(), "bar".to_owned(), "baz".to_owned()];
1607 /// // `"baz".to_owned()` is deallocated.
1608 /// v.unsafe_set(2, "qux".to_owned());
1610 /// // Out of bounds: could cause a crash, or overwriting
1611 /// // other data, or something else.
1612 /// // v.unsafe_set(10, "oops".to_owned());
1615 unsafe fn unsafe_set(self, index: uint, val: T);
1617 /// Unchecked vector index assignment. Does not drop the
1618 /// old value and hence is only suitable when the vector
1619 /// is newly allocated.
1624 /// let mut v = ["foo".to_owned(), "bar".to_owned()];
1626 /// // memory leak! `"bar".to_owned()` is not deallocated.
1627 /// unsafe { v.init_elem(1, "baz".to_owned()); }
1629 unsafe fn init_elem(self, i: uint, val: T);
1631 /// Copies raw bytes from `src` to `self`.
1633 /// This does not run destructors on the overwritten elements, and
1634 /// ignores move semantics. `self` and `src` must not
1635 /// overlap. Fails if `self` is shorter than `src`.
1636 unsafe fn copy_memory(self, src: &[T]);
1639 impl<'a,T> MutableVector<'a, T> for &'a mut [T] {
1641 fn as_mut_slice(self) -> &'a mut [T] { self }
1643 fn mut_slice(self, start: uint, end: uint) -> &'a mut [T] {
1644 assert!(start <= end);
1645 assert!(end <= self.len());
1648 data: self.as_mut_ptr().offset(start as int) as *T,
1655 fn mut_slice_from(self, start: uint) -> &'a mut [T] {
1656 let len = self.len();
1657 self.mut_slice(start, len)
1661 fn mut_slice_to(self, end: uint) -> &'a mut [T] {
1662 self.mut_slice(0, end)
1666 fn mut_split_at(self, mid: uint) -> (&'a mut [T], &'a mut [T]) {
1668 let len = self.len();
1669 let self2: &'a mut [T] = cast::transmute_copy(&self);
1670 (self.mut_slice(0, mid), self2.mut_slice(mid, len))
1675 fn mut_iter(self) -> MutItems<'a, T> {
1677 let p = self.as_mut_ptr();
1678 if mem::size_of::<T>() == 0 {
1680 end: (p as uint + self.len()) as *mut T,
1681 marker: marker::ContravariantLifetime::<'a>,
1682 marker2: marker::NoCopy}
1685 end: p.offset(self.len() as int),
1686 marker: marker::ContravariantLifetime::<'a>,
1687 marker2: marker::NoCopy}
1693 fn mut_last(self) -> Option<&'a mut T> {
1694 let len = self.len();
1695 if len == 0 { return None; }
1696 Some(&mut self[len - 1])
1700 fn mut_rev_iter(self) -> RevMutItems<'a, T> {
1701 self.mut_iter().rev()
1705 fn mut_split(self, pred: |&T|: 'a -> bool) -> MutSplits<'a, T> {
1706 MutSplits { v: self, pred: pred, finished: false }
1710 fn mut_chunks(self, chunk_size: uint) -> MutChunks<'a, T> {
1711 assert!(chunk_size > 0);
1712 MutChunks { v: self, chunk_size: chunk_size }
1715 fn mut_shift_ref(&mut self) -> Option<&'a mut T> {
1716 if self.len() == 0 { return None; }
1718 let s: &mut Slice<T> = transmute(self);
1719 Some(cast::transmute_mut(&*raw::shift_ptr(s)))
1723 fn mut_pop_ref(&mut self) -> Option<&'a mut T> {
1724 if self.len() == 0 { return None; }
1726 let s: &mut Slice<T> = transmute(self);
1727 Some(cast::transmute_mut(&*raw::pop_ptr(s)))
1731 fn swap(self, a: uint, b: uint) {
1733 // Can't take two mutable loans from one vector, so instead just cast
1734 // them to their raw pointers to do the swap
1735 let pa: *mut T = &mut self[a];
1736 let pb: *mut T = &mut self[b];
1742 let mut i: uint = 0;
1743 let ln = self.len();
1745 self.swap(i, ln - i - 1);
1751 fn sort_by(self, compare: |&T, &T| -> Ordering) {
1752 merge_sort(self, compare)
1756 fn move_from(self, mut src: ~[T], start: uint, end: uint) -> uint {
1757 for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
1760 cmp::min(self.len(), end-start)
1764 unsafe fn unsafe_mut_ref(self, index: uint) -> &'a mut T {
1765 transmute((self.repr().data as *mut T).offset(index as int))
1769 fn as_mut_ptr(self) -> *mut T {
1770 self.repr().data as *mut T
1774 unsafe fn unsafe_set(self, index: uint, val: T) {
1775 *self.unsafe_mut_ref(index) = val;
1779 unsafe fn init_elem(self, i: uint, val: T) {
1780 mem::move_val_init(&mut (*self.as_mut_ptr().offset(i as int)), val);
1784 unsafe fn copy_memory(self, src: &[T]) {
1785 let len_src = src.len();
1786 assert!(self.len() >= len_src);
1787 ptr::copy_nonoverlapping_memory(self.as_mut_ptr(), src.as_ptr(), len_src)
1791 /// Trait for &[T] where T is Cloneable
1792 pub trait MutableCloneableVector<T> {
1793 /// Copies as many elements from `src` as it can into `self` (the
1794 /// shorter of `self.len()` and `src.len()`). Returns the number
1795 /// of elements copied.
1800 /// use std::slice::MutableCloneableVector;
1802 /// let mut dst = [0, 0, 0];
1803 /// let src = [1, 2];
1805 /// assert!(dst.copy_from(src) == 2);
1806 /// assert!(dst == [1, 2, 0]);
1808 /// let src2 = [3, 4, 5, 6];
1809 /// assert!(dst.copy_from(src2) == 3);
1810 /// assert!(dst == [3, 4, 5]);
1812 fn copy_from(self, &[T]) -> uint;
1815 impl<'a, T:Clone> MutableCloneableVector<T> for &'a mut [T] {
1817 fn copy_from(self, src: &[T]) -> uint {
1818 for (a, b) in self.mut_iter().zip(src.iter()) {
1821 cmp::min(self.len(), src.len())
1825 /// Methods for mutable vectors with orderable elements, such as
1826 /// in-place sorting.
1827 pub trait MutableTotalOrdVector<T> {
1828 /// Sort the vector, in place.
1830 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
1835 /// let mut v = [-5, 4, 1, -3, 2];
1838 /// assert!(v == [-5, -3, 1, 2, 4]);
1842 impl<'a, T: TotalOrd> MutableTotalOrdVector<T> for &'a mut [T] {
1845 self.sort_by(|a,b| a.cmp(b))
1850 * Constructs a vector from an unsafe pointer to a buffer
1854 * * ptr - An unsafe pointer to a buffer of `T`
1855 * * elts - The number of elements in the buffer
1857 // Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
1858 pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
1859 raw::from_buf_raw(ptr, elts)
1862 /// Unsafe operations
1864 use cast::transmute;
1869 use slice::{MutableVector, OwnedVector};
1873 * Form a slice from a pointer and length (as a number of units,
1877 pub unsafe fn buf_as_slice<T,U>(p: *T, len: uint, f: |v: &[T]| -> U)
1886 * Form a slice from a pointer and length (as a number of units,
1890 pub unsafe fn mut_buf_as_slice<T,
1894 f: |v: &mut [T]| -> U)
1903 * Constructs a vector from an unsafe pointer to a buffer
1907 * * ptr - An unsafe pointer to a buffer of `T`
1908 * * elts - The number of elements in the buffer
1910 // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
1912 pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
1913 let mut dst = Vec::with_capacity(elts);
1915 ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
1916 dst.move_iter().collect()
1920 * Returns a pointer to first element in slice and adjusts
1921 * slice so it no longer contains that element. Fails if
1922 * slice is empty. O(1).
1924 pub unsafe fn shift_ptr<T>(slice: &mut Slice<T>) -> *T {
1925 if slice.len == 0 { fail!("shift on empty slice"); }
1926 let head: *T = slice.data;
1927 slice.data = slice.data.offset(1);
1933 * Returns a pointer to last element in slice and adjusts
1934 * slice so it no longer contains that element. Fails if
1935 * slice is empty. O(1).
1937 pub unsafe fn pop_ptr<T>(slice: &mut Slice<T>) -> *T {
1938 if slice.len == 0 { fail!("pop on empty slice"); }
1939 let tail: *T = slice.data.offset((slice.len - 1) as int);
1945 /// Operations on `[u8]`.
1947 use container::Container;
1948 use slice::MutableVector;
1951 /// A trait for operations on mutable `[u8]`s.
1952 pub trait MutableByteVector {
1953 /// Sets all bytes of the receiver to the given value.
1954 fn set_memory(self, value: u8);
1957 impl<'a> MutableByteVector for &'a mut [u8] {
1959 fn set_memory(self, value: u8) {
1960 unsafe { ptr::set_memory(self.as_mut_ptr(), value, self.len()) };
1964 /// Copies data from `src` to `dst`
1966 /// `src` and `dst` must not overlap. Fails if the length of `dst`
1967 /// is less than the length of `src`.
1969 pub fn copy_memory(dst: &mut [u8], src: &[u8]) {
1970 // Bound checks are done at .copy_memory.
1971 unsafe { dst.copy_memory(src) }
1975 impl<A: Clone> Clone for ~[A] {
1977 fn clone(&self) -> ~[A] {
1978 // Use the fast to_owned on &[A] for cloning
1979 self.as_slice().to_owned()
1983 impl<'a, T: fmt::Show> fmt::Show for &'a [T] {
1984 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1985 if f.flags & (1 << (fmt::parse::FlagAlternate as uint)) == 0 {
1986 try!(write!(f.buf, "["));
1988 let mut is_first = true;
1989 for x in self.iter() {
1993 try!(write!(f.buf, ", "));
1995 try!(write!(f.buf, "{}", *x))
1997 if f.flags & (1 << (fmt::parse::FlagAlternate as uint)) == 0 {
1998 try!(write!(f.buf, "]"));
2004 impl<'a, T: fmt::Show> fmt::Show for &'a mut [T] {
2005 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2006 self.as_slice().fmt(f)
2010 impl<T: fmt::Show> fmt::Show for ~[T] {
2011 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
2012 self.as_slice().fmt(f)
2016 // This works because every lifetime is a sub-lifetime of 'static
2017 impl<'a, A> Default for &'a [A] {
2018 fn default() -> &'a [A] { &'a [] }
2021 impl<A> Default for ~[A] {
2022 fn default() -> ~[A] { ~[] }
2025 /// Immutable slice iterator
2026 pub struct Items<'a, T> {
2029 marker: marker::ContravariantLifetime<'a>
2032 /// Mutable slice iterator
2033 pub struct MutItems<'a, T> {
2036 marker: marker::ContravariantLifetime<'a>,
2037 marker2: marker::NoCopy
2040 macro_rules! iterator {
2041 (struct $name:ident -> $ptr:ty, $elem:ty) => {
2042 impl<'a, T> Iterator<$elem> for $name<'a, T> {
2044 fn next(&mut self) -> Option<$elem> {
2045 // could be implemented with slices, but this avoids bounds checks
2047 if self.ptr == self.end {
2051 self.ptr = if mem::size_of::<T>() == 0 {
2052 // purposefully don't use 'ptr.offset' because for
2053 // vectors with 0-size elements this would return the
2055 transmute(self.ptr as uint + 1)
2060 Some(transmute(old))
2066 fn size_hint(&self) -> (uint, Option<uint>) {
2067 let diff = (self.end as uint) - (self.ptr as uint);
2068 let exact = diff / mem::nonzero_size_of::<T>();
2069 (exact, Some(exact))
2073 impl<'a, T> DoubleEndedIterator<$elem> for $name<'a, T> {
2075 fn next_back(&mut self) -> Option<$elem> {
2076 // could be implemented with slices, but this avoids bounds checks
2078 if self.end == self.ptr {
2081 self.end = if mem::size_of::<T>() == 0 {
2082 // See above for why 'ptr.offset' isn't used
2083 transmute(self.end as uint - 1)
2087 Some(transmute(self.end))
2095 impl<'a, T> RandomAccessIterator<&'a T> for Items<'a, T> {
2097 fn indexable(&self) -> uint {
2098 let (exact, _) = self.size_hint();
2103 fn idx(&mut self, index: uint) -> Option<&'a T> {
2105 if index < self.indexable() {
2106 transmute(self.ptr.offset(index as int))
2114 iterator!{struct Items -> *T, &'a T}
2115 pub type RevItems<'a, T> = Rev<Items<'a, T>>;
2117 impl<'a, T> ExactSize<&'a T> for Items<'a, T> {}
2118 impl<'a, T> ExactSize<&'a mut T> for MutItems<'a, T> {}
2120 impl<'a, T> Clone for Items<'a, T> {
2121 fn clone(&self) -> Items<'a, T> { *self }
2124 iterator!{struct MutItems -> *mut T, &'a mut T}
2125 pub type RevMutItems<'a, T> = Rev<MutItems<'a, T>>;
2127 /// An iterator over the subslices of the vector which are separated
2128 /// by elements that match `pred`.
2129 pub struct MutSplits<'a, T> {
2131 pred: |t: &T|: 'a -> bool,
2135 impl<'a, T> Iterator<&'a mut [T]> for MutSplits<'a, T> {
2137 fn next(&mut self) -> Option<&'a mut [T]> {
2138 if self.finished { return None; }
2140 let pred = &mut self.pred;
2141 match self.v.iter().position(|x| (*pred)(x)) {
2143 self.finished = true;
2144 let tmp = mem::replace(&mut self.v, &mut []);
2145 let len = tmp.len();
2146 let (head, tail) = tmp.mut_split_at(len);
2151 let tmp = mem::replace(&mut self.v, &mut []);
2152 let (head, tail) = tmp.mut_split_at(idx);
2153 self.v = tail.mut_slice_from(1);
2160 fn size_hint(&self) -> (uint, Option<uint>) {
2164 // if the predicate doesn't match anything, we yield one slice
2165 // if it matches every element, we yield len+1 empty slices.
2166 (1, Some(self.v.len() + 1))
2171 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutSplits<'a, T> {
2173 fn next_back(&mut self) -> Option<&'a mut [T]> {
2174 if self.finished { return None; }
2176 let pred = &mut self.pred;
2177 match self.v.iter().rposition(|x| (*pred)(x)) {
2179 self.finished = true;
2180 let tmp = mem::replace(&mut self.v, &mut []);
2184 let tmp = mem::replace(&mut self.v, &mut []);
2185 let (head, tail) = tmp.mut_split_at(idx);
2187 Some(tail.mut_slice_from(1))
2193 /// An iterator over a vector in (non-overlapping) mutable chunks (`size` elements at a time). When
2194 /// the vector len is not evenly divided by the chunk size, the last slice of the iteration will be
2196 pub struct MutChunks<'a, T> {
2201 impl<'a, T> Iterator<&'a mut [T]> for MutChunks<'a, T> {
2203 fn next(&mut self) -> Option<&'a mut [T]> {
2204 if self.v.len() == 0 {
2207 let sz = cmp::min(self.v.len(), self.chunk_size);
2208 let tmp = mem::replace(&mut self.v, &mut []);
2209 let (head, tail) = tmp.mut_split_at(sz);
2216 fn size_hint(&self) -> (uint, Option<uint>) {
2217 if self.v.len() == 0 {
2220 let (n, rem) = div_rem(self.v.len(), self.chunk_size);
2221 let n = if rem > 0 { n + 1 } else { n };
2227 impl<'a, T> DoubleEndedIterator<&'a mut [T]> for MutChunks<'a, T> {
2229 fn next_back(&mut self) -> Option<&'a mut [T]> {
2230 if self.v.len() == 0 {
2233 let remainder = self.v.len() % self.chunk_size;
2234 let sz = if remainder != 0 { remainder } else { self.chunk_size };
2235 let tmp = mem::replace(&mut self.v, &mut []);
2236 let tmp_len = tmp.len();
2237 let (head, tail) = tmp.mut_split_at(tmp_len - sz);
2244 /// An iterator that moves out of a vector.
2245 pub struct MoveItems<T> {
2246 allocation: *mut u8, // the block of memory allocated for the vector
2247 iter: Items<'static, T>
2250 impl<T> Iterator<T> for MoveItems<T> {
2252 fn next(&mut self) -> Option<T> {
2254 self.iter.next().map(|x| ptr::read(x))
2259 fn size_hint(&self) -> (uint, Option<uint>) {
2260 self.iter.size_hint()
2264 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
2266 fn next_back(&mut self) -> Option<T> {
2268 self.iter.next_back().map(|x| ptr::read(x))
2273 #[unsafe_destructor]
2274 impl<T> Drop for MoveItems<T> {
2275 fn drop(&mut self) {
2276 // destroy the remaining elements
2279 exchange_free(self.allocation as *u8)
2284 /// An iterator that moves out of a vector in reverse order.
2285 pub type RevMoveItems<T> = Rev<MoveItems<T>>;
2287 impl<A> FromIterator<A> for ~[A] {
2288 fn from_iter<T: Iterator<A>>(mut iterator: T) -> ~[A] {
2289 let mut xs: Vec<A> = iterator.collect();
2291 // Must shrink so the capacity is the same as the length. The length of
2292 // the ~[T] vector must exactly match the length of the allocation.
2296 assert!(len == xs.capacity());
2297 let data = xs.as_mut_ptr();
2299 let data_size = len.checked_mul(&mem::size_of::<A>());
2300 let data_size = data_size.expect("overflow in from_iter()");
2301 let size = mem::size_of::<RawVec<()>>().checked_add(&data_size);
2302 let size = size.expect("overflow in from_iter()");
2305 // This is some terribly awful code. Note that all of this will go away
2306 // with DST because creating ~[T] from Vec<T> will just be some pointer
2309 let ret = malloc_raw(size) as *mut RawVec<()>;
2311 (*ret).fill = len * mem::nonzero_size_of::<A>();
2312 (*ret).alloc = len * mem::nonzero_size_of::<A>();
2313 ptr::copy_nonoverlapping_memory(&mut (*ret).data as *mut _ as *mut u8,
2316 xs.set_len(0); // ownership has been transferred
2317 cast::transmute(ret)
2328 use rand::{Rng, task_rng};
2330 fn square(n: uint) -> uint { n * n }
2332 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
2335 fn test_unsafe_ptrs() {
2337 // Test on-stack copy-from-buf.
2339 let mut ptr = a.as_ptr();
2340 let b = from_buf(ptr, 3u);
2341 assert_eq!(b.len(), 3u);
2342 assert_eq!(b[0], 1);
2343 assert_eq!(b[1], 2);
2344 assert_eq!(b[2], 3);
2346 // Test on-heap copy-from-buf.
2347 let c = ~[1, 2, 3, 4, 5];
2349 let d = from_buf(ptr, 5u);
2350 assert_eq!(d.len(), 5u);
2351 assert_eq!(d[0], 1);
2352 assert_eq!(d[1], 2);
2353 assert_eq!(d[2], 3);
2354 assert_eq!(d[3], 4);
2355 assert_eq!(d[4], 5);
2361 // Test on-stack from_fn.
2362 let mut v = Vec::from_fn(3u, square);
2364 let v = v.as_slice();
2365 assert_eq!(v.len(), 3u);
2366 assert_eq!(v[0], 0u);
2367 assert_eq!(v[1], 1u);
2368 assert_eq!(v[2], 4u);
2371 // Test on-heap from_fn.
2372 v = Vec::from_fn(5u, square);
2374 let v = v.as_slice();
2375 assert_eq!(v.len(), 5u);
2376 assert_eq!(v[0], 0u);
2377 assert_eq!(v[1], 1u);
2378 assert_eq!(v[2], 4u);
2379 assert_eq!(v[3], 9u);
2380 assert_eq!(v[4], 16u);
2385 fn test_from_elem() {
2386 // Test on-stack from_elem.
2387 let mut v = Vec::from_elem(2u, 10u);
2389 let v = v.as_slice();
2390 assert_eq!(v.len(), 2u);
2391 assert_eq!(v[0], 10u);
2392 assert_eq!(v[1], 10u);
2395 // Test on-heap from_elem.
2396 v = Vec::from_elem(6u, 20u);
2398 let v = v.as_slice();
2399 assert_eq!(v[0], 20u);
2400 assert_eq!(v[1], 20u);
2401 assert_eq!(v[2], 20u);
2402 assert_eq!(v[3], 20u);
2403 assert_eq!(v[4], 20u);
2404 assert_eq!(v[5], 20u);
2409 fn test_is_empty() {
2410 let xs: [int, ..0] = [];
2411 assert!(xs.is_empty());
2412 assert!(![0].is_empty());
2416 fn test_len_divzero() {
2418 let v0 : &[Z] = &[];
2419 let v1 : &[Z] = &[[]];
2420 let v2 : &[Z] = &[[], []];
2421 assert_eq!(mem::size_of::<Z>(), 0);
2422 assert_eq!(v0.len(), 0);
2423 assert_eq!(v1.len(), 1);
2424 assert_eq!(v2.len(), 2);
2430 assert_eq!(a.get(1), None);
2432 assert_eq!(a.get(1).unwrap(), &12);
2434 assert_eq!(a.get(1).unwrap(), &12);
2440 assert_eq!(a.head(), None);
2442 assert_eq!(a.head().unwrap(), &11);
2444 assert_eq!(a.head().unwrap(), &11);
2450 assert_eq!(a.tail(), &[]);
2452 assert_eq!(a.tail(), &[12]);
2457 fn test_tail_empty() {
2458 let a: ~[int] = ~[];
2464 let mut a = ~[11, 12, 13];
2465 assert_eq!(a.tailn(0), &[11, 12, 13]);
2467 assert_eq!(a.tailn(2), &[13]);
2472 fn test_tailn_empty() {
2473 let a: ~[int] = ~[];
2480 assert_eq!(a.init(), &[]);
2482 assert_eq!(a.init(), &[11]);
2487 fn test_init_empty() {
2488 let a: ~[int] = ~[];
2494 let mut a = ~[11, 12, 13];
2495 assert_eq!(a.initn(0), &[11, 12, 13]);
2497 assert_eq!(a.initn(2), &[11]);
2502 fn test_initn_empty() {
2503 let a: ~[int] = ~[];
2510 assert_eq!(a.last(), None);
2512 assert_eq!(a.last().unwrap(), &11);
2514 assert_eq!(a.last().unwrap(), &12);
2519 // Test fixed length vector.
2520 let vec_fixed = [1, 2, 3, 4];
2521 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
2522 assert_eq!(v_a.len(), 3u);
2523 assert_eq!(v_a[0], 2);
2524 assert_eq!(v_a[1], 3);
2525 assert_eq!(v_a[2], 4);
2528 let vec_stack = &[1, 2, 3];
2529 let v_b = vec_stack.slice(1u, 3u).to_owned();
2530 assert_eq!(v_b.len(), 2u);
2531 assert_eq!(v_b[0], 2);
2532 assert_eq!(v_b[1], 3);
2534 // Test on exchange heap.
2535 let vec_unique = ~[1, 2, 3, 4, 5, 6];
2536 let v_d = vec_unique.slice(1u, 6u).to_owned();
2537 assert_eq!(v_d.len(), 5u);
2538 assert_eq!(v_d[0], 2);
2539 assert_eq!(v_d[1], 3);
2540 assert_eq!(v_d[2], 4);
2541 assert_eq!(v_d[3], 5);
2542 assert_eq!(v_d[4], 6);
2546 fn test_slice_from() {
2547 let vec = &[1, 2, 3, 4];
2548 assert_eq!(vec.slice_from(0), vec);
2549 assert_eq!(vec.slice_from(2), &[3, 4]);
2550 assert_eq!(vec.slice_from(4), &[]);
2554 fn test_slice_to() {
2555 let vec = &[1, 2, 3, 4];
2556 assert_eq!(vec.slice_to(4), vec);
2557 assert_eq!(vec.slice_to(2), &[1, 2]);
2558 assert_eq!(vec.slice_to(0), &[]);
2564 let mut v = vec![5];
2566 assert_eq!(v.len(), 0);
2567 assert_eq!(e, Some(5));
2569 assert_eq!(f, None);
2571 assert_eq!(g, None);
2575 fn test_swap_remove() {
2576 let mut v = vec![1, 2, 3, 4, 5];
2577 let mut e = v.swap_remove(0);
2578 assert_eq!(e, Some(1));
2579 assert_eq!(v, vec![5, 2, 3, 4]);
2580 e = v.swap_remove(3);
2581 assert_eq!(e, Some(4));
2582 assert_eq!(v, vec![5, 2, 3]);
2584 e = v.swap_remove(3);
2585 assert_eq!(e, None);
2586 assert_eq!(v, vec![5, 2, 3]);
2590 fn test_swap_remove_noncopyable() {
2591 // Tests that we don't accidentally run destructors twice.
2592 let mut v = vec![::unstable::sync::Exclusive::new(()),
2593 ::unstable::sync::Exclusive::new(()),
2594 ::unstable::sync::Exclusive::new(())];
2595 let mut _e = v.swap_remove(0);
2596 assert_eq!(v.len(), 2);
2597 _e = v.swap_remove(1);
2598 assert_eq!(v.len(), 1);
2599 _e = v.swap_remove(0);
2600 assert_eq!(v.len(), 0);
2605 // Test on-stack push().
2608 assert_eq!(v.len(), 1u);
2609 assert_eq!(v.as_slice()[0], 1);
2611 // Test on-heap push().
2613 assert_eq!(v.len(), 2u);
2614 assert_eq!(v.as_slice()[0], 1);
2615 assert_eq!(v.as_slice()[1], 2);
2620 // Test on-stack grow().
2624 let v = v.as_slice();
2625 assert_eq!(v.len(), 2u);
2626 assert_eq!(v[0], 1);
2627 assert_eq!(v[1], 1);
2630 // Test on-heap grow().
2633 let v = v.as_slice();
2634 assert_eq!(v.len(), 5u);
2635 assert_eq!(v[0], 1);
2636 assert_eq!(v[1], 1);
2637 assert_eq!(v[2], 2);
2638 assert_eq!(v[3], 2);
2639 assert_eq!(v[4], 2);
2646 v.grow_fn(3u, square);
2647 let v = v.as_slice();
2648 assert_eq!(v.len(), 3u);
2649 assert_eq!(v[0], 0u);
2650 assert_eq!(v[1], 1u);
2651 assert_eq!(v[2], 4u);
2655 fn test_grow_set() {
2656 let mut v = vec![1, 2, 3];
2657 v.grow_set(4u, &4, 5);
2658 let v = v.as_slice();
2659 assert_eq!(v.len(), 5u);
2660 assert_eq!(v[0], 1);
2661 assert_eq!(v[1], 2);
2662 assert_eq!(v[2], 3);
2663 assert_eq!(v[3], 4);
2664 assert_eq!(v[4], 5);
2668 fn test_truncate() {
2669 let mut v = vec![~6,~5,~4];
2671 let v = v.as_slice();
2672 assert_eq!(v.len(), 1);
2673 assert_eq!(*(v[0]), 6);
2674 // If the unsafe block didn't drop things properly, we blow up here.
2679 let mut v = vec![~6,~5,~4];
2681 assert_eq!(v.len(), 0);
2682 // If the unsafe block didn't drop things properly, we blow up here.
2687 fn case(a: Vec<uint>, b: Vec<uint>) {
2692 case(vec![], vec![]);
2693 case(vec![1], vec![1]);
2694 case(vec![1,1], vec![1]);
2695 case(vec![1,2,3], vec![1,2,3]);
2696 case(vec![1,1,2,3], vec![1,2,3]);
2697 case(vec![1,2,2,3], vec![1,2,3]);
2698 case(vec![1,2,3,3], vec![1,2,3]);
2699 case(vec![1,1,2,2,2,3,3], vec![1,2,3]);
2703 fn test_dedup_unique() {
2704 let mut v0 = vec![~1, ~1, ~2, ~3];
2706 let mut v1 = vec![~1, ~2, ~2, ~3];
2708 let mut v2 = vec![~1, ~2, ~3, ~3];
2711 * If the ~pointers were leaked or otherwise misused, valgrind and/or
2712 * rustrt should raise errors.
2717 fn test_dedup_shared() {
2718 let mut v0 = vec![~1, ~1, ~2, ~3];
2720 let mut v1 = vec![~1, ~2, ~2, ~3];
2722 let mut v2 = vec![~1, ~2, ~3, ~3];
2725 * If the pointers were leaked or otherwise misused, valgrind and/or
2726 * rustrt should raise errors.
2732 let mut v = vec![1, 2, 3, 4, 5];
2734 assert_eq!(v, vec![1, 3, 5]);
2738 fn test_zip_unzip() {
2739 let z1 = vec![(1, 4), (2, 5), (3, 6)];
2741 let (left, right) = unzip(z1.iter().map(|&x| x));
2743 assert_eq!((1, 4), (left[0], right[0]));
2744 assert_eq!((2, 5), (left[1], right[1]));
2745 assert_eq!((3, 6), (left[2], right[2]));
2749 fn test_element_swaps() {
2750 let mut v = [1, 2, 3];
2751 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
2754 0 => assert!(v == [1, 3, 2]),
2755 1 => assert!(v == [3, 1, 2]),
2756 2 => assert!(v == [3, 2, 1]),
2757 3 => assert!(v == [2, 3, 1]),
2758 4 => assert!(v == [2, 1, 3]),
2759 5 => assert!(v == [1, 2, 3]),
2766 fn test_permutations() {
2768 let v: [int, ..0] = [];
2769 let mut it = v.permutations();
2770 assert_eq!(it.next(), None);
2773 let v = ["Hello".to_owned()];
2774 let mut it = v.permutations();
2775 assert_eq!(it.next(), None);
2779 let mut it = v.permutations();
2780 assert_eq!(it.next(), Some(~[1,2,3]));
2781 assert_eq!(it.next(), Some(~[1,3,2]));
2782 assert_eq!(it.next(), Some(~[3,1,2]));
2783 assert_eq!(it.next(), Some(~[3,2,1]));
2784 assert_eq!(it.next(), Some(~[2,3,1]));
2785 assert_eq!(it.next(), Some(~[2,1,3]));
2786 assert_eq!(it.next(), None);
2789 // check that we have N! permutations
2790 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
2792 for _perm in v.permutations() {
2795 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
2800 fn test_position_elem() {
2801 assert!([].position_elem(&1).is_none());
2803 let v1 = ~[1, 2, 3, 3, 2, 5];
2804 assert_eq!(v1.position_elem(&1), Some(0u));
2805 assert_eq!(v1.position_elem(&2), Some(1u));
2806 assert_eq!(v1.position_elem(&5), Some(5u));
2807 assert!(v1.position_elem(&4).is_none());
2811 fn test_bsearch_elem() {
2812 assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
2813 assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
2814 assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
2815 assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
2816 assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
2818 assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
2819 assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
2820 assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
2821 assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
2823 assert_eq!([2,4,6,8].bsearch_elem(&1), None);
2824 assert_eq!([2,4,6,8].bsearch_elem(&5), None);
2825 assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
2826 assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
2828 assert_eq!([2,4,6].bsearch_elem(&1), None);
2829 assert_eq!([2,4,6].bsearch_elem(&5), None);
2830 assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
2831 assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
2833 assert_eq!([2,4].bsearch_elem(&1), None);
2834 assert_eq!([2,4].bsearch_elem(&5), None);
2835 assert_eq!([2,4].bsearch_elem(&2), Some(0));
2836 assert_eq!([2,4].bsearch_elem(&4), Some(1));
2838 assert_eq!([2].bsearch_elem(&1), None);
2839 assert_eq!([2].bsearch_elem(&5), None);
2840 assert_eq!([2].bsearch_elem(&2), Some(0));
2842 assert_eq!([].bsearch_elem(&1), None);
2843 assert_eq!([].bsearch_elem(&5), None);
2845 assert!([1,1,1,1,1].bsearch_elem(&1) != None);
2846 assert!([1,1,1,1,2].bsearch_elem(&1) != None);
2847 assert!([1,1,1,2,2].bsearch_elem(&1) != None);
2848 assert!([1,1,2,2,2].bsearch_elem(&1) != None);
2849 assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
2851 assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
2852 assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
2857 let mut v: ~[int] = ~[10, 20];
2858 assert_eq!(v[0], 10);
2859 assert_eq!(v[1], 20);
2861 assert_eq!(v[0], 20);
2862 assert_eq!(v[1], 10);
2864 let mut v3: ~[int] = ~[];
2866 assert!(v3.is_empty());
2871 use realstd::slice::Vector;
2872 use realstd::clone::Clone;
2873 for len in range(4u, 25) {
2874 for _ in range(0, 100) {
2875 let mut v = task_rng().gen_vec::<uint>(len);
2876 let mut v1 = v.clone();
2878 v.as_mut_slice().sort();
2879 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
2881 v1.as_mut_slice().sort_by(|a, b| a.cmp(b));
2882 assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
2884 v1.as_mut_slice().sort_by(|a, b| b.cmp(a));
2885 assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
2889 // shouldn't fail/crash
2890 let mut v: [uint, .. 0] = [];
2893 let mut v = [0xDEADBEEFu];
2895 assert!(v == [0xDEADBEEF]);
2899 fn test_sort_stability() {
2900 for len in range(4, 25) {
2901 for _ in range(0 , 10) {
2902 let mut counts = [0, .. 10];
2904 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
2905 // where the first item of each tuple is random, but
2906 // the second item represents which occurrence of that
2907 // number this element is, i.e. the second elements
2908 // will occur in sorted order.
2909 let mut v = range(0, len).map(|_| {
2910 let n = task_rng().gen::<uint>() % 10;
2913 }).collect::<~[(uint, int)]>();
2915 // only sort on the first element, so an unstable sort
2916 // may mix up the counts.
2917 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
2919 // this comparison includes the count (the second item
2920 // of the tuple), so elements with equal first items
2921 // will need to be ordered with increasing
2922 // counts... i.e. exactly asserting that this sort is
2924 assert!(v.windows(2).all(|w| w[0] <= w[1]));
2930 fn test_partition() {
2931 assert_eq!((~[]).partition(|x: &int| *x < 3), (~[], ~[]));
2932 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
2933 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 2), (~[1], ~[2, 3]));
2934 assert_eq!((~[1, 2, 3]).partition(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
2938 fn test_partitioned() {
2939 assert_eq!(([]).partitioned(|x: &int| *x < 3), (~[], ~[]))
2940 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (~[1, 2, 3], ~[]));
2941 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (~[1], ~[2, 3]));
2942 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (~[], ~[1, 2, 3]));
2947 let v: [~[int], ..0] = [];
2948 assert_eq!(v.concat_vec(), ~[]);
2949 assert_eq!([~[1], ~[2,3]].concat_vec(), ~[1, 2, 3]);
2951 assert_eq!([&[1], &[2,3]].concat_vec(), ~[1, 2, 3]);
2956 let v: [~[int], ..0] = [];
2957 assert_eq!(v.connect_vec(&0), ~[]);
2958 assert_eq!([~[1], ~[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
2959 assert_eq!([~[1], ~[2], ~[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
2961 assert_eq!(v.connect_vec(&0), ~[]);
2962 assert_eq!([&[1], &[2, 3]].connect_vec(&0), ~[1, 0, 2, 3]);
2963 assert_eq!([&[1], &[2], &[3]].connect_vec(&0), ~[1, 0, 2, 0, 3]);
2968 let mut x = vec![1, 2, 3];
2969 assert_eq!(x.shift(), Some(1));
2970 assert_eq!(&x, &vec![2, 3]);
2971 assert_eq!(x.shift(), Some(2));
2972 assert_eq!(x.shift(), Some(3));
2973 assert_eq!(x.shift(), None);
2974 assert_eq!(x.len(), 0);
2979 let mut x = vec![1, 2, 3];
2981 assert_eq!(x, vec![0, 1, 2, 3]);
2986 let mut a = vec![1, 2, 4];
2988 assert_eq!(a, vec![1, 2, 3, 4]);
2990 let mut a = vec![1, 2, 3];
2992 assert_eq!(a, vec![0, 1, 2, 3]);
2994 let mut a = vec![1, 2, 3];
2996 assert_eq!(a, vec![1, 2, 3, 4]);
3000 assert_eq!(a, vec![1]);
3005 fn test_insert_oob() {
3006 let mut a = vec![1, 2, 3];
3012 let mut a = vec![1,2,3,4];
3014 assert_eq!(a.remove(2), Some(3));
3015 assert_eq!(a, vec![1,2,4]);
3017 assert_eq!(a.remove(2), Some(4));
3018 assert_eq!(a, vec![1,2]);
3020 assert_eq!(a.remove(2), None);
3021 assert_eq!(a, vec![1,2]);
3023 assert_eq!(a.remove(0), Some(1));
3024 assert_eq!(a, vec![2]);
3026 assert_eq!(a.remove(0), Some(2));
3027 assert_eq!(a, vec![]);
3029 assert_eq!(a.remove(0), None);
3030 assert_eq!(a.remove(10), None);
3034 fn test_capacity() {
3035 let mut v = vec![0u64];
3036 v.reserve_exact(10u);
3037 assert_eq!(v.capacity(), 10u);
3038 let mut v = vec![0u32];
3039 v.reserve_exact(10u);
3040 assert_eq!(v.capacity(), 10u);
3045 let v = vec![1, 2, 3, 4, 5];
3046 let v = v.slice(1u, 3u);
3047 assert_eq!(v.len(), 2u);
3048 assert_eq!(v[0], 2);
3049 assert_eq!(v[1], 3);
3055 fn test_from_fn_fail() {
3056 Vec::from_fn(100, |v| {
3057 if v == 50 { fail!() }
3064 fn test_from_elem_fail() {
3070 boxes: (~int, Rc<int>)
3074 fn clone(&self) -> S {
3075 let s = unsafe { cast::transmute_mut(self) };
3077 if s.f == 10 { fail!() }
3078 S { f: s.f, boxes: s.boxes.clone() }
3082 let s = S { f: 0, boxes: (~0, Rc::new(0)) };
3083 let _ = Vec::from_elem(100, s);
3088 fn test_grow_fn_fail() {
3091 v.grow_fn(100, |i| {
3101 fn test_permute_fail() {
3103 let v = [(~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0)), (~0, Rc::new(0))];
3105 for _ in v.permutations() {
3115 fn test_copy_memory_oob() {
3117 let mut a = [1, 2, 3, 4];
3118 let b = [1, 2, 3, 4, 5];
3124 fn test_total_ord() {
3125 [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
3126 [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
3127 [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
3128 [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
3129 [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
3133 fn test_iterator() {
3135 let xs = [1, 2, 5, 10, 11];
3136 let mut it = xs.iter();
3137 assert_eq!(it.size_hint(), (5, Some(5)));
3138 assert_eq!(it.next().unwrap(), &1);
3139 assert_eq!(it.size_hint(), (4, Some(4)));
3140 assert_eq!(it.next().unwrap(), &2);
3141 assert_eq!(it.size_hint(), (3, Some(3)));
3142 assert_eq!(it.next().unwrap(), &5);
3143 assert_eq!(it.size_hint(), (2, Some(2)));
3144 assert_eq!(it.next().unwrap(), &10);
3145 assert_eq!(it.size_hint(), (1, Some(1)));
3146 assert_eq!(it.next().unwrap(), &11);
3147 assert_eq!(it.size_hint(), (0, Some(0)));
3148 assert!(it.next().is_none());
3152 fn test_random_access_iterator() {
3154 let xs = [1, 2, 5, 10, 11];
3155 let mut it = xs.iter();
3157 assert_eq!(it.indexable(), 5);
3158 assert_eq!(it.idx(0).unwrap(), &1);
3159 assert_eq!(it.idx(2).unwrap(), &5);
3160 assert_eq!(it.idx(4).unwrap(), &11);
3161 assert!(it.idx(5).is_none());
3163 assert_eq!(it.next().unwrap(), &1);
3164 assert_eq!(it.indexable(), 4);
3165 assert_eq!(it.idx(0).unwrap(), &2);
3166 assert_eq!(it.idx(3).unwrap(), &11);
3167 assert!(it.idx(4).is_none());
3169 assert_eq!(it.next().unwrap(), &2);
3170 assert_eq!(it.indexable(), 3);
3171 assert_eq!(it.idx(1).unwrap(), &10);
3172 assert!(it.idx(3).is_none());
3174 assert_eq!(it.next().unwrap(), &5);
3175 assert_eq!(it.indexable(), 2);
3176 assert_eq!(it.idx(1).unwrap(), &11);
3178 assert_eq!(it.next().unwrap(), &10);
3179 assert_eq!(it.indexable(), 1);
3180 assert_eq!(it.idx(0).unwrap(), &11);
3181 assert!(it.idx(1).is_none());
3183 assert_eq!(it.next().unwrap(), &11);
3184 assert_eq!(it.indexable(), 0);
3185 assert!(it.idx(0).is_none());
3187 assert!(it.next().is_none());
3191 fn test_iter_size_hints() {
3193 let mut xs = [1, 2, 5, 10, 11];
3194 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
3195 assert_eq!(xs.rev_iter().size_hint(), (5, Some(5)));
3196 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
3197 assert_eq!(xs.mut_rev_iter().size_hint(), (5, Some(5)));
3201 fn test_iter_clone() {
3203 let mut it = xs.iter();
3205 let mut jt = it.clone();
3206 assert_eq!(it.next(), jt.next());
3207 assert_eq!(it.next(), jt.next());
3208 assert_eq!(it.next(), jt.next());
3212 fn test_mut_iterator() {
3214 let mut xs = [1, 2, 3, 4, 5];
3215 for x in xs.mut_iter() {
3218 assert!(xs == [2, 3, 4, 5, 6])
3222 fn test_rev_iterator() {
3225 let xs = [1, 2, 5, 10, 11];
3226 let ys = [11, 10, 5, 2, 1];
3228 for &x in xs.rev_iter() {
3229 assert_eq!(x, ys[i]);
3236 fn test_mut_rev_iterator() {
3238 let mut xs = [1u, 2, 3, 4, 5];
3239 for (i,x) in xs.mut_rev_iter().enumerate() {
3242 assert!(xs == [5, 5, 5, 5, 5])
3246 fn test_move_iterator() {
3248 let xs = ~[1u,2,3,4,5];
3249 assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
3253 fn test_move_rev_iterator() {
3255 let xs = ~[1u,2,3,4,5];
3256 assert_eq!(xs.move_rev_iter().fold(0, |a: uint, b: uint| 10*a + b), 54321);
3260 fn test_splitator() {
3261 let xs = &[1i,2,3,4,5];
3263 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3264 ~[&[1], &[3], &[5]]);
3265 assert_eq!(xs.split(|x| *x == 1).collect::<~[&[int]]>(),
3266 ~[&[], &[2,3,4,5]]);
3267 assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(),
3268 ~[&[1,2,3,4], &[]]);
3269 assert_eq!(xs.split(|x| *x == 10).collect::<~[&[int]]>(),
3271 assert_eq!(xs.split(|_| true).collect::<~[&[int]]>(),
3272 ~[&[], &[], &[], &[], &[], &[]]);
3274 let xs: &[int] = &[];
3275 assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3279 fn test_splitnator() {
3280 let xs = &[1i,2,3,4,5];
3282 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3284 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3286 assert_eq!(xs.splitn(3, |_| true).collect::<~[&[int]]>(),
3287 ~[&[], &[], &[], &[4,5]]);
3289 let xs: &[int] = &[];
3290 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3294 fn test_rsplitator() {
3295 let xs = &[1i,2,3,4,5];
3297 assert_eq!(xs.rsplit(|x| *x % 2 == 0).collect::<~[&[int]]>(),
3298 ~[&[5], &[3], &[1]]);
3299 assert_eq!(xs.rsplit(|x| *x == 1).collect::<~[&[int]]>(),
3300 ~[&[2,3,4,5], &[]]);
3301 assert_eq!(xs.rsplit(|x| *x == 5).collect::<~[&[int]]>(),
3302 ~[&[], &[1,2,3,4]]);
3303 assert_eq!(xs.rsplit(|x| *x == 10).collect::<~[&[int]]>(),
3306 let xs: &[int] = &[];
3307 assert_eq!(xs.rsplit(|x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3311 fn test_rsplitnator() {
3312 let xs = &[1,2,3,4,5];
3314 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3316 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
3318 assert_eq!(xs.rsplitn(3, |_| true).collect::<~[&[int]]>(),
3319 ~[&[], &[], &[], &[1,2]]);
3321 let xs: &[int] = &[];
3322 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<~[&[int]]>(), ~[&[]]);
3326 fn test_windowsator() {
3327 let v = &[1i,2,3,4];
3329 assert_eq!(v.windows(2).collect::<~[&[int]]>(), ~[&[1,2], &[2,3], &[3,4]]);
3330 assert_eq!(v.windows(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[2,3,4]]);
3331 assert!(v.windows(6).next().is_none());
3336 fn test_windowsator_0() {
3337 let v = &[1i,2,3,4];
3338 let _it = v.windows(0);
3342 fn test_chunksator() {
3343 let v = &[1i,2,3,4,5];
3345 assert_eq!(v.chunks(2).collect::<~[&[int]]>(), ~[&[1i,2], &[3,4], &[5]]);
3346 assert_eq!(v.chunks(3).collect::<~[&[int]]>(), ~[&[1i,2,3], &[4,5]]);
3347 assert_eq!(v.chunks(6).collect::<~[&[int]]>(), ~[&[1i,2,3,4,5]]);
3349 assert_eq!(v.chunks(2).rev().collect::<~[&[int]]>(), ~[&[5i], &[3,4], &[1,2]]);
3350 let mut it = v.chunks(2);
3351 assert_eq!(it.indexable(), 3);
3352 assert_eq!(it.idx(0).unwrap(), &[1,2]);
3353 assert_eq!(it.idx(1).unwrap(), &[3,4]);
3354 assert_eq!(it.idx(2).unwrap(), &[5]);
3355 assert_eq!(it.idx(3), None);
3360 fn test_chunksator_0() {
3361 let v = &[1i,2,3,4];
3362 let _it = v.chunks(0);
3366 fn test_move_from() {
3367 let mut a = [1,2,3,4,5];
3369 assert_eq!(a.move_from(b, 0, 3), 3);
3370 assert!(a == [6,7,8,4,5]);
3371 let mut a = [7,2,8,1];
3372 let b = ~[3,1,4,1,5,9];
3373 assert_eq!(a.move_from(b, 0, 6), 4);
3374 assert!(a == [3,1,4,1]);
3375 let mut a = [1,2,3,4];
3376 let b = ~[5,6,7,8,9,0];
3377 assert_eq!(a.move_from(b, 2, 3), 1);
3378 assert!(a == [7,2,3,4]);
3379 let mut a = [1,2,3,4,5];
3380 let b = ~[5,6,7,8,9,0];
3381 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
3382 assert!(a == [1,2,6,7,5]);
3386 fn test_copy_from() {
3387 let mut a = [1,2,3,4,5];
3389 assert_eq!(a.copy_from(b), 3);
3390 assert!(a == [6,7,8,4,5]);
3391 let mut c = [7,2,8,1];
3392 let d = [3,1,4,1,5,9];
3393 assert_eq!(c.copy_from(d), 4);
3394 assert!(c == [3,1,4,1]);
3398 fn test_reverse_part() {
3399 let mut values = [1,2,3,4,5];
3400 values.mut_slice(1, 4).reverse();
3401 assert!(values == [1,4,3,2,5]);
3406 macro_rules! test_show_vec(
3407 ($x:expr, $x_str:expr) => ({
3408 let (x, x_str) = ($x, $x_str);
3409 assert_eq!(format!("{}", x), x_str);
3410 assert_eq!(format!("{}", x.as_slice()), x_str);
3413 let empty: ~[int] = ~[];
3414 test_show_vec!(empty, "[]".to_owned());
3415 test_show_vec!(~[1], "[1]".to_owned());
3416 test_show_vec!(~[1, 2, 3], "[1, 2, 3]".to_owned());
3417 test_show_vec!(~[~[], ~[1u], ~[1u, 1u]], "[[], [1], [1, 1]]".to_owned());
3419 let empty_mut: &mut [int] = &mut[];
3420 test_show_vec!(empty_mut, "[]".to_owned());
3421 test_show_vec!(&mut[1], "[1]".to_owned());
3422 test_show_vec!(&mut[1, 2, 3], "[1, 2, 3]".to_owned());
3423 test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]], "[[], [1], [1, 1]]".to_owned());
3427 fn test_vec_default() {
3428 use default::Default;
3431 let v: $ty = Default::default();
3432 assert!(v.is_empty());
3442 fn test_bytes_set_memory() {
3443 use slice::bytes::MutableByteVector;
3444 let mut values = [1u8,2,3,4,5];
3445 values.mut_slice(0,5).set_memory(0xAB);
3446 assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
3447 values.mut_slice(2,4).set_memory(0xFF);
3448 assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
3453 fn test_overflow_does_not_cause_segfault() {
3455 v.reserve_exact(-1);
3462 fn test_overflow_does_not_cause_segfault_managed() {
3464 let mut v = vec![Rc::new(1)];
3465 v.reserve_exact(-1);
3470 fn test_mut_split_at() {
3471 let mut values = [1u8,2,3,4,5];
3473 let (left, right) = values.mut_split_at(2);
3474 assert!(left.slice(0, left.len()) == [1, 2]);
3475 for p in left.mut_iter() {
3479 assert!(right.slice(0, right.len()) == [3, 4, 5]);
3480 for p in right.mut_iter() {
3485 assert!(values == [2, 3, 5, 6, 7]);
3488 #[deriving(Clone, Eq)]
3492 fn test_iter_zero_sized() {
3493 let mut v = vec![Foo, Foo, Foo];
3494 assert_eq!(v.len(), 3);
3503 for f in v.slice(1, 3).iter() {
3509 for f in v.mut_iter() {
3515 for f in v.move_iter() {
3519 assert_eq!(cnt, 11);
3521 let xs = vec![Foo, Foo, Foo];
3522 assert_eq!(format!("{:?}", xs.slice(0, 2).to_owned()),
3523 "~[slice::tests::Foo, slice::tests::Foo]".to_owned());
3525 let xs: [Foo, ..3] = [Foo, Foo, Foo];
3526 assert_eq!(format!("{:?}", xs.slice(0, 2).to_owned()),
3527 "~[slice::tests::Foo, slice::tests::Foo]".to_owned());
3529 for f in xs.iter() {
3537 fn test_shrink_to_fit() {
3538 let mut xs = vec![0, 1, 2, 3];
3539 for i in range(4, 100) {
3542 assert_eq!(xs.capacity(), 128);
3544 assert_eq!(xs.capacity(), 100);
3545 assert_eq!(xs, range(0, 100).collect::<Vec<_>>());
3549 fn test_starts_with() {
3550 assert!(bytes!("foobar").starts_with(bytes!("foo")));
3551 assert!(!bytes!("foobar").starts_with(bytes!("oob")));
3552 assert!(!bytes!("foobar").starts_with(bytes!("bar")));
3553 assert!(!bytes!("foo").starts_with(bytes!("foobar")));
3554 assert!(!bytes!("bar").starts_with(bytes!("foobar")));
3555 assert!(bytes!("foobar").starts_with(bytes!("foobar")));
3556 let empty: &[u8] = [];
3557 assert!(empty.starts_with(empty));
3558 assert!(!empty.starts_with(bytes!("foo")));
3559 assert!(bytes!("foobar").starts_with(empty));
3563 fn test_ends_with() {
3564 assert!(bytes!("foobar").ends_with(bytes!("bar")));
3565 assert!(!bytes!("foobar").ends_with(bytes!("oba")));
3566 assert!(!bytes!("foobar").ends_with(bytes!("foo")));
3567 assert!(!bytes!("foo").ends_with(bytes!("foobar")));
3568 assert!(!bytes!("bar").ends_with(bytes!("foobar")));
3569 assert!(bytes!("foobar").ends_with(bytes!("foobar")));
3570 let empty: &[u8] = [];
3571 assert!(empty.ends_with(empty));
3572 assert!(!empty.ends_with(bytes!("foo")));
3573 assert!(bytes!("foobar").ends_with(empty));
3577 fn test_shift_ref() {
3578 let mut x: &[int] = [1, 2, 3, 4, 5];
3579 let h = x.shift_ref();
3580 assert_eq!(*h.unwrap(), 1);
3581 assert_eq!(x.len(), 4);
3582 assert_eq!(x[0], 2);
3583 assert_eq!(x[3], 5);
3585 let mut y: &[int] = [];
3586 assert_eq!(y.shift_ref(), None);
3591 let mut x: &[int] = [1, 2, 3, 4, 5];
3592 let h = x.pop_ref();
3593 assert_eq!(*h.unwrap(), 5);
3594 assert_eq!(x.len(), 4);
3595 assert_eq!(x[0], 1);
3596 assert_eq!(x[3], 4);
3598 let mut y: &[int] = [];
3599 assert!(y.pop_ref().is_none());
3603 fn test_mut_splitator() {
3604 let mut xs = [0,1,0,2,3,0,0,4,5,0];
3605 assert_eq!(xs.mut_split(|x| *x == 0).len(), 6);
3606 for slice in xs.mut_split(|x| *x == 0) {
3609 assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
3611 let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
3612 for slice in xs.mut_split(|x| *x == 0).take(5) {
3615 assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
3619 fn test_mut_splitator_rev() {
3620 let mut xs = [1,2,0,3,4,0,0,5,6,0];
3621 for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
3624 assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
3628 fn test_mut_chunks() {
3629 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
3630 for (i, chunk) in v.mut_chunks(3).enumerate() {
3631 for x in chunk.mut_iter() {
3635 let result = [0u8, 0, 0, 1, 1, 1, 2];
3636 assert!(v == result);
3640 fn test_mut_chunks_rev() {
3641 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
3642 for (i, chunk) in v.mut_chunks(3).rev().enumerate() {
3643 for x in chunk.mut_iter() {
3647 let result = [2u8, 2, 2, 1, 1, 1, 0];
3648 assert!(v == result);
3653 fn test_mut_chunks_0() {
3654 let mut v = [1, 2, 3, 4];
3655 let _it = v.mut_chunks(0);
3659 fn test_mut_shift_ref() {
3660 let mut x: &mut [int] = [1, 2, 3, 4, 5];
3661 let h = x.mut_shift_ref();
3662 assert_eq!(*h.unwrap(), 1);
3663 assert_eq!(x.len(), 4);
3664 assert_eq!(x[0], 2);
3665 assert_eq!(x[3], 5);
3667 let mut y: &mut [int] = [];
3668 assert!(y.mut_shift_ref().is_none());
3672 fn test_mut_pop_ref() {
3673 let mut x: &mut [int] = [1, 2, 3, 4, 5];
3674 let h = x.mut_pop_ref();
3675 assert_eq!(*h.unwrap(), 5);
3676 assert_eq!(x.len(), 4);
3677 assert_eq!(x[0], 1);
3678 assert_eq!(x[3], 4);
3680 let mut y: &mut [int] = [];
3681 assert!(y.mut_pop_ref().is_none());
3685 fn test_mut_last() {
3686 let mut x = [1, 2, 3, 4, 5];
3687 let h = x.mut_last();
3688 assert_eq!(*h.unwrap(), 5);
3690 let y: &mut [int] = [];
3691 assert!(y.mut_last().is_none());
3698 use self::test::Bencher;
3702 use rand::{weak_rng, Rng};
3705 fn iterator(b: &mut Bencher) {
3706 // peculiar numbers to stop LLVM from optimising the summation
3708 let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
3715 // sum == 11806, to stop dead code elimination.
3716 if sum == 0 {fail!()}
3721 fn mut_iterator(b: &mut Bencher) {
3722 let mut v = Vec::from_elem(100, 0);
3726 for x in v.mut_iter() {
3734 fn add(b: &mut Bencher) {
3735 let xs: &[int] = [5, ..10];
3736 let ys: &[int] = [5, ..10];
3743 fn concat(b: &mut Bencher) {
3744 let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
3746 xss.as_slice().concat_vec()
3751 fn connect(b: &mut Bencher) {
3752 let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
3754 xss.as_slice().connect_vec(&0)
3759 fn push(b: &mut Bencher) {
3760 let mut vec: Vec<uint> = vec![];
3768 fn starts_with_same_vector(b: &mut Bencher) {
3769 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
3771 vec.as_slice().starts_with(vec.as_slice())
3776 fn starts_with_single_element(b: &mut Bencher) {
3777 let vec: Vec<uint> = vec![0];
3779 vec.as_slice().starts_with(vec.as_slice())
3784 fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
3785 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
3786 let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
3789 vec.as_slice().starts_with(match_vec.as_slice())
3794 fn ends_with_same_vector(b: &mut Bencher) {
3795 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
3797 vec.as_slice().ends_with(vec.as_slice())
3802 fn ends_with_single_element(b: &mut Bencher) {
3803 let vec: Vec<uint> = vec![0];
3805 vec.as_slice().ends_with(vec.as_slice())
3810 fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
3811 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
3812 let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
3813 match_vec.as_mut_slice()[0] = 200;
3815 vec.as_slice().starts_with(match_vec.as_slice())
3820 fn contains_last_element(b: &mut Bencher) {
3821 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
3828 fn zero_1kb_from_elem(b: &mut Bencher) {
3830 Vec::from_elem(1024, 0u8)
3835 fn zero_1kb_set_memory(b: &mut Bencher) {
3837 let mut v: Vec<uint> = Vec::with_capacity(1024);
3839 let vp = v.as_mut_ptr();
3840 ptr::set_memory(vp, 0, 1024);
3848 fn zero_1kb_fixed_repeat(b: &mut Bencher) {
3855 fn zero_1kb_loop_set(b: &mut Bencher) {
3857 let mut v: Vec<uint> = Vec::with_capacity(1024);
3861 for i in range(0u, 1024) {
3868 fn zero_1kb_mut_iter(b: &mut Bencher) {
3870 let mut v = Vec::with_capacity(1024);
3874 for x in v.mut_iter() {
3882 fn random_inserts(b: &mut Bencher) {
3883 let mut rng = weak_rng();
3885 let mut v = Vec::from_elem(30, (0u, 0u));
3886 for _ in range(0, 100) {
3888 v.insert(rng.gen::<uint>() % (l + 1),
3894 fn random_removes(b: &mut Bencher) {
3895 let mut rng = weak_rng();
3897 let mut v = Vec::from_elem(130, (0u, 0u));
3898 for _ in range(0, 100) {
3900 v.remove(rng.gen::<uint>() % l);
3906 fn sort_random_small(b: &mut Bencher) {
3907 let mut rng = weak_rng();
3909 let mut v = rng.gen_vec::<u64>(5);
3910 v.as_mut_slice().sort();
3912 b.bytes = 5 * mem::size_of::<u64>() as u64;
3916 fn sort_random_medium(b: &mut Bencher) {
3917 let mut rng = weak_rng();
3919 let mut v = rng.gen_vec::<u64>(100);
3920 v.as_mut_slice().sort();
3922 b.bytes = 100 * mem::size_of::<u64>() as u64;
3926 fn sort_random_large(b: &mut Bencher) {
3927 let mut rng = weak_rng();
3929 let mut v = rng.gen_vec::<u64>(10000);
3930 v.as_mut_slice().sort();
3932 b.bytes = 10000 * mem::size_of::<u64>() as u64;
3936 fn sort_sorted(b: &mut Bencher) {
3937 let mut v = Vec::from_fn(10000, |i| i);
3941 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;
3944 type BigSortable = (u64,u64,u64,u64);
3947 fn sort_big_random_small(b: &mut Bencher) {
3948 let mut rng = weak_rng();
3950 let mut v = rng.gen_vec::<BigSortable>(5);
3953 b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
3957 fn sort_big_random_medium(b: &mut Bencher) {
3958 let mut rng = weak_rng();
3960 let mut v = rng.gen_vec::<BigSortable>(100);
3963 b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
3967 fn sort_big_random_large(b: &mut Bencher) {
3968 let mut rng = weak_rng();
3970 let mut v = rng.gen_vec::<BigSortable>(10000);
3973 b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
3977 fn sort_big_sorted(b: &mut Bencher) {
3978 let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
3982 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;