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`, `Eq`, `Ord` -- 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`.
100 #![doc(primitive = "slice")]
104 use cmp::{Ord, Ordering, Less, Greater};
106 use container::Container;
111 use option::{None, Option, Some};
114 use rt::heap::{allocate, deallocate};
115 use finally::try_finally;
118 pub use core::slice::{ref_slice, mut_ref_slice, Splits, Windows};
119 pub use core::slice::{Chunks, Vector, ImmutableVector, ImmutableEqVector};
120 pub use core::slice::{ImmutableOrdVector, MutableVector, Items, MutItems};
121 pub use core::slice::{MutSplits, MutChunks};
122 pub use core::slice::{bytes, MutableCloneableVector};
124 // Functional utilities
126 #[allow(missing_doc)]
127 pub trait VectorVector<T> {
128 // FIXME #5898: calling these .concat and .connect conflicts with
129 // StrVector::con{cat,nect}, since they have generic contents.
130 /// Flattens a vector of vectors of T into a single vector of T.
131 fn concat_vec(&self) -> Vec<T>;
133 /// Concatenate a vector of vectors, placing a given separator between each.
134 fn connect_vec(&self, sep: &T) -> Vec<T>;
137 impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
138 fn concat_vec(&self) -> Vec<T> {
139 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
140 let mut result = Vec::with_capacity(size);
141 for v in self.iter() {
142 result.push_all(v.as_slice())
147 fn connect_vec(&self, sep: &T) -> Vec<T> {
148 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
149 let mut result = Vec::with_capacity(size + self.len());
150 let mut first = true;
151 for v in self.iter() {
152 if first { first = false } else { result.push(sep.clone()) }
153 result.push_all(v.as_slice())
159 /// An Iterator that yields the element swaps needed to produce
160 /// a sequence of all possible permutations for an indexed sequence of
161 /// elements. Each permutation is only a single swap apart.
163 /// The Steinhaus–Johnson–Trotter algorithm is used.
165 /// Generates even and odd permutations alternately.
167 /// The last generated swap is always (0, 1), and it returns the
168 /// sequence to its initial order.
169 pub struct ElementSwaps {
170 sdir: Vec<SizeDirection>,
171 /// If true, emit the last swap that returns the sequence to initial state
177 /// Create an `ElementSwaps` iterator for a sequence of `length` elements
178 pub fn new(length: uint) -> ElementSwaps {
179 // Initialize `sdir` with a direction that position should move in
180 // (all negative at the beginning) and the `size` of the
181 // element (equal to the original index).
184 sdir: range(0, length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
190 enum Direction { Pos, Neg }
192 /// An Index and Direction together
193 struct SizeDirection {
198 impl Iterator<(uint, uint)> for ElementSwaps {
200 fn next(&mut self) -> Option<(uint, uint)> {
201 fn new_pos(i: uint, s: Direction) -> uint {
202 i + match s { Pos => 1, Neg => -1 }
205 // Find the index of the largest mobile element:
206 // The direction should point into the vector, and the
207 // swap should be with a smaller `size` element.
208 let max = self.sdir.iter().map(|&x| x).enumerate()
210 new_pos(i, sd.dir) < self.sdir.len() &&
211 self.sdir.get(new_pos(i, sd.dir)).size < sd.size)
212 .max_by(|&(_, sd)| sd.size);
215 let j = new_pos(i, sd.dir);
216 self.sdir.as_mut_slice().swap(i, j);
218 // Swap the direction of each larger SizeDirection
219 for x in self.sdir.mut_iter() {
220 if x.size > sd.size {
221 x.dir = match x.dir { Pos => Neg, Neg => Pos };
224 self.swaps_made += 1;
227 None => if self.emit_reset {
228 self.emit_reset = false;
229 if self.sdir.len() > 1 {
231 self.swaps_made += 1;
234 // Vector is of the form [] or [x], and the only permutation is itself
235 self.swaps_made += 1;
243 fn size_hint(&self) -> (uint, Option<uint>) {
244 // For a vector of size n, there are exactly n! permutations.
245 let n = range(2, self.sdir.len() + 1).product();
246 (n - self.swaps_made, Some(n - self.swaps_made))
250 /// An Iterator that uses `ElementSwaps` to iterate through
251 /// all possible permutations of a vector.
253 /// The first iteration yields a clone of the vector as it is,
254 /// then each successive element is the vector with one
257 /// Generates even and odd permutations alternately.
258 pub struct Permutations<T> {
263 impl<T: Clone> Iterator<~[T]> for Permutations<T> {
265 fn next(&mut self) -> Option<~[T]> {
266 match self.swaps.next() {
268 Some((0,0)) => Some(self.v.clone()),
270 let elt = self.v.clone();
278 fn size_hint(&self) -> (uint, Option<uint>) {
279 self.swaps.size_hint()
283 /// Extension methods for vector slices with cloneable elements
284 pub trait CloneableVector<T> {
285 /// Copy `self` into a new owned vector
286 fn to_owned(&self) -> ~[T];
288 /// Convert `self` into an owned vector, not making a copy if possible.
289 fn into_owned(self) -> ~[T];
292 /// Extension methods for vector slices
293 impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
294 /// Returns a copy of `v`.
296 fn to_owned(&self) -> ~[T] {
297 use RawVec = core::raw::Vec;
298 use num::{CheckedAdd, CheckedMul};
301 let len = self.len();
302 let data_size = len.checked_mul(&mem::size_of::<T>());
303 let data_size = data_size.expect("overflow in to_owned()");
304 let size = mem::size_of::<RawVec<()>>().checked_add(&data_size);
305 let size = size.expect("overflow in to_owned()");
308 // this should pass the real required alignment
309 let ret = allocate(size, 8) as *mut RawVec<()>;
311 let a_size = mem::size_of::<T>();
312 let a_size = if a_size == 0 {1} else {a_size};
313 (*ret).fill = len * a_size;
314 (*ret).alloc = len * a_size;
316 // Be careful with the following loop. We want it to be optimized
317 // to a memcpy (or something similarly fast) when T is Copy. LLVM
318 // is easily confused, so any extra operations during the loop can
319 // prevent this optimization.
321 let p = &mut (*ret).data as *mut _ as *mut T;
324 |i, ()| while *i < len {
326 &mut(*p.offset(*i as int)),
327 self.unsafe_ref(*i).clone());
331 // we must be failing, clean up after ourselves
332 for j in range(0, *i as int) {
333 ptr::read(&*p.offset(j));
335 // FIXME: #13994 (should pass align and size here)
336 deallocate(ret as *mut u8, 0, 8);
343 fn into_owned(self) -> ~[T] { self.to_owned() }
346 /// Extension methods for owned vectors
347 impl<T: Clone> CloneableVector<T> for ~[T] {
349 fn to_owned(&self) -> ~[T] { self.clone() }
352 fn into_owned(self) -> ~[T] { self }
355 /// Extension methods for vectors containing `Clone` elements.
356 pub trait ImmutableCloneableVector<T> {
357 /// Partitions the vector into two vectors `(A,B)`, where all
358 /// elements of `A` satisfy `f` and all elements of `B` do not.
359 fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>);
361 /// Create an iterator that yields every possible permutation of the
362 /// vector in succession.
363 fn permutations(self) -> Permutations<T>;
366 impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
368 fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
369 let mut lefts = Vec::new();
370 let mut rights = Vec::new();
372 for elt in self.iter() {
374 lefts.push((*elt).clone());
376 rights.push((*elt).clone());
383 fn permutations(self) -> Permutations<T> {
385 swaps: ElementSwaps::new(self.len()),
392 /// Extension methods for owned vectors.
393 pub trait OwnedVector<T> {
394 /// Creates a consuming iterator, that is, one that moves each
395 /// value out of the vector (from start to end). The vector cannot
396 /// be used after calling this.
401 /// let v = ~["a".to_string(), "b".to_string()];
402 /// for s in v.move_iter() {
403 /// // s has type ~str, not &~str
404 /// println!("{}", s);
407 fn move_iter(self) -> MoveItems<T>;
410 * Partitions the vector into two vectors `(A,B)`, where all
411 * elements of `A` satisfy `f` and all elements of `B` do not.
413 fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>);
416 impl<T> OwnedVector<T> for ~[T] {
418 fn move_iter(self) -> MoveItems<T> {
420 let iter = transmute(self.iter());
421 let ptr = transmute(self);
422 MoveItems { allocation: ptr, iter: iter }
427 fn partition(self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
428 let mut lefts = Vec::new();
429 let mut rights = Vec::new();
431 for elt in self.move_iter() {
443 fn insertion_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
444 let len = v.len() as int;
445 let buf_v = v.as_mut_ptr();
448 for i in range(1, len) {
449 // j satisfies: 0 <= j <= i;
453 let read_ptr = buf_v.offset(i) as *T;
455 // find where to insert, we need to do strict <,
456 // rather than <=, to maintain stability.
458 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
460 compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
464 // shift everything to the right, to make space to
465 // insert this value.
467 // j + 1 could be `len` (for the last `i`), but in
468 // that case, `i == j` so we don't copy. The
469 // `.offset(j)` is always in bounds.
472 let tmp = ptr::read(read_ptr);
473 ptr::copy_memory(buf_v.offset(j + 1),
476 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
485 fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
486 // warning: this wildly uses unsafe.
487 static BASE_INSERTION: uint = 32;
488 static LARGE_INSERTION: uint = 16;
490 // FIXME #12092: smaller insertion runs seems to make sorting
491 // vectors of large elements a little faster on some platforms,
492 // but hasn't been tested/tuned extensively
493 let insertion = if size_of::<T>() <= 16 {
501 // short vectors get sorted in-place via insertion sort to avoid allocations
502 if len <= insertion {
503 insertion_sort(v, compare);
507 // allocate some memory to use as scratch memory, we keep the
508 // length 0 so we can keep shallow copies of the contents of `v`
509 // without risking the dtors running on an object twice if
511 let mut working_space = Vec::with_capacity(2 * len);
512 // these both are buffers of length `len`.
513 let mut buf_dat = working_space.as_mut_ptr();
514 let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
517 let buf_v = v.as_ptr();
519 // step 1. sort short runs with insertion sort. This takes the
520 // values from `v` and sorts them into `buf_dat`, leaving that
521 // with sorted runs of length INSERTION.
523 // We could hardcode the sorting comparisons here, and we could
524 // manipulate/step the pointers themselves, rather than repeatedly
526 for start in range_step(0, len, insertion) {
528 for i in range(start, cmp::min(start + insertion, len)) {
529 // j satisfies: start <= j <= i;
530 let mut j = i as int;
533 let read_ptr = buf_v.offset(i as int);
535 // find where to insert, we need to do strict <,
536 // rather than <=, to maintain stability.
538 // start <= j - 1 < len, so .offset(j - 1) is in
540 while j > start as int &&
541 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
545 // shift everything to the right, to make space to
546 // insert this value.
548 // j + 1 could be `len` (for the last `i`), but in
549 // that case, `i == j` so we don't copy. The
550 // `.offset(j)` is always in bounds.
551 ptr::copy_memory(buf_dat.offset(j + 1),
554 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
559 // step 2. merge the sorted runs.
560 let mut width = insertion;
562 // merge the sorted runs of length `width` in `buf_dat` two at
563 // a time, placing the result in `buf_tmp`.
565 // 0 <= start <= len.
566 for start in range_step(0, len, 2 * width) {
567 // manipulate pointers directly for speed (rather than
568 // using a `for` loop with `range` and `.offset` inside
571 // the end of the first run & start of the
572 // second. Offset of `len` is defined, since this is
573 // precisely one byte past the end of the object.
574 let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
575 // end of the second. Similar reasoning to the above re safety.
576 let right_end_idx = cmp::min(start + 2 * width, len);
577 let right_end = buf_dat.offset(right_end_idx as int);
579 // the pointers to the elements under consideration
580 // from the two runs.
582 // both of these are in bounds.
583 let mut left = buf_dat.offset(start as int);
584 let mut right = right_start;
586 // where we're putting the results, it is a run of
587 // length `2*width`, so we step it once for each step
588 // of either `left` or `right`. `buf_tmp` has length
589 // `len`, so these are in bounds.
590 let mut out = buf_tmp.offset(start as int);
591 let out_end = buf_tmp.offset(right_end_idx as int);
593 while out < out_end {
594 // Either the left or the right run are exhausted,
595 // so just copy the remainder from the other run
596 // and move on; this gives a huge speed-up (order
597 // of 25%) for mostly sorted vectors (the best
599 if left == right_start {
600 // the number remaining in this run.
601 let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
602 ptr::copy_nonoverlapping_memory(out, &*right, elems);
604 } else if right == right_end {
605 let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
606 ptr::copy_nonoverlapping_memory(out, &*left, elems);
610 // check which side is smaller, and that's the
611 // next element for the new run.
613 // `left < right_start` and `right < right_end`,
614 // so these are valid.
615 let to_copy = if compare(&*left, &*right) == Greater {
620 ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
626 mem::swap(&mut buf_dat, &mut buf_tmp);
631 // write the result to `v` in one go, so that there are never two copies
632 // of the same object in `v`.
634 ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
637 // increment the pointer, returning the old pointer.
639 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
641 *ptr = ptr.offset(1);
646 /// Extension methods for vectors such that their elements are
648 pub trait MutableVectorAllocating<'a, T> {
649 /// Sort the vector, in place, using `compare` to compare
652 /// This sort is `O(n log n)` worst-case and stable, but allocates
653 /// approximately `2 * n`, where `n` is the length of `self`.
658 /// let mut v = [5i, 4, 1, 3, 2];
659 /// v.sort_by(|a, b| a.cmp(b));
660 /// assert!(v == [1, 2, 3, 4, 5]);
662 /// // reverse sorting
663 /// v.sort_by(|a, b| b.cmp(a));
664 /// assert!(v == [5, 4, 3, 2, 1]);
666 fn sort_by(self, compare: |&T, &T| -> Ordering);
669 * Consumes `src` and moves as many elements as it can into `self`
670 * from the range [start,end).
672 * Returns the number of elements copied (the shorter of self.len()
677 * * src - A mutable vector of `T`
678 * * start - The index into `src` to start copying from
679 * * end - The index into `str` to stop copying from
681 fn move_from(self, src: ~[T], start: uint, end: uint) -> uint;
684 impl<'a,T> MutableVectorAllocating<'a, T> for &'a mut [T] {
686 fn sort_by(self, compare: |&T, &T| -> Ordering) {
687 merge_sort(self, compare)
691 fn move_from(self, mut src: ~[T], start: uint, end: uint) -> uint {
692 for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
695 cmp::min(self.len(), end-start)
699 /// Methods for mutable vectors with orderable elements, such as
700 /// in-place sorting.
701 pub trait MutableOrdVector<T> {
702 /// Sort the vector, in place.
704 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
709 /// let mut v = [-5, 4, 1, -3, 2];
712 /// assert!(v == [-5, -3, 1, 2, 4]);
716 /// Mutates the slice to the next lexicographic permutation.
718 /// Returns `true` if successful, `false` if the slice is at the last-ordered permutation.
723 /// let v = &mut [0, 1, 2];
724 /// v.next_permutation();
725 /// assert_eq!(v, &mut [0, 2, 1]);
726 /// v.next_permutation();
727 /// assert_eq!(v, &mut [1, 0, 2]);
729 fn next_permutation(self) -> bool;
731 /// Mutates the slice to the previous lexicographic permutation.
733 /// Returns `true` if successful, `false` if the slice is at the first-ordered permutation.
738 /// let v = &mut [1, 0, 2];
739 /// v.prev_permutation();
740 /// assert_eq!(v, &mut [0, 2, 1]);
741 /// v.prev_permutation();
742 /// assert_eq!(v, &mut [0, 1, 2]);
744 fn prev_permutation(self) -> bool;
747 impl<'a, T: Ord> MutableOrdVector<T> for &'a mut [T] {
750 self.sort_by(|a,b| a.cmp(b))
753 fn next_permutation(self) -> bool {
754 // These cases only have 1 permutation each, so we can't do anything.
755 if self.len() < 2 { return false; }
757 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
758 let mut i = self.len() - 1;
759 while i > 0 && self[i-1] >= self[i] {
763 // If that is the entire vector, this is the last-ordered permutation.
768 // Step 2: Find the rightmost element larger than the pivot (i-1)
769 let mut j = self.len() - 1;
770 while j >= i && self[j] <= self[i-1] {
774 // Step 3: Swap that element with the pivot
777 // Step 4: Reverse the (previously) weakly decreasing part
778 self.mut_slice_from(i).reverse();
783 fn prev_permutation(self) -> bool {
784 // These cases only have 1 permutation each, so we can't do anything.
785 if self.len() < 2 { return false; }
787 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
788 let mut i = self.len() - 1;
789 while i > 0 && self[i-1] <= self[i] {
793 // If that is the entire vector, this is the first-ordered permutation.
798 // Step 2: Reverse the weakly increasing part
799 self.mut_slice_from(i).reverse();
801 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
802 let mut j = self.len() - 1;
803 while j >= i && self[j-1] < self[i-1] {
807 // Step 4: Swap that element with the pivot
814 /// Unsafe operations
816 pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
817 pub use core::slice::raw::{shift_ptr, pop_ptr};
820 /// An iterator that moves out of a vector.
821 pub struct MoveItems<T> {
822 allocation: *mut u8, // the block of memory allocated for the vector
823 iter: Items<'static, T>
826 impl<T> Iterator<T> for MoveItems<T> {
828 fn next(&mut self) -> Option<T> {
830 self.iter.next().map(|x| ptr::read(x))
835 fn size_hint(&self) -> (uint, Option<uint>) {
836 self.iter.size_hint()
840 impl<T> DoubleEndedIterator<T> for MoveItems<T> {
842 fn next_back(&mut self) -> Option<T> {
844 self.iter.next_back().map(|x| ptr::read(x))
850 impl<T> Drop for MoveItems<T> {
852 // destroy the remaining elements
855 // FIXME: #13994 (should pass align and size here)
856 deallocate(self.allocation, 0, 8)
867 use rand::{Rng, task_rng};
870 fn square(n: uint) -> uint { n * n }
872 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
876 // Test on-stack from_fn.
877 let mut v = Vec::from_fn(3u, square);
879 let v = v.as_slice();
880 assert_eq!(v.len(), 3u);
881 assert_eq!(v[0], 0u);
882 assert_eq!(v[1], 1u);
883 assert_eq!(v[2], 4u);
886 // Test on-heap from_fn.
887 v = Vec::from_fn(5u, square);
889 let v = v.as_slice();
890 assert_eq!(v.len(), 5u);
891 assert_eq!(v[0], 0u);
892 assert_eq!(v[1], 1u);
893 assert_eq!(v[2], 4u);
894 assert_eq!(v[3], 9u);
895 assert_eq!(v[4], 16u);
900 fn test_from_elem() {
901 // Test on-stack from_elem.
902 let mut v = Vec::from_elem(2u, 10u);
904 let v = v.as_slice();
905 assert_eq!(v.len(), 2u);
906 assert_eq!(v[0], 10u);
907 assert_eq!(v[1], 10u);
910 // Test on-heap from_elem.
911 v = Vec::from_elem(6u, 20u);
913 let v = v.as_slice();
914 assert_eq!(v[0], 20u);
915 assert_eq!(v[1], 20u);
916 assert_eq!(v[2], 20u);
917 assert_eq!(v[3], 20u);
918 assert_eq!(v[4], 20u);
919 assert_eq!(v[5], 20u);
925 let xs: [int, ..0] = [];
926 assert!(xs.is_empty());
927 assert!(![0].is_empty());
931 fn test_len_divzero() {
934 let v1 : &[Z] = &[[]];
935 let v2 : &[Z] = &[[], []];
936 assert_eq!(mem::size_of::<Z>(), 0);
937 assert_eq!(v0.len(), 0);
938 assert_eq!(v1.len(), 1);
939 assert_eq!(v2.len(), 2);
944 let mut a = box [11];
945 assert_eq!(a.get(1), None);
947 assert_eq!(a.get(1).unwrap(), &12);
948 a = box [11, 12, 13];
949 assert_eq!(a.get(1).unwrap(), &12);
955 assert_eq!(a.head(), None);
957 assert_eq!(a.head().unwrap(), &11);
959 assert_eq!(a.head().unwrap(), &11);
964 let mut a = box [11];
965 assert_eq!(a.tail(), &[]);
967 assert_eq!(a.tail(), &[12]);
972 fn test_tail_empty() {
973 let a: ~[int] = box [];
979 let mut a = box [11, 12, 13];
980 assert_eq!(a.tailn(0), &[11, 12, 13]);
981 a = box [11, 12, 13];
982 assert_eq!(a.tailn(2), &[13]);
987 fn test_tailn_empty() {
988 let a: ~[int] = box [];
994 let mut a = box [11];
995 assert_eq!(a.init(), &[]);
997 assert_eq!(a.init(), &[11]);
1002 fn test_init_empty() {
1003 let a: ~[int] = box [];
1009 let mut a = box [11, 12, 13];
1010 assert_eq!(a.initn(0), &[11, 12, 13]);
1011 a = box [11, 12, 13];
1012 assert_eq!(a.initn(2), &[11]);
1017 fn test_initn_empty() {
1018 let a: ~[int] = box [];
1025 assert_eq!(a.last(), None);
1027 assert_eq!(a.last().unwrap(), &11);
1029 assert_eq!(a.last().unwrap(), &12);
1034 // Test fixed length vector.
1035 let vec_fixed = [1, 2, 3, 4];
1036 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_owned();
1037 assert_eq!(v_a.len(), 3u);
1038 assert_eq!(v_a[0], 2);
1039 assert_eq!(v_a[1], 3);
1040 assert_eq!(v_a[2], 4);
1043 let vec_stack = &[1, 2, 3];
1044 let v_b = vec_stack.slice(1u, 3u).to_owned();
1045 assert_eq!(v_b.len(), 2u);
1046 assert_eq!(v_b[0], 2);
1047 assert_eq!(v_b[1], 3);
1050 let vec_unique = box [1, 2, 3, 4, 5, 6];
1051 let v_d = vec_unique.slice(1u, 6u).to_owned();
1052 assert_eq!(v_d.len(), 5u);
1053 assert_eq!(v_d[0], 2);
1054 assert_eq!(v_d[1], 3);
1055 assert_eq!(v_d[2], 4);
1056 assert_eq!(v_d[3], 5);
1057 assert_eq!(v_d[4], 6);
1061 fn test_slice_from() {
1062 let vec = &[1, 2, 3, 4];
1063 assert_eq!(vec.slice_from(0), vec);
1064 assert_eq!(vec.slice_from(2), &[3, 4]);
1065 assert_eq!(vec.slice_from(4), &[]);
1069 fn test_slice_to() {
1070 let vec = &[1, 2, 3, 4];
1071 assert_eq!(vec.slice_to(4), vec);
1072 assert_eq!(vec.slice_to(2), &[1, 2]);
1073 assert_eq!(vec.slice_to(0), &[]);
1079 let mut v = vec![5];
1081 assert_eq!(v.len(), 0);
1082 assert_eq!(e, Some(5));
1084 assert_eq!(f, None);
1086 assert_eq!(g, None);
1090 fn test_swap_remove() {
1091 let mut v = vec![1, 2, 3, 4, 5];
1092 let mut e = v.swap_remove(0);
1093 assert_eq!(e, Some(1));
1094 assert_eq!(v, vec![5, 2, 3, 4]);
1095 e = v.swap_remove(3);
1096 assert_eq!(e, Some(4));
1097 assert_eq!(v, vec![5, 2, 3]);
1099 e = v.swap_remove(3);
1100 assert_eq!(e, None);
1101 assert_eq!(v, vec![5, 2, 3]);
1105 fn test_swap_remove_noncopyable() {
1106 // Tests that we don't accidentally run destructors twice.
1107 let mut v = vec![::unstable::sync::Exclusive::new(()),
1108 ::unstable::sync::Exclusive::new(()),
1109 ::unstable::sync::Exclusive::new(())];
1110 let mut _e = v.swap_remove(0);
1111 assert_eq!(v.len(), 2);
1112 _e = v.swap_remove(1);
1113 assert_eq!(v.len(), 1);
1114 _e = v.swap_remove(0);
1115 assert_eq!(v.len(), 0);
1120 // Test on-stack push().
1123 assert_eq!(v.len(), 1u);
1124 assert_eq!(v.as_slice()[0], 1);
1126 // Test on-heap push().
1128 assert_eq!(v.len(), 2u);
1129 assert_eq!(v.as_slice()[0], 1);
1130 assert_eq!(v.as_slice()[1], 2);
1135 // Test on-stack grow().
1139 let v = v.as_slice();
1140 assert_eq!(v.len(), 2u);
1141 assert_eq!(v[0], 1);
1142 assert_eq!(v[1], 1);
1145 // Test on-heap grow().
1148 let v = v.as_slice();
1149 assert_eq!(v.len(), 5u);
1150 assert_eq!(v[0], 1);
1151 assert_eq!(v[1], 1);
1152 assert_eq!(v[2], 2);
1153 assert_eq!(v[3], 2);
1154 assert_eq!(v[4], 2);
1161 v.grow_fn(3u, square);
1162 let v = v.as_slice();
1163 assert_eq!(v.len(), 3u);
1164 assert_eq!(v[0], 0u);
1165 assert_eq!(v[1], 1u);
1166 assert_eq!(v[2], 4u);
1170 fn test_grow_set() {
1171 let mut v = vec![1, 2, 3];
1172 v.grow_set(4u, &4, 5);
1173 let v = v.as_slice();
1174 assert_eq!(v.len(), 5u);
1175 assert_eq!(v[0], 1);
1176 assert_eq!(v[1], 2);
1177 assert_eq!(v[2], 3);
1178 assert_eq!(v[3], 4);
1179 assert_eq!(v[4], 5);
1183 fn test_truncate() {
1184 let mut v = vec![box 6,box 5,box 4];
1186 let v = v.as_slice();
1187 assert_eq!(v.len(), 1);
1188 assert_eq!(*(v[0]), 6);
1189 // If the unsafe block didn't drop things properly, we blow up here.
1194 let mut v = vec![box 6,box 5,box 4];
1196 assert_eq!(v.len(), 0);
1197 // If the unsafe block didn't drop things properly, we blow up here.
1202 fn case(a: Vec<uint>, b: Vec<uint>) {
1207 case(vec![], vec![]);
1208 case(vec![1], vec![1]);
1209 case(vec![1,1], vec![1]);
1210 case(vec![1,2,3], vec![1,2,3]);
1211 case(vec![1,1,2,3], vec![1,2,3]);
1212 case(vec![1,2,2,3], vec![1,2,3]);
1213 case(vec![1,2,3,3], vec![1,2,3]);
1214 case(vec![1,1,2,2,2,3,3], vec![1,2,3]);
1218 fn test_dedup_unique() {
1219 let mut v0 = vec![box 1, box 1, box 2, box 3];
1221 let mut v1 = vec![box 1, box 2, box 2, box 3];
1223 let mut v2 = vec![box 1, box 2, box 3, box 3];
1226 * If the boxed pointers were leaked or otherwise misused, valgrind
1227 * and/or rustrt should raise errors.
1232 fn test_dedup_shared() {
1233 let mut v0 = vec![box 1, box 1, box 2, box 3];
1235 let mut v1 = vec![box 1, box 2, box 2, box 3];
1237 let mut v2 = vec![box 1, box 2, box 3, box 3];
1240 * If the pointers were leaked or otherwise misused, valgrind and/or
1241 * rustrt should raise errors.
1247 let mut v = vec![1, 2, 3, 4, 5];
1249 assert_eq!(v, vec![1, 3, 5]);
1253 fn test_element_swaps() {
1254 let mut v = [1, 2, 3];
1255 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
1258 0 => assert!(v == [1, 3, 2]),
1259 1 => assert!(v == [3, 1, 2]),
1260 2 => assert!(v == [3, 2, 1]),
1261 3 => assert!(v == [2, 3, 1]),
1262 4 => assert!(v == [2, 1, 3]),
1263 5 => assert!(v == [1, 2, 3]),
1270 fn test_permutations() {
1272 let v: [int, ..0] = [];
1273 let mut it = v.permutations();
1274 let (min_size, max_opt) = it.size_hint();
1275 assert_eq!(min_size, 1);
1276 assert_eq!(max_opt.unwrap(), 1);
1277 assert_eq!(it.next(), Some(v.as_slice().to_owned()));
1278 assert_eq!(it.next(), None);
1281 let v = ["Hello".to_string()];
1282 let mut it = v.permutations();
1283 let (min_size, max_opt) = it.size_hint();
1284 assert_eq!(min_size, 1);
1285 assert_eq!(max_opt.unwrap(), 1);
1286 assert_eq!(it.next(), Some(v.as_slice().to_owned()));
1287 assert_eq!(it.next(), None);
1291 let mut it = v.permutations();
1292 let (min_size, max_opt) = it.size_hint();
1293 assert_eq!(min_size, 3*2);
1294 assert_eq!(max_opt.unwrap(), 3*2);
1295 assert_eq!(it.next(), Some(box [1,2,3]));
1296 assert_eq!(it.next(), Some(box [1,3,2]));
1297 assert_eq!(it.next(), Some(box [3,1,2]));
1298 let (min_size, max_opt) = it.size_hint();
1299 assert_eq!(min_size, 3);
1300 assert_eq!(max_opt.unwrap(), 3);
1301 assert_eq!(it.next(), Some(box [3,2,1]));
1302 assert_eq!(it.next(), Some(box [2,3,1]));
1303 assert_eq!(it.next(), Some(box [2,1,3]));
1304 assert_eq!(it.next(), None);
1307 // check that we have N! permutations
1308 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
1310 let mut it = v.permutations();
1311 let (min_size, max_opt) = it.size_hint();
1315 assert_eq!(amt, it.swaps.swaps_made);
1316 assert_eq!(amt, min_size);
1317 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
1318 assert_eq!(amt, max_opt.unwrap());
1323 fn test_lexicographic_permutations() {
1324 let v : &mut[int] = &mut[1, 2, 3, 4, 5];
1325 assert!(v.prev_permutation() == false);
1326 assert!(v.next_permutation());
1327 assert_eq!(v, &mut[1, 2, 3, 5, 4]);
1328 assert!(v.prev_permutation());
1329 assert_eq!(v, &mut[1, 2, 3, 4, 5]);
1330 assert!(v.next_permutation());
1331 assert!(v.next_permutation());
1332 assert_eq!(v, &mut[1, 2, 4, 3, 5]);
1333 assert!(v.next_permutation());
1334 assert_eq!(v, &mut[1, 2, 4, 5, 3]);
1336 let v : &mut[int] = &mut[1, 0, 0, 0];
1337 assert!(v.next_permutation() == false);
1338 assert!(v.prev_permutation());
1339 assert_eq!(v, &mut[0, 1, 0, 0]);
1340 assert!(v.prev_permutation());
1341 assert_eq!(v, &mut[0, 0, 1, 0]);
1342 assert!(v.prev_permutation());
1343 assert_eq!(v, &mut[0, 0, 0, 1]);
1344 assert!(v.prev_permutation() == false);
1348 fn test_lexicographic_permutations_empty_and_short() {
1349 let empty : &mut[int] = &mut[];
1350 assert!(empty.next_permutation() == false);
1351 assert_eq!(empty, &mut[]);
1352 assert!(empty.prev_permutation() == false);
1353 assert_eq!(empty, &mut[]);
1355 let one_elem : &mut[int] = &mut[4];
1356 assert!(one_elem.prev_permutation() == false);
1357 assert_eq!(one_elem, &mut[4]);
1358 assert!(one_elem.next_permutation() == false);
1359 assert_eq!(one_elem, &mut[4]);
1361 let two_elem : &mut[int] = &mut[1, 2];
1362 assert!(two_elem.prev_permutation() == false);
1363 assert_eq!(two_elem, &mut[1, 2]);
1364 assert!(two_elem.next_permutation());
1365 assert_eq!(two_elem, &mut[2, 1]);
1366 assert!(two_elem.next_permutation() == false);
1367 assert_eq!(two_elem, &mut[2, 1]);
1368 assert!(two_elem.prev_permutation());
1369 assert_eq!(two_elem, &mut[1, 2]);
1370 assert!(two_elem.prev_permutation() == false);
1371 assert_eq!(two_elem, &mut[1, 2]);
1375 fn test_position_elem() {
1376 assert!([].position_elem(&1).is_none());
1378 let v1 = box [1, 2, 3, 3, 2, 5];
1379 assert_eq!(v1.position_elem(&1), Some(0u));
1380 assert_eq!(v1.position_elem(&2), Some(1u));
1381 assert_eq!(v1.position_elem(&5), Some(5u));
1382 assert!(v1.position_elem(&4).is_none());
1386 fn test_bsearch_elem() {
1387 assert_eq!([1,2,3,4,5].bsearch_elem(&5), Some(4));
1388 assert_eq!([1,2,3,4,5].bsearch_elem(&4), Some(3));
1389 assert_eq!([1,2,3,4,5].bsearch_elem(&3), Some(2));
1390 assert_eq!([1,2,3,4,5].bsearch_elem(&2), Some(1));
1391 assert_eq!([1,2,3,4,5].bsearch_elem(&1), Some(0));
1393 assert_eq!([2,4,6,8,10].bsearch_elem(&1), None);
1394 assert_eq!([2,4,6,8,10].bsearch_elem(&5), None);
1395 assert_eq!([2,4,6,8,10].bsearch_elem(&4), Some(1));
1396 assert_eq!([2,4,6,8,10].bsearch_elem(&10), Some(4));
1398 assert_eq!([2,4,6,8].bsearch_elem(&1), None);
1399 assert_eq!([2,4,6,8].bsearch_elem(&5), None);
1400 assert_eq!([2,4,6,8].bsearch_elem(&4), Some(1));
1401 assert_eq!([2,4,6,8].bsearch_elem(&8), Some(3));
1403 assert_eq!([2,4,6].bsearch_elem(&1), None);
1404 assert_eq!([2,4,6].bsearch_elem(&5), None);
1405 assert_eq!([2,4,6].bsearch_elem(&4), Some(1));
1406 assert_eq!([2,4,6].bsearch_elem(&6), Some(2));
1408 assert_eq!([2,4].bsearch_elem(&1), None);
1409 assert_eq!([2,4].bsearch_elem(&5), None);
1410 assert_eq!([2,4].bsearch_elem(&2), Some(0));
1411 assert_eq!([2,4].bsearch_elem(&4), Some(1));
1413 assert_eq!([2].bsearch_elem(&1), None);
1414 assert_eq!([2].bsearch_elem(&5), None);
1415 assert_eq!([2].bsearch_elem(&2), Some(0));
1417 assert_eq!([].bsearch_elem(&1), None);
1418 assert_eq!([].bsearch_elem(&5), None);
1420 assert!([1,1,1,1,1].bsearch_elem(&1) != None);
1421 assert!([1,1,1,1,2].bsearch_elem(&1) != None);
1422 assert!([1,1,1,2,2].bsearch_elem(&1) != None);
1423 assert!([1,1,2,2,2].bsearch_elem(&1) != None);
1424 assert_eq!([1,2,2,2,2].bsearch_elem(&1), Some(0));
1426 assert_eq!([1,2,3,4,5].bsearch_elem(&6), None);
1427 assert_eq!([1,2,3,4,5].bsearch_elem(&0), None);
1432 let mut v: ~[int] = box [10, 20];
1433 assert_eq!(v[0], 10);
1434 assert_eq!(v[1], 20);
1436 assert_eq!(v[0], 20);
1437 assert_eq!(v[1], 10);
1439 let mut v3: ~[int] = box [];
1441 assert!(v3.is_empty());
1446 use realstd::slice::Vector;
1447 use realstd::clone::Clone;
1448 for len in range(4u, 25) {
1449 for _ in range(0, 100) {
1450 let mut v = task_rng().gen_iter::<uint>().take(len)
1451 .collect::<Vec<uint>>();
1452 let mut v1 = v.clone();
1454 v.as_mut_slice().sort();
1455 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1457 v1.as_mut_slice().sort_by(|a, b| a.cmp(b));
1458 assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
1460 v1.as_mut_slice().sort_by(|a, b| b.cmp(a));
1461 assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
1465 // shouldn't fail/crash
1466 let mut v: [uint, .. 0] = [];
1469 let mut v = [0xDEADBEEFu];
1471 assert!(v == [0xDEADBEEF]);
1475 fn test_sort_stability() {
1476 for len in range(4, 25) {
1477 for _ in range(0 , 10) {
1478 let mut counts = [0, .. 10];
1480 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
1481 // where the first item of each tuple is random, but
1482 // the second item represents which occurrence of that
1483 // number this element is, i.e. the second elements
1484 // will occur in sorted order.
1485 let mut v = range(0, len).map(|_| {
1486 let n = task_rng().gen::<uint>() % 10;
1489 }).collect::<Vec<(uint, int)>>();
1491 // only sort on the first element, so an unstable sort
1492 // may mix up the counts.
1493 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
1495 // this comparison includes the count (the second item
1496 // of the tuple), so elements with equal first items
1497 // will need to be ordered with increasing
1498 // counts... i.e. exactly asserting that this sort is
1500 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1506 fn test_partition() {
1507 assert_eq!((box []).partition(|x: &int| *x < 3), (vec![], vec![]));
1508 assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1509 assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1510 assert_eq!((box [1, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1514 fn test_partitioned() {
1515 assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
1516 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1517 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1518 assert_eq!(([1, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1523 let v: [~[int], ..0] = [];
1524 assert_eq!(v.concat_vec(), vec![]);
1525 assert_eq!([box [1], box [2,3]].concat_vec(), vec![1, 2, 3]);
1527 assert_eq!([&[1], &[2,3]].concat_vec(), vec![1, 2, 3]);
1532 let v: [~[int], ..0] = [];
1533 assert_eq!(v.connect_vec(&0), vec![]);
1534 assert_eq!([box [1], box [2, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
1535 assert_eq!([box [1], box [2], box [3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
1537 assert_eq!([&[1], &[2, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
1538 assert_eq!([&[1], &[2], &[3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
1543 let mut x = vec![1, 2, 3];
1544 assert_eq!(x.shift(), Some(1));
1545 assert_eq!(&x, &vec![2, 3]);
1546 assert_eq!(x.shift(), Some(2));
1547 assert_eq!(x.shift(), Some(3));
1548 assert_eq!(x.shift(), None);
1549 assert_eq!(x.len(), 0);
1554 let mut x = vec![1, 2, 3];
1556 assert_eq!(x, vec![0, 1, 2, 3]);
1561 let mut a = vec![1, 2, 4];
1563 assert_eq!(a, vec![1, 2, 3, 4]);
1565 let mut a = vec![1, 2, 3];
1567 assert_eq!(a, vec![0, 1, 2, 3]);
1569 let mut a = vec![1, 2, 3];
1571 assert_eq!(a, vec![1, 2, 3, 4]);
1575 assert_eq!(a, vec![1]);
1580 fn test_insert_oob() {
1581 let mut a = vec![1, 2, 3];
1587 let mut a = vec![1,2,3,4];
1589 assert_eq!(a.remove(2), Some(3));
1590 assert_eq!(a, vec![1,2,4]);
1592 assert_eq!(a.remove(2), Some(4));
1593 assert_eq!(a, vec![1,2]);
1595 assert_eq!(a.remove(2), None);
1596 assert_eq!(a, vec![1,2]);
1598 assert_eq!(a.remove(0), Some(1));
1599 assert_eq!(a, vec![2]);
1601 assert_eq!(a.remove(0), Some(2));
1602 assert_eq!(a, vec![]);
1604 assert_eq!(a.remove(0), None);
1605 assert_eq!(a.remove(10), None);
1609 fn test_capacity() {
1610 let mut v = vec![0u64];
1611 v.reserve_exact(10u);
1612 assert_eq!(v.capacity(), 10u);
1613 let mut v = vec![0u32];
1614 v.reserve_exact(10u);
1615 assert_eq!(v.capacity(), 10u);
1620 let v = vec![1, 2, 3, 4, 5];
1621 let v = v.slice(1u, 3u);
1622 assert_eq!(v.len(), 2u);
1623 assert_eq!(v[0], 2);
1624 assert_eq!(v[1], 3);
1630 fn test_from_fn_fail() {
1631 Vec::from_fn(100, |v| {
1632 if v == 50 { fail!() }
1639 fn test_from_elem_fail() {
1645 boxes: (Box<int>, Rc<int>)
1649 fn clone(&self) -> S {
1650 self.f.set(self.f.get() + 1);
1651 if self.f.get() == 10 { fail!() }
1652 S { f: self.f, boxes: self.boxes.clone() }
1656 let s = S { f: Cell::new(0), boxes: (box 0, Rc::new(0)) };
1657 let _ = Vec::from_elem(100, s);
1662 fn test_grow_fn_fail() {
1665 v.grow_fn(100, |i| {
1675 fn test_permute_fail() {
1677 let v = [(box 0, Rc::new(0)), (box 0, Rc::new(0)),
1678 (box 0, Rc::new(0)), (box 0, Rc::new(0))];
1680 for _ in v.permutations() {
1690 fn test_copy_memory_oob() {
1692 let mut a = [1, 2, 3, 4];
1693 let b = [1, 2, 3, 4, 5];
1699 fn test_total_ord() {
1700 [1, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
1701 [1, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
1702 [1, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
1703 [1, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
1704 [2, 2].cmp(& &[1, 2, 3, 4]) == Greater;
1708 fn test_iterator() {
1710 let xs = [1, 2, 5, 10, 11];
1711 let mut it = xs.iter();
1712 assert_eq!(it.size_hint(), (5, Some(5)));
1713 assert_eq!(it.next().unwrap(), &1);
1714 assert_eq!(it.size_hint(), (4, Some(4)));
1715 assert_eq!(it.next().unwrap(), &2);
1716 assert_eq!(it.size_hint(), (3, Some(3)));
1717 assert_eq!(it.next().unwrap(), &5);
1718 assert_eq!(it.size_hint(), (2, Some(2)));
1719 assert_eq!(it.next().unwrap(), &10);
1720 assert_eq!(it.size_hint(), (1, Some(1)));
1721 assert_eq!(it.next().unwrap(), &11);
1722 assert_eq!(it.size_hint(), (0, Some(0)));
1723 assert!(it.next().is_none());
1727 fn test_random_access_iterator() {
1729 let xs = [1, 2, 5, 10, 11];
1730 let mut it = xs.iter();
1732 assert_eq!(it.indexable(), 5);
1733 assert_eq!(it.idx(0).unwrap(), &1);
1734 assert_eq!(it.idx(2).unwrap(), &5);
1735 assert_eq!(it.idx(4).unwrap(), &11);
1736 assert!(it.idx(5).is_none());
1738 assert_eq!(it.next().unwrap(), &1);
1739 assert_eq!(it.indexable(), 4);
1740 assert_eq!(it.idx(0).unwrap(), &2);
1741 assert_eq!(it.idx(3).unwrap(), &11);
1742 assert!(it.idx(4).is_none());
1744 assert_eq!(it.next().unwrap(), &2);
1745 assert_eq!(it.indexable(), 3);
1746 assert_eq!(it.idx(1).unwrap(), &10);
1747 assert!(it.idx(3).is_none());
1749 assert_eq!(it.next().unwrap(), &5);
1750 assert_eq!(it.indexable(), 2);
1751 assert_eq!(it.idx(1).unwrap(), &11);
1753 assert_eq!(it.next().unwrap(), &10);
1754 assert_eq!(it.indexable(), 1);
1755 assert_eq!(it.idx(0).unwrap(), &11);
1756 assert!(it.idx(1).is_none());
1758 assert_eq!(it.next().unwrap(), &11);
1759 assert_eq!(it.indexable(), 0);
1760 assert!(it.idx(0).is_none());
1762 assert!(it.next().is_none());
1766 fn test_iter_size_hints() {
1768 let mut xs = [1, 2, 5, 10, 11];
1769 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
1770 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
1774 fn test_iter_clone() {
1776 let mut it = xs.iter();
1778 let mut jt = it.clone();
1779 assert_eq!(it.next(), jt.next());
1780 assert_eq!(it.next(), jt.next());
1781 assert_eq!(it.next(), jt.next());
1785 fn test_mut_iterator() {
1787 let mut xs = [1, 2, 3, 4, 5];
1788 for x in xs.mut_iter() {
1791 assert!(xs == [2, 3, 4, 5, 6])
1795 fn test_rev_iterator() {
1798 let xs = [1, 2, 5, 10, 11];
1799 let ys = [11, 10, 5, 2, 1];
1801 for &x in xs.iter().rev() {
1802 assert_eq!(x, ys[i]);
1809 fn test_mut_rev_iterator() {
1811 let mut xs = [1u, 2, 3, 4, 5];
1812 for (i,x) in xs.mut_iter().rev().enumerate() {
1815 assert!(xs == [5, 5, 5, 5, 5])
1819 fn test_move_iterator() {
1821 let xs = box [1u,2,3,4,5];
1822 assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
1826 fn test_move_rev_iterator() {
1828 let xs = box [1u,2,3,4,5];
1829 assert_eq!(xs.move_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
1833 fn test_splitator() {
1834 let xs = &[1i,2,3,4,5];
1836 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1837 &[&[1], &[3], &[5]]);
1838 assert_eq!(xs.split(|x| *x == 1).collect::<Vec<&[int]>>().as_slice(),
1839 &[&[], &[2,3,4,5]]);
1840 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(),
1841 &[&[1,2,3,4], &[]]);
1842 assert_eq!(xs.split(|x| *x == 10).collect::<Vec<&[int]>>().as_slice(),
1844 assert_eq!(xs.split(|_| true).collect::<Vec<&[int]>>().as_slice(),
1845 &[&[], &[], &[], &[], &[], &[]]);
1847 let xs: &[int] = &[];
1848 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1852 fn test_splitnator() {
1853 let xs = &[1i,2,3,4,5];
1855 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1857 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1859 assert_eq!(xs.splitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
1860 &[&[], &[], &[], &[4,5]]);
1862 let xs: &[int] = &[];
1863 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1867 fn test_rsplitator() {
1868 let xs = &[1i,2,3,4,5];
1870 assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<&[int]>>().as_slice(),
1871 &[&[5], &[3], &[1]]);
1872 assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<&[int]>>().as_slice(),
1873 &[&[2,3,4,5], &[]]);
1874 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(),
1875 &[&[], &[1,2,3,4]]);
1876 assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<&[int]>>().as_slice(),
1879 let xs: &[int] = &[];
1880 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1884 fn test_rsplitnator() {
1885 let xs = &[1,2,3,4,5];
1887 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1889 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1891 assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
1892 &[&[], &[], &[], &[1,2]]);
1894 let xs: &[int] = &[];
1895 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1899 fn test_windowsator() {
1900 let v = &[1i,2,3,4];
1902 assert_eq!(v.windows(2).collect::<Vec<&[int]>>().as_slice(), &[&[1,2], &[2,3], &[3,4]]);
1903 assert_eq!(v.windows(3).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3], &[2,3,4]]);
1904 assert!(v.windows(6).next().is_none());
1909 fn test_windowsator_0() {
1910 let v = &[1i,2,3,4];
1911 let _it = v.windows(0);
1915 fn test_chunksator() {
1916 let v = &[1i,2,3,4,5];
1918 assert_eq!(v.chunks(2).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2], &[3,4], &[5]]);
1919 assert_eq!(v.chunks(3).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3], &[4,5]]);
1920 assert_eq!(v.chunks(6).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3,4,5]]);
1922 assert_eq!(v.chunks(2).rev().collect::<Vec<&[int]>>().as_slice(), &[&[5i], &[3,4], &[1,2]]);
1923 let mut it = v.chunks(2);
1924 assert_eq!(it.indexable(), 3);
1925 assert_eq!(it.idx(0).unwrap(), &[1,2]);
1926 assert_eq!(it.idx(1).unwrap(), &[3,4]);
1927 assert_eq!(it.idx(2).unwrap(), &[5]);
1928 assert_eq!(it.idx(3), None);
1933 fn test_chunksator_0() {
1934 let v = &[1i,2,3,4];
1935 let _it = v.chunks(0);
1939 fn test_move_from() {
1940 let mut a = [1,2,3,4,5];
1941 let b = box [6,7,8];
1942 assert_eq!(a.move_from(b, 0, 3), 3);
1943 assert!(a == [6,7,8,4,5]);
1944 let mut a = [7,2,8,1];
1945 let b = box [3,1,4,1,5,9];
1946 assert_eq!(a.move_from(b, 0, 6), 4);
1947 assert!(a == [3,1,4,1]);
1948 let mut a = [1,2,3,4];
1949 let b = box [5,6,7,8,9,0];
1950 assert_eq!(a.move_from(b, 2, 3), 1);
1951 assert!(a == [7,2,3,4]);
1952 let mut a = [1,2,3,4,5];
1953 let b = box [5,6,7,8,9,0];
1954 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
1955 assert!(a == [1,2,6,7,5]);
1959 fn test_copy_from() {
1960 let mut a = [1,2,3,4,5];
1962 assert_eq!(a.copy_from(b), 3);
1963 assert!(a == [6,7,8,4,5]);
1964 let mut c = [7,2,8,1];
1965 let d = [3,1,4,1,5,9];
1966 assert_eq!(c.copy_from(d), 4);
1967 assert!(c == [3,1,4,1]);
1971 fn test_reverse_part() {
1972 let mut values = [1,2,3,4,5];
1973 values.mut_slice(1, 4).reverse();
1974 assert!(values == [1,4,3,2,5]);
1979 macro_rules! test_show_vec(
1980 ($x:expr, $x_str:expr) => ({
1981 let (x, x_str) = ($x, $x_str);
1982 assert_eq!(format!("{}", x), x_str);
1983 assert_eq!(format!("{}", x.as_slice()), x_str);
1986 let empty: ~[int] = box [];
1987 test_show_vec!(empty, "[]".to_string());
1988 test_show_vec!(box [1], "[1]".to_string());
1989 test_show_vec!(box [1, 2, 3], "[1, 2, 3]".to_string());
1990 test_show_vec!(box [box [], box [1u], box [1u, 1u]],
1991 "[[], [1], [1, 1]]".to_string());
1993 let empty_mut: &mut [int] = &mut[];
1994 test_show_vec!(empty_mut, "[]".to_string());
1995 test_show_vec!(&mut[1], "[1]".to_string());
1996 test_show_vec!(&mut[1, 2, 3], "[1, 2, 3]".to_string());
1997 test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]],
1998 "[[], [1], [1, 1]]".to_string());
2002 fn test_vec_default() {
2003 use default::Default;
2006 let v: $ty = Default::default();
2007 assert!(v.is_empty());
2017 fn test_bytes_set_memory() {
2018 use slice::bytes::MutableByteVector;
2019 let mut values = [1u8,2,3,4,5];
2020 values.mut_slice(0,5).set_memory(0xAB);
2021 assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
2022 values.mut_slice(2,4).set_memory(0xFF);
2023 assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
2028 fn test_overflow_does_not_cause_segfault() {
2030 v.reserve_exact(-1);
2037 fn test_overflow_does_not_cause_segfault_managed() {
2039 let mut v = vec![Rc::new(1)];
2040 v.reserve_exact(-1);
2045 fn test_mut_split_at() {
2046 let mut values = [1u8,2,3,4,5];
2048 let (left, right) = values.mut_split_at(2);
2049 assert!(left.slice(0, left.len()) == [1, 2]);
2050 for p in left.mut_iter() {
2054 assert!(right.slice(0, right.len()) == [3, 4, 5]);
2055 for p in right.mut_iter() {
2060 assert!(values == [2, 3, 5, 6, 7]);
2063 #[deriving(Clone, PartialEq)]
2067 fn test_iter_zero_sized() {
2068 let mut v = vec![Foo, Foo, Foo];
2069 assert_eq!(v.len(), 3);
2078 for f in v.slice(1, 3).iter() {
2084 for f in v.mut_iter() {
2090 for f in v.move_iter() {
2094 assert_eq!(cnt, 11);
2096 let xs: [Foo, ..3] = [Foo, Foo, Foo];
2098 for f in xs.iter() {
2106 fn test_shrink_to_fit() {
2107 let mut xs = vec![0, 1, 2, 3];
2108 for i in range(4, 100) {
2111 assert_eq!(xs.capacity(), 128);
2113 assert_eq!(xs.capacity(), 100);
2114 assert_eq!(xs, range(0, 100).collect::<Vec<_>>());
2118 fn test_starts_with() {
2119 assert!(bytes!("foobar").starts_with(bytes!("foo")));
2120 assert!(!bytes!("foobar").starts_with(bytes!("oob")));
2121 assert!(!bytes!("foobar").starts_with(bytes!("bar")));
2122 assert!(!bytes!("foo").starts_with(bytes!("foobar")));
2123 assert!(!bytes!("bar").starts_with(bytes!("foobar")));
2124 assert!(bytes!("foobar").starts_with(bytes!("foobar")));
2125 let empty: &[u8] = [];
2126 assert!(empty.starts_with(empty));
2127 assert!(!empty.starts_with(bytes!("foo")));
2128 assert!(bytes!("foobar").starts_with(empty));
2132 fn test_ends_with() {
2133 assert!(bytes!("foobar").ends_with(bytes!("bar")));
2134 assert!(!bytes!("foobar").ends_with(bytes!("oba")));
2135 assert!(!bytes!("foobar").ends_with(bytes!("foo")));
2136 assert!(!bytes!("foo").ends_with(bytes!("foobar")));
2137 assert!(!bytes!("bar").ends_with(bytes!("foobar")));
2138 assert!(bytes!("foobar").ends_with(bytes!("foobar")));
2139 let empty: &[u8] = [];
2140 assert!(empty.ends_with(empty));
2141 assert!(!empty.ends_with(bytes!("foo")));
2142 assert!(bytes!("foobar").ends_with(empty));
2146 fn test_shift_ref() {
2147 let mut x: &[int] = [1, 2, 3, 4, 5];
2148 let h = x.shift_ref();
2149 assert_eq!(*h.unwrap(), 1);
2150 assert_eq!(x.len(), 4);
2151 assert_eq!(x[0], 2);
2152 assert_eq!(x[3], 5);
2154 let mut y: &[int] = [];
2155 assert_eq!(y.shift_ref(), None);
2160 let mut x: &[int] = [1, 2, 3, 4, 5];
2161 let h = x.pop_ref();
2162 assert_eq!(*h.unwrap(), 5);
2163 assert_eq!(x.len(), 4);
2164 assert_eq!(x[0], 1);
2165 assert_eq!(x[3], 4);
2167 let mut y: &[int] = [];
2168 assert!(y.pop_ref().is_none());
2172 fn test_mut_splitator() {
2173 let mut xs = [0,1,0,2,3,0,0,4,5,0];
2174 assert_eq!(xs.mut_split(|x| *x == 0).len(), 6);
2175 for slice in xs.mut_split(|x| *x == 0) {
2178 assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2180 let mut xs = [0,1,0,2,3,0,0,4,5,0,6,7];
2181 for slice in xs.mut_split(|x| *x == 0).take(5) {
2184 assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2188 fn test_mut_splitator_rev() {
2189 let mut xs = [1,2,0,3,4,0,0,5,6,0];
2190 for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
2193 assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2197 fn test_mut_chunks() {
2198 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2199 for (i, chunk) in v.mut_chunks(3).enumerate() {
2200 for x in chunk.mut_iter() {
2204 let result = [0u8, 0, 0, 1, 1, 1, 2];
2205 assert!(v == result);
2209 fn test_mut_chunks_rev() {
2210 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2211 for (i, chunk) in v.mut_chunks(3).rev().enumerate() {
2212 for x in chunk.mut_iter() {
2216 let result = [2u8, 2, 2, 1, 1, 1, 0];
2217 assert!(v == result);
2222 fn test_mut_chunks_0() {
2223 let mut v = [1, 2, 3, 4];
2224 let _it = v.mut_chunks(0);
2228 fn test_mut_shift_ref() {
2229 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2230 let h = x.mut_shift_ref();
2231 assert_eq!(*h.unwrap(), 1);
2232 assert_eq!(x.len(), 4);
2233 assert_eq!(x[0], 2);
2234 assert_eq!(x[3], 5);
2236 let mut y: &mut [int] = [];
2237 assert!(y.mut_shift_ref().is_none());
2241 fn test_mut_pop_ref() {
2242 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2243 let h = x.mut_pop_ref();
2244 assert_eq!(*h.unwrap(), 5);
2245 assert_eq!(x.len(), 4);
2246 assert_eq!(x[0], 1);
2247 assert_eq!(x[3], 4);
2249 let mut y: &mut [int] = [];
2250 assert!(y.mut_pop_ref().is_none());
2254 fn test_mut_last() {
2255 let mut x = [1, 2, 3, 4, 5];
2256 let h = x.mut_last();
2257 assert_eq!(*h.unwrap(), 5);
2259 let y: &mut [int] = [];
2260 assert!(y.mut_last().is_none());
2267 use self::test::Bencher;
2271 use rand::{weak_rng, Rng};
2274 fn iterator(b: &mut Bencher) {
2275 // peculiar numbers to stop LLVM from optimising the summation
2277 let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
2284 // sum == 11806, to stop dead code elimination.
2285 if sum == 0 {fail!()}
2290 fn mut_iterator(b: &mut Bencher) {
2291 let mut v = Vec::from_elem(100, 0);
2295 for x in v.mut_iter() {
2303 fn concat(b: &mut Bencher) {
2304 let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
2306 xss.as_slice().concat_vec()
2311 fn connect(b: &mut Bencher) {
2312 let xss: Vec<Vec<uint>> = Vec::from_fn(100, |i| range(0, i).collect());
2314 xss.as_slice().connect_vec(&0)
2319 fn push(b: &mut Bencher) {
2320 let mut vec: Vec<uint> = vec![];
2328 fn starts_with_same_vector(b: &mut Bencher) {
2329 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2331 vec.as_slice().starts_with(vec.as_slice())
2336 fn starts_with_single_element(b: &mut Bencher) {
2337 let vec: Vec<uint> = vec![0];
2339 vec.as_slice().starts_with(vec.as_slice())
2344 fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2345 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2346 let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
2349 vec.as_slice().starts_with(match_vec.as_slice())
2354 fn ends_with_same_vector(b: &mut Bencher) {
2355 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2357 vec.as_slice().ends_with(vec.as_slice())
2362 fn ends_with_single_element(b: &mut Bencher) {
2363 let vec: Vec<uint> = vec![0];
2365 vec.as_slice().ends_with(vec.as_slice())
2370 fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2371 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2372 let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
2373 match_vec.as_mut_slice()[0] = 200;
2375 vec.as_slice().starts_with(match_vec.as_slice())
2380 fn contains_last_element(b: &mut Bencher) {
2381 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2388 fn zero_1kb_from_elem(b: &mut Bencher) {
2390 Vec::from_elem(1024, 0u8)
2395 fn zero_1kb_set_memory(b: &mut Bencher) {
2397 let mut v: Vec<uint> = Vec::with_capacity(1024);
2399 let vp = v.as_mut_ptr();
2400 ptr::set_memory(vp, 0, 1024);
2408 fn zero_1kb_fixed_repeat(b: &mut Bencher) {
2415 fn zero_1kb_loop_set(b: &mut Bencher) {
2417 let mut v: Vec<uint> = Vec::with_capacity(1024);
2421 for i in range(0u, 1024) {
2428 fn zero_1kb_mut_iter(b: &mut Bencher) {
2430 let mut v = Vec::with_capacity(1024);
2434 for x in v.mut_iter() {
2442 fn random_inserts(b: &mut Bencher) {
2443 let mut rng = weak_rng();
2445 let mut v = Vec::from_elem(30, (0u, 0u));
2446 for _ in range(0, 100) {
2448 v.insert(rng.gen::<uint>() % (l + 1),
2454 fn random_removes(b: &mut Bencher) {
2455 let mut rng = weak_rng();
2457 let mut v = Vec::from_elem(130, (0u, 0u));
2458 for _ in range(0, 100) {
2460 v.remove(rng.gen::<uint>() % l);
2466 fn sort_random_small(b: &mut Bencher) {
2467 let mut rng = weak_rng();
2469 let mut v = rng.gen_iter::<u64>().take(5).collect::<Vec<u64>>();
2470 v.as_mut_slice().sort();
2472 b.bytes = 5 * mem::size_of::<u64>() as u64;
2476 fn sort_random_medium(b: &mut Bencher) {
2477 let mut rng = weak_rng();
2479 let mut v = rng.gen_iter::<u64>().take(100).collect::<Vec<u64>>();
2480 v.as_mut_slice().sort();
2482 b.bytes = 100 * mem::size_of::<u64>() as u64;
2486 fn sort_random_large(b: &mut Bencher) {
2487 let mut rng = weak_rng();
2489 let mut v = rng.gen_iter::<u64>().take(10000).collect::<Vec<u64>>();
2490 v.as_mut_slice().sort();
2492 b.bytes = 10000 * mem::size_of::<u64>() as u64;
2496 fn sort_sorted(b: &mut Bencher) {
2497 let mut v = Vec::from_fn(10000, |i| i);
2501 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;
2504 type BigSortable = (u64,u64,u64,u64);
2507 fn sort_big_random_small(b: &mut Bencher) {
2508 let mut rng = weak_rng();
2510 let mut v = rng.gen_iter::<BigSortable>().take(5)
2511 .collect::<Vec<BigSortable>>();
2514 b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
2518 fn sort_big_random_medium(b: &mut Bencher) {
2519 let mut rng = weak_rng();
2521 let mut v = rng.gen_iter::<BigSortable>().take(100)
2522 .collect::<Vec<BigSortable>>();
2525 b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
2529 fn sort_big_random_large(b: &mut Bencher) {
2530 let mut rng = weak_rng();
2532 let mut v = rng.gen_iter::<BigSortable>().take(10000)
2533 .collect::<Vec<BigSortable>>();
2536 b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
2540 fn sort_big_sorted(b: &mut Bencher) {
2541 let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
2545 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;