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 * `.mut_iter()` returns an iterator that allows modifying each value.
85 * `.move_iter()` converts an owned vector into an iterator that
86 moves out a value from the vector each iteration.
87 * Further iterators exist that split, chunk or permute the vector.
89 ## Function definitions
91 There are a number of free functions that create or take vectors, for example:
93 * Creating a vector, like `from_elem` and `from_fn`
94 * Creating a vector with a given size: `with_capacity`
95 * Modifying a vector and returning it, like `append`
96 * Operations on paired elements, like `unzip`.
103 use cmp::{TotalOrd, Ordering, Less, Greater};
105 use container::Container;
110 use option::{None, Option, Some};
113 use rt::global_heap::{exchange_free};
114 use unstable::finally::try_finally;
117 pub use core::slice::{ref_slice, mut_ref_slice, Splits, Windows};
118 pub use core::slice::{Chunks, Vector, ImmutableVector, ImmutableEqVector};
119 pub use core::slice::{ImmutableTotalOrdVector, MutableVector, Items, MutItems};
120 pub use core::slice::{RevItems, RevMutItems, MutSplits, MutChunks};
121 pub use core::slice::{bytes, MutableCloneableVector};
123 // Functional utilities
125 #[allow(missing_doc)]
126 pub trait VectorVector<T> {
127 // FIXME #5898: calling these .concat and .connect conflicts with
128 // StrVector::con{cat,nect}, since they have generic contents.
129 /// Flattens a vector of vectors of T into a single vector of T.
130 fn concat_vec(&self) -> ~[T];
132 /// Concatenate a vector of vectors, placing a given separator between each.
133 fn connect_vec(&self, sep: &T) -> ~[T];
136 impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
137 fn concat_vec(&self) -> ~[T] {
138 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
139 let mut result = Vec::with_capacity(size);
140 for v in self.iter() {
141 result.push_all(v.as_slice())
143 result.move_iter().collect()
146 fn connect_vec(&self, sep: &T) -> ~[T] {
147 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
148 let mut result = Vec::with_capacity(size + self.len());
149 let mut first = true;
150 for v in self.iter() {
151 if first { first = false } else { result.push(sep.clone()) }
152 result.push_all(v.as_slice())
154 result.move_iter().collect()
159 * Convert an iterator of pairs into a pair of vectors.
161 * Returns a tuple containing two vectors where the i-th element of the first
162 * vector contains the first element of the i-th tuple of the input iterator,
163 * and the i-th element of the second vector contains the second element
164 * of the i-th tuple of the input iterator.
166 pub fn unzip<T, U, V: Iterator<(T, U)>>(mut iter: V) -> (~[T], ~[U]) {
167 let (lo, _) = iter.size_hint();
168 let mut ts = Vec::with_capacity(lo);
169 let mut us = Vec::with_capacity(lo);
174 (ts.move_iter().collect(), us.move_iter().collect())
177 /// An Iterator that yields the element swaps needed to produce
178 /// a sequence of all possible permutations for an indexed sequence of
179 /// elements. Each permutation is only a single swap apart.
181 /// The Steinhaus–Johnson–Trotter algorithm is used.
183 /// Generates even and odd permutations alternately.
185 /// The last generated swap is always (0, 1), and it returns the
186 /// sequence to its initial order.
187 pub struct ElementSwaps {
188 sdir: ~[SizeDirection],
189 /// If true, emit the last swap that returns the sequence to initial state
195 /// Create an `ElementSwaps` iterator for a sequence of `length` elements
196 pub fn new(length: uint) -> ElementSwaps {
197 // Initialize `sdir` with a direction that position should move in
198 // (all negative at the beginning) and the `size` of the
199 // element (equal to the original index).
202 sdir: range(0, length)
203 .map(|i| SizeDirection{ size: i, dir: Neg })
210 enum Direction { Pos, Neg }
212 /// An Index and Direction together
213 struct SizeDirection {
218 impl Iterator<(uint, uint)> for ElementSwaps {
220 fn next(&mut self) -> Option<(uint, uint)> {
221 fn new_pos(i: uint, s: Direction) -> uint {
222 i + match s { Pos => 1, Neg => -1 }
225 // Find the index of the largest mobile element:
226 // The direction should point into the vector, and the
227 // swap should be with a smaller `size` element.
228 let max = self.sdir.iter().map(|&x| x).enumerate()
230 new_pos(i, sd.dir) < self.sdir.len() &&
231 self.sdir[new_pos(i, sd.dir)].size < sd.size)
232 .max_by(|&(_, sd)| sd.size);
235 let j = new_pos(i, sd.dir);
236 self.sdir.swap(i, j);
238 // Swap the direction of each larger SizeDirection
239 for x in self.sdir.mut_iter() {
240 if x.size > sd.size {
241 x.dir = match x.dir { Pos => Neg, Neg => Pos };
244 self.swaps_made += 1;
247 None => if self.emit_reset {
248 self.emit_reset = false;
249 if self.sdir.len() > 1 {
251 self.swaps_made += 1;
254 // Vector is of the form [] or [x], and the only permutation is itself
255 self.swaps_made += 1;
263 fn size_hint(&self) -> (uint, Option<uint>) {
264 // For a vector of size n, there are exactly n! permutations.
265 let n = range(2, self.sdir.len() + 1).product();
266 (n - self.swaps_made, Some(n - self.swaps_made))
270 /// An Iterator that uses `ElementSwaps` to iterate through
271 /// all possible permutations of a vector.
273 /// The first iteration yields a clone of the vector as it is,
274 /// then each successive element is the vector with one
277 /// Generates even and odd permutations alternately.
278 pub struct Permutations<T> {
283 impl<T: Clone> Iterator<~[T]> for Permutations<T> {
285 fn next(&mut self) -> Option<~[T]> {
286 match self.swaps.next() {
288 Some((0,0)) => Some(self.v.clone()),
290 let elt = self.v.clone();
298 fn size_hint(&self) -> (uint, Option<uint>) {
299 self.swaps.size_hint()
303 /// Extension methods for vector slices with cloneable elements
304 pub trait CloneableVector<T> {
305 /// Copy `self` into a new owned vector
306 fn to_owned(&self) -> ~[T];
308 /// Convert `self` into an owned vector, not making a copy if possible.
309 fn into_owned(self) -> ~[T];
312 /// Extension methods for vector slices
313 impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
314 /// Returns a copy of `v`.
316 fn to_owned(&self) -> ~[T] {
317 let len = self.len();
318 let mut result = Vec::with_capacity(len);
319 // Unsafe code so this can be optimised to a memcpy (or something
320 // similarly fast) when T is Copy. LLVM is easily confused, so any
321 // extra operations during the loop can prevent this optimisation
324 let p = result.as_mut_ptr();
325 // Use try_finally here otherwise the write to length
326 // inside the loop stops LLVM from optimising this.
329 |i, ()| while *i < len {
331 &mut(*p.offset(*i as int)),
332 self.unsafe_ref(*i).clone());
335 |i| result.set_len(*i));
337 result.move_iter().collect()
341 fn into_owned(self) -> ~[T] { self.to_owned() }
344 /// Extension methods for owned vectors
345 impl<T: Clone> CloneableVector<T> for ~[T] {
347 fn to_owned(&self) -> ~[T] { self.clone() }
350 fn into_owned(self) -> ~[T] { self }
353 /// Extension methods for vectors containing `Clone` elements.
354 pub trait ImmutableCloneableVector<T> {
355 /// Partitions the vector into two vectors `(A,B)`, where all
356 /// elements of `A` satisfy `f` and all elements of `B` do not.
357 fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]);
359 /// Create an iterator that yields every possible permutation of the
360 /// vector in succession.
361 fn permutations(self) -> Permutations<T>;
364 impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
366 fn partitioned(&self, f: |&T| -> bool) -> (~[T], ~[T]) {
367 let mut lefts = Vec::new();
368 let mut rights = Vec::new();
370 for elt in self.iter() {
372 lefts.push((*elt).clone());
374 rights.push((*elt).clone());
378 (lefts.move_iter().collect(), rights.move_iter().collect())
381 fn permutations(self) -> Permutations<T> {
383 swaps: ElementSwaps::new(self.len()),
390 /// Extension methods for owned vectors.
391 pub trait OwnedVector<T> {
392 /// Creates a consuming iterator, that is, one that moves each
393 /// value out of the vector (from start to end). The vector cannot
394 /// be used after calling this.
399 /// let v = ~["a".to_owned(), "b".to_owned()];
400 /// for s in v.move_iter() {
401 /// // s has type ~str, not &~str
402 /// println!("{}", s);
405 fn move_iter(self) -> MoveItems<T>;
406 /// Creates a consuming iterator that moves out of the vector in
408 #[deprecated = "replaced by .move_iter().rev()"]
409 fn move_rev_iter(self) -> Rev<MoveItems<T>>;
412 * Partitions the vector into two vectors `(A,B)`, where all
413 * elements of `A` satisfy `f` and all elements of `B` do not.
415 fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]);
418 impl<T> OwnedVector<T> for ~[T] {
420 fn move_iter(self) -> MoveItems<T> {
422 let iter = transmute(self.iter());
423 let ptr = transmute(self);
424 MoveItems { allocation: ptr, iter: iter }
429 #[deprecated = "replaced by .move_iter().rev()"]
430 fn move_rev_iter(self) -> Rev<MoveItems<T>> {
431 self.move_iter().rev()
435 fn partition(self, f: |&T| -> bool) -> (~[T], ~[T]) {
436 let mut lefts = Vec::new();
437 let mut rights = Vec::new();
439 for elt in self.move_iter() {
447 (lefts.move_iter().collect(), rights.move_iter().collect())
451 fn insertion_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
452 let len = v.len() as int;
453 let buf_v = v.as_mut_ptr();
456 for i in range(1, len) {
457 // j satisfies: 0 <= j <= i;
461 let read_ptr = buf_v.offset(i) as *T;
463 // find where to insert, we need to do strict <,
464 // rather than <=, to maintain stability.
466 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
468 compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
472 // shift everything to the right, to make space to
473 // insert this value.
475 // j + 1 could be `len` (for the last `i`), but in
476 // that case, `i == j` so we don't copy. The
477 // `.offset(j)` is always in bounds.
480 let tmp = ptr::read(read_ptr);
481 ptr::copy_memory(buf_v.offset(j + 1),
484 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
493 fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
494 // warning: this wildly uses unsafe.
495 static BASE_INSERTION: uint = 32;
496 static LARGE_INSERTION: uint = 16;
498 // FIXME #12092: smaller insertion runs seems to make sorting
499 // vectors of large elements a little faster on some platforms,
500 // but hasn't been tested/tuned extensively
501 let insertion = if size_of::<T>() <= 16 {
509 // short vectors get sorted in-place via insertion sort to avoid allocations
510 if len <= insertion {
511 insertion_sort(v, compare);
515 // allocate some memory to use as scratch memory, we keep the
516 // length 0 so we can keep shallow copies of the contents of `v`
517 // without risking the dtors running on an object twice if
519 let mut working_space = Vec::with_capacity(2 * len);
520 // these both are buffers of length `len`.
521 let mut buf_dat = working_space.as_mut_ptr();
522 let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
525 let buf_v = v.as_ptr();
527 // step 1. sort short runs with insertion sort. This takes the
528 // values from `v` and sorts them into `buf_dat`, leaving that
529 // with sorted runs of length INSERTION.
531 // We could hardcode the sorting comparisons here, and we could
532 // manipulate/step the pointers themselves, rather than repeatedly
534 for start in range_step(0, len, insertion) {
536 for i in range(start, cmp::min(start + insertion, len)) {
537 // j satisfies: start <= j <= i;
538 let mut j = i as int;
541 let read_ptr = buf_v.offset(i as int);
543 // find where to insert, we need to do strict <,
544 // rather than <=, to maintain stability.
546 // start <= j - 1 < len, so .offset(j - 1) is in
548 while j > start as int &&
549 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
553 // shift everything to the right, to make space to
554 // insert this value.
556 // j + 1 could be `len` (for the last `i`), but in
557 // that case, `i == j` so we don't copy. The
558 // `.offset(j)` is always in bounds.
559 ptr::copy_memory(buf_dat.offset(j + 1),
562 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
567 // step 2. merge the sorted runs.
568 let mut width = insertion;
570 // merge the sorted runs of length `width` in `buf_dat` two at
571 // a time, placing the result in `buf_tmp`.
573 // 0 <= start <= len.
574 for start in range_step(0, len, 2 * width) {
575 // manipulate pointers directly for speed (rather than
576 // using a `for` loop with `range` and `.offset` inside
579 // the end of the first run & start of the
580 // second. Offset of `len` is defined, since this is
581 // precisely one byte past the end of the object.
582 let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
583 // end of the second. Similar reasoning to the above re safety.
584 let right_end_idx = cmp::min(start + 2 * width, len);
585 let right_end = buf_dat.offset(right_end_idx as int);
587 // the pointers to the elements under consideration
588 // from the two runs.
590 // both of these are in bounds.
591 let mut left = buf_dat.offset(start as int);
592 let mut right = right_start;
594 // where we're putting the results, it is a run of
595 // length `2*width`, so we step it once for each step
596 // of either `left` or `right`. `buf_tmp` has length
597 // `len`, so these are in bounds.
598 let mut out = buf_tmp.offset(start as int);
599 let out_end = buf_tmp.offset(right_end_idx as int);
601 while out < out_end {
602 // Either the left or the right run are exhausted,
603 // so just copy the remainder from the other run
604 // and move on; this gives a huge speed-up (order
605 // of 25%) for mostly sorted vectors (the best
607 if left == right_start {
608 // the number remaining in this run.
609 let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
610 ptr::copy_nonoverlapping_memory(out, &*right, elems);
612 } else if right == right_end {
613 let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
614 ptr::copy_nonoverlapping_memory(out, &*left, elems);
618 // check which side is smaller, and that's the
619 // next element for the new run.
621 // `left < right_start` and `right < right_end`,
622 // so these are valid.
623 let to_copy = if compare(&*left, &*right) == Greater {
628 ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
634 mem::swap(&mut buf_dat, &mut buf_tmp);
639 // write the result to `v` in one go, so that there are never two copies
640 // of the same object in `v`.
642 ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
645 // increment the pointer, returning the old pointer.
647 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
649 *ptr = ptr.offset(1);
654 /// Extension methods for vectors such that their elements are
656 pub trait MutableVectorAllocating<'a, T> {
657 /// Sort the vector, in place, using `compare` to compare
660 /// This sort is `O(n log n)` worst-case and stable, but allocates
661 /// approximately `2 * n`, where `n` is the length of `self`.
666 /// let mut v = [5i, 4, 1, 3, 2];
667 /// v.sort_by(|a, b| a.cmp(b));
668 /// assert!(v == [1, 2, 3, 4, 5]);
670 /// // reverse sorting
671 /// v.sort_by(|a, b| b.cmp(a));
672 /// assert!(v == [5, 4, 3, 2, 1]);
674 fn sort_by(self, compare: |&T, &T| -> Ordering);
677 * Consumes `src` and moves as many elements as it can into `self`
678 * from the range [start,end).
680 * Returns the number of elements copied (the shorter of self.len()
685 * * src - A mutable vector of `T`
686 * * start - The index into `src` to start copying from
687 * * end - The index into `str` to stop copying from
689 fn move_from(self, src: ~[T], start: uint, end: uint) -> uint;
692 impl<'a,T> MutableVectorAllocating<'a, T> for &'a mut [T] {
694 fn sort_by(self, compare: |&T, &T| -> Ordering) {
695 merge_sort(self, compare)
699 fn move_from(self, mut src: ~[T], start: uint, end: uint) -> uint {
700 for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
703 cmp::min(self.len(), end-start)
707 /// Methods for mutable vectors with orderable elements, such as
708 /// in-place sorting.
709 pub trait MutableTotalOrdVector<T> {
710 /// Sort the vector, in place.
712 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
717 /// let mut v = [-5, 4, 1, -3, 2];
720 /// assert!(v == [-5, -3, 1, 2, 4]);
725 impl<'a, T: TotalOrd> MutableTotalOrdVector<T> for &'a mut [T] {
728 self.sort_by(|a,b| a.cmp(b))
733 * Constructs a vector from an unsafe pointer to a buffer
737 * * ptr - An unsafe pointer to a buffer of `T`
738 * * elts - The number of elements in the buffer
740 // Wrapper for fn in raw: needs to be called by net_tcp::on_tcp_read_cb
741 pub unsafe fn from_buf<T>(ptr: *T, elts: uint) -> ~[T] {
742 raw::from_buf_raw(ptr, elts)
745 /// Unsafe operations
749 use slice::{MutableVector, OwnedVector};
752 pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
753 pub use core::slice::raw::{shift_ptr, pop_ptr};
756 * Constructs a vector from an unsafe pointer to a buffer
760 * * ptr - An unsafe pointer to a buffer of `T`
761 * * elts - The number of elements in the buffer
763 // Was in raw, but needs to be called by net_tcp::on_tcp_read_cb
765 pub unsafe fn from_buf_raw<T>(ptr: *T, elts: uint) -> ~[T] {
766 let mut dst = Vec::with_capacity(elts);
768 ptr::copy_memory(dst.as_mut_ptr(), ptr, elts);
769 dst.move_iter().collect()
773 /// An iterator that moves out of a vector.
774 pub struct MoveItems<T> {
775 allocation: *mut u8, // the block of memory allocated for the vector
776 iter: Items<'static, T>
779 impl<T> Iterator<T> for MoveItems<T> {
781 fn next(&mut self) -> Option<T> {
783 self.iter.next().map(|x| ptr::read(x))
788 fn size_hint(&self) -> (uint, Option<uint>) {
789 self.iter.size_hint()
793 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
795 fn next_back(&mut self) -> Option<T> {
797 self.iter.next_back().map(|x| ptr::read(x))
803 impl<T> Drop for MoveItems<T> {
805 // destroy the remaining elements
808 exchange_free(self.allocation as *u8)
813 /// An iterator that moves out of a vector in reverse order.
814 #[deprecated = "replaced by Rev<MoveItems<'a, T>>"]
815 pub type RevMoveItems<T> = Rev<MoveItems<T>>;
823 use rand::{Rng, task_rng};
826 fn square(n: uint) -> uint { n * n }
828 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
831 fn test_unsafe_ptrs() {
833 // Test on-stack copy-from-buf.
834 let a = box [1, 2, 3];
835 let mut ptr = a.as_ptr();
836 let b = from_buf(ptr, 3u);
837 assert_eq!(b.len(), 3u);
842 // Test on-heap copy-from-buf.
843 let c = box [1, 2, 3, 4, 5];
845 let d = from_buf(ptr, 5u);
846 assert_eq!(d.len(), 5u);
857 // Test on-stack from_fn.
858 let mut v = Vec::from_fn(3u, square);
860 let v = v.as_slice();
861 assert_eq!(v.len(), 3u);
862 assert_eq!(v[0], 0u);
863 assert_eq!(v[1], 1u);
864 assert_eq!(v[2], 4u);
867 // Test on-heap from_fn.
868 v = Vec::from_fn(5u, square);
870 let v = v.as_slice();
871 assert_eq!(v.len(), 5u);
872 assert_eq!(v[0], 0u);
873 assert_eq!(v[1], 1u);
874 assert_eq!(v[2], 4u);
875 assert_eq!(v[3], 9u);
876 assert_eq!(v[4], 16u);
881 fn test_from_elem() {
882 // Test on-stack from_elem.
883 let mut v = Vec::from_elem(2u, 10u);
885 let v = v.as_slice();
886 assert_eq!(v.len(), 2u);
887 assert_eq!(v[0], 10u);
888 assert_eq!(v[1], 10u);
891 // Test on-heap from_elem.
892 v = Vec::from_elem(6u, 20u);
894 let v = v.as_slice();
895 assert_eq!(v[0], 20u);
896 assert_eq!(v[1], 20u);
897 assert_eq!(v[2], 20u);
898 assert_eq!(v[3], 20u);
899 assert_eq!(v[4], 20u);
900 assert_eq!(v[5], 20u);
906 let xs: [int, ..0] = [];
907 assert!(xs.is_empty());
908 assert!(![0].is_empty());
912 fn test_len_divzero() {
915 let v1 : &[Z] = &[[]];
916 let v2 : &[Z] = &[[], []];
917 assert_eq!(mem::size_of::<Z>(), 0);
918 assert_eq!(v0.len(), 0);
919 assert_eq!(v1.len(), 1);
920 assert_eq!(v2.len(), 2);
925 let mut a = box [11];
926 assert_eq!(a.get(1), None);
928 assert_eq!(a.get(1).unwrap(), &12);
929 a = box [11, 12, 13];
930 assert_eq!(a.get(1).unwrap(), &12);
936 assert_eq!(a.head(), None);
938 assert_eq!(a.head().unwrap(), &11);
940 assert_eq!(a.head().unwrap(), &11);
945 let mut a = box [11];
946 assert_eq!(a.tail(), &[]);
948 assert_eq!(a.tail(), &[12]);
953 fn test_tail_empty() {
954 let a: ~[int] = box [];
960 let mut a = box [11, 12, 13];
961 assert_eq!(a.tailn(0), &[11, 12, 13]);
962 a = box [11, 12, 13];
963 assert_eq!(a.tailn(2), &[13]);
968 fn test_tailn_empty() {
969 let a: ~[int] = box [];
975 let mut a = box [11];
976 assert_eq!(a.init(), &[]);
978 assert_eq!(a.init(), &[11]);
983 fn test_init_empty() {
984 let a: ~[int] = box [];
990 let mut a = box [11, 12, 13];
991 assert_eq!(a.initn(0), &[11, 12, 13]);
992 a = box [11, 12, 13];
993 assert_eq!(a.initn(2), &[11]);
998 fn test_initn_empty() {
999 let a: ~[int] = box [];
1006 assert_eq!(a.last(), None);
1008 assert_eq!(a.last().unwrap(), &11);
1010 assert_eq!(a.last().unwrap(), &12);
1015 // Test fixed length vector.
1016 let vec_fixed = [1, 2, 3, 4];
1017 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
1018 assert_eq!(v_a.len(), 3u);
1019 assert_eq!(v_a[0], 2);
1020 assert_eq!(v_a[1], 3);
1021 assert_eq!(v_a[2], 4);
1024 let vec_stack = &[1, 2, 3];
1025 let v_b = vec_stack.slice(1u, 3u).to_owned();
1026 assert_eq!(v_b.len(), 2u);
1027 assert_eq!(v_b[0], 2);
1028 assert_eq!(v_b[1], 3);
1030 // Test on exchange heap.
1031 let vec_unique = box [1, 2, 3, 4, 5, 6];
1032 let v_d = vec_unique.slice(1u, 6u).to_owned();
1033 assert_eq!(v_d.len(), 5u);
1034 assert_eq!(v_d[0], 2);
1035 assert_eq!(v_d[1], 3);
1036 assert_eq!(v_d[2], 4);
1037 assert_eq!(v_d[3], 5);
1038 assert_eq!(v_d[4], 6);
1042 fn test_slice_from() {
1043 let vec = &[1, 2, 3, 4];
1044 assert_eq!(vec.slice_from(0), vec);
1045 assert_eq!(vec.slice_from(2), &[3, 4]);
1046 assert_eq!(vec.slice_from(4), &[]);
1050 fn test_slice_to() {
1051 let vec = &[1, 2, 3, 4];
1052 assert_eq!(vec.slice_to(4), vec);
1053 assert_eq!(vec.slice_to(2), &[1, 2]);
1054 assert_eq!(vec.slice_to(0), &[]);
1060 let mut v = vec![5];
1062 assert_eq!(v.len(), 0);
1063 assert_eq!(e, Some(5));
1065 assert_eq!(f, None);
1067 assert_eq!(g, None);
1071 fn test_swap_remove() {
1072 let mut v = vec![1, 2, 3, 4, 5];
1073 let mut e = v.swap_remove(0);
1074 assert_eq!(e, Some(1));
1075 assert_eq!(v, vec![5, 2, 3, 4]);
1076 e = v.swap_remove(3);
1077 assert_eq!(e, Some(4));
1078 assert_eq!(v, vec![5, 2, 3]);
1080 e = v.swap_remove(3);
1081 assert_eq!(e, None);
1082 assert_eq!(v, vec![5, 2, 3]);
1086 fn test_swap_remove_noncopyable() {
1087 // Tests that we don't accidentally run destructors twice.
1088 let mut v = vec![::unstable::sync::Exclusive::new(()),
1089 ::unstable::sync::Exclusive::new(()),
1090 ::unstable::sync::Exclusive::new(())];
1091 let mut _e = v.swap_remove(0);
1092 assert_eq!(v.len(), 2);
1093 _e = v.swap_remove(1);
1094 assert_eq!(v.len(), 1);
1095 _e = v.swap_remove(0);
1096 assert_eq!(v.len(), 0);
1101 // Test on-stack push().
1104 assert_eq!(v.len(), 1u);
1105 assert_eq!(v.as_slice()[0], 1);
1107 // Test on-heap push().
1109 assert_eq!(v.len(), 2u);
1110 assert_eq!(v.as_slice()[0], 1);
1111 assert_eq!(v.as_slice()[1], 2);
1116 // Test on-stack grow().
1120 let v = v.as_slice();
1121 assert_eq!(v.len(), 2u);
1122 assert_eq!(v[0], 1);
1123 assert_eq!(v[1], 1);
1126 // Test on-heap grow().
1129 let v = v.as_slice();
1130 assert_eq!(v.len(), 5u);
1131 assert_eq!(v[0], 1);
1132 assert_eq!(v[1], 1);
1133 assert_eq!(v[2], 2);
1134 assert_eq!(v[3], 2);
1135 assert_eq!(v[4], 2);
1142 v.grow_fn(3u, square);
1143 let v = v.as_slice();
1144 assert_eq!(v.len(), 3u);
1145 assert_eq!(v[0], 0u);
1146 assert_eq!(v[1], 1u);
1147 assert_eq!(v[2], 4u);
1151 fn test_grow_set() {
1152 let mut v = vec![1, 2, 3];
1153 v.grow_set(4u, &4, 5);
1154 let v = v.as_slice();
1155 assert_eq!(v.len(), 5u);
1156 assert_eq!(v[0], 1);
1157 assert_eq!(v[1], 2);
1158 assert_eq!(v[2], 3);
1159 assert_eq!(v[3], 4);
1160 assert_eq!(v[4], 5);
1164 fn test_truncate() {
1165 let mut v = vec![box 6,box 5,box 4];
1167 let v = v.as_slice();
1168 assert_eq!(v.len(), 1);
1169 assert_eq!(*(v[0]), 6);
1170 // If the unsafe block didn't drop things properly, we blow up here.
1175 let mut v = vec![box 6,box 5,box 4];
1177 assert_eq!(v.len(), 0);
1178 // If the unsafe block didn't drop things properly, we blow up here.
1183 fn case(a: Vec<uint>, b: Vec<uint>) {
1188 case(vec![], vec![]);
1189 case(vec![1], vec![1]);
1190 case(vec![1,1], vec![1]);
1191 case(vec![1,2,3], vec![1,2,3]);
1192 case(vec![1,1,2,3], vec![1,2,3]);
1193 case(vec![1,2,2,3], vec![1,2,3]);
1194 case(vec![1,2,3,3], vec![1,2,3]);
1195 case(vec![1,1,2,2,2,3,3], vec![1,2,3]);
1199 fn test_dedup_unique() {
1200 let mut v0 = vec![box 1, box 1, box 2, box 3];
1202 let mut v1 = vec![box 1, box 2, box 2, box 3];
1204 let mut v2 = vec![box 1, box 2, box 3, box 3];
1207 * If the boxed pointers were leaked or otherwise misused, valgrind
1208 * and/or rustrt should raise errors.
1213 fn test_dedup_shared() {
1214 let mut v0 = vec![box 1, box 1, box 2, box 3];
1216 let mut v1 = vec![box 1, box 2, box 2, box 3];
1218 let mut v2 = vec![box 1, box 2, box 3, box 3];
1221 * If the pointers were leaked or otherwise misused, valgrind and/or
1222 * rustrt should raise errors.
1228 let mut v = vec![1, 2, 3, 4, 5];
1230 assert_eq!(v, vec![1, 3, 5]);
1234 fn test_zip_unzip() {
1235 let z1 = vec![(1, 4), (2, 5), (3, 6)];
1237 let (left, right) = unzip(z1.iter().map(|&x| x));
1239 assert_eq!((1, 4), (left[0], right[0]));
1240 assert_eq!((2, 5), (left[1], right[1]));
1241 assert_eq!((3, 6), (left[2], right[2]));
1245 fn test_element_swaps() {
1246 let mut v = [1, 2, 3];
1247 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
1250 0 => assert!(v == [1, 3, 2]),
1251 1 => assert!(v == [3, 1, 2]),
1252 2 => assert!(v == [3, 2, 1]),
1253 3 => assert!(v == [2, 3, 1]),
1254 4 => assert!(v == [2, 1, 3]),
1255 5 => assert!(v == [1, 2, 3]),
1262 fn test_permutations() {
1264 let v: [int, ..0] = [];
1265 let mut it = v.permutations();
1266 let (min_size, max_opt) = it.size_hint();
1267 assert_eq!(min_size, 1);
1268 assert_eq!(max_opt.unwrap(), 1);
1269 assert_eq!(it.next(), Some(v.as_slice().to_owned()));
1270 assert_eq!(it.next(), None);
1273 let v = ["Hello".to_owned()];
1274 let mut it = v.permutations();
1275 let (min_size, max_opt) = it.size_hint();
1276 assert_eq!(min_size, 1);
1277 assert_eq!(max_opt.unwrap(), 1);
1278 assert_eq!(it.next(), Some(v.as_slice().to_owned()));
1279 assert_eq!(it.next(), None);
1283 let mut it = v.permutations();
1284 let (min_size, max_opt) = it.size_hint();
1285 assert_eq!(min_size, 3*2);
1286 assert_eq!(max_opt.unwrap(), 3*2);
1287 assert_eq!(it.next(), Some(box [1,2,3]));
1288 assert_eq!(it.next(), Some(box [1,3,2]));
1289 assert_eq!(it.next(), Some(box [3,1,2]));
1290 let (min_size, max_opt) = it.size_hint();
1291 assert_eq!(min_size, 3);
1292 assert_eq!(max_opt.unwrap(), 3);
1293 assert_eq!(it.next(), Some(box [3,2,1]));
1294 assert_eq!(it.next(), Some(box [2,3,1]));
1295 assert_eq!(it.next(), Some(box [2,1,3]));
1296 assert_eq!(it.next(), None);
1299 // check that we have N! permutations
1300 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
1302 let mut it = v.permutations();
1303 let (min_size, max_opt) = it.size_hint();
1307 assert_eq!(amt, it.swaps.swaps_made);
1308 assert_eq!(amt, min_size);
1309 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
1310 assert_eq!(amt, max_opt.unwrap());
1315 fn test_position_elem() {
1316 assert!([].position_elem(&1).is_none());
1318 let v1 = box [1, 2, 3, 3, 2, 5];
1319 assert_eq!(v1.position_elem(&1), Some(0u));
1320 assert_eq!(v1.position_elem(&2), Some(1u));
1321 assert_eq!(v1.position_elem(&5), Some(5u));
1322 assert!(v1.position_elem(&4).is_none());
1326 fn test_bsearch_elem() {
1327 assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
1328 assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
1329 assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
1330 assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
1331 assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
1333 assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
1334 assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
1335 assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
1336 assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
1338 assert_eq!([2,4,6,8].bsearch_elem(&1), None);
1339 assert_eq!([2,4,6,8].bsearch_elem(&5), None);
1340 assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
1341 assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
1343 assert_eq!([2,4,6].bsearch_elem(&1), None);
1344 assert_eq!([2,4,6].bsearch_elem(&5), None);
1345 assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
1346 assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
1348 assert_eq!([2,4].bsearch_elem(&1), None);
1349 assert_eq!([2,4].bsearch_elem(&5), None);
1350 assert_eq!([2,4].bsearch_elem(&2), Some(0));
1351 assert_eq!([2,4].bsearch_elem(&4), Some(1));
1353 assert_eq!([2].bsearch_elem(&1), None);
1354 assert_eq!([2].bsearch_elem(&5), None);
1355 assert_eq!([2].bsearch_elem(&2), Some(0));
1357 assert_eq!([].bsearch_elem(&1), None);
1358 assert_eq!([].bsearch_elem(&5), None);
1360 assert!([1,1,1,1,1].bsearch_elem(&1) != None);
1361 assert!([1,1,1,1,2].bsearch_elem(&1) != None);
1362 assert!([1,1,1,2,2].bsearch_elem(&1) != None);
1363 assert!([1,1,2,2,2].bsearch_elem(&1) != None);
1364 assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
1366 assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
1367 assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
1372 let mut v: ~[int] = box [10, 20];
1373 assert_eq!(v[0], 10);
1374 assert_eq!(v[1], 20);
1376 assert_eq!(v[0], 20);
1377 assert_eq!(v[1], 10);
1379 let mut v3: ~[int] = box [];
1381 assert!(v3.is_empty());
1386 use realstd::slice::Vector;
1387 use realstd::clone::Clone;
1388 for len in range(4u, 25) {
1389 for _ in range(0, 100) {
1390 let mut v = task_rng().gen_vec::<uint>(len);
1391 let mut v1 = v.clone();
1393 v.as_mut_slice().sort();
1394 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1396 v1.as_mut_slice().sort_by(|a, b| a.cmp(b));
1397 assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
1399 v1.as_mut_slice().sort_by(|a, b| b.cmp(a));
1400 assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
1404 // shouldn't fail/crash
1405 let mut v: [uint, .. 0] = [];
1408 let mut v = [0xDEADBEEFu];
1410 assert!(v == [0xDEADBEEF]);
1414 fn test_sort_stability() {
1415 for len in range(4, 25) {
1416 for _ in range(0 , 10) {
1417 let mut counts = [0, .. 10];
1419 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
1420 // where the first item of each tuple is random, but
1421 // the second item represents which occurrence of that
1422 // number this element is, i.e. the second elements
1423 // will occur in sorted order.
1424 let mut v = range(0, len).map(|_| {
1425 let n = task_rng().gen::<uint>() % 10;
1428 }).collect::<~[(uint, int)]>();
1430 // only sort on the first element, so an unstable sort
1431 // may mix up the counts.
1432 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
1434 // this comparison includes the count (the second item
1435 // of the tuple), so elements with equal first items
1436 // will need to be ordered with increasing
1437 // counts... i.e. exactly asserting that this sort is
1439 assert!(v.windows(2).all(|w| w[0] <= w[1]));
1445 fn test_partition() {
1446 assert_eq!((box []).partition(|x: &int| *x < 3), (box [], box []));
1447 assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 4), (box [1, 2, 3], box []));
1448 assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 2), (box [1], box [2, 3]));
1449 assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 0), (box [], box [1, 2, 3]));
1453 fn test_partitioned() {
1454 assert_eq!(([]).partitioned(|x: &int| *x < 3), (box [], box []))
1455 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (box [1, 2, 3], box []));
1456 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (box [1], box [2, 3]));
1457 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (box [], box [1, 2, 3]));
1462 let v: [~[int], ..0] = [];
1463 assert_eq!(v.concat_vec(), box []);
1464 assert_eq!([box [1], box [2,3]].concat_vec(), box [1, 2, 3]);
1466 assert_eq!([&[1], &[2,3]].concat_vec(), box [1, 2, 3]);
1471 let v: [~[int], ..0] = [];
1472 assert_eq!(v.connect_vec(&0), box []);
1473 assert_eq!([box [1], box [2, 3]].connect_vec(&0), box [1, 0, 2, 3]);
1474 assert_eq!([box [1], box [2], box [3]].connect_vec(&0), box [1, 0, 2, 0, 3]);
1476 assert_eq!(v.connect_vec(&0), box []);
1477 assert_eq!([&[1], &[2, 3]].connect_vec(&0), box [1, 0, 2, 3]);
1478 assert_eq!([&[1], &[2], &[3]].connect_vec(&0), box [1, 0, 2, 0, 3]);
1483 let mut x = vec![1, 2, 3];
1484 assert_eq!(x.shift(), Some(1));
1485 assert_eq!(&x, &vec![2, 3]);
1486 assert_eq!(x.shift(), Some(2));
1487 assert_eq!(x.shift(), Some(3));
1488 assert_eq!(x.shift(), None);
1489 assert_eq!(x.len(), 0);
1494 let mut x = vec![1, 2, 3];
1496 assert_eq!(x, vec![0, 1, 2, 3]);
1501 let mut a = vec![1, 2, 4];
1503 assert_eq!(a, vec![1, 2, 3, 4]);
1505 let mut a = vec![1, 2, 3];
1507 assert_eq!(a, vec![0, 1, 2, 3]);
1509 let mut a = vec![1, 2, 3];
1511 assert_eq!(a, vec![1, 2, 3, 4]);
1515 assert_eq!(a, vec![1]);
1520 fn test_insert_oob() {
1521 let mut a = vec![1, 2, 3];
1527 let mut a = vec![1,2,3,4];
1529 assert_eq!(a.remove(2), Some(3));
1530 assert_eq!(a, vec![1,2,4]);
1532 assert_eq!(a.remove(2), Some(4));
1533 assert_eq!(a, vec![1,2]);
1535 assert_eq!(a.remove(2), None);
1536 assert_eq!(a, vec![1,2]);
1538 assert_eq!(a.remove(0), Some(1));
1539 assert_eq!(a, vec![2]);
1541 assert_eq!(a.remove(0), Some(2));
1542 assert_eq!(a, vec![]);
1544 assert_eq!(a.remove(0), None);
1545 assert_eq!(a.remove(10), None);
1549 fn test_capacity() {
1550 let mut v = vec![0u64];
1551 v.reserve_exact(10u);
1552 assert_eq!(v.capacity(), 10u);
1553 let mut v = vec![0u32];
1554 v.reserve_exact(10u);
1555 assert_eq!(v.capacity(), 10u);
1560 let v = vec![1, 2, 3, 4, 5];
1561 let v = v.slice(1u, 3u);
1562 assert_eq!(v.len(), 2u);
1563 assert_eq!(v[0], 2);
1564 assert_eq!(v[1], 3);
1570 fn test_from_fn_fail() {
1571 Vec::from_fn(100, |v| {
1572 if v == 50 { fail!() }
1579 fn test_from_elem_fail() {
1586 boxes: (Box<int>, Rc<int>)
1590 fn clone(&self) -> S {
1591 self.f.set(self.f.get() + 1);
1592 if self.f.get() == 10 { fail!() }
1593 S { f: self.f, boxes: self.boxes.clone() }
1597 let s = S { f: Cell::new(0), boxes: (box 0, Rc::new(0)) };
1598 let _ = Vec::from_elem(100, s);
1603 fn test_grow_fn_fail() {
1606 v.grow_fn(100, |i| {
1616 fn test_permute_fail() {
1618 let v = [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
1619 (box 0, Rc::new(0)), (box 0, Rc::new(0))];
1621 for _ in v.permutations() {
1631 fn test_copy_memory_oob() {
1633 let mut a = [1, 2, 3, 4];
1634 let b = [1, 2, 3, 4, 5];
1640 fn test_total_ord() {
1641 [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
1642 [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
1643 [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
1644 [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
1645 [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
1649 fn test_iterator() {
1651 let xs = [1, 2, 5, 10, 11];
1652 let mut it = xs.iter();
1653 assert_eq!(it.size_hint(), (5, Some(5)));
1654 assert_eq!(it.next().unwrap(), &1);
1655 assert_eq!(it.size_hint(), (4, Some(4)));
1656 assert_eq!(it.next().unwrap(), &2);
1657 assert_eq!(it.size_hint(), (3, Some(3)));
1658 assert_eq!(it.next().unwrap(), &5);
1659 assert_eq!(it.size_hint(), (2, Some(2)));
1660 assert_eq!(it.next().unwrap(), &10);
1661 assert_eq!(it.size_hint(), (1, Some(1)));
1662 assert_eq!(it.next().unwrap(), &11);
1663 assert_eq!(it.size_hint(), (0, Some(0)));
1664 assert!(it.next().is_none());
1668 fn test_random_access_iterator() {
1670 let xs = [1, 2, 5, 10, 11];
1671 let mut it = xs.iter();
1673 assert_eq!(it.indexable(), 5);
1674 assert_eq!(it.idx(0).unwrap(), &1);
1675 assert_eq!(it.idx(2).unwrap(), &5);
1676 assert_eq!(it.idx(4).unwrap(), &11);
1677 assert!(it.idx(5).is_none());
1679 assert_eq!(it.next().unwrap(), &1);
1680 assert_eq!(it.indexable(), 4);
1681 assert_eq!(it.idx(0).unwrap(), &2);
1682 assert_eq!(it.idx(3).unwrap(), &11);
1683 assert!(it.idx(4).is_none());
1685 assert_eq!(it.next().unwrap(), &2);
1686 assert_eq!(it.indexable(), 3);
1687 assert_eq!(it.idx(1).unwrap(), &10);
1688 assert!(it.idx(3).is_none());
1690 assert_eq!(it.next().unwrap(), &5);
1691 assert_eq!(it.indexable(), 2);
1692 assert_eq!(it.idx(1).unwrap(), &11);
1694 assert_eq!(it.next().unwrap(), &10);
1695 assert_eq!(it.indexable(), 1);
1696 assert_eq!(it.idx(0).unwrap(), &11);
1697 assert!(it.idx(1).is_none());
1699 assert_eq!(it.next().unwrap(), &11);
1700 assert_eq!(it.indexable(), 0);
1701 assert!(it.idx(0).is_none());
1703 assert!(it.next().is_none());
1707 fn test_iter_size_hints() {
1709 let mut xs = [1, 2, 5, 10, 11];
1710 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
1711 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
1715 fn test_iter_clone() {
1717 let mut it = xs.iter();
1719 let mut jt = it.clone();
1720 assert_eq!(it.next(), jt.next());
1721 assert_eq!(it.next(), jt.next());
1722 assert_eq!(it.next(), jt.next());
1726 fn test_mut_iterator() {
1728 let mut xs = [1, 2, 3, 4, 5];
1729 for x in xs.mut_iter() {
1732 assert!(xs == [2, 3, 4, 5, 6])
1736 fn test_rev_iterator() {
1739 let xs = [1, 2, 5, 10, 11];
1740 let ys = [11, 10, 5, 2, 1];
1742 for &x in xs.iter().rev() {
1743 assert_eq!(x, ys[i]);
1750 fn test_mut_rev_iterator() {
1752 let mut xs = [1u, 2, 3, 4, 5];
1753 for (i,x) in xs.mut_iter().rev().enumerate() {
1756 assert!(xs == [5, 5, 5, 5, 5])
1760 fn test_move_iterator() {
1762 let xs = box [1u,2,3,4,5];
1763 assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
1767 fn test_move_rev_iterator() {
1769 let xs = box [1u,2,3,4,5];
1770 assert_eq!(xs.move_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
1774 fn test_splitator() {
1775 let xs = &[1i,2,3,4,5];
1777 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<~[&[int]]>(),
1778 box [&[1], &[3], &[5]]);
1779 assert_eq!(xs.split(|x| *x == 1).collect::<~[&[int]]>(),
1780 box [&[], &[2,3,4,5]]);
1781 assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(),
1782 box [&[1,2,3,4], &[]]);
1783 assert_eq!(xs.split(|x| *x == 10).collect::<~[&[int]]>(),
1784 box [&[1,2,3,4,5]]);
1785 assert_eq!(xs.split(|_| true).collect::<~[&[int]]>(),
1786 box [&[], &[], &[], &[], &[], &[]]);
1788 let xs: &[int] = &[];
1789 assert_eq!(xs.split(|x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
1793 fn test_splitnator() {
1794 let xs = &[1i,2,3,4,5];
1796 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
1797 box [&[1,2,3,4,5]]);
1798 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
1799 box [&[1], &[3,4,5]]);
1800 assert_eq!(xs.splitn(3, |_| true).collect::<~[&[int]]>(),
1801 box [&[], &[], &[], &[4,5]]);
1803 let xs: &[int] = &[];
1804 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
1808 fn test_rsplitator() {
1809 let xs = &[1i,2,3,4,5];
1811 assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<~[&[int]]>(),
1812 box [&[5], &[3], &[1]]);
1813 assert_eq!(xs.split(|x| *x == 1).rev().collect::<~[&[int]]>(),
1814 box [&[2,3,4,5], &[]]);
1815 assert_eq!(xs.split(|x| *x == 5).rev().collect::<~[&[int]]>(),
1816 box [&[], &[1,2,3,4]]);
1817 assert_eq!(xs.split(|x| *x == 10).rev().collect::<~[&[int]]>(),
1818 box [&[1,2,3,4,5]]);
1820 let xs: &[int] = &[];
1821 assert_eq!(xs.split(|x| *x == 5).rev().collect::<~[&[int]]>(), box [&[]]);
1825 fn test_rsplitnator() {
1826 let xs = &[1,2,3,4,5];
1828 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<~[&[int]]>(),
1829 box [&[1,2,3,4,5]]);
1830 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<~[&[int]]>(),
1831 box [&[5], &[1,2,3]]);
1832 assert_eq!(xs.rsplitn(3, |_| true).collect::<~[&[int]]>(),
1833 box [&[], &[], &[], &[1,2]]);
1835 let xs: &[int] = &[];
1836 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<~[&[int]]>(), box [&[]]);
1840 fn test_windowsator() {
1841 let v = &[1i,2,3,4];
1843 assert_eq!(v.windows(2).collect::<~[&[int]]>(), box [&[1,2], &[2,3], &[3,4]]);
1844 assert_eq!(v.windows(3).collect::<~[&[int]]>(), box [&[1i,2,3], &[2,3,4]]);
1845 assert!(v.windows(6).next().is_none());
1850 fn test_windowsator_0() {
1851 let v = &[1i,2,3,4];
1852 let _it = v.windows(0);
1856 fn test_chunksator() {
1857 let v = &[1i,2,3,4,5];
1859 assert_eq!(v.chunks(2).collect::<~[&[int]]>(), box [&[1i,2], &[3,4], &[5]]);
1860 assert_eq!(v.chunks(3).collect::<~[&[int]]>(), box [&[1i,2,3], &[4,5]]);
1861 assert_eq!(v.chunks(6).collect::<~[&[int]]>(), box [&[1i,2,3,4,5]]);
1863 assert_eq!(v.chunks(2).rev().collect::<~[&[int]]>(), box [&[5i], &[3,4], &[1,2]]);
1864 let mut it = v.chunks(2);
1865 assert_eq!(it.indexable(), 3);
1866 assert_eq!(it.idx(0).unwrap(), &[1,2]);
1867 assert_eq!(it.idx(1).unwrap(), &[3,4]);
1868 assert_eq!(it.idx(2).unwrap(), &[5]);
1869 assert_eq!(it.idx(3), None);
1874 fn test_chunksator_0() {
1875 let v = &[1i,2,3,4];
1876 let _it = v.chunks(0);
1880 fn test_move_from() {
1881 let mut a = [1,2,3,4,5];
1882 let b = box [6,7,8];
1883 assert_eq!(a.move_from(b, 0, 3), 3);
1884 assert!(a == [6,7,8,4,5]);
1885 let mut a = [7,2,8,1];
1886 let b = box [3,1,4,1,5,9];
1887 assert_eq!(a.move_from(b, 0, 6), 4);
1888 assert!(a == [3,1,4,1]);
1889 let mut a = [1,2,3,4];
1890 let b = box [5,6,7,8,9,0];
1891 assert_eq!(a.move_from(b, 2, 3), 1);
1892 assert!(a == [7,2,3,4]);
1893 let mut a = [1,2,3,4,5];
1894 let b = box [5,6,7,8,9,0];
1895 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
1896 assert!(a == [1,2,6,7,5]);
1900 fn test_copy_from() {
1901 let mut a = [1,2,3,4,5];
1903 assert_eq!(a.copy_from(b), 3);
1904 assert!(a == [6,7,8,4,5]);
1905 let mut c = [7,2,8,1];
1906 let d = [3,1,4,1,5,9];
1907 assert_eq!(c.copy_from(d), 4);
1908 assert!(c == [3,1,4,1]);
1912 fn test_reverse_part() {
1913 let mut values = [1,2,3,4,5];
1914 values.mut_slice(1, 4).reverse();
1915 assert!(values == [1,4,3,2,5]);
1920 macro_rules! test_show_vec(
1921 ($x:expr, $x_str:expr) => ({
1922 let (x, x_str) = ($x, $x_str);
1923 assert_eq!(format!("{}", x), x_str);
1924 assert_eq!(format!("{}", x.as_slice()), x_str);
1927 let empty: ~[int] = box [];
1928 test_show_vec!(empty, "[]".to_owned());
1929 test_show_vec!(box [1], "[1]".to_owned());
1930 test_show_vec!(box [1, 2, 3], "[1, 2, 3]".to_owned());
1931 test_show_vec!(box [box [], box [1u], box [1u, 1u]], "[[], [1], [1, 1]]".to_owned());
1933 let empty_mut: &mut [int] = &mut[];
1934 test_show_vec!(empty_mut, "[]".to_owned());
1935 test_show_vec!(&mut[1], "[1]".to_owned());
1936 test_show_vec!(&mut[1, 2, 3], "[1, 2, 3]".to_owned());
1937 test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]], "[[], [1], [1, 1]]".to_owned());
1941 fn test_vec_default() {
1942 use default::Default;
1945 let v: $ty = Default::default();
1946 assert!(v.is_empty());
1956 fn test_bytes_set_memory() {
1957 use slice::bytes::MutableByteVector;
1958 let mut values = [1u8,2,3,4,5];
1959 values.mut_slice(0,5).set_memory(0xAB);
1960 assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
1961 values.mut_slice(2,4).set_memory(0xFF);
1962 assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
1967 fn test_overflow_does_not_cause_segfault() {
1969 v.reserve_exact(-1);
1976 fn test_overflow_does_not_cause_segfault_managed() {
1978 let mut v = vec![Rc::new(1)];
1979 v.reserve_exact(-1);
1984 fn test_mut_split_at() {
1985 let mut values = [1u8,2,3,4,5];
1987 let (left, right) = values.mut_split_at(2);
1988 assert!(left.slice(0, left.len()) == [1, 2]);
1989 for p in left.mut_iter() {
1993 assert!(right.slice(0, right.len()) == [3, 4, 5]);
1994 for p in right.mut_iter() {
1999 assert!(values == [2, 3, 5, 6, 7]);
2002 #[deriving(Clone, Eq)]
2006 fn test_iter_zero_sized() {
2007 let mut v = vec![Foo, Foo, Foo];
2008 assert_eq!(v.len(), 3);
2017 for f in v.slice(1, 3).iter() {
2023 for f in v.mut_iter() {
2029 for f in v.move_iter() {
2033 assert_eq!(cnt, 11);
2035 let xs: [Foo, ..3] = [Foo, Foo, Foo];
2037 for f in xs.iter() {
2045 fn test_shrink_to_fit() {
2046 let mut xs = vec![0, 1, 2, 3];
2047 for i in range(4, 100) {
2050 assert_eq!(xs.capacity(), 128);
2052 assert_eq!(xs.capacity(), 100);
2053 assert_eq!(xs, range(0, 100).collect::<Vec<_>>());
2057 fn test_starts_with() {
2058 assert!(bytes!("foobar").starts_with(bytes!("foo")));
2059 assert!(!bytes!("foobar").starts_with(bytes!("oob")));
2060 assert!(!bytes!("foobar").starts_with(bytes!("bar")));
2061 assert!(!bytes!("foo").starts_with(bytes!("foobar")));
2062 assert!(!bytes!("bar").starts_with(bytes!("foobar")));
2063 assert!(bytes!("foobar").starts_with(bytes!("foobar")));
2064 let empty: &[u8] = [];
2065 assert!(empty.starts_with(empty));
2066 assert!(!empty.starts_with(bytes!("foo")));
2067 assert!(bytes!("foobar").starts_with(empty));
2071 fn test_ends_with() {
2072 assert!(bytes!("foobar").ends_with(bytes!("bar")));
2073 assert!(!bytes!("foobar").ends_with(bytes!("oba")));
2074 assert!(!bytes!("foobar").ends_with(bytes!("foo")));
2075 assert!(!bytes!("foo").ends_with(bytes!("foobar")));
2076 assert!(!bytes!("bar").ends_with(bytes!("foobar")));
2077 assert!(bytes!("foobar").ends_with(bytes!("foobar")));
2078 let empty: &[u8] = [];
2079 assert!(empty.ends_with(empty));
2080 assert!(!empty.ends_with(bytes!("foo")));
2081 assert!(bytes!("foobar").ends_with(empty));
2085 fn test_shift_ref() {
2086 let mut x: &[int] = [1, 2, 3, 4, 5];
2087 let h = x.shift_ref();
2088 assert_eq!(*h.unwrap(), 1);
2089 assert_eq!(x.len(), 4);
2090 assert_eq!(x[0], 2);
2091 assert_eq!(x[3], 5);
2093 let mut y: &[int] = [];
2094 assert_eq!(y.shift_ref(), None);
2099 let mut x: &[int] = [1, 2, 3, 4, 5];
2100 let h = x.pop_ref();
2101 assert_eq!(*h.unwrap(), 5);
2102 assert_eq!(x.len(), 4);
2103 assert_eq!(x[0], 1);
2104 assert_eq!(x[3], 4);
2106 let mut y: &[int] = [];
2107 assert!(y.pop_ref().is_none());
2111 fn test_mut_splitator() {
2112 let mut xs = [0,1,0,2,3,0,0,4,5,0];
2113 assert_eq!(xs.mut_split(|x| *x == 0).len(), 6);
2114 for slice in xs.mut_split(|x| *x == 0) {
2117 assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2119 let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
2120 for slice in xs.mut_split(|x| *x == 0).take(5) {
2123 assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2127 fn test_mut_splitator_rev() {
2128 let mut xs = [1,2,0,3,4,0,0,5,6,0];
2129 for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
2132 assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2136 fn test_mut_chunks() {
2137 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2138 for (i, chunk) in v.mut_chunks(3).enumerate() {
2139 for x in chunk.mut_iter() {
2143 let result = [0u8, 0, 0, 1, 1, 1, 2];
2144 assert!(v == result);
2148 fn test_mut_chunks_rev() {
2149 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2150 for (i, chunk) in v.mut_chunks(3).rev().enumerate() {
2151 for x in chunk.mut_iter() {
2155 let result = [2u8, 2, 2, 1, 1, 1, 0];
2156 assert!(v == result);
2161 fn test_mut_chunks_0() {
2162 let mut v = [1, 2, 3, 4];
2163 let _it = v.mut_chunks(0);
2167 fn test_mut_shift_ref() {
2168 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2169 let h = x.mut_shift_ref();
2170 assert_eq!(*h.unwrap(), 1);
2171 assert_eq!(x.len(), 4);
2172 assert_eq!(x[0], 2);
2173 assert_eq!(x[3], 5);
2175 let mut y: &mut [int] = [];
2176 assert!(y.mut_shift_ref().is_none());
2180 fn test_mut_pop_ref() {
2181 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2182 let h = x.mut_pop_ref();
2183 assert_eq!(*h.unwrap(), 5);
2184 assert_eq!(x.len(), 4);
2185 assert_eq!(x[0], 1);
2186 assert_eq!(x[3], 4);
2188 let mut y: &mut [int] = [];
2189 assert!(y.mut_pop_ref().is_none());
2193 fn test_mut_last() {
2194 let mut x = [1, 2, 3, 4, 5];
2195 let h = x.mut_last();
2196 assert_eq!(*h.unwrap(), 5);
2198 let y: &mut [int] = [];
2199 assert!(y.mut_last().is_none());
2206 use self::test::Bencher;
2210 use rand::{weak_rng, Rng};
2213 fn iterator(b: &mut Bencher) {
2214 // peculiar numbers to stop LLVM from optimising the summation
2216 let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
2223 // sum == 11806, to stop dead code elimination.
2224 if sum == 0 {fail!()}
2229 fn mut_iterator(b: &mut Bencher) {
2230 let mut v = Vec::from_elem(100, 0);
2234 for x in v.mut_iter() {
2242 fn add(b: &mut Bencher) {
2243 let xs: &[int] = [5, ..10];
2244 let ys: &[int] = [5, ..10];
2251 fn concat(b: &mut Bencher) {
2252 let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
2254 xss.as_slice().concat_vec()
2259 fn connect(b: &mut Bencher) {
2260 let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
2262 xss.as_slice().connect_vec(&0)
2267 fn push(b: &mut Bencher) {
2268 let mut vec: Vec<uint> = vec![];
2276 fn starts_with_same_vector(b: &mut Bencher) {
2277 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2279 vec.as_slice().starts_with(vec.as_slice())
2284 fn starts_with_single_element(b: &mut Bencher) {
2285 let vec: Vec<uint> = vec![0];
2287 vec.as_slice().starts_with(vec.as_slice())
2292 fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2293 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2294 let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
2297 vec.as_slice().starts_with(match_vec.as_slice())
2302 fn ends_with_same_vector(b: &mut Bencher) {
2303 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2305 vec.as_slice().ends_with(vec.as_slice())
2310 fn ends_with_single_element(b: &mut Bencher) {
2311 let vec: Vec<uint> = vec![0];
2313 vec.as_slice().ends_with(vec.as_slice())
2318 fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2319 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2320 let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
2321 match_vec.as_mut_slice()[0] = 200;
2323 vec.as_slice().starts_with(match_vec.as_slice())
2328 fn contains_last_element(b: &mut Bencher) {
2329 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2336 fn zero_1kb_from_elem(b: &mut Bencher) {
2338 Vec::from_elem(1024, 0u8)
2343 fn zero_1kb_set_memory(b: &mut Bencher) {
2345 let mut v: Vec<uint> = Vec::with_capacity(1024);
2347 let vp = v.as_mut_ptr();
2348 ptr::set_memory(vp, 0, 1024);
2356 fn zero_1kb_fixed_repeat(b: &mut Bencher) {
2363 fn zero_1kb_loop_set(b: &mut Bencher) {
2365 let mut v: Vec<uint> = Vec::with_capacity(1024);
2369 for i in range(0u, 1024) {
2376 fn zero_1kb_mut_iter(b: &mut Bencher) {
2378 let mut v = Vec::with_capacity(1024);
2382 for x in v.mut_iter() {
2390 fn random_inserts(b: &mut Bencher) {
2391 let mut rng = weak_rng();
2393 let mut v = Vec::from_elem(30, (0u, 0u));
2394 for _ in range(0, 100) {
2396 v.insert(rng.gen::<uint>() % (l + 1),
2402 fn random_removes(b: &mut Bencher) {
2403 let mut rng = weak_rng();
2405 let mut v = Vec::from_elem(130, (0u, 0u));
2406 for _ in range(0, 100) {
2408 v.remove(rng.gen::<uint>() % l);
2414 fn sort_random_small(b: &mut Bencher) {
2415 let mut rng = weak_rng();
2417 let mut v = rng.gen_vec::<u64>(5);
2418 v.as_mut_slice().sort();
2420 b.bytes = 5 * mem::size_of::<u64>() as u64;
2424 fn sort_random_medium(b: &mut Bencher) {
2425 let mut rng = weak_rng();
2427 let mut v = rng.gen_vec::<u64>(100);
2428 v.as_mut_slice().sort();
2430 b.bytes = 100 * mem::size_of::<u64>() as u64;
2434 fn sort_random_large(b: &mut Bencher) {
2435 let mut rng = weak_rng();
2437 let mut v = rng.gen_vec::<u64>(10000);
2438 v.as_mut_slice().sort();
2440 b.bytes = 10000 * mem::size_of::<u64>() as u64;
2444 fn sort_sorted(b: &mut Bencher) {
2445 let mut v = Vec::from_fn(10000, |i| i);
2449 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;
2452 type BigSortable = (u64,u64,u64,u64);
2455 fn sort_big_random_small(b: &mut Bencher) {
2456 let mut rng = weak_rng();
2458 let mut v = rng.gen_vec::<BigSortable>(5);
2461 b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
2465 fn sort_big_random_medium(b: &mut Bencher) {
2466 let mut rng = weak_rng();
2468 let mut v = rng.gen_vec::<BigSortable>(100);
2471 b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
2475 fn sort_big_random_large(b: &mut Bencher) {
2476 let mut rng = weak_rng();
2478 let mut v = rng.gen_vec::<BigSortable>(10000);
2481 b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
2485 fn sort_big_sorted(b: &mut Bencher) {
2486 let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
2490 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;