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 = [1i, 2i, 3i];
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 = [0i, 1i, 2i];
45 let last_numbers = numbers.slice(1, 3);
46 // last_numbers is now &[1i, 2i]
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![0i, 1i, 2i];
59 // numbers is now vec![0i, 1i, 2i, 7i];
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 = [0i, 1i, 2i];
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")]
102 use core::prelude::*;
105 use core::mem::size_of;
108 use core::iter::{range_step, MultiplicativeIterator};
113 pub use core::slice::{ref_slice, mut_ref_slice, Splits, Windows};
114 pub use core::slice::{Chunks, Vector, ImmutableVector, ImmutableEqVector};
115 pub use core::slice::{ImmutableOrdVector, MutableVector, Items, MutItems};
116 pub use core::slice::{MutSplits, MutChunks};
117 pub use core::slice::{bytes, MutableCloneableVector};
119 // Functional utilities
121 #[allow(missing_doc)]
122 pub trait VectorVector<T> {
123 // FIXME #5898: calling these .concat and .connect conflicts with
124 // StrVector::con{cat,nect}, since they have generic contents.
125 /// Flattens a vector of vectors of T into a single vector of T.
126 fn concat_vec(&self) -> Vec<T>;
128 /// Concatenate a vector of vectors, placing a given separator between each.
129 fn connect_vec(&self, sep: &T) -> Vec<T>;
132 impl<'a, T: Clone, V: Vector<T>> VectorVector<T> for &'a [V] {
133 fn concat_vec(&self) -> Vec<T> {
134 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
135 let mut result = Vec::with_capacity(size);
136 for v in self.iter() {
137 result.push_all(v.as_slice())
142 fn connect_vec(&self, sep: &T) -> Vec<T> {
143 let size = self.iter().fold(0u, |acc, v| acc + v.as_slice().len());
144 let mut result = Vec::with_capacity(size + self.len());
145 let mut first = true;
146 for v in self.iter() {
147 if first { first = false } else { result.push(sep.clone()) }
148 result.push_all(v.as_slice())
154 /// An Iterator that yields the element swaps needed to produce
155 /// a sequence of all possible permutations for an indexed sequence of
156 /// elements. Each permutation is only a single swap apart.
158 /// The Steinhaus-Johnson-Trotter algorithm is used.
160 /// Generates even and odd permutations alternately.
162 /// The last generated swap is always (0, 1), and it returns the
163 /// sequence to its initial order.
164 pub struct ElementSwaps {
165 sdir: Vec<SizeDirection>,
166 /// If true, emit the last swap that returns the sequence to initial state
172 /// Create an `ElementSwaps` iterator for a sequence of `length` elements
173 pub fn new(length: uint) -> ElementSwaps {
174 // Initialize `sdir` with a direction that position should move in
175 // (all negative at the beginning) and the `size` of the
176 // element (equal to the original index).
179 sdir: range(0, length).map(|i| SizeDirection{ size: i, dir: Neg }).collect(),
185 enum Direction { Pos, Neg }
187 /// An Index and Direction together
188 struct SizeDirection {
193 impl Iterator<(uint, uint)> for ElementSwaps {
195 fn next(&mut self) -> Option<(uint, uint)> {
196 fn new_pos(i: uint, s: Direction) -> uint {
197 i + match s { Pos => 1, Neg => -1 }
200 // Find the index of the largest mobile element:
201 // The direction should point into the vector, and the
202 // swap should be with a smaller `size` element.
203 let max = self.sdir.iter().map(|&x| x).enumerate()
205 new_pos(i, sd.dir) < self.sdir.len() &&
206 self.sdir.get(new_pos(i, sd.dir)).size < sd.size)
207 .max_by(|&(_, sd)| sd.size);
210 let j = new_pos(i, sd.dir);
211 self.sdir.as_mut_slice().swap(i, j);
213 // Swap the direction of each larger SizeDirection
214 for x in self.sdir.mut_iter() {
215 if x.size > sd.size {
216 x.dir = match x.dir { Pos => Neg, Neg => Pos };
219 self.swaps_made += 1;
222 None => if self.emit_reset {
223 self.emit_reset = false;
224 if self.sdir.len() > 1 {
226 self.swaps_made += 1;
229 // Vector is of the form [] or [x], and the only permutation is itself
230 self.swaps_made += 1;
238 fn size_hint(&self) -> (uint, Option<uint>) {
239 // For a vector of size n, there are exactly n! permutations.
240 let n = range(2, self.sdir.len() + 1).product();
241 (n - self.swaps_made, Some(n - self.swaps_made))
245 /// An Iterator that uses `ElementSwaps` to iterate through
246 /// all possible permutations of a vector.
248 /// The first iteration yields a clone of the vector as it is,
249 /// then each successive element is the vector with one
252 /// Generates even and odd permutations alternately.
253 pub struct Permutations<T> {
258 impl<T: Clone> Iterator<Vec<T>> for Permutations<T> {
260 fn next(&mut self) -> Option<Vec<T>> {
261 match self.swaps.next() {
263 Some((0,0)) => Some(self.v.clone()),
265 let elt = self.v.clone();
266 self.v.as_mut_slice().swap(a, b);
273 fn size_hint(&self) -> (uint, Option<uint>) {
274 self.swaps.size_hint()
278 /// Extension methods for vector slices with cloneable elements
279 pub trait CloneableVector<T> {
280 /// Copy `self` into a new vector
281 fn to_vec(&self) -> Vec<T>;
283 /// Deprecated. Use `to_vec`
284 #[deprecated = "Replaced by `to_vec`"]
285 fn to_owned(&self) -> Vec<T> {
289 /// Convert `self` into an owned vector, not making a copy if possible.
290 fn into_vec(self) -> Vec<T>;
292 /// Deprecated. Use `into_vec`
293 #[deprecated = "Replaced by `into_vec`"]
294 fn into_owned(self) -> Vec<T> {
299 /// Extension methods for vector slices
300 impl<'a, T: Clone> CloneableVector<T> for &'a [T] {
301 /// Returns a copy of `v`.
303 fn to_vec(&self) -> Vec<T> { Vec::from_slice(*self) }
306 fn into_vec(self) -> Vec<T> { self.to_vec() }
309 /// Extension methods for vectors containing `Clone` elements.
310 pub trait ImmutableCloneableVector<T> {
311 /// Partitions the vector into two vectors `(A,B)`, where all
312 /// elements of `A` satisfy `f` and all elements of `B` do not.
313 fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>);
315 /// Create an iterator that yields every possible permutation of the
316 /// vector in succession.
317 fn permutations(self) -> Permutations<T>;
320 impl<'a,T:Clone> ImmutableCloneableVector<T> for &'a [T] {
322 fn partitioned(&self, f: |&T| -> bool) -> (Vec<T>, Vec<T>) {
323 let mut lefts = Vec::new();
324 let mut rights = Vec::new();
326 for elt in self.iter() {
328 lefts.push((*elt).clone());
330 rights.push((*elt).clone());
337 fn permutations(self) -> Permutations<T> {
339 swaps: ElementSwaps::new(self.len()),
346 fn insertion_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
347 let len = v.len() as int;
348 let buf_v = v.as_mut_ptr();
351 for i in range(1, len) {
352 // j satisfies: 0 <= j <= i;
356 let read_ptr = buf_v.offset(i) as *const T;
358 // find where to insert, we need to do strict <,
359 // rather than <=, to maintain stability.
361 // 0 <= j - 1 < len, so .offset(j - 1) is in bounds.
363 compare(&*read_ptr, &*buf_v.offset(j - 1)) == Less {
367 // shift everything to the right, to make space to
368 // insert this value.
370 // j + 1 could be `len` (for the last `i`), but in
371 // that case, `i == j` so we don't copy. The
372 // `.offset(j)` is always in bounds.
375 let tmp = ptr::read(read_ptr);
376 ptr::copy_memory(buf_v.offset(j + 1),
379 ptr::copy_nonoverlapping_memory(buf_v.offset(j),
388 fn merge_sort<T>(v: &mut [T], compare: |&T, &T| -> Ordering) {
389 // warning: this wildly uses unsafe.
390 static BASE_INSERTION: uint = 32;
391 static LARGE_INSERTION: uint = 16;
393 // FIXME #12092: smaller insertion runs seems to make sorting
394 // vectors of large elements a little faster on some platforms,
395 // but hasn't been tested/tuned extensively
396 let insertion = if size_of::<T>() <= 16 {
404 // short vectors get sorted in-place via insertion sort to avoid allocations
405 if len <= insertion {
406 insertion_sort(v, compare);
410 // allocate some memory to use as scratch memory, we keep the
411 // length 0 so we can keep shallow copies of the contents of `v`
412 // without risking the dtors running on an object twice if
414 let mut working_space = Vec::with_capacity(2 * len);
415 // these both are buffers of length `len`.
416 let mut buf_dat = working_space.as_mut_ptr();
417 let mut buf_tmp = unsafe {buf_dat.offset(len as int)};
420 let buf_v = v.as_ptr();
422 // step 1. sort short runs with insertion sort. This takes the
423 // values from `v` and sorts them into `buf_dat`, leaving that
424 // with sorted runs of length INSERTION.
426 // We could hardcode the sorting comparisons here, and we could
427 // manipulate/step the pointers themselves, rather than repeatedly
429 for start in range_step(0, len, insertion) {
431 for i in range(start, cmp::min(start + insertion, len)) {
432 // j satisfies: start <= j <= i;
433 let mut j = i as int;
436 let read_ptr = buf_v.offset(i as int);
438 // find where to insert, we need to do strict <,
439 // rather than <=, to maintain stability.
441 // start <= j - 1 < len, so .offset(j - 1) is in
443 while j > start as int &&
444 compare(&*read_ptr, &*buf_dat.offset(j - 1)) == Less {
448 // shift everything to the right, to make space to
449 // insert this value.
451 // j + 1 could be `len` (for the last `i`), but in
452 // that case, `i == j` so we don't copy. The
453 // `.offset(j)` is always in bounds.
454 ptr::copy_memory(buf_dat.offset(j + 1),
457 ptr::copy_nonoverlapping_memory(buf_dat.offset(j), read_ptr, 1);
462 // step 2. merge the sorted runs.
463 let mut width = insertion;
465 // merge the sorted runs of length `width` in `buf_dat` two at
466 // a time, placing the result in `buf_tmp`.
468 // 0 <= start <= len.
469 for start in range_step(0, len, 2 * width) {
470 // manipulate pointers directly for speed (rather than
471 // using a `for` loop with `range` and `.offset` inside
474 // the end of the first run & start of the
475 // second. Offset of `len` is defined, since this is
476 // precisely one byte past the end of the object.
477 let right_start = buf_dat.offset(cmp::min(start + width, len) as int);
478 // end of the second. Similar reasoning to the above re safety.
479 let right_end_idx = cmp::min(start + 2 * width, len);
480 let right_end = buf_dat.offset(right_end_idx as int);
482 // the pointers to the elements under consideration
483 // from the two runs.
485 // both of these are in bounds.
486 let mut left = buf_dat.offset(start as int);
487 let mut right = right_start;
489 // where we're putting the results, it is a run of
490 // length `2*width`, so we step it once for each step
491 // of either `left` or `right`. `buf_tmp` has length
492 // `len`, so these are in bounds.
493 let mut out = buf_tmp.offset(start as int);
494 let out_end = buf_tmp.offset(right_end_idx as int);
496 while out < out_end {
497 // Either the left or the right run are exhausted,
498 // so just copy the remainder from the other run
499 // and move on; this gives a huge speed-up (order
500 // of 25%) for mostly sorted vectors (the best
502 if left == right_start {
503 // the number remaining in this run.
504 let elems = (right_end as uint - right as uint) / mem::size_of::<T>();
505 ptr::copy_nonoverlapping_memory(out, &*right, elems);
507 } else if right == right_end {
508 let elems = (right_start as uint - left as uint) / mem::size_of::<T>();
509 ptr::copy_nonoverlapping_memory(out, &*left, elems);
513 // check which side is smaller, and that's the
514 // next element for the new run.
516 // `left < right_start` and `right < right_end`,
517 // so these are valid.
518 let to_copy = if compare(&*left, &*right) == Greater {
523 ptr::copy_nonoverlapping_memory(out, &*to_copy, 1);
529 mem::swap(&mut buf_dat, &mut buf_tmp);
534 // write the result to `v` in one go, so that there are never two copies
535 // of the same object in `v`.
537 ptr::copy_nonoverlapping_memory(v.as_mut_ptr(), &*buf_dat, len);
540 // increment the pointer, returning the old pointer.
542 unsafe fn step<T>(ptr: &mut *mut T) -> *mut T {
544 *ptr = ptr.offset(1);
549 /// Extension methods for vectors such that their elements are
551 pub trait MutableVectorAllocating<'a, T> {
552 /// Sort the vector, in place, using `compare` to compare
555 /// This sort is `O(n log n)` worst-case and stable, but allocates
556 /// approximately `2 * n`, where `n` is the length of `self`.
561 /// let mut v = [5i, 4, 1, 3, 2];
562 /// v.sort_by(|a, b| a.cmp(b));
563 /// assert!(v == [1, 2, 3, 4, 5]);
565 /// // reverse sorting
566 /// v.sort_by(|a, b| b.cmp(a));
567 /// assert!(v == [5, 4, 3, 2, 1]);
569 fn sort_by(self, compare: |&T, &T| -> Ordering);
572 * Consumes `src` and moves as many elements as it can into `self`
573 * from the range [start,end).
575 * Returns the number of elements copied (the shorter of self.len()
580 * * src - A mutable vector of `T`
581 * * start - The index into `src` to start copying from
582 * * end - The index into `str` to stop copying from
584 fn move_from(self, src: Vec<T>, start: uint, end: uint) -> uint;
587 impl<'a,T> MutableVectorAllocating<'a, T> for &'a mut [T] {
589 fn sort_by(self, compare: |&T, &T| -> Ordering) {
590 merge_sort(self, compare)
594 fn move_from(self, mut src: Vec<T>, start: uint, end: uint) -> uint {
595 for (a, b) in self.mut_iter().zip(src.mut_slice(start, end).mut_iter()) {
598 cmp::min(self.len(), end-start)
602 /// Methods for mutable vectors with orderable elements, such as
603 /// in-place sorting.
604 pub trait MutableOrdVector<T> {
605 /// Sort the vector, in place.
607 /// This is equivalent to `self.sort_by(|a, b| a.cmp(b))`.
612 /// let mut v = [-5i, 4, 1, -3, 2];
615 /// assert!(v == [-5i, -3, 1, 2, 4]);
619 /// Mutates the slice to the next lexicographic permutation.
621 /// Returns `true` if successful, `false` if the slice is at the last-ordered permutation.
626 /// let v = &mut [0i, 1, 2];
627 /// v.next_permutation();
628 /// assert_eq!(v, &mut [0i, 2, 1]);
629 /// v.next_permutation();
630 /// assert_eq!(v, &mut [1i, 0, 2]);
632 fn next_permutation(self) -> bool;
634 /// Mutates the slice to the previous lexicographic permutation.
636 /// Returns `true` if successful, `false` if the slice is at the first-ordered permutation.
641 /// let v = &mut [1i, 0, 2];
642 /// v.prev_permutation();
643 /// assert_eq!(v, &mut [0i, 2, 1]);
644 /// v.prev_permutation();
645 /// assert_eq!(v, &mut [0i, 1, 2]);
647 fn prev_permutation(self) -> bool;
650 impl<'a, T: Ord> MutableOrdVector<T> for &'a mut [T] {
653 self.sort_by(|a,b| a.cmp(b))
656 fn next_permutation(self) -> bool {
657 // These cases only have 1 permutation each, so we can't do anything.
658 if self.len() < 2 { return false; }
660 // Step 1: Identify the longest, rightmost weakly decreasing part of the vector
661 let mut i = self.len() - 1;
662 while i > 0 && self[i-1] >= self[i] {
666 // If that is the entire vector, this is the last-ordered permutation.
671 // Step 2: Find the rightmost element larger than the pivot (i-1)
672 let mut j = self.len() - 1;
673 while j >= i && self[j] <= self[i-1] {
677 // Step 3: Swap that element with the pivot
680 // Step 4: Reverse the (previously) weakly decreasing part
681 self.mut_slice_from(i).reverse();
686 fn prev_permutation(self) -> bool {
687 // These cases only have 1 permutation each, so we can't do anything.
688 if self.len() < 2 { return false; }
690 // Step 1: Identify the longest, rightmost weakly increasing part of the vector
691 let mut i = self.len() - 1;
692 while i > 0 && self[i-1] <= self[i] {
696 // If that is the entire vector, this is the first-ordered permutation.
701 // Step 2: Reverse the weakly increasing part
702 self.mut_slice_from(i).reverse();
704 // Step 3: Find the rightmost element equal to or bigger than the pivot (i-1)
705 let mut j = self.len() - 1;
706 while j >= i && self[j-1] < self[i-1] {
710 // Step 4: Swap that element with the pivot
717 /// Unsafe operations
719 pub use core::slice::raw::{buf_as_slice, mut_buf_as_slice};
720 pub use core::slice::raw::{shift_ptr, pop_ptr};
726 use std::default::Default;
729 use std::rand::{Rng, task_rng};
737 fn square(n: uint) -> uint { n * n }
739 fn is_odd(n: &uint) -> bool { *n % 2u == 1u }
743 // Test on-stack from_fn.
744 let mut v = Vec::from_fn(3u, square);
746 let v = v.as_slice();
747 assert_eq!(v.len(), 3u);
748 assert_eq!(v[0], 0u);
749 assert_eq!(v[1], 1u);
750 assert_eq!(v[2], 4u);
753 // Test on-heap from_fn.
754 v = Vec::from_fn(5u, square);
756 let v = v.as_slice();
757 assert_eq!(v.len(), 5u);
758 assert_eq!(v[0], 0u);
759 assert_eq!(v[1], 1u);
760 assert_eq!(v[2], 4u);
761 assert_eq!(v[3], 9u);
762 assert_eq!(v[4], 16u);
767 fn test_from_elem() {
768 // Test on-stack from_elem.
769 let mut v = Vec::from_elem(2u, 10u);
771 let v = v.as_slice();
772 assert_eq!(v.len(), 2u);
773 assert_eq!(v[0], 10u);
774 assert_eq!(v[1], 10u);
777 // Test on-heap from_elem.
778 v = Vec::from_elem(6u, 20u);
780 let v = v.as_slice();
781 assert_eq!(v[0], 20u);
782 assert_eq!(v[1], 20u);
783 assert_eq!(v[2], 20u);
784 assert_eq!(v[3], 20u);
785 assert_eq!(v[4], 20u);
786 assert_eq!(v[5], 20u);
792 let xs: [int, ..0] = [];
793 assert!(xs.is_empty());
794 assert!(![0i].is_empty());
798 fn test_len_divzero() {
801 let v1 : &[Z] = &[[]];
802 let v2 : &[Z] = &[[], []];
803 assert_eq!(mem::size_of::<Z>(), 0);
804 assert_eq!(v0.len(), 0);
805 assert_eq!(v1.len(), 1);
806 assert_eq!(v2.len(), 2);
811 let mut a = vec![11i];
812 assert_eq!(a.as_slice().get(1), None);
814 assert_eq!(a.as_slice().get(1).unwrap(), &12);
815 a = vec![11i, 12, 13];
816 assert_eq!(a.as_slice().get(1).unwrap(), &12);
822 assert_eq!(a.as_slice().head(), None);
824 assert_eq!(a.as_slice().head().unwrap(), &11);
826 assert_eq!(a.as_slice().head().unwrap(), &11);
831 let mut a = vec![11i];
832 assert_eq!(a.tail(), &[]);
834 assert_eq!(a.tail(), &[12]);
839 fn test_tail_empty() {
840 let a: Vec<int> = vec![];
846 let mut a = vec![11i, 12, 13];
847 assert_eq!(a.tailn(0), &[11, 12, 13]);
848 a = vec![11i, 12, 13];
849 assert_eq!(a.tailn(2), &[13]);
854 fn test_tailn_empty() {
855 let a: Vec<int> = vec![];
861 let mut a = vec![11i];
862 assert_eq!(a.init(), &[]);
864 assert_eq!(a.init(), &[11]);
869 fn test_init_empty() {
870 let a: Vec<int> = vec![];
876 let mut a = vec![11i, 12, 13];
877 assert_eq!(a.as_slice().initn(0), &[11, 12, 13]);
878 a = vec![11i, 12, 13];
879 assert_eq!(a.as_slice().initn(2), &[11]);
884 fn test_initn_empty() {
885 let a: Vec<int> = vec![];
886 a.as_slice().initn(2);
892 assert_eq!(a.as_slice().last(), None);
894 assert_eq!(a.as_slice().last().unwrap(), &11);
896 assert_eq!(a.as_slice().last().unwrap(), &12);
901 // Test fixed length vector.
902 let vec_fixed = [1i, 2, 3, 4];
903 let v_a = vec_fixed.slice(1u, vec_fixed.len()).to_vec();
904 assert_eq!(v_a.len(), 3u);
905 let v_a = v_a.as_slice();
906 assert_eq!(v_a[0], 2);
907 assert_eq!(v_a[1], 3);
908 assert_eq!(v_a[2], 4);
911 let vec_stack = &[1i, 2, 3];
912 let v_b = vec_stack.slice(1u, 3u).to_vec();
913 assert_eq!(v_b.len(), 2u);
914 let v_b = v_b.as_slice();
915 assert_eq!(v_b[0], 2);
916 assert_eq!(v_b[1], 3);
919 let vec_unique = vec![1i, 2, 3, 4, 5, 6];
920 let v_d = vec_unique.slice(1u, 6u).to_vec();
921 assert_eq!(v_d.len(), 5u);
922 let v_d = v_d.as_slice();
923 assert_eq!(v_d[0], 2);
924 assert_eq!(v_d[1], 3);
925 assert_eq!(v_d[2], 4);
926 assert_eq!(v_d[3], 5);
927 assert_eq!(v_d[4], 6);
931 fn test_slice_from() {
932 let vec = &[1i, 2, 3, 4];
933 assert_eq!(vec.slice_from(0), vec);
934 assert_eq!(vec.slice_from(2), &[3, 4]);
935 assert_eq!(vec.slice_from(4), &[]);
940 let vec = &[1i, 2, 3, 4];
941 assert_eq!(vec.slice_to(4), vec);
942 assert_eq!(vec.slice_to(2), &[1, 2]);
943 assert_eq!(vec.slice_to(0), &[]);
949 let mut v = vec![5i];
951 assert_eq!(v.len(), 0);
952 assert_eq!(e, Some(5));
960 fn test_swap_remove() {
961 let mut v = vec![1i, 2, 3, 4, 5];
962 let mut e = v.swap_remove(0);
963 assert_eq!(e, Some(1));
964 assert_eq!(v, vec![5i, 2, 3, 4]);
965 e = v.swap_remove(3);
966 assert_eq!(e, Some(4));
967 assert_eq!(v, vec![5i, 2, 3]);
969 e = v.swap_remove(3);
971 assert_eq!(v, vec![5i, 2, 3]);
975 fn test_swap_remove_noncopyable() {
976 // Tests that we don't accidentally run destructors twice.
977 let mut v = vec![rt::exclusive::Exclusive::new(()),
978 rt::exclusive::Exclusive::new(()),
979 rt::exclusive::Exclusive::new(())];
980 let mut _e = v.swap_remove(0);
981 assert_eq!(v.len(), 2);
982 _e = v.swap_remove(1);
983 assert_eq!(v.len(), 1);
984 _e = v.swap_remove(0);
985 assert_eq!(v.len(), 0);
990 // Test on-stack push().
993 assert_eq!(v.len(), 1u);
994 assert_eq!(v.as_slice()[0], 1);
996 // Test on-heap push().
998 assert_eq!(v.len(), 2u);
999 assert_eq!(v.as_slice()[0], 1);
1000 assert_eq!(v.as_slice()[1], 2);
1005 // Test on-stack grow().
1009 let v = v.as_slice();
1010 assert_eq!(v.len(), 2u);
1011 assert_eq!(v[0], 1);
1012 assert_eq!(v[1], 1);
1015 // Test on-heap grow().
1018 let v = v.as_slice();
1019 assert_eq!(v.len(), 5u);
1020 assert_eq!(v[0], 1);
1021 assert_eq!(v[1], 1);
1022 assert_eq!(v[2], 2);
1023 assert_eq!(v[3], 2);
1024 assert_eq!(v[4], 2);
1031 v.grow_fn(3u, square);
1032 let v = v.as_slice();
1033 assert_eq!(v.len(), 3u);
1034 assert_eq!(v[0], 0u);
1035 assert_eq!(v[1], 1u);
1036 assert_eq!(v[2], 4u);
1040 fn test_grow_set() {
1041 let mut v = vec![1i, 2, 3];
1042 v.grow_set(4u, &4, 5);
1043 let v = v.as_slice();
1044 assert_eq!(v.len(), 5u);
1045 assert_eq!(v[0], 1);
1046 assert_eq!(v[1], 2);
1047 assert_eq!(v[2], 3);
1048 assert_eq!(v[3], 4);
1049 assert_eq!(v[4], 5);
1053 fn test_truncate() {
1054 let mut v = vec![box 6i,box 5,box 4];
1056 let v = v.as_slice();
1057 assert_eq!(v.len(), 1);
1058 assert_eq!(*(v[0]), 6);
1059 // If the unsafe block didn't drop things properly, we blow up here.
1064 let mut v = vec![box 6i,box 5,box 4];
1066 assert_eq!(v.len(), 0);
1067 // If the unsafe block didn't drop things properly, we blow up here.
1072 fn case(a: Vec<uint>, b: Vec<uint>) {
1077 case(vec![], vec![]);
1078 case(vec![1u], vec![1]);
1079 case(vec![1u,1], vec![1]);
1080 case(vec![1u,2,3], vec![1,2,3]);
1081 case(vec![1u,1,2,3], vec![1,2,3]);
1082 case(vec![1u,2,2,3], vec![1,2,3]);
1083 case(vec![1u,2,3,3], vec![1,2,3]);
1084 case(vec![1u,1,2,2,2,3,3], vec![1,2,3]);
1088 fn test_dedup_unique() {
1089 let mut v0 = vec![box 1i, box 1, box 2, box 3];
1091 let mut v1 = vec![box 1i, box 2, box 2, box 3];
1093 let mut v2 = vec![box 1i, box 2, box 3, box 3];
1096 * If the boxed pointers were leaked or otherwise misused, valgrind
1097 * and/or rustrt should raise errors.
1102 fn test_dedup_shared() {
1103 let mut v0 = vec![box 1i, box 1, box 2, box 3];
1105 let mut v1 = vec![box 1i, box 2, box 2, box 3];
1107 let mut v2 = vec![box 1i, box 2, box 3, box 3];
1110 * If the pointers were leaked or otherwise misused, valgrind and/or
1111 * rustrt should raise errors.
1117 let mut v = vec![1u, 2, 3, 4, 5];
1119 assert_eq!(v, vec![1u, 3, 5]);
1123 fn test_element_swaps() {
1124 let mut v = [1i, 2, 3];
1125 for (i, (a, b)) in ElementSwaps::new(v.len()).enumerate() {
1128 0 => assert!(v == [1, 3, 2]),
1129 1 => assert!(v == [3, 1, 2]),
1130 2 => assert!(v == [3, 2, 1]),
1131 3 => assert!(v == [2, 3, 1]),
1132 4 => assert!(v == [2, 1, 3]),
1133 5 => assert!(v == [1, 2, 3]),
1140 fn test_permutations() {
1142 let v: [int, ..0] = [];
1143 let mut it = v.permutations();
1144 let (min_size, max_opt) = it.size_hint();
1145 assert_eq!(min_size, 1);
1146 assert_eq!(max_opt.unwrap(), 1);
1147 assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1148 assert_eq!(it.next(), None);
1151 let v = ["Hello".to_string()];
1152 let mut it = v.permutations();
1153 let (min_size, max_opt) = it.size_hint();
1154 assert_eq!(min_size, 1);
1155 assert_eq!(max_opt.unwrap(), 1);
1156 assert_eq!(it.next(), Some(v.as_slice().to_vec()));
1157 assert_eq!(it.next(), None);
1161 let mut it = v.permutations();
1162 let (min_size, max_opt) = it.size_hint();
1163 assert_eq!(min_size, 3*2);
1164 assert_eq!(max_opt.unwrap(), 3*2);
1165 assert_eq!(it.next(), Some(vec![1,2,3]));
1166 assert_eq!(it.next(), Some(vec![1,3,2]));
1167 assert_eq!(it.next(), Some(vec![3,1,2]));
1168 let (min_size, max_opt) = it.size_hint();
1169 assert_eq!(min_size, 3);
1170 assert_eq!(max_opt.unwrap(), 3);
1171 assert_eq!(it.next(), Some(vec![3,2,1]));
1172 assert_eq!(it.next(), Some(vec![2,3,1]));
1173 assert_eq!(it.next(), Some(vec![2,1,3]));
1174 assert_eq!(it.next(), None);
1177 // check that we have N! permutations
1178 let v = ['A', 'B', 'C', 'D', 'E', 'F'];
1180 let mut it = v.permutations();
1181 let (min_size, max_opt) = it.size_hint();
1185 assert_eq!(amt, it.swaps.swaps_made);
1186 assert_eq!(amt, min_size);
1187 assert_eq!(amt, 2 * 3 * 4 * 5 * 6);
1188 assert_eq!(amt, max_opt.unwrap());
1193 fn test_lexicographic_permutations() {
1194 let v : &mut[int] = &mut[1i, 2, 3, 4, 5];
1195 assert!(v.prev_permutation() == false);
1196 assert!(v.next_permutation());
1197 assert_eq!(v, &mut[1, 2, 3, 5, 4]);
1198 assert!(v.prev_permutation());
1199 assert_eq!(v, &mut[1, 2, 3, 4, 5]);
1200 assert!(v.next_permutation());
1201 assert!(v.next_permutation());
1202 assert_eq!(v, &mut[1, 2, 4, 3, 5]);
1203 assert!(v.next_permutation());
1204 assert_eq!(v, &mut[1, 2, 4, 5, 3]);
1206 let v : &mut[int] = &mut[1i, 0, 0, 0];
1207 assert!(v.next_permutation() == false);
1208 assert!(v.prev_permutation());
1209 assert_eq!(v, &mut[0, 1, 0, 0]);
1210 assert!(v.prev_permutation());
1211 assert_eq!(v, &mut[0, 0, 1, 0]);
1212 assert!(v.prev_permutation());
1213 assert_eq!(v, &mut[0, 0, 0, 1]);
1214 assert!(v.prev_permutation() == false);
1218 fn test_lexicographic_permutations_empty_and_short() {
1219 let empty : &mut[int] = &mut[];
1220 assert!(empty.next_permutation() == false);
1221 assert_eq!(empty, &mut[]);
1222 assert!(empty.prev_permutation() == false);
1223 assert_eq!(empty, &mut[]);
1225 let one_elem : &mut[int] = &mut[4i];
1226 assert!(one_elem.prev_permutation() == false);
1227 assert_eq!(one_elem, &mut[4]);
1228 assert!(one_elem.next_permutation() == false);
1229 assert_eq!(one_elem, &mut[4]);
1231 let two_elem : &mut[int] = &mut[1i, 2];
1232 assert!(two_elem.prev_permutation() == false);
1233 assert_eq!(two_elem, &mut[1, 2]);
1234 assert!(two_elem.next_permutation());
1235 assert_eq!(two_elem, &mut[2, 1]);
1236 assert!(two_elem.next_permutation() == false);
1237 assert_eq!(two_elem, &mut[2, 1]);
1238 assert!(two_elem.prev_permutation());
1239 assert_eq!(two_elem, &mut[1, 2]);
1240 assert!(two_elem.prev_permutation() == false);
1241 assert_eq!(two_elem, &mut[1, 2]);
1245 fn test_position_elem() {
1246 assert!([].position_elem(&1i).is_none());
1248 let v1 = vec![1i, 2, 3, 3, 2, 5];
1249 assert_eq!(v1.as_slice().position_elem(&1), Some(0u));
1250 assert_eq!(v1.as_slice().position_elem(&2), Some(1u));
1251 assert_eq!(v1.as_slice().position_elem(&5), Some(5u));
1252 assert!(v1.as_slice().position_elem(&4).is_none());
1256 fn test_bsearch_elem() {
1257 assert_eq!([1i,2,3,4,5].bsearch_elem(&5), Some(4));
1258 assert_eq!([1i,2,3,4,5].bsearch_elem(&4), Some(3));
1259 assert_eq!([1i,2,3,4,5].bsearch_elem(&3), Some(2));
1260 assert_eq!([1i,2,3,4,5].bsearch_elem(&2), Some(1));
1261 assert_eq!([1i,2,3,4,5].bsearch_elem(&1), Some(0));
1263 assert_eq!([2i,4,6,8,10].bsearch_elem(&1), None);
1264 assert_eq!([2i,4,6,8,10].bsearch_elem(&5), None);
1265 assert_eq!([2i,4,6,8,10].bsearch_elem(&4), Some(1));
1266 assert_eq!([2i,4,6,8,10].bsearch_elem(&10), Some(4));
1268 assert_eq!([2i,4,6,8].bsearch_elem(&1), None);
1269 assert_eq!([2i,4,6,8].bsearch_elem(&5), None);
1270 assert_eq!([2i,4,6,8].bsearch_elem(&4), Some(1));
1271 assert_eq!([2i,4,6,8].bsearch_elem(&8), Some(3));
1273 assert_eq!([2i,4,6].bsearch_elem(&1), None);
1274 assert_eq!([2i,4,6].bsearch_elem(&5), None);
1275 assert_eq!([2i,4,6].bsearch_elem(&4), Some(1));
1276 assert_eq!([2i,4,6].bsearch_elem(&6), Some(2));
1278 assert_eq!([2i,4].bsearch_elem(&1), None);
1279 assert_eq!([2i,4].bsearch_elem(&5), None);
1280 assert_eq!([2i,4].bsearch_elem(&2), Some(0));
1281 assert_eq!([2i,4].bsearch_elem(&4), Some(1));
1283 assert_eq!([2i].bsearch_elem(&1), None);
1284 assert_eq!([2i].bsearch_elem(&5), None);
1285 assert_eq!([2i].bsearch_elem(&2), Some(0));
1287 assert_eq!([].bsearch_elem(&1i), None);
1288 assert_eq!([].bsearch_elem(&5i), None);
1290 assert!([1i,1,1,1,1].bsearch_elem(&1) != None);
1291 assert!([1i,1,1,1,2].bsearch_elem(&1) != None);
1292 assert!([1i,1,1,2,2].bsearch_elem(&1) != None);
1293 assert!([1i,1,2,2,2].bsearch_elem(&1) != None);
1294 assert_eq!([1i,2,2,2,2].bsearch_elem(&1), Some(0));
1296 assert_eq!([1i,2,3,4,5].bsearch_elem(&6), None);
1297 assert_eq!([1i,2,3,4,5].bsearch_elem(&0), None);
1302 let mut v: Vec<int> = vec![10i, 20];
1303 assert_eq!(*v.get(0), 10);
1304 assert_eq!(*v.get(1), 20);
1306 assert_eq!(*v.get(0), 20);
1307 assert_eq!(*v.get(1), 10);
1309 let mut v3: Vec<int> = vec![];
1311 assert!(v3.is_empty());
1316 for len in range(4u, 25) {
1317 for _ in range(0i, 100) {
1318 let mut v = task_rng().gen_iter::<uint>().take(len)
1319 .collect::<Vec<uint>>();
1320 let mut v1 = v.clone();
1322 v.as_mut_slice().sort();
1323 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1325 v1.as_mut_slice().sort_by(|a, b| a.cmp(b));
1326 assert!(v1.as_slice().windows(2).all(|w| w[0] <= w[1]));
1328 v1.as_mut_slice().sort_by(|a, b| b.cmp(a));
1329 assert!(v1.as_slice().windows(2).all(|w| w[0] >= w[1]));
1333 // shouldn't fail/crash
1334 let mut v: [uint, .. 0] = [];
1337 let mut v = [0xDEADBEEFu];
1339 assert!(v == [0xDEADBEEF]);
1343 fn test_sort_stability() {
1344 for len in range(4i, 25) {
1345 for _ in range(0u, 10) {
1346 let mut counts = [0i, .. 10];
1348 // create a vector like [(6, 1), (5, 1), (6, 2), ...],
1349 // where the first item of each tuple is random, but
1350 // the second item represents which occurrence of that
1351 // number this element is, i.e. the second elements
1352 // will occur in sorted order.
1353 let mut v = range(0, len).map(|_| {
1354 let n = task_rng().gen::<uint>() % 10;
1357 }).collect::<Vec<(uint, int)>>();
1359 // only sort on the first element, so an unstable sort
1360 // may mix up the counts.
1361 v.sort_by(|&(a,_), &(b,_)| a.cmp(&b));
1363 // this comparison includes the count (the second item
1364 // of the tuple), so elements with equal first items
1365 // will need to be ordered with increasing
1366 // counts... i.e. exactly asserting that this sort is
1368 assert!(v.as_slice().windows(2).all(|w| w[0] <= w[1]));
1374 fn test_partition() {
1375 assert_eq!((vec![]).partition(|x: &int| *x < 3), (vec![], vec![]));
1376 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1377 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1378 assert_eq!((vec![1i, 2, 3]).partition(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1382 fn test_partitioned() {
1383 assert_eq!(([]).partitioned(|x: &int| *x < 3), (vec![], vec![]));
1384 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 4), (vec![1, 2, 3], vec![]));
1385 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 2), (vec![1], vec![2, 3]));
1386 assert_eq!(([1i, 2, 3]).partitioned(|x: &int| *x < 0), (vec![], vec![1, 2, 3]));
1391 let v: [Vec<int>, ..0] = [];
1392 assert_eq!(v.concat_vec(), vec![]);
1393 assert_eq!([vec![1i], vec![2i,3i]].concat_vec(), vec![1, 2, 3]);
1395 assert_eq!([&[1i], &[2i,3i]].concat_vec(), vec![1, 2, 3]);
1400 let v: [Vec<int>, ..0] = [];
1401 assert_eq!(v.connect_vec(&0), vec![]);
1402 assert_eq!([vec![1i], vec![2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
1403 assert_eq!([vec![1i], vec![2i], vec![3i]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
1405 assert_eq!([&[1i], &[2i, 3]].connect_vec(&0), vec![1, 0, 2, 3]);
1406 assert_eq!([&[1i], &[2i], &[3]].connect_vec(&0), vec![1, 0, 2, 0, 3]);
1411 let mut x = vec![1i, 2, 3];
1412 assert_eq!(x.shift(), Some(1));
1413 assert_eq!(&x, &vec![2i, 3]);
1414 assert_eq!(x.shift(), Some(2));
1415 assert_eq!(x.shift(), Some(3));
1416 assert_eq!(x.shift(), None);
1417 assert_eq!(x.len(), 0);
1422 let mut x = vec![1i, 2, 3];
1424 assert_eq!(x, vec![0, 1, 2, 3]);
1429 let mut a = vec![1i, 2, 4];
1431 assert_eq!(a, vec![1, 2, 3, 4]);
1433 let mut a = vec![1i, 2, 3];
1435 assert_eq!(a, vec![0, 1, 2, 3]);
1437 let mut a = vec![1i, 2, 3];
1439 assert_eq!(a, vec![1, 2, 3, 4]);
1443 assert_eq!(a, vec![1]);
1448 fn test_insert_oob() {
1449 let mut a = vec![1i, 2, 3];
1455 let mut a = vec![1i,2,3,4];
1457 assert_eq!(a.remove(2), Some(3));
1458 assert_eq!(a, vec![1i,2,4]);
1460 assert_eq!(a.remove(2), Some(4));
1461 assert_eq!(a, vec![1i,2]);
1463 assert_eq!(a.remove(2), None);
1464 assert_eq!(a, vec![1i,2]);
1466 assert_eq!(a.remove(0), Some(1));
1467 assert_eq!(a, vec![2i]);
1469 assert_eq!(a.remove(0), Some(2));
1470 assert_eq!(a, vec![]);
1472 assert_eq!(a.remove(0), None);
1473 assert_eq!(a.remove(10), None);
1477 fn test_capacity() {
1478 let mut v = vec![0u64];
1479 v.reserve_exact(10u);
1480 assert_eq!(v.capacity(), 10u);
1481 let mut v = vec![0u32];
1482 v.reserve_exact(10u);
1483 assert_eq!(v.capacity(), 10u);
1488 let v = vec![1i, 2, 3, 4, 5];
1489 let v = v.slice(1u, 3u);
1490 assert_eq!(v.len(), 2u);
1491 assert_eq!(v[0], 2);
1492 assert_eq!(v[1], 3);
1498 fn test_from_fn_fail() {
1499 Vec::from_fn(100, |v| {
1500 if v == 50 { fail!() }
1507 fn test_from_elem_fail() {
1511 boxes: (Box<int>, Rc<int>)
1515 fn clone(&self) -> S {
1516 self.f.set(self.f.get() + 1);
1517 if self.f.get() == 10 { fail!() }
1518 S { f: self.f, boxes: self.boxes.clone() }
1522 let s = S { f: Cell::new(0), boxes: (box 0, Rc::new(0)) };
1523 let _ = Vec::from_elem(100, s);
1528 fn test_grow_fn_fail() {
1530 v.grow_fn(100, |i| {
1534 (box 0i, Rc::new(0i))
1540 fn test_permute_fail() {
1541 let v = [(box 0i, Rc::new(0i)), (box 0i, Rc::new(0i)),
1542 (box 0i, Rc::new(0i)), (box 0i, Rc::new(0i))];
1544 for _ in v.permutations() {
1554 fn test_copy_memory_oob() {
1556 let mut a = [1i, 2, 3, 4];
1557 let b = [1i, 2, 3, 4, 5];
1563 fn test_total_ord() {
1564 [1i, 2, 3, 4].cmp(& &[1, 2, 3]) == Greater;
1565 [1i, 2, 3].cmp(& &[1, 2, 3, 4]) == Less;
1566 [1i, 2, 3, 4].cmp(& &[1, 2, 3, 4]) == Equal;
1567 [1i, 2, 3, 4, 5, 5, 5, 5].cmp(& &[1, 2, 3, 4, 5, 6]) == Less;
1568 [2i, 2].cmp(& &[1, 2, 3, 4]) == Greater;
1572 fn test_iterator() {
1573 let xs = [1i, 2, 5, 10, 11];
1574 let mut it = xs.iter();
1575 assert_eq!(it.size_hint(), (5, Some(5)));
1576 assert_eq!(it.next().unwrap(), &1);
1577 assert_eq!(it.size_hint(), (4, Some(4)));
1578 assert_eq!(it.next().unwrap(), &2);
1579 assert_eq!(it.size_hint(), (3, Some(3)));
1580 assert_eq!(it.next().unwrap(), &5);
1581 assert_eq!(it.size_hint(), (2, Some(2)));
1582 assert_eq!(it.next().unwrap(), &10);
1583 assert_eq!(it.size_hint(), (1, Some(1)));
1584 assert_eq!(it.next().unwrap(), &11);
1585 assert_eq!(it.size_hint(), (0, Some(0)));
1586 assert!(it.next().is_none());
1590 fn test_random_access_iterator() {
1591 let xs = [1i, 2, 5, 10, 11];
1592 let mut it = xs.iter();
1594 assert_eq!(it.indexable(), 5);
1595 assert_eq!(it.idx(0).unwrap(), &1);
1596 assert_eq!(it.idx(2).unwrap(), &5);
1597 assert_eq!(it.idx(4).unwrap(), &11);
1598 assert!(it.idx(5).is_none());
1600 assert_eq!(it.next().unwrap(), &1);
1601 assert_eq!(it.indexable(), 4);
1602 assert_eq!(it.idx(0).unwrap(), &2);
1603 assert_eq!(it.idx(3).unwrap(), &11);
1604 assert!(it.idx(4).is_none());
1606 assert_eq!(it.next().unwrap(), &2);
1607 assert_eq!(it.indexable(), 3);
1608 assert_eq!(it.idx(1).unwrap(), &10);
1609 assert!(it.idx(3).is_none());
1611 assert_eq!(it.next().unwrap(), &5);
1612 assert_eq!(it.indexable(), 2);
1613 assert_eq!(it.idx(1).unwrap(), &11);
1615 assert_eq!(it.next().unwrap(), &10);
1616 assert_eq!(it.indexable(), 1);
1617 assert_eq!(it.idx(0).unwrap(), &11);
1618 assert!(it.idx(1).is_none());
1620 assert_eq!(it.next().unwrap(), &11);
1621 assert_eq!(it.indexable(), 0);
1622 assert!(it.idx(0).is_none());
1624 assert!(it.next().is_none());
1628 fn test_iter_size_hints() {
1629 let mut xs = [1i, 2, 5, 10, 11];
1630 assert_eq!(xs.iter().size_hint(), (5, Some(5)));
1631 assert_eq!(xs.mut_iter().size_hint(), (5, Some(5)));
1635 fn test_iter_clone() {
1636 let xs = [1i, 2, 5];
1637 let mut it = xs.iter();
1639 let mut jt = it.clone();
1640 assert_eq!(it.next(), jt.next());
1641 assert_eq!(it.next(), jt.next());
1642 assert_eq!(it.next(), jt.next());
1646 fn test_mut_iterator() {
1647 let mut xs = [1i, 2, 3, 4, 5];
1648 for x in xs.mut_iter() {
1651 assert!(xs == [2, 3, 4, 5, 6])
1655 fn test_rev_iterator() {
1657 let xs = [1i, 2, 5, 10, 11];
1658 let ys = [11, 10, 5, 2, 1];
1660 for &x in xs.iter().rev() {
1661 assert_eq!(x, ys[i]);
1668 fn test_mut_rev_iterator() {
1669 let mut xs = [1u, 2, 3, 4, 5];
1670 for (i,x) in xs.mut_iter().rev().enumerate() {
1673 assert!(xs == [5, 5, 5, 5, 5])
1677 fn test_move_iterator() {
1678 let xs = vec![1u,2,3,4,5];
1679 assert_eq!(xs.move_iter().fold(0, |a: uint, b: uint| 10*a + b), 12345);
1683 fn test_move_rev_iterator() {
1684 let xs = vec![1u,2,3,4,5];
1685 assert_eq!(xs.move_iter().rev().fold(0, |a: uint, b: uint| 10*a + b), 54321);
1689 fn test_splitator() {
1690 let xs = &[1i,2,3,4,5];
1692 assert_eq!(xs.split(|x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1693 &[&[1], &[3], &[5]]);
1694 assert_eq!(xs.split(|x| *x == 1).collect::<Vec<&[int]>>().as_slice(),
1695 &[&[], &[2,3,4,5]]);
1696 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(),
1697 &[&[1,2,3,4], &[]]);
1698 assert_eq!(xs.split(|x| *x == 10).collect::<Vec<&[int]>>().as_slice(),
1700 assert_eq!(xs.split(|_| true).collect::<Vec<&[int]>>().as_slice(),
1701 &[&[], &[], &[], &[], &[], &[]]);
1703 let xs: &[int] = &[];
1704 assert_eq!(xs.split(|x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1708 fn test_splitnator() {
1709 let xs = &[1i,2,3,4,5];
1711 assert_eq!(xs.splitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1713 assert_eq!(xs.splitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1715 assert_eq!(xs.splitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
1716 &[&[], &[], &[], &[4,5]]);
1718 let xs: &[int] = &[];
1719 assert_eq!(xs.splitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1723 fn test_rsplitator() {
1724 let xs = &[1i,2,3,4,5];
1726 assert_eq!(xs.split(|x| *x % 2 == 0).rev().collect::<Vec<&[int]>>().as_slice(),
1727 &[&[5], &[3], &[1]]);
1728 assert_eq!(xs.split(|x| *x == 1).rev().collect::<Vec<&[int]>>().as_slice(),
1729 &[&[2,3,4,5], &[]]);
1730 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(),
1731 &[&[], &[1,2,3,4]]);
1732 assert_eq!(xs.split(|x| *x == 10).rev().collect::<Vec<&[int]>>().as_slice(),
1735 let xs: &[int] = &[];
1736 assert_eq!(xs.split(|x| *x == 5).rev().collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1740 fn test_rsplitnator() {
1741 let xs = &[1,2,3,4,5];
1743 assert_eq!(xs.rsplitn(0, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1745 assert_eq!(xs.rsplitn(1, |x| *x % 2 == 0).collect::<Vec<&[int]>>().as_slice(),
1747 assert_eq!(xs.rsplitn(3, |_| true).collect::<Vec<&[int]>>().as_slice(),
1748 &[&[], &[], &[], &[1,2]]);
1750 let xs: &[int] = &[];
1751 assert_eq!(xs.rsplitn(1, |x| *x == 5).collect::<Vec<&[int]>>().as_slice(), &[&[]]);
1755 fn test_windowsator() {
1756 let v = &[1i,2,3,4];
1758 assert_eq!(v.windows(2).collect::<Vec<&[int]>>().as_slice(), &[&[1,2], &[2,3], &[3,4]]);
1759 assert_eq!(v.windows(3).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3], &[2,3,4]]);
1760 assert!(v.windows(6).next().is_none());
1765 fn test_windowsator_0() {
1766 let v = &[1i,2,3,4];
1767 let _it = v.windows(0);
1771 fn test_chunksator() {
1772 let v = &[1i,2,3,4,5];
1774 assert_eq!(v.chunks(2).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2], &[3,4], &[5]]);
1775 assert_eq!(v.chunks(3).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3], &[4,5]]);
1776 assert_eq!(v.chunks(6).collect::<Vec<&[int]>>().as_slice(), &[&[1i,2,3,4,5]]);
1778 assert_eq!(v.chunks(2).rev().collect::<Vec<&[int]>>().as_slice(), &[&[5i], &[3,4], &[1,2]]);
1779 let mut it = v.chunks(2);
1780 assert_eq!(it.indexable(), 3);
1781 assert_eq!(it.idx(0).unwrap(), &[1,2]);
1782 assert_eq!(it.idx(1).unwrap(), &[3,4]);
1783 assert_eq!(it.idx(2).unwrap(), &[5]);
1784 assert_eq!(it.idx(3), None);
1789 fn test_chunksator_0() {
1790 let v = &[1i,2,3,4];
1791 let _it = v.chunks(0);
1795 fn test_move_from() {
1796 let mut a = [1i,2,3,4,5];
1797 let b = vec![6i,7,8];
1798 assert_eq!(a.move_from(b, 0, 3), 3);
1799 assert!(a == [6i,7,8,4,5]);
1800 let mut a = [7i,2,8,1];
1801 let b = vec![3i,1,4,1,5,9];
1802 assert_eq!(a.move_from(b, 0, 6), 4);
1803 assert!(a == [3i,1,4,1]);
1804 let mut a = [1i,2,3,4];
1805 let b = vec![5i,6,7,8,9,0];
1806 assert_eq!(a.move_from(b, 2, 3), 1);
1807 assert!(a == [7i,2,3,4]);
1808 let mut a = [1i,2,3,4,5];
1809 let b = vec![5i,6,7,8,9,0];
1810 assert_eq!(a.mut_slice(2,4).move_from(b,1,6), 2);
1811 assert!(a == [1i,2,6,7,5]);
1815 fn test_copy_from() {
1816 let mut a = [1i,2,3,4,5];
1818 assert_eq!(a.copy_from(b), 3);
1819 assert!(a == [6i,7,8,4,5]);
1820 let mut c = [7i,2,8,1];
1821 let d = [3i,1,4,1,5,9];
1822 assert_eq!(c.copy_from(d), 4);
1823 assert!(c == [3i,1,4,1]);
1827 fn test_reverse_part() {
1828 let mut values = [1i,2,3,4,5];
1829 values.mut_slice(1, 4).reverse();
1830 assert!(values == [1,4,3,2,5]);
1835 macro_rules! test_show_vec(
1836 ($x:expr, $x_str:expr) => ({
1837 let (x, x_str) = ($x, $x_str);
1838 assert_eq!(format!("{}", x), x_str);
1839 assert_eq!(format!("{}", x.as_slice()), x_str);
1842 let empty: Vec<int> = vec![];
1843 test_show_vec!(empty, "[]".to_string());
1844 test_show_vec!(vec![1i], "[1]".to_string());
1845 test_show_vec!(vec![1i, 2, 3], "[1, 2, 3]".to_string());
1846 test_show_vec!(vec![vec![], vec![1u], vec![1u, 1u]],
1847 "[[], [1], [1, 1]]".to_string());
1849 let empty_mut: &mut [int] = &mut[];
1850 test_show_vec!(empty_mut, "[]".to_string());
1851 test_show_vec!(&mut[1i], "[1]".to_string());
1852 test_show_vec!(&mut[1i, 2, 3], "[1, 2, 3]".to_string());
1853 test_show_vec!(&mut[&mut[], &mut[1u], &mut[1u, 1u]],
1854 "[[], [1], [1, 1]]".to_string());
1858 fn test_vec_default() {
1861 let v: $ty = Default::default();
1862 assert!(v.is_empty());
1871 fn test_bytes_set_memory() {
1872 use slice::bytes::MutableByteVector;
1873 let mut values = [1u8,2,3,4,5];
1874 values.mut_slice(0,5).set_memory(0xAB);
1875 assert!(values == [0xAB, 0xAB, 0xAB, 0xAB, 0xAB]);
1876 values.mut_slice(2,4).set_memory(0xFF);
1877 assert!(values == [0xAB, 0xAB, 0xFF, 0xFF, 0xAB]);
1882 fn test_overflow_does_not_cause_segfault() {
1884 v.reserve_exact(-1);
1891 fn test_overflow_does_not_cause_segfault_managed() {
1892 let mut v = vec![Rc::new(1i)];
1893 v.reserve_exact(-1);
1894 v.push(Rc::new(2i));
1898 fn test_mut_split_at() {
1899 let mut values = [1u8,2,3,4,5];
1901 let (left, right) = values.mut_split_at(2);
1902 assert!(left.slice(0, left.len()) == [1, 2]);
1903 for p in left.mut_iter() {
1907 assert!(right.slice(0, right.len()) == [3, 4, 5]);
1908 for p in right.mut_iter() {
1913 assert!(values == [2, 3, 5, 6, 7]);
1916 #[deriving(Clone, PartialEq)]
1920 fn test_iter_zero_sized() {
1921 let mut v = vec![Foo, Foo, Foo];
1922 assert_eq!(v.len(), 3);
1931 for f in v.slice(1, 3).iter() {
1937 for f in v.mut_iter() {
1943 for f in v.move_iter() {
1947 assert_eq!(cnt, 11);
1949 let xs: [Foo, ..3] = [Foo, Foo, Foo];
1951 for f in xs.iter() {
1959 fn test_shrink_to_fit() {
1960 let mut xs = vec![0, 1, 2, 3];
1961 for i in range(4i, 100) {
1964 assert_eq!(xs.capacity(), 128);
1966 assert_eq!(xs.capacity(), 100);
1967 assert_eq!(xs, range(0i, 100i).collect::<Vec<_>>());
1971 fn test_starts_with() {
1972 assert!(b"foobar".starts_with(b"foo"));
1973 assert!(!b"foobar".starts_with(b"oob"));
1974 assert!(!b"foobar".starts_with(b"bar"));
1975 assert!(!b"foo".starts_with(b"foobar"));
1976 assert!(!b"bar".starts_with(b"foobar"));
1977 assert!(b"foobar".starts_with(b"foobar"));
1978 let empty: &[u8] = [];
1979 assert!(empty.starts_with(empty));
1980 assert!(!empty.starts_with(b"foo"));
1981 assert!(b"foobar".starts_with(empty));
1985 fn test_ends_with() {
1986 assert!(b"foobar".ends_with(b"bar"));
1987 assert!(!b"foobar".ends_with(b"oba"));
1988 assert!(!b"foobar".ends_with(b"foo"));
1989 assert!(!b"foo".ends_with(b"foobar"));
1990 assert!(!b"bar".ends_with(b"foobar"));
1991 assert!(b"foobar".ends_with(b"foobar"));
1992 let empty: &[u8] = [];
1993 assert!(empty.ends_with(empty));
1994 assert!(!empty.ends_with(b"foo"));
1995 assert!(b"foobar".ends_with(empty));
1999 fn test_shift_ref() {
2000 let mut x: &[int] = [1, 2, 3, 4, 5];
2001 let h = x.shift_ref();
2002 assert_eq!(*h.unwrap(), 1);
2003 assert_eq!(x.len(), 4);
2004 assert_eq!(x[0], 2);
2005 assert_eq!(x[3], 5);
2007 let mut y: &[int] = [];
2008 assert_eq!(y.shift_ref(), None);
2013 let mut x: &[int] = [1, 2, 3, 4, 5];
2014 let h = x.pop_ref();
2015 assert_eq!(*h.unwrap(), 5);
2016 assert_eq!(x.len(), 4);
2017 assert_eq!(x[0], 1);
2018 assert_eq!(x[3], 4);
2020 let mut y: &[int] = [];
2021 assert!(y.pop_ref().is_none());
2025 fn test_mut_splitator() {
2026 let mut xs = [0i,1,0,2,3,0,0,4,5,0];
2027 assert_eq!(xs.mut_split(|x| *x == 0).count(), 6);
2028 for slice in xs.mut_split(|x| *x == 0) {
2031 assert!(xs == [0,1,0,3,2,0,0,5,4,0]);
2033 let mut xs = [0i,1,0,2,3,0,0,4,5,0,6,7];
2034 for slice in xs.mut_split(|x| *x == 0).take(5) {
2037 assert!(xs == [0,1,0,3,2,0,0,5,4,0,6,7]);
2041 fn test_mut_splitator_rev() {
2042 let mut xs = [1i,2,0,3,4,0,0,5,6,0];
2043 for slice in xs.mut_split(|x| *x == 0).rev().take(4) {
2046 assert!(xs == [1,2,0,4,3,0,0,6,5,0]);
2051 let mut v = [0i,1,2];
2052 assert_eq!(v.get_mut(3), None);
2053 v.get_mut(1).map(|e| *e = 7);
2054 assert_eq!(v[1], 7);
2056 assert_eq!(v.get_mut(2), Some(&mut x));
2060 fn test_mut_chunks() {
2061 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2062 for (i, chunk) in v.mut_chunks(3).enumerate() {
2063 for x in chunk.mut_iter() {
2067 let result = [0u8, 0, 0, 1, 1, 1, 2];
2068 assert!(v == result);
2072 fn test_mut_chunks_rev() {
2073 let mut v = [0u8, 1, 2, 3, 4, 5, 6];
2074 for (i, chunk) in v.mut_chunks(3).rev().enumerate() {
2075 for x in chunk.mut_iter() {
2079 let result = [2u8, 2, 2, 1, 1, 1, 0];
2080 assert!(v == result);
2085 fn test_mut_chunks_0() {
2086 let mut v = [1i, 2, 3, 4];
2087 let _it = v.mut_chunks(0);
2091 fn test_mut_shift_ref() {
2092 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2093 let h = x.mut_shift_ref();
2094 assert_eq!(*h.unwrap(), 1);
2095 assert_eq!(x.len(), 4);
2096 assert_eq!(x[0], 2);
2097 assert_eq!(x[3], 5);
2099 let mut y: &mut [int] = [];
2100 assert!(y.mut_shift_ref().is_none());
2104 fn test_mut_pop_ref() {
2105 let mut x: &mut [int] = [1, 2, 3, 4, 5];
2106 let h = x.mut_pop_ref();
2107 assert_eq!(*h.unwrap(), 5);
2108 assert_eq!(x.len(), 4);
2109 assert_eq!(x[0], 1);
2110 assert_eq!(x[3], 4);
2112 let mut y: &mut [int] = [];
2113 assert!(y.mut_pop_ref().is_none());
2117 fn test_mut_last() {
2118 let mut x = [1i, 2, 3, 4, 5];
2119 let h = x.mut_last();
2120 assert_eq!(*h.unwrap(), 5);
2122 let y: &mut [int] = [];
2123 assert!(y.mut_last().is_none());
2129 use std::prelude::*;
2130 use std::rand::{weak_rng, Rng};
2138 fn iterator(b: &mut Bencher) {
2139 // peculiar numbers to stop LLVM from optimising the summation
2141 let v = Vec::from_fn(100, |i| i ^ (i << 1) ^ (i >> 1));
2148 // sum == 11806, to stop dead code elimination.
2149 if sum == 0 {fail!()}
2154 fn mut_iterator(b: &mut Bencher) {
2155 let mut v = Vec::from_elem(100, 0i);
2159 for x in v.mut_iter() {
2167 fn concat(b: &mut Bencher) {
2168 let xss: Vec<Vec<uint>> =
2169 Vec::from_fn(100, |i| range(0u, i).collect());
2171 xss.as_slice().concat_vec()
2176 fn connect(b: &mut Bencher) {
2177 let xss: Vec<Vec<uint>> =
2178 Vec::from_fn(100, |i| range(0u, i).collect());
2180 xss.as_slice().connect_vec(&0)
2185 fn push(b: &mut Bencher) {
2186 let mut vec: Vec<uint> = vec![];
2194 fn starts_with_same_vector(b: &mut Bencher) {
2195 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2197 vec.as_slice().starts_with(vec.as_slice())
2202 fn starts_with_single_element(b: &mut Bencher) {
2203 let vec: Vec<uint> = vec![0];
2205 vec.as_slice().starts_with(vec.as_slice())
2210 fn starts_with_diff_one_element_at_end(b: &mut Bencher) {
2211 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2212 let mut match_vec: Vec<uint> = Vec::from_fn(99, |i| i);
2215 vec.as_slice().starts_with(match_vec.as_slice())
2220 fn ends_with_same_vector(b: &mut Bencher) {
2221 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2223 vec.as_slice().ends_with(vec.as_slice())
2228 fn ends_with_single_element(b: &mut Bencher) {
2229 let vec: Vec<uint> = vec![0];
2231 vec.as_slice().ends_with(vec.as_slice())
2236 fn ends_with_diff_one_element_at_beginning(b: &mut Bencher) {
2237 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2238 let mut match_vec: Vec<uint> = Vec::from_fn(100, |i| i);
2239 match_vec.as_mut_slice()[0] = 200;
2241 vec.as_slice().starts_with(match_vec.as_slice())
2246 fn contains_last_element(b: &mut Bencher) {
2247 let vec: Vec<uint> = Vec::from_fn(100, |i| i);
2254 fn zero_1kb_from_elem(b: &mut Bencher) {
2256 Vec::from_elem(1024, 0u8)
2261 fn zero_1kb_set_memory(b: &mut Bencher) {
2263 let mut v: Vec<uint> = Vec::with_capacity(1024);
2265 let vp = v.as_mut_ptr();
2266 ptr::set_memory(vp, 0, 1024);
2274 fn zero_1kb_loop_set(b: &mut Bencher) {
2276 let mut v: Vec<uint> = Vec::with_capacity(1024);
2280 for i in range(0u, 1024) {
2287 fn zero_1kb_mut_iter(b: &mut Bencher) {
2289 let mut v = Vec::with_capacity(1024);
2293 for x in v.mut_iter() {
2301 fn random_inserts(b: &mut Bencher) {
2302 let mut rng = weak_rng();
2304 let mut v = Vec::from_elem(30, (0u, 0u));
2305 for _ in range(0u, 100) {
2307 v.insert(rng.gen::<uint>() % (l + 1),
2313 fn random_removes(b: &mut Bencher) {
2314 let mut rng = weak_rng();
2316 let mut v = Vec::from_elem(130, (0u, 0u));
2317 for _ in range(0u, 100) {
2319 v.remove(rng.gen::<uint>() % l);
2325 fn sort_random_small(b: &mut Bencher) {
2326 let mut rng = weak_rng();
2328 let mut v = rng.gen_iter::<u64>().take(5).collect::<Vec<u64>>();
2329 v.as_mut_slice().sort();
2331 b.bytes = 5 * mem::size_of::<u64>() as u64;
2335 fn sort_random_medium(b: &mut Bencher) {
2336 let mut rng = weak_rng();
2338 let mut v = rng.gen_iter::<u64>().take(100).collect::<Vec<u64>>();
2339 v.as_mut_slice().sort();
2341 b.bytes = 100 * mem::size_of::<u64>() as u64;
2345 fn sort_random_large(b: &mut Bencher) {
2346 let mut rng = weak_rng();
2348 let mut v = rng.gen_iter::<u64>().take(10000).collect::<Vec<u64>>();
2349 v.as_mut_slice().sort();
2351 b.bytes = 10000 * mem::size_of::<u64>() as u64;
2355 fn sort_sorted(b: &mut Bencher) {
2356 let mut v = Vec::from_fn(10000, |i| i);
2360 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;
2363 type BigSortable = (u64,u64,u64,u64);
2366 fn sort_big_random_small(b: &mut Bencher) {
2367 let mut rng = weak_rng();
2369 let mut v = rng.gen_iter::<BigSortable>().take(5)
2370 .collect::<Vec<BigSortable>>();
2373 b.bytes = 5 * mem::size_of::<BigSortable>() as u64;
2377 fn sort_big_random_medium(b: &mut Bencher) {
2378 let mut rng = weak_rng();
2380 let mut v = rng.gen_iter::<BigSortable>().take(100)
2381 .collect::<Vec<BigSortable>>();
2384 b.bytes = 100 * mem::size_of::<BigSortable>() as u64;
2388 fn sort_big_random_large(b: &mut Bencher) {
2389 let mut rng = weak_rng();
2391 let mut v = rng.gen_iter::<BigSortable>().take(10000)
2392 .collect::<Vec<BigSortable>>();
2395 b.bytes = 10000 * mem::size_of::<BigSortable>() as u64;
2399 fn sort_big_sorted(b: &mut Bencher) {
2400 let mut v = Vec::from_fn(10000u, |i| (i, i, i, i));
2404 b.bytes = (v.len() * mem::size_of_val(v.get(0))) as u64;